D3D9Graphics.cpp 86 KB

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