D3D9Graphics.cpp 81 KB

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