D3D9Graphics.cpp 74 KB

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