D3D11Graphics.cpp 82 KB

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