D3D11Graphics.cpp 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662
  1. // Copyright (c) 2008-2022 the Urho3D project
  2. // License: MIT
  3. #include "../../Precompiled.h"
  4. #include "../../Core/Context.h"
  5. #include "../../Core/ProcessUtils.h"
  6. #include "../../Core/Profiler.h"
  7. #include "../../Graphics/Geometry.h"
  8. #include "../../Graphics/Graphics.h"
  9. #include "../../Graphics/GraphicsEvents.h"
  10. #include "../../Graphics/Renderer.h"
  11. #include "../../GraphicsAPI/ConstantBuffer.h"
  12. #include "../../GraphicsAPI/Direct3D11/D3D11GraphicsImpl.h"
  13. #include "../../GraphicsAPI/Direct3D11/D3D11ShaderProgram.h"
  14. #include "../../GraphicsAPI/IndexBuffer.h"
  15. #include "../../GraphicsAPI/Shader.h"
  16. #include "../../GraphicsAPI/ShaderPrecache.h"
  17. #include "../../GraphicsAPI/Texture2D.h"
  18. #include "../../GraphicsAPI/TextureCube.h"
  19. #include "../../GraphicsAPI/VertexBuffer.h"
  20. #include "../../IO/File.h"
  21. #include "../../IO/Log.h"
  22. #include "../../Resource/ResourceCache.h"
  23. #include <SDL/SDL.h>
  24. #include <SDL/SDL_syswm.h>
  25. #include "../../DebugNew.h"
  26. #ifdef _MSC_VER
  27. #pragma warning(disable:4355)
  28. #endif
  29. namespace Urho3D
  30. {
  31. static const D3D11_COMPARISON_FUNC d3dCmpFunc[] =
  32. {
  33. D3D11_COMPARISON_ALWAYS,
  34. D3D11_COMPARISON_EQUAL,
  35. D3D11_COMPARISON_NOT_EQUAL,
  36. D3D11_COMPARISON_LESS,
  37. D3D11_COMPARISON_LESS_EQUAL,
  38. D3D11_COMPARISON_GREATER,
  39. D3D11_COMPARISON_GREATER_EQUAL
  40. };
  41. static const DWORD d3dBlendEnable[] =
  42. {
  43. FALSE,
  44. TRUE,
  45. TRUE,
  46. TRUE,
  47. TRUE,
  48. TRUE,
  49. TRUE,
  50. TRUE,
  51. TRUE
  52. };
  53. static const D3D11_BLEND d3dSrcBlend[] =
  54. {
  55. D3D11_BLEND_ONE,
  56. D3D11_BLEND_ONE,
  57. D3D11_BLEND_DEST_COLOR,
  58. D3D11_BLEND_SRC_ALPHA,
  59. D3D11_BLEND_SRC_ALPHA,
  60. D3D11_BLEND_ONE,
  61. D3D11_BLEND_INV_DEST_ALPHA,
  62. D3D11_BLEND_ONE,
  63. D3D11_BLEND_SRC_ALPHA,
  64. };
  65. static const D3D11_BLEND d3dDestBlend[] =
  66. {
  67. D3D11_BLEND_ZERO,
  68. D3D11_BLEND_ONE,
  69. D3D11_BLEND_ZERO,
  70. D3D11_BLEND_INV_SRC_ALPHA,
  71. D3D11_BLEND_ONE,
  72. D3D11_BLEND_INV_SRC_ALPHA,
  73. D3D11_BLEND_DEST_ALPHA,
  74. D3D11_BLEND_ONE,
  75. D3D11_BLEND_ONE
  76. };
  77. static const D3D11_BLEND_OP d3dBlendOp[] =
  78. {
  79. D3D11_BLEND_OP_ADD,
  80. D3D11_BLEND_OP_ADD,
  81. D3D11_BLEND_OP_ADD,
  82. D3D11_BLEND_OP_ADD,
  83. D3D11_BLEND_OP_ADD,
  84. D3D11_BLEND_OP_ADD,
  85. D3D11_BLEND_OP_ADD,
  86. D3D11_BLEND_OP_REV_SUBTRACT,
  87. D3D11_BLEND_OP_REV_SUBTRACT
  88. };
  89. static const D3D11_STENCIL_OP d3dStencilOp[] =
  90. {
  91. D3D11_STENCIL_OP_KEEP,
  92. D3D11_STENCIL_OP_ZERO,
  93. D3D11_STENCIL_OP_REPLACE,
  94. D3D11_STENCIL_OP_INCR,
  95. D3D11_STENCIL_OP_DECR
  96. };
  97. static const D3D11_CULL_MODE d3dCullMode[] =
  98. {
  99. D3D11_CULL_NONE,
  100. D3D11_CULL_BACK,
  101. D3D11_CULL_FRONT
  102. };
  103. static const D3D11_FILL_MODE d3dFillMode[] =
  104. {
  105. D3D11_FILL_SOLID,
  106. D3D11_FILL_WIREFRAME,
  107. D3D11_FILL_WIREFRAME // Point fill mode not supported
  108. };
  109. static void GetD3DPrimitiveType(unsigned elementCount, PrimitiveType type, unsigned& primitiveCount,
  110. D3D_PRIMITIVE_TOPOLOGY& d3dPrimitiveType)
  111. {
  112. switch (type)
  113. {
  114. case TRIANGLE_LIST:
  115. primitiveCount = elementCount / 3;
  116. d3dPrimitiveType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
  117. break;
  118. case LINE_LIST:
  119. primitiveCount = elementCount / 2;
  120. d3dPrimitiveType = D3D_PRIMITIVE_TOPOLOGY_LINELIST;
  121. break;
  122. case POINT_LIST:
  123. primitiveCount = elementCount;
  124. d3dPrimitiveType = D3D_PRIMITIVE_TOPOLOGY_POINTLIST;
  125. break;
  126. case TRIANGLE_STRIP:
  127. primitiveCount = elementCount - 2;
  128. d3dPrimitiveType = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
  129. break;
  130. case LINE_STRIP:
  131. primitiveCount = elementCount - 1;
  132. d3dPrimitiveType = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP;
  133. break;
  134. case TRIANGLE_FAN:
  135. // Triangle fan is not supported on D3D11
  136. primitiveCount = 0;
  137. d3dPrimitiveType = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED;
  138. break;
  139. }
  140. }
  141. static HWND GetWindowHandle(SDL_Window* window)
  142. {
  143. SDL_SysWMinfo sysInfo;
  144. SDL_VERSION(&sysInfo.version);
  145. SDL_GetWindowWMInfo(window, &sysInfo);
  146. return sysInfo.info.win.window;
  147. }
  148. void Graphics::Constructor_D3D11()
  149. {
  150. impl_ = new GraphicsImpl_D3D11();
  151. position_ = IntVector2(SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED);
  152. shaderPath_ = "Shaders/HLSL/";
  153. shaderExtension_ = ".hlsl";
  154. orientations_ = "LandscapeLeft LandscapeRight";
  155. apiName_ = "D3D11";
  156. Graphics::pixelUVOffset = Vector2(0.0f, 0.0f);
  157. Graphics::gl3Support = false;
  158. SetTextureUnitMappings_D3D11();
  159. ResetCachedState_D3D11();
  160. context_->RequireSDL(SDL_INIT_VIDEO);
  161. // Register Graphics library object factories
  162. RegisterGraphicsLibrary(context_);
  163. }
  164. void Graphics::Destructor_D3D11()
  165. {
  166. {
  167. MutexLock lock(gpuObjectMutex_);
  168. // Release all GPU objects that still exist
  169. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  170. (*i)->Release();
  171. gpuObjects_.Clear();
  172. }
  173. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  174. impl->vertexDeclarations_.Clear();
  175. impl->allConstantBuffers_.Clear();
  176. for (HashMap<unsigned, ID3D11BlendState*>::Iterator i = impl->blendStates_.Begin(); i != impl->blendStates_.End(); ++i)
  177. {
  178. URHO3D_SAFE_RELEASE(i->second_);
  179. }
  180. impl->blendStates_.Clear();
  181. for (HashMap<unsigned, ID3D11DepthStencilState*>::Iterator i = impl->depthStates_.Begin(); i != impl->depthStates_.End(); ++i)
  182. {
  183. URHO3D_SAFE_RELEASE(i->second_);
  184. }
  185. impl->depthStates_.Clear();
  186. for (HashMap<unsigned, ID3D11RasterizerState*>::Iterator i = impl->rasterizerStates_.Begin();
  187. i != impl->rasterizerStates_.End(); ++i)
  188. {
  189. URHO3D_SAFE_RELEASE(i->second_);
  190. }
  191. impl->rasterizerStates_.Clear();
  192. URHO3D_SAFE_RELEASE(impl->defaultRenderTargetView_);
  193. URHO3D_SAFE_RELEASE(impl->defaultDepthStencilView_);
  194. URHO3D_SAFE_RELEASE(impl->defaultDepthTexture_);
  195. URHO3D_SAFE_RELEASE(impl->resolveTexture_);
  196. URHO3D_SAFE_RELEASE(impl->swapChain_);
  197. URHO3D_SAFE_RELEASE(impl->deviceContext_);
  198. URHO3D_SAFE_RELEASE(impl->device_);
  199. if (window_)
  200. {
  201. SDL_ShowCursor(SDL_TRUE);
  202. SDL_DestroyWindow(window_);
  203. window_ = nullptr;
  204. }
  205. delete static_cast<GraphicsImpl_D3D11*>(impl_);
  206. impl_ = nullptr;
  207. context_->ReleaseSDL();
  208. }
  209. bool Graphics::SetScreenMode_D3D11(int width, int height, const ScreenModeParams& params, bool maximize)
  210. {
  211. URHO3D_PROFILE(SetScreenMode_D3D11);
  212. // Ensure that parameters are properly filled
  213. ScreenModeParams newParams = params;
  214. AdjustScreenMode(width, height, newParams, maximize);
  215. // Find out the full screen mode display format (match desktop color depth)
  216. SDL_DisplayMode mode;
  217. SDL_GetDesktopDisplayMode(newParams.monitor_, &mode);
  218. const DXGI_FORMAT fullscreenFormat = SDL_BITSPERPIXEL(mode.format) == 16 ? DXGI_FORMAT_B5G6R5_UNORM : DXGI_FORMAT_R8G8B8A8_UNORM;
  219. // If nothing changes, do not reset the device
  220. if (width == width_ && height == height_ && newParams == screenParams_)
  221. return true;
  222. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  223. if (!window_)
  224. {
  225. if (!OpenWindow_D3D11(width, height, newParams.resizable_, newParams.borderless_))
  226. return false;
  227. }
  228. AdjustWindow_D3D11(width, height, newParams.fullscreen_, newParams.borderless_, newParams.monitor_);
  229. if (maximize)
  230. {
  231. Maximize();
  232. SDL_GetWindowSize(window_, &width, &height);
  233. }
  234. const int oldMultiSample = screenParams_.multiSample_;
  235. screenParams_ = newParams;
  236. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  237. if (!impl->device_ || screenParams_.multiSample_ != oldMultiSample)
  238. CreateDevice_D3D11(width, height);
  239. UpdateSwapChain_D3D11(width, height);
  240. // Clear the initial window contents to black
  241. Clear_D3D11(CLEAR_COLOR);
  242. impl->swapChain_->Present(0, 0);
  243. OnScreenModeChanged();
  244. return true;
  245. }
  246. void Graphics::SetSRGB_D3D11(bool enable)
  247. {
  248. bool newEnable = enable && sRGBWriteSupport_;
  249. if (newEnable != sRGB_)
  250. {
  251. sRGB_ = newEnable;
  252. if (GetImpl_D3D11()->swapChain_)
  253. {
  254. // Recreate swap chain for the new backbuffer format
  255. CreateDevice_D3D11(width_, height_);
  256. UpdateSwapChain_D3D11(width_, height_);
  257. }
  258. }
  259. }
  260. void Graphics::SetDither_D3D11(bool enable)
  261. {
  262. // No effect on Direct3D11
  263. }
  264. void Graphics::SetFlushGPU_D3D11(bool enable)
  265. {
  266. flushGPU_ = enable;
  267. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  268. if (impl->device_)
  269. {
  270. IDXGIDevice1* dxgiDevice;
  271. impl->device_->QueryInterface(IID_IDXGIDevice1, (void**)&dxgiDevice);
  272. if (dxgiDevice)
  273. {
  274. dxgiDevice->SetMaximumFrameLatency(enable ? 1 : 3);
  275. dxgiDevice->Release();
  276. }
  277. }
  278. }
  279. void Graphics::SetForceGL2_D3D11(bool enable)
  280. {
  281. // No effect on Direct3D11
  282. }
  283. void Graphics::Close_D3D11()
  284. {
  285. if (window_)
  286. {
  287. SDL_ShowCursor(SDL_TRUE);
  288. SDL_DestroyWindow(window_);
  289. window_ = nullptr;
  290. }
  291. }
  292. bool Graphics::TakeScreenShot_D3D11(Image& destImage)
  293. {
  294. URHO3D_PROFILE(TakeScreenShot_D3D11);
  295. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  296. if (!impl->device_)
  297. return false;
  298. D3D11_TEXTURE2D_DESC textureDesc;
  299. memset(&textureDesc, 0, sizeof textureDesc);
  300. textureDesc.Width = (UINT)width_;
  301. textureDesc.Height = (UINT)height_;
  302. textureDesc.MipLevels = 1;
  303. textureDesc.ArraySize = 1;
  304. textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  305. textureDesc.SampleDesc.Count = 1;
  306. textureDesc.SampleDesc.Quality = 0;
  307. textureDesc.Usage = D3D11_USAGE_STAGING;
  308. textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  309. ID3D11Texture2D* stagingTexture = nullptr;
  310. HRESULT hr = impl->device_->CreateTexture2D(&textureDesc, nullptr, &stagingTexture);
  311. if (FAILED(hr))
  312. {
  313. URHO3D_SAFE_RELEASE(stagingTexture);
  314. URHO3D_LOGD3DERROR("Could not create staging texture for screenshot", hr);
  315. return false;
  316. }
  317. ID3D11Resource* source = nullptr;
  318. impl->defaultRenderTargetView_->GetResource(&source);
  319. if (screenParams_.multiSample_ > 1)
  320. {
  321. // If backbuffer is multisampled, need another DEFAULT usage texture to resolve the data to first
  322. CreateResolveTexture_D3D11();
  323. if (!impl->resolveTexture_)
  324. {
  325. stagingTexture->Release();
  326. source->Release();
  327. return false;
  328. }
  329. impl->deviceContext_->ResolveSubresource(impl->resolveTexture_, 0, source, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
  330. impl->deviceContext_->CopyResource(stagingTexture, impl->resolveTexture_);
  331. }
  332. else
  333. impl->deviceContext_->CopyResource(stagingTexture, source);
  334. source->Release();
  335. D3D11_MAPPED_SUBRESOURCE mappedData;
  336. mappedData.pData = nullptr;
  337. hr = impl->deviceContext_->Map(stagingTexture, 0, D3D11_MAP_READ, 0, &mappedData);
  338. if (FAILED(hr) || !mappedData.pData)
  339. {
  340. URHO3D_LOGD3DERROR("Could not map staging texture for screenshot", hr);
  341. stagingTexture->Release();
  342. return false;
  343. }
  344. destImage.SetSize(width_, height_, 3);
  345. unsigned char* destData = destImage.GetData();
  346. for (int y = 0; y < height_; ++y)
  347. {
  348. unsigned char* src = (unsigned char*)mappedData.pData + y * mappedData.RowPitch;
  349. for (int x = 0; x < width_; ++x)
  350. {
  351. *destData++ = *src++;
  352. *destData++ = *src++;
  353. *destData++ = *src++;
  354. ++src;
  355. }
  356. }
  357. impl->deviceContext_->Unmap(stagingTexture, 0);
  358. stagingTexture->Release();
  359. return true;
  360. }
  361. bool Graphics::BeginFrame_D3D11()
  362. {
  363. if (!IsInitialized_D3D11())
  364. return false;
  365. // If using an external window, check it for size changes, and reset screen mode if necessary
  366. if (externalWindow_)
  367. {
  368. int width, height;
  369. SDL_GetWindowSize(window_, &width, &height);
  370. if (width != width_ || height != height_)
  371. SetMode(width, height);
  372. }
  373. else
  374. {
  375. // To prevent a loop of endless device loss and flicker, do not attempt to render when in fullscreen
  376. // and the window is minimized
  377. if (screenParams_.fullscreen_ && (SDL_GetWindowFlags(window_) & SDL_WINDOW_MINIMIZED))
  378. return false;
  379. }
  380. // Set default rendertarget and depth buffer
  381. ResetRenderTargets_D3D11();
  382. // Cleanup textures from previous frame
  383. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  384. SetTexture_D3D11(i, nullptr);
  385. numPrimitives_ = 0;
  386. numBatches_ = 0;
  387. SendEvent(E_BEGINRENDERING);
  388. return true;
  389. }
  390. void Graphics::EndFrame_D3D11()
  391. {
  392. if (!IsInitialized_D3D11())
  393. return;
  394. {
  395. URHO3D_PROFILE(Present);
  396. SendEvent(E_ENDRENDERING);
  397. GetImpl_D3D11()->swapChain_->Present(screenParams_.vsync_ ? 1 : 0, 0);
  398. }
  399. // Clean up too large scratch buffers
  400. CleanupScratchBuffers();
  401. }
  402. void Graphics::Clear_D3D11(ClearTargetFlags flags, const Color& color, float depth, unsigned stencil)
  403. {
  404. IntVector2 rtSize = GetRenderTargetDimensions_D3D11();
  405. bool oldColorWrite = colorWrite_;
  406. bool oldDepthWrite = depthWrite_;
  407. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  408. // D3D11 clear always clears the whole target regardless of viewport or scissor test settings
  409. // Emulate partial clear by rendering a quad
  410. if (!viewport_.left_ && !viewport_.top_ && viewport_.right_ == rtSize.x_ && viewport_.bottom_ == rtSize.y_)
  411. {
  412. // Make sure we use the read-write version of the depth stencil
  413. SetDepthWrite_D3D11(true);
  414. PrepareDraw_D3D11();
  415. if ((flags & CLEAR_COLOR) && impl->renderTargetViews_[0])
  416. impl->deviceContext_->ClearRenderTargetView(impl->renderTargetViews_[0], color.Data());
  417. if ((flags & (CLEAR_DEPTH | CLEAR_STENCIL)) && impl->depthStencilView_)
  418. {
  419. unsigned depthClearFlags = 0;
  420. if (flags & CLEAR_DEPTH)
  421. depthClearFlags |= D3D11_CLEAR_DEPTH;
  422. if (flags & CLEAR_STENCIL)
  423. depthClearFlags |= D3D11_CLEAR_STENCIL;
  424. impl->deviceContext_->ClearDepthStencilView(impl->depthStencilView_, depthClearFlags, depth, (UINT8)stencil);
  425. }
  426. }
  427. else
  428. {
  429. Renderer* renderer = GetSubsystem<Renderer>();
  430. if (!renderer)
  431. return;
  432. Geometry* geometry = renderer->GetQuadGeometry();
  433. Matrix3x4 model = Matrix3x4::IDENTITY;
  434. Matrix4 projection = Matrix4::IDENTITY;
  435. model.m23_ = Clamp(depth, 0.0f, 1.0f);
  436. SetBlendMode_D3D11(BLEND_REPLACE);
  437. SetColorWrite_D3D11(flags & CLEAR_COLOR);
  438. SetCullMode_D3D11(CULL_NONE);
  439. SetDepthTest_D3D11(CMP_ALWAYS);
  440. SetDepthWrite_D3D11(flags & CLEAR_DEPTH);
  441. SetFillMode_D3D11(FILL_SOLID);
  442. SetScissorTest_D3D11(false);
  443. SetStencilTest_D3D11(flags & CLEAR_STENCIL, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, stencil);
  444. SetShaders_D3D11(GetShader_D3D11(VS, "ClearFramebuffer"), GetShader_D3D11(PS, "ClearFramebuffer"));
  445. SetShaderParameter_D3D11(VSP_MODEL, model);
  446. SetShaderParameter_D3D11(VSP_VIEWPROJ, projection);
  447. SetShaderParameter_D3D11(PSP_MATDIFFCOLOR, color);
  448. geometry->Draw(this);
  449. SetStencilTest_D3D11(false);
  450. ClearParameterSources_D3D11();
  451. }
  452. // Restore color & depth write state now
  453. SetColorWrite_D3D11(oldColorWrite);
  454. SetDepthWrite_D3D11(oldDepthWrite);
  455. }
  456. bool Graphics::ResolveToTexture_D3D11(Texture2D* destination, const IntRect& viewport)
  457. {
  458. if (!destination || !destination->GetRenderSurface())
  459. return false;
  460. URHO3D_PROFILE(ResolveToTexture_D3D11);
  461. IntRect vpCopy = viewport;
  462. if (vpCopy.right_ <= vpCopy.left_)
  463. vpCopy.right_ = vpCopy.left_ + 1;
  464. if (vpCopy.bottom_ <= vpCopy.top_)
  465. vpCopy.bottom_ = vpCopy.top_ + 1;
  466. D3D11_BOX srcBox;
  467. srcBox.left = Clamp(vpCopy.left_, 0, width_);
  468. srcBox.top = Clamp(vpCopy.top_, 0, height_);
  469. srcBox.right = Clamp(vpCopy.right_, 0, width_);
  470. srcBox.bottom = Clamp(vpCopy.bottom_, 0, height_);
  471. srcBox.front = 0;
  472. srcBox.back = 1;
  473. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  474. ID3D11Resource* source = nullptr;
  475. const bool resolve = screenParams_.multiSample_ > 1;
  476. impl->defaultRenderTargetView_->GetResource(&source);
  477. if (!resolve)
  478. {
  479. if (!srcBox.left && !srcBox.top && srcBox.right == width_ && srcBox.bottom == height_)
  480. impl->deviceContext_->CopyResource((ID3D11Resource*)destination->GetGPUObject(), source);
  481. else
  482. impl->deviceContext_->CopySubresourceRegion((ID3D11Resource*)destination->GetGPUObject(), 0, 0, 0, 0, source, 0, &srcBox);
  483. }
  484. else
  485. {
  486. if (!srcBox.left && !srcBox.top && srcBox.right == width_ && srcBox.bottom == height_)
  487. {
  488. impl->deviceContext_->ResolveSubresource((ID3D11Resource*)destination->GetGPUObject(), 0, source, 0, (DXGI_FORMAT)
  489. destination->GetFormat());
  490. }
  491. else
  492. {
  493. CreateResolveTexture_D3D11();
  494. if (impl->resolveTexture_)
  495. {
  496. impl->deviceContext_->ResolveSubresource(impl->resolveTexture_, 0, source, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
  497. impl->deviceContext_->CopySubresourceRegion((ID3D11Resource*)destination->GetGPUObject(), 0, 0, 0, 0, impl->resolveTexture_, 0, &srcBox);
  498. }
  499. }
  500. }
  501. source->Release();
  502. return true;
  503. }
  504. bool Graphics::ResolveToTexture_D3D11(Texture2D* texture)
  505. {
  506. if (!texture)
  507. return false;
  508. RenderSurface* surface = texture->GetRenderSurface();
  509. if (!surface)
  510. return false;
  511. texture->SetResolveDirty(false);
  512. surface->SetResolveDirty(false);
  513. ID3D11Resource* source = (ID3D11Resource*)texture->GetGPUObject();
  514. ID3D11Resource* dest = (ID3D11Resource*)texture->GetResolveTexture();
  515. if (!source || !dest)
  516. return false;
  517. GetImpl_D3D11()->deviceContext_->ResolveSubresource(dest, 0, source, 0, (DXGI_FORMAT)texture->GetFormat());
  518. return true;
  519. }
  520. bool Graphics::ResolveToTexture_D3D11(TextureCube* texture)
  521. {
  522. if (!texture)
  523. return false;
  524. texture->SetResolveDirty(false);
  525. ID3D11Resource* source = (ID3D11Resource*)texture->GetGPUObject();
  526. ID3D11Resource* dest = (ID3D11Resource*)texture->GetResolveTexture();
  527. if (!source || !dest)
  528. return false;
  529. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  530. {
  531. // Resolve only the surface(s) that were actually rendered to
  532. RenderSurface* surface = texture->GetRenderSurface((CubeMapFace)i);
  533. if (!surface->IsResolveDirty())
  534. continue;
  535. surface->SetResolveDirty(false);
  536. unsigned subResource = D3D11CalcSubresource(0, i, texture->GetLevels());
  537. GetImpl_D3D11()->deviceContext_->ResolveSubresource(dest, subResource, source, subResource, (DXGI_FORMAT)texture->GetFormat());
  538. }
  539. return true;
  540. }
  541. void Graphics::Draw_D3D11(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  542. {
  543. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  544. if (!vertexCount || !impl->shaderProgram_)
  545. return;
  546. PrepareDraw_D3D11();
  547. unsigned primitiveCount;
  548. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  549. if (fillMode_ == FILL_POINT)
  550. type = POINT_LIST;
  551. GetD3DPrimitiveType(vertexCount, type, primitiveCount, d3dPrimitiveType);
  552. if (d3dPrimitiveType != primitiveType_)
  553. {
  554. impl->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  555. primitiveType_ = d3dPrimitiveType;
  556. }
  557. impl->deviceContext_->Draw(vertexCount, vertexStart);
  558. numPrimitives_ += primitiveCount;
  559. ++numBatches_;
  560. }
  561. void Graphics::Draw_D3D11(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  562. {
  563. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  564. if (!vertexCount || !impl->shaderProgram_)
  565. return;
  566. PrepareDraw_D3D11();
  567. unsigned primitiveCount;
  568. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  569. if (fillMode_ == FILL_POINT)
  570. type = POINT_LIST;
  571. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  572. if (d3dPrimitiveType != primitiveType_)
  573. {
  574. impl->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  575. primitiveType_ = d3dPrimitiveType;
  576. }
  577. impl->deviceContext_->DrawIndexed(indexCount, indexStart, 0);
  578. numPrimitives_ += primitiveCount;
  579. ++numBatches_;
  580. }
  581. void Graphics::Draw_D3D11(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned baseVertexIndex, unsigned minVertex, unsigned vertexCount)
  582. {
  583. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  584. if (!vertexCount || !impl->shaderProgram_)
  585. return;
  586. PrepareDraw_D3D11();
  587. unsigned primitiveCount;
  588. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  589. if (fillMode_ == FILL_POINT)
  590. type = POINT_LIST;
  591. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  592. if (d3dPrimitiveType != primitiveType_)
  593. {
  594. impl->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  595. primitiveType_ = d3dPrimitiveType;
  596. }
  597. impl->deviceContext_->DrawIndexed(indexCount, indexStart, baseVertexIndex);
  598. numPrimitives_ += primitiveCount;
  599. ++numBatches_;
  600. }
  601. void Graphics::DrawInstanced_D3D11(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount,
  602. unsigned instanceCount)
  603. {
  604. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  605. if (!indexCount || !instanceCount || !impl->shaderProgram_)
  606. return;
  607. PrepareDraw_D3D11();
  608. unsigned primitiveCount;
  609. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  610. if (fillMode_ == FILL_POINT)
  611. type = POINT_LIST;
  612. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  613. if (d3dPrimitiveType != primitiveType_)
  614. {
  615. impl->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  616. primitiveType_ = d3dPrimitiveType;
  617. }
  618. impl->deviceContext_->DrawIndexedInstanced(indexCount, instanceCount, indexStart, 0, 0);
  619. numPrimitives_ += instanceCount * primitiveCount;
  620. ++numBatches_;
  621. }
  622. void Graphics::DrawInstanced_D3D11(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned baseVertexIndex, unsigned minVertex, unsigned vertexCount,
  623. unsigned instanceCount)
  624. {
  625. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  626. if (!indexCount || !instanceCount || !impl->shaderProgram_)
  627. return;
  628. PrepareDraw_D3D11();
  629. unsigned primitiveCount;
  630. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  631. if (fillMode_ == FILL_POINT)
  632. type = POINT_LIST;
  633. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  634. if (d3dPrimitiveType != primitiveType_)
  635. {
  636. impl->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  637. primitiveType_ = d3dPrimitiveType;
  638. }
  639. impl->deviceContext_->DrawIndexedInstanced(indexCount, instanceCount, indexStart, baseVertexIndex, 0);
  640. numPrimitives_ += instanceCount * primitiveCount;
  641. ++numBatches_;
  642. }
  643. void Graphics::SetVertexBuffer_D3D11(VertexBuffer* buffer)
  644. {
  645. // Note: this is not multi-instance safe
  646. static PODVector<VertexBuffer*> vertexBuffers(1);
  647. vertexBuffers[0] = buffer;
  648. SetVertexBuffers_D3D11(vertexBuffers);
  649. }
  650. bool Graphics::SetVertexBuffers_D3D11(const PODVector<VertexBuffer*>& buffers, unsigned instanceOffset)
  651. {
  652. if (buffers.Size() > MAX_VERTEX_STREAMS)
  653. {
  654. URHO3D_LOGERROR("Too many vertex buffers");
  655. return false;
  656. }
  657. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  658. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  659. {
  660. VertexBuffer* buffer = nullptr;
  661. bool changed = false;
  662. buffer = i < buffers.Size() ? buffers[i] : nullptr;
  663. if (buffer)
  664. {
  665. const PODVector<VertexElement>& elements = buffer->GetElements();
  666. // Check if buffer has per-instance data
  667. bool hasInstanceData = elements.Size() && elements[0].perInstance_;
  668. unsigned offset = hasInstanceData ? instanceOffset * buffer->GetVertexSize() : 0;
  669. if (buffer != vertexBuffers_[i] || offset != impl->vertexOffsets_[i])
  670. {
  671. vertexBuffers_[i] = buffer;
  672. impl->vertexBuffers_[i] = (ID3D11Buffer*)buffer->GetGPUObject();
  673. impl->vertexSizes_[i] = buffer->GetVertexSize();
  674. impl->vertexOffsets_[i] = offset;
  675. changed = true;
  676. }
  677. }
  678. else if (vertexBuffers_[i])
  679. {
  680. vertexBuffers_[i] = nullptr;
  681. impl->vertexBuffers_[i] = nullptr;
  682. impl->vertexSizes_[i] = 0;
  683. impl->vertexOffsets_[i] = 0;
  684. changed = true;
  685. }
  686. if (changed)
  687. {
  688. impl->vertexDeclarationDirty_ = true;
  689. if (impl->firstDirtyVB_ == M_MAX_UNSIGNED)
  690. impl->firstDirtyVB_ = impl->lastDirtyVB_ = i;
  691. else
  692. {
  693. if (i < impl->firstDirtyVB_)
  694. impl->firstDirtyVB_ = i;
  695. if (i > impl->lastDirtyVB_)
  696. impl->lastDirtyVB_ = i;
  697. }
  698. }
  699. }
  700. return true;
  701. }
  702. bool Graphics::SetVertexBuffers_D3D11(const Vector<SharedPtr<VertexBuffer>>& buffers, unsigned instanceOffset)
  703. {
  704. return SetVertexBuffers_D3D11(reinterpret_cast<const PODVector<VertexBuffer*>&>(buffers), instanceOffset);
  705. }
  706. void Graphics::SetIndexBuffer_D3D11(IndexBuffer* buffer)
  707. {
  708. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  709. if (buffer != indexBuffer_)
  710. {
  711. if (buffer)
  712. impl->deviceContext_->IASetIndexBuffer((ID3D11Buffer*)buffer->GetGPUObject(),
  713. buffer->GetIndexSize() == sizeof(unsigned short) ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  714. else
  715. impl->deviceContext_->IASetIndexBuffer(nullptr, DXGI_FORMAT_UNKNOWN, 0);
  716. indexBuffer_ = buffer;
  717. }
  718. }
  719. void Graphics::SetShaders_D3D11(ShaderVariation* vs, ShaderVariation* ps)
  720. {
  721. // Switch to the clip plane variations if necessary
  722. if (useClipPlane_)
  723. {
  724. if (vs)
  725. vs = vs->GetOwner()->GetVariation(VS, vs->GetDefinesClipPlane());
  726. if (ps)
  727. ps = ps->GetOwner()->GetVariation(PS, ps->GetDefinesClipPlane());
  728. }
  729. if (vs == vertexShader_ && ps == pixelShader_)
  730. return;
  731. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  732. if (vs != vertexShader_)
  733. {
  734. // Create the shader now if not yet created. If already attempted, do not retry
  735. if (vs && !vs->GetGPUObject())
  736. {
  737. if (vs->GetCompilerOutput().Empty())
  738. {
  739. URHO3D_PROFILE(CompileVertexShader);
  740. bool success = vs->Create();
  741. if (!success)
  742. {
  743. URHO3D_LOGERROR("Failed to compile vertex shader " + vs->GetFullName() + ":\n" + vs->GetCompilerOutput());
  744. vs = nullptr;
  745. }
  746. }
  747. else
  748. vs = nullptr;
  749. }
  750. impl->deviceContext_->VSSetShader((ID3D11VertexShader*)(vs ? vs->GetGPUObject() : nullptr), nullptr, 0);
  751. vertexShader_ = vs;
  752. impl->vertexDeclarationDirty_ = true;
  753. }
  754. if (ps != pixelShader_)
  755. {
  756. if (ps && !ps->GetGPUObject())
  757. {
  758. if (ps->GetCompilerOutput().Empty())
  759. {
  760. URHO3D_PROFILE(CompilePixelShader);
  761. bool success = ps->Create();
  762. if (!success)
  763. {
  764. URHO3D_LOGERROR("Failed to compile pixel shader " + ps->GetFullName() + ":\n" + ps->GetCompilerOutput());
  765. ps = nullptr;
  766. }
  767. }
  768. else
  769. ps = nullptr;
  770. }
  771. impl->deviceContext_->PSSetShader((ID3D11PixelShader*)(ps ? ps->GetGPUObject() : nullptr), nullptr, 0);
  772. pixelShader_ = ps;
  773. }
  774. // Update current shader parameters & constant buffers
  775. if (vertexShader_ && pixelShader_)
  776. {
  777. Pair<ShaderVariation*, ShaderVariation*> key = MakePair(vertexShader_, pixelShader_);
  778. ShaderProgramMap_D3D11::Iterator i = impl->shaderPrograms_.Find(key);
  779. if (i != impl->shaderPrograms_.End())
  780. impl->shaderProgram_ = i->second_.Get();
  781. else
  782. {
  783. ShaderProgram_D3D11* newProgram = impl->shaderPrograms_[key] = new ShaderProgram_D3D11(this, vertexShader_, pixelShader_);
  784. impl->shaderProgram_ = newProgram;
  785. }
  786. bool vsBuffersChanged = false;
  787. bool psBuffersChanged = false;
  788. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  789. {
  790. ID3D11Buffer* vsBuffer = impl->shaderProgram_->vsConstantBuffers_[i] ? (ID3D11Buffer*)impl->shaderProgram_->vsConstantBuffers_[i]->
  791. GetGPUObject() : nullptr;
  792. if (vsBuffer != impl->constantBuffers_[VS][i])
  793. {
  794. impl->constantBuffers_[VS][i] = vsBuffer;
  795. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  796. vsBuffersChanged = true;
  797. }
  798. ID3D11Buffer* psBuffer = impl->shaderProgram_->psConstantBuffers_[i] ? (ID3D11Buffer*)impl->shaderProgram_->psConstantBuffers_[i]->
  799. GetGPUObject() : nullptr;
  800. if (psBuffer != impl->constantBuffers_[PS][i])
  801. {
  802. impl->constantBuffers_[PS][i] = psBuffer;
  803. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  804. psBuffersChanged = true;
  805. }
  806. }
  807. if (vsBuffersChanged)
  808. impl->deviceContext_->VSSetConstantBuffers(0, MAX_SHADER_PARAMETER_GROUPS, &impl->constantBuffers_[VS][0]);
  809. if (psBuffersChanged)
  810. impl->deviceContext_->PSSetConstantBuffers(0, MAX_SHADER_PARAMETER_GROUPS, &impl->constantBuffers_[PS][0]);
  811. }
  812. else
  813. impl->shaderProgram_ = nullptr;
  814. // Store shader combination if shader dumping in progress
  815. if (shaderPrecache_)
  816. shaderPrecache_->StoreShaders(vertexShader_, pixelShader_);
  817. // Update clip plane parameter if necessary
  818. if (useClipPlane_)
  819. SetShaderParameter_D3D11(VSP_CLIPPLANE, clipPlane_);
  820. }
  821. void Graphics::SetShaderParameter_D3D11(StringHash param, const float* data, unsigned count)
  822. {
  823. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  824. HashMap<StringHash, ShaderParameter>::Iterator i;
  825. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  826. return;
  827. ConstantBuffer* buffer = i->second_.bufferPtr_;
  828. if (!buffer->IsDirty())
  829. impl->dirtyConstantBuffers_.Push(buffer);
  830. buffer->SetParameter(i->second_.offset_, (unsigned)(count * sizeof(float)), data);
  831. }
  832. void Graphics::SetShaderParameter_D3D11(StringHash param, float value)
  833. {
  834. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  835. HashMap<StringHash, ShaderParameter>::Iterator i;
  836. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  837. return;
  838. ConstantBuffer* buffer = i->second_.bufferPtr_;
  839. if (!buffer->IsDirty())
  840. impl->dirtyConstantBuffers_.Push(buffer);
  841. buffer->SetParameter(i->second_.offset_, sizeof(float), &value);
  842. }
  843. void Graphics::SetShaderParameter_D3D11(StringHash param, int value)
  844. {
  845. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  846. HashMap<StringHash, ShaderParameter>::Iterator i;
  847. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  848. return;
  849. ConstantBuffer* buffer = i->second_.bufferPtr_;
  850. if (!buffer->IsDirty())
  851. impl->dirtyConstantBuffers_.Push(buffer);
  852. buffer->SetParameter(i->second_.offset_, sizeof(int), &value);
  853. }
  854. void Graphics::SetShaderParameter_D3D11(StringHash param, bool value)
  855. {
  856. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  857. HashMap<StringHash, ShaderParameter>::Iterator i;
  858. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  859. return;
  860. ConstantBuffer* buffer = i->second_.bufferPtr_;
  861. if (!buffer->IsDirty())
  862. impl->dirtyConstantBuffers_.Push(buffer);
  863. buffer->SetParameter(i->second_.offset_, sizeof(bool), &value);
  864. }
  865. void Graphics::SetShaderParameter_D3D11(StringHash param, const Color& color)
  866. {
  867. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  868. HashMap<StringHash, ShaderParameter>::Iterator i;
  869. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  870. return;
  871. ConstantBuffer* buffer = i->second_.bufferPtr_;
  872. if (!buffer->IsDirty())
  873. impl->dirtyConstantBuffers_.Push(buffer);
  874. buffer->SetParameter(i->second_.offset_, sizeof(Color), &color);
  875. }
  876. void Graphics::SetShaderParameter_D3D11(StringHash param, const Vector2& vector)
  877. {
  878. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  879. HashMap<StringHash, ShaderParameter>::Iterator i;
  880. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  881. return;
  882. ConstantBuffer* buffer = i->second_.bufferPtr_;
  883. if (!buffer->IsDirty())
  884. impl->dirtyConstantBuffers_.Push(buffer);
  885. buffer->SetParameter(i->second_.offset_, sizeof(Vector2), &vector);
  886. }
  887. void Graphics::SetShaderParameter_D3D11(StringHash param, const Matrix3& matrix)
  888. {
  889. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  890. HashMap<StringHash, ShaderParameter>::Iterator i;
  891. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  892. return;
  893. ConstantBuffer* buffer = i->second_.bufferPtr_;
  894. if (!buffer->IsDirty())
  895. impl->dirtyConstantBuffers_.Push(buffer);
  896. buffer->SetVector3ArrayParameter(i->second_.offset_, 3, &matrix);
  897. }
  898. void Graphics::SetShaderParameter_D3D11(StringHash param, const Vector3& vector)
  899. {
  900. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  901. HashMap<StringHash, ShaderParameter>::Iterator i;
  902. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  903. return;
  904. ConstantBuffer* buffer = i->second_.bufferPtr_;
  905. if (!buffer->IsDirty())
  906. impl->dirtyConstantBuffers_.Push(buffer);
  907. buffer->SetParameter(i->second_.offset_, sizeof(Vector3), &vector);
  908. }
  909. void Graphics::SetShaderParameter_D3D11(StringHash param, const Matrix4& matrix)
  910. {
  911. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  912. HashMap<StringHash, ShaderParameter>::Iterator i;
  913. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  914. return;
  915. ConstantBuffer* buffer = i->second_.bufferPtr_;
  916. if (!buffer->IsDirty())
  917. impl->dirtyConstantBuffers_.Push(buffer);
  918. buffer->SetParameter(i->second_.offset_, sizeof(Matrix4), &matrix);
  919. }
  920. void Graphics::SetShaderParameter_D3D11(StringHash param, const Vector4& vector)
  921. {
  922. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  923. HashMap<StringHash, ShaderParameter>::Iterator i;
  924. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  925. return;
  926. ConstantBuffer* buffer = i->second_.bufferPtr_;
  927. if (!buffer->IsDirty())
  928. impl->dirtyConstantBuffers_.Push(buffer);
  929. buffer->SetParameter(i->second_.offset_, sizeof(Vector4), &vector);
  930. }
  931. void Graphics::SetShaderParameter_D3D11(StringHash param, const Matrix3x4& matrix)
  932. {
  933. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  934. HashMap<StringHash, ShaderParameter>::Iterator i;
  935. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  936. return;
  937. ConstantBuffer* buffer = i->second_.bufferPtr_;
  938. if (!buffer->IsDirty())
  939. impl->dirtyConstantBuffers_.Push(buffer);
  940. buffer->SetParameter(i->second_.offset_, sizeof(Matrix3x4), &matrix);
  941. }
  942. bool Graphics::NeedParameterUpdate_D3D11(ShaderParameterGroup group, const void* source)
  943. {
  944. if ((unsigned)(size_t)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  945. {
  946. shaderParameterSources_[group] = source;
  947. return true;
  948. }
  949. else
  950. return false;
  951. }
  952. bool Graphics::HasShaderParameter_D3D11(StringHash param)
  953. {
  954. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  955. return impl->shaderProgram_ && impl->shaderProgram_->parameters_.Find(param) != impl->shaderProgram_->parameters_.End();
  956. }
  957. bool Graphics::HasTextureUnit_D3D11(TextureUnit unit)
  958. {
  959. return (vertexShader_ && vertexShader_->HasTextureUnit(unit)) || (pixelShader_ && pixelShader_->HasTextureUnit(unit));
  960. }
  961. void Graphics::ClearParameterSource_D3D11(ShaderParameterGroup group)
  962. {
  963. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  964. }
  965. void Graphics::ClearParameterSources_D3D11()
  966. {
  967. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  968. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  969. }
  970. void Graphics::ClearTransformSources_D3D11()
  971. {
  972. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  973. shaderParameterSources_[SP_OBJECT] = (const void*)M_MAX_UNSIGNED;
  974. }
  975. void Graphics::SetTexture_D3D11(unsigned index, Texture* texture)
  976. {
  977. if (index >= MAX_TEXTURE_UNITS)
  978. return;
  979. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  980. if (texture)
  981. {
  982. if (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture)
  983. texture = texture->GetBackupTexture();
  984. else
  985. {
  986. // Resolve multisampled texture now as necessary
  987. if (texture->GetMultiSample() > 1 && texture->GetAutoResolve() && texture->IsResolveDirty())
  988. {
  989. if (texture->GetType() == Texture2D::GetTypeStatic())
  990. ResolveToTexture_D3D11(static_cast<Texture2D*>(texture));
  991. if (texture->GetType() == TextureCube::GetTypeStatic())
  992. ResolveToTexture_D3D11(static_cast<TextureCube*>(texture));
  993. }
  994. }
  995. if (texture && texture->GetLevelsDirty())
  996. texture->RegenerateLevels();
  997. }
  998. if (texture && texture->GetParametersDirty())
  999. {
  1000. texture->UpdateParameters();
  1001. textures_[index] = nullptr; // Force reassign
  1002. }
  1003. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1004. if (texture != textures_[index])
  1005. {
  1006. if (impl->firstDirtyTexture_ == M_MAX_UNSIGNED)
  1007. impl->firstDirtyTexture_ = impl->lastDirtyTexture_ = index;
  1008. else
  1009. {
  1010. if (index < impl->firstDirtyTexture_)
  1011. impl->firstDirtyTexture_ = index;
  1012. if (index > impl->lastDirtyTexture_)
  1013. impl->lastDirtyTexture_ = index;
  1014. }
  1015. textures_[index] = texture;
  1016. impl->shaderResourceViews_[index] = texture ? (ID3D11ShaderResourceView*)texture->GetShaderResourceView() : nullptr;
  1017. impl->samplers_[index] = texture ? (ID3D11SamplerState*)texture->GetSampler() : nullptr;
  1018. impl->texturesDirty_ = true;
  1019. }
  1020. }
  1021. void Graphics::SetDefaultTextureFilterMode_D3D11(TextureFilterMode mode)
  1022. {
  1023. if (mode != defaultTextureFilterMode_)
  1024. {
  1025. defaultTextureFilterMode_ = mode;
  1026. SetTextureParametersDirty_D3D11();
  1027. }
  1028. }
  1029. void Graphics::SetDefaultTextureAnisotropy_D3D11(unsigned level)
  1030. {
  1031. level = Max(level, 1U);
  1032. if (level != defaultTextureAnisotropy_)
  1033. {
  1034. defaultTextureAnisotropy_ = level;
  1035. SetTextureParametersDirty_D3D11();
  1036. }
  1037. }
  1038. void Graphics::SetTextureParametersDirty_D3D11()
  1039. {
  1040. MutexLock lock(gpuObjectMutex_);
  1041. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1042. {
  1043. Texture* texture = dynamic_cast<Texture*>(*i);
  1044. if (texture)
  1045. texture->SetParametersDirty();
  1046. }
  1047. }
  1048. void Graphics::ResetRenderTargets_D3D11()
  1049. {
  1050. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1051. SetRenderTarget_D3D11(i, (RenderSurface*)nullptr);
  1052. SetDepthStencil_D3D11((RenderSurface*)nullptr);
  1053. SetViewport_D3D11(IntRect(0, 0, width_, height_));
  1054. }
  1055. void Graphics::ResetRenderTarget_D3D11(unsigned index)
  1056. {
  1057. SetRenderTarget_D3D11(index, (RenderSurface*)nullptr);
  1058. }
  1059. void Graphics::ResetDepthStencil_D3D11()
  1060. {
  1061. SetDepthStencil_D3D11((RenderSurface*)nullptr);
  1062. }
  1063. void Graphics::SetRenderTarget_D3D11(unsigned index, RenderSurface* renderTarget)
  1064. {
  1065. if (index >= MAX_RENDERTARGETS)
  1066. return;
  1067. if (renderTarget != renderTargets_[index])
  1068. {
  1069. renderTargets_[index] = renderTarget;
  1070. GetImpl_D3D11()->renderTargetsDirty_ = true;
  1071. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1072. if (renderTarget)
  1073. {
  1074. Texture* parentTexture = renderTarget->GetParentTexture();
  1075. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1076. {
  1077. if (textures_[i] == parentTexture)
  1078. SetTexture_D3D11(i, textures_[i]->GetBackupTexture());
  1079. }
  1080. // If multisampled, mark the texture & surface needing resolve
  1081. if (parentTexture->GetMultiSample() > 1 && parentTexture->GetAutoResolve())
  1082. {
  1083. parentTexture->SetResolveDirty(true);
  1084. renderTarget->SetResolveDirty(true);
  1085. }
  1086. // If mipmapped, mark the levels needing regeneration
  1087. if (parentTexture->GetLevels() > 1)
  1088. parentTexture->SetLevelsDirty();
  1089. }
  1090. }
  1091. }
  1092. void Graphics::SetRenderTarget_D3D11(unsigned index, Texture2D* texture)
  1093. {
  1094. RenderSurface* renderTarget = nullptr;
  1095. if (texture)
  1096. renderTarget = texture->GetRenderSurface();
  1097. SetRenderTarget_D3D11(index, renderTarget);
  1098. }
  1099. void Graphics::SetDepthStencil_D3D11(RenderSurface* depthStencil)
  1100. {
  1101. if (depthStencil != depthStencil_)
  1102. {
  1103. depthStencil_ = depthStencil;
  1104. GetImpl_D3D11()->renderTargetsDirty_ = true;
  1105. }
  1106. }
  1107. void Graphics::SetDepthStencil_D3D11(Texture2D* texture)
  1108. {
  1109. RenderSurface* depthStencil = nullptr;
  1110. if (texture)
  1111. depthStencil = texture->GetRenderSurface();
  1112. SetDepthStencil_D3D11(depthStencil);
  1113. // Constant depth bias depends on the bitdepth
  1114. GetImpl_D3D11()->rasterizerStateDirty_ = true;
  1115. }
  1116. void Graphics::SetViewport_D3D11(const IntRect& rect)
  1117. {
  1118. IntVector2 size = GetRenderTargetDimensions_D3D11();
  1119. IntRect rectCopy = rect;
  1120. if (rectCopy.right_ <= rectCopy.left_)
  1121. rectCopy.right_ = rectCopy.left_ + 1;
  1122. if (rectCopy.bottom_ <= rectCopy.top_)
  1123. rectCopy.bottom_ = rectCopy.top_ + 1;
  1124. rectCopy.left_ = Clamp(rectCopy.left_, 0, size.x_);
  1125. rectCopy.top_ = Clamp(rectCopy.top_, 0, size.y_);
  1126. rectCopy.right_ = Clamp(rectCopy.right_, 0, size.x_);
  1127. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, size.y_);
  1128. static D3D11_VIEWPORT d3dViewport;
  1129. d3dViewport.TopLeftX = (float)rectCopy.left_;
  1130. d3dViewport.TopLeftY = (float)rectCopy.top_;
  1131. d3dViewport.Width = (float)(rectCopy.right_ - rectCopy.left_);
  1132. d3dViewport.Height = (float)(rectCopy.bottom_ - rectCopy.top_);
  1133. d3dViewport.MinDepth = 0.0f;
  1134. d3dViewport.MaxDepth = 1.0f;
  1135. GetImpl_D3D11()->deviceContext_->RSSetViewports(1, &d3dViewport);
  1136. viewport_ = rectCopy;
  1137. // Disable scissor test, needs to be re-enabled by the user
  1138. SetScissorTest_D3D11(false);
  1139. }
  1140. void Graphics::SetBlendMode_D3D11(BlendMode mode, bool alphaToCoverage)
  1141. {
  1142. if (mode != blendMode_ || alphaToCoverage != alphaToCoverage_)
  1143. {
  1144. blendMode_ = mode;
  1145. alphaToCoverage_ = alphaToCoverage;
  1146. GetImpl_D3D11()->blendStateDirty_ = true;
  1147. }
  1148. }
  1149. void Graphics::SetColorWrite_D3D11(bool enable)
  1150. {
  1151. if (enable != colorWrite_)
  1152. {
  1153. colorWrite_ = enable;
  1154. GetImpl_D3D11()->blendStateDirty_ = true;
  1155. }
  1156. }
  1157. void Graphics::SetCullMode_D3D11(CullMode mode)
  1158. {
  1159. if (mode != cullMode_)
  1160. {
  1161. cullMode_ = mode;
  1162. GetImpl_D3D11()->rasterizerStateDirty_ = true;
  1163. }
  1164. }
  1165. void Graphics::SetDepthBias_D3D11(float constantBias, float slopeScaledBias)
  1166. {
  1167. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1168. {
  1169. constantDepthBias_ = constantBias;
  1170. slopeScaledDepthBias_ = slopeScaledBias;
  1171. GetImpl_D3D11()->rasterizerStateDirty_ = true;
  1172. }
  1173. }
  1174. void Graphics::SetDepthTest_D3D11(CompareMode mode)
  1175. {
  1176. if (mode != depthTestMode_)
  1177. {
  1178. depthTestMode_ = mode;
  1179. GetImpl_D3D11()->depthStateDirty_ = true;
  1180. }
  1181. }
  1182. void Graphics::SetDepthWrite_D3D11(bool enable)
  1183. {
  1184. if (enable != depthWrite_)
  1185. {
  1186. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1187. depthWrite_ = enable;
  1188. impl->depthStateDirty_ = true;
  1189. // Also affects whether a read-only version of depth-stencil should be bound, to allow sampling
  1190. impl->renderTargetsDirty_ = true;
  1191. }
  1192. }
  1193. void Graphics::SetFillMode_D3D11(FillMode mode)
  1194. {
  1195. if (mode != fillMode_)
  1196. {
  1197. fillMode_ = mode;
  1198. GetImpl_D3D11()->rasterizerStateDirty_ = true;
  1199. }
  1200. }
  1201. void Graphics::SetLineAntiAlias_D3D11(bool enable)
  1202. {
  1203. if (enable != lineAntiAlias_)
  1204. {
  1205. lineAntiAlias_ = enable;
  1206. GetImpl_D3D11()->rasterizerStateDirty_ = true;
  1207. }
  1208. }
  1209. void Graphics::SetScissorTest_D3D11(bool enable, const Rect& rect, bool borderInclusive)
  1210. {
  1211. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1212. // Disable scissor in that case to reduce state changes
  1213. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1214. enable = false;
  1215. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1216. if (enable)
  1217. {
  1218. IntVector2 rtSize(GetRenderTargetDimensions_D3D11());
  1219. IntVector2 viewSize(viewport_.Size());
  1220. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1221. IntRect intRect;
  1222. int expand = borderInclusive ? 1 : 0;
  1223. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1224. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1225. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1226. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1227. if (intRect.right_ == intRect.left_)
  1228. intRect.right_++;
  1229. if (intRect.bottom_ == intRect.top_)
  1230. intRect.bottom_++;
  1231. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1232. enable = false;
  1233. if (enable && intRect != scissorRect_)
  1234. {
  1235. scissorRect_ = intRect;
  1236. impl->scissorRectDirty_ = true;
  1237. }
  1238. }
  1239. if (enable != scissorTest_)
  1240. {
  1241. scissorTest_ = enable;
  1242. impl->rasterizerStateDirty_ = true;
  1243. }
  1244. }
  1245. void Graphics::SetScissorTest_D3D11(bool enable, const IntRect& rect)
  1246. {
  1247. IntVector2 rtSize(GetRenderTargetDimensions_D3D11());
  1248. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1249. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1250. if (enable)
  1251. {
  1252. IntRect intRect;
  1253. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1254. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1255. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1256. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1257. if (intRect.right_ == intRect.left_)
  1258. intRect.right_++;
  1259. if (intRect.bottom_ == intRect.top_)
  1260. intRect.bottom_++;
  1261. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1262. enable = false;
  1263. if (enable && intRect != scissorRect_)
  1264. {
  1265. scissorRect_ = intRect;
  1266. impl->scissorRectDirty_ = true;
  1267. }
  1268. }
  1269. if (enable != scissorTest_)
  1270. {
  1271. scissorTest_ = enable;
  1272. impl->rasterizerStateDirty_ = true;
  1273. }
  1274. }
  1275. void Graphics::SetStencilTest_D3D11(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef,
  1276. unsigned compareMask, unsigned writeMask)
  1277. {
  1278. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1279. if (enable != stencilTest_)
  1280. {
  1281. stencilTest_ = enable;
  1282. impl->depthStateDirty_ = true;
  1283. }
  1284. if (enable)
  1285. {
  1286. if (mode != stencilTestMode_)
  1287. {
  1288. stencilTestMode_ = mode;
  1289. impl->depthStateDirty_ = true;
  1290. }
  1291. if (pass != stencilPass_)
  1292. {
  1293. stencilPass_ = pass;
  1294. impl->depthStateDirty_ = true;
  1295. }
  1296. if (fail != stencilFail_)
  1297. {
  1298. stencilFail_ = fail;
  1299. impl->depthStateDirty_ = true;
  1300. }
  1301. if (zFail != stencilZFail_)
  1302. {
  1303. stencilZFail_ = zFail;
  1304. impl->depthStateDirty_ = true;
  1305. }
  1306. if (compareMask != stencilCompareMask_)
  1307. {
  1308. stencilCompareMask_ = compareMask;
  1309. impl->depthStateDirty_ = true;
  1310. }
  1311. if (writeMask != stencilWriteMask_)
  1312. {
  1313. stencilWriteMask_ = writeMask;
  1314. impl->depthStateDirty_ = true;
  1315. }
  1316. if (stencilRef != stencilRef_)
  1317. {
  1318. stencilRef_ = stencilRef;
  1319. impl->stencilRefDirty_ = true;
  1320. impl->depthStateDirty_ = true;
  1321. }
  1322. }
  1323. }
  1324. void Graphics::SetClipPlane_D3D11(bool enable, const Plane& clipPlane, const Matrix3x4& view, const Matrix4& projection)
  1325. {
  1326. useClipPlane_ = enable;
  1327. if (enable)
  1328. {
  1329. Matrix4 viewProj = projection * view;
  1330. clipPlane_ = clipPlane.Transformed(viewProj).ToVector4();
  1331. SetShaderParameter_D3D11(VSP_CLIPPLANE, clipPlane_);
  1332. }
  1333. }
  1334. bool Graphics::IsInitialized_D3D11() const
  1335. {
  1336. return window_ != nullptr && GetImpl_D3D11()->GetDevice() != nullptr;
  1337. }
  1338. PODVector<int> Graphics::GetMultiSampleLevels_D3D11() const
  1339. {
  1340. PODVector<int> ret;
  1341. ret.Push(1);
  1342. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1343. if (impl->device_)
  1344. {
  1345. for (unsigned i = 2; i <= 16; ++i)
  1346. {
  1347. if (impl->CheckMultiSampleSupport(sRGB_ ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM, i))
  1348. ret.Push(i);
  1349. }
  1350. }
  1351. return ret;
  1352. }
  1353. unsigned Graphics::GetFormat_D3D11(CompressedFormat format) const
  1354. {
  1355. switch (format)
  1356. {
  1357. case CF_RGBA:
  1358. return DXGI_FORMAT_R8G8B8A8_UNORM;
  1359. case CF_DXT1:
  1360. return DXGI_FORMAT_BC1_UNORM;
  1361. case CF_DXT3:
  1362. return DXGI_FORMAT_BC2_UNORM;
  1363. case CF_DXT5:
  1364. return DXGI_FORMAT_BC3_UNORM;
  1365. default:
  1366. return 0;
  1367. }
  1368. }
  1369. ShaderVariation* Graphics::GetShader_D3D11(ShaderType type, const String& name, const String& defines) const
  1370. {
  1371. return GetShader_D3D11(type, name.CString(), defines.CString());
  1372. }
  1373. ShaderVariation* Graphics::GetShader_D3D11(ShaderType type, const char* name, const char* defines) const
  1374. {
  1375. if (lastShaderName_ != name || !lastShader_)
  1376. {
  1377. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1378. String fullShaderName = shaderPath_ + name + shaderExtension_;
  1379. // Try to reduce repeated error log prints because of missing shaders
  1380. if (lastShaderName_ == name && !cache->Exists(fullShaderName))
  1381. return nullptr;
  1382. lastShader_ = cache->GetResource<Shader>(fullShaderName);
  1383. lastShaderName_ = name;
  1384. }
  1385. return lastShader_ ? lastShader_->GetVariation(type, defines) : nullptr;
  1386. }
  1387. VertexBuffer* Graphics::GetVertexBuffer_D3D11(unsigned index) const
  1388. {
  1389. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : nullptr;
  1390. }
  1391. ShaderProgram_D3D11* Graphics::GetShaderProgram_D3D11() const
  1392. {
  1393. return GetImpl_D3D11()->shaderProgram_;
  1394. }
  1395. TextureUnit Graphics::GetTextureUnit_D3D11(const String& name)
  1396. {
  1397. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1398. if (i != textureUnits_.End())
  1399. return i->second_;
  1400. else
  1401. return MAX_TEXTURE_UNITS;
  1402. }
  1403. const String& Graphics::GetTextureUnitName_D3D11(TextureUnit unit)
  1404. {
  1405. for (HashMap<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1406. {
  1407. if (i->second_ == unit)
  1408. return i->first_;
  1409. }
  1410. return String::EMPTY;
  1411. }
  1412. Texture* Graphics::GetTexture_D3D11(unsigned index) const
  1413. {
  1414. return index < MAX_TEXTURE_UNITS ? textures_[index] : nullptr;
  1415. }
  1416. RenderSurface* Graphics::GetRenderTarget_D3D11(unsigned index) const
  1417. {
  1418. return index < MAX_RENDERTARGETS ? renderTargets_[index] : nullptr;
  1419. }
  1420. IntVector2 Graphics::GetRenderTargetDimensions_D3D11() const
  1421. {
  1422. int width, height;
  1423. if (renderTargets_[0])
  1424. {
  1425. width = renderTargets_[0]->GetWidth();
  1426. height = renderTargets_[0]->GetHeight();
  1427. }
  1428. else if (depthStencil_) // Depth-only rendering
  1429. {
  1430. width = depthStencil_->GetWidth();
  1431. height = depthStencil_->GetHeight();
  1432. }
  1433. else
  1434. {
  1435. width = width_;
  1436. height = height_;
  1437. }
  1438. return IntVector2(width, height);
  1439. }
  1440. bool Graphics::GetDither_D3D11() const
  1441. {
  1442. return false;
  1443. }
  1444. bool Graphics::IsDeviceLost_D3D11() const
  1445. {
  1446. // Direct3D11 graphics context is never considered lost
  1447. /// \todo The device could be lost in case of graphics adapters getting disabled during runtime. This is not currently handled
  1448. return false;
  1449. }
  1450. void Graphics::OnWindowResized_D3D11()
  1451. {
  1452. if (!GetImpl_D3D11()->device_ || !window_)
  1453. return;
  1454. int newWidth, newHeight;
  1455. SDL_GetWindowSize(window_, &newWidth, &newHeight);
  1456. if (newWidth == width_ && newHeight == height_)
  1457. return;
  1458. UpdateSwapChain_D3D11(newWidth, newHeight);
  1459. // Reset rendertargets and viewport for the new screen size
  1460. ResetRenderTargets_D3D11();
  1461. URHO3D_LOGDEBUGF("Window was resized to %dx%d", width_, height_);
  1462. using namespace ScreenMode;
  1463. VariantMap& eventData = GetEventDataMap();
  1464. eventData[P_WIDTH] = width_;
  1465. eventData[P_HEIGHT] = height_;
  1466. eventData[P_FULLSCREEN] = screenParams_.fullscreen_;
  1467. eventData[P_RESIZABLE] = screenParams_.resizable_;
  1468. eventData[P_BORDERLESS] = screenParams_.borderless_;
  1469. eventData[P_HIGHDPI] = screenParams_.highDPI_;
  1470. SendEvent(E_SCREENMODE, eventData);
  1471. }
  1472. void Graphics::OnWindowMoved_D3D11()
  1473. {
  1474. if (!GetImpl_D3D11()->device_ || !window_ || screenParams_.fullscreen_)
  1475. return;
  1476. int newX, newY;
  1477. SDL_GetWindowPosition(window_, &newX, &newY);
  1478. if (newX == position_.x_ && newY == position_.y_)
  1479. return;
  1480. position_.x_ = newX;
  1481. position_.y_ = newY;
  1482. URHO3D_LOGTRACEF("Window was moved to %d,%d", position_.x_, position_.y_);
  1483. using namespace WindowPos;
  1484. VariantMap& eventData = GetEventDataMap();
  1485. eventData[P_X] = position_.x_;
  1486. eventData[P_Y] = position_.y_;
  1487. SendEvent(E_WINDOWPOS, eventData);
  1488. }
  1489. void Graphics::CleanupShaderPrograms_D3D11(ShaderVariation* variation)
  1490. {
  1491. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1492. for (ShaderProgramMap_D3D11::Iterator i = impl->shaderPrograms_.Begin(); i != impl->shaderPrograms_.End();)
  1493. {
  1494. if (i->first_.first_ == variation || i->first_.second_ == variation)
  1495. i = impl->shaderPrograms_.Erase(i);
  1496. else
  1497. ++i;
  1498. }
  1499. if (vertexShader_ == variation || pixelShader_ == variation)
  1500. impl->shaderProgram_ = nullptr;
  1501. }
  1502. ConstantBuffer* Graphics::GetOrCreateConstantBuffer_D3D11(ShaderType type, unsigned index, unsigned size)
  1503. {
  1504. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1505. // Ensure that different shader types and index slots get unique buffers, even if the size is same
  1506. unsigned key = type | (index << 1) | (size << 4);
  1507. ConstantBufferMap::Iterator i = impl->allConstantBuffers_.Find(key);
  1508. if (i != impl->allConstantBuffers_.End())
  1509. return i->second_.Get();
  1510. else
  1511. {
  1512. SharedPtr<ConstantBuffer> newConstantBuffer(new ConstantBuffer(context_));
  1513. newConstantBuffer->SetSize(size);
  1514. impl->allConstantBuffers_[key] = newConstantBuffer;
  1515. return newConstantBuffer.Get();
  1516. }
  1517. }
  1518. unsigned Graphics::GetAlphaFormat_D3D11()
  1519. {
  1520. return DXGI_FORMAT_A8_UNORM;
  1521. }
  1522. unsigned Graphics::GetLuminanceFormat_D3D11()
  1523. {
  1524. // Note: not same sampling behavior as on D3D9; need to sample the R channel only
  1525. return DXGI_FORMAT_R8_UNORM;
  1526. }
  1527. unsigned Graphics::GetLuminanceAlphaFormat_D3D11()
  1528. {
  1529. // Note: not same sampling behavior as on D3D9; need to sample the RG channels
  1530. return DXGI_FORMAT_R8G8_UNORM;
  1531. }
  1532. unsigned Graphics::GetRGBFormat_D3D11()
  1533. {
  1534. return DXGI_FORMAT_R8G8B8A8_UNORM;
  1535. }
  1536. unsigned Graphics::GetRGBAFormat_D3D11()
  1537. {
  1538. return DXGI_FORMAT_R8G8B8A8_UNORM;
  1539. }
  1540. unsigned Graphics::GetRGBA16Format_D3D11()
  1541. {
  1542. return DXGI_FORMAT_R16G16B16A16_UNORM;
  1543. }
  1544. unsigned Graphics::GetRGBAFloat16Format_D3D11()
  1545. {
  1546. return DXGI_FORMAT_R16G16B16A16_FLOAT;
  1547. }
  1548. unsigned Graphics::GetRGBAFloat32Format_D3D11()
  1549. {
  1550. return DXGI_FORMAT_R32G32B32A32_FLOAT;
  1551. }
  1552. unsigned Graphics::GetRG16Format_D3D11()
  1553. {
  1554. return DXGI_FORMAT_R16G16_UNORM;
  1555. }
  1556. unsigned Graphics::GetRGFloat16Format_D3D11()
  1557. {
  1558. return DXGI_FORMAT_R16G16_FLOAT;
  1559. }
  1560. unsigned Graphics::GetRGFloat32Format_D3D11()
  1561. {
  1562. return DXGI_FORMAT_R32G32_FLOAT;
  1563. }
  1564. unsigned Graphics::GetFloat16Format_D3D11()
  1565. {
  1566. return DXGI_FORMAT_R16_FLOAT;
  1567. }
  1568. unsigned Graphics::GetFloat32Format_D3D11()
  1569. {
  1570. return DXGI_FORMAT_R32_FLOAT;
  1571. }
  1572. unsigned Graphics::GetLinearDepthFormat_D3D11()
  1573. {
  1574. return DXGI_FORMAT_R32_FLOAT;
  1575. }
  1576. unsigned Graphics::GetDepthStencilFormat_D3D11()
  1577. {
  1578. return DXGI_FORMAT_R24G8_TYPELESS;
  1579. }
  1580. unsigned Graphics::GetReadableDepthFormat_D3D11()
  1581. {
  1582. return DXGI_FORMAT_R24G8_TYPELESS;
  1583. }
  1584. unsigned Graphics::GetFormat_D3D11(const String& formatName)
  1585. {
  1586. String nameLower = formatName.ToLower().Trimmed();
  1587. if (nameLower == "a")
  1588. return GetAlphaFormat_D3D11();
  1589. if (nameLower == "l")
  1590. return GetLuminanceFormat_D3D11();
  1591. if (nameLower == "la")
  1592. return GetLuminanceAlphaFormat_D3D11();
  1593. if (nameLower == "rgb")
  1594. return GetRGBFormat_D3D11();
  1595. if (nameLower == "rgba")
  1596. return GetRGBAFormat_D3D11();
  1597. if (nameLower == "rgba16")
  1598. return GetRGBA16Format_D3D11();
  1599. if (nameLower == "rgba16f")
  1600. return GetRGBAFloat16Format_D3D11();
  1601. if (nameLower == "rgba32f")
  1602. return GetRGBAFloat32Format_D3D11();
  1603. if (nameLower == "rg16")
  1604. return GetRG16Format_D3D11();
  1605. if (nameLower == "rg16f")
  1606. return GetRGFloat16Format_D3D11();
  1607. if (nameLower == "rg32f")
  1608. return GetRGFloat32Format_D3D11();
  1609. if (nameLower == "r16f")
  1610. return GetFloat16Format_D3D11();
  1611. if (nameLower == "r32f" || nameLower == "float")
  1612. return GetFloat32Format_D3D11();
  1613. if (nameLower == "lineardepth" || nameLower == "depth")
  1614. return GetLinearDepthFormat_D3D11();
  1615. if (nameLower == "d24s8")
  1616. return GetDepthStencilFormat_D3D11();
  1617. if (nameLower == "readabledepth" || nameLower == "hwdepth")
  1618. return GetReadableDepthFormat_D3D11();
  1619. return GetRGBFormat_D3D11();
  1620. }
  1621. unsigned Graphics::GetMaxBones_D3D11()
  1622. {
  1623. return 128;
  1624. }
  1625. bool Graphics::GetGL3Support_D3D11()
  1626. {
  1627. return false;
  1628. }
  1629. bool Graphics::OpenWindow_D3D11(int width, int height, bool resizable, bool borderless)
  1630. {
  1631. if (!externalWindow_)
  1632. {
  1633. unsigned flags = 0;
  1634. if (resizable)
  1635. flags |= SDL_WINDOW_RESIZABLE;
  1636. if (borderless)
  1637. flags |= SDL_WINDOW_BORDERLESS;
  1638. window_ = SDL_CreateWindow(windowTitle_.CString(), position_.x_, position_.y_, width, height, flags);
  1639. }
  1640. else
  1641. window_ = SDL_CreateWindowFrom(externalWindow_, 0);
  1642. if (!window_)
  1643. {
  1644. URHO3D_LOGERRORF("Could not create window, root cause: '%s'", SDL_GetError());
  1645. return false;
  1646. }
  1647. SDL_GetWindowPosition(window_, &position_.x_, &position_.y_);
  1648. CreateWindowIcon();
  1649. return true;
  1650. }
  1651. void Graphics::AdjustWindow_D3D11(int& newWidth, int& newHeight, bool& newFullscreen, bool& newBorderless, int& monitor)
  1652. {
  1653. if (!externalWindow_)
  1654. {
  1655. // Keep current window position because it may change in intermediate callbacks
  1656. const IntVector2 oldPosition = position_;
  1657. bool reposition = false;
  1658. bool resizePostponed = false;
  1659. if (!newWidth || !newHeight)
  1660. {
  1661. SDL_MaximizeWindow(window_);
  1662. SDL_GetWindowSize(window_, &newWidth, &newHeight);
  1663. }
  1664. else
  1665. {
  1666. SDL_Rect display_rect;
  1667. SDL_GetDisplayBounds(monitor, &display_rect);
  1668. reposition = newFullscreen || (newBorderless && newWidth >= display_rect.w && newHeight >= display_rect.h);
  1669. if (reposition)
  1670. {
  1671. // Reposition the window on the specified monitor if it's supposed to cover the entire monitor
  1672. SDL_SetWindowPosition(window_, display_rect.x, display_rect.y);
  1673. }
  1674. // Postpone window resize if exiting fullscreen to avoid redundant resolution change
  1675. if (!newFullscreen && screenParams_.fullscreen_)
  1676. resizePostponed = true;
  1677. else
  1678. SDL_SetWindowSize(window_, newWidth, newHeight);
  1679. }
  1680. // Turn off window fullscreen mode so it gets repositioned to the correct monitor
  1681. SDL_SetWindowFullscreen(window_, SDL_FALSE);
  1682. // Hack fix: on SDL 2.0.4 a fullscreen->windowed transition results in a maximized window when the D3D device is reset, so hide before
  1683. if (!newFullscreen) SDL_HideWindow(window_);
  1684. SDL_SetWindowFullscreen(window_, newFullscreen ? SDL_WINDOW_FULLSCREEN : 0);
  1685. SDL_SetWindowBordered(window_, newBorderless ? SDL_FALSE : SDL_TRUE);
  1686. if (!newFullscreen) SDL_ShowWindow(window_);
  1687. // Resize now if was postponed
  1688. if (resizePostponed)
  1689. SDL_SetWindowSize(window_, newWidth, newHeight);
  1690. // Ensure that window keeps its position
  1691. if (!reposition)
  1692. SDL_SetWindowPosition(window_, oldPosition.x_, oldPosition.y_);
  1693. else
  1694. position_ = oldPosition;
  1695. }
  1696. else
  1697. {
  1698. // If external window, must ask its dimensions instead of trying to set them
  1699. SDL_GetWindowSize(window_, &newWidth, &newHeight);
  1700. newFullscreen = false;
  1701. }
  1702. }
  1703. bool Graphics::CreateDevice_D3D11(int width, int height)
  1704. {
  1705. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1706. // Device needs only to be created once
  1707. if (!impl->device_)
  1708. {
  1709. HRESULT hr = D3D11CreateDevice(
  1710. nullptr,
  1711. D3D_DRIVER_TYPE_HARDWARE,
  1712. nullptr,
  1713. 0,
  1714. nullptr,
  1715. 0,
  1716. D3D11_SDK_VERSION,
  1717. &impl->device_,
  1718. nullptr,
  1719. &impl->deviceContext_
  1720. );
  1721. if (FAILED(hr))
  1722. {
  1723. URHO3D_SAFE_RELEASE(impl->device_);
  1724. URHO3D_SAFE_RELEASE(impl->deviceContext_);
  1725. URHO3D_LOGD3DERROR("Failed to create D3D11 device", hr);
  1726. return false;
  1727. }
  1728. CheckFeatureSupport_D3D11();
  1729. // Set the flush mode now as the device has been created
  1730. SetFlushGPU_D3D11(flushGPU_);
  1731. }
  1732. // Check that multisample level is supported
  1733. PODVector<int> multiSampleLevels = GetMultiSampleLevels_D3D11();
  1734. if (!multiSampleLevels.Contains(screenParams_.multiSample_))
  1735. screenParams_.multiSample_ = 1;
  1736. // Create swap chain. Release old if necessary
  1737. if (impl->swapChain_)
  1738. {
  1739. impl->swapChain_->Release();
  1740. impl->swapChain_ = nullptr;
  1741. }
  1742. IDXGIDevice* dxgiDevice = nullptr;
  1743. impl->device_->QueryInterface(IID_IDXGIDevice, (void**)&dxgiDevice);
  1744. IDXGIAdapter* dxgiAdapter = nullptr;
  1745. dxgiDevice->GetParent(IID_IDXGIAdapter, (void**)&dxgiAdapter);
  1746. IDXGIFactory* dxgiFactory = nullptr;
  1747. dxgiAdapter->GetParent(IID_IDXGIFactory, (void**)&dxgiFactory);
  1748. DXGI_RATIONAL refreshRateRational = {};
  1749. IDXGIOutput* dxgiOutput = nullptr;
  1750. UINT numModes = 0;
  1751. dxgiAdapter->EnumOutputs(screenParams_.monitor_, &dxgiOutput);
  1752. dxgiOutput->GetDisplayModeList(sRGB_ ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM, 0, &numModes, 0);
  1753. // find the best matching refresh rate with the specified resolution
  1754. if (numModes > 0)
  1755. {
  1756. DXGI_MODE_DESC* modes = new DXGI_MODE_DESC[numModes];
  1757. dxgiOutput->GetDisplayModeList(sRGB_ ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM, 0, &numModes, modes);
  1758. unsigned bestMatchingRateIndex = -1;
  1759. unsigned bestError = M_MAX_UNSIGNED;
  1760. for (unsigned i = 0; i < numModes; ++i)
  1761. {
  1762. if (width != modes[i].Width || height != modes[i].Height)
  1763. continue;
  1764. float rate = (float)modes[i].RefreshRate.Numerator / modes[i].RefreshRate.Denominator;
  1765. unsigned error = (unsigned)(Abs(rate - screenParams_.refreshRate_));
  1766. if (error < bestError)
  1767. {
  1768. bestMatchingRateIndex = i;
  1769. bestError = error;
  1770. }
  1771. }
  1772. if (bestMatchingRateIndex != -1)
  1773. {
  1774. refreshRateRational.Numerator = modes[bestMatchingRateIndex].RefreshRate.Numerator;
  1775. refreshRateRational.Denominator = modes[bestMatchingRateIndex].RefreshRate.Denominator;
  1776. }
  1777. delete[] modes;
  1778. }
  1779. dxgiOutput->Release();
  1780. DXGI_SWAP_CHAIN_DESC swapChainDesc;
  1781. memset(&swapChainDesc, 0, sizeof swapChainDesc);
  1782. swapChainDesc.BufferCount = 1;
  1783. swapChainDesc.BufferDesc.Width = (UINT)width;
  1784. swapChainDesc.BufferDesc.Height = (UINT)height;
  1785. swapChainDesc.BufferDesc.Format = sRGB_ ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM;
  1786. swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  1787. swapChainDesc.BufferDesc.RefreshRate.Numerator = refreshRateRational.Numerator;
  1788. swapChainDesc.BufferDesc.RefreshRate.Denominator = refreshRateRational.Denominator;
  1789. swapChainDesc.OutputWindow = GetWindowHandle(window_);
  1790. swapChainDesc.SampleDesc.Count = static_cast<UINT>(screenParams_.multiSample_);
  1791. swapChainDesc.SampleDesc.Quality = impl->GetMultiSampleQuality(swapChainDesc.BufferDesc.Format, screenParams_.multiSample_);
  1792. swapChainDesc.Windowed = TRUE;
  1793. swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
  1794. HRESULT hr = dxgiFactory->CreateSwapChain(impl->device_, &swapChainDesc, &impl->swapChain_);
  1795. // After creating the swap chain, disable automatic Alt-Enter fullscreen/windowed switching
  1796. // (the application will switch manually if it wants to)
  1797. dxgiFactory->MakeWindowAssociation(GetWindowHandle(window_), DXGI_MWA_NO_ALT_ENTER);
  1798. #ifdef URHO3D_LOGGING
  1799. DXGI_ADAPTER_DESC desc;
  1800. dxgiAdapter->GetDesc(&desc);
  1801. String adapterDesc(desc.Description);
  1802. URHO3D_LOGINFO("Adapter used " + adapterDesc);
  1803. #endif
  1804. dxgiFactory->Release();
  1805. dxgiAdapter->Release();
  1806. dxgiDevice->Release();
  1807. if (FAILED(hr))
  1808. {
  1809. URHO3D_SAFE_RELEASE(impl->swapChain_);
  1810. URHO3D_LOGD3DERROR("Failed to create D3D11 swap chain", hr);
  1811. return false;
  1812. }
  1813. return true;
  1814. }
  1815. bool Graphics::UpdateSwapChain_D3D11(int width, int height)
  1816. {
  1817. bool success = true;
  1818. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1819. ID3D11RenderTargetView* nullView = nullptr;
  1820. impl->deviceContext_->OMSetRenderTargets(1, &nullView, nullptr);
  1821. if (impl->defaultRenderTargetView_)
  1822. {
  1823. impl->defaultRenderTargetView_->Release();
  1824. impl->defaultRenderTargetView_ = nullptr;
  1825. }
  1826. if (impl->defaultDepthStencilView_)
  1827. {
  1828. impl->defaultDepthStencilView_->Release();
  1829. impl->defaultDepthStencilView_ = nullptr;
  1830. }
  1831. if (impl->defaultDepthTexture_)
  1832. {
  1833. impl->defaultDepthTexture_->Release();
  1834. impl->defaultDepthTexture_ = nullptr;
  1835. }
  1836. if (impl->resolveTexture_)
  1837. {
  1838. impl->resolveTexture_->Release();
  1839. impl->resolveTexture_ = nullptr;
  1840. }
  1841. impl->depthStencilView_ = nullptr;
  1842. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1843. impl->renderTargetViews_[i] = nullptr;
  1844. impl->renderTargetsDirty_ = true;
  1845. impl->swapChain_->ResizeBuffers(1, (UINT)width, (UINT)height, DXGI_FORMAT_UNKNOWN, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH);
  1846. // Create default rendertarget view representing the backbuffer
  1847. ID3D11Texture2D* backbufferTexture;
  1848. HRESULT hr = impl->swapChain_->GetBuffer(0, IID_ID3D11Texture2D, (void**)&backbufferTexture);
  1849. if (FAILED(hr))
  1850. {
  1851. URHO3D_SAFE_RELEASE(backbufferTexture);
  1852. URHO3D_LOGD3DERROR("Failed to get backbuffer texture", hr);
  1853. success = false;
  1854. }
  1855. else
  1856. {
  1857. hr = impl->device_->CreateRenderTargetView(backbufferTexture, nullptr, &impl->defaultRenderTargetView_);
  1858. backbufferTexture->Release();
  1859. if (FAILED(hr))
  1860. {
  1861. URHO3D_SAFE_RELEASE(impl->defaultRenderTargetView_);
  1862. URHO3D_LOGD3DERROR("Failed to create backbuffer rendertarget view", hr);
  1863. success = false;
  1864. }
  1865. }
  1866. // Create default depth-stencil texture and view
  1867. D3D11_TEXTURE2D_DESC depthDesc;
  1868. memset(&depthDesc, 0, sizeof depthDesc);
  1869. depthDesc.Width = (UINT)width;
  1870. depthDesc.Height = (UINT)height;
  1871. depthDesc.MipLevels = 1;
  1872. depthDesc.ArraySize = 1;
  1873. depthDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
  1874. depthDesc.SampleDesc.Count = static_cast<UINT>(screenParams_.multiSample_);
  1875. depthDesc.SampleDesc.Quality = impl->GetMultiSampleQuality(depthDesc.Format, screenParams_.multiSample_);
  1876. depthDesc.Usage = D3D11_USAGE_DEFAULT;
  1877. depthDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  1878. depthDesc.CPUAccessFlags = 0;
  1879. depthDesc.MiscFlags = 0;
  1880. hr = impl->device_->CreateTexture2D(&depthDesc, nullptr, &impl->defaultDepthTexture_);
  1881. if (FAILED(hr))
  1882. {
  1883. URHO3D_SAFE_RELEASE(impl->defaultDepthTexture_);
  1884. URHO3D_LOGD3DERROR("Failed to create backbuffer depth-stencil texture", hr);
  1885. success = false;
  1886. }
  1887. else
  1888. {
  1889. hr = impl->device_->CreateDepthStencilView(impl->defaultDepthTexture_, nullptr, &impl->defaultDepthStencilView_);
  1890. if (FAILED(hr))
  1891. {
  1892. URHO3D_SAFE_RELEASE(impl->defaultDepthStencilView_);
  1893. URHO3D_LOGD3DERROR("Failed to create backbuffer depth-stencil view", hr);
  1894. success = false;
  1895. }
  1896. }
  1897. // Update internally held backbuffer size
  1898. width_ = width;
  1899. height_ = height;
  1900. ResetRenderTargets_D3D11();
  1901. return success;
  1902. }
  1903. void Graphics::CheckFeatureSupport_D3D11()
  1904. {
  1905. anisotropySupport_ = true;
  1906. dxtTextureSupport_ = true;
  1907. lightPrepassSupport_ = true;
  1908. deferredSupport_ = true;
  1909. hardwareShadowSupport_ = true;
  1910. instancingSupport_ = true;
  1911. shadowMapFormat_ = DXGI_FORMAT_R16_TYPELESS;
  1912. hiresShadowMapFormat_ = DXGI_FORMAT_R32_TYPELESS;
  1913. dummyColorFormat_ = DXGI_FORMAT_UNKNOWN;
  1914. sRGBSupport_ = true;
  1915. sRGBWriteSupport_ = true;
  1916. }
  1917. void Graphics::ResetCachedState_D3D11()
  1918. {
  1919. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1920. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1921. {
  1922. vertexBuffers_[i] = nullptr;
  1923. impl->vertexBuffers_[i] = nullptr;
  1924. impl->vertexSizes_[i] = 0;
  1925. impl->vertexOffsets_[i] = 0;
  1926. }
  1927. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1928. {
  1929. textures_[i] = nullptr;
  1930. impl->shaderResourceViews_[i] = nullptr;
  1931. impl->samplers_[i] = nullptr;
  1932. }
  1933. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1934. {
  1935. renderTargets_[i] = nullptr;
  1936. impl->renderTargetViews_[i] = nullptr;
  1937. }
  1938. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  1939. {
  1940. impl->constantBuffers_[VS][i] = nullptr;
  1941. impl->constantBuffers_[PS][i] = nullptr;
  1942. }
  1943. depthStencil_ = nullptr;
  1944. impl->depthStencilView_ = nullptr;
  1945. viewport_ = IntRect(0, 0, width_, height_);
  1946. indexBuffer_ = nullptr;
  1947. vertexDeclarationHash_ = 0;
  1948. primitiveType_ = 0;
  1949. vertexShader_ = nullptr;
  1950. pixelShader_ = nullptr;
  1951. blendMode_ = BLEND_REPLACE;
  1952. alphaToCoverage_ = false;
  1953. colorWrite_ = true;
  1954. cullMode_ = CULL_CCW;
  1955. constantDepthBias_ = 0.0f;
  1956. slopeScaledDepthBias_ = 0.0f;
  1957. depthTestMode_ = CMP_LESSEQUAL;
  1958. depthWrite_ = true;
  1959. fillMode_ = FILL_SOLID;
  1960. lineAntiAlias_ = false;
  1961. scissorTest_ = false;
  1962. scissorRect_ = IntRect::ZERO;
  1963. stencilTest_ = false;
  1964. stencilTestMode_ = CMP_ALWAYS;
  1965. stencilPass_ = OP_KEEP;
  1966. stencilFail_ = OP_KEEP;
  1967. stencilZFail_ = OP_KEEP;
  1968. stencilRef_ = 0;
  1969. stencilCompareMask_ = M_MAX_UNSIGNED;
  1970. stencilWriteMask_ = M_MAX_UNSIGNED;
  1971. useClipPlane_ = false;
  1972. impl->shaderProgram_ = nullptr;
  1973. impl->renderTargetsDirty_ = true;
  1974. impl->texturesDirty_ = true;
  1975. impl->vertexDeclarationDirty_ = true;
  1976. impl->blendStateDirty_ = true;
  1977. impl->depthStateDirty_ = true;
  1978. impl->rasterizerStateDirty_ = true;
  1979. impl->scissorRectDirty_ = true;
  1980. impl->stencilRefDirty_ = true;
  1981. impl->blendStateHash_ = M_MAX_UNSIGNED;
  1982. impl->depthStateHash_ = M_MAX_UNSIGNED;
  1983. impl->rasterizerStateHash_ = M_MAX_UNSIGNED;
  1984. impl->firstDirtyTexture_ = impl->lastDirtyTexture_ = M_MAX_UNSIGNED;
  1985. impl->firstDirtyVB_ = impl->lastDirtyVB_ = M_MAX_UNSIGNED;
  1986. impl->dirtyConstantBuffers_.Clear();
  1987. }
  1988. void Graphics::PrepareDraw_D3D11()
  1989. {
  1990. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1991. if (impl->renderTargetsDirty_)
  1992. {
  1993. impl->depthStencilView_ =
  1994. (depthStencil_ && depthStencil_->GetUsage() == TEXTURE_DEPTHSTENCIL) ?
  1995. (ID3D11DepthStencilView*)depthStencil_->GetRenderTargetView() : impl->defaultDepthStencilView_;
  1996. // If possible, bind a read-only depth stencil view to allow reading depth in shader
  1997. if (!depthWrite_ && depthStencil_ && depthStencil_->GetReadOnlyView())
  1998. impl->depthStencilView_ = (ID3D11DepthStencilView*)depthStencil_->GetReadOnlyView();
  1999. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2000. impl->renderTargetViews_[i] =
  2001. (renderTargets_[i] && renderTargets_[i]->GetUsage() == TEXTURE_RENDERTARGET) ?
  2002. (ID3D11RenderTargetView*)renderTargets_[i]->GetRenderTargetView() : nullptr;
  2003. // If rendertarget 0 is null and not doing depth-only rendering, render to the backbuffer
  2004. // Special case: if rendertarget 0 is null and depth stencil has same size as backbuffer, assume the intention is to do
  2005. // backbuffer rendering with a custom depth stencil
  2006. if (!renderTargets_[0] &&
  2007. (!depthStencil_ || (depthStencil_ && depthStencil_->GetWidth() == width_ && depthStencil_->GetHeight() == height_)))
  2008. impl->renderTargetViews_[0] = impl->defaultRenderTargetView_;
  2009. impl->deviceContext_->OMSetRenderTargets(MAX_RENDERTARGETS, &impl->renderTargetViews_[0], impl->depthStencilView_);
  2010. impl->renderTargetsDirty_ = false;
  2011. }
  2012. if (impl->texturesDirty_ && impl->firstDirtyTexture_ < M_MAX_UNSIGNED)
  2013. {
  2014. // Set also VS textures to enable vertex texture fetch to work the same way as on OpenGL
  2015. impl->deviceContext_->VSSetShaderResources(impl->firstDirtyTexture_, impl->lastDirtyTexture_ - impl->firstDirtyTexture_ + 1,
  2016. &impl->shaderResourceViews_[impl->firstDirtyTexture_]);
  2017. impl->deviceContext_->VSSetSamplers(impl->firstDirtyTexture_, impl->lastDirtyTexture_ - impl->firstDirtyTexture_ + 1,
  2018. &impl->samplers_[impl->firstDirtyTexture_]);
  2019. impl->deviceContext_->PSSetShaderResources(impl->firstDirtyTexture_, impl->lastDirtyTexture_ - impl->firstDirtyTexture_ + 1,
  2020. &impl->shaderResourceViews_[impl->firstDirtyTexture_]);
  2021. impl->deviceContext_->PSSetSamplers(impl->firstDirtyTexture_, impl->lastDirtyTexture_ - impl->firstDirtyTexture_ + 1,
  2022. &impl->samplers_[impl->firstDirtyTexture_]);
  2023. impl->firstDirtyTexture_ = impl->lastDirtyTexture_ = M_MAX_UNSIGNED;
  2024. impl->texturesDirty_ = false;
  2025. }
  2026. if (impl->vertexDeclarationDirty_ && vertexShader_ && vertexShader_->GetByteCode().Size())
  2027. {
  2028. if (impl->firstDirtyVB_ < M_MAX_UNSIGNED)
  2029. {
  2030. impl->deviceContext_->IASetVertexBuffers(impl->firstDirtyVB_, impl->lastDirtyVB_ - impl->firstDirtyVB_ + 1,
  2031. &impl->vertexBuffers_[impl->firstDirtyVB_], &impl->vertexSizes_[impl->firstDirtyVB_], &impl->vertexOffsets_[impl->firstDirtyVB_]);
  2032. impl->firstDirtyVB_ = impl->lastDirtyVB_ = M_MAX_UNSIGNED;
  2033. }
  2034. unsigned long long newVertexDeclarationHash = 0;
  2035. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2036. {
  2037. if (vertexBuffers_[i])
  2038. newVertexDeclarationHash |= vertexBuffers_[i]->GetBufferHash(i);
  2039. }
  2040. // Do not create input layout if no vertex buffers / elements
  2041. if (newVertexDeclarationHash)
  2042. {
  2043. /// \todo Using a 64bit total hash for vertex shader and vertex buffer elements hash may not guarantee uniqueness
  2044. newVertexDeclarationHash += vertexShader_->GetElementHash();
  2045. if (newVertexDeclarationHash != vertexDeclarationHash_)
  2046. {
  2047. VertexDeclarationMap_D3D11::Iterator i =
  2048. impl->vertexDeclarations_.Find(newVertexDeclarationHash);
  2049. if (i == impl->vertexDeclarations_.End())
  2050. {
  2051. SharedPtr<VertexDeclaration_D3D11> newVertexDeclaration(new VertexDeclaration_D3D11(this, vertexShader_, vertexBuffers_));
  2052. i = impl->vertexDeclarations_.Insert(MakePair(newVertexDeclarationHash, newVertexDeclaration));
  2053. }
  2054. impl->deviceContext_->IASetInputLayout((ID3D11InputLayout*)i->second_->GetInputLayout());
  2055. vertexDeclarationHash_ = newVertexDeclarationHash;
  2056. }
  2057. }
  2058. impl->vertexDeclarationDirty_ = false;
  2059. }
  2060. if (impl->blendStateDirty_)
  2061. {
  2062. unsigned newBlendStateHash = (unsigned)((colorWrite_ ? 1 : 0) | (alphaToCoverage_ ? 2 : 0) | (blendMode_ << 2));
  2063. if (newBlendStateHash != impl->blendStateHash_)
  2064. {
  2065. HashMap<unsigned, ID3D11BlendState*>::Iterator i = impl->blendStates_.Find(newBlendStateHash);
  2066. if (i == impl->blendStates_.End())
  2067. {
  2068. URHO3D_PROFILE(CreateBlendState);
  2069. D3D11_BLEND_DESC stateDesc;
  2070. memset(&stateDesc, 0, sizeof stateDesc);
  2071. stateDesc.AlphaToCoverageEnable = alphaToCoverage_ ? TRUE : FALSE;
  2072. stateDesc.IndependentBlendEnable = false;
  2073. stateDesc.RenderTarget[0].BlendEnable = d3dBlendEnable[blendMode_];
  2074. stateDesc.RenderTarget[0].SrcBlend = d3dSrcBlend[blendMode_];
  2075. stateDesc.RenderTarget[0].DestBlend = d3dDestBlend[blendMode_];
  2076. stateDesc.RenderTarget[0].BlendOp = d3dBlendOp[blendMode_];
  2077. stateDesc.RenderTarget[0].SrcBlendAlpha = d3dSrcBlend[blendMode_];
  2078. stateDesc.RenderTarget[0].DestBlendAlpha = d3dDestBlend[blendMode_];
  2079. stateDesc.RenderTarget[0].BlendOpAlpha = d3dBlendOp[blendMode_];
  2080. stateDesc.RenderTarget[0].RenderTargetWriteMask = colorWrite_ ? D3D11_COLOR_WRITE_ENABLE_ALL : 0x0;
  2081. ID3D11BlendState* newBlendState = nullptr;
  2082. HRESULT hr = impl->device_->CreateBlendState(&stateDesc, &newBlendState);
  2083. if (FAILED(hr))
  2084. {
  2085. URHO3D_SAFE_RELEASE(newBlendState);
  2086. URHO3D_LOGD3DERROR("Failed to create blend state", hr);
  2087. }
  2088. i = impl->blendStates_.Insert(MakePair(newBlendStateHash, newBlendState));
  2089. }
  2090. impl->deviceContext_->OMSetBlendState(i->second_, nullptr, M_MAX_UNSIGNED);
  2091. impl->blendStateHash_ = newBlendStateHash;
  2092. }
  2093. impl->blendStateDirty_ = false;
  2094. }
  2095. if (impl->depthStateDirty_)
  2096. {
  2097. unsigned newDepthStateHash =
  2098. (depthWrite_ ? 1 : 0) | (stencilTest_ ? 2 : 0) | (depthTestMode_ << 2) | ((stencilCompareMask_ & 0xff) << 5) |
  2099. ((stencilWriteMask_ & 0xff) << 13) | (stencilTestMode_ << 21) |
  2100. ((stencilFail_ + stencilZFail_ * 5 + stencilPass_ * 25) << 24);
  2101. if (newDepthStateHash != impl->depthStateHash_ || impl->stencilRefDirty_)
  2102. {
  2103. HashMap<unsigned, ID3D11DepthStencilState*>::Iterator i = impl->depthStates_.Find(newDepthStateHash);
  2104. if (i == impl->depthStates_.End())
  2105. {
  2106. URHO3D_PROFILE(CreateDepthState);
  2107. D3D11_DEPTH_STENCIL_DESC stateDesc;
  2108. memset(&stateDesc, 0, sizeof stateDesc);
  2109. stateDesc.DepthEnable = TRUE;
  2110. stateDesc.DepthWriteMask = depthWrite_ ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO;
  2111. stateDesc.DepthFunc = d3dCmpFunc[depthTestMode_];
  2112. stateDesc.StencilEnable = stencilTest_ ? TRUE : FALSE;
  2113. stateDesc.StencilReadMask = (unsigned char)stencilCompareMask_;
  2114. stateDesc.StencilWriteMask = (unsigned char)stencilWriteMask_;
  2115. stateDesc.FrontFace.StencilFailOp = d3dStencilOp[stencilFail_];
  2116. stateDesc.FrontFace.StencilDepthFailOp = d3dStencilOp[stencilZFail_];
  2117. stateDesc.FrontFace.StencilPassOp = d3dStencilOp[stencilPass_];
  2118. stateDesc.FrontFace.StencilFunc = d3dCmpFunc[stencilTestMode_];
  2119. stateDesc.BackFace.StencilFailOp = d3dStencilOp[stencilFail_];
  2120. stateDesc.BackFace.StencilDepthFailOp = d3dStencilOp[stencilZFail_];
  2121. stateDesc.BackFace.StencilPassOp = d3dStencilOp[stencilPass_];
  2122. stateDesc.BackFace.StencilFunc = d3dCmpFunc[stencilTestMode_];
  2123. ID3D11DepthStencilState* newDepthState = nullptr;
  2124. HRESULT hr = impl->device_->CreateDepthStencilState(&stateDesc, &newDepthState);
  2125. if (FAILED(hr))
  2126. {
  2127. URHO3D_SAFE_RELEASE(newDepthState);
  2128. URHO3D_LOGD3DERROR("Failed to create depth state", hr);
  2129. }
  2130. i = impl->depthStates_.Insert(MakePair(newDepthStateHash, newDepthState));
  2131. }
  2132. impl->deviceContext_->OMSetDepthStencilState(i->second_, stencilRef_);
  2133. impl->depthStateHash_ = newDepthStateHash;
  2134. }
  2135. impl->depthStateDirty_ = false;
  2136. impl->stencilRefDirty_ = false;
  2137. }
  2138. if (impl->rasterizerStateDirty_)
  2139. {
  2140. unsigned depthBits = 24;
  2141. if (depthStencil_ && depthStencil_->GetParentTexture()->GetFormat() == DXGI_FORMAT_R16_TYPELESS)
  2142. depthBits = 16;
  2143. int scaledDepthBias = (int)(constantDepthBias_ * (1 << depthBits));
  2144. unsigned newRasterizerStateHash =
  2145. (scissorTest_ ? 1 : 0) | (lineAntiAlias_ ? 2 : 0) | (fillMode_ << 2) | (cullMode_ << 4) |
  2146. ((scaledDepthBias & 0x1fff) << 6) | (((int)(slopeScaledDepthBias_ * 100.0f) & 0x1fff) << 19);
  2147. if (newRasterizerStateHash != impl->rasterizerStateHash_)
  2148. {
  2149. HashMap<unsigned, ID3D11RasterizerState*>::Iterator i = impl->rasterizerStates_.Find(newRasterizerStateHash);
  2150. if (i == impl->rasterizerStates_.End())
  2151. {
  2152. URHO3D_PROFILE(CreateRasterizerState);
  2153. D3D11_RASTERIZER_DESC stateDesc;
  2154. memset(&stateDesc, 0, sizeof stateDesc);
  2155. stateDesc.FillMode = d3dFillMode[fillMode_];
  2156. stateDesc.CullMode = d3dCullMode[cullMode_];
  2157. stateDesc.FrontCounterClockwise = FALSE;
  2158. stateDesc.DepthBias = scaledDepthBias;
  2159. stateDesc.DepthBiasClamp = M_INFINITY;
  2160. stateDesc.SlopeScaledDepthBias = slopeScaledDepthBias_;
  2161. stateDesc.DepthClipEnable = TRUE;
  2162. stateDesc.ScissorEnable = scissorTest_ ? TRUE : FALSE;
  2163. stateDesc.MultisampleEnable = lineAntiAlias_ ? FALSE : TRUE;
  2164. stateDesc.AntialiasedLineEnable = lineAntiAlias_ ? TRUE : FALSE;
  2165. ID3D11RasterizerState* newRasterizerState = nullptr;
  2166. HRESULT hr = impl->device_->CreateRasterizerState(&stateDesc, &newRasterizerState);
  2167. if (FAILED(hr))
  2168. {
  2169. URHO3D_SAFE_RELEASE(newRasterizerState);
  2170. URHO3D_LOGD3DERROR("Failed to create rasterizer state", hr);
  2171. }
  2172. i = impl->rasterizerStates_.Insert(MakePair(newRasterizerStateHash, newRasterizerState));
  2173. }
  2174. impl->deviceContext_->RSSetState(i->second_);
  2175. impl->rasterizerStateHash_ = newRasterizerStateHash;
  2176. }
  2177. impl->rasterizerStateDirty_ = false;
  2178. }
  2179. if (impl->scissorRectDirty_)
  2180. {
  2181. D3D11_RECT d3dRect;
  2182. d3dRect.left = scissorRect_.left_;
  2183. d3dRect.top = scissorRect_.top_;
  2184. d3dRect.right = scissorRect_.right_;
  2185. d3dRect.bottom = scissorRect_.bottom_;
  2186. impl->deviceContext_->RSSetScissorRects(1, &d3dRect);
  2187. impl->scissorRectDirty_ = false;
  2188. }
  2189. for (unsigned i = 0; i < impl->dirtyConstantBuffers_.Size(); ++i)
  2190. impl->dirtyConstantBuffers_[i]->Apply();
  2191. impl->dirtyConstantBuffers_.Clear();
  2192. }
  2193. void Graphics::CreateResolveTexture_D3D11()
  2194. {
  2195. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  2196. if (impl->resolveTexture_)
  2197. return;
  2198. D3D11_TEXTURE2D_DESC textureDesc;
  2199. memset(&textureDesc, 0, sizeof textureDesc);
  2200. textureDesc.Width = (UINT)width_;
  2201. textureDesc.Height = (UINT)height_;
  2202. textureDesc.MipLevels = 1;
  2203. textureDesc.ArraySize = 1;
  2204. textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  2205. textureDesc.SampleDesc.Count = 1;
  2206. textureDesc.SampleDesc.Quality = 0;
  2207. textureDesc.Usage = D3D11_USAGE_DEFAULT;
  2208. textureDesc.CPUAccessFlags = 0;
  2209. HRESULT hr = impl->device_->CreateTexture2D(&textureDesc, nullptr, &impl->resolveTexture_);
  2210. if (FAILED(hr))
  2211. {
  2212. URHO3D_SAFE_RELEASE(impl->resolveTexture_);
  2213. URHO3D_LOGD3DERROR("Could not create resolve texture", hr);
  2214. }
  2215. }
  2216. void Graphics::SetTextureUnitMappings_D3D11()
  2217. {
  2218. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2219. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2220. textureUnits_["NormalMap"] = TU_NORMAL;
  2221. textureUnits_["SpecMap"] = TU_SPECULAR;
  2222. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2223. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  2224. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  2225. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2226. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  2227. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  2228. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2229. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  2230. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  2231. textureUnits_["VolumeMap"] = TU_VOLUMEMAP;
  2232. textureUnits_["ZoneCubeMap"] = TU_ZONE;
  2233. textureUnits_["ZoneVolumeMap"] = TU_ZONE;
  2234. }
  2235. }