D3D9Graphics.cpp 82 KB

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