D3D9Graphics.cpp 78 KB

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