blob: 781276f8bbd827d8afe8001fe5a8102a2cb10e12 [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{
1203 IDirect3DIndexBuffer9 *indexBuffer;
1204 unsigned int serial;
1205 GLenum err = mIndexDataManager->prepareIndexData(type, count, elementArrayBuffer, indices, indexInfo, &indexBuffer, &serial);
1206
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001207 if (err == GL_NO_ERROR)
1208 {
1209 if (serial != mAppliedIBSerial)
1210 {
1211 mDevice->SetIndices(indexBuffer);
1212 mAppliedIBSerial = serial;
1213 }
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 {
1234 mDevice->SetIndices(countingIB->getBuffer());
1235 mAppliedIBSerial = countingIB->getSerial();
1236 }
1237
1238 for (int i = 0; i < mRepeatDraw; i++)
1239 {
1240 mDevice->DrawIndexedPrimitive(mPrimitiveType, 0, 0, count, 0, mPrimitiveCount);
1241 }
1242 }
1243 else
1244 {
1245 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
1246 return error(GL_OUT_OF_MEMORY);
1247 }
1248 }
1249 else // Regular case
1250 {
1251 mDevice->DrawPrimitive(mPrimitiveType, 0, mPrimitiveCount);
1252 }
1253}
1254
daniel@transgaming.com31240482012-11-28 21:06:41 +00001255void 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 +00001256{
1257 startScene();
1258
1259 if (mode == GL_LINE_LOOP)
1260 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001261 drawLineLoop(count, type, indices, indexInfo.minIndex, elementArrayBuffer);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001262 }
1263 else
1264 {
1265 for (int i = 0; i < mRepeatDraw; i++)
1266 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001267 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
1268 mDevice->DrawIndexedPrimitive(mPrimitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, mPrimitiveCount);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001269 }
1270 }
1271}
1272
1273void Renderer9::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer)
1274{
1275 // Get the raw indices for an indexed draw
1276 if (type != GL_NONE && elementArrayBuffer)
1277 {
1278 gl::Buffer *indexBuffer = elementArrayBuffer;
1279 intptr_t offset = reinterpret_cast<intptr_t>(indices);
1280 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
1281 }
1282
1283 UINT startIndex = 0;
1284 bool succeeded = false;
1285
1286 if (get32BitIndexSupport())
1287 {
1288 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
1289
1290 if (!mLineLoopIB)
1291 {
daniel@transgaming.com50cc7252012-12-20 21:09:23 +00001292 mLineLoopIB = new StreamingIndexBufferInterface(this, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX32);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001293 }
1294
1295 if (mLineLoopIB)
1296 {
1297 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_INT);
1298
1299 UINT offset = 0;
1300 unsigned int *data = static_cast<unsigned int*>(mLineLoopIB->map(spaceNeeded, &offset));
1301 startIndex = offset / 4;
1302
1303 if (data)
1304 {
1305 switch (type)
1306 {
1307 case GL_NONE: // Non-indexed draw
1308 for (int i = 0; i < count; i++)
1309 {
1310 data[i] = i;
1311 }
1312 data[count] = 0;
1313 break;
1314 case GL_UNSIGNED_BYTE:
1315 for (int i = 0; i < count; i++)
1316 {
1317 data[i] = static_cast<const GLubyte*>(indices)[i];
1318 }
1319 data[count] = static_cast<const GLubyte*>(indices)[0];
1320 break;
1321 case GL_UNSIGNED_SHORT:
1322 for (int i = 0; i < count; i++)
1323 {
1324 data[i] = static_cast<const GLushort*>(indices)[i];
1325 }
1326 data[count] = static_cast<const GLushort*>(indices)[0];
1327 break;
1328 case GL_UNSIGNED_INT:
1329 for (int i = 0; i < count; i++)
1330 {
1331 data[i] = static_cast<const GLuint*>(indices)[i];
1332 }
1333 data[count] = static_cast<const GLuint*>(indices)[0];
1334 break;
1335 default: UNREACHABLE();
1336 }
1337
1338 mLineLoopIB->unmap();
1339 succeeded = true;
1340 }
1341 }
1342 }
1343 else
1344 {
1345 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
1346
1347 if (!mLineLoopIB)
1348 {
daniel@transgaming.com50cc7252012-12-20 21:09:23 +00001349 mLineLoopIB = new StreamingIndexBufferInterface(this, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX16);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001350 }
1351
1352 if (mLineLoopIB)
1353 {
1354 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_SHORT);
1355
1356 UINT offset = 0;
1357 unsigned short *data = static_cast<unsigned short*>(mLineLoopIB->map(spaceNeeded, &offset));
1358 startIndex = offset / 2;
1359
1360 if (data)
1361 {
1362 switch (type)
1363 {
1364 case GL_NONE: // Non-indexed draw
1365 for (int i = 0; i < count; i++)
1366 {
1367 data[i] = i;
1368 }
1369 data[count] = 0;
1370 break;
1371 case GL_UNSIGNED_BYTE:
1372 for (int i = 0; i < count; i++)
1373 {
1374 data[i] = static_cast<const GLubyte*>(indices)[i];
1375 }
1376 data[count] = static_cast<const GLubyte*>(indices)[0];
1377 break;
1378 case GL_UNSIGNED_SHORT:
1379 for (int i = 0; i < count; i++)
1380 {
1381 data[i] = static_cast<const GLushort*>(indices)[i];
1382 }
1383 data[count] = static_cast<const GLushort*>(indices)[0];
1384 break;
1385 case GL_UNSIGNED_INT:
1386 for (int i = 0; i < count; i++)
1387 {
1388 data[i] = static_cast<const GLuint*>(indices)[i];
1389 }
1390 data[count] = static_cast<const GLuint*>(indices)[0];
1391 break;
1392 default: UNREACHABLE();
1393 }
1394
1395 mLineLoopIB->unmap();
1396 succeeded = true;
1397 }
1398 }
1399 }
1400
1401 if (succeeded)
1402 {
1403 if (mAppliedIBSerial != mLineLoopIB->getSerial())
1404 {
1405 mDevice->SetIndices(mLineLoopIB->getBuffer());
1406 mAppliedIBSerial = mLineLoopIB->getSerial();
1407 }
1408
1409 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
1410 }
1411 else
1412 {
1413 ERR("Could not create a looping index buffer for GL_LINE_LOOP.");
1414 return error(GL_OUT_OF_MEMORY);
1415 }
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001416}
1417
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001418void Renderer9::applyShaders(gl::ProgramBinary *programBinary)
1419{
daniel@transgaming.come4991412012-12-20 20:55:34 +00001420 unsigned int programBinarySerial = programBinary->getSerial();
1421 if (programBinarySerial != mAppliedProgramBinarySerial)
1422 {
1423 ShaderExecutable *vertexExe = programBinary->getVertexExecutable();
1424 ShaderExecutable *pixelExe = programBinary->getPixelExecutable();
daniel@transgaming.com95892412012-11-28 20:59:09 +00001425
daniel@transgaming.come4991412012-12-20 20:55:34 +00001426 IDirect3DVertexShader9 *vertexShader = NULL;
1427 if (vertexExe) vertexShader = ShaderExecutable9::makeShaderExecutable9(vertexExe)->getVertexShader();
daniel@transgaming.com95892412012-11-28 20:59:09 +00001428
daniel@transgaming.come4991412012-12-20 20:55:34 +00001429 IDirect3DPixelShader9 *pixelShader = NULL;
1430 if (pixelExe) pixelShader = ShaderExecutable9::makeShaderExecutable9(pixelExe)->getPixelShader();
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001431
daniel@transgaming.come4991412012-12-20 20:55:34 +00001432 mDevice->SetPixelShader(pixelShader);
1433 mDevice->SetVertexShader(vertexShader);
1434 programBinary->dirtyAllUniforms();
1435
1436 mAppliedProgramBinarySerial = programBinarySerial;
1437 }
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001438}
1439
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001440void Renderer9::applyUniforms(const gl::UniformArray *uniformArray)
1441{
1442 for (std::vector<gl::Uniform*>::const_iterator ub = uniformArray->begin(), ue = uniformArray->end(); ub != ue; ++ub)
1443 {
1444 gl::Uniform *targetUniform = *ub;
1445
1446 if (targetUniform->dirty)
1447 {
1448 int arraySize = targetUniform->arraySize;
1449 GLfloat *f = (GLfloat*)targetUniform->data;
1450 GLint *i = (GLint*)targetUniform->data;
1451 GLboolean *b = (GLboolean*)targetUniform->data;
1452
1453 switch (targetUniform->type)
1454 {
1455 case GL_SAMPLER_2D:
1456 case GL_SAMPLER_CUBE:
1457 break;
1458 case GL_BOOL: applyUniformnbv(targetUniform, arraySize, 1, b); break;
1459 case GL_BOOL_VEC2: applyUniformnbv(targetUniform, arraySize, 2, b); break;
1460 case GL_BOOL_VEC3: applyUniformnbv(targetUniform, arraySize, 3, b); break;
1461 case GL_BOOL_VEC4: applyUniformnbv(targetUniform, arraySize, 4, b); break;
1462 case GL_FLOAT:
1463 case GL_FLOAT_VEC2:
1464 case GL_FLOAT_VEC3:
1465 case GL_FLOAT_VEC4:
1466 case GL_FLOAT_MAT2:
1467 case GL_FLOAT_MAT3:
1468 case GL_FLOAT_MAT4: applyUniformnfv(targetUniform, f); break;
1469 case GL_INT: applyUniform1iv(targetUniform, arraySize, i); break;
1470 case GL_INT_VEC2: applyUniform2iv(targetUniform, arraySize, i); break;
1471 case GL_INT_VEC3: applyUniform3iv(targetUniform, arraySize, i); break;
1472 case GL_INT_VEC4: applyUniform4iv(targetUniform, arraySize, i); break;
1473 default:
1474 UNREACHABLE();
1475 }
1476
1477 targetUniform->dirty = false;
1478 }
1479 }
1480}
1481
1482void Renderer9::applyUniformnbv(gl::Uniform *targetUniform, GLsizei count, int width, const GLboolean *v)
1483{
1484 float vector[gl::D3D9_MAX_FLOAT_CONSTANTS * 4];
1485 BOOL boolVector[gl::D3D9_MAX_BOOL_CONSTANTS];
1486
1487 if (targetUniform->ps.float4Index >= 0 || targetUniform->vs.float4Index >= 0)
1488 {
1489 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1490 for (int i = 0; i < count; i++)
1491 {
1492 for (int j = 0; j < 4; j++)
1493 {
1494 if (j < width)
1495 {
1496 vector[i * 4 + j] = (v[i * width + j] == GL_FALSE) ? 0.0f : 1.0f;
1497 }
1498 else
1499 {
1500 vector[i * 4 + j] = 0.0f;
1501 }
1502 }
1503 }
1504 }
1505
1506 if (targetUniform->ps.boolIndex >= 0 || targetUniform->vs.boolIndex >= 0)
1507 {
1508 int psCount = targetUniform->ps.boolIndex >= 0 ? targetUniform->ps.registerCount : 0;
1509 int vsCount = targetUniform->vs.boolIndex >= 0 ? targetUniform->vs.registerCount : 0;
1510 int copyCount = std::min(count * width, std::max(psCount, vsCount));
1511 ASSERT(copyCount <= gl::D3D9_MAX_BOOL_CONSTANTS);
1512 for (int i = 0; i < copyCount; i++)
1513 {
1514 boolVector[i] = v[i] != GL_FALSE;
1515 }
1516 }
1517
1518 if (targetUniform->ps.float4Index >= 0)
1519 {
1520 mDevice->SetPixelShaderConstantF(targetUniform->ps.float4Index, vector, targetUniform->ps.registerCount);
1521 }
1522
1523 if (targetUniform->ps.boolIndex >= 0)
1524 {
1525 mDevice->SetPixelShaderConstantB(targetUniform->ps.boolIndex, boolVector, targetUniform->ps.registerCount);
1526 }
1527
1528 if (targetUniform->vs.float4Index >= 0)
1529 {
1530 mDevice->SetVertexShaderConstantF(targetUniform->vs.float4Index, vector, targetUniform->vs.registerCount);
1531 }
1532
1533 if (targetUniform->vs.boolIndex >= 0)
1534 {
1535 mDevice->SetVertexShaderConstantB(targetUniform->vs.boolIndex, boolVector, targetUniform->vs.registerCount);
1536 }
1537}
1538
1539bool Renderer9::applyUniformnfv(gl::Uniform *targetUniform, const GLfloat *v)
1540{
1541 if (targetUniform->ps.registerCount)
1542 {
1543 mDevice->SetPixelShaderConstantF(targetUniform->ps.float4Index, v, targetUniform->ps.registerCount);
1544 }
1545
1546 if (targetUniform->vs.registerCount)
1547 {
1548 mDevice->SetVertexShaderConstantF(targetUniform->vs.float4Index, v, targetUniform->vs.registerCount);
1549 }
1550
1551 return true;
1552}
1553
1554bool Renderer9::applyUniform1iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
1555{
1556 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1557 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1558
1559 for (int i = 0; i < count; i++)
1560 {
1561 vector[i] = gl::Vector4((float)v[i], 0, 0, 0);
1562 }
1563
1564 if (targetUniform->ps.registerCount)
1565 {
1566 if (targetUniform->ps.float4Index >= 0)
1567 {
1568 mDevice->SetPixelShaderConstantF(targetUniform->ps.float4Index, (const float*)vector, targetUniform->ps.registerCount);
1569 }
1570 }
1571
1572 if (targetUniform->vs.registerCount)
1573 {
1574 if (targetUniform->vs.float4Index >= 0)
1575 {
1576 mDevice->SetVertexShaderConstantF(targetUniform->vs.float4Index, (const float *)vector, targetUniform->vs.registerCount);
1577 }
1578 }
1579
1580 return true;
1581}
1582
1583bool Renderer9::applyUniform2iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
1584{
1585 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1586 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1587
1588 for (int i = 0; i < count; i++)
1589 {
1590 vector[i] = gl::Vector4((float)v[0], (float)v[1], 0, 0);
1591
1592 v += 2;
1593 }
1594
1595 applyUniformniv(targetUniform, count, vector);
1596
1597 return true;
1598}
1599
1600bool Renderer9::applyUniform3iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
1601{
1602 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1603 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1604
1605 for (int i = 0; i < count; i++)
1606 {
1607 vector[i] = gl::Vector4((float)v[0], (float)v[1], (float)v[2], 0);
1608
1609 v += 3;
1610 }
1611
1612 applyUniformniv(targetUniform, count, vector);
1613
1614 return true;
1615}
1616
1617bool Renderer9::applyUniform4iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
1618{
1619 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1620 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1621
1622 for (int i = 0; i < count; i++)
1623 {
1624 vector[i] = gl::Vector4((float)v[0], (float)v[1], (float)v[2], (float)v[3]);
1625
1626 v += 4;
1627 }
1628
1629 applyUniformniv(targetUniform, count, vector);
1630
1631 return true;
1632}
1633
1634void Renderer9::applyUniformniv(gl::Uniform *targetUniform, GLsizei count, const gl::Vector4 *vector)
1635{
1636 if (targetUniform->ps.registerCount)
1637 {
1638 ASSERT(targetUniform->ps.float4Index >= 0);
1639 mDevice->SetPixelShaderConstantF(targetUniform->ps.float4Index, (const float *)vector, targetUniform->ps.registerCount);
1640 }
1641
1642 if (targetUniform->vs.registerCount)
1643 {
1644 ASSERT(targetUniform->vs.float4Index >= 0);
1645 mDevice->SetVertexShaderConstantF(targetUniform->vs.float4Index, (const float *)vector, targetUniform->vs.registerCount);
1646 }
1647}
1648
daniel@transgaming.com084a2572012-11-28 20:55:17 +00001649void Renderer9::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001650{
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001651 D3DCOLOR color = D3DCOLOR_ARGB(gl::unorm<8>(clearParams.colorClearValue.alpha),
1652 gl::unorm<8>(clearParams.colorClearValue.red),
1653 gl::unorm<8>(clearParams.colorClearValue.green),
1654 gl::unorm<8>(clearParams.colorClearValue.blue));
1655 float depth = gl::clamp01(clearParams.depthClearValue);
1656 int stencil = clearParams.stencilClearValue & 0x000000FF;
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001657
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001658 unsigned int stencilUnmasked = 0x0;
1659 if ((clearParams.mask & GL_STENCIL_BUFFER_BIT) && frameBuffer->hasStencil())
1660 {
1661 unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
1662 stencilUnmasked = (0x1 << stencilSize) - 1;
1663 }
1664
1665 bool alphaUnmasked = (gl::GetAlphaSize(mRenderTargetDesc.format) == 0) || clearParams.colorMaskAlpha;
1666
1667 const bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
1668 (clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
1669 const bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
1670 !(clearParams.colorMaskRed && clearParams.colorMaskGreen &&
1671 clearParams.colorMaskBlue && alphaUnmasked);
1672
1673 if (needMaskedColorClear || needMaskedStencilClear)
1674 {
1675 // State which is altered in all paths from this point to the clear call is saved.
1676 // State which is altered in only some paths will be flagged dirty in the case that
1677 // that path is taken.
1678 HRESULT hr;
1679 if (mMaskedClearSavedState == NULL)
1680 {
1681 hr = mDevice->BeginStateBlock();
1682 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1683
1684 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1685 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1686 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1687 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1688 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1689 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1690 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1691 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1692 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1693 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1694 mDevice->SetPixelShader(NULL);
1695 mDevice->SetVertexShader(NULL);
1696 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
1697 mDevice->SetStreamSource(0, NULL, 0, 0);
1698 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1699 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1700 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1701 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1702 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1703 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1704 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1705
1706 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1707 {
1708 mDevice->SetStreamSourceFreq(i, 1);
1709 }
1710
1711 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
1712 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1713 }
1714
1715 ASSERT(mMaskedClearSavedState != NULL);
1716
1717 if (mMaskedClearSavedState != NULL)
1718 {
1719 hr = mMaskedClearSavedState->Capture();
1720 ASSERT(SUCCEEDED(hr));
1721 }
1722
1723 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1724 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1725 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1726 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1727 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1728 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1729 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1730 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1731
1732 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1733 {
1734 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE,
1735 gl_d3d9::ConvertColorMask(clearParams.colorMaskRed,
1736 clearParams.colorMaskGreen,
1737 clearParams.colorMaskBlue,
1738 clearParams.colorMaskAlpha));
1739 }
1740 else
1741 {
1742 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1743 }
1744
1745 if (stencilUnmasked != 0x0 && (clearParams.mask & GL_STENCIL_BUFFER_BIT))
1746 {
1747 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
1748 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
1749 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
1750 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
1751 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
1752 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
1753 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
1754 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
1755 }
1756 else
1757 {
1758 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1759 }
1760
1761 mDevice->SetPixelShader(NULL);
1762 mDevice->SetVertexShader(NULL);
1763 mDevice->SetFVF(D3DFVF_XYZRHW);
1764 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1765 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1766 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1767 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1768 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1769 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1770 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1771
1772 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1773 {
1774 mDevice->SetStreamSourceFreq(i, 1);
1775 }
1776
1777 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
1778 quad[0][0] = -0.5f;
1779 quad[0][1] = mRenderTargetDesc.height - 0.5f;
1780 quad[0][2] = 0.0f;
1781 quad[0][3] = 1.0f;
1782
1783 quad[1][0] = mRenderTargetDesc.width - 0.5f;
1784 quad[1][1] = mRenderTargetDesc.height - 0.5f;
1785 quad[1][2] = 0.0f;
1786 quad[1][3] = 1.0f;
1787
1788 quad[2][0] = -0.5f;
1789 quad[2][1] = -0.5f;
1790 quad[2][2] = 0.0f;
1791 quad[2][3] = 1.0f;
1792
1793 quad[3][0] = mRenderTargetDesc.width - 0.5f;
1794 quad[3][1] = -0.5f;
1795 quad[3][2] = 0.0f;
1796 quad[3][3] = 1.0f;
1797
1798 startScene();
1799 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
1800
1801 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1802 {
1803 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
1804 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
1805 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
1806 }
1807
1808 if (mMaskedClearSavedState != NULL)
1809 {
1810 mMaskedClearSavedState->Apply();
1811 }
1812 }
1813 else if (clearParams.mask)
1814 {
1815 DWORD dxClearFlags = 0;
1816 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1817 {
1818 dxClearFlags |= D3DCLEAR_TARGET;
1819 }
1820 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1821 {
1822 dxClearFlags |= D3DCLEAR_ZBUFFER;
1823 }
1824 if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
1825 {
1826 dxClearFlags |= D3DCLEAR_STENCIL;
1827 }
1828
1829 mDevice->Clear(0, NULL, dxClearFlags, color, depth, stencil);
1830 }
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001831}
1832
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001833void Renderer9::markAllStateDirty()
1834{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001835 mAppliedRenderTargetSerial = 0;
1836 mAppliedDepthbufferSerial = 0;
1837 mAppliedStencilbufferSerial = 0;
1838 mDepthStencilInitialized = false;
1839 mRenderTargetDescInitialized = false;
1840
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001841 mForceSetDepthStencilState = true;
1842 mForceSetRasterState = true;
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001843 mForceSetScissor = true;
1844 mForceSetViewport = true;
daniel@transgaming.com9a067372012-12-20 20:55:24 +00001845 mForceSetBlendState = true;
1846
1847 mAppliedIBSerial = 0;
daniel@transgaming.come4991412012-12-20 20:55:34 +00001848 mAppliedProgramBinarySerial = 0;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001849
1850 mVertexDeclarationCache.markStateDirty();
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001851}
1852
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001853void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001854{
1855 while (!mEventQueryPool.empty())
1856 {
1857 mEventQueryPool.back()->Release();
1858 mEventQueryPool.pop_back();
1859 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001860
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001861 if (mMaskedClearSavedState)
1862 {
1863 mMaskedClearSavedState->Release();
1864 mMaskedClearSavedState = NULL;
1865 }
1866
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001867 mVertexShaderCache.clear();
1868 mPixelShaderCache.clear();
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001869
daniel@transgaming.come569fc52012-11-28 20:56:02 +00001870 delete mBlit;
1871 mBlit = NULL;
1872
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001873 delete mVertexDataManager;
1874 mVertexDataManager = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001875
1876 delete mIndexDataManager;
1877 mIndexDataManager = NULL;
1878
1879 delete mLineLoopIB;
1880 mLineLoopIB = NULL;
daniel@transgaming.come4e1a332012-12-20 20:52:09 +00001881
1882 for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1883 {
1884 delete mNullColorbufferCache[i].buffer;
1885 mNullColorbufferCache[i].buffer = NULL;
1886 }
1887
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001888}
1889
1890
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001891void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001892{
1893 mDeviceLost = true;
1894}
1895
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001896bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001897{
1898 return mDeviceLost;
1899}
1900
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001901// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001902bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001903{
1904 bool isLost = false;
1905
1906 if (mDeviceEx)
1907 {
1908 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
1909 }
1910 else if (mDevice)
1911 {
1912 isLost = FAILED(mDevice->TestCooperativeLevel());
1913 }
1914 else
1915 {
1916 // No device yet, so no reset required
1917 }
1918
1919 if (isLost)
1920 {
1921 // ensure we note the device loss --
1922 // we'll probably get this done again by markDeviceLost
1923 // but best to remember it!
1924 // Note that we don't want to clear the device loss status here
1925 // -- this needs to be done by resetDevice
1926 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001927 if (notify)
1928 {
1929 mDisplay->notifyDeviceLost();
1930 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001931 }
1932
1933 return isLost;
1934}
1935
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001936bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001937{
1938 HRESULT status = D3D_OK;
1939
1940 if (mDeviceEx)
1941 {
1942 status = mDeviceEx->CheckDeviceState(NULL);
1943 }
1944 else if (mDevice)
1945 {
1946 status = mDevice->TestCooperativeLevel();
1947 }
1948
1949 switch (status)
1950 {
1951 case D3DERR_DEVICENOTRESET:
1952 case D3DERR_DEVICEHUNG:
1953 return true;
1954 default:
1955 return false;
1956 }
1957}
1958
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001959bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001960{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001961 releaseDeviceResources();
1962
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001963 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
1964
1965 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001966 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001967 int attempts = 3;
1968
1969 while (lost && attempts > 0)
1970 {
1971 if (mDeviceEx)
1972 {
1973 Sleep(500); // Give the graphics driver some CPU time
1974 result = mDeviceEx->ResetEx(&presentParameters, NULL);
1975 }
1976 else
1977 {
1978 result = mDevice->TestCooperativeLevel();
1979 while (result == D3DERR_DEVICELOST)
1980 {
1981 Sleep(100); // Give the graphics driver some CPU time
1982 result = mDevice->TestCooperativeLevel();
1983 }
1984
1985 if (result == D3DERR_DEVICENOTRESET)
1986 {
1987 result = mDevice->Reset(&presentParameters);
1988 }
1989 }
1990
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001991 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001992 attempts --;
1993 }
1994
1995 if (FAILED(result))
1996 {
1997 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
1998 return false;
1999 }
2000
2001 // reset device defaults
2002 initializeDevice();
2003 mDeviceLost = false;
2004
2005 return true;
2006}
2007
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002008DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002009{
2010 return mAdapterIdentifier.VendorId;
2011}
2012
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002013const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002014{
2015 return mAdapterIdentifier.Description;
2016}
2017
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002018GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002019{
2020 return mAdapterIdentifier.DeviceIdentifier;
2021}
2022
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002023void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002024{
2025 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
2026 {
2027 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
2028 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
2029
2030 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
2031 }
2032}
2033
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002034bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002035{
2036 D3DDISPLAYMODE currentDisplayMode;
2037 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2038
2039 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
2040}
2041
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002042bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002043{
2044 D3DDISPLAYMODE currentDisplayMode;
2045 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2046
2047 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
2048}
2049
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002050bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002051{
2052 D3DDISPLAYMODE currentDisplayMode;
2053 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2054
2055 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
2056}
2057
2058// we use INTZ for depth textures in Direct3D9
2059// we also want NULL texture support to ensure the we can make depth-only FBOs
2060// see http://aras-p.info/texts/D3D9GPUHacks.html
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002061bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002062{
2063 D3DDISPLAYMODE currentDisplayMode;
2064 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2065
2066 bool intz = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
2067 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ));
2068 bool null = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
2069 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
2070
2071 return intz && null;
2072}
2073
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002074bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002075{
2076 D3DDISPLAYMODE currentDisplayMode;
2077 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2078
2079 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
2080 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
2081 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
2082 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
2083
2084 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
2085 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F))&&
2086 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
2087 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
2088
2089 if (!*filtering && !*renderable)
2090 {
2091 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
2092 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
2093 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
2094 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
2095 }
2096 else
2097 {
2098 return true;
2099 }
2100}
2101
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002102bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002103{
2104 D3DDISPLAYMODE currentDisplayMode;
2105 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2106
2107 *filtering = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
2108 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
2109 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
2110 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
2111
2112 *renderable = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
2113 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
2114 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
2115 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
2116
2117 if (!*filtering && !*renderable)
2118 {
2119 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
2120 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
2121 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
2122 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
2123 }
2124 else
2125 {
2126 return true;
2127 }
2128}
2129
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002130bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002131{
2132 D3DDISPLAYMODE currentDisplayMode;
2133 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2134
2135 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
2136}
2137
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002138bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002139{
2140 D3DDISPLAYMODE currentDisplayMode;
2141 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2142
2143 return SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
2144}
2145
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002146bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002147{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00002148 return mSupportsTextureFilterAnisotropy;
2149}
2150
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002151float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00002152{
2153 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002154 {
2155 return mDeviceCaps.MaxAnisotropy;
2156 }
2157 return 1.0f;
2158}
2159
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002160bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002161{
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002162 IDirect3DQuery9 *query = allocateEventQuery();
2163 if (query)
2164 {
2165 freeEventQuery(query);
2166 return true;
2167 }
2168 else
2169 {
2170 return false;
2171 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002172 return true;
2173}
2174
2175// Only Direct3D 10 ready devices support all the necessary vertex texture formats.
2176// We test this using D3D9 by checking support for the R16F format.
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002177bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002178{
2179 if (!mDevice || mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(3, 0))
2180 {
2181 return false;
2182 }
2183
2184 D3DDISPLAYMODE currentDisplayMode;
2185 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
2186
2187 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F);
2188
2189 return SUCCEEDED(result);
2190}
2191
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002192bool Renderer9::getNonPower2TextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002193{
2194 return mSupportsNonPower2Textures;
2195}
2196
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002197bool Renderer9::getOcclusionQuerySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002198{
2199 if (!mDevice)
2200 {
2201 return false;
2202 }
2203
2204 IDirect3DQuery9 *query = NULL;
2205 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &query);
2206 if (SUCCEEDED(result) && query)
2207 {
2208 query->Release();
2209 return true;
2210 }
2211 else
2212 {
2213 return false;
2214 }
2215}
2216
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002217bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002218{
2219 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
2220}
2221
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002222bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00002223{
2224 // PIX doesn't seem to support using share handles, so disable them.
2225 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00002226 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00002227}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002228
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00002229int Renderer9::getMajorShaderModel() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002230{
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00002231 return D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion);
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002232}
2233
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002234float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002235{
2236 return mDeviceCaps.MaxPointSize;
2237}
2238
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002239int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002240{
2241 return (int)mDeviceCaps.MaxTextureWidth;
2242}
2243
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002244int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002245{
2246 return (int)mDeviceCaps.MaxTextureHeight;
2247}
2248
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002249bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002250{
2251 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
2252}
2253
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002254DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002255{
2256 return mDeviceCaps.DeclTypes;
2257}
2258
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002259int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002260{
2261 return mMinSwapInterval;
2262}
2263
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002264int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002265{
2266 return mMaxSwapInterval;
2267}
2268
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002269int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002270{
2271 return mMaxSupportedSamples;
2272}
2273
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002274int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002275{
2276 if (requested == 0)
2277 {
2278 return requested;
2279 }
2280
2281 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
2282 if (itr == mMultiSampleSupport.end())
2283 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00002284 if (format == D3DFMT_UNKNOWN)
2285 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002286 return -1;
2287 }
2288
2289 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
2290 {
2291 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
2292 {
2293 return i;
2294 }
2295 }
2296
2297 return -1;
2298}
2299
daniel@transgaming.coma9571682012-11-28 19:33:08 +00002300D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
2301{
2302 switch (internalformat)
2303 {
2304 case GL_DEPTH_COMPONENT16:
2305 case GL_DEPTH_COMPONENT32_OES:
2306 case GL_DEPTH24_STENCIL8_OES:
2307 return D3DFMT_INTZ;
2308 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
2309 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
2310 return D3DFMT_DXT1;
2311 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
2312 return D3DFMT_DXT3;
2313 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
2314 return D3DFMT_DXT5;
2315 case GL_RGBA32F_EXT:
2316 case GL_RGB32F_EXT:
2317 case GL_ALPHA32F_EXT:
2318 case GL_LUMINANCE32F_EXT:
2319 case GL_LUMINANCE_ALPHA32F_EXT:
2320 return D3DFMT_A32B32G32R32F;
2321 case GL_RGBA16F_EXT:
2322 case GL_RGB16F_EXT:
2323 case GL_ALPHA16F_EXT:
2324 case GL_LUMINANCE16F_EXT:
2325 case GL_LUMINANCE_ALPHA16F_EXT:
2326 return D3DFMT_A16B16G16R16F;
2327 case GL_LUMINANCE8_EXT:
2328 if (getLuminanceTextureSupport())
2329 {
2330 return D3DFMT_L8;
2331 }
2332 break;
2333 case GL_LUMINANCE8_ALPHA8_EXT:
2334 if (getLuminanceAlphaTextureSupport())
2335 {
2336 return D3DFMT_A8L8;
2337 }
2338 break;
2339 case GL_RGB8_OES:
2340 case GL_RGB565:
2341 return D3DFMT_X8R8G8B8;
2342 }
2343
2344 return D3DFMT_A8R8G8B8;
2345}
2346
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002347bool Renderer9::copyToRenderTarget(TextureStorage2D *dest, TextureStorage2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002348{
2349 bool result = false;
2350
2351 if (source && dest)
2352 {
2353 int levels = source->levelCount();
2354 for (int i = 0; i < levels; ++i)
2355 {
2356 IDirect3DSurface9 *srcSurf = source->getSurfaceLevel(i, false);
2357 IDirect3DSurface9 *dstSurf = dest->getSurfaceLevel(i, false);
2358
2359 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2360
2361 if (srcSurf) srcSurf->Release();
2362 if (dstSurf) dstSurf->Release();
2363
2364 if (!result)
2365 return false;
2366 }
2367 }
2368
2369 return result;
2370}
2371
daniel@transgaming.com31b13e12012-11-28 19:34:30 +00002372bool Renderer9::copyToRenderTarget(TextureStorageCubeMap *dest, TextureStorageCubeMap *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 f = 0; f < 6; f++)
2380 {
2381 for (int i = 0; i < levels; i++)
2382 {
2383 IDirect3DSurface9 *srcSurf = source->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
2384 IDirect3DSurface9 *dstSurf = dest->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
2385
2386 result = copyToRenderTarget(dstSurf, srcSurf, source->isManaged());
2387
2388 if (srcSurf) srcSurf->Release();
2389 if (dstSurf) dstSurf->Release();
2390
2391 if (!result)
2392 return false;
2393 }
2394 }
2395 }
2396
2397 return result;
2398}
2399
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002400D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002401{
2402 if (mD3d9Ex != NULL)
2403 {
2404 return D3DPOOL_DEFAULT;
2405 }
2406 else
2407 {
2408 if (!(usage & D3DUSAGE_DYNAMIC))
2409 {
2410 return D3DPOOL_MANAGED;
2411 }
2412 }
2413
2414 return D3DPOOL_DEFAULT;
2415}
2416
daniel@transgaming.com38380882012-11-28 19:36:39 +00002417bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2418 GLint xoffset, GLint yoffset, TextureStorage2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002419{
2420 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
2421}
2422
daniel@transgaming.com38380882012-11-28 19:36:39 +00002423bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
2424 GLint xoffset, GLint yoffset, TextureStorageCubeMap *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002425{
2426 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
2427}
2428
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002429bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
2430 bool blitRenderTarget, bool blitDepthStencil)
2431{
2432 endScene();
2433
2434 if (blitRenderTarget)
2435 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002436 gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer();
2437 gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer();
2438 RenderTarget9 *readRenderTarget = NULL;
2439 RenderTarget9 *drawRenderTarget = NULL;
2440 IDirect3DSurface9* readSurface = NULL;
2441 IDirect3DSurface9* drawSurface = NULL;
2442
2443 if (readBuffer)
2444 {
2445 readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
2446 }
2447 if (drawBuffer)
2448 {
2449 drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
2450 }
2451
2452 if (readRenderTarget)
2453 {
2454 readSurface = readRenderTarget->getSurface();
2455 }
2456 if (drawRenderTarget)
2457 {
2458 drawSurface = drawRenderTarget->getSurface();
2459 }
2460
2461 if (!readSurface || !drawSurface)
2462 {
2463 ERR("Failed to retrieve the render target.");
2464 return error(GL_OUT_OF_MEMORY, false);
2465 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002466
2467 RECT srcRect, dstRect;
2468 RECT *srcRectPtr = NULL;
2469 RECT *dstRectPtr = NULL;
2470
2471 if (readRect)
2472 {
2473 srcRect.left = readRect->x;
2474 srcRect.right = readRect->x + readRect->width;
2475 srcRect.top = readRect->y;
2476 srcRect.bottom = readRect->y + readRect->height;
2477 srcRectPtr = &srcRect;
2478 }
2479
2480 if (drawRect)
2481 {
2482 dstRect.left = drawRect->x;
2483 dstRect.right = drawRect->x + drawRect->width;
2484 dstRect.top = drawRect->y;
2485 dstRect.bottom = drawRect->y + drawRect->height;
2486 dstRectPtr = &dstRect;
2487 }
2488
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002489 HRESULT result = mDevice->StretchRect(readSurface, srcRectPtr, drawSurface, dstRectPtr, D3DTEXF_NONE);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002490
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002491 readSurface->Release();
2492 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002493
2494 if (FAILED(result))
2495 {
2496 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2497 return false;
2498 }
2499 }
2500
2501 if (blitDepthStencil)
2502 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002503 gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
2504 gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
2505 RenderTarget9 *readDepthStencil = NULL;
2506 RenderTarget9 *drawDepthStencil = NULL;
2507 IDirect3DSurface9* readSurface = NULL;
2508 IDirect3DSurface9* drawSurface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002509
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002510 if (readBuffer)
2511 {
2512 readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
2513 }
2514 if (drawBuffer)
2515 {
2516 drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
2517 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002518
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002519 if (readDepthStencil)
2520 {
2521 readSurface = readDepthStencil->getSurface();
2522 }
2523 if (drawDepthStencil)
2524 {
2525 drawSurface = drawDepthStencil->getSurface();
2526 }
2527
2528 if (!readSurface || !drawSurface)
2529 {
2530 ERR("Failed to retrieve the render target.");
2531 return error(GL_OUT_OF_MEMORY, false);
2532 }
2533
2534 HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
2535
2536 readSurface->Release();
2537 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002538
2539 if (FAILED(result))
2540 {
2541 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2542 return false;
2543 }
2544 }
2545
2546 return true;
2547}
2548
2549void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
2550 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
2551{
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002552 RenderTarget9 *renderTarget = NULL;
2553 IDirect3DSurface9 *surface = NULL;
2554 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
2555
2556 if (colorbuffer)
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002557 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002558 renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
2559 }
2560
2561 if (renderTarget)
2562 {
2563 surface = renderTarget->getSurface();
2564 }
2565
2566 if (!surface)
2567 {
2568 // context must be lost
2569 return;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002570 }
2571
2572 D3DSURFACE_DESC desc;
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002573 surface->GetDesc(&desc);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002574
2575 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2576 {
2577 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002578 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002579 return error(GL_OUT_OF_MEMORY);
2580 }
2581
2582 HRESULT result;
2583 IDirect3DSurface9 *systemSurface = NULL;
2584 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
2585 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2586 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2587 if (directToPixels)
2588 {
2589 // Use the pixels ptr as a shared handle to write directly into client's memory
2590 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2591 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2592 if (FAILED(result))
2593 {
2594 // Try again without the shared handle
2595 directToPixels = false;
2596 }
2597 }
2598
2599 if (!directToPixels)
2600 {
2601 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2602 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2603 if (FAILED(result))
2604 {
2605 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002606 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002607 return error(GL_OUT_OF_MEMORY);
2608 }
2609 }
2610
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002611 result = mDevice->GetRenderTargetData(surface, systemSurface);
2612 surface->Release();
2613 surface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002614
2615 if (FAILED(result))
2616 {
2617 systemSurface->Release();
2618
2619 // It turns out that D3D will sometimes produce more error
2620 // codes than those documented.
daniel@transgaming.com414c9162012-11-28 20:54:57 +00002621 if (checkDeviceLost(result))
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002622 return error(GL_OUT_OF_MEMORY);
2623 else
2624 {
2625 UNREACHABLE();
2626 return;
2627 }
2628
2629 }
2630
2631 if (directToPixels)
2632 {
2633 systemSurface->Release();
2634 return;
2635 }
2636
2637 RECT rect;
2638 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
2639 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
2640 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2641 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2642
2643 D3DLOCKED_RECT lock;
2644 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2645
2646 if (FAILED(result))
2647 {
2648 UNREACHABLE();
2649 systemSurface->Release();
2650
2651 return; // No sensible error to generate
2652 }
2653
2654 unsigned char *dest = (unsigned char*)pixels;
2655 unsigned short *dest16 = (unsigned short*)pixels;
2656
2657 unsigned char *source;
2658 int inputPitch;
2659 if (packReverseRowOrder)
2660 {
2661 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2662 inputPitch = -lock.Pitch;
2663 }
2664 else
2665 {
2666 source = (unsigned char*)lock.pBits;
2667 inputPitch = lock.Pitch;
2668 }
2669
2670 unsigned int fastPixelSize = 0;
2671
2672 if (desc.Format == D3DFMT_A8R8G8B8 &&
2673 format == GL_BGRA_EXT &&
2674 type == GL_UNSIGNED_BYTE)
2675 {
2676 fastPixelSize = 4;
2677 }
2678 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2679 format == GL_BGRA_EXT &&
2680 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2681 (desc.Format == D3DFMT_A1R5G5B5 &&
2682 format == GL_BGRA_EXT &&
2683 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2684 {
2685 fastPixelSize = 2;
2686 }
2687 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2688 format == GL_RGBA &&
2689 type == GL_HALF_FLOAT_OES)
2690 {
2691 fastPixelSize = 8;
2692 }
2693 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2694 format == GL_RGBA &&
2695 type == GL_FLOAT)
2696 {
2697 fastPixelSize = 16;
2698 }
2699
2700 for (int j = 0; j < rect.bottom - rect.top; j++)
2701 {
2702 if (fastPixelSize != 0)
2703 {
2704 // Fast path for formats which require no translation:
2705 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2706 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2707 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2708 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2709 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2710 //
2711 // Note that buffers with no alpha go through the slow path below.
2712 memcpy(dest + j * outputPitch,
2713 source + j * inputPitch,
2714 (rect.right - rect.left) * fastPixelSize);
2715 continue;
2716 }
2717
2718 for (int i = 0; i < rect.right - rect.left; i++)
2719 {
2720 float r;
2721 float g;
2722 float b;
2723 float a;
2724
2725 switch (desc.Format)
2726 {
2727 case D3DFMT_R5G6B5:
2728 {
2729 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2730
2731 a = 1.0f;
2732 b = (rgb & 0x001F) * (1.0f / 0x001F);
2733 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2734 r = (rgb & 0xF800) * (1.0f / 0xF800);
2735 }
2736 break;
2737 case D3DFMT_A1R5G5B5:
2738 {
2739 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2740
2741 a = (argb & 0x8000) ? 1.0f : 0.0f;
2742 b = (argb & 0x001F) * (1.0f / 0x001F);
2743 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2744 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2745 }
2746 break;
2747 case D3DFMT_A8R8G8B8:
2748 {
2749 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2750
2751 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2752 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2753 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2754 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2755 }
2756 break;
2757 case D3DFMT_X8R8G8B8:
2758 {
2759 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2760
2761 a = 1.0f;
2762 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2763 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2764 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2765 }
2766 break;
2767 case D3DFMT_A2R10G10B10:
2768 {
2769 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2770
2771 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2772 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2773 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2774 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2775 }
2776 break;
2777 case D3DFMT_A32B32G32R32F:
2778 {
2779 // float formats in D3D are stored rgba, rather than the other way round
2780 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2781 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2782 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2783 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2784 }
2785 break;
2786 case D3DFMT_A16B16G16R16F:
2787 {
2788 // float formats in D3D are stored rgba, rather than the other way round
2789 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2790 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2791 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2792 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
2793 }
2794 break;
2795 default:
2796 UNIMPLEMENTED(); // FIXME
2797 UNREACHABLE();
2798 return;
2799 }
2800
2801 switch (format)
2802 {
2803 case GL_RGBA:
2804 switch (type)
2805 {
2806 case GL_UNSIGNED_BYTE:
2807 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2808 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2809 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2810 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2811 break;
2812 default: UNREACHABLE();
2813 }
2814 break;
2815 case GL_BGRA_EXT:
2816 switch (type)
2817 {
2818 case GL_UNSIGNED_BYTE:
2819 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2820 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2821 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2822 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2823 break;
2824 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2825 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2826 // this type is packed as follows:
2827 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2828 // --------------------------------------------------------------------------------
2829 // | 4th | 3rd | 2nd | 1st component |
2830 // --------------------------------------------------------------------------------
2831 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2832 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2833 ((unsigned short)(15 * a + 0.5f) << 12)|
2834 ((unsigned short)(15 * r + 0.5f) << 8) |
2835 ((unsigned short)(15 * g + 0.5f) << 4) |
2836 ((unsigned short)(15 * b + 0.5f) << 0);
2837 break;
2838 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2839 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2840 // this type is packed as follows:
2841 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2842 // --------------------------------------------------------------------------------
2843 // | 4th | 3rd | 2nd | 1st component |
2844 // --------------------------------------------------------------------------------
2845 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2846 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2847 ((unsigned short)( a + 0.5f) << 15) |
2848 ((unsigned short)(31 * r + 0.5f) << 10) |
2849 ((unsigned short)(31 * g + 0.5f) << 5) |
2850 ((unsigned short)(31 * b + 0.5f) << 0);
2851 break;
2852 default: UNREACHABLE();
2853 }
2854 break;
2855 case GL_RGB:
2856 switch (type)
2857 {
2858 case GL_UNSIGNED_SHORT_5_6_5:
2859 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2860 ((unsigned short)(31 * b + 0.5f) << 0) |
2861 ((unsigned short)(63 * g + 0.5f) << 5) |
2862 ((unsigned short)(31 * r + 0.5f) << 11);
2863 break;
2864 case GL_UNSIGNED_BYTE:
2865 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2866 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2867 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2868 break;
2869 default: UNREACHABLE();
2870 }
2871 break;
2872 default: UNREACHABLE();
2873 }
2874 }
2875 }
2876
2877 systemSurface->UnlockRect();
2878
2879 systemSurface->Release();
2880}
2881
daniel@transgaming.comf2423652012-11-28 20:53:50 +00002882RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
2883{
2884 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2885 IDirect3DSurface9 *surface = NULL;
2886 if (depth)
2887 {
2888 surface = swapChain9->getDepthStencil();
2889 }
2890 else
2891 {
2892 surface = swapChain9->getRenderTarget();
2893 }
2894
2895 RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
2896
2897 return renderTarget;
2898}
2899
2900RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
2901{
2902 RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
2903 return renderTarget;
2904}
2905
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002906ShaderExecutable *Renderer9::loadExecutable(const void *function, size_t length, GLenum type, void *data)
daniel@transgaming.com55318902012-11-28 20:58:58 +00002907{
2908 ShaderExecutable9 *executable = NULL;
daniel@transgaming.com31240482012-11-28 21:06:41 +00002909 D3DConstantTable *table = reinterpret_cast<D3DConstantTable *>(data);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002910
2911 switch (type)
2912 {
2913 case GL_VERTEX_SHADER:
2914 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002915 IDirect3DVertexShader9 *vshader = createVertexShader((DWORD*)function, length);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002916 if (vshader)
2917 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002918 executable = new ShaderExecutable9(function, length, vshader, table);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002919 }
2920 }
2921 break;
2922 case GL_FRAGMENT_SHADER:
2923 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002924 IDirect3DPixelShader9 *pshader = createPixelShader((DWORD*)function, length);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002925 if (pshader)
2926 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002927 executable = new ShaderExecutable9(function, length, pshader, table);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002928 }
2929 }
2930 break;
2931 default:
2932 UNREACHABLE();
2933 break;
2934 }
2935
2936 return executable;
2937}
2938
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002939ShaderExecutable *Renderer9::compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, GLenum type)
2940{
2941 const char *profile = NULL;
2942
2943 switch (type)
2944 {
2945 case GL_VERTEX_SHADER:
2946 profile = getMajorShaderModel() >= 3 ? "vs_3_0" : "vs_2_0";
2947 break;
2948 case GL_FRAGMENT_SHADER:
2949 profile = getMajorShaderModel() >= 3 ? "ps_3_0" : "ps_2_0";
2950 break;
2951 default:
2952 UNREACHABLE();
2953 return NULL;
2954 }
2955
daniel@transgaming.com25e16af2012-11-28 21:05:57 +00002956 ID3DBlob *binary = compileToBinary(infoLog, shaderHLSL, profile, true);
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002957 if (!binary)
2958 return NULL;
2959
daniel@transgaming.com31240482012-11-28 21:06:41 +00002960 D3DConstantTable *constantTable = new D3DConstantTable(binary->GetBufferPointer(), binary->GetBufferSize());
daniel@transgaming.combe281b02012-11-28 21:05:48 +00002961 if (constantTable->error())
2962 {
2963 delete constantTable;
2964 binary->Release();
2965 return NULL;
2966 }
2967
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002968 ShaderExecutable *executable = loadExecutable(binary->GetBufferPointer(), binary->GetBufferSize(), type, constantTable);
daniel@transgaming.com536dd6e2012-11-28 21:00:18 +00002969 binary->Release();
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002970
2971 return executable;
2972}
2973
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002974bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
2975{
2976 return mBlit->boxFilter(source, dest);
2977}
2978
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002979D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002980{
2981 if (mD3d9Ex != NULL)
2982 {
2983 return D3DPOOL_DEFAULT;
2984 }
2985 else
2986 {
2987 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2988 {
2989 return D3DPOOL_MANAGED;
2990 }
2991 }
2992
2993 return D3DPOOL_DEFAULT;
2994}
2995
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002996bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
2997{
2998 if (source && dest)
2999 {
3000 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
3001 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
3002
3003 if (fromManaged)
3004 {
3005 D3DSURFACE_DESC desc;
3006 source->GetDesc(&desc);
3007
3008 IDirect3DSurface9 *surf = 0;
3009 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
3010
3011 if (SUCCEEDED(result))
3012 {
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00003013 Image9::copyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00003014 result = device->UpdateSurface(surf, NULL, dest, NULL);
3015 surf->Release();
3016 }
3017 }
3018 else
3019 {
3020 endScene();
3021 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
3022 }
3023
3024 if (FAILED(result))
3025 {
3026 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
3027 return false;
3028 }
3029 }
3030
3031 return true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00003032}
3033
daniel@transgaming.com244e1832012-12-20 20:52:35 +00003034Image *Renderer9::createImage()
3035{
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00003036 return new Image9();
daniel@transgaming.com244e1832012-12-20 20:52:35 +00003037}
3038
daniel@transgaming.comf721fdb2012-12-20 20:53:11 +00003039void Renderer9::generateMipmap(Image *dest, Image *src)
3040{
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00003041 Image9 *src9 = Image9::makeImage9(src);
3042 Image9 *dst9 = Image9::makeImage9(dest);
3043 Image9::generateMipmap(dst9, src9);
daniel@transgaming.comf721fdb2012-12-20 20:53:11 +00003044}
3045
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003046}