Renderer.cpp 35.5 KB
Newer Older
Gargaj's avatar
Gargaj committed
1
2
3
#include <windows.h>
#include <windowsx.h>
#include <tchar.h>
Gargaj's avatar
Gargaj committed
4
#include <float.h>
Gargaj's avatar
Gargaj committed
5

Gargaj's avatar
Gargaj committed
6
#include <d3d11.h>
Gargaj's avatar
Gargaj committed
7
8
#include <D3Dcompiler.h>

Gargaj's avatar
Gargaj committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include "../Renderer.h"

#define STBI_HEADER_FILE_ONLY
#include <stb_image.c>
#include "../external/scintilla/include/Scintilla.h"

#define DEVTYPE D3DDEVTYPE_HAL

const char * shaderKeyword =
  "BlendState break Buffer cbuffer class compile const continue DepthStencilState"
  " DepthStencilView discard do else extern false for GeometryShader if in inline"
  " inout interface namespace linear centroid nointerpolation noperspective sample"
  " out pass PixelShader precise RasterizerState RenderTargetView return register"
  " Sampler Sampler1D Sampler2D Sampler3D SamplerCUBE SamplerState"
  " SamplerComparisonState shared Stateblock StateblockState static struct switch"
  " tbuffer technique technique10 technique11 texture Texture1D Texture1DArray"
  " Texture2D Texture2DArray Texture2DMS Texture2DMSArray Texture3D TextureCube"
  " TextureCubeArray true typedef uniform VertexShader void volatile while";

const char * shaderType = 
  "AppendStructuredBuffer bool bool2 bool3 bool4 Buffer ByteAddressBuffer"
  " ConsumeStructuredBuffer double double2 double3 double4 float float1x1"
  " float1x2 float1x3 float1x4 float2 float2x1 float2x2 float2x3 float2x4"
  " float3 float3x1 float3x2 float3x3 float3x4 float4 float4x1 float4x2"
  " float4x3 float4x4 half half2 half3 half4 InputPatch int int2 int3 int4 line"
  " lineadj LineStream matrix OutputPatch point PointStream RWBuffer"
  " RWByteAddressBuffer RWStructuredBuffer RWTexture1D RWTexture1DArray"
  " RWTexture2D RWTexture2DArray RWTexture3D string StructuredBuffer Texture1D"
  " Texture1DArray Texture2D Texture2DArray Texture2DMS Texture2DMSArray"
  " Texture3D triangle triangleadj TriangleStream uint uint2 uint3 uint4 vector";

const char * shaderBuiltin =
  "abs acos all AllMemoryBarrier AllMemoryBarrierWithGroupSync any asdouble"
  " asfloat asin asint asuint atan atan2 ceil clamp clip cos cosh countbits"
  " cross D3DCOLORtoUBYTE4 ddx ddx_coarse ddx_fine ddy ddy_coarse ddy_fine"
  " degrees determinant DeviceMemoryBarrier DeviceMemoryBarrierWithGroupSync"
  " distance dot dst EvaluateAttributeAtCentroid EvaluateAttributeAtSample"
  " EvaluateAttributeSnapped exp exp2 f16tof32 f32tof16 faceforward firstbithigh"
  " firstbitlow floor fmod frac frexp fwidth GetRenderTargetSampleCount"
  " GetRenderTargetSamplePosition GroupMemoryBarrier GroupMemoryBarrierWithGroupSync"
  " InterlockedAdd InterlockedAnd InterlockedCompareExchange InterlockedCompareStore"
  " InterlockedExchange InterlockedMax InterlockedMin InterlockedOr InterlockedXor"
  " isfinite isinf isnan ldexp length lerp lit log log10 log2 mad max min modf mul"
  " noise normalize pow Process2DQuadTessFactorsAvg Process2DQuadTessFactorsMax"
  " Process2DQuadTessFactorsMin ProcessIsolineTessFactors ProcessQuadTessFactorsAvg"
  " ProcessQuadTessFactorsMax ProcessQuadTessFactorsMin ProcessTriTessFactorsAvg"
  " ProcessTriTessFactorsMax ProcessTriTessFactorsMin radians rcp reflect refract"
  " reversebits round rsqrt saturate sign sin sincos sinh smoothstep sqrt step"
  " tan tanh tex1D tex1Dbias tex1Dgrad tex1Dlod tex1Dproj tex2D tex2Dbias"
  " tex2Dgrad tex2Dlod tex2Dproj tex3D tex3Dbias tex3Dgrad tex3Dlod tex3Dproj"
  " texCUBE texCUBEbias texCUBEgrad texCUBElod texCUBEproj transpose trunc";

namespace Renderer
{
  char * defaultShaderFilename = "shader.dx11.hlsl";
  char defaultShader[65536] = 
65
66
67
68
    "{%textures:begin%}" // leave off \n here
    "Texture2D {%textures:name%};\n"
    "{%textures:end%}" // leave off \n here
    "Texture1D texFFT; // towards 0.0 is bass / lower freq, towards 1.0 is higher / treble freq\n"
Gargaj's avatar
Gargaj committed
69
    "SamplerState smp;\n"
Gargaj's avatar
Gargaj committed
70
    "\n"
Gargaj's avatar
Gargaj committed
71
72
    "cbuffer constants\n"
    "{\n"
73
74
75
76
77
    "  float fGlobalTime; // in seconds\n"
    "  float2 v2Resolution; // viewport resolution (in pixels)\n"
    "{%midi:begin%}"
    "  float {%midi:name%};\n"
    "{%midi:end%}"
Gargaj's avatar
Gargaj committed
78
    "}\n"
Gargaj's avatar
Gargaj committed
79
    "\n"
80
81
82
83
84
    "float4 plas( float2 v, float time )\n"
    "{\n"
    "  float c = 0.5 + sin( v.x * 10.0 ) + cos( sin( time + v.y ) * 20.0 );\n"
    "  return float4( sin(c * 0.2 + cos(time)), c * 0.15, cos( c * 0.1 + time / .4 ) * .25, 1.0 );\n"
    "}\n"
Gargaj's avatar
Gargaj committed
85
    "float4 main( float4 position : SV_POSITION, float2 TexCoord : TEXCOORD ) : SV_TARGET\n"
Gargaj's avatar
Gargaj committed
86
87
88
89
90
91
92
93
94
95
    "{\n"
    "  float2 uv = TexCoord;\n"
    "  uv -= 0.5;\n"
    "  uv /= float2(v2Resolution.y / v2Resolution.x, 1);"
    "\n"
    "  float2 m;\n"
    "  m.x = atan(uv.x / uv.y) / 3.14;\n"
    "  m.y = 1 / length(uv) * .2;\n"
    "  float d = m.y;\n"
    "\n"
Gargaj's avatar
Gargaj committed
96
    "  float f = texFFT.Sample( smp, d ).r * 100;\n"
Gargaj's avatar
Gargaj committed
97
98
99
    "  m.x += sin( fGlobalTime ) * 0.1;\n"
    "  m.y += fGlobalTime * 0.25;\n"
    "\n"
100
101
102
    "  float4 t = plas( m * 3.14, fGlobalTime ) / d;\n"
    "  t = saturate( t );\n"
    "  return f + t;\n"
Gargaj's avatar
Gargaj committed
103
    "}";
Gargaj's avatar
Gargaj committed
104

Gargaj's avatar
Gargaj committed
105
  char defaultVertexShader[65536] = 
Gargaj's avatar
Gargaj committed
106
107
    "struct VS_INPUT_PP { float3 Pos : POSITION; float2 TexCoord : TEXCOORD; };\n"
    "struct VS_OUTPUT_PP { float4 Pos : SV_POSITION; float2 TexCoord : TEXCOORD; };\n"
Gargaj's avatar
Gargaj committed
108
109
110
111
112
113
114
115
116
117
118
    "\n"
    "VS_OUTPUT_PP main( VS_INPUT_PP In )\n"
    "{\n"
    "  VS_OUTPUT_PP Out;\n"
    "  Out.Pos = float4( In.Pos, 1.0 );\n"
    "  Out.TexCoord = In.TexCoord;\n"
    "  return Out;\n"
    "}\n";

