D3D9Graphics.cpp 81 KB

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