D3D9Graphics.cpp 80 KB

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