  bool run = true;

Gargaj's avatar
Gargaj committed
119
120
121
122
123
124
125
  IDXGISwapChain * pSwapChain = NULL;
  ID3D11Device * pDevice = NULL;
  ID3D11DeviceContext * pContext = NULL;
  ID3D11RenderTargetView * pRenderTarget = NULL;
  ID3D11VertexShader * pVertexShader = NULL;
  ID3D11PixelShader * theShader = NULL;
  ID3D11ShaderReflection * pShaderReflection = NULL;
Gargaj's avatar
Gargaj committed
126

Gargaj's avatar
Gargaj committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
  int nWidth = 0;
  int nHeight = 0;
  HWND hWnd = NULL;

  KeyEvent keyEventBuffer[512];
  int keyEventBufferCount = 0;
  MouseEvent mouseEventBuffer[512];
  int mouseEventBufferCount = 0;

  LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) 
  {
    switch (uMsg) 
    {
    case WM_KEYDOWN: 
      {
        int sciKey = 0;
        switch(wParam)
        {
        case VK_DOWN:         sciKey = SCK_DOWN;      break;
        case VK_UP:           sciKey = SCK_UP;        break;
        case VK_LEFT:         sciKey = SCK_LEFT;      break;
        case VK_RIGHT:        sciKey = SCK_RIGHT;     break;
        case VK_HOME:         sciKey = SCK_HOME;      break;
        case VK_END:          sciKey = SCK_END;       break;
        case VK_PRIOR:        sciKey = SCK_PRIOR;     break;
        case VK_NEXT:         sciKey = SCK_NEXT;      break;
        case VK_DELETE:       sciKey = SCK_DELETE;    break;
        case VK_INSERT:       sciKey = SCK_INSERT;    break;
        case VK_ESCAPE:       sciKey = SCK_ESCAPE;    break;
        case VK_BACK:         sciKey = SCK_BACK;      break;
        case VK_TAB:          sciKey = SCK_TAB;       break;
        case VK_RETURN:       sciKey = SCK_RETURN;    break;
//         case VK_KP_PLUS:      sciKey = SCK_ADD;       break;
//         case VK_KP_MINUS:     sciKey = SCK_SUBTRACT;  break;
//         case VK_KP_DIVIDE:    sciKey = SCK_DIVIDE;    break;
//         case VK_LSUPER:       sciKey = SCK_WIN;       break;
//         case VK_RSUPER:       sciKey = SCK_RWIN;      break;
        case VK_MENU:         sciKey = SCK_MENU;      break;
//         case VK_SLASH:        sciKey = '/';           break;
//         case VK_ASTERISK:     sciKey = '`';           break;
//         case VK_LEFTBRACKET:  sciKey = '[';           break;
//         case VK_BACKSLASH:    sciKey = '\\';          break;
//         case VK_RIGHTBRACKET: sciKey = ']';           break;
Gargaj's avatar
Gargaj committed
170
        case VK_F2:         sciKey = 283;      break;
Gargaj's avatar
Gargaj committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
        case VK_F5:         sciKey = 286;      break;
        case VK_F11:        sciKey = 292;      break;
        case VK_SHIFT:
        case VK_LSHIFT:
        case VK_RSHIFT:
        case VK_LMENU:
        case VK_RMENU:
        case VK_CONTROL:
        case VK_LCONTROL:
        case VK_RCONTROL:
          sciKey = 0;
          break;
        default:
          sciKey = wParam;
        }
        if (sciKey)
        {
          keyEventBuffer[keyEventBufferCount].ctrl  = GetAsyncKeyState( VK_LCONTROL ) || GetAsyncKeyState( VK_RCONTROL );
          keyEventBuffer[keyEventBufferCount].alt   = GetAsyncKeyState( VK_LMENU ) || GetAsyncKeyState( VK_RMENU );
          keyEventBuffer[keyEventBufferCount].shift = GetAsyncKeyState( VK_LSHIFT ) || GetAsyncKeyState( VK_RSHIFT );
          keyEventBuffer[keyEventBufferCount].scanCode = sciKey;
          keyEventBuffer[keyEventBufferCount].character = 0;
          keyEventBufferCount++;
        }
        //pKeys[wParam] = 1;
      } break;
    case WM_CHAR: 
      {
        if (wParam >= 32)
        {
          keyEventBuffer[keyEventBufferCount].ctrl  = GetAsyncKeyState( VK_LCONTROL ) || GetAsyncKeyState( VK_RCONTROL );
          keyEventBuffer[keyEventBufferCount].alt   = GetAsyncKeyState( VK_LMENU ) || GetAsyncKeyState( VK_RMENU );
          keyEventBuffer[keyEventBufferCount].shift = GetAsyncKeyState( VK_LSHIFT ) || GetAsyncKeyState( VK_RSHIFT );
          keyEventBuffer[keyEventBufferCount].scanCode = 0;
          keyEventBuffer[keyEventBufferCount].character = wParam;
          keyEventBufferCount++;
        }
        //pKeys[wParam] = 1;
      } break;

    case WM_KEYUP: 
      {
        //pKeys[wParam] = 0;
      } break;

    case WM_LBUTTONDOWN: 
      {
        mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_DOWN;
        mouseEventBuffer[mouseEventBufferCount].button = MOUSEBUTTON_LEFT;
        mouseEventBuffer[mouseEventBufferCount].x = GET_X_LPARAM(lParam);
        mouseEventBuffer[mouseEventBufferCount].y = GET_Y_LPARAM(lParam);
        mouseEventBufferCount++;
      } break;

    case WM_MOUSEMOVE: 
      {
        mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_MOVE;
        mouseEventBuffer[mouseEventBufferCount].x = GET_X_LPARAM(lParam);
        mouseEventBuffer[mouseEventBufferCount].y = GET_Y_LPARAM(lParam);
        mouseEventBufferCount++;
      } break;

    case WM_LBUTTONUP: 
      {
        mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_UP;
        mouseEventBuffer[mouseEventBufferCount].button = MOUSEBUTTON_LEFT;
        mouseEventBuffer[mouseEventBufferCount].x = GET_X_LPARAM(lParam);
        mouseEventBuffer[mouseEventBufferCount].y = GET_Y_LPARAM(lParam);
        mouseEventBufferCount++;
      } break;

    case WM_SYSCOMMAND: 
      {
        switch (wParam) 
        {
        case SC_SCREENSAVE:
        case SC_MONITORPOWER: 
          {
            return 0;
          }
        }
      } break;

    case WM_CLOSE: 
      {
        run = false;
      } break;
    }

    return DefWindowProc(hWnd, uMsg, wParam, lParam);
  }

  bool InitWindow(RENDERER_SETTINGS * pSetup) 
  {
    WNDCLASS WC;

    WC.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    WC.lpfnWndProc = &WndProc;
    WC.cbClsExtra = 0;
    WC.cbWndExtra = 0;
    WC.hInstance = GetModuleHandle(NULL);
    //WC.hIcon = LoadIcon(setup->hInstance,MAKEINTRESOURCE(IDI_ICON1));
    WC.hIcon = NULL;
    WC.hCursor = LoadCursor(NULL, IDC_ARROW);
    WC.hbrBackground = NULL;
    WC.lpszMenuName = NULL;
    WC.lpszClassName = _T("fwzwnd");
    if(!RegisterClass(&WC)) return 0;

    DWORD wExStyle = WS_EX_APPWINDOW;
    DWORD wStyle = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
    if (pSetup->windowMode == RENDERER_WINDOWMODE_WINDOWED) wStyle |= WS_OVERLAPPED | WS_CAPTION;

    RECT wr={0,0,pSetup->nWidth,pSetup->nHeight};
    AdjustWindowRectEx(&wr, wStyle, FALSE, wExStyle);

Gargaj's avatar
Gargaj committed
287
    hWnd = CreateWindowEx(wExStyle,_T("fwzwnd"),_T("BONZOMATIC - Direct3D 11.0 edition"),wStyle,
Gargaj's avatar
Gargaj committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
      (GetSystemMetrics(SM_CXSCREEN) - pSetup->nWidth )/2,
      (GetSystemMetrics(SM_CYSCREEN) - pSetup->nHeight)/2,
      wr.right-wr.left, wr.bottom-wr.top,
      NULL, NULL, WC.hInstance, NULL);

    if (!hWnd) 
      return false;

    ShowWindow(hWnd, SW_SHOW);
    SetForegroundWindow(hWnd);
    SetFocus(hWnd);

    return true;
  }

