D3D9Graphics.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340
  1. //
  2. // Copyright (c) 2008-2013 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 "AnimatedModel.h"
  24. #include "Animation.h"
  25. #include "AnimationController.h"
  26. #include "Camera.h"
  27. #include "Context.h"
  28. #include "CustomGeometry.h"
  29. #include "DebugRenderer.h"
  30. #include "DecalSet.h"
  31. #include "Graphics.h"
  32. #include "GraphicsEvents.h"
  33. #include "GraphicsImpl.h"
  34. #include "IndexBuffer.h"
  35. #include "Log.h"
  36. #include "Material.h"
  37. #include "Octree.h"
  38. #include "ParticleEmitter.h"
  39. #include "ProcessUtils.h"
  40. #include "Profiler.h"
  41. #include "Shader.h"
  42. #include "ShaderVariation.h"
  43. #include "Skybox.h"
  44. #include "StringUtils.h"
  45. #include "Technique.h"
  46. #include "Terrain.h"
  47. #include "TerrainPatch.h"
  48. #include "Texture2D.h"
  49. #include "TextureCube.h"
  50. #include "VertexBuffer.h"
  51. #include "VertexDeclaration.h"
  52. #include "Zone.h"
  53. #include "DebugNew.h"
  54. #ifdef _MSC_VER
  55. #pragma warning(disable:4355)
  56. #endif
  57. namespace Urho3D
  58. {
  59. extern "C" HWND WIN_GetWindowHandle(SDL_Window* window);
  60. static const D3DCMPFUNC d3dCmpFunc[] =
  61. {
  62. D3DCMP_ALWAYS,
  63. D3DCMP_EQUAL,
  64. D3DCMP_NOTEQUAL,
  65. D3DCMP_LESS,
  66. D3DCMP_LESSEQUAL,
  67. D3DCMP_GREATER,
  68. D3DCMP_GREATEREQUAL
  69. };
  70. static const D3DTEXTUREFILTERTYPE d3dMinMagFilter[] =
  71. {
  72. D3DTEXF_POINT,
  73. D3DTEXF_LINEAR,
  74. D3DTEXF_LINEAR,
  75. D3DTEXF_ANISOTROPIC
  76. };
  77. static const D3DTEXTUREFILTERTYPE d3dMipFilter[] =
  78. {
  79. D3DTEXF_POINT,
  80. D3DTEXF_POINT,
  81. D3DTEXF_LINEAR,
  82. D3DTEXF_ANISOTROPIC
  83. };
  84. static const D3DTEXTUREADDRESS d3dAddressMode[] =
  85. {
  86. D3DTADDRESS_WRAP,
  87. D3DTADDRESS_MIRROR,
  88. D3DTADDRESS_CLAMP,
  89. D3DTADDRESS_BORDER
  90. };
  91. static const DWORD d3dBlendEnable[] =
  92. {
  93. FALSE,
  94. TRUE,
  95. TRUE,
  96. TRUE,
  97. TRUE,
  98. TRUE,
  99. TRUE
  100. };
  101. static const D3DBLEND d3dSrcBlend[] =
  102. {
  103. D3DBLEND_ONE,
  104. D3DBLEND_ONE,
  105. D3DBLEND_DESTCOLOR,
  106. D3DBLEND_SRCALPHA,
  107. D3DBLEND_SRCALPHA,
  108. D3DBLEND_ONE,
  109. D3DBLEND_INVDESTALPHA,
  110. };
  111. static const D3DBLEND d3dDestBlend[] =
  112. {
  113. D3DBLEND_ZERO,
  114. D3DBLEND_ONE,
  115. D3DBLEND_ZERO,
  116. D3DBLEND_INVSRCALPHA,
  117. D3DBLEND_ONE,
  118. D3DBLEND_INVSRCALPHA,
  119. D3DBLEND_DESTALPHA
  120. };
  121. static const D3DCULL d3dCullMode[] =
  122. {
  123. D3DCULL_NONE,
  124. D3DCULL_CCW,
  125. D3DCULL_CW
  126. };
  127. static const D3DFILLMODE d3dFillMode[] =
  128. {
  129. D3DFILL_SOLID,
  130. D3DFILL_WIREFRAME,
  131. D3DFILL_POINT
  132. };
  133. static const D3DSTENCILOP d3dStencilOp[] =
  134. {
  135. D3DSTENCILOP_KEEP,
  136. D3DSTENCILOP_ZERO,
  137. D3DSTENCILOP_REPLACE,
  138. D3DSTENCILOP_INCR,
  139. D3DSTENCILOP_DECR
  140. };
  141. static unsigned GetD3DColor(const Color& color)
  142. {
  143. unsigned r = (unsigned)(Clamp(color.r_ * 255.0f, 0.0f, 255.0f));
  144. unsigned g = (unsigned)(Clamp(color.g_ * 255.0f, 0.0f, 255.0f));
  145. unsigned b = (unsigned)(Clamp(color.b_ * 255.0f, 0.0f, 255.0f));
  146. unsigned a = (unsigned)(Clamp(color.a_ * 255.0f, 0.0f, 255.0f));
  147. return (((a) & 0xff) << 24) | (((r) & 0xff) << 16) | (((g) & 0xff) << 8) | ((b) & 0xff);
  148. }
  149. static unsigned numInstances = 0;
  150. static unsigned depthStencilFormat = D3DFMT_D24S8;
  151. OBJECTTYPESTATIC(Graphics);
  152. Graphics::Graphics(Context* context) :
  153. Object(context),
  154. impl_(new GraphicsImpl()),
  155. externalWindow_(0),
  156. width_(0),
  157. height_(0),
  158. multiSample_(1),
  159. windowPosX_(0),
  160. windowPosY_(0),
  161. fullscreen_(false),
  162. vsync_(false),
  163. tripleBuffer_(false),
  164. deviceLost_(false),
  165. lightPrepassSupport_(false),
  166. deferredSupport_(false),
  167. hardwareShadowSupport_(false),
  168. streamOffsetSupport_(false),
  169. hasSM3_(false),
  170. forceSM2_(false),
  171. numPrimitives_(0),
  172. numBatches_(0),
  173. maxScratchBufferRequest_(0),
  174. defaultTextureFilterMode_(FILTER_BILINEAR)
  175. {
  176. SetTextureUnitMappings();
  177. // If first instance in this process, initialize SDL under static mutex. Note that Graphics subsystem will also be in charge
  178. // of shutting down SDL as a whole, so it should be the last SDL-using subsystem (Audio and Input also use SDL) alive
  179. {
  180. MutexLock lock(GetStaticMutex());
  181. if (!numInstances)
  182. SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_NOPARACHUTE);
  183. ++numInstances;
  184. }
  185. }
  186. Graphics::~Graphics()
  187. {
  188. // Release all GPU objects that still exist
  189. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  190. (*i)->Release();
  191. gpuObjects_.Clear();
  192. vertexDeclarations_.Clear();
  193. if (impl_->defaultColorSurface_)
  194. {
  195. impl_->defaultColorSurface_->Release();
  196. impl_->defaultColorSurface_ = 0;
  197. }
  198. if (impl_->defaultDepthStencilSurface_)
  199. {
  200. impl_->defaultDepthStencilSurface_->Release();
  201. impl_->defaultDepthStencilSurface_ = 0;
  202. }
  203. if (impl_->device_)
  204. {
  205. impl_->device_->Release();
  206. impl_->device_ = 0;
  207. }
  208. if (impl_->interface_)
  209. {
  210. impl_->interface_->Release();
  211. impl_->interface_ = 0;
  212. }
  213. if (impl_->window_)
  214. {
  215. MutexLock lock(GetStaticMutex());
  216. SDL_ShowCursor(SDL_TRUE);
  217. SDL_DestroyWindow(impl_->window_);
  218. impl_->window_ = 0;
  219. }
  220. delete impl_;
  221. impl_ = 0;
  222. // If last instance in this process, shut down SDL under static mutex
  223. {
  224. MutexLock lock(GetStaticMutex());
  225. --numInstances;
  226. if (!numInstances)
  227. SDL_Quit();
  228. }
  229. }
  230. void Graphics::SetExternalWindow(void* window)
  231. {
  232. if (!impl_->window_)
  233. externalWindow_ = window;
  234. else
  235. LOGERROR("Window already opened, can not set external window");
  236. }
  237. void Graphics::SetWindowTitle(const String& windowTitle)
  238. {
  239. windowTitle_ = windowTitle;
  240. if (impl_->window_)
  241. SDL_SetWindowTitle(impl_->window_, windowTitle_.CString());
  242. }
  243. bool Graphics::SetMode(int width, int height, bool fullscreen, bool vsync, bool tripleBuffer, int multiSample)
  244. {
  245. PROFILE(SetScreenMode);
  246. // Find out the full screen mode display format (match desktop color depth)
  247. SDL_DisplayMode mode;
  248. SDL_GetDesktopDisplayMode(0, &mode);
  249. D3DFORMAT fullscreenFormat = SDL_BITSPERPIXEL(mode.format) == 16 ? D3DFMT_R5G6B5 : D3DFMT_X8R8G8B8;
  250. // If zero dimensions in windowed mode, set default. If zero in fullscreen, use desktop mode
  251. if (!width || !height)
  252. {
  253. if (!fullscreen)
  254. {
  255. width = 800;
  256. height = 600;
  257. }
  258. else
  259. {
  260. width = mode.w;
  261. height = mode.h;
  262. }
  263. }
  264. multiSample = Clamp(multiSample, 1, (int)D3DMULTISAMPLE_16_SAMPLES);
  265. // If nothing changes, do not reset the device
  266. if (width == width_ && height == height_ && fullscreen == fullscreen_ && vsync == vsync_ && tripleBuffer ==
  267. tripleBuffer_ && multiSample == multiSample_)
  268. return true;
  269. if (!impl_->window_)
  270. {
  271. if (!OpenWindow(width, height))
  272. return false;
  273. }
  274. if (!impl_->interface_)
  275. {
  276. if (!CreateInterface())
  277. return false;
  278. CheckFeatureSupport();
  279. }
  280. // Note: GetMultiSample() will not reflect the actual hardware multisample mode, but rather what the caller wanted.
  281. multiSample_ = multiSample;
  282. // Check fullscreen mode validity. If not valid, revert to windowed
  283. if (fullscreen)
  284. {
  285. PODVector<IntVector2> resolutions = GetResolutions();
  286. fullscreen = false;
  287. for (unsigned i = 0; i < resolutions.Size(); ++i)
  288. {
  289. if (width == resolutions[i].x_ && height == resolutions[i].y_)
  290. {
  291. fullscreen = true;
  292. break;
  293. }
  294. }
  295. }
  296. // Fall back to non-multisampled if unsupported multisampling mode
  297. if (multiSample > 1)
  298. {
  299. if (FAILED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, fullscreenFormat, FALSE,
  300. (D3DMULTISAMPLE_TYPE)multiSample, NULL)))
  301. multiSample = 1;
  302. }
  303. AdjustWindow(width, height, fullscreen);
  304. if (fullscreen)
  305. {
  306. impl_->presentParams_.BackBufferFormat = fullscreenFormat;
  307. impl_->presentParams_.Windowed = false;
  308. }
  309. else
  310. {
  311. impl_->presentParams_.BackBufferFormat = D3DFMT_UNKNOWN;
  312. impl_->presentParams_.Windowed = true;
  313. }
  314. impl_->presentParams_.BackBufferWidth = width;
  315. impl_->presentParams_.BackBufferHeight = height;
  316. impl_->presentParams_.BackBufferCount = tripleBuffer ? 2 : 1;
  317. impl_->presentParams_.MultiSampleType = multiSample > 1 ? (D3DMULTISAMPLE_TYPE)multiSample : D3DMULTISAMPLE_NONE;
  318. impl_->presentParams_.MultiSampleQuality = 0;
  319. impl_->presentParams_.SwapEffect = D3DSWAPEFFECT_DISCARD;
  320. impl_->presentParams_.hDeviceWindow = WIN_GetWindowHandle(impl_->window_);
  321. impl_->presentParams_.EnableAutoDepthStencil = TRUE;
  322. impl_->presentParams_.AutoDepthStencilFormat = D3DFMT_D24S8;
  323. impl_->presentParams_.Flags = 0;
  324. impl_->presentParams_.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
  325. if (vsync)
  326. impl_->presentParams_.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
  327. else
  328. impl_->presentParams_.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  329. width_ = width;
  330. height_ = height;
  331. fullscreen_ = fullscreen;
  332. vsync_ = vsync;
  333. tripleBuffer_ = tripleBuffer;
  334. if (!impl_->device_)
  335. {
  336. unsigned adapter = D3DADAPTER_DEFAULT;
  337. unsigned deviceType = D3DDEVTYPE_HAL;
  338. // Check for PerfHUD adapter
  339. for (unsigned i=0; i < impl_->interface_->GetAdapterCount(); ++i)
  340. {
  341. D3DADAPTER_IDENTIFIER9 identifier;
  342. impl_->interface_->GetAdapterIdentifier(i, 0, &identifier);
  343. if (strstr(identifier.Description, "PerfHUD") != 0)
  344. {
  345. adapter = i;
  346. deviceType = D3DDEVTYPE_REF;
  347. break;
  348. }
  349. }
  350. impl_->interface_->GetAdapterIdentifier(adapter, 0, &impl_->adapterIdentifier_);
  351. if (!CreateDevice(adapter, deviceType))
  352. return false;
  353. }
  354. else
  355. ResetDevice();
  356. // Clear the initial window contents to black
  357. impl_->device_->BeginScene();
  358. Clear(CLEAR_COLOR);
  359. impl_->device_->EndScene();
  360. impl_->device_->Present(0, 0, 0, 0);
  361. if (multiSample > 1)
  362. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed") +
  363. " multisample " + String(multiSample));
  364. else
  365. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed"));
  366. using namespace ScreenMode;
  367. VariantMap eventData;
  368. eventData[P_WIDTH] = width_;
  369. eventData[P_HEIGHT] = height_;
  370. eventData[P_FULLSCREEN] = fullscreen_;
  371. SendEvent(E_SCREENMODE, eventData);
  372. return true;
  373. }
  374. bool Graphics::SetMode(int width, int height)
  375. {
  376. return SetMode(width, height, fullscreen_, vsync_, tripleBuffer_, multiSample_);
  377. }
  378. bool Graphics::ToggleFullscreen()
  379. {
  380. return SetMode(width_, height_, !fullscreen_, vsync_, tripleBuffer_, multiSample_);
  381. }
  382. void Graphics::Close()
  383. {
  384. if (impl_->window_)
  385. {
  386. MutexLock lock(GetStaticMutex());
  387. SDL_ShowCursor(SDL_TRUE);
  388. SDL_DestroyWindow(impl_->window_);
  389. impl_->window_ = 0;
  390. }
  391. }
  392. bool Graphics::TakeScreenShot(Image& destImage)
  393. {
  394. PROFILE(TakeScreenShot);
  395. if (!impl_->device_)
  396. return false;
  397. D3DSURFACE_DESC surfaceDesc;
  398. impl_->defaultColorSurface_->GetDesc(&surfaceDesc);
  399. // If possible, get the backbuffer data, because it is a lot faster.
  400. // However, if we are multisampled, need to use the front buffer
  401. bool useBackBuffer = true;
  402. if (impl_->presentParams_.MultiSampleType)
  403. {
  404. useBackBuffer = false;
  405. surfaceDesc.Format = D3DFMT_A8R8G8B8;
  406. }
  407. IDirect3DSurface9* surface = 0;
  408. impl_->device_->CreateOffscreenPlainSurface(width_, height_, surfaceDesc.Format, D3DPOOL_SYSTEMMEM, &surface, 0);
  409. if (!surface)
  410. return false;
  411. if (useBackBuffer)
  412. impl_->device_->GetRenderTargetData(impl_->defaultColorSurface_, surface);
  413. else
  414. impl_->device_->GetFrontBufferData(0, surface);
  415. D3DLOCKED_RECT lockedRect;
  416. lockedRect.pBits = 0;
  417. surface->LockRect(&lockedRect, 0, D3DLOCK_NOSYSLOCK | D3DLOCK_READONLY);
  418. if (!lockedRect.pBits)
  419. {
  420. surface->Release();
  421. return false;
  422. }
  423. destImage.SetSize(width_, height_, 3);
  424. unsigned char* destData = destImage.GetData();
  425. if (surfaceDesc.Format == D3DFMT_R5G6B5)
  426. {
  427. for (int y = 0; y < height_; ++y)
  428. {
  429. unsigned short* src = (unsigned short*)((unsigned char*)lockedRect.pBits + y * lockedRect.Pitch);
  430. unsigned char* dest = destData + y * width_ * 3;
  431. for (int x = 0; x < width_; ++x)
  432. {
  433. unsigned short rgb = *src++;
  434. int b = rgb & 31;
  435. int g = (rgb >> 5) & 63;
  436. int r = (rgb >> 11);
  437. *dest++ = (int)(r * 255.0f / 31.0f);
  438. *dest++ = (int)(g * 255.0f / 63.0f);
  439. *dest++ = (int)(b * 255.0f / 31.0f);
  440. }
  441. }
  442. }
  443. else
  444. {
  445. for (int y = 0; y < height_; ++y)
  446. {
  447. unsigned char* src = (unsigned char*)lockedRect.pBits + y * lockedRect.Pitch;
  448. unsigned char* dest = destData + y * width_ * 3;
  449. for (int x = 0; x < width_; ++x)
  450. {
  451. *dest++ = src[2];
  452. *dest++ = src[1];
  453. *dest++ = src[0];
  454. src += 4;
  455. }
  456. }
  457. }
  458. surface->UnlockRect();
  459. surface->Release();
  460. return true;
  461. }
  462. bool Graphics::BeginFrame()
  463. {
  464. if (!IsInitialized())
  465. return false;
  466. // If using an external window, check it for size changes, and reset screen mode if necessary
  467. if (externalWindow_)
  468. {
  469. int width, height;
  470. SDL_GetWindowSize(impl_->window_, &width, &height);
  471. if (width != width_ || height != height_)
  472. SetMode(width, height);
  473. }
  474. // Check for lost device before rendering
  475. HRESULT hr = impl_->device_->TestCooperativeLevel();
  476. if (hr != D3D_OK)
  477. {
  478. PROFILE(DeviceLost);
  479. deviceLost_ = true;
  480. // The device can not be reset yet, sleep and try again eventually
  481. if (hr == D3DERR_DEVICELOST)
  482. {
  483. Sleep(20);
  484. return false;
  485. }
  486. // The device is lost, but ready to be reset. Reset device but do not render on this frame yet
  487. if (hr == D3DERR_DEVICENOTRESET)
  488. {
  489. ResetDevice();
  490. return false;
  491. }
  492. }
  493. impl_->device_->BeginScene();
  494. // Set default rendertarget and depth buffer
  495. ResetRenderTargets();
  496. // Cleanup textures from previous frame
  497. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  498. SetTexture(i, 0);
  499. // Cleanup stream frequencies from previous frame
  500. ResetStreamFrequencies();
  501. numPrimitives_ = 0;
  502. numBatches_ = 0;
  503. SendEvent(E_BEGINRENDERING);
  504. return true;
  505. }
  506. void Graphics::EndFrame()
  507. {
  508. if (!IsInitialized())
  509. return;
  510. PROFILE(Present);
  511. SendEvent(E_ENDRENDERING);
  512. impl_->device_->EndScene();
  513. impl_->device_->Present(0, 0, 0, 0);
  514. // Clean up too large scratch buffers
  515. CleanupScratchBuffers();
  516. }
  517. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  518. {
  519. DWORD d3dFlags = 0;
  520. if (flags & CLEAR_COLOR)
  521. d3dFlags |= D3DCLEAR_TARGET;
  522. if (flags & CLEAR_DEPTH)
  523. d3dFlags |= D3DCLEAR_ZBUFFER;
  524. if (flags & CLEAR_STENCIL)
  525. d3dFlags |= D3DCLEAR_STENCIL;
  526. impl_->device_->Clear(0, 0, d3dFlags, GetD3DColor(color), depth, stencil);
  527. }
  528. bool Graphics::ResolveToTexture(Texture2D* destination, const IntRect& viewport)
  529. {
  530. if (!destination || !destination->GetRenderSurface() || destination->GetWidth() != width_ ||
  531. destination->GetHeight() != height_)
  532. return false;
  533. PROFILE(ResolveToTexture);
  534. IntRect vpCopy = viewport;
  535. if (vpCopy.right_ <= vpCopy.left_)
  536. vpCopy.right_ = vpCopy.left_ + 1;
  537. if (vpCopy.bottom_ <= vpCopy.top_)
  538. vpCopy.bottom_ = vpCopy.top_ + 1;
  539. RECT rect;
  540. rect.left = Clamp(vpCopy.left_, 0, width_);
  541. rect.top = Clamp(vpCopy.top_, 0, height_);
  542. rect.right = Clamp(vpCopy.right_, 0, width_);
  543. rect.bottom = Clamp(vpCopy.bottom_, 0, height_);
  544. return SUCCEEDED(impl_->device_->StretchRect(impl_->defaultColorSurface_, &rect,
  545. (IDirect3DSurface9*)destination->GetRenderSurface()->GetSurface(), &rect, D3DTEXF_NONE));
  546. }
  547. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  548. {
  549. if (!vertexCount)
  550. return;
  551. ResetStreamFrequencies();
  552. unsigned primitiveCount = 0;
  553. switch (type)
  554. {
  555. case TRIANGLE_LIST:
  556. primitiveCount = vertexCount / 3;
  557. impl_->device_->DrawPrimitive(D3DPT_TRIANGLELIST, vertexStart, primitiveCount);
  558. break;
  559. case LINE_LIST:
  560. primitiveCount = vertexCount / 2;
  561. impl_->device_->DrawPrimitive(D3DPT_LINELIST, vertexStart, primitiveCount);
  562. break;
  563. }
  564. numPrimitives_ += primitiveCount;
  565. ++numBatches_;
  566. }
  567. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  568. {
  569. if (!indexCount)
  570. return;
  571. ResetStreamFrequencies();
  572. unsigned primitiveCount = 0;
  573. switch (type)
  574. {
  575. case TRIANGLE_LIST:
  576. primitiveCount = indexCount / 3;
  577. impl_->device_->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  578. break;
  579. case LINE_LIST:
  580. primitiveCount = indexCount / 2;
  581. impl_->device_->DrawIndexedPrimitive(D3DPT_LINELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  582. break;
  583. }
  584. numPrimitives_ += primitiveCount;
  585. ++numBatches_;
  586. }
  587. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount,
  588. unsigned instanceCount)
  589. {
  590. if (!indexCount || !instanceCount)
  591. return;
  592. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  593. {
  594. VertexBuffer* buffer = vertexBuffers_[i];
  595. if (buffer)
  596. {
  597. if (buffer->GetElementMask() & MASK_INSTANCEMATRIX1)
  598. SetStreamFrequency(i, D3DSTREAMSOURCE_INSTANCEDATA | 1);
  599. else
  600. SetStreamFrequency(i, D3DSTREAMSOURCE_INDEXEDDATA | instanceCount);
  601. }
  602. }
  603. unsigned primitiveCount = 0;
  604. switch (type)
  605. {
  606. case TRIANGLE_LIST:
  607. primitiveCount = indexCount / 3;
  608. impl_->device_->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  609. break;
  610. case LINE_LIST:
  611. primitiveCount = indexCount / 2;
  612. impl_->device_->DrawIndexedPrimitive(D3DPT_LINELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  613. break;
  614. }
  615. numPrimitives_ += instanceCount * primitiveCount;
  616. ++numBatches_;
  617. }
  618. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  619. {
  620. Vector<VertexBuffer*> vertexBuffers(1);
  621. PODVector<unsigned> elementMasks(1);
  622. vertexBuffers[0] = buffer;
  623. elementMasks[0] = MASK_DEFAULT;
  624. SetVertexBuffers(vertexBuffers, elementMasks);
  625. }
  626. bool Graphics::SetVertexBuffers(const Vector<VertexBuffer*>& buffers, const PODVector<unsigned>&
  627. elementMasks, unsigned instanceOffset)
  628. {
  629. if (buffers.Size() > MAX_VERTEX_STREAMS)
  630. {
  631. LOGERROR("Too many vertex buffers");
  632. return false;
  633. }
  634. if (buffers.Size() != elementMasks.Size())
  635. {
  636. LOGERROR("Amount of element masks and vertex buffers does not match");
  637. return false;
  638. }
  639. // Build vertex declaration hash code out of the buffers & masks
  640. unsigned long long hash = 0;
  641. for (unsigned i = 0; i < buffers.Size(); ++i)
  642. {
  643. if (!buffers[i])
  644. continue;
  645. hash |= buffers[i]->GetBufferHash(i, elementMasks[i]);
  646. }
  647. if (hash)
  648. {
  649. // If no previous vertex declaration for that hash, create new
  650. if (!vertexDeclarations_.Contains(hash))
  651. {
  652. SharedPtr<VertexDeclaration> newDeclaration(new VertexDeclaration(this, buffers, elementMasks));
  653. if (!newDeclaration->GetDeclaration())
  654. {
  655. LOGERROR("Failed to create vertex declaration");
  656. return false;
  657. }
  658. vertexDeclarations_[hash] = newDeclaration;
  659. }
  660. VertexDeclaration* declaration = vertexDeclarations_[hash];
  661. if (declaration != vertexDeclaration_)
  662. {
  663. impl_->device_->SetVertexDeclaration(declaration->GetDeclaration());
  664. vertexDeclaration_ = declaration;
  665. }
  666. }
  667. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  668. {
  669. VertexBuffer* buffer = 0;
  670. unsigned offset = 0;
  671. if (i < buffers.Size())
  672. {
  673. buffer = buffers[i];
  674. if (buffer && buffer->GetElementMask() & MASK_INSTANCEMATRIX1)
  675. offset = instanceOffset * buffer->GetVertexSize();
  676. }
  677. if (buffer != vertexBuffers_[i] || offset != streamOffsets_[i])
  678. {
  679. if (buffer)
  680. impl_->device_->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->GetGPUObject(), offset, buffer->GetVertexSize());
  681. else
  682. impl_->device_->SetStreamSource(i, 0, 0, 0);
  683. vertexBuffers_[i] = buffer;
  684. streamOffsets_[i] = offset;
  685. }
  686. }
  687. return true;
  688. }
  689. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>&
  690. elementMasks, unsigned instanceOffset)
  691. {
  692. if (buffers.Size() > MAX_VERTEX_STREAMS)
  693. {
  694. LOGERROR("Too many vertex buffers");
  695. return false;
  696. }
  697. if (buffers.Size() != elementMasks.Size())
  698. {
  699. LOGERROR("Amount of element masks and vertex buffers does not match");
  700. return false;
  701. }
  702. unsigned long long hash = 0;
  703. for (unsigned i = 0; i < buffers.Size(); ++i)
  704. {
  705. if (!buffers[i])
  706. continue;
  707. hash |= buffers[i]->GetBufferHash(i, elementMasks[i]);
  708. }
  709. if (hash)
  710. {
  711. if (!vertexDeclarations_.Contains(hash))
  712. {
  713. SharedPtr<VertexDeclaration> newDeclaration(new VertexDeclaration(this, buffers, elementMasks));
  714. if (!newDeclaration->GetDeclaration())
  715. {
  716. LOGERROR("Failed to create vertex declaration");
  717. return false;
  718. }
  719. vertexDeclarations_[hash] = newDeclaration;
  720. }
  721. VertexDeclaration* declaration = vertexDeclarations_[hash];
  722. if (declaration != vertexDeclaration_)
  723. {
  724. impl_->device_->SetVertexDeclaration(declaration->GetDeclaration());
  725. vertexDeclaration_ = declaration;
  726. }
  727. }
  728. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  729. {
  730. VertexBuffer* buffer = 0;
  731. unsigned offset = 0;
  732. if (i < buffers.Size())
  733. {
  734. buffer = buffers[i];
  735. if (buffer && buffer->GetElementMask() & MASK_INSTANCEMATRIX1)
  736. offset = instanceOffset * buffer->GetVertexSize();
  737. }
  738. if (buffer != vertexBuffers_[i] || offset != streamOffsets_[i])
  739. {
  740. if (buffer)
  741. impl_->device_->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->GetGPUObject(), offset, buffer->GetVertexSize());
  742. else
  743. impl_->device_->SetStreamSource(i, 0, 0, 0);
  744. vertexBuffers_[i] = buffer;
  745. streamOffsets_[i] = offset;
  746. }
  747. }
  748. return true;
  749. }
  750. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  751. {
  752. if (buffer != indexBuffer_)
  753. {
  754. if (buffer)
  755. impl_->device_->SetIndices((IDirect3DIndexBuffer9*)buffer->GetGPUObject());
  756. else
  757. impl_->device_->SetIndices(0);
  758. indexBuffer_ = buffer;
  759. }
  760. }
  761. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  762. {
  763. if (vs == vertexShader_ && ps == pixelShader_)
  764. return;
  765. ClearParameterSources();
  766. if (vs != vertexShader_)
  767. {
  768. // Clear all previous vertex shader register mappings
  769. for (HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Begin(); i != shaderParameters_.End(); ++i)
  770. {
  771. if (i->second_.type_ == VS)
  772. i->second_.register_ = M_MAX_UNSIGNED;
  773. }
  774. // Create the shader now if not yet created. If already attempted, do not retry
  775. if (vs && !vs->IsCreated())
  776. {
  777. if (!vs->IsFailed())
  778. {
  779. PROFILE(CreateVertexShader);
  780. bool success = vs->Create();
  781. if (success)
  782. LOGDEBUG("Created vertex shader " + vs->GetName());
  783. else
  784. {
  785. LOGERROR("Failed to create vertex shader " + vs->GetName());
  786. vs = 0;
  787. }
  788. }
  789. else
  790. vs = 0;
  791. }
  792. if (vs && vs->GetShaderType() == VS)
  793. {
  794. impl_->device_->SetVertexShader((IDirect3DVertexShader9*)vs->GetGPUObject());
  795. // Update the parameter-to-register mappings
  796. const HashMap<StringHash, ShaderParameter>& parameters = vs->GetParameters();
  797. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  798. shaderParameters_[i->first_].register_ = i->second_.register_;
  799. }
  800. else
  801. {
  802. impl_->device_->SetVertexShader(0);
  803. vs = 0;
  804. }
  805. vertexShader_ = vs;
  806. }
  807. if (ps != pixelShader_)
  808. {
  809. for (HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Begin(); i != shaderParameters_.End(); ++i)
  810. {
  811. if (i->second_.type_ == PS)
  812. i->second_.register_ = M_MAX_UNSIGNED;
  813. }
  814. if (ps && !ps->IsCreated())
  815. {
  816. if (!ps->IsFailed())
  817. {
  818. PROFILE(CreatePixelShader);
  819. bool success = ps->Create();
  820. if (success)
  821. LOGDEBUG("Created pixel shader " + ps->GetName());
  822. else
  823. {
  824. LOGERROR("Failed to create pixel shader " + ps->GetName());
  825. ps = 0;
  826. }
  827. }
  828. else
  829. ps = 0;
  830. }
  831. if (ps && ps->GetShaderType() == PS)
  832. {
  833. impl_->device_->SetPixelShader((IDirect3DPixelShader9*)ps->GetGPUObject());
  834. const HashMap<StringHash, ShaderParameter>& parameters = ps->GetParameters();
  835. for (HashMap<StringHash, ShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i)
  836. shaderParameters_[i->first_].register_ = i->second_.register_;
  837. }
  838. else
  839. {
  840. impl_->device_->SetPixelShader(0);
  841. ps = 0;
  842. }
  843. pixelShader_ = ps;
  844. }
  845. }
  846. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  847. {
  848. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  849. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  850. return;
  851. if (i->second_.type_ == VS)
  852. impl_->device_->SetVertexShaderConstantF(i->second_.register_, data, count / 4);
  853. else
  854. impl_->device_->SetPixelShaderConstantF(i->second_.register_, data, count / 4);
  855. }
  856. void Graphics::SetShaderParameter(StringHash param, float value)
  857. {
  858. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  859. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  860. return;
  861. float data[4];
  862. data[0] = value;
  863. data[1] = 0.0f;
  864. data[2] = 0.0f;
  865. data[3] = 0.0f;
  866. if (i->second_.type_ == VS)
  867. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data[0], 1);
  868. else
  869. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data[0], 1);
  870. }
  871. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  872. {
  873. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  874. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  875. return;
  876. if (i->second_.type_ == VS)
  877. impl_->device_->SetVertexShaderConstantF(i->second_.register_, color.Data(), 1);
  878. else
  879. impl_->device_->SetPixelShaderConstantF(i->second_.register_, color.Data(), 1);
  880. }
  881. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  882. {
  883. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  884. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  885. return;
  886. float data[12];
  887. data[0] = matrix.m00_;
  888. data[1] = matrix.m01_;
  889. data[2] = matrix.m02_;
  890. data[3] = 0.0f;
  891. data[4] = matrix.m10_;
  892. data[5] = matrix.m11_;
  893. data[6] = matrix.m12_;
  894. data[7] = 0.0f;
  895. data[8] = matrix.m20_;
  896. data[9] = matrix.m21_;
  897. data[10] = matrix.m22_;
  898. data[11] = 0.0f;
  899. if (i->second_.type_ == VS)
  900. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data[0], 3);
  901. else
  902. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data[0], 3);
  903. }
  904. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  905. {
  906. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  907. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  908. return;
  909. float data[4];
  910. data[0] = vector.x_;
  911. data[1] = vector.y_;
  912. data[2] = vector.z_;
  913. data[3] = 0.0f;
  914. if (i->second_.type_ == VS)
  915. impl_->device_->SetVertexShaderConstantF(i->second_.register_, &data[0], 1);
  916. else
  917. impl_->device_->SetPixelShaderConstantF(i->second_.register_, &data[0], 1);
  918. }
  919. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  920. {
  921. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  922. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  923. return;
  924. if (i->second_.type_ == VS)
  925. impl_->device_->SetVertexShaderConstantF(i->second_.register_, matrix.Data(), 4);
  926. else
  927. impl_->device_->SetPixelShaderConstantF(i->second_.register_, matrix.Data(), 4);
  928. }
  929. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  930. {
  931. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  932. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  933. return;
  934. if (i->second_.type_ == VS)
  935. impl_->device_->SetVertexShaderConstantF(i->second_.register_, vector.Data(), 1);
  936. else
  937. impl_->device_->SetPixelShaderConstantF(i->second_.register_, vector.Data(), 1);
  938. }
  939. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  940. {
  941. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  942. if (i == shaderParameters_.End() || i->second_.register_ >= MAX_CONSTANT_REGISTERS)
  943. return;
  944. if (i->second_.type_ == VS)
  945. impl_->device_->SetVertexShaderConstantF(i->second_.register_, matrix.Data(), 3);
  946. else
  947. impl_->device_->SetPixelShaderConstantF(i->second_.register_, matrix.Data(), 3);
  948. }
  949. void Graphics::RegisterShaderParameter(StringHash param, const ShaderParameter& definition)
  950. {
  951. HashMap<StringHash, ShaderParameter>::Iterator i = shaderParameters_.Find(param);
  952. if (i == shaderParameters_.End())
  953. {
  954. // Define new parameter
  955. i = shaderParameters_.Insert(MakePair(param, definition));
  956. i->second_.register_ = M_MAX_UNSIGNED;
  957. // Rehash the parameters to ensure minimum load factor and fast queries
  958. shaderParameters_.Rehash(NextPowerOfTwo(shaderParameters_.Size()));
  959. }
  960. else
  961. {
  962. // Existing parameter: check that there is no conflict
  963. if (i->second_.type_ != definition.type_)
  964. LOGWARNING("Shader type mismatch on shader parameter " + String(param));
  965. // The same parameter is possibly defined with different sizes in different shaders. Use the highest size
  966. if (i->second_.regCount_ < definition.regCount_)
  967. i->second_.regCount_ = definition.regCount_;
  968. }
  969. }
  970. bool Graphics::NeedParameterUpdate(ShaderParameterGroup group, const void* source)
  971. {
  972. if ((unsigned)shaderParameterSources_[group] == M_MAX_UNSIGNED || shaderParameterSources_[group] != source)
  973. {
  974. shaderParameterSources_[group] = source;
  975. return true;
  976. }
  977. else
  978. return false;
  979. }
  980. bool Graphics::HasShaderParameter(ShaderType type, StringHash param)
  981. {
  982. if (type == VS)
  983. return vertexShader_ && vertexShader_->HasParameter(param);
  984. else
  985. return pixelShader_ && pixelShader_->HasParameter(param);
  986. }
  987. bool Graphics::HasTextureUnit(TextureUnit unit)
  988. {
  989. return pixelShader_ && pixelShader_->HasTextureUnit(unit);
  990. }
  991. void Graphics::ClearParameterSource(ShaderParameterGroup group)
  992. {
  993. shaderParameterSources_[group] = (const void*)M_MAX_UNSIGNED;
  994. }
  995. void Graphics::ClearParameterSources()
  996. {
  997. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS; ++i)
  998. shaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  999. }
  1000. void Graphics::ClearTransformSources()
  1001. {
  1002. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  1003. shaderParameterSources_[SP_OBJECTTRANSFORM] = (const void*)M_MAX_UNSIGNED;
  1004. }
  1005. void Graphics::SetTexture(unsigned index, Texture* texture)
  1006. {
  1007. if (index >= MAX_TEXTURE_UNITS)
  1008. return;
  1009. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  1010. if (texture)
  1011. {
  1012. if (texture == viewTexture_ || (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture))
  1013. texture = texture->GetBackupTexture();
  1014. }
  1015. if (texture != textures_[index])
  1016. {
  1017. if (texture)
  1018. impl_->device_->SetTexture(index, (IDirect3DBaseTexture9*)texture->GetGPUObject());
  1019. else
  1020. impl_->device_->SetTexture(index, 0);
  1021. textures_[index] = texture;
  1022. }
  1023. if (texture)
  1024. {
  1025. TextureFilterMode filterMode = texture->GetFilterMode();
  1026. if (filterMode == FILTER_DEFAULT)
  1027. filterMode = defaultTextureFilterMode_;
  1028. D3DTEXTUREFILTERTYPE minMag, mip;
  1029. minMag = d3dMinMagFilter[filterMode];
  1030. if (minMag != impl_->minMagFilters_[index])
  1031. {
  1032. impl_->device_->SetSamplerState(index, D3DSAMP_MAGFILTER, minMag);
  1033. impl_->device_->SetSamplerState(index, D3DSAMP_MINFILTER, minMag);
  1034. impl_->minMagFilters_[index] = minMag;
  1035. }
  1036. mip = d3dMipFilter[filterMode];
  1037. if (mip != impl_->mipFilters_[index])
  1038. {
  1039. impl_->device_->SetSamplerState(index, D3DSAMP_MIPFILTER, mip);
  1040. impl_->mipFilters_[index] = mip;
  1041. }
  1042. D3DTEXTUREADDRESS u, v;
  1043. u = d3dAddressMode[texture->GetAddressMode(COORD_U)];
  1044. if (u != impl_->uAddressModes_[index])
  1045. {
  1046. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSU, u);
  1047. impl_->uAddressModes_[index] = u;
  1048. }
  1049. v = d3dAddressMode[texture->GetAddressMode(COORD_V)];
  1050. if (v != impl_->vAddressModes_[index])
  1051. {
  1052. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSV, v);
  1053. impl_->vAddressModes_[index] = v;
  1054. }
  1055. if (texture->GetType() == TextureCube::GetTypeStatic())
  1056. {
  1057. D3DTEXTUREADDRESS w = d3dAddressMode[texture->GetAddressMode(COORD_W)];
  1058. if (w != impl_->wAddressModes_[index])
  1059. {
  1060. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSW, w);
  1061. impl_->wAddressModes_[index] = w;
  1062. }
  1063. }
  1064. if (u == D3DTADDRESS_BORDER || v == D3DTADDRESS_BORDER)
  1065. {
  1066. const Color& borderColor = texture->GetBorderColor();
  1067. if (borderColor != impl_->borderColors_[index])
  1068. {
  1069. impl_->device_->SetSamplerState(index, D3DSAMP_BORDERCOLOR, GetD3DColor(borderColor));
  1070. impl_->borderColors_[index] = borderColor;
  1071. }
  1072. }
  1073. }
  1074. }
  1075. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1076. {
  1077. defaultTextureFilterMode_ = mode;
  1078. }
  1079. void Graphics::ResetRenderTargets()
  1080. {
  1081. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1082. SetRenderTarget(i, (RenderSurface*)0);
  1083. SetDepthStencil((RenderSurface*)0);
  1084. SetViewport(IntRect(0, 0, width_, height_));
  1085. }
  1086. void Graphics::ResetRenderTarget(unsigned index)
  1087. {
  1088. SetRenderTarget(index, (RenderSurface*)0);
  1089. }
  1090. void Graphics::ResetDepthStencil()
  1091. {
  1092. SetDepthStencil((RenderSurface*)0);
  1093. }
  1094. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1095. {
  1096. if (index >= MAX_RENDERTARGETS)
  1097. return;
  1098. IDirect3DSurface9* newColorSurface = 0;
  1099. if (renderTarget)
  1100. {
  1101. if (renderTarget->GetUsage() != TEXTURE_RENDERTARGET)
  1102. return;
  1103. newColorSurface = (IDirect3DSurface9*)renderTarget->GetSurface();
  1104. }
  1105. else
  1106. {
  1107. if (!index)
  1108. newColorSurface = impl_->defaultColorSurface_;
  1109. }
  1110. renderTargets_[index] = renderTarget;
  1111. if (newColorSurface != impl_->colorSurfaces_[index])
  1112. {
  1113. impl_->device_->SetRenderTarget(index, newColorSurface);
  1114. impl_->colorSurfaces_[index] = newColorSurface;
  1115. // Setting the first rendertarget causes viewport to be reset
  1116. if (!index)
  1117. {
  1118. IntVector2 rtSize = GetRenderTargetDimensions();
  1119. viewport_ = IntRect(0, 0, rtSize.x_, rtSize.y_);
  1120. }
  1121. }
  1122. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1123. if (renderTarget)
  1124. {
  1125. Texture* parentTexture = renderTarget->GetParentTexture();
  1126. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1127. {
  1128. if (textures_[i] == parentTexture)
  1129. SetTexture(i, textures_[i]->GetBackupTexture());
  1130. }
  1131. }
  1132. }
  1133. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1134. {
  1135. RenderSurface* renderTarget = 0;
  1136. if (texture)
  1137. renderTarget = texture->GetRenderSurface();
  1138. SetRenderTarget(index, renderTarget);
  1139. }
  1140. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1141. {
  1142. IDirect3DSurface9* newDepthStencilSurface = 0;
  1143. if (depthStencil && depthStencil->GetUsage() == TEXTURE_DEPTHSTENCIL)
  1144. {
  1145. newDepthStencilSurface = (IDirect3DSurface9*)depthStencil->GetSurface();
  1146. depthStencil_ = depthStencil;
  1147. }
  1148. if (!newDepthStencilSurface)
  1149. {
  1150. newDepthStencilSurface = impl_->defaultDepthStencilSurface_;
  1151. depthStencil_ = 0;
  1152. }
  1153. if (newDepthStencilSurface != impl_->depthStencilSurface_)
  1154. {
  1155. impl_->device_->SetDepthStencilSurface(newDepthStencilSurface);
  1156. impl_->depthStencilSurface_ = newDepthStencilSurface;
  1157. }
  1158. }
  1159. void Graphics::SetDepthStencil(Texture2D* texture)
  1160. {
  1161. RenderSurface* depthStencil = 0;
  1162. if (texture)
  1163. depthStencil = texture->GetRenderSurface();
  1164. SetDepthStencil(depthStencil);
  1165. }
  1166. void Graphics::SetViewTexture(Texture* texture)
  1167. {
  1168. viewTexture_ = texture;
  1169. if (viewTexture_)
  1170. {
  1171. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1172. {
  1173. if (textures_[i] == viewTexture_)
  1174. SetTexture(i, textures_[i]->GetBackupTexture());
  1175. }
  1176. }
  1177. }
  1178. void Graphics::SetViewport(const IntRect& rect)
  1179. {
  1180. IntVector2 size = GetRenderTargetDimensions();
  1181. IntRect rectCopy = rect;
  1182. if (rectCopy.right_ <= rectCopy.left_)
  1183. rectCopy.right_ = rectCopy.left_ + 1;
  1184. if (rectCopy.bottom_ <= rectCopy.top_)
  1185. rectCopy.bottom_ = rectCopy.top_ + 1;
  1186. rectCopy.left_ = Clamp(rectCopy.left_, 0, size.x_);
  1187. rectCopy.top_ = Clamp(rectCopy.top_, 0, size.y_);
  1188. rectCopy.right_ = Clamp(rectCopy.right_, 0, size.x_);
  1189. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, size.y_);
  1190. D3DVIEWPORT9 vp;
  1191. vp.MinZ = 0.0f;
  1192. vp.MaxZ = 1.0f;
  1193. vp.X = rectCopy.left_;
  1194. vp.Y = rectCopy.top_;
  1195. vp.Width = rectCopy.Width();
  1196. vp.Height = rectCopy.Height();
  1197. impl_->device_->SetViewport(&vp);
  1198. viewport_ = rectCopy;
  1199. // Disable scissor test, needs to be re-enabled by the user
  1200. SetScissorTest(false);
  1201. }
  1202. void Graphics::SetTextureAnisotropy(unsigned level)
  1203. {
  1204. if (level < 1)
  1205. level = 1;
  1206. if (level != textureAnisotropy_)
  1207. {
  1208. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1209. impl_->device_->SetSamplerState(i, D3DSAMP_MAXANISOTROPY, level);
  1210. textureAnisotropy_ = level;
  1211. }
  1212. }
  1213. void Graphics::SetBlendMode(BlendMode mode)
  1214. {
  1215. if (mode != blendMode_)
  1216. {
  1217. if (d3dBlendEnable[mode] != impl_->blendEnable_)
  1218. {
  1219. impl_->device_->SetRenderState(D3DRS_ALPHABLENDENABLE, d3dBlendEnable[mode]);
  1220. impl_->blendEnable_ = d3dBlendEnable[mode];
  1221. }
  1222. if (impl_->blendEnable_)
  1223. {
  1224. if (d3dSrcBlend[mode] != impl_->srcBlend_)
  1225. {
  1226. impl_->device_->SetRenderState(D3DRS_SRCBLEND, d3dSrcBlend[mode]);
  1227. impl_->srcBlend_ = d3dSrcBlend[mode];
  1228. }
  1229. if (d3dDestBlend[mode] != impl_->destBlend_)
  1230. {
  1231. impl_->device_->SetRenderState(D3DRS_DESTBLEND, d3dDestBlend[mode]);
  1232. impl_->destBlend_ = d3dDestBlend[mode];
  1233. }
  1234. }
  1235. blendMode_ = mode;
  1236. }
  1237. }
  1238. void Graphics::SetColorWrite(bool enable)
  1239. {
  1240. if (enable != colorWrite_)
  1241. {
  1242. impl_->device_->SetRenderState(D3DRS_COLORWRITEENABLE, enable ? D3DCOLORWRITEENABLE_RED |
  1243. D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA : 0);
  1244. colorWrite_ = enable;
  1245. }
  1246. }
  1247. void Graphics::SetCullMode(CullMode mode)
  1248. {
  1249. if (mode != cullMode_)
  1250. {
  1251. impl_->device_->SetRenderState(D3DRS_CULLMODE, d3dCullMode[mode]);
  1252. cullMode_ = mode;
  1253. }
  1254. }
  1255. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1256. {
  1257. if (constantBias != constantDepthBias_)
  1258. {
  1259. impl_->device_->SetRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&constantBias));
  1260. constantDepthBias_ = constantBias;
  1261. }
  1262. if (slopeScaledBias != slopeScaledDepthBias_)
  1263. {
  1264. impl_->device_->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&slopeScaledBias));
  1265. slopeScaledDepthBias_ = slopeScaledBias;
  1266. }
  1267. }
  1268. void Graphics::SetDepthTest(CompareMode mode)
  1269. {
  1270. if (mode != depthTestMode_)
  1271. {
  1272. impl_->device_->SetRenderState(D3DRS_ZFUNC, d3dCmpFunc[mode]);
  1273. depthTestMode_ = mode;
  1274. }
  1275. }
  1276. void Graphics::SetDepthWrite(bool enable)
  1277. {
  1278. if (enable != depthWrite_)
  1279. {
  1280. impl_->device_->SetRenderState(D3DRS_ZWRITEENABLE, enable ? TRUE : FALSE);
  1281. depthWrite_ = enable;
  1282. }
  1283. }
  1284. void Graphics::SetFillMode(FillMode mode)
  1285. {
  1286. if (mode != fillMode_)
  1287. {
  1288. impl_->device_->SetRenderState(D3DRS_FILLMODE, d3dFillMode[mode]);
  1289. fillMode_ = mode;
  1290. }
  1291. }
  1292. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1293. {
  1294. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1295. // Disable scissor in that case to reduce state changes
  1296. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1297. enable = false;
  1298. if (enable)
  1299. {
  1300. IntVector2 rtSize(GetRenderTargetDimensions());
  1301. IntVector2 viewSize(viewport_.Size());
  1302. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1303. IntRect intRect;
  1304. int expand = borderInclusive ? 1 : 0;
  1305. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1306. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1307. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1308. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1309. if (intRect.right_ == intRect.left_)
  1310. intRect.right_++;
  1311. if (intRect.bottom_ == intRect.top_)
  1312. intRect.bottom_++;
  1313. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1314. enable = false;
  1315. if (enable && scissorRect_ != intRect)
  1316. {
  1317. RECT d3dRect;
  1318. d3dRect.left = intRect.left_;
  1319. d3dRect.top = intRect.top_;
  1320. d3dRect.right = intRect.right_;
  1321. d3dRect.bottom = intRect.bottom_;
  1322. impl_->device_->SetScissorRect(&d3dRect);
  1323. scissorRect_ = intRect;
  1324. }
  1325. }
  1326. else
  1327. scissorRect_ = IntRect::ZERO;
  1328. if (enable != scissorTest_)
  1329. {
  1330. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1331. scissorTest_ = enable;
  1332. }
  1333. }
  1334. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1335. {
  1336. IntVector2 rtSize(GetRenderTargetDimensions());
  1337. IntVector2 viewSize(viewport_.Size());
  1338. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1339. if (enable)
  1340. {
  1341. IntRect intRect;
  1342. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1343. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1344. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1345. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1346. if (intRect.right_ == intRect.left_)
  1347. intRect.right_++;
  1348. if (intRect.bottom_ == intRect.top_)
  1349. intRect.bottom_++;
  1350. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1351. enable = false;
  1352. if (enable && scissorRect_ != intRect)
  1353. {
  1354. RECT d3dRect;
  1355. d3dRect.left = intRect.left_;
  1356. d3dRect.top = intRect.top_;
  1357. d3dRect.right = intRect.right_;
  1358. d3dRect.bottom = intRect.bottom_;
  1359. impl_->device_->SetScissorRect(&d3dRect);
  1360. scissorRect_ = intRect;
  1361. }
  1362. }
  1363. else
  1364. scissorRect_ = IntRect::ZERO;
  1365. if (enable != scissorTest_)
  1366. {
  1367. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1368. scissorTest_ = enable;
  1369. }
  1370. }
  1371. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned compareMask, unsigned writeMask)
  1372. {
  1373. if (enable != stencilTest_)
  1374. {
  1375. impl_->device_->SetRenderState(D3DRS_STENCILENABLE, enable ? TRUE : FALSE);
  1376. stencilTest_ = enable;
  1377. }
  1378. if (enable)
  1379. {
  1380. if (mode != stencilTestMode_)
  1381. {
  1382. impl_->device_->SetRenderState(D3DRS_STENCILFUNC, d3dCmpFunc[mode]);
  1383. stencilTestMode_ = mode;
  1384. }
  1385. if (pass != stencilPass_)
  1386. {
  1387. impl_->device_->SetRenderState(D3DRS_STENCILPASS, d3dStencilOp[pass]);
  1388. stencilPass_ = pass;
  1389. }
  1390. if (fail != stencilFail_)
  1391. {
  1392. impl_->device_->SetRenderState(D3DRS_STENCILFAIL, d3dStencilOp[fail]);
  1393. stencilFail_ = fail;
  1394. }
  1395. if (zFail != stencilZFail_)
  1396. {
  1397. impl_->device_->SetRenderState(D3DRS_STENCILZFAIL, d3dStencilOp[zFail]);
  1398. stencilZFail_ = zFail;
  1399. }
  1400. if (stencilRef != stencilRef_)
  1401. {
  1402. impl_->device_->SetRenderState(D3DRS_STENCILREF, stencilRef);
  1403. stencilRef_ = stencilRef;
  1404. }
  1405. if (compareMask != stencilCompareMask_)
  1406. {
  1407. impl_->device_->SetRenderState(D3DRS_STENCILMASK, compareMask);
  1408. stencilCompareMask_ = compareMask;
  1409. }
  1410. if (writeMask != stencilWriteMask_)
  1411. {
  1412. impl_->device_->SetRenderState(D3DRS_STENCILWRITEMASK, writeMask);
  1413. stencilWriteMask_ = writeMask;
  1414. }
  1415. }
  1416. }
  1417. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1418. {
  1419. if (index < MAX_VERTEX_STREAMS && streamFrequencies_[index] != frequency)
  1420. {
  1421. impl_->device_->SetStreamSourceFreq(index, frequency);
  1422. streamFrequencies_[index] = frequency;
  1423. }
  1424. }
  1425. void Graphics::ResetStreamFrequencies()
  1426. {
  1427. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1428. {
  1429. if (streamFrequencies_[i] != 1)
  1430. {
  1431. impl_->device_->SetStreamSourceFreq(i, 1);
  1432. streamFrequencies_[i] = 1;
  1433. }
  1434. }
  1435. }
  1436. void Graphics::SetForceSM2(bool enable)
  1437. {
  1438. if (!IsInitialized())
  1439. forceSM2_ = enable;
  1440. else
  1441. LOGERROR("Force Shader Model 2 can not be changed after setting the initial screen mode");
  1442. }
  1443. bool Graphics::IsInitialized() const
  1444. {
  1445. return impl_->window_ != 0 && impl_->GetDevice() != 0;
  1446. }
  1447. PODVector<IntVector2> Graphics::GetResolutions() const
  1448. {
  1449. PODVector<IntVector2> ret;
  1450. unsigned numModes = SDL_GetNumDisplayModes(0);
  1451. for (unsigned i = 0; i < numModes; ++i)
  1452. {
  1453. SDL_DisplayMode mode;
  1454. SDL_GetDisplayMode(0, i, &mode);
  1455. int width = mode.w;
  1456. int height = mode.h;
  1457. // Store mode if unique
  1458. bool unique = true;
  1459. for (unsigned j = 0; j < ret.Size(); ++j)
  1460. {
  1461. if (ret[j].x_ == width && ret[j].y_ == height)
  1462. {
  1463. unique = false;
  1464. break;
  1465. }
  1466. }
  1467. if (unique)
  1468. ret.Push(IntVector2(width, height));
  1469. }
  1470. return ret;
  1471. }
  1472. PODVector<int> Graphics::GetMultiSampleLevels() const
  1473. {
  1474. PODVector<int> ret;
  1475. // No multisampling always supported
  1476. ret.Push(1);
  1477. if (!impl_->interface_)
  1478. return ret;
  1479. SDL_DisplayMode mode;
  1480. SDL_GetDesktopDisplayMode(0, &mode);
  1481. D3DFORMAT fullscreenFormat = SDL_BITSPERPIXEL(mode.format) == 16 ? D3DFMT_R5G6B5 : D3DFMT_X8R8G8B8;
  1482. for (unsigned i = (int)D3DMULTISAMPLE_2_SAMPLES; i < (int)D3DMULTISAMPLE_16_SAMPLES; ++i)
  1483. {
  1484. if (SUCCEEDED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, fullscreenFormat, FALSE,
  1485. (D3DMULTISAMPLE_TYPE)i, NULL)))
  1486. ret.Push(i);
  1487. }
  1488. return ret;
  1489. }
  1490. unsigned Graphics::GetFormat(CompressedFormat format) const
  1491. {
  1492. switch (format)
  1493. {
  1494. case CF_DXT1:
  1495. return D3DFMT_DXT1;
  1496. case CF_DXT3:
  1497. return D3DFMT_DXT3;
  1498. case CF_DXT5:
  1499. return D3DFMT_DXT5;
  1500. }
  1501. return 0;
  1502. }
  1503. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1504. {
  1505. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1506. }
  1507. TextureUnit Graphics::GetTextureUnit(const String& name)
  1508. {
  1509. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1510. if (i != textureUnits_.End())
  1511. return i->second_;
  1512. else
  1513. return MAX_TEXTURE_UNITS;
  1514. }
  1515. Texture* Graphics::GetTexture(unsigned index) const
  1516. {
  1517. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1518. }
  1519. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1520. {
  1521. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1522. }
  1523. unsigned Graphics::GetStreamFrequency(unsigned index) const
  1524. {
  1525. return index < MAX_VERTEX_STREAMS ? streamFrequencies_[index] : 0;
  1526. }
  1527. IntVector2 Graphics::GetRenderTargetDimensions() const
  1528. {
  1529. int width, height;
  1530. if (renderTargets_[0])
  1531. {
  1532. width = renderTargets_[0]->GetWidth();
  1533. height = renderTargets_[0]->GetHeight();
  1534. }
  1535. else
  1536. {
  1537. width = width_;
  1538. height = height_;
  1539. }
  1540. return IntVector2(width, height);
  1541. }
  1542. void Graphics::AddGPUObject(GPUObject* object)
  1543. {
  1544. gpuObjects_.Push(object);
  1545. }
  1546. void Graphics::RemoveGPUObject(GPUObject* object)
  1547. {
  1548. gpuObjects_.Remove(object);
  1549. }
  1550. void* Graphics::ReserveScratchBuffer(unsigned size)
  1551. {
  1552. if (!size)
  1553. return 0;
  1554. if (size > maxScratchBufferRequest_)
  1555. maxScratchBufferRequest_ = size;
  1556. // First check for a free buffer that is large enough
  1557. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1558. {
  1559. if (!i->reserved_ && i->size_ >= size)
  1560. {
  1561. i->reserved_ = true;
  1562. return i->data_.Get();
  1563. }
  1564. }
  1565. // Then check if a free buffer can be resized
  1566. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1567. {
  1568. if (!i->reserved_)
  1569. {
  1570. i->data_ = new unsigned char[size];
  1571. i->size_ = size;
  1572. i->reserved_ = true;
  1573. LOGDEBUG("Resized scratch buffer to size " + String(size));
  1574. return i->data_.Get();
  1575. }
  1576. }
  1577. // Finally allocate a new buffer
  1578. ScratchBuffer newBuffer;
  1579. newBuffer.data_ = new unsigned char[size];
  1580. newBuffer.size_ = size;
  1581. newBuffer.reserved_ = true;
  1582. scratchBuffers_.Push(newBuffer);
  1583. return newBuffer.data_.Get();
  1584. LOGDEBUG("Allocated scratch buffer with size " + String(size));
  1585. }
  1586. void Graphics::FreeScratchBuffer(void* buffer)
  1587. {
  1588. if (!buffer)
  1589. return;
  1590. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1591. {
  1592. if (i->reserved_ && i->data_.Get() == buffer)
  1593. {
  1594. i->reserved_ = false;
  1595. return;
  1596. }
  1597. }
  1598. LOGWARNING("Reserved scratch buffer " + ToStringHex((unsigned)buffer) + " not found");
  1599. }
  1600. void Graphics::CleanupScratchBuffers()
  1601. {
  1602. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1603. {
  1604. if (!i->reserved_ && i->size_ > maxScratchBufferRequest_ * 2)
  1605. {
  1606. i->data_ = maxScratchBufferRequest_ > 0 ? new unsigned char[maxScratchBufferRequest_] : 0;
  1607. i->size_ = maxScratchBufferRequest_;
  1608. LOGDEBUG("Resized scratch buffer to size " + String(maxScratchBufferRequest_));
  1609. }
  1610. }
  1611. maxScratchBufferRequest_ = 0;
  1612. }
  1613. unsigned Graphics::GetAlphaFormat()
  1614. {
  1615. return D3DFMT_A8;
  1616. }
  1617. unsigned Graphics::GetLuminanceFormat()
  1618. {
  1619. return D3DFMT_L8;
  1620. }
  1621. unsigned Graphics::GetLuminanceAlphaFormat()
  1622. {
  1623. return D3DFMT_A8L8;
  1624. }
  1625. unsigned Graphics::GetRGBFormat()
  1626. {
  1627. return D3DFMT_X8R8G8B8;
  1628. }
  1629. unsigned Graphics::GetRGBAFormat()
  1630. {
  1631. return D3DFMT_A8R8G8B8;
  1632. }
  1633. unsigned Graphics::GetRGBA16Format()
  1634. {
  1635. return D3DFMT_A16B16G16R16;
  1636. }
  1637. unsigned Graphics::GetRGBAFloat16Format()
  1638. {
  1639. return D3DFMT_A16B16G16R16F;
  1640. }
  1641. unsigned Graphics::GetRGBAFloat32Format()
  1642. {
  1643. return D3DFMT_A32B32G32R32F;
  1644. }
  1645. unsigned Graphics::GetRG16Format()
  1646. {
  1647. return D3DFMT_G16R16;
  1648. }
  1649. unsigned Graphics::GetRGFloat16Format()
  1650. {
  1651. return D3DFMT_G16R16F;
  1652. }
  1653. unsigned Graphics::GetRGFloat32Format()
  1654. {
  1655. return D3DFMT_G32R32F;
  1656. }
  1657. unsigned Graphics::GetFloat16Format()
  1658. {
  1659. return D3DFMT_R16F;
  1660. }
  1661. unsigned Graphics::GetFloat32Format()
  1662. {
  1663. return D3DFMT_R32F;
  1664. }
  1665. unsigned Graphics::GetLinearDepthFormat()
  1666. {
  1667. return D3DFMT_R32F;
  1668. }
  1669. unsigned Graphics::GetDepthStencilFormat()
  1670. {
  1671. return depthStencilFormat;
  1672. }
  1673. unsigned Graphics::GetFormat(const String& formatName)
  1674. {
  1675. String nameLower = formatName.ToLower().Trimmed();
  1676. if (nameLower == "a")
  1677. return GetAlphaFormat();
  1678. if (nameLower == "l")
  1679. return GetLuminanceFormat();
  1680. if (nameLower == "la")
  1681. return GetLuminanceAlphaFormat();
  1682. if (nameLower == "rgb")
  1683. return GetRGBFormat();
  1684. if (nameLower == "rgba")
  1685. return GetRGBAFormat();
  1686. if (nameLower == "rgba16")
  1687. return GetRGBA16Format();
  1688. if (nameLower == "rgba16f")
  1689. return GetRGBAFloat16Format();
  1690. if (nameLower == "rgba32f")
  1691. return GetRGBAFloat32Format();
  1692. if (nameLower == "rg16")
  1693. return GetRG16Format();
  1694. if (nameLower == "rg16f")
  1695. return GetRGFloat16Format();
  1696. if (nameLower == "rg32f")
  1697. return GetRGFloat32Format();
  1698. if (nameLower == "r16f")
  1699. return GetFloat16Format();
  1700. if (nameLower == "r32f" || nameLower == "float")
  1701. return GetFloat32Format();
  1702. if (nameLower == "lineardepth" || nameLower == "depth")
  1703. return GetLinearDepthFormat();
  1704. if (nameLower == "d24s8")
  1705. return GetDepthStencilFormat();
  1706. return GetRGBFormat();
  1707. }
  1708. bool Graphics::OpenWindow(int width, int height)
  1709. {
  1710. if (!externalWindow_)
  1711. impl_->window_ = SDL_CreateWindow(windowTitle_.CString(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, 0);
  1712. else
  1713. impl_->window_ = SDL_CreateWindowFrom(externalWindow_, 0);
  1714. if (!impl_->window_)
  1715. {
  1716. LOGERROR("Could not create window");
  1717. return false;
  1718. }
  1719. return true;
  1720. }
  1721. void Graphics::AdjustWindow(int& newWidth, int& newHeight, bool& newFullscreen)
  1722. {
  1723. if (!externalWindow_)
  1724. {
  1725. SDL_SetWindowSize(impl_->window_, newWidth, newHeight);
  1726. SDL_SetWindowFullscreen(impl_->window_, newFullscreen ? SDL_TRUE : SDL_FALSE);
  1727. }
  1728. else
  1729. {
  1730. // If external window, must ask its dimensions instead of trying to set them
  1731. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  1732. newFullscreen = false;
  1733. }
  1734. }
  1735. bool Graphics::CreateInterface()
  1736. {
  1737. impl_->interface_ = Direct3DCreate9(D3D9b_SDK_VERSION);
  1738. if (!impl_->interface_)
  1739. {
  1740. LOGERROR("Could not create Direct3D9 interface");
  1741. return false;
  1742. }
  1743. if (FAILED(impl_->interface_->GetDeviceCaps(impl_->adapter_, impl_->deviceType_, &impl_->deviceCaps_)))
  1744. {
  1745. LOGERROR("Could not get Direct3D capabilities");
  1746. return false;
  1747. }
  1748. if (FAILED(impl_->interface_->GetAdapterIdentifier(impl_->adapter_, 0, &impl_->adapterIdentifier_)))
  1749. {
  1750. LOGERROR("Could not get Direct3D adapter identifier");
  1751. return false;
  1752. }
  1753. if (impl_->deviceCaps_.PixelShaderVersion < D3DPS_VERSION(2, 0))
  1754. {
  1755. LOGERROR("Shader model 2.0 display adapter is required");
  1756. return false;
  1757. }
  1758. return true;
  1759. }
  1760. bool Graphics::CreateDevice(unsigned adapter, unsigned deviceType)
  1761. {
  1762. DWORD behaviorFlags = 0;
  1763. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
  1764. {
  1765. behaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
  1766. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_PUREDEVICE)
  1767. behaviorFlags |= D3DCREATE_PUREDEVICE;
  1768. }
  1769. else
  1770. behaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  1771. if (FAILED(impl_->interface_->CreateDevice(
  1772. adapter,
  1773. (D3DDEVTYPE)deviceType,
  1774. WIN_GetWindowHandle(impl_->window_),
  1775. behaviorFlags,
  1776. &impl_->presentParams_,
  1777. &impl_->device_)))
  1778. {
  1779. LOGERROR("Could not create Direct3D9 device");
  1780. return false;
  1781. }
  1782. impl_->adapter_ = adapter;
  1783. impl_->deviceType_ = (D3DDEVTYPE)deviceType;
  1784. OnDeviceReset();
  1785. LOGINFO("Created Direct3D9 device");
  1786. return true;
  1787. }
  1788. void Graphics::CheckFeatureSupport()
  1789. {
  1790. // Reset features first
  1791. lightPrepassSupport_ = false;
  1792. deferredSupport_ = false;
  1793. hardwareShadowSupport_ = false;
  1794. streamOffsetSupport_ = false;
  1795. hasSM3_ = false;
  1796. depthStencilFormat = D3DFMT_D24S8;
  1797. // Check hardware shadow map support: prefer NVIDIA style hardware depth compared shadow maps if available
  1798. shadowMapFormat_ = D3DFMT_D16;
  1799. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1800. {
  1801. hardwareShadowSupport_ = true;
  1802. // Check for hires depth support
  1803. hiresShadowMapFormat_ = D3DFMT_D24X8;
  1804. if (!impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1805. hiresShadowMapFormat_ = 0;
  1806. }
  1807. else
  1808. {
  1809. // ATI DF16 format needs manual depth compare in the shader
  1810. shadowMapFormat_ = MAKEFOURCC('D', 'F', '1', '6');
  1811. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1812. {
  1813. // Check for hires depth support
  1814. hiresShadowMapFormat_ = MAKEFOURCC('D', 'F', '2', '4');
  1815. if (!impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1816. hiresShadowMapFormat_ = 0;
  1817. }
  1818. else
  1819. {
  1820. // No shadow map support
  1821. shadowMapFormat_ = 0;
  1822. hiresShadowMapFormat_ = 0;
  1823. }
  1824. }
  1825. // Check for Intel 4 Series with an old driver, enable manual shadow map compare in that case
  1826. if (shadowMapFormat_ == D3DFMT_D16)
  1827. {
  1828. if (impl_->adapterIdentifier_.VendorId == 0x8086 && impl_->adapterIdentifier_.DeviceId == 0x2a42 &&
  1829. impl_->adapterIdentifier_.DriverVersion.QuadPart <= 0x0007000f000a05d0ULL)
  1830. hardwareShadowSupport_ = false;
  1831. }
  1832. // Check for dummy color rendertarget format used with hardware shadow maps
  1833. dummyColorFormat_ = D3DFMT_A8R8G8B8;
  1834. D3DFORMAT nullFormat = (D3DFORMAT)MAKEFOURCC('N', 'U', 'L', 'L');
  1835. if (impl_->CheckFormatSupport(nullFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1836. dummyColorFormat_ = nullFormat;
  1837. else if (impl_->CheckFormatSupport(D3DFMT_R16F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1838. dummyColorFormat_ = D3DFMT_R16F;
  1839. else if (impl_->CheckFormatSupport(D3DFMT_R5G6B5, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1840. dummyColorFormat_ = D3DFMT_R5G6B5;
  1841. else if (impl_->CheckFormatSupport(D3DFMT_A4R4G4B4, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1842. dummyColorFormat_ = D3DFMT_A4R4G4B4;
  1843. // Check for Shader Model 3
  1844. if (!forceSM2_)
  1845. {
  1846. if (impl_->deviceCaps_.VertexShaderVersion >= D3DVS_VERSION(3, 0) && impl_->deviceCaps_.PixelShaderVersion >=
  1847. D3DPS_VERSION(3, 0))
  1848. hasSM3_ = true;
  1849. }
  1850. // Check for light prepass and deferred rendering support
  1851. if (impl_->deviceCaps_.NumSimultaneousRTs >= 2 && impl_->CheckFormatSupport(D3DFMT_R32F, D3DUSAGE_RENDERTARGET,
  1852. D3DRTYPE_TEXTURE))
  1853. {
  1854. lightPrepassSupport_ = true;
  1855. if (impl_->deviceCaps_.NumSimultaneousRTs >= 4)
  1856. deferredSupport_ = true;
  1857. }
  1858. // Check for stream offset (needed for instancing)
  1859. if (impl_->deviceCaps_.DevCaps2 & D3DDEVCAPS2_STREAMOFFSET)
  1860. streamOffsetSupport_ = true;
  1861. SendEvent(E_GRAPHICSFEATURES);
  1862. }
  1863. void Graphics::ResetDevice()
  1864. {
  1865. OnDeviceLost();
  1866. if (SUCCEEDED(impl_->device_->Reset(&impl_->presentParams_)))
  1867. {
  1868. deviceLost_ = false;
  1869. OnDeviceReset();
  1870. }
  1871. }
  1872. void Graphics::OnDeviceLost()
  1873. {
  1874. LOGINFO("Device lost");
  1875. if (impl_->defaultColorSurface_)
  1876. {
  1877. impl_->defaultColorSurface_->Release();
  1878. impl_->defaultColorSurface_ = 0;
  1879. }
  1880. if (impl_->defaultDepthStencilSurface_)
  1881. {
  1882. impl_->defaultDepthStencilSurface_->Release();
  1883. impl_->defaultDepthStencilSurface_ = 0;
  1884. }
  1885. for (unsigned i = 0; i < gpuObjects_.Size(); ++i)
  1886. gpuObjects_[i]->OnDeviceLost();
  1887. }
  1888. void Graphics::OnDeviceReset()
  1889. {
  1890. for (unsigned i = 0; i < gpuObjects_.Size(); ++i)
  1891. gpuObjects_[i]->OnDeviceReset();
  1892. // Get default surfaces
  1893. impl_->device_->GetRenderTarget(0, &impl_->defaultColorSurface_);
  1894. impl_->device_->GetDepthStencilSurface(&impl_->defaultDepthStencilSurface_);
  1895. ResetCachedState();
  1896. }
  1897. void Graphics::ResetCachedState()
  1898. {
  1899. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1900. {
  1901. vertexBuffers_[i] = 0;
  1902. streamOffsets_[i] = 0;
  1903. }
  1904. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1905. {
  1906. textures_[i] = 0;
  1907. impl_->minMagFilters_[i] = D3DTEXF_POINT;
  1908. impl_->mipFilters_[i] = D3DTEXF_NONE;
  1909. impl_->uAddressModes_[i] = D3DTADDRESS_WRAP;
  1910. impl_->vAddressModes_[i] = D3DTADDRESS_WRAP;
  1911. impl_->wAddressModes_[i] = D3DTADDRESS_WRAP;
  1912. impl_->borderColors_[i] = Color(0.0f, 0.0f, 0.0f, 0.0f);
  1913. }
  1914. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1915. {
  1916. renderTargets_[i] = 0;
  1917. impl_->colorSurfaces_[i] = 0;
  1918. }
  1919. depthStencil_ = 0;
  1920. impl_->depthStencilSurface_ = 0;
  1921. viewTexture_ = 0;
  1922. viewport_ = IntRect(0, 0, width_, height_);
  1923. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1924. streamFrequencies_[i] = 1;
  1925. indexBuffer_ = 0;
  1926. vertexDeclaration_ = 0;
  1927. vertexShader_ = 0;
  1928. pixelShader_ = 0;
  1929. blendMode_ = BLEND_REPLACE;
  1930. textureAnisotropy_ = 1;
  1931. colorWrite_ = true;
  1932. cullMode_ = CULL_CCW;
  1933. constantDepthBias_ = 0.0f;
  1934. slopeScaledDepthBias_ = 0.0f;
  1935. depthTestMode_ = CMP_LESSEQUAL;
  1936. depthWrite_ = true;
  1937. fillMode_ = FILL_SOLID;
  1938. scissorTest_ = false;
  1939. scissorRect_ = IntRect::ZERO;
  1940. stencilTest_ = false;
  1941. stencilTestMode_ = CMP_ALWAYS;
  1942. stencilPass_ = OP_KEEP;
  1943. stencilFail_ = OP_KEEP;
  1944. stencilZFail_ = OP_KEEP;
  1945. stencilRef_ = 0;
  1946. stencilCompareMask_ = M_MAX_UNSIGNED;
  1947. stencilWriteMask_ = M_MAX_UNSIGNED;
  1948. impl_->blendEnable_ = FALSE;
  1949. impl_->srcBlend_ = D3DBLEND_ONE;
  1950. impl_->destBlend_ = D3DBLEND_ZERO;
  1951. }
  1952. void Graphics::SetTextureUnitMappings()
  1953. {
  1954. textureUnits_["DiffMap"] = TU_DIFFUSE;
  1955. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  1956. textureUnits_["NormalMap"] = TU_NORMAL;
  1957. textureUnits_["SpecMap"] = TU_SPECULAR;
  1958. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  1959. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  1960. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  1961. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  1962. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  1963. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  1964. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  1965. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  1966. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  1967. }
  1968. void RegisterGraphicsLibrary(Context* context)
  1969. {
  1970. Animation::RegisterObject(context);
  1971. Material::RegisterObject(context);
  1972. Model::RegisterObject(context);
  1973. Shader::RegisterObject(context);
  1974. Technique::RegisterObject(context);
  1975. Texture2D::RegisterObject(context);
  1976. TextureCube::RegisterObject(context);
  1977. Camera::RegisterObject(context);
  1978. Drawable::RegisterObject(context);
  1979. Light::RegisterObject(context);
  1980. StaticModel::RegisterObject(context);
  1981. Skybox::RegisterObject(context);
  1982. AnimatedModel::RegisterObject(context);
  1983. AnimationController::RegisterObject(context);
  1984. BillboardSet::RegisterObject(context);
  1985. ParticleEmitter::RegisterObject(context);
  1986. CustomGeometry::RegisterObject(context);
  1987. DecalSet::RegisterObject(context);
  1988. Terrain::RegisterObject(context);
  1989. TerrainPatch::RegisterObject(context);
  1990. DebugRenderer::RegisterObject(context);
  1991. Octree::RegisterObject(context);
  1992. Zone::RegisterObject(context);
  1993. }
  1994. }