D3D9Graphics.cpp 86 KB

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