Gargaj's avatar
Gargaj committed
303
  bool bVsync = false;
Gargaj's avatar
Gargaj committed
304
305
  bool InitDirect3D(RENDERER_SETTINGS * pSetup) 
  {
Gargaj's avatar
Gargaj committed
306
307
    DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;

Gargaj's avatar
Gargaj committed
308
309
310
    DXGI_SWAP_CHAIN_DESC desc;
    ZeroMemory(&desc, sizeof(DXGI_SWAP_CHAIN_DESC));
    desc.BufferCount = 1;
Gargaj's avatar
Gargaj committed
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
    desc.BufferDesc.Width = pSetup->nWidth;
    desc.BufferDesc.Height = pSetup->nHeight;
    desc.BufferDesc.Format = format;
    if (pSetup->bVsync)
    {
      bVsync = true;
      IDXGIFactory1 * pFactory = NULL;
      HRESULT hr = CreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**)&pFactory);
      if (pFactory)
      {
        IDXGIAdapter1 * pAdapter = NULL;
        pFactory->EnumAdapters1( 0, &pAdapter );
        if (pAdapter)
        {
          IDXGIOutput * pOutput = NULL;
          pAdapter->EnumOutputs( 0, &pOutput );
          if (pOutput)
          {
            unsigned int nModeCount = 0;
            pOutput->GetDisplayModeList( format, DXGI_ENUM_MODES_INTERLACED | DXGI_ENUM_MODES_SCALING, &nModeCount, NULL);

            DXGI_MODE_DESC * pModes = new DXGI_MODE_DESC[ nModeCount ];
            pOutput->GetDisplayModeList( format, DXGI_ENUM_MODES_INTERLACED | DXGI_ENUM_MODES_SCALING, &nModeCount, pModes);

            for (int i=0; i<nModeCount; i++)
            {
              if (pModes[i].Width == pSetup->nWidth && pModes[i].Height == pSetup->nHeight)
              {
                desc.BufferDesc = pModes[i];
                break;
              }
            }
            delete[] pModes;

            pOutput->Release();
          }

          pAdapter->Release();
        }

        pFactory->Release();
      }
    }
Gargaj's avatar
Gargaj committed
354
355
    desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    desc.OutputWindow = hWnd;
Gargaj's avatar
Gargaj committed
356
357
358
359
360
361
362
    desc.SampleDesc.Count = 1;
    desc.Windowed = pSetup->windowMode != RENDERER_WINDOWMODE_FULLSCREEN;

    DWORD deviceCreationFlags = 0;
#ifdef _DEBUG
    //deviceCreationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
Gargaj's avatar
Gargaj committed
363

Gargaj's avatar
Gargaj committed
364
365
366
367
    if (D3D11CreateDeviceAndSwapChain(
      NULL,
      D3D_DRIVER_TYPE_HARDWARE,
      NULL,
Gargaj's avatar
Gargaj committed
368
      deviceCreationFlags,
Gargaj's avatar
Gargaj committed
369
370
371
372
373
374
375
376
      NULL,
      NULL,
      D3D11_SDK_VERSION,
      &desc,
      &pSwapChain,
      &pDevice,
      NULL,
      &pContext) != S_OK)
Gargaj's avatar
Gargaj committed
377
378
      return false;

Gargaj's avatar
Gargaj committed
379
    ID3D11Texture2D * pBackBuffer = NULL;
Gargaj's avatar
Gargaj committed
380
381
382
383
384
385
386
    pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&pBackBuffer);

    pDevice->CreateRenderTargetView(pBackBuffer, NULL, &pRenderTarget);
    pBackBuffer->Release();

    pContext->OMSetRenderTargets(1, &pRenderTarget, NULL);

Gargaj's avatar
Gargaj committed
387
    return true;
Gargaj's avatar
Gargaj committed
388
389
  }

Gargaj's avatar
Gargaj committed
390
391
  ID3D11Buffer * pFullscreenQuadVB = NULL;
  ID3D11InputLayout * pFullscreenQuadLayout = NULL;
Gargaj's avatar
Gargaj committed
392
393
  ID3D11SamplerState * pFullscreenQuadSamplerState = NULL;
  ID3D11Buffer * pFullscreenQuadConstantBuffer = NULL;
