D3D9Graphics.cpp 81 KB

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