D3D9Graphics.cpp 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651
  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/Graphics.h"
  27. #include "../../Graphics/GraphicsEvents.h"
  28. #include "../../Graphics/GraphicsImpl.h"
  29. #include "../../Graphics/IndexBuffer.h"
  30. #include "../../Graphics/Shader.h"
  31. #include "../../Graphics/ShaderPrecache.h"
  32. #include "../../Graphics/ShaderProgram.h"
  33. #include "../../Graphics/Texture2D.h"
  34. #include "../../Graphics/TextureCube.h"
  35. #include "../../Graphics/VertexBuffer.h"
  36. #include "../../Graphics/VertexDeclaration.h"
  37. #include "../../IO/File.h"
  38. #include "../../IO/Log.h"
  39. #include "../../Resource/ResourceCache.h"
  40. // ATOMIC BEGIN
  41. #include <SDL/include/SDL.h>
  42. #include <SDL/include/SDL_syswm.h>
  43. // ATOMIC END
  44. #include "../../DebugNew.h"
  45. #ifdef _MSC_VER
  46. #pragma warning(disable:4355)
  47. #endif
  48. // Prefer the high-performance GPU on switchable GPU systems
  49. extern "C"
  50. {
  51. __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  52. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  53. }
  54. // Fix missing define in MinGW headers
  55. #ifndef D3DPRESENT_LINEAR_CONTENT
  56. #define D3DPRESENT_LINEAR_CONTENT 0x00000002L
  57. #endif
  58. #ifndef D3DSTREAMSOURCE_INDEXEDDATA
  59. #define D3DSTREAMSOURCE_INDEXEDDATA (1<<30)
  60. #endif
  61. #ifndef D3DSTREAMSOURCE_INSTANCEDATA
  62. #define D3DSTREAMSOURCE_INSTANCEDATA (2<<30)
  63. #endif
  64. namespace Atomic
  65. {
  66. static const D3DCMPFUNC d3dCmpFunc[] =
  67. {
  68. D3DCMP_ALWAYS,
  69. D3DCMP_EQUAL,
  70. D3DCMP_NOTEQUAL,
  71. D3DCMP_LESS,
  72. D3DCMP_LESSEQUAL,
  73. D3DCMP_GREATER,
  74. D3DCMP_GREATEREQUAL
  75. };
  76. static const D3DTEXTUREFILTERTYPE d3dMinMagFilter[] =
  77. {
  78. D3DTEXF_POINT,
  79. D3DTEXF_LINEAR,
  80. D3DTEXF_LINEAR,
  81. D3DTEXF_ANISOTROPIC
  82. };
  83. static const D3DTEXTUREFILTERTYPE d3dMipFilter[] =
  84. {
  85. D3DTEXF_POINT,
  86. D3DTEXF_POINT,
  87. D3DTEXF_LINEAR,
  88. D3DTEXF_ANISOTROPIC
  89. };
  90. static const D3DTEXTUREADDRESS d3dAddressMode[] =
  91. {
  92. D3DTADDRESS_WRAP,
  93. D3DTADDRESS_MIRROR,
  94. D3DTADDRESS_CLAMP,
  95. D3DTADDRESS_BORDER
  96. };
  97. static const DWORD d3dBlendEnable[] =
  98. {
  99. FALSE,
  100. TRUE,
  101. TRUE,
  102. TRUE,
  103. TRUE,
  104. TRUE,
  105. TRUE,
  106. TRUE
  107. };
  108. static const D3DBLEND d3dSrcBlend[] =
  109. {
  110. D3DBLEND_ONE,
  111. D3DBLEND_ONE,
  112. D3DBLEND_DESTCOLOR,
  113. D3DBLEND_SRCALPHA,
  114. D3DBLEND_SRCALPHA,
  115. D3DBLEND_ONE,
  116. D3DBLEND_INVDESTALPHA,
  117. D3DBLEND_ONE,
  118. D3DBLEND_SRCALPHA,
  119. };
  120. static const D3DBLEND d3dDestBlend[] =
  121. {
  122. D3DBLEND_ZERO,
  123. D3DBLEND_ONE,
  124. D3DBLEND_ZERO,
  125. D3DBLEND_INVSRCALPHA,
  126. D3DBLEND_ONE,
  127. D3DBLEND_INVSRCALPHA,
  128. D3DBLEND_DESTALPHA,
  129. D3DBLEND_ONE,
  130. D3DBLEND_ONE
  131. };
  132. static const D3DBLENDOP d3dBlendOp[] =
  133. {
  134. D3DBLENDOP_ADD,
  135. D3DBLENDOP_ADD,
  136. D3DBLENDOP_ADD,
  137. D3DBLENDOP_ADD,
  138. D3DBLENDOP_ADD,
  139. D3DBLENDOP_ADD,
  140. D3DBLENDOP_ADD,
  141. D3DBLENDOP_REVSUBTRACT,
  142. D3DBLENDOP_REVSUBTRACT
  143. };
  144. static const D3DCULL d3dCullMode[] =
  145. {
  146. D3DCULL_NONE,
  147. D3DCULL_CCW,
  148. D3DCULL_CW
  149. };
  150. static const D3DFILLMODE d3dFillMode[] =
  151. {
  152. D3DFILL_SOLID,
  153. D3DFILL_WIREFRAME,
  154. D3DFILL_POINT
  155. };
  156. static const D3DSTENCILOP d3dStencilOp[] =
  157. {
  158. D3DSTENCILOP_KEEP,
  159. D3DSTENCILOP_ZERO,
  160. D3DSTENCILOP_REPLACE,
  161. D3DSTENCILOP_INCR,
  162. D3DSTENCILOP_DECR
  163. };
  164. static unsigned GetD3DColor(const Color& color)
  165. {
  166. unsigned r = (unsigned)(Clamp(color.r_ * 255.0f, 0.0f, 255.0f));
  167. unsigned g = (unsigned)(Clamp(color.g_ * 255.0f, 0.0f, 255.0f));
  168. unsigned b = (unsigned)(Clamp(color.b_ * 255.0f, 0.0f, 255.0f));
  169. unsigned a = (unsigned)(Clamp(color.a_ * 255.0f, 0.0f, 255.0f));
  170. return (((a) & 0xff) << 24) | (((r) & 0xff) << 16) | (((g) & 0xff) << 8) | ((b) & 0xff);
  171. }
  172. static void GetD3DPrimitiveType(unsigned elementCount, PrimitiveType type, unsigned& primitiveCount,
  173. D3DPRIMITIVETYPE& d3dPrimitiveType)
  174. {
  175. switch (type)
  176. {
  177. case TRIANGLE_LIST:
  178. primitiveCount = elementCount / 3;
  179. d3dPrimitiveType = D3DPT_TRIANGLELIST;
  180. break;
  181. case LINE_LIST:
  182. primitiveCount = elementCount / 2;
  183. d3dPrimitiveType = D3DPT_LINELIST;
  184. break;
  185. case POINT_LIST:
  186. primitiveCount = elementCount;
  187. d3dPrimitiveType = D3DPT_POINTLIST;
  188. break;
  189. case TRIANGLE_STRIP:
  190. primitiveCount = elementCount - 2;
  191. d3dPrimitiveType = D3DPT_TRIANGLESTRIP;
  192. break;
  193. case LINE_STRIP:
  194. primitiveCount = elementCount - 1;
  195. d3dPrimitiveType = D3DPT_LINESTRIP;
  196. break;
  197. case TRIANGLE_FAN:
  198. primitiveCount = elementCount - 2;
  199. d3dPrimitiveType = D3DPT_TRIANGLEFAN;
  200. break;
  201. }
  202. }
  203. static HWND GetWindowHandle(SDL_Window* window)
  204. {
  205. SDL_SysWMinfo sysInfo;
  206. SDL_VERSION(&sysInfo.version);
  207. SDL_GetWindowWMInfo(window, &sysInfo);
  208. return sysInfo.info.win.window;
  209. }
  210. static unsigned readableDepthFormat = 0;
  211. const Vector2 Graphics::pixelUVOffset(0.5f, 0.5f);
  212. bool Graphics::gl3Support = false;
  213. Graphics::Graphics(Context* context) :
  214. Object(context),
  215. impl_(new GraphicsImpl()),
  216. window_(0),
  217. externalWindow_(0),
  218. width_(0),
  219. height_(0),
  220. position_(SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED),
  221. multiSample_(1),
  222. fullscreen_(false),
  223. borderless_(false),
  224. resizable_(false),
  225. highDPI_(false),
  226. vsync_(false),
  227. tripleBuffer_(false),
  228. flushGPU_(false),
  229. sRGB_(false),
  230. anisotropySupport_(false),
  231. dxtTextureSupport_(false),
  232. etcTextureSupport_(false),
  233. pvrtcTextureSupport_(false),
  234. hardwareShadowSupport_(false),
  235. lightPrepassSupport_(false),
  236. deferredSupport_(false),
  237. instancingSupport_(false),
  238. sRGBSupport_(false),
  239. sRGBWriteSupport_(false),
  240. numPrimitives_(0),
  241. numBatches_(0),
  242. maxScratchBufferRequest_(0),
  243. defaultTextureFilterMode_(FILTER_TRILINEAR),
  244. defaultTextureAnisotropy_(4),
  245. shaderPath_("Shaders/HLSL/"),
  246. shaderExtension_(".hlsl"),
  247. orientations_("LandscapeLeft LandscapeRight"),
  248. apiName_("D3D9")
  249. {
  250. SetTextureUnitMappings();
  251. // Initialize SDL now. Graphics should be the first SDL-using subsystem to be created
  252. SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_NOPARACHUTE
  253. | SDL_INIT_TIMER | SDL_INIT_HAPTIC ); // ATOMIC BEGIN HAPTIC //ATOMIC END
  254. // Register Graphics library object factories
  255. RegisterGraphicsLibrary(context_);
  256. }
  257. Graphics::~Graphics()
  258. {
  259. {
  260. MutexLock lock(gpuObjectMutex_);
  261. // Release all GPU objects that still exist
  262. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  263. (*i)->Release();
  264. gpuObjects_.Clear();
  265. }
  266. impl_->vertexDeclarations_.Clear();
  267. ATOMIC_SAFE_RELEASE(impl_->defaultColorSurface_);
  268. ATOMIC_SAFE_RELEASE(impl_->defaultDepthStencilSurface_);
  269. ATOMIC_SAFE_RELEASE(impl_->frameQuery_);
  270. ATOMIC_SAFE_RELEASE(impl_->device_);
  271. ATOMIC_SAFE_RELEASE(impl_->interface_);
  272. if (window_)
  273. {
  274. SDL_ShowCursor(SDL_TRUE);
  275. SDL_DestroyWindow(window_);
  276. window_ = 0;
  277. }
  278. delete impl_;
  279. impl_ = 0;
  280. // Shut down SDL now. Graphics should be the last SDL-using subsystem to be destroyed
  281. SDL_Quit();
  282. }
  283. bool Graphics::SetMode(int width, int height, bool fullscreen, bool borderless, bool resizable, bool highDPI, bool vsync,
  284. bool tripleBuffer, int multiSample)
  285. {
  286. ATOMIC_PROFILE(SetScreenMode);
  287. highDPI = false; // SDL does not support High DPI mode on Windows platform yet, so always disable it for now
  288. bool maximize = false;
  289. // Find out the full screen mode display format (match desktop color depth)
  290. SDL_DisplayMode mode;
  291. SDL_GetDesktopDisplayMode(0, &mode);
  292. D3DFORMAT fullscreenFormat = SDL_BITSPERPIXEL(mode.format) == 16 ? D3DFMT_R5G6B5 : D3DFMT_X8R8G8B8;
  293. // 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
  294. if (!width || !height)
  295. {
  296. if (fullscreen || borderless)
  297. {
  298. width = mode.w;
  299. height = mode.h;
  300. }
  301. else
  302. {
  303. maximize = resizable;
  304. width = 1024;
  305. height = 768;
  306. }
  307. }
  308. // Fullscreen or Borderless can not be resizable
  309. if (fullscreen || borderless)
  310. resizable = false;
  311. // Borderless cannot be fullscreen, they are mutually exclusive
  312. if (borderless)
  313. fullscreen = false;
  314. multiSample = Clamp(multiSample, 1, (int)D3DMULTISAMPLE_16_SAMPLES);
  315. // If nothing changes, do not reset the device
  316. if (width == width_ && height == height_ && fullscreen == fullscreen_ && borderless == borderless_ && resizable == resizable_ &&
  317. vsync == vsync_ && tripleBuffer == tripleBuffer_ && multiSample == multiSample_)
  318. return true;
  319. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  320. if (!window_)
  321. {
  322. if (!OpenWindow(width, height, resizable, borderless))
  323. return false;
  324. }
  325. if (!impl_->interface_)
  326. {
  327. if (!CreateInterface())
  328. return false;
  329. CheckFeatureSupport();
  330. }
  331. // Note: GetMultiSample() will not reflect the actual hardware multisample mode, but rather what the caller wanted.
  332. multiSample_ = multiSample;
  333. // Check fullscreen mode validity. Use a closest match if not found
  334. if (fullscreen)
  335. {
  336. PODVector<IntVector2> resolutions = GetResolutions();
  337. if (resolutions.Size())
  338. {
  339. unsigned best = 0;
  340. unsigned bestError = M_MAX_UNSIGNED;
  341. for (unsigned i = 0; i < resolutions.Size(); ++i)
  342. {
  343. unsigned error = (unsigned)(Abs(resolutions[i].x_ - width) + Abs(resolutions[i].y_ - height));
  344. if (error < bestError)
  345. {
  346. best = i;
  347. bestError = error;
  348. }
  349. }
  350. width = resolutions[best].x_;
  351. height = resolutions[best].y_;
  352. }
  353. }
  354. // Fall back to non-multisampled if unsupported multisampling mode
  355. if (multiSample > 1)
  356. {
  357. if (FAILED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, fullscreenFormat, FALSE,
  358. (D3DMULTISAMPLE_TYPE)multiSample, NULL)))
  359. multiSample = 1;
  360. }
  361. AdjustWindow(width, height, fullscreen, borderless);
  362. if (maximize)
  363. {
  364. Maximize();
  365. SDL_GetWindowSize(window_, &width, &height);
  366. }
  367. if (fullscreen)
  368. {
  369. impl_->presentParams_.BackBufferFormat = fullscreenFormat;
  370. impl_->presentParams_.Windowed = false;
  371. }
  372. else
  373. {
  374. impl_->presentParams_.BackBufferFormat = D3DFMT_UNKNOWN;
  375. impl_->presentParams_.Windowed = true;
  376. }
  377. impl_->presentParams_.BackBufferWidth = (UINT)width;
  378. impl_->presentParams_.BackBufferHeight = (UINT)height;
  379. impl_->presentParams_.BackBufferCount = tripleBuffer ? 2 : 1;
  380. impl_->presentParams_.MultiSampleType = multiSample > 1 ? (D3DMULTISAMPLE_TYPE)multiSample : D3DMULTISAMPLE_NONE;
  381. impl_->presentParams_.MultiSampleQuality = 0;
  382. impl_->presentParams_.SwapEffect = D3DSWAPEFFECT_DISCARD;
  383. impl_->presentParams_.hDeviceWindow = GetWindowHandle(window_);
  384. impl_->presentParams_.EnableAutoDepthStencil = TRUE;
  385. impl_->presentParams_.AutoDepthStencilFormat = D3DFMT_D24S8;
  386. impl_->presentParams_.Flags = D3DPRESENT_LINEAR_CONTENT;
  387. impl_->presentParams_.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
  388. if (vsync)
  389. impl_->presentParams_.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
  390. else
  391. impl_->presentParams_.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  392. width_ = width;
  393. height_ = height;
  394. fullscreen_ = fullscreen;
  395. borderless_ = borderless;
  396. resizable_ = resizable;
  397. highDPI_ = highDPI;
  398. vsync_ = vsync;
  399. tripleBuffer_ = tripleBuffer;
  400. if (!impl_->device_)
  401. {
  402. unsigned adapter = D3DADAPTER_DEFAULT;
  403. unsigned deviceType = D3DDEVTYPE_HAL;
  404. // Check for PerfHUD adapter
  405. for (unsigned i = 0; i < impl_->interface_->GetAdapterCount(); ++i)
  406. {
  407. D3DADAPTER_IDENTIFIER9 identifier;
  408. impl_->interface_->GetAdapterIdentifier(i, 0, &identifier);
  409. if (strstr(identifier.Description, "PerfHUD") != 0)
  410. {
  411. adapter = i;
  412. deviceType = D3DDEVTYPE_REF;
  413. break;
  414. }
  415. }
  416. impl_->interface_->GetAdapterIdentifier(adapter, 0, &impl_->adapterIdentifier_);
  417. if (!CreateDevice(adapter, deviceType))
  418. return false;
  419. }
  420. else
  421. ResetDevice();
  422. // Clear the initial window contents to black
  423. impl_->device_->BeginScene();
  424. Clear(CLEAR_COLOR);
  425. impl_->device_->EndScene();
  426. impl_->device_->Present(0, 0, 0, 0);
  427. #ifdef ATOMIC_LOGGING
  428. String msg;
  429. msg.AppendWithFormat("Set screen mode %dx%d %s", width_, height_, (fullscreen_ ? "fullscreen" : "windowed"));
  430. if (borderless_)
  431. msg.Append(" borderless");
  432. if (resizable_)
  433. msg.Append(" resizable");
  434. if (multiSample > 1)
  435. msg.AppendWithFormat(" multisample %d", multiSample);
  436. ATOMIC_LOGINFO(msg);
  437. #endif
  438. using namespace ScreenMode;
  439. VariantMap& eventData = GetEventDataMap();
  440. eventData[P_WIDTH] = width_;
  441. eventData[P_HEIGHT] = height_;
  442. eventData[P_FULLSCREEN] = fullscreen_;
  443. eventData[P_BORDERLESS] = borderless_;
  444. eventData[P_RESIZABLE] = resizable_;
  445. eventData[P_HIGHDPI] = highDPI_;
  446. SendEvent(E_SCREENMODE, eventData);
  447. return true;
  448. }
  449. bool Graphics::SetMode(int width, int height)
  450. {
  451. return SetMode(width, height, fullscreen_, borderless_, resizable_, highDPI_, vsync_, tripleBuffer_, multiSample_);
  452. }
  453. void Graphics::SetSRGB(bool enable)
  454. {
  455. sRGB_ = enable && sRGBWriteSupport_;
  456. }
  457. void Graphics::SetDither(bool enable)
  458. {
  459. // No effect on Direct3D9
  460. }
  461. void Graphics::SetFlushGPU(bool enable)
  462. {
  463. flushGPU_ = enable;
  464. }
  465. void Graphics::SetForceGL2(bool enable)
  466. {
  467. // No effect on Direct3D9
  468. }
  469. void Graphics::Close()
  470. {
  471. if (window_)
  472. {
  473. SDL_ShowCursor(SDL_TRUE);
  474. SDL_DestroyWindow(window_);
  475. window_ = 0;
  476. }
  477. }
  478. bool Graphics::TakeScreenShot(Image* destImage)
  479. {
  480. ATOMIC_PROFILE(TakeScreenShot);
  481. if (!impl_->device_)
  482. return false;
  483. if (IsDeviceLost())
  484. {
  485. ATOMIC_LOGERROR("Can not take screenshot while device is lost");
  486. return false;
  487. }
  488. D3DSURFACE_DESC surfaceDesc;
  489. impl_->defaultColorSurface_->GetDesc(&surfaceDesc);
  490. // If possible, get the backbuffer data, because it is a lot faster.
  491. // However, if we are multisampled, need to use the front buffer
  492. bool useBackBuffer = true;
  493. unsigned surfaceWidth = (unsigned)width_;
  494. unsigned surfaceHeight = (unsigned)height_;
  495. if (impl_->presentParams_.MultiSampleType)
  496. {
  497. // If windowed and multisampled, must still capture the whole screen
  498. if (!fullscreen_)
  499. {
  500. IntVector2 desktopSize = GetDesktopResolution();
  501. surfaceWidth = (unsigned)desktopSize.x_;
  502. surfaceHeight = (unsigned)desktopSize.y_;
  503. }
  504. useBackBuffer = false;
  505. surfaceDesc.Format = D3DFMT_A8R8G8B8;
  506. }
  507. IDirect3DSurface9* surface = 0;
  508. HRESULT hr = impl_->device_->CreateOffscreenPlainSurface(surfaceWidth, surfaceHeight, surfaceDesc.Format, D3DPOOL_SYSTEMMEM, &surface, 0);
  509. if (FAILED(hr))
  510. {
  511. ATOMIC_SAFE_RELEASE(surface);
  512. ATOMIC_LOGD3DERROR("Could not create surface for taking a screenshot", hr);
  513. return false;
  514. }
  515. if (useBackBuffer)
  516. hr = impl_->device_->GetRenderTargetData(impl_->defaultColorSurface_, surface);
  517. else
  518. hr = impl_->device_->GetFrontBufferData(0, surface);
  519. if (FAILED(hr))
  520. {
  521. ATOMIC_SAFE_RELEASE(surface);
  522. ATOMIC_LOGD3DERROR("Could not get rendertarget data for taking a screenshot", hr);
  523. return false;
  524. }
  525. // If capturing the whole screen, determine the window rect
  526. RECT sourceRect;
  527. if (surfaceHeight == height_ && surfaceWidth == width_)
  528. {
  529. sourceRect.left = 0;
  530. sourceRect.top = 0;
  531. sourceRect.right = width_;
  532. sourceRect.bottom = height_;
  533. }
  534. else
  535. {
  536. HWND hwnd = GetWindowHandle(window_);
  537. GetClientRect(hwnd, &sourceRect);
  538. ClientToScreen(hwnd, (LPPOINT)&sourceRect);
  539. }
  540. D3DLOCKED_RECT lockedRect;
  541. lockedRect.pBits = 0;
  542. hr = surface->LockRect(&lockedRect, &sourceRect, D3DLOCK_NOSYSLOCK | D3DLOCK_READONLY);
  543. if (FAILED(hr) || !lockedRect.pBits)
  544. {
  545. ATOMIC_SAFE_RELEASE(surface);
  546. ATOMIC_LOGD3DERROR("Could not lock surface for taking a screenshot", hr);
  547. return false;
  548. }
  549. destImage->SetSize(width_, height_, 3);
  550. unsigned char* destData = destImage->GetData();
  551. if (surfaceDesc.Format == D3DFMT_R5G6B5)
  552. {
  553. for (int y = 0; y < height_; ++y)
  554. {
  555. unsigned short* src = (unsigned short*)((unsigned char*)lockedRect.pBits + y * lockedRect.Pitch);
  556. unsigned char* dest = destData + y * width_ * 3;
  557. for (int x = 0; x < width_; ++x)
  558. {
  559. unsigned short rgb = *src++;
  560. int b = rgb & 31;
  561. int g = (rgb >> 5) & 63;
  562. int r = (rgb >> 11);
  563. dest[0] = (unsigned char)(r * 255.0f / 31.0f);
  564. dest[1] = (unsigned char)(g * 255.0f / 63.0f);
  565. dest[2] = (unsigned char)(b * 255.0f / 31.0f);
  566. dest += 3;
  567. }
  568. }
  569. }
  570. else
  571. {
  572. for (int y = 0; y < height_; ++y)
  573. {
  574. unsigned char* src = (unsigned char*)lockedRect.pBits + y * lockedRect.Pitch;
  575. unsigned char* dest = destData + y * width_ * 3;
  576. for (int x = 0; x < width_; ++x)
  577. {
  578. dest[0] = src[2];
  579. dest[1] = src[1];
  580. dest[2] = src[0];
  581. src += 4;
  582. dest += 3;
  583. }
  584. }
  585. }
  586. surface->UnlockRect();
  587. surface->Release();
  588. return true;
  589. }
  590. bool Graphics::BeginFrame()
  591. {
  592. if (!IsInitialized())
  593. return false;
  594. // If using an external window, check it for size changes, and reset screen mode if necessary
  595. if (externalWindow_)
  596. {
  597. int width, height;
  598. SDL_GetWindowSize(window_, &width, &height);
  599. if (width != width_ || height != height_)
  600. SetMode(width, height);
  601. }
  602. else
  603. {
  604. // To prevent a loop of endless device loss and flicker, do not attempt to render when in fullscreen
  605. // and the window is minimized
  606. if (fullscreen_ && (SDL_GetWindowFlags(window_) & SDL_WINDOW_MINIMIZED))
  607. return false;
  608. }
  609. // Check for lost device before rendering
  610. HRESULT hr = impl_->device_->TestCooperativeLevel();
  611. if (hr != D3D_OK)
  612. {
  613. ATOMIC_PROFILE(DeviceLost);
  614. impl_->deviceLost_ = true;
  615. // The device can not be reset yet, sleep and try again eventually
  616. if (hr == D3DERR_DEVICELOST)
  617. {
  618. Time::Sleep(20);
  619. return false;
  620. }
  621. // The device is lost, but ready to be reset. Reset device but do not render on this frame yet
  622. if (hr == D3DERR_DEVICENOTRESET)
  623. {
  624. ResetDevice();
  625. return false;
  626. }
  627. }
  628. impl_->device_->BeginScene();
  629. // Set default rendertarget and depth buffer
  630. ResetRenderTargets();
  631. // Cleanup textures from previous frame
  632. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  633. SetTexture(i, 0);
  634. numPrimitives_ = 0;
  635. numBatches_ = 0;
  636. SendEvent(E_BEGINRENDERING);
  637. return true;
  638. }
  639. void Graphics::EndFrame()
  640. {
  641. if (!IsInitialized())
  642. return;
  643. {
  644. ATOMIC_PROFILE(Present);
  645. SendEvent(E_ENDRENDERING);
  646. impl_->device_->EndScene();
  647. impl_->device_->Present(0, 0, 0, 0);
  648. }
  649. // Optionally flush GPU buffer to avoid control lag or framerate fluctuations due to multiple frame buffering
  650. // If a query was issued on the previous frame, first wait for it to finish
  651. if (impl_->frameQuery_)
  652. {
  653. if (impl_->queryIssued_)
  654. {
  655. ATOMIC_PROFILE(FlushGPU);
  656. while (impl_->frameQuery_->GetData(0, 0, D3DGETDATA_FLUSH) == S_FALSE)
  657. {
  658. }
  659. impl_->queryIssued_ = false;
  660. }
  661. if (flushGPU_)
  662. {
  663. impl_->frameQuery_->Issue(D3DISSUE_END);
  664. impl_->queryIssued_ = true;
  665. }
  666. }
  667. // Clean up too large scratch buffers
  668. CleanupScratchBuffers();
  669. }
  670. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  671. {
  672. DWORD d3dFlags = 0;
  673. if (flags & CLEAR_COLOR)
  674. d3dFlags |= D3DCLEAR_TARGET;
  675. if (flags & CLEAR_DEPTH)
  676. d3dFlags |= D3DCLEAR_ZBUFFER;
  677. if (flags & CLEAR_STENCIL)
  678. d3dFlags |= D3DCLEAR_STENCIL;
  679. impl_->device_->Clear(0, 0, d3dFlags, GetD3DColor(color), depth, stencil);
  680. }
  681. bool Graphics::ResolveToTexture(Texture2D* destination, const IntRect& viewport)
  682. {
  683. if (!destination || !destination->GetRenderSurface())
  684. return false;
  685. ATOMIC_PROFILE(ResolveToTexture);
  686. IntRect vpCopy = viewport;
  687. if (vpCopy.right_ <= vpCopy.left_)
  688. vpCopy.right_ = vpCopy.left_ + 1;
  689. if (vpCopy.bottom_ <= vpCopy.top_)
  690. vpCopy.bottom_ = vpCopy.top_ + 1;
  691. RECT rect;
  692. rect.left = Clamp(vpCopy.left_, 0, width_);
  693. rect.top = Clamp(vpCopy.top_, 0, height_);
  694. rect.right = Clamp(vpCopy.right_, 0, width_);
  695. rect.bottom = Clamp(vpCopy.bottom_, 0, height_);
  696. RECT destRect;
  697. destRect.left = 0;
  698. destRect.top = 0;
  699. destRect.right = destination->GetWidth();
  700. destRect.bottom = destination->GetHeight();
  701. HRESULT hr = impl_->device_->StretchRect(impl_->defaultColorSurface_, &rect,
  702. (IDirect3DSurface9*)destination->GetRenderSurface()->GetSurface(), &destRect, D3DTEXF_NONE);
  703. if (FAILED(hr))
  704. {
  705. ATOMIC_LOGD3DERROR("Failed to resolve to texture", hr);
  706. return false;
  707. }
  708. else
  709. return true;
  710. }
  711. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  712. {
  713. if (!vertexCount)
  714. return;
  715. ResetStreamFrequencies();
  716. unsigned primitiveCount;
  717. D3DPRIMITIVETYPE d3dPrimitiveType;
  718. GetD3DPrimitiveType(vertexCount, type, primitiveCount, d3dPrimitiveType);
  719. impl_->device_->DrawPrimitive(d3dPrimitiveType, vertexStart, primitiveCount);
  720. numPrimitives_ += primitiveCount;
  721. ++numBatches_;
  722. }
  723. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  724. {
  725. if (!indexCount)
  726. return;
  727. ResetStreamFrequencies();
  728. unsigned primitiveCount;
  729. D3DPRIMITIVETYPE d3dPrimitiveType;
  730. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  731. impl_->device_->DrawIndexedPrimitive(d3dPrimitiveType, 0, minVertex, vertexCount, indexStart, primitiveCount);
  732. numPrimitives_ += primitiveCount;
  733. ++numBatches_;
  734. }
  735. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned baseVertexIndex, unsigned minVertex, unsigned vertexCount)
  736. {
  737. if (!indexCount)
  738. return;
  739. ResetStreamFrequencies();
  740. unsigned primitiveCount;
  741. D3DPRIMITIVETYPE d3dPrimitiveType;
  742. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  743. impl_->device_->DrawIndexedPrimitive(d3dPrimitiveType, baseVertexIndex, minVertex, vertexCount, indexStart, primitiveCount);
  744. numPrimitives_ += primitiveCount;
  745. ++numBatches_;
  746. }
  747. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount,
  748. unsigned instanceCount)
  749. {
  750. if (!indexCount || !instanceCount)
  751. return;
  752. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  753. {
  754. VertexBuffer* buffer = vertexBuffers_[i];
  755. if (buffer)
  756. {
  757. const PODVector<VertexElement>& elements = buffer->GetElements();
  758. // Check if buffer has per-instance data
  759. if (elements.Size() && elements[0].perInstance_)
  760. SetStreamFrequency(i, D3DSTREAMSOURCE_INSTANCEDATA | 1u);
  761. else
  762. SetStreamFrequency(i, D3DSTREAMSOURCE_INDEXEDDATA | instanceCount);
  763. }
  764. }
  765. unsigned primitiveCount;
  766. D3DPRIMITIVETYPE d3dPrimitiveType;
  767. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  768. impl_->device_->DrawIndexedPrimitive(d3dPrimitiveType, 0, minVertex, vertexCount, indexStart, primitiveCount);
  769. numPrimitives_ += instanceCount * primitiveCount;
  770. ++numBatches_;
  771. }
  772. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned baseVertexIndex, unsigned minVertex,
  773. unsigned vertexCount, unsigned instanceCount)
  774. {
  775. if (!indexCount || !instanceCount)
  776. return;
  777. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  778. {
  779. VertexBuffer* buffer = vertexBuffers_[i];
  780. if (buffer)
  781. {
  782. const PODVector<VertexElement>& elements = buffer->GetElements();
  783. // Check if buffer has per-instance data
  784. if (elements.Size() && elements[0].perInstance_)
  785. SetStreamFrequency(i, D3DSTREAMSOURCE_INSTANCEDATA | 1u);
  786. else
  787. SetStreamFrequency(i, D3DSTREAMSOURCE_INDEXEDDATA | instanceCount);
  788. }
  789. }
  790. unsigned primitiveCount;
  791. D3DPRIMITIVETYPE d3dPrimitiveType;
  792. GetD3DPrimitiveType(indexCount, type, primitiveCount, d3dPrimitiveType);
  793. impl_->device_->DrawIndexedPrimitive(d3dPrimitiveType, baseVertexIndex, minVertex, vertexCount, indexStart, primitiveCount);
  794. numPrimitives_ += instanceCount * primitiveCount;
  795. ++numBatches_;
  796. }
  797. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  798. {
  799. // Note: this is not multi-instance safe
  800. static PODVector<VertexBuffer*> vertexBuffers(1);
  801. vertexBuffers[0] = buffer;
  802. SetVertexBuffers(vertexBuffers);
  803. }
  804. bool Graphics::SetVertexBuffers(const PODVector<VertexBuffer*>& buffers, unsigned instanceOffset)
  805. {
  806. if (buffers.Size() > MAX_VERTEX_STREAMS)
  807. {
  808. ATOMIC_LOGERROR("Too many vertex buffers");
  809. return false;
  810. }
  811. // Build vertex declaration hash code out of the buffers
  812. unsigned long long hash = 0;
  813. for (unsigned i = 0; i < buffers.Size(); ++i)
  814. {
  815. if (!buffers[i])
  816. continue;
  817. hash |= buffers[i]->GetBufferHash(i);
  818. }
  819. if (hash)
  820. {
  821. // If no previous vertex declaration for that hash, create new
  822. VertexDeclarationMap::Iterator i = impl_->vertexDeclarations_.Find(hash);
  823. if (i == impl_->vertexDeclarations_.End())
  824. {
  825. SharedPtr<VertexDeclaration> newDeclaration(new VertexDeclaration(this, buffers));
  826. if (!newDeclaration->GetDeclaration())
  827. return false;
  828. i = impl_->vertexDeclarations_.Insert(MakePair(hash, newDeclaration));
  829. }
  830. VertexDeclaration* declaration = i->second_;
  831. if (declaration != impl_->vertexDeclaration_)
  832. {
  833. impl_->device_->SetVertexDeclaration(declaration->GetDeclaration());
  834. impl_->vertexDeclaration_ = declaration;
  835. }
  836. }
  837. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  838. {
  839. VertexBuffer* buffer = 0;
  840. unsigned offset = 0;
  841. if (i < buffers.Size() && buffers[i])
  842. {
  843. buffer = buffers[i];
  844. const PODVector<VertexElement>& elements = buffer->GetElements();
  845. // Check if buffer has per-instance data; add instance offset in that case
  846. if (elements.Size() && elements[0].perInstance_)
  847. offset = instanceOffset * buffer->GetVertexSize();
  848. }
  849. if (buffer != vertexBuffers_[i] || offset != impl_->streamOffsets_[i])
  850. {
  851. if (buffer)
  852. impl_->device_->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->GetGPUObject(), offset,
  853. buffer->GetVertexSize());
  854. else
  855. impl_->device_->SetStreamSource(i, 0, 0, 0);
  856. vertexBuffers_[i] = buffer;
  857. impl_->streamOffsets_[i] = offset;
  858. }
  859. }
  860. return true;
  861. }
  862. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, unsigned instanceOffset)
  863. {
  864. return SetVertexBuffers(reinterpret_cast<const PODVector<VertexBuffer*>&>(buffers), instanceOffset);
  865. }
  866. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  867. {
  868. if (buffer != indexBuffer_)
  869. {
  870. if (buffer)
  871. impl_->device_->SetIndices((IDirect3DIndexBuffer9*)buffer->GetGPUObject());
  872. else
  873. impl_->device_->SetIndices(0);
  874. indexBuffer_ = buffer;
  875. }
  876. }
  877. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  878. {
  879. if (vs == vertexShader_ && ps == pixelShader_)
  880. return;
  881. ClearParameterSources();
  882. if (vs != vertexShader_)
  883. {
  884. // Create the shader now if not yet created. If already attempted, do not retry
  885. if (vs && !vs->GetGPUObject())
  886. {
  887. if (vs->GetCompilerOutput().Empty())
  888. {
  889. ATOMIC_PROFILE(CompileVertexShader);
  890. bool success = vs->Create();
  891. if (!success)
  892. {
  893. ATOMIC_LOGERROR("Failed to compile vertex shader " + vs->GetFullName() + ":\n" + vs->GetCompilerOutput());
  894. vs = 0;
  895. }
  896. }
  897. else
  898. vs = 0;
  899. }
  900. if (vs && vs->GetShaderType() == VS)
  901. impl_->device_->SetVertexShader((IDirect3DVertexShader9*)vs->GetGPUObject());
  902. else
  903. {
  904. impl_->device_->SetVertexShader(0);
  905. vs = 0;
  906. }
  907. vertexShader_ = vs;
  908. }
  909. if (ps != pixelShader_)
  910. {
  911. if (ps && !ps->GetGPUObject())
  912. {
  913. if (ps->GetCompilerOutput().Empty())
  914. {
  915. ATOMIC_PROFILE(CompilePixelShader);
  916. bool success = ps->Create();
  917. if (!success)
  918. {
  919. ATOMIC_LOGERROR("Failed to compile pixel shader " + ps->GetFullName() + ":\n" + ps->GetCompilerOutput());
  920. ps = 0;
  921. }
  922. }
  923. else
  924. ps = 0;
  925. }
  926. if (ps && ps->GetShaderType() == PS)
  927. impl_->device_->SetPixelShader((IDirect3DPixelShader9*)ps->GetGPUObject());
  928. else
  929. {
  930. impl_->device_->SetPixelShader(0);
  931. ps = 0;
  932. }
  933. pixelShader_ = ps;
  934. }
  935. // Update current available shader parameters
  936. if (vertexShader_ && pixelShader_)
  937. {
  938. Pair<ShaderVariation*, ShaderVariation*> key = MakePair(vertexShader_, pixelShader_);
  939. ShaderProgramMap::Iterator i = impl_->shaderPrograms_.Find(key);
  940. if (i != impl_->shaderPrograms_.End())
  941. impl_->shaderProgram_ = i->second_.Get();
  942. else
  943. {
  944. ShaderProgram* newProgram = impl_->shaderPrograms_[key] = new ShaderProgram(vertexShader_, pixelShader_);
  945. impl_->shaderProgram_ = newProgram;
  946. }
  947. }
  948. else
  949. impl_->shaderProgram_ = 0;
  950. // Store shader combination if shader dumping in progress
  951. if (shaderPrecache_)
  952. shaderPrecache_->StoreShaders(vertexShader_, pixelShader_);
  953. }
  954. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  955. {
  956. HashMap<StringHash, ShaderParameter>::Iterator i;
  957. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  958. return;
  959. if (i->second_.type_ == VS)
  960. impl_->device_->SetVertexShaderConstantF(i->second_.register_, data, count / 4);
  961. else
  962. impl_->device_->SetPixelShaderConstantF(i->second_.register_, data, count / 4);
  963. }
  964. void Graphics::SetShaderParameter(StringHash param, float value)
  965. {
  966. HashMap<StringHash, ShaderParameter>::Iterator i;
  967. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  968. return;
  969. static Vector4 data(Vector4::ZERO);
  970. data.x_ = value;
  971. if (i->second_.type_ == VS)
  972. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data.x_, 1);
  973. else
  974. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data.x_, 1);
  975. }
  976. void Graphics::SetShaderParameter(StringHash param, bool value)
  977. {
  978. /// \todo Bool constants possibly have no effect on Direct3D9
  979. HashMap<StringHash, ShaderParameter>::Iterator i;
  980. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  981. return;
  982. BOOL data = value;
  983. if (i->second_.type_ == VS)
  984. impl_->device_->SetVertexShaderConstantB(i->second_.register_, &data, 1);
  985. else
  986. impl_->device_->SetPixelShaderConstantB(i->second_.register_, &data, 1);
  987. }
  988. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  989. {
  990. HashMap<StringHash, ShaderParameter>::Iterator i;
  991. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  992. return;
  993. if (i->second_.type_ == VS)
  994. impl_->device_->SetVertexShaderConstantF(i->second_.register_, color.Data(), 1);
  995. else
  996. impl_->device_->SetPixelShaderConstantF(i->second_.register_, color.Data(), 1);
  997. }
  998. void Graphics::SetShaderParameter(StringHash param, const Vector2& vector)
  999. {
  1000. HashMap<StringHash, ShaderParameter>::Iterator i;
  1001. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  1002. return;
  1003. static Vector4 data(Vector4::ZERO);
  1004. data.x_ = vector.x_;
  1005. data.y_ = vector.y_;
  1006. if (i->second_.type_ == VS)
  1007. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data.x_, 1);
  1008. else
  1009. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data.x_, 1);
  1010. }
  1011. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  1012. {
  1013. HashMap<StringHash, ShaderParameter>::Iterator i;
  1014. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  1015. return;
  1016. static Matrix3x4 data(Matrix3x4::ZERO);
  1017. data.m00_ = matrix.m00_;
  1018. data.m01_ = matrix.m01_;
  1019. data.m02_ = matrix.m02_;
  1020. data.m10_ = matrix.m10_;
  1021. data.m11_ = matrix.m11_;
  1022. data.m12_ = matrix.m12_;
  1023. data.m20_ = matrix.m20_;
  1024. data.m21_ = matrix.m21_;
  1025. data.m22_ = matrix.m22_;
  1026. if (i->second_.type_ == VS)
  1027. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data.m00_, 3);
  1028. else
  1029. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data.m00_, 3);
  1030. }
  1031. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  1032. {
  1033. HashMap<StringHash, ShaderParameter>::Iterator i;
  1034. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  1035. return;
  1036. static Vector4 data(Vector4::ZERO);
  1037. data.x_ = vector.x_;
  1038. data.y_ = vector.y_;
  1039. data.z_ = vector.z_;
  1040. if (i->second_.type_ == VS)
  1041. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data.x_, 1);
  1042. else
  1043. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data.x_, 1);
  1044. }
  1045. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  1046. {
  1047. HashMap<StringHash, ShaderParameter>::Iterator i;
  1048. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  1049. return;
  1050. if (i->second_.type_ == VS)
  1051. impl_->device_->SetVertexShaderConstantF(i->second_.register_, matrix.Data(), 4);
  1052. else
  1053. impl_->device_->SetPixelShaderConstantF(i->second_.register_, matrix.Data(), 4);
  1054. }
  1055. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  1056. {
  1057. HashMap<StringHash, ShaderParameter>::Iterator i;
  1058. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  1059. return;
  1060. if (i->second_.type_ == VS)
  1061. impl_->device_->SetVertexShaderConstantF(i->second_.register_, vector.Data(), 1);
  1062. else
  1063. impl_->device_->SetPixelShaderConstantF(i->second_.register_, vector.Data(), 1);
  1064. }
  1065. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  1066. {
  1067. HashMap<StringHash, ShaderParameter>::Iterator i;
  1068. if (!impl_->shaderProgram_ || (i = impl_->shaderProgram_->parameters_.Find(param)) == impl_->shaderProgram_->parameters_.End())
  1069. return;
  1070. if (i->second_.type_ == VS)
  1071. impl_->device_->SetVertexShaderConstantF(i->second_.register_, matrix.Data(), 3);
  1072. else
  1073. impl_->device_->SetPixelShaderConstantF(i->second_.register_, matrix.Data(), 3);
  1074. }
  1075. void Graphics::SetShaderParameter(StringHash param, const Variant& value)
  1076. {
  1077. switch (value.GetType())
  1078. {
  1079. case VAR_BOOL:
  1080. SetShaderParameter(param, value.GetBool());
  1081. break;
  1082. case VAR_FLOAT:
  1083. SetShaderParameter(param, value.GetFloat());
  1084. break;
  1085. case VAR_VECTOR2:
  1086. SetShaderParameter(param, value.GetVector2());
  1087. break;
  1088. case VAR_VECTOR3:
  1089. SetShaderParameter(param, value.GetVector3());
  1090. break;
  1091. case VAR_VECTOR4:
  1092. SetShaderParameter(param, value.GetVector4());
  1093. break;
  1094. case VAR_COLOR:
  1095. SetShaderParameter(param, value.GetColor());
  1096. break;
  1097. case VAR_MATRIX3:
  1098. SetShaderParameter(param, value.GetMatrix3());
  1099. break;
  1100. case VAR_MATRIX3X4:
  1101. SetShaderParameter(param, value.GetMatrix3x4());
  1102. break;
  1103. case VAR_MATRIX4:
  1104. SetShaderParameter(param, value.GetMatrix4());
  1105. break;
  1106. case VAR_BUFFER:
  1107. {
  1108. const PODVector<unsigned char>& buffer = value.GetBuffer();
  1109. if (buffer.Size() >= sizeof(float))
  1110. SetShaderParameter(param, reinterpret_cast<const float*>(&buffer[0]), buffer.Size() / sizeof(float));
  1111. }
  1112. break;
  1113. default:
  1114. // Unsupported parameter type, do nothing
  1115. break;
  1116. }
  1117. }
  1118. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  1119. {
  1120. if ((unsigned)(size_t)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  1121. {
  1122. shaderParameterSources_[group] = source;
  1123. return true;
  1124. }
  1125. else
  1126. return false;
  1127. }
  1128. bool Graphics::HasShaderParameter(StringHash param)
  1129. {
  1130. return impl_->shaderProgram_ && impl_->shaderProgram_->parameters_.Find(param) != impl_->shaderProgram_->parameters_.End();
  1131. }
  1132. bool Graphics::HasTextureUnit(TextureUnit unit)
  1133. {
  1134. return pixelShader_ && pixelShader_->HasTextureUnit(unit);
  1135. }
  1136. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  1137. {
  1138. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  1139. }
  1140. void Graphics::ClearParameterSources()
  1141. {
  1142. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  1143. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  1144. }
  1145. void Graphics::ClearTransformSources()
  1146. {
  1147. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  1148. shaderParameterSources_[SP_OBJECT] = (const void*)M_MAX_UNSIGNED;
  1149. }
  1150. void Graphics::SetTexture(unsigned index, Texture* texture)
  1151. {
  1152. if (index >= MAX_TEXTURE_UNITS)
  1153. return;
  1154. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  1155. if (texture)
  1156. {
  1157. if (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture)
  1158. texture = texture->GetBackupTexture();
  1159. }
  1160. if (texture != textures_[index])
  1161. {
  1162. if (texture)
  1163. impl_->device_->SetTexture(index, (IDirect3DBaseTexture9*)texture->GetGPUObject());
  1164. else
  1165. impl_->device_->SetTexture(index, 0);
  1166. textures_[index] = texture;
  1167. }
  1168. if (texture)
  1169. {
  1170. TextureFilterMode filterMode = texture->GetFilterMode();
  1171. if (filterMode == FILTER_DEFAULT)
  1172. filterMode = defaultTextureFilterMode_;
  1173. D3DTEXTUREFILTERTYPE minMag, mip;
  1174. minMag = d3dMinMagFilter[filterMode];
  1175. if (minMag != impl_->minMagFilters_[index])
  1176. {
  1177. impl_->device_->SetSamplerState(index, D3DSAMP_MAGFILTER, minMag);
  1178. impl_->device_->SetSamplerState(index, D3DSAMP_MINFILTER, minMag);
  1179. impl_->minMagFilters_[index] = minMag;
  1180. }
  1181. mip = d3dMipFilter[filterMode];
  1182. if (mip != impl_->mipFilters_[index])
  1183. {
  1184. impl_->device_->SetSamplerState(index, D3DSAMP_MIPFILTER, mip);
  1185. impl_->mipFilters_[index] = mip;
  1186. }
  1187. D3DTEXTUREADDRESS u, v;
  1188. u = d3dAddressMode[texture->GetAddressMode(COORD_U)];
  1189. if (u != impl_->uAddressModes_[index])
  1190. {
  1191. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSU, u);
  1192. impl_->uAddressModes_[index] = u;
  1193. }
  1194. v = d3dAddressMode[texture->GetAddressMode(COORD_V)];
  1195. if (v != impl_->vAddressModes_[index])
  1196. {
  1197. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSV, v);
  1198. impl_->vAddressModes_[index] = v;
  1199. }
  1200. if (texture->GetType() == TextureCube::GetTypeStatic())
  1201. {
  1202. D3DTEXTUREADDRESS w = d3dAddressMode[texture->GetAddressMode(COORD_W)];
  1203. if (w != impl_->wAddressModes_[index])
  1204. {
  1205. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSW, w);
  1206. impl_->wAddressModes_[index] = w;
  1207. }
  1208. }
  1209. unsigned maxAnisotropy = texture->GetAnisotropy();
  1210. if (!maxAnisotropy)
  1211. maxAnisotropy = defaultTextureAnisotropy_;
  1212. if (maxAnisotropy != impl_->maxAnisotropy_[index])
  1213. {
  1214. impl_->device_->SetSamplerState(index, D3DSAMP_MAXANISOTROPY, maxAnisotropy);
  1215. impl_->maxAnisotropy_[index] = maxAnisotropy;
  1216. }
  1217. if (u == D3DTADDRESS_BORDER || v == D3DTADDRESS_BORDER)
  1218. {
  1219. const Color& borderColor = texture->GetBorderColor();
  1220. if (borderColor != impl_->borderColors_[index])
  1221. {
  1222. impl_->device_->SetSamplerState(index, D3DSAMP_BORDERCOLOR, GetD3DColor(borderColor));
  1223. impl_->borderColors_[index] = borderColor;
  1224. }
  1225. }
  1226. if (sRGBSupport_)
  1227. {
  1228. bool sRGB = texture->GetSRGB();
  1229. if (sRGB != impl_->sRGBModes_[index])
  1230. {
  1231. impl_->device_->SetSamplerState(index, D3DSAMP_SRGBTEXTURE, sRGB ? TRUE : FALSE);
  1232. impl_->sRGBModes_[index] = sRGB;
  1233. }
  1234. }
  1235. }
  1236. }
  1237. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1238. {
  1239. defaultTextureFilterMode_ = mode;
  1240. }
  1241. void Graphics::SetDefaultTextureAnisotropy(unsigned level)
  1242. {
  1243. defaultTextureAnisotropy_ = Max(level, 1U);
  1244. }
  1245. void Graphics::ResetRenderTargets()
  1246. {
  1247. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1248. SetRenderTarget(i, (RenderSurface*)0);
  1249. SetDepthStencil((RenderSurface*)0);
  1250. SetViewport(IntRect(0, 0, width_, height_));
  1251. }
  1252. void Graphics::ResetRenderTarget(unsigned index)
  1253. {
  1254. SetRenderTarget(index, (RenderSurface*)0);
  1255. }
  1256. void Graphics::ResetDepthStencil()
  1257. {
  1258. SetDepthStencil((RenderSurface*)0);
  1259. }
  1260. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1261. {
  1262. if (index >= MAX_RENDERTARGETS)
  1263. return;
  1264. IDirect3DSurface9* newColorSurface = 0;
  1265. if (renderTarget)
  1266. {
  1267. if (renderTarget->GetUsage() != TEXTURE_RENDERTARGET)
  1268. return;
  1269. newColorSurface = (IDirect3DSurface9*)renderTarget->GetSurface();
  1270. }
  1271. else
  1272. {
  1273. if (!index)
  1274. newColorSurface = impl_->defaultColorSurface_;
  1275. }
  1276. renderTargets_[index] = renderTarget;
  1277. if (newColorSurface != impl_->colorSurfaces_[index])
  1278. {
  1279. impl_->device_->SetRenderTarget(index, newColorSurface);
  1280. impl_->colorSurfaces_[index] = newColorSurface;
  1281. // Setting the first rendertarget causes viewport to be reset
  1282. if (!index)
  1283. {
  1284. IntVector2 rtSize = GetRenderTargetDimensions();
  1285. viewport_ = IntRect(0, 0, rtSize.x_, rtSize.y_);
  1286. }
  1287. }
  1288. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1289. if (renderTarget)
  1290. {
  1291. Texture* parentTexture = renderTarget->GetParentTexture();
  1292. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1293. {
  1294. if (textures_[i] == parentTexture)
  1295. SetTexture(i, textures_[i]->GetBackupTexture());
  1296. }
  1297. }
  1298. // First rendertarget controls sRGB write mode
  1299. if (!index && sRGBWriteSupport_)
  1300. {
  1301. bool sRGBWrite = renderTarget ? renderTarget->GetParentTexture()->GetSRGB() : sRGB_;
  1302. if (sRGBWrite != impl_->sRGBWrite_)
  1303. {
  1304. impl_->device_->SetRenderState(D3DRS_SRGBWRITEENABLE, sRGBWrite ? TRUE : FALSE);
  1305. impl_->sRGBWrite_ = sRGBWrite;
  1306. }
  1307. }
  1308. }
  1309. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1310. {
  1311. RenderSurface* renderTarget = 0;
  1312. if (texture)
  1313. renderTarget = texture->GetRenderSurface();
  1314. SetRenderTarget(index, renderTarget);
  1315. }
  1316. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1317. {
  1318. IDirect3DSurface9* newDepthStencilSurface = 0;
  1319. if (depthStencil && depthStencil->GetUsage() == TEXTURE_DEPTHSTENCIL)
  1320. {
  1321. newDepthStencilSurface = (IDirect3DSurface9*)depthStencil->GetSurface();
  1322. depthStencil_ = depthStencil;
  1323. }
  1324. if (!newDepthStencilSurface)
  1325. {
  1326. newDepthStencilSurface = impl_->defaultDepthStencilSurface_;
  1327. depthStencil_ = 0;
  1328. }
  1329. if (newDepthStencilSurface != impl_->depthStencilSurface_)
  1330. {
  1331. impl_->device_->SetDepthStencilSurface(newDepthStencilSurface);
  1332. impl_->depthStencilSurface_ = newDepthStencilSurface;
  1333. }
  1334. }
  1335. void Graphics::SetDepthStencil(Texture2D* texture)
  1336. {
  1337. RenderSurface* depthStencil = 0;
  1338. if (texture)
  1339. depthStencil = texture->GetRenderSurface();
  1340. SetDepthStencil(depthStencil);
  1341. }
  1342. void Graphics::SetViewport(const IntRect& rect)
  1343. {
  1344. IntVector2 size = GetRenderTargetDimensions();
  1345. IntRect rectCopy = rect;
  1346. if (rectCopy.right_ <= rectCopy.left_)
  1347. rectCopy.right_ = rectCopy.left_ + 1;
  1348. if (rectCopy.bottom_ <= rectCopy.top_)
  1349. rectCopy.bottom_ = rectCopy.top_ + 1;
  1350. rectCopy.left_ = Clamp(rectCopy.left_, 0, size.x_);
  1351. rectCopy.top_ = Clamp(rectCopy.top_, 0, size.y_);
  1352. rectCopy.right_ = Clamp(rectCopy.right_, 0, size.x_);
  1353. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, size.y_);
  1354. D3DVIEWPORT9 vp;
  1355. vp.MinZ = 0.0f;
  1356. vp.MaxZ = 1.0f;
  1357. vp.X = (DWORD)rectCopy.left_;
  1358. vp.Y = (DWORD)rectCopy.top_;
  1359. vp.Width = (DWORD)rectCopy.Width();
  1360. vp.Height = (DWORD)rectCopy.Height();
  1361. impl_->device_->SetViewport(&vp);
  1362. viewport_ = rectCopy;
  1363. // Disable scissor test, needs to be re-enabled by the user
  1364. SetScissorTest(false);
  1365. }
  1366. void Graphics::SetBlendMode(BlendMode mode, bool /* alphaToCoverage */)
  1367. {
  1368. if (mode != blendMode_)
  1369. {
  1370. if (d3dBlendEnable[mode] != impl_->blendEnable_)
  1371. {
  1372. impl_->device_->SetRenderState(D3DRS_ALPHABLENDENABLE, d3dBlendEnable[mode]);
  1373. impl_->blendEnable_ = d3dBlendEnable[mode];
  1374. }
  1375. if (impl_->blendEnable_)
  1376. {
  1377. if (d3dSrcBlend[mode] != impl_->srcBlend_)
  1378. {
  1379. impl_->device_->SetRenderState(D3DRS_SRCBLEND, d3dSrcBlend[mode]);
  1380. impl_->srcBlend_ = d3dSrcBlend[mode];
  1381. }
  1382. if (d3dDestBlend[mode] != impl_->destBlend_)
  1383. {
  1384. impl_->device_->SetRenderState(D3DRS_DESTBLEND, d3dDestBlend[mode]);
  1385. impl_->destBlend_ = d3dDestBlend[mode];
  1386. }
  1387. if (d3dBlendOp[mode] != impl_->blendOp_)
  1388. {
  1389. impl_->device_->SetRenderState(D3DRS_BLENDOP, d3dBlendOp[mode]);
  1390. impl_->blendOp_ = d3dBlendOp[mode];
  1391. }
  1392. }
  1393. blendMode_ = mode;
  1394. }
  1395. }
  1396. void Graphics::SetColorWrite(bool enable)
  1397. {
  1398. if (enable != colorWrite_)
  1399. {
  1400. impl_->device_->SetRenderState(D3DRS_COLORWRITEENABLE,
  1401. enable ? D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA :
  1402. 0);
  1403. colorWrite_ = enable;
  1404. }
  1405. }
  1406. void Graphics::SetCullMode(CullMode mode)
  1407. {
  1408. if (mode != cullMode_)
  1409. {
  1410. impl_->device_->SetRenderState(D3DRS_CULLMODE, d3dCullMode[mode]);
  1411. cullMode_ = mode;
  1412. }
  1413. }
  1414. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1415. {
  1416. if (constantBias != constantDepthBias_)
  1417. {
  1418. impl_->device_->SetRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&constantBias));
  1419. constantDepthBias_ = constantBias;
  1420. }
  1421. if (slopeScaledBias != slopeScaledDepthBias_)
  1422. {
  1423. impl_->device_->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&slopeScaledBias));
  1424. slopeScaledDepthBias_ = slopeScaledBias;
  1425. }
  1426. }
  1427. void Graphics::SetDepthTest(CompareMode mode)
  1428. {
  1429. if (mode != depthTestMode_)
  1430. {
  1431. impl_->device_->SetRenderState(D3DRS_ZFUNC, d3dCmpFunc[mode]);
  1432. depthTestMode_ = mode;
  1433. }
  1434. }
  1435. void Graphics::SetDepthWrite(bool enable)
  1436. {
  1437. if (enable != depthWrite_)
  1438. {
  1439. impl_->device_->SetRenderState(D3DRS_ZWRITEENABLE, enable ? TRUE : FALSE);
  1440. depthWrite_ = enable;
  1441. }
  1442. }
  1443. void Graphics::SetFillMode(FillMode mode)
  1444. {
  1445. if (mode != fillMode_)
  1446. {
  1447. impl_->device_->SetRenderState(D3DRS_FILLMODE, d3dFillMode[mode]);
  1448. fillMode_ = mode;
  1449. }
  1450. }
  1451. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1452. {
  1453. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1454. // Disable scissor in that case to reduce state changes
  1455. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1456. enable = false;
  1457. if (enable)
  1458. {
  1459. IntVector2 rtSize(GetRenderTargetDimensions());
  1460. IntVector2 viewSize(viewport_.Size());
  1461. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1462. IntRect intRect;
  1463. int expand = borderInclusive ? 1 : 0;
  1464. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1465. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1466. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1467. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1468. if (intRect.right_ == intRect.left_)
  1469. intRect.right_++;
  1470. if (intRect.bottom_ == intRect.top_)
  1471. intRect.bottom_++;
  1472. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1473. enable = false;
  1474. if (enable && scissorRect_ != intRect)
  1475. {
  1476. RECT d3dRect;
  1477. d3dRect.left = intRect.left_;
  1478. d3dRect.top = intRect.top_;
  1479. d3dRect.right = intRect.right_;
  1480. d3dRect.bottom = intRect.bottom_;
  1481. impl_->device_->SetScissorRect(&d3dRect);
  1482. scissorRect_ = intRect;
  1483. }
  1484. }
  1485. else
  1486. scissorRect_ = IntRect::ZERO;
  1487. if (enable != scissorTest_)
  1488. {
  1489. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1490. scissorTest_ = enable;
  1491. }
  1492. }
  1493. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1494. {
  1495. IntVector2 rtSize(GetRenderTargetDimensions());
  1496. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1497. if (enable)
  1498. {
  1499. IntRect intRect;
  1500. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1501. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1502. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1503. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1504. if (intRect.right_ == intRect.left_)
  1505. intRect.right_++;
  1506. if (intRect.bottom_ == intRect.top_)
  1507. intRect.bottom_++;
  1508. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1509. enable = false;
  1510. if (enable && scissorRect_ != intRect)
  1511. {
  1512. RECT d3dRect;
  1513. d3dRect.left = intRect.left_;
  1514. d3dRect.top = intRect.top_;
  1515. d3dRect.right = intRect.right_;
  1516. d3dRect.bottom = intRect.bottom_;
  1517. impl_->device_->SetScissorRect(&d3dRect);
  1518. scissorRect_ = intRect;
  1519. }
  1520. }
  1521. else
  1522. scissorRect_ = IntRect::ZERO;
  1523. if (enable != scissorTest_)
  1524. {
  1525. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1526. scissorTest_ = enable;
  1527. }
  1528. }
  1529. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef,
  1530. unsigned compareMask, unsigned writeMask)
  1531. {
  1532. if (enable != stencilTest_)
  1533. {
  1534. impl_->device_->SetRenderState(D3DRS_STENCILENABLE, enable ? TRUE : FALSE);
  1535. stencilTest_ = enable;
  1536. }
  1537. if (enable)
  1538. {
  1539. if (mode != stencilTestMode_)
  1540. {
  1541. impl_->device_->SetRenderState(D3DRS_STENCILFUNC, d3dCmpFunc[mode]);
  1542. stencilTestMode_ = mode;
  1543. }
  1544. if (pass != stencilPass_)
  1545. {
  1546. impl_->device_->SetRenderState(D3DRS_STENCILPASS, d3dStencilOp[pass]);
  1547. stencilPass_ = pass;
  1548. }
  1549. if (fail != stencilFail_)
  1550. {
  1551. impl_->device_->SetRenderState(D3DRS_STENCILFAIL, d3dStencilOp[fail]);
  1552. stencilFail_ = fail;
  1553. }
  1554. if (zFail != stencilZFail_)
  1555. {
  1556. impl_->device_->SetRenderState(D3DRS_STENCILZFAIL, d3dStencilOp[zFail]);
  1557. stencilZFail_ = zFail;
  1558. }
  1559. if (stencilRef != stencilRef_)
  1560. {
  1561. impl_->device_->SetRenderState(D3DRS_STENCILREF, stencilRef);
  1562. stencilRef_ = stencilRef;
  1563. }
  1564. if (compareMask != stencilCompareMask_)
  1565. {
  1566. impl_->device_->SetRenderState(D3DRS_STENCILMASK, compareMask);
  1567. stencilCompareMask_ = compareMask;
  1568. }
  1569. if (writeMask != stencilWriteMask_)
  1570. {
  1571. impl_->device_->SetRenderState(D3DRS_STENCILWRITEMASK, writeMask);
  1572. stencilWriteMask_ = writeMask;
  1573. }
  1574. }
  1575. }
  1576. void Graphics::SetClipPlane(bool enable, const Plane& clipPlane, const Matrix3x4& view, const Matrix4& projection)
  1577. {
  1578. if (enable != useClipPlane_)
  1579. {
  1580. impl_->device_->SetRenderState(D3DRS_CLIPPLANEENABLE, enable ? 1 : 0);
  1581. useClipPlane_ = enable;
  1582. }
  1583. if (enable)
  1584. {
  1585. Matrix4 viewProj = projection * view;
  1586. impl_->device_->SetClipPlane(0, clipPlane.Transformed(viewProj).ToVector4().Data());
  1587. }
  1588. }
  1589. void Graphics::BeginDumpShaders(const String& fileName)
  1590. {
  1591. shaderPrecache_ = new ShaderPrecache(context_, fileName);
  1592. }
  1593. void Graphics::EndDumpShaders()
  1594. {
  1595. shaderPrecache_.Reset();
  1596. }
  1597. void Graphics::PrecacheShaders(Deserializer& source)
  1598. {
  1599. ATOMIC_PROFILE(PrecacheShaders);
  1600. ShaderPrecache::LoadShaders(this, source);
  1601. }
  1602. bool Graphics::IsInitialized() const
  1603. {
  1604. return window_ != 0 && impl_->GetDevice() != 0;
  1605. }
  1606. PODVector<int> Graphics::GetMultiSampleLevels() const
  1607. {
  1608. PODVector<int> ret;
  1609. // No multisampling always supported
  1610. ret.Push(1);
  1611. if (!impl_->interface_)
  1612. return ret;
  1613. SDL_DisplayMode mode;
  1614. SDL_GetDesktopDisplayMode(0, &mode);
  1615. D3DFORMAT fullscreenFormat = SDL_BITSPERPIXEL(mode.format) == 16 ? D3DFMT_R5G6B5 : D3DFMT_X8R8G8B8;
  1616. for (unsigned i = (int)D3DMULTISAMPLE_2_SAMPLES; i < (int)D3DMULTISAMPLE_16_SAMPLES; ++i)
  1617. {
  1618. if (SUCCEEDED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, fullscreenFormat, FALSE,
  1619. (D3DMULTISAMPLE_TYPE)i, NULL)))
  1620. ret.Push(i);
  1621. }
  1622. return ret;
  1623. }
  1624. unsigned Graphics::GetFormat(CompressedFormat format) const
  1625. {
  1626. switch (format)
  1627. {
  1628. case CF_RGBA:
  1629. return D3DFMT_A8R8G8B8;
  1630. case CF_DXT1:
  1631. return D3DFMT_DXT1;
  1632. case CF_DXT3:
  1633. return D3DFMT_DXT3;
  1634. case CF_DXT5:
  1635. return D3DFMT_DXT5;
  1636. default:
  1637. return 0;
  1638. }
  1639. }
  1640. ShaderVariation* Graphics::GetShader(ShaderType type, const String& name, const String& defines) const
  1641. {
  1642. return GetShader(type, name.CString(), defines.CString());
  1643. }
  1644. ShaderVariation* Graphics::GetShader(ShaderType type, const char* name, const char* defines) const
  1645. {
  1646. if (lastShaderName_ != name || !lastShader_)
  1647. {
  1648. ResourceCache* cache = GetSubsystem<ResourceCache>();
  1649. String fullShaderName = shaderPath_ + name + shaderExtension_;
  1650. // Try to reduce repeated error log prints because of missing shaders
  1651. if (lastShaderName_ == name && !cache->Exists(fullShaderName))
  1652. return 0;
  1653. lastShader_ = cache->GetResource<Shader>(fullShaderName);
  1654. lastShaderName_ = name;
  1655. }
  1656. return lastShader_ ? lastShader_->GetVariation(type, defines) : (ShaderVariation*)0;
  1657. }
  1658. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1659. {
  1660. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1661. }
  1662. TextureUnit Graphics::GetTextureUnit(const String& name)
  1663. {
  1664. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1665. if (i != textureUnits_.End())
  1666. return i->second_;
  1667. else
  1668. return MAX_TEXTURE_UNITS;
  1669. }
  1670. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1671. {
  1672. for (HashMap<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1673. {
  1674. if (i->second_ == unit)
  1675. return i->first_;
  1676. }
  1677. return String::EMPTY;
  1678. }
  1679. Texture* Graphics::GetTexture(unsigned index) const
  1680. {
  1681. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1682. }
  1683. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1684. {
  1685. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1686. }
  1687. IntVector2 Graphics::GetRenderTargetDimensions() const
  1688. {
  1689. int width, height;
  1690. if (renderTargets_[0])
  1691. {
  1692. width = renderTargets_[0]->GetWidth();
  1693. height = renderTargets_[0]->GetHeight();
  1694. }
  1695. else
  1696. {
  1697. width = width_;
  1698. height = height_;
  1699. }
  1700. return IntVector2(width, height);
  1701. }
  1702. bool Graphics::GetDither() const
  1703. {
  1704. return false;
  1705. }
  1706. bool Graphics::IsDeviceLost() const
  1707. {
  1708. return impl_->deviceLost_;
  1709. }
  1710. void Graphics::OnWindowResized()
  1711. {
  1712. if (!impl_->device_ || !window_)
  1713. return;
  1714. int newWidth, newHeight;
  1715. SDL_GetWindowSize(window_, &newWidth, &newHeight);
  1716. if (newWidth == width_ && newHeight == height_)
  1717. return;
  1718. width_ = newWidth;
  1719. height_ = newHeight;
  1720. impl_->presentParams_.BackBufferWidth = (UINT)width_;
  1721. impl_->presentParams_.BackBufferHeight = (UINT)height_;
  1722. ResetDevice();
  1723. // Reset rendertargets and viewport for the new screen size
  1724. ResetRenderTargets();
  1725. ATOMIC_LOGDEBUGF("Window was resized to %dx%d", width_, height_);
  1726. using namespace ScreenMode;
  1727. VariantMap& eventData = GetEventDataMap();
  1728. eventData[P_WIDTH] = width_;
  1729. eventData[P_HEIGHT] = height_;
  1730. eventData[P_FULLSCREEN] = fullscreen_;
  1731. eventData[P_RESIZABLE] = resizable_;
  1732. eventData[P_BORDERLESS] = borderless_;
  1733. SendEvent(E_SCREENMODE, eventData);
  1734. }
  1735. void Graphics::OnWindowMoved()
  1736. {
  1737. if (!impl_->device_ || !window_ || fullscreen_)
  1738. return;
  1739. int newX, newY;
  1740. SDL_GetWindowPosition(window_, &newX, &newY);
  1741. if (newX == position_.x_ && newY == position_.y_)
  1742. return;
  1743. position_.x_ = newX;
  1744. position_.y_ = newY;
  1745. ATOMIC_LOGDEBUGF("Window was moved to %d,%d", position_.x_, position_.y_);
  1746. using namespace WindowPos;
  1747. VariantMap& eventData = GetEventDataMap();
  1748. eventData[P_X] = position_.x_;
  1749. eventData[P_Y] = position_.y_;
  1750. SendEvent(E_WINDOWPOS, eventData);
  1751. }
  1752. void Graphics::CleanupShaderPrograms(ShaderVariation* variation)
  1753. {
  1754. for (ShaderProgramMap::Iterator i = impl_->shaderPrograms_.Begin(); i != impl_->shaderPrograms_.End();)
  1755. {
  1756. if (i->first_.first_ == variation || i->first_.second_ == variation)
  1757. i = impl_->shaderPrograms_.Erase(i);
  1758. else
  1759. ++i;
  1760. }
  1761. if (vertexShader_ == variation || pixelShader_ == variation)
  1762. impl_->shaderProgram_ = 0;
  1763. }
  1764. unsigned Graphics::GetAlphaFormat()
  1765. {
  1766. return D3DFMT_A8;
  1767. }
  1768. unsigned Graphics::GetLuminanceFormat()
  1769. {
  1770. return D3DFMT_L8;
  1771. }
  1772. unsigned Graphics::GetLuminanceAlphaFormat()
  1773. {
  1774. return D3DFMT_A8L8;
  1775. }
  1776. unsigned Graphics::GetRGBFormat()
  1777. {
  1778. return D3DFMT_X8R8G8B8;
  1779. }
  1780. unsigned Graphics::GetRGBAFormat()
  1781. {
  1782. return D3DFMT_A8R8G8B8;
  1783. }
  1784. unsigned Graphics::GetRGBA16Format()
  1785. {
  1786. return D3DFMT_A16B16G16R16;
  1787. }
  1788. unsigned Graphics::GetRGBAFloat16Format()
  1789. {
  1790. return D3DFMT_A16B16G16R16F;
  1791. }
  1792. unsigned Graphics::GetRGBAFloat32Format()
  1793. {
  1794. return D3DFMT_A32B32G32R32F;
  1795. }
  1796. unsigned Graphics::GetRG16Format()
  1797. {
  1798. return D3DFMT_G16R16;
  1799. }
  1800. unsigned Graphics::GetRGFloat16Format()
  1801. {
  1802. return D3DFMT_G16R16F;
  1803. }
  1804. unsigned Graphics::GetRGFloat32Format()
  1805. {
  1806. return D3DFMT_G32R32F;
  1807. }
  1808. unsigned Graphics::GetFloat16Format()
  1809. {
  1810. return D3DFMT_R16F;
  1811. }
  1812. unsigned Graphics::GetFloat32Format()
  1813. {
  1814. return D3DFMT_R32F;
  1815. }
  1816. unsigned Graphics::GetLinearDepthFormat()
  1817. {
  1818. return D3DFMT_R32F;
  1819. }
  1820. unsigned Graphics::GetDepthStencilFormat()
  1821. {
  1822. return D3DFMT_D24S8;
  1823. }
  1824. unsigned Graphics::GetReadableDepthFormat()
  1825. {
  1826. return readableDepthFormat;
  1827. }
  1828. unsigned Graphics::GetFormat(const String& formatName)
  1829. {
  1830. String nameLower = formatName.ToLower().Trimmed();
  1831. if (nameLower == "a")
  1832. return GetAlphaFormat();
  1833. if (nameLower == "l")
  1834. return GetLuminanceFormat();
  1835. if (nameLower == "la")
  1836. return GetLuminanceAlphaFormat();
  1837. if (nameLower == "rgb")
  1838. return GetRGBFormat();
  1839. if (nameLower == "rgba")
  1840. return GetRGBAFormat();
  1841. if (nameLower == "rgba16")
  1842. return GetRGBA16Format();
  1843. if (nameLower == "rgba16f")
  1844. return GetRGBAFloat16Format();
  1845. if (nameLower == "rgba32f")
  1846. return GetRGBAFloat32Format();
  1847. if (nameLower == "rg16")
  1848. return GetRG16Format();
  1849. if (nameLower == "rg16f")
  1850. return GetRGFloat16Format();
  1851. if (nameLower == "rg32f")
  1852. return GetRGFloat32Format();
  1853. if (nameLower == "r16f")
  1854. return GetFloat16Format();
  1855. if (nameLower == "r32f" || nameLower == "float")
  1856. return GetFloat32Format();
  1857. if (nameLower == "lineardepth" || nameLower == "depth")
  1858. return GetLinearDepthFormat();
  1859. if (nameLower == "d24s8")
  1860. return GetDepthStencilFormat();
  1861. if (nameLower == "readabledepth" || nameLower == "hwdepth")
  1862. return GetReadableDepthFormat();
  1863. return GetRGBFormat();
  1864. }
  1865. unsigned Graphics::GetMaxBones()
  1866. {
  1867. return 64;
  1868. }
  1869. bool Graphics::GetGL3Support()
  1870. {
  1871. return gl3Support;
  1872. }
  1873. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1874. {
  1875. if (index < MAX_VERTEX_STREAMS && impl_->streamFrequencies_[index] != frequency)
  1876. {
  1877. impl_->device_->SetStreamSourceFreq(index, frequency);
  1878. impl_->streamFrequencies_[index] = frequency;
  1879. }
  1880. }
  1881. void Graphics::ResetStreamFrequencies()
  1882. {
  1883. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1884. {
  1885. if (impl_->streamFrequencies_[i] != 1)
  1886. {
  1887. impl_->device_->SetStreamSourceFreq(i, 1);
  1888. impl_->streamFrequencies_[i] = 1;
  1889. }
  1890. }
  1891. }
  1892. bool Graphics::OpenWindow(int width, int height, bool resizable, bool borderless)
  1893. {
  1894. if (!externalWindow_)
  1895. {
  1896. unsigned flags = 0;
  1897. if (resizable)
  1898. flags |= SDL_WINDOW_RESIZABLE;
  1899. if (borderless)
  1900. flags |= SDL_WINDOW_BORDERLESS;
  1901. window_ = SDL_CreateWindow(windowTitle_.CString(), position_.x_, position_.y_, width, height, flags);
  1902. }
  1903. else
  1904. window_ = SDL_CreateWindowFrom(externalWindow_, 0);
  1905. if (!window_)
  1906. {
  1907. ATOMIC_LOGERRORF("Could not create window, root cause: '%s'", SDL_GetError());
  1908. return false;
  1909. }
  1910. SDL_GetWindowPosition(window_, &position_.x_, &position_.y_);
  1911. CreateWindowIcon();
  1912. return true;
  1913. }
  1914. void Graphics::AdjustWindow(int& newWidth, int& newHeight, bool& newFullscreen, bool& newBorderless)
  1915. {
  1916. if (!externalWindow_)
  1917. {
  1918. if (!newWidth || !newHeight)
  1919. {
  1920. SDL_MaximizeWindow(window_);
  1921. SDL_GetWindowSize(window_, &newWidth, &newHeight);
  1922. }
  1923. else
  1924. SDL_SetWindowSize(window_, newWidth, newHeight);
  1925. // 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
  1926. SDL_HideWindow(window_);
  1927. SDL_SetWindowFullscreen(window_, newFullscreen ? SDL_WINDOW_FULLSCREEN : 0);
  1928. SDL_SetWindowBordered(window_, newBorderless ? SDL_FALSE : SDL_TRUE);
  1929. SDL_ShowWindow(window_);
  1930. }
  1931. else
  1932. {
  1933. // If external window, must ask its dimensions instead of trying to set them
  1934. SDL_GetWindowSize(window_, &newWidth, &newHeight);
  1935. newFullscreen = false;
  1936. }
  1937. }
  1938. bool Graphics::CreateInterface()
  1939. {
  1940. impl_->interface_ = Direct3DCreate9(D3D_SDK_VERSION);
  1941. if (!impl_->interface_)
  1942. {
  1943. ATOMIC_LOGERROR("Could not create Direct3D9 interface");
  1944. return false;
  1945. }
  1946. HRESULT hr = impl_->interface_->GetDeviceCaps(impl_->adapter_, impl_->deviceType_, &impl_->deviceCaps_);
  1947. if (FAILED(hr))
  1948. {
  1949. ATOMIC_LOGD3DERROR("Could not get Direct3D capabilities", hr);
  1950. return false;
  1951. }
  1952. hr = impl_->interface_->GetAdapterIdentifier(impl_->adapter_, 0, &impl_->adapterIdentifier_);
  1953. if (FAILED(hr))
  1954. {
  1955. ATOMIC_LOGD3DERROR("Could not get Direct3D adapter identifier", hr);
  1956. return false;
  1957. }
  1958. if (impl_->deviceCaps_.PixelShaderVersion < D3DPS_VERSION(3, 0))
  1959. {
  1960. ATOMIC_LOGERROR("Shader model 3.0 display adapter is required");
  1961. return false;
  1962. }
  1963. return true;
  1964. }
  1965. bool Graphics::CreateDevice(unsigned adapter, unsigned deviceType)
  1966. {
  1967. #ifdef ATOMIC_LUAJIT
  1968. DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE;
  1969. #else
  1970. DWORD behaviorFlags = 0;
  1971. #endif
  1972. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
  1973. {
  1974. behaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
  1975. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_PUREDEVICE)
  1976. behaviorFlags |= D3DCREATE_PUREDEVICE;
  1977. }
  1978. else
  1979. behaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  1980. HRESULT hr = impl_->interface_->CreateDevice(
  1981. adapter,
  1982. (D3DDEVTYPE)deviceType,
  1983. GetWindowHandle(window_),
  1984. behaviorFlags,
  1985. &impl_->presentParams_,
  1986. &impl_->device_);
  1987. if (FAILED(hr))
  1988. {
  1989. ATOMIC_LOGD3DERROR("Could not create Direct3D9 device", hr);
  1990. return false;
  1991. }
  1992. impl_->adapter_ = adapter;
  1993. impl_->deviceType_ = (D3DDEVTYPE)deviceType;
  1994. OnDeviceReset();
  1995. ATOMIC_LOGINFO("Created Direct3D9 device");
  1996. return true;
  1997. }
  1998. void Graphics::CheckFeatureSupport()
  1999. {
  2000. anisotropySupport_ = true;
  2001. dxtTextureSupport_ = true;
  2002. // Reset features first
  2003. lightPrepassSupport_ = false;
  2004. deferredSupport_ = false;
  2005. hardwareShadowSupport_ = false;
  2006. instancingSupport_ = false;
  2007. readableDepthFormat = 0;
  2008. // Check hardware shadow map support: prefer NVIDIA style hardware depth compared shadow maps if available
  2009. shadowMapFormat_ = D3DFMT_D16;
  2010. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2011. {
  2012. hardwareShadowSupport_ = true;
  2013. // Check for hires depth support
  2014. hiresShadowMapFormat_ = D3DFMT_D24X8;
  2015. if (!impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2016. hiresShadowMapFormat_ = 0;
  2017. }
  2018. else
  2019. {
  2020. // ATI DF16 format needs manual depth compare in the shader
  2021. shadowMapFormat_ = MAKEFOURCC('D', 'F', '1', '6');
  2022. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2023. {
  2024. // Check for hires depth support
  2025. hiresShadowMapFormat_ = MAKEFOURCC('D', 'F', '2', '4');
  2026. if (!impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2027. hiresShadowMapFormat_ = 0;
  2028. }
  2029. else
  2030. {
  2031. // No shadow map support
  2032. shadowMapFormat_ = 0;
  2033. hiresShadowMapFormat_ = 0;
  2034. }
  2035. }
  2036. // Check for Intel 4 Series with an old driver, enable manual shadow map compare in that case
  2037. if (shadowMapFormat_ == D3DFMT_D16)
  2038. {
  2039. if (impl_->adapterIdentifier_.VendorId == 0x8086 && impl_->adapterIdentifier_.DeviceId == 0x2a42 &&
  2040. impl_->adapterIdentifier_.DriverVersion.QuadPart <= 0x0007000f000a05d0ULL)
  2041. hardwareShadowSupport_ = false;
  2042. }
  2043. // Check for readable depth (INTZ hack)
  2044. D3DFORMAT intZFormat = (D3DFORMAT)MAKEFOURCC('I', 'N', 'T', 'Z');
  2045. if (impl_->CheckFormatSupport(intZFormat, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2046. readableDepthFormat = intZFormat;
  2047. // Check for dummy color rendertarget format used with hardware shadow maps
  2048. dummyColorFormat_ = D3DFMT_A8R8G8B8;
  2049. D3DFORMAT nullFormat = (D3DFORMAT)MAKEFOURCC('N', 'U', 'L', 'L');
  2050. if (impl_->CheckFormatSupport(nullFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2051. dummyColorFormat_ = nullFormat;
  2052. else if (impl_->CheckFormatSupport(D3DFMT_R16F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2053. dummyColorFormat_ = D3DFMT_R16F;
  2054. else if (impl_->CheckFormatSupport(D3DFMT_R5G6B5, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2055. dummyColorFormat_ = D3DFMT_R5G6B5;
  2056. else if (impl_->CheckFormatSupport(D3DFMT_A4R4G4B4, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2057. dummyColorFormat_ = D3DFMT_A4R4G4B4;
  2058. // Check for light prepass and deferred rendering support
  2059. if (impl_->deviceCaps_.NumSimultaneousRTs >= 2 && impl_->CheckFormatSupport(D3DFMT_R32F, D3DUSAGE_RENDERTARGET,
  2060. D3DRTYPE_TEXTURE))
  2061. {
  2062. lightPrepassSupport_ = true;
  2063. if (impl_->deviceCaps_.NumSimultaneousRTs >= 4)
  2064. deferredSupport_ = true;
  2065. }
  2066. // Check for stream offset (needed for instancing)
  2067. if (impl_->deviceCaps_.DevCaps2 & D3DDEVCAPS2_STREAMOFFSET)
  2068. instancingSupport_ = true;
  2069. // Check for sRGB read & write
  2070. /// \todo Should be checked for each texture format separately
  2071. sRGBSupport_ = impl_->CheckFormatSupport(D3DFMT_X8R8G8B8, D3DUSAGE_QUERY_SRGBREAD, D3DRTYPE_TEXTURE);
  2072. sRGBWriteSupport_ = impl_->CheckFormatSupport(D3DFMT_X8R8G8B8, D3DUSAGE_QUERY_SRGBWRITE, D3DRTYPE_TEXTURE);
  2073. }
  2074. void Graphics::ResetDevice()
  2075. {
  2076. OnDeviceLost();
  2077. if (SUCCEEDED(impl_->device_->Reset(&impl_->presentParams_)))
  2078. {
  2079. impl_->deviceLost_ = false;
  2080. OnDeviceReset();
  2081. }
  2082. }
  2083. void Graphics::OnDeviceLost()
  2084. {
  2085. ATOMIC_LOGINFO("Device lost");
  2086. if (impl_->defaultColorSurface_)
  2087. {
  2088. impl_->defaultColorSurface_->Release();
  2089. impl_->defaultColorSurface_ = 0;
  2090. }
  2091. if (impl_->defaultDepthStencilSurface_)
  2092. {
  2093. impl_->defaultDepthStencilSurface_->Release();
  2094. impl_->defaultDepthStencilSurface_ = 0;
  2095. }
  2096. if (impl_->frameQuery_)
  2097. {
  2098. impl_->frameQuery_->Release();
  2099. impl_->frameQuery_ = 0;
  2100. }
  2101. {
  2102. MutexLock lock(gpuObjectMutex_);
  2103. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2104. (*i)->OnDeviceLost();
  2105. }
  2106. SendEvent(E_DEVICELOST);
  2107. }
  2108. void Graphics::OnDeviceReset()
  2109. {
  2110. {
  2111. MutexLock lock(gpuObjectMutex_);
  2112. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2113. (*i)->OnDeviceReset();
  2114. }
  2115. // Get default surfaces
  2116. impl_->device_->GetRenderTarget(0, &impl_->defaultColorSurface_);
  2117. impl_->device_->GetDepthStencilSurface(&impl_->defaultDepthStencilSurface_);
  2118. // Create frame query for flushing the GPU command buffer
  2119. impl_->device_->CreateQuery(D3DQUERYTYPE_EVENT, &impl_->frameQuery_);
  2120. ResetCachedState();
  2121. SendEvent(E_DEVICERESET);
  2122. }
  2123. void Graphics::ResetCachedState()
  2124. {
  2125. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2126. {
  2127. vertexBuffers_[i] = 0;
  2128. impl_->streamOffsets_[i] = 0;
  2129. }
  2130. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  2131. {
  2132. textures_[i] = 0;
  2133. impl_->minMagFilters_[i] = D3DTEXF_POINT;
  2134. impl_->mipFilters_[i] = D3DTEXF_NONE;
  2135. impl_->uAddressModes_[i] = D3DTADDRESS_WRAP;
  2136. impl_->vAddressModes_[i] = D3DTADDRESS_WRAP;
  2137. impl_->wAddressModes_[i] = D3DTADDRESS_WRAP;
  2138. impl_->maxAnisotropy_[i] = M_MAX_UNSIGNED;
  2139. impl_->borderColors_[i] = Color(0.0f, 0.0f, 0.0f, 0.0f);
  2140. impl_->sRGBModes_[i] = false;
  2141. }
  2142. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2143. {
  2144. renderTargets_[i] = 0;
  2145. impl_->colorSurfaces_[i] = 0;
  2146. }
  2147. depthStencil_ = 0;
  2148. impl_->depthStencilSurface_ = 0;
  2149. viewport_ = IntRect(0, 0, width_, height_);
  2150. impl_->sRGBWrite_ = false;
  2151. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2152. impl_->streamFrequencies_[i] = 1;
  2153. indexBuffer_ = 0;
  2154. vertexShader_ = 0;
  2155. pixelShader_ = 0;
  2156. blendMode_ = BLEND_REPLACE;
  2157. alphaToCoverage_ = false;
  2158. colorWrite_ = true;
  2159. cullMode_ = CULL_CCW;
  2160. constantDepthBias_ = 0.0f;
  2161. slopeScaledDepthBias_ = 0.0f;
  2162. depthTestMode_ = CMP_LESSEQUAL;
  2163. depthWrite_ = true;
  2164. fillMode_ = FILL_SOLID;
  2165. scissorTest_ = false;
  2166. scissorRect_ = IntRect::ZERO;
  2167. stencilTest_ = false;
  2168. stencilTestMode_ = CMP_ALWAYS;
  2169. stencilPass_ = OP_KEEP;
  2170. stencilFail_ = OP_KEEP;
  2171. stencilZFail_ = OP_KEEP;
  2172. stencilRef_ = 0;
  2173. stencilCompareMask_ = M_MAX_UNSIGNED;
  2174. stencilWriteMask_ = M_MAX_UNSIGNED;
  2175. useClipPlane_ = false;
  2176. impl_->blendEnable_ = FALSE;
  2177. impl_->srcBlend_ = D3DBLEND_ONE;
  2178. impl_->destBlend_ = D3DBLEND_ZERO;
  2179. impl_->blendOp_ = D3DBLENDOP_ADD;
  2180. impl_->vertexDeclaration_ = 0;
  2181. impl_->queryIssued_ = false;
  2182. }
  2183. void Graphics::SetTextureUnitMappings()
  2184. {
  2185. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2186. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2187. textureUnits_["NormalMap"] = TU_NORMAL;
  2188. textureUnits_["SpecMap"] = TU_SPECULAR;
  2189. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2190. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  2191. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  2192. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2193. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  2194. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  2195. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2196. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  2197. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  2198. textureUnits_["VolumeMap"] = TU_VOLUMEMAP;
  2199. textureUnits_["ZoneCubeMap"] = TU_ZONE;
  2200. textureUnits_["ZoneVolumeMap"] = TU_ZONE;
  2201. }
  2202. // ATOMIC BEGIN
  2203. // To satisfy script binding linking
  2204. void Graphics::SetTextureForUpdate(Texture* texture)
  2205. {
  2206. }
  2207. void Graphics::SetTextureParametersDirty()
  2208. {
  2209. }
  2210. /// Return shader program. This is an API-specific class and should not be used by applications.
  2211. ShaderProgram* Graphics::GetShaderProgram() const
  2212. {
  2213. return 0;
  2214. }
  2215. /// Restore GPU objects and reinitialize state. Requires an open window. Used only on OpenGL.
  2216. void Graphics::Restore()
  2217. {
  2218. }
  2219. void Graphics::CleanupRenderSurface(RenderSurface* surface)
  2220. {
  2221. }
  2222. ConstantBuffer* Graphics::GetOrCreateConstantBuffer(ShaderType type, unsigned index, unsigned size)
  2223. {
  2224. return 0;
  2225. }
  2226. void Graphics::MarkFBODirty()
  2227. {
  2228. }
  2229. void Graphics::SetVBO(unsigned object)
  2230. {
  2231. }
  2232. void Graphics::SetUBO(unsigned object)
  2233. {
  2234. }
  2235. // ATOMIC END
  2236. }