2
0

D3D9Graphics.cpp 70 KB

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