blob: 00c3fcf32d3f021dc948a69813e43bf27d73edc3 [file] [log] [blame]
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001//
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6
daniel@transgaming.com1d6aff22012-11-28 19:30:42 +00007// Renderer9.cpp: Implements a back-end specific class for the D3D9 renderer.
daniel@transgaming.com621ce052012-10-31 17:52:29 +00008
daniel@transgaming.com621ce052012-10-31 17:52:29 +00009#include "common/debug.h"
daniel@transgaming.com493d4f82012-11-28 19:35:45 +000010#include "libGLESv2/main.h"
daniel@transgaming.com621ce052012-10-31 17:52:29 +000011#include "libGLESv2/utilities.h"
daniel@transgaming.com493d4f82012-11-28 19:35:45 +000012#include "libGLESv2/mathutil.h"
daniel@transgaming.com91207b72012-11-28 20:56:43 +000013#include "libGLESv2/Buffer.h"
daniel@transgaming.com493d4f82012-11-28 19:35:45 +000014#include "libGLESv2/Framebuffer.h"
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +000015#include "libGLESv2/Program.h"
16#include "libGLESv2/ProgramBinary.h"
daniel@transgaming.com50aadb02012-11-28 21:06:11 +000017#include "libGLESv2/renderer/IndexDataManager.h"
18#include "libGLESv2/renderer/VertexDataManager.h"
daniel@transgaming.com2507f412012-10-31 18:46:48 +000019#include "libGLESv2/renderer/Renderer9.h"
daniel@transgaming.comd8e36562012-10-31 19:52:19 +000020#include "libGLESv2/renderer/renderer9_utils.h"
daniel@transgaming.coma9c71422012-11-28 20:58:45 +000021#include "libGLESv2/renderer/ShaderExecutable9.h"
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +000022#include "libGLESv2/renderer/SwapChain9.h"
daniel@transgaming.com34da3972012-12-20 21:10:29 +000023#include "libGLESv2/renderer/TextureStorage9.h"
daniel@transgaming.com4ba24062012-12-20 20:54:24 +000024#include "libGLESv2/renderer/Image9.h"
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000025#include "libGLESv2/renderer/Blit.h"
daniel@transgaming.comd186dc72012-11-28 19:40:16 +000026#include "libGLESv2/renderer/RenderTarget9.h"
daniel@transgaming.com3f255b42012-12-20 21:07:35 +000027#include "libGLESv2/renderer/VertexBuffer9.h"
daniel@transgaming.com0b6d7742012-12-20 21:09:47 +000028#include "libGLESv2/renderer/IndexBuffer9.h"
daniel@transgaming.com621ce052012-10-31 17:52:29 +000029
daniel@transgaming.com3281f972012-10-31 18:38:51 +000030#include "libEGL/Config.h"
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000031#include "libEGL/Display.h"
32
daniel@transgaming.com621ce052012-10-31 17:52:29 +000033// Can also be enabled by defining FORCE_REF_RAST in the project's predefined macros
34#define REF_RAST 0
35
36// The "Debug This Pixel..." feature in PIX often fails when using the
37// D3D9Ex interfaces. In order to get debug pixel to work on a Vista/Win 7
38// machine, define "ANGLE_ENABLE_D3D9EX=0" in your project file.
39#if !defined(ANGLE_ENABLE_D3D9EX)
40// Enables use of the IDirect3D9Ex interface, when available
41#define ANGLE_ENABLE_D3D9EX 1
42#endif // !defined(ANGLE_ENABLE_D3D9EX)
43
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +000044namespace rx
daniel@transgaming.com621ce052012-10-31 17:52:29 +000045{
daniel@transgaming.com222ee082012-11-28 19:31:49 +000046static const D3DFORMAT RenderTargetFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000047 {
48 D3DFMT_A1R5G5B5,
49 // D3DFMT_A2R10G10B10, // The color_ramp conformance test uses ReadPixels with UNSIGNED_BYTE causing it to think that rendering skipped a colour value.
50 D3DFMT_A8R8G8B8,
51 D3DFMT_R5G6B5,
52 // D3DFMT_X1R5G5B5, // Has no compatible OpenGL ES renderbuffer format
53 D3DFMT_X8R8G8B8
54 };
55
daniel@transgaming.com222ee082012-11-28 19:31:49 +000056static const D3DFORMAT DepthStencilFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000057 {
58 D3DFMT_UNKNOWN,
59 // D3DFMT_D16_LOCKABLE,
60 D3DFMT_D32,
61 // D3DFMT_D15S1,
62 D3DFMT_D24S8,
63 D3DFMT_D24X8,
64 // D3DFMT_D24X4S4,
65 D3DFMT_D16,
66 // D3DFMT_D32F_LOCKABLE,
67 // D3DFMT_D24FS8
68 };
daniel@transgaming.com621ce052012-10-31 17:52:29 +000069
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000070Renderer9::Renderer9(egl::Display *display, HDC hDc, bool softwareDevice) : Renderer(display), mDc(hDc), mSoftwareDevice(softwareDevice)
daniel@transgaming.com621ce052012-10-31 17:52:29 +000071{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000072 mD3d9Module = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000073
74 mD3d9 = NULL;
75 mD3d9Ex = NULL;
76 mDevice = NULL;
77 mDeviceEx = NULL;
78 mDeviceWindow = NULL;
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000079 mBlit = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000080
81 mAdapter = D3DADAPTER_DEFAULT;
82
83 #if REF_RAST == 1 || defined(FORCE_REF_RAST)
84 mDeviceType = D3DDEVTYPE_REF;
85 #else
86 mDeviceType = D3DDEVTYPE_HAL;
87 #endif
88
89 mDeviceLost = false;
daniel@transgaming.comb7833982012-10-31 18:31:46 +000090
91 mMaxSupportedSamples = 0;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +000092
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +000093 mMaskedClearSavedState = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +000094
95 mVertexDataManager = NULL;
96 mIndexDataManager = NULL;
97 mLineLoopIB = NULL;
daniel@transgaming.come4e1a332012-12-20 20:52:09 +000098
99 mMaxNullColorbufferLRU = 0;
100 for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
101 {
102 mNullColorbufferCache[i].lruCount = 0;
103 mNullColorbufferCache[i].width = 0;
104 mNullColorbufferCache[i].height = 0;
105 mNullColorbufferCache[i].buffer = NULL;
106 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000107}
108
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000109Renderer9::~Renderer9()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000110{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000111 releaseDeviceResources();
112
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000113 if (mDevice)
114 {
115 // If the device is lost, reset it first to prevent leaving the driver in an unstable state
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000116 if (testDeviceLost(false))
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000117 {
118 resetDevice();
119 }
120
121 mDevice->Release();
122 mDevice = NULL;
123 }
124
125 if (mDeviceEx)
126 {
127 mDeviceEx->Release();
128 mDeviceEx = NULL;
129 }
130
131 if (mD3d9)
132 {
133 mD3d9->Release();
134 mD3d9 = NULL;
135 }
136
137 if (mDeviceWindow)
138 {
139 DestroyWindow(mDeviceWindow);
140 mDeviceWindow = NULL;
141 }
142
143 if (mD3d9Ex)
144 {
145 mD3d9Ex->Release();
146 mD3d9Ex = NULL;
147 }
148
149 if (mD3d9Module)
150 {
151 mD3d9Module = NULL;
152 }
153
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000154 while (!mMultiSampleSupport.empty())
155 {
156 delete [] mMultiSampleSupport.begin()->second;
157 mMultiSampleSupport.erase(mMultiSampleSupport.begin());
158 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000159}
160
daniel@transgaming.comb64ed282012-11-28 20:54:02 +0000161Renderer9 *Renderer9::makeRenderer9(Renderer *renderer)
162{
163 ASSERT(dynamic_cast<rx::Renderer9*>(renderer) != NULL);
164 return static_cast<rx::Renderer9*>(renderer);
165}
166
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000167EGLint Renderer9::initialize()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000168{
daniel@transgaming.com25e16af2012-11-28 21:05:57 +0000169 if (!initializeCompiler())
170 {
171 return EGL_NOT_INITIALIZED;
172 }
173
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +0000174 if (mSoftwareDevice)
175 {
176 mD3d9Module = GetModuleHandle(TEXT("swiftshader_d3d9.dll"));
177 }
178 else
179 {
180 mD3d9Module = GetModuleHandle(TEXT("d3d9.dll"));
181 }
182
183 if (mD3d9Module == NULL)
184 {
185 ERR("No D3D9 module found - aborting!\n");
186 return EGL_NOT_INITIALIZED;
187 }
188
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000189 typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex**);
190 Direct3DCreate9ExFunc Direct3DCreate9ExPtr = reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
191
192 // Use Direct3D9Ex if available. Among other things, this version is less
193 // inclined to report a lost context, for example when the user switches
194 // desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are available.
195 if (ANGLE_ENABLE_D3D9EX && Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9Ex)))
196 {
197 ASSERT(mD3d9Ex);
198 mD3d9Ex->QueryInterface(IID_IDirect3D9, reinterpret_cast<void**>(&mD3d9));
199 ASSERT(mD3d9);
200 }
201 else
202 {
203 mD3d9 = Direct3DCreate9(D3D_SDK_VERSION);
204 }
205
206 if (!mD3d9)
207 {
208 ERR("Could not create D3D9 device - aborting!\n");
209 return EGL_NOT_INITIALIZED;
210 }
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000211
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000212 if (mDc != NULL)
213 {
214 // UNIMPLEMENTED(); // FIXME: Determine which adapter index the device context corresponds to
215 }
216
217 HRESULT result;
218
219 // Give up on getting device caps after about one second.
220 for (int i = 0; i < 10; ++i)
221 {
222 result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);
223 if (SUCCEEDED(result))
224 {
225 break;
226 }
227 else if (result == D3DERR_NOTAVAILABLE)
228 {
229 Sleep(100); // Give the driver some time to initialize/recover
230 }
231 else if (FAILED(result)) // D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY, D3DERR_INVALIDDEVICE, or another error we can't recover from
232 {
233 ERR("failed to get device caps (0x%x)\n", result);
234 return EGL_NOT_INITIALIZED;
235 }
236 }
237
238 if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
239 {
240 ERR("Renderer does not support PS 2.0. aborting!\n");
241 return EGL_NOT_INITIALIZED;
242 }
243
244 // When DirectX9 is running with an older DirectX8 driver, a StretchRect from a regular texture to a render target texture is not supported.
245 // This is required by Texture2D::convertToRenderTarget.
246 if ((mDeviceCaps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) == 0)
247 {
248 ERR("Renderer does not support stretctrect from textures!\n");
249 return EGL_NOT_INITIALIZED;
250 }
251
252 mD3d9->GetAdapterIdentifier(mAdapter, 0, &mAdapterIdentifier);
253
254 // ATI cards on XP have problems with non-power-of-two textures.
255 mSupportsNonPower2Textures = !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_POW2) &&
256 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP_POW2) &&
257 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) &&
258 !(getComparableOSVersion() < versionWindowsVista && mAdapterIdentifier.VendorId == VENDOR_ID_AMD);
259
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000260 // Must support a minimum of 2:1 anisotropy for max anisotropy to be considered supported, per the spec
261 mSupportsTextureFilterAnisotropy = ((mDeviceCaps.RasterCaps & D3DPRASTERCAPS_ANISOTROPY) && (mDeviceCaps.MaxAnisotropy >= 2));
262
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000263 mMinSwapInterval = 4;
264 mMaxSwapInterval = 0;
265
266 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE)
267 {
268 mMinSwapInterval = std::min(mMinSwapInterval, 0);
269 mMaxSwapInterval = std::max(mMaxSwapInterval, 0);
270 }
271 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)
272 {
273 mMinSwapInterval = std::min(mMinSwapInterval, 1);
274 mMaxSwapInterval = std::max(mMaxSwapInterval, 1);
275 }
276 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)
277 {
278 mMinSwapInterval = std::min(mMinSwapInterval, 2);
279 mMaxSwapInterval = std::max(mMaxSwapInterval, 2);
280 }
281 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)
282 {
283 mMinSwapInterval = std::min(mMinSwapInterval, 3);
284 mMaxSwapInterval = std::max(mMaxSwapInterval, 3);
285 }
286 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)
287 {
288 mMinSwapInterval = std::min(mMinSwapInterval, 4);
289 mMaxSwapInterval = std::max(mMaxSwapInterval, 4);
290 }
291
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000292 int max = 0;
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000293 for (int i = 0; i < sizeof(RenderTargetFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000294 {
295 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000296 getMultiSampleSupport(RenderTargetFormats[i], multisampleArray);
297 mMultiSampleSupport[RenderTargetFormats[i]] = multisampleArray;
daniel@transgaming.com92955622012-10-31 18:38:41 +0000298
299 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
300 {
301 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
302 {
303 max = j;
304 }
305 }
306 }
307
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000308 for (int i = 0; i < sizeof(DepthStencilFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000309 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000310 if (DepthStencilFormats[i] == D3DFMT_UNKNOWN)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000311 continue;
312
313 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000314 getMultiSampleSupport(DepthStencilFormats[i], multisampleArray);
315 mMultiSampleSupport[DepthStencilFormats[i]] = multisampleArray;
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000316
317 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
318 {
319 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
320 {
321 max = j;
322 }
323 }
324 }
325
326 mMaxSupportedSamples = max;
327
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000328 static const TCHAR windowName[] = TEXT("AngleHiddenWindow");
329 static const TCHAR className[] = TEXT("STATIC");
330
331 mDeviceWindow = CreateWindowEx(WS_EX_NOACTIVATE, className, windowName, WS_DISABLED | WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
332
333 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
334 DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE | D3DCREATE_NOWINDOWCHANGES;
335
336 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE, &presentParameters, &mDevice);
337 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DEVICELOST)
338 {
339 return EGL_BAD_ALLOC;
340 }
341
342 if (FAILED(result))
343 {
344 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &presentParameters, &mDevice);
345
346 if (FAILED(result))
347 {
348 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_NOTAVAILABLE || result == D3DERR_DEVICELOST);
349 return EGL_BAD_ALLOC;
350 }
351 }
352
353 if (mD3d9Ex)
354 {
355 result = mDevice->QueryInterface(IID_IDirect3DDevice9Ex, (void**) &mDeviceEx);
356 ASSERT(SUCCEEDED(result));
357 }
358
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000359 mVertexShaderCache.initialize(mDevice);
360 mPixelShaderCache.initialize(mDevice);
361
daniel@transgaming.com669c9952013-01-11 04:08:16 +0000362 // Check occlusion query support
363 IDirect3DQuery9 *occlusionQuery = NULL;
364 if (SUCCEEDED(mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &occlusionQuery)) && occlusionQuery)
365 {
366 occlusionQuery->Release();
367 mOcclusionQuerySupport = true;
368 }
369 else
370 {
371 mOcclusionQuerySupport = false;
372 }
373
374 // Check event query support
375 IDirect3DQuery9 *eventQuery = NULL;
376 if (SUCCEEDED(mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &eventQuery)) && eventQuery)
377 {
378 eventQuery->Release();
379 mEventQuerySupport = true;
380 }
381 else
382 {
383 mEventQuerySupport = false;
384 }
385
386 D3DDISPLAYMODE currentDisplayMode;
387 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
388
389 // Check vertex texture support
390 // Only Direct3D 10 ready devices support all the necessary vertex texture formats.
391 // We test this using D3D9 by checking support for the R16F format.
392 mVertexTextureSupport = mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0) &&
393 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
394 D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F));
395
396 // Check depth texture support
397 // we use INTZ for depth textures in Direct3D9
398 // we also want NULL texture support to ensure the we can make depth-only FBOs
399 // see http://aras-p.info/texts/D3D9GPUHacks.html
400 mDepthTextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
401 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ)) &&
402 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
403 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
404
405 // Check 32 bit floating point texture support
406 mFloat32FilterSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
407 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
408 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
409 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
410
411 mFloat32RenderSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
412 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
413 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
414 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
415
416 if (!mFloat32FilterSupport && !mFloat32RenderSupport)
417 {
418 mFloat32TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
419 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
420 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
421 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
422 }
423 else
424 {
425 mFloat32TextureSupport = true;
426 }
427
428 // Check 16 bit floating point texture support
429 mFloat16FilterSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
430 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
431 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
432 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
433
434 mFloat16RenderSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
435 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
436 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
437 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
438
439 if (!mFloat16FilterSupport && !mFloat16RenderSupport)
440 {
441 mFloat16TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
442 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
443 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
444 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
445 }
446 else
447 {
448 mFloat16TextureSupport = true;
449 }
450
451 // Check DXT texture support
452 mDXT1TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
453 mDXT3TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
454 mDXT5TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
455
456 // Check luminance[alpha] texture support
457 mLuminanceTextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
458 mLuminanceAlphaTextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
459
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000460 initializeDevice();
461
462 return EGL_SUCCESS;
463}
464
465// do any one-time device initialization
466// NOTE: this is also needed after a device lost/reset
467// to reset the scene status and ensure the default states are reset.
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000468void Renderer9::initializeDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000469{
470 // Permanent non-default states
471 mDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
472 mDevice->SetRenderState(D3DRS_LASTPIXEL, FALSE);
473
474 if (mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0))
475 {
476 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, (DWORD&)mDeviceCaps.MaxPointSize);
477 }
478 else
479 {
480 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, 0x3F800000); // 1.0f
481 }
482
daniel@transgaming.comc43a6052012-11-28 19:41:51 +0000483 markAllStateDirty();
484
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000485 mSceneStarted = false;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +0000486
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000487 ASSERT(!mBlit && !mVertexDataManager && !mIndexDataManager);
daniel@transgaming.come569fc52012-11-28 20:56:02 +0000488 mBlit = new Blit(this);
daniel@transgaming.com31240482012-11-28 21:06:41 +0000489 mVertexDataManager = new rx::VertexDataManager(this);
490 mIndexDataManager = new rx::IndexDataManager(this);
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000491}
492
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000493D3DPRESENT_PARAMETERS Renderer9::getDefaultPresentParameters()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000494{
495 D3DPRESENT_PARAMETERS presentParameters = {0};
496
497 // The default swap chain is never actually used. Surface will create a new swap chain with the proper parameters.
498 presentParameters.AutoDepthStencilFormat = D3DFMT_UNKNOWN;
499 presentParameters.BackBufferCount = 1;
500 presentParameters.BackBufferFormat = D3DFMT_UNKNOWN;
501 presentParameters.BackBufferWidth = 1;
502 presentParameters.BackBufferHeight = 1;
503 presentParameters.EnableAutoDepthStencil = FALSE;
504 presentParameters.Flags = 0;
505 presentParameters.hDeviceWindow = mDeviceWindow;
506 presentParameters.MultiSampleQuality = 0;
507 presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE;
508 presentParameters.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
509 presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
510 presentParameters.Windowed = TRUE;
511
512 return presentParameters;
513}
514
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000515int Renderer9::generateConfigs(ConfigDesc **configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000516{
517 D3DDISPLAYMODE currentDisplayMode;
518 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
519
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000520 unsigned int numRenderFormats = sizeof(RenderTargetFormats) / sizeof(RenderTargetFormats[0]);
521 unsigned int numDepthFormats = sizeof(DepthStencilFormats) / sizeof(DepthStencilFormats[0]);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000522 (*configDescList) = new ConfigDesc[numRenderFormats * numDepthFormats];
523 int numConfigs = 0;
524
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000525 for (unsigned int formatIndex = 0; formatIndex < numRenderFormats; formatIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000526 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000527 D3DFORMAT renderTargetFormat = RenderTargetFormats[formatIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000528
529 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, renderTargetFormat);
530
531 if (SUCCEEDED(result))
532 {
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000533 for (unsigned int depthStencilIndex = 0; depthStencilIndex < numDepthFormats; depthStencilIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000534 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000535 D3DFORMAT depthStencilFormat = DepthStencilFormats[depthStencilIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000536 HRESULT result = D3D_OK;
537
538 if(depthStencilFormat != D3DFMT_UNKNOWN)
539 {
540 result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFormat);
541 }
542
543 if (SUCCEEDED(result))
544 {
545 if(depthStencilFormat != D3DFMT_UNKNOWN)
546 {
547 result = mD3d9->CheckDepthStencilMatch(mAdapter, mDeviceType, currentDisplayMode.Format, renderTargetFormat, depthStencilFormat);
548 }
549
550 if (SUCCEEDED(result))
551 {
552 ConfigDesc newConfig;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000553 newConfig.renderTargetFormat = d3d9_gl::ConvertBackBufferFormat(renderTargetFormat);
554 newConfig.depthStencilFormat = d3d9_gl::ConvertDepthStencilFormat(depthStencilFormat);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000555 newConfig.multiSample = 0; // FIXME: enumerate multi-sampling
556 newConfig.fastConfig = (currentDisplayMode.Format == renderTargetFormat);
557
558 (*configDescList)[numConfigs++] = newConfig;
559 }
560 }
561 }
562 }
563 }
564
565 return numConfigs;
566}
567
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000568void Renderer9::deleteConfigs(ConfigDesc *configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000569{
570 delete [] (configDescList);
571}
572
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000573void Renderer9::startScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000574{
575 if (!mSceneStarted)
576 {
577 long result = mDevice->BeginScene();
578 if (SUCCEEDED(result)) {
579 // This is defensive checking against the device being
580 // lost at unexpected times.
581 mSceneStarted = true;
582 }
583 }
584}
585
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000586void Renderer9::endScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000587{
588 if (mSceneStarted)
589 {
590 // EndScene can fail if the device was lost, for example due
591 // to a TDR during a draw call.
592 mDevice->EndScene();
593 mSceneStarted = false;
594 }
595}
596
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000597// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000598void Renderer9::sync(bool block)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000599{
600 HRESULT result;
601
602 IDirect3DQuery9* query = allocateEventQuery();
603 if (!query)
604 {
605 return;
606 }
607
608 result = query->Issue(D3DISSUE_END);
609 ASSERT(SUCCEEDED(result));
610
611 do
612 {
613 result = query->GetData(NULL, 0, D3DGETDATA_FLUSH);
614
615 if(block && result == S_FALSE)
616 {
617 // Keep polling, but allow other threads to do something useful first
618 Sleep(0);
619 // explicitly check for device loss
620 // some drivers seem to return S_FALSE even if the device is lost
621 // instead of D3DERR_DEVICELOST like they should
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000622 if (testDeviceLost(false))
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000623 {
624 result = D3DERR_DEVICELOST;
625 }
626 }
627 }
628 while(block && result == S_FALSE);
629
630 freeEventQuery(query);
631
632 if (isDeviceLostError(result))
633 {
634 mDisplay->notifyDeviceLost();
635 }
636}
637
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000638SwapChain *Renderer9::createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
639{
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +0000640 return new rx::SwapChain9(this, window, shareHandle, backBufferFormat, depthBufferFormat);
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000641}
642
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000643// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000644IDirect3DQuery9* Renderer9::allocateEventQuery()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000645{
646 IDirect3DQuery9 *query = NULL;
647
648 if (mEventQueryPool.empty())
649 {
650 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &query);
651 ASSERT(SUCCEEDED(result));
652 }
653 else
654 {
655 query = mEventQueryPool.back();
656 mEventQueryPool.pop_back();
657 }
658
659 return query;
660}
661
662// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000663void Renderer9::freeEventQuery(IDirect3DQuery9* query)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000664{
665 if (mEventQueryPool.size() > 1000)
666 {
667 query->Release();
668 }
669 else
670 {
671 mEventQueryPool.push_back(query);
672 }
673}
674
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000675IDirect3DVertexShader9 *Renderer9::createVertexShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000676{
677 return mVertexShaderCache.create(function, length);
678}
679
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000680IDirect3DPixelShader9 *Renderer9::createPixelShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000681{
682 return mPixelShaderCache.create(function, length);
683}
684
daniel@transgaming.com113f0eb2012-10-31 18:46:58 +0000685HRESULT Renderer9::createVertexBuffer(UINT Length, DWORD Usage, IDirect3DVertexBuffer9 **ppVertexBuffer)
686{
687 D3DPOOL Pool = getBufferPool(Usage);
688 return mDevice->CreateVertexBuffer(Length, Usage, 0, Pool, ppVertexBuffer, NULL);
689}
690
daniel@transgaming.com3f255b42012-12-20 21:07:35 +0000691VertexBuffer *Renderer9::createVertexBuffer()
692{
693 return new VertexBuffer9(this);
694}
695
daniel@transgaming.com113f0eb2012-10-31 18:46:58 +0000696HRESULT Renderer9::createIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, IDirect3DIndexBuffer9 **ppIndexBuffer)
697{
698 D3DPOOL Pool = getBufferPool(Usage);
699 return mDevice->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, NULL);
700}
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000701
daniel@transgaming.com0b6d7742012-12-20 21:09:47 +0000702IndexBuffer *Renderer9::createIndexBuffer()
703{
704 return new IndexBuffer9(this);
705}
706
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000707void Renderer9::setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &samplerState)
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000708{
709 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
710 int d3dSampler = index + d3dSamplerOffset;
711
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000712 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSU, gl_d3d9::ConvertTextureWrap(samplerState.wrapS));
713 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSV, gl_d3d9::ConvertTextureWrap(samplerState.wrapT));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000714
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000715 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAGFILTER, gl_d3d9::ConvertMagFilter(samplerState.magFilter, samplerState.maxAnisotropy));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000716 D3DTEXTUREFILTERTYPE d3dMinFilter, d3dMipFilter;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000717 gl_d3d9::ConvertMinFilter(samplerState.minFilter, &d3dMinFilter, &d3dMipFilter, samplerState.maxAnisotropy);
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000718 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MINFILTER, d3dMinFilter);
719 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPFILTER, d3dMipFilter);
720 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXMIPLEVEL, samplerState.lodOffset);
721 if (mSupportsTextureFilterAnisotropy)
722 {
723 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, (DWORD)samplerState.maxAnisotropy);
724 }
725}
726
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000727void Renderer9::setTexture(gl::SamplerType type, int index, gl::Texture *texture)
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000728{
729 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
730 int d3dSampler = index + d3dSamplerOffset;
731 IDirect3DBaseTexture9 *d3dTexture = NULL;
732
733 if (texture)
734 {
daniel@transgaming.com87705f82012-12-20 21:10:45 +0000735 TextureStorageInterface *texStorage = texture->getNativeTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000736 if (texStorage)
737 {
daniel@transgaming.com87705f82012-12-20 21:10:45 +0000738 TextureStorage9 *storage9 = TextureStorage9::makeTextureStorage9(texStorage->getStorageInstance());
daniel@transgaming.com34da3972012-12-20 21:10:29 +0000739 d3dTexture = storage9->getBaseTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000740 }
741 // If we get NULL back from getBaseTexture here, something went wrong
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000742 // in the texture class and we're unexpectedly missing the d3d texture
743 ASSERT(d3dTexture != NULL);
744 }
745
746 mDevice->SetTexture(d3dSampler, d3dTexture);
747}
748
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000749void Renderer9::setRasterizerState(const gl::RasterizerState &rasterState)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000750{
751 bool rasterStateChanged = mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000752
753 if (rasterStateChanged)
754 {
755 // Set the cull mode
756 if (rasterState.cullFace)
757 {
758 mDevice->SetRenderState(D3DRS_CULLMODE, gl_d3d9::ConvertCullMode(rasterState.cullMode, rasterState.frontFace));
759 }
760 else
761 {
762 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
763 }
764
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000765 if (rasterState.polygonOffsetFill)
766 {
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000767 if (mCurDepthSize > 0)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000768 {
769 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
770
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000771 float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(mCurDepthSize));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000772 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
773 }
774 }
775 else
776 {
777 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
778 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
779 }
780
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000781 mCurRasterState = rasterState;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000782 }
783
784 mForceSetRasterState = false;
785}
786
787void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
788{
789 bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
790 bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
791 bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
792
793 if (blendStateChanged || blendColorChanged)
794 {
795 if (blendState.blend)
796 {
797 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
798
799 if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
800 blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
801 {
802 mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
803 }
804 else
805 {
806 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
807 gl::unorm<8>(blendColor.alpha),
808 gl::unorm<8>(blendColor.alpha),
809 gl::unorm<8>(blendColor.alpha)));
810 }
811
812 mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
813 mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
814 mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
815
816 if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
817 blendState.destBlendRGB != blendState.destBlendAlpha ||
818 blendState.blendEquationRGB != blendState.blendEquationAlpha)
819 {
820 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
821
822 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
823 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
824 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
825 }
826 else
827 {
828 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
829 }
830 }
831 else
832 {
833 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
834 }
835
836 if (blendState.sampleAlphaToCoverage)
837 {
838 FIXME("Sample alpha to coverage is unimplemented.");
839 }
840
841 // Set the color mask
842 bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
843 // Apparently some ATI cards have a bug where a draw with a zero color
844 // write mask can cause later draws to have incorrect results. Instead,
845 // set a nonzero color write mask but modify the blend state so that no
846 // drawing is done.
847 // http://code.google.com/p/angleproject/issues/detail?id=169
848
849 DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
850 blendState.colorMaskBlue, blendState.colorMaskAlpha);
851 if (colorMask == 0 && !zeroColorMaskAllowed)
852 {
853 // Enable green channel, but set blending so nothing will be drawn.
854 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
855 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
856
857 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
858 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
859 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
860 }
861 else
862 {
863 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
864 }
865
866 mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
867
868 mCurBlendState = blendState;
869 mCurBlendColor = blendColor;
870 }
871
872 if (sampleMaskChanged)
873 {
874 // Set the multisample mask
875 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
876 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
877
878 mCurSampleMask = sampleMask;
879 }
880
881 mForceSetBlendState = false;
882}
883
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000884void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000885 int stencilBackRef, bool frontFaceCCW)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000886{
887 bool depthStencilStateChanged = mForceSetDepthStencilState ||
888 memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000889 bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
890 stencilBackRef != mCurStencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000891 bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000892
893 if (depthStencilStateChanged)
894 {
895 if (depthStencilState.depthTest)
896 {
897 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
898 mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
899 }
900 else
901 {
902 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
903 }
904
905 mCurDepthStencilState = depthStencilState;
906 }
907
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000908 if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000909 {
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000910 if (depthStencilState.stencilTest && mCurStencilSize > 0)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000911 {
912 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
913 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
914
915 // FIXME: Unsupported by D3D9
916 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
917 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
918 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
919 if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000920 stencilRef != stencilBackRef ||
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000921 depthStencilState.stencilMask != depthStencilState.stencilBackMask)
922 {
923 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
924 return error(GL_INVALID_OPERATION);
925 }
926
927 // get the maximum size of the stencil ref
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000928 unsigned int maxStencil = (1 << mCurStencilSize) - 1;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000929
930 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
931 depthStencilState.stencilWritemask);
932 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
933 gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
934
935 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000936 (stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000937 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
938 depthStencilState.stencilMask);
939
940 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
941 gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
942 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
943 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
944 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
945 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
946
947 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
948 depthStencilState.stencilBackWritemask);
949 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
950 gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
951
952 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000953 (stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000954 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
955 depthStencilState.stencilBackMask);
956
957 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
958 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
959 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
960 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
961 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
962 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
963 }
964 else
965 {
966 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
967 }
968
969 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
970
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000971 mCurStencilRef = stencilRef;
972 mCurStencilBackRef = stencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000973 mCurFrontFaceCCW = frontFaceCCW;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000974 }
975
976 mForceSetDepthStencilState = false;
977}
978
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000979void Renderer9::setScissorRectangle(const gl::Rectangle &scissor, bool enabled)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000980{
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000981 bool scissorChanged = mForceSetScissor ||
982 memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0 ||
983 enabled != mScissorEnabled;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000984
daniel@transgaming.com04f1b332012-11-28 21:00:40 +0000985 if (scissorChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000986 {
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000987 if (enabled)
988 {
989 RECT rect;
990 rect.left = gl::clamp(scissor.x, 0, static_cast<int>(mRenderTargetDesc.width));
991 rect.top = gl::clamp(scissor.y, 0, static_cast<int>(mRenderTargetDesc.height));
992 rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(mRenderTargetDesc.width));
993 rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(mRenderTargetDesc.height));
994 mDevice->SetScissorRect(&rect);
995 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000996
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000997 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, enabled ? TRUE : FALSE);
998
999 mScissorEnabled = enabled;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001000 mCurScissor = scissor;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001001 }
1002
1003 mForceSetScissor = false;
1004}
1005
daniel@transgaming.com12985182012-12-20 20:56:31 +00001006bool Renderer9::setViewport(const gl::Rectangle &viewport, float zNear, float zFar, GLenum drawMode, GLenum frontFace,
1007 bool ignoreViewport, gl::ProgramBinary *currentProgram, bool forceSetUniforms)
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001008{
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +00001009 gl::Rectangle actualViewport = viewport;
1010 float actualZNear = gl::clamp01(zNear);
1011 float actualZFar = gl::clamp01(zFar);
1012 if (ignoreViewport)
1013 {
1014 actualViewport.x = 0;
1015 actualViewport.y = 0;
1016 actualViewport.width = mRenderTargetDesc.width;
1017 actualViewport.height = mRenderTargetDesc.height;
1018 actualZNear = 0.0f;
1019 actualZFar = 1.0f;
1020 }
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001021
1022 D3DVIEWPORT9 dxViewport;
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +00001023 dxViewport.X = gl::clamp(actualViewport.x, 0, static_cast<int>(mRenderTargetDesc.width));
1024 dxViewport.Y = gl::clamp(actualViewport.y, 0, static_cast<int>(mRenderTargetDesc.height));
1025 dxViewport.Width = gl::clamp(actualViewport.width, 0, static_cast<int>(mRenderTargetDesc.width) - static_cast<int>(dxViewport.X));
1026 dxViewport.Height = gl::clamp(actualViewport.height, 0, static_cast<int>(mRenderTargetDesc.height) - static_cast<int>(dxViewport.Y));
1027 dxViewport.MinZ = actualZNear;
1028 dxViewport.MaxZ = actualZFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001029
1030 if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
1031 {
1032 return false; // Nothing to render
1033 }
1034
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +00001035 bool viewportChanged = mForceSetViewport || memcmp(&actualViewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
1036 actualZNear != mCurNear || actualZFar != mCurFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001037 if (viewportChanged)
1038 {
1039 mDevice->SetViewport(&dxViewport);
1040
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +00001041 mCurViewport = actualViewport;
1042 mCurNear = actualZNear;
1043 mCurFar = actualZFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001044 }
1045
1046 if (currentProgram && (viewportChanged || forceSetUniforms))
1047 {
daniel@transgaming.com88853c52012-12-20 20:56:40 +00001048 currentProgram->applyDxHalfPixelSize(1.0f / dxViewport.Width, -1.0f / dxViewport.Height);
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001049
1050 // These values are used for computing gl_FragCoord in Program::linkVaryings().
daniel@transgaming.com88853c52012-12-20 20:56:40 +00001051 currentProgram->applyDxCoord(actualViewport.width * 0.5f,
1052 actualViewport.height * 0.5f,
1053 actualViewport.x + (actualViewport.width * 0.5f),
1054 actualViewport.y + (actualViewport.height * 0.5f));
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001055
daniel@transgaming.com12985182012-12-20 20:56:31 +00001056 GLfloat ccw = !gl::IsTriangleMode(drawMode) ? 0.0f : (frontFace == GL_CCW ? 1.0f : -1.0f);
daniel@transgaming.com88853c52012-12-20 20:56:40 +00001057 currentProgram->applyDxDepthFront((actualZFar - actualZNear) * 0.5f, (actualZNear + actualZFar) * 0.5f, ccw);
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001058
daniel@transgaming.com88853c52012-12-20 20:56:40 +00001059 currentProgram->applyDxDepthRange(actualZNear, actualZFar, actualZFar - actualZNear);
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001060 }
1061
1062 mForceSetViewport = false;
1063 return true;
1064}
1065
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001066bool Renderer9::applyPrimitiveType(GLenum mode, GLsizei count)
1067{
1068 switch (mode)
1069 {
1070 case GL_POINTS:
1071 mPrimitiveType = D3DPT_POINTLIST;
1072 mPrimitiveCount = count;
1073 break;
1074 case GL_LINES:
1075 mPrimitiveType = D3DPT_LINELIST;
1076 mPrimitiveCount = count / 2;
1077 break;
1078 case GL_LINE_LOOP:
1079 mPrimitiveType = D3DPT_LINESTRIP;
1080 mPrimitiveCount = count - 1; // D3D doesn't support line loops, so we draw the last line separately
1081 break;
1082 case GL_LINE_STRIP:
1083 mPrimitiveType = D3DPT_LINESTRIP;
1084 mPrimitiveCount = count - 1;
1085 break;
1086 case GL_TRIANGLES:
1087 mPrimitiveType = D3DPT_TRIANGLELIST;
1088 mPrimitiveCount = count / 3;
1089 break;
1090 case GL_TRIANGLE_STRIP:
1091 mPrimitiveType = D3DPT_TRIANGLESTRIP;
1092 mPrimitiveCount = count - 2;
1093 break;
1094 case GL_TRIANGLE_FAN:
1095 mPrimitiveType = D3DPT_TRIANGLEFAN;
1096 mPrimitiveCount = count - 2;
1097 break;
1098 default:
1099 return error(GL_INVALID_ENUM, false);
1100 }
1101
1102 return mPrimitiveCount > 0;
1103}
1104
daniel@transgaming.come4e1a332012-12-20 20:52:09 +00001105
1106gl::Renderbuffer *Renderer9::getNullColorbuffer(gl::Renderbuffer *depthbuffer)
1107{
1108 if (!depthbuffer)
1109 {
1110 ERR("Unexpected null depthbuffer for depth-only FBO.");
1111 return NULL;
1112 }
1113
1114 GLsizei width = depthbuffer->getWidth();
1115 GLsizei height = depthbuffer->getHeight();
1116
1117 // search cached nullcolorbuffers
1118 for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1119 {
1120 if (mNullColorbufferCache[i].buffer != NULL &&
1121 mNullColorbufferCache[i].width == width &&
1122 mNullColorbufferCache[i].height == height)
1123 {
1124 mNullColorbufferCache[i].lruCount = ++mMaxNullColorbufferLRU;
1125 return mNullColorbufferCache[i].buffer;
1126 }
1127 }
1128
1129 gl::Renderbuffer *nullbuffer = new gl::Renderbuffer(this, 0, new gl::Colorbuffer(this, width, height, GL_NONE, 0));
1130
1131 // add nullbuffer to the cache
1132 NullColorbufferCacheEntry *oldest = &mNullColorbufferCache[0];
1133 for (int i = 1; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1134 {
1135 if (mNullColorbufferCache[i].lruCount < oldest->lruCount)
1136 {
1137 oldest = &mNullColorbufferCache[i];
1138 }
1139 }
1140
1141 delete oldest->buffer;
1142 oldest->buffer = nullbuffer;
1143 oldest->lruCount = ++mMaxNullColorbufferLRU;
1144 oldest->width = width;
1145 oldest->height = height;
1146
1147 return nullbuffer;
1148}
1149
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001150bool Renderer9::applyRenderTarget(gl::Framebuffer *framebuffer)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001151{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001152 // if there is no color attachment we must synthesize a NULL colorattachment
1153 // to keep the D3D runtime happy. This should only be possible if depth texturing.
1154 gl::Renderbuffer *renderbufferObject = NULL;
1155 if (framebuffer->getColorbufferType() != GL_NONE)
1156 {
1157 renderbufferObject = framebuffer->getColorbuffer();
1158 }
1159 else
1160 {
daniel@transgaming.come4e1a332012-12-20 20:52:09 +00001161 renderbufferObject = getNullColorbuffer(framebuffer->getDepthbuffer());
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001162 }
1163 if (!renderbufferObject)
1164 {
1165 ERR("unable to locate renderbuffer for FBO.");
1166 return false;
1167 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001168
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001169 bool renderTargetChanged = false;
1170 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1171 if (renderTargetSerial != mAppliedRenderTargetSerial)
1172 {
1173 // Apply the render target on the device
1174 IDirect3DSurface9 *renderTargetSurface = NULL;
1175
1176 RenderTarget *renderTarget = renderbufferObject->getRenderTarget();
1177 if (renderTarget)
1178 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001179 renderTargetSurface = RenderTarget9::makeRenderTarget9(renderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001180 }
1181
1182 if (!renderTargetSurface)
1183 {
1184 ERR("render target pointer unexpectedly null.");
1185 return false; // Context must be lost
1186 }
1187
1188 mDevice->SetRenderTarget(0, renderTargetSurface);
1189 renderTargetSurface->Release();
1190
1191 mAppliedRenderTargetSerial = renderTargetSerial;
1192 renderTargetChanged = true;
1193 }
1194
1195 gl::Renderbuffer *depthStencil = NULL;
1196 unsigned int depthbufferSerial = 0;
1197 unsigned int stencilbufferSerial = 0;
1198 if (framebuffer->getDepthbufferType() != GL_NONE)
1199 {
1200 depthStencil = framebuffer->getDepthbuffer();
1201 if (!depthStencil)
1202 {
1203 ERR("Depth stencil pointer unexpectedly null.");
1204 return false;
1205 }
1206
1207 depthbufferSerial = depthStencil->getSerial();
1208 }
1209 else if (framebuffer->getStencilbufferType() != GL_NONE)
1210 {
1211 depthStencil = framebuffer->getStencilbuffer();
1212 if (!depthStencil)
1213 {
1214 ERR("Depth stencil pointer unexpectedly null.");
1215 return false;
1216 }
1217
1218 stencilbufferSerial = depthStencil->getSerial();
1219 }
1220
1221 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1222 stencilbufferSerial != mAppliedStencilbufferSerial ||
1223 !mDepthStencilInitialized)
1224 {
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001225 unsigned int depthSize = 0;
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001226 unsigned int stencilSize = 0;
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001227
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001228 // Apply the depth stencil on the device
1229 if (depthStencil)
1230 {
1231 IDirect3DSurface9 *depthStencilSurface = NULL;
1232 RenderTarget *depthStencilRenderTarget = depthStencil->getDepthStencil();
1233
1234 if (depthStencilRenderTarget)
1235 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001236 depthStencilSurface = RenderTarget9::makeRenderTarget9(depthStencilRenderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001237 }
1238
1239 if (!depthStencilSurface)
1240 {
1241 ERR("depth stencil pointer unexpectedly null.");
1242 return false; // Context must be lost
1243 }
1244
1245 mDevice->SetDepthStencilSurface(depthStencilSurface);
1246 depthStencilSurface->Release();
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001247
1248 depthSize = depthStencil->getDepthSize();
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001249 stencilSize = depthStencil->getStencilSize();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001250 }
1251 else
1252 {
1253 mDevice->SetDepthStencilSurface(NULL);
1254 }
1255
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001256 if (!mDepthStencilInitialized || depthSize != mCurDepthSize)
1257 {
1258 mCurDepthSize = depthSize;
1259 mForceSetRasterState = true;
1260 }
1261
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001262 if (!mDepthStencilInitialized || stencilSize != mCurStencilSize)
1263 {
1264 mCurStencilSize = stencilSize;
1265 mForceSetDepthStencilState = true;
1266 }
1267
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001268 mAppliedDepthbufferSerial = depthbufferSerial;
1269 mAppliedStencilbufferSerial = stencilbufferSerial;
1270 mDepthStencilInitialized = true;
1271 }
1272
1273 if (renderTargetChanged || !mRenderTargetDescInitialized)
1274 {
1275 mForceSetScissor = true;
1276 mForceSetViewport = true;
1277
1278 mRenderTargetDesc.width = renderbufferObject->getWidth();
1279 mRenderTargetDesc.height = renderbufferObject->getHeight();
1280 mRenderTargetDesc.format = renderbufferObject->getActualFormat();
1281 mRenderTargetDescInitialized = true;
1282 }
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001283
1284 return true;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001285}
daniel@transgaming.coma734f272012-10-31 18:07:48 +00001286
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001287GLenum Renderer9::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances)
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001288{
daniel@transgaming.com31240482012-11-28 21:06:41 +00001289 TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001290 GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
1291 if (err != GL_NO_ERROR)
1292 {
1293 return err;
1294 }
1295
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001296 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, &mRepeatDraw);
1297}
1298
1299// Applies the indices and element array bindings to the Direct3D 9 device
daniel@transgaming.com31240482012-11-28 21:06:41 +00001300GLenum Renderer9::applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001301{
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001302 GLenum err = mIndexDataManager->prepareIndexData(type, count, elementArrayBuffer, indices, indexInfo);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001303
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001304 if (err == GL_NO_ERROR)
1305 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001306 if (indexInfo->serial != mAppliedIBSerial)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001307 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001308 IndexBuffer9* indexBuffer = IndexBuffer9::makeIndexBuffer9(indexInfo->indexBuffer);
1309
1310 mDevice->SetIndices(indexBuffer->getBuffer());
1311 mAppliedIBSerial = indexInfo->serial;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001312 }
1313 }
1314
1315 return err;
1316}
1317
1318void Renderer9::drawArrays(GLenum mode, GLsizei count, GLsizei instances)
1319{
1320 startScene();
1321
1322 if (mode == GL_LINE_LOOP)
1323 {
1324 drawLineLoop(count, GL_NONE, NULL, 0, NULL);
1325 }
1326 else if (instances > 0)
1327 {
daniel@transgaming.com50cc7252012-12-20 21:09:23 +00001328 StaticIndexBufferInterface *countingIB = mIndexDataManager->getCountingIndices(count);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001329 if (countingIB)
1330 {
1331 if (mAppliedIBSerial != countingIB->getSerial())
1332 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001333 IndexBuffer9 *indexBuffer = IndexBuffer9::makeIndexBuffer9(countingIB->getIndexBuffer());
1334
1335 mDevice->SetIndices(indexBuffer->getBuffer());
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001336 mAppliedIBSerial = countingIB->getSerial();
1337 }
1338
1339 for (int i = 0; i < mRepeatDraw; i++)
1340 {
1341 mDevice->DrawIndexedPrimitive(mPrimitiveType, 0, 0, count, 0, mPrimitiveCount);
1342 }
1343 }
1344 else
1345 {
1346 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
1347 return error(GL_OUT_OF_MEMORY);
1348 }
1349 }
1350 else // Regular case
1351 {
1352 mDevice->DrawPrimitive(mPrimitiveType, 0, mPrimitiveCount);
1353 }
1354}
1355
daniel@transgaming.com31240482012-11-28 21:06:41 +00001356void Renderer9::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer, const TranslatedIndexData &indexInfo)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001357{
1358 startScene();
1359
1360 if (mode == GL_LINE_LOOP)
1361 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001362 drawLineLoop(count, type, indices, indexInfo.minIndex, elementArrayBuffer);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001363 }
1364 else
1365 {
1366 for (int i = 0; i < mRepeatDraw; i++)
1367 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001368 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
1369 mDevice->DrawIndexedPrimitive(mPrimitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, mPrimitiveCount);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001370 }
1371 }
1372}
1373
1374void Renderer9::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer)
1375{
1376 // Get the raw indices for an indexed draw
1377 if (type != GL_NONE && elementArrayBuffer)
1378 {
1379 gl::Buffer *indexBuffer = elementArrayBuffer;
1380 intptr_t offset = reinterpret_cast<intptr_t>(indices);
1381 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
1382 }
1383
1384 UINT startIndex = 0;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001385
1386 if (get32BitIndexSupport())
1387 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001388 if (!mLineLoopIB)
1389 {
1390 mLineLoopIB = new StreamingIndexBufferInterface(this);
1391 if (!mLineLoopIB->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_INT))
1392 {
1393 delete mLineLoopIB;
1394 mLineLoopIB = NULL;
1395
1396 ERR("Could not create a 32-bit looping index buffer for GL_LINE_LOOP.");
1397 return error(GL_OUT_OF_MEMORY);
1398 }
1399 }
1400
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001401 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001402 if (!mLineLoopIB->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_INT))
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001403 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001404 ERR("Could not reserve enough space in looping index buffer for GL_LINE_LOOP.");
1405 return error(GL_OUT_OF_MEMORY);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001406 }
1407
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001408 void* mappedMemory = NULL;
1409 int offset = mLineLoopIB->mapBuffer(spaceNeeded, &mappedMemory);
1410 if (offset == -1 || mappedMemory == NULL)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001411 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001412 ERR("Could not map index buffer for GL_LINE_LOOP.");
1413 return error(GL_OUT_OF_MEMORY);
1414 }
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001415
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001416 startIndex = static_cast<UINT>(offset) / 4;
1417 unsigned int *data = reinterpret_cast<unsigned int*>(mappedMemory);
1418
1419 switch (type)
1420 {
1421 case GL_NONE: // Non-indexed draw
1422 for (int i = 0; i < count; i++)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001423 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001424 data[i] = i;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001425 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001426 data[count] = 0;
1427 break;
1428 case GL_UNSIGNED_BYTE:
1429 for (int i = 0; i < count; i++)
1430 {
1431 data[i] = static_cast<const GLubyte*>(indices)[i];
1432 }
1433 data[count] = static_cast<const GLubyte*>(indices)[0];
1434 break;
1435 case GL_UNSIGNED_SHORT:
1436 for (int i = 0; i < count; i++)
1437 {
1438 data[i] = static_cast<const GLushort*>(indices)[i];
1439 }
1440 data[count] = static_cast<const GLushort*>(indices)[0];
1441 break;
1442 case GL_UNSIGNED_INT:
1443 for (int i = 0; i < count; i++)
1444 {
1445 data[i] = static_cast<const GLuint*>(indices)[i];
1446 }
1447 data[count] = static_cast<const GLuint*>(indices)[0];
1448 break;
1449 default: UNREACHABLE();
1450 }
1451
1452 if (!mLineLoopIB->unmapBuffer())
1453 {
1454 ERR("Could not unmap index buffer for GL_LINE_LOOP.");
1455 return error(GL_OUT_OF_MEMORY);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001456 }
1457 }
1458 else
1459 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001460 if (!mLineLoopIB)
1461 {
1462 mLineLoopIB = new StreamingIndexBufferInterface(this);
1463 if (!mLineLoopIB->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_SHORT))
1464 {
1465 delete mLineLoopIB;
1466 mLineLoopIB = NULL;
1467
1468 ERR("Could not create a 16-bit looping index buffer for GL_LINE_LOOP.");
1469 return error(GL_OUT_OF_MEMORY);
1470 }
1471 }
1472
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001473 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001474 if (!mLineLoopIB->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_SHORT))
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001475 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001476 ERR("Could not reserve enough space in looping index buffer for GL_LINE_LOOP.");
1477 return error(GL_OUT_OF_MEMORY);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001478 }
1479
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001480 void* mappedMemory = NULL;
1481 int offset = mLineLoopIB->mapBuffer(spaceNeeded, &mappedMemory);
1482 if (offset == -1 || mappedMemory == NULL)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001483 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001484 ERR("Could not map index buffer for GL_LINE_LOOP.");
1485 return error(GL_OUT_OF_MEMORY);
1486 }
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001487
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001488 startIndex = static_cast<UINT>(offset) / 2;
1489 unsigned short *data = reinterpret_cast<unsigned short*>(mappedMemory);
1490
1491 switch (type)
1492 {
1493 case GL_NONE: // Non-indexed draw
1494 for (int i = 0; i < count; i++)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001495 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001496 data[i] = i;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001497 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001498 data[count] = 0;
1499 break;
1500 case GL_UNSIGNED_BYTE:
1501 for (int i = 0; i < count; i++)
1502 {
1503 data[i] = static_cast<const GLubyte*>(indices)[i];
1504 }
1505 data[count] = static_cast<const GLubyte*>(indices)[0];
1506 break;
1507 case GL_UNSIGNED_SHORT:
1508 for (int i = 0; i < count; i++)
1509 {
1510 data[i] = static_cast<const GLushort*>(indices)[i];
1511 }
1512 data[count] = static_cast<const GLushort*>(indices)[0];
1513 break;
1514 case GL_UNSIGNED_INT:
1515 for (int i = 0; i < count; i++)
1516 {
1517 data[i] = static_cast<const GLuint*>(indices)[i];
1518 }
1519 data[count] = static_cast<const GLuint*>(indices)[0];
1520 break;
1521 default: UNREACHABLE();
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001522 }
1523
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001524 if (!mLineLoopIB->unmapBuffer())
1525 {
1526 ERR("Could not unmap index buffer for GL_LINE_LOOP.");
1527 return error(GL_OUT_OF_MEMORY);
1528 }
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001529 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001530
1531 if (mAppliedIBSerial != mLineLoopIB->getSerial())
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001532 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001533 IndexBuffer9 *indexBuffer = IndexBuffer9::makeIndexBuffer9(mLineLoopIB->getIndexBuffer());
1534
1535 mDevice->SetIndices(indexBuffer->getBuffer());
1536 mAppliedIBSerial = mLineLoopIB->getSerial();
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001537 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001538
1539 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001540}
1541
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001542void Renderer9::applyShaders(gl::ProgramBinary *programBinary)
1543{
daniel@transgaming.come4991412012-12-20 20:55:34 +00001544 unsigned int programBinarySerial = programBinary->getSerial();
1545 if (programBinarySerial != mAppliedProgramBinarySerial)
1546 {
1547 ShaderExecutable *vertexExe = programBinary->getVertexExecutable();
1548 ShaderExecutable *pixelExe = programBinary->getPixelExecutable();
daniel@transgaming.com95892412012-11-28 20:59:09 +00001549
daniel@transgaming.come4991412012-12-20 20:55:34 +00001550 IDirect3DVertexShader9 *vertexShader = NULL;
1551 if (vertexExe) vertexShader = ShaderExecutable9::makeShaderExecutable9(vertexExe)->getVertexShader();
daniel@transgaming.com95892412012-11-28 20:59:09 +00001552
daniel@transgaming.come4991412012-12-20 20:55:34 +00001553 IDirect3DPixelShader9 *pixelShader = NULL;
1554 if (pixelExe) pixelShader = ShaderExecutable9::makeShaderExecutable9(pixelExe)->getPixelShader();
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001555
daniel@transgaming.come4991412012-12-20 20:55:34 +00001556 mDevice->SetPixelShader(pixelShader);
1557 mDevice->SetVertexShader(vertexShader);
1558 programBinary->dirtyAllUniforms();
1559
1560 mAppliedProgramBinarySerial = programBinarySerial;
1561 }
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001562}
1563
daniel@transgaming.coma390e1e2013-01-11 04:09:39 +00001564void Renderer9::applyUniforms(const gl::UniformArray *uniformArray, const dx_VertexConstants &vertexConstants, const dx_PixelConstants &pixelConstants)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001565{
1566 for (std::vector<gl::Uniform*>::const_iterator ub = uniformArray->begin(), ue = uniformArray->end(); ub != ue; ++ub)
1567 {
1568 gl::Uniform *targetUniform = *ub;
1569
1570 if (targetUniform->dirty)
1571 {
daniel@transgaming.come6d12e92012-12-20 21:12:47 +00001572 int count = targetUniform->elementCount();
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001573 GLfloat *f = (GLfloat*)targetUniform->data;
1574 GLint *i = (GLint*)targetUniform->data;
1575 GLboolean *b = (GLboolean*)targetUniform->data;
1576
1577 switch (targetUniform->type)
1578 {
1579 case GL_SAMPLER_2D:
1580 case GL_SAMPLER_CUBE:
1581 break;
daniel@transgaming.come6d12e92012-12-20 21:12:47 +00001582 case GL_BOOL: applyUniformnbv(targetUniform, count, 1, b); break;
1583 case GL_BOOL_VEC2: applyUniformnbv(targetUniform, count, 2, b); break;
1584 case GL_BOOL_VEC3: applyUniformnbv(targetUniform, count, 3, b); break;
1585 case GL_BOOL_VEC4: applyUniformnbv(targetUniform, count, 4, b); break;
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001586 case GL_FLOAT:
1587 case GL_FLOAT_VEC2:
1588 case GL_FLOAT_VEC3:
1589 case GL_FLOAT_VEC4:
1590 case GL_FLOAT_MAT2:
1591 case GL_FLOAT_MAT3:
daniel@transgaming.come6d12e92012-12-20 21:12:47 +00001592 case GL_FLOAT_MAT4: applyUniformnfv(targetUniform, f); break;
1593 case GL_INT: applyUniform1iv(targetUniform, count, i); break;
1594 case GL_INT_VEC2: applyUniform2iv(targetUniform, count, i); break;
1595 case GL_INT_VEC3: applyUniform3iv(targetUniform, count, i); break;
1596 case GL_INT_VEC4: applyUniform4iv(targetUniform, count, i); break;
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001597 default:
1598 UNREACHABLE();
1599 }
1600
1601 targetUniform->dirty = false;
1602 }
1603 }
daniel@transgaming.coma390e1e2013-01-11 04:09:39 +00001604
1605 // Driver uniforms
1606 mDevice->SetVertexShaderConstantF(0, (float*)&vertexConstants, sizeof(dx_VertexConstants) / sizeof(float[4]));
1607 mDevice->SetPixelShaderConstantF(0, (float*)&pixelConstants, sizeof(dx_PixelConstants) / sizeof(float[4]));
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001608}
1609
1610void Renderer9::applyUniformnbv(gl::Uniform *targetUniform, GLsizei count, int width, const GLboolean *v)
1611{
1612 float vector[gl::D3D9_MAX_FLOAT_CONSTANTS * 4];
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001613
daniel@transgaming.come76b64b2013-01-11 04:10:08 +00001614 if (targetUniform->psRegisterIndex >= 0 || targetUniform->vsRegisterIndex >= 0)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001615 {
1616 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1617 for (int i = 0; i < count; i++)
1618 {
1619 for (int j = 0; j < 4; j++)
1620 {
1621 if (j < width)
1622 {
1623 vector[i * 4 + j] = (v[i * width + j] == GL_FALSE) ? 0.0f : 1.0f;
1624 }
1625 else
1626 {
1627 vector[i * 4 + j] = 0.0f;
1628 }
1629 }
1630 }
1631 }
1632
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001633 applyUniformnfv(targetUniform, vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001634}
1635
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001636void Renderer9::applyUniformnfv(gl::Uniform *targetUniform, const GLfloat *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001637{
daniel@transgaming.come76b64b2013-01-11 04:10:08 +00001638 if (targetUniform->psRegisterIndex >= 0)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001639 {
daniel@transgaming.come76b64b2013-01-11 04:10:08 +00001640 mDevice->SetPixelShaderConstantF(targetUniform->psRegisterIndex, v, targetUniform->registerCount);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001641 }
1642
daniel@transgaming.come76b64b2013-01-11 04:10:08 +00001643 if (targetUniform->vsRegisterIndex >= 0)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001644 {
daniel@transgaming.come76b64b2013-01-11 04:10:08 +00001645 mDevice->SetVertexShaderConstantF(targetUniform->vsRegisterIndex, v, targetUniform->registerCount);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001646 }
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001647}
1648
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001649void Renderer9::applyUniform1iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001650{
1651 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1652 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1653
1654 for (int i = 0; i < count; i++)
1655 {
1656 vector[i] = gl::Vector4((float)v[i], 0, 0, 0);
1657 }
1658
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001659 applyUniformnfv(targetUniform, (const GLfloat*)vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001660}
1661
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001662void Renderer9::applyUniform2iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001663{
1664 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1665 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1666
1667 for (int i = 0; i < count; i++)
1668 {
1669 vector[i] = gl::Vector4((float)v[0], (float)v[1], 0, 0);
1670
1671 v += 2;
1672 }
1673
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001674 applyUniformnfv(targetUniform, (const GLfloat*)vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001675}
1676
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001677void Renderer9::applyUniform3iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001678{
1679 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1680 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1681
1682 for (int i = 0; i < count; i++)
1683 {
1684 vector[i] = gl::Vector4((float)v[0], (float)v[1], (float)v[2], 0);
1685
1686 v += 3;
1687 }
1688
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001689 applyUniformnfv(targetUniform, (const GLfloat*)vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001690}
1691
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001692void Renderer9::applyUniform4iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001693{
1694 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1695 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1696
1697 for (int i = 0; i < count; i++)
1698 {
1699 vector[i] = gl::Vector4((float)v[0], (float)v[1], (float)v[2], (float)v[3]);
1700
1701 v += 4;
1702 }
1703
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001704 applyUniformnfv(targetUniform, (const GLfloat*)vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001705}
1706
daniel@transgaming.com084a2572012-11-28 20:55:17 +00001707void Renderer9::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001708{
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001709 D3DCOLOR color = D3DCOLOR_ARGB(gl::unorm<8>(clearParams.colorClearValue.alpha),
1710 gl::unorm<8>(clearParams.colorClearValue.red),
1711 gl::unorm<8>(clearParams.colorClearValue.green),
1712 gl::unorm<8>(clearParams.colorClearValue.blue));
1713 float depth = gl::clamp01(clearParams.depthClearValue);
1714 int stencil = clearParams.stencilClearValue & 0x000000FF;
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001715
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001716 unsigned int stencilUnmasked = 0x0;
1717 if ((clearParams.mask & GL_STENCIL_BUFFER_BIT) && frameBuffer->hasStencil())
1718 {
1719 unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
1720 stencilUnmasked = (0x1 << stencilSize) - 1;
1721 }
1722
1723 bool alphaUnmasked = (gl::GetAlphaSize(mRenderTargetDesc.format) == 0) || clearParams.colorMaskAlpha;
1724
1725 const bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
1726 (clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
1727 const bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
1728 !(clearParams.colorMaskRed && clearParams.colorMaskGreen &&
1729 clearParams.colorMaskBlue && alphaUnmasked);
1730
1731 if (needMaskedColorClear || needMaskedStencilClear)
1732 {
1733 // State which is altered in all paths from this point to the clear call is saved.
1734 // State which is altered in only some paths will be flagged dirty in the case that
1735 // that path is taken.
1736 HRESULT hr;
1737 if (mMaskedClearSavedState == NULL)
1738 {
1739 hr = mDevice->BeginStateBlock();
1740 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1741
1742 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1743 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1744 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1745 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1746 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1747 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1748 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1749 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1750 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1751 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1752 mDevice->SetPixelShader(NULL);
1753 mDevice->SetVertexShader(NULL);
1754 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
1755 mDevice->SetStreamSource(0, NULL, 0, 0);
1756 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1757 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1758 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1759 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1760 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1761 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1762 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1763
1764 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1765 {
1766 mDevice->SetStreamSourceFreq(i, 1);
1767 }
1768
1769 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
1770 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1771 }
1772
1773 ASSERT(mMaskedClearSavedState != NULL);
1774
1775 if (mMaskedClearSavedState != NULL)
1776 {
1777 hr = mMaskedClearSavedState->Capture();
1778 ASSERT(SUCCEEDED(hr));
1779 }
1780
1781 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1782 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1783 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1784 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1785 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1786 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1787 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1788 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1789
1790 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1791 {
1792 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE,
1793 gl_d3d9::ConvertColorMask(clearParams.colorMaskRed,
1794 clearParams.colorMaskGreen,
1795 clearParams.colorMaskBlue,
1796 clearParams.colorMaskAlpha));
1797 }
1798 else
1799 {
1800 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1801 }
1802
1803 if (stencilUnmasked != 0x0 && (clearParams.mask & GL_STENCIL_BUFFER_BIT))
1804 {
1805 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
1806 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
1807 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
1808 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
1809 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
1810 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
1811 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
1812 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
1813 }
1814 else
1815 {
1816 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1817 }
1818
1819 mDevice->SetPixelShader(NULL);
1820 mDevice->SetVertexShader(NULL);
1821 mDevice->SetFVF(D3DFVF_XYZRHW);
1822 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1823 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1824 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1825 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1826 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1827 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1828 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1829
1830 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1831 {
1832 mDevice->SetStreamSourceFreq(i, 1);
1833 }
1834
1835 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
1836 quad[0][0] = -0.5f;
1837 quad[0][1] = mRenderTargetDesc.height - 0.5f;
1838 quad[0][2] = 0.0f;
1839 quad[0][3] = 1.0f;
1840
1841 quad[1][0] = mRenderTargetDesc.width - 0.5f;
1842 quad[1][1] = mRenderTargetDesc.height - 0.5f;
1843 quad[1][2] = 0.0f;
1844 quad[1][3] = 1.0f;
1845
1846 quad[2][0] = -0.5f;
1847 quad[2][1] = -0.5f;
1848 quad[2][2] = 0.0f;
1849 quad[2][3] = 1.0f;
1850
1851 quad[3][0] = mRenderTargetDesc.width - 0.5f;
1852 quad[3][1] = -0.5f;
1853 quad[3][2] = 0.0f;
1854 quad[3][3] = 1.0f;
1855
1856 startScene();
1857 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
1858
1859 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1860 {
1861 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
1862 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
1863 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
1864 }
1865
1866 if (mMaskedClearSavedState != NULL)
1867 {
1868 mMaskedClearSavedState->Apply();
1869 }
1870 }
1871 else if (clearParams.mask)
1872 {
1873 DWORD dxClearFlags = 0;
1874 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1875 {
1876 dxClearFlags |= D3DCLEAR_TARGET;
1877 }
1878 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1879 {
1880 dxClearFlags |= D3DCLEAR_ZBUFFER;
1881 }
1882 if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
1883 {
1884 dxClearFlags |= D3DCLEAR_STENCIL;
1885 }
1886
1887 mDevice->Clear(0, NULL, dxClearFlags, color, depth, stencil);
1888 }
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001889}
1890
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001891void Renderer9::markAllStateDirty()
1892{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001893 mAppliedRenderTargetSerial = 0;
1894 mAppliedDepthbufferSerial = 0;
1895 mAppliedStencilbufferSerial = 0;
1896 mDepthStencilInitialized = false;
1897 mRenderTargetDescInitialized = false;
1898
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001899 mForceSetDepthStencilState = true;
1900 mForceSetRasterState = true;
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001901 mForceSetScissor = true;
1902 mForceSetViewport = true;
daniel@transgaming.com9a067372012-12-20 20:55:24 +00001903 mForceSetBlendState = true;
1904
1905 mAppliedIBSerial = 0;
daniel@transgaming.come4991412012-12-20 20:55:34 +00001906 mAppliedProgramBinarySerial = 0;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001907
1908 mVertexDeclarationCache.markStateDirty();
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001909}
1910
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001911void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001912{
1913 while (!mEventQueryPool.empty())
1914 {
1915 mEventQueryPool.back()->Release();
1916 mEventQueryPool.pop_back();
1917 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001918
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001919 if (mMaskedClearSavedState)
1920 {
1921 mMaskedClearSavedState->Release();
1922 mMaskedClearSavedState = NULL;
1923 }
1924
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001925 mVertexShaderCache.clear();
1926 mPixelShaderCache.clear();
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001927
daniel@transgaming.come569fc52012-11-28 20:56:02 +00001928 delete mBlit;
1929 mBlit = NULL;
1930
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001931 delete mVertexDataManager;
1932 mVertexDataManager = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001933
1934 delete mIndexDataManager;
1935 mIndexDataManager = NULL;
1936
1937 delete mLineLoopIB;
1938 mLineLoopIB = NULL;
daniel@transgaming.come4e1a332012-12-20 20:52:09 +00001939
1940 for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1941 {
1942 delete mNullColorbufferCache[i].buffer;
1943 mNullColorbufferCache[i].buffer = NULL;
1944 }
1945
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001946}
1947
1948
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001949void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001950{
1951 mDeviceLost = true;
1952}
1953
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001954bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001955{
1956 return mDeviceLost;
1957}
1958
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001959// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001960bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001961{
1962 bool isLost = false;
1963
1964 if (mDeviceEx)
1965 {
1966 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
1967 }
1968 else if (mDevice)
1969 {
1970 isLost = FAILED(mDevice->TestCooperativeLevel());
1971 }
1972 else
1973 {
1974 // No device yet, so no reset required
1975 }
1976
1977 if (isLost)
1978 {
1979 // ensure we note the device loss --
1980 // we'll probably get this done again by markDeviceLost
1981 // but best to remember it!
1982 // Note that we don't want to clear the device loss status here
1983 // -- this needs to be done by resetDevice
1984 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001985 if (notify)
1986 {
1987 mDisplay->notifyDeviceLost();
1988 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001989 }
1990
1991 return isLost;
1992}
1993
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001994bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001995{
1996 HRESULT status = D3D_OK;
1997
1998 if (mDeviceEx)
1999 {
2000 status = mDeviceEx->CheckDeviceState(NULL);
2001 }
2002 else if (mDevice)
2003 {
2004 status = mDevice->TestCooperativeLevel();
2005 }
2006
2007 switch (status)
2008 {
2009 case D3DERR_DEVICENOTRESET:
2010 case D3DERR_DEVICEHUNG:
2011 return true;
2012 default:
2013 return false;
2014 }
2015}
2016
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002017bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002018{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00002019 releaseDeviceResources();
2020
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002021 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
2022
2023 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00002024 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002025 int attempts = 3;
2026
2027 while (lost && attempts > 0)
2028 {
2029 if (mDeviceEx)
2030 {
2031 Sleep(500); // Give the graphics driver some CPU time
2032 result = mDeviceEx->ResetEx(&presentParameters, NULL);
2033 }
2034 else
2035 {
2036 result = mDevice->TestCooperativeLevel();
2037 while (result == D3DERR_DEVICELOST)
2038 {
2039 Sleep(100); // Give the graphics driver some CPU time
2040 result = mDevice->TestCooperativeLevel();
2041 }
2042
2043 if (result == D3DERR_DEVICENOTRESET)
2044 {
2045 result = mDevice->Reset(&presentParameters);
2046 }
2047 }
2048
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00002049 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002050 attempts --;
2051 }
2052
2053 if (FAILED(result))
2054 {
2055 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
2056 return false;
2057 }
2058
2059 // reset device defaults
2060 initializeDevice();
2061 mDeviceLost = false;
2062
2063 return true;
2064}
2065
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002066DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002067{
2068 return mAdapterIdentifier.VendorId;
2069}
2070
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002071const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002072{
2073 return mAdapterIdentifier.Description;
2074}
2075
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002076GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002077{
2078 return mAdapterIdentifier.DeviceIdentifier;
2079}
2080
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002081void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002082{
2083 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
2084 {
2085 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
2086 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
2087
2088 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
2089 }
2090}
2091
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002092bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002093{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002094 return mDXT1TextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002095}
2096
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002097bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002098{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002099 return mDXT3TextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002100}
2101
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002102bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002103{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002104 return mDXT5TextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002105}
2106
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002107bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002108{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002109 return mDepthTextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002110}
2111
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002112bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002113{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002114 *filtering = mFloat32FilterSupport;
2115 *renderable = mFloat32RenderSupport;
2116 return mFloat32TextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002117}
2118
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002119bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002120{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002121 *filtering = mFloat16FilterSupport;
2122 *renderable = mFloat16RenderSupport;
2123 return mFloat16TextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002124}
2125
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002126bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002127{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002128 return mLuminanceTextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002129}
2130
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002131bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002132{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002133 return mLuminanceAlphaTextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002134}
2135
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002136bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002137{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00002138 return mSupportsTextureFilterAnisotropy;
2139}
2140
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002141float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00002142{
2143 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002144 {
2145 return mDeviceCaps.MaxAnisotropy;
2146 }
2147 return 1.0f;
2148}
2149
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002150bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002151{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002152 return mEventQuerySupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002153}
2154
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002155bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002156{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002157 return mVertexTextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002158}
2159
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002160bool Renderer9::getNonPower2TextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002161{
2162 return mSupportsNonPower2Textures;
2163}
2164
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002165bool Renderer9::getOcclusionQuerySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002166{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002167 return mOcclusionQuerySupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002168}
2169
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002170bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002171{
2172 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
2173}
2174
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002175bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00002176{
2177 // PIX doesn't seem to support using share handles, so disable them.
2178 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00002179 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00002180}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002181
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00002182int Renderer9::getMajorShaderModel() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002183{
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00002184 return D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion);
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002185}
2186
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002187float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002188{
2189 return mDeviceCaps.MaxPointSize;
2190}
2191
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002192int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002193{
2194 return (int)mDeviceCaps.MaxTextureWidth;
2195}
2196
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002197int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002198{
2199 return (int)mDeviceCaps.MaxTextureHeight;
2200}
2201
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002202bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002203{
2204 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
2205}
2206
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002207DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002208{
2209 return mDeviceCaps.DeclTypes;
2210}
2211
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002212int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002213{
2214 return mMinSwapInterval;
2215}
2216
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002217int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002218{
2219 return mMaxSwapInterval;
2220}
2221
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002222int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002223{
2224 return mMaxSupportedSamples;
2225}
2226
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002227int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002228{
2229 if (requested == 0)
2230 {
2231 return requested;
2232 }
2233
2234 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
2235 if (itr == mMultiSampleSupport.end())
2236 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00002237 if (format == D3DFMT_UNKNOWN)
2238 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002239 return -1;
2240 }
2241
2242 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
2243 {
2244 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
2245 {
2246 return i;
2247 }
2248 }
2249
2250 return -1;
2251}
2252
daniel@transgaming.coma9571682012-11-28 19:33:08 +00002253D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
2254{
2255 switch (internalformat)
2256 {
2257 case GL_DEPTH_COMPONENT16:
2258 case GL_DEPTH_COMPONENT32_OES:
2259 case GL_DEPTH24_STENCIL8_OES:
2260 return D3DFMT_INTZ;
2261 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
2262 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
2263 return D3DFMT_DXT1;
2264 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
2265 return D3DFMT_DXT3;
2266 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
2267 return D3DFMT_DXT5;
2268 case GL_RGBA32F_EXT:
2269 case GL_RGB32F_EXT:
2270 case GL_ALPHA32F_EXT:
2271 case GL_LUMINANCE32F_EXT:
2272 case GL_LUMINANCE_ALPHA32F_EXT:
2273 return D3DFMT_A32B32G32R32F;
2274 case GL_RGBA16F_EXT:
2275 case GL_RGB16F_EXT:
2276 case GL_ALPHA16F_EXT:
2277 case GL_LUMINANCE16F_EXT:
2278 case GL_LUMINANCE_ALPHA16F_EXT:
2279 return D3DFMT_A16B16G16R16F;
2280 case GL_LUMINANCE8_EXT:
2281 if (getLuminanceTextureSupport())
2282 {
2283 return D3DFMT_L8;
2284 }
2285 break;
2286 case GL_LUMINANCE8_ALPHA8_EXT:
2287 if (getLuminanceAlphaTextureSupport())
2288 {
2289 return D3DFMT_A8L8;
2290 }
2291 break;
2292 case GL_RGB8_OES:
2293 case GL_RGB565:
2294 return D3DFMT_X8R8G8B8;
2295 }
2296
2297 return D3DFMT_A8R8G8B8;
2298}
2299
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002300bool Renderer9::copyToRenderTarget(TextureStorageInterface2D *dest, TextureStorageInterface2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002301{
2302 bool result = false;
2303
2304 if (source && dest)
2305 {
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002306 TextureStorage9_2D *source9 = TextureStorage9_2D::makeTextureStorage9_2D(source->getStorageInstance());
2307 TextureStorage9_2D *dest9 = TextureStorage9_2D::makeTextureStorage9_2D(dest->getStorageInstance());
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002308
2309 int levels = source9->levelCount();
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002310 for (int i = 0; i < levels; ++i)
2311 {
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002312 IDirect3DSurface9 *srcSurf = source9->getSurfaceLevel(i, false);
2313 IDirect3DSurface9 *dstSurf = dest9->getSurfaceLevel(i, false);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002314
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002315 result = copyToRenderTarget(dstSurf, srcSurf, source9->isManaged());
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002316
2317 if (srcSurf) srcSurf->Release();
2318 if (dstSurf) dstSurf->Release();
2319
2320 if (!result)
2321 return false;
2322 }
2323 }
2324
2325 return result;
2326}
2327
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002328bool Renderer9::copyToRenderTarget(TextureStorageInterfaceCube *dest, TextureStorageInterfaceCube *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002329{
2330 bool result = false;
2331
2332 if (source && dest)
2333 {
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002334 TextureStorage9_Cube *source9 = TextureStorage9_Cube::makeTextureStorage9_Cube(source->getStorageInstance());
2335 TextureStorage9_Cube *dest9 = TextureStorage9_Cube::makeTextureStorage9_Cube(dest->getStorageInstance());
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002336 int levels = source9->levelCount();
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002337 for (int f = 0; f < 6; f++)
2338 {
2339 for (int i = 0; i < levels; i++)
2340 {
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002341 IDirect3DSurface9 *srcSurf = source9->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
2342 IDirect3DSurface9 *dstSurf = dest9->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002343
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002344 result = copyToRenderTarget(dstSurf, srcSurf, source9->isManaged());
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002345
2346 if (srcSurf) srcSurf->Release();
2347 if (dstSurf) dstSurf->Release();
2348
2349 if (!result)
2350 return false;
2351 }
2352 }
2353 }
2354
2355 return result;
2356}
2357
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002358D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002359{
2360 if (mD3d9Ex != NULL)
2361 {
2362 return D3DPOOL_DEFAULT;
2363 }
2364 else
2365 {
2366 if (!(usage & D3DUSAGE_DYNAMIC))
2367 {
2368 return D3DPOOL_MANAGED;
2369 }
2370 }
2371
2372 return D3DPOOL_DEFAULT;
2373}
2374
daniel@transgaming.com38380882012-11-28 19:36:39 +00002375bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002376 GLint xoffset, GLint yoffset, TextureStorageInterface2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002377{
2378 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
2379}
2380
daniel@transgaming.com38380882012-11-28 19:36:39 +00002381bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002382 GLint xoffset, GLint yoffset, TextureStorageInterfaceCube *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002383{
2384 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
2385}
2386
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002387bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
2388 bool blitRenderTarget, bool blitDepthStencil)
2389{
2390 endScene();
2391
2392 if (blitRenderTarget)
2393 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002394 gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer();
2395 gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer();
2396 RenderTarget9 *readRenderTarget = NULL;
2397 RenderTarget9 *drawRenderTarget = NULL;
2398 IDirect3DSurface9* readSurface = NULL;
2399 IDirect3DSurface9* drawSurface = NULL;
2400
2401 if (readBuffer)
2402 {
2403 readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
2404 }
2405 if (drawBuffer)
2406 {
2407 drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
2408 }
2409
2410 if (readRenderTarget)
2411 {
2412 readSurface = readRenderTarget->getSurface();
2413 }
2414 if (drawRenderTarget)
2415 {
2416 drawSurface = drawRenderTarget->getSurface();
2417 }
2418
2419 if (!readSurface || !drawSurface)
2420 {
2421 ERR("Failed to retrieve the render target.");
2422 return error(GL_OUT_OF_MEMORY, false);
2423 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002424
2425 RECT srcRect, dstRect;
2426 RECT *srcRectPtr = NULL;
2427 RECT *dstRectPtr = NULL;
2428
2429 if (readRect)
2430 {
2431 srcRect.left = readRect->x;
2432 srcRect.right = readRect->x + readRect->width;
2433 srcRect.top = readRect->y;
2434 srcRect.bottom = readRect->y + readRect->height;
2435 srcRectPtr = &srcRect;
2436 }
2437
2438 if (drawRect)
2439 {
2440 dstRect.left = drawRect->x;
2441 dstRect.right = drawRect->x + drawRect->width;
2442 dstRect.top = drawRect->y;
2443 dstRect.bottom = drawRect->y + drawRect->height;
2444 dstRectPtr = &dstRect;
2445 }
2446
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002447 HRESULT result = mDevice->StretchRect(readSurface, srcRectPtr, drawSurface, dstRectPtr, D3DTEXF_NONE);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002448
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002449 readSurface->Release();
2450 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002451
2452 if (FAILED(result))
2453 {
2454 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2455 return false;
2456 }
2457 }
2458
2459 if (blitDepthStencil)
2460 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002461 gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
2462 gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
2463 RenderTarget9 *readDepthStencil = NULL;
2464 RenderTarget9 *drawDepthStencil = NULL;
2465 IDirect3DSurface9* readSurface = NULL;
2466 IDirect3DSurface9* drawSurface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002467
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002468 if (readBuffer)
2469 {
2470 readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
2471 }
2472 if (drawBuffer)
2473 {
2474 drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
2475 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002476
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002477 if (readDepthStencil)
2478 {
2479 readSurface = readDepthStencil->getSurface();
2480 }
2481 if (drawDepthStencil)
2482 {
2483 drawSurface = drawDepthStencil->getSurface();
2484 }
2485
2486 if (!readSurface || !drawSurface)
2487 {
2488 ERR("Failed to retrieve the render target.");
2489 return error(GL_OUT_OF_MEMORY, false);
2490 }
2491
2492 HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
2493
2494 readSurface->Release();
2495 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002496
2497 if (FAILED(result))
2498 {
2499 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2500 return false;
2501 }
2502 }
2503
2504 return true;
2505}
2506
2507void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
2508 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
2509{
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002510 RenderTarget9 *renderTarget = NULL;
2511 IDirect3DSurface9 *surface = NULL;
2512 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
2513
2514 if (colorbuffer)
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002515 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002516 renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
2517 }
2518
2519 if (renderTarget)
2520 {
2521 surface = renderTarget->getSurface();
2522 }
2523
2524 if (!surface)
2525 {
2526 // context must be lost
2527 return;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002528 }
2529
2530 D3DSURFACE_DESC desc;
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002531 surface->GetDesc(&desc);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002532
2533 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2534 {
2535 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002536 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002537 return error(GL_OUT_OF_MEMORY);
2538 }
2539
2540 HRESULT result;
2541 IDirect3DSurface9 *systemSurface = NULL;
2542 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
2543 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2544 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2545 if (directToPixels)
2546 {
2547 // Use the pixels ptr as a shared handle to write directly into client's memory
2548 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2549 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2550 if (FAILED(result))
2551 {
2552 // Try again without the shared handle
2553 directToPixels = false;
2554 }
2555 }
2556
2557 if (!directToPixels)
2558 {
2559 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2560 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2561 if (FAILED(result))
2562 {
2563 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002564 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002565 return error(GL_OUT_OF_MEMORY);
2566 }
2567 }
2568
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002569 result = mDevice->GetRenderTargetData(surface, systemSurface);
2570 surface->Release();
2571 surface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002572
2573 if (FAILED(result))
2574 {
2575 systemSurface->Release();
2576
2577 // It turns out that D3D will sometimes produce more error
2578 // codes than those documented.
daniel@transgaming.com414c9162012-11-28 20:54:57 +00002579 if (checkDeviceLost(result))
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002580 return error(GL_OUT_OF_MEMORY);
2581 else
2582 {
2583 UNREACHABLE();
2584 return;
2585 }
2586
2587 }
2588
2589 if (directToPixels)
2590 {
2591 systemSurface->Release();
2592 return;
2593 }
2594
2595 RECT rect;
2596 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
2597 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
2598 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2599 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2600
2601 D3DLOCKED_RECT lock;
2602 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2603
2604 if (FAILED(result))
2605 {
2606 UNREACHABLE();
2607 systemSurface->Release();
2608
2609 return; // No sensible error to generate
2610 }
2611
2612 unsigned char *dest = (unsigned char*)pixels;
2613 unsigned short *dest16 = (unsigned short*)pixels;
2614
2615 unsigned char *source;
2616 int inputPitch;
2617 if (packReverseRowOrder)
2618 {
2619 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2620 inputPitch = -lock.Pitch;
2621 }
2622 else
2623 {
2624 source = (unsigned char*)lock.pBits;
2625 inputPitch = lock.Pitch;
2626 }
2627
2628 unsigned int fastPixelSize = 0;
2629
2630 if (desc.Format == D3DFMT_A8R8G8B8 &&
2631 format == GL_BGRA_EXT &&
2632 type == GL_UNSIGNED_BYTE)
2633 {
2634 fastPixelSize = 4;
2635 }
2636 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2637 format == GL_BGRA_EXT &&
2638 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2639 (desc.Format == D3DFMT_A1R5G5B5 &&
2640 format == GL_BGRA_EXT &&
2641 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2642 {
2643 fastPixelSize = 2;
2644 }
2645 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2646 format == GL_RGBA &&
2647 type == GL_HALF_FLOAT_OES)
2648 {
2649 fastPixelSize = 8;
2650 }
2651 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2652 format == GL_RGBA &&
2653 type == GL_FLOAT)
2654 {
2655 fastPixelSize = 16;
2656 }
2657
2658 for (int j = 0; j < rect.bottom - rect.top; j++)
2659 {
2660 if (fastPixelSize != 0)
2661 {
2662 // Fast path for formats which require no translation:
2663 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2664 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2665 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2666 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2667 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2668 //
2669 // Note that buffers with no alpha go through the slow path below.
2670 memcpy(dest + j * outputPitch,
2671 source + j * inputPitch,
2672 (rect.right - rect.left) * fastPixelSize);
2673 continue;
2674 }
2675
2676 for (int i = 0; i < rect.right - rect.left; i++)
2677 {
2678 float r;
2679 float g;
2680 float b;
2681 float a;
2682
2683 switch (desc.Format)
2684 {
2685 case D3DFMT_R5G6B5:
2686 {
2687 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2688
2689 a = 1.0f;
2690 b = (rgb & 0x001F) * (1.0f / 0x001F);
2691 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2692 r = (rgb & 0xF800) * (1.0f / 0xF800);
2693 }
2694 break;
2695 case D3DFMT_A1R5G5B5:
2696 {
2697 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2698
2699 a = (argb & 0x8000) ? 1.0f : 0.0f;
2700 b = (argb & 0x001F) * (1.0f / 0x001F);
2701 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2702 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2703 }
2704 break;
2705 case D3DFMT_A8R8G8B8:
2706 {
2707 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2708
2709 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2710 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2711 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2712 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2713 }
2714 break;
2715 case D3DFMT_X8R8G8B8:
2716 {
2717 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2718
2719 a = 1.0f;
2720 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2721 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2722 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2723 }
2724 break;
2725 case D3DFMT_A2R10G10B10:
2726 {
2727 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2728
2729 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2730 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2731 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2732 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2733 }
2734 break;
2735 case D3DFMT_A32B32G32R32F:
2736 {
2737 // float formats in D3D are stored rgba, rather than the other way round
2738 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2739 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2740 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2741 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2742 }
2743 break;
2744 case D3DFMT_A16B16G16R16F:
2745 {
2746 // float formats in D3D are stored rgba, rather than the other way round
2747 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2748 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2749 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2750 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
2751 }
2752 break;
2753 default:
2754 UNIMPLEMENTED(); // FIXME
2755 UNREACHABLE();
2756 return;
2757 }
2758
2759 switch (format)
2760 {
2761 case GL_RGBA:
2762 switch (type)
2763 {
2764 case GL_UNSIGNED_BYTE:
2765 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2766 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2767 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2768 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2769 break;
2770 default: UNREACHABLE();
2771 }
2772 break;
2773 case GL_BGRA_EXT:
2774 switch (type)
2775 {
2776 case GL_UNSIGNED_BYTE:
2777 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2778 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2779 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2780 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2781 break;
2782 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2783 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2784 // this type is packed as follows:
2785 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2786 // --------------------------------------------------------------------------------
2787 // | 4th | 3rd | 2nd | 1st component |
2788 // --------------------------------------------------------------------------------
2789 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2790 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2791 ((unsigned short)(15 * a + 0.5f) << 12)|
2792 ((unsigned short)(15 * r + 0.5f) << 8) |
2793 ((unsigned short)(15 * g + 0.5f) << 4) |
2794 ((unsigned short)(15 * b + 0.5f) << 0);
2795 break;
2796 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2797 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2798 // this type is packed as follows:
2799 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2800 // --------------------------------------------------------------------------------
2801 // | 4th | 3rd | 2nd | 1st component |
2802 // --------------------------------------------------------------------------------
2803 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2804 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2805 ((unsigned short)( a + 0.5f) << 15) |
2806 ((unsigned short)(31 * r + 0.5f) << 10) |
2807 ((unsigned short)(31 * g + 0.5f) << 5) |
2808 ((unsigned short)(31 * b + 0.5f) << 0);
2809 break;
2810 default: UNREACHABLE();
2811 }
2812 break;
2813 case GL_RGB:
2814 switch (type)
2815 {
2816 case GL_UNSIGNED_SHORT_5_6_5:
2817 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2818 ((unsigned short)(31 * b + 0.5f) << 0) |
2819 ((unsigned short)(63 * g + 0.5f) << 5) |
2820 ((unsigned short)(31 * r + 0.5f) << 11);
2821 break;
2822 case GL_UNSIGNED_BYTE:
2823 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2824 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2825 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2826 break;
2827 default: UNREACHABLE();
2828 }
2829 break;
2830 default: UNREACHABLE();
2831 }
2832 }
2833 }
2834
2835 systemSurface->UnlockRect();
2836
2837 systemSurface->Release();
2838}
2839
daniel@transgaming.comf2423652012-11-28 20:53:50 +00002840RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
2841{
2842 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2843 IDirect3DSurface9 *surface = NULL;
2844 if (depth)
2845 {
2846 surface = swapChain9->getDepthStencil();
2847 }
2848 else
2849 {
2850 surface = swapChain9->getRenderTarget();
2851 }
2852
2853 RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
2854
2855 return renderTarget;
2856}
2857
2858RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
2859{
2860 RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
2861 return renderTarget;
2862}
2863
daniel@transgaming.com2275f912012-12-20 21:13:22 +00002864ShaderExecutable *Renderer9::loadExecutable(const void *function, size_t length, GLenum type)
daniel@transgaming.com55318902012-11-28 20:58:58 +00002865{
2866 ShaderExecutable9 *executable = NULL;
daniel@transgaming.com55318902012-11-28 20:58:58 +00002867
2868 switch (type)
2869 {
2870 case GL_VERTEX_SHADER:
2871 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002872 IDirect3DVertexShader9 *vshader = createVertexShader((DWORD*)function, length);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002873 if (vshader)
2874 {
daniel@transgaming.com2275f912012-12-20 21:13:22 +00002875 executable = new ShaderExecutable9(function, length, vshader);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002876 }
2877 }
2878 break;
2879 case GL_FRAGMENT_SHADER:
2880 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002881 IDirect3DPixelShader9 *pshader = createPixelShader((DWORD*)function, length);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002882 if (pshader)
2883 {
daniel@transgaming.com2275f912012-12-20 21:13:22 +00002884 executable = new ShaderExecutable9(function, length, pshader);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002885 }
2886 }
2887 break;
2888 default:
2889 UNREACHABLE();
2890 break;
2891 }
2892
2893 return executable;
2894}
2895
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002896ShaderExecutable *Renderer9::compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, GLenum type)
2897{
2898 const char *profile = NULL;
2899
2900 switch (type)
2901 {
2902 case GL_VERTEX_SHADER:
2903 profile = getMajorShaderModel() >= 3 ? "vs_3_0" : "vs_2_0";
2904 break;
2905 case GL_FRAGMENT_SHADER:
2906 profile = getMajorShaderModel() >= 3 ? "ps_3_0" : "ps_2_0";
2907 break;
2908 default:
2909 UNREACHABLE();
2910 return NULL;
2911 }
2912
daniel@transgaming.com25e16af2012-11-28 21:05:57 +00002913 ID3DBlob *binary = compileToBinary(infoLog, shaderHLSL, profile, true);
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002914 if (!binary)
2915 return NULL;
2916
daniel@transgaming.com2275f912012-12-20 21:13:22 +00002917 ShaderExecutable *executable = loadExecutable(binary->GetBufferPointer(), binary->GetBufferSize(), type);
daniel@transgaming.com536dd6e2012-11-28 21:00:18 +00002918 binary->Release();
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002919
2920 return executable;
2921}
2922
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002923bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
2924{
2925 return mBlit->boxFilter(source, dest);
2926}
2927
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002928D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002929{
2930 if (mD3d9Ex != NULL)
2931 {
2932 return D3DPOOL_DEFAULT;
2933 }
2934 else
2935 {
2936 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2937 {
2938 return D3DPOOL_MANAGED;
2939 }
2940 }
2941
2942 return D3DPOOL_DEFAULT;
2943}
2944
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002945bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
2946{
2947 if (source && dest)
2948 {
2949 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
2950 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
2951
2952 if (fromManaged)
2953 {
2954 D3DSURFACE_DESC desc;
2955 source->GetDesc(&desc);
2956
2957 IDirect3DSurface9 *surf = 0;
2958 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
2959
2960 if (SUCCEEDED(result))
2961 {
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00002962 Image9::copyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002963 result = device->UpdateSurface(surf, NULL, dest, NULL);
2964 surf->Release();
2965 }
2966 }
2967 else
2968 {
2969 endScene();
2970 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
2971 }
2972
2973 if (FAILED(result))
2974 {
2975 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2976 return false;
2977 }
2978 }
2979
2980 return true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00002981}
2982
daniel@transgaming.com244e1832012-12-20 20:52:35 +00002983Image *Renderer9::createImage()
2984{
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00002985 return new Image9();
daniel@transgaming.com244e1832012-12-20 20:52:35 +00002986}
2987
daniel@transgaming.comf721fdb2012-12-20 20:53:11 +00002988void Renderer9::generateMipmap(Image *dest, Image *src)
2989{
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00002990 Image9 *src9 = Image9::makeImage9(src);
2991 Image9 *dst9 = Image9::makeImage9(dest);
2992 Image9::generateMipmap(dst9, src9);
daniel@transgaming.comf721fdb2012-12-20 20:53:11 +00002993}
2994
daniel@transgaming.com413d2712012-12-20 21:11:04 +00002995TextureStorage *Renderer9::createTextureStorage2D(SwapChain *swapChain)
2996{
2997 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2998 return new TextureStorage9_2D(this, swapChain9);
2999}
3000
3001TextureStorage *Renderer9::createTextureStorage2D(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height)
3002{
3003 return new TextureStorage9_2D(this, levels, internalformat, usage, forceRenderable, width, height);
3004}
3005
3006TextureStorage *Renderer9::createTextureStorageCube(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size)
3007{
3008 return new TextureStorage9_Cube(this, levels, internalformat, usage, forceRenderable, size);
3009}
3010
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003011}