D3D9Graphics.cpp 76 KB

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