D3D9Graphics.cpp 69 KB

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