Renderer.cpp 24.8 KB
Newer Older
Gargaj's avatar
Gargaj committed
1
#include <windows.h>
Gargaj's avatar
Gargaj committed
2
#include <windowsx.h>
Gargaj's avatar
Gargaj committed
3
#include <tchar.h>
Gargaj's avatar
Gargaj committed
4
#include <d3d9.h>
Gargaj's avatar
Gargaj committed
5
#include <d3dx9.h>
Gargaj's avatar
Gargaj committed
6
7
8
9
10
11
#include "../Renderer.h"

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

Gargaj's avatar
Gargaj committed
12
13
#define DEVTYPE D3DDEVTYPE_HAL

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
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";

Gargaj's avatar
Gargaj committed
58
59
namespace Renderer
{
60
  char * defaultShaderFilename = "shader.dx9.hlsl";
Gargaj's avatar
Gargaj committed
61
  char defaultShader[65536] = 
Gargaj's avatar
Gargaj committed
62
    "texture texTFFT; sampler1D texFFT = sampler_state { Texture = <texTFFT>; }; \n"
63
    "// towards 0.0 is bass / lower freq, towards 1.0 is higher / treble freq\n"
Gargaj's avatar
Gargaj committed
64
    "\n"
65
66
67
68
69
70
71
72
73
    "{%textures:begin%}" // leave off \n here
    "texture raw{%textures:name%}; sampler2D {%textures:name%} = sampler_state { Texture = <raw{%textures:name%}>; };\n"
    "{%textures:end%}"
    "\n"
    "{%midi:begin%}" // leave off \n here
    "float {%midi:name%};\n"
    "{%midi:end%}"
    "float fGlobalTime; // in seconds\n"
    "float2 v2Resolution; // viewport resolution (in pixels)\n"
Gargaj's avatar
Gargaj committed
74
    "\n"
75
76
77
78
79
    "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
80
    "float4 main( float2 TexCoord : TEXCOORD0 ) : COLOR0\n"
Gargaj's avatar
Gargaj committed
81
82
83
    "{\n"
    "  float2 uv = TexCoord;\n"
    "  uv -= 0.5;\n"
Gargaj's avatar
Gargaj committed
84
    "  uv /= float2(v2Resolution.y / v2Resolution.x, 1);"
Gargaj's avatar
Gargaj committed
85
86
87
88
89
90
    "\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
91
    "  float f = tex1D( texFFT, d ).r * 100;\n"
Gargaj's avatar
Gargaj committed
92
93
94
    "  m.x += sin( fGlobalTime ) * 0.1;\n"
    "  m.y += fGlobalTime * 0.25;\n"
    "\n"
95
96
97
    "  float4 t = plas( m * 3.14, fGlobalTime ) / d;\n"
    "  t = saturate( t );\n"
    "  return f + t;\n"
Gargaj's avatar
Gargaj committed
98
    "}";
99
100
101
102
103
104
105
106
107
108
109
  char defaultVertexShader[65536] = 
    "struct VS_INPUT_PP { float3 Pos : POSITION0; float2 TexCoord : TEXCOORD0; };\n"
    "struct VS_OUTPUT_PP { float4 Pos : POSITION0; float2 TexCoord : TEXCOORD0; };\n"
    "\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";
Gargaj's avatar
Gargaj committed
110
111
112

  bool run = true;

Gargaj's avatar
Gargaj committed
113
114
  LPDIRECT3D9 pD3D = NULL;
  LPDIRECT3DDEVICE9 pDevice = NULL;
Gargaj's avatar
Gargaj committed
115
  LPD3DXCONSTANTTABLE pConstantTable = NULL;
116
  LPDIRECT3DVERTEXSHADER9 pVertexShader = NULL;
Gargaj's avatar
Gargaj committed
117
  LPDIRECT3DPIXELSHADER9 theShader = NULL;
Gargaj's avatar
Gargaj committed
118

Gargaj's avatar
Gargaj committed
119
120
  int nWidth = 0;
  int nHeight = 0;
Gargaj's avatar
Gargaj committed
121
122
123
124
125
126
127
128
129
130
131
132
133
  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: 
      {
Gargaj's avatar
Gargaj committed
134
135
        int sciKey = 0;
        switch(wParam)
Gargaj's avatar
Gargaj committed
136
        {
Gargaj's avatar
Gargaj committed
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
        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
162
        case VK_F2:         sciKey = 283;      break;
Gargaj's avatar
Gargaj committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
        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;
Gargaj's avatar
Gargaj committed
184
          keyEventBuffer[keyEventBufferCount].character = 0;
Gargaj's avatar
Gargaj committed
185
186
187
188
189
190
          keyEventBufferCount++;
        }
        //pKeys[wParam] = 1;
      } break;
    case WM_CHAR: 
      {
Gargaj's avatar
Gargaj committed
191
        if (wParam >= 32)
Gargaj's avatar
Gargaj committed
192
193
194
195
196
197
198
        {
          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++;
Gargaj's avatar
Gargaj committed
199
200
201
202
203
204
205
206
207
208
209
        }
        //pKeys[wParam] = 1;
      } break;

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

