D3D11Graphics.cpp 84 KB

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