D3D9Graphics.cpp 81 KB

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