D3D9Graphics.cpp 70 KB

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