D3D9Graphics.cpp 78 KB

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