blob: b974965a4c433664a5b3866ad9b0c64c3090067f [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.com9d4346f2012-10-31 19:52:04 +000023#include "libGLESv2/renderer/TextureStorage.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.com31b13e12012-11-28 19:34:30 +0000637 TextureStorage *texStorage = texture->getNativeTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000638 if (texStorage)
639 {
640 d3dTexture = texStorage->getBaseTexture();
641 }
642 // If we get NULL back from getBaseTexture here, something went wrong
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000643 // in the texture class and we're unexpectedly missing the d3d texture
644 ASSERT(d3dTexture != NULL);
645 }
646
647 mDevice->SetTexture(d3dSampler, d3dTexture);
648}
649
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000650void Renderer9::setRasterizerState(const gl::RasterizerState &rasterState)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000651{
652 bool rasterStateChanged = mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000653
654 if (rasterStateChanged)
655 {
656 // Set the cull mode
657 if (rasterState.cullFace)
658 {
659 mDevice->SetRenderState(D3DRS_CULLMODE, gl_d3d9::ConvertCullMode(rasterState.cullMode, rasterState.frontFace));
660 }
661 else
662 {
663 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
664 }
665
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000666 if (rasterState.polygonOffsetFill)
667 {
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000668 if (mCurDepthSize > 0)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000669 {
670 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
671
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000672 float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(mCurDepthSize));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000673 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
674 }
675 }
676 else
677 {
678 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
679 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
680 }
681
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000682 mCurRasterState = rasterState;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000683 }
684
685 mForceSetRasterState = false;
686}
687
688void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
689{
690 bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
691 bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
692 bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
693
694 if (blendStateChanged || blendColorChanged)
695 {
696 if (blendState.blend)
697 {
698 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
699
700 if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
701 blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
702 {
703 mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
704 }
705 else
706 {
707 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
708 gl::unorm<8>(blendColor.alpha),
709 gl::unorm<8>(blendColor.alpha),
710 gl::unorm<8>(blendColor.alpha)));
711 }
712
713 mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
714 mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
715 mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
716
717 if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
718 blendState.destBlendRGB != blendState.destBlendAlpha ||
719 blendState.blendEquationRGB != blendState.blendEquationAlpha)
720 {
721 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
722
723 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
724 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
725 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
726 }
727 else
728 {
729 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
730 }
731 }
732 else
733 {
734 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
735 }
736
737 if (blendState.sampleAlphaToCoverage)
738 {
739 FIXME("Sample alpha to coverage is unimplemented.");
740 }
741
742 // Set the color mask
743 bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
744 // Apparently some ATI cards have a bug where a draw with a zero color
745 // write mask can cause later draws to have incorrect results. Instead,
746 // set a nonzero color write mask but modify the blend state so that no
747 // drawing is done.
748 // http://code.google.com/p/angleproject/issues/detail?id=169
749
750 DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
751 blendState.colorMaskBlue, blendState.colorMaskAlpha);
752 if (colorMask == 0 && !zeroColorMaskAllowed)
753 {
754 // Enable green channel, but set blending so nothing will be drawn.
755 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
756 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
757
758 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
759 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
760 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
761 }
762 else
763 {
764 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
765 }
766
767 mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
768
769 mCurBlendState = blendState;
770 mCurBlendColor = blendColor;
771 }
772
773 if (sampleMaskChanged)
774 {
775 // Set the multisample mask
776 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
777 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
778
779 mCurSampleMask = sampleMask;
780 }
781
782 mForceSetBlendState = false;
783}
784
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000785void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000786 int stencilBackRef, bool frontFaceCCW)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000787{
788 bool depthStencilStateChanged = mForceSetDepthStencilState ||
789 memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000790 bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
791 stencilBackRef != mCurStencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000792 bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000793
794 if (depthStencilStateChanged)
795 {
796 if (depthStencilState.depthTest)
797 {
798 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
799 mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
800 }
801 else
802 {
803 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
804 }
805
806 mCurDepthStencilState = depthStencilState;
807 }
808
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000809 if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000810 {
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000811 if (depthStencilState.stencilTest && mCurStencilSize > 0)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000812 {
813 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
814 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
815
816 // FIXME: Unsupported by D3D9
817 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
818 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
819 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
820 if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000821 stencilRef != stencilBackRef ||
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000822 depthStencilState.stencilMask != depthStencilState.stencilBackMask)
823 {
824 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
825 return error(GL_INVALID_OPERATION);
826 }
827
828 // get the maximum size of the stencil ref
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000829 unsigned int maxStencil = (1 << mCurStencilSize) - 1;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000830
831 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
832 depthStencilState.stencilWritemask);
833 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
834 gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
835
836 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000837 (stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000838 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
839 depthStencilState.stencilMask);
840
841 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
842 gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
843 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
844 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
845 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
846 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
847
848 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
849 depthStencilState.stencilBackWritemask);
850 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
851 gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
852
853 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000854 (stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000855 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
856 depthStencilState.stencilBackMask);
857
858 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
859 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
860 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
861 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
862 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
863 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
864 }
865 else
866 {
867 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
868 }
869
870 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
871
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000872 mCurStencilRef = stencilRef;
873 mCurStencilBackRef = stencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000874 mCurFrontFaceCCW = frontFaceCCW;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000875 }
876
877 mForceSetDepthStencilState = false;
878}
879
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000880void Renderer9::setScissorRectangle(const gl::Rectangle &scissor, bool enabled)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000881{
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000882 bool scissorChanged = mForceSetScissor ||
883 memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0 ||
884 enabled != mScissorEnabled;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000885
daniel@transgaming.com04f1b332012-11-28 21:00:40 +0000886 if (scissorChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000887 {
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000888 if (enabled)
889 {
890 RECT rect;
891 rect.left = gl::clamp(scissor.x, 0, static_cast<int>(mRenderTargetDesc.width));
892 rect.top = gl::clamp(scissor.y, 0, static_cast<int>(mRenderTargetDesc.height));
893 rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(mRenderTargetDesc.width));
894 rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(mRenderTargetDesc.height));
895 mDevice->SetScissorRect(&rect);
896 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000897
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +0000898 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, enabled ? TRUE : FALSE);
899
900 mScissorEnabled = enabled;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000901 mCurScissor = scissor;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000902 }
903
904 mForceSetScissor = false;
905}
906
daniel@transgaming.com12985182012-12-20 20:56:31 +0000907bool Renderer9::setViewport(const gl::Rectangle &viewport, float zNear, float zFar, GLenum drawMode, GLenum frontFace,
908 bool ignoreViewport, gl::ProgramBinary *currentProgram, bool forceSetUniforms)
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000909{
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000910 gl::Rectangle actualViewport = viewport;
911 float actualZNear = gl::clamp01(zNear);
912 float actualZFar = gl::clamp01(zFar);
913 if (ignoreViewport)
914 {
915 actualViewport.x = 0;
916 actualViewport.y = 0;
917 actualViewport.width = mRenderTargetDesc.width;
918 actualViewport.height = mRenderTargetDesc.height;
919 actualZNear = 0.0f;
920 actualZFar = 1.0f;
921 }
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000922
923 D3DVIEWPORT9 dxViewport;
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000924 dxViewport.X = gl::clamp(actualViewport.x, 0, static_cast<int>(mRenderTargetDesc.width));
925 dxViewport.Y = gl::clamp(actualViewport.y, 0, static_cast<int>(mRenderTargetDesc.height));
926 dxViewport.Width = gl::clamp(actualViewport.width, 0, static_cast<int>(mRenderTargetDesc.width) - static_cast<int>(dxViewport.X));
927 dxViewport.Height = gl::clamp(actualViewport.height, 0, static_cast<int>(mRenderTargetDesc.height) - static_cast<int>(dxViewport.Y));
928 dxViewport.MinZ = actualZNear;
929 dxViewport.MaxZ = actualZFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000930
931 if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
932 {
933 return false; // Nothing to render
934 }
935
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000936 bool viewportChanged = mForceSetViewport || memcmp(&actualViewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
937 actualZNear != mCurNear || actualZFar != mCurFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000938 if (viewportChanged)
939 {
940 mDevice->SetViewport(&dxViewport);
941
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +0000942 mCurViewport = actualViewport;
943 mCurNear = actualZNear;
944 mCurFar = actualZFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000945 }
946
947 if (currentProgram && (viewportChanged || forceSetUniforms))
948 {
daniel@transgaming.com88853c52012-12-20 20:56:40 +0000949 currentProgram->applyDxHalfPixelSize(1.0f / dxViewport.Width, -1.0f / dxViewport.Height);
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000950
951 // These values are used for computing gl_FragCoord in Program::linkVaryings().
daniel@transgaming.com88853c52012-12-20 20:56:40 +0000952 currentProgram->applyDxCoord(actualViewport.width * 0.5f,
953 actualViewport.height * 0.5f,
954 actualViewport.x + (actualViewport.width * 0.5f),
955 actualViewport.y + (actualViewport.height * 0.5f));
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000956
daniel@transgaming.com12985182012-12-20 20:56:31 +0000957 GLfloat ccw = !gl::IsTriangleMode(drawMode) ? 0.0f : (frontFace == GL_CCW ? 1.0f : -1.0f);
daniel@transgaming.com88853c52012-12-20 20:56:40 +0000958 currentProgram->applyDxDepthFront((actualZFar - actualZNear) * 0.5f, (actualZNear + actualZFar) * 0.5f, ccw);
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000959
daniel@transgaming.com88853c52012-12-20 20:56:40 +0000960 currentProgram->applyDxDepthRange(actualZNear, actualZFar, actualZFar - actualZNear);
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +0000961 }
962
963 mForceSetViewport = false;
964 return true;
965}
966
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000967bool Renderer9::applyPrimitiveType(GLenum mode, GLsizei count)
968{
969 switch (mode)
970 {
971 case GL_POINTS:
972 mPrimitiveType = D3DPT_POINTLIST;
973 mPrimitiveCount = count;
974 break;
975 case GL_LINES:
976 mPrimitiveType = D3DPT_LINELIST;
977 mPrimitiveCount = count / 2;
978 break;
979 case GL_LINE_LOOP:
980 mPrimitiveType = D3DPT_LINESTRIP;
981 mPrimitiveCount = count - 1; // D3D doesn't support line loops, so we draw the last line separately
982 break;
983 case GL_LINE_STRIP:
984 mPrimitiveType = D3DPT_LINESTRIP;
985 mPrimitiveCount = count - 1;
986 break;
987 case GL_TRIANGLES:
988 mPrimitiveType = D3DPT_TRIANGLELIST;
989 mPrimitiveCount = count / 3;
990 break;
991 case GL_TRIANGLE_STRIP:
992 mPrimitiveType = D3DPT_TRIANGLESTRIP;
993 mPrimitiveCount = count - 2;
994 break;
995 case GL_TRIANGLE_FAN:
996 mPrimitiveType = D3DPT_TRIANGLEFAN;
997 mPrimitiveCount = count - 2;
998 break;
999 default:
1000 return error(GL_INVALID_ENUM, false);
1001 }
1002
1003 return mPrimitiveCount > 0;
1004}
1005
daniel@transgaming.come4e1a332012-12-20 20:52:09 +00001006
1007gl::Renderbuffer *Renderer9::getNullColorbuffer(gl::Renderbuffer *depthbuffer)
1008{
1009 if (!depthbuffer)
1010 {
1011 ERR("Unexpected null depthbuffer for depth-only FBO.");
1012 return NULL;
1013 }
1014
1015 GLsizei width = depthbuffer->getWidth();
1016 GLsizei height = depthbuffer->getHeight();
1017
1018 // search cached nullcolorbuffers
1019 for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1020 {
1021 if (mNullColorbufferCache[i].buffer != NULL &&
1022 mNullColorbufferCache[i].width == width &&
1023 mNullColorbufferCache[i].height == height)
1024 {
1025 mNullColorbufferCache[i].lruCount = ++mMaxNullColorbufferLRU;
1026 return mNullColorbufferCache[i].buffer;
1027 }
1028 }
1029
1030 gl::Renderbuffer *nullbuffer = new gl::Renderbuffer(this, 0, new gl::Colorbuffer(this, width, height, GL_NONE, 0));
1031
1032 // add nullbuffer to the cache
1033 NullColorbufferCacheEntry *oldest = &mNullColorbufferCache[0];
1034 for (int i = 1; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1035 {
1036 if (mNullColorbufferCache[i].lruCount < oldest->lruCount)
1037 {
1038 oldest = &mNullColorbufferCache[i];
1039 }
1040 }
1041
1042 delete oldest->buffer;
1043 oldest->buffer = nullbuffer;
1044 oldest->lruCount = ++mMaxNullColorbufferLRU;
1045 oldest->width = width;
1046 oldest->height = height;
1047
1048 return nullbuffer;
1049}
1050
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001051bool Renderer9::applyRenderTarget(gl::Framebuffer *framebuffer)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001052{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001053 // if there is no color attachment we must synthesize a NULL colorattachment
1054 // to keep the D3D runtime happy. This should only be possible if depth texturing.
1055 gl::Renderbuffer *renderbufferObject = NULL;
1056 if (framebuffer->getColorbufferType() != GL_NONE)
1057 {
1058 renderbufferObject = framebuffer->getColorbuffer();
1059 }
1060 else
1061 {
daniel@transgaming.come4e1a332012-12-20 20:52:09 +00001062 renderbufferObject = getNullColorbuffer(framebuffer->getDepthbuffer());
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001063 }
1064 if (!renderbufferObject)
1065 {
1066 ERR("unable to locate renderbuffer for FBO.");
1067 return false;
1068 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001069
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001070 bool renderTargetChanged = false;
1071 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1072 if (renderTargetSerial != mAppliedRenderTargetSerial)
1073 {
1074 // Apply the render target on the device
1075 IDirect3DSurface9 *renderTargetSurface = NULL;
1076
1077 RenderTarget *renderTarget = renderbufferObject->getRenderTarget();
1078 if (renderTarget)
1079 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001080 renderTargetSurface = RenderTarget9::makeRenderTarget9(renderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001081 }
1082
1083 if (!renderTargetSurface)
1084 {
1085 ERR("render target pointer unexpectedly null.");
1086 return false; // Context must be lost
1087 }
1088
1089 mDevice->SetRenderTarget(0, renderTargetSurface);
1090 renderTargetSurface->Release();
1091
1092 mAppliedRenderTargetSerial = renderTargetSerial;
1093 renderTargetChanged = true;
1094 }
1095
1096 gl::Renderbuffer *depthStencil = NULL;
1097 unsigned int depthbufferSerial = 0;
1098 unsigned int stencilbufferSerial = 0;
1099 if (framebuffer->getDepthbufferType() != GL_NONE)
1100 {
1101 depthStencil = framebuffer->getDepthbuffer();
1102 if (!depthStencil)
1103 {
1104 ERR("Depth stencil pointer unexpectedly null.");
1105 return false;
1106 }
1107
1108 depthbufferSerial = depthStencil->getSerial();
1109 }
1110 else if (framebuffer->getStencilbufferType() != GL_NONE)
1111 {
1112 depthStencil = framebuffer->getStencilbuffer();
1113 if (!depthStencil)
1114 {
1115 ERR("Depth stencil pointer unexpectedly null.");
1116 return false;
1117 }
1118
1119 stencilbufferSerial = depthStencil->getSerial();
1120 }
1121
1122 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1123 stencilbufferSerial != mAppliedStencilbufferSerial ||
1124 !mDepthStencilInitialized)
1125 {
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001126 unsigned int depthSize = 0;
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001127 unsigned int stencilSize = 0;
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001128
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001129 // Apply the depth stencil on the device
1130 if (depthStencil)
1131 {
1132 IDirect3DSurface9 *depthStencilSurface = NULL;
1133 RenderTarget *depthStencilRenderTarget = depthStencil->getDepthStencil();
1134
1135 if (depthStencilRenderTarget)
1136 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001137 depthStencilSurface = RenderTarget9::makeRenderTarget9(depthStencilRenderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001138 }
1139
1140 if (!depthStencilSurface)
1141 {
1142 ERR("depth stencil pointer unexpectedly null.");
1143 return false; // Context must be lost
1144 }
1145
1146 mDevice->SetDepthStencilSurface(depthStencilSurface);
1147 depthStencilSurface->Release();
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001148
1149 depthSize = depthStencil->getDepthSize();
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001150 stencilSize = depthStencil->getStencilSize();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001151 }
1152 else
1153 {
1154 mDevice->SetDepthStencilSurface(NULL);
1155 }
1156
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001157 if (!mDepthStencilInitialized || depthSize != mCurDepthSize)
1158 {
1159 mCurDepthSize = depthSize;
1160 mForceSetRasterState = true;
1161 }
1162
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001163 if (!mDepthStencilInitialized || stencilSize != mCurStencilSize)
1164 {
1165 mCurStencilSize = stencilSize;
1166 mForceSetDepthStencilState = true;
1167 }
1168
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001169 mAppliedDepthbufferSerial = depthbufferSerial;
1170 mAppliedStencilbufferSerial = stencilbufferSerial;
1171 mDepthStencilInitialized = true;
1172 }
1173
1174 if (renderTargetChanged || !mRenderTargetDescInitialized)
1175 {
1176 mForceSetScissor = true;
1177 mForceSetViewport = true;
1178
1179 mRenderTargetDesc.width = renderbufferObject->getWidth();
1180 mRenderTargetDesc.height = renderbufferObject->getHeight();
1181 mRenderTargetDesc.format = renderbufferObject->getActualFormat();
1182 mRenderTargetDescInitialized = true;
1183 }
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001184
1185 return true;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001186}
daniel@transgaming.coma734f272012-10-31 18:07:48 +00001187
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001188GLenum Renderer9::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances)
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001189{
daniel@transgaming.com31240482012-11-28 21:06:41 +00001190 TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001191 GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
1192 if (err != GL_NO_ERROR)
1193 {
1194 return err;
1195 }
1196
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001197 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, &mRepeatDraw);
1198}
1199
1200// Applies the indices and element array bindings to the Direct3D 9 device
daniel@transgaming.com31240482012-11-28 21:06:41 +00001201GLenum Renderer9::applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001202{
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001203 GLenum err = mIndexDataManager->prepareIndexData(type, count, elementArrayBuffer, indices, indexInfo);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001204
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001205 if (err == GL_NO_ERROR)
1206 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001207 if (indexInfo->serial != mAppliedIBSerial)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001208 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001209 IndexBuffer9* indexBuffer = IndexBuffer9::makeIndexBuffer9(indexInfo->indexBuffer);
1210
1211 mDevice->SetIndices(indexBuffer->getBuffer());
1212 mAppliedIBSerial = indexInfo->serial;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001213 }
1214 }
1215
1216 return err;
1217}
1218
1219void Renderer9::drawArrays(GLenum mode, GLsizei count, GLsizei instances)
1220{
1221 startScene();
1222
1223 if (mode == GL_LINE_LOOP)
1224 {
1225 drawLineLoop(count, GL_NONE, NULL, 0, NULL);
1226 }
1227 else if (instances > 0)
1228 {
daniel@transgaming.com50cc7252012-12-20 21:09:23 +00001229 StaticIndexBufferInterface *countingIB = mIndexDataManager->getCountingIndices(count);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001230 if (countingIB)
1231 {
1232 if (mAppliedIBSerial != countingIB->getSerial())
1233 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001234 IndexBuffer9 *indexBuffer = IndexBuffer9::makeIndexBuffer9(countingIB->getIndexBuffer());
1235
1236 mDevice->SetIndices(indexBuffer->getBuffer());
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001237 mAppliedIBSerial = countingIB->getSerial();
1238 }
1239
1240 for (int i = 0; i < mRepeatDraw; i++)
1241 {
1242 mDevice->DrawIndexedPrimitive(mPrimitiveType, 0, 0, count, 0, mPrimitiveCount);
1243 }
1244 }
1245 else
1246 {
1247 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
1248 return error(GL_OUT_OF_MEMORY);
1249 }
1250 }
1251 else // Regular case
1252 {
1253 mDevice->DrawPrimitive(mPrimitiveType, 0, mPrimitiveCount);
1254 }
1255}
1256
daniel@transgaming.com31240482012-11-28 21:06:41 +00001257void 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 +00001258{
1259 startScene();
1260
1261 if (mode == GL_LINE_LOOP)
1262 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001263 drawLineLoop(count, type, indices, indexInfo.minIndex, elementArrayBuffer);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001264 }
1265 else
1266 {
1267 for (int i = 0; i < mRepeatDraw; i++)
1268 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001269 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
1270 mDevice->DrawIndexedPrimitive(mPrimitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, mPrimitiveCount);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001271 }
1272 }
1273}
1274
1275void Renderer9::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer)
1276{
1277 // Get the raw indices for an indexed draw
1278 if (type != GL_NONE && elementArrayBuffer)
1279 {
1280 gl::Buffer *indexBuffer = elementArrayBuffer;
1281 intptr_t offset = reinterpret_cast<intptr_t>(indices);
1282 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
1283 }
1284
1285 UINT startIndex = 0;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001286
1287 if (get32BitIndexSupport())
1288 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001289 if (!mLineLoopIB)
1290 {
1291 mLineLoopIB = new StreamingIndexBufferInterface(this);
1292 if (!mLineLoopIB->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_INT))
1293 {
1294 delete mLineLoopIB;
1295 mLineLoopIB = NULL;
1296
1297 ERR("Could not create a 32-bit looping index buffer for GL_LINE_LOOP.");
1298 return error(GL_OUT_OF_MEMORY);
1299 }
1300 }
1301
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001302 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001303 if (!mLineLoopIB->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_INT))
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001304 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001305 ERR("Could not reserve enough space in looping index buffer for GL_LINE_LOOP.");
1306 return error(GL_OUT_OF_MEMORY);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001307 }
1308
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001309 void* mappedMemory = NULL;
1310 int offset = mLineLoopIB->mapBuffer(spaceNeeded, &mappedMemory);
1311 if (offset == -1 || mappedMemory == NULL)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001312 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001313 ERR("Could not map index buffer for GL_LINE_LOOP.");
1314 return error(GL_OUT_OF_MEMORY);
1315 }
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001316
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001317 startIndex = static_cast<UINT>(offset) / 4;
1318 unsigned int *data = reinterpret_cast<unsigned int*>(mappedMemory);
1319
1320 switch (type)
1321 {
1322 case GL_NONE: // Non-indexed draw
1323 for (int i = 0; i < count; i++)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001324 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001325 data[i] = i;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001326 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001327 data[count] = 0;
1328 break;
1329 case GL_UNSIGNED_BYTE:
1330 for (int i = 0; i < count; i++)
1331 {
1332 data[i] = static_cast<const GLubyte*>(indices)[i];
1333 }
1334 data[count] = static_cast<const GLubyte*>(indices)[0];
1335 break;
1336 case GL_UNSIGNED_SHORT:
1337 for (int i = 0; i < count; i++)
1338 {
1339 data[i] = static_cast<const GLushort*>(indices)[i];
1340 }
1341 data[count] = static_cast<const GLushort*>(indices)[0];
1342 break;
1343 case GL_UNSIGNED_INT:
1344 for (int i = 0; i < count; i++)
1345 {
1346 data[i] = static_cast<const GLuint*>(indices)[i];
1347 }
1348 data[count] = static_cast<const GLuint*>(indices)[0];
1349 break;
1350 default: UNREACHABLE();
1351 }
1352
1353 if (!mLineLoopIB->unmapBuffer())
1354 {
1355 ERR("Could not unmap index buffer for GL_LINE_LOOP.");
1356 return error(GL_OUT_OF_MEMORY);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001357 }
1358 }
1359 else
1360 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001361 if (!mLineLoopIB)
1362 {
1363 mLineLoopIB = new StreamingIndexBufferInterface(this);
1364 if (!mLineLoopIB->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_SHORT))
1365 {
1366 delete mLineLoopIB;
1367 mLineLoopIB = NULL;
1368
1369 ERR("Could not create a 16-bit looping index buffer for GL_LINE_LOOP.");
1370 return error(GL_OUT_OF_MEMORY);
1371 }
1372 }
1373
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001374 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001375 if (!mLineLoopIB->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_SHORT))
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001376 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001377 ERR("Could not reserve enough space in looping index buffer for GL_LINE_LOOP.");
1378 return error(GL_OUT_OF_MEMORY);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001379 }
1380
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001381 void* mappedMemory = NULL;
1382 int offset = mLineLoopIB->mapBuffer(spaceNeeded, &mappedMemory);
1383 if (offset == -1 || mappedMemory == NULL)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001384 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001385 ERR("Could not map index buffer for GL_LINE_LOOP.");
1386 return error(GL_OUT_OF_MEMORY);
1387 }
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001388
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001389 startIndex = static_cast<UINT>(offset) / 2;
1390 unsigned short *data = reinterpret_cast<unsigned short*>(mappedMemory);
1391
1392 switch (type)
1393 {
1394 case GL_NONE: // Non-indexed draw
1395 for (int i = 0; i < count; i++)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001396 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001397 data[i] = i;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001398 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001399 data[count] = 0;
1400 break;
1401 case GL_UNSIGNED_BYTE:
1402 for (int i = 0; i < count; i++)
1403 {
1404 data[i] = static_cast<const GLubyte*>(indices)[i];
1405 }
1406 data[count] = static_cast<const GLubyte*>(indices)[0];
1407 break;
1408 case GL_UNSIGNED_SHORT:
1409 for (int i = 0; i < count; i++)
1410 {
1411 data[i] = static_cast<const GLushort*>(indices)[i];
1412 }
1413 data[count] = static_cast<const GLushort*>(indices)[0];
1414 break;
1415 case GL_UNSIGNED_INT:
1416 for (int i = 0; i < count; i++)
1417 {
1418 data[i] = static_cast<const GLuint*>(indices)[i];
1419 }
1420 data[count] = static_cast<const GLuint*>(indices)[0];
1421 break;
1422 default: UNREACHABLE();
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001423 }
1424
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001425 if (!mLineLoopIB->unmapBuffer())
1426 {
1427 ERR("Could not unmap index buffer for GL_LINE_LOOP.");
1428 return error(GL_OUT_OF_MEMORY);
1429 }
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001430 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001431
1432 if (mAppliedIBSerial != mLineLoopIB->getSerial())
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001433 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001434 IndexBuffer9 *indexBuffer = IndexBuffer9::makeIndexBuffer9(mLineLoopIB->getIndexBuffer());
1435
1436 mDevice->SetIndices(indexBuffer->getBuffer());
1437 mAppliedIBSerial = mLineLoopIB->getSerial();
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001438 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001439
1440 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001441}
1442
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001443void Renderer9::applyShaders(gl::ProgramBinary *programBinary)
1444{
daniel@transgaming.come4991412012-12-20 20:55:34 +00001445 unsigned int programBinarySerial = programBinary->getSerial();
1446 if (programBinarySerial != mAppliedProgramBinarySerial)
1447 {
1448 ShaderExecutable *vertexExe = programBinary->getVertexExecutable();
1449 ShaderExecutable *pixelExe = programBinary->getPixelExecutable();
daniel@transgaming.com95892412012-11-28 20:59:09 +00001450
daniel@transgaming.come4991412012-12-20 20:55:34 +00001451 IDirect3DVertexShader9 *vertexShader = NULL;
1452 if (vertexExe) vertexShader = ShaderExecutable9::makeShaderExecutable9(vertexExe)->getVertexShader();
daniel@transgaming.com95892412012-11-28 20:59:09 +00001453
daniel@transgaming.come4991412012-12-20 20:55:34 +00001454 IDirect3DPixelShader9 *pixelShader = NULL;
1455 if (pixelExe) pixelShader = ShaderExecutable9::makeShaderExecutable9(pixelExe)->getPixelShader();
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001456
daniel@transgaming.come4991412012-12-20 20:55:34 +00001457 mDevice->SetPixelShader(pixelShader);
1458 mDevice->SetVertexShader(vertexShader);
1459 programBinary->dirtyAllUniforms();
1460
1461 mAppliedProgramBinarySerial = programBinarySerial;
1462 }
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001463}
1464
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001465void Renderer9::applyUniforms(const gl::UniformArray *uniformArray)
1466{
1467 for (std::vector<gl::Uniform*>::const_iterator ub = uniformArray->begin(), ue = uniformArray->end(); ub != ue; ++ub)
1468 {
1469 gl::Uniform *targetUniform = *ub;
1470
1471 if (targetUniform->dirty)
1472 {
1473 int arraySize = targetUniform->arraySize;
1474 GLfloat *f = (GLfloat*)targetUniform->data;
1475 GLint *i = (GLint*)targetUniform->data;
1476 GLboolean *b = (GLboolean*)targetUniform->data;
1477
1478 switch (targetUniform->type)
1479 {
1480 case GL_SAMPLER_2D:
1481 case GL_SAMPLER_CUBE:
1482 break;
1483 case GL_BOOL: applyUniformnbv(targetUniform, arraySize, 1, b); break;
1484 case GL_BOOL_VEC2: applyUniformnbv(targetUniform, arraySize, 2, b); break;
1485 case GL_BOOL_VEC3: applyUniformnbv(targetUniform, arraySize, 3, b); break;
1486 case GL_BOOL_VEC4: applyUniformnbv(targetUniform, arraySize, 4, b); break;
1487 case GL_FLOAT:
1488 case GL_FLOAT_VEC2:
1489 case GL_FLOAT_VEC3:
1490 case GL_FLOAT_VEC4:
1491 case GL_FLOAT_MAT2:
1492 case GL_FLOAT_MAT3:
1493 case GL_FLOAT_MAT4: applyUniformnfv(targetUniform, f); break;
1494 case GL_INT: applyUniform1iv(targetUniform, arraySize, i); break;
1495 case GL_INT_VEC2: applyUniform2iv(targetUniform, arraySize, i); break;
1496 case GL_INT_VEC3: applyUniform3iv(targetUniform, arraySize, i); break;
1497 case GL_INT_VEC4: applyUniform4iv(targetUniform, arraySize, i); break;
1498 default:
1499 UNREACHABLE();
1500 }
1501
1502 targetUniform->dirty = false;
1503 }
1504 }
1505}
1506
1507void Renderer9::applyUniformnbv(gl::Uniform *targetUniform, GLsizei count, int width, const GLboolean *v)
1508{
1509 float vector[gl::D3D9_MAX_FLOAT_CONSTANTS * 4];
1510 BOOL boolVector[gl::D3D9_MAX_BOOL_CONSTANTS];
1511
1512 if (targetUniform->ps.float4Index >= 0 || targetUniform->vs.float4Index >= 0)
1513 {
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
1531 if (targetUniform->ps.boolIndex >= 0 || targetUniform->vs.boolIndex >= 0)
1532 {
1533 int psCount = targetUniform->ps.boolIndex >= 0 ? targetUniform->ps.registerCount : 0;
1534 int vsCount = targetUniform->vs.boolIndex >= 0 ? targetUniform->vs.registerCount : 0;
1535 int copyCount = std::min(count * width, std::max(psCount, vsCount));
1536 ASSERT(copyCount <= gl::D3D9_MAX_BOOL_CONSTANTS);
1537 for (int i = 0; i < copyCount; i++)
1538 {
1539 boolVector[i] = v[i] != GL_FALSE;
1540 }
1541 }
1542
1543 if (targetUniform->ps.float4Index >= 0)
1544 {
1545 mDevice->SetPixelShaderConstantF(targetUniform->ps.float4Index, vector, targetUniform->ps.registerCount);
1546 }
1547
1548 if (targetUniform->ps.boolIndex >= 0)
1549 {
1550 mDevice->SetPixelShaderConstantB(targetUniform->ps.boolIndex, boolVector, targetUniform->ps.registerCount);
1551 }
1552
1553 if (targetUniform->vs.float4Index >= 0)
1554 {
1555 mDevice->SetVertexShaderConstantF(targetUniform->vs.float4Index, vector, targetUniform->vs.registerCount);
1556 }
1557
1558 if (targetUniform->vs.boolIndex >= 0)
1559 {
1560 mDevice->SetVertexShaderConstantB(targetUniform->vs.boolIndex, boolVector, targetUniform->vs.registerCount);
1561 }
1562}
1563
1564bool Renderer9::applyUniformnfv(gl::Uniform *targetUniform, const GLfloat *v)
1565{
1566 if (targetUniform->ps.registerCount)
1567 {
1568 mDevice->SetPixelShaderConstantF(targetUniform->ps.float4Index, v, targetUniform->ps.registerCount);
1569 }
1570
1571 if (targetUniform->vs.registerCount)
1572 {
1573 mDevice->SetVertexShaderConstantF(targetUniform->vs.float4Index, v, targetUniform->vs.registerCount);
1574 }
1575
1576 return true;
1577}
1578
1579bool Renderer9::applyUniform1iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
1580{
1581 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1582 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1583
1584 for (int i = 0; i < count; i++)
1585 {
1586 vector[i] = gl::Vector4((float)v[i], 0, 0, 0);
1587 }
1588
1589 if (targetUniform->ps.registerCount)
1590 {
1591 if (targetUniform->ps.float4Index >= 0)
1592 {
1593 mDevice->SetPixelShaderConstantF(targetUniform->ps.float4Index, (const float*)vector, targetUniform->ps.registerCount);
1594 }
1595 }
1596
1597 if (targetUniform->vs.registerCount)
1598 {
1599 if (targetUniform->vs.float4Index >= 0)
1600 {
1601 mDevice->SetVertexShaderConstantF(targetUniform->vs.float4Index, (const float *)vector, targetUniform->vs.registerCount);
1602 }
1603 }
1604
1605 return true;
1606}
1607
1608bool Renderer9::applyUniform2iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
1609{
1610 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1611 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1612
1613 for (int i = 0; i < count; i++)
1614 {
1615 vector[i] = gl::Vector4((float)v[0], (float)v[1], 0, 0);
1616
1617 v += 2;
1618 }
1619
1620 applyUniformniv(targetUniform, count, vector);
1621
1622 return true;
1623}
1624
1625bool Renderer9::applyUniform3iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
1626{
1627 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1628 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1629
1630 for (int i = 0; i < count; i++)
1631 {
1632 vector[i] = gl::Vector4((float)v[0], (float)v[1], (float)v[2], 0);
1633
1634 v += 3;
1635 }
1636
1637 applyUniformniv(targetUniform, count, vector);
1638
1639 return true;
1640}
1641
1642bool Renderer9::applyUniform4iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
1643{
1644 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1645 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1646
1647 for (int i = 0; i < count; i++)
1648 {
1649 vector[i] = gl::Vector4((float)v[0], (float)v[1], (float)v[2], (float)v[3]);
1650
1651 v += 4;
1652 }
1653
1654 applyUniformniv(targetUniform, count, vector);
1655
1656 return true;
1657}
1658
1659void Renderer9::applyUniformniv(gl::Uniform *targetUniform, GLsizei count, const gl::Vector4 *vector)
1660{
1661 if (targetUniform->ps.registerCount)
1662 {
1663 ASSERT(targetUniform->ps.float4Index >= 0);
1664 mDevice->SetPixelShaderConstantF(targetUniform->ps.float4Index, (const float *)vector, targetUniform->ps.registerCount);
1665 }
1666
1667 if (targetUniform->vs.registerCount)
1668 {
1669 ASSERT(targetUniform->vs.float4Index >= 0);
1670 mDevice->SetVertexShaderConstantF(targetUniform->vs.float4Index, (const float *)vector, targetUniform->vs.registerCount);
1671 }
1672}
1673
daniel@transgaming.com084a2572012-11-28 20:55:17 +00001674void Renderer9::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001675{
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001676 D3DCOLOR color = D3DCOLOR_ARGB(gl::unorm<8>(clearParams.colorClearValue.alpha),
1677 gl::unorm<8>(clearParams.colorClearValue.red),
1678 gl::unorm<8>(clearParams.colorClearValue.green),
1679 gl::unorm<8>(clearParams.colorClearValue.blue));
1680 float depth = gl::clamp01(clearParams.depthClearValue);
1681 int stencil = clearParams.stencilClearValue & 0x000000FF;
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001682
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001683 unsigned int stencilUnmasked = 0x0;
1684 if ((clearParams.mask & GL_STENCIL_BUFFER_BIT) && frameBuffer->hasStencil())
1685 {
1686 unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
1687 stencilUnmasked = (0x1 << stencilSize) - 1;
1688 }
1689
1690 bool alphaUnmasked = (gl::GetAlphaSize(mRenderTargetDesc.format) == 0) || clearParams.colorMaskAlpha;
1691
1692 const bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
1693 (clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
1694 const bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
1695 !(clearParams.colorMaskRed && clearParams.colorMaskGreen &&
1696 clearParams.colorMaskBlue && alphaUnmasked);
1697
1698 if (needMaskedColorClear || needMaskedStencilClear)
1699 {
1700 // State which is altered in all paths from this point to the clear call is saved.
1701 // State which is altered in only some paths will be flagged dirty in the case that
1702 // that path is taken.
1703 HRESULT hr;
1704 if (mMaskedClearSavedState == NULL)
1705 {
1706 hr = mDevice->BeginStateBlock();
1707 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1708
1709 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1710 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1711 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1712 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1713 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1714 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1715 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1716 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1717 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1718 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1719 mDevice->SetPixelShader(NULL);
1720 mDevice->SetVertexShader(NULL);
1721 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
1722 mDevice->SetStreamSource(0, NULL, 0, 0);
1723 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1724 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1725 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1726 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1727 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1728 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1729 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1730
1731 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1732 {
1733 mDevice->SetStreamSourceFreq(i, 1);
1734 }
1735
1736 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
1737 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1738 }
1739
1740 ASSERT(mMaskedClearSavedState != NULL);
1741
1742 if (mMaskedClearSavedState != NULL)
1743 {
1744 hr = mMaskedClearSavedState->Capture();
1745 ASSERT(SUCCEEDED(hr));
1746 }
1747
1748 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1749 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1750 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1751 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1752 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1753 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1754 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1755 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1756
1757 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1758 {
1759 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE,
1760 gl_d3d9::ConvertColorMask(clearParams.colorMaskRed,
1761 clearParams.colorMaskGreen,
1762 clearParams.colorMaskBlue,
1763 clearParams.colorMaskAlpha));
1764 }
1765 else
1766 {
1767 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1768 }
1769
1770 if (stencilUnmasked != 0x0 && (clearParams.mask & GL_STENCIL_BUFFER_BIT))
1771 {
1772 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
1773 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
1774 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
1775 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
1776 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
1777 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
1778 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
1779 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
1780 }
1781 else
1782 {
1783 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1784 }
1785
1786 mDevice->SetPixelShader(NULL);
1787 mDevice->SetVertexShader(NULL);
1788 mDevice->SetFVF(D3DFVF_XYZRHW);
1789 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1790 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1791 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1792 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1793 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1794 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1795 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1796
1797 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1798 {
1799 mDevice->SetStreamSourceFreq(i, 1);
1800 }
1801
1802 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
1803 quad[0][0] = -0.5f;
1804 quad[0][1] = mRenderTargetDesc.height - 0.5f;
1805 quad[0][2] = 0.0f;
1806 quad[0][3] = 1.0f;
1807
1808 quad[1][0] = mRenderTargetDesc.width - 0.5f;
1809 quad[1][1] = mRenderTargetDesc.height - 0.5f;
1810 quad[1][2] = 0.0f;
1811 quad[1][3] = 1.0f;
1812
1813 quad[2][0] = -0.5f;
1814 quad[2][1] = -0.5f;
1815 quad[2][2] = 0.0f;
1816 quad[2][3] = 1.0f;
1817
1818 quad[3][0] = mRenderTargetDesc.width - 0.5f;
1819 quad[3][1] = -0.5f;
1820 quad[3][2] = 0.0f;
1821 quad[3][3] = 1.0f;
1822
1823 startScene();
1824 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
1825
1826 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1827 {
1828 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
1829 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
1830 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
1831 }
1832
1833 if (mMaskedClearSavedState != NULL)
1834 {
1835 mMaskedClearSavedState->Apply();
1836 }
1837 }
1838 else if (clearParams.mask)
1839 {
1840 DWORD dxClearFlags = 0;
1841 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1842 {
1843 dxClearFlags |= D3DCLEAR_TARGET;
1844 }
1845 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1846 {
1847 dxClearFlags |= D3DCLEAR_ZBUFFER;
1848 }
1849 if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
1850 {
1851 dxClearFlags |= D3DCLEAR_STENCIL;
1852 }
1853
1854 mDevice->Clear(0, NULL, dxClearFlags, color, depth, stencil);
1855 }
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001856}
1857
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001858void Renderer9::markAllStateDirty()
1859{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001860 mAppliedRenderTargetSerial = 0;
1861 mAppliedDepthbufferSerial = 0;
1862 mAppliedStencilbufferSerial = 0;
1863 mDepthStencilInitialized = false;
1864 mRenderTargetDescInitialized = false;
1865
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001866 mForceSetDepthStencilState = true;
1867 mForceSetRasterState = true;
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001868 mForceSetScissor = true;
1869 mForceSetViewport = true;
daniel@transgaming.com9a067372012-12-20 20:55:24 +00001870 mForceSetBlendState = true;
1871
1872 mAppliedIBSerial = 0;
daniel@transgaming.come4991412012-12-20 20:55:34 +00001873 mAppliedProgramBinarySerial = 0;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001874
1875 mVertexDeclarationCache.markStateDirty();
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001876}
1877
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001878void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001879{
1880 while (!mEventQueryPool.empty())
1881 {
1882 mEventQueryPool.back()->Release();
1883 mEventQueryPool.pop_back();
1884 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001885
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001886 if (mMaskedClearSavedState)
1887 {
1888 mMaskedClearSavedState->Release();
1889 mMaskedClearSavedState = NULL;
1890 }
1891
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001892 mVertexShaderCache.clear();
1893 mPixelShaderCache.clear();
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001894
daniel@transgaming.come569fc52012-11-28 20:56:02 +00001895 delete mBlit;
1896 mBlit = NULL;
1897
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001898 delete mVertexDataManager;
1899 mVertexDataManager = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001900
1901 delete mIndexDataManager;
1902 mIndexDataManager = NULL;
1903
1904 delete mLineLoopIB;
1905 mLineLoopIB = NULL;
daniel@transgaming.come4e1a332012-12-20 20:52:09 +00001906
1907 for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1908 {
1909 delete mNullColorbufferCache[i].buffer;
1910 mNullColorbufferCache[i].buffer = NULL;
1911 }
1912
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001913}
1914
1915
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001916void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001917{
1918 mDeviceLost = true;
1919}
1920
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001921bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001922{
1923 return mDeviceLost;
1924}
1925
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001926// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001927bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001928{
1929 bool isLost = false;
1930
1931 if (mDeviceEx)
1932 {
1933 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
1934 }
1935 else if (mDevice)
1936 {
1937 isLost = FAILED(mDevice->TestCooperativeLevel());
1938 }
1939 else
1940 {
1941 // No device yet, so no reset required
1942 }
1943
1944 if (isLost)
1945 {
1946 // ensure we note the device loss --
1947 // we'll probably get this done again by markDeviceLost
1948 // but best to remember it!
1949 // Note that we don't want to clear the device loss status here
1950 // -- this needs to be done by resetDevice
1951 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001952 if (notify)
1953 {
1954 mDisplay->notifyDeviceLost();
1955 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001956 }
1957
1958 return isLost;
1959}
1960
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001961bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001962{
1963 HRESULT status = D3D_OK;
1964
1965 if (mDeviceEx)
1966 {
1967 status = mDeviceEx->CheckDeviceState(NULL);
1968 }
1969 else if (mDevice)
1970 {
1971 status = mDevice->TestCooperativeLevel();
1972 }
1973
1974 switch (status)
1975 {
1976 case D3DERR_DEVICENOTRESET:
1977 case D3DERR_DEVICEHUNG:
1978 return true;
1979 default:
1980 return false;
1981 }
1982}
1983
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001984bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001985{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001986 releaseDeviceResources();
1987
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001988 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
1989
1990 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001991 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001992 int attempts = 3;
1993
1994 while (lost && attempts > 0)
1995 {
1996 if (mDeviceEx)
1997 {
1998 Sleep(500); // Give the graphics driver some CPU time
1999 result = mDeviceEx->ResetEx(&presentParameters, NULL);
2000 }
2001 else
2002 {
2003 result = mDevice->TestCooperativeLevel();
2004 while (result == D3DERR_DEVICELOST)
2005 {
2006 Sleep(100); // Give the graphics driver some CPU time
2007 result = mDevice->TestCooperativeLevel();
2008 }
2009
2010 if (result == D3DERR_DEVICENOTRESET)
2011 {
2012 result = mDevice->Reset(&presentParameters);
2013 }
2014 }
2015
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00002016 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002017 attempts --;
2018 }
2019
2020 if (FAILED(result))
2021 {
2022 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
2023 return false;
2024 }
2025
2026 // reset device defaults
2027 initializeDevice();
2028 mDeviceLost = false;
2029
2030 return true;
2031}
2032
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002033DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002034{
2035 return mAdapterIdentifier.VendorId;
2036}
2037
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002038const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002039{
2040 return mAdapterIdentifier.Description;
2041}
2042
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002043GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002044{
2045 return mAdapterIdentifier.DeviceIdentifier;
2046}
2047
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002048void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002049{
2050 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
2051 {
2052 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
2053 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
2054
2055 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
2056 }
2057}
2058
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002059bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002060{
2061 D3DDISPLAYMODE currentDisplayMode;
2062 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2063
2064 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
2065}
2066
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002067bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002068{
2069 D3DDISPLAYMODE currentDisplayMode;
2070 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2071
2072 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
2073}
2074
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002075bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002076{
2077 D3DDISPLAYMODE currentDisplayMode;
2078 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2079
2080 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
2081}
2082
2083// we use INTZ for depth textures in Direct3D9
2084// we also want NULL texture support to ensure the we can make depth-only FBOs
2085// see http://aras-p.info/texts/D3D9GPUHacks.html
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002086bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002087{
2088 D3DDISPLAYMODE currentDisplayMode;
2089 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2090
2091 bool intz = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
2092 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ));
2093 bool null = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
2094 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
2095
2096 return intz && null;
2097}
2098
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002099bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002100{
2101 D3DDISPLAYMODE currentDisplayMode;
2102 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2103
2104 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
2105 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
2106 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
2107 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
2108
2109 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
2110 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F))&&
2111 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
2112 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
2113
2114 if (!*filtering && !*renderable)
2115 {
2116 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
2117 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
2118 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
2119 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
2120 }
2121 else
2122 {
2123 return true;
2124 }
2125}
2126
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002127bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002128{
2129 D3DDISPLAYMODE currentDisplayMode;
2130 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2131
2132 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
2133 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
2134 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
2135 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
2136
2137 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
2138 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
2139 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
2140 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
2141
2142 if (!*filtering && !*renderable)
2143 {
2144 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
2145 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
2146 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
2147 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
2148 }
2149 else
2150 {
2151 return true;
2152 }
2153}
2154
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002155bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002156{
2157 D3DDISPLAYMODE currentDisplayMode;
2158 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2159
2160 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
2161}
2162
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002163bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002164{
2165 D3DDISPLAYMODE currentDisplayMode;
2166 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2167
2168 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
2169}
2170
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002171bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002172{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00002173 return mSupportsTextureFilterAnisotropy;
2174}
2175
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002176float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00002177{
2178 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002179 {
2180 return mDeviceCaps.MaxAnisotropy;
2181 }
2182 return 1.0f;
2183}
2184
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002185bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002186{
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002187 IDirect3DQuery9 *query = allocateEventQuery();
2188 if (query)
2189 {
2190 freeEventQuery(query);
2191 return true;
2192 }
2193 else
2194 {
2195 return false;
2196 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002197 return true;
2198}
2199
2200// Only Direct3D 10 ready devices support all the necessary vertex texture formats.
2201// We test this using D3D9 by checking support for the R16F format.
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002202bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002203{
2204 if (!mDevice || mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(3, 0))
2205 {
2206 return false;
2207 }
2208
2209 D3DDISPLAYMODE currentDisplayMode;
2210 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2211
2212 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F);
2213
2214 return SUCCEEDED(result);
2215}
2216
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002217bool Renderer9::getNonPower2TextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002218{
2219 return mSupportsNonPower2Textures;
2220}
2221
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002222bool Renderer9::getOcclusionQuerySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002223{
2224 if (!mDevice)
2225 {
2226 return false;
2227 }
2228
2229 IDirect3DQuery9 *query = NULL;
2230 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query);
2231 if (SUCCEEDED(result) && query)
2232 {
2233 query->Release();
2234 return true;
2235 }
2236 else
2237 {
2238 return false;
2239 }
2240}
2241
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002242bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002243{
2244 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
2245}
2246
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002247bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00002248{
2249 // PIX doesn't seem to support using share handles, so disable them.
2250 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00002251 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00002252}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002253
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00002254int Renderer9::getMajorShaderModel() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002255{
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00002256 return D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion);
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002257}
2258
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002259float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002260{
2261 return mDeviceCaps.MaxPointSize;
2262}
2263
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002264int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002265{
2266 return (int)mDeviceCaps.MaxTextureWidth;
2267}
2268
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002269int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002270{
2271 return (int)mDeviceCaps.MaxTextureHeight;
2272}
2273
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002274bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002275{
2276 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
2277}
2278
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002279DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002280{
2281 return mDeviceCaps.DeclTypes;
2282}
2283
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002284int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002285{
2286 return mMinSwapInterval;
2287}
2288
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002289int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002290{
2291 return mMaxSwapInterval;
2292}
2293
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002294int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002295{
2296 return mMaxSupportedSamples;
2297}
2298
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002299int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002300{
2301 if (requested == 0)
2302 {
2303 return requested;
2304 }
2305
2306 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
2307 if (itr == mMultiSampleSupport.end())
2308 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00002309 if (format == D3DFMT_UNKNOWN)
2310 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002311 return -1;
2312 }
2313
2314 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
2315 {
2316 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
2317 {
2318 return i;
2319 }
2320 }
2321
2322 return -1;
2323}
2324
daniel@transgaming.coma9571682012-11-28 19:33:08 +00002325D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
2326{
2327 switch (internalformat)
2328 {
2329 case GL_DEPTH_COMPONENT16:
2330 case GL_DEPTH_COMPONENT32_OES:
2331 case GL_DEPTH24_STENCIL8_OES:
2332 return D3DFMT_INTZ;
2333 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
2334 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
2335 return D3DFMT_DXT1;
2336 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
2337 return D3DFMT_DXT3;
2338 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
2339 return D3DFMT_DXT5;
2340 case GL_RGBA32F_EXT:
2341 case GL_RGB32F_EXT:
2342 case GL_ALPHA32F_EXT:
2343 case GL_LUMINANCE32F_EXT:
2344 case GL_LUMINANCE_ALPHA32F_EXT:
2345 return D3DFMT_A32B32G32R32F;
2346 case GL_RGBA16F_EXT:
2347 case GL_RGB16F_EXT:
2348 case GL_ALPHA16F_EXT:
2349 case GL_LUMINANCE16F_EXT:
2350 case GL_LUMINANCE_ALPHA16F_EXT:
2351 return D3DFMT_A16B16G16R16F;
2352 case GL_LUMINANCE8_EXT:
2353 if (getLuminanceTextureSupport())
2354 {
2355 return D3DFMT_L8;
2356 }
2357 break;
2358 case GL_LUMINANCE8_ALPHA8_EXT:
2359 if (getLuminanceAlphaTextureSupport())
2360 {
2361 return D3DFMT_A8L8;
2362 }
2363 break;
2364 case GL_RGB8_OES:
2365 case GL_RGB565:
2366 return D3DFMT_X8R8G8B8;
2367 }
2368
2369 return D3DFMT_A8R8G8B8;
2370}
2371
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002372bool Renderer9::copyToRenderTarget(TextureStorage2D *dest, TextureStorage2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002373{
2374 bool result = false;
2375
2376 if (source && dest)
2377 {
2378 int levels = source->levelCount();
2379 for (int i = 0; i < levels; ++i)
2380 {
2381 IDirect3DSurface9 *srcSurf = source->getSurfaceLevel(i, false);
2382 IDirect3DSurface9 *dstSurf = dest->getSurfaceLevel(i, false);
2383
2384 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2385
2386 if (srcSurf) srcSurf->Release();
2387 if (dstSurf) dstSurf->Release();
2388
2389 if (!result)
2390 return false;
2391 }
2392 }
2393
2394 return result;
2395}
2396
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002397bool Renderer9::copyToRenderTarget(TextureStorageCubeMap *dest, TextureStorageCubeMap *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002398{
2399 bool result = false;
2400
2401 if (source && dest)
2402 {
2403 int levels = source->levelCount();
2404 for (int f = 0; f < 6; f++)
2405 {
2406 for (int i = 0; i < levels; i++)
2407 {
2408 IDirect3DSurface9 *srcSurf = source->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
2409 IDirect3DSurface9 *dstSurf = dest->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
2410
2411 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2412
2413 if (srcSurf) srcSurf->Release();
2414 if (dstSurf) dstSurf->Release();
2415
2416 if (!result)
2417 return false;
2418 }
2419 }
2420 }
2421
2422 return result;
2423}
2424
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002425D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002426{
2427 if (mD3d9Ex != NULL)
2428 {
2429 return D3DPOOL_DEFAULT;
2430 }
2431 else
2432 {
2433 if (!(usage & D3DUSAGE_DYNAMIC))
2434 {
2435 return D3DPOOL_MANAGED;
2436 }
2437 }
2438
2439 return D3DPOOL_DEFAULT;
2440}
2441
daniel@transgaming.com38380882012-11-28 19:36:39 +00002442bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2443 GLint xoffset, GLint yoffset, TextureStorage2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002444{
2445 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
2446}
2447
daniel@transgaming.com38380882012-11-28 19:36:39 +00002448bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2449 GLint xoffset, GLint yoffset, TextureStorageCubeMap *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002450{
2451 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
2452}
2453
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002454bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
2455 bool blitRenderTarget, bool blitDepthStencil)
2456{
2457 endScene();
2458
2459 if (blitRenderTarget)
2460 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002461 gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer();
2462 gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer();
2463 RenderTarget9 *readRenderTarget = NULL;
2464 RenderTarget9 *drawRenderTarget = NULL;
2465 IDirect3DSurface9* readSurface = NULL;
2466 IDirect3DSurface9* drawSurface = NULL;
2467
2468 if (readBuffer)
2469 {
2470 readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
2471 }
2472 if (drawBuffer)
2473 {
2474 drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
2475 }
2476
2477 if (readRenderTarget)
2478 {
2479 readSurface = readRenderTarget->getSurface();
2480 }
2481 if (drawRenderTarget)
2482 {
2483 drawSurface = drawRenderTarget->getSurface();
2484 }
2485
2486 if (!readSurface || !drawSurface)
2487 {
2488 ERR("Failed to retrieve the render target.");
2489 return error(GL_OUT_OF_MEMORY, false);
2490 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002491
2492 RECT srcRect, dstRect;
2493 RECT *srcRectPtr = NULL;
2494 RECT *dstRectPtr = NULL;
2495
2496 if (readRect)
2497 {
2498 srcRect.left = readRect->x;
2499 srcRect.right = readRect->x + readRect->width;
2500 srcRect.top = readRect->y;
2501 srcRect.bottom = readRect->y + readRect->height;
2502 srcRectPtr = &srcRect;
2503 }
2504
2505 if (drawRect)
2506 {
2507 dstRect.left = drawRect->x;
2508 dstRect.right = drawRect->x + drawRect->width;
2509 dstRect.top = drawRect->y;
2510 dstRect.bottom = drawRect->y + drawRect->height;
2511 dstRectPtr = &dstRect;
2512 }
2513
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002514 HRESULT result = mDevice->StretchRect(readSurface, srcRectPtr, drawSurface, dstRectPtr, D3DTEXF_NONE);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002515
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002516 readSurface->Release();
2517 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002518
2519 if (FAILED(result))
2520 {
2521 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2522 return false;
2523 }
2524 }
2525
2526 if (blitDepthStencil)
2527 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002528 gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
2529 gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
2530 RenderTarget9 *readDepthStencil = NULL;
2531 RenderTarget9 *drawDepthStencil = NULL;
2532 IDirect3DSurface9* readSurface = NULL;
2533 IDirect3DSurface9* drawSurface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002534
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002535 if (readBuffer)
2536 {
2537 readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
2538 }
2539 if (drawBuffer)
2540 {
2541 drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
2542 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002543
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002544 if (readDepthStencil)
2545 {
2546 readSurface = readDepthStencil->getSurface();
2547 }
2548 if (drawDepthStencil)
2549 {
2550 drawSurface = drawDepthStencil->getSurface();
2551 }
2552
2553 if (!readSurface || !drawSurface)
2554 {
2555 ERR("Failed to retrieve the render target.");
2556 return error(GL_OUT_OF_MEMORY, false);
2557 }
2558
2559 HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
2560
2561 readSurface->Release();
2562 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002563
2564 if (FAILED(result))
2565 {
2566 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2567 return false;
2568 }
2569 }
2570
2571 return true;
2572}
2573
2574void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
2575 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
2576{
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002577 RenderTarget9 *renderTarget = NULL;
2578 IDirect3DSurface9 *surface = NULL;
2579 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
2580
2581 if (colorbuffer)
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002582 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002583 renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
2584 }
2585
2586 if (renderTarget)
2587 {
2588 surface = renderTarget->getSurface();
2589 }
2590
2591 if (!surface)
2592 {
2593 // context must be lost
2594 return;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002595 }
2596
2597 D3DSURFACE_DESC desc;
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002598 surface->GetDesc(&desc);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002599
2600 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2601 {
2602 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002603 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002604 return error(GL_OUT_OF_MEMORY);
2605 }
2606
2607 HRESULT result;
2608 IDirect3DSurface9 *systemSurface = NULL;
2609 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
2610 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2611 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2612 if (directToPixels)
2613 {
2614 // Use the pixels ptr as a shared handle to write directly into client's memory
2615 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2616 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2617 if (FAILED(result))
2618 {
2619 // Try again without the shared handle
2620 directToPixels = false;
2621 }
2622 }
2623
2624 if (!directToPixels)
2625 {
2626 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2627 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2628 if (FAILED(result))
2629 {
2630 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002631 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002632 return error(GL_OUT_OF_MEMORY);
2633 }
2634 }
2635
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002636 result = mDevice->GetRenderTargetData(surface, systemSurface);
2637 surface->Release();
2638 surface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002639
2640 if (FAILED(result))
2641 {
2642 systemSurface->Release();
2643
2644 // It turns out that D3D will sometimes produce more error
2645 // codes than those documented.
daniel@transgaming.com414c9162012-11-28 20:54:57 +00002646 if (checkDeviceLost(result))
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002647 return error(GL_OUT_OF_MEMORY);
2648 else
2649 {
2650 UNREACHABLE();
2651 return;
2652 }
2653
2654 }
2655
2656 if (directToPixels)
2657 {
2658 systemSurface->Release();
2659 return;
2660 }
2661
2662 RECT rect;
2663 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
2664 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
2665 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2666 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2667
2668 D3DLOCKED_RECT lock;
2669 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2670
2671 if (FAILED(result))
2672 {
2673 UNREACHABLE();
2674 systemSurface->Release();
2675
2676 return; // No sensible error to generate
2677 }
2678
2679 unsigned char *dest = (unsigned char*)pixels;
2680 unsigned short *dest16 = (unsigned short*)pixels;
2681
2682 unsigned char *source;
2683 int inputPitch;
2684 if (packReverseRowOrder)
2685 {
2686 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2687 inputPitch = -lock.Pitch;
2688 }
2689 else
2690 {
2691 source = (unsigned char*)lock.pBits;
2692 inputPitch = lock.Pitch;
2693 }
2694
2695 unsigned int fastPixelSize = 0;
2696
2697 if (desc.Format == D3DFMT_A8R8G8B8 &&
2698 format == GL_BGRA_EXT &&
2699 type == GL_UNSIGNED_BYTE)
2700 {
2701 fastPixelSize = 4;
2702 }
2703 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2704 format == GL_BGRA_EXT &&
2705 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2706 (desc.Format == D3DFMT_A1R5G5B5 &&
2707 format == GL_BGRA_EXT &&
2708 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2709 {
2710 fastPixelSize = 2;
2711 }
2712 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2713 format == GL_RGBA &&
2714 type == GL_HALF_FLOAT_OES)
2715 {
2716 fastPixelSize = 8;
2717 }
2718 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2719 format == GL_RGBA &&
2720 type == GL_FLOAT)
2721 {
2722 fastPixelSize = 16;
2723 }
2724
2725 for (int j = 0; j < rect.bottom - rect.top; j++)
2726 {
2727 if (fastPixelSize != 0)
2728 {
2729 // Fast path for formats which require no translation:
2730 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2731 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2732 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2733 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2734 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2735 //
2736 // Note that buffers with no alpha go through the slow path below.
2737 memcpy(dest + j * outputPitch,
2738 source + j * inputPitch,
2739 (rect.right - rect.left) * fastPixelSize);
2740 continue;
2741 }
2742
2743 for (int i = 0; i < rect.right - rect.left; i++)
2744 {
2745 float r;
2746 float g;
2747 float b;
2748 float a;
2749
2750 switch (desc.Format)
2751 {
2752 case D3DFMT_R5G6B5:
2753 {
2754 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2755
2756 a = 1.0f;
2757 b = (rgb & 0x001F) * (1.0f / 0x001F);
2758 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2759 r = (rgb & 0xF800) * (1.0f / 0xF800);
2760 }
2761 break;
2762 case D3DFMT_A1R5G5B5:
2763 {
2764 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2765
2766 a = (argb & 0x8000) ? 1.0f : 0.0f;
2767 b = (argb & 0x001F) * (1.0f / 0x001F);
2768 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2769 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2770 }
2771 break;
2772 case D3DFMT_A8R8G8B8:
2773 {
2774 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2775
2776 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2777 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2778 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2779 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2780 }
2781 break;
2782 case D3DFMT_X8R8G8B8:
2783 {
2784 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2785
2786 a = 1.0f;
2787 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2788 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2789 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2790 }
2791 break;
2792 case D3DFMT_A2R10G10B10:
2793 {
2794 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2795
2796 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2797 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2798 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2799 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2800 }
2801 break;
2802 case D3DFMT_A32B32G32R32F:
2803 {
2804 // float formats in D3D are stored rgba, rather than the other way round
2805 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2806 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2807 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2808 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2809 }
2810 break;
2811 case D3DFMT_A16B16G16R16F:
2812 {
2813 // float formats in D3D are stored rgba, rather than the other way round
2814 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2815 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2816 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2817 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
2818 }
2819 break;
2820 default:
2821 UNIMPLEMENTED(); // FIXME
2822 UNREACHABLE();
2823 return;
2824 }
2825
2826 switch (format)
2827 {
2828 case GL_RGBA:
2829 switch (type)
2830 {
2831 case GL_UNSIGNED_BYTE:
2832 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2833 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2834 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2835 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2836 break;
2837 default: UNREACHABLE();
2838 }
2839 break;
2840 case GL_BGRA_EXT:
2841 switch (type)
2842 {
2843 case GL_UNSIGNED_BYTE:
2844 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2845 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2846 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2847 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2848 break;
2849 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2850 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2851 // this type is packed as follows:
2852 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2853 // --------------------------------------------------------------------------------
2854 // | 4th | 3rd | 2nd | 1st component |
2855 // --------------------------------------------------------------------------------
2856 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2857 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2858 ((unsigned short)(15 * a + 0.5f) << 12)|
2859 ((unsigned short)(15 * r + 0.5f) << 8) |
2860 ((unsigned short)(15 * g + 0.5f) << 4) |
2861 ((unsigned short)(15 * b + 0.5f) << 0);
2862 break;
2863 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2864 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2865 // this type is packed as follows:
2866 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2867 // --------------------------------------------------------------------------------
2868 // | 4th | 3rd | 2nd | 1st component |
2869 // --------------------------------------------------------------------------------
2870 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2871 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2872 ((unsigned short)( a + 0.5f) << 15) |
2873 ((unsigned short)(31 * r + 0.5f) << 10) |
2874 ((unsigned short)(31 * g + 0.5f) << 5) |
2875 ((unsigned short)(31 * b + 0.5f) << 0);
2876 break;
2877 default: UNREACHABLE();
2878 }
2879 break;
2880 case GL_RGB:
2881 switch (type)
2882 {
2883 case GL_UNSIGNED_SHORT_5_6_5:
2884 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2885 ((unsigned short)(31 * b + 0.5f) << 0) |
2886 ((unsigned short)(63 * g + 0.5f) << 5) |
2887 ((unsigned short)(31 * r + 0.5f) << 11);
2888 break;
2889 case GL_UNSIGNED_BYTE:
2890 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2891 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2892 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2893 break;
2894 default: UNREACHABLE();
2895 }
2896 break;
2897 default: UNREACHABLE();
2898 }
2899 }
2900 }
2901
2902 systemSurface->UnlockRect();
2903
2904 systemSurface->Release();
2905}
2906
daniel@transgaming.comf2423652012-11-28 20:53:50 +00002907RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
2908{
2909 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2910 IDirect3DSurface9 *surface = NULL;
2911 if (depth)
2912 {
2913 surface = swapChain9->getDepthStencil();
2914 }
2915 else
2916 {
2917 surface = swapChain9->getRenderTarget();
2918 }
2919
2920 RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
2921
2922 return renderTarget;
2923}
2924
2925RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
2926{
2927 RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
2928 return renderTarget;
2929}
2930
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002931ShaderExecutable *Renderer9::loadExecutable(const void *function, size_t length, GLenum type, void *data)
daniel@transgaming.com55318902012-11-28 20:58:58 +00002932{
2933 ShaderExecutable9 *executable = NULL;
daniel@transgaming.com31240482012-11-28 21:06:41 +00002934 D3DConstantTable *table = reinterpret_cast<D3DConstantTable *>(data);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002935
2936 switch (type)
2937 {
2938 case GL_VERTEX_SHADER:
2939 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002940 IDirect3DVertexShader9 *vshader = createVertexShader((DWORD*)function, length);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002941 if (vshader)
2942 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002943 executable = new ShaderExecutable9(function, length, vshader, table);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002944 }
2945 }
2946 break;
2947 case GL_FRAGMENT_SHADER:
2948 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002949 IDirect3DPixelShader9 *pshader = createPixelShader((DWORD*)function, length);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002950 if (pshader)
2951 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002952 executable = new ShaderExecutable9(function, length, pshader, table);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002953 }
2954 }
2955 break;
2956 default:
2957 UNREACHABLE();
2958 break;
2959 }
2960
2961 return executable;
2962}
2963
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002964ShaderExecutable *Renderer9::compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, GLenum type)
2965{
2966 const char *profile = NULL;
2967
2968 switch (type)
2969 {
2970 case GL_VERTEX_SHADER:
2971 profile = getMajorShaderModel() >= 3 ? "vs_3_0" : "vs_2_0";
2972 break;
2973 case GL_FRAGMENT_SHADER:
2974 profile = getMajorShaderModel() >= 3 ? "ps_3_0" : "ps_2_0";
2975 break;
2976 default:
2977 UNREACHABLE();
2978 return NULL;
2979 }
2980
daniel@transgaming.com25e16af2012-11-28 21:05:57 +00002981 ID3DBlob *binary = compileToBinary(infoLog, shaderHLSL, profile, true);
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002982 if (!binary)
2983 return NULL;
2984
daniel@transgaming.com31240482012-11-28 21:06:41 +00002985 D3DConstantTable *constantTable = new D3DConstantTable(binary->GetBufferPointer(), binary->GetBufferSize());
daniel@transgaming.combe281b02012-11-28 21:05:48 +00002986 if (constantTable->error())
2987 {
2988 delete constantTable;
2989 binary->Release();
2990 return NULL;
2991 }
2992
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002993 ShaderExecutable *executable = loadExecutable(binary->GetBufferPointer(), binary->GetBufferSize(), type, constantTable);
daniel@transgaming.com536dd6e2012-11-28 21:00:18 +00002994 binary->Release();
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002995
2996 return executable;
2997}
2998
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002999bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
3000{
3001 return mBlit->boxFilter(source, dest);
3002}
3003
daniel@transgaming.com2507f412012-10-31 18:46:48 +00003004D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003005{
3006 if (mD3d9Ex != NULL)
3007 {
3008 return D3DPOOL_DEFAULT;
3009 }
3010 else
3011 {
3012 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
3013 {
3014 return D3DPOOL_MANAGED;
3015 }
3016 }
3017
3018 return D3DPOOL_DEFAULT;
3019}
3020
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00003021bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
3022{
3023 if (source && dest)
3024 {
3025 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
3026 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
3027
3028 if (fromManaged)
3029 {
3030 D3DSURFACE_DESC desc;
3031 source->GetDesc(&desc);
3032
3033 IDirect3DSurface9 *surf = 0;
3034 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
3035
3036 if (SUCCEEDED(result))
3037 {
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00003038 Image9::copyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00003039 result = device->UpdateSurface(surf, NULL, dest, NULL);
3040 surf->Release();
3041 }
3042 }
3043 else
3044 {
3045 endScene();
3046 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
3047 }
3048
3049 if (FAILED(result))
3050 {
3051 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
3052 return false;
3053 }
3054 }
3055
3056 return true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00003057}
3058
daniel@transgaming.com244e1832012-12-20 20:52:35 +00003059Image *Renderer9::createImage()
3060{
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00003061 return new Image9();
daniel@transgaming.com244e1832012-12-20 20:52:35 +00003062}
3063
daniel@transgaming.comf721fdb2012-12-20 20:53:11 +00003064void Renderer9::generateMipmap(Image *dest, Image *src)
3065{
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00003066 Image9 *src9 = Image9::makeImage9(src);
3067 Image9 *dst9 = Image9::makeImage9(dest);
3068 Image9::generateMipmap(dst9, src9);
daniel@transgaming.comf721fdb2012-12-20 20:53:11 +00003069}
3070
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003071}