    case WM_LBUTTONDOWN: 
      {
210
        mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_DOWN;
Gargaj's avatar
Gargaj committed
211
212
213
214
        mouseEventBuffer[mouseEventBufferCount].button = MOUSEBUTTON_LEFT;
        mouseEventBuffer[mouseEventBufferCount].x = GET_X_LPARAM(lParam);
        mouseEventBuffer[mouseEventBufferCount].y = GET_Y_LPARAM(lParam);
        mouseEventBufferCount++;
Gargaj's avatar
Gargaj committed
215
216
      } break;

217
218
219
220
221
222
223
224
    case WM_MOUSEMOVE: 
      {
        mouseEventBuffer[mouseEventBufferCount].eventType = MOUSEEVENTTYPE_MOVE;
        mouseEventBuffer[mouseEventBufferCount].x = GET_X_LPARAM(lParam);
        mouseEventBuffer[mouseEventBufferCount].y = GET_Y_LPARAM(lParam);
        mouseEventBufferCount++;
      } break;

Gargaj's avatar
Gargaj committed
225
226
    case WM_LBUTTONUP: 
      {
227
228
229
230
231
        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++;
Gargaj's avatar
Gargaj committed
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
      } 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) 
Gargaj's avatar
Gargaj committed
256
  {
Gargaj's avatar
Gargaj committed
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
    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
278

279
    hWnd = CreateWindowEx(wExStyle,_T("fwzwnd"),_T("BONZOMATIC - Direct3D 9.0c edition"),wStyle,
Gargaj's avatar
Gargaj committed
280
281
282
283
284
285
      (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) 
Gargaj's avatar
Gargaj committed
286
287
      return false;

Gargaj's avatar
Gargaj committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
    ShowWindow(hWnd, SW_SHOW);
    SetForegroundWindow(hWnd);
    SetFocus(hWnd);

    return true;
  }

  bool InitDirect3D(RENDERER_SETTINGS * pSetup) 
  {
    pD3D=Direct3DCreate9(D3D9b_SDK_VERSION);
    if (!pD3D) return false;

    nWidth  = pSetup->nWidth;
    nHeight = pSetup->nHeight;

    D3DPRESENT_PARAMETERS d3dpp;
    ZeroMemory(&d3dpp,sizeof(d3dpp));

    d3dpp.SwapEffect     = D3DSWAPEFFECT_DISCARD;
    d3dpp.hDeviceWindow  = hWnd;
    d3dpp.Windowed       = pSetup->windowMode != RENDERER_WINDOWMODE_FULLSCREEN;
Gargaj's avatar
Gargaj committed
309
    d3dpp.PresentationInterval = pSetup->bVsync ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
Gargaj's avatar
Gargaj committed
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332

    d3dpp.BackBufferCount  = 1;

    d3dpp.BackBufferWidth  = pSetup->nWidth;
    d3dpp.BackBufferHeight = pSetup->nHeight;

    D3DDISPLAYMODE d3ddm;
    if( FAILED( pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm ) ) )
      return false;

    static D3DFORMAT pBackbufferFormats32[] = {
      D3DFMT_X8R8G8B8,
      D3DFMT_A8R8G8B8,
      D3DFMT_UNKNOWN
    };
    D3DFORMAT * pFormats = pBackbufferFormats32;
    for (int i=0; pFormats[i] != D3DFMT_UNKNOWN; i++)
      if ( SUCCEEDED(pD3D->CheckDeviceType( D3DADAPTER_DEFAULT, DEVTYPE, d3ddm.Format, pFormats[i], d3dpp.Windowed )) )
        d3dpp.BackBufferFormat = pFormats[i];

    if (d3dpp.BackBufferFormat == D3DFMT_UNKNOWN) 
      return false;

333
    d3dpp.EnableAutoDepthStencil = FALSE;
Gargaj's avatar
Gargaj committed
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356

    static D3DMULTISAMPLE_TYPE pMultisampleTypes[]=
    {
      D3DMULTISAMPLE_2_SAMPLES,
      D3DMULTISAMPLE_4_SAMPLES,
      D3DMULTISAMPLE_6_SAMPLES,
      D3DMULTISAMPLE_8_SAMPLES,
      D3DMULTISAMPLE_NONE
    };

    d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;

    HRESULT h;
    h = pD3D->CreateDevice( D3DADAPTER_DEFAULT, DEVTYPE, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &pDevice);
    if (h != D3D_OK) 
    {
      h = pD3D->CreateDevice( D3DADAPTER_DEFAULT, DEVTYPE, hWnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &pDevice);
      if(h != D3D_OK) 
      {
        return false;
      }
    }

Gargaj's avatar
Gargaj committed
357
    pDevice->SetRenderState( D3DRS_LIGHTING, FALSE );
Gargaj's avatar
Gargaj committed
358
359
360
361
362

    for (int x=0; x<4; x++) 
    {
      pDevice->SetSamplerState( x, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
      pDevice->SetSamplerState( x, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
363
      pDevice->SetSamplerState( x, D3DSAMP_MIPFILTER, D3DTEXF_NONE);
Gargaj's avatar
Gargaj committed
364
365
366
367
    }
    return 1;
  }

Gargaj's avatar
Gargaj committed
368
  LPDIRECT3DVERTEXBUFFER9 pFullscreenQuadVB = NULL;
Gargaj's avatar
Gargaj committed
369
  LPDIRECT3DVERTEXBUFFER9 pGUIQuadVB = NULL;
Gargaj's avatar
Gargaj committed
370
  LPDIRECT3DVERTEXDECLARATION9 pFullscreenQuadVertexDecl = NULL;
Gargaj's avatar
Gargaj committed
371
372

#define GUIQUADVB_SIZE (128*6)
Gargaj's avatar
Gargaj committed
373

Gargaj's avatar
Gargaj committed
374
375
376
377
378
379
380
  bool Open( RENDERER_SETTINGS * settings )
  {
    if (!InitWindow(settings))
      return false;

    if (!InitDirect3D(settings))
      return false;
Gargaj's avatar
Gargaj committed
381

Gargaj's avatar
Gargaj committed
382
    static D3DVERTEXELEMENT9 pFullscreenQuadElements[] = 
Gargaj's avatar
Gargaj committed
383
384
385
386
387
388
389
390
391
    {
      { 0, 0*sizeof(float), D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
      { 0, 3*sizeof(float), D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
      D3DDECL_END()
    };

    static float pQuad[] = {
      -1.0, -1.0,  0.0, 0.0, 0.0,
      -1.0,  1.0,  0.0, 0.0, 1.0,
392
       1.0, -1.0,  0.0, 1.0, 0.0,
Gargaj's avatar
Gargaj committed
393
394
395
396
397
398
399
400
401
       1.0,  1.0,  0.0, 1.0, 1.0,
    };

    pDevice->CreateVertexBuffer( 4 * 5 * sizeof(float), D3DUSAGE_WRITEONLY, D3DFVF_XYZ | D3DFVF_TEX1, D3DPOOL_DEFAULT, &pFullscreenQuadVB, NULL);
    void * v;
    pFullscreenQuadVB->Lock( 0, 4 * 5 * sizeof(float), &v, NULL );
    CopyMemory( v, pQuad, 4 * 5 * sizeof(float) );
    pFullscreenQuadVB->Unlock();

Gargaj's avatar
Gargaj committed
402
    pDevice->CreateVertexDeclaration( pFullscreenQuadElements, &pFullscreenQuadVertexDecl );
Gargaj's avatar
Gargaj committed
403
404
405

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

406
407
408
409
410
411
412
413
    pDevice->CreateVertexBuffer( GUIQUADVB_SIZE * 6 * sizeof(float), D3DUSAGE_WRITEONLY, D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1, D3DPOOL_DEFAULT, &pGUIQuadVB, NULL);

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

    LPD3DXBUFFER pShader = NULL;
    LPD3DXBUFFER pErrors = NULL;

    if (D3DXCompileShader( defaultVertexShader, strlen(defaultVertexShader), NULL, NULL, "main", "vs_3_0", NULL, &pShader, &pErrors, NULL ) != D3D_OK)
Gargaj's avatar
Gargaj committed
414
    {
415
416
      return false;
    }
Gargaj's avatar
Gargaj committed
417

418
419
420
421
    if (pDevice->CreateVertexShader( (DWORD*)pShader->GetBufferPointer(), &pVertexShader ) != D3D_OK)
    {
      return false;
    }
Gargaj's avatar
Gargaj committed
422

Gargaj's avatar
Gargaj committed
423
424
425
    return true;
  }

Gargaj's avatar
Gargaj committed
426
  unsigned int nCacheFlushCount = 0;
Gargaj's avatar
Gargaj committed
427
428
  void StartFrame()
  {
Gargaj's avatar
Gargaj committed
429
    nCacheFlushCount = 0;
Gargaj's avatar
Gargaj committed
430
    MSG msg;
Gargaj's avatar
Gargaj committed
431
432
    if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) 
    {
Gargaj's avatar
Gargaj committed
433
434
435
436
      TranslateMessage( &msg );
      DispatchMessage( &msg );
    }

Gargaj's avatar
Gargaj committed
437
438
    pDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER , 0xFF808080, 1.0f, 0 );
    pDevice->BeginScene();
Gargaj's avatar
Gargaj committed
439
440
441
  }
  void EndFrame()
  {
Gargaj's avatar
Gargaj committed
442
443
    pDevice->EndScene();
    pDevice->Present( NULL, NULL, NULL, NULL );
Gargaj's avatar
Gargaj committed
444
445
446
447
448
449
450
  }
  bool WantsToQuit()
  {
    return !run;
  }
  void Close()
  {
Gargaj's avatar
Gargaj committed
451
452
453
454
455
    if (pFullscreenQuadVB) pFullscreenQuadVB->Release();
    if (pFullscreenQuadVertexDecl) pFullscreenQuadVertexDecl->Release();
    if (pGUIQuadVB) pGUIQuadVB->Release();
    if (pVertexShader) pVertexShader->Release();
    if (theShader) theShader->Release();
Gargaj's avatar
Gargaj committed
456
457
    if (pDevice) pDevice->Release();
    if (pD3D) pD3D->Release();
Gargaj's avatar
Gargaj committed
458
459
460
461
462
    if (!hWnd) 
    {
      DestroyWindow(hWnd);
      UnregisterClass(_T("fwzwnd"),GetModuleHandle(NULL));
    }
Gargaj's avatar
Gargaj committed
463
464
465
466
  }

  void RenderFullscreenQuad()
  {
Gargaj's avatar
Gargaj committed
467
468
    pDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, false );

469
    pDevice->SetVertexShader( pVertexShader );
Gargaj's avatar
Gargaj committed
470
471
    pDevice->SetPixelShader( theShader );
    
Gargaj's avatar
Gargaj committed
472
    pDevice->SetVertexDeclaration( pFullscreenQuadVertexDecl );
Gargaj's avatar
Gargaj committed
473
474
    pDevice->SetStreamSource( 0, pFullscreenQuadVB, 0, sizeof(float) * 5 ); 
    pDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 );
Gargaj's avatar
Gargaj committed
475
476
477
478
  }

  bool ReloadShader( char * szShaderCode, int nShaderCodeSize, char * szErrorBuffer, int nErrorBufferSize )
  {
Gargaj's avatar
Gargaj committed
479
480
481
    LPD3DXBUFFER pShader = NULL;
    LPD3DXBUFFER pErrors = NULL;

482
    if (D3DXCompileShader( szShaderCode, nShaderCodeSize, NULL, NULL, "main", "ps_3_0", NULL, &pShader, &pErrors, &pConstantTable ) != D3D_OK)
Gargaj's avatar
Gargaj committed
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
    {
      memset( szErrorBuffer, 0, nErrorBufferSize );
      strncpy( szErrorBuffer, (char*)pErrors->GetBufferPointer(), nErrorBufferSize - 1 );
      return false;
    }

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

    if (pDevice->CreatePixelShader( (DWORD*)pShader->GetBufferPointer(), &theShader ) != D3D_OK)
    {
      return false;
    }

Gargaj's avatar
Gargaj committed
500
501
502
503
504
    return true;
  }

  void SetShaderConstant( char * szConstName, float x )
  {
Gargaj's avatar
Gargaj committed
505
    pConstantTable->SetFloat( pDevice, szConstName, x );
Gargaj's avatar
Gargaj committed
506
507
508
509
  }

  void SetShaderConstant( char * szConstName, float x, float y )
  {
Gargaj's avatar
Gargaj committed
510
    pConstantTable->SetVector( pDevice, szConstName, &D3DXVECTOR4(x, y, 0, 0) );
Gargaj's avatar
Gargaj committed
511
512
513
514
  }

  struct DX9Texture : public Texture
  {
Gargaj's avatar
Gargaj committed
515
    LPDIRECT3DTEXTURE9 pTexture;
Gargaj's avatar
Gargaj committed
516
517
518
519
520
  };

  int textureUnit = 0;
  Texture * CreateRGBA8TextureFromFile( char * szFilename )
  {
Gargaj's avatar
Gargaj committed
521
522
523
524
525
526
527
    LPDIRECT3DTEXTURE9 pTex = NULL;
    D3DXIMAGE_INFO info;
    HRESULT h = D3DXCreateTextureFromFileExA(
      pDevice,
      szFilename,
      D3DX_DEFAULT,
      D3DX_DEFAULT,
528
      0,
Gargaj's avatar
Gargaj committed
529
530
531
532
533
534
535
536
537
538
539
540
541
      NULL,
      D3DFMT_FROM_FILE,
      D3DPOOL_DEFAULT,
      D3DX_FILTER_NONE,
      D3DX_DEFAULT,
      NULL,
      &info,
      NULL,
      &pTex);

    if (!pTex)
      return NULL;

Gargaj's avatar
Gargaj committed
542
    DX9Texture * tex = new DX9Texture();
Gargaj's avatar
Gargaj committed
543
544
545
    tex->pTexture = pTex;
    tex->width = info.Width;
    tex->height = info.Height;
Gargaj's avatar
Gargaj committed
546
547
548
549
550
551
    tex->type = TEXTURETYPE_2D;
    return tex;
  }

  Texture * Create1DR32Texture( int w )
  {
Gargaj's avatar
Gargaj committed
552
553
554
555
556
557
558
559
560
561
562
    LPDIRECT3DTEXTURE9 pTex = NULL;
    pDevice->CreateTexture( w, 1, 0, D3DUSAGE_DYNAMIC, D3DFMT_R32F, D3DPOOL_DEFAULT, &pTex, NULL );

    if (!pTex)
      return NULL;

    D3DLOCKED_RECT rect;
    pTex->LockRect( 0, &rect, NULL, NULL );
    memset( rect.pBits, 0, w * sizeof(float) );
    pTex->UnlockRect(0);

Gargaj's avatar
Gargaj committed
563
    DX9Texture * tex = new DX9Texture();
Gargaj's avatar
Gargaj committed
564
    tex->pTexture = pTex;
Gargaj's avatar
Gargaj committed
565
566
567
568
569
570
571
572
    tex->width = w;
    tex->height = 1;
    tex->type = TEXTURETYPE_1D;
    return tex;
  }

  void SetShaderTexture( char * szTextureName, Texture * tex )
  {
Gargaj's avatar
Gargaj committed
573
    int idx = pConstantTable->GetSamplerIndex( szTextureName );
Gargaj's avatar
Gargaj committed
574
    if (idx >= 0)
575
576
577
578
    {
      pDevice->SetSamplerState( idx, D3DSAMP_SRGBTEXTURE, TRUE );
      pDevice->SetSamplerState( idx, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP );
      pDevice->SetSamplerState( idx, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP );
Gargaj's avatar
Gargaj committed
579
      pDevice->SetTexture( idx, ((DX9Texture *)tex)->pTexture );
580
    }
Gargaj's avatar
Gargaj committed
581
582
583
584
  }

  bool UpdateR32Texture( Texture * tex, float * data )
  {
Gargaj's avatar
Gargaj committed
585
586
587
588
589
590
591
    LPDIRECT3DTEXTURE9 pTex = ((DX9Texture *)tex)->pTexture;
    
    D3DLOCKED_RECT rect;
    pTex->LockRect( 0, &rect, NULL, D3DLOCK_DISCARD );
    memcpy( rect.pBits, data, tex->width * sizeof(float) );
    pTex->UnlockRect(0);

Gargaj's avatar
Gargaj committed
592
593
594
595
596
    return true;
  }

  Texture * CreateA8TextureFromData( int w, int h, unsigned char * data )
  {
Gargaj's avatar
Gargaj committed
597
    LPDIRECT3DTEXTURE9 pTex = NULL;
Gargaj's avatar
Gargaj committed
598
    pDevice->CreateTexture( w, h, 0, NULL, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &pTex, NULL );
Gargaj's avatar
Gargaj committed
599
600
601
602
603
604
605
606
607
608

    if (!pTex)
      return NULL;

    D3DLOCKED_RECT rect;
    pTex->LockRect( 0, &rect, NULL, NULL );
    unsigned char * src = data;
    unsigned char * dst = (unsigned char *)rect.pBits;
    for (int i=0; i<h; i++)
    {
Gargaj's avatar
Gargaj committed
609
610
611
612
613
614
615
616
      unsigned char * srcLine = src;
      unsigned int * dstLine = (unsigned int *)dst;
      for (int j=0; j<w; j++)
      {
        *dstLine = (*srcLine << 24) | 0xFFFFFF;
        srcLine++;
        dstLine++;
      }
Gargaj's avatar
Gargaj committed
617
618
619
620
621
      src += w * sizeof(unsigned char);
      dst += rect.Pitch;
    }
    pTex->UnlockRect(0);

Gargaj's avatar
Gargaj committed
622
    DX9Texture * tex = new DX9Texture();
Gargaj's avatar
Gargaj committed
623
    tex->pTexture = pTex;
Gargaj's avatar
Gargaj committed
624
    tex->width = w;
Gargaj's avatar
Gargaj committed
625
    tex->height = h;
Gargaj's avatar
Gargaj committed
626
627
628
629
    tex->type = TEXTURETYPE_1D;
    return tex;
  }

