blob: 786bc69083998fbee183130e93c1d17140e4a778 [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.com50aadb02012-11-28 21:06:11 +000017#include "libGLESv2/renderer/IndexDataManager.h"
18#include "libGLESv2/renderer/VertexDataManager.h"
daniel@transgaming.com2507f412012-10-31 18:46:48 +000019#include "libGLESv2/renderer/Renderer9.h"
daniel@transgaming.comd8e36562012-10-31 19:52:19 +000020#include "libGLESv2/renderer/renderer9_utils.h"
daniel@transgaming.coma9c71422012-11-28 20:58:45 +000021#include "libGLESv2/renderer/ShaderExecutable9.h"
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +000022#include "libGLESv2/renderer/SwapChain9.h"
daniel@transgaming.com34da3972012-12-20 21:10:29 +000023#include "libGLESv2/renderer/TextureStorage9.h"
daniel@transgaming.com4ba24062012-12-20 20:54:24 +000024#include "libGLESv2/renderer/Image9.h"
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000025#include "libGLESv2/renderer/Blit.h"
daniel@transgaming.comd186dc72012-11-28 19:40:16 +000026#include "libGLESv2/renderer/RenderTarget9.h"
daniel@transgaming.com3f255b42012-12-20 21:07:35 +000027#include "libGLESv2/renderer/VertexBuffer9.h"
daniel@transgaming.com0b6d7742012-12-20 21:09:47 +000028#include "libGLESv2/renderer/IndexBuffer9.h"
daniel@transgaming.com621ce052012-10-31 17:52:29 +000029
daniel@transgaming.com3281f972012-10-31 18:38:51 +000030#include "libEGL/Config.h"
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000031#include "libEGL/Display.h"
32
daniel@transgaming.com621ce052012-10-31 17:52:29 +000033// Can also be enabled by defining FORCE_REF_RAST in the project's predefined macros
34#define REF_RAST 0
35
36// The "Debug This Pixel..." feature in PIX often fails when using the
37// D3D9Ex interfaces. In order to get debug pixel to work on a Vista/Win 7
38// machine, define "ANGLE_ENABLE_D3D9EX=0" in your project file.
39#if !defined(ANGLE_ENABLE_D3D9EX)
40// Enables use of the IDirect3D9Ex interface, when available
41#define ANGLE_ENABLE_D3D9EX 1
42#endif // !defined(ANGLE_ENABLE_D3D9EX)
43
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +000044namespace rx
daniel@transgaming.com621ce052012-10-31 17:52:29 +000045{
daniel@transgaming.com222ee082012-11-28 19:31:49 +000046static const D3DFORMAT RenderTargetFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000047 {
48 D3DFMT_A1R5G5B5,
49 // D3DFMT_A2R10G10B10, // The color_ramp conformance test uses ReadPixels with UNSIGNED_BYTE causing it to think that rendering skipped a colour value.
50 D3DFMT_A8R8G8B8,
51 D3DFMT_R5G6B5,
52 // D3DFMT_X1R5G5B5, // Has no compatible OpenGL ES renderbuffer format
53 D3DFMT_X8R8G8B8
54 };
55
daniel@transgaming.com222ee082012-11-28 19:31:49 +000056static const D3DFORMAT DepthStencilFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000057 {
58 D3DFMT_UNKNOWN,
59 // D3DFMT_D16_LOCKABLE,
60 D3DFMT_D32,
61 // D3DFMT_D15S1,
62 D3DFMT_D24S8,
63 D3DFMT_D24X8,
64 // D3DFMT_D24X4S4,
65 D3DFMT_D16,
66 // D3DFMT_D32F_LOCKABLE,
67 // D3DFMT_D24FS8
68 };
daniel@transgaming.com621ce052012-10-31 17:52:29 +000069
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000070Renderer9::Renderer9(egl::Display *display, HDC hDc, bool softwareDevice) : Renderer(display), mDc(hDc), mSoftwareDevice(softwareDevice)
daniel@transgaming.com621ce052012-10-31 17:52:29 +000071{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000072 mD3d9Module = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000073
74 mD3d9 = NULL;
75 mD3d9Ex = NULL;
76 mDevice = NULL;
77 mDeviceEx = NULL;
78 mDeviceWindow = NULL;
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000079 mBlit = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000080
81 mAdapter = D3DADAPTER_DEFAULT;
82
83 #if REF_RAST == 1 || defined(FORCE_REF_RAST)
84 mDeviceType = D3DDEVTYPE_REF;
85 #else
86 mDeviceType = D3DDEVTYPE_HAL;
87 #endif
88
89 mDeviceLost = false;
daniel@transgaming.comb7833982012-10-31 18:31:46 +000090
91 mMaxSupportedSamples = 0;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +000092
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +000093 mMaskedClearSavedState = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +000094
95 mVertexDataManager = NULL;
96 mIndexDataManager = NULL;
97 mLineLoopIB = NULL;
daniel@transgaming.come4e1a332012-12-20 20:52:09 +000098
99 mMaxNullColorbufferLRU = 0;
100 for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
101 {
102 mNullColorbufferCache[i].lruCount = 0;
103 mNullColorbufferCache[i].width = 0;
104 mNullColorbufferCache[i].height = 0;
105 mNullColorbufferCache[i].buffer = NULL;
106 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000107}
108
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000109Renderer9::~Renderer9()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000110{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000111 releaseDeviceResources();
112
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000113 if (mDevice)
114 {
115 // If the device is lost, reset it first to prevent leaving the driver in an unstable state
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000116 if (testDeviceLost(false))
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000117 {
118 resetDevice();
119 }
120
121 mDevice->Release();
122 mDevice = NULL;
123 }
124
125 if (mDeviceEx)
126 {
127 mDeviceEx->Release();
128 mDeviceEx = NULL;
129 }
130
131 if (mD3d9)
132 {
133 mD3d9->Release();
134 mD3d9 = NULL;
135 }
136
137 if (mDeviceWindow)
138 {
139 DestroyWindow(mDeviceWindow);
140 mDeviceWindow = NULL;
141 }
142
143 if (mD3d9Ex)
144 {
145 mD3d9Ex->Release();
146 mD3d9Ex = NULL;
147 }
148
149 if (mD3d9Module)
150 {
151 mD3d9Module = NULL;
152 }
153
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000154 while (!mMultiSampleSupport.empty())
155 {
156 delete [] mMultiSampleSupport.begin()->second;
157 mMultiSampleSupport.erase(mMultiSampleSupport.begin());
158 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000159}
160
daniel@transgaming.comb64ed282012-11-28 20:54:02 +0000161Renderer9 *Renderer9::makeRenderer9(Renderer *renderer)
162{
163 ASSERT(dynamic_cast<rx::Renderer9*>(renderer) != NULL);
164 return static_cast<rx::Renderer9*>(renderer);
165}
166
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000167EGLint Renderer9::initialize()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000168{
daniel@transgaming.com25e16af2012-11-28 21:05:57 +0000169 if (!initializeCompiler())
170 {
171 return EGL_NOT_INITIALIZED;
172 }
173
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +0000174 if (mSoftwareDevice)
175 {
176 mD3d9Module = GetModuleHandle(TEXT("swiftshader_d3d9.dll"));
177 }
178 else
179 {
180 mD3d9Module = GetModuleHandle(TEXT("d3d9.dll"));
181 }
182
183 if (mD3d9Module == NULL)
184 {
185 ERR("No D3D9 module found - aborting!\n");
186 return EGL_NOT_INITIALIZED;
187 }
188
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000189 typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex**);
190 Direct3DCreate9ExFunc Direct3DCreate9ExPtr = reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
191
192 // Use Direct3D9Ex if available. Among other things, this version is less
193 // inclined to report a lost context, for example when the user switches
194 // desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are available.
195 if (ANGLE_ENABLE_D3D9EX && Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9Ex)))
196 {
197 ASSERT(mD3d9Ex);
198 mD3d9Ex->QueryInterface(IID_IDirect3D9, reinterpret_cast<void**>(&mD3d9));
199 ASSERT(mD3d9);
200 }
201 else
202 {
203 mD3d9 = Direct3DCreate9(D3D_SDK_VERSION);
204 }
205
206 if (!mD3d9)
207 {
208 ERR("Could not create D3D9 device - aborting!\n");
209 return EGL_NOT_INITIALIZED;
210 }
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000211
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000212 if (mDc != NULL)
213 {
214 // UNIMPLEMENTED(); // FIXME: Determine which adapter index the device context corresponds to
215 }
216
217 HRESULT result;
218
219 // Give up on getting device caps after about one second.
220 for (int i = 0; i < 10; ++i)
221 {
222 result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);
223 if (SUCCEEDED(result))
224 {
225 break;
226 }
227 else if (result == D3DERR_NOTAVAILABLE)
228 {
229 Sleep(100); // Give the driver some time to initialize/recover
230 }
231 else if (FAILED(result)) // D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY, D3DERR_INVALIDDEVICE, or another error we can't recover from
232 {
233 ERR("failed to get device caps (0x%x)\n", result);
234 return EGL_NOT_INITIALIZED;
235 }
236 }
237
238 if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
239 {
240 ERR("Renderer does not support PS 2.0. aborting!\n");
241 return EGL_NOT_INITIALIZED;
242 }
243
244 // When DirectX9 is running with an older DirectX8 driver, a StretchRect from a regular texture to a render target texture is not supported.
245 // This is required by Texture2D::convertToRenderTarget.
246 if ((mDeviceCaps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) == 0)
247 {
248 ERR("Renderer does not support stretctrect from textures!\n");
249 return EGL_NOT_INITIALIZED;
250 }
251
252 mD3d9->GetAdapterIdentifier(mAdapter, 0, &mAdapterIdentifier);
253
254 // ATI cards on XP have problems with non-power-of-two textures.
255 mSupportsNonPower2Textures = !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_POW2) &&
256 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP_POW2) &&
257 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) &&
258 !(getComparableOSVersion() < versionWindowsVista && mAdapterIdentifier.VendorId == VENDOR_ID_AMD);
259
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000260 // Must support a minimum of 2:1 anisotropy for max anisotropy to be considered supported, per the spec
261 mSupportsTextureFilterAnisotropy = ((mDeviceCaps.RasterCaps & D3DPRASTERCAPS_ANISOTROPY) && (mDeviceCaps.MaxAnisotropy >= 2));
262
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000263 mMinSwapInterval = 4;
264 mMaxSwapInterval = 0;
265
266 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE)
267 {
268 mMinSwapInterval = std::min(mMinSwapInterval, 0);
269 mMaxSwapInterval = std::max(mMaxSwapInterval, 0);
270 }
271 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)
272 {
273 mMinSwapInterval = std::min(mMinSwapInterval, 1);
274 mMaxSwapInterval = std::max(mMaxSwapInterval, 1);
275 }
276 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)
277 {
278 mMinSwapInterval = std::min(mMinSwapInterval, 2);
279 mMaxSwapInterval = std::max(mMaxSwapInterval, 2);
280 }
281 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)
282 {
283 mMinSwapInterval = std::min(mMinSwapInterval, 3);
284 mMaxSwapInterval = std::max(mMaxSwapInterval, 3);
285 }
286 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)
287 {
288 mMinSwapInterval = std::min(mMinSwapInterval, 4);
289 mMaxSwapInterval = std::max(mMaxSwapInterval, 4);
290 }
291
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000292 int max = 0;
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000293 for (int i = 0; i < sizeof(RenderTargetFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000294 {
295 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000296 getMultiSampleSupport(RenderTargetFormats[i], multisampleArray);
297 mMultiSampleSupport[RenderTargetFormats[i]] = multisampleArray;
daniel@transgaming.com92955622012-10-31 18:38:41 +0000298
299 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
300 {
301 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
302 {
303 max = j;
304 }
305 }
306 }
307
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000308 for (int i = 0; i < sizeof(DepthStencilFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000309 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000310 if (DepthStencilFormats[i] == D3DFMT_UNKNOWN)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000311 continue;
312
313 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000314 getMultiSampleSupport(DepthStencilFormats[i], multisampleArray);
315 mMultiSampleSupport[DepthStencilFormats[i]] = multisampleArray;
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000316
317 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
318 {
319 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
320 {
321 max = j;
322 }
323 }
324 }
325
326 mMaxSupportedSamples = max;
327
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000328 static const TCHAR windowName[] = TEXT("AngleHiddenWindow");
329 static const TCHAR className[] = TEXT("STATIC");
330
331 mDeviceWindow = CreateWindowEx(WS_EX_NOACTIVATE, className, windowName, WS_DISABLED | WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
332
333 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
334 DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE | D3DCREATE_NOWINDOWCHANGES;
335
336 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE, &presentParameters, &mDevice);
337 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DEVICELOST)
338 {
339 return EGL_BAD_ALLOC;
340 }
341
342 if (FAILED(result))
343 {
344 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &presentParameters, &mDevice);
345
346 if (FAILED(result))
347 {
348 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_NOTAVAILABLE || result == D3DERR_DEVICELOST);
349 return EGL_BAD_ALLOC;
350 }
351 }
352
353 if (mD3d9Ex)
354 {
355 result = mDevice->QueryInterface(IID_IDirect3DDevice9Ex, (void**) &mDeviceEx);
356 ASSERT(SUCCEEDED(result));
357 }
358
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000359 mVertexShaderCache.initialize(mDevice);
360 mPixelShaderCache.initialize(mDevice);
361
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000362 initializeDevice();
363
364 return EGL_SUCCESS;
365}
366
367// do any one-time device initialization
368// NOTE: this is also needed after a device lost/reset
369// to reset the scene status and ensure the default states are reset.
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000370void Renderer9::initializeDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000371{
372 // Permanent non-default states
373 mDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
374 mDevice->SetRenderState(D3DRS_LASTPIXEL, FALSE);
375
376 if (mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0))
377 {
378 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, (DWORD&)mDeviceCaps.MaxPointSize);
379 }
380 else
381 {
382 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, 0x3F800000); // 1.0f
383 }
384
daniel@transgaming.comc43a6052012-11-28 19:41:51 +0000385 markAllStateDirty();
386
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000387 mSceneStarted = false;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +0000388
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000389 ASSERT(!mBlit && !mVertexDataManager && !mIndexDataManager);
daniel@transgaming.come569fc52012-11-28 20:56:02 +0000390 mBlit = new Blit(this);
daniel@transgaming.com31240482012-11-28 21:06:41 +0000391 mVertexDataManager = new rx::VertexDataManager(this);
392 mIndexDataManager = new rx::IndexDataManager(this);
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000393}
394
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000395D3DPRESENT_PARAMETERS Renderer9::getDefaultPresentParameters()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000396{
397 D3DPRESENT_PARAMETERS presentParameters = {0};
398
399 // The default swap chain is never actually used. Surface will create a new swap chain with the proper parameters.
400 presentParameters.AutoDepthStencilFormat = D3DFMT_UNKNOWN;
401 presentParameters.BackBufferCount = 1;
402 presentParameters.BackBufferFormat = D3DFMT_UNKNOWN;
403 presentParameters.BackBufferWidth = 1;
404 presentParameters.BackBufferHeight = 1;
405 presentParameters.EnableAutoDepthStencil = FALSE;
406 presentParameters.Flags = 0;
407 presentParameters.hDeviceWindow = mDeviceWindow;
408 presentParameters.MultiSampleQuality = 0;
409 presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE;
410 presentParameters.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
411 presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
412 presentParameters.Windowed = TRUE;
413
414 return presentParameters;
415}
416
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000417int Renderer9::generateConfigs(ConfigDesc **configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000418{
419 D3DDISPLAYMODE currentDisplayMode;
420 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
421
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000422 unsigned int numRenderFormats = sizeof(RenderTargetFormats) / sizeof(RenderTargetFormats[0]);
423 unsigned int numDepthFormats = sizeof(DepthStencilFormats) / sizeof(DepthStencilFormats[0]);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000424 (*configDescList) = new ConfigDesc[numRenderFormats * numDepthFormats];
425 int numConfigs = 0;
426
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000427 for (unsigned int formatIndex = 0; formatIndex < numRenderFormats; formatIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000428 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000429 D3DFORMAT renderTargetFormat = RenderTargetFormats[formatIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000430
431 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, renderTargetFormat);
432
433 if (SUCCEEDED(result))
434 {
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000435 for (unsigned int depthStencilIndex = 0; depthStencilIndex < numDepthFormats; depthStencilIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000436 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000437 D3DFORMAT depthStencilFormat = DepthStencilFormats[depthStencilIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000438 HRESULT result = D3D_OK;
439
440 if(depthStencilFormat != D3DFMT_UNKNOWN)
441 {
442 result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFormat);
443 }
444
445 if (SUCCEEDED(result))
446 {
447 if(depthStencilFormat != D3DFMT_UNKNOWN)
448 {
449 result = mD3d9->CheckDepthStencilMatch(mAdapter, mDeviceType, currentDisplayMode.Format, renderTargetFormat, depthStencilFormat);
450 }
451
452 if (SUCCEEDED(result))
453 {
454 ConfigDesc newConfig;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000455 newConfig.renderTargetFormat = d3d9_gl::ConvertBackBufferFormat(renderTargetFormat);
456 newConfig.depthStencilFormat = d3d9_gl::ConvertDepthStencilFormat(depthStencilFormat);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000457 newConfig.multiSample = 0; // FIXME: enumerate multi-sampling
458 newConfig.fastConfig = (currentDisplayMode.Format == renderTargetFormat);
459
460 (*configDescList)[numConfigs++] = newConfig;
461 }
462 }
463 }
464 }
465 }
466
467 return numConfigs;
468}
469
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000470void Renderer9::deleteConfigs(ConfigDesc *configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000471{
472 delete [] (configDescList);
473}
474
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000475void Renderer9::startScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000476{
477 if (!mSceneStarted)
478 {
479 long result = mDevice->BeginScene();
480 if (SUCCEEDED(result)) {
481 // This is defensive checking against the device being
482 // lost at unexpected times.
483 mSceneStarted = true;
484 }
485 }
486}
487
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000488void Renderer9::endScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000489{
490 if (mSceneStarted)
491 {
492 // EndScene can fail if the device was lost, for example due
493 // to a TDR during a draw call.
494 mDevice->EndScene();
495 mSceneStarted = false;
496 }
497}
498
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000499// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000500void Renderer9::sync(bool block)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000501{
502 HRESULT result;
503
504 IDirect3DQuery9* query = allocateEventQuery();
505 if (!query)
506 {
507 return;
508 }
509
510 result = query->Issue(D3DISSUE_END);
511 ASSERT(SUCCEEDED(result));
512
513 do
514 {
515 result = query->GetData(NULL, 0, D3DGETDATA_FLUSH);
516
517 if(block && result == S_FALSE)
518 {
519 // Keep polling, but allow other threads to do something useful first
520 Sleep(0);
521 // explicitly check for device loss
522 // some drivers seem to return S_FALSE even if the device is lost
523 // instead of D3DERR_DEVICELOST like they should
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000524 if (testDeviceLost(false))
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000525 {
526 result = D3DERR_DEVICELOST;
527 }
528 }
529 }
530 while(block && result == S_FALSE);
531
532 freeEventQuery(query);
533
534 if (isDeviceLostError(result))
535 {
536 mDisplay->notifyDeviceLost();
537 }
538}
539
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000540SwapChain *Renderer9::createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
541{
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +0000542 return new rx::SwapChain9(this, window, shareHandle, backBufferFormat, depthBufferFormat);
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000543}
544
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000545// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000546IDirect3DQuery9* Renderer9::allocateEventQuery()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000547{
548 IDirect3DQuery9 *query = NULL;
549
550 if (mEventQueryPool.empty())
551 {
552 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &query);
553 ASSERT(SUCCEEDED(result));
554 }
555 else
556 {
557 query = mEventQueryPool.back();
558 mEventQueryPool.pop_back();
559 }
560
561 return query;
562}
563
564// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000565void Renderer9::freeEventQuery(IDirect3DQuery9* query)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000566{
567 if (mEventQueryPool.size() > 1000)
568 {
569 query->Release();
570 }
571 else
572 {
573 mEventQueryPool.push_back(query);
574 }
575}
576
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000577IDirect3DVertexShader9 *Renderer9::createVertexShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000578{
579 return mVertexShaderCache.create(function, length);
580}
581
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000582IDirect3DPixelShader9 *Renderer9::createPixelShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000583{
584 return mPixelShaderCache.create(function, length);
585}
586
daniel@transgaming.com113f0eb2012-10-31 18:46:58 +0000587HRESULT Renderer9::createVertexBuffer(UINT Length, DWORD Usage, IDirect3DVertexBuffer9 **ppVertexBuffer)
588{
589 D3DPOOL Pool = getBufferPool(Usage);
590 return mDevice->CreateVertexBuffer(Length, Usage, 0, Pool, ppVertexBuffer, NULL);
591}
592
daniel@transgaming.com3f255b42012-12-20 21:07:35 +0000593VertexBuffer *Renderer9::createVertexBuffer()
594{
595 return new VertexBuffer9(this);
596}
597
daniel@transgaming.com113f0eb2012-10-31 18:46:58 +0000598HRESULT Renderer9::createIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, IDirect3DIndexBuffer9 **ppIndexBuffer)
599{
600 D3DPOOL Pool = getBufferPool(Usage);
601 return mDevice->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, NULL);
602}
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000603
daniel@transgaming.com0b6d7742012-12-20 21:09:47 +0000604IndexBuffer *Renderer9::createIndexBuffer()
605{
606 return new IndexBuffer9(this);
607}
608
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000609void Renderer9::setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &samplerState)
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000610{
611 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
612 int d3dSampler = index + d3dSamplerOffset;
613
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000614 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSU, gl_d3d9::ConvertTextureWrap(samplerState.wrapS));
615 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSV, gl_d3d9::ConvertTextureWrap(samplerState.wrapT));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000616
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000617 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAGFILTER, gl_d3d9::ConvertMagFilter(samplerState.magFilter, samplerState.maxAnisotropy));
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000618 D3DTEXTUREFILTERTYPE d3dMinFilter, d3dMipFilter;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000619 gl_d3d9::ConvertMinFilter(samplerState.minFilter, &d3dMinFilter, &d3dMipFilter, samplerState.maxAnisotropy);
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000620 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MINFILTER, d3dMinFilter);
621 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPFILTER, d3dMipFilter);
622 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXMIPLEVEL, samplerState.lodOffset);
623 if (mSupportsTextureFilterAnisotropy)
624 {
625 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, (DWORD)samplerState.maxAnisotropy);
626 }
627}
628
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000629void Renderer9::setTexture(gl::SamplerType type, int index, gl::Texture *texture)
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000630{
631 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
632 int d3dSampler = index + d3dSamplerOffset;
633 IDirect3DBaseTexture9 *d3dTexture = NULL;
634
635 if (texture)
636 {
daniel@transgaming.com87705f82012-12-20 21:10:45 +0000637 TextureStorageInterface *texStorage = texture->getNativeTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000638 if (texStorage)
639 {
daniel@transgaming.com87705f82012-12-20 21:10:45 +0000640 TextureStorage9 *storage9 = TextureStorage9::makeTextureStorage9(texStorage->getStorageInstance());
daniel@transgaming.com34da3972012-12-20 21:10:29 +0000641 d3dTexture = storage9->getBaseTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000642 }
643 // If we get NULL back from getBaseTexture here, something went wrong
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000644 // in the texture class and we're unexpectedly missing the d3d texture
645 ASSERT(d3dTexture != NULL);
646 }
647
648 mDevice->SetTexture(d3dSampler, d3dTexture);
649}
650
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000651void Renderer9::setRasterizerState(const gl::RasterizerState &rasterState)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000652{
653 bool rasterStateChanged = mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000654
655 if (rasterStateChanged)
656 {
657 // Set the cull mode
658 if (rasterState.cullFace)
659 {
660 mDevice->SetRenderState(D3DRS_CULLMODE, gl_d3d9::ConvertCullMode(rasterState.cullMode, rasterState.frontFace));
661 }
662 else
663 {
664 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
665 }
666
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000667 if (rasterState.polygonOffsetFill)
668 {
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000669 if (mCurDepthSize > 0)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000670 {
671 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
672
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000673 float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(mCurDepthSize));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000674 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
675 }
676 }
677 else
678 {
679 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
680 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
681 }
682
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000683 mCurRasterState = rasterState;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000684 }
685
686 mForceSetRasterState = false;
687}
688
689void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
690{
691 bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
692 bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
693 bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
694
695 if (blendStateChanged || blendColorChanged)
696 {
697 if (blendState.blend)
698 {
699 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
700
701 if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
702 blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
703 {
704 mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
705 }
706 else
707 {
708 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
709 gl::unorm<8>(blendColor.alpha),
710 gl::unorm<8>(blendColor.alpha),
711 gl::unorm<8>(blendColor.alpha)));
712 }
713
714 mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
715 mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
716 mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
717
718 if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
719 blendState.destBlendRGB != blendState.destBlendAlpha ||
720 blendState.blendEquationRGB != blendState.blendEquationAlpha)
721 {
722 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
723
724 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
725 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
726 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
727 }
728 else
729 {
730 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
731 }
732 }
733 else
734 {
735 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
736 }
737
738 if (blendState.sampleAlphaToCoverage)
739 {
740 FIXME("Sample alpha to coverage is unimplemented.");
741 }
742
743 // Set the color mask
744 bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
745 // Apparently some ATI cards have a bug where a draw with a zero color
746 // write mask can cause later draws to have incorrect results. Instead,
747 // set a nonzero color write mask but modify the blend state so that no
748 // drawing is done.
749 // http://code.google.com/p/angleproject/issues/detail?id=169
750
751 DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
752 blendState.colorMaskBlue, blendState.colorMaskAlpha);
753 if (colorMask == 0 && !zeroColorMaskAllowed)
754 {
755 // Enable green channel, but set blending so nothing will be drawn.
756 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
757 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
758
759 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
760 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
761 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
762 }
763 else
764 {
765 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
766 }
767
768 mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
769
770 mCurBlendState = blendState;
771 mCurBlendColor = blendColor;
772 }
773
774 if (sampleMaskChanged)
775 {
776 // Set the multisample mask
777 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
778 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
779
780 mCurSampleMask = sampleMask;
781 }
782
783 mForceSetBlendState = false;
784}
785
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000786void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000787 int stencilBackRef, bool frontFaceCCW)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000788{
789 bool depthStencilStateChanged = mForceSetDepthStencilState ||
790 memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000791 bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
792 stencilBackRef != mCurStencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000793 bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000794
795 if (depthStencilStateChanged)
796 {
797 if (depthStencilState.depthTest)
798 {
799 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
800 mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
801 }
802 else
803 {
804 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
805 }
806
807 mCurDepthStencilState = depthStencilState;
808 }
809
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000810 if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000811 {
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000812 if (depthStencilState.stencilTest && mCurStencilSize > 0)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000813 {
814 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
815 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
816
817 // FIXME: Unsupported by D3D9
818 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
819 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
820 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
821 if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000822 stencilRef != stencilBackRef ||
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000823 depthStencilState.stencilMask != depthStencilState.stencilBackMask)
824 {
825 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
826 return error(GL_INVALID_OPERATION);
827 }
828
829 // get the maximum size of the stencil ref
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000830 unsigned int maxStencil = (1 << mCurStencilSize) - 1;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000831
832 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
833 depthStencilState.stencilWritemask);
834 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
835 gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
836
837 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000838 (stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000839 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
840 depthStencilState.stencilMask);
841
842 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
843 gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
844 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
845 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
846 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
847 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
848
849 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
850 depthStencilState.stencilBackWritemask);
851 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
852 gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
853
854 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000855 (stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000856 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
857 depthStencilState.stencilBackMask);
858
859 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
860 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
861 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
862 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
863 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
864 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
865 }
866 else
867 {
868 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
869 }
870
871 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
872
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000873 mCurStencilRef = stencilRef;
874 mCurStencilBackRef = stencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000875 mCurFrontFaceCCW = frontFaceCCW;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000876 }
877
878 mForceSetDepthStencilState = false;
879}
880
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000881void Renderer9::setScissorRectangle(const gl::Rectangle &scissor, bool enabled)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000882{
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000883 bool scissorChanged = mForceSetScissor ||
884 memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0 ||
885 enabled != mScissorEnabled;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000886
daniel@transgaming.com04f1b332012-11-28 21:00:40 +0000887 if (scissorChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000888 {
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000889 if (enabled)
890 {
891 RECT rect;
892 rect.left = gl::clamp(scissor.x, 0, static_cast<int>(mRenderTargetDesc.width));
893 rect.top = gl::clamp(scissor.y, 0, static_cast<int>(mRenderTargetDesc.height));
894 rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(mRenderTargetDesc.width));
895 rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(mRenderTargetDesc.height));
896 mDevice->SetScissorRect(&rect);
897 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000898
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000899 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, enabled ? TRUE : FALSE);
900
901 mScissorEnabled = enabled;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000902 mCurScissor = scissor;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000903 }
904
905 mForceSetScissor = false;
906}
907
daniel@transgaming.com12985182012-12-20 20:56:31 +0000908bool Renderer9::setViewport(const gl::Rectangle &viewport, float zNear, float zFar, GLenum drawMode, GLenum frontFace,
909 bool ignoreViewport, gl::ProgramBinary *currentProgram, bool forceSetUniforms)
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000910{
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000911 gl::Rectangle actualViewport = viewport;
912 float actualZNear = gl::clamp01(zNear);
913 float actualZFar = gl::clamp01(zFar);
914 if (ignoreViewport)
915 {
916 actualViewport.x = 0;
917 actualViewport.y = 0;
918 actualViewport.width = mRenderTargetDesc.width;
919 actualViewport.height = mRenderTargetDesc.height;
920 actualZNear = 0.0f;
921 actualZFar = 1.0f;
922 }
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000923
924 D3DVIEWPORT9 dxViewport;
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000925 dxViewport.X = gl::clamp(actualViewport.x, 0, static_cast<int>(mRenderTargetDesc.width));
926 dxViewport.Y = gl::clamp(actualViewport.y, 0, static_cast<int>(mRenderTargetDesc.height));
927 dxViewport.Width = gl::clamp(actualViewport.width, 0, static_cast<int>(mRenderTargetDesc.width) - static_cast<int>(dxViewport.X));
928 dxViewport.Height = gl::clamp(actualViewport.height, 0, static_cast<int>(mRenderTargetDesc.height) - static_cast<int>(dxViewport.Y));
929 dxViewport.MinZ = actualZNear;
930 dxViewport.MaxZ = actualZFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000931
932 if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
933 {
934 return false; // Nothing to render
935 }
936
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000937 bool viewportChanged = mForceSetViewport || memcmp(&actualViewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
938 actualZNear != mCurNear || actualZFar != mCurFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000939 if (viewportChanged)
940 {
941 mDevice->SetViewport(&dxViewport);
942
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000943 mCurViewport = actualViewport;
944 mCurNear = actualZNear;
945 mCurFar = actualZFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000946 }
947
948 if (currentProgram && (viewportChanged || forceSetUniforms))
949 {
daniel@transgaming.com88853c52012-12-20 20:56:40 +0000950 currentProgram->applyDxHalfPixelSize(1.0f / dxViewport.Width, -1.0f / dxViewport.Height);
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000951
952 // These values are used for computing gl_FragCoord in Program::linkVaryings().
daniel@transgaming.com88853c52012-12-20 20:56:40 +0000953 currentProgram->applyDxCoord(actualViewport.width * 0.5f,
954 actualViewport.height * 0.5f,
955 actualViewport.x + (actualViewport.width * 0.5f),
956 actualViewport.y + (actualViewport.height * 0.5f));
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000957
daniel@transgaming.com12985182012-12-20 20:56:31 +0000958 GLfloat ccw = !gl::IsTriangleMode(drawMode) ? 0.0f : (frontFace == GL_CCW ? 1.0f : -1.0f);
daniel@transgaming.com88853c52012-12-20 20:56:40 +0000959 currentProgram->applyDxDepthFront((actualZFar - actualZNear) * 0.5f, (actualZNear + actualZFar) * 0.5f, ccw);
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000960
daniel@transgaming.com88853c52012-12-20 20:56:40 +0000961 currentProgram->applyDxDepthRange(actualZNear, actualZFar, actualZFar - actualZNear);
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000962 }
963
964 mForceSetViewport = false;
965 return true;
966}
967
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000968bool Renderer9::applyPrimitiveType(GLenum mode, GLsizei count)
969{
970 switch (mode)
971 {
972 case GL_POINTS:
973 mPrimitiveType = D3DPT_POINTLIST;
974 mPrimitiveCount = count;
975 break;
976 case GL_LINES:
977 mPrimitiveType = D3DPT_LINELIST;
978 mPrimitiveCount = count / 2;
979 break;
980 case GL_LINE_LOOP:
981 mPrimitiveType = D3DPT_LINESTRIP;
982 mPrimitiveCount = count - 1; // D3D doesn't support line loops, so we draw the last line separately
983 break;
984 case GL_LINE_STRIP:
985 mPrimitiveType = D3DPT_LINESTRIP;
986 mPrimitiveCount = count - 1;
987 break;
988 case GL_TRIANGLES:
989 mPrimitiveType = D3DPT_TRIANGLELIST;
990 mPrimitiveCount = count / 3;
991 break;
992 case GL_TRIANGLE_STRIP:
993 mPrimitiveType = D3DPT_TRIANGLESTRIP;
994 mPrimitiveCount = count - 2;
995 break;
996 case GL_TRIANGLE_FAN:
997 mPrimitiveType = D3DPT_TRIANGLEFAN;
998 mPrimitiveCount = count - 2;
999 break;
1000 default:
1001 return error(GL_INVALID_ENUM, false);
1002 }
1003
1004 return mPrimitiveCount > 0;
1005}
1006
daniel@transgaming.come4e1a332012-12-20 20:52:09 +00001007
1008gl::Renderbuffer *Renderer9::getNullColorbuffer(gl::Renderbuffer *depthbuffer)
1009{
1010 if (!depthbuffer)
1011 {
1012 ERR("Unexpected null depthbuffer for depth-only FBO.");
1013 return NULL;
1014 }
1015
1016 GLsizei width = depthbuffer->getWidth();
1017 GLsizei height = depthbuffer->getHeight();
1018
1019 // search cached nullcolorbuffers
1020 for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1021 {
1022 if (mNullColorbufferCache[i].buffer != NULL &&
1023 mNullColorbufferCache[i].width == width &&
1024 mNullColorbufferCache[i].height == height)
1025 {
1026 mNullColorbufferCache[i].lruCount = ++mMaxNullColorbufferLRU;
1027 return mNullColorbufferCache[i].buffer;
1028 }
1029 }
1030
1031 gl::Renderbuffer *nullbuffer = new gl::Renderbuffer(this, 0, new gl::Colorbuffer(this, width, height, GL_NONE, 0));
1032
1033 // add nullbuffer to the cache
1034 NullColorbufferCacheEntry *oldest = &mNullColorbufferCache[0];
1035 for (int i = 1; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1036 {
1037 if (mNullColorbufferCache[i].lruCount < oldest->lruCount)
1038 {
1039 oldest = &mNullColorbufferCache[i];
1040 }
1041 }
1042
1043 delete oldest->buffer;
1044 oldest->buffer = nullbuffer;
1045 oldest->lruCount = ++mMaxNullColorbufferLRU;
1046 oldest->width = width;
1047 oldest->height = height;
1048
1049 return nullbuffer;
1050}
1051
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001052bool Renderer9::applyRenderTarget(gl::Framebuffer *framebuffer)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001053{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001054 // if there is no color attachment we must synthesize a NULL colorattachment
1055 // to keep the D3D runtime happy. This should only be possible if depth texturing.
1056 gl::Renderbuffer *renderbufferObject = NULL;
1057 if (framebuffer->getColorbufferType() != GL_NONE)
1058 {
1059 renderbufferObject = framebuffer->getColorbuffer();
1060 }
1061 else
1062 {
daniel@transgaming.come4e1a332012-12-20 20:52:09 +00001063 renderbufferObject = getNullColorbuffer(framebuffer->getDepthbuffer());
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001064 }
1065 if (!renderbufferObject)
1066 {
1067 ERR("unable to locate renderbuffer for FBO.");
1068 return false;
1069 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001070
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001071 bool renderTargetChanged = false;
1072 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1073 if (renderTargetSerial != mAppliedRenderTargetSerial)
1074 {
1075 // Apply the render target on the device
1076 IDirect3DSurface9 *renderTargetSurface = NULL;
1077
1078 RenderTarget *renderTarget = renderbufferObject->getRenderTarget();
1079 if (renderTarget)
1080 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001081 renderTargetSurface = RenderTarget9::makeRenderTarget9(renderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001082 }
1083
1084 if (!renderTargetSurface)
1085 {
1086 ERR("render target pointer unexpectedly null.");
1087 return false; // Context must be lost
1088 }
1089
1090 mDevice->SetRenderTarget(0, renderTargetSurface);
1091 renderTargetSurface->Release();
1092
1093 mAppliedRenderTargetSerial = renderTargetSerial;
1094 renderTargetChanged = true;
1095 }
1096
1097 gl::Renderbuffer *depthStencil = NULL;
1098 unsigned int depthbufferSerial = 0;
1099 unsigned int stencilbufferSerial = 0;
1100 if (framebuffer->getDepthbufferType() != GL_NONE)
1101 {
1102 depthStencil = framebuffer->getDepthbuffer();
1103 if (!depthStencil)
1104 {
1105 ERR("Depth stencil pointer unexpectedly null.");
1106 return false;
1107 }
1108
1109 depthbufferSerial = depthStencil->getSerial();
1110 }
1111 else if (framebuffer->getStencilbufferType() != GL_NONE)
1112 {
1113 depthStencil = framebuffer->getStencilbuffer();
1114 if (!depthStencil)
1115 {
1116 ERR("Depth stencil pointer unexpectedly null.");
1117 return false;
1118 }
1119
1120 stencilbufferSerial = depthStencil->getSerial();
1121 }
1122
1123 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1124 stencilbufferSerial != mAppliedStencilbufferSerial ||
1125 !mDepthStencilInitialized)
1126 {
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001127 unsigned int depthSize = 0;
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001128 unsigned int stencilSize = 0;
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001129
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001130 // Apply the depth stencil on the device
1131 if (depthStencil)
1132 {
1133 IDirect3DSurface9 *depthStencilSurface = NULL;
1134 RenderTarget *depthStencilRenderTarget = depthStencil->getDepthStencil();
1135
1136 if (depthStencilRenderTarget)
1137 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001138 depthStencilSurface = RenderTarget9::makeRenderTarget9(depthStencilRenderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001139 }
1140
1141 if (!depthStencilSurface)
1142 {
1143 ERR("depth stencil pointer unexpectedly null.");
1144 return false; // Context must be lost
1145 }
1146
1147 mDevice->SetDepthStencilSurface(depthStencilSurface);
1148 depthStencilSurface->Release();
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001149
1150 depthSize = depthStencil->getDepthSize();
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001151 stencilSize = depthStencil->getStencilSize();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001152 }
1153 else
1154 {
1155 mDevice->SetDepthStencilSurface(NULL);
1156 }
1157
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001158 if (!mDepthStencilInitialized || depthSize != mCurDepthSize)
1159 {
1160 mCurDepthSize = depthSize;
1161 mForceSetRasterState = true;
1162 }
1163
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001164 if (!mDepthStencilInitialized || stencilSize != mCurStencilSize)
1165 {
1166 mCurStencilSize = stencilSize;
1167 mForceSetDepthStencilState = true;
1168 }
1169
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001170 mAppliedDepthbufferSerial = depthbufferSerial;
1171 mAppliedStencilbufferSerial = stencilbufferSerial;
1172 mDepthStencilInitialized = true;
1173 }
1174
1175 if (renderTargetChanged || !mRenderTargetDescInitialized)
1176 {
1177 mForceSetScissor = true;
1178 mForceSetViewport = true;
1179
1180 mRenderTargetDesc.width = renderbufferObject->getWidth();
1181 mRenderTargetDesc.height = renderbufferObject->getHeight();
1182 mRenderTargetDesc.format = renderbufferObject->getActualFormat();
1183 mRenderTargetDescInitialized = true;
1184 }
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001185
1186 return true;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001187}
daniel@transgaming.coma734f272012-10-31 18:07:48 +00001188
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001189GLenum Renderer9::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances)
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001190{
daniel@transgaming.com31240482012-11-28 21:06:41 +00001191 TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001192 GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
1193 if (err != GL_NO_ERROR)
1194 {
1195 return err;
1196 }
1197
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001198 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, &mRepeatDraw);
1199}
1200
1201// Applies the indices and element array bindings to the Direct3D 9 device
daniel@transgaming.com31240482012-11-28 21:06:41 +00001202GLenum Renderer9::applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001203{
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001204 GLenum err = mIndexDataManager->prepareIndexData(type, count, elementArrayBuffer, indices, indexInfo);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001205
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001206 if (err == GL_NO_ERROR)
1207 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001208 if (indexInfo->serial != mAppliedIBSerial)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001209 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001210 IndexBuffer9* indexBuffer = IndexBuffer9::makeIndexBuffer9(indexInfo->indexBuffer);
1211
1212 mDevice->SetIndices(indexBuffer->getBuffer());
1213 mAppliedIBSerial = indexInfo->serial;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001214 }
1215 }
1216
1217 return err;
1218}
1219
1220void Renderer9::drawArrays(GLenum mode, GLsizei count, GLsizei instances)
1221{
1222 startScene();
1223
1224 if (mode == GL_LINE_LOOP)
1225 {
1226 drawLineLoop(count, GL_NONE, NULL, 0, NULL);
1227 }
1228 else if (instances > 0)
1229 {
daniel@transgaming.com50cc7252012-12-20 21:09:23 +00001230 StaticIndexBufferInterface *countingIB = mIndexDataManager->getCountingIndices(count);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001231 if (countingIB)
1232 {
1233 if (mAppliedIBSerial != countingIB->getSerial())
1234 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001235 IndexBuffer9 *indexBuffer = IndexBuffer9::makeIndexBuffer9(countingIB->getIndexBuffer());
1236
1237 mDevice->SetIndices(indexBuffer->getBuffer());
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001238 mAppliedIBSerial = countingIB->getSerial();
1239 }
1240
1241 for (int i = 0; i < mRepeatDraw; i++)
1242 {
1243 mDevice->DrawIndexedPrimitive(mPrimitiveType, 0, 0, count, 0, mPrimitiveCount);
1244 }
1245 }
1246 else
1247 {
1248 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
1249 return error(GL_OUT_OF_MEMORY);
1250 }
1251 }
1252 else // Regular case
1253 {
1254 mDevice->DrawPrimitive(mPrimitiveType, 0, mPrimitiveCount);
1255 }
1256}
1257
daniel@transgaming.com31240482012-11-28 21:06:41 +00001258void Renderer9::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer, const TranslatedIndexData &indexInfo)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001259{
1260 startScene();
1261
1262 if (mode == GL_LINE_LOOP)
1263 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001264 drawLineLoop(count, type, indices, indexInfo.minIndex, elementArrayBuffer);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001265 }
1266 else
1267 {
1268 for (int i = 0; i < mRepeatDraw; i++)
1269 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001270 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
1271 mDevice->DrawIndexedPrimitive(mPrimitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, mPrimitiveCount);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001272 }
1273 }
1274}
1275
1276void Renderer9::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer)
1277{
1278 // Get the raw indices for an indexed draw
1279 if (type != GL_NONE && elementArrayBuffer)
1280 {
1281 gl::Buffer *indexBuffer = elementArrayBuffer;
1282 intptr_t offset = reinterpret_cast<intptr_t>(indices);
1283 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
1284 }
1285
1286 UINT startIndex = 0;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001287
1288 if (get32BitIndexSupport())
1289 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001290 if (!mLineLoopIB)
1291 {
1292 mLineLoopIB = new StreamingIndexBufferInterface(this);
1293 if (!mLineLoopIB->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_INT))
1294 {
1295 delete mLineLoopIB;
1296 mLineLoopIB = NULL;
1297
1298 ERR("Could not create a 32-bit looping index buffer for GL_LINE_LOOP.");
1299 return error(GL_OUT_OF_MEMORY);
1300 }
1301 }
1302
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001303 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001304 if (!mLineLoopIB->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_INT))
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001305 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001306 ERR("Could not reserve enough space in looping index buffer for GL_LINE_LOOP.");
1307 return error(GL_OUT_OF_MEMORY);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001308 }
1309
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001310 void* mappedMemory = NULL;
1311 int offset = mLineLoopIB->mapBuffer(spaceNeeded, &mappedMemory);
1312 if (offset == -1 || mappedMemory == NULL)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001313 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001314 ERR("Could not map index buffer for GL_LINE_LOOP.");
1315 return error(GL_OUT_OF_MEMORY);
1316 }
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001317
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001318 startIndex = static_cast<UINT>(offset) / 4;
1319 unsigned int *data = reinterpret_cast<unsigned int*>(mappedMemory);
1320
1321 switch (type)
1322 {
1323 case GL_NONE: // Non-indexed draw
1324 for (int i = 0; i < count; i++)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001325 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001326 data[i] = i;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001327 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001328 data[count] = 0;
1329 break;
1330 case GL_UNSIGNED_BYTE:
1331 for (int i = 0; i < count; i++)
1332 {
1333 data[i] = static_cast<const GLubyte*>(indices)[i];
1334 }
1335 data[count] = static_cast<const GLubyte*>(indices)[0];
1336 break;
1337 case GL_UNSIGNED_SHORT:
1338 for (int i = 0; i < count; i++)
1339 {
1340 data[i] = static_cast<const GLushort*>(indices)[i];
1341 }
1342 data[count] = static_cast<const GLushort*>(indices)[0];
1343 break;
1344 case GL_UNSIGNED_INT:
1345 for (int i = 0; i < count; i++)
1346 {
1347 data[i] = static_cast<const GLuint*>(indices)[i];
1348 }
1349 data[count] = static_cast<const GLuint*>(indices)[0];
1350 break;
1351 default: UNREACHABLE();
1352 }
1353
1354 if (!mLineLoopIB->unmapBuffer())
1355 {
1356 ERR("Could not unmap index buffer for GL_LINE_LOOP.");
1357 return error(GL_OUT_OF_MEMORY);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001358 }
1359 }
1360 else
1361 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001362 if (!mLineLoopIB)
1363 {
1364 mLineLoopIB = new StreamingIndexBufferInterface(this);
1365 if (!mLineLoopIB->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_SHORT))
1366 {
1367 delete mLineLoopIB;
1368 mLineLoopIB = NULL;
1369
1370 ERR("Could not create a 16-bit looping index buffer for GL_LINE_LOOP.");
1371 return error(GL_OUT_OF_MEMORY);
1372 }
1373 }
1374
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001375 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001376 if (!mLineLoopIB->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_SHORT))
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001377 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001378 ERR("Could not reserve enough space in looping index buffer for GL_LINE_LOOP.");
1379 return error(GL_OUT_OF_MEMORY);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001380 }
1381
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001382 void* mappedMemory = NULL;
1383 int offset = mLineLoopIB->mapBuffer(spaceNeeded, &mappedMemory);
1384 if (offset == -1 || mappedMemory == NULL)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001385 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001386 ERR("Could not map index buffer for GL_LINE_LOOP.");
1387 return error(GL_OUT_OF_MEMORY);
1388 }
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001389
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001390 startIndex = static_cast<UINT>(offset) / 2;
1391 unsigned short *data = reinterpret_cast<unsigned short*>(mappedMemory);
1392
1393 switch (type)
1394 {
1395 case GL_NONE: // Non-indexed draw
1396 for (int i = 0; i < count; i++)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001397 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001398 data[i] = i;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001399 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001400 data[count] = 0;
1401 break;
1402 case GL_UNSIGNED_BYTE:
1403 for (int i = 0; i < count; i++)
1404 {
1405 data[i] = static_cast<const GLubyte*>(indices)[i];
1406 }
1407 data[count] = static_cast<const GLubyte*>(indices)[0];
1408 break;
1409 case GL_UNSIGNED_SHORT:
1410 for (int i = 0; i < count; i++)
1411 {
1412 data[i] = static_cast<const GLushort*>(indices)[i];
1413 }
1414 data[count] = static_cast<const GLushort*>(indices)[0];
1415 break;
1416 case GL_UNSIGNED_INT:
1417 for (int i = 0; i < count; i++)
1418 {
1419 data[i] = static_cast<const GLuint*>(indices)[i];
1420 }
1421 data[count] = static_cast<const GLuint*>(indices)[0];
1422 break;
1423 default: UNREACHABLE();
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001424 }
1425
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001426 if (!mLineLoopIB->unmapBuffer())
1427 {
1428 ERR("Could not unmap index buffer for GL_LINE_LOOP.");
1429 return error(GL_OUT_OF_MEMORY);
1430 }
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001431 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001432
1433 if (mAppliedIBSerial != mLineLoopIB->getSerial())
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001434 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001435 IndexBuffer9 *indexBuffer = IndexBuffer9::makeIndexBuffer9(mLineLoopIB->getIndexBuffer());
1436
1437 mDevice->SetIndices(indexBuffer->getBuffer());
1438 mAppliedIBSerial = mLineLoopIB->getSerial();
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001439 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001440
1441 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001442}
1443
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001444void Renderer9::applyShaders(gl::ProgramBinary *programBinary)
1445{
daniel@transgaming.come4991412012-12-20 20:55:34 +00001446 unsigned int programBinarySerial = programBinary->getSerial();
1447 if (programBinarySerial != mAppliedProgramBinarySerial)
1448 {
1449 ShaderExecutable *vertexExe = programBinary->getVertexExecutable();
1450 ShaderExecutable *pixelExe = programBinary->getPixelExecutable();
daniel@transgaming.com95892412012-11-28 20:59:09 +00001451
daniel@transgaming.come4991412012-12-20 20:55:34 +00001452 IDirect3DVertexShader9 *vertexShader = NULL;
1453 if (vertexExe) vertexShader = ShaderExecutable9::makeShaderExecutable9(vertexExe)->getVertexShader();
daniel@transgaming.com95892412012-11-28 20:59:09 +00001454
daniel@transgaming.come4991412012-12-20 20:55:34 +00001455 IDirect3DPixelShader9 *pixelShader = NULL;
1456 if (pixelExe) pixelShader = ShaderExecutable9::makeShaderExecutable9(pixelExe)->getPixelShader();
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001457
daniel@transgaming.come4991412012-12-20 20:55:34 +00001458 mDevice->SetPixelShader(pixelShader);
1459 mDevice->SetVertexShader(vertexShader);
1460 programBinary->dirtyAllUniforms();
1461
1462 mAppliedProgramBinarySerial = programBinarySerial;
1463 }
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001464}
1465
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001466void Renderer9::applyUniforms(const gl::UniformArray *uniformArray)
1467{
1468 for (std::vector<gl::Uniform*>::const_iterator ub = uniformArray->begin(), ue = uniformArray->end(); ub != ue; ++ub)
1469 {
1470 gl::Uniform *targetUniform = *ub;
1471
1472 if (targetUniform->dirty)
1473 {
daniel@transgaming.come6d12e92012-12-20 21:12:47 +00001474 int count = targetUniform->elementCount();
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001475 GLfloat *f = (GLfloat*)targetUniform->data;
1476 GLint *i = (GLint*)targetUniform->data;
1477 GLboolean *b = (GLboolean*)targetUniform->data;
1478
1479 switch (targetUniform->type)
1480 {
1481 case GL_SAMPLER_2D:
1482 case GL_SAMPLER_CUBE:
1483 break;
daniel@transgaming.come6d12e92012-12-20 21:12:47 +00001484 case GL_BOOL: applyUniformnbv(targetUniform, count, 1, b); break;
1485 case GL_BOOL_VEC2: applyUniformnbv(targetUniform, count, 2, b); break;
1486 case GL_BOOL_VEC3: applyUniformnbv(targetUniform, count, 3, b); break;
1487 case GL_BOOL_VEC4: applyUniformnbv(targetUniform, count, 4, b); break;
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001488 case GL_FLOAT:
1489 case GL_FLOAT_VEC2:
1490 case GL_FLOAT_VEC3:
1491 case GL_FLOAT_VEC4:
1492 case GL_FLOAT_MAT2:
1493 case GL_FLOAT_MAT3:
daniel@transgaming.come6d12e92012-12-20 21:12:47 +00001494 case GL_FLOAT_MAT4: applyUniformnfv(targetUniform, f); break;
1495 case GL_INT: applyUniform1iv(targetUniform, count, i); break;
1496 case GL_INT_VEC2: applyUniform2iv(targetUniform, count, i); break;
1497 case GL_INT_VEC3: applyUniform3iv(targetUniform, count, i); break;
1498 case GL_INT_VEC4: applyUniform4iv(targetUniform, count, i); break;
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001499 default:
1500 UNREACHABLE();
1501 }
1502
1503 targetUniform->dirty = false;
1504 }
1505 }
1506}
1507
1508void Renderer9::applyUniformnbv(gl::Uniform *targetUniform, GLsizei count, int width, const GLboolean *v)
1509{
1510 float vector[gl::D3D9_MAX_FLOAT_CONSTANTS * 4];
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001511
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001512 if (targetUniform->ps.registerIndex >= 0 || targetUniform->vs.registerIndex >= 0)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001513 {
1514 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1515 for (int i = 0; i < count; i++)
1516 {
1517 for (int j = 0; j < 4; j++)
1518 {
1519 if (j < width)
1520 {
1521 vector[i * 4 + j] = (v[i * width + j] == GL_FALSE) ? 0.0f : 1.0f;
1522 }
1523 else
1524 {
1525 vector[i * 4 + j] = 0.0f;
1526 }
1527 }
1528 }
1529 }
1530
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001531 applyUniformnfv(targetUniform, vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001532}
1533
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001534void Renderer9::applyUniformnfv(gl::Uniform *targetUniform, const GLfloat *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001535{
1536 if (targetUniform->ps.registerCount)
1537 {
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001538 ASSERT(targetUniform->ps.registerIndex >= 0);
1539 mDevice->SetPixelShaderConstantF(targetUniform->ps.registerIndex, v, targetUniform->ps.registerCount);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001540 }
1541
1542 if (targetUniform->vs.registerCount)
1543 {
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001544 ASSERT(targetUniform->vs.registerIndex >= 0);
1545 mDevice->SetVertexShaderConstantF(targetUniform->vs.registerIndex, v, targetUniform->vs.registerCount);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001546 }
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001547}
1548
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001549void Renderer9::applyUniform1iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001550{
1551 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1552 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1553
1554 for (int i = 0; i < count; i++)
1555 {
1556 vector[i] = gl::Vector4((float)v[i], 0, 0, 0);
1557 }
1558
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001559 applyUniformnfv(targetUniform, (const GLfloat*)vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001560}
1561
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001562void Renderer9::applyUniform2iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001563{
1564 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1565 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1566
1567 for (int i = 0; i < count; i++)
1568 {
1569 vector[i] = gl::Vector4((float)v[0], (float)v[1], 0, 0);
1570
1571 v += 2;
1572 }
1573
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001574 applyUniformnfv(targetUniform, (const GLfloat*)vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001575}
1576
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001577void Renderer9::applyUniform3iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001578{
1579 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1580 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1581
1582 for (int i = 0; i < count; i++)
1583 {
1584 vector[i] = gl::Vector4((float)v[0], (float)v[1], (float)v[2], 0);
1585
1586 v += 3;
1587 }
1588
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001589 applyUniformnfv(targetUniform, (const GLfloat*)vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001590}
1591
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001592void Renderer9::applyUniform4iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001593{
1594 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1595 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1596
1597 for (int i = 0; i < count; i++)
1598 {
1599 vector[i] = gl::Vector4((float)v[0], (float)v[1], (float)v[2], (float)v[3]);
1600
1601 v += 4;
1602 }
1603
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001604 applyUniformnfv(targetUniform, (const GLfloat*)vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001605}
1606
daniel@transgaming.com084a2572012-11-28 20:55:17 +00001607void Renderer9::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001608{
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001609 D3DCOLOR color = D3DCOLOR_ARGB(gl::unorm<8>(clearParams.colorClearValue.alpha),
1610 gl::unorm<8>(clearParams.colorClearValue.red),
1611 gl::unorm<8>(clearParams.colorClearValue.green),
1612 gl::unorm<8>(clearParams.colorClearValue.blue));
1613 float depth = gl::clamp01(clearParams.depthClearValue);
1614 int stencil = clearParams.stencilClearValue & 0x000000FF;
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001615
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001616 unsigned int stencilUnmasked = 0x0;
1617 if ((clearParams.mask & GL_STENCIL_BUFFER_BIT) && frameBuffer->hasStencil())
1618 {
1619 unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
1620 stencilUnmasked = (0x1 << stencilSize) - 1;
1621 }
1622
1623 bool alphaUnmasked = (gl::GetAlphaSize(mRenderTargetDesc.format) == 0) || clearParams.colorMaskAlpha;
1624
1625 const bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
1626 (clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
1627 const bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
1628 !(clearParams.colorMaskRed && clearParams.colorMaskGreen &&
1629 clearParams.colorMaskBlue && alphaUnmasked);
1630
1631 if (needMaskedColorClear || needMaskedStencilClear)
1632 {
1633 // State which is altered in all paths from this point to the clear call is saved.
1634 // State which is altered in only some paths will be flagged dirty in the case that
1635 // that path is taken.
1636 HRESULT hr;
1637 if (mMaskedClearSavedState == NULL)
1638 {
1639 hr = mDevice->BeginStateBlock();
1640 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1641
1642 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1643 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1644 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1645 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1646 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1647 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1648 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1649 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1650 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1651 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1652 mDevice->SetPixelShader(NULL);
1653 mDevice->SetVertexShader(NULL);
1654 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
1655 mDevice->SetStreamSource(0, NULL, 0, 0);
1656 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1657 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1658 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1659 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1660 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1661 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1662 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1663
1664 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1665 {
1666 mDevice->SetStreamSourceFreq(i, 1);
1667 }
1668
1669 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
1670 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1671 }
1672
1673 ASSERT(mMaskedClearSavedState != NULL);
1674
1675 if (mMaskedClearSavedState != NULL)
1676 {
1677 hr = mMaskedClearSavedState->Capture();
1678 ASSERT(SUCCEEDED(hr));
1679 }
1680
1681 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1682 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1683 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1684 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1685 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1686 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1687 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1688 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1689
1690 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1691 {
1692 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE,
1693 gl_d3d9::ConvertColorMask(clearParams.colorMaskRed,
1694 clearParams.colorMaskGreen,
1695 clearParams.colorMaskBlue,
1696 clearParams.colorMaskAlpha));
1697 }
1698 else
1699 {
1700 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1701 }
1702
1703 if (stencilUnmasked != 0x0 && (clearParams.mask & GL_STENCIL_BUFFER_BIT))
1704 {
1705 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
1706 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
1707 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
1708 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
1709 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
1710 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
1711 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
1712 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
1713 }
1714 else
1715 {
1716 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1717 }
1718
1719 mDevice->SetPixelShader(NULL);
1720 mDevice->SetVertexShader(NULL);
1721 mDevice->SetFVF(D3DFVF_XYZRHW);
1722 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1723 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1724 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1725 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1726 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1727 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1728 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1729
1730 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1731 {
1732 mDevice->SetStreamSourceFreq(i, 1);
1733 }
1734
1735 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
1736 quad[0][0] = -0.5f;
1737 quad[0][1] = mRenderTargetDesc.height - 0.5f;
1738 quad[0][2] = 0.0f;
1739 quad[0][3] = 1.0f;
1740
1741 quad[1][0] = mRenderTargetDesc.width - 0.5f;
1742 quad[1][1] = mRenderTargetDesc.height - 0.5f;
1743 quad[1][2] = 0.0f;
1744 quad[1][3] = 1.0f;
1745
1746 quad[2][0] = -0.5f;
1747 quad[2][1] = -0.5f;
1748 quad[2][2] = 0.0f;
1749 quad[2][3] = 1.0f;
1750
1751 quad[3][0] = mRenderTargetDesc.width - 0.5f;
1752 quad[3][1] = -0.5f;
1753 quad[3][2] = 0.0f;
1754 quad[3][3] = 1.0f;
1755
1756 startScene();
1757 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
1758
1759 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1760 {
1761 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
1762 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
1763 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
1764 }
1765
1766 if (mMaskedClearSavedState != NULL)
1767 {
1768 mMaskedClearSavedState->Apply();
1769 }
1770 }
1771 else if (clearParams.mask)
1772 {
1773 DWORD dxClearFlags = 0;
1774 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1775 {
1776 dxClearFlags |= D3DCLEAR_TARGET;
1777 }
1778 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1779 {
1780 dxClearFlags |= D3DCLEAR_ZBUFFER;
1781 }
1782 if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
1783 {
1784 dxClearFlags |= D3DCLEAR_STENCIL;
1785 }
1786
1787 mDevice->Clear(0, NULL, dxClearFlags, color, depth, stencil);
1788 }
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001789}
1790
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001791void Renderer9::markAllStateDirty()
1792{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001793 mAppliedRenderTargetSerial = 0;
1794 mAppliedDepthbufferSerial = 0;
1795 mAppliedStencilbufferSerial = 0;
1796 mDepthStencilInitialized = false;
1797 mRenderTargetDescInitialized = false;
1798
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001799 mForceSetDepthStencilState = true;
1800 mForceSetRasterState = true;
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001801 mForceSetScissor = true;
1802 mForceSetViewport = true;
daniel@transgaming.com9a067372012-12-20 20:55:24 +00001803 mForceSetBlendState = true;
1804
1805 mAppliedIBSerial = 0;
daniel@transgaming.come4991412012-12-20 20:55:34 +00001806 mAppliedProgramBinarySerial = 0;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001807
1808 mVertexDeclarationCache.markStateDirty();
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001809}
1810
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001811void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001812{
1813 while (!mEventQueryPool.empty())
1814 {
1815 mEventQueryPool.back()->Release();
1816 mEventQueryPool.pop_back();
1817 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001818
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001819 if (mMaskedClearSavedState)
1820 {
1821 mMaskedClearSavedState->Release();
1822 mMaskedClearSavedState = NULL;
1823 }
1824
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001825 mVertexShaderCache.clear();
1826 mPixelShaderCache.clear();
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001827
daniel@transgaming.come569fc52012-11-28 20:56:02 +00001828 delete mBlit;
1829 mBlit = NULL;
1830
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001831 delete mVertexDataManager;
1832 mVertexDataManager = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001833
1834 delete mIndexDataManager;
1835 mIndexDataManager = NULL;
1836
1837 delete mLineLoopIB;
1838 mLineLoopIB = NULL;
daniel@transgaming.come4e1a332012-12-20 20:52:09 +00001839
1840 for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1841 {
1842 delete mNullColorbufferCache[i].buffer;
1843 mNullColorbufferCache[i].buffer = NULL;
1844 }
1845
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001846}
1847
1848
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001849void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001850{
1851 mDeviceLost = true;
1852}
1853
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001854bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001855{
1856 return mDeviceLost;
1857}
1858
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001859// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001860bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001861{
1862 bool isLost = false;
1863
1864 if (mDeviceEx)
1865 {
1866 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
1867 }
1868 else if (mDevice)
1869 {
1870 isLost = FAILED(mDevice->TestCooperativeLevel());
1871 }
1872 else
1873 {
1874 // No device yet, so no reset required
1875 }
1876
1877 if (isLost)
1878 {
1879 // ensure we note the device loss --
1880 // we'll probably get this done again by markDeviceLost
1881 // but best to remember it!
1882 // Note that we don't want to clear the device loss status here
1883 // -- this needs to be done by resetDevice
1884 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001885 if (notify)
1886 {
1887 mDisplay->notifyDeviceLost();
1888 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001889 }
1890
1891 return isLost;
1892}
1893
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001894bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001895{
1896 HRESULT status = D3D_OK;
1897
1898 if (mDeviceEx)
1899 {
1900 status = mDeviceEx->CheckDeviceState(NULL);
1901 }
1902 else if (mDevice)
1903 {
1904 status = mDevice->TestCooperativeLevel();
1905 }
1906
1907 switch (status)
1908 {
1909 case D3DERR_DEVICENOTRESET:
1910 case D3DERR_DEVICEHUNG:
1911 return true;
1912 default:
1913 return false;
1914 }
1915}
1916
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001917bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001918{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001919 releaseDeviceResources();
1920
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001921 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
1922
1923 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001924 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001925 int attempts = 3;
1926
1927 while (lost && attempts > 0)
1928 {
1929 if (mDeviceEx)
1930 {
1931 Sleep(500); // Give the graphics driver some CPU time
1932 result = mDeviceEx->ResetEx(&presentParameters, NULL);
1933 }
1934 else
1935 {
1936 result = mDevice->TestCooperativeLevel();
1937 while (result == D3DERR_DEVICELOST)
1938 {
1939 Sleep(100); // Give the graphics driver some CPU time
1940 result = mDevice->TestCooperativeLevel();
1941 }
1942
1943 if (result == D3DERR_DEVICENOTRESET)
1944 {
1945 result = mDevice->Reset(&presentParameters);
1946 }
1947 }
1948
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001949 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001950 attempts --;
1951 }
1952
1953 if (FAILED(result))
1954 {
1955 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
1956 return false;
1957 }
1958
1959 // reset device defaults
1960 initializeDevice();
1961 mDeviceLost = false;
1962
1963 return true;
1964}
1965
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001966DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001967{
1968 return mAdapterIdentifier.VendorId;
1969}
1970
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001971const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001972{
1973 return mAdapterIdentifier.Description;
1974}
1975
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001976GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00001977{
1978 return mAdapterIdentifier.DeviceIdentifier;
1979}
1980
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001981void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001982{
1983 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
1984 {
1985 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
1986 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
1987
1988 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
1989 }
1990}
1991
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001992bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001993{
1994 D3DDISPLAYMODE currentDisplayMode;
1995 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
1996
1997 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
1998}
1999
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002000bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002001{
2002 D3DDISPLAYMODE currentDisplayMode;
2003 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2004
2005 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
2006}
2007
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002008bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002009{
2010 D3DDISPLAYMODE currentDisplayMode;
2011 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2012
2013 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
2014}
2015
2016// we use INTZ for depth textures in Direct3D9
2017// we also want NULL texture support to ensure the we can make depth-only FBOs
2018// see http://aras-p.info/texts/D3D9GPUHacks.html
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002019bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002020{
2021 D3DDISPLAYMODE currentDisplayMode;
2022 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2023
2024 bool intz = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
2025 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ));
2026 bool null = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
2027 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
2028
2029 return intz && null;
2030}
2031
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002032bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002033{
2034 D3DDISPLAYMODE currentDisplayMode;
2035 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2036
2037 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
2038 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
2039 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
2040 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
2041
2042 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
2043 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F))&&
2044 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
2045 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
2046
2047 if (!*filtering && !*renderable)
2048 {
2049 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
2050 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
2051 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
2052 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
2053 }
2054 else
2055 {
2056 return true;
2057 }
2058}
2059
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002060bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002061{
2062 D3DDISPLAYMODE currentDisplayMode;
2063 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2064
2065 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
2066 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
2067 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
2068 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
2069
2070 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
2071 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
2072 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
2073 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
2074
2075 if (!*filtering && !*renderable)
2076 {
2077 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
2078 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
2079 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
2080 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
2081 }
2082 else
2083 {
2084 return true;
2085 }
2086}
2087
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002088bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002089{
2090 D3DDISPLAYMODE currentDisplayMode;
2091 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2092
2093 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
2094}
2095
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002096bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002097{
2098 D3DDISPLAYMODE currentDisplayMode;
2099 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2100
2101 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
2102}
2103
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002104bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002105{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00002106 return mSupportsTextureFilterAnisotropy;
2107}
2108
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002109float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00002110{
2111 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002112 {
2113 return mDeviceCaps.MaxAnisotropy;
2114 }
2115 return 1.0f;
2116}
2117
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002118bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002119{
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002120 IDirect3DQuery9 *query = allocateEventQuery();
2121 if (query)
2122 {
2123 freeEventQuery(query);
2124 return true;
2125 }
2126 else
2127 {
2128 return false;
2129 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002130 return true;
2131}
2132
2133// Only Direct3D 10 ready devices support all the necessary vertex texture formats.
2134// We test this using D3D9 by checking support for the R16F format.
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002135bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002136{
2137 if (!mDevice || mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(3, 0))
2138 {
2139 return false;
2140 }
2141
2142 D3DDISPLAYMODE currentDisplayMode;
2143 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2144
2145 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F);
2146
2147 return SUCCEEDED(result);
2148}
2149
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002150bool Renderer9::getNonPower2TextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002151{
2152 return mSupportsNonPower2Textures;
2153}
2154
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002155bool Renderer9::getOcclusionQuerySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002156{
2157 if (!mDevice)
2158 {
2159 return false;
2160 }
2161
2162 IDirect3DQuery9 *query = NULL;
2163 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query);
2164 if (SUCCEEDED(result) && query)
2165 {
2166 query->Release();
2167 return true;
2168 }
2169 else
2170 {
2171 return false;
2172 }
2173}
2174
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002175bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002176{
2177 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
2178}
2179
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002180bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00002181{
2182 // PIX doesn't seem to support using share handles, so disable them.
2183 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00002184 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00002185}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002186
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00002187int Renderer9::getMajorShaderModel() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002188{
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00002189 return D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion);
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002190}
2191
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002192float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002193{
2194 return mDeviceCaps.MaxPointSize;
2195}
2196
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002197int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002198{
2199 return (int)mDeviceCaps.MaxTextureWidth;
2200}
2201
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002202int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002203{
2204 return (int)mDeviceCaps.MaxTextureHeight;
2205}
2206
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002207bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002208{
2209 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
2210}
2211
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002212DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002213{
2214 return mDeviceCaps.DeclTypes;
2215}
2216
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002217int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002218{
2219 return mMinSwapInterval;
2220}
2221
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002222int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002223{
2224 return mMaxSwapInterval;
2225}
2226
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002227int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002228{
2229 return mMaxSupportedSamples;
2230}
2231
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002232int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002233{
2234 if (requested == 0)
2235 {
2236 return requested;
2237 }
2238
2239 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
2240 if (itr == mMultiSampleSupport.end())
2241 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00002242 if (format == D3DFMT_UNKNOWN)
2243 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002244 return -1;
2245 }
2246
2247 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
2248 {
2249 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
2250 {
2251 return i;
2252 }
2253 }
2254
2255 return -1;
2256}
2257
daniel@transgaming.coma9571682012-11-28 19:33:08 +00002258D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
2259{
2260 switch (internalformat)
2261 {
2262 case GL_DEPTH_COMPONENT16:
2263 case GL_DEPTH_COMPONENT32_OES:
2264 case GL_DEPTH24_STENCIL8_OES:
2265 return D3DFMT_INTZ;
2266 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
2267 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
2268 return D3DFMT_DXT1;
2269 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
2270 return D3DFMT_DXT3;
2271 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
2272 return D3DFMT_DXT5;
2273 case GL_RGBA32F_EXT:
2274 case GL_RGB32F_EXT:
2275 case GL_ALPHA32F_EXT:
2276 case GL_LUMINANCE32F_EXT:
2277 case GL_LUMINANCE_ALPHA32F_EXT:
2278 return D3DFMT_A32B32G32R32F;
2279 case GL_RGBA16F_EXT:
2280 case GL_RGB16F_EXT:
2281 case GL_ALPHA16F_EXT:
2282 case GL_LUMINANCE16F_EXT:
2283 case GL_LUMINANCE_ALPHA16F_EXT:
2284 return D3DFMT_A16B16G16R16F;
2285 case GL_LUMINANCE8_EXT:
2286 if (getLuminanceTextureSupport())
2287 {
2288 return D3DFMT_L8;
2289 }
2290 break;
2291 case GL_LUMINANCE8_ALPHA8_EXT:
2292 if (getLuminanceAlphaTextureSupport())
2293 {
2294 return D3DFMT_A8L8;
2295 }
2296 break;
2297 case GL_RGB8_OES:
2298 case GL_RGB565:
2299 return D3DFMT_X8R8G8B8;
2300 }
2301
2302 return D3DFMT_A8R8G8B8;
2303}
2304
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002305bool Renderer9::copyToRenderTarget(TextureStorageInterface2D *dest, TextureStorageInterface2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002306{
2307 bool result = false;
2308
2309 if (source && dest)
2310 {
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002311 TextureStorage9_2D *source9 = TextureStorage9_2D::makeTextureStorage9_2D(source->getStorageInstance());
2312 TextureStorage9_2D *dest9 = TextureStorage9_2D::makeTextureStorage9_2D(dest->getStorageInstance());
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002313
2314 int levels = source9->levelCount();
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002315 for (int i = 0; i < levels; ++i)
2316 {
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002317 IDirect3DSurface9 *srcSurf = source9->getSurfaceLevel(i, false);
2318 IDirect3DSurface9 *dstSurf = dest9->getSurfaceLevel(i, false);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002319
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002320 result = copyToRenderTarget(dstSurf, srcSurf, source9->isManaged());
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002321
2322 if (srcSurf) srcSurf->Release();
2323 if (dstSurf) dstSurf->Release();
2324
2325 if (!result)
2326 return false;
2327 }
2328 }
2329
2330 return result;
2331}
2332
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002333bool Renderer9::copyToRenderTarget(TextureStorageInterfaceCube *dest, TextureStorageInterfaceCube *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002334{
2335 bool result = false;
2336
2337 if (source && dest)
2338 {
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002339 TextureStorage9_Cube *source9 = TextureStorage9_Cube::makeTextureStorage9_Cube(source->getStorageInstance());
2340 TextureStorage9_Cube *dest9 = TextureStorage9_Cube::makeTextureStorage9_Cube(dest->getStorageInstance());
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002341 int levels = source9->levelCount();
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002342 for (int f = 0; f < 6; f++)
2343 {
2344 for (int i = 0; i < levels; i++)
2345 {
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002346 IDirect3DSurface9 *srcSurf = source9->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
2347 IDirect3DSurface9 *dstSurf = dest9->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002348
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002349 result = copyToRenderTarget(dstSurf, srcSurf, source9->isManaged());
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002350
2351 if (srcSurf) srcSurf->Release();
2352 if (dstSurf) dstSurf->Release();
2353
2354 if (!result)
2355 return false;
2356 }
2357 }
2358 }
2359
2360 return result;
2361}
2362
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002363D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002364{
2365 if (mD3d9Ex != NULL)
2366 {
2367 return D3DPOOL_DEFAULT;
2368 }
2369 else
2370 {
2371 if (!(usage & D3DUSAGE_DYNAMIC))
2372 {
2373 return D3DPOOL_MANAGED;
2374 }
2375 }
2376
2377 return D3DPOOL_DEFAULT;
2378}
2379
daniel@transgaming.com38380882012-11-28 19:36:39 +00002380bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002381 GLint xoffset, GLint yoffset, TextureStorageInterface2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002382{
2383 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
2384}
2385
daniel@transgaming.com38380882012-11-28 19:36:39 +00002386bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002387 GLint xoffset, GLint yoffset, TextureStorageInterfaceCube *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002388{
2389 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
2390}
2391
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002392bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
2393 bool blitRenderTarget, bool blitDepthStencil)
2394{
2395 endScene();
2396
2397 if (blitRenderTarget)
2398 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002399 gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer();
2400 gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer();
2401 RenderTarget9 *readRenderTarget = NULL;
2402 RenderTarget9 *drawRenderTarget = NULL;
2403 IDirect3DSurface9* readSurface = NULL;
2404 IDirect3DSurface9* drawSurface = NULL;
2405
2406 if (readBuffer)
2407 {
2408 readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
2409 }
2410 if (drawBuffer)
2411 {
2412 drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
2413 }
2414
2415 if (readRenderTarget)
2416 {
2417 readSurface = readRenderTarget->getSurface();
2418 }
2419 if (drawRenderTarget)
2420 {
2421 drawSurface = drawRenderTarget->getSurface();
2422 }
2423
2424 if (!readSurface || !drawSurface)
2425 {
2426 ERR("Failed to retrieve the render target.");
2427 return error(GL_OUT_OF_MEMORY, false);
2428 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002429
2430 RECT srcRect, dstRect;
2431 RECT *srcRectPtr = NULL;
2432 RECT *dstRectPtr = NULL;
2433
2434 if (readRect)
2435 {
2436 srcRect.left = readRect->x;
2437 srcRect.right = readRect->x + readRect->width;
2438 srcRect.top = readRect->y;
2439 srcRect.bottom = readRect->y + readRect->height;
2440 srcRectPtr = &srcRect;
2441 }
2442
2443 if (drawRect)
2444 {
2445 dstRect.left = drawRect->x;
2446 dstRect.right = drawRect->x + drawRect->width;
2447 dstRect.top = drawRect->y;
2448 dstRect.bottom = drawRect->y + drawRect->height;
2449 dstRectPtr = &dstRect;
2450 }
2451
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002452 HRESULT result = mDevice->StretchRect(readSurface, srcRectPtr, drawSurface, dstRectPtr, D3DTEXF_NONE);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002453
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002454 readSurface->Release();
2455 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002456
2457 if (FAILED(result))
2458 {
2459 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2460 return false;
2461 }
2462 }
2463
2464 if (blitDepthStencil)
2465 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002466 gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
2467 gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
2468 RenderTarget9 *readDepthStencil = NULL;
2469 RenderTarget9 *drawDepthStencil = NULL;
2470 IDirect3DSurface9* readSurface = NULL;
2471 IDirect3DSurface9* drawSurface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002472
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002473 if (readBuffer)
2474 {
2475 readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
2476 }
2477 if (drawBuffer)
2478 {
2479 drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
2480 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002481
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002482 if (readDepthStencil)
2483 {
2484 readSurface = readDepthStencil->getSurface();
2485 }
2486 if (drawDepthStencil)
2487 {
2488 drawSurface = drawDepthStencil->getSurface();
2489 }
2490
2491 if (!readSurface || !drawSurface)
2492 {
2493 ERR("Failed to retrieve the render target.");
2494 return error(GL_OUT_OF_MEMORY, false);
2495 }
2496
2497 HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
2498
2499 readSurface->Release();
2500 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002501
2502 if (FAILED(result))
2503 {
2504 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2505 return false;
2506 }
2507 }
2508
2509 return true;
2510}
2511
2512void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
2513 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
2514{
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002515 RenderTarget9 *renderTarget = NULL;
2516 IDirect3DSurface9 *surface = NULL;
2517 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
2518
2519 if (colorbuffer)
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002520 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002521 renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
2522 }
2523
2524 if (renderTarget)
2525 {
2526 surface = renderTarget->getSurface();
2527 }
2528
2529 if (!surface)
2530 {
2531 // context must be lost
2532 return;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002533 }
2534
2535 D3DSURFACE_DESC desc;
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002536 surface->GetDesc(&desc);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002537
2538 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2539 {
2540 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002541 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002542 return error(GL_OUT_OF_MEMORY);
2543 }
2544
2545 HRESULT result;
2546 IDirect3DSurface9 *systemSurface = NULL;
2547 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
2548 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2549 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2550 if (directToPixels)
2551 {
2552 // Use the pixels ptr as a shared handle to write directly into client's memory
2553 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2554 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2555 if (FAILED(result))
2556 {
2557 // Try again without the shared handle
2558 directToPixels = false;
2559 }
2560 }
2561
2562 if (!directToPixels)
2563 {
2564 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2565 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2566 if (FAILED(result))
2567 {
2568 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002569 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002570 return error(GL_OUT_OF_MEMORY);
2571 }
2572 }
2573
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002574 result = mDevice->GetRenderTargetData(surface, systemSurface);
2575 surface->Release();
2576 surface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002577
2578 if (FAILED(result))
2579 {
2580 systemSurface->Release();
2581
2582 // It turns out that D3D will sometimes produce more error
2583 // codes than those documented.
daniel@transgaming.com414c9162012-11-28 20:54:57 +00002584 if (checkDeviceLost(result))
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002585 return error(GL_OUT_OF_MEMORY);
2586 else
2587 {
2588 UNREACHABLE();
2589 return;
2590 }
2591
2592 }
2593
2594 if (directToPixels)
2595 {
2596 systemSurface->Release();
2597 return;
2598 }
2599
2600 RECT rect;
2601 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
2602 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
2603 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2604 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2605
2606 D3DLOCKED_RECT lock;
2607 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2608
2609 if (FAILED(result))
2610 {
2611 UNREACHABLE();
2612 systemSurface->Release();
2613
2614 return; // No sensible error to generate
2615 }
2616
2617 unsigned char *dest = (unsigned char*)pixels;
2618 unsigned short *dest16 = (unsigned short*)pixels;
2619
2620 unsigned char *source;
2621 int inputPitch;
2622 if (packReverseRowOrder)
2623 {
2624 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2625 inputPitch = -lock.Pitch;
2626 }
2627 else
2628 {
2629 source = (unsigned char*)lock.pBits;
2630 inputPitch = lock.Pitch;
2631 }
2632
2633 unsigned int fastPixelSize = 0;
2634
2635 if (desc.Format == D3DFMT_A8R8G8B8 &&
2636 format == GL_BGRA_EXT &&
2637 type == GL_UNSIGNED_BYTE)
2638 {
2639 fastPixelSize = 4;
2640 }
2641 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2642 format == GL_BGRA_EXT &&
2643 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2644 (desc.Format == D3DFMT_A1R5G5B5 &&
2645 format == GL_BGRA_EXT &&
2646 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2647 {
2648 fastPixelSize = 2;
2649 }
2650 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2651 format == GL_RGBA &&
2652 type == GL_HALF_FLOAT_OES)
2653 {
2654 fastPixelSize = 8;
2655 }
2656 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2657 format == GL_RGBA &&
2658 type == GL_FLOAT)
2659 {
2660 fastPixelSize = 16;
2661 }
2662
2663 for (int j = 0; j < rect.bottom - rect.top; j++)
2664 {
2665 if (fastPixelSize != 0)
2666 {
2667 // Fast path for formats which require no translation:
2668 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2669 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2670 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2671 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2672 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2673 //
2674 // Note that buffers with no alpha go through the slow path below.
2675 memcpy(dest + j * outputPitch,
2676 source + j * inputPitch,
2677 (rect.right - rect.left) * fastPixelSize);
2678 continue;
2679 }
2680
2681 for (int i = 0; i < rect.right - rect.left; i++)
2682 {
2683 float r;
2684 float g;
2685 float b;
2686 float a;
2687
2688 switch (desc.Format)
2689 {
2690 case D3DFMT_R5G6B5:
2691 {
2692 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2693
2694 a = 1.0f;
2695 b = (rgb & 0x001F) * (1.0f / 0x001F);
2696 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2697 r = (rgb & 0xF800) * (1.0f / 0xF800);
2698 }
2699 break;
2700 case D3DFMT_A1R5G5B5:
2701 {
2702 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2703
2704 a = (argb & 0x8000) ? 1.0f : 0.0f;
2705 b = (argb & 0x001F) * (1.0f / 0x001F);
2706 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2707 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2708 }
2709 break;
2710 case D3DFMT_A8R8G8B8:
2711 {
2712 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2713
2714 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2715 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2716 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2717 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2718 }
2719 break;
2720 case D3DFMT_X8R8G8B8:
2721 {
2722 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2723
2724 a = 1.0f;
2725 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2726 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2727 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2728 }
2729 break;
2730 case D3DFMT_A2R10G10B10:
2731 {
2732 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2733
2734 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2735 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2736 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2737 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2738 }
2739 break;
2740 case D3DFMT_A32B32G32R32F:
2741 {
2742 // float formats in D3D are stored rgba, rather than the other way round
2743 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2744 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2745 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2746 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2747 }
2748 break;
2749 case D3DFMT_A16B16G16R16F:
2750 {
2751 // float formats in D3D are stored rgba, rather than the other way round
2752 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2753 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2754 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2755 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
2756 }
2757 break;
2758 default:
2759 UNIMPLEMENTED(); // FIXME
2760 UNREACHABLE();
2761 return;
2762 }
2763
2764 switch (format)
2765 {
2766 case GL_RGBA:
2767 switch (type)
2768 {
2769 case GL_UNSIGNED_BYTE:
2770 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2771 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2772 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2773 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2774 break;
2775 default: UNREACHABLE();
2776 }
2777 break;
2778 case GL_BGRA_EXT:
2779 switch (type)
2780 {
2781 case GL_UNSIGNED_BYTE:
2782 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2783 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2784 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2785 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2786 break;
2787 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2788 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2789 // this type is packed as follows:
2790 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2791 // --------------------------------------------------------------------------------
2792 // | 4th | 3rd | 2nd | 1st component |
2793 // --------------------------------------------------------------------------------
2794 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2795 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2796 ((unsigned short)(15 * a + 0.5f) << 12)|
2797 ((unsigned short)(15 * r + 0.5f) << 8) |
2798 ((unsigned short)(15 * g + 0.5f) << 4) |
2799 ((unsigned short)(15 * b + 0.5f) << 0);
2800 break;
2801 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2802 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2803 // this type is packed as follows:
2804 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2805 // --------------------------------------------------------------------------------
2806 // | 4th | 3rd | 2nd | 1st component |
2807 // --------------------------------------------------------------------------------
2808 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2809 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2810 ((unsigned short)( a + 0.5f) << 15) |
2811 ((unsigned short)(31 * r + 0.5f) << 10) |
2812 ((unsigned short)(31 * g + 0.5f) << 5) |
2813 ((unsigned short)(31 * b + 0.5f) << 0);
2814 break;
2815 default: UNREACHABLE();
2816 }
2817 break;
2818 case GL_RGB:
2819 switch (type)
2820 {
2821 case GL_UNSIGNED_SHORT_5_6_5:
2822 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2823 ((unsigned short)(31 * b + 0.5f) << 0) |
2824 ((unsigned short)(63 * g + 0.5f) << 5) |
2825 ((unsigned short)(31 * r + 0.5f) << 11);
2826 break;
2827 case GL_UNSIGNED_BYTE:
2828 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2829 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2830 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2831 break;
2832 default: UNREACHABLE();
2833 }
2834 break;
2835 default: UNREACHABLE();
2836 }
2837 }
2838 }
2839
2840 systemSurface->UnlockRect();
2841
2842 systemSurface->Release();
2843}
2844
daniel@transgaming.comf2423652012-11-28 20:53:50 +00002845RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
2846{
2847 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2848 IDirect3DSurface9 *surface = NULL;
2849 if (depth)
2850 {
2851 surface = swapChain9->getDepthStencil();
2852 }
2853 else
2854 {
2855 surface = swapChain9->getRenderTarget();
2856 }
2857
2858 RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
2859
2860 return renderTarget;
2861}
2862
2863RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
2864{
2865 RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
2866 return renderTarget;
2867}
2868
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002869ShaderExecutable *Renderer9::loadExecutable(const void *function, size_t length, GLenum type, void *data)
daniel@transgaming.com55318902012-11-28 20:58:58 +00002870{
2871 ShaderExecutable9 *executable = NULL;
daniel@transgaming.com31240482012-11-28 21:06:41 +00002872 D3DConstantTable *table = reinterpret_cast<D3DConstantTable *>(data);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002873
2874 switch (type)
2875 {
2876 case GL_VERTEX_SHADER:
2877 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002878 IDirect3DVertexShader9 *vshader = createVertexShader((DWORD*)function, length);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002879 if (vshader)
2880 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002881 executable = new ShaderExecutable9(function, length, vshader, table);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002882 }
2883 }
2884 break;
2885 case GL_FRAGMENT_SHADER:
2886 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002887 IDirect3DPixelShader9 *pshader = createPixelShader((DWORD*)function, length);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002888 if (pshader)
2889 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002890 executable = new ShaderExecutable9(function, length, pshader, table);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002891 }
2892 }
2893 break;
2894 default:
2895 UNREACHABLE();
2896 break;
2897 }
2898
2899 return executable;
2900}
2901
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002902ShaderExecutable *Renderer9::compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, GLenum type)
2903{
2904 const char *profile = NULL;
2905
2906 switch (type)
2907 {
2908 case GL_VERTEX_SHADER:
2909 profile = getMajorShaderModel() >= 3 ? "vs_3_0" : "vs_2_0";
2910 break;
2911 case GL_FRAGMENT_SHADER:
2912 profile = getMajorShaderModel() >= 3 ? "ps_3_0" : "ps_2_0";
2913 break;
2914 default:
2915 UNREACHABLE();
2916 return NULL;
2917 }
2918
daniel@transgaming.com25e16af2012-11-28 21:05:57 +00002919 ID3DBlob *binary = compileToBinary(infoLog, shaderHLSL, profile, true);
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002920 if (!binary)
2921 return NULL;
2922
daniel@transgaming.com31240482012-11-28 21:06:41 +00002923 D3DConstantTable *constantTable = new D3DConstantTable(binary->GetBufferPointer(), binary->GetBufferSize());
daniel@transgaming.combe281b02012-11-28 21:05:48 +00002924 if (constantTable->error())
2925 {
2926 delete constantTable;
2927 binary->Release();
2928 return NULL;
2929 }
2930
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002931 ShaderExecutable *executable = loadExecutable(binary->GetBufferPointer(), binary->GetBufferSize(), type, constantTable);
daniel@transgaming.com536dd6e2012-11-28 21:00:18 +00002932 binary->Release();
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002933
2934 return executable;
2935}
2936
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002937bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
2938{
2939 return mBlit->boxFilter(source, dest);
2940}
2941
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002942D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002943{
2944 if (mD3d9Ex != NULL)
2945 {
2946 return D3DPOOL_DEFAULT;
2947 }
2948 else
2949 {
2950 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2951 {
2952 return D3DPOOL_MANAGED;
2953 }
2954 }
2955
2956 return D3DPOOL_DEFAULT;
2957}
2958
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002959bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
2960{
2961 if (source && dest)
2962 {
2963 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
2964 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
2965
2966 if (fromManaged)
2967 {
2968 D3DSURFACE_DESC desc;
2969 source->GetDesc(&desc);
2970
2971 IDirect3DSurface9 *surf = 0;
2972 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
2973
2974 if (SUCCEEDED(result))
2975 {
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00002976 Image9::copyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002977 result = device->UpdateSurface(surf, NULL, dest, NULL);
2978 surf->Release();
2979 }
2980 }
2981 else
2982 {
2983 endScene();
2984 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
2985 }
2986
2987 if (FAILED(result))
2988 {
2989 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2990 return false;
2991 }
2992 }
2993
2994 return true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00002995}
2996
daniel@transgaming.com244e1832012-12-20 20:52:35 +00002997Image *Renderer9::createImage()
2998{
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00002999 return new Image9();
daniel@transgaming.com244e1832012-12-20 20:52:35 +00003000}
3001
daniel@transgaming.comf721fdb2012-12-20 20:53:11 +00003002void Renderer9::generateMipmap(Image *dest, Image *src)
3003{
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00003004 Image9 *src9 = Image9::makeImage9(src);
3005 Image9 *dst9 = Image9::makeImage9(dest);
3006 Image9::generateMipmap(dst9, src9);
daniel@transgaming.comf721fdb2012-12-20 20:53:11 +00003007}
3008
daniel@transgaming.com413d2712012-12-20 21:11:04 +00003009TextureStorage *Renderer9::createTextureStorage2D(SwapChain *swapChain)
3010{
3011 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
3012 return new TextureStorage9_2D(this, swapChain9);
3013}
3014
3015TextureStorage *Renderer9::createTextureStorage2D(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height)
3016{
3017 return new TextureStorage9_2D(this, levels, internalformat, usage, forceRenderable, width, height);
3018}
3019
3020TextureStorage *Renderer9::createTextureStorageCube(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size)
3021{
3022 return new TextureStorage9_Cube(this, levels, internalformat, usage, forceRenderable, size);
3023}
3024
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003025}