394
395
#define FULLSCREENQUADCONSTANTS_SIZE 512
  unsigned char pFullscreenQuadConstants[FULLSCREENQUADCONSTANTS_SIZE];
Gargaj's avatar
Gargaj committed
396
397
  ID3D11BlendState* pFullscreenQuadBlendState = NULL;
  ID3D11RasterizerState * pFullscreenQuadRasterizerState = NULL;
Gargaj's avatar
Gargaj committed
398

Gargaj's avatar
Gargaj committed
399
  bool InitD3D11QuadRendering( RENDERER_SETTINGS * settings )
Gargaj's avatar
Gargaj committed
400
  {
Gargaj's avatar
Gargaj committed
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
    ID3DBlob * pCode = NULL;
    ID3DBlob * pErrors = NULL;
    if (D3DCompile( defaultVertexShader, strlen(defaultVertexShader), NULL, NULL, NULL, "main", "vs_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK)
    {
      return false;
    }

    if (pDevice->CreateVertexShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &pVertexShader ) != S_OK)
    {
      return false;
    }

    //////////////////////////////////////////////////////////////////////////

    static float pQuad[] = {
Gargaj's avatar
Gargaj committed
416
417
418
419
      -1.0, -1.0,  0.5, 0.0, 0.0,
      -1.0,  1.0,  0.5, 0.0, 1.0,
       1.0, -1.0,  0.5, 1.0, 0.0,
       1.0,  1.0,  0.5, 1.0, 1.0,
Gargaj's avatar
Gargaj committed
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
    };

    D3D11_BUFFER_DESC desc;
    ZeroMemory(&desc, sizeof(D3D11_BUFFER_DESC));

    desc.ByteWidth = sizeof(float) * 5 * 4;
    desc.Usage = D3D11_USAGE_DEFAULT;
    desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;

    D3D11_SUBRESOURCE_DATA subData;
    ZeroMemory(&subData, sizeof(D3D11_SUBRESOURCE_DATA));
    subData.pSysMem = pQuad;

    if (pDevice->CreateBuffer(&desc, &subData, &pFullscreenQuadVB) != S_OK)
      return false;

    static D3D11_INPUT_ELEMENT_DESC pQuadDesc[] =
    {
Gargaj's avatar
Gargaj committed
438
439
      {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0},
      {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT   , 0, 3 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0},
Gargaj's avatar
Gargaj committed
440
441
    };

Gargaj's avatar
Gargaj committed
442
443
    if (pDevice->CreateInputLayout( pQuadDesc, 2, pCode->GetBufferPointer(), pCode->GetBufferSize(), &pFullscreenQuadLayout) != S_OK)
      return false;
Gargaj's avatar
Gargaj committed
444

Gargaj's avatar
Gargaj committed
445
446
447
448
449
450
451
452
453
454
455
456
457
458
    //////////////////////////////////////////////////////////////////////////

    D3D11_VIEWPORT viewport;
    ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT));

    viewport.TopLeftX = 0;
    viewport.TopLeftY = 0;
    viewport.Width  = settings->nWidth;
    viewport.Height = settings->nHeight;

    pContext->RSSetViewports(1, &viewport);

    //////////////////////////////////////////////////////////////////////////

Gargaj's avatar
Gargaj committed
459
    D3D11_SAMPLER_DESC sampDesc = CD3D11_SAMPLER_DESC( CD3D11_DEFAULT() );
Gargaj's avatar
Gargaj committed
460
461
462
463
    sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    sampDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT;
Gargaj's avatar
Gargaj committed
464
    if (pDevice->CreateSamplerState( &sampDesc, &pFullscreenQuadSamplerState ) != S_OK)
Gargaj's avatar
Gargaj committed
465
466
467
468
469
470
      return false;

    //////////////////////////////////////////////////////////////////////////

    D3D11_BUFFER_DESC cbDesc;
    ZeroMemory( &cbDesc, sizeof(D3D11_BUFFER_DESC) );
Gargaj's avatar
Gargaj committed
471
    cbDesc.ByteWidth = sizeof( pFullscreenQuadConstants );
Gargaj's avatar
Gargaj committed
472
473
474
475
476
    cbDesc.Usage = D3D11_USAGE_DYNAMIC;
    cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

    ZeroMemory( &subData, sizeof(D3D11_SUBRESOURCE_DATA) );
Gargaj's avatar
Gargaj committed
477
    subData.pSysMem = &pFullscreenQuadConstants;
Gargaj's avatar
Gargaj committed
478

Gargaj's avatar
Gargaj committed
479
480
481
    if (pDevice->CreateBuffer( &cbDesc, &subData, &pFullscreenQuadConstantBuffer ) != S_OK)
      return false;

Gargaj's avatar
Gargaj committed
482
483
484
485
486
487
488
489
490
491
    //////////////////////////////////////////////////////////////////////////

    D3D11_BLEND_DESC blendDesc = CD3D11_BLEND_DESC( CD3D11_DEFAULT() );
    if (pDevice->CreateBlendState( &blendDesc, &pFullscreenQuadBlendState ) != S_OK)
      return false;

    D3D11_RASTERIZER_DESC rastDesc = CD3D11_RASTERIZER_DESC( CD3D11_DEFAULT() );
    if (pDevice->CreateRasterizerState( &rastDesc, &pFullscreenQuadRasterizerState ) != S_OK)
      return false;

Gargaj's avatar
Gargaj committed
492
493
494
    return true;
  }

495
#define GUIQUADVB_SIZE (1024 * 6)
Gargaj's avatar
Gargaj committed
496

497
  char defaultGUIPixelShader[65536] = 
Gargaj's avatar
Gargaj committed
498
499
    "Texture2D tex;\n"
    "SamplerState smp;\n"
500
    "float4 main( float4 position : SV_POSITION, float4 Color: COLOR, float2 TexCoord : TEXCOORD0, float Factor : TEXCOORD1 ) : SV_TARGET\n"
Gargaj's avatar
Gargaj committed
501
    "{\n"
Gargaj's avatar
Gargaj committed
502
    "  float4 v4Texture = Color * tex.Sample(smp,TexCoord);//float4( Color.rgb, Color.a * .a );\n"
503
504
    "  float4 v4Color = Color;\n"
    "  return lerp( v4Texture, v4Color, Factor );\n"
Gargaj's avatar
Gargaj committed
505
506
    "}\n";
  char defaultGUIVertexShader[65536] = 
507
508
    "struct VS_INPUT_PP { float3 Pos : POSITION; float4 Color: COLOR; float2 TexCoord : TEXCOORD0; float Factor : TEXCOORD1; };\n"
    "struct VS_OUTPUT_PP { float4 Pos : SV_POSITION; float4 Color: COLOR; float2 TexCoord : TEXCOORD0; float Factor : TEXCOORD1; };\n"
