D3D9Graphics.cpp 78 KB

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