D3D9Graphics.cpp 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640
  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. if (impl_->presentParams_.MultiSampleType)
  454. {
  455. useBackBuffer = false;
  456. surfaceDesc.Format = D3DFMT_A8R8G8B8;
  457. }
  458. IDirect3DSurface9* surface = 0;
  459. impl_->device_->CreateOffscreenPlainSurface(width_, height_, surfaceDesc.Format, D3DPOOL_SYSTEMMEM, &surface, 0);
  460. if (!surface)
  461. return false;
  462. if (useBackBuffer)
  463. impl_->device_->GetRenderTargetData(impl_->defaultColorSurface_, surface);
  464. else
  465. impl_->device_->GetFrontBufferData(0, surface);
  466. D3DLOCKED_RECT lockedRect;
  467. lockedRect.pBits = 0;
  468. surface->LockRect(&lockedRect, 0, D3DLOCK_NOSYSLOCK | D3DLOCK_READONLY);
  469. if (!lockedRect.pBits)
  470. {
  471. surface->Release();
  472. return false;
  473. }
  474. destImage.SetSize(width_, height_, 3);
  475. unsigned char* destData = destImage.GetData();
  476. if (surfaceDesc.Format == D3DFMT_R5G6B5)
  477. {
  478. for (int y = 0; y < height_; ++y)
  479. {
  480. unsigned short* src = (unsigned short*)((unsigned char*)lockedRect.pBits + y * lockedRect.Pitch);
  481. unsigned char* dest = destData + y * width_ * 3;
  482. for (int x = 0; x < width_; ++x)
  483. {
  484. unsigned short rgb = *src++;
  485. int b = rgb & 31;
  486. int g = (rgb >> 5) & 63;
  487. int r = (rgb >> 11);
  488. dest[0] = (int)(r * 255.0f / 31.0f);
  489. dest[1] = (int)(g * 255.0f / 63.0f);
  490. dest[2] = (int)(b * 255.0f / 31.0f);
  491. dest += 3;
  492. }
  493. }
  494. }
  495. else
  496. {
  497. for (int y = 0; y < height_; ++y)
  498. {
  499. unsigned char* src = (unsigned char*)lockedRect.pBits + y * lockedRect.Pitch;
  500. unsigned char* dest = destData + y * width_ * 3;
  501. for (int x = 0; x < width_; ++x)
  502. {
  503. dest[0] = src[2];
  504. dest[1] = src[1];
  505. dest[2] = src[0];
  506. src += 4;
  507. dest += 3;
  508. }
  509. }
  510. }
  511. surface->UnlockRect();
  512. surface->Release();
  513. return true;
  514. }
  515. bool Graphics::BeginFrame()
  516. {
  517. if (!IsInitialized())
  518. return false;
  519. // If using an external window, check it for size changes, and reset screen mode if necessary
  520. if (externalWindow_)
  521. {
  522. int width, height;
  523. SDL_GetWindowSize(impl_->window_, &width, &height);
  524. if (width != width_ || height != height_)
  525. SetMode(width, height);
  526. }
  527. // Check for lost device before rendering
  528. HRESULT hr = impl_->device_->TestCooperativeLevel();
  529. if (hr != D3D_OK)
  530. {
  531. PROFILE(DeviceLost);
  532. deviceLost_ = true;
  533. // The device can not be reset yet, sleep and try again eventually
  534. if (hr == D3DERR_DEVICELOST)
  535. {
  536. Time::Sleep(20);
  537. return false;
  538. }
  539. // The device is lost, but ready to be reset. Reset device but do not render on this frame yet
  540. if (hr == D3DERR_DEVICENOTRESET)
  541. {
  542. ResetDevice();
  543. return false;
  544. }
  545. }
  546. // If a query was issued on the previous frame, wait for it to finish before beginning the next
  547. if (impl_->frameQuery_ && queryIssued_)
  548. {
  549. PROFILE(FlushGPU);
  550. while (impl_->frameQuery_->GetData(0, 0, D3DGETDATA_FLUSH) == S_FALSE)
  551. {
  552. }
  553. queryIssued_ = false;
  554. }
  555. impl_->device_->BeginScene();
  556. // Set default rendertarget and depth buffer
  557. ResetRenderTargets();
  558. // Cleanup textures from previous frame
  559. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  560. SetTexture(i, 0);
  561. // Cleanup stream frequencies from previous frame
  562. ResetStreamFrequencies();
  563. numPrimitives_ = 0;
  564. numBatches_ = 0;
  565. SendEvent(E_BEGINRENDERING);
  566. return true;
  567. }
  568. void Graphics::EndFrame()
  569. {
  570. if (!IsInitialized())
  571. return;
  572. PROFILE(Present);
  573. SendEvent(E_ENDRENDERING);
  574. impl_->device_->EndScene();
  575. impl_->device_->Present(0, 0, 0, 0);
  576. // Optionally flush GPU buffer to avoid control lag or framerate fluctuations due to pre-render
  577. if (impl_->frameQuery_ && flushGPU_)
  578. {
  579. impl_->frameQuery_->Issue(D3DISSUE_END);
  580. queryIssued_ = true;
  581. }
  582. // Clean up too large scratch buffers
  583. CleanupScratchBuffers();
  584. }
  585. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  586. {
  587. DWORD d3dFlags = 0;
  588. if (flags & CLEAR_COLOR)
  589. d3dFlags |= D3DCLEAR_TARGET;
  590. if (flags & CLEAR_DEPTH)
  591. d3dFlags |= D3DCLEAR_ZBUFFER;
  592. if (flags & CLEAR_STENCIL)
  593. d3dFlags |= D3DCLEAR_STENCIL;
  594. impl_->device_->Clear(0, 0, d3dFlags, GetD3DColor(color), depth, stencil);
  595. }
  596. bool Graphics::ResolveToTexture(Texture2D* destination, const IntRect& viewport)
  597. {
  598. if (!destination || !destination->GetRenderSurface() || destination->GetWidth() != width_ ||
  599. destination->GetHeight() != height_)
  600. return false;
  601. PROFILE(ResolveToTexture);
  602. IntRect vpCopy = viewport;
  603. if (vpCopy.right_ <= vpCopy.left_)
  604. vpCopy.right_ = vpCopy.left_ + 1;
  605. if (vpCopy.bottom_ <= vpCopy.top_)
  606. vpCopy.bottom_ = vpCopy.top_ + 1;
  607. RECT rect;
  608. rect.left = Clamp(vpCopy.left_, 0, width_);
  609. rect.top = Clamp(vpCopy.top_, 0, height_);
  610. rect.right = Clamp(vpCopy.right_, 0, width_);
  611. rect.bottom = Clamp(vpCopy.bottom_, 0, height_);
  612. return SUCCEEDED(impl_->device_->StretchRect(impl_->defaultColorSurface_, &rect,
  613. (IDirect3DSurface9*)destination->GetRenderSurface()->GetSurface(), &rect, D3DTEXF_NONE));
  614. }
  615. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  616. {
  617. if (!vertexCount)
  618. return;
  619. ResetStreamFrequencies();
  620. unsigned primitiveCount = 0;
  621. switch (type)
  622. {
  623. case TRIANGLE_LIST:
  624. primitiveCount = vertexCount / 3;
  625. impl_->device_->DrawPrimitive(D3DPT_TRIANGLELIST, vertexStart, primitiveCount);
  626. break;
  627. case LINE_LIST:
  628. primitiveCount = vertexCount / 2;
  629. impl_->device_->DrawPrimitive(D3DPT_LINELIST, vertexStart, primitiveCount);
  630. break;
  631. }
  632. numPrimitives_ += primitiveCount;
  633. ++numBatches_;
  634. }
  635. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  636. {
  637. if (!indexCount)
  638. return;
  639. ResetStreamFrequencies();
  640. unsigned primitiveCount = 0;
  641. switch (type)
  642. {
  643. case TRIANGLE_LIST:
  644. primitiveCount = indexCount / 3;
  645. impl_->device_->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  646. break;
  647. case LINE_LIST:
  648. primitiveCount = indexCount / 2;
  649. impl_->device_->DrawIndexedPrimitive(D3DPT_LINELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  650. break;
  651. }
  652. numPrimitives_ += primitiveCount;
  653. ++numBatches_;
  654. }
  655. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount,
  656. unsigned instanceCount)
  657. {
  658. if (!indexCount || !instanceCount)
  659. return;
  660. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  661. {
  662. VertexBuffer* buffer = vertexBuffers_[i];
  663. if (buffer)
  664. {
  665. if (buffer->GetElementMask() & MASK_INSTANCEMATRIX1)
  666. SetStreamFrequency(i, D3DSTREAMSOURCE_INSTANCEDATA | 1);
  667. else
  668. SetStreamFrequency(i, D3DSTREAMSOURCE_INDEXEDDATA | instanceCount);
  669. }
  670. }
  671. unsigned primitiveCount = 0;
  672. switch (type)
  673. {
  674. case TRIANGLE_LIST:
  675. primitiveCount = indexCount / 3;
  676. impl_->device_->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  677. break;
  678. case LINE_LIST:
  679. primitiveCount = indexCount / 2;
  680. impl_->device_->DrawIndexedPrimitive(D3DPT_LINELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  681. break;
  682. }
  683. numPrimitives_ += instanceCount * primitiveCount;
  684. ++numBatches_;
  685. }
  686. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  687. {
  688. // Note: this is not multi-instance safe
  689. static PODVector<VertexBuffer*> vertexBuffers(1);
  690. static PODVector<unsigned> elementMasks(1);
  691. vertexBuffers[0] = buffer;
  692. elementMasks[0] = MASK_DEFAULT;
  693. SetVertexBuffers(vertexBuffers, elementMasks);
  694. }
  695. bool Graphics::SetVertexBuffers(const PODVector<VertexBuffer*>& buffers, const PODVector<unsigned>&
  696. elementMasks, unsigned instanceOffset)
  697. {
  698. if (buffers.Size() > MAX_VERTEX_STREAMS)
  699. {
  700. LOGERROR("Too many vertex buffers");
  701. return false;
  702. }
  703. if (buffers.Size() != elementMasks.Size())
  704. {
  705. LOGERROR("Amount of element masks and vertex buffers does not match");
  706. return false;
  707. }
  708. // Build vertex declaration hash code out of the buffers & masks
  709. unsigned long long hash = 0;
  710. for (unsigned i = 0; i < buffers.Size(); ++i)
  711. {
  712. if (!buffers[i])
  713. continue;
  714. hash |= buffers[i]->GetBufferHash(i, elementMasks[i]);
  715. }
  716. if (hash)
  717. {
  718. // If no previous vertex declaration for that hash, create new
  719. if (!vertexDeclarations_.Contains(hash))
  720. {
  721. SharedPtr<VertexDeclaration> newDeclaration(new VertexDeclaration(this, buffers, elementMasks));
  722. if (!newDeclaration->GetDeclaration())
  723. {
  724. LOGERROR("Failed to create vertex declaration");
  725. return false;
  726. }
  727. vertexDeclarations_[hash] = newDeclaration;
  728. }
  729. VertexDeclaration* declaration = vertexDeclarations_[hash];
  730. if (declaration != vertexDeclaration_)
  731. {
  732. impl_->device_->SetVertexDeclaration(declaration->GetDeclaration());
  733. vertexDeclaration_ = declaration;
  734. }
  735. }
  736. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  737. {
  738. VertexBuffer* buffer = 0;
  739. unsigned offset = 0;
  740. if (i < buffers.Size())
  741. {
  742. buffer = buffers[i];
  743. if (buffer && buffer->GetElementMask() & MASK_INSTANCEMATRIX1)
  744. offset = instanceOffset * buffer->GetVertexSize();
  745. }
  746. if (buffer != vertexBuffers_[i] || offset != streamOffsets_[i])
  747. {
  748. if (buffer)
  749. impl_->device_->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->GetGPUObject(), offset, buffer->GetVertexSize());
  750. else
  751. impl_->device_->SetStreamSource(i, 0, 0, 0);
  752. vertexBuffers_[i] = buffer;
  753. streamOffsets_[i] = offset;
  754. }
  755. }
  756. return true;
  757. }
  758. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>&
  759. elementMasks, unsigned instanceOffset)
  760. {
  761. if (buffers.Size() > MAX_VERTEX_STREAMS)
  762. {
  763. LOGERROR("Too many vertex buffers");
  764. return false;
  765. }
  766. if (buffers.Size() != elementMasks.Size())
  767. {
  768. LOGERROR("Amount of element masks and vertex buffers does not match");
  769. return false;
  770. }
  771. unsigned long long hash = 0;
  772. for (unsigned i = 0; i < buffers.Size(); ++i)
  773. {
  774. if (!buffers[i])
  775. continue;
  776. hash |= buffers[i]->GetBufferHash(i, elementMasks[i]);
  777. }
  778. if (hash)
  779. {
  780. if (!vertexDeclarations_.Contains(hash))
  781. {
  782. SharedPtr<VertexDeclaration> newDeclaration(new VertexDeclaration(this, buffers, elementMasks));
  783. if (!newDeclaration->GetDeclaration())
  784. {
  785. LOGERROR("Failed to create vertex declaration");
  786. return false;
  787. }
  788. vertexDeclarations_[hash] = newDeclaration;
  789. }
  790. VertexDeclaration* declaration = vertexDeclarations_[hash];
  791. if (declaration != vertexDeclaration_)
  792. {
  793. impl_->device_->SetVertexDeclaration(declaration->GetDeclaration());
  794. vertexDeclaration_ = declaration;
  795. }
  796. }
  797. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  798. {
  799. VertexBuffer* buffer = 0;
  800. unsigned offset = 0;
  801. if (i < buffers.Size())
  802. {
  803. buffer = buffers[i];
  804. if (buffer && buffer->GetElementMask() & MASK_INSTANCEMATRIX1)
  805. offset = instanceOffset * buffer->GetVertexSize();
  806. }
  807. if (buffer != vertexBuffers_[i] || offset != streamOffsets_[i])
  808. {
  809. if (buffer)
  810. impl_->device_->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->GetGPUObject(), offset, buffer->GetVertexSize());
  811. else
  812. impl_->device_->SetStreamSource(i, 0, 0, 0);
  813. vertexBuffers_[i] = buffer;
  814. streamOffsets_[i] = offset;
  815. }
  816. }
  817. return true;
  818. }
  819. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  820. {
  821. if (buffer != indexBuffer_)
  822. {
  823. if (buffer)
  824. impl_->device_->SetIndices((IDirect3DIndexBuffer9*)buffer->GetGPUObject());
  825. else
  826. impl_->device_->SetIndices(0);
  827. indexBuffer_ = buffer;
  828. }
  829. }
  830. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  831. {
  832. if (vs == vertexShader_ && ps == pixelShader_)
  833. return;
  834. ClearParameterSources();
  835. if (vs != vertexShader_)
  836. {
  837. // Clear all previous vertex shader register mappings
  838. for (HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Begin(); i != shaderParameters_.End(); ++i)
  839. {
  840. if (i->second_.type_ == VS)
  841. i->second_.register_ = M_MAX_UNSIGNED;
  842. }
  843. // Create the shader now if not yet created. If already attempted, do not retry
  844. if (vs && !vs->IsCreated())
  845. {
  846. if (!vs->IsFailed())
  847. {
  848. PROFILE(CreateVertexShader);
  849. bool success = vs->Create();
  850. if (success)
  851. LOGDEBUG("Created vertex shader " + vs->GetName());
  852. else
  853. {
  854. LOGERROR("Failed to create vertex shader " + vs->GetName());
  855. vs = 0;
  856. }
  857. }
  858. else
  859. vs = 0;
  860. }
  861. if (vs && vs->GetShaderType() == VS)
  862. {
  863. impl_->device_->SetVertexShader((IDirect3DVertexShader9*)vs->GetGPUObject());
  864. // Update the parameter-to-register mappings
  865. const HashMap<StringHash, ShaderParameter>& parameters = vs->GetParameters();
  866. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  867. shaderParameters_[i->first_].register_ = i->second_.register_;
  868. }
  869. else
  870. {
  871. impl_->device_->SetVertexShader(0);
  872. vs = 0;
  873. }
  874. vertexShader_ = vs;
  875. }
  876. if (ps != pixelShader_)
  877. {
  878. for (HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Begin(); i != shaderParameters_.End(); ++i)
  879. {
  880. if (i->second_.type_ == PS)
  881. i->second_.register_ = M_MAX_UNSIGNED;
  882. }
  883. if (ps && !ps->IsCreated())
  884. {
  885. if (!ps->IsFailed())
  886. {
  887. PROFILE(CreatePixelShader);
  888. bool success = ps->Create();
  889. if (success)
  890. LOGDEBUG("Created pixel shader " + ps->GetName());
  891. else
  892. {
  893. LOGERROR("Failed to create pixel shader " + ps->GetName());
  894. ps = 0;
  895. }
  896. }
  897. else
  898. ps = 0;
  899. }
  900. if (ps && ps->GetShaderType() == PS)
  901. {
  902. impl_->device_->SetPixelShader((IDirect3DPixelShader9*)ps->GetGPUObject());
  903. const HashMap<StringHash, ShaderParameter>& parameters = ps->GetParameters();
  904. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  905. shaderParameters_[i->first_].register_ = i->second_.register_;
  906. }
  907. else
  908. {
  909. impl_->device_->SetPixelShader(0);
  910. ps = 0;
  911. }
  912. pixelShader_ = ps;
  913. }
  914. }
  915. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  916. {
  917. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  918. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  919. return;
  920. if (i->second_.type_ == VS)
  921. impl_->device_->SetVertexShaderConstantF(i->second_.register_, data, count / 4);
  922. else
  923. impl_->device_->SetPixelShaderConstantF(i->second_.register_, data, count / 4);
  924. }
  925. void Graphics::SetShaderParameter(StringHash param, float value)
  926. {
  927. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  928. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  929. return;
  930. float data[4];
  931. data[0] = value;
  932. data[1] = 0.0f;
  933. data[2] = 0.0f;
  934. data[3] = 0.0f;
  935. if (i->second_.type_ == VS)
  936. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data[0], 1);
  937. else
  938. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data[0], 1);
  939. }
  940. void Graphics::SetShaderParameter(StringHash param, bool value)
  941. {
  942. /// \todo Bool constants possibly have no effect on Direct3D9
  943. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  944. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  945. return;
  946. BOOL data = value;
  947. if (i->second_.type_ == VS)
  948. impl_->device_->SetVertexShaderConstantB(i->second_.register_, &data, 1);
  949. else
  950. impl_->device_->SetPixelShaderConstantB(i->second_.register_, &data, 1);
  951. }
  952. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  953. {
  954. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  955. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  956. return;
  957. if (i->second_.type_ == VS)
  958. impl_->device_->SetVertexShaderConstantF(i->second_.register_, color.Data(), 1);
  959. else
  960. impl_->device_->SetPixelShaderConstantF(i->second_.register_, color.Data(), 1);
  961. }
  962. void Graphics::SetShaderParameter(StringHash param, const Vector2& vector)
  963. {
  964. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  965. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  966. return;
  967. float data[4];
  968. data[0] = vector.x_;
  969. data[1] = vector.y_;
  970. data[2] = 0.0f;
  971. data[3] = 0.0f;
  972. if (i->second_.type_ == VS)
  973. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data[0], 1);
  974. else
  975. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data[0], 1);
  976. }
  977. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  978. {
  979. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  980. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  981. return;
  982. float data[12];
  983. data[0] = matrix.m00_;
  984. data[1] = matrix.m01_;
  985. data[2] = matrix.m02_;
  986. data[3] = 0.0f;
  987. data[4] = matrix.m10_;
  988. data[5] = matrix.m11_;
  989. data[6] = matrix.m12_;
  990. data[7] = 0.0f;
  991. data[8] = matrix.m20_;
  992. data[9] = matrix.m21_;
  993. data[10] = matrix.m22_;
  994. data[11] = 0.0f;
  995. if (i->second_.type_ == VS)
  996. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data[0], 3);
  997. else
  998. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data[0], 3);
  999. }
  1000. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  1001. {
  1002. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  1003. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  1004. return;
  1005. float data[4];
  1006. data[0] = vector.x_;
  1007. data[1] = vector.y_;
  1008. data[2] = vector.z_;
  1009. data[3] = 0.0f;
  1010. if (i->second_.type_ == VS)
  1011. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data[0], 1);
  1012. else
  1013. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data[0], 1);
  1014. }
  1015. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  1016. {
  1017. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  1018. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  1019. return;
  1020. if (i->second_.type_ == VS)
  1021. impl_->device_->SetVertexShaderConstantF(i->second_.register_, matrix.Data(), 4);
  1022. else
  1023. impl_->device_->SetPixelShaderConstantF(i->second_.register_, matrix.Data(), 4);
  1024. }
  1025. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  1026. {
  1027. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  1028. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  1029. return;
  1030. if (i->second_.type_ == VS)
  1031. impl_->device_->SetVertexShaderConstantF(i->second_.register_, vector.Data(), 1);
  1032. else
  1033. impl_->device_->SetPixelShaderConstantF(i->second_.register_, vector.Data(), 1);
  1034. }
  1035. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  1036. {
  1037. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  1038. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  1039. return;
  1040. if (i->second_.type_ == VS)
  1041. impl_->device_->SetVertexShaderConstantF(i->second_.register_, matrix.Data(), 3);
  1042. else
  1043. impl_->device_->SetPixelShaderConstantF(i->second_.register_, matrix.Data(), 3);
  1044. }
  1045. void Graphics::SetShaderParameter(StringHash param, const Variant& value)
  1046. {
  1047. switch (value.GetType())
  1048. {
  1049. case VAR_BOOL:
  1050. SetShaderParameter(param, value.GetBool());
  1051. break;
  1052. case VAR_FLOAT:
  1053. SetShaderParameter(param, value.GetFloat());
  1054. break;
  1055. case VAR_VECTOR2:
  1056. SetShaderParameter(param, value.GetVector2());
  1057. break;
  1058. case VAR_VECTOR3:
  1059. SetShaderParameter(param, value.GetVector3());
  1060. break;
  1061. case VAR_VECTOR4:
  1062. SetShaderParameter(param, value.GetVector4());
  1063. break;
  1064. default:
  1065. // Unsupported parameter type, do nothing
  1066. break;
  1067. }
  1068. }
  1069. void Graphics::RegisterShaderParameter(StringHash param, const ShaderParameter& definition)
  1070. {
  1071. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  1072. if (i == shaderParameters_.End())
  1073. {
  1074. // Define new parameter
  1075. i = shaderParameters_.Insert(MakePair(param, definition));
  1076. i->second_.register_ = M_MAX_UNSIGNED;
  1077. // Rehash the parameters to ensure minimum load factor and fast queries
  1078. shaderParameters_.Rehash(NextPowerOfTwo(shaderParameters_.Size()));
  1079. }
  1080. else
  1081. {
  1082. // Existing parameter: check that there is no conflict
  1083. if (i->second_.type_ != definition.type_)
  1084. LOGWARNING("Shader type mismatch on shader parameter " + String(param));
  1085. // The same parameter is possibly defined with different sizes in different shaders. Use the highest size
  1086. if (i->second_.regCount_ < definition.regCount_)
  1087. i->second_.regCount_ = definition.regCount_;
  1088. }
  1089. }
  1090. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  1091. {
  1092. if ((unsigned)(size_t)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  1093. {
  1094. shaderParameterSources_[group] = source;
  1095. return true;
  1096. }
  1097. else
  1098. return false;
  1099. }
  1100. bool Graphics::HasShaderParameter(ShaderType type, StringHash param)
  1101. {
  1102. if (type == VS)
  1103. return vertexShader_ && vertexShader_->HasParameter(param);
  1104. else
  1105. return pixelShader_ && pixelShader_->HasParameter(param);
  1106. }
  1107. bool Graphics::HasTextureUnit(TextureUnit unit)
  1108. {
  1109. return pixelShader_ && pixelShader_->HasTextureUnit(unit);
  1110. }
  1111. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  1112. {
  1113. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  1114. }
  1115. void Graphics::ClearParameterSources()
  1116. {
  1117. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  1118. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  1119. }
  1120. void Graphics::ClearTransformSources()
  1121. {
  1122. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  1123. shaderParameterSources_[SP_OBJECTTRANSFORM] = (const void*)M_MAX_UNSIGNED;
  1124. }
  1125. void Graphics::SetTexture(unsigned index, Texture* texture)
  1126. {
  1127. if (index >= MAX_TEXTURE_UNITS)
  1128. return;
  1129. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  1130. if (texture)
  1131. {
  1132. if (texture == viewTexture_ || (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture))
  1133. texture = texture->GetBackupTexture();
  1134. }
  1135. if (texture != textures_[index])
  1136. {
  1137. if (texture)
  1138. impl_->device_->SetTexture(index, (IDirect3DBaseTexture9*)texture->GetGPUObject());
  1139. else
  1140. impl_->device_->SetTexture(index, 0);
  1141. textures_[index] = texture;
  1142. }
  1143. if (texture)
  1144. {
  1145. TextureFilterMode filterMode = texture->GetFilterMode();
  1146. if (filterMode == FILTER_DEFAULT)
  1147. filterMode = defaultTextureFilterMode_;
  1148. D3DTEXTUREFILTERTYPE minMag, mip;
  1149. minMag = d3dMinMagFilter[filterMode];
  1150. if (minMag != impl_->minMagFilters_[index])
  1151. {
  1152. impl_->device_->SetSamplerState(index, D3DSAMP_MAGFILTER, minMag);
  1153. impl_->device_->SetSamplerState(index, D3DSAMP_MINFILTER, minMag);
  1154. impl_->minMagFilters_[index] = minMag;
  1155. }
  1156. mip = d3dMipFilter[filterMode];
  1157. if (mip != impl_->mipFilters_[index])
  1158. {
  1159. impl_->device_->SetSamplerState(index, D3DSAMP_MIPFILTER, mip);
  1160. impl_->mipFilters_[index] = mip;
  1161. }
  1162. D3DTEXTUREADDRESS u, v;
  1163. u = d3dAddressMode[texture->GetAddressMode(COORD_U)];
  1164. if (u != impl_->uAddressModes_[index])
  1165. {
  1166. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSU, u);
  1167. impl_->uAddressModes_[index] = u;
  1168. }
  1169. v = d3dAddressMode[texture->GetAddressMode(COORD_V)];
  1170. if (v != impl_->vAddressModes_[index])
  1171. {
  1172. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSV, v);
  1173. impl_->vAddressModes_[index] = v;
  1174. }
  1175. if (texture->GetType() == TextureCube::GetTypeStatic())
  1176. {
  1177. D3DTEXTUREADDRESS w = d3dAddressMode[texture->GetAddressMode(COORD_W)];
  1178. if (w != impl_->wAddressModes_[index])
  1179. {
  1180. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSW, w);
  1181. impl_->wAddressModes_[index] = w;
  1182. }
  1183. }
  1184. if (u == D3DTADDRESS_BORDER || v == D3DTADDRESS_BORDER)
  1185. {
  1186. const Color& borderColor = texture->GetBorderColor();
  1187. if (borderColor != impl_->borderColors_[index])
  1188. {
  1189. impl_->device_->SetSamplerState(index, D3DSAMP_BORDERCOLOR, GetD3DColor(borderColor));
  1190. impl_->borderColors_[index] = borderColor;
  1191. }
  1192. }
  1193. if (sRGBSupport_)
  1194. {
  1195. bool sRGB = texture->GetSRGB();
  1196. if (sRGB != impl_->sRGBModes_[index])
  1197. {
  1198. impl_->device_->SetSamplerState(index, D3DSAMP_SRGBTEXTURE, sRGB ? TRUE : FALSE);
  1199. impl_->sRGBModes_[index] = sRGB;
  1200. }
  1201. }
  1202. }
  1203. }
  1204. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1205. {
  1206. defaultTextureFilterMode_ = mode;
  1207. }
  1208. void Graphics::ResetRenderTargets()
  1209. {
  1210. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1211. SetRenderTarget(i, (RenderSurface*)0);
  1212. SetDepthStencil((RenderSurface*)0);
  1213. SetViewport(IntRect(0, 0, width_, height_));
  1214. }
  1215. void Graphics::ResetRenderTarget(unsigned index)
  1216. {
  1217. SetRenderTarget(index, (RenderSurface*)0);
  1218. }
  1219. void Graphics::ResetDepthStencil()
  1220. {
  1221. SetDepthStencil((RenderSurface*)0);
  1222. }
  1223. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1224. {
  1225. if (index >= MAX_RENDERTARGETS)
  1226. return;
  1227. IDirect3DSurface9* newColorSurface = 0;
  1228. if (renderTarget)
  1229. {
  1230. if (renderTarget->GetUsage() != TEXTURE_RENDERTARGET)
  1231. return;
  1232. newColorSurface = (IDirect3DSurface9*)renderTarget->GetSurface();
  1233. }
  1234. else
  1235. {
  1236. if (!index)
  1237. newColorSurface = impl_->defaultColorSurface_;
  1238. }
  1239. renderTargets_[index] = renderTarget;
  1240. if (newColorSurface != impl_->colorSurfaces_[index])
  1241. {
  1242. impl_->device_->SetRenderTarget(index, newColorSurface);
  1243. impl_->colorSurfaces_[index] = newColorSurface;
  1244. // Setting the first rendertarget causes viewport to be reset
  1245. if (!index)
  1246. {
  1247. IntVector2 rtSize = GetRenderTargetDimensions();
  1248. viewport_ = IntRect(0, 0, rtSize.x_, rtSize.y_);
  1249. }
  1250. }
  1251. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1252. if (renderTarget)
  1253. {
  1254. Texture* parentTexture = renderTarget->GetParentTexture();
  1255. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1256. {
  1257. if (textures_[i] == parentTexture)
  1258. SetTexture(i, textures_[i]->GetBackupTexture());
  1259. }
  1260. }
  1261. // First rendertarget controls sRGB write mode
  1262. if (!index && sRGBWriteSupport_)
  1263. {
  1264. bool sRGBWrite = renderTarget ? renderTarget->GetParentTexture()->GetSRGB() : sRGB_;
  1265. if (sRGBWrite != impl_->sRGBWrite_)
  1266. {
  1267. impl_->device_->SetRenderState(D3DRS_SRGBWRITEENABLE, sRGBWrite ? TRUE : FALSE);
  1268. impl_->sRGBWrite_ = sRGBWrite;
  1269. }
  1270. }
  1271. }
  1272. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1273. {
  1274. RenderSurface* renderTarget = 0;
  1275. if (texture)
  1276. renderTarget = texture->GetRenderSurface();
  1277. SetRenderTarget(index, renderTarget);
  1278. }
  1279. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1280. {
  1281. IDirect3DSurface9* newDepthStencilSurface = 0;
  1282. if (depthStencil && depthStencil->GetUsage() == TEXTURE_DEPTHSTENCIL)
  1283. {
  1284. newDepthStencilSurface = (IDirect3DSurface9*)depthStencil->GetSurface();
  1285. depthStencil_ = depthStencil;
  1286. }
  1287. if (!newDepthStencilSurface)
  1288. {
  1289. newDepthStencilSurface = impl_->defaultDepthStencilSurface_;
  1290. depthStencil_ = 0;
  1291. }
  1292. if (newDepthStencilSurface != impl_->depthStencilSurface_)
  1293. {
  1294. impl_->device_->SetDepthStencilSurface(newDepthStencilSurface);
  1295. impl_->depthStencilSurface_ = newDepthStencilSurface;
  1296. }
  1297. }
  1298. void Graphics::SetDepthStencil(Texture2D* texture)
  1299. {
  1300. RenderSurface* depthStencil = 0;
  1301. if (texture)
  1302. depthStencil = texture->GetRenderSurface();
  1303. SetDepthStencil(depthStencil);
  1304. }
  1305. void Graphics::SetViewTexture(Texture* texture)
  1306. {
  1307. viewTexture_ = texture;
  1308. if (viewTexture_)
  1309. {
  1310. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1311. {
  1312. if (textures_[i] == viewTexture_)
  1313. SetTexture(i, textures_[i]->GetBackupTexture());
  1314. }
  1315. }
  1316. }
  1317. void Graphics::SetViewport(const IntRect& rect)
  1318. {
  1319. IntVector2 size = GetRenderTargetDimensions();
  1320. IntRect rectCopy = rect;
  1321. if (rectCopy.right_ <= rectCopy.left_)
  1322. rectCopy.right_ = rectCopy.left_ + 1;
  1323. if (rectCopy.bottom_ <= rectCopy.top_)
  1324. rectCopy.bottom_ = rectCopy.top_ + 1;
  1325. rectCopy.left_ = Clamp(rectCopy.left_, 0, size.x_);
  1326. rectCopy.top_ = Clamp(rectCopy.top_, 0, size.y_);
  1327. rectCopy.right_ = Clamp(rectCopy.right_, 0, size.x_);
  1328. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, size.y_);
  1329. D3DVIEWPORT9 vp;
  1330. vp.MinZ = 0.0f;
  1331. vp.MaxZ = 1.0f;
  1332. vp.X = rectCopy.left_;
  1333. vp.Y = rectCopy.top_;
  1334. vp.Width = rectCopy.Width();
  1335. vp.Height = rectCopy.Height();
  1336. impl_->device_->SetViewport(&vp);
  1337. viewport_ = rectCopy;
  1338. // Disable scissor test, needs to be re-enabled by the user
  1339. SetScissorTest(false);
  1340. }
  1341. void Graphics::SetTextureAnisotropy(unsigned level)
  1342. {
  1343. if (level < 1)
  1344. level = 1;
  1345. if (level != textureAnisotropy_)
  1346. {
  1347. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1348. impl_->device_->SetSamplerState(i, D3DSAMP_MAXANISOTROPY, level);
  1349. textureAnisotropy_ = level;
  1350. }
  1351. }
  1352. void Graphics::SetBlendMode(BlendMode mode)
  1353. {
  1354. if (mode != blendMode_)
  1355. {
  1356. if (d3dBlendEnable[mode] != impl_->blendEnable_)
  1357. {
  1358. impl_->device_->SetRenderState(D3DRS_ALPHABLENDENABLE, d3dBlendEnable[mode]);
  1359. impl_->blendEnable_ = d3dBlendEnable[mode];
  1360. }
  1361. if (impl_->blendEnable_)
  1362. {
  1363. if (d3dSrcBlend[mode] != impl_->srcBlend_)
  1364. {
  1365. impl_->device_->SetRenderState(D3DRS_SRCBLEND, d3dSrcBlend[mode]);
  1366. impl_->srcBlend_ = d3dSrcBlend[mode];
  1367. }
  1368. if (d3dDestBlend[mode] != impl_->destBlend_)
  1369. {
  1370. impl_->device_->SetRenderState(D3DRS_DESTBLEND, d3dDestBlend[mode]);
  1371. impl_->destBlend_ = d3dDestBlend[mode];
  1372. }
  1373. }
  1374. blendMode_ = mode;
  1375. }
  1376. }
  1377. void Graphics::SetColorWrite(bool enable)
  1378. {
  1379. if (enable != colorWrite_)
  1380. {
  1381. impl_->device_->SetRenderState(D3DRS_COLORWRITEENABLE, enable ? D3DCOLORWRITEENABLE_RED |
  1382. D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA : 0);
  1383. colorWrite_ = enable;
  1384. }
  1385. }
  1386. void Graphics::SetCullMode(CullMode mode)
  1387. {
  1388. if (mode != cullMode_)
  1389. {
  1390. impl_->device_->SetRenderState(D3DRS_CULLMODE, d3dCullMode[mode]);
  1391. cullMode_ = mode;
  1392. }
  1393. }
  1394. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1395. {
  1396. if (constantBias != constantDepthBias_)
  1397. {
  1398. impl_->device_->SetRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&constantBias));
  1399. constantDepthBias_ = constantBias;
  1400. }
  1401. if (slopeScaledBias != slopeScaledDepthBias_)
  1402. {
  1403. impl_->device_->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&slopeScaledBias));
  1404. slopeScaledDepthBias_ = slopeScaledBias;
  1405. }
  1406. }
  1407. void Graphics::SetDepthTest(CompareMode mode)
  1408. {
  1409. if (mode != depthTestMode_)
  1410. {
  1411. impl_->device_->SetRenderState(D3DRS_ZFUNC, d3dCmpFunc[mode]);
  1412. depthTestMode_ = mode;
  1413. }
  1414. }
  1415. void Graphics::SetDepthWrite(bool enable)
  1416. {
  1417. if (enable != depthWrite_)
  1418. {
  1419. impl_->device_->SetRenderState(D3DRS_ZWRITEENABLE, enable ? TRUE : FALSE);
  1420. depthWrite_ = enable;
  1421. }
  1422. }
  1423. void Graphics::SetFillMode(FillMode mode)
  1424. {
  1425. if (mode != fillMode_)
  1426. {
  1427. impl_->device_->SetRenderState(D3DRS_FILLMODE, d3dFillMode[mode]);
  1428. fillMode_ = mode;
  1429. }
  1430. }
  1431. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1432. {
  1433. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1434. // Disable scissor in that case to reduce state changes
  1435. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1436. enable = false;
  1437. if (enable)
  1438. {
  1439. IntVector2 rtSize(GetRenderTargetDimensions());
  1440. IntVector2 viewSize(viewport_.Size());
  1441. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1442. IntRect intRect;
  1443. int expand = borderInclusive ? 1 : 0;
  1444. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1445. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1446. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1447. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1448. if (intRect.right_ == intRect.left_)
  1449. intRect.right_++;
  1450. if (intRect.bottom_ == intRect.top_)
  1451. intRect.bottom_++;
  1452. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1453. enable = false;
  1454. if (enable && scissorRect_ != intRect)
  1455. {
  1456. RECT d3dRect;
  1457. d3dRect.left = intRect.left_;
  1458. d3dRect.top = intRect.top_;
  1459. d3dRect.right = intRect.right_;
  1460. d3dRect.bottom = intRect.bottom_;
  1461. impl_->device_->SetScissorRect(&d3dRect);
  1462. scissorRect_ = intRect;
  1463. }
  1464. }
  1465. else
  1466. scissorRect_ = IntRect::ZERO;
  1467. if (enable != scissorTest_)
  1468. {
  1469. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1470. scissorTest_ = enable;
  1471. }
  1472. }
  1473. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1474. {
  1475. IntVector2 rtSize(GetRenderTargetDimensions());
  1476. IntVector2 viewSize(viewport_.Size());
  1477. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1478. if (enable)
  1479. {
  1480. IntRect intRect;
  1481. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1482. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1483. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1484. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1485. if (intRect.right_ == intRect.left_)
  1486. intRect.right_++;
  1487. if (intRect.bottom_ == intRect.top_)
  1488. intRect.bottom_++;
  1489. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1490. enable = false;
  1491. if (enable && scissorRect_ != intRect)
  1492. {
  1493. RECT d3dRect;
  1494. d3dRect.left = intRect.left_;
  1495. d3dRect.top = intRect.top_;
  1496. d3dRect.right = intRect.right_;
  1497. d3dRect.bottom = intRect.bottom_;
  1498. impl_->device_->SetScissorRect(&d3dRect);
  1499. scissorRect_ = intRect;
  1500. }
  1501. }
  1502. else
  1503. scissorRect_ = IntRect::ZERO;
  1504. if (enable != scissorTest_)
  1505. {
  1506. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1507. scissorTest_ = enable;
  1508. }
  1509. }
  1510. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned compareMask, unsigned writeMask)
  1511. {
  1512. if (enable != stencilTest_)
  1513. {
  1514. impl_->device_->SetRenderState(D3DRS_STENCILENABLE, enable ? TRUE : FALSE);
  1515. stencilTest_ = enable;
  1516. }
  1517. if (enable)
  1518. {
  1519. if (mode != stencilTestMode_)
  1520. {
  1521. impl_->device_->SetRenderState(D3DRS_STENCILFUNC, d3dCmpFunc[mode]);
  1522. stencilTestMode_ = mode;
  1523. }
  1524. if (pass != stencilPass_)
  1525. {
  1526. impl_->device_->SetRenderState(D3DRS_STENCILPASS, d3dStencilOp[pass]);
  1527. stencilPass_ = pass;
  1528. }
  1529. if (fail != stencilFail_)
  1530. {
  1531. impl_->device_->SetRenderState(D3DRS_STENCILFAIL, d3dStencilOp[fail]);
  1532. stencilFail_ = fail;
  1533. }
  1534. if (zFail != stencilZFail_)
  1535. {
  1536. impl_->device_->SetRenderState(D3DRS_STENCILZFAIL, d3dStencilOp[zFail]);
  1537. stencilZFail_ = zFail;
  1538. }
  1539. if (stencilRef != stencilRef_)
  1540. {
  1541. impl_->device_->SetRenderState(D3DRS_STENCILREF, stencilRef);
  1542. stencilRef_ = stencilRef;
  1543. }
  1544. if (compareMask != stencilCompareMask_)
  1545. {
  1546. impl_->device_->SetRenderState(D3DRS_STENCILMASK, compareMask);
  1547. stencilCompareMask_ = compareMask;
  1548. }
  1549. if (writeMask != stencilWriteMask_)
  1550. {
  1551. impl_->device_->SetRenderState(D3DRS_STENCILWRITEMASK, writeMask);
  1552. stencilWriteMask_ = writeMask;
  1553. }
  1554. }
  1555. }
  1556. void Graphics::SetClipPlane(bool enable, const Plane& clipPlane, const Matrix3x4& view, const Matrix4& projection)
  1557. {
  1558. if (enable != useClipPlane_)
  1559. {
  1560. impl_->device_->SetRenderState(D3DRS_CLIPPLANEENABLE, enable ? 1 : 0);
  1561. useClipPlane_ = enable;
  1562. }
  1563. if (enable)
  1564. {
  1565. Matrix4 viewProj = projection * view;
  1566. impl_->device_->SetClipPlane(0, clipPlane.Transformed(viewProj).ToVector4().Data());
  1567. }
  1568. }
  1569. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1570. {
  1571. if (index < MAX_VERTEX_STREAMS && streamFrequencies_[index] != frequency)
  1572. {
  1573. impl_->device_->SetStreamSourceFreq(index, frequency);
  1574. streamFrequencies_[index] = frequency;
  1575. }
  1576. }
  1577. void Graphics::ResetStreamFrequencies()
  1578. {
  1579. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1580. {
  1581. if (streamFrequencies_[i] != 1)
  1582. {
  1583. impl_->device_->SetStreamSourceFreq(i, 1);
  1584. streamFrequencies_[i] = 1;
  1585. }
  1586. }
  1587. }
  1588. void Graphics::SetForceSM2(bool enable)
  1589. {
  1590. if (!IsInitialized())
  1591. forceSM2_ = enable;
  1592. else
  1593. LOGERROR("Force Shader Model 2 can not be changed after setting the initial screen mode");
  1594. }
  1595. bool Graphics::IsInitialized() const
  1596. {
  1597. return impl_->window_ != 0 && impl_->GetDevice() != 0;
  1598. }
  1599. IntVector2 Graphics::GetWindowPosition() const
  1600. {
  1601. IntVector2 ret(IntVector2::ZERO);
  1602. if (impl_->window_)
  1603. SDL_GetWindowPosition(impl_->window_, &ret.x_, &ret.y_);
  1604. return ret;
  1605. }
  1606. PODVector<IntVector2> Graphics::GetResolutions() const
  1607. {
  1608. PODVector<IntVector2> ret;
  1609. unsigned numModes = SDL_GetNumDisplayModes(0);
  1610. for (unsigned i = 0; i < numModes; ++i)
  1611. {
  1612. SDL_DisplayMode mode;
  1613. SDL_GetDisplayMode(0, i, &mode);
  1614. int width = mode.w;
  1615. int height = mode.h;
  1616. // Store mode if unique
  1617. bool unique = true;
  1618. for (unsigned j = 0; j < ret.Size(); ++j)
  1619. {
  1620. if (ret[j].x_ == width && ret[j].y_ == height)
  1621. {
  1622. unique = false;
  1623. break;
  1624. }
  1625. }
  1626. if (unique)
  1627. ret.Push(IntVector2(width, height));
  1628. }
  1629. return ret;
  1630. }
  1631. PODVector<int> Graphics::GetMultiSampleLevels() const
  1632. {
  1633. PODVector<int> ret;
  1634. // No multisampling always supported
  1635. ret.Push(1);
  1636. if (!impl_->interface_)
  1637. return ret;
  1638. SDL_DisplayMode mode;
  1639. SDL_GetDesktopDisplayMode(0, &mode);
  1640. D3DFORMAT fullscreenFormat = SDL_BITSPERPIXEL(mode.format) == 16 ? D3DFMT_R5G6B5 : D3DFMT_X8R8G8B8;
  1641. for (unsigned i = (int)D3DMULTISAMPLE_2_SAMPLES; i < (int)D3DMULTISAMPLE_16_SAMPLES; ++i)
  1642. {
  1643. if (SUCCEEDED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, fullscreenFormat, FALSE,
  1644. (D3DMULTISAMPLE_TYPE)i, NULL)))
  1645. ret.Push(i);
  1646. }
  1647. return ret;
  1648. }
  1649. IntVector2 Graphics::GetDesktopResolution() const
  1650. {
  1651. SDL_DisplayMode mode;
  1652. SDL_GetDesktopDisplayMode(0, &mode);
  1653. return IntVector2(mode.w, mode.h);
  1654. }
  1655. unsigned Graphics::GetFormat(CompressedFormat format) const
  1656. {
  1657. switch (format)
  1658. {
  1659. case CF_DXT1:
  1660. return D3DFMT_DXT1;
  1661. case CF_DXT3:
  1662. return D3DFMT_DXT3;
  1663. case CF_DXT5:
  1664. return D3DFMT_DXT5;
  1665. }
  1666. return 0;
  1667. }
  1668. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1669. {
  1670. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1671. }
  1672. TextureUnit Graphics::GetTextureUnit(const String& name)
  1673. {
  1674. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1675. if (i != textureUnits_.End())
  1676. return i->second_;
  1677. else
  1678. return MAX_TEXTURE_UNITS;
  1679. }
  1680. Texture* Graphics::GetTexture(unsigned index) const
  1681. {
  1682. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1683. }
  1684. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1685. {
  1686. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1687. }
  1688. unsigned Graphics::GetStreamFrequency(unsigned index) const
  1689. {
  1690. return index < MAX_VERTEX_STREAMS ? streamFrequencies_[index] : 0;
  1691. }
  1692. IntVector2 Graphics::GetRenderTargetDimensions() const
  1693. {
  1694. int width, height;
  1695. if (renderTargets_[0])
  1696. {
  1697. width = renderTargets_[0]->GetWidth();
  1698. height = renderTargets_[0]->GetHeight();
  1699. }
  1700. else
  1701. {
  1702. width = width_;
  1703. height = height_;
  1704. }
  1705. return IntVector2(width, height);
  1706. }
  1707. void Graphics::WindowResized()
  1708. {
  1709. if (!impl_->device_ || !impl_->window_)
  1710. return;
  1711. int newWidth, newHeight;
  1712. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  1713. if (newWidth == width_ && newHeight == height_)
  1714. return;
  1715. width_ = newWidth;
  1716. height_ = newHeight;
  1717. impl_->presentParams_.BackBufferWidth = width_;
  1718. impl_->presentParams_.BackBufferHeight = height_;
  1719. ResetDevice();
  1720. // Reset rendertargets and viewport for the new screen size
  1721. ResetRenderTargets();
  1722. 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::Maximize()
  1733. {
  1734. if (!impl_->window_)
  1735. return;
  1736. SDL_MaximizeWindow(impl_->window_);
  1737. }
  1738. void Graphics::Minimize()
  1739. {
  1740. if (!impl_->window_)
  1741. return;
  1742. SDL_MinimizeWindow(impl_->window_);
  1743. }
  1744. void Graphics::AddGPUObject(GPUObject* object)
  1745. {
  1746. gpuObjects_.Push(object);
  1747. }
  1748. void Graphics::RemoveGPUObject(GPUObject* object)
  1749. {
  1750. gpuObjects_.Remove(object);
  1751. }
  1752. void* Graphics::ReserveScratchBuffer(unsigned size)
  1753. {
  1754. if (!size)
  1755. return 0;
  1756. if (size > maxScratchBufferRequest_)
  1757. maxScratchBufferRequest_ = size;
  1758. // First check for a free buffer that is large enough
  1759. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1760. {
  1761. if (!i->reserved_ && i->size_ >= size)
  1762. {
  1763. i->reserved_ = true;
  1764. return i->data_.Get();
  1765. }
  1766. }
  1767. // Then check if a free buffer can be resized
  1768. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1769. {
  1770. if (!i->reserved_)
  1771. {
  1772. i->data_ = new unsigned char[size];
  1773. i->size_ = size;
  1774. i->reserved_ = true;
  1775. LOGDEBUG("Resized scratch buffer to size " + String(size));
  1776. return i->data_.Get();
  1777. }
  1778. }
  1779. // Finally allocate a new buffer
  1780. ScratchBuffer newBuffer;
  1781. newBuffer.data_ = new unsigned char[size];
  1782. newBuffer.size_ = size;
  1783. newBuffer.reserved_ = true;
  1784. scratchBuffers_.Push(newBuffer);
  1785. return newBuffer.data_.Get();
  1786. LOGDEBUG("Allocated scratch buffer with size " + String(size));
  1787. }
  1788. void Graphics::FreeScratchBuffer(void* buffer)
  1789. {
  1790. if (!buffer)
  1791. return;
  1792. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1793. {
  1794. if (i->reserved_ && i->data_.Get() == buffer)
  1795. {
  1796. i->reserved_ = false;
  1797. return;
  1798. }
  1799. }
  1800. LOGWARNING("Reserved scratch buffer " + ToStringHex((unsigned)(size_t)buffer) + " not found");
  1801. }
  1802. void Graphics::CleanupScratchBuffers()
  1803. {
  1804. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1805. {
  1806. if (!i->reserved_ && i->size_ > maxScratchBufferRequest_ * 2)
  1807. {
  1808. i->data_ = maxScratchBufferRequest_ > 0 ? new unsigned char[maxScratchBufferRequest_] : 0;
  1809. i->size_ = maxScratchBufferRequest_;
  1810. LOGDEBUG("Resized scratch buffer to size " + String(maxScratchBufferRequest_));
  1811. }
  1812. }
  1813. maxScratchBufferRequest_ = 0;
  1814. }
  1815. unsigned Graphics::GetAlphaFormat()
  1816. {
  1817. return D3DFMT_A8;
  1818. }
  1819. unsigned Graphics::GetLuminanceFormat()
  1820. {
  1821. return D3DFMT_L8;
  1822. }
  1823. unsigned Graphics::GetLuminanceAlphaFormat()
  1824. {
  1825. return D3DFMT_A8L8;
  1826. }
  1827. unsigned Graphics::GetRGBFormat()
  1828. {
  1829. return D3DFMT_X8R8G8B8;
  1830. }
  1831. unsigned Graphics::GetRGBAFormat()
  1832. {
  1833. return D3DFMT_A8R8G8B8;
  1834. }
  1835. unsigned Graphics::GetRGBA16Format()
  1836. {
  1837. return D3DFMT_A16B16G16R16;
  1838. }
  1839. unsigned Graphics::GetRGBAFloat16Format()
  1840. {
  1841. return D3DFMT_A16B16G16R16F;
  1842. }
  1843. unsigned Graphics::GetRGBAFloat32Format()
  1844. {
  1845. return D3DFMT_A32B32G32R32F;
  1846. }
  1847. unsigned Graphics::GetRG16Format()
  1848. {
  1849. return D3DFMT_G16R16;
  1850. }
  1851. unsigned Graphics::GetRGFloat16Format()
  1852. {
  1853. return D3DFMT_G16R16F;
  1854. }
  1855. unsigned Graphics::GetRGFloat32Format()
  1856. {
  1857. return D3DFMT_G32R32F;
  1858. }
  1859. unsigned Graphics::GetFloat16Format()
  1860. {
  1861. return D3DFMT_R16F;
  1862. }
  1863. unsigned Graphics::GetFloat32Format()
  1864. {
  1865. return D3DFMT_R32F;
  1866. }
  1867. unsigned Graphics::GetLinearDepthFormat()
  1868. {
  1869. return D3DFMT_R32F;
  1870. }
  1871. unsigned Graphics::GetDepthStencilFormat()
  1872. {
  1873. return depthStencilFormat;
  1874. }
  1875. unsigned Graphics::GetFormat(const String& formatName)
  1876. {
  1877. String nameLower = formatName.ToLower().Trimmed();
  1878. if (nameLower == "a")
  1879. return GetAlphaFormat();
  1880. if (nameLower == "l")
  1881. return GetLuminanceFormat();
  1882. if (nameLower == "la")
  1883. return GetLuminanceAlphaFormat();
  1884. if (nameLower == "rgb")
  1885. return GetRGBFormat();
  1886. if (nameLower == "rgba")
  1887. return GetRGBAFormat();
  1888. if (nameLower == "rgba16")
  1889. return GetRGBA16Format();
  1890. if (nameLower == "rgba16f")
  1891. return GetRGBAFloat16Format();
  1892. if (nameLower == "rgba32f")
  1893. return GetRGBAFloat32Format();
  1894. if (nameLower == "rg16")
  1895. return GetRG16Format();
  1896. if (nameLower == "rg16f")
  1897. return GetRGFloat16Format();
  1898. if (nameLower == "rg32f")
  1899. return GetRGFloat32Format();
  1900. if (nameLower == "r16f")
  1901. return GetFloat16Format();
  1902. if (nameLower == "r32f" || nameLower == "float")
  1903. return GetFloat32Format();
  1904. if (nameLower == "lineardepth" || nameLower == "depth")
  1905. return GetLinearDepthFormat();
  1906. if (nameLower == "d24s8")
  1907. return GetDepthStencilFormat();
  1908. return GetRGBFormat();
  1909. }
  1910. bool Graphics::OpenWindow(int width, int height, bool resizable, bool borderless)
  1911. {
  1912. if (!externalWindow_)
  1913. {
  1914. unsigned flags = 0;
  1915. if (resizable)
  1916. flags |= SDL_WINDOW_RESIZABLE;
  1917. if (borderless)
  1918. flags |= SDL_WINDOW_BORDERLESS;
  1919. impl_->window_ = SDL_CreateWindow(windowTitle_.CString(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags);
  1920. }
  1921. else
  1922. impl_->window_ = SDL_CreateWindowFrom(externalWindow_, 0);
  1923. if (!impl_->window_)
  1924. {
  1925. LOGERROR("Could not create window");
  1926. return false;
  1927. }
  1928. CreateWindowIcon();
  1929. return true;
  1930. }
  1931. void Graphics::CreateWindowIcon()
  1932. {
  1933. if (windowIcon_)
  1934. {
  1935. SDL_Surface* surface = windowIcon_->GetSDLSurface();
  1936. if (surface)
  1937. {
  1938. SDL_SetWindowIcon(impl_->window_, surface);
  1939. SDL_FreeSurface(surface);
  1940. }
  1941. }
  1942. }
  1943. void Graphics::AdjustWindow(int& newWidth, int& newHeight, bool& newFullscreen, bool& newBorderless)
  1944. {
  1945. if (!externalWindow_)
  1946. {
  1947. if (!newWidth || !newHeight)
  1948. {
  1949. SDL_MaximizeWindow(impl_->window_);
  1950. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  1951. }
  1952. else
  1953. SDL_SetWindowSize(impl_->window_, newWidth, newHeight);
  1954. SDL_SetWindowFullscreen(impl_->window_, newFullscreen ? SDL_TRUE : SDL_FALSE);
  1955. SDL_SetWindowBordered(impl_->window_, newBorderless ? SDL_FALSE : SDL_TRUE);
  1956. }
  1957. else
  1958. {
  1959. // If external window, must ask its dimensions instead of trying to set them
  1960. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  1961. newFullscreen = false;
  1962. }
  1963. }
  1964. bool Graphics::CreateInterface()
  1965. {
  1966. impl_->interface_ = Direct3DCreate9(D3D_SDK_VERSION);
  1967. if (!impl_->interface_)
  1968. {
  1969. LOGERROR("Could not create Direct3D9 interface");
  1970. return false;
  1971. }
  1972. if (FAILED(impl_->interface_->GetDeviceCaps(impl_->adapter_, impl_->deviceType_, &impl_->deviceCaps_)))
  1973. {
  1974. LOGERROR("Could not get Direct3D capabilities");
  1975. return false;
  1976. }
  1977. if (FAILED(impl_->interface_->GetAdapterIdentifier(impl_->adapter_, 0, &impl_->adapterIdentifier_)))
  1978. {
  1979. LOGERROR("Could not get Direct3D adapter identifier");
  1980. return false;
  1981. }
  1982. if (impl_->deviceCaps_.PixelShaderVersion < D3DPS_VERSION(2, 0))
  1983. {
  1984. LOGERROR("Shader model 2.0 display adapter is required");
  1985. return false;
  1986. }
  1987. return true;
  1988. }
  1989. bool Graphics::CreateDevice(unsigned adapter, unsigned deviceType)
  1990. {
  1991. #ifdef ENABLE_LUAJIT
  1992. DWORD behaviorFlags = D3DCREATE_FPU_PRESERVE;
  1993. #else
  1994. DWORD behaviorFlags = 0;
  1995. #endif
  1996. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
  1997. {
  1998. behaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
  1999. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_PUREDEVICE)
  2000. behaviorFlags |= D3DCREATE_PUREDEVICE;
  2001. }
  2002. else
  2003. behaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  2004. if (FAILED(impl_->interface_->CreateDevice(
  2005. adapter,
  2006. (D3DDEVTYPE)deviceType,
  2007. WIN_GetWindowHandle(impl_->window_),
  2008. behaviorFlags,
  2009. &impl_->presentParams_,
  2010. &impl_->device_)))
  2011. {
  2012. LOGERROR("Could not create Direct3D9 device");
  2013. return false;
  2014. }
  2015. impl_->adapter_ = adapter;
  2016. impl_->deviceType_ = (D3DDEVTYPE)deviceType;
  2017. OnDeviceReset();
  2018. LOGINFO("Created Direct3D9 device");
  2019. return true;
  2020. }
  2021. void Graphics::CheckFeatureSupport()
  2022. {
  2023. // Reset features first
  2024. lightPrepassSupport_ = false;
  2025. deferredSupport_ = false;
  2026. hardwareShadowSupport_ = false;
  2027. streamOffsetSupport_ = false;
  2028. hasSM3_ = false;
  2029. depthStencilFormat = D3DFMT_D24S8;
  2030. // Check hardware shadow map support: prefer NVIDIA style hardware depth compared shadow maps if available
  2031. shadowMapFormat_ = D3DFMT_D16;
  2032. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2033. {
  2034. hardwareShadowSupport_ = true;
  2035. // Check for hires depth support
  2036. hiresShadowMapFormat_ = D3DFMT_D24X8;
  2037. if (!impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2038. hiresShadowMapFormat_ = 0;
  2039. }
  2040. else
  2041. {
  2042. // ATI DF16 format needs manual depth compare in the shader
  2043. shadowMapFormat_ = MAKEFOURCC('D', 'F', '1', '6');
  2044. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2045. {
  2046. // Check for hires depth support
  2047. hiresShadowMapFormat_ = MAKEFOURCC('D', 'F', '2', '4');
  2048. if (!impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  2049. hiresShadowMapFormat_ = 0;
  2050. }
  2051. else
  2052. {
  2053. // No shadow map support
  2054. shadowMapFormat_ = 0;
  2055. hiresShadowMapFormat_ = 0;
  2056. }
  2057. }
  2058. // Check for Intel 4 Series with an old driver, enable manual shadow map compare in that case
  2059. if (shadowMapFormat_ == D3DFMT_D16)
  2060. {
  2061. if (impl_->adapterIdentifier_.VendorId == 0x8086 && impl_->adapterIdentifier_.DeviceId == 0x2a42 &&
  2062. impl_->adapterIdentifier_.DriverVersion.QuadPart <= 0x0007000f000a05d0ULL)
  2063. hardwareShadowSupport_ = false;
  2064. }
  2065. // Check for dummy color rendertarget format used with hardware shadow maps
  2066. dummyColorFormat_ = D3DFMT_A8R8G8B8;
  2067. D3DFORMAT nullFormat = (D3DFORMAT)MAKEFOURCC('N', 'U', 'L', 'L');
  2068. if (impl_->CheckFormatSupport(nullFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2069. dummyColorFormat_ = nullFormat;
  2070. else if (impl_->CheckFormatSupport(D3DFMT_R16F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2071. dummyColorFormat_ = D3DFMT_R16F;
  2072. else if (impl_->CheckFormatSupport(D3DFMT_R5G6B5, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2073. dummyColorFormat_ = D3DFMT_R5G6B5;
  2074. else if (impl_->CheckFormatSupport(D3DFMT_A4R4G4B4, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  2075. dummyColorFormat_ = D3DFMT_A4R4G4B4;
  2076. // Check for Shader Model 3
  2077. if (!forceSM2_)
  2078. {
  2079. if (impl_->deviceCaps_.VertexShaderVersion >= D3DVS_VERSION(3, 0) && impl_->deviceCaps_.PixelShaderVersion >=
  2080. D3DPS_VERSION(3, 0))
  2081. hasSM3_ = true;
  2082. }
  2083. // Check for light prepass and deferred rendering support
  2084. if (impl_->deviceCaps_.NumSimultaneousRTs >= 2 && impl_->CheckFormatSupport(D3DFMT_R32F, D3DUSAGE_RENDERTARGET,
  2085. D3DRTYPE_TEXTURE))
  2086. {
  2087. lightPrepassSupport_ = true;
  2088. if (impl_->deviceCaps_.NumSimultaneousRTs >= 4)
  2089. deferredSupport_ = true;
  2090. }
  2091. // Check for stream offset (needed for instancing)
  2092. if (impl_->deviceCaps_.DevCaps2 & D3DDEVCAPS2_STREAMOFFSET)
  2093. streamOffsetSupport_ = true;
  2094. // Check for sRGB read & write
  2095. /// \todo Should be checked for each texture format separately
  2096. sRGBSupport_ = impl_->CheckFormatSupport(D3DFMT_X8R8G8B8, D3DUSAGE_QUERY_SRGBREAD, D3DRTYPE_TEXTURE);
  2097. sRGBWriteSupport_ = impl_->CheckFormatSupport(D3DFMT_X8R8G8B8, D3DUSAGE_QUERY_SRGBWRITE, D3DRTYPE_TEXTURE);
  2098. SendEvent(E_GRAPHICSFEATURES);
  2099. }
  2100. void Graphics::ResetDevice()
  2101. {
  2102. OnDeviceLost();
  2103. if (SUCCEEDED(impl_->device_->Reset(&impl_->presentParams_)))
  2104. {
  2105. deviceLost_ = false;
  2106. OnDeviceReset();
  2107. }
  2108. }
  2109. void Graphics::OnDeviceLost()
  2110. {
  2111. LOGINFO("Device lost");
  2112. if (impl_->defaultColorSurface_)
  2113. {
  2114. impl_->defaultColorSurface_->Release();
  2115. impl_->defaultColorSurface_ = 0;
  2116. }
  2117. if (impl_->defaultDepthStencilSurface_)
  2118. {
  2119. impl_->defaultDepthStencilSurface_->Release();
  2120. impl_->defaultDepthStencilSurface_ = 0;
  2121. }
  2122. if (impl_->frameQuery_)
  2123. {
  2124. impl_->frameQuery_->Release();
  2125. impl_->frameQuery_ = 0;
  2126. }
  2127. for (unsigned i = 0; i < gpuObjects_.Size(); ++i)
  2128. gpuObjects_[i]->OnDeviceLost();
  2129. }
  2130. void Graphics::OnDeviceReset()
  2131. {
  2132. for (unsigned i = 0; i < gpuObjects_.Size(); ++i)
  2133. gpuObjects_[i]->OnDeviceReset();
  2134. // Get default surfaces
  2135. impl_->device_->GetRenderTarget(0, &impl_->defaultColorSurface_);
  2136. impl_->device_->GetDepthStencilSurface(&impl_->defaultDepthStencilSurface_);
  2137. // Create frame query for flushing the GPU command buffer
  2138. impl_->device_->CreateQuery(D3DQUERYTYPE_EVENT, &impl_->frameQuery_);
  2139. ResetCachedState();
  2140. }
  2141. void Graphics::ResetCachedState()
  2142. {
  2143. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2144. {
  2145. vertexBuffers_[i] = 0;
  2146. streamOffsets_[i] = 0;
  2147. }
  2148. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  2149. {
  2150. textures_[i] = 0;
  2151. impl_->minMagFilters_[i] = D3DTEXF_POINT;
  2152. impl_->mipFilters_[i] = D3DTEXF_NONE;
  2153. impl_->uAddressModes_[i] = D3DTADDRESS_WRAP;
  2154. impl_->vAddressModes_[i] = D3DTADDRESS_WRAP;
  2155. impl_->wAddressModes_[i] = D3DTADDRESS_WRAP;
  2156. impl_->borderColors_[i] = Color(0.0f, 0.0f, 0.0f, 0.0f);
  2157. impl_->sRGBModes_[i] = false;
  2158. }
  2159. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2160. {
  2161. renderTargets_[i] = 0;
  2162. impl_->colorSurfaces_[i] = 0;
  2163. }
  2164. depthStencil_ = 0;
  2165. impl_->depthStencilSurface_ = 0;
  2166. viewTexture_ = 0;
  2167. viewport_ = IntRect(0, 0, width_, height_);
  2168. impl_->sRGBWrite_ = false;
  2169. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2170. streamFrequencies_[i] = 1;
  2171. indexBuffer_ = 0;
  2172. vertexDeclaration_ = 0;
  2173. vertexShader_ = 0;
  2174. pixelShader_ = 0;
  2175. blendMode_ = BLEND_REPLACE;
  2176. textureAnisotropy_ = 1;
  2177. colorWrite_ = true;
  2178. cullMode_ = CULL_CCW;
  2179. constantDepthBias_ = 0.0f;
  2180. slopeScaledDepthBias_ = 0.0f;
  2181. depthTestMode_ = CMP_LESSEQUAL;
  2182. depthWrite_ = true;
  2183. fillMode_ = FILL_SOLID;
  2184. scissorTest_ = false;
  2185. scissorRect_ = IntRect::ZERO;
  2186. stencilTest_ = false;
  2187. stencilTestMode_ = CMP_ALWAYS;
  2188. stencilPass_ = OP_KEEP;
  2189. stencilFail_ = OP_KEEP;
  2190. stencilZFail_ = OP_KEEP;
  2191. stencilRef_ = 0;
  2192. stencilCompareMask_ = M_MAX_UNSIGNED;
  2193. stencilWriteMask_ = M_MAX_UNSIGNED;
  2194. useClipPlane_ = false;
  2195. impl_->blendEnable_ = FALSE;
  2196. impl_->srcBlend_ = D3DBLEND_ONE;
  2197. impl_->destBlend_ = D3DBLEND_ZERO;
  2198. queryIssued_ = false;
  2199. }
  2200. void Graphics::SetTextureUnitMappings()
  2201. {
  2202. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2203. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2204. textureUnits_["NormalMap"] = TU_NORMAL;
  2205. textureUnits_["SpecMap"] = TU_SPECULAR;
  2206. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2207. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  2208. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  2209. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2210. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  2211. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  2212. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2213. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  2214. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  2215. textureUnits_["VolumeMap"] = TU_VOLUMEMAP;
  2216. }
  2217. void RegisterGraphicsLibrary(Context* context)
  2218. {
  2219. Animation::RegisterObject(context);
  2220. Material::RegisterObject(context);
  2221. Model::RegisterObject(context);
  2222. Shader::RegisterObject(context);
  2223. Technique::RegisterObject(context);
  2224. Texture2D::RegisterObject(context);
  2225. Texture3D::RegisterObject(context);
  2226. TextureCube::RegisterObject(context);
  2227. Camera::RegisterObject(context);
  2228. Drawable::RegisterObject(context);
  2229. Light::RegisterObject(context);
  2230. StaticModel::RegisterObject(context);
  2231. StaticModelGroup::RegisterObject(context);
  2232. Skybox::RegisterObject(context);
  2233. AnimatedModel::RegisterObject(context);
  2234. AnimationController::RegisterObject(context);
  2235. BillboardSet::RegisterObject(context);
  2236. ParticleEmitter::RegisterObject(context);
  2237. CustomGeometry::RegisterObject(context);
  2238. DecalSet::RegisterObject(context);
  2239. Terrain::RegisterObject(context);
  2240. TerrainPatch::RegisterObject(context);
  2241. DebugRenderer::RegisterObject(context);
  2242. Octree::RegisterObject(context);
  2243. Zone::RegisterObject(context);
  2244. }
  2245. }