D3D9Graphics.cpp 81 KB

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