D3D11Graphics.cpp 81 KB

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