D3D9Graphics.cpp 69 KB

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