D3D9Graphics.cpp 86 KB

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