blob: 7b23c94b30081a789ccfc09c79410ef6a7518493 [file] [log] [blame]
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001//
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6
daniel@transgaming.com1d6aff22012-11-28 19:30:42 +00007// Renderer9.cpp: Implements a back-end specific class for the D3D9 renderer.
daniel@transgaming.com621ce052012-10-31 17:52:29 +00008
daniel@transgaming.com621ce052012-10-31 17:52:29 +00009#include "common/debug.h"
daniel@transgaming.com493d4f82012-11-28 19:35:45 +000010#include "libGLESv2/main.h"
daniel@transgaming.com621ce052012-10-31 17:52:29 +000011#include "libGLESv2/utilities.h"
daniel@transgaming.com493d4f82012-11-28 19:35:45 +000012#include "libGLESv2/mathutil.h"
daniel@transgaming.com91207b72012-11-28 20:56:43 +000013#include "libGLESv2/Buffer.h"
daniel@transgaming.com493d4f82012-11-28 19:35:45 +000014#include "libGLESv2/Framebuffer.h"
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +000015#include "libGLESv2/Program.h"
16#include "libGLESv2/ProgramBinary.h"
daniel@transgaming.com50aadb02012-11-28 21:06:11 +000017#include "libGLESv2/renderer/IndexDataManager.h"
18#include "libGLESv2/renderer/VertexDataManager.h"
daniel@transgaming.com2507f412012-10-31 18:46:48 +000019#include "libGLESv2/renderer/Renderer9.h"
daniel@transgaming.comd8e36562012-10-31 19:52:19 +000020#include "libGLESv2/renderer/renderer9_utils.h"
daniel@transgaming.coma9c71422012-11-28 20:58:45 +000021#include "libGLESv2/renderer/ShaderExecutable9.h"
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +000022#include "libGLESv2/renderer/SwapChain9.h"
daniel@transgaming.com34da3972012-12-20 21:10:29 +000023#include "libGLESv2/renderer/TextureStorage9.h"
daniel@transgaming.com4ba24062012-12-20 20:54:24 +000024#include "libGLESv2/renderer/Image9.h"
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000025#include "libGLESv2/renderer/Blit.h"
daniel@transgaming.comd186dc72012-11-28 19:40:16 +000026#include "libGLESv2/renderer/RenderTarget9.h"
daniel@transgaming.com3f255b42012-12-20 21:07:35 +000027#include "libGLESv2/renderer/VertexBuffer9.h"
daniel@transgaming.com0b6d7742012-12-20 21:09:47 +000028#include "libGLESv2/renderer/IndexBuffer9.h"
daniel@transgaming.com621ce052012-10-31 17:52:29 +000029
daniel@transgaming.com3281f972012-10-31 18:38:51 +000030#include "libEGL/Config.h"
daniel@transgaming.comef21ab22012-10-31 17:52:47 +000031#include "libEGL/Display.h"
32
daniel@transgaming.com621ce052012-10-31 17:52:29 +000033// Can also be enabled by defining FORCE_REF_RAST in the project's predefined macros
34#define REF_RAST 0
35
36// The "Debug This Pixel..." feature in PIX often fails when using the
37// D3D9Ex interfaces. In order to get debug pixel to work on a Vista/Win 7
38// machine, define "ANGLE_ENABLE_D3D9EX=0" in your project file.
39#if !defined(ANGLE_ENABLE_D3D9EX)
40// Enables use of the IDirect3D9Ex interface, when available
41#define ANGLE_ENABLE_D3D9EX 1
42#endif // !defined(ANGLE_ENABLE_D3D9EX)
43
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +000044namespace rx
daniel@transgaming.com621ce052012-10-31 17:52:29 +000045{
daniel@transgaming.com222ee082012-11-28 19:31:49 +000046static const D3DFORMAT RenderTargetFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000047 {
48 D3DFMT_A1R5G5B5,
49 // D3DFMT_A2R10G10B10, // The color_ramp conformance test uses ReadPixels with UNSIGNED_BYTE causing it to think that rendering skipped a colour value.
50 D3DFMT_A8R8G8B8,
51 D3DFMT_R5G6B5,
52 // D3DFMT_X1R5G5B5, // Has no compatible OpenGL ES renderbuffer format
53 D3DFMT_X8R8G8B8
54 };
55
daniel@transgaming.com222ee082012-11-28 19:31:49 +000056static const D3DFORMAT DepthStencilFormats[] =
daniel@transgaming.com92955622012-10-31 18:38:41 +000057 {
58 D3DFMT_UNKNOWN,
59 // D3DFMT_D16_LOCKABLE,
60 D3DFMT_D32,
61 // D3DFMT_D15S1,
62 D3DFMT_D24S8,
63 D3DFMT_D24X8,
64 // D3DFMT_D24X4S4,
65 D3DFMT_D16,
66 // D3DFMT_D32F_LOCKABLE,
67 // D3DFMT_D24FS8
68 };
daniel@transgaming.com621ce052012-10-31 17:52:29 +000069
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000070Renderer9::Renderer9(egl::Display *display, HDC hDc, bool softwareDevice) : Renderer(display), mDc(hDc), mSoftwareDevice(softwareDevice)
daniel@transgaming.com621ce052012-10-31 17:52:29 +000071{
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +000072 mD3d9Module = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000073
74 mD3d9 = NULL;
75 mD3d9Ex = NULL;
76 mDevice = NULL;
77 mDeviceEx = NULL;
78 mDeviceWindow = NULL;
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +000079 mBlit = NULL;
daniel@transgaming.com621ce052012-10-31 17:52:29 +000080
81 mAdapter = D3DADAPTER_DEFAULT;
82
83 #if REF_RAST == 1 || defined(FORCE_REF_RAST)
84 mDeviceType = D3DDEVTYPE_REF;
85 #else
86 mDeviceType = D3DDEVTYPE_HAL;
87 #endif
88
89 mDeviceLost = false;
daniel@transgaming.comb7833982012-10-31 18:31:46 +000090
91 mMaxSupportedSamples = 0;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +000092
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +000093 mMaskedClearSavedState = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +000094
95 mVertexDataManager = NULL;
96 mIndexDataManager = NULL;
97 mLineLoopIB = NULL;
daniel@transgaming.come4e1a332012-12-20 20:52:09 +000098
99 mMaxNullColorbufferLRU = 0;
100 for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
101 {
102 mNullColorbufferCache[i].lruCount = 0;
103 mNullColorbufferCache[i].width = 0;
104 mNullColorbufferCache[i].height = 0;
105 mNullColorbufferCache[i].buffer = NULL;
106 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000107}
108
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000109Renderer9::~Renderer9()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000110{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000111 releaseDeviceResources();
112
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000113 if (mDevice)
114 {
115 // If the device is lost, reset it first to prevent leaving the driver in an unstable state
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000116 if (testDeviceLost(false))
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000117 {
118 resetDevice();
119 }
120
121 mDevice->Release();
122 mDevice = NULL;
123 }
124
125 if (mDeviceEx)
126 {
127 mDeviceEx->Release();
128 mDeviceEx = NULL;
129 }
130
131 if (mD3d9)
132 {
133 mD3d9->Release();
134 mD3d9 = NULL;
135 }
136
137 if (mDeviceWindow)
138 {
139 DestroyWindow(mDeviceWindow);
140 mDeviceWindow = NULL;
141 }
142
143 if (mD3d9Ex)
144 {
145 mD3d9Ex->Release();
146 mD3d9Ex = NULL;
147 }
148
149 if (mD3d9Module)
150 {
151 mD3d9Module = NULL;
152 }
153
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000154 while (!mMultiSampleSupport.empty())
155 {
156 delete [] mMultiSampleSupport.begin()->second;
157 mMultiSampleSupport.erase(mMultiSampleSupport.begin());
158 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000159}
160
daniel@transgaming.comb64ed282012-11-28 20:54:02 +0000161Renderer9 *Renderer9::makeRenderer9(Renderer *renderer)
162{
163 ASSERT(dynamic_cast<rx::Renderer9*>(renderer) != NULL);
164 return static_cast<rx::Renderer9*>(renderer);
165}
166
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000167EGLint Renderer9::initialize()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000168{
daniel@transgaming.com25e16af2012-11-28 21:05:57 +0000169 if (!initializeCompiler())
170 {
171 return EGL_NOT_INITIALIZED;
172 }
173
daniel@transgaming.com95ffbc12012-10-31 19:55:27 +0000174 if (mSoftwareDevice)
175 {
176 mD3d9Module = GetModuleHandle(TEXT("swiftshader_d3d9.dll"));
177 }
178 else
179 {
180 mD3d9Module = GetModuleHandle(TEXT("d3d9.dll"));
181 }
182
183 if (mD3d9Module == NULL)
184 {
185 ERR("No D3D9 module found - aborting!\n");
186 return EGL_NOT_INITIALIZED;
187 }
188
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000189 typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT, IDirect3D9Ex**);
190 Direct3DCreate9ExFunc Direct3DCreate9ExPtr = reinterpret_cast<Direct3DCreate9ExFunc>(GetProcAddress(mD3d9Module, "Direct3DCreate9Ex"));
191
192 // Use Direct3D9Ex if available. Among other things, this version is less
193 // inclined to report a lost context, for example when the user switches
194 // desktop. Direct3D9Ex is available in Windows Vista and later if suitable drivers are available.
195 if (ANGLE_ENABLE_D3D9EX && Direct3DCreate9ExPtr && SUCCEEDED(Direct3DCreate9ExPtr(D3D_SDK_VERSION, &mD3d9Ex)))
196 {
197 ASSERT(mD3d9Ex);
198 mD3d9Ex->QueryInterface(IID_IDirect3D9, reinterpret_cast<void**>(&mD3d9));
199 ASSERT(mD3d9);
200 }
201 else
202 {
203 mD3d9 = Direct3DCreate9(D3D_SDK_VERSION);
204 }
205
206 if (!mD3d9)
207 {
208 ERR("Could not create D3D9 device - aborting!\n");
209 return EGL_NOT_INITIALIZED;
210 }
daniel@transgaming.com7d738a22012-11-28 19:43:08 +0000211
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000212 if (mDc != NULL)
213 {
214 // UNIMPLEMENTED(); // FIXME: Determine which adapter index the device context corresponds to
215 }
216
217 HRESULT result;
218
219 // Give up on getting device caps after about one second.
220 for (int i = 0; i < 10; ++i)
221 {
222 result = mD3d9->GetDeviceCaps(mAdapter, mDeviceType, &mDeviceCaps);
223 if (SUCCEEDED(result))
224 {
225 break;
226 }
227 else if (result == D3DERR_NOTAVAILABLE)
228 {
229 Sleep(100); // Give the driver some time to initialize/recover
230 }
231 else if (FAILED(result)) // D3DERR_OUTOFVIDEOMEMORY, E_OUTOFMEMORY, D3DERR_INVALIDDEVICE, or another error we can't recover from
232 {
233 ERR("failed to get device caps (0x%x)\n", result);
234 return EGL_NOT_INITIALIZED;
235 }
236 }
237
238 if (mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
239 {
240 ERR("Renderer does not support PS 2.0. aborting!\n");
241 return EGL_NOT_INITIALIZED;
242 }
243
244 // When DirectX9 is running with an older DirectX8 driver, a StretchRect from a regular texture to a render target texture is not supported.
245 // This is required by Texture2D::convertToRenderTarget.
246 if ((mDeviceCaps.DevCaps2 & D3DDEVCAPS2_CAN_STRETCHRECT_FROM_TEXTURES) == 0)
247 {
248 ERR("Renderer does not support stretctrect from textures!\n");
249 return EGL_NOT_INITIALIZED;
250 }
251
252 mD3d9->GetAdapterIdentifier(mAdapter, 0, &mAdapterIdentifier);
253
254 // ATI cards on XP have problems with non-power-of-two textures.
255 mSupportsNonPower2Textures = !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_POW2) &&
256 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_CUBEMAP_POW2) &&
257 !(mDeviceCaps.TextureCaps & D3DPTEXTURECAPS_NONPOW2CONDITIONAL) &&
258 !(getComparableOSVersion() < versionWindowsVista && mAdapterIdentifier.VendorId == VENDOR_ID_AMD);
259
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000260 // Must support a minimum of 2:1 anisotropy for max anisotropy to be considered supported, per the spec
261 mSupportsTextureFilterAnisotropy = ((mDeviceCaps.RasterCaps & D3DPRASTERCAPS_ANISOTROPY) && (mDeviceCaps.MaxAnisotropy >= 2));
262
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000263 mMinSwapInterval = 4;
264 mMaxSwapInterval = 0;
265
266 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_IMMEDIATE)
267 {
268 mMinSwapInterval = std::min(mMinSwapInterval, 0);
269 mMaxSwapInterval = std::max(mMaxSwapInterval, 0);
270 }
271 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_ONE)
272 {
273 mMinSwapInterval = std::min(mMinSwapInterval, 1);
274 mMaxSwapInterval = std::max(mMaxSwapInterval, 1);
275 }
276 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_TWO)
277 {
278 mMinSwapInterval = std::min(mMinSwapInterval, 2);
279 mMaxSwapInterval = std::max(mMaxSwapInterval, 2);
280 }
281 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_THREE)
282 {
283 mMinSwapInterval = std::min(mMinSwapInterval, 3);
284 mMaxSwapInterval = std::max(mMaxSwapInterval, 3);
285 }
286 if (mDeviceCaps.PresentationIntervals & D3DPRESENT_INTERVAL_FOUR)
287 {
288 mMinSwapInterval = std::min(mMinSwapInterval, 4);
289 mMaxSwapInterval = std::max(mMaxSwapInterval, 4);
290 }
291
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000292 int max = 0;
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000293 for (int i = 0; i < sizeof(RenderTargetFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000294 {
295 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000296 getMultiSampleSupport(RenderTargetFormats[i], multisampleArray);
297 mMultiSampleSupport[RenderTargetFormats[i]] = multisampleArray;
daniel@transgaming.com92955622012-10-31 18:38:41 +0000298
299 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
300 {
301 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
302 {
303 max = j;
304 }
305 }
306 }
307
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000308 for (int i = 0; i < sizeof(DepthStencilFormats) / sizeof(D3DFORMAT); ++i)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000309 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000310 if (DepthStencilFormats[i] == D3DFMT_UNKNOWN)
daniel@transgaming.com92955622012-10-31 18:38:41 +0000311 continue;
312
313 bool *multisampleArray = new bool[D3DMULTISAMPLE_16_SAMPLES + 1];
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000314 getMultiSampleSupport(DepthStencilFormats[i], multisampleArray);
315 mMultiSampleSupport[DepthStencilFormats[i]] = multisampleArray;
daniel@transgaming.comb7833982012-10-31 18:31:46 +0000316
317 for (int j = D3DMULTISAMPLE_16_SAMPLES; j >= 0; --j)
318 {
319 if (multisampleArray[j] && j != D3DMULTISAMPLE_NONMASKABLE && j > max)
320 {
321 max = j;
322 }
323 }
324 }
325
326 mMaxSupportedSamples = max;
327
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000328 static const TCHAR windowName[] = TEXT("AngleHiddenWindow");
329 static const TCHAR className[] = TEXT("STATIC");
330
331 mDeviceWindow = CreateWindowEx(WS_EX_NOACTIVATE, className, windowName, WS_DISABLED | WS_POPUP, 0, 0, 1, 1, HWND_MESSAGE, NULL, GetModuleHandle(NULL), NULL);
332
333 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
334 DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE | D3DCREATE_NOWINDOWCHANGES;
335
336 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE, &presentParameters, &mDevice);
337 if (result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_DEVICELOST)
338 {
339 return EGL_BAD_ALLOC;
340 }
341
342 if (FAILED(result))
343 {
344 result = mD3d9->CreateDevice(mAdapter, mDeviceType, mDeviceWindow, behaviorFlags | D3DCREATE_SOFTWARE_VERTEXPROCESSING, &presentParameters, &mDevice);
345
346 if (FAILED(result))
347 {
348 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY || result == D3DERR_NOTAVAILABLE || result == D3DERR_DEVICELOST);
349 return EGL_BAD_ALLOC;
350 }
351 }
352
353 if (mD3d9Ex)
354 {
355 result = mDevice->QueryInterface(IID_IDirect3DDevice9Ex, (void**) &mDeviceEx);
356 ASSERT(SUCCEEDED(result));
357 }
358
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000359 mVertexShaderCache.initialize(mDevice);
360 mPixelShaderCache.initialize(mDevice);
361
daniel@transgaming.com669c9952013-01-11 04:08:16 +0000362 // Check occlusion query support
363 IDirect3DQuery9 *occlusionQuery = NULL;
364 if (SUCCEEDED(mDevice->CreateQuery(D3DQUERYTYPE_OCCLUSION, &occlusionQuery)) && occlusionQuery)
365 {
366 occlusionQuery->Release();
367 mOcclusionQuerySupport = true;
368 }
369 else
370 {
371 mOcclusionQuerySupport = false;
372 }
373
374 // Check event query support
375 IDirect3DQuery9 *eventQuery = NULL;
376 if (SUCCEEDED(mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &eventQuery)) && eventQuery)
377 {
378 eventQuery->Release();
379 mEventQuerySupport = true;
380 }
381 else
382 {
383 mEventQuerySupport = false;
384 }
385
386 D3DDISPLAYMODE currentDisplayMode;
387 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
388
389 // Check vertex texture support
390 // Only Direct3D 10 ready devices support all the necessary vertex texture formats.
391 // We test this using D3D9 by checking support for the R16F format.
392 mVertexTextureSupport = mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0) &&
393 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
394 D3DUSAGE_QUERY_VERTEXTEXTURE, D3DRTYPE_TEXTURE, D3DFMT_R16F));
395
396 // Check depth texture support
397 // we use INTZ for depth textures in Direct3D9
398 // we also want NULL texture support to ensure the we can make depth-only FBOs
399 // see http://aras-p.info/texts/D3D9GPUHacks.html
400 mDepthTextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
401 D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE, D3DFMT_INTZ)) &&
402 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format,
403 D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, D3DFMT_NULL));
404
405 // Check 32 bit floating point texture support
406 mFloat32FilterSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
407 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
408 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
409 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
410
411 mFloat32RenderSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
412 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
413 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
414 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
415
416 if (!mFloat32FilterSupport && !mFloat32RenderSupport)
417 {
418 mFloat32TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
419 D3DRTYPE_TEXTURE, D3DFMT_A32B32G32R32F)) &&
420 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
421 D3DRTYPE_CUBETEXTURE, D3DFMT_A32B32G32R32F));
422 }
423 else
424 {
425 mFloat32TextureSupport = true;
426 }
427
428 // Check 16 bit floating point texture support
429 mFloat16FilterSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
430 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
431 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_QUERY_FILTER,
432 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
433
434 mFloat16RenderSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
435 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
436 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET,
437 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
438
439 if (!mFloat16FilterSupport && !mFloat16RenderSupport)
440 {
441 mFloat16TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
442 D3DRTYPE_TEXTURE, D3DFMT_A16B16G16R16F)) &&
443 SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0,
444 D3DRTYPE_CUBETEXTURE, D3DFMT_A16B16G16R16F));
445 }
446 else
447 {
448 mFloat16TextureSupport = true;
449 }
450
451 // Check DXT texture support
452 mDXT1TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT1));
453 mDXT3TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT3));
454 mDXT5TextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_DXT5));
455
456 // Check luminance[alpha] texture support
457 mLuminanceTextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_L8));
458 mLuminanceAlphaTextureSupport = SUCCEEDED(mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, 0, D3DRTYPE_TEXTURE, D3DFMT_A8L8));
459
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000460 initializeDevice();
461
462 return EGL_SUCCESS;
463}
464
465// do any one-time device initialization
466// NOTE: this is also needed after a device lost/reset
467// to reset the scene status and ensure the default states are reset.
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000468void Renderer9::initializeDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000469{
470 // Permanent non-default states
471 mDevice->SetRenderState(D3DRS_POINTSPRITEENABLE, TRUE);
472 mDevice->SetRenderState(D3DRS_LASTPIXEL, FALSE);
473
474 if (mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0))
475 {
476 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, (DWORD&)mDeviceCaps.MaxPointSize);
477 }
478 else
479 {
480 mDevice->SetRenderState(D3DRS_POINTSIZE_MAX, 0x3F800000); // 1.0f
481 }
482
daniel@transgaming.comc43a6052012-11-28 19:41:51 +0000483 markAllStateDirty();
484
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000485 mSceneStarted = false;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +0000486
daniel@transgaming.com91207b72012-11-28 20:56:43 +0000487 ASSERT(!mBlit && !mVertexDataManager && !mIndexDataManager);
daniel@transgaming.come569fc52012-11-28 20:56:02 +0000488 mBlit = new Blit(this);
daniel@transgaming.com31240482012-11-28 21:06:41 +0000489 mVertexDataManager = new rx::VertexDataManager(this);
490 mIndexDataManager = new rx::IndexDataManager(this);
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000491}
492
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000493D3DPRESENT_PARAMETERS Renderer9::getDefaultPresentParameters()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000494{
495 D3DPRESENT_PARAMETERS presentParameters = {0};
496
497 // The default swap chain is never actually used. Surface will create a new swap chain with the proper parameters.
498 presentParameters.AutoDepthStencilFormat = D3DFMT_UNKNOWN;
499 presentParameters.BackBufferCount = 1;
500 presentParameters.BackBufferFormat = D3DFMT_UNKNOWN;
501 presentParameters.BackBufferWidth = 1;
502 presentParameters.BackBufferHeight = 1;
503 presentParameters.EnableAutoDepthStencil = FALSE;
504 presentParameters.Flags = 0;
505 presentParameters.hDeviceWindow = mDeviceWindow;
506 presentParameters.MultiSampleQuality = 0;
507 presentParameters.MultiSampleType = D3DMULTISAMPLE_NONE;
508 presentParameters.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
509 presentParameters.SwapEffect = D3DSWAPEFFECT_DISCARD;
510 presentParameters.Windowed = TRUE;
511
512 return presentParameters;
513}
514
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000515int Renderer9::generateConfigs(ConfigDesc **configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000516{
517 D3DDISPLAYMODE currentDisplayMode;
518 mD3d9->GetAdapterDisplayMode(mAdapter, &currentDisplayMode);
519
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000520 unsigned int numRenderFormats = sizeof(RenderTargetFormats) / sizeof(RenderTargetFormats[0]);
521 unsigned int numDepthFormats = sizeof(DepthStencilFormats) / sizeof(DepthStencilFormats[0]);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000522 (*configDescList) = new ConfigDesc[numRenderFormats * numDepthFormats];
523 int numConfigs = 0;
524
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000525 for (unsigned int formatIndex = 0; formatIndex < numRenderFormats; formatIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000526 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000527 D3DFORMAT renderTargetFormat = RenderTargetFormats[formatIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000528
529 HRESULT result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_RENDERTARGET, D3DRTYPE_SURFACE, renderTargetFormat);
530
531 if (SUCCEEDED(result))
532 {
daniel@transgaming.come3e826d2012-11-28 19:42:35 +0000533 for (unsigned int depthStencilIndex = 0; depthStencilIndex < numDepthFormats; depthStencilIndex++)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000534 {
daniel@transgaming.com222ee082012-11-28 19:31:49 +0000535 D3DFORMAT depthStencilFormat = DepthStencilFormats[depthStencilIndex];
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000536 HRESULT result = D3D_OK;
537
538 if(depthStencilFormat != D3DFMT_UNKNOWN)
539 {
540 result = mD3d9->CheckDeviceFormat(mAdapter, mDeviceType, currentDisplayMode.Format, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_SURFACE, depthStencilFormat);
541 }
542
543 if (SUCCEEDED(result))
544 {
545 if(depthStencilFormat != D3DFMT_UNKNOWN)
546 {
547 result = mD3d9->CheckDepthStencilMatch(mAdapter, mDeviceType, currentDisplayMode.Format, renderTargetFormat, depthStencilFormat);
548 }
549
550 if (SUCCEEDED(result))
551 {
552 ConfigDesc newConfig;
daniel@transgaming.com682a37c2012-11-28 19:34:44 +0000553 newConfig.renderTargetFormat = d3d9_gl::ConvertBackBufferFormat(renderTargetFormat);
554 newConfig.depthStencilFormat = d3d9_gl::ConvertDepthStencilFormat(depthStencilFormat);
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000555 newConfig.multiSample = 0; // FIXME: enumerate multi-sampling
556 newConfig.fastConfig = (currentDisplayMode.Format == renderTargetFormat);
557
558 (*configDescList)[numConfigs++] = newConfig;
559 }
560 }
561 }
562 }
563 }
564
565 return numConfigs;
566}
567
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000568void Renderer9::deleteConfigs(ConfigDesc *configDescList)
daniel@transgaming.com3281f972012-10-31 18:38:51 +0000569{
570 delete [] (configDescList);
571}
572
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000573void Renderer9::startScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000574{
575 if (!mSceneStarted)
576 {
577 long result = mDevice->BeginScene();
578 if (SUCCEEDED(result)) {
579 // This is defensive checking against the device being
580 // lost at unexpected times.
581 mSceneStarted = true;
582 }
583 }
584}
585
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000586void Renderer9::endScene()
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000587{
588 if (mSceneStarted)
589 {
590 // EndScene can fail if the device was lost, for example due
591 // to a TDR during a draw call.
592 mDevice->EndScene();
593 mSceneStarted = false;
594 }
595}
596
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000597// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000598void Renderer9::sync(bool block)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000599{
600 HRESULT result;
601
602 IDirect3DQuery9* query = allocateEventQuery();
603 if (!query)
604 {
605 return;
606 }
607
608 result = query->Issue(D3DISSUE_END);
609 ASSERT(SUCCEEDED(result));
610
611 do
612 {
613 result = query->GetData(NULL, 0, D3DGETDATA_FLUSH);
614
615 if(block && result == S_FALSE)
616 {
617 // Keep polling, but allow other threads to do something useful first
618 Sleep(0);
619 // explicitly check for device loss
620 // some drivers seem to return S_FALSE even if the device is lost
621 // instead of D3DERR_DEVICELOST like they should
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000622 if (testDeviceLost(false))
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000623 {
624 result = D3DERR_DEVICELOST;
625 }
626 }
627 }
628 while(block && result == S_FALSE);
629
630 freeEventQuery(query);
631
632 if (isDeviceLostError(result))
633 {
634 mDisplay->notifyDeviceLost();
635 }
636}
637
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000638SwapChain *Renderer9::createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
639{
daniel@transgaming.coma27e05b2012-11-28 19:39:42 +0000640 return new rx::SwapChain9(this, window, shareHandle, backBufferFormat, depthBufferFormat);
daniel@transgaming.comb9bb2792012-11-28 19:36:49 +0000641}
642
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000643// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000644IDirect3DQuery9* Renderer9::allocateEventQuery()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000645{
646 IDirect3DQuery9 *query = NULL;
647
648 if (mEventQueryPool.empty())
649 {
650 HRESULT result = mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &query);
651 ASSERT(SUCCEEDED(result));
652 }
653 else
654 {
655 query = mEventQueryPool.back();
656 mEventQueryPool.pop_back();
657 }
658
659 return query;
660}
661
662// D3D9_REPLACE
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000663void Renderer9::freeEventQuery(IDirect3DQuery9* query)
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000664{
665 if (mEventQueryPool.size() > 1000)
666 {
667 query->Release();
668 }
669 else
670 {
671 mEventQueryPool.push_back(query);
672 }
673}
674
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000675IDirect3DVertexShader9 *Renderer9::createVertexShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000676{
677 return mVertexShaderCache.create(function, length);
678}
679
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000680IDirect3DPixelShader9 *Renderer9::createPixelShader(const DWORD *function, size_t length)
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000681{
682 return mPixelShaderCache.create(function, length);
683}
684
daniel@transgaming.com113f0eb2012-10-31 18:46:58 +0000685HRESULT Renderer9::createVertexBuffer(UINT Length, DWORD Usage, IDirect3DVertexBuffer9 **ppVertexBuffer)
686{
687 D3DPOOL Pool = getBufferPool(Usage);
688 return mDevice->CreateVertexBuffer(Length, Usage, 0, Pool, ppVertexBuffer, NULL);
689}
690
daniel@transgaming.com3f255b42012-12-20 21:07:35 +0000691VertexBuffer *Renderer9::createVertexBuffer()
692{
693 return new VertexBuffer9(this);
694}
695
daniel@transgaming.com113f0eb2012-10-31 18:46:58 +0000696HRESULT Renderer9::createIndexBuffer(UINT Length, DWORD Usage, D3DFORMAT Format, IDirect3DIndexBuffer9 **ppIndexBuffer)
697{
698 D3DPOOL Pool = getBufferPool(Usage);
699 return mDevice->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, NULL);
700}
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000701
daniel@transgaming.com0b6d7742012-12-20 21:09:47 +0000702IndexBuffer *Renderer9::createIndexBuffer()
703{
704 return new IndexBuffer9(this);
705}
706
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000707void Renderer9::setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &samplerState)
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000708{
daniel@transgaming.come33c8bf2013-01-11 04:11:33 +0000709 bool *forceSetSamplers = (type == gl::SAMPLER_PIXEL) ? mForceSetPixelSamplerStates : mForceSetVertexSamplerStates;
710 gl::SamplerState *appliedSamplers = (type == gl::SAMPLER_PIXEL) ? mCurPixelSamplerStates: mCurVertexSamplerStates;
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000711
daniel@transgaming.come33c8bf2013-01-11 04:11:33 +0000712 if (forceSetSamplers[index] || memcmp(&samplerState, &appliedSamplers[index], sizeof(gl::SamplerState)) != 0)
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000713 {
daniel@transgaming.come33c8bf2013-01-11 04:11:33 +0000714 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
715 int d3dSampler = index + d3dSamplerOffset;
716
717 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSU, gl_d3d9::ConvertTextureWrap(samplerState.wrapS));
718 mDevice->SetSamplerState(d3dSampler, D3DSAMP_ADDRESSV, gl_d3d9::ConvertTextureWrap(samplerState.wrapT));
719
720 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAGFILTER, gl_d3d9::ConvertMagFilter(samplerState.magFilter, samplerState.maxAnisotropy));
721 D3DTEXTUREFILTERTYPE d3dMinFilter, d3dMipFilter;
722 gl_d3d9::ConvertMinFilter(samplerState.minFilter, &d3dMinFilter, &d3dMipFilter, samplerState.maxAnisotropy);
723 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MINFILTER, d3dMinFilter);
724 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MIPFILTER, d3dMipFilter);
725 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXMIPLEVEL, samplerState.lodOffset);
726 if (mSupportsTextureFilterAnisotropy)
727 {
728 mDevice->SetSamplerState(d3dSampler, D3DSAMP_MAXANISOTROPY, (DWORD)samplerState.maxAnisotropy);
729 }
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000730 }
daniel@transgaming.come33c8bf2013-01-11 04:11:33 +0000731
732 forceSetSamplers[index] = false;
733 appliedSamplers[index] = samplerState;
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000734}
735
daniel@transgaming.com2507f412012-10-31 18:46:48 +0000736void Renderer9::setTexture(gl::SamplerType type, int index, gl::Texture *texture)
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000737{
738 int d3dSamplerOffset = (type == gl::SAMPLER_PIXEL) ? 0 : D3DVERTEXTEXTURESAMPLER0;
739 int d3dSampler = index + d3dSamplerOffset;
740 IDirect3DBaseTexture9 *d3dTexture = NULL;
daniel@transgaming.come33c8bf2013-01-11 04:11:33 +0000741 unsigned int serial = 0;
742 bool forceSetTexture = false;
743
744 unsigned int *appliedSerials = (type == gl::SAMPLER_PIXEL) ? mCurPixelTextureSerials : mCurVertexTextureSerials;
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000745
746 if (texture)
747 {
daniel@transgaming.com87705f82012-12-20 21:10:45 +0000748 TextureStorageInterface *texStorage = texture->getNativeTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000749 if (texStorage)
750 {
daniel@transgaming.com87705f82012-12-20 21:10:45 +0000751 TextureStorage9 *storage9 = TextureStorage9::makeTextureStorage9(texStorage->getStorageInstance());
daniel@transgaming.com34da3972012-12-20 21:10:29 +0000752 d3dTexture = storage9->getBaseTexture();
daniel@transgaming.com9d4346f2012-10-31 19:52:04 +0000753 }
754 // If we get NULL back from getBaseTexture here, something went wrong
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000755 // in the texture class and we're unexpectedly missing the d3d texture
756 ASSERT(d3dTexture != NULL);
daniel@transgaming.come33c8bf2013-01-11 04:11:33 +0000757
758 serial = texture->getTextureSerial();
759 forceSetTexture = texture->hasDirtyImages();
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000760 }
761
daniel@transgaming.come33c8bf2013-01-11 04:11:33 +0000762 if (forceSetTexture || appliedSerials[index] != serial)
763 {
764 mDevice->SetTexture(d3dSampler, d3dTexture);
765 }
766
767 appliedSerials[index] = serial;
daniel@transgaming.coma734f272012-10-31 18:07:48 +0000768}
769
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000770void Renderer9::setRasterizerState(const gl::RasterizerState &rasterState)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000771{
772 bool rasterStateChanged = mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000773
774 if (rasterStateChanged)
775 {
776 // Set the cull mode
777 if (rasterState.cullFace)
778 {
779 mDevice->SetRenderState(D3DRS_CULLMODE, gl_d3d9::ConvertCullMode(rasterState.cullMode, rasterState.frontFace));
780 }
781 else
782 {
783 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
784 }
785
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000786 if (rasterState.polygonOffsetFill)
787 {
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000788 if (mCurDepthSize > 0)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000789 {
790 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&rasterState.polygonOffsetFactor);
791
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000792 float depthBias = ldexp(rasterState.polygonOffsetUnits, -static_cast<int>(mCurDepthSize));
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000793 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
794 }
795 }
796 else
797 {
798 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
799 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
800 }
801
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +0000802 mCurRasterState = rasterState;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000803 }
804
805 mForceSetRasterState = false;
806}
807
808void Renderer9::setBlendState(const gl::BlendState &blendState, const gl::Color &blendColor, unsigned int sampleMask)
809{
810 bool blendStateChanged = mForceSetBlendState || memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0;
811 bool blendColorChanged = mForceSetBlendState || memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0;
812 bool sampleMaskChanged = mForceSetBlendState || sampleMask != mCurSampleMask;
813
814 if (blendStateChanged || blendColorChanged)
815 {
816 if (blendState.blend)
817 {
818 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
819
820 if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
821 blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
822 {
823 mDevice->SetRenderState(D3DRS_BLENDFACTOR, gl_d3d9::ConvertColor(blendColor));
824 }
825 else
826 {
827 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(gl::unorm<8>(blendColor.alpha),
828 gl::unorm<8>(blendColor.alpha),
829 gl::unorm<8>(blendColor.alpha),
830 gl::unorm<8>(blendColor.alpha)));
831 }
832
833 mDevice->SetRenderState(D3DRS_SRCBLEND, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendRGB));
834 mDevice->SetRenderState(D3DRS_DESTBLEND, gl_d3d9::ConvertBlendFunc(blendState.destBlendRGB));
835 mDevice->SetRenderState(D3DRS_BLENDOP, gl_d3d9::ConvertBlendOp(blendState.blendEquationRGB));
836
837 if (blendState.sourceBlendRGB != blendState.sourceBlendAlpha ||
838 blendState.destBlendRGB != blendState.destBlendAlpha ||
839 blendState.blendEquationRGB != blendState.blendEquationAlpha)
840 {
841 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
842
843 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.sourceBlendAlpha));
844 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, gl_d3d9::ConvertBlendFunc(blendState.destBlendAlpha));
845 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, gl_d3d9::ConvertBlendOp(blendState.blendEquationAlpha));
846 }
847 else
848 {
849 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
850 }
851 }
852 else
853 {
854 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
855 }
856
857 if (blendState.sampleAlphaToCoverage)
858 {
859 FIXME("Sample alpha to coverage is unimplemented.");
860 }
861
862 // Set the color mask
863 bool zeroColorMaskAllowed = getAdapterVendor() != VENDOR_ID_AMD;
864 // Apparently some ATI cards have a bug where a draw with a zero color
865 // write mask can cause later draws to have incorrect results. Instead,
866 // set a nonzero color write mask but modify the blend state so that no
867 // drawing is done.
868 // http://code.google.com/p/angleproject/issues/detail?id=169
869
870 DWORD colorMask = gl_d3d9::ConvertColorMask(blendState.colorMaskRed, blendState.colorMaskGreen,
871 blendState.colorMaskBlue, blendState.colorMaskAlpha);
872 if (colorMask == 0 && !zeroColorMaskAllowed)
873 {
874 // Enable green channel, but set blending so nothing will be drawn.
875 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
876 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
877
878 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
879 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
880 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
881 }
882 else
883 {
884 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
885 }
886
887 mDevice->SetRenderState(D3DRS_DITHERENABLE, blendState.dither ? TRUE : FALSE);
888
889 mCurBlendState = blendState;
890 mCurBlendColor = blendColor;
891 }
892
893 if (sampleMaskChanged)
894 {
895 // Set the multisample mask
896 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
897 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, static_cast<DWORD>(sampleMask));
898
899 mCurSampleMask = sampleMask;
900 }
901
902 mForceSetBlendState = false;
903}
904
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000905void Renderer9::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000906 int stencilBackRef, bool frontFaceCCW)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000907{
908 bool depthStencilStateChanged = mForceSetDepthStencilState ||
909 memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0;
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000910 bool stencilRefChanged = mForceSetDepthStencilState || stencilRef != mCurStencilRef ||
911 stencilBackRef != mCurStencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000912 bool frontFaceCCWChanged = mForceSetDepthStencilState || frontFaceCCW != mCurFrontFaceCCW;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000913
914 if (depthStencilStateChanged)
915 {
916 if (depthStencilState.depthTest)
917 {
918 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
919 mDevice->SetRenderState(D3DRS_ZFUNC, gl_d3d9::ConvertComparison(depthStencilState.depthFunc));
920 }
921 else
922 {
923 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
924 }
925
926 mCurDepthStencilState = depthStencilState;
927 }
928
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000929 if (depthStencilStateChanged || stencilRefChanged || frontFaceCCWChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000930 {
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000931 if (depthStencilState.stencilTest && mCurStencilSize > 0)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000932 {
933 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
934 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
935
936 // FIXME: Unsupported by D3D9
937 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
938 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
939 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
940 if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000941 stencilRef != stencilBackRef ||
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000942 depthStencilState.stencilMask != depthStencilState.stencilBackMask)
943 {
944 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
945 return error(GL_INVALID_OPERATION);
946 }
947
948 // get the maximum size of the stencil ref
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +0000949 unsigned int maxStencil = (1 << mCurStencilSize) - 1;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000950
951 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
952 depthStencilState.stencilWritemask);
953 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
954 gl_d3d9::ConvertComparison(depthStencilState.stencilFunc));
955
956 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000957 (stencilRef < (int)maxStencil) ? stencilRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000958 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
959 depthStencilState.stencilMask);
960
961 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
962 gl_d3d9::ConvertStencilOp(depthStencilState.stencilFail));
963 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
964 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthFail));
965 mDevice->SetRenderState(frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
966 gl_d3d9::ConvertStencilOp(depthStencilState.stencilPassDepthPass));
967
968 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK,
969 depthStencilState.stencilBackWritemask);
970 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
971 gl_d3d9::ConvertComparison(depthStencilState.stencilBackFunc));
972
973 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF,
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000974 (stencilBackRef < (int)maxStencil) ? stencilBackRef : maxStencil);
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000975 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK,
976 depthStencilState.stencilBackMask);
977
978 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
979 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackFail));
980 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
981 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthFail));
982 mDevice->SetRenderState(!frontFaceCCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
983 gl_d3d9::ConvertStencilOp(depthStencilState.stencilBackPassDepthPass));
984 }
985 else
986 {
987 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
988 }
989
990 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, depthStencilState.depthMask ? TRUE : FALSE);
991
daniel@transgaming.com08c331d2012-11-28 19:38:39 +0000992 mCurStencilRef = stencilRef;
993 mCurStencilBackRef = stencilBackRef;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000994 mCurFrontFaceCCW = frontFaceCCW;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +0000995 }
996
997 mForceSetDepthStencilState = false;
998}
999
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +00001000void Renderer9::setScissorRectangle(const gl::Rectangle &scissor, bool enabled)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001001{
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +00001002 bool scissorChanged = mForceSetScissor ||
1003 memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0 ||
1004 enabled != mScissorEnabled;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001005
daniel@transgaming.com04f1b332012-11-28 21:00:40 +00001006 if (scissorChanged)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001007 {
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +00001008 if (enabled)
1009 {
1010 RECT rect;
1011 rect.left = gl::clamp(scissor.x, 0, static_cast<int>(mRenderTargetDesc.width));
1012 rect.top = gl::clamp(scissor.y, 0, static_cast<int>(mRenderTargetDesc.height));
1013 rect.right = gl::clamp(scissor.x + scissor.width, 0, static_cast<int>(mRenderTargetDesc.width));
1014 rect.bottom = gl::clamp(scissor.y + scissor.height, 0, static_cast<int>(mRenderTargetDesc.height));
1015 mDevice->SetScissorRect(&rect);
1016 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001017
daniel@transgaming.comd55e8c12012-11-28 21:07:02 +00001018 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, enabled ? TRUE : FALSE);
1019
1020 mScissorEnabled = enabled;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001021 mCurScissor = scissor;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001022 }
1023
1024 mForceSetScissor = false;
1025}
1026
daniel@transgaming.com12985182012-12-20 20:56:31 +00001027bool Renderer9::setViewport(const gl::Rectangle &viewport, float zNear, float zFar, GLenum drawMode, GLenum frontFace,
1028 bool ignoreViewport, gl::ProgramBinary *currentProgram, bool forceSetUniforms)
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001029{
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +00001030 gl::Rectangle actualViewport = viewport;
1031 float actualZNear = gl::clamp01(zNear);
1032 float actualZFar = gl::clamp01(zFar);
1033 if (ignoreViewport)
1034 {
1035 actualViewport.x = 0;
1036 actualViewport.y = 0;
1037 actualViewport.width = mRenderTargetDesc.width;
1038 actualViewport.height = mRenderTargetDesc.height;
1039 actualZNear = 0.0f;
1040 actualZFar = 1.0f;
1041 }
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001042
1043 D3DVIEWPORT9 dxViewport;
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +00001044 dxViewport.X = gl::clamp(actualViewport.x, 0, static_cast<int>(mRenderTargetDesc.width));
1045 dxViewport.Y = gl::clamp(actualViewport.y, 0, static_cast<int>(mRenderTargetDesc.height));
1046 dxViewport.Width = gl::clamp(actualViewport.width, 0, static_cast<int>(mRenderTargetDesc.width) - static_cast<int>(dxViewport.X));
1047 dxViewport.Height = gl::clamp(actualViewport.height, 0, static_cast<int>(mRenderTargetDesc.height) - static_cast<int>(dxViewport.Y));
1048 dxViewport.MinZ = actualZNear;
1049 dxViewport.MaxZ = actualZFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001050
1051 if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
1052 {
1053 return false; // Nothing to render
1054 }
1055
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +00001056 bool viewportChanged = mForceSetViewport || memcmp(&actualViewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
1057 actualZNear != mCurNear || actualZFar != mCurFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001058 if (viewportChanged)
1059 {
1060 mDevice->SetViewport(&dxViewport);
1061
daniel@transgaming.com4c4ce232012-11-28 21:01:40 +00001062 mCurViewport = actualViewport;
1063 mCurNear = actualZNear;
1064 mCurFar = actualZFar;
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001065 }
1066
1067 if (currentProgram && (viewportChanged || forceSetUniforms))
1068 {
daniel@transgaming.com88853c52012-12-20 20:56:40 +00001069 currentProgram->applyDxHalfPixelSize(1.0f / dxViewport.Width, -1.0f / dxViewport.Height);
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001070
1071 // These values are used for computing gl_FragCoord in Program::linkVaryings().
daniel@transgaming.com88853c52012-12-20 20:56:40 +00001072 currentProgram->applyDxCoord(actualViewport.width * 0.5f,
1073 actualViewport.height * 0.5f,
1074 actualViewport.x + (actualViewport.width * 0.5f),
1075 actualViewport.y + (actualViewport.height * 0.5f));
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001076
daniel@transgaming.com12985182012-12-20 20:56:31 +00001077 GLfloat ccw = !gl::IsTriangleMode(drawMode) ? 0.0f : (frontFace == GL_CCW ? 1.0f : -1.0f);
daniel@transgaming.com88853c52012-12-20 20:56:40 +00001078 currentProgram->applyDxDepthFront((actualZFar - actualZNear) * 0.5f, (actualZNear + actualZFar) * 0.5f, ccw);
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001079
daniel@transgaming.com88853c52012-12-20 20:56:40 +00001080 currentProgram->applyDxDepthRange(actualZNear, actualZFar, actualZFar - actualZNear);
daniel@transgaming.com83e80ee2012-11-28 19:40:53 +00001081 }
1082
1083 mForceSetViewport = false;
1084 return true;
1085}
1086
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001087bool Renderer9::applyPrimitiveType(GLenum mode, GLsizei count)
1088{
1089 switch (mode)
1090 {
1091 case GL_POINTS:
1092 mPrimitiveType = D3DPT_POINTLIST;
1093 mPrimitiveCount = count;
1094 break;
1095 case GL_LINES:
1096 mPrimitiveType = D3DPT_LINELIST;
1097 mPrimitiveCount = count / 2;
1098 break;
1099 case GL_LINE_LOOP:
1100 mPrimitiveType = D3DPT_LINESTRIP;
1101 mPrimitiveCount = count - 1; // D3D doesn't support line loops, so we draw the last line separately
1102 break;
1103 case GL_LINE_STRIP:
1104 mPrimitiveType = D3DPT_LINESTRIP;
1105 mPrimitiveCount = count - 1;
1106 break;
1107 case GL_TRIANGLES:
1108 mPrimitiveType = D3DPT_TRIANGLELIST;
1109 mPrimitiveCount = count / 3;
1110 break;
1111 case GL_TRIANGLE_STRIP:
1112 mPrimitiveType = D3DPT_TRIANGLESTRIP;
1113 mPrimitiveCount = count - 2;
1114 break;
1115 case GL_TRIANGLE_FAN:
1116 mPrimitiveType = D3DPT_TRIANGLEFAN;
1117 mPrimitiveCount = count - 2;
1118 break;
1119 default:
1120 return error(GL_INVALID_ENUM, false);
1121 }
1122
1123 return mPrimitiveCount > 0;
1124}
1125
daniel@transgaming.come4e1a332012-12-20 20:52:09 +00001126
1127gl::Renderbuffer *Renderer9::getNullColorbuffer(gl::Renderbuffer *depthbuffer)
1128{
1129 if (!depthbuffer)
1130 {
1131 ERR("Unexpected null depthbuffer for depth-only FBO.");
1132 return NULL;
1133 }
1134
1135 GLsizei width = depthbuffer->getWidth();
1136 GLsizei height = depthbuffer->getHeight();
1137
1138 // search cached nullcolorbuffers
1139 for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1140 {
1141 if (mNullColorbufferCache[i].buffer != NULL &&
1142 mNullColorbufferCache[i].width == width &&
1143 mNullColorbufferCache[i].height == height)
1144 {
1145 mNullColorbufferCache[i].lruCount = ++mMaxNullColorbufferLRU;
1146 return mNullColorbufferCache[i].buffer;
1147 }
1148 }
1149
1150 gl::Renderbuffer *nullbuffer = new gl::Renderbuffer(this, 0, new gl::Colorbuffer(this, width, height, GL_NONE, 0));
1151
1152 // add nullbuffer to the cache
1153 NullColorbufferCacheEntry *oldest = &mNullColorbufferCache[0];
1154 for (int i = 1; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1155 {
1156 if (mNullColorbufferCache[i].lruCount < oldest->lruCount)
1157 {
1158 oldest = &mNullColorbufferCache[i];
1159 }
1160 }
1161
1162 delete oldest->buffer;
1163 oldest->buffer = nullbuffer;
1164 oldest->lruCount = ++mMaxNullColorbufferLRU;
1165 oldest->width = width;
1166 oldest->height = height;
1167
1168 return nullbuffer;
1169}
1170
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001171bool Renderer9::applyRenderTarget(gl::Framebuffer *framebuffer)
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001172{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001173 // if there is no color attachment we must synthesize a NULL colorattachment
1174 // to keep the D3D runtime happy. This should only be possible if depth texturing.
1175 gl::Renderbuffer *renderbufferObject = NULL;
1176 if (framebuffer->getColorbufferType() != GL_NONE)
1177 {
1178 renderbufferObject = framebuffer->getColorbuffer();
1179 }
1180 else
1181 {
daniel@transgaming.come4e1a332012-12-20 20:52:09 +00001182 renderbufferObject = getNullColorbuffer(framebuffer->getDepthbuffer());
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001183 }
1184 if (!renderbufferObject)
1185 {
1186 ERR("unable to locate renderbuffer for FBO.");
1187 return false;
1188 }
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001189
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001190 bool renderTargetChanged = false;
1191 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1192 if (renderTargetSerial != mAppliedRenderTargetSerial)
1193 {
1194 // Apply the render target on the device
1195 IDirect3DSurface9 *renderTargetSurface = NULL;
1196
1197 RenderTarget *renderTarget = renderbufferObject->getRenderTarget();
1198 if (renderTarget)
1199 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001200 renderTargetSurface = RenderTarget9::makeRenderTarget9(renderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001201 }
1202
1203 if (!renderTargetSurface)
1204 {
1205 ERR("render target pointer unexpectedly null.");
1206 return false; // Context must be lost
1207 }
1208
1209 mDevice->SetRenderTarget(0, renderTargetSurface);
1210 renderTargetSurface->Release();
1211
1212 mAppliedRenderTargetSerial = renderTargetSerial;
1213 renderTargetChanged = true;
1214 }
1215
1216 gl::Renderbuffer *depthStencil = NULL;
1217 unsigned int depthbufferSerial = 0;
1218 unsigned int stencilbufferSerial = 0;
1219 if (framebuffer->getDepthbufferType() != GL_NONE)
1220 {
1221 depthStencil = framebuffer->getDepthbuffer();
1222 if (!depthStencil)
1223 {
1224 ERR("Depth stencil pointer unexpectedly null.");
1225 return false;
1226 }
1227
1228 depthbufferSerial = depthStencil->getSerial();
1229 }
1230 else if (framebuffer->getStencilbufferType() != GL_NONE)
1231 {
1232 depthStencil = framebuffer->getStencilbuffer();
1233 if (!depthStencil)
1234 {
1235 ERR("Depth stencil pointer unexpectedly null.");
1236 return false;
1237 }
1238
1239 stencilbufferSerial = depthStencil->getSerial();
1240 }
1241
1242 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1243 stencilbufferSerial != mAppliedStencilbufferSerial ||
1244 !mDepthStencilInitialized)
1245 {
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001246 unsigned int depthSize = 0;
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001247 unsigned int stencilSize = 0;
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001248
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001249 // Apply the depth stencil on the device
1250 if (depthStencil)
1251 {
1252 IDirect3DSurface9 *depthStencilSurface = NULL;
1253 RenderTarget *depthStencilRenderTarget = depthStencil->getDepthStencil();
1254
1255 if (depthStencilRenderTarget)
1256 {
daniel@transgaming.com965bcd22012-11-28 20:54:14 +00001257 depthStencilSurface = RenderTarget9::makeRenderTarget9(depthStencilRenderTarget)->getSurface();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001258 }
1259
1260 if (!depthStencilSurface)
1261 {
1262 ERR("depth stencil pointer unexpectedly null.");
1263 return false; // Context must be lost
1264 }
1265
1266 mDevice->SetDepthStencilSurface(depthStencilSurface);
1267 depthStencilSurface->Release();
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001268
1269 depthSize = depthStencil->getDepthSize();
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001270 stencilSize = depthStencil->getStencilSize();
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001271 }
1272 else
1273 {
1274 mDevice->SetDepthStencilSurface(NULL);
1275 }
1276
daniel@transgaming.com237bc7e2012-11-28 21:01:06 +00001277 if (!mDepthStencilInitialized || depthSize != mCurDepthSize)
1278 {
1279 mCurDepthSize = depthSize;
1280 mForceSetRasterState = true;
1281 }
1282
daniel@transgaming.com3a0ef482012-11-28 21:01:20 +00001283 if (!mDepthStencilInitialized || stencilSize != mCurStencilSize)
1284 {
1285 mCurStencilSize = stencilSize;
1286 mForceSetDepthStencilState = true;
1287 }
1288
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001289 mAppliedDepthbufferSerial = depthbufferSerial;
1290 mAppliedStencilbufferSerial = stencilbufferSerial;
1291 mDepthStencilInitialized = true;
1292 }
1293
1294 if (renderTargetChanged || !mRenderTargetDescInitialized)
1295 {
1296 mForceSetScissor = true;
1297 mForceSetViewport = true;
1298
1299 mRenderTargetDesc.width = renderbufferObject->getWidth();
1300 mRenderTargetDesc.height = renderbufferObject->getHeight();
1301 mRenderTargetDesc.format = renderbufferObject->getActualFormat();
1302 mRenderTargetDescInitialized = true;
1303 }
daniel@transgaming.comae39ee22012-11-28 19:42:02 +00001304
1305 return true;
daniel@transgaming.com493d4f82012-11-28 19:35:45 +00001306}
daniel@transgaming.coma734f272012-10-31 18:07:48 +00001307
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001308GLenum Renderer9::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances)
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001309{
daniel@transgaming.com31240482012-11-28 21:06:41 +00001310 TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001311 GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
1312 if (err != GL_NO_ERROR)
1313 {
1314 return err;
1315 }
1316
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001317 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, &mRepeatDraw);
1318}
1319
1320// Applies the indices and element array bindings to the Direct3D 9 device
daniel@transgaming.com31240482012-11-28 21:06:41 +00001321GLenum Renderer9::applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001322{
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001323 GLenum err = mIndexDataManager->prepareIndexData(type, count, elementArrayBuffer, indices, indexInfo);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001324
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001325 if (err == GL_NO_ERROR)
1326 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001327 if (indexInfo->serial != mAppliedIBSerial)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001328 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001329 IndexBuffer9* indexBuffer = IndexBuffer9::makeIndexBuffer9(indexInfo->indexBuffer);
1330
1331 mDevice->SetIndices(indexBuffer->getBuffer());
1332 mAppliedIBSerial = indexInfo->serial;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001333 }
1334 }
1335
1336 return err;
1337}
1338
1339void Renderer9::drawArrays(GLenum mode, GLsizei count, GLsizei instances)
1340{
1341 startScene();
1342
1343 if (mode == GL_LINE_LOOP)
1344 {
1345 drawLineLoop(count, GL_NONE, NULL, 0, NULL);
1346 }
1347 else if (instances > 0)
1348 {
daniel@transgaming.com50cc7252012-12-20 21:09:23 +00001349 StaticIndexBufferInterface *countingIB = mIndexDataManager->getCountingIndices(count);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001350 if (countingIB)
1351 {
1352 if (mAppliedIBSerial != countingIB->getSerial())
1353 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001354 IndexBuffer9 *indexBuffer = IndexBuffer9::makeIndexBuffer9(countingIB->getIndexBuffer());
1355
1356 mDevice->SetIndices(indexBuffer->getBuffer());
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001357 mAppliedIBSerial = countingIB->getSerial();
1358 }
1359
1360 for (int i = 0; i < mRepeatDraw; i++)
1361 {
1362 mDevice->DrawIndexedPrimitive(mPrimitiveType, 0, 0, count, 0, mPrimitiveCount);
1363 }
1364 }
1365 else
1366 {
1367 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
1368 return error(GL_OUT_OF_MEMORY);
1369 }
1370 }
1371 else // Regular case
1372 {
1373 mDevice->DrawPrimitive(mPrimitiveType, 0, mPrimitiveCount);
1374 }
1375}
1376
daniel@transgaming.com31240482012-11-28 21:06:41 +00001377void 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 +00001378{
1379 startScene();
1380
1381 if (mode == GL_LINE_LOOP)
1382 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001383 drawLineLoop(count, type, indices, indexInfo.minIndex, elementArrayBuffer);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001384 }
1385 else
1386 {
1387 for (int i = 0; i < mRepeatDraw; i++)
1388 {
daniel@transgaming.com97400dd2012-11-28 20:57:00 +00001389 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
1390 mDevice->DrawIndexedPrimitive(mPrimitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, mPrimitiveCount);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001391 }
1392 }
1393}
1394
1395void Renderer9::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer)
1396{
1397 // Get the raw indices for an indexed draw
1398 if (type != GL_NONE && elementArrayBuffer)
1399 {
1400 gl::Buffer *indexBuffer = elementArrayBuffer;
1401 intptr_t offset = reinterpret_cast<intptr_t>(indices);
1402 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
1403 }
1404
1405 UINT startIndex = 0;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001406
1407 if (get32BitIndexSupport())
1408 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001409 if (!mLineLoopIB)
1410 {
1411 mLineLoopIB = new StreamingIndexBufferInterface(this);
1412 if (!mLineLoopIB->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_INT))
1413 {
1414 delete mLineLoopIB;
1415 mLineLoopIB = NULL;
1416
1417 ERR("Could not create a 32-bit looping index buffer for GL_LINE_LOOP.");
1418 return error(GL_OUT_OF_MEMORY);
1419 }
1420 }
1421
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001422 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001423 if (!mLineLoopIB->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_INT))
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001424 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001425 ERR("Could not reserve enough space in looping index buffer for GL_LINE_LOOP.");
1426 return error(GL_OUT_OF_MEMORY);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001427 }
1428
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001429 void* mappedMemory = NULL;
1430 int offset = mLineLoopIB->mapBuffer(spaceNeeded, &mappedMemory);
1431 if (offset == -1 || mappedMemory == NULL)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001432 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001433 ERR("Could not map index buffer for GL_LINE_LOOP.");
1434 return error(GL_OUT_OF_MEMORY);
1435 }
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001436
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001437 startIndex = static_cast<UINT>(offset) / 4;
1438 unsigned int *data = reinterpret_cast<unsigned int*>(mappedMemory);
1439
1440 switch (type)
1441 {
1442 case GL_NONE: // Non-indexed draw
1443 for (int i = 0; i < count; i++)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001444 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001445 data[i] = i;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001446 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001447 data[count] = 0;
1448 break;
1449 case GL_UNSIGNED_BYTE:
1450 for (int i = 0; i < count; i++)
1451 {
1452 data[i] = static_cast<const GLubyte*>(indices)[i];
1453 }
1454 data[count] = static_cast<const GLubyte*>(indices)[0];
1455 break;
1456 case GL_UNSIGNED_SHORT:
1457 for (int i = 0; i < count; i++)
1458 {
1459 data[i] = static_cast<const GLushort*>(indices)[i];
1460 }
1461 data[count] = static_cast<const GLushort*>(indices)[0];
1462 break;
1463 case GL_UNSIGNED_INT:
1464 for (int i = 0; i < count; i++)
1465 {
1466 data[i] = static_cast<const GLuint*>(indices)[i];
1467 }
1468 data[count] = static_cast<const GLuint*>(indices)[0];
1469 break;
1470 default: UNREACHABLE();
1471 }
1472
1473 if (!mLineLoopIB->unmapBuffer())
1474 {
1475 ERR("Could not unmap index buffer for GL_LINE_LOOP.");
1476 return error(GL_OUT_OF_MEMORY);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001477 }
1478 }
1479 else
1480 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001481 if (!mLineLoopIB)
1482 {
1483 mLineLoopIB = new StreamingIndexBufferInterface(this);
1484 if (!mLineLoopIB->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_SHORT))
1485 {
1486 delete mLineLoopIB;
1487 mLineLoopIB = NULL;
1488
1489 ERR("Could not create a 16-bit looping index buffer for GL_LINE_LOOP.");
1490 return error(GL_OUT_OF_MEMORY);
1491 }
1492 }
1493
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001494 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001495 if (!mLineLoopIB->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_SHORT))
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001496 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001497 ERR("Could not reserve enough space in looping index buffer for GL_LINE_LOOP.");
1498 return error(GL_OUT_OF_MEMORY);
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001499 }
1500
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001501 void* mappedMemory = NULL;
1502 int offset = mLineLoopIB->mapBuffer(spaceNeeded, &mappedMemory);
1503 if (offset == -1 || mappedMemory == NULL)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001504 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001505 ERR("Could not map index buffer for GL_LINE_LOOP.");
1506 return error(GL_OUT_OF_MEMORY);
1507 }
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001508
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001509 startIndex = static_cast<UINT>(offset) / 2;
1510 unsigned short *data = reinterpret_cast<unsigned short*>(mappedMemory);
1511
1512 switch (type)
1513 {
1514 case GL_NONE: // Non-indexed draw
1515 for (int i = 0; i < count; i++)
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001516 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001517 data[i] = i;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001518 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001519 data[count] = 0;
1520 break;
1521 case GL_UNSIGNED_BYTE:
1522 for (int i = 0; i < count; i++)
1523 {
1524 data[i] = static_cast<const GLubyte*>(indices)[i];
1525 }
1526 data[count] = static_cast<const GLubyte*>(indices)[0];
1527 break;
1528 case GL_UNSIGNED_SHORT:
1529 for (int i = 0; i < count; i++)
1530 {
1531 data[i] = static_cast<const GLushort*>(indices)[i];
1532 }
1533 data[count] = static_cast<const GLushort*>(indices)[0];
1534 break;
1535 case GL_UNSIGNED_INT:
1536 for (int i = 0; i < count; i++)
1537 {
1538 data[i] = static_cast<const GLuint*>(indices)[i];
1539 }
1540 data[count] = static_cast<const GLuint*>(indices)[0];
1541 break;
1542 default: UNREACHABLE();
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001543 }
1544
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001545 if (!mLineLoopIB->unmapBuffer())
1546 {
1547 ERR("Could not unmap index buffer for GL_LINE_LOOP.");
1548 return error(GL_OUT_OF_MEMORY);
1549 }
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001550 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001551
1552 if (mAppliedIBSerial != mLineLoopIB->getSerial())
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001553 {
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001554 IndexBuffer9 *indexBuffer = IndexBuffer9::makeIndexBuffer9(mLineLoopIB->getIndexBuffer());
1555
1556 mDevice->SetIndices(indexBuffer->getBuffer());
1557 mAppliedIBSerial = mLineLoopIB->getSerial();
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001558 }
daniel@transgaming.com1e3a8042012-12-20 21:09:55 +00001559
1560 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001561}
1562
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001563void Renderer9::applyShaders(gl::ProgramBinary *programBinary)
1564{
daniel@transgaming.come4991412012-12-20 20:55:34 +00001565 unsigned int programBinarySerial = programBinary->getSerial();
1566 if (programBinarySerial != mAppliedProgramBinarySerial)
1567 {
1568 ShaderExecutable *vertexExe = programBinary->getVertexExecutable();
1569 ShaderExecutable *pixelExe = programBinary->getPixelExecutable();
daniel@transgaming.com95892412012-11-28 20:59:09 +00001570
daniel@transgaming.come4991412012-12-20 20:55:34 +00001571 IDirect3DVertexShader9 *vertexShader = NULL;
1572 if (vertexExe) vertexShader = ShaderExecutable9::makeShaderExecutable9(vertexExe)->getVertexShader();
daniel@transgaming.com95892412012-11-28 20:59:09 +00001573
daniel@transgaming.come4991412012-12-20 20:55:34 +00001574 IDirect3DPixelShader9 *pixelShader = NULL;
1575 if (pixelExe) pixelShader = ShaderExecutable9::makeShaderExecutable9(pixelExe)->getPixelShader();
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001576
daniel@transgaming.come4991412012-12-20 20:55:34 +00001577 mDevice->SetPixelShader(pixelShader);
1578 mDevice->SetVertexShader(vertexShader);
1579 programBinary->dirtyAllUniforms();
1580
1581 mAppliedProgramBinarySerial = programBinarySerial;
1582 }
daniel@transgaming.com5fbf1772012-11-28 20:54:43 +00001583}
1584
daniel@transgaming.coma390e1e2013-01-11 04:09:39 +00001585void Renderer9::applyUniforms(const gl::UniformArray *uniformArray, const dx_VertexConstants &vertexConstants, const dx_PixelConstants &pixelConstants)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001586{
1587 for (std::vector<gl::Uniform*>::const_iterator ub = uniformArray->begin(), ue = uniformArray->end(); ub != ue; ++ub)
1588 {
1589 gl::Uniform *targetUniform = *ub;
1590
1591 if (targetUniform->dirty)
1592 {
daniel@transgaming.come6d12e92012-12-20 21:12:47 +00001593 int count = targetUniform->elementCount();
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001594 GLfloat *f = (GLfloat*)targetUniform->data;
1595 GLint *i = (GLint*)targetUniform->data;
1596 GLboolean *b = (GLboolean*)targetUniform->data;
1597
1598 switch (targetUniform->type)
1599 {
1600 case GL_SAMPLER_2D:
1601 case GL_SAMPLER_CUBE:
1602 break;
daniel@transgaming.come6d12e92012-12-20 21:12:47 +00001603 case GL_BOOL: applyUniformnbv(targetUniform, count, 1, b); break;
1604 case GL_BOOL_VEC2: applyUniformnbv(targetUniform, count, 2, b); break;
1605 case GL_BOOL_VEC3: applyUniformnbv(targetUniform, count, 3, b); break;
1606 case GL_BOOL_VEC4: applyUniformnbv(targetUniform, count, 4, b); break;
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001607 case GL_FLOAT:
1608 case GL_FLOAT_VEC2:
1609 case GL_FLOAT_VEC3:
1610 case GL_FLOAT_VEC4:
1611 case GL_FLOAT_MAT2:
1612 case GL_FLOAT_MAT3:
daniel@transgaming.come6d12e92012-12-20 21:12:47 +00001613 case GL_FLOAT_MAT4: applyUniformnfv(targetUniform, f); break;
1614 case GL_INT: applyUniform1iv(targetUniform, count, i); break;
1615 case GL_INT_VEC2: applyUniform2iv(targetUniform, count, i); break;
1616 case GL_INT_VEC3: applyUniform3iv(targetUniform, count, i); break;
1617 case GL_INT_VEC4: applyUniform4iv(targetUniform, count, i); break;
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001618 default:
1619 UNREACHABLE();
1620 }
1621
1622 targetUniform->dirty = false;
1623 }
1624 }
daniel@transgaming.coma390e1e2013-01-11 04:09:39 +00001625
1626 // Driver uniforms
1627 mDevice->SetVertexShaderConstantF(0, (float*)&vertexConstants, sizeof(dx_VertexConstants) / sizeof(float[4]));
1628 mDevice->SetPixelShaderConstantF(0, (float*)&pixelConstants, sizeof(dx_PixelConstants) / sizeof(float[4]));
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001629}
1630
1631void Renderer9::applyUniformnbv(gl::Uniform *targetUniform, GLsizei count, int width, const GLboolean *v)
1632{
1633 float vector[gl::D3D9_MAX_FLOAT_CONSTANTS * 4];
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001634
daniel@transgaming.come76b64b2013-01-11 04:10:08 +00001635 if (targetUniform->psRegisterIndex >= 0 || targetUniform->vsRegisterIndex >= 0)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001636 {
1637 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1638 for (int i = 0; i < count; i++)
1639 {
1640 for (int j = 0; j < 4; j++)
1641 {
1642 if (j < width)
1643 {
1644 vector[i * 4 + j] = (v[i * width + j] == GL_FALSE) ? 0.0f : 1.0f;
1645 }
1646 else
1647 {
1648 vector[i * 4 + j] = 0.0f;
1649 }
1650 }
1651 }
1652 }
1653
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001654 applyUniformnfv(targetUniform, vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001655}
1656
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001657void Renderer9::applyUniformnfv(gl::Uniform *targetUniform, const GLfloat *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001658{
daniel@transgaming.come76b64b2013-01-11 04:10:08 +00001659 if (targetUniform->psRegisterIndex >= 0)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001660 {
daniel@transgaming.come76b64b2013-01-11 04:10:08 +00001661 mDevice->SetPixelShaderConstantF(targetUniform->psRegisterIndex, v, targetUniform->registerCount);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001662 }
1663
daniel@transgaming.come76b64b2013-01-11 04:10:08 +00001664 if (targetUniform->vsRegisterIndex >= 0)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001665 {
daniel@transgaming.come76b64b2013-01-11 04:10:08 +00001666 mDevice->SetVertexShaderConstantF(targetUniform->vsRegisterIndex, v, targetUniform->registerCount);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001667 }
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001668}
1669
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001670void Renderer9::applyUniform1iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001671{
1672 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1673 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1674
1675 for (int i = 0; i < count; i++)
1676 {
1677 vector[i] = gl::Vector4((float)v[i], 0, 0, 0);
1678 }
1679
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001680 applyUniformnfv(targetUniform, (const GLfloat*)vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001681}
1682
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001683void Renderer9::applyUniform2iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001684{
1685 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1686 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1687
1688 for (int i = 0; i < count; i++)
1689 {
1690 vector[i] = gl::Vector4((float)v[0], (float)v[1], 0, 0);
1691
1692 v += 2;
1693 }
1694
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001695 applyUniformnfv(targetUniform, (const GLfloat*)vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001696}
1697
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001698void Renderer9::applyUniform3iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001699{
1700 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1701 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1702
1703 for (int i = 0; i < count; i++)
1704 {
1705 vector[i] = gl::Vector4((float)v[0], (float)v[1], (float)v[2], 0);
1706
1707 v += 3;
1708 }
1709
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001710 applyUniformnfv(targetUniform, (const GLfloat*)vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001711}
1712
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001713void Renderer9::applyUniform4iv(gl::Uniform *targetUniform, GLsizei count, const GLint *v)
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001714{
1715 ASSERT(count <= gl::D3D9_MAX_FLOAT_CONSTANTS);
1716 gl::Vector4 vector[gl::D3D9_MAX_FLOAT_CONSTANTS];
1717
1718 for (int i = 0; i < count; i++)
1719 {
1720 vector[i] = gl::Vector4((float)v[0], (float)v[1], (float)v[2], (float)v[3]);
1721
1722 v += 4;
1723 }
1724
daniel@transgaming.comf9561862012-12-20 21:12:07 +00001725 applyUniformnfv(targetUniform, (const GLfloat*)vector);
daniel@transgaming.comb6e55102012-12-20 21:08:14 +00001726}
1727
daniel@transgaming.com084a2572012-11-28 20:55:17 +00001728void Renderer9::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001729{
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001730 D3DCOLOR color = D3DCOLOR_ARGB(gl::unorm<8>(clearParams.colorClearValue.alpha),
1731 gl::unorm<8>(clearParams.colorClearValue.red),
1732 gl::unorm<8>(clearParams.colorClearValue.green),
1733 gl::unorm<8>(clearParams.colorClearValue.blue));
1734 float depth = gl::clamp01(clearParams.depthClearValue);
1735 int stencil = clearParams.stencilClearValue & 0x000000FF;
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001736
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001737 unsigned int stencilUnmasked = 0x0;
1738 if ((clearParams.mask & GL_STENCIL_BUFFER_BIT) && frameBuffer->hasStencil())
1739 {
1740 unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
1741 stencilUnmasked = (0x1 << stencilSize) - 1;
1742 }
1743
1744 bool alphaUnmasked = (gl::GetAlphaSize(mRenderTargetDesc.format) == 0) || clearParams.colorMaskAlpha;
1745
1746 const bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
1747 (clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
1748 const bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
1749 !(clearParams.colorMaskRed && clearParams.colorMaskGreen &&
1750 clearParams.colorMaskBlue && alphaUnmasked);
1751
1752 if (needMaskedColorClear || needMaskedStencilClear)
1753 {
1754 // State which is altered in all paths from this point to the clear call is saved.
1755 // State which is altered in only some paths will be flagged dirty in the case that
1756 // that path is taken.
1757 HRESULT hr;
1758 if (mMaskedClearSavedState == NULL)
1759 {
1760 hr = mDevice->BeginStateBlock();
1761 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1762
1763 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1764 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1765 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1766 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1767 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1768 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1769 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1770 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1771 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1772 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1773 mDevice->SetPixelShader(NULL);
1774 mDevice->SetVertexShader(NULL);
1775 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
1776 mDevice->SetStreamSource(0, NULL, 0, 0);
1777 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1778 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1779 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1780 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1781 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1782 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1783 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1784
1785 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1786 {
1787 mDevice->SetStreamSourceFreq(i, 1);
1788 }
1789
1790 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
1791 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
1792 }
1793
1794 ASSERT(mMaskedClearSavedState != NULL);
1795
1796 if (mMaskedClearSavedState != NULL)
1797 {
1798 hr = mMaskedClearSavedState->Capture();
1799 ASSERT(SUCCEEDED(hr));
1800 }
1801
1802 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
1803 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
1804 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
1805 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
1806 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
1807 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
1808 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
1809 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
1810
1811 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1812 {
1813 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE,
1814 gl_d3d9::ConvertColorMask(clearParams.colorMaskRed,
1815 clearParams.colorMaskGreen,
1816 clearParams.colorMaskBlue,
1817 clearParams.colorMaskAlpha));
1818 }
1819 else
1820 {
1821 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
1822 }
1823
1824 if (stencilUnmasked != 0x0 && (clearParams.mask & GL_STENCIL_BUFFER_BIT))
1825 {
1826 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
1827 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
1828 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
1829 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
1830 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, clearParams.stencilWriteMask);
1831 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
1832 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
1833 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
1834 }
1835 else
1836 {
1837 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
1838 }
1839
1840 mDevice->SetPixelShader(NULL);
1841 mDevice->SetVertexShader(NULL);
1842 mDevice->SetFVF(D3DFVF_XYZRHW);
1843 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
1844 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
1845 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
1846 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
1847 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
1848 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
1849 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
1850
1851 for(int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
1852 {
1853 mDevice->SetStreamSourceFreq(i, 1);
1854 }
1855
1856 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
1857 quad[0][0] = -0.5f;
1858 quad[0][1] = mRenderTargetDesc.height - 0.5f;
1859 quad[0][2] = 0.0f;
1860 quad[0][3] = 1.0f;
1861
1862 quad[1][0] = mRenderTargetDesc.width - 0.5f;
1863 quad[1][1] = mRenderTargetDesc.height - 0.5f;
1864 quad[1][2] = 0.0f;
1865 quad[1][3] = 1.0f;
1866
1867 quad[2][0] = -0.5f;
1868 quad[2][1] = -0.5f;
1869 quad[2][2] = 0.0f;
1870 quad[2][3] = 1.0f;
1871
1872 quad[3][0] = mRenderTargetDesc.width - 0.5f;
1873 quad[3][1] = -0.5f;
1874 quad[3][2] = 0.0f;
1875 quad[3][3] = 1.0f;
1876
1877 startScene();
1878 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
1879
1880 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1881 {
1882 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
1883 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
1884 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
1885 }
1886
1887 if (mMaskedClearSavedState != NULL)
1888 {
1889 mMaskedClearSavedState->Apply();
1890 }
1891 }
1892 else if (clearParams.mask)
1893 {
1894 DWORD dxClearFlags = 0;
1895 if (clearParams.mask & GL_COLOR_BUFFER_BIT)
1896 {
1897 dxClearFlags |= D3DCLEAR_TARGET;
1898 }
1899 if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
1900 {
1901 dxClearFlags |= D3DCLEAR_ZBUFFER;
1902 }
1903 if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
1904 {
1905 dxClearFlags |= D3DCLEAR_STENCIL;
1906 }
1907
1908 mDevice->Clear(0, NULL, dxClearFlags, color, depth, stencil);
1909 }
daniel@transgaming.comd084c622012-11-28 19:36:05 +00001910}
1911
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001912void Renderer9::markAllStateDirty()
1913{
daniel@transgaming.com220e79a2012-11-28 19:42:11 +00001914 mAppliedRenderTargetSerial = 0;
1915 mAppliedDepthbufferSerial = 0;
1916 mAppliedStencilbufferSerial = 0;
1917 mDepthStencilInitialized = false;
1918 mRenderTargetDescInitialized = false;
1919
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001920 mForceSetDepthStencilState = true;
1921 mForceSetRasterState = true;
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001922 mForceSetScissor = true;
1923 mForceSetViewport = true;
daniel@transgaming.com9a067372012-12-20 20:55:24 +00001924 mForceSetBlendState = true;
1925
daniel@transgaming.come33c8bf2013-01-11 04:11:33 +00001926 for (unsigned int i = 0; i < gl::MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF; i++)
1927 {
1928 mForceSetVertexSamplerStates[i] = true;
1929 mCurVertexTextureSerials[i] = 0;
1930 }
1931 for (unsigned int i = 0; i < gl::MAX_TEXTURE_IMAGE_UNITS; i++)
1932 {
1933 mForceSetPixelSamplerStates[i] = true;
1934 mCurPixelTextureSerials[i] = 0;
1935 }
1936
daniel@transgaming.com9a067372012-12-20 20:55:24 +00001937 mAppliedIBSerial = 0;
daniel@transgaming.come4991412012-12-20 20:55:34 +00001938 mAppliedProgramBinarySerial = 0;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001939
1940 mVertexDeclarationCache.markStateDirty();
daniel@transgaming.comc43a6052012-11-28 19:41:51 +00001941}
1942
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001943void Renderer9::releaseDeviceResources()
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001944{
1945 while (!mEventQueryPool.empty())
1946 {
1947 mEventQueryPool.back()->Release();
1948 mEventQueryPool.pop_back();
1949 }
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001950
daniel@transgaming.com0393e5b2012-11-28 20:55:33 +00001951 if (mMaskedClearSavedState)
1952 {
1953 mMaskedClearSavedState->Release();
1954 mMaskedClearSavedState = NULL;
1955 }
1956
daniel@transgaming.come4733d72012-10-31 18:07:01 +00001957 mVertexShaderCache.clear();
1958 mPixelShaderCache.clear();
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001959
daniel@transgaming.come569fc52012-11-28 20:56:02 +00001960 delete mBlit;
1961 mBlit = NULL;
1962
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00001963 delete mVertexDataManager;
1964 mVertexDataManager = NULL;
daniel@transgaming.com91207b72012-11-28 20:56:43 +00001965
1966 delete mIndexDataManager;
1967 mIndexDataManager = NULL;
1968
1969 delete mLineLoopIB;
1970 mLineLoopIB = NULL;
daniel@transgaming.come4e1a332012-12-20 20:52:09 +00001971
1972 for (int i = 0; i < NUM_NULL_COLORBUFFER_CACHE_ENTRIES; i++)
1973 {
1974 delete mNullColorbufferCache[i].buffer;
1975 mNullColorbufferCache[i].buffer = NULL;
1976 }
1977
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001978}
1979
1980
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001981void Renderer9::markDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001982{
1983 mDeviceLost = true;
1984}
1985
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001986bool Renderer9::isDeviceLost()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001987{
1988 return mDeviceLost;
1989}
1990
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00001991// set notify to true to broadcast a message to all contexts of the device loss
daniel@transgaming.com2507f412012-10-31 18:46:48 +00001992bool Renderer9::testDeviceLost(bool notify)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00001993{
1994 bool isLost = false;
1995
1996 if (mDeviceEx)
1997 {
1998 isLost = FAILED(mDeviceEx->CheckDeviceState(NULL));
1999 }
2000 else if (mDevice)
2001 {
2002 isLost = FAILED(mDevice->TestCooperativeLevel());
2003 }
2004 else
2005 {
2006 // No device yet, so no reset required
2007 }
2008
2009 if (isLost)
2010 {
2011 // ensure we note the device loss --
2012 // we'll probably get this done again by markDeviceLost
2013 // but best to remember it!
2014 // Note that we don't want to clear the device loss status here
2015 // -- this needs to be done by resetDevice
2016 mDeviceLost = true;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00002017 if (notify)
2018 {
2019 mDisplay->notifyDeviceLost();
2020 }
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002021 }
2022
2023 return isLost;
2024}
2025
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002026bool Renderer9::testDeviceResettable()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002027{
2028 HRESULT status = D3D_OK;
2029
2030 if (mDeviceEx)
2031 {
2032 status = mDeviceEx->CheckDeviceState(NULL);
2033 }
2034 else if (mDevice)
2035 {
2036 status = mDevice->TestCooperativeLevel();
2037 }
2038
2039 switch (status)
2040 {
2041 case D3DERR_DEVICENOTRESET:
2042 case D3DERR_DEVICEHUNG:
2043 return true;
2044 default:
2045 return false;
2046 }
2047}
2048
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002049bool Renderer9::resetDevice()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002050{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00002051 releaseDeviceResources();
2052
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002053 D3DPRESENT_PARAMETERS presentParameters = getDefaultPresentParameters();
2054
2055 HRESULT result = D3D_OK;
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00002056 bool lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002057 int attempts = 3;
2058
2059 while (lost && attempts > 0)
2060 {
2061 if (mDeviceEx)
2062 {
2063 Sleep(500); // Give the graphics driver some CPU time
2064 result = mDeviceEx->ResetEx(&presentParameters, NULL);
2065 }
2066 else
2067 {
2068 result = mDevice->TestCooperativeLevel();
2069 while (result == D3DERR_DEVICELOST)
2070 {
2071 Sleep(100); // Give the graphics driver some CPU time
2072 result = mDevice->TestCooperativeLevel();
2073 }
2074
2075 if (result == D3DERR_DEVICENOTRESET)
2076 {
2077 result = mDevice->Reset(&presentParameters);
2078 }
2079 }
2080
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00002081 lost = testDeviceLost(false);
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002082 attempts --;
2083 }
2084
2085 if (FAILED(result))
2086 {
2087 ERR("Reset/ResetEx failed multiple times: 0x%08X", result);
2088 return false;
2089 }
2090
2091 // reset device defaults
2092 initializeDevice();
2093 mDeviceLost = false;
2094
2095 return true;
2096}
2097
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002098DWORD Renderer9::getAdapterVendor() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002099{
2100 return mAdapterIdentifier.VendorId;
2101}
2102
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002103const char *Renderer9::getAdapterDescription() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002104{
2105 return mAdapterIdentifier.Description;
2106}
2107
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002108GUID Renderer9::getAdapterIdentifier() const
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002109{
2110 return mAdapterIdentifier.DeviceIdentifier;
2111}
2112
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002113void Renderer9::getMultiSampleSupport(D3DFORMAT format, bool *multiSampleArray)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002114{
2115 for (int multiSampleIndex = 0; multiSampleIndex <= D3DMULTISAMPLE_16_SAMPLES; multiSampleIndex++)
2116 {
2117 HRESULT result = mD3d9->CheckDeviceMultiSampleType(mAdapter, mDeviceType, format,
2118 TRUE, (D3DMULTISAMPLE_TYPE)multiSampleIndex, NULL);
2119
2120 multiSampleArray[multiSampleIndex] = SUCCEEDED(result);
2121 }
2122}
2123
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002124bool Renderer9::getDXT1TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002125{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002126 return mDXT1TextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002127}
2128
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002129bool Renderer9::getDXT3TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002130{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002131 return mDXT3TextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002132}
2133
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002134bool Renderer9::getDXT5TextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002135{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002136 return mDXT5TextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002137}
2138
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002139bool Renderer9::getDepthTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002140{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002141 return mDepthTextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002142}
2143
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002144bool Renderer9::getFloat32TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002145{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002146 *filtering = mFloat32FilterSupport;
2147 *renderable = mFloat32RenderSupport;
2148 return mFloat32TextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002149}
2150
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002151bool Renderer9::getFloat16TextureSupport(bool *filtering, bool *renderable)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002152{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002153 *filtering = mFloat16FilterSupport;
2154 *renderable = mFloat16RenderSupport;
2155 return mFloat16TextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002156}
2157
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002158bool Renderer9::getLuminanceTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002159{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002160 return mLuminanceTextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002161}
2162
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002163bool Renderer9::getLuminanceAlphaTextureSupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002164{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002165 return mLuminanceAlphaTextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002166}
2167
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002168bool Renderer9::getTextureFilterAnisotropySupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002169{
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00002170 return mSupportsTextureFilterAnisotropy;
2171}
2172
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002173float Renderer9::getTextureMaxAnisotropy() const
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00002174{
2175 if (mSupportsTextureFilterAnisotropy)
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002176 {
2177 return mDeviceCaps.MaxAnisotropy;
2178 }
2179 return 1.0f;
2180}
2181
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002182bool Renderer9::getEventQuerySupport()
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002183{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002184 return mEventQuerySupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002185}
2186
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002187bool Renderer9::getVertexTextureSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002188{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002189 return mVertexTextureSupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002190}
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{
daniel@transgaming.com669c9952013-01-11 04:08:16 +00002199 return mOcclusionQuerySupport;
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002200}
2201
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002202bool Renderer9::getInstancingSupport() const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002203{
2204 return mDeviceCaps.PixelShaderVersion >= D3DPS_VERSION(3, 0);
2205}
2206
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002207bool Renderer9::getShareHandleSupport() const
daniel@transgaming.com313e3922012-10-31 17:52:39 +00002208{
2209 // PIX doesn't seem to support using share handles, so disable them.
2210 // D3D9_REPLACE
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00002211 return (mD3d9Ex != NULL) && !gl::perfActive();
daniel@transgaming.com313e3922012-10-31 17:52:39 +00002212}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002213
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00002214int Renderer9::getMajorShaderModel() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002215{
daniel@transgaming.com9549bea2012-11-28 20:57:23 +00002216 return D3DSHADER_VERSION_MAJOR(mDeviceCaps.PixelShaderVersion);
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002217}
2218
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002219float Renderer9::getMaxPointSize() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002220{
2221 return mDeviceCaps.MaxPointSize;
2222}
2223
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002224int Renderer9::getMaxTextureWidth() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002225{
2226 return (int)mDeviceCaps.MaxTextureWidth;
2227}
2228
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002229int Renderer9::getMaxTextureHeight() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002230{
2231 return (int)mDeviceCaps.MaxTextureHeight;
2232}
2233
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002234bool Renderer9::get32BitIndexSupport() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002235{
2236 return mDeviceCaps.MaxVertexIndex >= (1 << 16);
2237}
2238
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002239DWORD Renderer9::getCapsDeclTypes() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002240{
2241 return mDeviceCaps.DeclTypes;
2242}
2243
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002244int Renderer9::getMinSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002245{
2246 return mMinSwapInterval;
2247}
2248
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002249int Renderer9::getMaxSwapInterval() const
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +00002250{
2251 return mMaxSwapInterval;
2252}
2253
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002254int Renderer9::getMaxSupportedSamples() const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002255{
2256 return mMaxSupportedSamples;
2257}
2258
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002259int Renderer9::getNearestSupportedSamples(D3DFORMAT format, int requested) const
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002260{
2261 if (requested == 0)
2262 {
2263 return requested;
2264 }
2265
2266 std::map<D3DFORMAT, bool *>::const_iterator itr = mMultiSampleSupport.find(format);
2267 if (itr == mMultiSampleSupport.end())
2268 {
daniel@transgaming.com92955622012-10-31 18:38:41 +00002269 if (format == D3DFMT_UNKNOWN)
2270 return 0;
daniel@transgaming.comb7833982012-10-31 18:31:46 +00002271 return -1;
2272 }
2273
2274 for (int i = requested; i <= D3DMULTISAMPLE_16_SAMPLES; ++i)
2275 {
2276 if (itr->second[i] && i != D3DMULTISAMPLE_NONMASKABLE)
2277 {
2278 return i;
2279 }
2280 }
2281
2282 return -1;
2283}
2284
daniel@transgaming.coma9571682012-11-28 19:33:08 +00002285D3DFORMAT Renderer9::ConvertTextureInternalFormat(GLint internalformat)
2286{
2287 switch (internalformat)
2288 {
2289 case GL_DEPTH_COMPONENT16:
2290 case GL_DEPTH_COMPONENT32_OES:
2291 case GL_DEPTH24_STENCIL8_OES:
2292 return D3DFMT_INTZ;
2293 case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
2294 case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
2295 return D3DFMT_DXT1;
2296 case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
2297 return D3DFMT_DXT3;
2298 case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
2299 return D3DFMT_DXT5;
2300 case GL_RGBA32F_EXT:
2301 case GL_RGB32F_EXT:
2302 case GL_ALPHA32F_EXT:
2303 case GL_LUMINANCE32F_EXT:
2304 case GL_LUMINANCE_ALPHA32F_EXT:
2305 return D3DFMT_A32B32G32R32F;
2306 case GL_RGBA16F_EXT:
2307 case GL_RGB16F_EXT:
2308 case GL_ALPHA16F_EXT:
2309 case GL_LUMINANCE16F_EXT:
2310 case GL_LUMINANCE_ALPHA16F_EXT:
2311 return D3DFMT_A16B16G16R16F;
2312 case GL_LUMINANCE8_EXT:
2313 if (getLuminanceTextureSupport())
2314 {
2315 return D3DFMT_L8;
2316 }
2317 break;
2318 case GL_LUMINANCE8_ALPHA8_EXT:
2319 if (getLuminanceAlphaTextureSupport())
2320 {
2321 return D3DFMT_A8L8;
2322 }
2323 break;
2324 case GL_RGB8_OES:
2325 case GL_RGB565:
2326 return D3DFMT_X8R8G8B8;
2327 }
2328
2329 return D3DFMT_A8R8G8B8;
2330}
2331
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002332bool Renderer9::copyToRenderTarget(TextureStorageInterface2D *dest, TextureStorageInterface2D *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002333{
2334 bool result = false;
2335
2336 if (source && dest)
2337 {
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002338 TextureStorage9_2D *source9 = TextureStorage9_2D::makeTextureStorage9_2D(source->getStorageInstance());
2339 TextureStorage9_2D *dest9 = TextureStorage9_2D::makeTextureStorage9_2D(dest->getStorageInstance());
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002340
2341 int levels = source9->levelCount();
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002342 for (int i = 0; i < levels; ++i)
2343 {
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002344 IDirect3DSurface9 *srcSurf = source9->getSurfaceLevel(i, false);
2345 IDirect3DSurface9 *dstSurf = dest9->getSurfaceLevel(i, false);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002346
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002347 result = copyToRenderTarget(dstSurf, srcSurf, source9->isManaged());
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002348
2349 if (srcSurf) srcSurf->Release();
2350 if (dstSurf) dstSurf->Release();
2351
2352 if (!result)
2353 return false;
2354 }
2355 }
2356
2357 return result;
2358}
2359
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002360bool Renderer9::copyToRenderTarget(TextureStorageInterfaceCube *dest, TextureStorageInterfaceCube *source)
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002361{
2362 bool result = false;
2363
2364 if (source && dest)
2365 {
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002366 TextureStorage9_Cube *source9 = TextureStorage9_Cube::makeTextureStorage9_Cube(source->getStorageInstance());
2367 TextureStorage9_Cube *dest9 = TextureStorage9_Cube::makeTextureStorage9_Cube(dest->getStorageInstance());
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002368 int levels = source9->levelCount();
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002369 for (int f = 0; f < 6; f++)
2370 {
2371 for (int i = 0; i < levels; i++)
2372 {
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002373 IDirect3DSurface9 *srcSurf = source9->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, false);
2374 IDirect3DSurface9 *dstSurf = dest9->getCubeMapSurface(GL_TEXTURE_CUBE_MAP_POSITIVE_X + f, i, true);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002375
daniel@transgaming.com34da3972012-12-20 21:10:29 +00002376 result = copyToRenderTarget(dstSurf, srcSurf, source9->isManaged());
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002377
2378 if (srcSurf) srcSurf->Release();
2379 if (dstSurf) dstSurf->Release();
2380
2381 if (!result)
2382 return false;
2383 }
2384 }
2385 }
2386
2387 return result;
2388}
2389
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002390D3DPOOL Renderer9::getBufferPool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002391{
2392 if (mD3d9Ex != NULL)
2393 {
2394 return D3DPOOL_DEFAULT;
2395 }
2396 else
2397 {
2398 if (!(usage & D3DUSAGE_DYNAMIC))
2399 {
2400 return D3DPOOL_MANAGED;
2401 }
2402 }
2403
2404 return D3DPOOL_DEFAULT;
2405}
2406
daniel@transgaming.com38380882012-11-28 19:36:39 +00002407bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002408 GLint xoffset, GLint yoffset, TextureStorageInterface2D *storage, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002409{
2410 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, level);
2411}
2412
daniel@transgaming.com38380882012-11-28 19:36:39 +00002413bool Renderer9::copyImage(gl::Framebuffer *framebuffer, const RECT &sourceRect, GLenum destFormat,
daniel@transgaming.com87705f82012-12-20 21:10:45 +00002414 GLint xoffset, GLint yoffset, TextureStorageInterfaceCube *storage, GLenum target, GLint level)
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002415{
2416 return mBlit->copy(framebuffer, sourceRect, destFormat, xoffset, yoffset, storage, target, level);
2417}
2418
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002419bool Renderer9::blitRect(gl::Framebuffer *readFramebuffer, gl::Rectangle *readRect, gl::Framebuffer *drawFramebuffer, gl::Rectangle *drawRect,
2420 bool blitRenderTarget, bool blitDepthStencil)
2421{
2422 endScene();
2423
2424 if (blitRenderTarget)
2425 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002426 gl::Renderbuffer *readBuffer = readFramebuffer->getColorbuffer();
2427 gl::Renderbuffer *drawBuffer = drawFramebuffer->getColorbuffer();
2428 RenderTarget9 *readRenderTarget = NULL;
2429 RenderTarget9 *drawRenderTarget = NULL;
2430 IDirect3DSurface9* readSurface = NULL;
2431 IDirect3DSurface9* drawSurface = NULL;
2432
2433 if (readBuffer)
2434 {
2435 readRenderTarget = RenderTarget9::makeRenderTarget9(readBuffer->getRenderTarget());
2436 }
2437 if (drawBuffer)
2438 {
2439 drawRenderTarget = RenderTarget9::makeRenderTarget9(drawBuffer->getRenderTarget());
2440 }
2441
2442 if (readRenderTarget)
2443 {
2444 readSurface = readRenderTarget->getSurface();
2445 }
2446 if (drawRenderTarget)
2447 {
2448 drawSurface = drawRenderTarget->getSurface();
2449 }
2450
2451 if (!readSurface || !drawSurface)
2452 {
2453 ERR("Failed to retrieve the render target.");
2454 return error(GL_OUT_OF_MEMORY, false);
2455 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002456
2457 RECT srcRect, dstRect;
2458 RECT *srcRectPtr = NULL;
2459 RECT *dstRectPtr = NULL;
2460
2461 if (readRect)
2462 {
2463 srcRect.left = readRect->x;
2464 srcRect.right = readRect->x + readRect->width;
2465 srcRect.top = readRect->y;
2466 srcRect.bottom = readRect->y + readRect->height;
2467 srcRectPtr = &srcRect;
2468 }
2469
2470 if (drawRect)
2471 {
2472 dstRect.left = drawRect->x;
2473 dstRect.right = drawRect->x + drawRect->width;
2474 dstRect.top = drawRect->y;
2475 dstRect.bottom = drawRect->y + drawRect->height;
2476 dstRectPtr = &dstRect;
2477 }
2478
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002479 HRESULT result = mDevice->StretchRect(readSurface, srcRectPtr, drawSurface, dstRectPtr, D3DTEXF_NONE);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002480
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002481 readSurface->Release();
2482 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002483
2484 if (FAILED(result))
2485 {
2486 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2487 return false;
2488 }
2489 }
2490
2491 if (blitDepthStencil)
2492 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002493 gl::Renderbuffer *readBuffer = readFramebuffer->getDepthOrStencilbuffer();
2494 gl::Renderbuffer *drawBuffer = drawFramebuffer->getDepthOrStencilbuffer();
2495 RenderTarget9 *readDepthStencil = NULL;
2496 RenderTarget9 *drawDepthStencil = NULL;
2497 IDirect3DSurface9* readSurface = NULL;
2498 IDirect3DSurface9* drawSurface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002499
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002500 if (readBuffer)
2501 {
2502 readDepthStencil = RenderTarget9::makeRenderTarget9(readBuffer->getDepthStencil());
2503 }
2504 if (drawBuffer)
2505 {
2506 drawDepthStencil = RenderTarget9::makeRenderTarget9(drawBuffer->getDepthStencil());
2507 }
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002508
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002509 if (readDepthStencil)
2510 {
2511 readSurface = readDepthStencil->getSurface();
2512 }
2513 if (drawDepthStencil)
2514 {
2515 drawSurface = drawDepthStencil->getSurface();
2516 }
2517
2518 if (!readSurface || !drawSurface)
2519 {
2520 ERR("Failed to retrieve the render target.");
2521 return error(GL_OUT_OF_MEMORY, false);
2522 }
2523
2524 HRESULT result = mDevice->StretchRect(readSurface, NULL, drawSurface, NULL, D3DTEXF_NONE);
2525
2526 readSurface->Release();
2527 drawSurface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002528
2529 if (FAILED(result))
2530 {
2531 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
2532 return false;
2533 }
2534 }
2535
2536 return true;
2537}
2538
2539void Renderer9::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
2540 GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
2541{
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002542 RenderTarget9 *renderTarget = NULL;
2543 IDirect3DSurface9 *surface = NULL;
2544 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
2545
2546 if (colorbuffer)
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002547 {
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002548 renderTarget = RenderTarget9::makeRenderTarget9(colorbuffer->getRenderTarget());
2549 }
2550
2551 if (renderTarget)
2552 {
2553 surface = renderTarget->getSurface();
2554 }
2555
2556 if (!surface)
2557 {
2558 // context must be lost
2559 return;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002560 }
2561
2562 D3DSURFACE_DESC desc;
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002563 surface->GetDesc(&desc);
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002564
2565 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2566 {
2567 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002568 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002569 return error(GL_OUT_OF_MEMORY);
2570 }
2571
2572 HRESULT result;
2573 IDirect3DSurface9 *systemSurface = NULL;
2574 bool directToPixels = !packReverseRowOrder && packAlignment <= 4 && getShareHandleSupport() &&
2575 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2576 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2577 if (directToPixels)
2578 {
2579 // Use the pixels ptr as a shared handle to write directly into client's memory
2580 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2581 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2582 if (FAILED(result))
2583 {
2584 // Try again without the shared handle
2585 directToPixels = false;
2586 }
2587 }
2588
2589 if (!directToPixels)
2590 {
2591 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2592 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2593 if (FAILED(result))
2594 {
2595 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002596 surface->Release();
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002597 return error(GL_OUT_OF_MEMORY);
2598 }
2599 }
2600
daniel@transgaming.comd186dc72012-11-28 19:40:16 +00002601 result = mDevice->GetRenderTargetData(surface, systemSurface);
2602 surface->Release();
2603 surface = NULL;
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002604
2605 if (FAILED(result))
2606 {
2607 systemSurface->Release();
2608
2609 // It turns out that D3D will sometimes produce more error
2610 // codes than those documented.
daniel@transgaming.com414c9162012-11-28 20:54:57 +00002611 if (checkDeviceLost(result))
daniel@transgaming.com6c872172012-11-28 19:39:33 +00002612 return error(GL_OUT_OF_MEMORY);
2613 else
2614 {
2615 UNREACHABLE();
2616 return;
2617 }
2618
2619 }
2620
2621 if (directToPixels)
2622 {
2623 systemSurface->Release();
2624 return;
2625 }
2626
2627 RECT rect;
2628 rect.left = gl::clamp(x, 0L, static_cast<LONG>(desc.Width));
2629 rect.top = gl::clamp(y, 0L, static_cast<LONG>(desc.Height));
2630 rect.right = gl::clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2631 rect.bottom = gl::clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2632
2633 D3DLOCKED_RECT lock;
2634 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2635
2636 if (FAILED(result))
2637 {
2638 UNREACHABLE();
2639 systemSurface->Release();
2640
2641 return; // No sensible error to generate
2642 }
2643
2644 unsigned char *dest = (unsigned char*)pixels;
2645 unsigned short *dest16 = (unsigned short*)pixels;
2646
2647 unsigned char *source;
2648 int inputPitch;
2649 if (packReverseRowOrder)
2650 {
2651 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2652 inputPitch = -lock.Pitch;
2653 }
2654 else
2655 {
2656 source = (unsigned char*)lock.pBits;
2657 inputPitch = lock.Pitch;
2658 }
2659
2660 unsigned int fastPixelSize = 0;
2661
2662 if (desc.Format == D3DFMT_A8R8G8B8 &&
2663 format == GL_BGRA_EXT &&
2664 type == GL_UNSIGNED_BYTE)
2665 {
2666 fastPixelSize = 4;
2667 }
2668 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2669 format == GL_BGRA_EXT &&
2670 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2671 (desc.Format == D3DFMT_A1R5G5B5 &&
2672 format == GL_BGRA_EXT &&
2673 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2674 {
2675 fastPixelSize = 2;
2676 }
2677 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2678 format == GL_RGBA &&
2679 type == GL_HALF_FLOAT_OES)
2680 {
2681 fastPixelSize = 8;
2682 }
2683 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2684 format == GL_RGBA &&
2685 type == GL_FLOAT)
2686 {
2687 fastPixelSize = 16;
2688 }
2689
2690 for (int j = 0; j < rect.bottom - rect.top; j++)
2691 {
2692 if (fastPixelSize != 0)
2693 {
2694 // Fast path for formats which require no translation:
2695 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2696 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2697 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2698 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2699 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2700 //
2701 // Note that buffers with no alpha go through the slow path below.
2702 memcpy(dest + j * outputPitch,
2703 source + j * inputPitch,
2704 (rect.right - rect.left) * fastPixelSize);
2705 continue;
2706 }
2707
2708 for (int i = 0; i < rect.right - rect.left; i++)
2709 {
2710 float r;
2711 float g;
2712 float b;
2713 float a;
2714
2715 switch (desc.Format)
2716 {
2717 case D3DFMT_R5G6B5:
2718 {
2719 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2720
2721 a = 1.0f;
2722 b = (rgb & 0x001F) * (1.0f / 0x001F);
2723 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2724 r = (rgb & 0xF800) * (1.0f / 0xF800);
2725 }
2726 break;
2727 case D3DFMT_A1R5G5B5:
2728 {
2729 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2730
2731 a = (argb & 0x8000) ? 1.0f : 0.0f;
2732 b = (argb & 0x001F) * (1.0f / 0x001F);
2733 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2734 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2735 }
2736 break;
2737 case D3DFMT_A8R8G8B8:
2738 {
2739 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2740
2741 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2742 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2743 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2744 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2745 }
2746 break;
2747 case D3DFMT_X8R8G8B8:
2748 {
2749 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2750
2751 a = 1.0f;
2752 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2753 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2754 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2755 }
2756 break;
2757 case D3DFMT_A2R10G10B10:
2758 {
2759 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2760
2761 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2762 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2763 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2764 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2765 }
2766 break;
2767 case D3DFMT_A32B32G32R32F:
2768 {
2769 // float formats in D3D are stored rgba, rather than the other way round
2770 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2771 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2772 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2773 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2774 }
2775 break;
2776 case D3DFMT_A16B16G16R16F:
2777 {
2778 // float formats in D3D are stored rgba, rather than the other way round
2779 r = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2780 g = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2781 b = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2782 a = gl::float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
2783 }
2784 break;
2785 default:
2786 UNIMPLEMENTED(); // FIXME
2787 UNREACHABLE();
2788 return;
2789 }
2790
2791 switch (format)
2792 {
2793 case GL_RGBA:
2794 switch (type)
2795 {
2796 case GL_UNSIGNED_BYTE:
2797 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2798 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2799 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2800 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2801 break;
2802 default: UNREACHABLE();
2803 }
2804 break;
2805 case GL_BGRA_EXT:
2806 switch (type)
2807 {
2808 case GL_UNSIGNED_BYTE:
2809 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2810 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2811 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2812 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2813 break;
2814 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2815 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2816 // this type is packed as follows:
2817 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2818 // --------------------------------------------------------------------------------
2819 // | 4th | 3rd | 2nd | 1st component |
2820 // --------------------------------------------------------------------------------
2821 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2822 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2823 ((unsigned short)(15 * a + 0.5f) << 12)|
2824 ((unsigned short)(15 * r + 0.5f) << 8) |
2825 ((unsigned short)(15 * g + 0.5f) << 4) |
2826 ((unsigned short)(15 * b + 0.5f) << 0);
2827 break;
2828 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2829 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2830 // this type is packed as follows:
2831 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2832 // --------------------------------------------------------------------------------
2833 // | 4th | 3rd | 2nd | 1st component |
2834 // --------------------------------------------------------------------------------
2835 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2836 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2837 ((unsigned short)( a + 0.5f) << 15) |
2838 ((unsigned short)(31 * r + 0.5f) << 10) |
2839 ((unsigned short)(31 * g + 0.5f) << 5) |
2840 ((unsigned short)(31 * b + 0.5f) << 0);
2841 break;
2842 default: UNREACHABLE();
2843 }
2844 break;
2845 case GL_RGB:
2846 switch (type)
2847 {
2848 case GL_UNSIGNED_SHORT_5_6_5:
2849 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2850 ((unsigned short)(31 * b + 0.5f) << 0) |
2851 ((unsigned short)(63 * g + 0.5f) << 5) |
2852 ((unsigned short)(31 * r + 0.5f) << 11);
2853 break;
2854 case GL_UNSIGNED_BYTE:
2855 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2856 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2857 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2858 break;
2859 default: UNREACHABLE();
2860 }
2861 break;
2862 default: UNREACHABLE();
2863 }
2864 }
2865 }
2866
2867 systemSurface->UnlockRect();
2868
2869 systemSurface->Release();
2870}
2871
daniel@transgaming.comf2423652012-11-28 20:53:50 +00002872RenderTarget *Renderer9::createRenderTarget(SwapChain *swapChain, bool depth)
2873{
2874 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
2875 IDirect3DSurface9 *surface = NULL;
2876 if (depth)
2877 {
2878 surface = swapChain9->getDepthStencil();
2879 }
2880 else
2881 {
2882 surface = swapChain9->getRenderTarget();
2883 }
2884
2885 RenderTarget9 *renderTarget = new RenderTarget9(this, surface);
2886
2887 return renderTarget;
2888}
2889
2890RenderTarget *Renderer9::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
2891{
2892 RenderTarget9 *renderTarget = new RenderTarget9(this, width, height, format, samples);
2893 return renderTarget;
2894}
2895
daniel@transgaming.com2275f912012-12-20 21:13:22 +00002896ShaderExecutable *Renderer9::loadExecutable(const void *function, size_t length, GLenum type)
daniel@transgaming.com55318902012-11-28 20:58:58 +00002897{
2898 ShaderExecutable9 *executable = NULL;
daniel@transgaming.com55318902012-11-28 20:58:58 +00002899
2900 switch (type)
2901 {
2902 case GL_VERTEX_SHADER:
2903 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002904 IDirect3DVertexShader9 *vshader = createVertexShader((DWORD*)function, length);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002905 if (vshader)
2906 {
daniel@transgaming.com2275f912012-12-20 21:13:22 +00002907 executable = new ShaderExecutable9(function, length, vshader);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002908 }
2909 }
2910 break;
2911 case GL_FRAGMENT_SHADER:
2912 {
daniel@transgaming.com7b18d0c2012-11-28 21:04:10 +00002913 IDirect3DPixelShader9 *pshader = createPixelShader((DWORD*)function, length);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002914 if (pshader)
2915 {
daniel@transgaming.com2275f912012-12-20 21:13:22 +00002916 executable = new ShaderExecutable9(function, length, pshader);
daniel@transgaming.com55318902012-11-28 20:58:58 +00002917 }
2918 }
2919 break;
2920 default:
2921 UNREACHABLE();
2922 break;
2923 }
2924
2925 return executable;
2926}
2927
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002928ShaderExecutable *Renderer9::compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, GLenum type)
2929{
2930 const char *profile = NULL;
2931
2932 switch (type)
2933 {
2934 case GL_VERTEX_SHADER:
2935 profile = getMajorShaderModel() >= 3 ? "vs_3_0" : "vs_2_0";
2936 break;
2937 case GL_FRAGMENT_SHADER:
2938 profile = getMajorShaderModel() >= 3 ? "ps_3_0" : "ps_2_0";
2939 break;
2940 default:
2941 UNREACHABLE();
2942 return NULL;
2943 }
2944
daniel@transgaming.com25e16af2012-11-28 21:05:57 +00002945 ID3DBlob *binary = compileToBinary(infoLog, shaderHLSL, profile, true);
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002946 if (!binary)
2947 return NULL;
2948
daniel@transgaming.com2275f912012-12-20 21:13:22 +00002949 ShaderExecutable *executable = loadExecutable(binary->GetBufferPointer(), binary->GetBufferSize(), type);
daniel@transgaming.com536dd6e2012-11-28 21:00:18 +00002950 binary->Release();
daniel@transgaming.coma9c71422012-11-28 20:58:45 +00002951
2952 return executable;
2953}
2954
daniel@transgaming.comde8a7ff2012-11-28 19:34:13 +00002955bool Renderer9::boxFilter(IDirect3DSurface9 *source, IDirect3DSurface9 *dest)
2956{
2957 return mBlit->boxFilter(source, dest);
2958}
2959
daniel@transgaming.com2507f412012-10-31 18:46:48 +00002960D3DPOOL Renderer9::getTexturePool(DWORD usage) const
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002961{
2962 if (mD3d9Ex != NULL)
2963 {
2964 return D3DPOOL_DEFAULT;
2965 }
2966 else
2967 {
2968 if (!(usage & (D3DUSAGE_DEPTHSTENCIL | D3DUSAGE_RENDERTARGET)))
2969 {
2970 return D3DPOOL_MANAGED;
2971 }
2972 }
2973
2974 return D3DPOOL_DEFAULT;
2975}
2976
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002977bool Renderer9::copyToRenderTarget(IDirect3DSurface9 *dest, IDirect3DSurface9 *source, bool fromManaged)
2978{
2979 if (source && dest)
2980 {
2981 HRESULT result = D3DERR_OUTOFVIDEOMEMORY;
2982 IDirect3DDevice9 *device = getDevice(); // D3D9_REPLACE
2983
2984 if (fromManaged)
2985 {
2986 D3DSURFACE_DESC desc;
2987 source->GetDesc(&desc);
2988
2989 IDirect3DSurface9 *surf = 0;
2990 result = device->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format, D3DPOOL_SYSTEMMEM, &surf, NULL);
2991
2992 if (SUCCEEDED(result))
2993 {
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00002994 Image9::copyLockableSurfaces(surf, source);
daniel@transgaming.com1d80eee2012-11-28 19:33:31 +00002995 result = device->UpdateSurface(surf, NULL, dest, NULL);
2996 surf->Release();
2997 }
2998 }
2999 else
3000 {
3001 endScene();
3002 result = device->StretchRect(source, NULL, dest, NULL, D3DTEXF_NONE);
3003 }
3004
3005 if (FAILED(result))
3006 {
3007 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
3008 return false;
3009 }
3010 }
3011
3012 return true;
daniel@transgaming.com67094ee2012-11-28 20:53:04 +00003013}
3014
daniel@transgaming.com244e1832012-12-20 20:52:35 +00003015Image *Renderer9::createImage()
3016{
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00003017 return new Image9();
daniel@transgaming.com244e1832012-12-20 20:52:35 +00003018}
3019
daniel@transgaming.comf721fdb2012-12-20 20:53:11 +00003020void Renderer9::generateMipmap(Image *dest, Image *src)
3021{
daniel@transgaming.com4ba24062012-12-20 20:54:24 +00003022 Image9 *src9 = Image9::makeImage9(src);
3023 Image9 *dst9 = Image9::makeImage9(dest);
3024 Image9::generateMipmap(dst9, src9);
daniel@transgaming.comf721fdb2012-12-20 20:53:11 +00003025}
3026
daniel@transgaming.com413d2712012-12-20 21:11:04 +00003027TextureStorage *Renderer9::createTextureStorage2D(SwapChain *swapChain)
3028{
3029 SwapChain9 *swapChain9 = SwapChain9::makeSwapChain9(swapChain);
3030 return new TextureStorage9_2D(this, swapChain9);
3031}
3032
3033TextureStorage *Renderer9::createTextureStorage2D(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height)
3034{
3035 return new TextureStorage9_2D(this, levels, internalformat, usage, forceRenderable, width, height);
3036}
3037
3038TextureStorage *Renderer9::createTextureStorageCube(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size)
3039{
3040 return new TextureStorage9_Cube(this, levels, internalformat, usage, forceRenderable, size);
3041}
3042
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003043}