Renderer.cpp 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Geometry.h"
  25. #include "IndexBuffer.h"
  26. #include "Log.h"
  27. #include "Matrix4x3.h"
  28. #include "PixelShader.h"
  29. #include "Profiler.h"
  30. #include "Renderer.h"
  31. #include "RendererEvents.h"
  32. #include "RendererImpl.h"
  33. #include "StringUtils.h"
  34. #include "Texture2D.h"
  35. #include "TextureCube.h"
  36. #include "VertexBuffer.h"
  37. #include "VertexDeclaration.h"
  38. #include "VertexShader.h"
  39. #include <cstring>
  40. #include "DebugNew.h"
  41. #ifdef _MSC_VER
  42. #pragma warning(disable:4355)
  43. #endif
  44. static const DWORD windowStyle = WS_OVERLAPPEDWINDOW & ~WS_THICKFRAME & ~WS_MAXIMIZEBOX;
  45. static const D3DCMPFUNC d3dCmpFunc[] =
  46. {
  47. D3DCMP_ALWAYS,
  48. D3DCMP_EQUAL,
  49. D3DCMP_NOTEQUAL,
  50. D3DCMP_LESS,
  51. D3DCMP_LESSEQUAL,
  52. D3DCMP_GREATER,
  53. D3DCMP_GREATEREQUAL
  54. };
  55. // These are for optimizing the case where user supplies a single vertex buffer in setVertexBuffer()
  56. std::vector<VertexBuffer*> vertexBuffers;
  57. std::vector<unsigned> elementMasks;
  58. std::map<HWND, Renderer*> renderers;
  59. static LRESULT CALLBACK wndProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam);
  60. Renderer::Renderer(const std::string& windowTitle) :
  61. mImpl(new RendererImpl()),
  62. mWindowTitle(windowTitle),
  63. mMode(RENDER_FORWARD),
  64. mWidth(0),
  65. mHeight(0),
  66. mMultiSample(0),
  67. mWindowPosX(0),
  68. mWindowPosY(0),
  69. mFullscreen(false),
  70. mVsync(false),
  71. mClosed(false),
  72. mDeviceLost(false),
  73. mQueryIssued(false),
  74. mSystemDepthStencil(false),
  75. mDeferredSupport(false),
  76. mPrepassSupport(false),
  77. mSM3Support(false),
  78. mHardwareDepthSupport(false),
  79. mHardwareShadowSupport(false),
  80. mHiresShadowSupport(false),
  81. mForceSM2(false),
  82. mNumPrimitives(0),
  83. mNumBatches(0),
  84. mImmediateBuffer(0),
  85. mDefaultTextureFilterMode(FILTER_BILINEAR)
  86. {
  87. LOGINFO("Renderer created");
  88. resetCachedState();
  89. vertexBuffers.resize(1);
  90. elementMasks.resize(1);
  91. elementMasks[0] = MASK_DEFAULT;
  92. subscribeToEvent(EVENT_WINDOWMESSAGE, EVENT_HANDLER(Renderer, handleWindowMessage));
  93. }
  94. Renderer::~Renderer()
  95. {
  96. mVertexDeclarations.clear();
  97. if (mImpl->mFrameQuery)
  98. {
  99. mImpl->mFrameQuery->Release();
  100. mImpl->mFrameQuery = 0;
  101. }
  102. if (mImpl->mDefaultColorSurface)
  103. {
  104. mImpl->mDefaultColorSurface->Release();
  105. mImpl->mDefaultColorSurface = 0;
  106. }
  107. if (mImpl->mDefaultDepthStencilSurface)
  108. {
  109. if (mSystemDepthStencil)
  110. mImpl->mDefaultDepthStencilSurface->Release();
  111. mImpl->mDefaultDepthStencilSurface = 0;
  112. }
  113. if (mImpl->mDevice)
  114. {
  115. mImpl->mDevice->Release();
  116. mImpl->mDevice = 0;
  117. }
  118. if (mImpl->mInterface)
  119. {
  120. mImpl->mInterface->Release();
  121. mImpl->mInterface = 0;
  122. }
  123. if (mImpl->mWindow)
  124. {
  125. DestroyWindow(mImpl->mWindow);
  126. renderers.erase(mImpl->mWindow);
  127. mImpl->mWindow = 0;
  128. }
  129. delete mImpl;
  130. mImpl = 0;
  131. LOGINFO("Renderer shut down");
  132. }
  133. void Renderer::messagePump()
  134. {
  135. MSG msg;
  136. while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
  137. {
  138. TranslateMessage(&msg);
  139. DispatchMessage(&msg);
  140. if (msg.message == WM_QUIT)
  141. mClosed = true;
  142. }
  143. }
  144. void Renderer::setWindowTitle(const std::string& windowTitle)
  145. {
  146. mWindowTitle = windowTitle;
  147. if (mImpl->mWindow)
  148. SetWindowText(mImpl->mWindow, mWindowTitle.c_str());
  149. }
  150. void Renderer::setMode(RenderMode mode, int width, int height, bool fullscreen, bool vsync, int multiSample)
  151. {
  152. // Find out the full screen mode display format (match desktop color depth)
  153. D3DFORMAT fullscreenFormat = mImpl->getDesktopFormat();
  154. // If zero dimensions, use the desktop default
  155. if ((width <= 0) || (height <= 0))
  156. {
  157. if (fullscreen)
  158. {
  159. IntVector2 desktopResolution = mImpl->getDesktopResolution();
  160. width = desktopResolution.mX;
  161. height = desktopResolution.mY;
  162. }
  163. else
  164. {
  165. width = 800;
  166. height = 600;
  167. }
  168. }
  169. if ((mode == mMode) && (width == mWidth) && (height == mHeight) && (fullscreen == mFullscreen) && (vsync == mVsync)
  170. && (multiSample == mMultiSample))
  171. return;
  172. if (!mImpl->mWindow)
  173. createWindow(width, height);
  174. if (!mImpl->mInterface)
  175. createInterface();
  176. // Disable deferred / light prepass rendering if not supported
  177. // Note: we do not fall back from deferred to light prepass, because there might not be shaders / materials
  178. // defined for it. Instead fall back directly to forward rendering
  179. if ((mode == RENDER_DEFERRED) && (!mDeferredSupport))
  180. mode = RENDER_FORWARD;
  181. if ((mode == RENDER_PREPASS) && (!mPrepassSupport))
  182. mode = RENDER_FORWARD;
  183. if (multiSample >= (int)D3DMULTISAMPLE_2_SAMPLES)
  184. multiSample = clamp(multiSample, (int)D3DMULTISAMPLE_NONE, (int)D3DMULTISAMPLE_16_SAMPLES);
  185. else
  186. multiSample = 0;
  187. // Note: getMultiSample() will not reflect the actual hardware multisample mode, but rather what the caller wanted.
  188. // In deferred or light prepass mode, it is used to control the edge filter
  189. mMultiSample = multiSample;
  190. if (mode != RENDER_FORWARD)
  191. multiSample = 0;
  192. // Check fullscreen mode validity. If not valid, revert to windowed
  193. if (fullscreen)
  194. {
  195. std::vector<IntVector2> resolutions = getResolutions();
  196. fullscreen = false;
  197. for (unsigned i = 0; i < resolutions.size(); ++i)
  198. {
  199. if ((width == resolutions[i].mX) && (height == resolutions[i].mY))
  200. {
  201. fullscreen = true;
  202. break;
  203. }
  204. }
  205. }
  206. // Fall back to non-multisampled if unsupported multisampling mode
  207. if (multiSample)
  208. {
  209. if (FAILED(mImpl->mInterface->CheckDeviceMultiSampleType(mImpl->mAdapter, mImpl->mDeviceType, fullscreenFormat, FALSE,
  210. (D3DMULTISAMPLE_TYPE)multiSample, NULL)))
  211. multiSample = 0;
  212. }
  213. // Save window placement if currently windowed
  214. if (!mFullscreen)
  215. {
  216. WINDOWPLACEMENT wndpl;
  217. wndpl.length = sizeof wndpl;
  218. if (SUCCEEDED(GetWindowPlacement(mImpl->mWindow, &wndpl)))
  219. {
  220. mWindowPosX = wndpl.rcNormalPosition.left;
  221. mWindowPosY = wndpl.rcNormalPosition.top;
  222. }
  223. }
  224. if (fullscreen)
  225. {
  226. mImpl->mPresentParams.BackBufferFormat = fullscreenFormat;
  227. mImpl->mPresentParams.Windowed = false;
  228. }
  229. else
  230. {
  231. mImpl->mPresentParams.BackBufferFormat = D3DFMT_UNKNOWN;
  232. mImpl->mPresentParams.Windowed = true;
  233. }
  234. // Use autodepthstencil normally. However, if INTZ depth is available and deferred rendering is enabled,
  235. // create a depth texture instead
  236. bool autoDepthStencil = true;
  237. if ((mode != RENDER_FORWARD) && (mHardwareDepthSupport))
  238. autoDepthStencil = false;
  239. mImpl->mPresentParams.BackBufferWidth = width;
  240. mImpl->mPresentParams.BackBufferHeight = height;
  241. mImpl->mPresentParams.BackBufferCount = 1;
  242. mImpl->mPresentParams.MultiSampleType = (D3DMULTISAMPLE_TYPE)multiSample;
  243. mImpl->mPresentParams.MultiSampleQuality = 0;
  244. mImpl->mPresentParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
  245. mImpl->mPresentParams.hDeviceWindow = mImpl->mWindow;
  246. mImpl->mPresentParams.EnableAutoDepthStencil = autoDepthStencil;
  247. mImpl->mPresentParams.AutoDepthStencilFormat = D3DFMT_D24S8;
  248. mImpl->mPresentParams.Flags = 0;
  249. mImpl->mPresentParams.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
  250. if (vsync)
  251. mImpl->mPresentParams.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
  252. else
  253. mImpl->mPresentParams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  254. mWidth = width;
  255. mHeight = height;
  256. mFullscreen = fullscreen;
  257. mVsync = vsync;
  258. mMode = mode;
  259. if (!mImpl->mDevice)
  260. {
  261. unsigned adapter = D3DADAPTER_DEFAULT;
  262. unsigned deviceType = D3DDEVTYPE_HAL;
  263. // Check for PerfHUD adapter
  264. for (unsigned i=0; i < mImpl->mInterface->GetAdapterCount(); ++i)
  265. {
  266. D3DADAPTER_IDENTIFIER9 identifier;
  267. mImpl->mInterface->GetAdapterIdentifier(i, 0, &identifier);
  268. if (strstr(identifier.Description, "PerfHUD") != 0)
  269. {
  270. adapter = i;
  271. deviceType = D3DDEVTYPE_REF;
  272. break;
  273. }
  274. }
  275. mImpl->mInterface->GetAdapterIdentifier(adapter, 0, &mImpl->mAdapterIdentifier);
  276. createDevice(adapter, deviceType);
  277. }
  278. else
  279. resetDevice();
  280. // Adjust window style/size now
  281. if (fullscreen)
  282. {
  283. SetWindowLongPtr(mImpl->mWindow, GWL_STYLE, WS_POPUP);
  284. SetWindowPos(mImpl->mWindow, HWND_TOP, 0, 0, width, height, SWP_NOZORDER | SWP_SHOWWINDOW);
  285. }
  286. else
  287. {
  288. RECT rect = {0, 0, width, height};
  289. AdjustWindowRect(&rect, windowStyle, false);
  290. SetWindowLongPtr(mImpl->mWindow, GWL_STYLE, windowStyle);
  291. SetWindowPos(mImpl->mWindow, HWND_TOP, mWindowPosX, mWindowPosY, rect.right - rect.left, rect.bottom - rect.top,
  292. SWP_NOZORDER | SWP_SHOWWINDOW);
  293. // Clean up the desktop of the old window contents
  294. InvalidateRect(0, 0, true);
  295. }
  296. using namespace ScreenMode;
  297. VariantMap eventData;
  298. eventData[P_WIDTH] = mWidth;
  299. eventData[P_HEIGHT] = mHeight;
  300. eventData[P_FULLSCREEN] = mFullscreen;
  301. sendEvent(EVENT_SCREENMODE, eventData);
  302. if (!multiSample)
  303. LOGINFO("Set screen mode " + toString(mWidth) + "x" + toString(mHeight) + " " + (mFullscreen ? "fullscreen" : "windowed"));
  304. else
  305. LOGINFO("Set screen mode " + toString(mWidth) + "x" + toString(mHeight) + " " + (mFullscreen ? "fullscreen" : "windowed") +
  306. " multisample " + toString(multiSample));
  307. }
  308. void Renderer::setMode(int width, int height)
  309. {
  310. setMode(mMode, width, height, mFullscreen, mVsync, mMultiSample);
  311. }
  312. void Renderer::toggleFullscreen()
  313. {
  314. setMode(mMode, mWidth, mHeight, !mFullscreen, mVsync, mMultiSample);
  315. }
  316. void Renderer::close()
  317. {
  318. if (mImpl->mWindow)
  319. {
  320. mDiffBuffer.reset();
  321. mNormalBuffer.reset();
  322. mDepthBuffer.reset();
  323. mImmediateVertexBuffers.clear();
  324. DestroyWindow(mImpl->mWindow);
  325. renderers.erase(mImpl->mWindow);
  326. mImpl->mWindow = 0;
  327. mClosed = true;
  328. }
  329. }
  330. bool Renderer::takeScreenShot(Image& destImage)
  331. {
  332. PROFILE(Renderer_TakeScreenShot);
  333. if (!mImpl->mDevice)
  334. return false;
  335. D3DSURFACE_DESC surfaceDesc;
  336. mImpl->mDefaultColorSurface->GetDesc(&surfaceDesc);
  337. // If possible, get the backbuffer data, because it is a lot faster.
  338. // However, if we are multisampled, need to use the front buffer
  339. bool useBackBuffer = true;
  340. if (mImpl->mPresentParams.MultiSampleType)
  341. {
  342. useBackBuffer = false;
  343. surfaceDesc.Format = D3DFMT_A8R8G8B8;
  344. }
  345. IDirect3DSurface9* surface = 0;
  346. mImpl->mDevice->CreateOffscreenPlainSurface(mWidth, mHeight, surfaceDesc.Format, D3DPOOL_SYSTEMMEM, &surface, 0);
  347. if (!surface)
  348. return false;
  349. if (useBackBuffer)
  350. mImpl->mDevice->GetRenderTargetData(mImpl->mDefaultColorSurface, surface);
  351. else
  352. mImpl->mDevice->GetFrontBufferData(0, surface);
  353. D3DLOCKED_RECT lockedRect;
  354. lockedRect.pBits = 0;
  355. surface->LockRect(&lockedRect, 0, D3DLOCK_NOSYSLOCK | D3DLOCK_READONLY);
  356. if (!lockedRect.pBits)
  357. {
  358. surface->Release();
  359. return false;
  360. }
  361. destImage.setSize(mWidth, mHeight, 3);
  362. unsigned char* destData = destImage.getData();
  363. if (surfaceDesc.Format == D3DFMT_R5G6B5)
  364. {
  365. for (int y = 0; y < mHeight; ++y)
  366. {
  367. unsigned short* src = (unsigned short*)((unsigned char*)lockedRect.pBits + y * lockedRect.Pitch);
  368. unsigned char* dest = destData + y * mWidth * 3;
  369. for (int x = 0; x < mWidth; ++x)
  370. {
  371. unsigned short rgb = *src++;
  372. int b = rgb & 31;
  373. int g = (rgb >> 5) & 63;
  374. int r = (rgb >> 11);
  375. *dest++ = (int)(r * 255.0f / 31.0f);
  376. *dest++ = (int)(g * 255.0f / 63.0f);
  377. *dest++ = (int)(b * 255.0f / 31.0f);
  378. }
  379. }
  380. }
  381. else
  382. {
  383. for (int y = 0; y < mHeight; ++y)
  384. {
  385. unsigned char* src = (unsigned char*)lockedRect.pBits + y * lockedRect.Pitch;
  386. unsigned char* dest = destData + y * mWidth * 3;
  387. for (int x = 0; x < mWidth; ++x)
  388. {
  389. *dest++ = src[2];
  390. *dest++ = src[1];
  391. *dest++ = src[0];
  392. src += 4;
  393. }
  394. }
  395. }
  396. surface->UnlockRect();
  397. surface->Release();
  398. return true;
  399. }
  400. bool Renderer::beginFrame()
  401. {
  402. PROFILE(Renderer_BeginFrame);
  403. if (!mImpl->mDevice)
  404. EXCEPTION("Must have initial screen mode set before rendering");
  405. if (mClosed)
  406. return false;
  407. // Check for lost device before rendering
  408. HRESULT hr = mImpl->mDevice->TestCooperativeLevel();
  409. if (hr != D3D_OK)
  410. {
  411. mDeviceLost = true;
  412. // The device can not be reset yet, sleep and try again eventually
  413. if (hr == D3DERR_DEVICELOST)
  414. {
  415. Sleep(20);
  416. return false;
  417. }
  418. // The device is lost, but ready to be reset. Reset device but do not render on this frame yet
  419. if (hr == D3DERR_DEVICENOTRESET)
  420. {
  421. resetDevice();
  422. return false;
  423. }
  424. }
  425. mImpl->mDevice->BeginScene();
  426. // If a query was issued on the previous frame, wait for it to finish before beginning the next
  427. if ((mImpl->mFrameQuery) && (mQueryIssued))
  428. {
  429. while (mImpl->mFrameQuery->GetData(0, 0, D3DGETDATA_FLUSH) == S_FALSE)
  430. {
  431. }
  432. mQueryIssued = false;
  433. }
  434. // Set default rendertarget and depth buffer
  435. resetRenderTargets();
  436. mViewTexture = 0;
  437. // Cleanup textures from previous frame
  438. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  439. setTexture(i, 0);
  440. // Cleanup stream frequencies from previous frame
  441. resetStreamFrequencies();
  442. // Reset immediate mode vertex buffer positions
  443. for (std::map<unsigned, unsigned>::iterator i = mImmediateVertexBufferPos.begin(); i != mImmediateVertexBufferPos.end(); ++i)
  444. i->second = 0;
  445. mNumPrimitives = 0;
  446. mNumBatches = 0;
  447. sendEvent(EVENT_BEGINFRAME);
  448. return true;
  449. }
  450. void Renderer::endFrame(bool flushCommands)
  451. {
  452. PROFILE(Renderer_EndFrame);
  453. if (mClosed)
  454. return;
  455. sendEvent(EVENT_ENDFRAME);
  456. // Optionally flush GPU buffer to avoid control lag or framerate fluctuations due to pre-render
  457. if ((mImpl->mFrameQuery) && (flushCommands))
  458. {
  459. mImpl->mFrameQuery->Issue(D3DISSUE_END);
  460. mQueryIssued = true;
  461. }
  462. mImpl->mDevice->EndScene();
  463. mImpl->mDevice->Present(0, 0, 0, 0);
  464. }
  465. void Renderer::clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  466. {
  467. DWORD d3dFlags = 0;
  468. if (flags & CLEAR_COLOR)
  469. d3dFlags |= D3DCLEAR_TARGET;
  470. if (flags & CLEAR_DEPTH)
  471. d3dFlags |= D3DCLEAR_ZBUFFER;
  472. if (flags & CLEAR_STENCIL)
  473. d3dFlags |= D3DCLEAR_STENCIL;
  474. mImpl->mDevice->Clear(0, 0, d3dFlags, getD3DColor(color), depth, stencil);
  475. }
  476. void Renderer::draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount,
  477. unsigned instanceCount)
  478. {
  479. if (!indexCount)
  480. return;
  481. unsigned primitiveCount = 0;
  482. switch (type)
  483. {
  484. case TRIANGLE_LIST:
  485. primitiveCount = indexCount / 3;
  486. mImpl->mDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  487. break;
  488. case LINE_LIST:
  489. primitiveCount = indexCount / 2;
  490. mImpl->mDevice->DrawIndexedPrimitive(D3DPT_LINELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  491. break;
  492. }
  493. mNumPrimitives += primitiveCount * instanceCount;
  494. mNumBatches++;
  495. }
  496. void Renderer::draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount, unsigned instanceCount)
  497. {
  498. if (!vertexCount)
  499. return;
  500. unsigned primitiveCount;
  501. switch (type)
  502. {
  503. case TRIANGLE_LIST:
  504. primitiveCount = vertexCount / 3;
  505. mImpl->mDevice->DrawPrimitive(D3DPT_TRIANGLELIST, vertexStart, primitiveCount);
  506. break;
  507. case LINE_LIST:
  508. primitiveCount = vertexCount / 2;
  509. mImpl->mDevice->DrawPrimitive(D3DPT_LINELIST, vertexStart, primitiveCount);
  510. break;
  511. }
  512. mNumPrimitives += primitiveCount * instanceCount;
  513. mNumBatches++;
  514. }
  515. void Renderer::setVertexBuffer(VertexBuffer* buffer)
  516. {
  517. vertexBuffers[0] = buffer;
  518. setVertexBuffers(vertexBuffers, elementMasks);
  519. }
  520. bool Renderer::setVertexBuffers(const std::vector<VertexBuffer*>& buffers, const std::vector<unsigned>& elementMasks)
  521. {
  522. if (buffers.size() > MAX_VERTEX_STREAMS)
  523. {
  524. LOGERROR("Too many vertex buffers");
  525. return false;
  526. }
  527. if (buffers.size() != elementMasks.size())
  528. {
  529. LOGERROR("Amount of element masks and vertex buffers does not match");
  530. return false;
  531. }
  532. // Build vertex declaration hash code out of the buffers & masks
  533. unsigned long long hash = 0;
  534. for (unsigned i = 0; i < buffers.size(); ++i)
  535. {
  536. if (!buffers[i])
  537. continue;
  538. hash |= buffers[i]->getHash(i, elementMasks[i]);
  539. }
  540. if (hash)
  541. {
  542. // If no previous vertex declaration for that hash, create new
  543. if (mVertexDeclarations.find(hash) == mVertexDeclarations.end())
  544. mVertexDeclarations[hash] = new VertexDeclaration(this, buffers, elementMasks);
  545. VertexDeclaration* declaration = mVertexDeclarations[hash];
  546. if (declaration != mVertexDeclaration)
  547. {
  548. mImpl->mDevice->SetVertexDeclaration(declaration->getDeclaration());
  549. mVertexDeclaration = declaration;
  550. }
  551. }
  552. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  553. {
  554. VertexBuffer* buffer = 0;
  555. if (i < buffers.size())
  556. buffer = buffers[i];
  557. if (buffer != mVertexBuffer[i])
  558. {
  559. if (buffer)
  560. mImpl->mDevice->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->getObject(), 0, buffer->getVertexSize());
  561. else
  562. mImpl->mDevice->SetStreamSource(i, 0, 0, 0);
  563. mVertexBuffer[i] = buffer;
  564. }
  565. }
  566. return true;
  567. }
  568. bool Renderer::setVertexBuffers(const std::vector<SharedPtr<VertexBuffer> >& buffers, const std::vector<unsigned>&
  569. elementMasks)
  570. {
  571. if (buffers.size() > MAX_VERTEX_STREAMS)
  572. {
  573. LOGERROR("Too many vertex buffers");
  574. return false;
  575. }
  576. if (buffers.size() != elementMasks.size())
  577. {
  578. LOGERROR("Amount of element masks and vertex buffers does not match");
  579. return false;
  580. }
  581. // Build vertex declaration hash code out of the buffers & masks
  582. unsigned long long hash = 0;
  583. for (unsigned i = 0; i < buffers.size(); ++i)
  584. {
  585. if (!buffers[i])
  586. continue;
  587. hash |= buffers[i]->getHash(i, elementMasks[i]);
  588. }
  589. if (hash)
  590. {
  591. // If no previous vertex declaration for that hash, create new
  592. if (mVertexDeclarations.find(hash) == mVertexDeclarations.end())
  593. mVertexDeclarations[hash] = new VertexDeclaration(this, buffers, elementMasks);
  594. VertexDeclaration* declaration = mVertexDeclarations[hash];
  595. if (declaration != mVertexDeclaration)
  596. {
  597. mImpl->mDevice->SetVertexDeclaration(declaration->getDeclaration());
  598. mVertexDeclaration = declaration;
  599. }
  600. }
  601. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  602. {
  603. VertexBuffer* buffer = 0;
  604. if (i < buffers.size())
  605. buffer = buffers[i];
  606. if (buffer != mVertexBuffer[i])
  607. {
  608. if (buffer)
  609. mImpl->mDevice->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->getObject(), 0, buffer->getVertexSize());
  610. else
  611. mImpl->mDevice->SetStreamSource(i, 0, 0, 0);
  612. mVertexBuffer[i] = buffer;
  613. }
  614. }
  615. return true;
  616. }
  617. void Renderer::setIndexBuffer(IndexBuffer* buffer)
  618. {
  619. if (buffer != mIndexBuffer)
  620. {
  621. if (buffer)
  622. mImpl->mDevice->SetIndices((IDirect3DIndexBuffer9*)buffer->getObject());
  623. else
  624. mImpl->mDevice->SetIndices(0);
  625. mIndexBuffer = buffer;
  626. }
  627. }
  628. void Renderer::setVertexShader(VertexShader* shader)
  629. {
  630. if (shader != mVertexShader)
  631. {
  632. if (shader)
  633. mImpl->mDevice->SetVertexShader((IDirect3DVertexShader9*)shader->getObject());
  634. else
  635. mImpl->mDevice->SetVertexShader(0);
  636. mVertexShader = shader;
  637. }
  638. }
  639. void Renderer::setVertexShaderConstant(unsigned index, const bool* data, unsigned count)
  640. {
  641. if (index >= MAX_CONSTANT_REGISTERS)
  642. return;
  643. mImpl->mDevice->SetVertexShaderConstantB(index, (const BOOL*)data, count);
  644. }
  645. void Renderer::setVertexShaderConstant(unsigned index, const float* data, unsigned count)
  646. {
  647. if (index >= MAX_CONSTANT_REGISTERS)
  648. return;
  649. mImpl->mDevice->SetVertexShaderConstantF(index, data, count / 4);
  650. }
  651. void Renderer::setVertexShaderConstant(unsigned index, const int* data, unsigned count)
  652. {
  653. if (index >= MAX_CONSTANT_REGISTERS)
  654. return;
  655. mImpl->mDevice->SetVertexShaderConstantI(index, data, count / 4);
  656. }
  657. void Renderer::setVertexShaderConstant(unsigned index, float value)
  658. {
  659. if (index >= MAX_CONSTANT_REGISTERS)
  660. return;
  661. static float data[4] =
  662. {
  663. 0.0f,
  664. 0.0f,
  665. 0.0f,
  666. 0.0f
  667. };
  668. data[0] = value;
  669. mImpl->mDevice->SetVertexShaderConstantF(index, &data[0], 1);
  670. }
  671. void Renderer::setVertexShaderConstant(unsigned index, const Color& color)
  672. {
  673. if (index >= MAX_CONSTANT_REGISTERS)
  674. return;
  675. mImpl->mDevice->SetVertexShaderConstantF(index, color.getData(), 1);
  676. }
  677. void Renderer::setVertexShaderConstant(unsigned index, const Matrix3& matrix)
  678. {
  679. if (index >= MAX_CONSTANT_REGISTERS)
  680. return;
  681. static float data[12];
  682. data[0] = matrix.m00;
  683. data[1] = matrix.m01;
  684. data[2] = matrix.m02;
  685. data[3] = 0.0f;
  686. data[4] = matrix.m10;
  687. data[5] = matrix.m11;
  688. data[6] = matrix.m12;
  689. data[7] = 0.0f;
  690. data[8] = matrix.m20;
  691. data[9] = matrix.m21;
  692. data[10] = matrix.m22;
  693. data[11] = 0.0f;
  694. mImpl->mDevice->SetVertexShaderConstantF(index, &data[0], 3);
  695. }
  696. void Renderer::setVertexShaderConstant(unsigned index, const Vector3& vector)
  697. {
  698. if (index >= MAX_CONSTANT_REGISTERS)
  699. return;
  700. static float data[4] =
  701. {
  702. 0.0f,
  703. 0.0f,
  704. 0.0f,
  705. 0.0f
  706. };
  707. data[0] = vector.mX;
  708. data[1] = vector.mY;
  709. data[2] = vector.mZ;
  710. mImpl->mDevice->SetVertexShaderConstantF(index, &data[0], 1);
  711. }
  712. void Renderer::setVertexShaderConstant(unsigned index, const Matrix4& matrix)
  713. {
  714. if (index >= MAX_CONSTANT_REGISTERS)
  715. return;
  716. mImpl->mDevice->SetVertexShaderConstantF(index, matrix.getData(), 4);
  717. }
  718. void Renderer::setVertexShaderConstant(unsigned index, const Vector4& vector)
  719. {
  720. if (index >= MAX_CONSTANT_REGISTERS)
  721. return;
  722. mImpl->mDevice->SetVertexShaderConstantF(index, vector.getData(), 1);
  723. }
  724. void Renderer::setVertexShaderConstant(unsigned index, const Matrix4x3& matrix)
  725. {
  726. if (index >= MAX_CONSTANT_REGISTERS)
  727. return;
  728. mImpl->mDevice->SetVertexShaderConstantF(index, matrix.getData(), 3);
  729. }
  730. void Renderer::setPixelShader(PixelShader* shader)
  731. {
  732. if (shader != mPixelShader)
  733. {
  734. if (shader)
  735. mImpl->mDevice->SetPixelShader((IDirect3DPixelShader9*)shader->getObject());
  736. else
  737. mImpl->mDevice->SetPixelShader(0);
  738. mPixelShader = shader;
  739. }
  740. }
  741. void Renderer::setPixelShaderConstant(unsigned index, const bool* data, unsigned count)
  742. {
  743. if (index >= MAX_CONSTANT_REGISTERS)
  744. return;
  745. mImpl->mDevice->SetPixelShaderConstantB(index, (const BOOL*)data, count);
  746. }
  747. void Renderer::setPixelShaderConstant(unsigned index, const float* data, unsigned count)
  748. {
  749. if (index >= MAX_CONSTANT_REGISTERS)
  750. return;
  751. mImpl->mDevice->SetPixelShaderConstantF(index, data, count / 4);
  752. }
  753. void Renderer::setPixelShaderConstant(unsigned index, const int* data, unsigned count)
  754. {
  755. if (index >= MAX_CONSTANT_REGISTERS)
  756. return;
  757. mImpl->mDevice->SetPixelShaderConstantI(index, data, count / 4);
  758. }
  759. void Renderer::setPixelShaderConstant(unsigned index, float value)
  760. {
  761. if (index >= MAX_CONSTANT_REGISTERS)
  762. return;
  763. static float data[4] =
  764. {
  765. 0.0f,
  766. 0.0f,
  767. 0.0f,
  768. 0.0f
  769. };
  770. data[0] = value;
  771. mImpl->mDevice->SetPixelShaderConstantF(index, &data[0], 1);
  772. }
  773. void Renderer::setPixelShaderConstant(unsigned index, const Color& color)
  774. {
  775. if (index >= MAX_CONSTANT_REGISTERS)
  776. return;
  777. mImpl->mDevice->SetPixelShaderConstantF(index, color.getData(), 1);
  778. }
  779. void Renderer::setPixelShaderConstant(unsigned index, const Matrix3& matrix)
  780. {
  781. if (index >= MAX_CONSTANT_REGISTERS)
  782. return;
  783. static float data[12];
  784. data[0] = matrix.m00;
  785. data[1] = matrix.m01;
  786. data[2] = matrix.m02;
  787. data[3] = 0.0f;
  788. data[4] = matrix.m10;
  789. data[5] = matrix.m11;
  790. data[6] = matrix.m12;
  791. data[7] = 0.0f;
  792. data[8] = matrix.m20;
  793. data[9] = matrix.m21;
  794. data[10] = matrix.m22;
  795. data[11] = 0.0f;
  796. mImpl->mDevice->SetPixelShaderConstantF(index, &data[0], 3);
  797. }
  798. void Renderer::setPixelShaderConstant(unsigned index, const Vector3& vector)
  799. {
  800. if (index >= MAX_CONSTANT_REGISTERS)
  801. return;
  802. static float data[4] =
  803. {
  804. 0.0f,
  805. 0.0f,
  806. 0.0f,
  807. 0.0f
  808. };
  809. data[0] = vector.mX;
  810. data[1] = vector.mY;
  811. data[2] = vector.mZ;
  812. mImpl->mDevice->SetPixelShaderConstantF(index, &data[0], 1);
  813. }
  814. void Renderer::setPixelShaderConstant(unsigned index, const Matrix4& matrix)
  815. {
  816. if (index >= MAX_CONSTANT_REGISTERS)
  817. return;
  818. mImpl->mDevice->SetPixelShaderConstantF(index, matrix.getData(), 4);
  819. }
  820. void Renderer::setPixelShaderConstant(unsigned index, const Vector4& vector)
  821. {
  822. if (index >= MAX_CONSTANT_REGISTERS)
  823. return;
  824. mImpl->mDevice->SetPixelShaderConstantF(index, vector.getData(), 1);
  825. }
  826. void Renderer::setPixelShaderConstant(unsigned index, const Matrix4x3& matrix)
  827. {
  828. if (index >= MAX_CONSTANT_REGISTERS)
  829. return;
  830. mImpl->mDevice->SetPixelShaderConstantF(index, matrix.getData(), 3);
  831. }
  832. void Renderer::setTexture(unsigned index, Texture* texture)
  833. {
  834. if (index >= MAX_TEXTURE_UNITS)
  835. return;
  836. // Check if texture is currently bound as a render target. In that case, use its backup texture, or blank if not defined
  837. if (texture)
  838. {
  839. if ((mRenderTarget[0]) && (mRenderTarget[0]->getParentTexture() == texture))
  840. texture = texture->getBackupTexture();
  841. // Check also for an user-specifiable view texture: this is to make forward & deferred rendering behave similarly
  842. // (during G-buffer rendering it would otherwise be valid to have the final rendertarget texture bound)
  843. else if (texture == mViewTexture)
  844. texture = texture->getBackupTexture();
  845. }
  846. if (texture != mTexture[index])
  847. {
  848. if (texture)
  849. mImpl->mDevice->SetTexture(index, (IDirect3DBaseTexture9*)texture->getObject());
  850. else
  851. mImpl->mDevice->SetTexture(index, 0);
  852. mTexture[index] = texture;
  853. }
  854. if (texture)
  855. {
  856. static const D3DTEXTUREFILTERTYPE d3dMinMagFilter[] =
  857. {
  858. D3DTEXF_POINT,
  859. D3DTEXF_LINEAR,
  860. D3DTEXF_LINEAR,
  861. D3DTEXF_ANISOTROPIC
  862. };
  863. static const D3DTEXTUREFILTERTYPE d3dMipFilter[] =
  864. {
  865. D3DTEXF_POINT,
  866. D3DTEXF_POINT,
  867. D3DTEXF_LINEAR,
  868. D3DTEXF_ANISOTROPIC
  869. };
  870. static const D3DTEXTUREADDRESS d3dAddressMode[] =
  871. {
  872. D3DTADDRESS_WRAP,
  873. D3DTADDRESS_MIRROR,
  874. D3DTADDRESS_CLAMP,
  875. D3DTADDRESS_BORDER
  876. };
  877. TextureFilterMode filterMode = texture->getFilterMode();
  878. if (filterMode == FILTER_DEFAULT)
  879. filterMode = mDefaultTextureFilterMode;
  880. D3DTEXTUREFILTERTYPE minMag, mip;
  881. minMag = d3dMinMagFilter[filterMode];
  882. if (minMag != mImpl->mMinMagFilter[index])
  883. {
  884. mImpl->mDevice->SetSamplerState(index, D3DSAMP_MAGFILTER, minMag);
  885. mImpl->mDevice->SetSamplerState(index, D3DSAMP_MINFILTER, minMag);
  886. mImpl->mMinMagFilter[index] = minMag;
  887. }
  888. mip = d3dMipFilter[filterMode];
  889. if (mip != mImpl->mMipFilter[index])
  890. {
  891. mImpl->mDevice->SetSamplerState(index, D3DSAMP_MIPFILTER, mip);
  892. mImpl->mMipFilter[index] = mip;
  893. }
  894. D3DTEXTUREADDRESS u, v;
  895. u = d3dAddressMode[texture->getAddressMode(COORD_U)];
  896. if (u != mImpl->mUAddressMode[index])
  897. {
  898. mImpl->mDevice->SetSamplerState(index, D3DSAMP_ADDRESSU, u);
  899. mImpl->mUAddressMode[index] = u;
  900. }
  901. v = d3dAddressMode[texture->getAddressMode(COORD_V)];
  902. if (v != mImpl->mVAddressMode[index])
  903. {
  904. mImpl->mDevice->SetSamplerState(index, D3DSAMP_ADDRESSV, v);
  905. mImpl->mVAddressMode[index] = v;
  906. }
  907. if ((u == D3DTADDRESS_BORDER) || (v == D3DTADDRESS_BORDER))
  908. {
  909. const Color& borderColor = texture->getBorderColor();
  910. if (borderColor != mImpl->mBorderColor[index])
  911. {
  912. mImpl->mDevice->SetSamplerState(index, D3DSAMP_BORDERCOLOR, getD3DColor(borderColor));
  913. mImpl->mBorderColor[index] = borderColor;
  914. }
  915. }
  916. }
  917. }
  918. void Renderer::setDefaultTextureFilterMode(TextureFilterMode mode)
  919. {
  920. mDefaultTextureFilterMode = mode;
  921. }
  922. void Renderer::resetRenderTargets()
  923. {
  924. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  925. setRenderTarget(i, (RenderSurface*)0);
  926. setDepthStencil((RenderSurface*)0);
  927. setViewport(IntRect(0, 0, mWidth, mHeight));
  928. }
  929. void Renderer::resetRenderTarget(unsigned index)
  930. {
  931. setRenderTarget(index, (RenderSurface*)0);
  932. }
  933. void Renderer::resetDepthStencil()
  934. {
  935. setDepthStencil((RenderSurface*)0);
  936. }
  937. void Renderer::setRenderTarget(unsigned index, RenderSurface* renderTarget)
  938. {
  939. if (index >= MAX_RENDERTARGETS)
  940. return;
  941. IDirect3DSurface9* newColorSurface = 0;
  942. if (renderTarget)
  943. {
  944. if (renderTarget->getUsage() != TEXTURE_RENDERTARGET)
  945. return;
  946. newColorSurface = (IDirect3DSurface9*)renderTarget->getSurface();
  947. }
  948. else
  949. {
  950. if (!index)
  951. newColorSurface = mImpl->mDefaultColorSurface;
  952. }
  953. mRenderTarget[index] = renderTarget;
  954. if (newColorSurface != mImpl->mColorSurface[index])
  955. {
  956. mImpl->mDevice->SetRenderTarget(index, newColorSurface);
  957. mImpl->mColorSurface[index] = newColorSurface;
  958. }
  959. // If the rendertarget is also bound as a texture, replace with backup texture or null
  960. if (renderTarget)
  961. {
  962. Texture* parentTexture = renderTarget->getParentTexture();
  963. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  964. {
  965. if (mTexture[i] == parentTexture)
  966. setTexture(i, mTexture[i]->getBackupTexture());
  967. }
  968. }
  969. if (!index)
  970. {
  971. // Viewport has been reset
  972. IntVector2 rtSize = getRenderTargetDimensions();
  973. mViewport = IntRect(0, 0, rtSize.mX, rtSize.mY);
  974. // Disable scissor test, needs to be re-enabled by the user
  975. setScissorTest(false);
  976. }
  977. }
  978. void Renderer::setRenderTarget(unsigned index, Texture2D* renderTexture)
  979. {
  980. RenderSurface* renderTarget = 0;
  981. if (renderTexture)
  982. renderTarget = renderTexture->getRenderSurface();
  983. setRenderTarget(index, renderTarget);
  984. }
  985. void Renderer::setDepthStencil(RenderSurface* depthStencil)
  986. {
  987. IDirect3DSurface9* newDepthStencilSurface = 0;
  988. if ((depthStencil) && (depthStencil->getUsage() == TEXTURE_DEPTHSTENCIL))
  989. {
  990. newDepthStencilSurface = (IDirect3DSurface9*)depthStencil->getSurface();
  991. mDepthStencil = depthStencil;
  992. }
  993. if (!newDepthStencilSurface)
  994. {
  995. newDepthStencilSurface = mImpl->mDefaultDepthStencilSurface;
  996. mDepthStencil = 0;
  997. }
  998. if (newDepthStencilSurface != mImpl->mDepthStencilSurface)
  999. {
  1000. mImpl->mDevice->SetDepthStencilSurface(newDepthStencilSurface);
  1001. mImpl->mDepthStencilSurface = newDepthStencilSurface;
  1002. }
  1003. }
  1004. void Renderer::setDepthStencil(Texture2D* depthTexture)
  1005. {
  1006. RenderSurface* depthStencil = 0;
  1007. if (depthTexture)
  1008. depthStencil = depthTexture->getRenderSurface();
  1009. setDepthStencil(depthStencil);
  1010. }
  1011. void Renderer::setViewport(const IntRect& rect)
  1012. {
  1013. IntVector2 size = getRenderTargetDimensions();
  1014. IntRect rectCopy = rect;
  1015. if (rectCopy.mRight <= rectCopy.mLeft)
  1016. rectCopy.mRight = rectCopy.mLeft + 1;
  1017. if (rectCopy.mBottom <= rectCopy.mTop)
  1018. rectCopy.mBottom = rectCopy.mTop + 1;
  1019. rectCopy.mLeft = clamp(rectCopy.mLeft, 0, size.mX);
  1020. rectCopy.mTop = clamp(rectCopy.mTop, 0, size.mY);
  1021. rectCopy.mRight = clamp(rectCopy.mRight, 0, size.mX);
  1022. rectCopy.mBottom = clamp(rectCopy.mBottom, 0, size.mY);
  1023. D3DVIEWPORT9 vp;
  1024. vp.MinZ = 0.0f;
  1025. vp.MaxZ = 1.0f;
  1026. vp.X = rectCopy.mLeft;
  1027. vp.Y = rectCopy.mTop;
  1028. vp.Width = rectCopy.mRight - rectCopy.mLeft;
  1029. vp.Height = rectCopy.mBottom - rectCopy.mTop;
  1030. mImpl->mDevice->SetViewport(&vp);
  1031. mViewport = rectCopy;
  1032. // Disable scissor test, needs to be re-enabled by the user
  1033. setScissorTest(false);
  1034. }
  1035. void Renderer::setViewTexture(Texture* texture)
  1036. {
  1037. mViewTexture = texture;
  1038. // Check for the view texture being currently bound
  1039. if (texture)
  1040. {
  1041. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1042. {
  1043. if (mTexture[i] == texture)
  1044. setTexture(i, mTexture[i]->getBackupTexture());
  1045. }
  1046. }
  1047. }
  1048. void Renderer::setAlphaTest(bool enable, CompareMode mode, float alphaRef)
  1049. {
  1050. if (enable != mAlphaTest)
  1051. {
  1052. mImpl->mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, enable ? TRUE : FALSE);
  1053. mAlphaTest = enable;
  1054. }
  1055. if (enable)
  1056. {
  1057. if (mode != mAlphaTestMode)
  1058. {
  1059. mImpl->mDevice->SetRenderState(D3DRS_ALPHAFUNC, d3dCmpFunc[mode]);
  1060. mAlphaTestMode = mode;
  1061. }
  1062. if (alphaRef < 0.0f)
  1063. alphaRef = 0.0f;
  1064. if (alphaRef > 1.0f)
  1065. alphaRef = 1.0f;
  1066. if (alphaRef != mAlphaRef)
  1067. {
  1068. mImpl->mDevice->SetRenderState(D3DRS_ALPHAREF, (DWORD)(alphaRef * 255.0f));
  1069. mAlphaRef = alphaRef;
  1070. }
  1071. }
  1072. }
  1073. void Renderer::setTextureAnisotropy(unsigned level)
  1074. {
  1075. if (level < 1)
  1076. level = 1;
  1077. if (level != mTextureAnisotropy)
  1078. {
  1079. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1080. mImpl->mDevice->SetSamplerState(i, D3DSAMP_MAXANISOTROPY, level);
  1081. mTextureAnisotropy = level;
  1082. }
  1083. }
  1084. void Renderer::setBlendMode(BlendMode mode)
  1085. {
  1086. if (mode != mBlendMode)
  1087. {
  1088. static const DWORD d3dBlendEnable[] =
  1089. {
  1090. FALSE,
  1091. TRUE,
  1092. TRUE,
  1093. TRUE,
  1094. TRUE,
  1095. TRUE,
  1096. TRUE
  1097. };
  1098. static const D3DBLEND d3dSrcBlend[] =
  1099. {
  1100. D3DBLEND_ONE,
  1101. D3DBLEND_ONE,
  1102. D3DBLEND_DESTCOLOR,
  1103. D3DBLEND_SRCALPHA,
  1104. D3DBLEND_SRCALPHA,
  1105. D3DBLEND_ONE,
  1106. D3DBLEND_INVDESTALPHA,
  1107. };
  1108. static const D3DBLEND d3dDestBlend[] =
  1109. {
  1110. D3DBLEND_ZERO,
  1111. D3DBLEND_ONE,
  1112. D3DBLEND_ZERO,
  1113. D3DBLEND_INVSRCALPHA,
  1114. D3DBLEND_ONE,
  1115. D3DBLEND_INVSRCALPHA,
  1116. D3DBLEND_DESTALPHA
  1117. };
  1118. if (d3dBlendEnable[mode] != mImpl->mBlendEnable)
  1119. {
  1120. mImpl->mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, d3dBlendEnable[mode]);
  1121. mImpl->mBlendEnable = d3dBlendEnable[mode];
  1122. }
  1123. if (mImpl->mBlendEnable)
  1124. {
  1125. if (d3dSrcBlend[mode] != mImpl->mSrcBlend)
  1126. {
  1127. mImpl->mDevice->SetRenderState(D3DRS_SRCBLEND, d3dSrcBlend[mode]);
  1128. mImpl->mSrcBlend = d3dSrcBlend[mode];
  1129. }
  1130. if (d3dDestBlend[mode] != mImpl->mDestBlend)
  1131. {
  1132. mImpl->mDevice->SetRenderState(D3DRS_DESTBLEND, d3dDestBlend[mode]);
  1133. mImpl->mDestBlend = d3dDestBlend[mode];
  1134. }
  1135. }
  1136. mBlendMode = mode;
  1137. }
  1138. }
  1139. void Renderer::setColorWrite(bool enable)
  1140. {
  1141. if (enable != mColorWrite)
  1142. {
  1143. mImpl->mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, enable ? D3DCOLORWRITEENABLE_RED |
  1144. D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA : 0);
  1145. mColorWrite = enable;
  1146. }
  1147. }
  1148. void Renderer::setCullMode(CullMode mode)
  1149. {
  1150. if (mode != mCullMode)
  1151. {
  1152. static const D3DCULL d3dCullMode[] =
  1153. {
  1154. D3DCULL_NONE,
  1155. D3DCULL_CCW,
  1156. D3DCULL_CW
  1157. };
  1158. mImpl->mDevice->SetRenderState(D3DRS_CULLMODE, d3dCullMode[mode]);
  1159. mCullMode = mode;
  1160. }
  1161. }
  1162. void Renderer::setDepthBias(float constantBias, float slopeScaledBias)
  1163. {
  1164. if (constantBias != mDepthConstantBias)
  1165. {
  1166. mImpl->mDevice->SetRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&constantBias));
  1167. mDepthConstantBias = constantBias;
  1168. }
  1169. if (slopeScaledBias != mDepthSlopeScaledBias)
  1170. {
  1171. mImpl->mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&slopeScaledBias));
  1172. mDepthSlopeScaledBias = slopeScaledBias;
  1173. }
  1174. }
  1175. void Renderer::setDepthTest(CompareMode mode)
  1176. {
  1177. if (mode != mDepthTestMode)
  1178. {
  1179. mImpl->mDevice->SetRenderState(D3DRS_ZFUNC, d3dCmpFunc[mode]);
  1180. mDepthTestMode = mode;
  1181. }
  1182. }
  1183. void Renderer::setDepthWrite(bool enable)
  1184. {
  1185. if (enable != mDepthWrite)
  1186. {
  1187. mImpl->mDevice->SetRenderState(D3DRS_ZWRITEENABLE, enable ? TRUE : FALSE);
  1188. mDepthWrite = enable;
  1189. }
  1190. }
  1191. void Renderer::setFillMode(FillMode mode)
  1192. {
  1193. if (mode != mFillMode)
  1194. {
  1195. static const D3DFILLMODE d3dFillMode[] =
  1196. {
  1197. D3DFILL_SOLID,
  1198. D3DFILL_WIREFRAME
  1199. };
  1200. mImpl->mDevice->SetRenderState(D3DRS_FILLMODE, d3dFillMode[mode]);
  1201. mFillMode = mode;
  1202. }
  1203. }
  1204. void Renderer::setScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1205. {
  1206. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1207. // Disable scissor in that case to reduce state changes
  1208. if (rect == Rect::sFullRect)
  1209. enable = false;
  1210. // Check for illegal rect, disable in that case
  1211. if ((rect.mMax.mX < rect.mMin.mX) || (rect.mMax.mY < rect.mMin.mY))
  1212. enable = false;
  1213. if (enable)
  1214. {
  1215. IntVector2 rtSize(getRenderTargetDimensions());
  1216. IntVector2 viewSize(mViewport.mRight - mViewport.mLeft, mViewport.mBottom - mViewport.mTop);
  1217. IntVector2 viewPos(mViewport.mLeft, mViewport.mTop);
  1218. IntRect intRect;
  1219. int expand = borderInclusive ? 1 : 0;
  1220. intRect.mLeft = clamp((int)((rect.mMin.mX + 1.0f) * 0.5f * viewSize.mX) + viewPos.mX, 0, rtSize.mX - 1);
  1221. intRect.mTop = clamp((int)((-rect.mMax.mY + 1.0f) * 0.5f * viewSize.mY) + viewPos.mY, 0, rtSize.mY - 1);
  1222. intRect.mRight = clamp((int)((rect.mMax.mX + 1.0f) * 0.5f * viewSize.mX) + viewPos.mX + expand, 0, rtSize.mX);
  1223. intRect.mBottom = clamp((int)((-rect.mMin.mY + 1.0f) * 0.5f * viewSize.mY) + viewPos.mY + expand, 0, rtSize.mY);
  1224. if (intRect.mRight == intRect.mLeft)
  1225. intRect.mRight++;
  1226. if (intRect.mBottom == intRect.mTop)
  1227. intRect.mBottom++;
  1228. if ((intRect.mRight < intRect.mLeft) || (intRect.mBottom < intRect.mTop))
  1229. enable = false;
  1230. if ((enable) && (mScissorRect != intRect))
  1231. {
  1232. RECT d3dRect;
  1233. d3dRect.left = intRect.mLeft;
  1234. d3dRect.top = intRect.mTop;
  1235. d3dRect.right = intRect.mRight;
  1236. d3dRect.bottom = intRect.mBottom;
  1237. mImpl->mDevice->SetScissorRect(&d3dRect);
  1238. mScissorRect = intRect;
  1239. }
  1240. }
  1241. else
  1242. mScissorRect = IntRect::sZero;
  1243. if (enable != mScissorTest)
  1244. {
  1245. mImpl->mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1246. mScissorTest = enable;
  1247. }
  1248. }
  1249. void Renderer::setScissorTest(bool enable, const IntRect& rect)
  1250. {
  1251. IntVector2 rtSize(getRenderTargetDimensions());
  1252. IntVector2 viewSize(mViewport.mRight - mViewport.mLeft, mViewport.mBottom - mViewport.mTop);
  1253. IntVector2 viewPos(mViewport.mLeft, mViewport.mTop);
  1254. // Full scissor is same as disabling the test
  1255. if ((rect.mLeft <= 0) && (rect.mRight >= viewSize.mX) && (rect.mTop <= 0) && (rect.mBottom >= viewSize.mY))
  1256. enable = false;
  1257. // Check for illegal rect, disable in that case
  1258. if ((rect.mRight < rect.mLeft) || (rect.mBottom < rect.mTop))
  1259. enable = false;
  1260. if (enable)
  1261. {
  1262. IntRect intRect;
  1263. intRect.mLeft = clamp(rect.mLeft + viewPos.mX, 0, rtSize.mX - 1);
  1264. intRect.mTop = clamp(rect.mTop + viewPos.mY, 0, rtSize.mY - 1);
  1265. intRect.mRight = clamp(rect.mRight + viewPos.mX, 0, rtSize.mX);
  1266. intRect.mBottom = clamp(rect.mBottom + viewPos.mY, 0, rtSize.mY);
  1267. if (intRect.mRight == intRect.mLeft)
  1268. intRect.mRight++;
  1269. if (intRect.mBottom == intRect.mTop)
  1270. intRect.mBottom++;
  1271. if ((intRect.mRight < intRect.mLeft) || (intRect.mBottom < intRect.mTop))
  1272. enable = false;
  1273. if ((enable) && (mScissorRect != intRect))
  1274. {
  1275. RECT d3dRect;
  1276. d3dRect.left = intRect.mLeft;
  1277. d3dRect.top = intRect.mTop;
  1278. d3dRect.right = intRect.mRight;
  1279. d3dRect.bottom = intRect.mBottom;
  1280. mImpl->mDevice->SetScissorRect(&d3dRect);
  1281. mScissorRect = intRect;
  1282. }
  1283. }
  1284. else
  1285. mScissorRect = IntRect::sZero;
  1286. if (enable != mScissorTest)
  1287. {
  1288. mImpl->mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1289. mScissorTest = enable;
  1290. }
  1291. }
  1292. void Renderer::setStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned stencilMask)
  1293. {
  1294. if (enable != mStencilTest)
  1295. {
  1296. mImpl->mDevice->SetRenderState(D3DRS_STENCILENABLE, enable ? TRUE : FALSE);
  1297. mStencilTest = enable;
  1298. }
  1299. if (enable)
  1300. {
  1301. static const D3DSTENCILOP d3dStencilOp[] =
  1302. {
  1303. D3DSTENCILOP_KEEP,
  1304. D3DSTENCILOP_ZERO,
  1305. D3DSTENCILOP_REPLACE,
  1306. D3DSTENCILOP_INCR,
  1307. D3DSTENCILOP_DECR
  1308. };
  1309. if (mode != mStencilTestMode)
  1310. {
  1311. mImpl->mDevice->SetRenderState(D3DRS_STENCILFUNC, d3dCmpFunc[mode]);
  1312. mStencilTestMode = mode;
  1313. }
  1314. if (pass != mStencilPass)
  1315. {
  1316. mImpl->mDevice->SetRenderState(D3DRS_STENCILPASS, d3dStencilOp[pass]);
  1317. mStencilPass = pass;
  1318. }
  1319. if (fail != mStencilFail)
  1320. {
  1321. mImpl->mDevice->SetRenderState(D3DRS_STENCILFAIL, d3dStencilOp[fail]);
  1322. mStencilFail = fail;
  1323. }
  1324. if (zFail != mStencilZFail)
  1325. {
  1326. mImpl->mDevice->SetRenderState(D3DRS_STENCILZFAIL, d3dStencilOp[zFail]);
  1327. mStencilZFail = zFail;
  1328. }
  1329. if (stencilRef != mStencilRef)
  1330. {
  1331. mImpl->mDevice->SetRenderState(D3DRS_STENCILREF, stencilRef);
  1332. mStencilRef = stencilRef;
  1333. }
  1334. if (stencilMask != mStencilMask)
  1335. {
  1336. mImpl->mDevice->SetRenderState(D3DRS_STENCILMASK, stencilMask);
  1337. mStencilMask = stencilMask;
  1338. }
  1339. }
  1340. }
  1341. bool Renderer::setStreamFrequency(unsigned index, unsigned frequency)
  1342. {
  1343. if (index >= MAX_VERTEX_STREAMS)
  1344. {
  1345. LOGERROR("Illegal vertex stream index");
  1346. return false;
  1347. }
  1348. if (mStreamFrequency[index] != frequency)
  1349. {
  1350. mImpl->mDevice->SetStreamSourceFreq(index, frequency);
  1351. mStreamFrequency[index] = frequency;
  1352. }
  1353. return true;
  1354. }
  1355. void Renderer::resetStreamFrequencies()
  1356. {
  1357. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1358. {
  1359. if (mStreamFrequency[i] != 1)
  1360. {
  1361. mImpl->mDevice->SetStreamSourceFreq(i, 1);
  1362. mStreamFrequency[i] = 1;
  1363. }
  1364. }
  1365. }
  1366. bool Renderer::beginImmediate(PrimitiveType type, unsigned vertexCount, unsigned elementMask)
  1367. {
  1368. if (mImmediateBuffer)
  1369. {
  1370. LOGERROR("New immediate draw operation started before ending the last one");
  1371. return false;
  1372. }
  1373. if (!(elementMask & MASK_POSITION))
  1374. {
  1375. LOGERROR("Immediate draw operation must contain vertex positions");
  1376. return false;
  1377. }
  1378. if (!vertexCount)
  1379. return true;
  1380. // See if buffer exists for this vertex format. If not, create new
  1381. if (mImmediateVertexBuffers.find(elementMask) == mImmediateVertexBuffers.end())
  1382. {
  1383. VertexBuffer* newBuffer = new VertexBuffer(this, true);
  1384. unsigned size = vertexCount > IMMEDIATE_BUFFER_DEFAULT_SIZE ? vertexCount : IMMEDIATE_BUFFER_DEFAULT_SIZE;
  1385. newBuffer->setSize(size, elementMask);
  1386. mImmediateVertexBuffers[elementMask] = newBuffer;
  1387. mImmediateVertexBufferPos[elementMask] = 0;
  1388. }
  1389. // Resize buffer if it is too small
  1390. VertexBuffer* buffer = mImmediateVertexBuffers[elementMask];
  1391. if (buffer->getVertexCount() < vertexCount)
  1392. {
  1393. buffer->setSize(vertexCount, elementMask);
  1394. mImmediateVertexBufferPos[elementMask] = 0;
  1395. }
  1396. // Get the current lock position for the buffer
  1397. unsigned bufferPos = mImmediateVertexBufferPos[elementMask];
  1398. if (bufferPos + vertexCount >= buffer->getVertexCount())
  1399. bufferPos = 0;
  1400. LockMode lockMode = LOCK_DISCARD;
  1401. if (bufferPos != 0)
  1402. lockMode = LOCK_NOOVERWRITE;
  1403. // Note: the data pointer gets pre-decremented here, because the first call to defineVertex() will increment it
  1404. mImmediateDataPtr = ((unsigned char*)buffer->lock(bufferPos, vertexCount, lockMode)) - buffer->getVertexSize();
  1405. mImmediateBuffer = buffer;
  1406. mImmediateType= type;
  1407. mImmediateStartPos = bufferPos;
  1408. mImmediateVertexCount = vertexCount;
  1409. mImmediateCurrentVertex = 0;
  1410. // Store new buffer position for next lock into the same buffer
  1411. bufferPos += vertexCount;
  1412. if (bufferPos >= buffer->getVertexCount())
  1413. bufferPos = 0;
  1414. mImmediateVertexBufferPos[elementMask] = bufferPos;
  1415. return true;
  1416. }
  1417. bool Renderer::defineVertex(const Vector3& vertex)
  1418. {
  1419. if ((!mImmediateBuffer) || (mImmediateCurrentVertex >= mImmediateVertexCount))
  1420. return false;
  1421. mImmediateDataPtr += mImmediateBuffer->getVertexSize();
  1422. ++mImmediateCurrentVertex;
  1423. float* dest = (float*)(mImmediateDataPtr + mImmediateBuffer->getElementOffset(ELEMENT_POSITION));
  1424. const float* src = vertex.getData();
  1425. dest[0] = src[0];
  1426. dest[1] = src[1];
  1427. dest[2] = src[2];
  1428. return true;
  1429. }
  1430. bool Renderer::defineNormal(const Vector3& normal)
  1431. {
  1432. if ((!mImmediateBuffer) ||(!(mImmediateBuffer->getElementMask() & MASK_NORMAL)) || (!mImmediateCurrentVertex))
  1433. return false;
  1434. float* dest = (float*)(mImmediateDataPtr + mImmediateBuffer->getElementOffset(ELEMENT_NORMAL));
  1435. const float* src = normal.getData();
  1436. dest[0] = src[0];
  1437. dest[1] = src[1];
  1438. dest[2] = src[2];
  1439. return true;
  1440. }
  1441. bool Renderer::defineTexCoord(const Vector2& texCoord)
  1442. {
  1443. if ((!mImmediateBuffer) || (!(mImmediateBuffer->getElementMask() & MASK_TEXCOORD1)) || (!mImmediateCurrentVertex))
  1444. return false;
  1445. float* dest = (float*)(mImmediateDataPtr + mImmediateBuffer->getElementOffset(ELEMENT_TEXCOORD1));
  1446. const float* src = texCoord.getData();
  1447. dest[0] = src[0];
  1448. dest[1] = src[1];
  1449. return true;
  1450. }
  1451. bool Renderer::defineColor(const Color& color)
  1452. {
  1453. if ((!mImmediateBuffer) || (!(mImmediateBuffer->getElementMask() & MASK_COLOR)) || (!mImmediateCurrentVertex))
  1454. return false;
  1455. unsigned* dest = (unsigned*)(mImmediateDataPtr + mImmediateBuffer->getElementOffset(ELEMENT_COLOR));
  1456. *dest = getD3DColor(color);
  1457. return true;
  1458. }
  1459. bool Renderer::defineColor(unsigned color)
  1460. {
  1461. if ((!mImmediateBuffer) || (!(mImmediateBuffer->getElementMask() & MASK_COLOR)) || (!mImmediateCurrentVertex))
  1462. return false;
  1463. unsigned* dest = (unsigned*)(mImmediateDataPtr + mImmediateBuffer->getElementOffset(ELEMENT_COLOR));
  1464. *dest = color;
  1465. return true;
  1466. }
  1467. void Renderer::endImmediate()
  1468. {
  1469. if (mImmediateBuffer)
  1470. {
  1471. mImmediateBuffer->unlock();
  1472. setVertexBuffer(mImmediateBuffer);
  1473. draw(mImmediateType, mImmediateStartPos, mImmediateVertexCount);
  1474. mImmediateBuffer = 0;
  1475. }
  1476. }
  1477. void Renderer::setForceSM2(bool enable)
  1478. {
  1479. // Note: this only has effect before calling setMode() for the first time
  1480. mForceSM2 = enable;
  1481. }
  1482. unsigned char* Renderer::getImmediateDataPtr() const
  1483. {
  1484. if (!mImmediateBuffer)
  1485. {
  1486. LOGERROR("Immediate draw operation not started");
  1487. return 0;
  1488. }
  1489. // Pointer was pre-decremented in beginImmediate(). Undo that now
  1490. return mImmediateDataPtr + mImmediateBuffer->getVertexSize();
  1491. }
  1492. unsigned Renderer::getWindowHandle() const
  1493. {
  1494. return (unsigned)mImpl->mWindow;
  1495. }
  1496. std::vector<IntVector2> Renderer::getResolutions() const
  1497. {
  1498. std::vector<IntVector2> ret;
  1499. if (!mImpl->mInterface)
  1500. return ret;
  1501. D3DFORMAT fullscreenFormat = mImpl->getDesktopFormat();
  1502. unsigned numModes = mImpl->mInterface->GetAdapterModeCount(mImpl->mAdapter, fullscreenFormat);
  1503. D3DDISPLAYMODE displayMode;
  1504. for (unsigned i = 0; i < numModes; ++i)
  1505. {
  1506. if (FAILED(mImpl->mInterface->EnumAdapterModes(mImpl->mAdapter, fullscreenFormat, i, &displayMode)))
  1507. continue;
  1508. if (displayMode.Format != fullscreenFormat)
  1509. continue;
  1510. IntVector2 newMode(displayMode.Width, displayMode.Height);
  1511. // Check for duplicate before storing
  1512. bool unique = true;
  1513. for (unsigned j = 0; j < ret.size(); ++j)
  1514. {
  1515. if (ret[j] == newMode)
  1516. {
  1517. unique = false;
  1518. break;
  1519. }
  1520. }
  1521. if (unique)
  1522. ret.push_back(newMode);
  1523. }
  1524. return ret;
  1525. }
  1526. std::vector<int> Renderer::getMultiSampleLevels() const
  1527. {
  1528. std::vector<int> ret;
  1529. // No multisampling always supported
  1530. ret.push_back(0);
  1531. if (!mImpl->mInterface)
  1532. return ret;
  1533. for (unsigned i = (int)D3DMULTISAMPLE_2_SAMPLES; i < (int)D3DMULTISAMPLE_16_SAMPLES; ++i)
  1534. {
  1535. if (SUCCEEDED(mImpl->mInterface->CheckDeviceMultiSampleType(mImpl->mAdapter, mImpl->mDeviceType, D3DFMT_R8G8B8, FALSE,
  1536. (D3DMULTISAMPLE_TYPE)i, NULL)))
  1537. ret.push_back(i);
  1538. }
  1539. return ret;
  1540. }
  1541. VertexBuffer* Renderer::getVertexBuffer(unsigned index) const
  1542. {
  1543. return index < MAX_VERTEX_STREAMS ? mVertexBuffer[index] : 0;
  1544. }
  1545. Texture* Renderer::getTexture(unsigned index) const
  1546. {
  1547. return index < MAX_TEXTURE_UNITS ? mTexture[index] : 0;
  1548. }
  1549. RenderSurface* Renderer::getRenderTarget(unsigned index) const
  1550. {
  1551. return index < MAX_RENDERTARGETS ? mRenderTarget[index] : 0;
  1552. }
  1553. unsigned Renderer::getStreamFrequency(unsigned index) const
  1554. {
  1555. return index < MAX_VERTEX_STREAMS ? mStreamFrequency[index] : 0;
  1556. }
  1557. IntVector2 Renderer::getRenderTargetDimensions() const
  1558. {
  1559. int width, height;
  1560. if (mRenderTarget[0])
  1561. {
  1562. width = mRenderTarget[0]->getWidth();
  1563. height = mRenderTarget[0]->getHeight();
  1564. }
  1565. else
  1566. {
  1567. width = mWidth;
  1568. height = mHeight;
  1569. }
  1570. return IntVector2(width, height);
  1571. }
  1572. void Renderer::addGPUObject(GPUObject* object)
  1573. {
  1574. mGPUObjects.push_back(object);
  1575. }
  1576. void Renderer::removeGPUObject(GPUObject* object)
  1577. {
  1578. for (unsigned i = 0; i < mGPUObjects.size(); ++i)
  1579. {
  1580. if (mGPUObjects[i] == object)
  1581. {
  1582. mGPUObjects.erase(mGPUObjects.begin() + i);
  1583. return;
  1584. }
  1585. }
  1586. }
  1587. void Renderer::createWindow(int width, int height)
  1588. {
  1589. WNDCLASS wc;
  1590. wc.style = CS_HREDRAW | CS_VREDRAW;
  1591. wc.lpfnWndProc = wndProc;
  1592. wc.cbClsExtra = 0;
  1593. wc.cbWndExtra = 0;
  1594. wc.hInstance = mImpl->mInstance;
  1595. wc.hIcon = LoadIcon(0, IDI_APPLICATION);
  1596. wc.hCursor = LoadCursor(0, IDC_ARROW);
  1597. wc.hbrBackground = 0;
  1598. wc.lpszMenuName = 0;
  1599. wc.lpszClassName = "D3DWindow";
  1600. RegisterClass(&wc);
  1601. RECT rect = {0, 0, width, height};
  1602. AdjustWindowRect(&rect, windowStyle, false);
  1603. mImpl->mWindow = CreateWindow("D3DWindow", mWindowTitle.c_str(), windowStyle, CW_USEDEFAULT, CW_USEDEFAULT,
  1604. rect.right, rect.bottom, 0, 0, mImpl->mInstance, 0);
  1605. if (!mImpl->mWindow)
  1606. EXCEPTION("Could not create window");
  1607. // Save window placement
  1608. WINDOWPLACEMENT wndpl;
  1609. wndpl.length = sizeof wndpl;
  1610. if (SUCCEEDED(GetWindowPlacement(mImpl->mWindow, &wndpl)))
  1611. {
  1612. mWindowPosX = wndpl.rcNormalPosition.left;
  1613. mWindowPosY = wndpl.rcNormalPosition.top;
  1614. }
  1615. renderers[mImpl->mWindow] = this;
  1616. }
  1617. void Renderer::createInterface()
  1618. {
  1619. mImpl->mInterface = Direct3DCreate9(D3D9b_SDK_VERSION);
  1620. if (!mImpl->mInterface)
  1621. EXCEPTION("Could not create Direct3D9 interface");
  1622. if (FAILED(mImpl->mInterface->GetDeviceCaps(mImpl->mAdapter, mImpl->mDeviceType, &mImpl->mDeviceCaps)))
  1623. EXCEPTION("Could not get Direct3D capabilities");
  1624. if (FAILED(mImpl->mInterface->GetAdapterIdentifier(mImpl->mAdapter, 0, &mImpl->mAdapterIdentifier)))
  1625. EXCEPTION("Could not get Direct3D adapter identifier");
  1626. if (mImpl->mDeviceCaps.PixelShaderVersion < D3DPS_VERSION(2, 0))
  1627. EXCEPTION("Shader model 2.0 display adapter is required");
  1628. // Check supported features: Shader Model 3, deferred / light prepass rendering, hardware depth texture, shadow map,
  1629. // dummy color surface
  1630. if (!mForceSM2)
  1631. {
  1632. if ((mImpl->mDeviceCaps.VertexShaderVersion >= D3DVS_VERSION(3, 0)) && (mImpl->mDeviceCaps.PixelShaderVersion >=
  1633. D3DPS_VERSION(3, 0)))
  1634. mSM3Support = true;
  1635. }
  1636. if (mImpl->checkFormatSupport(D3DFMT_R32F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1637. {
  1638. if (mImpl->mDeviceCaps.NumSimultaneousRTs >= 3)
  1639. mDeferredSupport = true;
  1640. if (mImpl->mDeviceCaps.NumSimultaneousRTs >= 2)
  1641. mPrepassSupport = true;
  1642. }
  1643. if (mImpl->checkFormatSupport((D3DFORMAT)MAKEFOURCC('I', 'N', 'T', 'Z'), D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1644. {
  1645. // Sampling INTZ buffer directly while also using it for depth test results in performance loss on ATI GPUs
  1646. // at least on Vista/Win7 (see http://aras-p.info/texts/D3D9GPUHacks.html). So, use INTZ buffer only with
  1647. // other vendors, or on Windows XP
  1648. unsigned windowsVersion = GetVersion() & 0xff;
  1649. if ((mImpl->mAdapterIdentifier.VendorId != 0x1002) || (windowsVersion < 6))
  1650. mHardwareDepthSupport = true;
  1651. }
  1652. // Prefer NVIDIA style hardware depth compared shadow maps if available
  1653. mShadowMapFormat = D3DFMT_D16;
  1654. if (mImpl->checkFormatSupport((D3DFORMAT)mShadowMapFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1655. {
  1656. mHardwareShadowSupport = true;
  1657. // Check for hires depth support
  1658. mHiresShadowMapFormat = D3DFMT_D24X8;
  1659. if (mImpl->checkFormatSupport((D3DFORMAT)mHiresShadowMapFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1660. mHiresShadowSupport = true;
  1661. else
  1662. mHiresShadowMapFormat = mShadowMapFormat;
  1663. }
  1664. else
  1665. {
  1666. // ATI DF16 format needs manual depth compare in the shader
  1667. mShadowMapFormat = MAKEFOURCC('D', 'F', '1', '6');
  1668. if (mImpl->checkFormatSupport((D3DFORMAT)mShadowMapFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1669. {
  1670. // Check for hires depth support
  1671. mHiresShadowMapFormat = MAKEFOURCC('D', 'F', '2', '4');
  1672. if (mImpl->checkFormatSupport((D3DFORMAT)mHiresShadowMapFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1673. mHiresShadowSupport = true;
  1674. else
  1675. mHiresShadowMapFormat = mShadowMapFormat;
  1676. }
  1677. else
  1678. {
  1679. // No depth texture shadow map support -> no shadows at all
  1680. mShadowMapFormat = D3DFMT_UNKNOWN;
  1681. mHiresShadowMapFormat = D3DFMT_UNKNOWN;
  1682. }
  1683. }
  1684. // Check for Intel 4 Series with an old driver, enable manual shadow map compare in that case
  1685. if (mShadowMapFormat == D3DFMT_D16)
  1686. {
  1687. if ((mImpl->mAdapterIdentifier.VendorId == 0x8086) && (mImpl->mAdapterIdentifier.DeviceId == 0x2a42) &&
  1688. (mImpl->mAdapterIdentifier.DriverVersion.QuadPart <= 0x0007000f000a05d0ULL))
  1689. mHardwareShadowSupport = false;
  1690. }
  1691. mDummyColorFormat = D3DFMT_A8R8G8B8;
  1692. D3DFORMAT nullFormat = (D3DFORMAT)MAKEFOURCC('N', 'U', 'L', 'L');
  1693. if (mImpl->checkFormatSupport(nullFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1694. mDummyColorFormat = nullFormat;
  1695. else if (mImpl->checkFormatSupport(D3DFMT_R16F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1696. mDummyColorFormat = D3DFMT_R16F;
  1697. else if (mImpl->checkFormatSupport(D3DFMT_R5G6B5, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1698. mDummyColorFormat = D3DFMT_R5G6B5;
  1699. else if (mImpl->checkFormatSupport(D3DFMT_A4R4G4B4, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1700. mDummyColorFormat = D3DFMT_A4R4G4B4;
  1701. }
  1702. void Renderer::createDevice(unsigned adapter, unsigned deviceType)
  1703. {
  1704. DWORD behaviorFlags = 0;
  1705. if (mImpl->mDeviceCaps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
  1706. {
  1707. behaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
  1708. if (mImpl->mDeviceCaps.DevCaps & D3DDEVCAPS_PUREDEVICE)
  1709. behaviorFlags |= D3DCREATE_PUREDEVICE;
  1710. }
  1711. else
  1712. behaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  1713. if (FAILED(mImpl->mInterface->CreateDevice(
  1714. adapter, // adapter
  1715. (D3DDEVTYPE)deviceType, // device type
  1716. mImpl->mWindow, // window associated with device
  1717. behaviorFlags, // vertex processing
  1718. &mImpl->mPresentParams, // present parameters
  1719. &mImpl->mDevice))) // return created device
  1720. EXCEPTION("Could not create Direct3D device");
  1721. mImpl->mAdapter = adapter;
  1722. mImpl->mDeviceType = (D3DDEVTYPE)deviceType;
  1723. onDeviceReset();
  1724. }
  1725. void Renderer::createRenderTargets()
  1726. {
  1727. if (mMode != RENDER_FORWARD)
  1728. {
  1729. // In deferred rendering, the diffuse buffer stores diffuse albedo. In light prepass, it is used for light accumulation
  1730. if (!mDiffBuffer)
  1731. {
  1732. mDiffBuffer = new Texture2D(this, TEXTURE_RENDERTARGET);
  1733. mDiffBuffer->setSize(0, 0, D3DFMT_A8R8G8B8);
  1734. }
  1735. if (!mNormalBuffer)
  1736. {
  1737. mNormalBuffer = new Texture2D(this, TEXTURE_RENDERTARGET);
  1738. mNormalBuffer->setSize(0, 0, D3DFMT_A8R8G8B8);
  1739. }
  1740. if (!mDepthBuffer)
  1741. {
  1742. if (!mHardwareDepthSupport)
  1743. {
  1744. mDepthBuffer = new Texture2D(this, TEXTURE_RENDERTARGET);
  1745. mDepthBuffer->setSize(0, 0, D3DFMT_R32F);
  1746. }
  1747. else
  1748. {
  1749. mDepthBuffer = new Texture2D(this, TEXTURE_DEPTHSTENCIL);
  1750. mDepthBuffer->setSize(0, 0, (D3DFORMAT)MAKEFOURCC('I', 'N', 'T', 'Z'));
  1751. }
  1752. }
  1753. // If edge filtering is used, reserve screen buffer
  1754. // (later we will probably want the screen buffer reserved in any case, to do for example distortion effects,
  1755. // which will also be useful in forward rendering)
  1756. if (mMultiSample)
  1757. {
  1758. mScreenBuffer = new Texture2D(this, TEXTURE_RENDERTARGET);
  1759. mScreenBuffer->setSize(0, 0, D3DFMT_X8R8G8B8);
  1760. mScreenBuffer->setFilterMode(FILTER_BILINEAR);
  1761. }
  1762. else
  1763. mScreenBuffer.reset();
  1764. }
  1765. else
  1766. {
  1767. mDiffBuffer.reset();
  1768. mNormalBuffer.reset();
  1769. mDepthBuffer.reset();
  1770. mScreenBuffer.reset();
  1771. }
  1772. }
  1773. void Renderer::resetDevice()
  1774. {
  1775. onDeviceLost();
  1776. if (SUCCEEDED(mImpl->mDevice->Reset(&mImpl->mPresentParams)))
  1777. {
  1778. mDeviceLost = false;
  1779. onDeviceReset();
  1780. }
  1781. }
  1782. void Renderer::onDeviceLost()
  1783. {
  1784. if (mImpl->mFrameQuery)
  1785. {
  1786. mImpl->mFrameQuery->Release();
  1787. mImpl->mFrameQuery = 0;
  1788. }
  1789. if (mImpl->mDefaultColorSurface)
  1790. {
  1791. mImpl->mDefaultColorSurface->Release();
  1792. mImpl->mDefaultColorSurface = 0;
  1793. }
  1794. if (mImpl->mDefaultDepthStencilSurface)
  1795. {
  1796. if (mSystemDepthStencil)
  1797. mImpl->mDefaultDepthStencilSurface->Release();
  1798. mImpl->mDefaultDepthStencilSurface = 0;
  1799. }
  1800. for (unsigned i = 0; i < mGPUObjects.size(); ++i)
  1801. mGPUObjects[i]->onDeviceLost();
  1802. }
  1803. void Renderer::onDeviceReset()
  1804. {
  1805. resetCachedState();
  1806. // Create frame query
  1807. mImpl->mDevice->CreateQuery(D3DQUERYTYPE_EVENT, &mImpl->mFrameQuery);
  1808. // In case AutoDepthStencil is not used, depth buffering must be enabled manually
  1809. mImpl->mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
  1810. // Create deferred rendering buffers now
  1811. createRenderTargets();
  1812. for (unsigned i = 0; i < mGPUObjects.size(); ++i)
  1813. mGPUObjects[i]->onDeviceReset();
  1814. // Get default surfaces
  1815. mImpl->mDevice->GetRenderTarget(0, &mImpl->mDefaultColorSurface);
  1816. if (mImpl->mPresentParams.EnableAutoDepthStencil)
  1817. {
  1818. mImpl->mDevice->GetDepthStencilSurface(&mImpl->mDefaultDepthStencilSurface);
  1819. mSystemDepthStencil = true;
  1820. }
  1821. else
  1822. {
  1823. mImpl->mDefaultDepthStencilSurface = (IDirect3DSurface9*)mDepthBuffer->getRenderSurface()->getSurface();
  1824. mSystemDepthStencil = false;
  1825. }
  1826. mImmediateBuffer = 0;
  1827. }
  1828. void Renderer::resetCachedState()
  1829. {
  1830. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1831. mVertexBuffer[i] = 0;
  1832. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1833. {
  1834. mTexture[i] = 0;
  1835. mImpl->mMinMagFilter[i] = D3DTEXF_POINT;
  1836. mImpl->mMipFilter[i] = D3DTEXF_NONE;
  1837. mImpl->mUAddressMode[i] = D3DTADDRESS_WRAP;
  1838. mImpl->mVAddressMode[i] = D3DTADDRESS_WRAP;
  1839. mImpl->mBorderColor[i] = Color(0.0f, 0.0f, 0.0f, 0.0f);
  1840. }
  1841. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1842. {
  1843. mRenderTarget[i] = 0;
  1844. mImpl->mColorSurface[i] = 0;
  1845. }
  1846. mDepthStencil = 0;
  1847. mImpl->mDepthStencilSurface = 0;
  1848. mViewport = IntRect(0, 0, mWidth, mHeight);
  1849. mViewTexture = 0;
  1850. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1851. mStreamFrequency[i] = 0;
  1852. mIndexBuffer = 0;
  1853. mVertexDeclaration = 0;
  1854. mVertexShader = 0;
  1855. mPixelShader = 0;
  1856. mBlendMode = BLEND_REPLACE;
  1857. mAlphaTest = false;
  1858. mAlphaTestMode = CMP_ALWAYS;
  1859. mAlphaRef = 0.0f;
  1860. mTextureAnisotropy = 1;
  1861. mColorWrite = true;
  1862. mCullMode = CULL_CCW;
  1863. mDepthConstantBias = 0.0f;
  1864. mDepthSlopeScaledBias = 0.0f;
  1865. mDepthTestMode = CMP_LESSEQUAL;
  1866. mDepthWrite = true;
  1867. mFillMode = FILL_SOLID;
  1868. mScissorTest = false;
  1869. mScissorRect = IntRect::sZero;
  1870. mStencilTest = false;
  1871. mStencilTestMode = CMP_ALWAYS;
  1872. mStencilPass = OP_KEEP;
  1873. mStencilFail = OP_KEEP;
  1874. mStencilZFail = OP_KEEP;
  1875. mStencilRef = 0;
  1876. mStencilMask = M_MAX_UNSIGNED;
  1877. mImpl->mBlendEnable = FALSE;
  1878. mImpl->mSrcBlend = D3DBLEND_ONE;
  1879. mImpl->mDestBlend = D3DBLEND_ZERO;
  1880. mQueryIssued = false;
  1881. }
  1882. void Renderer::handleWindowMessage(StringHash eventType, VariantMap& eventData)
  1883. {
  1884. using namespace WindowMessage;
  1885. if (eventData[P_WINDOW].getInt() != (int)mImpl->mWindow)
  1886. return;
  1887. switch (eventData[P_MSG].getInt())
  1888. {
  1889. case WM_CLOSE:
  1890. close();
  1891. eventData[P_HANDLED] = true;
  1892. break;
  1893. case WM_DESTROY:
  1894. mClosed = true;
  1895. eventData[P_HANDLED] = true;
  1896. break;
  1897. }
  1898. }
  1899. LRESULT CALLBACK wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  1900. {
  1901. using namespace WindowMessage;
  1902. std::map<HWND, Renderer*>::const_iterator i = renderers.find(hwnd);
  1903. if (i != renderers.end())
  1904. {
  1905. VariantMap eventData;
  1906. eventData[P_WINDOW] = (int)hwnd;
  1907. eventData[P_MSG] = (int)msg;
  1908. eventData[P_WPARAM] = (int)wParam;
  1909. eventData[P_LPARAM] = (int)lParam;
  1910. eventData[P_HANDLED] = false;
  1911. i->second->sendEvent(EVENT_WINDOWMESSAGE, eventData);
  1912. if (eventData[P_HANDLED].getBool())
  1913. return 0;
  1914. }
  1915. return DefWindowProc(hwnd, msg, wParam, lParam);
  1916. }