D3D9Graphics.cpp 74 KB

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