Gargaj's avatar
Gargaj committed
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
  //////////////////////////////////////////////////////////////////////////
  // text rendering


  void StartTextRendering()
  {
    pDevice->SetVertexShader( NULL );
    pDevice->SetPixelShader( NULL );
    pDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, TRUE );
    //pDevice->SetVertexDeclaration( pGUIVertexDecl );
    pDevice->SetFVF(D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1);
    pDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
    pDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
    pDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );

    D3DXMATRIX mat;
    D3DXMatrixIdentity( &mat );
    pDevice->SetTransform( D3DTS_VIEW, &mat );
    pDevice->SetTransform( D3DTS_WORLD, &mat );
    D3DXMatrixOrthoOffCenterLH( (D3DXMATRIX*)&mat, 0, nWidth, nHeight, 0, -1.0f, 1.0f );
    pDevice->SetTransform( D3DTS_PROJECTION, &mat );

Gargaj's avatar
Gargaj committed
652
    pDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
Gargaj's avatar
Gargaj committed
653
    pDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE );
Gargaj's avatar
Gargaj committed
654
    pDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_TEXTURE );
Gargaj's avatar
Gargaj committed
655
656
657
658
659
    pDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
    pDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE );
    pDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_TEXTURE );
  }

Gargaj's avatar
Gargaj committed
660
661
  void ReleaseTexture( Texture * tex )
  {
Gargaj's avatar
Gargaj committed
662
663
    ((DX9Texture *)tex)->pTexture->Release();
    delete tex;
Gargaj's avatar
Gargaj committed
664
665
  }

