D3D9Graphics.cpp 83 KB

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