Gargaj's avatar
Gargaj committed
509
510
511
512
513
514
515
516
517
518
    "\n"
    "cbuffer c { float4x4 matProj; float2 v2Offset; }\n"
    "\n"
    "VS_OUTPUT_PP main( VS_INPUT_PP In )\n"
    "{\n"
    "  VS_OUTPUT_PP Out;\n"
    "  Out.Pos = float4( In.Pos + float3(v2Offset,0), 1.0 );\n"
    "  Out.Pos = mul( Out.Pos, matProj );\n"
    "  Out.Color = In.Color;\n"
    "  Out.TexCoord = In.TexCoord;\n"
519
    "  Out.Factor = In.Factor;\n"
Gargaj's avatar
Gargaj committed
520
521
522
523
    "  return Out;\n"
    "}\n";

  ID3D11VertexShader * pGUIVertexShader = NULL;
524
  ID3D11PixelShader * pGUIPixelShader = NULL;
Gargaj's avatar
Gargaj committed
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
  ID3D11Buffer * pGUIQuadVB = NULL;
  ID3D11InputLayout * pGUIQuadLayout = NULL;
  ID3D11Buffer * pGUIConstantBuffer = NULL;
  ID3D11BlendState* pGUIBlendState = NULL;
  ID3D11RasterizerState * pGUIRasterizerState = NULL;
  float pGUIMatrix[ 4 * 4 + 16 ];

  void MatrixOrthoOffCenterLH(float * pout, FLOAT l, FLOAT r, FLOAT b, FLOAT t, FLOAT zn, FLOAT zf)
  {
    ZeroMemory( pout, sizeof(float) * 4 * 4 );
    pout[0 + 0 * 4] = 2.0f / (r - l);
    pout[1 + 1 * 4] = 2.0f / (t - b);
    pout[2 + 2 * 4] = 1.0f / (zf -zn);
    pout[3 + 0 * 4] = -1.0f -2.0f *l / (r - l);
    pout[3 + 1 * 4] = 1.0f + 2.0f * t / (b - t);
    pout[3 + 2 * 4] = zn / (zn -zf);
    pout[3 + 3 * 4] = 1.0;
  }

  bool InitD3D11GUIRendering( RENDERER_SETTINGS * settings )
  {
    ID3DBlob * pCode = NULL;
    ID3DBlob * pErrors = NULL;
548
    if (D3DCompile( defaultGUIPixelShader, strlen(defaultGUIPixelShader), NULL, NULL, NULL, "main", "ps_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK)
Gargaj's avatar
Gargaj committed
549
550
551
552
    {
      return false;
    }

553
    if (pDevice->CreatePixelShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &pGUIPixelShader ) != S_OK)
Gargaj's avatar
Gargaj committed
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
    {
      return false;
    }

    if (D3DCompile( defaultGUIVertexShader, strlen(defaultGUIVertexShader), NULL, NULL, NULL, "main", "vs_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK)
    {
      return false;
    }

    if (pDevice->CreateVertexShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &pGUIVertexShader ) != S_OK)
    {
      return false;
    }

    D3D11_BUFFER_DESC desc;
    ZeroMemory(&desc, sizeof(D3D11_BUFFER_DESC));

571
    desc.ByteWidth = sizeof(float) * 7 * GUIQUADVB_SIZE;
Gargaj's avatar
Gargaj committed
572
573
574
575
576
577
578
579
580
581
582
583
    desc.Usage = D3D11_USAGE_DYNAMIC;
    desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

    if (pDevice->CreateBuffer(&desc, NULL, &pGUIQuadVB) != S_OK)
      return false;

    static D3D11_INPUT_ELEMENT_DESC pGUIDesc[] =
    {
      {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0},
      {"COLOR"   , 0, DXGI_FORMAT_R8G8B8A8_UNORM , 0, 3 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0},
      {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT   , 0, 4 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0},
584
      {"TEXCOORD", 1, DXGI_FORMAT_R32_FLOAT      , 0, 6 * sizeof(float), D3D11_INPUT_PER_VERTEX_DATA, 0},
Gargaj's avatar
Gargaj committed
585
586
    };

587
    if (pDevice->CreateInputLayout( pGUIDesc, 4, pCode->GetBufferPointer(), pCode->GetBufferSize(), &pGUIQuadLayout) != S_OK)
Gargaj's avatar
Gargaj committed
588
589
590
591
      return false;

    D3D11_BUFFER_DESC cbDesc;
    ZeroMemory( &cbDesc, sizeof(D3D11_BUFFER_DESC) );
Gargaj's avatar
Gargaj committed
592
    cbDesc.ByteWidth = sizeof( float ) * 4 * 4 * 2;
Gargaj's avatar
Gargaj committed
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
    cbDesc.Usage = D3D11_USAGE_DYNAMIC;
    cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;

    MatrixOrthoOffCenterLH( pGUIMatrix, 0, nWidth, nHeight, 0, -1.0f, 1.0f );
    
    D3D11_SUBRESOURCE_DATA subData;
    ZeroMemory( &subData, sizeof(D3D11_SUBRESOURCE_DATA) );
    subData.pSysMem = &pGUIMatrix;

    if (pDevice->CreateBuffer( &cbDesc, &subData, &pGUIConstantBuffer ) != S_OK)
      return false;

    D3D11_BLEND_DESC blendDesc = CD3D11_BLEND_DESC( CD3D11_DEFAULT() );
    blendDesc.RenderTarget[0].BlendEnable = true;
    blendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
    blendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
    if (pDevice->CreateBlendState( &blendDesc, &pGUIBlendState ) != S_OK)
      return false;

    D3D11_RASTERIZER_DESC rastDesc = CD3D11_RASTERIZER_DESC( CD3D11_DEFAULT() );
    rastDesc.ScissorEnable = true;
    if (pDevice->CreateRasterizerState( &rastDesc, &pGUIRasterizerState ) != S_OK)
      return false;

    return true;
  }

Gargaj's avatar
Gargaj committed
621
622
  bool Open( RENDERER_SETTINGS * settings )
  {
Gargaj's avatar
Gargaj committed
623
624
625
    nWidth  = settings->nWidth;
    nHeight = settings->nHeight;

Gargaj's avatar
Gargaj committed
626
627
628
629
630
631
632
    if (!InitWindow(settings))
      return false;

    if (!InitDirect3D(settings))
      return false;

    if (!InitD3D11QuadRendering(settings))
Gargaj's avatar
Gargaj committed
633
634
      return false;

Gargaj's avatar
Gargaj committed
635
636
637
    if (!InitD3D11GUIRendering(settings))
      return false;

Gargaj's avatar
Gargaj committed
638
639
640
641
642
    return true;
  }

  void StartFrame()
  {
Gargaj's avatar
Gargaj committed
643
644
645
646
647
648
649
650
651
    MSG msg;
    if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) 
    {
      TranslateMessage( &msg );
      DispatchMessage( &msg );
    }

    float f[4] = { 0.08f, 0.18f, 0.18f, 1.0f };
    pContext->ClearRenderTargetView(pRenderTarget, f);
Gargaj's avatar
Gargaj committed
652
653
654
  }
  void EndFrame()
  {
Gargaj's avatar
Gargaj committed
655
    pSwapChain->Present( bVsync ? 1 : 0, NULL );
Gargaj's avatar
Gargaj committed
656
657
658
659
660
661
662
  }
  bool WantsToQuit()
  {
    return !run;
  }
  void Close()
  {
Gargaj's avatar
Gargaj committed
663
664
    // TODO: a bunch of other crap needs to be deallocated here but i cant be arsed

Gargaj's avatar
Gargaj committed
665
666
667
    if (theShader) theShader->Release();
    if (pShaderReflection) pShaderReflection->Release();
    if (pVertexShader) pVertexShader->Release();
Gargaj's avatar
Gargaj committed
668

Gargaj's avatar
Gargaj committed
669
670
    if (pFullscreenQuadLayout) pFullscreenQuadLayout->Release();
    if (pFullscreenQuadVB) pFullscreenQuadVB->Release();
Gargaj's avatar
Gargaj committed
671
672
673
674
675
676
677
678
679
680
681
682
    if (pFullscreenQuadSamplerState) pFullscreenQuadSamplerState->Release();
    if (pFullscreenQuadConstantBuffer) pFullscreenQuadConstantBuffer->Release();
    if (pFullscreenQuadBlendState) pFullscreenQuadBlendState->Release();
    if (pFullscreenQuadRasterizerState) pFullscreenQuadRasterizerState->Release();

    if (pGUIRasterizerState) pGUIRasterizerState->Release();
    if (pGUIBlendState) pGUIBlendState->Release();
    if (pGUIConstantBuffer) pGUIConstantBuffer->Release();
    if (pGUIPixelShader) pGUIPixelShader->Release();
    if (pGUIVertexShader) pGUIVertexShader->Release();
    if (pGUIQuadLayout) pGUIQuadLayout->Release();
    if (pGUIQuadVB) pGUIQuadVB->Release();
Gargaj's avatar
Gargaj committed
683
684

    if (pRenderTarget) pRenderTarget->Release();
Gargaj's avatar
Gargaj committed
685
686
    if (pContext) pContext->Release();
    if (pSwapChain) pSwapChain->Release();
Gargaj's avatar
Gargaj committed
687
688
689
690
691
692
693
694
695
696
    if (pDevice) pDevice->Release();
    if (!hWnd) 
    {
      DestroyWindow(hWnd);
      UnregisterClass(_T("fwzwnd"),GetModuleHandle(NULL));
    }
  }

  void RenderFullscreenQuad()
  {
Gargaj's avatar
Gargaj committed
697
    float factor[4] = { 1.0f, 1.0f, 1.0f, 1.0f, };
Gargaj's avatar
Gargaj committed
698
699
700
    pContext->VSSetShader( pVertexShader, NULL, NULL );
    pContext->PSSetShader( theShader, NULL, NULL );
    pContext->IASetInputLayout( pFullscreenQuadLayout );
Gargaj's avatar
Gargaj committed
701
702
    pContext->PSSetSamplers( 0, 1, &pFullscreenQuadSamplerState );
    pContext->PSSetConstantBuffers( 0, 1, &pFullscreenQuadConstantBuffer );
Gargaj's avatar
Gargaj committed
703
704
    pContext->OMSetBlendState( pFullscreenQuadBlendState, factor, 0xFFFFFFFF );
    pContext->RSSetState( pFullscreenQuadRasterizerState );
Gargaj's avatar
Gargaj committed
705
706
707
708
709
710
711
712
713

    ID3D11Buffer * buffers[] = { pFullscreenQuadVB };
    UINT stride[] = { sizeof(float) * 5 };
    UINT offset[] = { 0 };

    pContext->IASetVertexBuffers( 0, 1, buffers, stride, offset );
    pContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP );

    pContext->Draw( 4, 0 );
Gargaj's avatar
Gargaj committed
714
715
  }

