D3D9Graphics.cpp 79 KB

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