D3D9Graphics.cpp 75 KB

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