Gargaj's avatar
Gargaj committed
716
  ID3D11ShaderReflectionConstantBuffer * pCBuf = NULL;
Gargaj's avatar
Gargaj committed
717
718
  bool ReloadShader( char * szShaderCode, int nShaderCodeSize, char * szErrorBuffer, int nErrorBufferSize )
  {
Gargaj's avatar
Gargaj committed
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
    ID3DBlob * pCode = NULL;
    ID3DBlob * pErrors = NULL;
    if (D3DCompile( szShaderCode, nShaderCodeSize, NULL, NULL, NULL, "main", "ps_4_0", NULL, NULL, &pCode, &pErrors ) != S_OK)
    {
      memset( szErrorBuffer, 0, nErrorBufferSize );
      strncpy( szErrorBuffer, (char*)pErrors->GetBufferPointer(), nErrorBufferSize - 1 );
      return false;
    }

    if (theShader) 
    {
      theShader->Release();
      theShader = NULL;
    }

    if (pDevice->CreatePixelShader( pCode->GetBufferPointer(), pCode->GetBufferSize(), NULL, &theShader ) != S_OK)
    {
      return false;
    }
    D3DReflect( pCode->GetBufferPointer(), pCode->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&pShaderReflection );
Gargaj's avatar
Gargaj committed
739
740
    pCBuf = pShaderReflection->GetConstantBufferByIndex(0);

Gargaj's avatar
Gargaj committed
741
742
743
    return true;
  }

Gargaj's avatar
Gargaj committed
744
745
746
  void __UpdateConstants()
  {
    D3D11_MAPPED_SUBRESOURCE subRes;
Gargaj's avatar
Gargaj committed
747
748
749
    pContext->Map( pFullscreenQuadConstantBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &subRes );
    CopyMemory( subRes.pData, &pFullscreenQuadConstants, sizeof(pFullscreenQuadConstants) );
    pContext->Unmap( pFullscreenQuadConstantBuffer, NULL );
Gargaj's avatar
Gargaj committed
750
751
  }

Gargaj's avatar
Gargaj committed
752
753
  void SetShaderConstant( char * szConstName, float x )
  {
Gargaj's avatar
Gargaj committed
754
755
    ID3D11ShaderReflectionVariable * pCVar = pCBuf->GetVariableByName( szConstName );
    D3D11_SHADER_VARIABLE_DESC pDesc;
756
757
    if (pCVar->GetDesc( &pDesc ) != S_OK)
      return;
Gargaj's avatar
Gargaj committed
758
    
Gargaj's avatar
Gargaj committed
759
    ((float*)(((unsigned char*)&pFullscreenQuadConstants) + pDesc.StartOffset))[0] = x;
Gargaj's avatar
Gargaj committed
760

Gargaj's avatar
Gargaj committed
761
    __UpdateConstants();
Gargaj's avatar
Gargaj committed
762
763
764
765
  }

  void SetShaderConstant( char * szConstName, float x, float y )
  {
Gargaj's avatar
Gargaj committed
766
767
    ID3D11ShaderReflectionVariable * pCVar = pCBuf->GetVariableByName(szConstName);
    D3D11_SHADER_VARIABLE_DESC pDesc;
768
769
    if (pCVar->GetDesc( &pDesc ) != S_OK)
      return;
Gargaj's avatar
Gargaj committed
770

Gargaj's avatar
Gargaj committed
771
772
    ((float*)(((unsigned char*)&pFullscreenQuadConstants) + pDesc.StartOffset))[0] = x;
    ((float*)(((unsigned char*)&pFullscreenQuadConstants) + pDesc.StartOffset))[1] = y;
Gargaj's avatar
Gargaj committed
773

Gargaj's avatar
Gargaj committed
774
    __UpdateConstants();
Gargaj's avatar
Gargaj committed
775
776
  }