Gargaj's avatar
Gargaj committed
666
667
668
669
670
671
672
  int bufferPointer = 0;
  unsigned char buffer[GUIQUADVB_SIZE * sizeof(float) * 6];
  bool lastModeIsQuad = true;
  void __FlushRenderCache()
  {
    if (!bufferPointer) return;

Gargaj's avatar
Gargaj committed
673
    nCacheFlushCount++;
Gargaj's avatar
Gargaj committed
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
    void * v = NULL;
    pGUIQuadVB->Lock( 0, bufferPointer * sizeof(float) * 6, &v, NULL );
    CopyMemory( v, buffer, bufferPointer * sizeof(float) * 6 );
    pGUIQuadVB->Unlock();

    pDevice->SetStreamSource( 0, pGUIQuadVB, 0, sizeof(float) * 6 ); 
    if (lastModeIsQuad)
      pDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, bufferPointer / 3 );
    else
      pDevice->DrawPrimitive( D3DPT_LINELIST, 0, bufferPointer / 2 );

    bufferPointer = 0;
  }
  inline unsigned int _dxARGBtoABGR(unsigned int abgr)
  {
    return (abgr&0xff00ff00)+((abgr<<16)&0x00ff0000)+((abgr>>16)&0x000000ff);
  }
Gargaj's avatar
Gargaj committed
691
  Texture * lastTexture = NULL;
