D3D11Graphics.cpp 82 KB

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