Gargaj's avatar
Gargaj committed
777
  struct DX11Texture : public Texture
Gargaj's avatar
Gargaj committed
778
  {
Gargaj's avatar
Gargaj committed
779
    ID3D11Resource * pTexture;
Gargaj's avatar
Gargaj committed
780
781
    DXGI_FORMAT format;
    ID3D11ShaderResourceView * pResourceView;
Gargaj's avatar
Gargaj committed
782
783
  };

Gargaj's avatar
Gargaj committed
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
  void CreateResourceView( DX11Texture * tex )
  {
    D3D11_SHADER_RESOURCE_VIEW_DESC desc;
    ZeroMemory( &desc, sizeof(D3D11_SHADER_RESOURCE_VIEW_DESC) );
    desc.Format = tex->format;
    if (tex->type == TEXTURETYPE_1D)
    {
      desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE1D;
      desc.Texture1D.MostDetailedMip = 0;
      desc.Texture1D.MipLevels = 1;
    }
    else if (tex->type == TEXTURETYPE_2D)
    {
      desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
      desc.Texture2D.MostDetailedMip = 0;
      desc.Texture2D.MipLevels = 1;
    }
    pDevice->CreateShaderResourceView( tex->pTexture, &desc, &tex->pResourceView );
  }

Gargaj's avatar
Gargaj committed
804
805
806
  int textureUnit = 0;
  Texture * CreateRGBA8TextureFromFile( char * szFilename )
  {
Gargaj's avatar
Gargaj committed
807
808
809
810
811
812
813
814
815
816
    int comp = 0;
    int width = 0;
    int height = 0;
    unsigned char * c = stbi_load( szFilename, (int*)&width, (int*)&height, &comp, STBI_rgb_alpha );
    if (!c) return NULL;

    D3D11_TEXTURE2D_DESC desc;
    ZeroMemory(&desc,sizeof(D3D11_TEXTURE2D_DESC));
    desc.Width = width;
    desc.Height = height;
Gargaj's avatar
Gargaj committed
817
    desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
Gargaj's avatar
Gargaj committed
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
    desc.MipLevels = 1;
    desc.ArraySize = 1;
    desc.SampleDesc.Count = 1;
    desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    
    D3D11_SUBRESOURCE_DATA subData;
    ZeroMemory(&subData,sizeof(D3D11_SUBRESOURCE_DATA));
    subData.pSysMem = c;
    subData.SysMemPitch = width * sizeof(unsigned char) * 4;

    ID3D11Texture2D * pTex = NULL;

    if (pDevice->CreateTexture2D( &desc, &subData, &pTex ) != S_OK)
      return NULL;

    stbi_image_free(c);

    DX11Texture * tex = new DX11Texture();
    tex->width = width;
    tex->height = height;
    tex->pTexture = pTex;
    tex->type = TEXTURETYPE_2D;
    tex->format = desc.Format;
    CreateResourceView(tex);
    return tex;
Gargaj's avatar
Gargaj committed
843
844
845
846
  }

  Texture * Create1DR32Texture( int w )
  {
Gargaj's avatar
Gargaj committed
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
    D3D11_TEXTURE1D_DESC desc;
    ZeroMemory(&desc,sizeof(D3D11_TEXTURE1D_DESC));
    desc.Width = w;
    desc.Format = DXGI_FORMAT_R32_FLOAT;
    desc.MipLevels = 1;
    desc.ArraySize = 1;
    desc.Usage = D3D11_USAGE_DYNAMIC;
    desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;

    ID3D11Texture1D * pTex = NULL;

    if (pDevice->CreateTexture1D( &desc, NULL, &pTex ) != S_OK)
      return NULL;

    DX11Texture * tex = new DX11Texture();
    tex->width = w;
    tex->height = 1;
    tex->pTexture = pTex;
    tex->type = TEXTURETYPE_1D;
    tex->format = desc.Format;
    CreateResourceView(tex);
    return tex;
Gargaj's avatar
Gargaj committed
870
871
872
873
  }

  void SetShaderTexture( char * szTextureName, Texture * tex )
  {
Gargaj's avatar
Gargaj committed
874
875
876
877
878
879
    D3D11_SHADER_INPUT_BIND_DESC desc;
    if (pShaderReflection->GetResourceBindingDescByName( szTextureName, &desc ) == S_OK)
    {
      DX11Texture * pTex = (DX11Texture *) tex;
      pContext->PSSetShaderResources( desc.BindPoint, 1, &pTex->pResourceView );
    }
Gargaj's avatar
Gargaj committed
880
881
882
883
  }

  bool UpdateR32Texture( Texture * tex, float * data )
  {
Gargaj's avatar
Gargaj committed
884
885
886
887
888
889
    ID3D11Texture1D * pTex = (ID3D11Texture1D *) ((DX11Texture *) tex)->pTexture;

    D3D11_MAPPED_SUBRESOURCE subRes;
    pContext->Map( pTex, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &subRes );
    CopyMemory( subRes.pData, data, sizeof(float) * tex->width );
    pContext->Unmap( pTex, NULL );
Gargaj's avatar
Gargaj committed
890
891
892
893
894
    return true;
  }

  Texture * CreateA8TextureFromData( int w, int h, unsigned char * data )
  {
Gargaj's avatar
Gargaj committed
895
896
897
898
    D3D11_TEXTURE2D_DESC desc;
    ZeroMemory(&desc,sizeof(D3D11_TEXTURE2D_DESC));
    desc.Width = w;
    desc.Height = h;
Gargaj's avatar
Gargaj committed
899
    desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
Gargaj's avatar
Gargaj committed
900
901
902
903
904
    desc.MipLevels = 1;
    desc.ArraySize = 1;
    desc.SampleDesc.Count = 1;
    desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;

Gargaj's avatar
Gargaj committed
905
906
907
    unsigned int * p = new unsigned int[ w * h ];
    for (int i=0; i < w * h; i++)
      p[i] = (data[i] << 24) | 0xFFFFFF;
Gargaj's avatar
Gargaj committed
908
909
    D3D11_SUBRESOURCE_DATA subData;
    ZeroMemory(&subData,sizeof(D3D11_SUBRESOURCE_DATA));
Gargaj's avatar
Gargaj committed
910
911
    subData.pSysMem = p;
    subData.SysMemPitch = w * sizeof(unsigned int);
Gargaj's avatar
Gargaj committed
912
913
914
915
916
917

    ID3D11Texture2D * pTex = NULL;

    if (pDevice->CreateTexture2D( &desc, &subData, &pTex ) != S_OK)
      return NULL;

Gargaj's avatar
Gargaj committed
918
919
    delete[] p;

Gargaj's avatar
Gargaj committed
920
921
922
923
924
925
926
927
    DX11Texture * tex = new DX11Texture();
    tex->width = w;
    tex->height = h;
    tex->pTexture = pTex;
    tex->type = TEXTURETYPE_2D;
    tex->format = desc.Format;
    CreateResourceView(tex);
    return tex;
Gargaj's avatar
Gargaj committed
928
929
  }