Gargaj's avatar
Gargaj committed
692
  void __WriteVertexToBuffer( const Vertex & v )
Gargaj's avatar
Gargaj committed
693
694
695
696
697
698
699
700
701
702
703
  {
    if (bufferPointer >= GUIQUADVB_SIZE)
    {
      __FlushRenderCache();
    }

    float * f = (float*)(buffer + bufferPointer * sizeof(float) * 6);
    *(f++) = v.x;
    *(f++) = v.y;
    *(f++) = 0.0;
    *(unsigned int *)(f++) = _dxARGBtoABGR( v.c );
Gargaj's avatar
Gargaj committed
704
705
    *(f++) = v.u + (lastTexture ? (0.5 / (float)lastTexture->width ) : 0.0);
    *(f++) = v.v + (lastTexture ? (0.5 / (float)lastTexture->height) : 0.0);
Gargaj's avatar
Gargaj committed
706
707
    bufferPointer++;
  }
Gargaj's avatar
Gargaj committed
708
709
  void BindTexture( Texture * tex )
  {
Gargaj's avatar
Gargaj committed
710
711
712
713
714
715
    if (lastTexture != tex)
    {
      __FlushRenderCache();
      lastTexture = tex;
      pDevice->SetTexture( 0, tex ? ((DX9Texture *)tex)->pTexture : NULL );
    }
Gargaj's avatar
Gargaj committed
716
717
  }

