D3D11Graphics.cpp 84 KB

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