Renderer.cpp 67 KB

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