Gargaj's avatar
Gargaj committed
930
931
932
933
934
935
936
  void ReleaseTexture( Texture * tex )
  {
    ((DX11Texture *)tex)->pResourceView->Release();
    ((DX11Texture *)tex)->pTexture->Release();
    delete tex;
  }

Gargaj's avatar
Gargaj committed
937
938
939
  //////////////////////////////////////////////////////////////////////////
  // text rendering

940
941
  int nDrawCallCount = 0;
  Texture * lastTexture = NULL;
Gargaj's avatar
Gargaj committed
942
943
  void StartTextRendering()
  {
Gargaj's avatar
Gargaj committed
944
945
    float factor[4] = { 1.0, 1.0, 1.0, 1.0 };
    pContext->VSSetShader( pGUIVertexShader, NULL, NULL );
946
    pContext->PSSetShader( pGUIPixelShader, NULL, NULL );
Gargaj's avatar
Gargaj committed
947
948
949
950
951
952
    pContext->IASetInputLayout( pGUIQuadLayout );
    pContext->VSSetConstantBuffers( 0, 1, &pGUIConstantBuffer );
    pContext->OMSetBlendState( pGUIBlendState, factor, 0xFFFFFFFF );
    pContext->RSSetState( pGUIRasterizerState );

    ID3D11Buffer * buffers[] = { pGUIQuadVB };
953
    UINT stride[] = { sizeof(float) * 7 };
Gargaj's avatar
Gargaj committed
954
    UINT offset[] = { 0 };
Gargaj's avatar
Gargaj committed
955

Gargaj's avatar
Gargaj committed
956
    pContext->IASetVertexBuffers( 0, 1, buffers, stride, offset );
957
958
959
    lastTexture = NULL;
    
    nDrawCallCount = 0;
Gargaj's avatar
Gargaj committed
960
961
962
  }

  int bufferPointer = 0;
963
  unsigned char buffer[GUIQUADVB_SIZE * sizeof(float) * 7];
Gargaj's avatar
Gargaj committed
964
965
966
967
968
  bool lastModeIsQuad = true;
  void __FlushRenderCache()
  {
    if (!bufferPointer) return;

Gargaj's avatar
Gargaj committed
969
970
    D3D11_MAPPED_SUBRESOURCE subRes;
    pContext->Map( pGUIQuadVB, 0, D3D11_MAP_WRITE_DISCARD, NULL, &subRes );
971
    CopyMemory( subRes.pData, buffer, bufferPointer * sizeof(float) * 7 );
Gargaj's avatar
Gargaj committed
972
    pContext->Unmap( pGUIQuadVB, 0 );
Gargaj's avatar
Gargaj committed
973
974

    if (lastModeIsQuad)
Gargaj's avatar
Gargaj committed
975
976
977
    {
      pContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
    }
Gargaj's avatar
Gargaj committed
978
    else
Gargaj's avatar
Gargaj committed
979
980
981
982
    {
      pContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_LINELIST );
    }
    pContext->Draw( bufferPointer, 0 );
983
    nDrawCallCount++;
Gargaj's avatar
Gargaj committed
984
985
986
987
988
989
990
991
992
993

    bufferPointer = 0;
  }
  void __WriteVertexToBuffer( const Vertex & v )
  {
    if (bufferPointer >= GUIQUADVB_SIZE)
    {
      __FlushRenderCache();
    }

994
    float * f = (float*)(buffer + bufferPointer * sizeof(float) * 7);
Gargaj's avatar
Gargaj committed
995
996
997
    *(f++) = v.x;
    *(f++) = v.y;
    *(f++) = 0.0;
Gargaj's avatar
Gargaj committed
998
    *(unsigned int *)(f++) = v.c;
Gargaj's avatar
Gargaj committed
999
1000
    *(f++) = v.u;
    *(f++) = v.v;
1001
    *(f++) = lastTexture ? 0.0 : 1.0;
Gargaj's avatar
Gargaj committed
1002
1003
1004
1005
1006
1007
1008
    bufferPointer++;
  }
  void BindTexture( Texture * tex )
  {
    if (lastTexture != tex)
    {
      lastTexture = tex;
Gargaj's avatar
Gargaj committed
1009
1010
      if (tex)
      {
Gargaj's avatar
Gargaj committed
1011
        __FlushRenderCache();
Gargaj's avatar
Gargaj committed
1012
1013
1014
        DX11Texture * pTex = (DX11Texture *) tex;
        pContext->PSSetShaderResources( 0, 1, &pTex->pResourceView );
      }
Gargaj's avatar
Gargaj committed
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
    }
  }

  void RenderQuad( const Vertex & a, const Vertex & b, const Vertex & c, const Vertex & d )
  {
    if (!lastModeIsQuad)
    {
      __FlushRenderCache();
      lastModeIsQuad = true;
    }
    __WriteVertexToBuffer(a);
    __WriteVertexToBuffer(b);
    __WriteVertexToBuffer(d);
    __WriteVertexToBuffer(b);
    __WriteVertexToBuffer(c);
Gargaj's avatar
Gargaj committed
1030
    __WriteVertexToBuffer(d);
Gargaj's avatar
Gargaj committed
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
  }

  void RenderLine( const Vertex & a, const Vertex & b )
  {
    if (lastModeIsQuad)
    {
      __FlushRenderCache();
      lastModeIsQuad = false;
    }
    __WriteVertexToBuffer(a);
    __WriteVertexToBuffer(b);
  }

  void SetTextRenderingViewport( Scintilla::PRectangle rect )
  {
    __FlushRenderCache();
Gargaj's avatar
Gargaj committed
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057

    pGUIMatrix[ 16 + 0 ] = rect.left;
    pGUIMatrix[ 16 + 1 ] = rect.top;

    D3D11_MAPPED_SUBRESOURCE subRes;
    pContext->Map( pGUIConstantBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &subRes );
    CopyMemory( subRes.pData, &pGUIMatrix, sizeof(float) * 16 * 2 );
    pContext->Unmap( pGUIConstantBuffer, NULL );

    D3D11_RECT rc = { rect.left, rect.top, rect.right, rect.bottom };
    pContext->RSSetScissorRects( 1, &rc );
Gargaj's avatar
Gargaj committed
1058
1059
1060
1061
1062
1063
1064
  }
  void EndTextRendering()
  {
    __FlushRenderCache();
  }

}