D3D9Graphics.cpp 80 KB

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