D3D11Graphics.cpp 83 KB

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