D3D9Graphics.cpp 81 KB

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