D3D9Graphics.cpp 78 KB

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