D3D11Graphics.cpp 84 KB

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