Gargaj's avatar
Gargaj committed
718
  void RenderQuad( const Vertex & a, const Vertex & b, const Vertex & c, const Vertex & d )
Gargaj's avatar
Gargaj committed
719
  {
Gargaj's avatar
Gargaj committed
720
721
722
723
724
725
726
727
728
729
    if (!lastModeIsQuad)
    {
      __FlushRenderCache();
      lastModeIsQuad = true;
    }
    __WriteVertexToBuffer(a);
    __WriteVertexToBuffer(b);
    __WriteVertexToBuffer(d);
    __WriteVertexToBuffer(b);
    __WriteVertexToBuffer(c);
730
    __WriteVertexToBuffer(d);
Gargaj's avatar
Gargaj committed
731
732
  }

Gargaj's avatar
Gargaj committed
733
  void RenderLine( const Vertex & a, const Vertex & b )
Gargaj's avatar
Gargaj committed
734
  {
Gargaj's avatar
Gargaj committed
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
    if (lastModeIsQuad)
    {
      __FlushRenderCache();
      lastModeIsQuad = false;
    }
    __WriteVertexToBuffer(a);
    __WriteVertexToBuffer(b);
  }

  void SetTextRenderingViewport( Scintilla::PRectangle rect )
  {
    __FlushRenderCache();
    D3DXMATRIX mat;
    D3DXMatrixIdentity( &mat );
    mat._41 = rect.left;
    mat._42 = rect.top;
    pDevice->SetTransform( D3DTS_WORLD, &mat );

    RECT rc = { rect.left, rect.top, rect.right, rect.bottom };
    pDevice->SetScissorRect( &rc );
  }
  void EndTextRendering()
  {
    __FlushRenderCache();
    pDevice->SetRenderState( D3DRS_SCISSORTESTENABLE, false );
    pDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, false );
Gargaj's avatar
Gargaj committed
761
762
763
  }

}