D3D11Graphics.cpp 84 KB

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