D3D9Graphics.cpp 69 KB

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