blob: e1a540018bed590a6421beba1f2afb8f119a7de6 [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.com493d4f82012-11-28 19:35:45 +0000663void Renderer9::setRasterizerState(const gl::RasterizerState &rasterState, unsigned int depthSize)
664{
665 bool rasterStateChanged = mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0;
666 bool depthSizeChanged = mForceSetRasterState || depthSize != mCurDepthSize;
667
668 if (rasterStateChanged)
669 {
670 // Set the cull mode
671 if (rasterState.cullFace)
672 {
673 mDevice->SetRenderState(D3DRS_CULLMODE, gl_d3d9::ConvertCullMode(rasterState.cullMode, rasterState.frontFace));
674 }
675 else
676 {
677 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
678 }
679
680 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, rasterState.scissorTest ? TRUE : FALSE);
681
682 mCurRasterState = rasterState;
683 }
684
685 if (rasterStateChanged || depthSizeChanged)
686 {
687 if (rasterState.polygonOffsetFill)
688 {
689 if (depthSize > 0)
690 {
691 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
692
693 float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(depthSize));
694 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
695 }
696 }
697 else
698 {
699 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
700 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
701 }
702
703 mCurDepthSize = depthSize;
704 }
705
706 mForceSetRasterState = false;
707}
708
709void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
710{
711 bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
712 bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
713 bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
714
715 if (blendStateChanged || blendColorChanged)
716 {
717 if (blendState.blend)
718 {
719 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
720
721 if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
722 blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
723 {
724 mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
725 }
726 else
727 {
728 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
729 gl::unorm<8>(blendColor.alpha),
730 gl::unorm<8>(blendColor.alpha),
731 gl::unorm<8>(blendColor.alpha)));
732 }
733
734 mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
735 mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
736 mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
737
738 if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
739 blendState.destBlendRGB != blendState.destBlendAlpha ||
740 blendState.blendEquationRGB != blendState.blendEquationAlpha)
741 {
742 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
743
744 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
745 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
746 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
747 }
748 else
749 {
750 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
751 }
752 }
753 else
754 {
755 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
756 }
757
758 if (blendState.sampleAlphaToCoverage)
759 {
760 FIXME("Sample alpha to coverage is unimplemented.");
761 }
762
763 // Set the color mask
764 bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
765 // Apparently some ATI cards have a bug where a draw with a zero color
766 // write mask can cause later draws to have incorrect results. Instead,
767 // set a nonzero color write mask but modify the blend state so that no
768 // drawing is done.
769 // http://code.google.com/p/angleproject/issues/detail?id=169
770
771 DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
772 blendState.colorMaskBlue, blendState.colorMaskAlpha);
773 if (colorMask == 0 && !zeroColorMaskAllowed)
774 {
775 // Enable green channel, but set blending so nothing will be drawn.
776 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
777 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
778
779 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
780 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
781 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
782 }
783 else
784 {
785 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
786 }
787
788 mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
789
790 mCurBlendState = blendState;
791 mCurBlendColor = blendColor;
792 }
793
794 if (sampleMaskChanged)
795 {
796 // Set the multisample mask
797 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
798 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
799
800 mCurSampleMask = sampleMask;
801 }
802
803 mForceSetBlendState = false;
804}
805
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000806void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
807 int stencilBackRef, bool frontFaceCCW, unsigned int stencilSize)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000808{
809 bool depthStencilStateChanged = mForceSetDepthStencilState ||
810 memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000811 bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
812 stencilBackRef != mCurStencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000813 bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
814 bool stencilSizeChanged = mForceSetDepthStencilState || stencilSize != mCurStencilSize;
815
816 if (depthStencilStateChanged)
817 {
818 if (depthStencilState.depthTest)
819 {
820 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
821 mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
822 }
823 else
824 {
825 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
826 }
827
828 mCurDepthStencilState = depthStencilState;
829 }
830
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000831 if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged || stencilSizeChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000832 {
833 if (depthStencilState.stencilTest && stencilSize > 0)
834 {
835 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
836 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
837
838 // FIXME: Unsupported by D3D9
839 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
840 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
841 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
842 if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000843 stencilRef != stencilBackRef ||
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000844 depthStencilState.stencilMask != depthStencilState.stencilBackMask)
845 {
846 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
847 return error(GL_INVALID_OPERATION);
848 }
849
850 // get the maximum size of the stencil ref
851 GLuint maxStencil = (1 << stencilSize) - 1;
852
853 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
854 depthStencilState.stencilWritemask);
855 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
856 gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
857
858 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000859 (stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000860 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
861 depthStencilState.stencilMask);
862
863 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
864 gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
865 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
866 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
867 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
868 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
869
870 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
871 depthStencilState.stencilBackWritemask);
872 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
873 gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
874
875 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000876 (stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000877 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
878 depthStencilState.stencilBackMask);
879
880 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
881 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
882 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
883 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
884 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
885 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
886 }
887 else
888 {
889 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
890 }
891
892 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
893
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000894 mCurStencilRef = stencilRef;
895 mCurStencilBackRef = stencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000896 mCurFrontFaceCCW = frontFaceCCW;
897 mCurStencilSize = stencilSize;
898 }
899
900 mForceSetDepthStencilState = false;
901}
902
daniel@transgaming.com04f1b332012-11-28 21:00:40 +0000903void Renderer9::setScissorRectangle(const gl::Rectangle &scissor)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000904{
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000905 bool scissorChanged = mForceSetScissor || memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0;
906
daniel@transgaming.com04f1b332012-11-28 21:00:40 +0000907 if (scissorChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000908 {
909 RECT rect;
daniel@transgaming.com04f1b332012-11-28 21:00:40 +0000910 rect.left = gl::clamp(scissor.x, 0, static_cast<int>(mRenderTargetDesc.width));
911 rect.top = gl::clamp(scissor.y, 0, static_cast<int>(mRenderTargetDesc.height));
912 rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(mRenderTargetDesc.width));
913 rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(mRenderTargetDesc.height));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000914 mDevice->SetScissorRect(&rect);
915
916 mCurScissor = scissor;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000917 }
918
919 mForceSetScissor = false;
920}
921
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000922bool Renderer9::setViewport(const gl::Rectangle& viewport, float zNear, float zFar,
923 unsigned int renderTargetWidth, unsigned int renderTargetHeight,
924 gl::ProgramBinary *currentProgram, bool forceSetUniforms)
925{
926 bool viewportChanged = mForceSetViewport || memcmp(&viewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
927 zNear != mCurNear || zFar != mCurFar;
928
929 D3DVIEWPORT9 dxViewport;
930 dxViewport.X = gl::clamp(viewport.x, 0, static_cast<int>(renderTargetWidth));
931 dxViewport.Y = gl::clamp(viewport.y, 0, static_cast<int>(renderTargetHeight));
932 dxViewport.Width = gl::clamp(viewport.width, 0, static_cast<int>(renderTargetWidth) - static_cast<int>(dxViewport.X));
933 dxViewport.Height = gl::clamp(viewport.height, 0, static_cast<int>(renderTargetHeight) - static_cast<int>(dxViewport.Y));
934 dxViewport.MinZ = zNear;
935 dxViewport.MaxZ = zFar;
936
937 if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
938 {
939 return false; // Nothing to render
940 }
941
942 if (viewportChanged)
943 {
944 mDevice->SetViewport(&dxViewport);
945
946 mCurViewport = viewport;
947 mCurNear = zNear;
948 mCurFar = zFar;
949 }
950
951 if (currentProgram && (viewportChanged || forceSetUniforms))
952 {
953 GLint halfPixelSize = currentProgram->getDxHalfPixelSizeLocation();
954 GLfloat xy[2] = { 1.0f / dxViewport.Width, -1.0f / dxViewport.Height };
955 currentProgram->setUniform2fv(halfPixelSize, 1, xy);
956
957 // These values are used for computing gl_FragCoord in Program::linkVaryings().
958 GLint coord = currentProgram->getDxCoordLocation();
959 GLfloat whxy[4] = { viewport.width * 0.5f,
960 viewport.height * 0.5f,
961 viewport.x + (viewport.width * 0.5f),
962 viewport.y + (viewport.height * 0.5f) };
963 currentProgram->setUniform4fv(coord, 1, whxy);
964
965 GLint depth = currentProgram->getDxDepthLocation();
966 GLfloat dz[2] = { (zFar - zNear) * 0.5f, (zNear + zFar) * 0.5f };
967 currentProgram->setUniform2fv(depth, 1, dz);
968
969 GLint depthRange = currentProgram->getDxDepthRangeLocation();
970 GLfloat nearFarDiff[3] = { zNear, zFar, zFar - zNear };
971 currentProgram->setUniform3fv(depthRange, 1, nearFarDiff);
972 }
973
974 mForceSetViewport = false;
975 return true;
976}
977
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000978bool Renderer9::applyPrimitiveType(GLenum mode, GLsizei count)
979{
980 switch (mode)
981 {
982 case GL_POINTS:
983 mPrimitiveType = D3DPT_POINTLIST;
984 mPrimitiveCount = count;
985 break;
986 case GL_LINES:
987 mPrimitiveType = D3DPT_LINELIST;
988 mPrimitiveCount = count / 2;
989 break;
990 case GL_LINE_LOOP:
991 mPrimitiveType = D3DPT_LINESTRIP;
992 mPrimitiveCount = count - 1; // D3D doesn't support line loops, so we draw the last line separately
993 break;
994 case GL_LINE_STRIP:
995 mPrimitiveType = D3DPT_LINESTRIP;
996 mPrimitiveCount = count - 1;
997 break;
998 case GL_TRIANGLES:
999 mPrimitiveType = D3DPT_TRIANGLELIST;
1000 mPrimitiveCount = count / 3;
1001 break;
1002 case GL_TRIANGLE_STRIP:
1003 mPrimitiveType = D3DPT_TRIANGLESTRIP;
1004 mPrimitiveCount = count - 2;
1005 break;
1006 case GL_TRIANGLE_FAN:
1007 mPrimitiveType = D3DPT_TRIANGLEFAN;
1008 mPrimitiveCount = count - 2;
1009 break;
1010 default:
1011 return error(GL_INVALID_ENUM, false);
1012 }
1013
1014 return mPrimitiveCount > 0;
1015}
1016
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001017bool Renderer9::applyRenderTarget(gl::Framebuffer *framebuffer)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001018{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001019 // if there is no color attachment we must synthesize a NULL colorattachment
1020 // to keep the D3D runtime happy. This should only be possible if depth texturing.
1021 gl::Renderbuffer *renderbufferObject = NULL;
1022 if (framebuffer->getColorbufferType() != GL_NONE)
1023 {
1024 renderbufferObject = framebuffer->getColorbuffer();
1025 }
1026 else
1027 {
1028 renderbufferObject = framebuffer->getNullColorbuffer();
1029 }
1030 if (!renderbufferObject)
1031 {
1032 ERR("unable to locate renderbuffer for FBO.");
1033 return false;
1034 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001035
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001036 bool renderTargetChanged = false;
1037 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1038 if (renderTargetSerial != mAppliedRenderTargetSerial)
1039 {
1040 // Apply the render target on the device
1041 IDirect3DSurface9 *renderTargetSurface = NULL;
1042
1043 RenderTarget *renderTarget = renderbufferObject->getRenderTarget();
1044 if (renderTarget)
1045 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001046 renderTargetSurface = RenderTarget9::makeRenderTarget9(renderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001047 }
1048
1049 if (!renderTargetSurface)
1050 {
1051 ERR("render target pointer unexpectedly null.");
1052 return false; // Context must be lost
1053 }
1054
1055 mDevice->SetRenderTarget(0, renderTargetSurface);
1056 renderTargetSurface->Release();
1057
1058 mAppliedRenderTargetSerial = renderTargetSerial;
1059 renderTargetChanged = true;
1060 }
1061
1062 gl::Renderbuffer *depthStencil = NULL;
1063 unsigned int depthbufferSerial = 0;
1064 unsigned int stencilbufferSerial = 0;
1065 if (framebuffer->getDepthbufferType() != GL_NONE)
1066 {
1067 depthStencil = framebuffer->getDepthbuffer();
1068 if (!depthStencil)
1069 {
1070 ERR("Depth stencil pointer unexpectedly null.");
1071 return false;
1072 }
1073
1074 depthbufferSerial = depthStencil->getSerial();
1075 }
1076 else if (framebuffer->getStencilbufferType() != GL_NONE)
1077 {
1078 depthStencil = framebuffer->getStencilbuffer();
1079 if (!depthStencil)
1080 {
1081 ERR("Depth stencil pointer unexpectedly null.");
1082 return false;
1083 }
1084
1085 stencilbufferSerial = depthStencil->getSerial();
1086 }
1087
1088 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1089 stencilbufferSerial != mAppliedStencilbufferSerial ||
1090 !mDepthStencilInitialized)
1091 {
1092 // Apply the depth stencil on the device
1093 if (depthStencil)
1094 {
1095 IDirect3DSurface9 *depthStencilSurface = NULL;
1096 RenderTarget *depthStencilRenderTarget = depthStencil->getDepthStencil();
1097
1098 if (depthStencilRenderTarget)
1099 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001100 depthStencilSurface = RenderTarget9::makeRenderTarget9(depthStencilRenderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001101 }
1102
1103 if (!depthStencilSurface)
1104 {
1105 ERR("depth stencil pointer unexpectedly null.");
1106 return false; // Context must be lost
1107 }
1108
1109 mDevice->SetDepthStencilSurface(depthStencilSurface);
1110 depthStencilSurface->Release();
1111 }
1112 else
1113 {
1114 mDevice->SetDepthStencilSurface(NULL);
1115 }
1116
1117 mAppliedDepthbufferSerial = depthbufferSerial;
1118 mAppliedStencilbufferSerial = stencilbufferSerial;
1119 mDepthStencilInitialized = true;
1120 }
1121
1122 if (renderTargetChanged || !mRenderTargetDescInitialized)
1123 {
1124 mForceSetScissor = true;
1125 mForceSetViewport = true;
1126
1127 mRenderTargetDesc.width = renderbufferObject->getWidth();
1128 mRenderTargetDesc.height = renderbufferObject->getHeight();
1129 mRenderTargetDesc.format = renderbufferObject->getActualFormat();
1130 mRenderTargetDescInitialized = true;
1131 }
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001132
1133 return true;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001134}
daniel@transgaming.coma734f272012-10-31 18:07:48 +00001135
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001136GLenum Renderer9::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances)
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001137{
1138 gl::TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
1139 GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
1140 if (err != GL_NO_ERROR)
1141 {
1142 return err;
1143 }
1144
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001145 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, &mRepeatDraw);
1146}
1147
1148// Applies the indices and element array bindings to the Direct3D 9 device
1149GLenum Renderer9::applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, gl::TranslatedIndexData *indexInfo)
1150{
1151 IDirect3DIndexBuffer9 *indexBuffer;
1152 unsigned int serial;
1153 GLenum err = mIndexDataManager->prepareIndexData(type, count, elementArrayBuffer, indices, indexInfo, &indexBuffer, &serial);
1154
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001155 if (err == GL_NO_ERROR)
1156 {
1157 if (serial != mAppliedIBSerial)
1158 {
1159 mDevice->SetIndices(indexBuffer);
1160 mAppliedIBSerial = serial;
1161 }
1162 }
1163
1164 return err;
1165}
1166
1167void Renderer9::drawArrays(GLenum mode, GLsizei count, GLsizei instances)
1168{
1169 startScene();
1170
1171 if (mode == GL_LINE_LOOP)
1172 {
1173 drawLineLoop(count, GL_NONE, NULL, 0, NULL);
1174 }
1175 else if (instances > 0)
1176 {
1177 gl::StaticIndexBuffer *countingIB = mIndexDataManager->getCountingIndices(count);
1178 if (countingIB)
1179 {
1180 if (mAppliedIBSerial != countingIB->getSerial())
1181 {
1182 mDevice->SetIndices(countingIB->getBuffer());
1183 mAppliedIBSerial = countingIB->getSerial();
1184 }
1185
1186 for (int i = 0; i < mRepeatDraw; i++)
1187 {
1188 mDevice->DrawIndexedPrimitive(mPrimitiveType, 0, 0, count, 0, mPrimitiveCount);
1189 }
1190 }
1191 else
1192 {
1193 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
1194 return error(GL_OUT_OF_MEMORY);
1195 }
1196 }
1197 else // Regular case
1198 {
1199 mDevice->DrawPrimitive(mPrimitiveType, 0, mPrimitiveCount);
1200 }
1201}
1202
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001203void 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 +00001204{
1205 startScene();
1206
1207 if (mode == GL_LINE_LOOP)
1208 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001209 drawLineLoop(count, type, indices, indexInfo.minIndex, elementArrayBuffer);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001210 }
1211 else
1212 {
1213 for (int i = 0; i < mRepeatDraw; i++)
1214 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001215 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
1216 mDevice->DrawIndexedPrimitive(mPrimitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, mPrimitiveCount);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001217 }
1218 }
1219}
1220
1221void Renderer9::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer)
1222{
1223 // Get the raw indices for an indexed draw
1224 if (type != GL_NONE && elementArrayBuffer)
1225 {
1226 gl::Buffer *indexBuffer = elementArrayBuffer;
1227 intptr_t offset = reinterpret_cast<intptr_t>(indices);
1228 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
1229 }
1230
1231 UINT startIndex = 0;
1232 bool succeeded = false;
1233
1234 if (get32BitIndexSupport())
1235 {
1236 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
1237
1238 if (!mLineLoopIB)
1239 {
1240 mLineLoopIB = new gl::StreamingIndexBuffer(this, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX32);
1241 }
1242
1243 if (mLineLoopIB)
1244 {
1245 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_INT);
1246
1247 UINT offset = 0;
1248 unsigned int *data = static_cast<unsigned int*>(mLineLoopIB->map(spaceNeeded, &offset));
1249 startIndex = offset / 4;
1250
1251 if (data)
1252 {
1253 switch (type)
1254 {
1255 case GL_NONE: // Non-indexed draw
1256 for (int i = 0; i < count; i++)
1257 {
1258 data[i] = i;
1259 }
1260 data[count] = 0;
1261 break;
1262 case GL_UNSIGNED_BYTE:
1263 for (int i = 0; i < count; i++)
1264 {
1265 data[i] = static_cast<const GLubyte*>(indices)[i];
1266 }
1267 data[count] = static_cast<const GLubyte*>(indices)[0];
1268 break;
1269 case GL_UNSIGNED_SHORT:
1270 for (int i = 0; i < count; i++)
1271 {
1272 data[i] = static_cast<const GLushort*>(indices)[i];
1273 }
1274 data[count] = static_cast<const GLushort*>(indices)[0];
1275 break;
1276 case GL_UNSIGNED_INT:
1277 for (int i = 0; i < count; i++)
1278 {
1279 data[i] = static_cast<const GLuint*>(indices)[i];
1280 }
1281 data[count] = static_cast<const GLuint*>(indices)[0];
1282 break;
1283 default: UNREACHABLE();
1284 }
1285
1286 mLineLoopIB->unmap();
1287 succeeded = true;
1288 }
1289 }
1290 }
1291 else
1292 {
1293 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
1294
1295 if (!mLineLoopIB)
1296 {
1297 mLineLoopIB = new gl::StreamingIndexBuffer(this, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX16);
1298 }
1299
1300 if (mLineLoopIB)
1301 {
1302 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_SHORT);
1303
1304 UINT offset = 0;
1305 unsigned short *data = static_cast<unsigned short*>(mLineLoopIB->map(spaceNeeded, &offset));
1306 startIndex = offset / 2;
1307
1308 if (data)
1309 {
1310 switch (type)
1311 {
1312 case GL_NONE: // Non-indexed draw
1313 for (int i = 0; i < count; i++)
1314 {
1315 data[i] = i;
1316 }
1317 data[count] = 0;
1318 break;
1319 case GL_UNSIGNED_BYTE:
1320 for (int i = 0; i < count; i++)
1321 {
1322 data[i] = static_cast<const GLubyte*>(indices)[i];
1323 }
1324 data[count] = static_cast<const GLubyte*>(indices)[0];
1325 break;
1326 case GL_UNSIGNED_SHORT:
1327 for (int i = 0; i < count; i++)
1328 {
1329 data[i] = static_cast<const GLushort*>(indices)[i];
1330 }
1331 data[count] = static_cast<const GLushort*>(indices)[0];
1332 break;
1333 case GL_UNSIGNED_INT:
1334 for (int i = 0; i < count; i++)
1335 {
1336 data[i] = static_cast<const GLuint*>(indices)[i];
1337 }
1338 data[count] = static_cast<const GLuint*>(indices)[0];
1339 break;
1340 default: UNREACHABLE();
1341 }
1342
1343 mLineLoopIB->unmap();
1344 succeeded = true;
1345 }
1346 }
1347 }
1348
1349 if (succeeded)
1350 {
1351 if (mAppliedIBSerial != mLineLoopIB->getSerial())
1352 {
1353 mDevice->SetIndices(mLineLoopIB->getBuffer());
1354 mAppliedIBSerial = mLineLoopIB->getSerial();
1355 }
1356
1357 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
1358 }
1359 else
1360 {
1361 ERR("Could not create a looping index buffer for GL_LINE_LOOP.");
1362 return error(GL_OUT_OF_MEMORY);
1363 }
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001364}
1365
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001366void Renderer9::applyShaders(gl::ProgramBinary *programBinary)
1367{
daniel@transgaming.com95892412012-11-28 20:59:09 +00001368 ShaderExecutable *vertexExe = programBinary->getVertexExecutable();
1369 ShaderExecutable *pixelExe = programBinary->getPixelExecutable();
1370
1371 IDirect3DVertexShader9 *vertexShader = NULL;
1372 if (vertexExe) vertexShader = ShaderExecutable9::makeShaderExecutable9(vertexExe)->getVertexShader();
1373
1374 IDirect3DPixelShader9 *pixelShader = NULL;
1375 if (pixelExe) pixelShader = ShaderExecutable9::makeShaderExecutable9(pixelExe)->getPixelShader();
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001376
1377 mDevice->SetPixelShader(pixelShader);
1378 mDevice->SetVertexShader(vertexShader);
1379 programBinary->dirtyAllUniforms();
1380}
1381
daniel@transgaming.com084a2572012-11-28 20:55:17 +00001382void Renderer9::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001383{
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001384 D3DCOLOR color = D3DCOLOR_ARGB(gl::unorm<8>(clearParams.colorClearValue.alpha),
1385 gl::unorm<8>(clearParams.colorClearValue.red),
1386 gl::unorm<8>(clearParams.colorClearValue.green),
1387 gl::unorm<8>(clearParams.colorClearValue.blue));
1388 float depth = gl::clamp01(clearParams.depthClearValue);
1389 int stencil = clearParams.stencilClearValue & 0x000000FF;
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001390
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001391 unsigned int stencilUnmasked = 0x0;
1392 if ((clearParams.mask & GL_STENCIL_BUFFER_BIT) && frameBuffer->hasStencil())
1393 {
1394 unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
1395 stencilUnmasked = (0x1 << stencilSize) - 1;
1396 }
1397
1398 bool alphaUnmasked = (gl::GetAlphaSize(mRenderTargetDesc.format) == 0) || clearParams.colorMaskAlpha;
1399
1400 const bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
1401 (clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
1402 const bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
1403 !(clearParams.colorMaskRed && clearParams.colorMaskGreen &&
1404 clearParams.colorMaskBlue && alphaUnmasked);
1405
1406 if (needMaskedColorClear || needMaskedStencilClear)
1407 {
1408 // State which is altered in all paths from this point to the clear call is saved.
1409 // State which is altered in only some paths will be flagged dirty in the case that
1410 // that path is taken.
1411 HRESULT hr;
1412 if (mMaskedClearSavedState == NULL)
1413 {
1414 hr = mDevice->BeginStateBlock();
1415 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1416
1417 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1418 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1419 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1420 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1421 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1422 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1423 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1424 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1425 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1426 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1427 mDevice->SetPixelShader(NULL);
1428 mDevice->SetVertexShader(NULL);
1429 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
1430 mDevice->SetStreamSource(0, NULL, 0, 0);
1431 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1432 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1433 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1434 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1435 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1436 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1437 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1438
1439 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1440 {
1441 mDevice->SetStreamSourceFreq(i, 1);
1442 }
1443
1444 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
1445 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1446 }
1447
1448 ASSERT(mMaskedClearSavedState != NULL);
1449
1450 if (mMaskedClearSavedState != NULL)
1451 {
1452 hr = mMaskedClearSavedState->Capture();
1453 ASSERT(SUCCEEDED(hr));
1454 }
1455
1456 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1457 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1458 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1459 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1460 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1461 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1462 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1463 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1464
1465 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1466 {
1467 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE,
1468 gl_d3d9::ConvertColorMask(clearParams.colorMaskRed,
1469 clearParams.colorMaskGreen,
1470 clearParams.colorMaskBlue,
1471 clearParams.colorMaskAlpha));
1472 }
1473 else
1474 {
1475 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1476 }
1477
1478 if (stencilUnmasked != 0x0 && (clearParams.mask & GL_STENCIL_BUFFER_BIT))
1479 {
1480 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
1481 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
1482 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
1483 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
1484 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
1485 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
1486 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
1487 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
1488 }
1489 else
1490 {
1491 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1492 }
1493
1494 mDevice->SetPixelShader(NULL);
1495 mDevice->SetVertexShader(NULL);
1496 mDevice->SetFVF(D3DFVF_XYZRHW);
1497 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1498 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1499 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1500 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1501 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1502 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1503 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1504
1505 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1506 {
1507 mDevice->SetStreamSourceFreq(i, 1);
1508 }
1509
1510 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
1511 quad[0][0] = -0.5f;
1512 quad[0][1] = mRenderTargetDesc.height - 0.5f;
1513 quad[0][2] = 0.0f;
1514 quad[0][3] = 1.0f;
1515
1516 quad[1][0] = mRenderTargetDesc.width - 0.5f;
1517 quad[1][1] = mRenderTargetDesc.height - 0.5f;
1518 quad[1][2] = 0.0f;
1519 quad[1][3] = 1.0f;
1520
1521 quad[2][0] = -0.5f;
1522 quad[2][1] = -0.5f;
1523 quad[2][2] = 0.0f;
1524 quad[2][3] = 1.0f;
1525
1526 quad[3][0] = mRenderTargetDesc.width - 0.5f;
1527 quad[3][1] = -0.5f;
1528 quad[3][2] = 0.0f;
1529 quad[3][3] = 1.0f;
1530
1531 startScene();
1532 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
1533
1534 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1535 {
1536 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
1537 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
1538 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
1539 }
1540
1541 if (mMaskedClearSavedState != NULL)
1542 {
1543 mMaskedClearSavedState->Apply();
1544 }
1545 }
1546 else if (clearParams.mask)
1547 {
1548 DWORD dxClearFlags = 0;
1549 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1550 {
1551 dxClearFlags |= D3DCLEAR_TARGET;
1552 }
1553 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1554 {
1555 dxClearFlags |= D3DCLEAR_ZBUFFER;
1556 }
1557 if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
1558 {
1559 dxClearFlags |= D3DCLEAR_STENCIL;
1560 }
1561
1562 mDevice->Clear(0, NULL, dxClearFlags, color, depth, stencil);
1563 }
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001564}
1565
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001566void Renderer9::markAllStateDirty()
1567{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001568 mAppliedRenderTargetSerial = 0;
1569 mAppliedDepthbufferSerial = 0;
1570 mAppliedStencilbufferSerial = 0;
1571 mDepthStencilInitialized = false;
1572 mRenderTargetDescInitialized = false;
1573
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001574 mForceSetDepthStencilState = true;
1575 mForceSetRasterState = true;
1576 mForceSetBlendState = true;
1577 mForceSetScissor = true;
1578 mForceSetViewport = true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001579
1580 mVertexDeclarationCache.markStateDirty();
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001581}
1582
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001583void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001584{
1585 while (!mEventQueryPool.empty())
1586 {
1587 mEventQueryPool.back()->Release();
1588 mEventQueryPool.pop_back();
1589 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001590
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001591 if (mMaskedClearSavedState)
1592 {
1593 mMaskedClearSavedState->Release();
1594 mMaskedClearSavedState = NULL;
1595 }
1596
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001597 mVertexShaderCache.clear();
1598 mPixelShaderCache.clear();
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001599
daniel@transgaming.come569fc52012-11-28 20:56:02 +00001600 delete mBlit;
1601 mBlit = NULL;
1602
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001603 delete mVertexDataManager;
1604 mVertexDataManager = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001605
1606 delete mIndexDataManager;
1607 mIndexDataManager = NULL;
1608
1609 delete mLineLoopIB;
1610 mLineLoopIB = NULL;
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001611}
1612
1613
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001614void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001615{
1616 mDeviceLost = true;
1617}
1618
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001619bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001620{
1621 return mDeviceLost;
1622}
1623
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001624// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001625bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001626{
1627 bool isLost = false;
1628
1629 if (mDeviceEx)
1630 {
1631 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
1632 }
1633 else if (mDevice)
1634 {
1635 isLost = FAILED(mDevice->TestCooperativeLevel());
1636 }
1637 else
1638 {
1639 // No device yet, so no reset required
1640 }
1641
1642 if (isLost)
1643 {
1644 // ensure we note the device loss --
1645 // we'll probably get this done again by markDeviceLost
1646 // but best to remember it!
1647 // Note that we don't want to clear the device loss status here
1648 // -- this needs to be done by resetDevice
1649 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001650 if (notify)
1651 {
1652 mDisplay->notifyDeviceLost();
1653 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001654 }
1655
1656 return isLost;
1657}
1658
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001659bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001660{
1661 HRESULT status = D3D_OK;
1662
1663 if (mDeviceEx)
1664 {
1665 status = mDeviceEx->CheckDeviceState(NULL);
1666 }
1667 else if (mDevice)
1668 {
1669 status = mDevice->TestCooperativeLevel();
1670 }
1671
1672 switch (status)
1673 {
1674 case D3DERR_DEVICENOTRESET:
1675 case D3DERR_DEVICEHUNG:
1676 return true;
1677 default:
1678 return false;
1679 }
1680}
1681
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001682bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001683{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001684 releaseDeviceResources();
1685
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001686 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
1687
1688 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001689 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001690 int attempts = 3;
1691
1692 while (lost && attempts > 0)
1693 {
1694 if (mDeviceEx)
1695 {
1696 Sleep(500); // Give the graphics driver some CPU time
1697 result = mDeviceEx->ResetEx(&presentParameters, NULL);
1698 }
1699 else
1700 {
1701 result = mDevice->TestCooperativeLevel();
1702 while (result == D3DERR_DEVICELOST)
1703 {
1704 Sleep(100); // Give the graphics driver some CPU time
1705 result = mDevice->TestCooperativeLevel();
1706 }
1707
1708 if (result == D3DERR_DEVICENOTRESET)
1709 {
1710 result = mDevice->Reset(&presentParameters);
1711 }
1712 }
1713
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001714 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001715 attempts --;
1716 }
1717
1718 if (FAILED(result))
1719 {
1720 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
1721 return false;
1722 }
1723
1724 // reset device defaults
1725 initializeDevice();
1726 mDeviceLost = false;
1727
1728 return true;
1729}
1730
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001731DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001732{
1733 return mAdapterIdentifier.VendorId;
1734}
1735
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001736const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001737{
1738 return mAdapterIdentifier.Description;
1739}
1740
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001741GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001742{
1743 return mAdapterIdentifier.DeviceIdentifier;
1744}
1745
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001746void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001747{
1748 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
1749 {
1750 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
1751 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
1752
1753 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
1754 }
1755}
1756
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001757bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001758{
1759 D3DDISPLAYMODE currentDisplayMode;
1760 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1761
1762 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
1763}
1764
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001765bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001766{
1767 D3DDISPLAYMODE currentDisplayMode;
1768 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1769
1770 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
1771}
1772
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001773bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001774{
1775 D3DDISPLAYMODE currentDisplayMode;
1776 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1777
1778 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
1779}
1780
1781// we use INTZ for depth textures in Direct3D9
1782// we also want NULL texture support to ensure the we can make depth-only FBOs
1783// see http://aras-p.info/texts/D3D9GPUHacks.html
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001784bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001785{
1786 D3DDISPLAYMODE currentDisplayMode;
1787 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1788
1789 bool intz = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1790 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ));
1791 bool null = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1792 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
1793
1794 return intz && null;
1795}
1796
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001797bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001798{
1799 D3DDISPLAYMODE currentDisplayMode;
1800 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1801
1802 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1803 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1804 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1805 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1806
1807 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1808 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F))&&
1809 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1810 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1811
1812 if (!*filtering && !*renderable)
1813 {
1814 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1815 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1816 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1817 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1818 }
1819 else
1820 {
1821 return true;
1822 }
1823}
1824
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001825bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001826{
1827 D3DDISPLAYMODE currentDisplayMode;
1828 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1829
1830 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1831 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1832 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1833 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1834
1835 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1836 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1837 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1838 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1839
1840 if (!*filtering && !*renderable)
1841 {
1842 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1843 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1844 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1845 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1846 }
1847 else
1848 {
1849 return true;
1850 }
1851}
1852
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001853bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001854{
1855 D3DDISPLAYMODE currentDisplayMode;
1856 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1857
1858 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
1859}
1860
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001861bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001862{
1863 D3DDISPLAYMODE currentDisplayMode;
1864 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1865
1866 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
1867}
1868
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001869bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001870{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001871 return mSupportsTextureFilterAnisotropy;
1872}
1873
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001874float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001875{
1876 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001877 {
1878 return mDeviceCaps.MaxAnisotropy;
1879 }
1880 return 1.0f;
1881}
1882
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001883bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001884{
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001885 IDirect3DQuery9 *query = allocateEventQuery();
1886 if (query)
1887 {
1888 freeEventQuery(query);
1889 return true;
1890 }
1891 else
1892 {
1893 return false;
1894 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001895 return true;
1896}
1897
1898// Only Direct3D 10 ready devices support all the necessary vertex texture formats.
1899// We test this using D3D9 by checking support for the R16F format.
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001900bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001901{
1902 if (!mDevice || mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(3, 0))
1903 {
1904 return false;
1905 }
1906
1907 D3DDISPLAYMODE currentDisplayMode;
1908 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1909
1910 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F);
1911
1912 return SUCCEEDED(result);
1913}
1914
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001915bool Renderer9::getNonPower2TextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001916{
1917 return mSupportsNonPower2Textures;
1918}
1919
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001920bool Renderer9::getOcclusionQuerySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001921{
1922 if (!mDevice)
1923 {
1924 return false;
1925 }
1926
1927 IDirect3DQuery9 *query = NULL;
1928 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query);
1929 if (SUCCEEDED(result) && query)
1930 {
1931 query->Release();
1932 return true;
1933 }
1934 else
1935 {
1936 return false;
1937 }
1938}
1939
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001940bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001941{
1942 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
1943}
1944
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001945bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001946{
1947 // PIX doesn't seem to support using share handles, so disable them.
1948 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00001949 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001950}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001951
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00001952int Renderer9::getMajorShaderModel() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001953{
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00001954 return D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion);
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001955}
1956
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001957float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001958{
1959 return mDeviceCaps.MaxPointSize;
1960}
1961
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001962int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001963{
1964 return (int)mDeviceCaps.MaxTextureWidth;
1965}
1966
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001967int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001968{
1969 return (int)mDeviceCaps.MaxTextureHeight;
1970}
1971
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001972bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001973{
1974 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
1975}
1976
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001977DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001978{
1979 return mDeviceCaps.DeclTypes;
1980}
1981
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001982int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001983{
1984 return mMinSwapInterval;
1985}
1986
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001987int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001988{
1989 return mMaxSwapInterval;
1990}
1991
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001992int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001993{
1994 return mMaxSupportedSamples;
1995}
1996
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001997int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001998{
1999 if (requested == 0)
2000 {
2001 return requested;
2002 }
2003
2004 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
2005 if (itr == mMultiSampleSupport.end())
2006 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00002007 if (format == D3DFMT_UNKNOWN)
2008 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002009 return -1;
2010 }
2011
2012 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
2013 {
2014 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
2015 {
2016 return i;
2017 }
2018 }
2019
2020 return -1;
2021}
2022
daniel@transgaming.coma9571682012-11-28 19:33:08 +00002023D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
2024{
2025 switch (internalformat)
2026 {
2027 case GL_DEPTH_COMPONENT16:
2028 case GL_DEPTH_COMPONENT32_OES:
2029 case GL_DEPTH24_STENCIL8_OES:
2030 return D3DFMT_INTZ;
2031 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
2032 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
2033 return D3DFMT_DXT1;
2034 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
2035 return D3DFMT_DXT3;
2036 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
2037 return D3DFMT_DXT5;
2038 case GL_RGBA32F_EXT:
2039 case GL_RGB32F_EXT:
2040 case GL_ALPHA32F_EXT:
2041 case GL_LUMINANCE32F_EXT:
2042 case GL_LUMINANCE_ALPHA32F_EXT:
2043 return D3DFMT_A32B32G32R32F;
2044 case GL_RGBA16F_EXT:
2045 case GL_RGB16F_EXT:
2046 case GL_ALPHA16F_EXT:
2047 case GL_LUMINANCE16F_EXT:
2048 case GL_LUMINANCE_ALPHA16F_EXT:
2049 return D3DFMT_A16B16G16R16F;
2050 case GL_LUMINANCE8_EXT:
2051 if (getLuminanceTextureSupport())
2052 {
2053 return D3DFMT_L8;
2054 }
2055 break;
2056 case GL_LUMINANCE8_ALPHA8_EXT:
2057 if (getLuminanceAlphaTextureSupport())
2058 {
2059 return D3DFMT_A8L8;
2060 }
2061 break;
2062 case GL_RGB8_OES:
2063 case GL_RGB565:
2064 return D3DFMT_X8R8G8B8;
2065 }
2066
2067 return D3DFMT_A8R8G8B8;
2068}
2069
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002070bool Renderer9::copyToRenderTarget(TextureStorage2D *dest, TextureStorage2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002071{
2072 bool result = false;
2073
2074 if (source && dest)
2075 {
2076 int levels = source->levelCount();
2077 for (int i = 0; i < levels; ++i)
2078 {
2079 IDirect3DSurface9 *srcSurf = source->getSurfaceLevel(i, false);
2080 IDirect3DSurface9 *dstSurf = dest->getSurfaceLevel(i, false);
2081
2082 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2083
2084 if (srcSurf) srcSurf->Release();
2085 if (dstSurf) dstSurf->Release();
2086
2087 if (!result)
2088 return false;
2089 }
2090 }
2091
2092 return result;
2093}
2094
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002095bool Renderer9::copyToRenderTarget(TextureStorageCubeMap *dest, TextureStorageCubeMap *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002096{
2097 bool result = false;
2098
2099 if (source && dest)
2100 {
2101 int levels = source->levelCount();
2102 for (int f = 0; f < 6; f++)
2103 {
2104 for (int i = 0; i < levels; i++)
2105 {
2106 IDirect3DSurface9 *srcSurf = source->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
2107 IDirect3DSurface9 *dstSurf = dest->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
2108
2109 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2110
2111 if (srcSurf) srcSurf->Release();
2112 if (dstSurf) dstSurf->Release();
2113
2114 if (!result)
2115 return false;
2116 }
2117 }
2118 }
2119
2120 return result;
2121}
2122
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002123D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002124{
2125 if (mD3d9Ex != NULL)
2126 {
2127 return D3DPOOL_DEFAULT;
2128 }
2129 else
2130 {
2131 if (!(usage & D3DUSAGE_DYNAMIC))
2132 {
2133 return D3DPOOL_MANAGED;
2134 }
2135 }
2136
2137 return D3DPOOL_DEFAULT;
2138}
2139
daniel@transgaming.com38380882012-11-28 19:36:39 +00002140bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2141 GLint xoffset, GLint yoffset, TextureStorage2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002142{
2143 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
2144}
2145
daniel@transgaming.com38380882012-11-28 19:36:39 +00002146bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2147 GLint xoffset, GLint yoffset, TextureStorageCubeMap *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002148{
2149 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
2150}
2151
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002152bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
2153 bool blitRenderTarget, bool blitDepthStencil)
2154{
2155 endScene();
2156
2157 if (blitRenderTarget)
2158 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002159 gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer();
2160 gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer();
2161 RenderTarget9 *readRenderTarget = NULL;
2162 RenderTarget9 *drawRenderTarget = NULL;
2163 IDirect3DSurface9* readSurface = NULL;
2164 IDirect3DSurface9* drawSurface = NULL;
2165
2166 if (readBuffer)
2167 {
2168 readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
2169 }
2170 if (drawBuffer)
2171 {
2172 drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
2173 }
2174
2175 if (readRenderTarget)
2176 {
2177 readSurface = readRenderTarget->getSurface();
2178 }
2179 if (drawRenderTarget)
2180 {
2181 drawSurface = drawRenderTarget->getSurface();
2182 }
2183
2184 if (!readSurface || !drawSurface)
2185 {
2186 ERR("Failed to retrieve the render target.");
2187 return error(GL_OUT_OF_MEMORY, false);
2188 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002189
2190 RECT srcRect, dstRect;
2191 RECT *srcRectPtr = NULL;
2192 RECT *dstRectPtr = NULL;
2193
2194 if (readRect)
2195 {
2196 srcRect.left = readRect->x;
2197 srcRect.right = readRect->x + readRect->width;
2198 srcRect.top = readRect->y;
2199 srcRect.bottom = readRect->y + readRect->height;
2200 srcRectPtr = &srcRect;
2201 }
2202
2203 if (drawRect)
2204 {
2205 dstRect.left = drawRect->x;
2206 dstRect.right = drawRect->x + drawRect->width;
2207 dstRect.top = drawRect->y;
2208 dstRect.bottom = drawRect->y + drawRect->height;
2209 dstRectPtr = &dstRect;
2210 }
2211
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002212 HRESULT result = mDevice->StretchRect(readSurface, srcRectPtr, drawSurface, dstRectPtr, D3DTEXF_NONE);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002213
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002214 readSurface->Release();
2215 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002216
2217 if (FAILED(result))
2218 {
2219 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2220 return false;
2221 }
2222 }
2223
2224 if (blitDepthStencil)
2225 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002226 gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
2227 gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
2228 RenderTarget9 *readDepthStencil = NULL;
2229 RenderTarget9 *drawDepthStencil = NULL;
2230 IDirect3DSurface9* readSurface = NULL;
2231 IDirect3DSurface9* drawSurface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002232
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002233 if (readBuffer)
2234 {
2235 readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
2236 }
2237 if (drawBuffer)
2238 {
2239 drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
2240 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002241
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002242 if (readDepthStencil)
2243 {
2244 readSurface = readDepthStencil->getSurface();
2245 }
2246 if (drawDepthStencil)
2247 {
2248 drawSurface = drawDepthStencil->getSurface();
2249 }
2250
2251 if (!readSurface || !drawSurface)
2252 {
2253 ERR("Failed to retrieve the render target.");
2254 return error(GL_OUT_OF_MEMORY, false);
2255 }
2256
2257 HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
2258
2259 readSurface->Release();
2260 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002261
2262 if (FAILED(result))
2263 {
2264 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2265 return false;
2266 }
2267 }
2268
2269 return true;
2270}
2271
2272void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
2273 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
2274{
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002275 RenderTarget9 *renderTarget = NULL;
2276 IDirect3DSurface9 *surface = NULL;
2277 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
2278
2279 if (colorbuffer)
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002280 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002281 renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
2282 }
2283
2284 if (renderTarget)
2285 {
2286 surface = renderTarget->getSurface();
2287 }
2288
2289 if (!surface)
2290 {
2291 // context must be lost
2292 return;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002293 }
2294
2295 D3DSURFACE_DESC desc;
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002296 surface->GetDesc(&desc);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002297
2298 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2299 {
2300 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002301 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002302 return error(GL_OUT_OF_MEMORY);
2303 }
2304
2305 HRESULT result;
2306 IDirect3DSurface9 *systemSurface = NULL;
2307 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
2308 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2309 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2310 if (directToPixels)
2311 {
2312 // Use the pixels ptr as a shared handle to write directly into client's memory
2313 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2314 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2315 if (FAILED(result))
2316 {
2317 // Try again without the shared handle
2318 directToPixels = false;
2319 }
2320 }
2321
2322 if (!directToPixels)
2323 {
2324 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2325 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2326 if (FAILED(result))
2327 {
2328 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002329 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002330 return error(GL_OUT_OF_MEMORY);
2331 }
2332 }
2333
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002334 result = mDevice->GetRenderTargetData(surface, systemSurface);
2335 surface->Release();
2336 surface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002337
2338 if (FAILED(result))
2339 {
2340 systemSurface->Release();
2341
2342 // It turns out that D3D will sometimes produce more error
2343 // codes than those documented.
daniel@transgaming.com414c9162012-11-28 20:54:57 +00002344 if (checkDeviceLost(result))
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002345 return error(GL_OUT_OF_MEMORY);
2346 else
2347 {
2348 UNREACHABLE();
2349 return;
2350 }
2351
2352 }
2353
2354 if (directToPixels)
2355 {
2356 systemSurface->Release();
2357 return;
2358 }
2359
2360 RECT rect;
2361 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
2362 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
2363 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2364 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2365
2366 D3DLOCKED_RECT lock;
2367 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2368
2369 if (FAILED(result))
2370 {
2371 UNREACHABLE();
2372 systemSurface->Release();
2373
2374 return; // No sensible error to generate
2375 }
2376
2377 unsigned char *dest = (unsigned char*)pixels;
2378 unsigned short *dest16 = (unsigned short*)pixels;
2379
2380 unsigned char *source;
2381 int inputPitch;
2382 if (packReverseRowOrder)
2383 {
2384 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2385 inputPitch = -lock.Pitch;
2386 }
2387 else
2388 {
2389 source = (unsigned char*)lock.pBits;
2390 inputPitch = lock.Pitch;
2391 }
2392
2393 unsigned int fastPixelSize = 0;
2394
2395 if (desc.Format == D3DFMT_A8R8G8B8 &&
2396 format == GL_BGRA_EXT &&
2397 type == GL_UNSIGNED_BYTE)
2398 {
2399 fastPixelSize = 4;
2400 }
2401 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2402 format == GL_BGRA_EXT &&
2403 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2404 (desc.Format == D3DFMT_A1R5G5B5 &&
2405 format == GL_BGRA_EXT &&
2406 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2407 {
2408 fastPixelSize = 2;
2409 }
2410 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2411 format == GL_RGBA &&
2412 type == GL_HALF_FLOAT_OES)
2413 {
2414 fastPixelSize = 8;
2415 }
2416 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2417 format == GL_RGBA &&
2418 type == GL_FLOAT)
2419 {
2420 fastPixelSize = 16;
2421 }
2422
2423 for (int j = 0; j < rect.bottom - rect.top; j++)
2424 {
2425 if (fastPixelSize != 0)
2426 {
2427 // Fast path for formats which require no translation:
2428 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2429 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2430 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2431 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2432 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2433 //
2434 // Note that buffers with no alpha go through the slow path below.
2435 memcpy(dest + j * outputPitch,
2436 source + j * inputPitch,
2437 (rect.right - rect.left) * fastPixelSize);
2438 continue;
2439 }
2440
2441 for (int i = 0; i < rect.right - rect.left; i++)
2442 {
2443 float r;
2444 float g;
2445 float b;
2446 float a;
2447
2448 switch (desc.Format)
2449 {
2450 case D3DFMT_R5G6B5:
2451 {
2452 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2453
2454 a = 1.0f;
2455 b = (rgb & 0x001F) * (1.0f / 0x001F);
2456 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2457 r = (rgb & 0xF800) * (1.0f / 0xF800);
2458 }
2459 break;
2460 case D3DFMT_A1R5G5B5:
2461 {
2462 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2463
2464 a = (argb & 0x8000) ? 1.0f : 0.0f;
2465 b = (argb & 0x001F) * (1.0f / 0x001F);
2466 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2467 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2468 }
2469 break;
2470 case D3DFMT_A8R8G8B8:
2471 {
2472 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2473
2474 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2475 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2476 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2477 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2478 }
2479 break;
2480 case D3DFMT_X8R8G8B8:
2481 {
2482 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2483
2484 a = 1.0f;
2485 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2486 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2487 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2488 }
2489 break;
2490 case D3DFMT_A2R10G10B10:
2491 {
2492 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2493
2494 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2495 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2496 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2497 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2498 }
2499 break;
2500 case D3DFMT_A32B32G32R32F:
2501 {
2502 // float formats in D3D are stored rgba, rather than the other way round
2503 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2504 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2505 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2506 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2507 }
2508 break;
2509 case D3DFMT_A16B16G16R16F:
2510 {
2511 // float formats in D3D are stored rgba, rather than the other way round
2512 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2513 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2514 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2515 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
2516 }
2517 break;
2518 default:
2519 UNIMPLEMENTED(); // FIXME
2520 UNREACHABLE();
2521 return;
2522 }
2523
2524 switch (format)
2525 {
2526 case GL_RGBA:
2527 switch (type)
2528 {
2529 case GL_UNSIGNED_BYTE:
2530 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2531 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2532 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2533 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2534 break;
2535 default: UNREACHABLE();
2536 }
2537 break;
2538 case GL_BGRA_EXT:
2539 switch (type)
2540 {
2541 case GL_UNSIGNED_BYTE:
2542 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2543 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2544 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2545 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2546 break;
2547 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2548 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2549 // this type is packed as follows:
2550 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2551 // --------------------------------------------------------------------------------
2552 // | 4th | 3rd | 2nd | 1st component |
2553 // --------------------------------------------------------------------------------
2554 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2555 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2556 ((unsigned short)(15 * a + 0.5f) << 12)|
2557 ((unsigned short)(15 * r + 0.5f) << 8) |
2558 ((unsigned short)(15 * g + 0.5f) << 4) |
2559 ((unsigned short)(15 * b + 0.5f) << 0);
2560 break;
2561 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2562 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2563 // this type is packed as follows:
2564 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2565 // --------------------------------------------------------------------------------
2566 // | 4th | 3rd | 2nd | 1st component |
2567 // --------------------------------------------------------------------------------
2568 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2569 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2570 ((unsigned short)( a + 0.5f) << 15) |
2571 ((unsigned short)(31 * r + 0.5f) << 10) |
2572 ((unsigned short)(31 * g + 0.5f) << 5) |
2573 ((unsigned short)(31 * b + 0.5f) << 0);
2574 break;
2575 default: UNREACHABLE();
2576 }
2577 break;
2578 case GL_RGB:
2579 switch (type)
2580 {
2581 case GL_UNSIGNED_SHORT_5_6_5:
2582 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2583 ((unsigned short)(31 * b + 0.5f) << 0) |
2584 ((unsigned short)(63 * g + 0.5f) << 5) |
2585 ((unsigned short)(31 * r + 0.5f) << 11);
2586 break;
2587 case GL_UNSIGNED_BYTE:
2588 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2589 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2590 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2591 break;
2592 default: UNREACHABLE();
2593 }
2594 break;
2595 default: UNREACHABLE();
2596 }
2597 }
2598 }
2599
2600 systemSurface->UnlockRect();
2601
2602 systemSurface->Release();
2603}
2604
daniel@transgaming.comf2423652012-11-28 20:53:50 +00002605RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
2606{
2607 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2608 IDirect3DSurface9 *surface = NULL;
2609 if (depth)
2610 {
2611 surface = swapChain9->getDepthStencil();
2612 }
2613 else
2614 {
2615 surface = swapChain9->getRenderTarget();
2616 }
2617
2618 RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
2619
2620 return renderTarget;
2621}
2622
2623RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
2624{
2625 RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
2626 return renderTarget;
2627}
2628
daniel@transgaming.com55318902012-11-28 20:58:58 +00002629ShaderExecutable *Renderer9::loadExecutable(const DWORD *function, size_t length, GLenum type, void *data)
2630{
2631 ShaderExecutable9 *executable = NULL;
2632 gl::D3DConstantTable *table = reinterpret_cast<gl::D3DConstantTable *>(data);
2633
2634 switch (type)
2635 {
2636 case GL_VERTEX_SHADER:
2637 {
2638 IDirect3DVertexShader9 *vshader = createVertexShader(function, length);
2639 if (vshader)
2640 {
2641 executable = new ShaderExecutable9(vshader, table);
2642 }
2643 }
2644 break;
2645 case GL_FRAGMENT_SHADER:
2646 {
2647 IDirect3DPixelShader9 *pshader = createPixelShader(function, length);
2648 if (pshader)
2649 {
2650 executable = new ShaderExecutable9(pshader, table);
2651 }
2652 }
2653 break;
2654 default:
2655 UNREACHABLE();
2656 break;
2657 }
2658
2659 return executable;
2660}
2661
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002662ShaderExecutable *Renderer9::compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, GLenum type)
2663{
2664 const char *profile = NULL;
2665
2666 switch (type)
2667 {
2668 case GL_VERTEX_SHADER:
2669 profile = getMajorShaderModel() >= 3 ? "vs_3_0" : "vs_2_0";
2670 break;
2671 case GL_FRAGMENT_SHADER:
2672 profile = getMajorShaderModel() >= 3 ? "ps_3_0" : "ps_2_0";
2673 break;
2674 default:
2675 UNREACHABLE();
2676 return NULL;
2677 }
2678
2679 gl::D3DConstantTable *constantTable = NULL;
2680 ID3D10Blob *binary = compileToBinary(infoLog, shaderHLSL, profile, &constantTable);
2681 if (!binary)
2682 return NULL;
2683
daniel@transgaming.com55318902012-11-28 20:58:58 +00002684 ShaderExecutable *executable = loadExecutable((DWORD *)binary->GetBufferPointer(), binary->GetBufferSize(), type, constantTable);
daniel@transgaming.com536dd6e2012-11-28 21:00:18 +00002685 binary->Release();
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002686
2687 return executable;
2688}
2689
2690// Compiles the HLSL code of the attached shaders into executable binaries
2691ID3D10Blob *Renderer9::compileToBinary(gl::InfoLog &infoLog, const char *hlsl, const char *profile, gl::D3DConstantTable **constantTable)
2692{
2693 if (!hlsl)
2694 {
2695 return NULL;
2696 }
2697
2698 HRESULT result = S_OK;
2699 UINT flags = 0;
2700 std::string sourceText;
2701 if (gl::perfActive())
2702 {
2703 flags |= D3DCOMPILE_DEBUG;
2704#ifdef NDEBUG
2705 flags |= ANGLE_COMPILE_OPTIMIZATION_LEVEL;
2706#else
2707 flags |= D3DCOMPILE_SKIP_OPTIMIZATION;
2708#endif
2709
2710 std::string sourcePath = getTempPath();
2711 sourceText = std::string("#line 2 \"") + sourcePath + std::string("\"\n\n") + std::string(hlsl);
2712 writeFile(sourcePath.c_str(), sourceText.c_str(), sourceText.size());
2713 }
2714 else
2715 {
2716 flags |= ANGLE_COMPILE_OPTIMIZATION_LEVEL;
2717 sourceText = hlsl;
2718 }
2719
2720 // Sometimes D3DCompile will fail with the default compilation flags for complicated shaders when it would otherwise pass with alternative options.
2721 // Try the default flags first and if compilation fails, try some alternatives.
2722 const static UINT extraFlags[] =
2723 {
2724 0,
2725 D3DCOMPILE_AVOID_FLOW_CONTROL,
2726 D3DCOMPILE_PREFER_FLOW_CONTROL
2727 };
2728
2729 const static char * const extraFlagNames[] =
2730 {
2731 "default",
2732 "avoid flow control",
2733 "prefer flow control"
2734 };
2735
2736 for (int i = 0; i < sizeof(extraFlags) / sizeof(UINT); ++i)
2737 {
2738 ID3D10Blob *errorMessage = NULL;
2739 ID3D10Blob *binary = NULL;
daniel@transgaming.comf0516cf2012-11-28 20:59:18 +00002740 result = mD3DCompileFunc(hlsl, strlen(hlsl), gl::g_fakepath, NULL, NULL,
2741 "main", profile, flags | extraFlags[i], 0, &binary, &errorMessage);
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002742 if (errorMessage)
2743 {
2744 const char *message = (const char*)errorMessage->GetBufferPointer();
2745
2746 infoLog.appendSanitized(message);
2747 TRACE("\n%s", hlsl);
2748 TRACE("\n%s", message);
2749
2750 errorMessage->Release();
2751 errorMessage = NULL;
2752 }
2753
2754 if (SUCCEEDED(result))
2755 {
2756 gl::D3DConstantTable *table = new gl::D3DConstantTable(binary->GetBufferPointer(), binary->GetBufferSize());
2757 if (table->error())
2758 {
2759 delete table;
2760 binary->Release();
2761 return NULL;
2762 }
2763
2764 *constantTable = table;
2765 return binary;
2766 }
2767 else
2768 {
2769 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY)
2770 {
2771 return error(GL_OUT_OF_MEMORY, (ID3D10Blob*) NULL);
2772 }
2773
2774 infoLog.append("Warning: D3D shader compilation failed with ");
2775 infoLog.append(extraFlagNames[i]);
2776 infoLog.append(" flags.");
2777 if (i + 1 < sizeof(extraFlagNames) / sizeof(char*))
2778 {
2779 infoLog.append(" Retrying with ");
2780 infoLog.append(extraFlagNames[i + 1]);
2781 infoLog.append(".\n");
2782 }
2783 }
2784 }
2785
2786 return NULL;
2787}
2788
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002789bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
2790{
2791 return mBlit->boxFilter(source, dest);
2792}
2793
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002794D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002795{
2796 if (mD3d9Ex != NULL)
2797 {
2798 return D3DPOOL_DEFAULT;
2799 }
2800 else
2801 {
2802 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2803 {
2804 return D3DPOOL_MANAGED;
2805 }
2806 }
2807
2808 return D3DPOOL_DEFAULT;
2809}
2810
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002811bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
2812{
2813 if (source && dest)
2814 {
2815 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
2816 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
2817
2818 if (fromManaged)
2819 {
2820 D3DSURFACE_DESC desc;
2821 source->GetDesc(&desc);
2822
2823 IDirect3DSurface9 *surf = 0;
2824 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
2825
2826 if (SUCCEEDED(result))
2827 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002828 Image::CopyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002829 result = device->UpdateSurface(surf, NULL, dest, NULL);
2830 surf->Release();
2831 }
2832 }
2833 else
2834 {
2835 endScene();
2836 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
2837 }
2838
2839 if (FAILED(result))
2840 {
2841 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2842 return false;
2843 }
2844 }
2845
2846 return true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00002847}
2848
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002849}