D3D9Graphics.cpp 83 KB

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