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