D3D9Graphics.cpp 79 KB

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