D3D11Graphics.cpp 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662
  1. // Copyright (c) 2008-2023 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::gl3Support = false;
  157. SetTextureUnitMappings_D3D11();
  158. ResetCachedState_D3D11();
  159. context_->RequireSDL(SDL_INIT_VIDEO);
  160. // Register Graphics library object factories
  161. RegisterGraphicsLibrary(context_);
  162. }
  163. void Graphics::Destructor_D3D11()
  164. {
  165. {
  166. MutexLock lock(gpuObjectMutex_);
  167. // Release all GPU objects that still exist
  168. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  169. (*i)->Release();
  170. gpuObjects_.Clear();
  171. }
  172. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  173. impl->vertexDeclarations_.Clear();
  174. impl->allConstantBuffers_.Clear();
  175. for (HashMap<hash32, ID3D11BlendState*>::Iterator i = impl->blendStates_.Begin(); i != impl->blendStates_.End(); ++i)
  176. {
  177. URHO3D_SAFE_RELEASE(i->second_);
  178. }
  179. impl->blendStates_.Clear();
  180. for (HashMap<hash32, ID3D11DepthStencilState*>::Iterator i = impl->depthStates_.Begin(); i != impl->depthStates_.End(); ++i)
  181. {
  182. URHO3D_SAFE_RELEASE(i->second_);
  183. }
  184. impl->depthStates_.Clear();
  185. for (HashMap<hash32, ID3D11RasterizerState*>::Iterator i = impl->rasterizerStates_.Begin();
  186. i != impl->rasterizerStates_.End(); ++i)
  187. {
  188. URHO3D_SAFE_RELEASE(i->second_);
  189. }
  190. impl->rasterizerStates_.Clear();
  191. URHO3D_SAFE_RELEASE(impl->defaultRenderTargetView_);
  192. URHO3D_SAFE_RELEASE(impl->defaultDepthStencilView_);
  193. URHO3D_SAFE_RELEASE(impl->defaultDepthTexture_);
  194. URHO3D_SAFE_RELEASE(impl->resolveTexture_);
  195. URHO3D_SAFE_RELEASE(impl->swapChain_);
  196. URHO3D_SAFE_RELEASE(impl->deviceContext_);
  197. URHO3D_SAFE_RELEASE(impl->device_);
  198. if (window_)
  199. {
  200. SDL_ShowCursor(SDL_TRUE);
  201. SDL_DestroyWindow(window_);
  202. window_ = nullptr;
  203. }
  204. delete static_cast<GraphicsImpl_D3D11*>(impl_);
  205. impl_ = nullptr;
  206. context_->ReleaseSDL();
  207. }
  208. bool Graphics::SetScreenMode_D3D11(int width, int height, const ScreenModeParams& params, bool maximize)
  209. {
  210. URHO3D_PROFILE(SetScreenMode_D3D11);
  211. // Ensure that parameters are properly filled
  212. ScreenModeParams newParams = params;
  213. AdjustScreenMode(width, height, newParams, maximize);
  214. // Find out the full screen mode display format (match desktop color depth)
  215. SDL_DisplayMode mode;
  216. SDL_GetDesktopDisplayMode(newParams.monitor_, &mode);
  217. const DXGI_FORMAT fullscreenFormat = SDL_BITSPERPIXEL(mode.format) == 16 ? DXGI_FORMAT_B5G6R5_UNORM : DXGI_FORMAT_R8G8B8A8_UNORM;
  218. // If nothing changes, do not reset the device
  219. if (width == width_ && height == height_ && newParams == screenParams_)
  220. return true;
  221. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  222. if (!window_)
  223. {
  224. if (!OpenWindow_D3D11(width, height, newParams.resizable_, newParams.borderless_))
  225. return false;
  226. }
  227. AdjustWindow_D3D11(width, height, newParams.fullscreen_, newParams.borderless_, newParams.resizable_, newParams.monitor_);
  228. if (maximize)
  229. {
  230. Maximize();
  231. SDL_GetWindowSize(window_, &width, &height);
  232. }
  233. const int oldMultiSample = screenParams_.multiSample_;
  234. screenParams_ = newParams;
  235. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  236. if (!impl->device_ || screenParams_.multiSample_ != oldMultiSample)
  237. CreateDevice_D3D11(width, height);
  238. UpdateSwapChain_D3D11(width, height);
  239. // Clear the initial window contents to black
  240. Clear_D3D11(CLEAR_COLOR);
  241. impl->swapChain_->Present(0, 0);
  242. OnScreenModeChanged();
  243. return true;
  244. }
  245. void Graphics::SetSRGB_D3D11(bool enable)
  246. {
  247. bool newEnable = enable && sRGBWriteSupport_;
  248. if (newEnable != sRGB_)
  249. {
  250. sRGB_ = newEnable;
  251. if (GetImpl_D3D11()->swapChain_)
  252. {
  253. // Recreate swap chain for the new backbuffer format
  254. CreateDevice_D3D11(width_, height_);
  255. UpdateSwapChain_D3D11(width_, height_);
  256. }
  257. }
  258. }
  259. void Graphics::SetDither_D3D11(bool enable)
  260. {
  261. // No effect on Direct3D11
  262. }
  263. void Graphics::SetFlushGPU_D3D11(bool enable)
  264. {
  265. flushGPU_ = enable;
  266. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  267. if (impl->device_)
  268. {
  269. IDXGIDevice1* dxgiDevice;
  270. impl->device_->QueryInterface(IID_IDXGIDevice1, (void**)&dxgiDevice);
  271. if (dxgiDevice)
  272. {
  273. dxgiDevice->SetMaximumFrameLatency(enable ? 1 : 3);
  274. dxgiDevice->Release();
  275. }
  276. }
  277. }
  278. void Graphics::SetForceGL2_D3D11(bool enable)
  279. {
  280. // No effect on Direct3D11
  281. }
  282. void Graphics::Close_D3D11()
  283. {
  284. if (window_)
  285. {
  286. SDL_ShowCursor(SDL_TRUE);
  287. SDL_DestroyWindow(window_);
  288. window_ = nullptr;
  289. }
  290. }
  291. bool Graphics::TakeScreenShot_D3D11(Image& destImage)
  292. {
  293. URHO3D_PROFILE(TakeScreenShot_D3D11);
  294. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  295. if (!impl->device_)
  296. return false;
  297. D3D11_TEXTURE2D_DESC textureDesc;
  298. memset(&textureDesc, 0, sizeof textureDesc);
  299. textureDesc.Width = (UINT)width_;
  300. textureDesc.Height = (UINT)height_;
  301. textureDesc.MipLevels = 1;
  302. textureDesc.ArraySize = 1;
  303. textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  304. textureDesc.SampleDesc.Count = 1;
  305. textureDesc.SampleDesc.Quality = 0;
  306. textureDesc.Usage = D3D11_USAGE_STAGING;
  307. textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  308. ID3D11Texture2D* stagingTexture = nullptr;
  309. HRESULT hr = impl->device_->CreateTexture2D(&textureDesc, nullptr, &stagingTexture);
  310. if (FAILED(hr))
  311. {
  312. URHO3D_SAFE_RELEASE(stagingTexture);
  313. URHO3D_LOGD3DERROR("Could not create staging texture for screenshot", hr);
  314. return false;
  315. }
  316. ID3D11Resource* source = nullptr;
  317. impl->defaultRenderTargetView_->GetResource(&source);
  318. if (screenParams_.multiSample_ > 1)
  319. {
  320. // If backbuffer is multisampled, need another DEFAULT usage texture to resolve the data to first
  321. CreateResolveTexture_D3D11();
  322. if (!impl->resolveTexture_)
  323. {
  324. stagingTexture->Release();
  325. source->Release();
  326. return false;
  327. }
  328. impl->deviceContext_->ResolveSubresource(impl->resolveTexture_, 0, source, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
  329. impl->deviceContext_->CopyResource(stagingTexture, impl->resolveTexture_);
  330. }
  331. else
  332. impl->deviceContext_->CopyResource(stagingTexture, source);
  333. source->Release();
  334. D3D11_MAPPED_SUBRESOURCE mappedData;
  335. mappedData.pData = nullptr;
  336. hr = impl->deviceContext_->Map(stagingTexture, 0, D3D11_MAP_READ, 0, &mappedData);
  337. if (FAILED(hr) || !mappedData.pData)
  338. {
  339. URHO3D_LOGD3DERROR("Could not map staging texture for screenshot", hr);
  340. stagingTexture->Release();
  341. return false;
  342. }
  343. destImage.SetSize(width_, height_, 3);
  344. unsigned char* destData = destImage.GetData();
  345. for (int y = 0; y < height_; ++y)
  346. {
  347. unsigned char* src = (unsigned char*)mappedData.pData + y * mappedData.RowPitch;
  348. for (int x = 0; x < width_; ++x)
  349. {
  350. *destData++ = *src++;
  351. *destData++ = *src++;
  352. *destData++ = *src++;
  353. ++src;
  354. }
  355. }
  356. impl->deviceContext_->Unmap(stagingTexture, 0);
  357. stagingTexture->Release();
  358. return true;
  359. }
  360. bool Graphics::BeginFrame_D3D11()
  361. {
  362. if (!IsInitialized_D3D11())
  363. return false;
  364. // If using an external window, check it for size changes, and reset screen mode if necessary
  365. if (externalWindow_)
  366. {
  367. int width, height;
  368. SDL_GetWindowSize(window_, &width, &height);
  369. if (width != width_ || height != height_)
  370. SetMode(width, height);
  371. }
  372. else
  373. {
  374. // To prevent a loop of endless device loss and flicker, do not attempt to render when in fullscreen
  375. // and the window is minimized
  376. if (screenParams_.fullscreen_ && (SDL_GetWindowFlags(window_) & SDL_WINDOW_MINIMIZED))
  377. return false;
  378. }
  379. // Set default rendertarget and depth buffer
  380. ResetRenderTargets_D3D11();
  381. // Cleanup textures from previous frame
  382. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  383. SetTexture_D3D11(i, nullptr);
  384. numPrimitives_ = 0;
  385. numBatches_ = 0;
  386. SendEvent(E_BEGINRENDERING);
  387. return true;
  388. }
  389. void Graphics::EndFrame_D3D11()
  390. {
  391. if (!IsInitialized_D3D11())
  392. return;
  393. {
  394. URHO3D_PROFILE(Present);
  395. SendEvent(E_ENDRENDERING);
  396. GetImpl_D3D11()->swapChain_->Present(screenParams_.vsync_ ? 1 : 0, 0);
  397. }
  398. // Clean up too large scratch buffers
  399. CleanupScratchBuffers();
  400. }
  401. void Graphics::Clear_D3D11(ClearTargetFlags flags, const Color& color, float depth, u32 stencil)
  402. {
  403. IntVector2 rtSize = GetRenderTargetDimensions_D3D11();
  404. bool oldColorWrite = colorWrite_;
  405. bool oldDepthWrite = depthWrite_;
  406. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  407. // D3D11 clear always clears the whole target regardless of viewport or scissor test settings
  408. // Emulate partial clear by rendering a quad
  409. if (!viewport_.left_ && !viewport_.top_ && viewport_.right_ == rtSize.x_ && viewport_.bottom_ == rtSize.y_)
  410. {
  411. // Make sure we use the read-write version of the depth stencil
  412. SetDepthWrite_D3D11(true);
  413. PrepareDraw_D3D11();
  414. if ((flags & CLEAR_COLOR) && impl->renderTargetViews_[0])
  415. impl->deviceContext_->ClearRenderTargetView(impl->renderTargetViews_[0], color.Data());
  416. if ((flags & (CLEAR_DEPTH | CLEAR_STENCIL)) && impl->depthStencilView_)
  417. {
  418. unsigned depthClearFlags = 0;
  419. if (flags & CLEAR_DEPTH)
  420. depthClearFlags |= D3D11_CLEAR_DEPTH;
  421. if (flags & CLEAR_STENCIL)
  422. depthClearFlags |= D3D11_CLEAR_STENCIL;
  423. impl->deviceContext_->ClearDepthStencilView(impl->depthStencilView_, depthClearFlags, depth, (UINT8)stencil);
  424. }
  425. }
  426. else
  427. {
  428. Renderer* renderer = GetSubsystem<Renderer>();
  429. if (!renderer)
  430. return;
  431. Geometry* geometry = renderer->GetQuadGeometry();
  432. Matrix3x4 model = Matrix3x4::IDENTITY;
  433. Matrix4 projection = Matrix4::IDENTITY;
  434. model.m23_ = Clamp(depth, 0.0f, 1.0f);
  435. SetBlendMode_D3D11(BLEND_REPLACE);
  436. SetColorWrite_D3D11(flags & CLEAR_COLOR);
  437. SetCullMode_D3D11(CULL_NONE);
  438. SetDepthTest_D3D11(CMP_ALWAYS);
  439. SetDepthWrite_D3D11(flags & CLEAR_DEPTH);
  440. SetFillMode_D3D11(FILL_SOLID);
  441. SetScissorTest_D3D11(false);
  442. SetStencilTest_D3D11(flags & CLEAR_STENCIL, CMP_ALWAYS, OP_REF, OP_KEEP, OP_KEEP, stencil);
  443. SetShaders_D3D11(GetShader_D3D11(VS, "ClearFramebuffer"), GetShader_D3D11(PS, "ClearFramebuffer"));
  444. SetShaderParameter_D3D11(VSP_MODEL, model);
  445. SetShaderParameter_D3D11(VSP_VIEWPROJ, projection);
  446. SetShaderParameter_D3D11(PSP_MATDIFFCOLOR, color);
  447. geometry->Draw(this);
  448. SetStencilTest_D3D11(false);
  449. ClearParameterSources_D3D11();
  450. }
  451. // Restore color & depth write state now
  452. SetColorWrite_D3D11(oldColorWrite);
  453. SetDepthWrite_D3D11(oldDepthWrite);
  454. }
  455. bool Graphics::ResolveToTexture_D3D11(Texture2D* destination, const IntRect& viewport)
  456. {
  457. if (!destination || !destination->GetRenderSurface())
  458. return false;
  459. URHO3D_PROFILE(ResolveToTexture_D3D11);
  460. IntRect vpCopy = viewport;
  461. if (vpCopy.right_ <= vpCopy.left_)
  462. vpCopy.right_ = vpCopy.left_ + 1;
  463. if (vpCopy.bottom_ <= vpCopy.top_)
  464. vpCopy.bottom_ = vpCopy.top_ + 1;
  465. D3D11_BOX srcBox;
  466. srcBox.left = Clamp(vpCopy.left_, 0, width_);
  467. srcBox.top = Clamp(vpCopy.top_, 0, height_);
  468. srcBox.right = Clamp(vpCopy.right_, 0, width_);
  469. srcBox.bottom = Clamp(vpCopy.bottom_, 0, height_);
  470. srcBox.front = 0;
  471. srcBox.back = 1;
  472. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  473. ID3D11Resource* source = nullptr;
  474. const bool resolve = screenParams_.multiSample_ > 1;
  475. impl->defaultRenderTargetView_->GetResource(&source);
  476. if (!resolve)
  477. {
  478. if (!srcBox.left && !srcBox.top && srcBox.right == width_ && srcBox.bottom == height_)
  479. impl->deviceContext_->CopyResource((ID3D11Resource*)destination->GetGPUObject(), source);
  480. else
  481. impl->deviceContext_->CopySubresourceRegion((ID3D11Resource*)destination->GetGPUObject(), 0, 0, 0, 0, source, 0, &srcBox);
  482. }
  483. else
  484. {
  485. if (!srcBox.left && !srcBox.top && srcBox.right == width_ && srcBox.bottom == height_)
  486. {
  487. impl->deviceContext_->ResolveSubresource((ID3D11Resource*)destination->GetGPUObject(), 0, source, 0, (DXGI_FORMAT)
  488. destination->GetFormat());
  489. }
  490. else
  491. {
  492. CreateResolveTexture_D3D11();
  493. if (impl->resolveTexture_)
  494. {
  495. impl->deviceContext_->ResolveSubresource(impl->resolveTexture_, 0, source, 0, DXGI_FORMAT_R8G8B8A8_UNORM);
  496. impl->deviceContext_->CopySubresourceRegion((ID3D11Resource*)destination->GetGPUObject(), 0, 0, 0, 0, impl->resolveTexture_, 0, &srcBox);
  497. }
  498. }
  499. }
  500. source->Release();
  501. return true;
  502. }
  503. bool Graphics::ResolveToTexture_D3D11(Texture2D* texture)
  504. {
  505. if (!texture)
  506. return false;
  507. RenderSurface* surface = texture->GetRenderSurface();
  508. if (!surface)
  509. return false;
  510. texture->SetResolveDirty(false);
  511. surface->SetResolveDirty(false);
  512. ID3D11Resource* source = (ID3D11Resource*)texture->GetGPUObject();
  513. ID3D11Resource* dest = (ID3D11Resource*)texture->GetResolveTexture();
  514. if (!source || !dest)
  515. return false;
  516. GetImpl_D3D11()->deviceContext_->ResolveSubresource(dest, 0, source, 0, (DXGI_FORMAT)texture->GetFormat());
  517. return true;
  518. }
  519. bool Graphics::ResolveToTexture_D3D11(TextureCube* texture)
  520. {
  521. if (!texture)
  522. return false;
  523. texture->SetResolveDirty(false);
  524. ID3D11Resource* source = (ID3D11Resource*)texture->GetGPUObject();
  525. ID3D11Resource* dest = (ID3D11Resource*)texture->GetResolveTexture();
  526. if (!source || !dest)
  527. return false;
  528. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  529. {
  530. // Resolve only the surface(s) that were actually rendered to
  531. RenderSurface* surface = texture->GetRenderSurface((CubeMapFace)i);
  532. if (!surface->IsResolveDirty())
  533. continue;
  534. surface->SetResolveDirty(false);
  535. unsigned subResource = D3D11CalcSubresource(0, i, texture->GetLevels());
  536. GetImpl_D3D11()->deviceContext_->ResolveSubresource(dest, subResource, source, subResource, (DXGI_FORMAT)texture->GetFormat());
  537. }
  538. return true;
  539. }
  540. void Graphics::Draw_D3D11(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  541. {
  542. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  543. if (!vertexCount || !impl->shaderProgram_)
  544. return;
  545. PrepareDraw_D3D11();
  546. unsigned primitiveCount;
  547. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  548. if (fillMode_ == FILL_POINT)
  549. type = POINT_LIST;
  550. GetD3DPrimitiveType(vertexCount, type, primitiveCount, d3dPrimitiveType);
  551. if (d3dPrimitiveType != primitiveType_)
  552. {
  553. impl->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  554. primitiveType_ = d3dPrimitiveType;
  555. }
  556. impl->deviceContext_->Draw(vertexCount, vertexStart);
  557. numPrimitives_ += primitiveCount;
  558. ++numBatches_;
  559. }
  560. void Graphics::Draw_D3D11(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  561. {
  562. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  563. if (!vertexCount || !impl->shaderProgram_)
  564. return;
  565. PrepareDraw_D3D11();
  566. unsigned primitiveCount;
  567. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  568. if (fillMode_ == FILL_POINT)
  569. type = POINT_LIST;
  570. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  571. if (d3dPrimitiveType != primitiveType_)
  572. {
  573. impl->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  574. primitiveType_ = d3dPrimitiveType;
  575. }
  576. impl->deviceContext_->DrawIndexed(indexCount, indexStart, 0);
  577. numPrimitives_ += primitiveCount;
  578. ++numBatches_;
  579. }
  580. void Graphics::Draw_D3D11(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned baseVertexIndex, unsigned minVertex, unsigned vertexCount)
  581. {
  582. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  583. if (!vertexCount || !impl->shaderProgram_)
  584. return;
  585. PrepareDraw_D3D11();
  586. unsigned primitiveCount;
  587. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  588. if (fillMode_ == FILL_POINT)
  589. type = POINT_LIST;
  590. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  591. if (d3dPrimitiveType != primitiveType_)
  592. {
  593. impl->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  594. primitiveType_ = d3dPrimitiveType;
  595. }
  596. impl->deviceContext_->DrawIndexed(indexCount, indexStart, baseVertexIndex);
  597. numPrimitives_ += primitiveCount;
  598. ++numBatches_;
  599. }
  600. void Graphics::DrawInstanced_D3D11(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount,
  601. unsigned instanceCount)
  602. {
  603. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  604. if (!indexCount || !instanceCount || !impl->shaderProgram_)
  605. return;
  606. PrepareDraw_D3D11();
  607. unsigned primitiveCount;
  608. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  609. if (fillMode_ == FILL_POINT)
  610. type = POINT_LIST;
  611. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  612. if (d3dPrimitiveType != primitiveType_)
  613. {
  614. impl->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  615. primitiveType_ = d3dPrimitiveType;
  616. }
  617. impl->deviceContext_->DrawIndexedInstanced(indexCount, instanceCount, indexStart, 0, 0);
  618. numPrimitives_ += instanceCount * primitiveCount;
  619. ++numBatches_;
  620. }
  621. void Graphics::DrawInstanced_D3D11(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned baseVertexIndex, unsigned minVertex, unsigned vertexCount,
  622. unsigned instanceCount)
  623. {
  624. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  625. if (!indexCount || !instanceCount || !impl->shaderProgram_)
  626. return;
  627. PrepareDraw_D3D11();
  628. unsigned primitiveCount;
  629. D3D_PRIMITIVE_TOPOLOGY d3dPrimitiveType;
  630. if (fillMode_ == FILL_POINT)
  631. type = POINT_LIST;
  632. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  633. if (d3dPrimitiveType != primitiveType_)
  634. {
  635. impl->deviceContext_->IASetPrimitiveTopology(d3dPrimitiveType);
  636. primitiveType_ = d3dPrimitiveType;
  637. }
  638. impl->deviceContext_->DrawIndexedInstanced(indexCount, instanceCount, indexStart, baseVertexIndex, 0);
  639. numPrimitives_ += instanceCount * primitiveCount;
  640. ++numBatches_;
  641. }
  642. void Graphics::SetVertexBuffer_D3D11(VertexBuffer* buffer)
  643. {
  644. // Note: this is not multi-instance safe
  645. static Vector<VertexBuffer*> vertexBuffers(1);
  646. vertexBuffers[0] = buffer;
  647. SetVertexBuffers_D3D11(vertexBuffers);
  648. }
  649. bool Graphics::SetVertexBuffers_D3D11(const Vector<VertexBuffer*>& buffers, unsigned instanceOffset)
  650. {
  651. if (buffers.Size() > MAX_VERTEX_STREAMS)
  652. {
  653. URHO3D_LOGERROR("Too many vertex buffers");
  654. return false;
  655. }
  656. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  657. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  658. {
  659. VertexBuffer* buffer = nullptr;
  660. bool changed = false;
  661. buffer = i < buffers.Size() ? buffers[i] : nullptr;
  662. if (buffer)
  663. {
  664. const Vector<VertexElement>& elements = buffer->GetElements();
  665. // Check if buffer has per-instance data
  666. bool hasInstanceData = elements.Size() && elements[0].perInstance_;
  667. unsigned offset = hasInstanceData ? instanceOffset * buffer->GetVertexSize() : 0;
  668. if (buffer != vertexBuffers_[i] || offset != impl->vertexOffsets_[i])
  669. {
  670. vertexBuffers_[i] = buffer;
  671. impl->vertexBuffers_[i] = (ID3D11Buffer*)buffer->GetGPUObject();
  672. impl->vertexSizes_[i] = buffer->GetVertexSize();
  673. impl->vertexOffsets_[i] = offset;
  674. changed = true;
  675. }
  676. }
  677. else if (vertexBuffers_[i])
  678. {
  679. vertexBuffers_[i] = nullptr;
  680. impl->vertexBuffers_[i] = nullptr;
  681. impl->vertexSizes_[i] = 0;
  682. impl->vertexOffsets_[i] = 0;
  683. changed = true;
  684. }
  685. if (changed)
  686. {
  687. impl->vertexDeclarationDirty_ = true;
  688. if (impl->firstDirtyVB_ == M_MAX_UNSIGNED)
  689. impl->firstDirtyVB_ = impl->lastDirtyVB_ = i;
  690. else
  691. {
  692. if (i < impl->firstDirtyVB_)
  693. impl->firstDirtyVB_ = i;
  694. if (i > impl->lastDirtyVB_)
  695. impl->lastDirtyVB_ = i;
  696. }
  697. }
  698. }
  699. return true;
  700. }
  701. bool Graphics::SetVertexBuffers_D3D11(const Vector<SharedPtr<VertexBuffer>>& buffers, unsigned instanceOffset)
  702. {
  703. return SetVertexBuffers_D3D11(reinterpret_cast<const Vector<VertexBuffer*>&>(buffers), instanceOffset);
  704. }
  705. void Graphics::SetIndexBuffer_D3D11(IndexBuffer* buffer)
  706. {
  707. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  708. if (buffer != indexBuffer_)
  709. {
  710. if (buffer)
  711. impl->deviceContext_->IASetIndexBuffer((ID3D11Buffer*)buffer->GetGPUObject(),
  712. buffer->GetIndexSize() == sizeof(unsigned short) ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
  713. else
  714. impl->deviceContext_->IASetIndexBuffer(nullptr, DXGI_FORMAT_UNKNOWN, 0);
  715. indexBuffer_ = buffer;
  716. }
  717. }
  718. void Graphics::SetShaders_D3D11(ShaderVariation* vs, ShaderVariation* ps)
  719. {
  720. // Switch to the clip plane variations if necessary
  721. if (useClipPlane_)
  722. {
  723. if (vs)
  724. vs = vs->GetOwner()->GetVariation(VS, vs->GetDefinesClipPlane());
  725. if (ps)
  726. ps = ps->GetOwner()->GetVariation(PS, ps->GetDefinesClipPlane());
  727. }
  728. if (vs == vertexShader_ && ps == pixelShader_)
  729. return;
  730. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  731. if (vs != vertexShader_)
  732. {
  733. // Create the shader now if not yet created. If already attempted, do not retry
  734. if (vs && !vs->GetGPUObject())
  735. {
  736. if (vs->GetCompilerOutput().Empty())
  737. {
  738. URHO3D_PROFILE(CompileVertexShader);
  739. bool success = vs->Create();
  740. if (!success)
  741. {
  742. URHO3D_LOGERROR("Failed to compile vertex shader " + vs->GetFullName() + ":\n" + vs->GetCompilerOutput());
  743. vs = nullptr;
  744. }
  745. }
  746. else
  747. vs = nullptr;
  748. }
  749. impl->deviceContext_->VSSetShader((ID3D11VertexShader*)(vs ? vs->GetGPUObject() : nullptr), nullptr, 0);
  750. vertexShader_ = vs;
  751. impl->vertexDeclarationDirty_ = true;
  752. }
  753. if (ps != pixelShader_)
  754. {
  755. if (ps && !ps->GetGPUObject())
  756. {
  757. if (ps->GetCompilerOutput().Empty())
  758. {
  759. URHO3D_PROFILE(CompilePixelShader);
  760. bool success = ps->Create();
  761. if (!success)
  762. {
  763. URHO3D_LOGERROR("Failed to compile pixel shader " + ps->GetFullName() + ":\n" + ps->GetCompilerOutput());
  764. ps = nullptr;
  765. }
  766. }
  767. else
  768. ps = nullptr;
  769. }
  770. impl->deviceContext_->PSSetShader((ID3D11PixelShader*)(ps ? ps->GetGPUObject() : nullptr), nullptr, 0);
  771. pixelShader_ = ps;
  772. }
  773. // Update current shader parameters & constant buffers
  774. if (vertexShader_ && pixelShader_)
  775. {
  776. Pair<ShaderVariation*, ShaderVariation*> key = MakePair(vertexShader_, pixelShader_);
  777. ShaderProgramMap_D3D11::Iterator i = impl->shaderPrograms_.Find(key);
  778. if (i != impl->shaderPrograms_.End())
  779. impl->shaderProgram_ = i->second_.Get();
  780. else
  781. {
  782. ShaderProgram_D3D11* newProgram = impl->shaderPrograms_[key] = new ShaderProgram_D3D11(this, vertexShader_, pixelShader_);
  783. impl->shaderProgram_ = newProgram;
  784. }
  785. bool vsBuffersChanged = false;
  786. bool psBuffersChanged = false;
  787. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  788. {
  789. ID3D11Buffer* vsBuffer = impl->shaderProgram_->vsConstantBuffers_[i] ? (ID3D11Buffer*)impl->shaderProgram_->vsConstantBuffers_[i]->
  790. GetGPUObject() : nullptr;
  791. if (vsBuffer != impl->constantBuffers_[VS][i])
  792. {
  793. impl->constantBuffers_[VS][i] = vsBuffer;
  794. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  795. vsBuffersChanged = true;
  796. }
  797. ID3D11Buffer* psBuffer = impl->shaderProgram_->psConstantBuffers_[i] ? (ID3D11Buffer*)impl->shaderProgram_->psConstantBuffers_[i]->
  798. GetGPUObject() : nullptr;
  799. if (psBuffer != impl->constantBuffers_[PS][i])
  800. {
  801. impl->constantBuffers_[PS][i] = psBuffer;
  802. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  803. psBuffersChanged = true;
  804. }
  805. }
  806. if (vsBuffersChanged)
  807. impl->deviceContext_->VSSetConstantBuffers(0, MAX_SHADER_PARAMETER_GROUPS, &impl->constantBuffers_[VS][0]);
  808. if (psBuffersChanged)
  809. impl->deviceContext_->PSSetConstantBuffers(0, MAX_SHADER_PARAMETER_GROUPS, &impl->constantBuffers_[PS][0]);
  810. }
  811. else
  812. impl->shaderProgram_ = nullptr;
  813. // Store shader combination if shader dumping in progress
  814. if (shaderPrecache_)
  815. shaderPrecache_->StoreShaders(vertexShader_, pixelShader_);
  816. // Update clip plane parameter if necessary
  817. if (useClipPlane_)
  818. SetShaderParameter_D3D11(VSP_CLIPPLANE, clipPlane_);
  819. }
  820. void Graphics::SetShaderParameter_D3D11(StringHash param, const float* data, unsigned count)
  821. {
  822. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  823. HashMap<StringHash, ShaderParameter>::Iterator i;
  824. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  825. return;
  826. ConstantBuffer* buffer = i->second_.bufferPtr_;
  827. if (!buffer->IsDirty())
  828. impl->dirtyConstantBuffers_.Push(buffer);
  829. buffer->SetParameter(i->second_.offset_, (unsigned)(count * sizeof(float)), data);
  830. }
  831. void Graphics::SetShaderParameter_D3D11(StringHash param, float value)
  832. {
  833. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  834. HashMap<StringHash, ShaderParameter>::Iterator i;
  835. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  836. return;
  837. ConstantBuffer* buffer = i->second_.bufferPtr_;
  838. if (!buffer->IsDirty())
  839. impl->dirtyConstantBuffers_.Push(buffer);
  840. buffer->SetParameter(i->second_.offset_, sizeof(float), &value);
  841. }
  842. void Graphics::SetShaderParameter_D3D11(StringHash param, int value)
  843. {
  844. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  845. HashMap<StringHash, ShaderParameter>::Iterator i;
  846. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  847. return;
  848. ConstantBuffer* buffer = i->second_.bufferPtr_;
  849. if (!buffer->IsDirty())
  850. impl->dirtyConstantBuffers_.Push(buffer);
  851. buffer->SetParameter(i->second_.offset_, sizeof(int), &value);
  852. }
  853. void Graphics::SetShaderParameter_D3D11(StringHash param, bool value)
  854. {
  855. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  856. HashMap<StringHash, ShaderParameter>::Iterator i;
  857. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  858. return;
  859. ConstantBuffer* buffer = i->second_.bufferPtr_;
  860. if (!buffer->IsDirty())
  861. impl->dirtyConstantBuffers_.Push(buffer);
  862. buffer->SetParameter(i->second_.offset_, sizeof(bool), &value);
  863. }
  864. void Graphics::SetShaderParameter_D3D11(StringHash param, const Color& color)
  865. {
  866. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  867. HashMap<StringHash, ShaderParameter>::Iterator i;
  868. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  869. return;
  870. ConstantBuffer* buffer = i->second_.bufferPtr_;
  871. if (!buffer->IsDirty())
  872. impl->dirtyConstantBuffers_.Push(buffer);
  873. buffer->SetParameter(i->second_.offset_, sizeof(Color), &color);
  874. }
  875. void Graphics::SetShaderParameter_D3D11(StringHash param, const Vector2& vector)
  876. {
  877. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  878. HashMap<StringHash, ShaderParameter>::Iterator i;
  879. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  880. return;
  881. ConstantBuffer* buffer = i->second_.bufferPtr_;
  882. if (!buffer->IsDirty())
  883. impl->dirtyConstantBuffers_.Push(buffer);
  884. buffer->SetParameter(i->second_.offset_, sizeof(Vector2), &vector);
  885. }
  886. void Graphics::SetShaderParameter_D3D11(StringHash param, const Matrix3& matrix)
  887. {
  888. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  889. HashMap<StringHash, ShaderParameter>::Iterator i;
  890. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  891. return;
  892. ConstantBuffer* buffer = i->second_.bufferPtr_;
  893. if (!buffer->IsDirty())
  894. impl->dirtyConstantBuffers_.Push(buffer);
  895. buffer->SetVector3ArrayParameter(i->second_.offset_, 3, &matrix);
  896. }
  897. void Graphics::SetShaderParameter_D3D11(StringHash param, const Vector3& vector)
  898. {
  899. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  900. HashMap<StringHash, ShaderParameter>::Iterator i;
  901. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  902. return;
  903. ConstantBuffer* buffer = i->second_.bufferPtr_;
  904. if (!buffer->IsDirty())
  905. impl->dirtyConstantBuffers_.Push(buffer);
  906. buffer->SetParameter(i->second_.offset_, sizeof(Vector3), &vector);
  907. }
  908. void Graphics::SetShaderParameter_D3D11(StringHash param, const Matrix4& matrix)
  909. {
  910. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  911. HashMap<StringHash, ShaderParameter>::Iterator i;
  912. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  913. return;
  914. ConstantBuffer* buffer = i->second_.bufferPtr_;
  915. if (!buffer->IsDirty())
  916. impl->dirtyConstantBuffers_.Push(buffer);
  917. buffer->SetParameter(i->second_.offset_, sizeof(Matrix4), &matrix);
  918. }
  919. void Graphics::SetShaderParameter_D3D11(StringHash param, const Vector4& vector)
  920. {
  921. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  922. HashMap<StringHash, ShaderParameter>::Iterator i;
  923. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  924. return;
  925. ConstantBuffer* buffer = i->second_.bufferPtr_;
  926. if (!buffer->IsDirty())
  927. impl->dirtyConstantBuffers_.Push(buffer);
  928. buffer->SetParameter(i->second_.offset_, sizeof(Vector4), &vector);
  929. }
  930. void Graphics::SetShaderParameter_D3D11(StringHash param, const Matrix3x4& matrix)
  931. {
  932. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  933. HashMap<StringHash, ShaderParameter>::Iterator i;
  934. if (!impl->shaderProgram_ || (i = impl->shaderProgram_->parameters_.Find(param)) == impl->shaderProgram_->parameters_.End())
  935. return;
  936. ConstantBuffer* buffer = i->second_.bufferPtr_;
  937. if (!buffer->IsDirty())
  938. impl->dirtyConstantBuffers_.Push(buffer);
  939. buffer->SetParameter(i->second_.offset_, sizeof(Matrix3x4), &matrix);
  940. }
  941. bool Graphics::NeedParameterUpdate_D3D11(ShaderParameterGroup group, const void* source)
  942. {
  943. if ((unsigned)(size_t)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  944. {
  945. shaderParameterSources_[group] = source;
  946. return true;
  947. }
  948. else
  949. return false;
  950. }
  951. bool Graphics::HasShaderParameter_D3D11(StringHash param)
  952. {
  953. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  954. return impl->shaderProgram_ && impl->shaderProgram_->parameters_.Find(param) != impl->shaderProgram_->parameters_.End();
  955. }
  956. bool Graphics::HasTextureUnit_D3D11(TextureUnit unit)
  957. {
  958. return (vertexShader_ && vertexShader_->HasTextureUnit(unit)) || (pixelShader_ && pixelShader_->HasTextureUnit(unit));
  959. }
  960. void Graphics::ClearParameterSource_D3D11(ShaderParameterGroup group)
  961. {
  962. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  963. }
  964. void Graphics::ClearParameterSources_D3D11()
  965. {
  966. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  967. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  968. }
  969. void Graphics::ClearTransformSources_D3D11()
  970. {
  971. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  972. shaderParameterSources_[SP_OBJECT] = (const void*)M_MAX_UNSIGNED;
  973. }
  974. void Graphics::SetTexture_D3D11(unsigned index, Texture* texture)
  975. {
  976. if (index >= MAX_TEXTURE_UNITS)
  977. return;
  978. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  979. if (texture)
  980. {
  981. if (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture)
  982. texture = texture->GetBackupTexture();
  983. else
  984. {
  985. // Resolve multisampled texture now as necessary
  986. if (texture->GetMultiSample() > 1 && texture->GetAutoResolve() && texture->IsResolveDirty())
  987. {
  988. if (texture->GetType() == Texture2D::GetTypeStatic())
  989. ResolveToTexture_D3D11(static_cast<Texture2D*>(texture));
  990. if (texture->GetType() == TextureCube::GetTypeStatic())
  991. ResolveToTexture_D3D11(static_cast<TextureCube*>(texture));
  992. }
  993. }
  994. if (texture && texture->GetLevelsDirty())
  995. texture->RegenerateLevels();
  996. }
  997. if (texture && texture->GetParametersDirty())
  998. {
  999. texture->UpdateParameters();
  1000. textures_[index] = nullptr; // Force reassign
  1001. }
  1002. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1003. if (texture != textures_[index])
  1004. {
  1005. if (impl->firstDirtyTexture_ == M_MAX_UNSIGNED)
  1006. impl->firstDirtyTexture_ = impl->lastDirtyTexture_ = index;
  1007. else
  1008. {
  1009. if (index < impl->firstDirtyTexture_)
  1010. impl->firstDirtyTexture_ = index;
  1011. if (index > impl->lastDirtyTexture_)
  1012. impl->lastDirtyTexture_ = index;
  1013. }
  1014. textures_[index] = texture;
  1015. impl->shaderResourceViews_[index] = texture ? (ID3D11ShaderResourceView*)texture->GetShaderResourceView() : nullptr;
  1016. impl->samplers_[index] = texture ? (ID3D11SamplerState*)texture->GetSampler() : nullptr;
  1017. impl->texturesDirty_ = true;
  1018. }
  1019. }
  1020. void Graphics::SetDefaultTextureFilterMode_D3D11(TextureFilterMode mode)
  1021. {
  1022. if (mode != defaultTextureFilterMode_)
  1023. {
  1024. defaultTextureFilterMode_ = mode;
  1025. SetTextureParametersDirty_D3D11();
  1026. }
  1027. }
  1028. void Graphics::SetDefaultTextureAnisotropy_D3D11(unsigned level)
  1029. {
  1030. level = Max(level, 1U);
  1031. if (level != defaultTextureAnisotropy_)
  1032. {
  1033. defaultTextureAnisotropy_ = level;
  1034. SetTextureParametersDirty_D3D11();
  1035. }
  1036. }
  1037. void Graphics::SetTextureParametersDirty_D3D11()
  1038. {
  1039. MutexLock lock(gpuObjectMutex_);
  1040. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1041. {
  1042. Texture* texture = dynamic_cast<Texture*>(*i);
  1043. if (texture)
  1044. texture->SetParametersDirty();
  1045. }
  1046. }
  1047. void Graphics::ResetRenderTargets_D3D11()
  1048. {
  1049. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1050. SetRenderTarget_D3D11(i, (RenderSurface*)nullptr);
  1051. SetDepthStencil_D3D11((RenderSurface*)nullptr);
  1052. SetViewport_D3D11(IntRect(0, 0, width_, height_));
  1053. }
  1054. void Graphics::ResetRenderTarget_D3D11(unsigned index)
  1055. {
  1056. SetRenderTarget_D3D11(index, (RenderSurface*)nullptr);
  1057. }
  1058. void Graphics::ResetDepthStencil_D3D11()
  1059. {
  1060. SetDepthStencil_D3D11((RenderSurface*)nullptr);
  1061. }
  1062. void Graphics::SetRenderTarget_D3D11(unsigned index, RenderSurface* renderTarget)
  1063. {
  1064. if (index >= MAX_RENDERTARGETS)
  1065. return;
  1066. if (renderTarget != renderTargets_[index])
  1067. {
  1068. renderTargets_[index] = renderTarget;
  1069. GetImpl_D3D11()->renderTargetsDirty_ = true;
  1070. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1071. if (renderTarget)
  1072. {
  1073. Texture* parentTexture = renderTarget->GetParentTexture();
  1074. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1075. {
  1076. if (textures_[i] == parentTexture)
  1077. SetTexture_D3D11(i, textures_[i]->GetBackupTexture());
  1078. }
  1079. // If multisampled, mark the texture & surface needing resolve
  1080. if (parentTexture->GetMultiSample() > 1 && parentTexture->GetAutoResolve())
  1081. {
  1082. parentTexture->SetResolveDirty(true);
  1083. renderTarget->SetResolveDirty(true);
  1084. }
  1085. // If mipmapped, mark the levels needing regeneration
  1086. if (parentTexture->GetLevels() > 1)
  1087. parentTexture->SetLevelsDirty();
  1088. }
  1089. }
  1090. }
  1091. void Graphics::SetRenderTarget_D3D11(unsigned index, Texture2D* texture)
  1092. {
  1093. RenderSurface* renderTarget = nullptr;
  1094. if (texture)
  1095. renderTarget = texture->GetRenderSurface();
  1096. SetRenderTarget_D3D11(index, renderTarget);
  1097. }
  1098. void Graphics::SetDepthStencil_D3D11(RenderSurface* depthStencil)
  1099. {
  1100. if (depthStencil != depthStencil_)
  1101. {
  1102. depthStencil_ = depthStencil;
  1103. GetImpl_D3D11()->renderTargetsDirty_ = true;
  1104. }
  1105. }
  1106. void Graphics::SetDepthStencil_D3D11(Texture2D* texture)
  1107. {
  1108. RenderSurface* depthStencil = nullptr;
  1109. if (texture)
  1110. depthStencil = texture->GetRenderSurface();
  1111. SetDepthStencil_D3D11(depthStencil);
  1112. // Constant depth bias depends on the bitdepth
  1113. GetImpl_D3D11()->rasterizerStateDirty_ = true;
  1114. }
  1115. void Graphics::SetViewport_D3D11(const IntRect& rect)
  1116. {
  1117. IntVector2 size = GetRenderTargetDimensions_D3D11();
  1118. IntRect rectCopy = rect;
  1119. if (rectCopy.right_ <= rectCopy.left_)
  1120. rectCopy.right_ = rectCopy.left_ + 1;
  1121. if (rectCopy.bottom_ <= rectCopy.top_)
  1122. rectCopy.bottom_ = rectCopy.top_ + 1;
  1123. rectCopy.left_ = Clamp(rectCopy.left_, 0, size.x_);
  1124. rectCopy.top_ = Clamp(rectCopy.top_, 0, size.y_);
  1125. rectCopy.right_ = Clamp(rectCopy.right_, 0, size.x_);
  1126. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, size.y_);
  1127. static D3D11_VIEWPORT d3dViewport;
  1128. d3dViewport.TopLeftX = (float)rectCopy.left_;
  1129. d3dViewport.TopLeftY = (float)rectCopy.top_;
  1130. d3dViewport.Width = (float)(rectCopy.right_ - rectCopy.left_);
  1131. d3dViewport.Height = (float)(rectCopy.bottom_ - rectCopy.top_);
  1132. d3dViewport.MinDepth = 0.0f;
  1133. d3dViewport.MaxDepth = 1.0f;
  1134. GetImpl_D3D11()->deviceContext_->RSSetViewports(1, &d3dViewport);
  1135. viewport_ = rectCopy;
  1136. // Disable scissor test, needs to be re-enabled by the user
  1137. SetScissorTest_D3D11(false);
  1138. }
  1139. void Graphics::SetBlendMode_D3D11(BlendMode mode, bool alphaToCoverage)
  1140. {
  1141. if (mode != blendMode_ || alphaToCoverage != alphaToCoverage_)
  1142. {
  1143. blendMode_ = mode;
  1144. alphaToCoverage_ = alphaToCoverage;
  1145. GetImpl_D3D11()->blendStateDirty_ = true;
  1146. }
  1147. }
  1148. void Graphics::SetColorWrite_D3D11(bool enable)
  1149. {
  1150. if (enable != colorWrite_)
  1151. {
  1152. colorWrite_ = enable;
  1153. GetImpl_D3D11()->blendStateDirty_ = true;
  1154. }
  1155. }
  1156. void Graphics::SetCullMode_D3D11(CullMode mode)
  1157. {
  1158. if (mode != cullMode_)
  1159. {
  1160. cullMode_ = mode;
  1161. GetImpl_D3D11()->rasterizerStateDirty_ = true;
  1162. }
  1163. }
  1164. void Graphics::SetDepthBias_D3D11(float constantBias, float slopeScaledBias)
  1165. {
  1166. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1167. {
  1168. constantDepthBias_ = constantBias;
  1169. slopeScaledDepthBias_ = slopeScaledBias;
  1170. GetImpl_D3D11()->rasterizerStateDirty_ = true;
  1171. }
  1172. }
  1173. void Graphics::SetDepthTest_D3D11(CompareMode mode)
  1174. {
  1175. if (mode != depthTestMode_)
  1176. {
  1177. depthTestMode_ = mode;
  1178. GetImpl_D3D11()->depthStateDirty_ = true;
  1179. }
  1180. }
  1181. void Graphics::SetDepthWrite_D3D11(bool enable)
  1182. {
  1183. if (enable != depthWrite_)
  1184. {
  1185. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1186. depthWrite_ = enable;
  1187. impl->depthStateDirty_ = true;
  1188. // Also affects whether a read-only version of depth-stencil should be bound, to allow sampling
  1189. impl->renderTargetsDirty_ = true;
  1190. }
  1191. }
  1192. void Graphics::SetFillMode_D3D11(FillMode mode)
  1193. {
  1194. if (mode != fillMode_)
  1195. {
  1196. fillMode_ = mode;
  1197. GetImpl_D3D11()->rasterizerStateDirty_ = true;
  1198. }
  1199. }
  1200. void Graphics::SetLineAntiAlias_D3D11(bool enable)
  1201. {
  1202. if (enable != lineAntiAlias_)
  1203. {
  1204. lineAntiAlias_ = enable;
  1205. GetImpl_D3D11()->rasterizerStateDirty_ = true;
  1206. }
  1207. }
  1208. void Graphics::SetScissorTest_D3D11(bool enable, const Rect& rect, bool borderInclusive)
  1209. {
  1210. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1211. // Disable scissor in that case to reduce state changes
  1212. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1213. enable = false;
  1214. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1215. if (enable)
  1216. {
  1217. IntVector2 rtSize(GetRenderTargetDimensions_D3D11());
  1218. IntVector2 viewSize(viewport_.Size());
  1219. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1220. IntRect intRect;
  1221. int expand = borderInclusive ? 1 : 0;
  1222. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1223. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1224. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1225. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1226. if (intRect.right_ == intRect.left_)
  1227. intRect.right_++;
  1228. if (intRect.bottom_ == intRect.top_)
  1229. intRect.bottom_++;
  1230. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1231. enable = false;
  1232. if (enable && intRect != scissorRect_)
  1233. {
  1234. scissorRect_ = intRect;
  1235. impl->scissorRectDirty_ = true;
  1236. }
  1237. }
  1238. if (enable != scissorTest_)
  1239. {
  1240. scissorTest_ = enable;
  1241. impl->rasterizerStateDirty_ = true;
  1242. }
  1243. }
  1244. void Graphics::SetScissorTest_D3D11(bool enable, const IntRect& rect)
  1245. {
  1246. IntVector2 rtSize(GetRenderTargetDimensions_D3D11());
  1247. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1248. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1249. if (enable)
  1250. {
  1251. IntRect intRect;
  1252. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1253. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1254. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1255. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1256. if (intRect.right_ == intRect.left_)
  1257. intRect.right_++;
  1258. if (intRect.bottom_ == intRect.top_)
  1259. intRect.bottom_++;
  1260. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1261. enable = false;
  1262. if (enable && intRect != scissorRect_)
  1263. {
  1264. scissorRect_ = intRect;
  1265. impl->scissorRectDirty_ = true;
  1266. }
  1267. }
  1268. if (enable != scissorTest_)
  1269. {
  1270. scissorTest_ = enable;
  1271. impl->rasterizerStateDirty_ = true;
  1272. }
  1273. }
  1274. void Graphics::SetStencilTest_D3D11(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, u32 stencilRef,
  1275. u32 compareMask, u32 writeMask)
  1276. {
  1277. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1278. if (enable != stencilTest_)
  1279. {
  1280. stencilTest_ = enable;
  1281. impl->depthStateDirty_ = true;
  1282. }
  1283. if (enable)
  1284. {
  1285. if (mode != stencilTestMode_)
  1286. {
  1287. stencilTestMode_ = mode;
  1288. impl->depthStateDirty_ = true;
  1289. }
  1290. if (pass != stencilPass_)
  1291. {
  1292. stencilPass_ = pass;
  1293. impl->depthStateDirty_ = true;
  1294. }
  1295. if (fail != stencilFail_)
  1296. {
  1297. stencilFail_ = fail;
  1298. impl->depthStateDirty_ = true;
  1299. }
  1300. if (zFail != stencilZFail_)
  1301. {
  1302. stencilZFail_ = zFail;
  1303. impl->depthStateDirty_ = true;
  1304. }
  1305. if (compareMask != stencilCompareMask_)
  1306. {
  1307. stencilCompareMask_ = compareMask;
  1308. impl->depthStateDirty_ = true;
  1309. }
  1310. if (writeMask != stencilWriteMask_)
  1311. {
  1312. stencilWriteMask_ = writeMask;
  1313. impl->depthStateDirty_ = true;
  1314. }
  1315. if (stencilRef != stencilRef_)
  1316. {
  1317. stencilRef_ = stencilRef;
  1318. impl->stencilRefDirty_ = true;
  1319. impl->depthStateDirty_ = true;
  1320. }
  1321. }
  1322. }
  1323. void Graphics::SetClipPlane_D3D11(bool enable, const Plane& clipPlane, const Matrix3x4& view, const Matrix4& projection)
  1324. {
  1325. useClipPlane_ = enable;
  1326. if (enable)
  1327. {
  1328. Matrix4 viewProj = projection * view;
  1329. clipPlane_ = clipPlane.Transformed(viewProj).ToVector4();
  1330. SetShaderParameter_D3D11(VSP_CLIPPLANE, clipPlane_);
  1331. }
  1332. }
  1333. bool Graphics::IsInitialized_D3D11() const
  1334. {
  1335. return window_ != nullptr && GetImpl_D3D11()->GetDevice() != nullptr;
  1336. }
  1337. Vector<int> Graphics::GetMultiSampleLevels_D3D11() const
  1338. {
  1339. Vector<int> ret;
  1340. ret.Push(1);
  1341. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1342. if (impl->device_)
  1343. {
  1344. for (unsigned i = 2; i <= 16; ++i)
  1345. {
  1346. if (impl->CheckMultiSampleSupport(sRGB_ ? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM, i))
  1347. ret.Push(i);
  1348. }
  1349. }
  1350. return ret;
  1351. }
  1352. unsigned Graphics::GetFormat_D3D11(CompressedFormat format) const
  1353. {
  1354. switch (format)
  1355. {
  1356. case CF_RGBA:
  1357. return DXGI_FORMAT_R8G8B8A8_UNORM;
  1358. case CF_DXT1:
  1359. return DXGI_FORMAT_BC1_UNORM;
  1360. case CF_DXT3:
  1361. return DXGI_FORMAT_BC2_UNORM;
  1362. case CF_DXT5:
  1363. return DXGI_FORMAT_BC3_UNORM;
  1364. default:
  1365. return 0;
  1366. }
  1367. }
  1368. ShaderVariation* Graphics::GetShader_D3D11(ShaderType type, const String& name, const String& defines) const
  1369. {
  1370. return GetShader_D3D11(type, name.CString(), defines.CString());
  1371. }
  1372. ShaderVariation* Graphics::GetShader_D3D11(ShaderType type, const char* name, const char* defines) const
  1373. {
  1374. if (lastShaderName_ != name || !lastShader_)
  1375. {
  1376. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1377. String fullShaderName = shaderPath_ + name + shaderExtension_;
  1378. // Try to reduce repeated error log prints because of missing shaders
  1379. if (lastShaderName_ == name && !cache->Exists(fullShaderName))
  1380. return nullptr;
  1381. lastShader_ = cache->GetResource<Shader>(fullShaderName);
  1382. lastShaderName_ = name;
  1383. }
  1384. return lastShader_ ? lastShader_->GetVariation(type, defines) : nullptr;
  1385. }
  1386. VertexBuffer* Graphics::GetVertexBuffer_D3D11(unsigned index) const
  1387. {
  1388. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : nullptr;
  1389. }
  1390. ShaderProgram_D3D11* Graphics::GetShaderProgram_D3D11() const
  1391. {
  1392. return GetImpl_D3D11()->shaderProgram_;
  1393. }
  1394. TextureUnit Graphics::GetTextureUnit_D3D11(const String& name)
  1395. {
  1396. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1397. if (i != textureUnits_.End())
  1398. return i->second_;
  1399. else
  1400. return MAX_TEXTURE_UNITS;
  1401. }
  1402. const String& Graphics::GetTextureUnitName_D3D11(TextureUnit unit)
  1403. {
  1404. for (HashMap<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1405. {
  1406. if (i->second_ == unit)
  1407. return i->first_;
  1408. }
  1409. return String::EMPTY;
  1410. }
  1411. Texture* Graphics::GetTexture_D3D11(unsigned index) const
  1412. {
  1413. return index < MAX_TEXTURE_UNITS ? textures_[index] : nullptr;
  1414. }
  1415. RenderSurface* Graphics::GetRenderTarget_D3D11(unsigned index) const
  1416. {
  1417. return index < MAX_RENDERTARGETS ? renderTargets_[index] : nullptr;
  1418. }
  1419. IntVector2 Graphics::GetRenderTargetDimensions_D3D11() const
  1420. {
  1421. int width, height;
  1422. if (renderTargets_[0])
  1423. {
  1424. width = renderTargets_[0]->GetWidth();
  1425. height = renderTargets_[0]->GetHeight();
  1426. }
  1427. else if (depthStencil_) // Depth-only rendering
  1428. {
  1429. width = depthStencil_->GetWidth();
  1430. height = depthStencil_->GetHeight();
  1431. }
  1432. else
  1433. {
  1434. width = width_;
  1435. height = height_;
  1436. }
  1437. return IntVector2(width, height);
  1438. }
  1439. bool Graphics::GetDither_D3D11() const
  1440. {
  1441. return false;
  1442. }
  1443. bool Graphics::IsDeviceLost_D3D11() const
  1444. {
  1445. // Direct3D11 graphics context is never considered lost
  1446. /// \todo The device could be lost in case of graphics adapters getting disabled during runtime. This is not currently handled
  1447. return false;
  1448. }
  1449. void Graphics::OnWindowResized_D3D11()
  1450. {
  1451. if (!GetImpl_D3D11()->device_ || !window_)
  1452. return;
  1453. int newWidth, newHeight;
  1454. SDL_GetWindowSize(window_, &newWidth, &newHeight);
  1455. if (newWidth == width_ && newHeight == height_)
  1456. return;
  1457. UpdateSwapChain_D3D11(newWidth, newHeight);
  1458. // Reset rendertargets and viewport for the new screen size
  1459. ResetRenderTargets_D3D11();
  1460. URHO3D_LOGDEBUGF("Window was resized to %dx%d", width_, height_);
  1461. using namespace ScreenMode;
  1462. VariantMap& eventData = GetEventDataMap();
  1463. eventData[P_WIDTH] = width_;
  1464. eventData[P_HEIGHT] = height_;
  1465. eventData[P_FULLSCREEN] = screenParams_.fullscreen_;
  1466. eventData[P_RESIZABLE] = screenParams_.resizable_;
  1467. eventData[P_BORDERLESS] = screenParams_.borderless_;
  1468. eventData[P_HIGHDPI] = screenParams_.highDPI_;
  1469. SendEvent(E_SCREENMODE, eventData);
  1470. }
  1471. void Graphics::OnWindowMoved_D3D11()
  1472. {
  1473. if (!GetImpl_D3D11()->device_ || !window_ || screenParams_.fullscreen_)
  1474. return;
  1475. int newX, newY;
  1476. SDL_GetWindowPosition(window_, &newX, &newY);
  1477. if (newX == position_.x_ && newY == position_.y_)
  1478. return;
  1479. position_.x_ = newX;
  1480. position_.y_ = newY;
  1481. URHO3D_LOGTRACEF("Window was moved to %d,%d", position_.x_, position_.y_);
  1482. using namespace WindowPos;
  1483. VariantMap& eventData = GetEventDataMap();
  1484. eventData[P_X] = position_.x_;
  1485. eventData[P_Y] = position_.y_;
  1486. SendEvent(E_WINDOWPOS, eventData);
  1487. }
  1488. void Graphics::CleanupShaderPrograms_D3D11(ShaderVariation* variation)
  1489. {
  1490. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1491. for (ShaderProgramMap_D3D11::Iterator i = impl->shaderPrograms_.Begin(); i != impl->shaderPrograms_.End();)
  1492. {
  1493. if (i->first_.first_ == variation || i->first_.second_ == variation)
  1494. i = impl->shaderPrograms_.Erase(i);
  1495. else
  1496. ++i;
  1497. }
  1498. if (vertexShader_ == variation || pixelShader_ == variation)
  1499. impl->shaderProgram_ = nullptr;
  1500. }
  1501. ConstantBuffer* Graphics::GetOrCreateConstantBuffer_D3D11(ShaderType type, unsigned index, unsigned size)
  1502. {
  1503. GraphicsImpl_D3D11* impl = GetImpl_D3D11();
  1504. // Ensure that different shader types and index slots get unique buffers, even if the size is same
  1505. hash32 key = type | (index << 1) | (size << 4);
  1506. ConstantBufferMap::Iterator i = impl->allConstantBuffers_.Find(key);
  1507. if (i != impl->allConstantBuffers_.End())
  1508. return i->second_.Get();
  1509. else
  1510. {
  1511. SharedPtr<ConstantBuffer> newConstantBuffer(new ConstantBuffer(context_));
  1512. newConstantBuffer->SetSize(size);
  1513. impl->allConstantBuffers_[key] = newConstantBuffer;
  1514. return newConstantBuffer.Get();
  1515. }
  1516. }
  1517. unsigned Graphics::GetAlphaFormat_D3D11()
  1518. {
  1519. return DXGI_FORMAT_A8_UNORM;
  1520. }
  1521. unsigned Graphics::GetLuminanceFormat_D3D11()
  1522. {
  1523. // Note: not same sampling behavior as on D3D9; need to sample the R channel only
  1524. return DXGI_FORMAT_R8_UNORM;
  1525. }
  1526. unsigned Graphics::GetLuminanceAlphaFormat_D3D11()
  1527. {
  1528. // Note: not same sampling behavior as on D3D9; need to sample the RG channels
  1529. return DXGI_FORMAT_R8G8_UNORM;
  1530. }
  1531. unsigned Graphics::GetRGBFormat_D3D11()
  1532. {
  1533. return DXGI_FORMAT_R8G8B8A8_UNORM;
  1534. }
  1535. unsigned Graphics::GetRGBAFormat_D3D11()
  1536. {
  1537. return DXGI_FORMAT_R8G8B8A8_UNORM;
  1538. }
  1539. unsigned Graphics::GetRGBA16Format_D3D11()
  1540. {
  1541. return DXGI_FORMAT_R16G16B16A16_UNORM;
  1542. }
  1543. unsigned Graphics::GetRGBAFloat16Format_D3D11()
  1544. {
  1545. return DXGI_FORMAT_R16G16B16A16_FLOAT;
  1546. }
  1547. unsigned Graphics::GetRGBAFloat32Format_D3D11()
  1548. {
  1549. return DXGI_FORMAT_R32G32B32A32_FLOAT;
  1550. }
  1551. unsigned Graphics::GetRG16Format_D3D11()
  1552. {
  1553. return DXGI_FORMAT_R16G16_UNORM;
  1554. }
  1555. unsigned Graphics::GetRGFloat16Format_D3D11()
  1556. {
  1557. return DXGI_FORMAT_R16G16_FLOAT;
  1558. }
  1559. unsigned Graphics::GetRGFloat32Format_D3D11()
  1560. {
  1561. return DXGI_FORMAT_R32G32_FLOAT;
  1562. }
  1563. unsigned Graphics::GetFloat16Format_D3D11()
  1564. {
  1565. return DXGI_FORMAT_R16_FLOAT;
  1566. }
  1567. unsigned Graphics::GetFloat32Format_D3D11()
  1568. {
  1569. return DXGI_FORMAT_R32_FLOAT;
  1570. }
  1571. unsigned Graphics::GetLinearDepthFormat_D3D11()
  1572. {
  1573. return DXGI_FORMAT_R32_FLOAT;
  1574. }
  1575. unsigned Graphics::GetDepthStencilFormat_D3D11()
  1576. {
  1577. return DXGI_FORMAT_R24G8_TYPELESS;
  1578. }
  1579. unsigned Graphics::GetReadableDepthFormat_D3D11()
  1580. {
  1581. return DXGI_FORMAT_R24G8_TYPELESS;
  1582. }
  1583. unsigned Graphics::GetFormat_D3D11(const String& formatName)
  1584. {
  1585. String nameLower = formatName.ToLower().Trimmed();
  1586. if (nameLower == "a")
  1587. return GetAlphaFormat_D3D11();
  1588. if (nameLower == "l")
  1589. return GetLuminanceFormat_D3D11();
  1590. if (nameLower == "la")
  1591. return GetLuminanceAlphaFormat_D3D11();
  1592. if (nameLower == "rgb")
  1593. return GetRGBFormat_D3D11();
  1594. if (nameLower == "rgba")
  1595. return GetRGBAFormat_D3D11();
  1596. if (nameLower == "rgba16")
  1597. return GetRGBA16Format_D3D11();
  1598. if (nameLower == "rgba16f")
  1599. return GetRGBAFloat16Format_D3D11();
  1600. if (nameLower == "rgba32f")
  1601. return GetRGBAFloat32Format_D3D11();
  1602. if (nameLower == "rg16")
  1603. return GetRG16Format_D3D11();
  1604. if (nameLower == "rg16f")
  1605. return GetRGFloat16Format_D3D11();
  1606. if (nameLower == "rg32f")
  1607. return GetRGFloat32Format_D3D11();
  1608. if (nameLower == "r16f")
  1609. return GetFloat16Format_D3D11();
  1610. if (nameLower == "r32f" || nameLower == "float")
  1611. return GetFloat32Format_D3D11();
  1612. if (nameLower == "lineardepth" || nameLower == "depth")
  1613. return GetLinearDepthFormat_D3D11();
  1614. if (nameLower == "d24s8")
  1615. return GetDepthStencilFormat_D3D11();
  1616. if (nameLower == "readabledepth" || nameLower == "hwdepth")
  1617. return GetReadableDepthFormat_D3D11();
  1618. return GetRGBFormat_D3D11();
  1619. }
  1620. unsigned Graphics::GetMaxBones_D3D11()
  1621. {
  1622. return 128;
  1623. }
  1624. bool Graphics::GetGL3Support_D3D11()
  1625. {
  1626. return false;
  1627. }
  1628. bool Graphics::OpenWindow_D3D11(int width, int height, bool resizable, bool borderless)
  1629. {
  1630. if (!externalWindow_)
  1631. {
  1632. unsigned flags = 0;
  1633. if (resizable)
  1634. flags |= SDL_WINDOW_RESIZABLE;
  1635. if (borderless)
  1636. flags |= SDL_WINDOW_BORDERLESS;
  1637. window_ = SDL_CreateWindow(windowTitle_.CString(), position_.x_, position_.y_, width, height, flags);
  1638. }
  1639. else
  1640. window_ = SDL_CreateWindowFrom(externalWindow_, 0);
  1641. if (!window_)
  1642. {
  1643. URHO3D_LOGERRORF("Could not create window, root cause: '%s'", SDL_GetError());
  1644. return false;
  1645. }
  1646. SDL_GetWindowPosition(window_, &position_.x_, &position_.y_);
  1647. CreateWindowIcon();
  1648. return true;
  1649. }
  1650. void Graphics::AdjustWindow_D3D11(int& newWidth, int& newHeight, bool& newFullscreen, bool& newBorderless, bool& newResizable, int& monitor)
  1651. {
  1652. if (!externalWindow_)
  1653. {
  1654. // Keep current window position because it may change in intermediate callbacks
  1655. const IntVector2 oldPosition = position_;
  1656. bool reposition = false;
  1657. bool resizePostponed = false;
  1658. if (!newWidth || !newHeight)
  1659. {
  1660. SDL_MaximizeWindow(window_);
  1661. SDL_GetWindowSize(window_, &newWidth, &newHeight);
  1662. }
  1663. else
  1664. {
  1665. SDL_Rect display_rect;
  1666. SDL_GetDisplayBounds(monitor, &display_rect);
  1667. reposition = newFullscreen || (newBorderless && newWidth >= display_rect.w && newHeight >= display_rect.h);
  1668. if (reposition)
  1669. {
  1670. // Reposition the window on the specified monitor if it's supposed to cover the entire monitor
  1671. SDL_SetWindowPosition(window_, display_rect.x, display_rect.y);
  1672. }
  1673. // Postpone window resize if exiting fullscreen to avoid redundant resolution change
  1674. if (!newFullscreen && screenParams_.fullscreen_)
  1675. resizePostponed = true;
  1676. else
  1677. SDL_SetWindowSize(window_, newWidth, newHeight);
  1678. }
  1679. // Turn off window fullscreen mode so it gets repositioned to the correct monitor
  1680. SDL_SetWindowFullscreen(window_, SDL_FALSE);
  1681. // 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
  1682. if (!newFullscreen) SDL_HideWindow(window_);
  1683. SDL_SetWindowFullscreen(window_, newFullscreen ? SDL_WINDOW_FULLSCREEN : 0);
  1684. SDL_SetWindowBordered(window_, newBorderless ? SDL_FALSE : SDL_TRUE);
  1685. SDL_SetWindowResizable(window_, newResizable ? SDL_TRUE : SDL_FALSE);
  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. Vector<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_U32_MASK_ALL_BITS;
  1970. stencilWriteMask_ = M_U32_MASK_ALL_BITS;
  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_U32;
  1982. impl->depthStateHash_ = M_MAX_U32;
  1983. impl->rasterizerStateHash_ = M_MAX_U32;
  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. hash64 newVertexDeclarationHash = 0;
  2035. for (i32 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. hash32 newBlendStateHash = (hash32)((colorWrite_ ? 1 : 0) | (alphaToCoverage_ ? 2 : 0) | (blendMode_ << 2));
  2063. if (newBlendStateHash != impl->blendStateHash_)
  2064. {
  2065. HashMap<hash32, 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. hash32 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<hash32, 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 = (UINT8)stencilCompareMask_;
  2114. stateDesc.StencilWriteMask = (UINT8)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. hash32 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<hash32, 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. }