blob: 62927015b76a07c480039ce7e90ca50d1af61bb5 [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"
13#include "libGLESv2/Framebuffer.h"
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +000014#include "libGLESv2/Program.h"
15#include "libGLESv2/ProgramBinary.h"
daniel@transgaming.com67094ee2012-11-28 20:53:04 +000016#include "libGLESv2/VertexDataManager.h"
daniel@transgaming.com2507f412012-10-31 18:46:48 +000017#include "libGLESv2/renderer/Renderer9.h"
daniel@transgaming.comd8e36562012-10-31 19:52:19 +000018#include "libGLESv2/renderer/renderer9_utils.h"
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +000019#include "libGLESv2/renderer/SwapChain9.h"
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +000020#include "libGLESv2/renderer/TextureStorage.h"
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +000021#include "libGLESv2/renderer/Image.h"
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000022#include "libGLESv2/renderer/Blit.h"
daniel@transgaming.comd186dc72012-11-28 19:40:16 +000023#include "libGLESv2/renderer/RenderTarget9.h"
daniel@transgaming.com621ce052012-10-31 17:52:29 +000024
daniel@transgaming.com3281f972012-10-31 18:38:51 +000025#include "libEGL/Config.h"
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000026#include "libEGL/Display.h"
27
daniel@transgaming.com621ce052012-10-31 17:52:29 +000028// Can also be enabled by defining FORCE_REF_RAST in the project's predefined macros
29#define REF_RAST 0
30
31// The "Debug This Pixel..." feature in PIX often fails when using the
32// D3D9Ex interfaces. In order to get debug pixel to work on a Vista/Win 7
33// machine, define "ANGLE_ENABLE_D3D9EX=0" in your project file.
34#if !defined(ANGLE_ENABLE_D3D9EX)
35// Enables use of the IDirect3D9Ex interface, when available
36#define ANGLE_ENABLE_D3D9EX 1
37#endif // !defined(ANGLE_ENABLE_D3D9EX)
38
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +000039namespace rx
daniel@transgaming.com621ce052012-10-31 17:52:29 +000040{
daniel@transgaming.com222ee082012-11-28 19:31:49 +000041static const D3DFORMAT RenderTargetFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000042 {
43 D3DFMT_A1R5G5B5,
44 // D3DFMT_A2R10G10B10, // The color_ramp conformance test uses ReadPixels with UNSIGNED_BYTE causing it to think that rendering skipped a colour value.
45 D3DFMT_A8R8G8B8,
46 D3DFMT_R5G6B5,
47 // D3DFMT_X1R5G5B5, // Has no compatible OpenGL ES renderbuffer format
48 D3DFMT_X8R8G8B8
49 };
50
daniel@transgaming.com222ee082012-11-28 19:31:49 +000051static const D3DFORMAT DepthStencilFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000052 {
53 D3DFMT_UNKNOWN,
54 // D3DFMT_D16_LOCKABLE,
55 D3DFMT_D32,
56 // D3DFMT_D15S1,
57 D3DFMT_D24S8,
58 D3DFMT_D24X8,
59 // D3DFMT_D24X4S4,
60 D3DFMT_D16,
61 // D3DFMT_D32F_LOCKABLE,
62 // D3DFMT_D24FS8
63 };
daniel@transgaming.com621ce052012-10-31 17:52:29 +000064
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000065Renderer9::Renderer9(egl::Display *display, HDC hDc, bool softwareDevice) : Renderer(display), mDc(hDc), mSoftwareDevice(softwareDevice)
daniel@transgaming.com621ce052012-10-31 17:52:29 +000066{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000067 mD3d9Module = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000068
daniel@transgaming.com7d738a22012-11-28 19:43:08 +000069 mD3dCompilerModule = NULL;
70
daniel@transgaming.com621ce052012-10-31 17:52:29 +000071 mD3d9 = NULL;
72 mD3d9Ex = NULL;
73 mDevice = NULL;
74 mDeviceEx = NULL;
75 mDeviceWindow = NULL;
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000076 mBlit = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000077
78 mAdapter = D3DADAPTER_DEFAULT;
79
80 #if REF_RAST == 1 || defined(FORCE_REF_RAST)
81 mDeviceType = D3DDEVTYPE_REF;
82 #else
83 mDeviceType = D3DDEVTYPE_HAL;
84 #endif
85
86 mDeviceLost = false;
daniel@transgaming.comb7833982012-10-31 18:31:46 +000087
88 mMaxSupportedSamples = 0;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +000089
90 mVertexDataManager = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000091}
92
daniel@transgaming.com2507f412012-10-31 18:46:48 +000093Renderer9::~Renderer9()
daniel@transgaming.com621ce052012-10-31 17:52:29 +000094{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000095 releaseDeviceResources();
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000096
97 delete mBlit;
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000098
daniel@transgaming.com621ce052012-10-31 17:52:29 +000099 if (mDevice)
100 {
101 // 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 +0000102 if (testDeviceLost(false))
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000103 {
104 resetDevice();
105 }
106
107 mDevice->Release();
108 mDevice = NULL;
109 }
110
111 if (mDeviceEx)
112 {
113 mDeviceEx->Release();
114 mDeviceEx = NULL;
115 }
116
117 if (mD3d9)
118 {
119 mD3d9->Release();
120 mD3d9 = NULL;
121 }
122
123 if (mDeviceWindow)
124 {
125 DestroyWindow(mDeviceWindow);
126 mDeviceWindow = NULL;
127 }
128
129 if (mD3d9Ex)
130 {
131 mD3d9Ex->Release();
132 mD3d9Ex = NULL;
133 }
134
135 if (mD3d9Module)
136 {
137 mD3d9Module = NULL;
138 }
139
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000140 if (mD3dCompilerModule)
141 {
142 FreeLibrary(mD3dCompilerModule);
143 mD3dCompilerModule = NULL;
144 }
145
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000146 while (!mMultiSampleSupport.empty())
147 {
148 delete [] mMultiSampleSupport.begin()->second;
149 mMultiSampleSupport.erase(mMultiSampleSupport.begin());
150 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000151}
152
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000153EGLint Renderer9::initialize()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000154{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +0000155 if (mSoftwareDevice)
156 {
157 mD3d9Module = GetModuleHandle(TEXT("swiftshader_d3d9.dll"));
158 }
159 else
160 {
161 mD3d9Module = GetModuleHandle(TEXT("d3d9.dll"));
162 }
163
164 if (mD3d9Module == NULL)
165 {
166 ERR("No D3D9 module found - aborting!\n");
167 return EGL_NOT_INITIALIZED;
168 }
169
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000170 typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex**);
171 Direct3DCreate9ExFunc Direct3DCreate9ExPtr = reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
172
173 // Use Direct3D9Ex if available. Among other things, this version is less
174 // inclined to report a lost context, for example when the user switches
175 // desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are available.
176 if (ANGLE_ENABLE_D3D9EX && Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9Ex)))
177 {
178 ASSERT(mD3d9Ex);
179 mD3d9Ex->QueryInterface(IID_IDirect3D9, reinterpret_cast<void**>(&mD3d9));
180 ASSERT(mD3d9);
181 }
182 else
183 {
184 mD3d9 = Direct3DCreate9(D3D_SDK_VERSION);
185 }
186
187 if (!mD3d9)
188 {
189 ERR("Could not create D3D9 device - aborting!\n");
190 return EGL_NOT_INITIALIZED;
191 }
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000192
193#if defined(ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES)
194 // Find a D3DCompiler module that had already been loaded based on a predefined list of versions.
195 static TCHAR* d3dCompilerNames[] = ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES;
196
197 for (int i = 0; i < sizeof(d3dCompilerNames) / sizeof(*d3dCompilerNames); ++i)
198 {
199 if (GetModuleHandleEx(0, d3dCompilerNames[i], &mD3dCompilerModule))
200 {
201 break;
202 }
203 }
204#else
205 // Load the version of the D3DCompiler DLL associated with the Direct3D version ANGLE was built with.
206 mD3dCompilerModule = LoadLibrary(D3DCOMPILER_DLL);
207#endif // ANGLE_PRELOADED_D3DCOMPILER_MODULE_NAMES
208
209 if (!mD3dCompilerModule)
210 {
211 terminate();
212 return false;
213 }
214
215 mD3DCompileFunc = reinterpret_cast<D3DCompileFunc>(GetProcAddress(mD3dCompilerModule, "D3DCompile"));
216 ASSERT(mD3DCompileFunc);
217
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000218 if (mDc != NULL)
219 {
220 // UNIMPLEMENTED(); // FIXME: Determine which adapter index the device context corresponds to
221 }
222
223 HRESULT result;
224
225 // Give up on getting device caps after about one second.
226 for (int i = 0; i < 10; ++i)
227 {
228 result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);
229 if (SUCCEEDED(result))
230 {
231 break;
232 }
233 else if (result == D3DERR_NOTAVAILABLE)
234 {
235 Sleep(100); // Give the driver some time to initialize/recover
236 }
237 else if (FAILED(result)) // D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY, D3DERR_INVALIDDEVICE, or another error we can't recover from
238 {
239 ERR("failed to get device caps (0x%x)\n", result);
240 return EGL_NOT_INITIALIZED;
241 }
242 }
243
244 if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
245 {
246 ERR("Renderer does not support PS 2.0. aborting!\n");
247 return EGL_NOT_INITIALIZED;
248 }
249
250 // When DirectX9 is running with an older DirectX8 driver, a StretchRect from a regular texture to a render target texture is not supported.
251 // This is required by Texture2D::convertToRenderTarget.
252 if ((mDeviceCaps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) == 0)
253 {
254 ERR("Renderer does not support stretctrect from textures!\n");
255 return EGL_NOT_INITIALIZED;
256 }
257
258 mD3d9->GetAdapterIdentifier(mAdapter, 0, &mAdapterIdentifier);
259
260 // ATI cards on XP have problems with non-power-of-two textures.
261 mSupportsNonPower2Textures = !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_POW2) &&
262 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP_POW2) &&
263 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) &&
264 !(getComparableOSVersion() < versionWindowsVista && mAdapterIdentifier.VendorId == VENDOR_ID_AMD);
265
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000266 // Must support a minimum of 2:1 anisotropy for max anisotropy to be considered supported, per the spec
267 mSupportsTextureFilterAnisotropy = ((mDeviceCaps.RasterCaps & D3DPRASTERCAPS_ANISOTROPY) && (mDeviceCaps.MaxAnisotropy >= 2));
268
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000269 mMinSwapInterval = 4;
270 mMaxSwapInterval = 0;
271
272 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE)
273 {
274 mMinSwapInterval = std::min(mMinSwapInterval, 0);
275 mMaxSwapInterval = std::max(mMaxSwapInterval, 0);
276 }
277 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)
278 {
279 mMinSwapInterval = std::min(mMinSwapInterval, 1);
280 mMaxSwapInterval = std::max(mMaxSwapInterval, 1);
281 }
282 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)
283 {
284 mMinSwapInterval = std::min(mMinSwapInterval, 2);
285 mMaxSwapInterval = std::max(mMaxSwapInterval, 2);
286 }
287 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)
288 {
289 mMinSwapInterval = std::min(mMinSwapInterval, 3);
290 mMaxSwapInterval = std::max(mMaxSwapInterval, 3);
291 }
292 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)
293 {
294 mMinSwapInterval = std::min(mMinSwapInterval, 4);
295 mMaxSwapInterval = std::max(mMaxSwapInterval, 4);
296 }
297
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000298 int max = 0;
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000299 for (int i = 0; i < sizeof(RenderTargetFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000300 {
301 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000302 getMultiSampleSupport(RenderTargetFormats[i], multisampleArray);
303 mMultiSampleSupport[RenderTargetFormats[i]] = multisampleArray;
daniel@transgaming.com92955622012-10-31 18:38:41 +0000304
305 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
306 {
307 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
308 {
309 max = j;
310 }
311 }
312 }
313
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000314 for (int i = 0; i < sizeof(DepthStencilFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000315 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000316 if (DepthStencilFormats[i] == D3DFMT_UNKNOWN)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000317 continue;
318
319 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000320 getMultiSampleSupport(DepthStencilFormats[i], multisampleArray);
321 mMultiSampleSupport[DepthStencilFormats[i]] = multisampleArray;
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000322
323 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
324 {
325 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
326 {
327 max = j;
328 }
329 }
330 }
331
332 mMaxSupportedSamples = max;
333
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000334 static const TCHAR windowName[] = TEXT("AngleHiddenWindow");
335 static const TCHAR className[] = TEXT("STATIC");
336
337 mDeviceWindow = CreateWindowEx(WS_EX_NOACTIVATE, className, windowName, WS_DISABLED | WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
338
339 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
340 DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE | D3DCREATE_NOWINDOWCHANGES;
341
342 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE, &presentParameters, &mDevice);
343 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DEVICELOST)
344 {
345 return EGL_BAD_ALLOC;
346 }
347
348 if (FAILED(result))
349 {
350 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &presentParameters, &mDevice);
351
352 if (FAILED(result))
353 {
354 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_NOTAVAILABLE || result == D3DERR_DEVICELOST);
355 return EGL_BAD_ALLOC;
356 }
357 }
358
359 if (mD3d9Ex)
360 {
361 result = mDevice->QueryInterface(IID_IDirect3DDevice9Ex, (void**) &mDeviceEx);
362 ASSERT(SUCCEEDED(result));
363 }
364
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000365 mVertexShaderCache.initialize(mDevice);
366 mPixelShaderCache.initialize(mDevice);
367
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000368 initializeDevice();
369
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +0000370 mBlit = new Blit(this);
371
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000372 return EGL_SUCCESS;
373}
374
375// do any one-time device initialization
376// NOTE: this is also needed after a device lost/reset
377// to reset the scene status and ensure the default states are reset.
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000378void Renderer9::initializeDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000379{
380 // Permanent non-default states
381 mDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
382 mDevice->SetRenderState(D3DRS_LASTPIXEL, FALSE);
383
384 if (mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0))
385 {
386 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, (DWORD&)mDeviceCaps.MaxPointSize);
387 }
388 else
389 {
390 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, 0x3F800000); // 1.0f
391 }
392
daniel@transgaming.comc43a6052012-11-28 19:41:51 +0000393 markAllStateDirty();
394
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000395 mSceneStarted = false;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +0000396
397 if (!mVertexDataManager)
398 {
399 mVertexDataManager = new gl::VertexDataManager(this);
400 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000401}
402
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000403D3DPRESENT_PARAMETERS Renderer9::getDefaultPresentParameters()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000404{
405 D3DPRESENT_PARAMETERS presentParameters = {0};
406
407 // The default swap chain is never actually used. Surface will create a new swap chain with the proper parameters.
408 presentParameters.AutoDepthStencilFormat = D3DFMT_UNKNOWN;
409 presentParameters.BackBufferCount = 1;
410 presentParameters.BackBufferFormat = D3DFMT_UNKNOWN;
411 presentParameters.BackBufferWidth = 1;
412 presentParameters.BackBufferHeight = 1;
413 presentParameters.EnableAutoDepthStencil = FALSE;
414 presentParameters.Flags = 0;
415 presentParameters.hDeviceWindow = mDeviceWindow;
416 presentParameters.MultiSampleQuality = 0;
417 presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE;
418 presentParameters.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
419 presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
420 presentParameters.Windowed = TRUE;
421
422 return presentParameters;
423}
424
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000425int Renderer9::generateConfigs(ConfigDesc **configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000426{
427 D3DDISPLAYMODE currentDisplayMode;
428 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
429
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000430 unsigned int numRenderFormats = sizeof(RenderTargetFormats) / sizeof(RenderTargetFormats[0]);
431 unsigned int numDepthFormats = sizeof(DepthStencilFormats) / sizeof(DepthStencilFormats[0]);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000432 (*configDescList) = new ConfigDesc[numRenderFormats * numDepthFormats];
433 int numConfigs = 0;
434
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000435 for (unsigned int formatIndex = 0; formatIndex < numRenderFormats; formatIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000436 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000437 D3DFORMAT renderTargetFormat = RenderTargetFormats[formatIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000438
439 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, renderTargetFormat);
440
441 if (SUCCEEDED(result))
442 {
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000443 for (unsigned int depthStencilIndex = 0; depthStencilIndex < numDepthFormats; depthStencilIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000444 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000445 D3DFORMAT depthStencilFormat = DepthStencilFormats[depthStencilIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000446 HRESULT result = D3D_OK;
447
448 if(depthStencilFormat != D3DFMT_UNKNOWN)
449 {
450 result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFormat);
451 }
452
453 if (SUCCEEDED(result))
454 {
455 if(depthStencilFormat != D3DFMT_UNKNOWN)
456 {
457 result = mD3d9->CheckDepthStencilMatch(mAdapter, mDeviceType, currentDisplayMode.Format, renderTargetFormat, depthStencilFormat);
458 }
459
460 if (SUCCEEDED(result))
461 {
462 ConfigDesc newConfig;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000463 newConfig.renderTargetFormat = d3d9_gl::ConvertBackBufferFormat(renderTargetFormat);
464 newConfig.depthStencilFormat = d3d9_gl::ConvertDepthStencilFormat(depthStencilFormat);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000465 newConfig.multiSample = 0; // FIXME: enumerate multi-sampling
466 newConfig.fastConfig = (currentDisplayMode.Format == renderTargetFormat);
467
468 (*configDescList)[numConfigs++] = newConfig;
469 }
470 }
471 }
472 }
473 }
474
475 return numConfigs;
476}
477
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000478void Renderer9::deleteConfigs(ConfigDesc *configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000479{
480 delete [] (configDescList);
481}
482
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000483void Renderer9::startScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000484{
485 if (!mSceneStarted)
486 {
487 long result = mDevice->BeginScene();
488 if (SUCCEEDED(result)) {
489 // This is defensive checking against the device being
490 // lost at unexpected times.
491 mSceneStarted = true;
492 }
493 }
494}
495
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000496void Renderer9::endScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000497{
498 if (mSceneStarted)
499 {
500 // EndScene can fail if the device was lost, for example due
501 // to a TDR during a draw call.
502 mDevice->EndScene();
503 mSceneStarted = false;
504 }
505}
506
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000507// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000508void Renderer9::sync(bool block)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000509{
510 HRESULT result;
511
512 IDirect3DQuery9* query = allocateEventQuery();
513 if (!query)
514 {
515 return;
516 }
517
518 result = query->Issue(D3DISSUE_END);
519 ASSERT(SUCCEEDED(result));
520
521 do
522 {
523 result = query->GetData(NULL, 0, D3DGETDATA_FLUSH);
524
525 if(block && result == S_FALSE)
526 {
527 // Keep polling, but allow other threads to do something useful first
528 Sleep(0);
529 // explicitly check for device loss
530 // some drivers seem to return S_FALSE even if the device is lost
531 // instead of D3DERR_DEVICELOST like they should
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000532 if (testDeviceLost(false))
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000533 {
534 result = D3DERR_DEVICELOST;
535 }
536 }
537 }
538 while(block && result == S_FALSE);
539
540 freeEventQuery(query);
541
542 if (isDeviceLostError(result))
543 {
544 mDisplay->notifyDeviceLost();
545 }
546}
547
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000548SwapChain *Renderer9::createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
549{
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +0000550 return new rx::SwapChain9(this, window, shareHandle, backBufferFormat, depthBufferFormat);
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000551}
552
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000553// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000554IDirect3DQuery9* Renderer9::allocateEventQuery()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000555{
556 IDirect3DQuery9 *query = NULL;
557
558 if (mEventQueryPool.empty())
559 {
560 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &query);
561 ASSERT(SUCCEEDED(result));
562 }
563 else
564 {
565 query = mEventQueryPool.back();
566 mEventQueryPool.pop_back();
567 }
568
569 return query;
570}
571
572// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000573void Renderer9::freeEventQuery(IDirect3DQuery9* query)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000574{
575 if (mEventQueryPool.size() > 1000)
576 {
577 query->Release();
578 }
579 else
580 {
581 mEventQueryPool.push_back(query);
582 }
583}
584
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000585
586HRESULT Renderer9::compileShaderSource(const char* hlsl, const char* sourceName, const char* profile, DWORD flags, ID3DBlob** binary, ID3DBlob** errorMessage)
587{
588 return mD3DCompileFunc(hlsl, strlen(hlsl), sourceName, NULL, NULL, "main", profile, flags, 0, binary, errorMessage);
589}
590
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000591IDirect3DVertexShader9 *Renderer9::createVertexShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000592{
593 return mVertexShaderCache.create(function, length);
594}
595
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000596IDirect3DPixelShader9 *Renderer9::createPixelShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000597{
598 return mPixelShaderCache.create(function, length);
599}
600
daniel@transgaming.com113f0eb2012-10-31 18:46:58 +0000601HRESULT Renderer9::createVertexBuffer(UINT Length, DWORD Usage, IDirect3DVertexBuffer9 **ppVertexBuffer)
602{
603 D3DPOOL Pool = getBufferPool(Usage);
604 return mDevice->CreateVertexBuffer(Length, Usage, 0, Pool, ppVertexBuffer, NULL);
605}
606
607HRESULT Renderer9::createIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, IDirect3DIndexBuffer9 **ppIndexBuffer)
608{
609 D3DPOOL Pool = getBufferPool(Usage);
610 return mDevice->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, NULL);
611}
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000612
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000613void Renderer9::setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &samplerState)
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000614{
615 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
616 int d3dSampler = index + d3dSamplerOffset;
617
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000618 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSU, gl_d3d9::ConvertTextureWrap(samplerState.wrapS));
619 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSV, gl_d3d9::ConvertTextureWrap(samplerState.wrapT));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000620
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000621 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAGFILTER, gl_d3d9::ConvertMagFilter(samplerState.magFilter, samplerState.maxAnisotropy));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000622 D3DTEXTUREFILTERTYPE d3dMinFilter, d3dMipFilter;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000623 gl_d3d9::ConvertMinFilter(samplerState.minFilter, &d3dMinFilter, &d3dMipFilter, samplerState.maxAnisotropy);
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000624 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MINFILTER, d3dMinFilter);
625 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPFILTER, d3dMipFilter);
626 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXMIPLEVEL, samplerState.lodOffset);
627 if (mSupportsTextureFilterAnisotropy)
628 {
629 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, (DWORD)samplerState.maxAnisotropy);
630 }
631}
632
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000633void Renderer9::setTexture(gl::SamplerType type, int index, gl::Texture *texture)
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000634{
635 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
636 int d3dSampler = index + d3dSamplerOffset;
637 IDirect3DBaseTexture9 *d3dTexture = NULL;
638
639 if (texture)
640 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +0000641 TextureStorage *texStorage = texture->getNativeTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000642 if (texStorage)
643 {
644 d3dTexture = texStorage->getBaseTexture();
645 }
646 // If we get NULL back from getBaseTexture here, something went wrong
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000647 // in the texture class and we're unexpectedly missing the d3d texture
648 ASSERT(d3dTexture != NULL);
649 }
650
651 mDevice->SetTexture(d3dSampler, d3dTexture);
652}
653
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000654void Renderer9::setRasterizerState(const gl::RasterizerState &rasterState, unsigned int depthSize)
655{
656 bool rasterStateChanged = mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0;
657 bool depthSizeChanged = mForceSetRasterState || depthSize != mCurDepthSize;
658
659 if (rasterStateChanged)
660 {
661 // Set the cull mode
662 if (rasterState.cullFace)
663 {
664 mDevice->SetRenderState(D3DRS_CULLMODE, gl_d3d9::ConvertCullMode(rasterState.cullMode, rasterState.frontFace));
665 }
666 else
667 {
668 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
669 }
670
671 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, rasterState.scissorTest ? TRUE : FALSE);
672
673 mCurRasterState = rasterState;
674 }
675
676 if (rasterStateChanged || depthSizeChanged)
677 {
678 if (rasterState.polygonOffsetFill)
679 {
680 if (depthSize > 0)
681 {
682 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
683
684 float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(depthSize));
685 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
686 }
687 }
688 else
689 {
690 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
691 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
692 }
693
694 mCurDepthSize = depthSize;
695 }
696
697 mForceSetRasterState = false;
698}
699
700void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
701{
702 bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
703 bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
704 bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
705
706 if (blendStateChanged || blendColorChanged)
707 {
708 if (blendState.blend)
709 {
710 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
711
712 if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
713 blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
714 {
715 mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
716 }
717 else
718 {
719 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
720 gl::unorm<8>(blendColor.alpha),
721 gl::unorm<8>(blendColor.alpha),
722 gl::unorm<8>(blendColor.alpha)));
723 }
724
725 mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
726 mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
727 mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
728
729 if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
730 blendState.destBlendRGB != blendState.destBlendAlpha ||
731 blendState.blendEquationRGB != blendState.blendEquationAlpha)
732 {
733 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
734
735 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
736 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
737 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
738 }
739 else
740 {
741 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
742 }
743 }
744 else
745 {
746 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
747 }
748
749 if (blendState.sampleAlphaToCoverage)
750 {
751 FIXME("Sample alpha to coverage is unimplemented.");
752 }
753
754 // Set the color mask
755 bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
756 // Apparently some ATI cards have a bug where a draw with a zero color
757 // write mask can cause later draws to have incorrect results. Instead,
758 // set a nonzero color write mask but modify the blend state so that no
759 // drawing is done.
760 // http://code.google.com/p/angleproject/issues/detail?id=169
761
762 DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
763 blendState.colorMaskBlue, blendState.colorMaskAlpha);
764 if (colorMask == 0 && !zeroColorMaskAllowed)
765 {
766 // Enable green channel, but set blending so nothing will be drawn.
767 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
768 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
769
770 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
771 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
772 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
773 }
774 else
775 {
776 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
777 }
778
779 mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
780
781 mCurBlendState = blendState;
782 mCurBlendColor = blendColor;
783 }
784
785 if (sampleMaskChanged)
786 {
787 // Set the multisample mask
788 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
789 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
790
791 mCurSampleMask = sampleMask;
792 }
793
794 mForceSetBlendState = false;
795}
796
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000797void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
798 int stencilBackRef, bool frontFaceCCW, unsigned int stencilSize)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000799{
800 bool depthStencilStateChanged = mForceSetDepthStencilState ||
801 memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000802 bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
803 stencilBackRef != mCurStencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000804 bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
805 bool stencilSizeChanged = mForceSetDepthStencilState || stencilSize != mCurStencilSize;
806
807 if (depthStencilStateChanged)
808 {
809 if (depthStencilState.depthTest)
810 {
811 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
812 mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
813 }
814 else
815 {
816 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
817 }
818
819 mCurDepthStencilState = depthStencilState;
820 }
821
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000822 if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged || stencilSizeChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000823 {
824 if (depthStencilState.stencilTest && stencilSize > 0)
825 {
826 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
827 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
828
829 // FIXME: Unsupported by D3D9
830 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
831 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
832 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
833 if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000834 stencilRef != stencilBackRef ||
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000835 depthStencilState.stencilMask != depthStencilState.stencilBackMask)
836 {
837 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
838 return error(GL_INVALID_OPERATION);
839 }
840
841 // get the maximum size of the stencil ref
842 GLuint maxStencil = (1 << stencilSize) - 1;
843
844 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
845 depthStencilState.stencilWritemask);
846 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
847 gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
848
849 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000850 (stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000851 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
852 depthStencilState.stencilMask);
853
854 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
855 gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
856 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
857 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
858 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
859 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
860
861 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
862 depthStencilState.stencilBackWritemask);
863 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
864 gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
865
866 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000867 (stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000868 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
869 depthStencilState.stencilBackMask);
870
871 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
872 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
873 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
874 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
875 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
876 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
877 }
878 else
879 {
880 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
881 }
882
883 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
884
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000885 mCurStencilRef = stencilRef;
886 mCurStencilBackRef = stencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000887 mCurFrontFaceCCW = frontFaceCCW;
888 mCurStencilSize = stencilSize;
889 }
890
891 mForceSetDepthStencilState = false;
892}
893
894void Renderer9::setScissorRectangle(const gl::Rectangle& scissor, unsigned int renderTargetWidth,
895 unsigned int renderTargetHeight)
896{
897 bool renderTargetSizedChanged = mForceSetScissor ||
898 renderTargetWidth != mCurRenderTargetWidth ||
899 renderTargetHeight != mCurRenderTargetHeight;
900 bool scissorChanged = mForceSetScissor || memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0;
901
902 if (renderTargetSizedChanged || scissorChanged)
903 {
904 RECT rect;
905 rect.left = gl::clamp(scissor.x, 0, static_cast<int>(renderTargetWidth));
daniel@transgaming.com1dd557a2012-11-28 19:44:00 +0000906 rect.top = gl::clamp(scissor.y, 0, static_cast<int>(renderTargetHeight));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000907 rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(renderTargetWidth));
daniel@transgaming.com1dd557a2012-11-28 19:44:00 +0000908 rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(renderTargetHeight));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000909 mDevice->SetScissorRect(&rect);
910
911 mCurScissor = scissor;
912 mCurRenderTargetWidth = renderTargetWidth;
913 mCurRenderTargetHeight = renderTargetHeight;
914 }
915
916 mForceSetScissor = false;
917}
918
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000919bool Renderer9::setViewport(const gl::Rectangle& viewport, float zNear, float zFar,
920 unsigned int renderTargetWidth, unsigned int renderTargetHeight,
921 gl::ProgramBinary *currentProgram, bool forceSetUniforms)
922{
923 bool viewportChanged = mForceSetViewport || memcmp(&viewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
924 zNear != mCurNear || zFar != mCurFar;
925
926 D3DVIEWPORT9 dxViewport;
927 dxViewport.X = gl::clamp(viewport.x, 0, static_cast<int>(renderTargetWidth));
928 dxViewport.Y = gl::clamp(viewport.y, 0, static_cast<int>(renderTargetHeight));
929 dxViewport.Width = gl::clamp(viewport.width, 0, static_cast<int>(renderTargetWidth) - static_cast<int>(dxViewport.X));
930 dxViewport.Height = gl::clamp(viewport.height, 0, static_cast<int>(renderTargetHeight) - static_cast<int>(dxViewport.Y));
931 dxViewport.MinZ = zNear;
932 dxViewport.MaxZ = zFar;
933
934 if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
935 {
936 return false; // Nothing to render
937 }
938
939 if (viewportChanged)
940 {
941 mDevice->SetViewport(&dxViewport);
942
943 mCurViewport = viewport;
944 mCurNear = zNear;
945 mCurFar = zFar;
946 }
947
948 if (currentProgram && (viewportChanged || forceSetUniforms))
949 {
950 GLint halfPixelSize = currentProgram->getDxHalfPixelSizeLocation();
951 GLfloat xy[2] = { 1.0f / dxViewport.Width, -1.0f / dxViewport.Height };
952 currentProgram->setUniform2fv(halfPixelSize, 1, xy);
953
954 // These values are used for computing gl_FragCoord in Program::linkVaryings().
955 GLint coord = currentProgram->getDxCoordLocation();
956 GLfloat whxy[4] = { viewport.width * 0.5f,
957 viewport.height * 0.5f,
958 viewport.x + (viewport.width * 0.5f),
959 viewport.y + (viewport.height * 0.5f) };
960 currentProgram->setUniform4fv(coord, 1, whxy);
961
962 GLint depth = currentProgram->getDxDepthLocation();
963 GLfloat dz[2] = { (zFar - zNear) * 0.5f, (zNear + zFar) * 0.5f };
964 currentProgram->setUniform2fv(depth, 1, dz);
965
966 GLint depthRange = currentProgram->getDxDepthRangeLocation();
967 GLfloat nearFarDiff[3] = { zNear, zFar, zFar - zNear };
968 currentProgram->setUniform3fv(depthRange, 1, nearFarDiff);
969 }
970
971 mForceSetViewport = false;
972 return true;
973}
974
daniel@transgaming.comae39ee22012-11-28 19:42:02 +0000975bool Renderer9::applyRenderTarget(gl::Framebuffer *framebuffer)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000976{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +0000977 // if there is no color attachment we must synthesize a NULL colorattachment
978 // to keep the D3D runtime happy. This should only be possible if depth texturing.
979 gl::Renderbuffer *renderbufferObject = NULL;
980 if (framebuffer->getColorbufferType() != GL_NONE)
981 {
982 renderbufferObject = framebuffer->getColorbuffer();
983 }
984 else
985 {
986 renderbufferObject = framebuffer->getNullColorbuffer();
987 }
988 if (!renderbufferObject)
989 {
990 ERR("unable to locate renderbuffer for FBO.");
991 return false;
992 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000993
daniel@transgaming.com220e79a2012-11-28 19:42:11 +0000994 bool renderTargetChanged = false;
995 unsigned int renderTargetSerial = renderbufferObject->getSerial();
996 if (renderTargetSerial != mAppliedRenderTargetSerial)
997 {
998 // Apply the render target on the device
999 IDirect3DSurface9 *renderTargetSurface = NULL;
1000
1001 RenderTarget *renderTarget = renderbufferObject->getRenderTarget();
1002 if (renderTarget)
1003 {
1004 renderTargetSurface = renderTarget->getSurface();
1005 }
1006
1007 if (!renderTargetSurface)
1008 {
1009 ERR("render target pointer unexpectedly null.");
1010 return false; // Context must be lost
1011 }
1012
1013 mDevice->SetRenderTarget(0, renderTargetSurface);
1014 renderTargetSurface->Release();
1015
1016 mAppliedRenderTargetSerial = renderTargetSerial;
1017 renderTargetChanged = true;
1018 }
1019
1020 gl::Renderbuffer *depthStencil = NULL;
1021 unsigned int depthbufferSerial = 0;
1022 unsigned int stencilbufferSerial = 0;
1023 if (framebuffer->getDepthbufferType() != GL_NONE)
1024 {
1025 depthStencil = framebuffer->getDepthbuffer();
1026 if (!depthStencil)
1027 {
1028 ERR("Depth stencil pointer unexpectedly null.");
1029 return false;
1030 }
1031
1032 depthbufferSerial = depthStencil->getSerial();
1033 }
1034 else if (framebuffer->getStencilbufferType() != GL_NONE)
1035 {
1036 depthStencil = framebuffer->getStencilbuffer();
1037 if (!depthStencil)
1038 {
1039 ERR("Depth stencil pointer unexpectedly null.");
1040 return false;
1041 }
1042
1043 stencilbufferSerial = depthStencil->getSerial();
1044 }
1045
1046 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1047 stencilbufferSerial != mAppliedStencilbufferSerial ||
1048 !mDepthStencilInitialized)
1049 {
1050 // Apply the depth stencil on the device
1051 if (depthStencil)
1052 {
1053 IDirect3DSurface9 *depthStencilSurface = NULL;
1054 RenderTarget *depthStencilRenderTarget = depthStencil->getDepthStencil();
1055
1056 if (depthStencilRenderTarget)
1057 {
1058 depthStencilSurface = depthStencilRenderTarget->getSurface();
1059 }
1060
1061 if (!depthStencilSurface)
1062 {
1063 ERR("depth stencil pointer unexpectedly null.");
1064 return false; // Context must be lost
1065 }
1066
1067 mDevice->SetDepthStencilSurface(depthStencilSurface);
1068 depthStencilSurface->Release();
1069 }
1070 else
1071 {
1072 mDevice->SetDepthStencilSurface(NULL);
1073 }
1074
1075 mAppliedDepthbufferSerial = depthbufferSerial;
1076 mAppliedStencilbufferSerial = stencilbufferSerial;
1077 mDepthStencilInitialized = true;
1078 }
1079
1080 if (renderTargetChanged || !mRenderTargetDescInitialized)
1081 {
1082 mForceSetScissor = true;
1083 mForceSetViewport = true;
1084
1085 mRenderTargetDesc.width = renderbufferObject->getWidth();
1086 mRenderTargetDesc.height = renderbufferObject->getHeight();
1087 mRenderTargetDesc.format = renderbufferObject->getActualFormat();
1088 mRenderTargetDescInitialized = true;
1089 }
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001090
1091 return true;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001092}
daniel@transgaming.coma734f272012-10-31 18:07:48 +00001093
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001094GLenum Renderer9::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances, GLsizei *repeatDraw)
1095{
1096 gl::TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
1097 GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
1098 if (err != GL_NO_ERROR)
1099 {
1100 return err;
1101 }
1102
1103 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, repeatDraw);
1104}
1105
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001106void Renderer9::clear(GLbitfield mask, const gl::Color &colorClear, float depthClear, int stencilClear,
1107 gl::Framebuffer *frameBuffer)
1108{
1109 mForceSetDepthStencilState = true;
1110
1111 // TODO
1112}
1113
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001114void Renderer9::markAllStateDirty()
1115{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001116 mAppliedRenderTargetSerial = 0;
1117 mAppliedDepthbufferSerial = 0;
1118 mAppliedStencilbufferSerial = 0;
1119 mDepthStencilInitialized = false;
1120 mRenderTargetDescInitialized = false;
1121
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001122 mForceSetDepthStencilState = true;
1123 mForceSetRasterState = true;
1124 mForceSetBlendState = true;
1125 mForceSetScissor = true;
1126 mForceSetViewport = true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001127
1128 mVertexDeclarationCache.markStateDirty();
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001129}
1130
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001131void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001132{
1133 while (!mEventQueryPool.empty())
1134 {
1135 mEventQueryPool.back()->Release();
1136 mEventQueryPool.pop_back();
1137 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001138
1139 mVertexShaderCache.clear();
1140 mPixelShaderCache.clear();
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001141
1142 delete mVertexDataManager;
1143 mVertexDataManager = NULL;
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001144}
1145
1146
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001147void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001148{
1149 mDeviceLost = true;
1150}
1151
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001152bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001153{
1154 return mDeviceLost;
1155}
1156
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001157// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001158bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001159{
1160 bool isLost = false;
1161
1162 if (mDeviceEx)
1163 {
1164 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
1165 }
1166 else if (mDevice)
1167 {
1168 isLost = FAILED(mDevice->TestCooperativeLevel());
1169 }
1170 else
1171 {
1172 // No device yet, so no reset required
1173 }
1174
1175 if (isLost)
1176 {
1177 // ensure we note the device loss --
1178 // we'll probably get this done again by markDeviceLost
1179 // but best to remember it!
1180 // Note that we don't want to clear the device loss status here
1181 // -- this needs to be done by resetDevice
1182 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001183 if (notify)
1184 {
1185 mDisplay->notifyDeviceLost();
1186 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001187 }
1188
1189 return isLost;
1190}
1191
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001192bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001193{
1194 HRESULT status = D3D_OK;
1195
1196 if (mDeviceEx)
1197 {
1198 status = mDeviceEx->CheckDeviceState(NULL);
1199 }
1200 else if (mDevice)
1201 {
1202 status = mDevice->TestCooperativeLevel();
1203 }
1204
1205 switch (status)
1206 {
1207 case D3DERR_DEVICENOTRESET:
1208 case D3DERR_DEVICEHUNG:
1209 return true;
1210 default:
1211 return false;
1212 }
1213}
1214
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001215bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001216{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001217 releaseDeviceResources();
1218
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001219 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
1220
1221 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001222 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001223 int attempts = 3;
1224
1225 while (lost && attempts > 0)
1226 {
1227 if (mDeviceEx)
1228 {
1229 Sleep(500); // Give the graphics driver some CPU time
1230 result = mDeviceEx->ResetEx(&presentParameters, NULL);
1231 }
1232 else
1233 {
1234 result = mDevice->TestCooperativeLevel();
1235 while (result == D3DERR_DEVICELOST)
1236 {
1237 Sleep(100); // Give the graphics driver some CPU time
1238 result = mDevice->TestCooperativeLevel();
1239 }
1240
1241 if (result == D3DERR_DEVICENOTRESET)
1242 {
1243 result = mDevice->Reset(&presentParameters);
1244 }
1245 }
1246
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001247 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001248 attempts --;
1249 }
1250
1251 if (FAILED(result))
1252 {
1253 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
1254 return false;
1255 }
1256
1257 // reset device defaults
1258 initializeDevice();
1259 mDeviceLost = false;
1260
1261 return true;
1262}
1263
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001264DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001265{
1266 return mAdapterIdentifier.VendorId;
1267}
1268
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001269const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001270{
1271 return mAdapterIdentifier.Description;
1272}
1273
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001274GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001275{
1276 return mAdapterIdentifier.DeviceIdentifier;
1277}
1278
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001279void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001280{
1281 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
1282 {
1283 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
1284 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
1285
1286 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
1287 }
1288}
1289
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001290bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001291{
1292 D3DDISPLAYMODE currentDisplayMode;
1293 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1294
1295 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
1296}
1297
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001298bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001299{
1300 D3DDISPLAYMODE currentDisplayMode;
1301 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1302
1303 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
1304}
1305
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001306bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001307{
1308 D3DDISPLAYMODE currentDisplayMode;
1309 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1310
1311 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
1312}
1313
1314// we use INTZ for depth textures in Direct3D9
1315// we also want NULL texture support to ensure the we can make depth-only FBOs
1316// see http://aras-p.info/texts/D3D9GPUHacks.html
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001317bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001318{
1319 D3DDISPLAYMODE currentDisplayMode;
1320 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1321
1322 bool intz = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1323 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ));
1324 bool null = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
1325 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
1326
1327 return intz && null;
1328}
1329
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001330bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001331{
1332 D3DDISPLAYMODE currentDisplayMode;
1333 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1334
1335 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1336 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1337 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1338 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1339
1340 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1341 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F))&&
1342 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1343 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1344
1345 if (!*filtering && !*renderable)
1346 {
1347 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1348 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
1349 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1350 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
1351 }
1352 else
1353 {
1354 return true;
1355 }
1356}
1357
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001358bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001359{
1360 D3DDISPLAYMODE currentDisplayMode;
1361 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1362
1363 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1364 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1365 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
1366 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1367
1368 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1369 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1370 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
1371 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1372
1373 if (!*filtering && !*renderable)
1374 {
1375 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1376 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
1377 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
1378 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
1379 }
1380 else
1381 {
1382 return true;
1383 }
1384}
1385
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001386bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001387{
1388 D3DDISPLAYMODE currentDisplayMode;
1389 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1390
1391 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
1392}
1393
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001394bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001395{
1396 D3DDISPLAYMODE currentDisplayMode;
1397 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1398
1399 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
1400}
1401
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001402bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001403{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001404 return mSupportsTextureFilterAnisotropy;
1405}
1406
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001407float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00001408{
1409 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001410 {
1411 return mDeviceCaps.MaxAnisotropy;
1412 }
1413 return 1.0f;
1414}
1415
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001416bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001417{
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001418 IDirect3DQuery9 *query = allocateEventQuery();
1419 if (query)
1420 {
1421 freeEventQuery(query);
1422 return true;
1423 }
1424 else
1425 {
1426 return false;
1427 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001428 return true;
1429}
1430
1431// Only Direct3D 10 ready devices support all the necessary vertex texture formats.
1432// We test this using D3D9 by checking support for the R16F format.
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001433bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001434{
1435 if (!mDevice || mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(3, 0))
1436 {
1437 return false;
1438 }
1439
1440 D3DDISPLAYMODE currentDisplayMode;
1441 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1442
1443 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F);
1444
1445 return SUCCEEDED(result);
1446}
1447
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001448bool Renderer9::getNonPower2TextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001449{
1450 return mSupportsNonPower2Textures;
1451}
1452
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001453bool Renderer9::getOcclusionQuerySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001454{
1455 if (!mDevice)
1456 {
1457 return false;
1458 }
1459
1460 IDirect3DQuery9 *query = NULL;
1461 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query);
1462 if (SUCCEEDED(result) && query)
1463 {
1464 query->Release();
1465 return true;
1466 }
1467 else
1468 {
1469 return false;
1470 }
1471}
1472
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001473bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001474{
1475 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
1476}
1477
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001478bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001479{
1480 // PIX doesn't seem to support using share handles, so disable them.
1481 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00001482 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00001483}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001484
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001485bool Renderer9::getShaderModel3Support() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001486{
1487 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
1488}
1489
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001490float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001491{
1492 return mDeviceCaps.MaxPointSize;
1493}
1494
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001495int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001496{
1497 return (int)mDeviceCaps.MaxTextureWidth;
1498}
1499
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001500int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001501{
1502 return (int)mDeviceCaps.MaxTextureHeight;
1503}
1504
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001505bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001506{
1507 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
1508}
1509
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001510DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001511{
1512 return mDeviceCaps.DeclTypes;
1513}
1514
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001515int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001516{
1517 return mMinSwapInterval;
1518}
1519
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001520int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00001521{
1522 return mMaxSwapInterval;
1523}
1524
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001525int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001526{
1527 return mMaxSupportedSamples;
1528}
1529
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001530int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001531{
1532 if (requested == 0)
1533 {
1534 return requested;
1535 }
1536
1537 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
1538 if (itr == mMultiSampleSupport.end())
1539 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00001540 if (format == D3DFMT_UNKNOWN)
1541 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00001542 return -1;
1543 }
1544
1545 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
1546 {
1547 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
1548 {
1549 return i;
1550 }
1551 }
1552
1553 return -1;
1554}
1555
daniel@transgaming.coma9571682012-11-28 19:33:08 +00001556D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
1557{
1558 switch (internalformat)
1559 {
1560 case GL_DEPTH_COMPONENT16:
1561 case GL_DEPTH_COMPONENT32_OES:
1562 case GL_DEPTH24_STENCIL8_OES:
1563 return D3DFMT_INTZ;
1564 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
1565 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
1566 return D3DFMT_DXT1;
1567 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
1568 return D3DFMT_DXT3;
1569 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
1570 return D3DFMT_DXT5;
1571 case GL_RGBA32F_EXT:
1572 case GL_RGB32F_EXT:
1573 case GL_ALPHA32F_EXT:
1574 case GL_LUMINANCE32F_EXT:
1575 case GL_LUMINANCE_ALPHA32F_EXT:
1576 return D3DFMT_A32B32G32R32F;
1577 case GL_RGBA16F_EXT:
1578 case GL_RGB16F_EXT:
1579 case GL_ALPHA16F_EXT:
1580 case GL_LUMINANCE16F_EXT:
1581 case GL_LUMINANCE_ALPHA16F_EXT:
1582 return D3DFMT_A16B16G16R16F;
1583 case GL_LUMINANCE8_EXT:
1584 if (getLuminanceTextureSupport())
1585 {
1586 return D3DFMT_L8;
1587 }
1588 break;
1589 case GL_LUMINANCE8_ALPHA8_EXT:
1590 if (getLuminanceAlphaTextureSupport())
1591 {
1592 return D3DFMT_A8L8;
1593 }
1594 break;
1595 case GL_RGB8_OES:
1596 case GL_RGB565:
1597 return D3DFMT_X8R8G8B8;
1598 }
1599
1600 return D3DFMT_A8R8G8B8;
1601}
1602
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00001603bool Renderer9::copyToRenderTarget(TextureStorage2D *dest, TextureStorage2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00001604{
1605 bool result = false;
1606
1607 if (source && dest)
1608 {
1609 int levels = source->levelCount();
1610 for (int i = 0; i < levels; ++i)
1611 {
1612 IDirect3DSurface9 *srcSurf = source->getSurfaceLevel(i, false);
1613 IDirect3DSurface9 *dstSurf = dest->getSurfaceLevel(i, false);
1614
1615 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
1616
1617 if (srcSurf) srcSurf->Release();
1618 if (dstSurf) dstSurf->Release();
1619
1620 if (!result)
1621 return false;
1622 }
1623 }
1624
1625 return result;
1626}
1627
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00001628bool Renderer9::copyToRenderTarget(TextureStorageCubeMap *dest, TextureStorageCubeMap *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00001629{
1630 bool result = false;
1631
1632 if (source && dest)
1633 {
1634 int levels = source->levelCount();
1635 for (int f = 0; f < 6; f++)
1636 {
1637 for (int i = 0; i < levels; i++)
1638 {
1639 IDirect3DSurface9 *srcSurf = source->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
1640 IDirect3DSurface9 *dstSurf = dest->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
1641
1642 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
1643
1644 if (srcSurf) srcSurf->Release();
1645 if (dstSurf) dstSurf->Release();
1646
1647 if (!result)
1648 return false;
1649 }
1650 }
1651 }
1652
1653 return result;
1654}
1655
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001656D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001657{
1658 if (mD3d9Ex != NULL)
1659 {
1660 return D3DPOOL_DEFAULT;
1661 }
1662 else
1663 {
1664 if (!(usage & D3DUSAGE_DYNAMIC))
1665 {
1666 return D3DPOOL_MANAGED;
1667 }
1668 }
1669
1670 return D3DPOOL_DEFAULT;
1671}
1672
daniel@transgaming.com38380882012-11-28 19:36:39 +00001673bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
1674 GLint xoffset, GLint yoffset, TextureStorage2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00001675{
1676 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
1677}
1678
daniel@transgaming.com38380882012-11-28 19:36:39 +00001679bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
1680 GLint xoffset, GLint yoffset, TextureStorageCubeMap *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00001681{
1682 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
1683}
1684
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001685bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
1686 bool blitRenderTarget, bool blitDepthStencil)
1687{
1688 endScene();
1689
1690 if (blitRenderTarget)
1691 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001692 gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer();
1693 gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer();
1694 RenderTarget9 *readRenderTarget = NULL;
1695 RenderTarget9 *drawRenderTarget = NULL;
1696 IDirect3DSurface9* readSurface = NULL;
1697 IDirect3DSurface9* drawSurface = NULL;
1698
1699 if (readBuffer)
1700 {
1701 readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
1702 }
1703 if (drawBuffer)
1704 {
1705 drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
1706 }
1707
1708 if (readRenderTarget)
1709 {
1710 readSurface = readRenderTarget->getSurface();
1711 }
1712 if (drawRenderTarget)
1713 {
1714 drawSurface = drawRenderTarget->getSurface();
1715 }
1716
1717 if (!readSurface || !drawSurface)
1718 {
1719 ERR("Failed to retrieve the render target.");
1720 return error(GL_OUT_OF_MEMORY, false);
1721 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001722
1723 RECT srcRect, dstRect;
1724 RECT *srcRectPtr = NULL;
1725 RECT *dstRectPtr = NULL;
1726
1727 if (readRect)
1728 {
1729 srcRect.left = readRect->x;
1730 srcRect.right = readRect->x + readRect->width;
1731 srcRect.top = readRect->y;
1732 srcRect.bottom = readRect->y + readRect->height;
1733 srcRectPtr = &srcRect;
1734 }
1735
1736 if (drawRect)
1737 {
1738 dstRect.left = drawRect->x;
1739 dstRect.right = drawRect->x + drawRect->width;
1740 dstRect.top = drawRect->y;
1741 dstRect.bottom = drawRect->y + drawRect->height;
1742 dstRectPtr = &dstRect;
1743 }
1744
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001745 HRESULT result = mDevice->StretchRect(readSurface, srcRectPtr, drawSurface, dstRectPtr, D3DTEXF_NONE);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001746
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001747 readSurface->Release();
1748 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001749
1750 if (FAILED(result))
1751 {
1752 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
1753 return false;
1754 }
1755 }
1756
1757 if (blitDepthStencil)
1758 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001759 gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
1760 gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
1761 RenderTarget9 *readDepthStencil = NULL;
1762 RenderTarget9 *drawDepthStencil = NULL;
1763 IDirect3DSurface9* readSurface = NULL;
1764 IDirect3DSurface9* drawSurface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001765
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001766 if (readBuffer)
1767 {
1768 readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
1769 }
1770 if (drawBuffer)
1771 {
1772 drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
1773 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001774
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001775 if (readDepthStencil)
1776 {
1777 readSurface = readDepthStencil->getSurface();
1778 }
1779 if (drawDepthStencil)
1780 {
1781 drawSurface = drawDepthStencil->getSurface();
1782 }
1783
1784 if (!readSurface || !drawSurface)
1785 {
1786 ERR("Failed to retrieve the render target.");
1787 return error(GL_OUT_OF_MEMORY, false);
1788 }
1789
1790 HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
1791
1792 readSurface->Release();
1793 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001794
1795 if (FAILED(result))
1796 {
1797 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
1798 return false;
1799 }
1800 }
1801
1802 return true;
1803}
1804
1805void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
1806 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
1807{
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001808 RenderTarget9 *renderTarget = NULL;
1809 IDirect3DSurface9 *surface = NULL;
1810 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
1811
1812 if (colorbuffer)
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001813 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001814 renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
1815 }
1816
1817 if (renderTarget)
1818 {
1819 surface = renderTarget->getSurface();
1820 }
1821
1822 if (!surface)
1823 {
1824 // context must be lost
1825 return;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001826 }
1827
1828 D3DSURFACE_DESC desc;
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001829 surface->GetDesc(&desc);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001830
1831 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
1832 {
1833 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001834 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001835 return error(GL_OUT_OF_MEMORY);
1836 }
1837
1838 HRESULT result;
1839 IDirect3DSurface9 *systemSurface = NULL;
1840 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
1841 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
1842 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
1843 if (directToPixels)
1844 {
1845 // Use the pixels ptr as a shared handle to write directly into client's memory
1846 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
1847 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
1848 if (FAILED(result))
1849 {
1850 // Try again without the shared handle
1851 directToPixels = false;
1852 }
1853 }
1854
1855 if (!directToPixels)
1856 {
1857 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
1858 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
1859 if (FAILED(result))
1860 {
1861 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001862 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001863 return error(GL_OUT_OF_MEMORY);
1864 }
1865 }
1866
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00001867 result = mDevice->GetRenderTargetData(surface, systemSurface);
1868 surface->Release();
1869 surface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00001870
1871 if (FAILED(result))
1872 {
1873 systemSurface->Release();
1874
1875 // It turns out that D3D will sometimes produce more error
1876 // codes than those documented.
1877 if (gl::checkDeviceLost(result))
1878 return error(GL_OUT_OF_MEMORY);
1879 else
1880 {
1881 UNREACHABLE();
1882 return;
1883 }
1884
1885 }
1886
1887 if (directToPixels)
1888 {
1889 systemSurface->Release();
1890 return;
1891 }
1892
1893 RECT rect;
1894 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
1895 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
1896 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
1897 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
1898
1899 D3DLOCKED_RECT lock;
1900 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
1901
1902 if (FAILED(result))
1903 {
1904 UNREACHABLE();
1905 systemSurface->Release();
1906
1907 return; // No sensible error to generate
1908 }
1909
1910 unsigned char *dest = (unsigned char*)pixels;
1911 unsigned short *dest16 = (unsigned short*)pixels;
1912
1913 unsigned char *source;
1914 int inputPitch;
1915 if (packReverseRowOrder)
1916 {
1917 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
1918 inputPitch = -lock.Pitch;
1919 }
1920 else
1921 {
1922 source = (unsigned char*)lock.pBits;
1923 inputPitch = lock.Pitch;
1924 }
1925
1926 unsigned int fastPixelSize = 0;
1927
1928 if (desc.Format == D3DFMT_A8R8G8B8 &&
1929 format == GL_BGRA_EXT &&
1930 type == GL_UNSIGNED_BYTE)
1931 {
1932 fastPixelSize = 4;
1933 }
1934 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
1935 format == GL_BGRA_EXT &&
1936 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
1937 (desc.Format == D3DFMT_A1R5G5B5 &&
1938 format == GL_BGRA_EXT &&
1939 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
1940 {
1941 fastPixelSize = 2;
1942 }
1943 else if (desc.Format == D3DFMT_A16B16G16R16F &&
1944 format == GL_RGBA &&
1945 type == GL_HALF_FLOAT_OES)
1946 {
1947 fastPixelSize = 8;
1948 }
1949 else if (desc.Format == D3DFMT_A32B32G32R32F &&
1950 format == GL_RGBA &&
1951 type == GL_FLOAT)
1952 {
1953 fastPixelSize = 16;
1954 }
1955
1956 for (int j = 0; j < rect.bottom - rect.top; j++)
1957 {
1958 if (fastPixelSize != 0)
1959 {
1960 // Fast path for formats which require no translation:
1961 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
1962 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
1963 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
1964 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
1965 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
1966 //
1967 // Note that buffers with no alpha go through the slow path below.
1968 memcpy(dest + j * outputPitch,
1969 source + j * inputPitch,
1970 (rect.right - rect.left) * fastPixelSize);
1971 continue;
1972 }
1973
1974 for (int i = 0; i < rect.right - rect.left; i++)
1975 {
1976 float r;
1977 float g;
1978 float b;
1979 float a;
1980
1981 switch (desc.Format)
1982 {
1983 case D3DFMT_R5G6B5:
1984 {
1985 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
1986
1987 a = 1.0f;
1988 b = (rgb & 0x001F) * (1.0f / 0x001F);
1989 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
1990 r = (rgb & 0xF800) * (1.0f / 0xF800);
1991 }
1992 break;
1993 case D3DFMT_A1R5G5B5:
1994 {
1995 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
1996
1997 a = (argb & 0x8000) ? 1.0f : 0.0f;
1998 b = (argb & 0x001F) * (1.0f / 0x001F);
1999 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2000 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2001 }
2002 break;
2003 case D3DFMT_A8R8G8B8:
2004 {
2005 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2006
2007 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2008 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2009 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2010 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2011 }
2012 break;
2013 case D3DFMT_X8R8G8B8:
2014 {
2015 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2016
2017 a = 1.0f;
2018 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2019 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2020 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2021 }
2022 break;
2023 case D3DFMT_A2R10G10B10:
2024 {
2025 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2026
2027 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2028 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2029 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2030 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2031 }
2032 break;
2033 case D3DFMT_A32B32G32R32F:
2034 {
2035 // float formats in D3D are stored rgba, rather than the other way round
2036 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2037 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2038 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2039 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2040 }
2041 break;
2042 case D3DFMT_A16B16G16R16F:
2043 {
2044 // float formats in D3D are stored rgba, rather than the other way round
2045 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2046 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2047 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2048 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
2049 }
2050 break;
2051 default:
2052 UNIMPLEMENTED(); // FIXME
2053 UNREACHABLE();
2054 return;
2055 }
2056
2057 switch (format)
2058 {
2059 case GL_RGBA:
2060 switch (type)
2061 {
2062 case GL_UNSIGNED_BYTE:
2063 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2064 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2065 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2066 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2067 break;
2068 default: UNREACHABLE();
2069 }
2070 break;
2071 case GL_BGRA_EXT:
2072 switch (type)
2073 {
2074 case GL_UNSIGNED_BYTE:
2075 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2076 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2077 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2078 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2079 break;
2080 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2081 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2082 // this type is packed as follows:
2083 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2084 // --------------------------------------------------------------------------------
2085 // | 4th | 3rd | 2nd | 1st component |
2086 // --------------------------------------------------------------------------------
2087 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2088 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2089 ((unsigned short)(15 * a + 0.5f) << 12)|
2090 ((unsigned short)(15 * r + 0.5f) << 8) |
2091 ((unsigned short)(15 * g + 0.5f) << 4) |
2092 ((unsigned short)(15 * b + 0.5f) << 0);
2093 break;
2094 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2095 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2096 // this type is packed as follows:
2097 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2098 // --------------------------------------------------------------------------------
2099 // | 4th | 3rd | 2nd | 1st component |
2100 // --------------------------------------------------------------------------------
2101 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2102 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2103 ((unsigned short)( a + 0.5f) << 15) |
2104 ((unsigned short)(31 * r + 0.5f) << 10) |
2105 ((unsigned short)(31 * g + 0.5f) << 5) |
2106 ((unsigned short)(31 * b + 0.5f) << 0);
2107 break;
2108 default: UNREACHABLE();
2109 }
2110 break;
2111 case GL_RGB:
2112 switch (type)
2113 {
2114 case GL_UNSIGNED_SHORT_5_6_5:
2115 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2116 ((unsigned short)(31 * b + 0.5f) << 0) |
2117 ((unsigned short)(63 * g + 0.5f) << 5) |
2118 ((unsigned short)(31 * r + 0.5f) << 11);
2119 break;
2120 case GL_UNSIGNED_BYTE:
2121 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2122 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2123 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2124 break;
2125 default: UNREACHABLE();
2126 }
2127 break;
2128 default: UNREACHABLE();
2129 }
2130 }
2131 }
2132
2133 systemSurface->UnlockRect();
2134
2135 systemSurface->Release();
2136}
2137
daniel@transgaming.comf2423652012-11-28 20:53:50 +00002138RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
2139{
2140 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2141 IDirect3DSurface9 *surface = NULL;
2142 if (depth)
2143 {
2144 surface = swapChain9->getDepthStencil();
2145 }
2146 else
2147 {
2148 surface = swapChain9->getRenderTarget();
2149 }
2150
2151 RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
2152
2153 return renderTarget;
2154}
2155
2156RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
2157{
2158 RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
2159 return renderTarget;
2160}
2161
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002162bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
2163{
2164 return mBlit->boxFilter(source, dest);
2165}
2166
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002167D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002168{
2169 if (mD3d9Ex != NULL)
2170 {
2171 return D3DPOOL_DEFAULT;
2172 }
2173 else
2174 {
2175 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2176 {
2177 return D3DPOOL_MANAGED;
2178 }
2179 }
2180
2181 return D3DPOOL_DEFAULT;
2182}
2183
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002184bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
2185{
2186 if (source && dest)
2187 {
2188 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
2189 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
2190
2191 if (fromManaged)
2192 {
2193 D3DSURFACE_DESC desc;
2194 source->GetDesc(&desc);
2195
2196 IDirect3DSurface9 *surf = 0;
2197 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
2198
2199 if (SUCCEEDED(result))
2200 {
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002201 Image::CopyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002202 result = device->UpdateSurface(surf, NULL, dest, NULL);
2203 surf->Release();
2204 }
2205 }
2206 else
2207 {
2208 endScene();
2209 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
2210 }
2211
2212 if (FAILED(result))
2213 {
2214 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2215 return false;
2216 }
2217 }
2218
2219 return true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00002220}
2221
2222VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
2223{
2224 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
2225 {
2226 mVertexDeclCache[i].vertexDeclaration = NULL;
2227 mVertexDeclCache[i].lruCount = 0;
2228 }
2229
2230 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2231 {
2232 mAppliedVBs[i].serial = 0;
2233 }
2234
2235 mLastSetVDecl = NULL;
2236 mInstancingEnabled = true;
2237}
2238
2239VertexDeclarationCache::~VertexDeclarationCache()
2240{
2241 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
2242 {
2243 if (mVertexDeclCache[i].vertexDeclaration)
2244 {
2245 mVertexDeclCache[i].vertexDeclaration->Release();
2246 }
2247 }
2248}
2249
2250GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, gl::TranslatedAttribute attributes[], gl::ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw)
2251{
2252 *repeatDraw = 1;
2253
2254 int indexedAttribute = gl::MAX_VERTEX_ATTRIBS;
2255 int instancedAttribute = gl::MAX_VERTEX_ATTRIBS;
2256
2257 if (instances > 0)
2258 {
2259 // Find an indexed attribute to be mapped to D3D stream 0
2260 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2261 {
2262 if (attributes[i].active)
2263 {
2264 if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS)
2265 {
2266 if (attributes[i].divisor == 0)
2267 {
2268 indexedAttribute = i;
2269 }
2270 }
2271 else if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
2272 {
2273 if (attributes[i].divisor != 0)
2274 {
2275 instancedAttribute = i;
2276 }
2277 }
2278 else break; // Found both an indexed and instanced attribute
2279 }
2280 }
2281
2282 if (indexedAttribute == gl::MAX_VERTEX_ATTRIBS)
2283 {
2284 return GL_INVALID_OPERATION;
2285 }
2286 }
2287
2288 D3DVERTEXELEMENT9 elements[gl::MAX_VERTEX_ATTRIBS + 1];
2289 D3DVERTEXELEMENT9 *element = &elements[0];
2290
2291 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2292 {
2293 if (attributes[i].active)
2294 {
2295 int stream = i;
2296
2297 if (instances > 0)
2298 {
2299 // Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
2300 if (instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
2301 {
2302 *repeatDraw = instances;
2303 }
2304 else
2305 {
2306 if (i == indexedAttribute)
2307 {
2308 stream = 0;
2309 }
2310 else if (i == 0)
2311 {
2312 stream = indexedAttribute;
2313 }
2314
2315 UINT frequency = 1;
2316
2317 if (attributes[i].divisor == 0)
2318 {
2319 frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
2320 }
2321 else
2322 {
2323 frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
2324 }
2325
2326 device->SetStreamSourceFreq(stream, frequency);
2327 mInstancingEnabled = true;
2328 }
2329 }
2330
2331 if (mAppliedVBs[stream].serial != attributes[i].serial ||
2332 mAppliedVBs[stream].stride != attributes[i].stride ||
2333 mAppliedVBs[stream].offset != attributes[i].offset)
2334 {
2335 device->SetStreamSource(stream, attributes[i].vertexBuffer, attributes[i].offset, attributes[i].stride);
2336 mAppliedVBs[stream].serial = attributes[i].serial;
2337 mAppliedVBs[stream].stride = attributes[i].stride;
2338 mAppliedVBs[stream].offset = attributes[i].offset;
2339 }
2340
2341 element->Stream = stream;
2342 element->Offset = 0;
2343 element->Type = attributes[i].type;
2344 element->Method = D3DDECLMETHOD_DEFAULT;
2345 element->Usage = D3DDECLUSAGE_TEXCOORD;
2346 element->UsageIndex = programBinary->getSemanticIndex(i);
2347 element++;
2348 }
2349 }
2350
2351 if (instances == 0 || instancedAttribute == gl::MAX_VERTEX_ATTRIBS)
2352 {
2353 if (mInstancingEnabled)
2354 {
2355 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2356 {
2357 device->SetStreamSourceFreq(i, 1);
2358 }
2359
2360 mInstancingEnabled = false;
2361 }
2362 }
2363
2364 static const D3DVERTEXELEMENT9 end = D3DDECL_END();
2365 *(element++) = end;
2366
2367 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
2368 {
2369 VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
2370 if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
2371 {
2372 entry->lruCount = ++mMaxLru;
2373 if(entry->vertexDeclaration != mLastSetVDecl)
2374 {
2375 device->SetVertexDeclaration(entry->vertexDeclaration);
2376 mLastSetVDecl = entry->vertexDeclaration;
2377 }
2378
2379 return GL_NO_ERROR;
2380 }
2381 }
2382
2383 VertexDeclCacheEntry *lastCache = mVertexDeclCache;
2384
2385 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
2386 {
2387 if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
2388 {
2389 lastCache = &mVertexDeclCache[i];
2390 }
2391 }
2392
2393 if (lastCache->vertexDeclaration != NULL)
2394 {
2395 lastCache->vertexDeclaration->Release();
2396 lastCache->vertexDeclaration = NULL;
2397 // mLastSetVDecl is set to the replacement, so we don't have to worry
2398 // about it.
2399 }
2400
2401 memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
2402 device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
2403 device->SetVertexDeclaration(lastCache->vertexDeclaration);
2404 mLastSetVDecl = lastCache->vertexDeclaration;
2405 lastCache->lruCount = ++mMaxLru;
2406
2407 return GL_NO_ERROR;
2408}
2409
2410void VertexDeclarationCache::markStateDirty()
2411{
2412 for (int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
2413 {
2414 mAppliedVBs[i].serial = 0;
2415 }
2416
2417 mLastSetVDecl = NULL;
2418 mInstancingEnabled = true; // Forces it to be disabled when not used
2419}
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002420
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002421}