blob: a834a4de91a6b12015f9bf367a7894836b254f89 [file] [log] [blame]
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001//
2// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
3// 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.com91207b72012-11-28 20:56:43 +000017#include "libGLESv2/IndexDataManager.h"
daniel@transgaming.com67094ee2012-11-28 20:53:04 +000018#include "libGLESv2/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.com9d4346f2012-10-31 19:52:04 +000023#include "libGLESv2/renderer/TextureStorage.h"
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +000024#include "libGLESv2/renderer/Image.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.com621ce052012-10-31 17:52:29 +000027
daniel@transgaming.com3281f972012-10-31 18:38:51 +000028#include "libEGL/Config.h"
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000029#include "libEGL/Display.h"
30
daniel@transgaming.com621ce052012-10-31 17:52:29 +000031// Can also be enabled by defining FORCE_REF_RAST in the project's predefined macros
32#define REF_RAST 0
33
34// The "Debug This Pixel..." feature in PIX often fails when using the
35// D3D9Ex interfaces. In order to get debug pixel to work on a Vista/Win 7
36// machine, define "ANGLE_ENABLE_D3D9EX=0" in your project file.
37#if !defined(ANGLE_ENABLE_D3D9EX)
38// Enables use of the IDirect3D9Ex interface, when available
39#define ANGLE_ENABLE_D3D9EX 1
40#endif // !defined(ANGLE_ENABLE_D3D9EX)
41
daniel@transgaming.coma9c71422012-11-28 20:58:45 +000042#if !defined(ANGLE_COMPILE_OPTIMIZATION_LEVEL)
43#define ANGLE_COMPILE_OPTIMIZATION_LEVEL D3DCOMPILE_OPTIMIZATION_LEVEL3
44#endif
45
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +000046namespace rx
daniel@transgaming.com621ce052012-10-31 17:52:29 +000047{
daniel@transgaming.com222ee082012-11-28 19:31:49 +000048static const D3DFORMAT RenderTargetFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000049 {
50 D3DFMT_A1R5G5B5,
51 // D3DFMT_A2R10G10B10, // The color_ramp conformance test uses ReadPixels with UNSIGNED_BYTE causing it to think that rendering skipped a colour value.
52 D3DFMT_A8R8G8B8,
53 D3DFMT_R5G6B5,
54 // D3DFMT_X1R5G5B5, // Has no compatible OpenGL ES renderbuffer format
55 D3DFMT_X8R8G8B8
56 };
57
daniel@transgaming.com222ee082012-11-28 19:31:49 +000058static const D3DFORMAT DepthStencilFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000059 {
60 D3DFMT_UNKNOWN,
61 // D3DFMT_D16_LOCKABLE,
62 D3DFMT_D32,
63 // D3DFMT_D15S1,
64 D3DFMT_D24S8,
65 D3DFMT_D24X8,
66 // D3DFMT_D24X4S4,
67 D3DFMT_D16,
68 // D3DFMT_D32F_LOCKABLE,
69 // D3DFMT_D24FS8
70 };
daniel@transgaming.com621ce052012-10-31 17:52:29 +000071
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000072Renderer9::Renderer9(egl::Display *display, HDC hDc, bool softwareDevice) : Renderer(display), mDc(hDc), mSoftwareDevice(softwareDevice)
daniel@transgaming.com621ce052012-10-31 17:52:29 +000073{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000074 mD3d9Module = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000075
daniel@transgaming.com7d738a22012-11-28 19:43:08 +000076 mD3dCompilerModule = NULL;
77
daniel@transgaming.com621ce052012-10-31 17:52:29 +000078 mD3d9 = NULL;
79 mD3d9Ex = NULL;
80 mDevice = NULL;
81 mDeviceEx = NULL;
82 mDeviceWindow = NULL;
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000083 mBlit = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000084
85 mAdapter = D3DADAPTER_DEFAULT;
86
87 #if REF_RAST == 1 || defined(FORCE_REF_RAST)
88 mDeviceType = D3DDEVTYPE_REF;
89 #else
90 mDeviceType = D3DDEVTYPE_HAL;
91 #endif
92
93 mDeviceLost = false;
daniel@transgaming.comb7833982012-10-31 18:31:46 +000094
95 mMaxSupportedSamples = 0;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +000096
daniel@transgaming.com91207b72012-11-28 20:56:43 +000097 mAppliedIBSerial = 0;
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +000098
99 mMaskedClearSavedState = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000100
101 mVertexDataManager = NULL;
102 mIndexDataManager = NULL;
103 mLineLoopIB = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000104}
105
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000106Renderer9::~Renderer9()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000107{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000108 releaseDeviceResources();
109
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000110 if (mDevice)
111 {
112 // 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 +0000113 if (testDeviceLost(false))
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000114 {
115 resetDevice();
116 }
117
118 mDevice->Release();
119 mDevice = NULL;
120 }
121
122 if (mDeviceEx)
123 {
124 mDeviceEx->Release();
125 mDeviceEx = NULL;
126 }
127
128 if (mD3d9)
129 {
130 mD3d9->Release();
131 mD3d9 = NULL;
132 }
133
134 if (mDeviceWindow)
135 {
136 DestroyWindow(mDeviceWindow);
137 mDeviceWindow = NULL;
138 }
139
140 if (mD3d9Ex)
141 {
142 mD3d9Ex->Release();
143 mD3d9Ex = NULL;
144 }
145
146 if (mD3d9Module)
147 {
148 mD3d9Module = NULL;
149 }
150
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000151 if (mD3dCompilerModule)
152 {
153 FreeLibrary(mD3dCompilerModule);
154 mD3dCompilerModule = NULL;
155 }
156
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000157 while (!mMultiSampleSupport.empty())
158 {
159 delete [] mMultiSampleSupport.begin()->second;
160 mMultiSampleSupport.erase(mMultiSampleSupport.begin());
161 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000162}
163
daniel@transgaming.comb64ed282012-11-28 20:54:02 +0000164Renderer9 *Renderer9::makeRenderer9(Renderer *renderer)
165{
166 ASSERT(dynamic_cast<rx::Renderer9*>(renderer) != NULL);
167 return static_cast<rx::Renderer9*>(renderer);
168}
169
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000170EGLint Renderer9::initialize()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000171{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +0000172 if (mSoftwareDevice)
173 {
174 mD3d9Module = GetModuleHandle(TEXT("swiftshader_d3d9.dll"));
175 }
176 else
177 {
178 mD3d9Module = GetModuleHandle(TEXT("d3d9.dll"));
179 }
180
181 if (mD3d9Module == NULL)
182 {
183 ERR("No D3D9 module found - aborting!\n");
184 return EGL_NOT_INITIALIZED;
185 }
186
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000187 typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex**);
188 Direct3DCreate9ExFunc Direct3DCreate9ExPtr = reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
189
190 // Use Direct3D9Ex if available. Among other things, this version is less
191 // inclined to report a lost context, for example when the user switches
192 // desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are available.
193 if (ANGLE_ENABLE_D3D9EX && Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9Ex)))
194 {
195 ASSERT(mD3d9Ex);
196 mD3d9Ex->QueryInterface(IID_IDirect3D9, reinterpret_cast<void**>(&mD3d9));
197 ASSERT(mD3d9);
198 }
199 else
200 {
201 mD3d9 = Direct3DCreate9(D3D_SDK_VERSION);
202 }
203
204 if (!mD3d9)
205 {
206 ERR("Could not create D3D9 device - aborting!\n");
207 return EGL_NOT_INITIALIZED;
208 }
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000209
210#if defined(ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES)
211 // Find a D3DCompiler module that had already been loaded based on a predefined list of versions.
212 static TCHAR* d3dCompilerNames[] = ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES;
213
214 for (int i = 0; i < sizeof(d3dCompilerNames) / sizeof(*d3dCompilerNames); ++i)
215 {
216 if (GetModuleHandleEx(0, d3dCompilerNames[i], &mD3dCompilerModule))
217 {
218 break;
219 }
220 }
221#else
222 // Load the version of the D3DCompiler DLL associated with the Direct3D version ANGLE was built with.
223 mD3dCompilerModule = LoadLibrary(D3DCOMPILER_DLL);
224#endif // ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES
225
226 if (!mD3dCompilerModule)
227 {
228 terminate();
229 return false;
230 }
231
232 mD3DCompileFunc = reinterpret_cast<D3DCompileFunc>(GetProcAddress(mD3dCompilerModule, "D3DCompile"));
233 ASSERT(mD3DCompileFunc);
234
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000235 if (mDc != NULL)
236 {
237 // UNIMPLEMENTED(); // FIXME: Determine which adapter index the device context corresponds to
238 }
239
240 HRESULT result;
241
242 // Give up on getting device caps after about one second.
243 for (int i = 0; i < 10; ++i)
244 {
245 result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);
246 if (SUCCEEDED(result))
247 {
248 break;
249 }
250 else if (result == D3DERR_NOTAVAILABLE)
251 {
252 Sleep(100); // Give the driver some time to initialize/recover
253 }
254 else if (FAILED(result)) // D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY, D3DERR_INVALIDDEVICE, or another error we can't recover from
255 {
256 ERR("failed to get device caps (0x%x)\n", result);
257 return EGL_NOT_INITIALIZED;
258 }
259 }
260
261 if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
262 {
263 ERR("Renderer does not support PS 2.0. aborting!\n");
264 return EGL_NOT_INITIALIZED;
265 }
266
267 // When DirectX9 is running with an older DirectX8 driver, a StretchRect from a regular texture to a render target texture is not supported.
268 // This is required by Texture2D::convertToRenderTarget.
269 if ((mDeviceCaps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) == 0)
270 {
271 ERR("Renderer does not support stretctrect from textures!\n");
272 return EGL_NOT_INITIALIZED;
273 }
274
275 mD3d9->GetAdapterIdentifier(mAdapter, 0, &mAdapterIdentifier);
276
277 // ATI cards on XP have problems with non-power-of-two textures.
278 mSupportsNonPower2Textures = !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_POW2) &&
279 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP_POW2) &&
280 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) &&
281 !(getComparableOSVersion() < versionWindowsVista && mAdapterIdentifier.VendorId == VENDOR_ID_AMD);
282
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000283 // Must support a minimum of 2:1 anisotropy for max anisotropy to be considered supported, per the spec
284 mSupportsTextureFilterAnisotropy = ((mDeviceCaps.RasterCaps & D3DPRASTERCAPS_ANISOTROPY) && (mDeviceCaps.MaxAnisotropy >= 2));
285
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000286 mMinSwapInterval = 4;
287 mMaxSwapInterval = 0;
288
289 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE)
290 {
291 mMinSwapInterval = std::min(mMinSwapInterval, 0);
292 mMaxSwapInterval = std::max(mMaxSwapInterval, 0);
293 }
294 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)
295 {
296 mMinSwapInterval = std::min(mMinSwapInterval, 1);
297 mMaxSwapInterval = std::max(mMaxSwapInterval, 1);
298 }
299 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)
300 {
301 mMinSwapInterval = std::min(mMinSwapInterval, 2);
302 mMaxSwapInterval = std::max(mMaxSwapInterval, 2);
303 }
304 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)
305 {
306 mMinSwapInterval = std::min(mMinSwapInterval, 3);
307 mMaxSwapInterval = std::max(mMaxSwapInterval, 3);
308 }
309 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)
310 {
311 mMinSwapInterval = std::min(mMinSwapInterval, 4);
312 mMaxSwapInterval = std::max(mMaxSwapInterval, 4);
313 }
314
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000315 int max = 0;
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000316 for (int i = 0; i < sizeof(RenderTargetFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000317 {
318 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000319 getMultiSampleSupport(RenderTargetFormats[i], multisampleArray);
320 mMultiSampleSupport[RenderTargetFormats[i]] = multisampleArray;
daniel@transgaming.com92955622012-10-31 18:38:41 +0000321
322 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
323 {
324 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
325 {
326 max = j;
327 }
328 }
329 }
330
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000331 for (int i = 0; i < sizeof(DepthStencilFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000332 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000333 if (DepthStencilFormats[i] == D3DFMT_UNKNOWN)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000334 continue;
335
336 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000337 getMultiSampleSupport(DepthStencilFormats[i], multisampleArray);
338 mMultiSampleSupport[DepthStencilFormats[i]] = multisampleArray;
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000339
340 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
341 {
342 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
343 {
344 max = j;
345 }
346 }
347 }
348
349 mMaxSupportedSamples = max;
350
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000351 static const TCHAR windowName[] = TEXT("AngleHiddenWindow");
352 static const TCHAR className[] = TEXT("STATIC");
353
354 mDeviceWindow = CreateWindowEx(WS_EX_NOACTIVATE, className, windowName, WS_DISABLED | WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
355
356 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
357 DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE | D3DCREATE_NOWINDOWCHANGES;
358
359 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE, &presentParameters, &mDevice);
360 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DEVICELOST)
361 {
362 return EGL_BAD_ALLOC;
363 }
364
365 if (FAILED(result))
366 {
367 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &presentParameters, &mDevice);
368
369 if (FAILED(result))
370 {
371 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_NOTAVAILABLE || result == D3DERR_DEVICELOST);
372 return EGL_BAD_ALLOC;
373 }
374 }
375
376 if (mD3d9Ex)
377 {
378 result = mDevice->QueryInterface(IID_IDirect3DDevice9Ex, (void**) &mDeviceEx);
379 ASSERT(SUCCEEDED(result));
380 }
381
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000382 mVertexShaderCache.initialize(mDevice);
383 mPixelShaderCache.initialize(mDevice);
384
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000385 initializeDevice();
386
387 return EGL_SUCCESS;
388}
389
390// do any one-time device initialization
391// NOTE: this is also needed after a device lost/reset
392// to reset the scene status and ensure the default states are reset.
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000393void Renderer9::initializeDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000394{
395 // Permanent non-default states
396 mDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
397 mDevice->SetRenderState(D3DRS_LASTPIXEL, FALSE);
398
399 if (mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0))
400 {
401 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, (DWORD&)mDeviceCaps.MaxPointSize);
402 }
403 else
404 {
405 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, 0x3F800000); // 1.0f
406 }
407
daniel@transgaming.comc43a6052012-11-28 19:41:51 +0000408 markAllStateDirty();
409
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000410 mSceneStarted = false;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +0000411
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000412 ASSERT(!mBlit && !mVertexDataManager && !mIndexDataManager);
daniel@transgaming.come569fc52012-11-28 20:56:02 +0000413 mBlit = new Blit(this);
414 mVertexDataManager = new gl::VertexDataManager(this);
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000415 mIndexDataManager = new gl::IndexDataManager(this);
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000416}
417
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000418D3DPRESENT_PARAMETERS Renderer9::getDefaultPresentParameters()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000419{
420 D3DPRESENT_PARAMETERS presentParameters = {0};
421
422 // The default swap chain is never actually used. Surface will create a new swap chain with the proper parameters.
423 presentParameters.AutoDepthStencilFormat = D3DFMT_UNKNOWN;
424 presentParameters.BackBufferCount = 1;
425 presentParameters.BackBufferFormat = D3DFMT_UNKNOWN;
426 presentParameters.BackBufferWidth = 1;
427 presentParameters.BackBufferHeight = 1;
428 presentParameters.EnableAutoDepthStencil = FALSE;
429 presentParameters.Flags = 0;
430 presentParameters.hDeviceWindow = mDeviceWindow;
431 presentParameters.MultiSampleQuality = 0;
432 presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE;
433 presentParameters.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
434 presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
435 presentParameters.Windowed = TRUE;
436
437 return presentParameters;
438}
439
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000440int Renderer9::generateConfigs(ConfigDesc **configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000441{
442 D3DDISPLAYMODE currentDisplayMode;
443 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
444
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000445 unsigned int numRenderFormats = sizeof(RenderTargetFormats) / sizeof(RenderTargetFormats[0]);
446 unsigned int numDepthFormats = sizeof(DepthStencilFormats) / sizeof(DepthStencilFormats[0]);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000447 (*configDescList) = new ConfigDesc[numRenderFormats * numDepthFormats];
448 int numConfigs = 0;
449
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000450 for (unsigned int formatIndex = 0; formatIndex < numRenderFormats; formatIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000451 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000452 D3DFORMAT renderTargetFormat = RenderTargetFormats[formatIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000453
454 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, renderTargetFormat);
455
456 if (SUCCEEDED(result))
457 {
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000458 for (unsigned int depthStencilIndex = 0; depthStencilIndex < numDepthFormats; depthStencilIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000459 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000460 D3DFORMAT depthStencilFormat = DepthStencilFormats[depthStencilIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000461 HRESULT result = D3D_OK;
462
463 if(depthStencilFormat != D3DFMT_UNKNOWN)
464 {
465 result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFormat);
466 }
467
468 if (SUCCEEDED(result))
469 {
470 if(depthStencilFormat != D3DFMT_UNKNOWN)
471 {
472 result = mD3d9->CheckDepthStencilMatch(mAdapter, mDeviceType, currentDisplayMode.Format, renderTargetFormat, depthStencilFormat);
473 }
474
475 if (SUCCEEDED(result))
476 {
477 ConfigDesc newConfig;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000478 newConfig.renderTargetFormat = d3d9_gl::ConvertBackBufferFormat(renderTargetFormat);
479 newConfig.depthStencilFormat = d3d9_gl::ConvertDepthStencilFormat(depthStencilFormat);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000480 newConfig.multiSample = 0; // FIXME: enumerate multi-sampling
481 newConfig.fastConfig = (currentDisplayMode.Format == renderTargetFormat);
482
483 (*configDescList)[numConfigs++] = newConfig;
484 }
485 }
486 }
487 }
488 }
489
490 return numConfigs;
491}
492
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000493void Renderer9::deleteConfigs(ConfigDesc *configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000494{
495 delete [] (configDescList);
496}
497
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000498void Renderer9::startScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000499{
500 if (!mSceneStarted)
501 {
502 long result = mDevice->BeginScene();
503 if (SUCCEEDED(result)) {
504 // This is defensive checking against the device being
505 // lost at unexpected times.
506 mSceneStarted = true;
507 }
508 }
509}
510
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000511void Renderer9::endScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000512{
513 if (mSceneStarted)
514 {
515 // EndScene can fail if the device was lost, for example due
516 // to a TDR during a draw call.
517 mDevice->EndScene();
518 mSceneStarted = false;
519 }
520}
521
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000522// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000523void Renderer9::sync(bool block)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000524{
525 HRESULT result;
526
527 IDirect3DQuery9* query = allocateEventQuery();
528 if (!query)
529 {
530 return;
531 }
532
533 result = query->Issue(D3DISSUE_END);
534 ASSERT(SUCCEEDED(result));
535
536 do
537 {
538 result = query->GetData(NULL, 0, D3DGETDATA_FLUSH);
539
540 if(block && result == S_FALSE)
541 {
542 // Keep polling, but allow other threads to do something useful first
543 Sleep(0);
544 // explicitly check for device loss
545 // some drivers seem to return S_FALSE even if the device is lost
546 // instead of D3DERR_DEVICELOST like they should
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000547 if (testDeviceLost(false))
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000548 {
549 result = D3DERR_DEVICELOST;
550 }
551 }
552 }
553 while(block && result == S_FALSE);
554
555 freeEventQuery(query);
556
557 if (isDeviceLostError(result))
558 {
559 mDisplay->notifyDeviceLost();
560 }
561}
562
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000563SwapChain *Renderer9::createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
564{
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +0000565 return new rx::SwapChain9(this, window, shareHandle, backBufferFormat, depthBufferFormat);
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000566}
567
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000568// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000569IDirect3DQuery9* Renderer9::allocateEventQuery()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000570{
571 IDirect3DQuery9 *query = NULL;
572
573 if (mEventQueryPool.empty())
574 {
575 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &query);
576 ASSERT(SUCCEEDED(result));
577 }
578 else
579 {
580 query = mEventQueryPool.back();
581 mEventQueryPool.pop_back();
582 }
583
584 return query;
585}
586
587// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000588void Renderer9::freeEventQuery(IDirect3DQuery9* query)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000589{
590 if (mEventQueryPool.size() > 1000)
591 {
592 query->Release();
593 }
594 else
595 {
596 mEventQueryPool.push_back(query);
597 }
598}
599
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000600IDirect3DVertexShader9 *Renderer9::createVertexShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000601{
602 return mVertexShaderCache.create(function, length);
603}
604
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000605IDirect3DPixelShader9 *Renderer9::createPixelShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000606{
607 return mPixelShaderCache.create(function, length);
608}
609
daniel@transgaming.com113f0eb2012-10-31 18:46:58 +0000610HRESULT Renderer9::createVertexBuffer(UINT Length, DWORD Usage, IDirect3DVertexBuffer9 **ppVertexBuffer)
611{
612 D3DPOOL Pool = getBufferPool(Usage);
613 return mDevice->CreateVertexBuffer(Length, Usage, 0, Pool, ppVertexBuffer, NULL);
614}
615
616HRESULT Renderer9::createIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, IDirect3DIndexBuffer9 **ppIndexBuffer)
617{
618 D3DPOOL Pool = getBufferPool(Usage);
619 return mDevice->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, NULL);
620}
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000621
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000622void Renderer9::setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &samplerState)
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000623{
624 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
625 int d3dSampler = index + d3dSamplerOffset;
626
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000627 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSU, gl_d3d9::ConvertTextureWrap(samplerState.wrapS));
628 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSV, gl_d3d9::ConvertTextureWrap(samplerState.wrapT));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000629
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000630 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAGFILTER, gl_d3d9::ConvertMagFilter(samplerState.magFilter, samplerState.maxAnisotropy));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000631 D3DTEXTUREFILTERTYPE d3dMinFilter, d3dMipFilter;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000632 gl_d3d9::ConvertMinFilter(samplerState.minFilter, &d3dMinFilter, &d3dMipFilter, samplerState.maxAnisotropy);
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000633 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MINFILTER, d3dMinFilter);
634 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPFILTER, d3dMipFilter);
635 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXMIPLEVEL, samplerState.lodOffset);
636 if (mSupportsTextureFilterAnisotropy)
637 {
638 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, (DWORD)samplerState.maxAnisotropy);
639 }
640}
641
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000642void Renderer9::setTexture(gl::SamplerType type, int index, gl::Texture *texture)
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000643{
644 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
645 int d3dSampler = index + d3dSamplerOffset;
646 IDirect3DBaseTexture9 *d3dTexture = NULL;
647
648 if (texture)
649 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +0000650 TextureStorage *texStorage = texture->getNativeTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000651 if (texStorage)
652 {
653 d3dTexture = texStorage->getBaseTexture();
654 }
655 // If we get NULL back from getBaseTexture here, something went wrong
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000656 // in the texture class and we're unexpectedly missing the d3d texture
657 ASSERT(d3dTexture != NULL);
658 }
659
660 mDevice->SetTexture(d3dSampler, d3dTexture);
661}
662
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000663void Renderer9::setRasterizerState(const gl::RasterizerState &rasterState)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000664{
665 bool rasterStateChanged = mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000666
667 if (rasterStateChanged)
668 {
669 // Set the cull mode
670 if (rasterState.cullFace)
671 {
672 mDevice->SetRenderState(D3DRS_CULLMODE, gl_d3d9::ConvertCullMode(rasterState.cullMode, rasterState.frontFace));
673 }
674 else
675 {
676 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
677 }
678
679 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, rasterState.scissorTest ? TRUE : FALSE);
680
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000681 if (rasterState.polygonOffsetFill)
682 {
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000683 if (mCurDepthSize > 0)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000684 {
685 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
686
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000687 float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(mCurDepthSize));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000688 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
689 }
690 }
691 else
692 {
693 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
694 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
695 }
696
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000697 mCurRasterState = rasterState;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000698 }
699
700 mForceSetRasterState = false;
701}
702
703void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
704{
705 bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
706 bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
707 bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
708
709 if (blendStateChanged || blendColorChanged)
710 {
711 if (blendState.blend)
712 {
713 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
714
715 if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
716 blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
717 {
718 mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
719 }
720 else
721 {
722 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
723 gl::unorm<8>(blendColor.alpha),
724 gl::unorm<8>(blendColor.alpha),
725 gl::unorm<8>(blendColor.alpha)));
726 }
727
728 mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
729 mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
730 mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
731
732 if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
733 blendState.destBlendRGB != blendState.destBlendAlpha ||
734 blendState.blendEquationRGB != blendState.blendEquationAlpha)
735 {
736 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
737
738 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
739 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
740 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
741 }
742 else
743 {
744 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
745 }
746 }
747 else
748 {
749 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
750 }
751
752 if (blendState.sampleAlphaToCoverage)
753 {
754 FIXME("Sample alpha to coverage is unimplemented.");
755 }
756
757 // Set the color mask
758 bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
759 // Apparently some ATI cards have a bug where a draw with a zero color
760 // write mask can cause later draws to have incorrect results. Instead,
761 // set a nonzero color write mask but modify the blend state so that no
762 // drawing is done.
763 // http://code.google.com/p/angleproject/issues/detail?id=169
764
765 DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
766 blendState.colorMaskBlue, blendState.colorMaskAlpha);
767 if (colorMask == 0 && !zeroColorMaskAllowed)
768 {
769 // Enable green channel, but set blending so nothing will be drawn.
770 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
771 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
772
773 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
774 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
775 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
776 }
777 else
778 {
779 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
780 }
781
782 mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
783
784 mCurBlendState = blendState;
785 mCurBlendColor = blendColor;
786 }
787
788 if (sampleMaskChanged)
789 {
790 // Set the multisample mask
791 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
792 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
793
794 mCurSampleMask = sampleMask;
795 }
796
797 mForceSetBlendState = false;
798}
799
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000800void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
801 int stencilBackRef, bool frontFaceCCW, unsigned int stencilSize)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000802{
803 bool depthStencilStateChanged = mForceSetDepthStencilState ||
804 memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000805 bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
806 stencilBackRef != mCurStencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000807 bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
808 bool stencilSizeChanged = mForceSetDepthStencilState || stencilSize != mCurStencilSize;
809
810 if (depthStencilStateChanged)
811 {
812 if (depthStencilState.depthTest)
813 {
814 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
815 mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
816 }
817 else
818 {
819 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
820 }
821
822 mCurDepthStencilState = depthStencilState;
823 }
824
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000825 if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged || stencilSizeChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000826 {
827 if (depthStencilState.stencilTest && stencilSize > 0)
828 {
829 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
830 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
831
832 // FIXME: Unsupported by D3D9
833 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
834 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
835 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
836 if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000837 stencilRef != stencilBackRef ||
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000838 depthStencilState.stencilMask != depthStencilState.stencilBackMask)
839 {
840 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
841 return error(GL_INVALID_OPERATION);
842 }
843
844 // get the maximum size of the stencil ref
845 GLuint maxStencil = (1 << stencilSize) - 1;
846
847 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
848 depthStencilState.stencilWritemask);
849 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
850 gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
851
852 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000853 (stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000854 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
855 depthStencilState.stencilMask);
856
857 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
858 gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
859 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
860 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
861 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
862 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
863
864 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
865 depthStencilState.stencilBackWritemask);
866 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
867 gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
868
869 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000870 (stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000871 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
872 depthStencilState.stencilBackMask);
873
874 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
875 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
876 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
877 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
878 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
879 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
880 }
881 else
882 {
883 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
884 }
885
886 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
887
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000888 mCurStencilRef = stencilRef;
889 mCurStencilBackRef = stencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000890 mCurFrontFaceCCW = frontFaceCCW;
891 mCurStencilSize = stencilSize;
892 }
893
894 mForceSetDepthStencilState = false;
895}
896
daniel@transgaming.com04f1b332012-11-28 21:00:40 +0000897void Renderer9::setScissorRectangle(const gl::Rectangle &scissor)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000898{
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000899 bool scissorChanged = mForceSetScissor || memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0;
900
daniel@transgaming.com04f1b332012-11-28 21:00:40 +0000901 if (scissorChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000902 {
903 RECT rect;
daniel@transgaming.com04f1b332012-11-28 21:00:40 +0000904 rect.left = gl::clamp(scissor.x, 0, static_cast<int>(mRenderTargetDesc.width));
905 rect.top = gl::clamp(scissor.y, 0, static_cast<int>(mRenderTargetDesc.height));
906 rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(mRenderTargetDesc.width));
907 rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(mRenderTargetDesc.height));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000908 mDevice->SetScissorRect(&rect);
909
910 mCurScissor = scissor;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000911 }
912
913 mForceSetScissor = false;
914}
915
daniel@transgaming.come2f7b6b2012-11-28 21:00:51 +0000916bool Renderer9::setViewport(const gl::Rectangle &viewport, float zNear, float zFar,
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000917 gl::ProgramBinary *currentProgram, bool forceSetUniforms)
918{
919 bool viewportChanged = mForceSetViewport || memcmp(&viewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
920 zNear != mCurNear || zFar != mCurFar;
921
922 D3DVIEWPORT9 dxViewport;
daniel@transgaming.come2f7b6b2012-11-28 21:00:51 +0000923 dxViewport.X = gl::clamp(viewport.x, 0, static_cast<int>(mRenderTargetDesc.width));
924 dxViewport.Y = gl::clamp(viewport.y, 0, static_cast<int>(mRenderTargetDesc.height));
925 dxViewport.Width = gl::clamp(viewport.width, 0, static_cast<int>(mRenderTargetDesc.width) - static_cast<int>(dxViewport.X));
926 dxViewport.Height = gl::clamp(viewport.height, 0, static_cast<int>(mRenderTargetDesc.height) - static_cast<int>(dxViewport.Y));
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000927 dxViewport.MinZ = zNear;
928 dxViewport.MaxZ = zFar;
929
930 if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
931 {
932 return false; // Nothing to render
933 }
934
935 if (viewportChanged)
936 {
937 mDevice->SetViewport(&dxViewport);
938
939 mCurViewport = viewport;
940 mCurNear = zNear;
941 mCurFar = zFar;
942 }
943
944 if (currentProgram && (viewportChanged || forceSetUniforms))
945 {
946 GLint halfPixelSize = currentProgram->getDxHalfPixelSizeLocation();
947 GLfloat xy[2] = { 1.0f / dxViewport.Width, -1.0f / dxViewport.Height };
948 currentProgram->setUniform2fv(halfPixelSize, 1, xy);
949
950 // These values are used for computing gl_FragCoord in Program::linkVaryings().
951 GLint coord = currentProgram->getDxCoordLocation();
952 GLfloat whxy[4] = { viewport.width * 0.5f,
953 viewport.height * 0.5f,
954 viewport.x + (viewport.width * 0.5f),
955 viewport.y + (viewport.height * 0.5f) };
956 currentProgram->setUniform4fv(coord, 1, whxy);
957
958 GLint depth = currentProgram->getDxDepthLocation();
959 GLfloat dz[2] = { (zFar - zNear) * 0.5f, (zNear + zFar) * 0.5f };
960 currentProgram->setUniform2fv(depth, 1, dz);
961
962 GLint depthRange = currentProgram->getDxDepthRangeLocation();
963 GLfloat nearFarDiff[3] = { zNear, zFar, zFar - zNear };
964 currentProgram->setUniform3fv(depthRange, 1, nearFarDiff);
965 }
966
967 mForceSetViewport = false;
968 return true;
969}
970
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000971bool Renderer9::applyPrimitiveType(GLenum mode, GLsizei count)
972{
973 switch (mode)
974 {
975 case GL_POINTS:
976 mPrimitiveType = D3DPT_POINTLIST;
977 mPrimitiveCount = count;
978 break;
979 case GL_LINES:
980 mPrimitiveType = D3DPT_LINELIST;
981 mPrimitiveCount = count / 2;
982 break;
983 case GL_LINE_LOOP:
984 mPrimitiveType = D3DPT_LINESTRIP;
985 mPrimitiveCount = count - 1; // D3D doesn't support line loops, so we draw the last line separately
986 break;
987 case GL_LINE_STRIP:
988 mPrimitiveType = D3DPT_LINESTRIP;
989 mPrimitiveCount = count - 1;
990 break;
991 case GL_TRIANGLES:
992 mPrimitiveType = D3DPT_TRIANGLELIST;
993 mPrimitiveCount = count / 3;
994 break;
995 case GL_TRIANGLE_STRIP:
996 mPrimitiveType = D3DPT_TRIANGLESTRIP;
997 mPrimitiveCount = count - 2;
998 break;
999 case GL_TRIANGLE_FAN:
1000 mPrimitiveType = D3DPT_TRIANGLEFAN;
1001 mPrimitiveCount = count - 2;
1002 break;
1003 default:
1004 return error(GL_INVALID_ENUM, false);
1005 }
1006
1007 return mPrimitiveCount > 0;
1008}
1009
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001010bool Renderer9::applyRenderTarget(gl::Framebuffer *framebuffer)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001011{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001012 // if there is no color attachment we must synthesize a NULL colorattachment
1013 // to keep the D3D runtime happy. This should only be possible if depth texturing.
1014 gl::Renderbuffer *renderbufferObject = NULL;
1015 if (framebuffer->getColorbufferType() != GL_NONE)
1016 {
1017 renderbufferObject = framebuffer->getColorbuffer();
1018 }
1019 else
1020 {
1021 renderbufferObject = framebuffer->getNullColorbuffer();
1022 }
1023 if (!renderbufferObject)
1024 {
1025 ERR("unable to locate renderbuffer for FBO.");
1026 return false;
1027 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001028
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001029 bool renderTargetChanged = false;
1030 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1031 if (renderTargetSerial != mAppliedRenderTargetSerial)
1032 {
1033 // Apply the render target on the device
1034 IDirect3DSurface9 *renderTargetSurface = NULL;
1035
1036 RenderTarget *renderTarget = renderbufferObject->getRenderTarget();
1037 if (renderTarget)
1038 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001039 renderTargetSurface = RenderTarget9::makeRenderTarget9(renderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001040 }
1041
1042 if (!renderTargetSurface)
1043 {
1044 ERR("render target pointer unexpectedly null.");
1045 return false; // Context must be lost
1046 }
1047
1048 mDevice->SetRenderTarget(0, renderTargetSurface);
1049 renderTargetSurface->Release();
1050
1051 mAppliedRenderTargetSerial = renderTargetSerial;
1052 renderTargetChanged = true;
1053 }
1054
1055 gl::Renderbuffer *depthStencil = NULL;
1056 unsigned int depthbufferSerial = 0;
1057 unsigned int stencilbufferSerial = 0;
1058 if (framebuffer->getDepthbufferType() != GL_NONE)
1059 {
1060 depthStencil = framebuffer->getDepthbuffer();
1061 if (!depthStencil)
1062 {
1063 ERR("Depth stencil pointer unexpectedly null.");
1064 return false;
1065 }
1066
1067 depthbufferSerial = depthStencil->getSerial();
1068 }
1069 else if (framebuffer->getStencilbufferType() != GL_NONE)
1070 {
1071 depthStencil = framebuffer->getStencilbuffer();
1072 if (!depthStencil)
1073 {
1074 ERR("Depth stencil pointer unexpectedly null.");
1075 return false;
1076 }
1077
1078 stencilbufferSerial = depthStencil->getSerial();
1079 }
1080
1081 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1082 stencilbufferSerial != mAppliedStencilbufferSerial ||
1083 !mDepthStencilInitialized)
1084 {
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001085 unsigned int depthSize = 0;
1086
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001087 // Apply the depth stencil on the device
1088 if (depthStencil)
1089 {
1090 IDirect3DSurface9 *depthStencilSurface = NULL;
1091 RenderTarget *depthStencilRenderTarget = depthStencil->getDepthStencil();
1092
1093 if (depthStencilRenderTarget)
1094 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001095 depthStencilSurface = RenderTarget9::makeRenderTarget9(depthStencilRenderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001096 }
1097
1098 if (!depthStencilSurface)
1099 {
1100 ERR("depth stencil pointer unexpectedly null.");
1101 return false; // Context must be lost
1102 }
1103
1104 mDevice->SetDepthStencilSurface(depthStencilSurface);
1105 depthStencilSurface->Release();
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001106
1107 depthSize = depthStencil->getDepthSize();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001108 }
1109 else
1110 {
1111 mDevice->SetDepthStencilSurface(NULL);
1112 }
1113
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001114 if (!mDepthStencilInitialized || depthSize != mCurDepthSize)
1115 {
1116 mCurDepthSize = depthSize;
1117 mForceSetRasterState = true;
1118 }
1119
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001120 mAppliedDepthbufferSerial = depthbufferSerial;
1121 mAppliedStencilbufferSerial = stencilbufferSerial;
1122 mDepthStencilInitialized = true;
1123 }
1124
1125 if (renderTargetChanged || !mRenderTargetDescInitialized)
1126 {
1127 mForceSetScissor = true;
1128 mForceSetViewport = true;
1129
1130 mRenderTargetDesc.width = renderbufferObject->getWidth();
1131 mRenderTargetDesc.height = renderbufferObject->getHeight();
1132 mRenderTargetDesc.format = renderbufferObject->getActualFormat();
1133 mRenderTargetDescInitialized = true;
1134 }
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001135
1136 return true;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001137}
daniel@transgaming.coma734f272012-10-31 18:07:48 +00001138
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001139GLenum Renderer9::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances)
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001140{
1141 gl::TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
1142 GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
1143 if (err != GL_NO_ERROR)
1144 {
1145 return err;
1146 }
1147
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001148 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, &mRepeatDraw);
1149}
1150
1151// Applies the indices and element array bindings to the Direct3D 9 device
1152GLenum Renderer9::applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, gl::TranslatedIndexData *indexInfo)
1153{
1154 IDirect3DIndexBuffer9 *indexBuffer;
1155 unsigned int serial;
1156 GLenum err = mIndexDataManager->prepareIndexData(type, count, elementArrayBuffer, indices, indexInfo, &indexBuffer, &serial);
1157
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001158 if (err == GL_NO_ERROR)
1159 {
1160 if (serial != mAppliedIBSerial)
1161 {
1162 mDevice->SetIndices(indexBuffer);
1163 mAppliedIBSerial = serial;
1164 }
1165 }
1166
1167 return err;
1168}
1169
1170void Renderer9::drawArrays(GLenum mode, GLsizei count, GLsizei instances)
1171{
1172 startScene();
1173
1174 if (mode == GL_LINE_LOOP)
1175 {
1176 drawLineLoop(count, GL_NONE, NULL, 0, NULL);
1177 }
1178 else if (instances > 0)
1179 {
1180 gl::StaticIndexBuffer *countingIB = mIndexDataManager->getCountingIndices(count);
1181 if (countingIB)
1182 {
1183 if (mAppliedIBSerial != countingIB->getSerial())
1184 {
1185 mDevice->SetIndices(countingIB->getBuffer());
1186 mAppliedIBSerial = countingIB->getSerial();
1187 }
1188
1189 for (int i = 0; i < mRepeatDraw; i++)
1190 {
1191 mDevice->DrawIndexedPrimitive(mPrimitiveType, 0, 0, count, 0, mPrimitiveCount);
1192 }
1193 }
1194 else
1195 {
1196 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
1197 return error(GL_OUT_OF_MEMORY);
1198 }
1199 }
1200 else // Regular case
1201 {
1202 mDevice->DrawPrimitive(mPrimitiveType, 0, mPrimitiveCount);
1203 }
1204}
1205
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001206void Renderer9::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer, const gl::TranslatedIndexData &indexInfo)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001207{
1208 startScene();
1209
1210 if (mode == GL_LINE_LOOP)
1211 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001212 drawLineLoop(count, type, indices, indexInfo.minIndex, elementArrayBuffer);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001213 }
1214 else
1215 {
1216 for (int i = 0; i < mRepeatDraw; i++)
1217 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001218 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
1219 mDevice->DrawIndexedPrimitive(mPrimitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, mPrimitiveCount);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001220 }
1221 }
1222}
1223
1224void Renderer9::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer)
1225{
1226 // Get the raw indices for an indexed draw
1227 if (type != GL_NONE && elementArrayBuffer)
1228 {
1229 gl::Buffer *indexBuffer = elementArrayBuffer;
1230 intptr_t offset = reinterpret_cast<intptr_t>(indices);
1231 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
1232 }
1233
1234 UINT startIndex = 0;
1235 bool succeeded = false;
1236
1237 if (get32BitIndexSupport())
1238 {
1239 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
1240
1241 if (!mLineLoopIB)
1242 {
1243 mLineLoopIB = new gl::StreamingIndexBuffer(this, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX32);
1244 }
1245
1246 if (mLineLoopIB)
1247 {
1248 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_INT);
1249
1250 UINT offset = 0;
1251 unsigned int *data = static_cast<unsigned int*>(mLineLoopIB->map(spaceNeeded, &offset));
1252 startIndex = offset / 4;
1253
1254 if (data)
1255 {
1256 switch (type)
1257 {
1258 case GL_NONE: // Non-indexed draw
1259 for (int i = 0; i < count; i++)
1260 {
1261 data[i] = i;
1262 }
1263 data[count] = 0;
1264 break;
1265 case GL_UNSIGNED_BYTE:
1266 for (int i = 0; i < count; i++)
1267 {
1268 data[i] = static_cast<const GLubyte*>(indices)[i];
1269 }
1270 data[count] = static_cast<const GLubyte*>(indices)[0];
1271 break;
1272 case GL_UNSIGNED_SHORT:
1273 for (int i = 0; i < count; i++)
1274 {
1275 data[i] = static_cast<const GLushort*>(indices)[i];
1276 }
1277 data[count] = static_cast<const GLushort*>(indices)[0];
1278 break;
1279 case GL_UNSIGNED_INT:
1280 for (int i = 0; i < count; i++)
1281 {
1282 data[i] = static_cast<const GLuint*>(indices)[i];
1283 }
1284 data[count] = static_cast<const GLuint*>(indices)[0];
1285 break;
1286 default: UNREACHABLE();
1287 }
1288
1289 mLineLoopIB->unmap();
1290 succeeded = true;
1291 }
1292 }
1293 }
1294 else
1295 {
1296 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
1297
1298 if (!mLineLoopIB)
1299 {
1300 mLineLoopIB = new gl::StreamingIndexBuffer(this, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX16);
1301 }
1302
1303 if (mLineLoopIB)
1304 {
1305 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_SHORT);
1306
1307 UINT offset = 0;
1308 unsigned short *data = static_cast<unsigned short*>(mLineLoopIB->map(spaceNeeded, &offset));
1309 startIndex = offset / 2;
1310
1311 if (data)
1312 {
1313 switch (type)
1314 {
1315 case GL_NONE: // Non-indexed draw
1316 for (int i = 0; i < count; i++)
1317 {
1318 data[i] = i;
1319 }
1320 data[count] = 0;
1321 break;
1322 case GL_UNSIGNED_BYTE:
1323 for (int i = 0; i < count; i++)
1324 {
1325 data[i] = static_cast<const GLubyte*>(indices)[i];
1326 }
1327 data[count] = static_cast<const GLubyte*>(indices)[0];
1328 break;
1329 case GL_UNSIGNED_SHORT:
1330 for (int i = 0; i < count; i++)
1331 {
1332 data[i] = static_cast<const GLushort*>(indices)[i];
1333 }
1334 data[count] = static_cast<const GLushort*>(indices)[0];
1335 break;
1336 case GL_UNSIGNED_INT:
1337 for (int i = 0; i < count; i++)
1338 {
1339 data[i] = static_cast<const GLuint*>(indices)[i];
1340 }
1341 data[count] = static_cast<const GLuint*>(indices)[0];
1342 break;
1343 default: UNREACHABLE();
1344 }
1345
1346 mLineLoopIB->unmap();
1347 succeeded = true;
1348 }
1349 }
1350 }
1351
1352 if (succeeded)
1353 {
1354 if (mAppliedIBSerial != mLineLoopIB->getSerial())
1355 {
1356 mDevice->SetIndices(mLineLoopIB->getBuffer());
1357 mAppliedIBSerial = mLineLoopIB->getSerial();
1358 }
1359
1360 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
1361 }
1362 else
1363 {
1364 ERR("Could not create a looping index buffer for GL_LINE_LOOP.");
1365 return error(GL_OUT_OF_MEMORY);
1366 }
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001367}
1368
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001369void Renderer9::applyShaders(gl::ProgramBinary *programBinary)
1370{
daniel@transgaming.com95892412012-11-28 20:59:09 +00001371 ShaderExecutable *vertexExe = programBinary->getVertexExecutable();
1372 ShaderExecutable *pixelExe = programBinary->getPixelExecutable();
1373
1374 IDirect3DVertexShader9 *vertexShader = NULL;
1375 if (vertexExe) vertexShader = ShaderExecutable9::makeShaderExecutable9(vertexExe)->getVertexShader();
1376
1377 IDirect3DPixelShader9 *pixelShader = NULL;
1378 if (pixelExe) pixelShader = ShaderExecutable9::makeShaderExecutable9(pixelExe)->getPixelShader();
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001379
1380 mDevice->SetPixelShader(pixelShader);
1381 mDevice->SetVertexShader(vertexShader);
1382 programBinary->dirtyAllUniforms();
1383}
1384
daniel@transgaming.com084a2572012-11-28 20:55:17 +00001385void Renderer9::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001386{
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001387 D3DCOLOR color = D3DCOLOR_ARGB(gl::unorm<8>(clearParams.colorClearValue.alpha),
1388 gl::unorm<8>(clearParams.colorClearValue.red),
1389 gl::unorm<8>(clearParams.colorClearValue.green),
1390 gl::unorm<8>(clearParams.colorClearValue.blue));
1391 float depth = gl::clamp01(clearParams.depthClearValue);
1392 int stencil = clearParams.stencilClearValue & 0x000000FF;
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001393
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001394 unsigned int stencilUnmasked = 0x0;
1395 if ((clearParams.mask & GL_STENCIL_BUFFER_BIT) && frameBuffer->hasStencil())
1396 {
1397 unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
1398 stencilUnmasked = (0x1 << stencilSize) - 1;
1399 }
1400
1401 bool alphaUnmasked = (gl::GetAlphaSize(mRenderTargetDesc.format) == 0) || clearParams.colorMaskAlpha;
1402
1403 const bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
1404 (clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
1405 const bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
1406 !(clearParams.colorMaskRed && clearParams.colorMaskGreen &&
1407 clearParams.colorMaskBlue && alphaUnmasked);
1408
1409 if (needMaskedColorClear || needMaskedStencilClear)
1410 {
1411 // State which is altered in all paths from this point to the clear call is saved.
1412 // State which is altered in only some paths will be flagged dirty in the case that
1413 // that path is taken.
1414 HRESULT hr;
1415 if (mMaskedClearSavedState == NULL)
1416 {
1417 hr = mDevice->BeginStateBlock();
1418 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1419
1420 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1421 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1422 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1423 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1424 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1425 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1426 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1427 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1428 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1429 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1430 mDevice->SetPixelShader(NULL);
1431 mDevice->SetVertexShader(NULL);
1432 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
1433 mDevice->SetStreamSource(0, NULL, 0, 0);
1434 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1435 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1436 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1437 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1438 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1439 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1440 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1441
1442 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1443 {
1444 mDevice->SetStreamSourceFreq(i, 1);
1445 }
1446
1447 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
1448 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1449 }
1450
1451 ASSERT(mMaskedClearSavedState != NULL);
1452
1453 if (mMaskedClearSavedState != NULL)
1454 {
1455 hr = mMaskedClearSavedState->Capture();
1456 ASSERT(SUCCEEDED(hr));
1457 }
1458
1459 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1460 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1461 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1462 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1463 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1464 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1465 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1466 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1467
1468 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1469 {
1470 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE,
1471 gl_d3d9::ConvertColorMask(clearParams.colorMaskRed,
1472 clearParams.colorMaskGreen,
1473 clearParams.colorMaskBlue,
1474 clearParams.colorMaskAlpha));
1475 }
1476 else
1477 {
1478 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1479 }
1480
1481 if (stencilUnmasked != 0x0 && (clearParams.mask & GL_STENCIL_BUFFER_BIT))
1482 {
1483 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
1484 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
1485 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
1486 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
1487 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
1488 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
1489 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
1490 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
1491 }
1492 else
1493 {
1494 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1495 }
1496
1497 mDevice->SetPixelShader(NULL);
1498 mDevice->SetVertexShader(NULL);
1499 mDevice->SetFVF(D3DFVF_XYZRHW);
1500 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1501 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1502 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1503 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1504 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1505 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1506 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1507
1508 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1509 {
1510 mDevice->SetStreamSourceFreq(i, 1);
1511 }
1512
1513 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
1514 quad[0][0] = -0.5f;
1515 quad[0][1] = mRenderTargetDesc.height - 0.5f;
1516 quad[0][2] = 0.0f;
1517 quad[0][3] = 1.0f;
1518
1519 quad[1][0] = mRenderTargetDesc.width - 0.5f;
1520 quad[1][1] = mRenderTargetDesc.height - 0.5f;
1521 quad[1][2] = 0.0f;
1522 quad[1][3] = 1.0f;
1523
1524 quad[2][0] = -0.5f;
1525 quad[2][1] = -0.5f;
1526 quad[2][2] = 0.0f;
1527 quad[2][3] = 1.0f;
1528
1529 quad[3][0] = mRenderTargetDesc.width - 0.5f;
1530 quad[3][1] = -0.5f;
1531 quad[3][2] = 0.0f;
1532 quad[3][3] = 1.0f;
1533
1534 startScene();
1535 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
1536
1537 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1538 {
1539 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
1540 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
1541 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
1542 }
1543
1544 if (mMaskedClearSavedState != NULL)
1545 {
1546 mMaskedClearSavedState->Apply();
1547 }
1548 }
1549 else if (clearParams.mask)
1550 {
1551 DWORD dxClearFlags = 0;
1552 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1553 {
1554 dxClearFlags |= D3DCLEAR_TARGET;
1555 }
1556 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1557 {
1558 dxClearFlags |= D3DCLEAR_ZBUFFER;
1559 }
1560 if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
1561 {
1562 dxClearFlags |= D3DCLEAR_STENCIL;
1563 }
1564
1565 mDevice->Clear(0, NULL, dxClearFlags, color, depth, stencil);
1566 }
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001567}
1568
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001569void Renderer9::markAllStateDirty()
1570{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001571 mAppliedRenderTargetSerial = 0;
1572 mAppliedDepthbufferSerial = 0;
1573 mAppliedStencilbufferSerial = 0;
1574 mDepthStencilInitialized = false;
1575 mRenderTargetDescInitialized = false;
1576
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001577 mForceSetDepthStencilState = true;
1578 mForceSetRasterState = true;
1579 mForceSetBlendState = true;
1580 mForceSetScissor = true;
1581 mForceSetViewport = true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001582
1583 mVertexDeclarationCache.markStateDirty();
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001584}
1585
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001586void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001587{
1588 while (!mEventQueryPool.empty())
1589 {
1590 mEventQueryPool.back()->Release();
1591 mEventQueryPool.pop_back();
1592 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001593
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001594 if (mMaskedClearSavedState)
1595 {
1596 mMaskedClearSavedState->Release();
1597 mMaskedClearSavedState = NULL;
1598 }
1599
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001600 mVertexShaderCache.clear();
1601 mPixelShaderCache.clear();
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001602
daniel@transgaming.come569fc52012-11-28 20:56:02 +00001603 delete mBlit;
1604 mBlit = NULL;
1605
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001606 delete mVertexDataManager;
1607 mVertexDataManager = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001608
1609 delete mIndexDataManager;
1610 mIndexDataManager = NULL;
1611
1612 delete mLineLoopIB;
1613 mLineLoopIB = NULL;
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001614}
1615
1616
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001617void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001618{
1619 mDeviceLost = true;
1620}
1621
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001622bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001623{
1624 return mDeviceLost;
1625}
1626
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001627// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001628bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001629{
1630 bool isLost = false;
1631
1632 if (mDeviceEx)
1633 {
1634 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
1635 }
1636 else if (mDevice)
1637 {
1638 isLost = FAILED(mDevice->TestCooperativeLevel());
1639 }
1640 else
1641 {
1642 // No device yet, so no reset required
1643 }
1644
1645 if (isLost)
1646 {
1647 // ensure we note the device loss --
1648 // we'll probably get this done again by markDeviceLost
1649 // but best to remember it!
1650 // Note that we don't want to clear the device loss status here
1651 // -- this needs to be done by resetDevice
1652 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001653 if (notify)
1654 {
1655 mDisplay->notifyDeviceLost();
1656 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001657 }
1658
1659 return isLost;
1660}
1661
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001662bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001663{
1664 HRESULT status = D3D_OK;
1665
1666 if (mDeviceEx)
1667 {
1668 status = mDeviceEx->CheckDeviceState(NULL);
1669 }
1670 else if (mDevice)
1671 {
1672 status = mDevice->TestCooperativeLevel();
1673 }
1674
1675 switch (status)
1676 {
1677 case D3DERR_DEVICENOTRESET:
1678 case D3DERR_DEVICEHUNG:
1679 return true;
1680 default:
1681 return false;
1682 }
1683}
1684
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001685bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001686{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001687 releaseDeviceResources();
1688
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001689 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
1690
1691 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001692 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001693 int attempts = 3;
1694
1695 while (lost && attempts > 0)
1696 {
1697 if (mDeviceEx)
1698 {
1699 Sleep(500); // Give the graphics driver some CPU time
1700 result = mDeviceEx->ResetEx(&presentParameters, NULL);
1701 }
1702 else
1703 {
1704 result = mDevice->TestCooperativeLevel();
1705 while (result == D3DERR_DEVICELOST)
1706 {
1707 Sleep(100); // Give the graphics driver some CPU time
1708 result = mDevice->TestCooperativeLevel();
1709 }
1710
1711 if (result == D3DERR_DEVICENOTRESET)
1712 {
1713 result = mDevice->Reset(&presentParameters);
1714 }
1715 }
1716
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001717 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001718 attempts --;
1719 }
1720
1721 if (FAILED(result))
1722 {
1723 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
1724 return false;
1725 }
1726
1727 // reset device defaults
1728 initializeDevice();
1729 mDeviceLost = false;
1730
1731 return true;
1732}
1733
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001734DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001735{
1736 return mAdapterIdentifier.VendorId;
1737}
1738
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001739const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001740{
1741 return mAdapterIdentifier.Description;
1742}
1743
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001744GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001745{
1746 return mAdapterIdentifier.DeviceIdentifier;
1747}
1748
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001749void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001750{
1751 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
1752 {
1753 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
1754 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
1755
1756 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
1757 }
1758}
1759
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001760bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001761{
1762 D3DDISPLAYMODE currentDisplayMode;
1763 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1764
1765 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
1766}
1767
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001768bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001769{
1770 D3DDISPLAYMODE currentDisplayMode;
1771 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1772
1773 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
1774}
1775
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001776bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001777{
1778 D3DDISPLAYMODE currentDisplayMode;
1779 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1780
1781 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
1782}
1783
1784// we use INTZ for depth textures in Direct3D9
1785// we also want NULL texture support to ensure the we can make depth-only FBOs
1786// see http://aras-p.info/texts/D3D9GPUHacks.html
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001787bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001788{
1789 D3DDISPLAYMODE currentDisplayMode;
1790 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1791
1792 bool intz = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1793 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ));
1794 bool null = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1795 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
1796
1797 return intz && null;
1798}
1799
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001800bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001801{
1802 D3DDISPLAYMODE currentDisplayMode;
1803 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1804
1805 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1806 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1807 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1808 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1809
1810 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1811 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F))&&
1812 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1813 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1814
1815 if (!*filtering && !*renderable)
1816 {
1817 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1818 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1819 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1820 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1821 }
1822 else
1823 {
1824 return true;
1825 }
1826}
1827
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001828bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001829{
1830 D3DDISPLAYMODE currentDisplayMode;
1831 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1832
1833 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1834 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1835 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1836 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1837
1838 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1839 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1840 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1841 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1842
1843 if (!*filtering && !*renderable)
1844 {
1845 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1846 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1847 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1848 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1849 }
1850 else
1851 {
1852 return true;
1853 }
1854}
1855
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001856bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001857{
1858 D3DDISPLAYMODE currentDisplayMode;
1859 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1860
1861 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
1862}
1863
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001864bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001865{
1866 D3DDISPLAYMODE currentDisplayMode;
1867 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1868
1869 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
1870}
1871
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001872bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001873{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001874 return mSupportsTextureFilterAnisotropy;
1875}
1876
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001877float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001878{
1879 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001880 {
1881 return mDeviceCaps.MaxAnisotropy;
1882 }
1883 return 1.0f;
1884}
1885
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001886bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001887{
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001888 IDirect3DQuery9 *query = allocateEventQuery();
1889 if (query)
1890 {
1891 freeEventQuery(query);
1892 return true;
1893 }
1894 else
1895 {
1896 return false;
1897 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001898 return true;
1899}
1900
1901// Only Direct3D 10 ready devices support all the necessary vertex texture formats.
1902// We test this using D3D9 by checking support for the R16F format.
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001903bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001904{
1905 if (!mDevice || mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(3, 0))
1906 {
1907 return false;
1908 }
1909
1910 D3DDISPLAYMODE currentDisplayMode;
1911 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1912
1913 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F);
1914
1915 return SUCCEEDED(result);
1916}
1917
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001918bool Renderer9::getNonPower2TextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001919{
1920 return mSupportsNonPower2Textures;
1921}
1922
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001923bool Renderer9::getOcclusionQuerySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001924{
1925 if (!mDevice)
1926 {
1927 return false;
1928 }
1929
1930 IDirect3DQuery9 *query = NULL;
1931 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query);
1932 if (SUCCEEDED(result) && query)
1933 {
1934 query->Release();
1935 return true;
1936 }
1937 else
1938 {
1939 return false;
1940 }
1941}
1942
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001943bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001944{
1945 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
1946}
1947
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001948bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001949{
1950 // PIX doesn't seem to support using share handles, so disable them.
1951 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00001952 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001953}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001954
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00001955int Renderer9::getMajorShaderModel() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001956{
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00001957 return D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion);
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001958}
1959
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001960float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001961{
1962 return mDeviceCaps.MaxPointSize;
1963}
1964
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001965int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001966{
1967 return (int)mDeviceCaps.MaxTextureWidth;
1968}
1969
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001970int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001971{
1972 return (int)mDeviceCaps.MaxTextureHeight;
1973}
1974
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001975bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001976{
1977 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
1978}
1979
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001980DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001981{
1982 return mDeviceCaps.DeclTypes;
1983}
1984
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001985int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001986{
1987 return mMinSwapInterval;
1988}
1989
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001990int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001991{
1992 return mMaxSwapInterval;
1993}
1994
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001995int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001996{
1997 return mMaxSupportedSamples;
1998}
1999
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002000int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002001{
2002 if (requested == 0)
2003 {
2004 return requested;
2005 }
2006
2007 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
2008 if (itr == mMultiSampleSupport.end())
2009 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00002010 if (format == D3DFMT_UNKNOWN)
2011 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002012 return -1;
2013 }
2014
2015 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
2016 {
2017 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
2018 {
2019 return i;
2020 }
2021 }
2022
2023 return -1;
2024}
2025
daniel@transgaming.coma9571682012-11-28 19:33:08 +00002026D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
2027{
2028 switch (internalformat)
2029 {
2030 case GL_DEPTH_COMPONENT16:
2031 case GL_DEPTH_COMPONENT32_OES:
2032 case GL_DEPTH24_STENCIL8_OES:
2033 return D3DFMT_INTZ;
2034 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
2035 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
2036 return D3DFMT_DXT1;
2037 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
2038 return D3DFMT_DXT3;
2039 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
2040 return D3DFMT_DXT5;
2041 case GL_RGBA32F_EXT:
2042 case GL_RGB32F_EXT:
2043 case GL_ALPHA32F_EXT:
2044 case GL_LUMINANCE32F_EXT:
2045 case GL_LUMINANCE_ALPHA32F_EXT:
2046 return D3DFMT_A32B32G32R32F;
2047 case GL_RGBA16F_EXT:
2048 case GL_RGB16F_EXT:
2049 case GL_ALPHA16F_EXT:
2050 case GL_LUMINANCE16F_EXT:
2051 case GL_LUMINANCE_ALPHA16F_EXT:
2052 return D3DFMT_A16B16G16R16F;
2053 case GL_LUMINANCE8_EXT:
2054 if (getLuminanceTextureSupport())
2055 {
2056 return D3DFMT_L8;
2057 }
2058 break;
2059 case GL_LUMINANCE8_ALPHA8_EXT:
2060 if (getLuminanceAlphaTextureSupport())
2061 {
2062 return D3DFMT_A8L8;
2063 }
2064 break;
2065 case GL_RGB8_OES:
2066 case GL_RGB565:
2067 return D3DFMT_X8R8G8B8;
2068 }
2069
2070 return D3DFMT_A8R8G8B8;
2071}
2072
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002073bool Renderer9::copyToRenderTarget(TextureStorage2D *dest, TextureStorage2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002074{
2075 bool result = false;
2076
2077 if (source && dest)
2078 {
2079 int levels = source->levelCount();
2080 for (int i = 0; i < levels; ++i)
2081 {
2082 IDirect3DSurface9 *srcSurf = source->getSurfaceLevel(i, false);
2083 IDirect3DSurface9 *dstSurf = dest->getSurfaceLevel(i, false);
2084
2085 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2086
2087 if (srcSurf) srcSurf->Release();
2088 if (dstSurf) dstSurf->Release();
2089
2090 if (!result)
2091 return false;
2092 }
2093 }
2094
2095 return result;
2096}
2097
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002098bool Renderer9::copyToRenderTarget(TextureStorageCubeMap *dest, TextureStorageCubeMap *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002099{
2100 bool result = false;
2101
2102 if (source && dest)
2103 {
2104 int levels = source->levelCount();
2105 for (int f = 0; f < 6; f++)
2106 {
2107 for (int i = 0; i < levels; i++)
2108 {
2109 IDirect3DSurface9 *srcSurf = source->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
2110 IDirect3DSurface9 *dstSurf = dest->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
2111
2112 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2113
2114 if (srcSurf) srcSurf->Release();
2115 if (dstSurf) dstSurf->Release();
2116
2117 if (!result)
2118 return false;
2119 }
2120 }
2121 }
2122
2123 return result;
2124}
2125
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002126D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002127{
2128 if (mD3d9Ex != NULL)
2129 {
2130 return D3DPOOL_DEFAULT;
2131 }
2132 else
2133 {
2134 if (!(usage & D3DUSAGE_DYNAMIC))
2135 {
2136 return D3DPOOL_MANAGED;
2137 }
2138 }
2139
2140 return D3DPOOL_DEFAULT;
2141}
2142
daniel@transgaming.com38380882012-11-28 19:36:39 +00002143bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2144 GLint xoffset, GLint yoffset, TextureStorage2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002145{
2146 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
2147}
2148
daniel@transgaming.com38380882012-11-28 19:36:39 +00002149bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2150 GLint xoffset, GLint yoffset, TextureStorageCubeMap *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002151{
2152 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
2153}
2154
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002155bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
2156 bool blitRenderTarget, bool blitDepthStencil)
2157{
2158 endScene();
2159
2160 if (blitRenderTarget)
2161 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002162 gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer();
2163 gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer();
2164 RenderTarget9 *readRenderTarget = NULL;
2165 RenderTarget9 *drawRenderTarget = NULL;
2166 IDirect3DSurface9* readSurface = NULL;
2167 IDirect3DSurface9* drawSurface = NULL;
2168
2169 if (readBuffer)
2170 {
2171 readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
2172 }
2173 if (drawBuffer)
2174 {
2175 drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
2176 }
2177
2178 if (readRenderTarget)
2179 {
2180 readSurface = readRenderTarget->getSurface();
2181 }
2182 if (drawRenderTarget)
2183 {
2184 drawSurface = drawRenderTarget->getSurface();
2185 }
2186
2187 if (!readSurface || !drawSurface)
2188 {
2189 ERR("Failed to retrieve the render target.");
2190 return error(GL_OUT_OF_MEMORY, false);
2191 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002192
2193 RECT srcRect, dstRect;
2194 RECT *srcRectPtr = NULL;
2195 RECT *dstRectPtr = NULL;
2196
2197 if (readRect)
2198 {
2199 srcRect.left = readRect->x;
2200 srcRect.right = readRect->x + readRect->width;
2201 srcRect.top = readRect->y;
2202 srcRect.bottom = readRect->y + readRect->height;
2203 srcRectPtr = &srcRect;
2204 }
2205
2206 if (drawRect)
2207 {
2208 dstRect.left = drawRect->x;
2209 dstRect.right = drawRect->x + drawRect->width;
2210 dstRect.top = drawRect->y;
2211 dstRect.bottom = drawRect->y + drawRect->height;
2212 dstRectPtr = &dstRect;
2213 }
2214
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002215 HRESULT result = mDevice->StretchRect(readSurface, srcRectPtr, drawSurface, dstRectPtr, D3DTEXF_NONE);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002216
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002217 readSurface->Release();
2218 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002219
2220 if (FAILED(result))
2221 {
2222 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2223 return false;
2224 }
2225 }
2226
2227 if (blitDepthStencil)
2228 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002229 gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
2230 gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
2231 RenderTarget9 *readDepthStencil = NULL;
2232 RenderTarget9 *drawDepthStencil = NULL;
2233 IDirect3DSurface9* readSurface = NULL;
2234 IDirect3DSurface9* drawSurface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002235
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002236 if (readBuffer)
2237 {
2238 readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
2239 }
2240 if (drawBuffer)
2241 {
2242 drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
2243 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002244
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002245 if (readDepthStencil)
2246 {
2247 readSurface = readDepthStencil->getSurface();
2248 }
2249 if (drawDepthStencil)
2250 {
2251 drawSurface = drawDepthStencil->getSurface();
2252 }
2253
2254 if (!readSurface || !drawSurface)
2255 {
2256 ERR("Failed to retrieve the render target.");
2257 return error(GL_OUT_OF_MEMORY, false);
2258 }
2259
2260 HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
2261
2262 readSurface->Release();
2263 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002264
2265 if (FAILED(result))
2266 {
2267 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2268 return false;
2269 }
2270 }
2271
2272 return true;
2273}
2274
2275void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
2276 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
2277{
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002278 RenderTarget9 *renderTarget = NULL;
2279 IDirect3DSurface9 *surface = NULL;
2280 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
2281
2282 if (colorbuffer)
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002283 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002284 renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
2285 }
2286
2287 if (renderTarget)
2288 {
2289 surface = renderTarget->getSurface();
2290 }
2291
2292 if (!surface)
2293 {
2294 // context must be lost
2295 return;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002296 }
2297
2298 D3DSURFACE_DESC desc;
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002299 surface->GetDesc(&desc);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002300
2301 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2302 {
2303 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002304 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002305 return error(GL_OUT_OF_MEMORY);
2306 }
2307
2308 HRESULT result;
2309 IDirect3DSurface9 *systemSurface = NULL;
2310 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
2311 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2312 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2313 if (directToPixels)
2314 {
2315 // Use the pixels ptr as a shared handle to write directly into client's memory
2316 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2317 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2318 if (FAILED(result))
2319 {
2320 // Try again without the shared handle
2321 directToPixels = false;
2322 }
2323 }
2324
2325 if (!directToPixels)
2326 {
2327 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2328 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2329 if (FAILED(result))
2330 {
2331 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002332 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002333 return error(GL_OUT_OF_MEMORY);
2334 }
2335 }
2336
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002337 result = mDevice->GetRenderTargetData(surface, systemSurface);
2338 surface->Release();
2339 surface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002340
2341 if (FAILED(result))
2342 {
2343 systemSurface->Release();
2344
2345 // It turns out that D3D will sometimes produce more error
2346 // codes than those documented.
daniel@transgaming.com414c9162012-11-28 20:54:57 +00002347 if (checkDeviceLost(result))
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002348 return error(GL_OUT_OF_MEMORY);
2349 else
2350 {
2351 UNREACHABLE();
2352 return;
2353 }
2354
2355 }
2356
2357 if (directToPixels)
2358 {
2359 systemSurface->Release();
2360 return;
2361 }
2362
2363 RECT rect;
2364 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
2365 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
2366 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2367 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2368
2369 D3DLOCKED_RECT lock;
2370 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2371
2372 if (FAILED(result))
2373 {
2374 UNREACHABLE();
2375 systemSurface->Release();
2376
2377 return; // No sensible error to generate
2378 }
2379
2380 unsigned char *dest = (unsigned char*)pixels;
2381 unsigned short *dest16 = (unsigned short*)pixels;
2382
2383 unsigned char *source;
2384 int inputPitch;
2385 if (packReverseRowOrder)
2386 {
2387 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2388 inputPitch = -lock.Pitch;
2389 }
2390 else
2391 {
2392 source = (unsigned char*)lock.pBits;
2393 inputPitch = lock.Pitch;
2394 }
2395
2396 unsigned int fastPixelSize = 0;
2397
2398 if (desc.Format == D3DFMT_A8R8G8B8 &&
2399 format == GL_BGRA_EXT &&
2400 type == GL_UNSIGNED_BYTE)
2401 {
2402 fastPixelSize = 4;
2403 }
2404 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2405 format == GL_BGRA_EXT &&
2406 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2407 (desc.Format == D3DFMT_A1R5G5B5 &&
2408 format == GL_BGRA_EXT &&
2409 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2410 {
2411 fastPixelSize = 2;
2412 }
2413 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2414 format == GL_RGBA &&
2415 type == GL_HALF_FLOAT_OES)
2416 {
2417 fastPixelSize = 8;
2418 }
2419 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2420 format == GL_RGBA &&
2421 type == GL_FLOAT)
2422 {
2423 fastPixelSize = 16;
2424 }
2425
2426 for (int j = 0; j < rect.bottom - rect.top; j++)
2427 {
2428 if (fastPixelSize != 0)
2429 {
2430 // Fast path for formats which require no translation:
2431 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2432 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2433 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2434 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2435 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2436 //
2437 // Note that buffers with no alpha go through the slow path below.
2438 memcpy(dest + j * outputPitch,
2439 source + j * inputPitch,
2440 (rect.right - rect.left) * fastPixelSize);
2441 continue;
2442 }
2443
2444 for (int i = 0; i < rect.right - rect.left; i++)
2445 {
2446 float r;
2447 float g;
2448 float b;
2449 float a;
2450
2451 switch (desc.Format)
2452 {
2453 case D3DFMT_R5G6B5:
2454 {
2455 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2456
2457 a = 1.0f;
2458 b = (rgb & 0x001F) * (1.0f / 0x001F);
2459 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2460 r = (rgb & 0xF800) * (1.0f / 0xF800);
2461 }
2462 break;
2463 case D3DFMT_A1R5G5B5:
2464 {
2465 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2466
2467 a = (argb & 0x8000) ? 1.0f : 0.0f;
2468 b = (argb & 0x001F) * (1.0f / 0x001F);
2469 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2470 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2471 }
2472 break;
2473 case D3DFMT_A8R8G8B8:
2474 {
2475 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2476
2477 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2478 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2479 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2480 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2481 }
2482 break;
2483 case D3DFMT_X8R8G8B8:
2484 {
2485 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2486
2487 a = 1.0f;
2488 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2489 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2490 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2491 }
2492 break;
2493 case D3DFMT_A2R10G10B10:
2494 {
2495 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2496
2497 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2498 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2499 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2500 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2501 }
2502 break;
2503 case D3DFMT_A32B32G32R32F:
2504 {
2505 // float formats in D3D are stored rgba, rather than the other way round
2506 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2507 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2508 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2509 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2510 }
2511 break;
2512 case D3DFMT_A16B16G16R16F:
2513 {
2514 // float formats in D3D are stored rgba, rather than the other way round
2515 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2516 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2517 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2518 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
2519 }
2520 break;
2521 default:
2522 UNIMPLEMENTED(); // FIXME
2523 UNREACHABLE();
2524 return;
2525 }
2526
2527 switch (format)
2528 {
2529 case GL_RGBA:
2530 switch (type)
2531 {
2532 case GL_UNSIGNED_BYTE:
2533 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2534 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2535 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2536 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2537 break;
2538 default: UNREACHABLE();
2539 }
2540 break;
2541 case GL_BGRA_EXT:
2542 switch (type)
2543 {
2544 case GL_UNSIGNED_BYTE:
2545 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2546 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2547 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2548 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2549 break;
2550 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2551 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2552 // this type is packed as follows:
2553 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2554 // --------------------------------------------------------------------------------
2555 // | 4th | 3rd | 2nd | 1st component |
2556 // --------------------------------------------------------------------------------
2557 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2558 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2559 ((unsigned short)(15 * a + 0.5f) << 12)|
2560 ((unsigned short)(15 * r + 0.5f) << 8) |
2561 ((unsigned short)(15 * g + 0.5f) << 4) |
2562 ((unsigned short)(15 * b + 0.5f) << 0);
2563 break;
2564 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2565 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2566 // this type is packed as follows:
2567 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2568 // --------------------------------------------------------------------------------
2569 // | 4th | 3rd | 2nd | 1st component |
2570 // --------------------------------------------------------------------------------
2571 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2572 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2573 ((unsigned short)( a + 0.5f) << 15) |
2574 ((unsigned short)(31 * r + 0.5f) << 10) |
2575 ((unsigned short)(31 * g + 0.5f) << 5) |
2576 ((unsigned short)(31 * b + 0.5f) << 0);
2577 break;
2578 default: UNREACHABLE();
2579 }
2580 break;
2581 case GL_RGB:
2582 switch (type)
2583 {
2584 case GL_UNSIGNED_SHORT_5_6_5:
2585 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2586 ((unsigned short)(31 * b + 0.5f) << 0) |
2587 ((unsigned short)(63 * g + 0.5f) << 5) |
2588 ((unsigned short)(31 * r + 0.5f) << 11);
2589 break;
2590 case GL_UNSIGNED_BYTE:
2591 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2592 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2593 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2594 break;
2595 default: UNREACHABLE();
2596 }
2597 break;
2598 default: UNREACHABLE();
2599 }
2600 }
2601 }
2602
2603 systemSurface->UnlockRect();
2604
2605 systemSurface->Release();
2606}
2607
daniel@transgaming.comf2423652012-11-28 20:53:50 +00002608RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
2609{
2610 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2611 IDirect3DSurface9 *surface = NULL;
2612 if (depth)
2613 {
2614 surface = swapChain9->getDepthStencil();
2615 }
2616 else
2617 {
2618 surface = swapChain9->getRenderTarget();
2619 }
2620
2621 RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
2622
2623 return renderTarget;
2624}
2625
2626RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
2627{
2628 RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
2629 return renderTarget;
2630}
2631
daniel@transgaming.com55318902012-11-28 20:58:58 +00002632ShaderExecutable *Renderer9::loadExecutable(const DWORD *function, size_t length, GLenum type, void *data)
2633{
2634 ShaderExecutable9 *executable = NULL;
2635 gl::D3DConstantTable *table = reinterpret_cast<gl::D3DConstantTable *>(data);
2636
2637 switch (type)
2638 {
2639 case GL_VERTEX_SHADER:
2640 {
2641 IDirect3DVertexShader9 *vshader = createVertexShader(function, length);
2642 if (vshader)
2643 {
2644 executable = new ShaderExecutable9(vshader, table);
2645 }
2646 }
2647 break;
2648 case GL_FRAGMENT_SHADER:
2649 {
2650 IDirect3DPixelShader9 *pshader = createPixelShader(function, length);
2651 if (pshader)
2652 {
2653 executable = new ShaderExecutable9(pshader, table);
2654 }
2655 }
2656 break;
2657 default:
2658 UNREACHABLE();
2659 break;
2660 }
2661
2662 return executable;
2663}
2664
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002665ShaderExecutable *Renderer9::compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, GLenum type)
2666{
2667 const char *profile = NULL;
2668
2669 switch (type)
2670 {
2671 case GL_VERTEX_SHADER:
2672 profile = getMajorShaderModel() >= 3 ? "vs_3_0" : "vs_2_0";
2673 break;
2674 case GL_FRAGMENT_SHADER:
2675 profile = getMajorShaderModel() >= 3 ? "ps_3_0" : "ps_2_0";
2676 break;
2677 default:
2678 UNREACHABLE();
2679 return NULL;
2680 }
2681
2682 gl::D3DConstantTable *constantTable = NULL;
2683 ID3D10Blob *binary = compileToBinary(infoLog, shaderHLSL, profile, &constantTable);
2684 if (!binary)
2685 return NULL;
2686
daniel@transgaming.com55318902012-11-28 20:58:58 +00002687 ShaderExecutable *executable = loadExecutable((DWORD *)binary->GetBufferPointer(), binary->GetBufferSize(), type, constantTable);
daniel@transgaming.com536dd6e2012-11-28 21:00:18 +00002688 binary->Release();
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002689
2690 return executable;
2691}
2692
2693// Compiles the HLSL code of the attached shaders into executable binaries
2694ID3D10Blob *Renderer9::compileToBinary(gl::InfoLog &infoLog, const char *hlsl, const char *profile, gl::D3DConstantTable **constantTable)
2695{
2696 if (!hlsl)
2697 {
2698 return NULL;
2699 }
2700
2701 HRESULT result = S_OK;
2702 UINT flags = 0;
2703 std::string sourceText;
2704 if (gl::perfActive())
2705 {
2706 flags |= D3DCOMPILE_DEBUG;
2707#ifdef NDEBUG
2708 flags |= ANGLE_COMPILE_OPTIMIZATION_LEVEL;
2709#else
2710 flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
2711#endif
2712
2713 std::string sourcePath = getTempPath();
2714 sourceText = std::string("#line 2 \"") + sourcePath + std::string("\"\n\n") + std::string(hlsl);
2715 writeFile(sourcePath.c_str(), sourceText.c_str(), sourceText.size());
2716 }
2717 else
2718 {
2719 flags |= ANGLE_COMPILE_OPTIMIZATION_LEVEL;
2720 sourceText = hlsl;
2721 }
2722
2723 // Sometimes D3DCompile will fail with the default compilation flags for complicated shaders when it would otherwise pass with alternative options.
2724 // Try the default flags first and if compilation fails, try some alternatives.
2725 const static UINT extraFlags[] =
2726 {
2727 0,
2728 D3DCOMPILE_AVOID_FLOW_CONTROL,
2729 D3DCOMPILE_PREFER_FLOW_CONTROL
2730 };
2731
2732 const static char * const extraFlagNames[] =
2733 {
2734 "default",
2735 "avoid flow control",
2736 "prefer flow control"
2737 };
2738
2739 for (int i = 0; i < sizeof(extraFlags) / sizeof(UINT); ++i)
2740 {
2741 ID3D10Blob *errorMessage = NULL;
2742 ID3D10Blob *binary = NULL;
daniel@transgaming.comf0516cf2012-11-28 20:59:18 +00002743 result = mD3DCompileFunc(hlsl, strlen(hlsl), gl::g_fakepath, NULL, NULL,
2744 "main", profile, flags | extraFlags[i], 0, &binary, &errorMessage);
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002745 if (errorMessage)
2746 {
2747 const char *message = (const char*)errorMessage->GetBufferPointer();
2748
2749 infoLog.appendSanitized(message);
2750 TRACE("\n%s", hlsl);
2751 TRACE("\n%s", message);
2752
2753 errorMessage->Release();
2754 errorMessage = NULL;
2755 }
2756
2757 if (SUCCEEDED(result))
2758 {
2759 gl::D3DConstantTable *table = new gl::D3DConstantTable(binary->GetBufferPointer(), binary->GetBufferSize());
2760 if (table->error())
2761 {
2762 delete table;
2763 binary->Release();
2764 return NULL;
2765 }
2766
2767 *constantTable = table;
2768 return binary;
2769 }
2770 else
2771 {
2772 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY)
2773 {
2774 return error(GL_OUT_OF_MEMORY, (ID3D10Blob*) NULL);
2775 }
2776
2777 infoLog.append("Warning: D3D shader compilation failed with ");
2778 infoLog.append(extraFlagNames[i]);
2779 infoLog.append(" flags.");
2780 if (i + 1 < sizeof(extraFlagNames) / sizeof(char*))
2781 {
2782 infoLog.append(" Retrying with ");
2783 infoLog.append(extraFlagNames[i + 1]);
2784 infoLog.append(".\n");
2785 }
2786 }
2787 }
2788
2789 return NULL;
2790}
2791
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002792bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
2793{
2794 return mBlit->boxFilter(source, dest);
2795}
2796
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002797D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002798{
2799 if (mD3d9Ex != NULL)
2800 {
2801 return D3DPOOL_DEFAULT;
2802 }
2803 else
2804 {
2805 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2806 {
2807 return D3DPOOL_MANAGED;
2808 }
2809 }
2810
2811 return D3DPOOL_DEFAULT;
2812}
2813
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002814bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
2815{
2816 if (source && dest)
2817 {
2818 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
2819 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
2820
2821 if (fromManaged)
2822 {
2823 D3DSURFACE_DESC desc;
2824 source->GetDesc(&desc);
2825
2826 IDirect3DSurface9 *surf = 0;
2827 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
2828
2829 if (SUCCEEDED(result))
2830 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002831 Image::CopyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002832 result = device->UpdateSurface(surf, NULL, dest, NULL);
2833 surf->Release();
2834 }
2835 }
2836 else
2837 {
2838 endScene();
2839 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
2840 }
2841
2842 if (FAILED(result))
2843 {
2844 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2845 return false;
2846 }
2847 }
2848
2849 return true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00002850}
2851
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002852}