D3D9Graphics.cpp 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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 String noParameter;
  135. static const DWORD windowStyle = WS_OVERLAPPEDWINDOW & ~WS_THICKFRAME & ~WS_MAXIMIZEBOX;
  136. static LRESULT CALLBACK wndProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam);
  137. OBJECTTYPESTATIC(Graphics);
  138. Graphics::Graphics(Context* context) :
  139. Object(context),
  140. impl_(new GraphicsImpl()),
  141. mode_(RENDER_FORWARD),
  142. width_(0),
  143. height_(0),
  144. multiSample_(0),
  145. windowPosX_(0),
  146. windowPosY_(0),
  147. fullscreen_(false),
  148. vsync_(false),
  149. flushGPU_(true),
  150. deviceLost_(false),
  151. queryIssued_(false),
  152. deferredSupport_(false),
  153. prepassSupport_(false),
  154. hardwareShadowSupport_(false),
  155. hiresShadowSupport_(false),
  156. streamOffsetSupport_(false),
  157. hasSM3_(false),
  158. forceSM2_(false),
  159. numPrimitives_(0),
  160. numBatches_(0),
  161. immediateBuffer_(0),
  162. defaultTextureFilterMode_(FILTER_BILINEAR)
  163. {
  164. ResetCachedState();
  165. InitializeShaderParameters();
  166. SubscribeToEvent(E_WINDOWMESSAGE, HANDLER(Graphics, HandleWindowMessage));
  167. }
  168. Graphics::~Graphics()
  169. {
  170. // Release all GPU objects that still exist
  171. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  172. (*i)->Release();
  173. gpuObjects_.Clear();
  174. vertexDeclarations_.Clear();
  175. if (impl_->frameQuery_)
  176. {
  177. impl_->frameQuery_->Release();
  178. impl_->frameQuery_ = 0;
  179. }
  180. if (impl_->defaultColorSurface_)
  181. {
  182. impl_->defaultColorSurface_->Release();
  183. impl_->defaultColorSurface_ = 0;
  184. }
  185. if (impl_->defaultDepthStencilSurface_)
  186. {
  187. impl_->defaultDepthStencilSurface_->Release();
  188. impl_->defaultDepthStencilSurface_ = 0;
  189. }
  190. if (impl_->device_)
  191. {
  192. impl_->device_->Release();
  193. impl_->device_ = 0;
  194. }
  195. if (impl_->interface_)
  196. {
  197. impl_->interface_->Release();
  198. impl_->interface_ = 0;
  199. }
  200. if (impl_->window_)
  201. {
  202. DestroyWindow(impl_->window_);
  203. impl_->window_ = 0;
  204. }
  205. delete impl_;
  206. impl_ = 0;
  207. }
  208. void Graphics::MessagePump()
  209. {
  210. MSG msg;
  211. while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
  212. {
  213. TranslateMessage(&msg);
  214. DispatchMessage(&msg);
  215. }
  216. }
  217. void Graphics::SetWindowTitle(const String& windowTitle)
  218. {
  219. windowTitle_ = windowTitle;
  220. if (impl_->window_)
  221. SetWindowText(impl_->window_, windowTitle_.CString());
  222. }
  223. bool Graphics::SetMode(RenderMode mode, int width, int height, bool fullscreen, bool vsync, int multiSample)
  224. {
  225. PROFILE(SetScreenMode);
  226. // Find out the full screen mode display format (match desktop color depth)
  227. D3DFORMAT fullscreenFormat = impl_->GetDesktopFormat();
  228. // If zero dimensions, use the desktop default
  229. if ((width <= 0) || (height <= 0))
  230. {
  231. if (fullscreen)
  232. {
  233. IntVector2 desktopResolution = impl_->GetDesktopResolution();
  234. width = desktopResolution.x_;
  235. height = desktopResolution.y_;
  236. }
  237. else
  238. {
  239. width = 800;
  240. height = 600;
  241. }
  242. }
  243. if ((mode == mode_) && (width == width_) && (height == height_) && (fullscreen == fullscreen_) && (vsync == vsync_)
  244. && (multiSample == multiSample_))
  245. return true;
  246. if (!impl_->window_)
  247. {
  248. if (!OpenWindow(width, height))
  249. return false;
  250. }
  251. if (!impl_->interface_)
  252. {
  253. if (!CreateInterface())
  254. return false;
  255. }
  256. // Disable deferred / light prepass rendering if not supported
  257. // Note: we do not fall back from deferred to light prepass, because there might not be shaders / materials
  258. // defined for it. Instead fall back directly to forward rendering
  259. if ((mode == RENDER_DEFERRED) && (!deferredSupport_))
  260. mode = RENDER_FORWARD;
  261. if ((mode == RENDER_PREPASS) && (!prepassSupport_))
  262. mode = RENDER_FORWARD;
  263. if (multiSample >= (int)D3DMULTISAMPLE_2_SAMPLES)
  264. multiSample = Clamp(multiSample, (int)D3DMULTISAMPLE_NONE, (int)D3DMULTISAMPLE_16_SAMPLES);
  265. else
  266. multiSample = 0;
  267. // Note: GetMultiSample() will not reflect the actual hardware multisample mode, but rather what the caller wanted.
  268. // In deferred or light prepass mode, it is used to control the edge filter
  269. multiSample_ = multiSample;
  270. if (mode != RENDER_FORWARD)
  271. multiSample = 0;
  272. // Check fullscreen mode validity. If not valid, revert to windowed
  273. if (fullscreen)
  274. {
  275. PODVector<IntVector2> resolutions = GetResolutions();
  276. fullscreen = false;
  277. for (unsigned i = 0; i < resolutions.Size(); ++i)
  278. {
  279. if ((width == resolutions[i].x_) && (height == resolutions[i].y_))
  280. {
  281. fullscreen = true;
  282. break;
  283. }
  284. }
  285. }
  286. // Fall back to non-multisampled if unsupported multisampling mode
  287. if (multiSample)
  288. {
  289. if (FAILED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, fullscreenFormat, FALSE,
  290. (D3DMULTISAMPLE_TYPE)multiSample, NULL)))
  291. multiSample = 0;
  292. }
  293. // Save window placement if currently windowed
  294. if (!fullscreen_)
  295. {
  296. WINDOWPLACEMENT wndpl;
  297. wndpl.length = sizeof wndpl;
  298. if (SUCCEEDED(GetWindowPlacement(impl_->window_, &wndpl)))
  299. {
  300. windowPosX_ = wndpl.rcNormalPosition.left;
  301. windowPosY_ = wndpl.rcNormalPosition.top;
  302. }
  303. }
  304. if (fullscreen)
  305. {
  306. impl_->presentParams_.BackBufferFormat = fullscreenFormat;
  307. impl_->presentParams_.Windowed = false;
  308. }
  309. else
  310. {
  311. impl_->presentParams_.BackBufferFormat = D3DFMT_UNKNOWN;
  312. impl_->presentParams_.Windowed = true;
  313. }
  314. impl_->presentParams_.BackBufferWidth = width;
  315. impl_->presentParams_.BackBufferHeight = height;
  316. impl_->presentParams_.BackBufferCount = 1;
  317. impl_->presentParams_.MultiSampleType = (D3DMULTISAMPLE_TYPE)multiSample;
  318. impl_->presentParams_.MultiSampleQuality = 0;
  319. impl_->presentParams_.SwapEffect = D3DSWAPEFFECT_DISCARD;
  320. impl_->presentParams_.hDeviceWindow = impl_->window_;
  321. impl_->presentParams_.EnableAutoDepthStencil = true;
  322. impl_->presentParams_.AutoDepthStencilFormat = D3DFMT_D24S8;
  323. impl_->presentParams_.Flags = 0;
  324. impl_->presentParams_.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
  325. if (vsync)
  326. impl_->presentParams_.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
  327. else
  328. impl_->presentParams_.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
  329. width_ = width;
  330. height_ = height;
  331. fullscreen_ = fullscreen;
  332. vsync_ = vsync;
  333. mode_ = mode;
  334. if (!impl_->device_)
  335. {
  336. unsigned adapter = D3DADAPTER_DEFAULT;
  337. unsigned deviceType = D3DDEVTYPE_HAL;
  338. // Check for PerfHUD adapter
  339. for (unsigned i=0; i < impl_->interface_->GetAdapterCount(); ++i)
  340. {
  341. D3DADAPTER_IDENTIFIER9 identifier;
  342. impl_->interface_->GetAdapterIdentifier(i, 0, &identifier);
  343. if (strstr(identifier.Description, "PerfHUD") != 0)
  344. {
  345. adapter = i;
  346. deviceType = D3DDEVTYPE_REF;
  347. break;
  348. }
  349. }
  350. impl_->interface_->GetAdapterIdentifier(adapter, 0, &impl_->adapterIdentifier_);
  351. if (!CreateDevice(adapter, deviceType))
  352. return false;
  353. }
  354. else
  355. ResetDevice();
  356. // Adjust window style/size now
  357. if (fullscreen)
  358. {
  359. SetWindowLongPtr(impl_->window_, GWL_STYLE, WS_POPUP);
  360. SetWindowPos(impl_->window_, HWND_TOP, 0, 0, width, height, SWP_NOZORDER | SWP_SHOWWINDOW);
  361. }
  362. else
  363. {
  364. RECT rect = {0, 0, width, height};
  365. AdjustWindowRect(&rect, windowStyle, false);
  366. SetWindowLongPtr(impl_->window_, GWL_STYLE, windowStyle);
  367. SetWindowPos(impl_->window_, HWND_TOP, windowPosX_, windowPosY_, rect.right - rect.left, rect.bottom - rect.top,
  368. SWP_NOZORDER | SWP_SHOWWINDOW);
  369. // Clean up the desktop of the old window contents
  370. InvalidateRect(0, 0, true);
  371. }
  372. if (!multiSample)
  373. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed"));
  374. else
  375. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed") +
  376. " multisample " + String(multiSample));
  377. using namespace ScreenMode;
  378. VariantMap eventData;
  379. eventData[P_WIDTH] = width_;
  380. eventData[P_HEIGHT] = height_;
  381. eventData[P_FULLSCREEN] = fullscreen_;
  382. SendEvent(E_SCREENMODE, eventData);
  383. return true;
  384. }
  385. bool Graphics::SetMode(int width, int height)
  386. {
  387. return SetMode(mode_, width, height, fullscreen_, vsync_, multiSample_);
  388. }
  389. bool Graphics::SetMode(RenderMode mode)
  390. {
  391. return SetMode(mode, width_, height_, fullscreen_, vsync_, multiSample_);
  392. }
  393. bool Graphics::ToggleFullscreen()
  394. {
  395. return SetMode(mode_, width_, height_, !fullscreen_, vsync_, multiSample_);
  396. }
  397. void Graphics::Close()
  398. {
  399. if (impl_->window_)
  400. {
  401. diffBuffer_.Reset();
  402. normalBuffer_.Reset();
  403. depthBuffer_.Reset();
  404. immediateVertexBuffers_.Clear();
  405. DestroyWindow(impl_->window_);
  406. impl_->window_ = 0;
  407. }
  408. }
  409. bool Graphics::TakeScreenShot(Image& destImage)
  410. {
  411. PROFILE(TakeScreenShot);
  412. if (!impl_->device_)
  413. return false;
  414. D3DSURFACE_DESC surfaceDesc;
  415. impl_->defaultColorSurface_->GetDesc(&surfaceDesc);
  416. // If possible, get the backbuffer data, because it is a lot faster.
  417. // However, if we are multisampled, need to use the front buffer
  418. bool useBackBuffer = true;
  419. if (impl_->presentParams_.MultiSampleType)
  420. {
  421. useBackBuffer = false;
  422. surfaceDesc.Format = D3DFMT_A8R8G8B8;
  423. }
  424. IDirect3DSurface9* surface = 0;
  425. impl_->device_->CreateOffscreenPlainSurface(width_, height_, surfaceDesc.Format, D3DPOOL_SYSTEMMEM, &surface, 0);
  426. if (!surface)
  427. return false;
  428. if (useBackBuffer)
  429. impl_->device_->GetRenderTargetData(impl_->defaultColorSurface_, surface);
  430. else
  431. impl_->device_->GetFrontBufferData(0, surface);
  432. D3DLOCKED_RECT lockedRect;
  433. lockedRect.pBits = 0;
  434. surface->LockRect(&lockedRect, 0, D3DLOCK_NOSYSLOCK | D3DLOCK_READONLY);
  435. if (!lockedRect.pBits)
  436. {
  437. surface->Release();
  438. return false;
  439. }
  440. destImage.SetSize(width_, height_, 3);
  441. unsigned char* destData = destImage.GetData();
  442. if (surfaceDesc.Format == D3DFMT_R5G6B5)
  443. {
  444. for (int y = 0; y < height_; ++y)
  445. {
  446. unsigned short* src = (unsigned short*)((unsigned char*)lockedRect.pBits + y * lockedRect.Pitch);
  447. unsigned char* dest = destData + y * width_ * 3;
  448. for (int x = 0; x < width_; ++x)
  449. {
  450. unsigned short rgb = *src++;
  451. int b = rgb & 31;
  452. int g = (rgb >> 5) & 63;
  453. int r = (rgb >> 11);
  454. *dest++ = (int)(r * 255.0f / 31.0f);
  455. *dest++ = (int)(g * 255.0f / 63.0f);
  456. *dest++ = (int)(b * 255.0f / 31.0f);
  457. }
  458. }
  459. }
  460. else
  461. {
  462. for (int y = 0; y < height_; ++y)
  463. {
  464. unsigned char* src = (unsigned char*)lockedRect.pBits + y * lockedRect.Pitch;
  465. unsigned char* dest = destData + y * width_ * 3;
  466. for (int x = 0; x < width_; ++x)
  467. {
  468. *dest++ = src[2];
  469. *dest++ = src[1];
  470. *dest++ = src[0];
  471. src += 4;
  472. }
  473. }
  474. }
  475. surface->UnlockRect();
  476. surface->Release();
  477. return true;
  478. }
  479. void Graphics::SetFlushGPU(bool enable)
  480. {
  481. flushGPU_ = enable;
  482. }
  483. bool Graphics::BeginFrame()
  484. {
  485. PROFILE(BeginRendering);
  486. if (!IsInitialized())
  487. return false;
  488. // Check for lost device before rendering
  489. HRESULT hr = impl_->device_->TestCooperativeLevel();
  490. if (hr != D3D_OK)
  491. {
  492. deviceLost_ = true;
  493. // The device can not be reset yet, sleep and try again eventually
  494. if (hr == D3DERR_DEVICELOST)
  495. {
  496. Sleep(20);
  497. return false;
  498. }
  499. // The device is lost, but ready to be reset. Reset device but do not render on this frame yet
  500. if (hr == D3DERR_DEVICENOTRESET)
  501. {
  502. ResetDevice();
  503. return false;
  504. }
  505. }
  506. impl_->device_->BeginScene();
  507. // If a query was issued on the previous frame, wait for it to finish before beginning the next
  508. if ((impl_->frameQuery_) && (queryIssued_))
  509. {
  510. while (impl_->frameQuery_->GetData(0, 0, D3DGETDATA_FLUSH) == S_FALSE)
  511. {
  512. }
  513. queryIssued_ = false;
  514. }
  515. // Set default rendertarget and depth buffer
  516. ResetRenderTargets();
  517. viewTexture_ = 0;
  518. // Cleanup textures from previous frame
  519. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  520. SetTexture(i, 0);
  521. // Cleanup stream frequencies from previous frame
  522. ResetStreamFrequencies();
  523. // Reset immediate mode vertex buffer positions
  524. for (Map<unsigned, unsigned>::Iterator i = immediateVertexBufferPos_.Begin(); i != immediateVertexBufferPos_.End(); ++i)
  525. i->second_ = 0;
  526. numPrimitives_ = 0;
  527. numBatches_ = 0;
  528. SendEvent(E_BEGINRENDER);
  529. return true;
  530. }
  531. void Graphics::EndFrame()
  532. {
  533. PROFILE(EndRendering);
  534. if (!IsInitialized())
  535. return;
  536. SendEvent(E_ENDRENDER);
  537. // Optionally flush GPU buffer to avoid control lag or framerate fluctuations due to pre-render
  538. if ((impl_->frameQuery_) && (flushGPU_))
  539. {
  540. impl_->frameQuery_->Issue(D3DISSUE_END);
  541. queryIssued_ = true;
  542. }
  543. {
  544. impl_->device_->EndScene();
  545. impl_->device_->Present(0, 0, 0, 0);
  546. }
  547. }
  548. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  549. {
  550. DWORD d3dFlags = 0;
  551. if (flags & CLEAR_COLOR)
  552. d3dFlags |= D3DCLEAR_TARGET;
  553. if (flags & CLEAR_DEPTH)
  554. d3dFlags |= D3DCLEAR_ZBUFFER;
  555. if (flags & CLEAR_STENCIL)
  556. d3dFlags |= D3DCLEAR_STENCIL;
  557. impl_->device_->Clear(0, 0, d3dFlags, color.ToUInt(), depth, stencil);
  558. }
  559. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  560. {
  561. if (!vertexCount)
  562. return;
  563. ResetStreamFrequencies();
  564. unsigned primitiveCount = 0;
  565. switch (type)
  566. {
  567. case TRIANGLE_LIST:
  568. primitiveCount = vertexCount / 3;
  569. impl_->device_->DrawPrimitive(D3DPT_TRIANGLELIST, vertexStart, primitiveCount);
  570. break;
  571. case LINE_LIST:
  572. primitiveCount = vertexCount / 2;
  573. impl_->device_->DrawPrimitive(D3DPT_LINELIST, vertexStart, primitiveCount);
  574. break;
  575. }
  576. numPrimitives_ += primitiveCount;
  577. ++numBatches_;
  578. }
  579. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  580. {
  581. if (!indexCount)
  582. return;
  583. ResetStreamFrequencies();
  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_ += primitiveCount;
  597. ++numBatches_;
  598. }
  599. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount,
  600. unsigned instanceCount)
  601. {
  602. if ((!indexCount) || (!instanceCount))
  603. return;
  604. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  605. {
  606. VertexBuffer* buffer = vertexBuffers_[i];
  607. if (buffer)
  608. {
  609. if (buffer->GetElementMask() & MASK_INSTANCEMATRIX1)
  610. SetStreamFrequency(i, D3DSTREAMSOURCE_INSTANCEDATA | 1);
  611. else
  612. SetStreamFrequency(i, D3DSTREAMSOURCE_INDEXEDDATA | instanceCount);
  613. }
  614. }
  615. unsigned primitiveCount = 0;
  616. switch (type)
  617. {
  618. case TRIANGLE_LIST:
  619. primitiveCount = indexCount / 3;
  620. impl_->device_->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  621. break;
  622. case LINE_LIST:
  623. primitiveCount = indexCount / 2;
  624. impl_->device_->DrawIndexedPrimitive(D3DPT_LINELIST, 0, minVertex, vertexCount, indexStart, primitiveCount);
  625. break;
  626. }
  627. numPrimitives_ += instanceCount * primitiveCount;
  628. ++numBatches_;
  629. }
  630. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  631. {
  632. Vector<VertexBuffer*> vertexBuffers(1);
  633. PODVector<unsigned> elementMasks(1);
  634. vertexBuffers[0] = buffer;
  635. elementMasks[0] = MASK_DEFAULT;
  636. SetVertexBuffers(vertexBuffers, elementMasks);
  637. }
  638. bool Graphics::SetVertexBuffers(const Vector<VertexBuffer*>& buffers, const PODVector<unsigned>&
  639. elementMasks, unsigned instanceOffset)
  640. {
  641. if (buffers.Size() > MAX_VERTEX_STREAMS)
  642. {
  643. LOGERROR("Too many vertex buffers");
  644. return false;
  645. }
  646. if (buffers.Size() != elementMasks.Size())
  647. {
  648. LOGERROR("Amount of element masks and vertex buffers does not match");
  649. return false;
  650. }
  651. // Build vertex declaration hash code out of the buffers & masks
  652. unsigned long long hash = 0;
  653. for (unsigned i = 0; i < buffers.Size(); ++i)
  654. {
  655. if (!buffers[i])
  656. continue;
  657. hash |= buffers[i]->GetHash(i, elementMasks[i]);
  658. }
  659. if (hash)
  660. {
  661. // If no previous vertex declaration for that hash, create new
  662. if (vertexDeclarations_.Find(hash) == vertexDeclarations_.End())
  663. {
  664. SharedPtr<VertexDeclaration> newDeclaration(new VertexDeclaration(this, buffers, elementMasks));
  665. if (!newDeclaration->GetDeclaration())
  666. {
  667. LOGERROR("Failed to create vertex declaration");
  668. return false;
  669. }
  670. vertexDeclarations_[hash] = newDeclaration;
  671. }
  672. VertexDeclaration* declaration = vertexDeclarations_[hash];
  673. if (declaration != vertexDeclaration_)
  674. {
  675. impl_->device_->SetVertexDeclaration(declaration->GetDeclaration());
  676. vertexDeclaration_ = declaration;
  677. }
  678. }
  679. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  680. {
  681. VertexBuffer* buffer = 0;
  682. unsigned offset = 0;
  683. if (i < buffers.Size())
  684. {
  685. buffer = buffers[i];
  686. if ((buffer) && (buffer->GetElementMask() & MASK_INSTANCEMATRIX1))
  687. offset = instanceOffset * buffer->GetVertexSize();
  688. }
  689. if ((buffer != vertexBuffers_[i]) || (offset != streamOffsets_[i]))
  690. {
  691. if (buffer)
  692. impl_->device_->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->GetGPUObject(), offset, buffer->GetVertexSize());
  693. else
  694. impl_->device_->SetStreamSource(i, 0, 0, 0);
  695. vertexBuffers_[i] = buffer;
  696. streamOffsets_[i] = offset;
  697. }
  698. }
  699. return true;
  700. }
  701. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>&
  702. elementMasks, unsigned instanceOffset)
  703. {
  704. if (buffers.Size() > MAX_VERTEX_STREAMS)
  705. {
  706. LOGERROR("Too many vertex buffers");
  707. return false;
  708. }
  709. if (buffers.Size() != elementMasks.Size())
  710. {
  711. LOGERROR("Amount of element masks and vertex buffers does not match");
  712. return false;
  713. }
  714. // Build vertex declaration hash code out of the buffers & masks
  715. unsigned long long hash = 0;
  716. for (unsigned i = 0; i < buffers.Size(); ++i)
  717. {
  718. if (!buffers[i])
  719. continue;
  720. hash |= buffers[i]->GetHash(i, elementMasks[i]);
  721. }
  722. if (hash)
  723. {
  724. // If no previous vertex declaration for that hash, create new
  725. if (vertexDeclarations_.Find(hash) == vertexDeclarations_.End())
  726. {
  727. SharedPtr<VertexDeclaration> newDeclaration(new VertexDeclaration(this, buffers, elementMasks));
  728. if (!newDeclaration->GetDeclaration())
  729. {
  730. LOGERROR("Failed to create vertex declaration");
  731. return false;
  732. }
  733. vertexDeclarations_[hash] = newDeclaration;
  734. }
  735. VertexDeclaration* declaration = vertexDeclarations_[hash];
  736. if (declaration != vertexDeclaration_)
  737. {
  738. impl_->device_->SetVertexDeclaration(declaration->GetDeclaration());
  739. vertexDeclaration_ = declaration;
  740. }
  741. }
  742. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  743. {
  744. VertexBuffer* buffer = 0;
  745. unsigned offset = 0;
  746. if (i < buffers.Size())
  747. {
  748. buffer = buffers[i];
  749. if ((buffer) && (buffer->GetElementMask() & MASK_INSTANCEMATRIX1))
  750. offset = instanceOffset * buffer->GetVertexSize();
  751. }
  752. if ((buffer != vertexBuffers_[i]) || (offset != streamOffsets_[i]))
  753. {
  754. if (buffer)
  755. impl_->device_->SetStreamSource(i, (IDirect3DVertexBuffer9*)buffer->GetGPUObject(), offset, buffer->GetVertexSize());
  756. else
  757. impl_->device_->SetStreamSource(i, 0, 0, 0);
  758. vertexBuffers_[i] = buffer;
  759. streamOffsets_[i] = offset;
  760. }
  761. }
  762. return true;
  763. }
  764. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  765. {
  766. if (buffer != indexBuffer_)
  767. {
  768. if (buffer)
  769. impl_->device_->SetIndices((IDirect3DIndexBuffer9*)buffer->GetGPUObject());
  770. else
  771. impl_->device_->SetIndices(0);
  772. indexBuffer_ = buffer;
  773. }
  774. }
  775. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  776. {
  777. if (vs != vertexShader_)
  778. {
  779. if ((vs) && (vs->GetShaderType() == VS))
  780. impl_->device_->SetVertexShader((IDirect3DVertexShader9*)vs->GetGPUObject());
  781. else
  782. impl_->device_->SetVertexShader(0);
  783. vertexShader_ = vs;
  784. }
  785. if (ps != pixelShader_)
  786. {
  787. if ((ps) && (ps->GetShaderType() == PS))
  788. impl_->device_->SetPixelShader((IDirect3DPixelShader9*)ps->GetGPUObject());
  789. else
  790. impl_->device_->SetPixelShader(0);
  791. pixelShader_ = ps;
  792. }
  793. }
  794. void Graphics::SetShaderParameter(ShaderParameter param, const bool* data, unsigned count)
  795. {
  796. unsigned index = shaderRegisters_[param];
  797. if (index >= MAX_CONSTANT_REGISTERS)
  798. return;
  799. if (param < PSP_AMBIENTCOLOR)
  800. impl_->device_->SetVertexShaderConstantB(index, (const BOOL*)data, count);
  801. else
  802. impl_->device_->SetPixelShaderConstantB(index, (const BOOL*)data, count);
  803. }
  804. void Graphics::SetShaderParameter(ShaderParameter param, const float* data, unsigned count)
  805. {
  806. unsigned index = shaderRegisters_[param];
  807. if (index >= MAX_CONSTANT_REGISTERS)
  808. return;
  809. if (param < PSP_AMBIENTCOLOR)
  810. impl_->device_->SetVertexShaderConstantF(index, data, count / 4);
  811. else
  812. impl_->device_->SetPixelShaderConstantF(index, data, count / 4);
  813. }
  814. void Graphics::SetShaderParameter(ShaderParameter param, const int* data, unsigned count)
  815. {
  816. unsigned index = shaderRegisters_[param];
  817. if (index >= MAX_CONSTANT_REGISTERS)
  818. return;
  819. if (param < PSP_AMBIENTCOLOR)
  820. impl_->device_->SetVertexShaderConstantI(index, data, count / 4);
  821. else
  822. impl_->device_->SetPixelShaderConstantI(index, data, count / 4);
  823. }
  824. void Graphics::SetShaderParameter(ShaderParameter param, float value)
  825. {
  826. unsigned index = shaderRegisters_[param];
  827. if (index >= MAX_CONSTANT_REGISTERS)
  828. return;
  829. float data[4];
  830. data[0] = value;
  831. data[1] = 0.0f;
  832. data[2] = 0.0f;
  833. data[3] = 0.0f;
  834. if (param < PSP_AMBIENTCOLOR)
  835. impl_->device_->SetVertexShaderConstantF(index, &data[0], 1);
  836. else
  837. impl_->device_->SetPixelShaderConstantF(index, &data[0], 1);
  838. }
  839. void Graphics::SetShaderParameter(ShaderParameter param, const Color& color)
  840. {
  841. unsigned index = shaderRegisters_[param];
  842. if (index >= MAX_CONSTANT_REGISTERS)
  843. return;
  844. if (param < PSP_AMBIENTCOLOR)
  845. impl_->device_->SetVertexShaderConstantF(index, color.GetData(), 1);
  846. else
  847. impl_->device_->SetPixelShaderConstantF(index, color.GetData(), 1);
  848. }
  849. void Graphics::SetShaderParameter(ShaderParameter param, const Matrix3& matrix)
  850. {
  851. unsigned index = shaderRegisters_[param];
  852. if (index >= MAX_CONSTANT_REGISTERS)
  853. return;
  854. float data[12];
  855. data[0] = matrix.m00_;
  856. data[1] = matrix.m01_;
  857. data[2] = matrix.m02_;
  858. data[3] = 0.0f;
  859. data[4] = matrix.m10_;
  860. data[5] = matrix.m11_;
  861. data[6] = matrix.m12_;
  862. data[7] = 0.0f;
  863. data[8] = matrix.m20_;
  864. data[9] = matrix.m21_;
  865. data[10] = matrix.m22_;
  866. data[11] = 0.0f;
  867. if (param < PSP_AMBIENTCOLOR)
  868. impl_->device_->SetVertexShaderConstantF(index, &data[0], 3);
  869. else
  870. impl_->device_->SetPixelShaderConstantF(index, &data[0], 3);
  871. }
  872. void Graphics::SetShaderParameter(ShaderParameter param, const Vector3& vector)
  873. {
  874. unsigned index = shaderRegisters_[param];
  875. if (index >= MAX_CONSTANT_REGISTERS)
  876. return;
  877. float data[4];
  878. data[0] = vector.x_;
  879. data[1] = vector.y_;
  880. data[2] = vector.z_;
  881. data[3] = 0.0f;
  882. if (param < PSP_AMBIENTCOLOR)
  883. impl_->device_->SetVertexShaderConstantF(index, &data[0], 1);
  884. else
  885. impl_->device_->SetPixelShaderConstantF(index, &data[0], 1);
  886. }
  887. void Graphics::SetShaderParameter(ShaderParameter param, const Matrix4& matrix)
  888. {
  889. unsigned index = shaderRegisters_[param];
  890. if (index >= MAX_CONSTANT_REGISTERS)
  891. return;
  892. if (param < PSP_AMBIENTCOLOR)
  893. impl_->device_->SetVertexShaderConstantF(index, matrix.GetData(), 4);
  894. else
  895. impl_->device_->SetPixelShaderConstantF(index, matrix.GetData(), 4);
  896. }
  897. void Graphics::SetShaderParameter(ShaderParameter param, const Vector4& vector)
  898. {
  899. unsigned index = shaderRegisters_[param];
  900. if (index >= MAX_CONSTANT_REGISTERS)
  901. return;
  902. if (param < PSP_AMBIENTCOLOR)
  903. impl_->device_->SetVertexShaderConstantF(index, vector.GetData(), 1);
  904. else
  905. impl_->device_->SetPixelShaderConstantF(index, vector.GetData(), 1);
  906. }
  907. void Graphics::SetShaderParameter(ShaderParameter param, const Matrix3x4& matrix)
  908. {
  909. unsigned index = shaderRegisters_[param];
  910. if (index >= MAX_CONSTANT_REGISTERS)
  911. return;
  912. if (param < PSP_AMBIENTCOLOR)
  913. impl_->device_->SetVertexShaderConstantF(index, matrix.GetData(), 3);
  914. else
  915. impl_->device_->SetPixelShaderConstantF(index, matrix.GetData(), 3);
  916. }
  917. bool Graphics::NeedParameterUpdate(ShaderParameter param, const void* source)
  918. {
  919. if (param < PSP_AMBIENTCOLOR)
  920. {
  921. if ((vertexShader_) && (vertexShader_->HasParameter(param)) && (lastShaderParameterSources_[param] != source))
  922. {
  923. lastShaderParameterSources_[param] = source;
  924. return true;
  925. }
  926. }
  927. else
  928. {
  929. if ((pixelShader_) && (pixelShader_->HasParameter(param)) && (lastShaderParameterSources_[param] != source))
  930. {
  931. lastShaderParameterSources_[param] = source;
  932. return true;
  933. }
  934. }
  935. return false;
  936. }
  937. bool Graphics::NeedTextureUnit(TextureUnit unit)
  938. {
  939. return (pixelShader_) && (pixelShader_->HasTextureUnit(unit));
  940. }
  941. void Graphics::ClearLastParameterSources()
  942. {
  943. for (unsigned i = 0; i < MAX_SHADER_PARAMETERS; ++i)
  944. lastShaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  945. }
  946. void Graphics::ClearTransformSources()
  947. {
  948. lastShaderParameterSources_[VSP_MODEL] = (const void*)M_MAX_UNSIGNED;
  949. lastShaderParameterSources_[VSP_VIEWPROJ] = (const void*)M_MAX_UNSIGNED;
  950. }
  951. void Graphics::SetTexture(unsigned index, Texture* texture)
  952. {
  953. if (index >= MAX_TEXTURE_UNITS)
  954. return;
  955. // Check if texture is currently bound as a render target. In that case, use its backup texture, or blank if not defined
  956. if (texture)
  957. {
  958. if ((renderTargets_[0]) && (renderTargets_[0]->GetParentTexture() == texture))
  959. texture = texture->GetBackupTexture();
  960. // Check also for the view texture, in case a specific rendering pass does not bind the destination render target,
  961. // but should still not sample it either
  962. else if (texture == viewTexture_)
  963. texture = texture->GetBackupTexture();
  964. }
  965. if (texture != textures_[index])
  966. {
  967. if (texture)
  968. impl_->device_->SetTexture(index, (IDirect3DBaseTexture9*)texture->GetGPUObject());
  969. else
  970. impl_->device_->SetTexture(index, 0);
  971. textures_[index] = texture;
  972. }
  973. if (texture)
  974. {
  975. TextureFilterMode filterMode = texture->GetFilterMode();
  976. if (filterMode == FILTER_DEFAULT)
  977. filterMode = defaultTextureFilterMode_;
  978. D3DTEXTUREFILTERTYPE minMag, mip;
  979. minMag = d3dMinMagFilter[filterMode];
  980. if (minMag != impl_->minMagFilters_[index])
  981. {
  982. impl_->device_->SetSamplerState(index, D3DSAMP_MAGFILTER, minMag);
  983. impl_->device_->SetSamplerState(index, D3DSAMP_MINFILTER, minMag);
  984. impl_->minMagFilters_[index] = minMag;
  985. }
  986. mip = d3dMipFilter[filterMode];
  987. if (mip != impl_->mipFilters_[index])
  988. {
  989. impl_->device_->SetSamplerState(index, D3DSAMP_MIPFILTER, mip);
  990. impl_->mipFilters_[index] = mip;
  991. }
  992. D3DTEXTUREADDRESS u, v;
  993. u = d3dAddressMode[texture->GetAddressMode(COORD_U)];
  994. if (u != impl_->uAddressModes_[index])
  995. {
  996. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSU, u);
  997. impl_->uAddressModes_[index] = u;
  998. }
  999. v = d3dAddressMode[texture->GetAddressMode(COORD_V)];
  1000. if (v != impl_->vAddressModes_[index])
  1001. {
  1002. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSV, v);
  1003. impl_->vAddressModes_[index] = v;
  1004. }
  1005. if ((u == D3DTADDRESS_BORDER) || (v == D3DTADDRESS_BORDER))
  1006. {
  1007. const Color& borderColor = texture->GetBorderColor();
  1008. if (borderColor != impl_->borderColors_[index])
  1009. {
  1010. impl_->device_->SetSamplerState(index, D3DSAMP_BORDERCOLOR, borderColor.ToUInt());
  1011. impl_->borderColors_[index] = borderColor;
  1012. }
  1013. }
  1014. }
  1015. }
  1016. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1017. {
  1018. defaultTextureFilterMode_ = mode;
  1019. }
  1020. void Graphics::ResetRenderTargets()
  1021. {
  1022. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1023. SetRenderTarget(i, (RenderSurface*)0);
  1024. SetDepthStencil((RenderSurface*)0);
  1025. }
  1026. void Graphics::ResetRenderTarget(unsigned index)
  1027. {
  1028. SetRenderTarget(index, (RenderSurface*)0);
  1029. }
  1030. void Graphics::ResetDepthStencil()
  1031. {
  1032. SetDepthStencil((RenderSurface*)0);
  1033. }
  1034. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1035. {
  1036. if (index >= MAX_RENDERTARGETS)
  1037. return;
  1038. IDirect3DSurface9* newColorSurface = 0;
  1039. if (renderTarget)
  1040. {
  1041. if (renderTarget->GetUsage() != TEXTURE_RENDERTARGET)
  1042. return;
  1043. newColorSurface = (IDirect3DSurface9*)renderTarget->GetSurface();
  1044. }
  1045. else
  1046. {
  1047. if (!index)
  1048. newColorSurface = impl_->defaultColorSurface_;
  1049. }
  1050. renderTargets_[index] = renderTarget;
  1051. if (newColorSurface != impl_->colorSurfaces_[index])
  1052. {
  1053. impl_->device_->SetRenderTarget(index, newColorSurface);
  1054. impl_->colorSurfaces_[index] = newColorSurface;
  1055. }
  1056. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1057. if (renderTarget)
  1058. {
  1059. Texture* parentTexture = renderTarget->GetParentTexture();
  1060. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1061. {
  1062. if (textures_[i] == parentTexture)
  1063. SetTexture(i, textures_[i]->GetBackupTexture());
  1064. }
  1065. }
  1066. if (!index)
  1067. {
  1068. // Viewport has been reset
  1069. IntVector2 rtSize = GetRenderTargetDimensions();
  1070. viewport_ = IntRect(0, 0, rtSize.x_, rtSize.y_);
  1071. // Disable scissor test, needs to be re-enabled by the user
  1072. SetScissorTest(false);
  1073. }
  1074. }
  1075. void Graphics::SetRenderTarget(unsigned index, Texture2D* renderTexture)
  1076. {
  1077. RenderSurface* renderTarget = 0;
  1078. if (renderTexture)
  1079. renderTarget = renderTexture->GetRenderSurface();
  1080. SetRenderTarget(index, renderTarget);
  1081. }
  1082. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1083. {
  1084. IDirect3DSurface9* newDepthStencilSurface = 0;
  1085. if ((depthStencil) && (depthStencil->GetUsage() == TEXTURE_DEPTHSTENCIL))
  1086. {
  1087. newDepthStencilSurface = (IDirect3DSurface9*)depthStencil->GetSurface();
  1088. depthStencil_ = depthStencil;
  1089. }
  1090. if (!newDepthStencilSurface)
  1091. {
  1092. newDepthStencilSurface = impl_->defaultDepthStencilSurface_;
  1093. depthStencil_ = 0;
  1094. }
  1095. if (newDepthStencilSurface != impl_->depthStencilSurface_)
  1096. {
  1097. impl_->device_->SetDepthStencilSurface(newDepthStencilSurface);
  1098. impl_->depthStencilSurface_ = newDepthStencilSurface;
  1099. }
  1100. }
  1101. void Graphics::SetDepthStencil(Texture2D* depthTexture)
  1102. {
  1103. RenderSurface* depthStencil = 0;
  1104. if (depthTexture)
  1105. depthStencil = depthTexture->GetRenderSurface();
  1106. SetDepthStencil(depthStencil);
  1107. }
  1108. void Graphics::SetViewport(const IntRect& rect)
  1109. {
  1110. IntVector2 size = GetRenderTargetDimensions();
  1111. IntRect rectCopy = rect;
  1112. if (rectCopy.right_ <= rectCopy.left_)
  1113. rectCopy.right_ = rectCopy.left_ + 1;
  1114. if (rectCopy.bottom_ <= rectCopy.top_)
  1115. rectCopy.bottom_ = rectCopy.top_ + 1;
  1116. rectCopy.left_ = Clamp(rectCopy.left_, 0, size.x_);
  1117. rectCopy.top_ = Clamp(rectCopy.top_, 0, size.y_);
  1118. rectCopy.right_ = Clamp(rectCopy.right_, 0, size.x_);
  1119. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, size.y_);
  1120. D3DVIEWPORT9 vp;
  1121. vp.MinZ = 0.0f;
  1122. vp.MaxZ = 1.0f;
  1123. vp.X = rectCopy.left_;
  1124. vp.Y = rectCopy.top_;
  1125. vp.Width = rectCopy.right_ - rectCopy.left_;
  1126. vp.Height = rectCopy.bottom_ - rectCopy.top_;
  1127. impl_->device_->SetViewport(&vp);
  1128. viewport_ = rectCopy;
  1129. // Disable scissor test, needs to be re-enabled by the user
  1130. SetScissorTest(false);
  1131. }
  1132. void Graphics::SetViewTexture(Texture* texture)
  1133. {
  1134. viewTexture_ = texture;
  1135. // Check for the view texture being currently bound
  1136. if (texture)
  1137. {
  1138. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1139. {
  1140. if (textures_[i] == texture)
  1141. SetTexture(i, textures_[i]->GetBackupTexture());
  1142. }
  1143. }
  1144. }
  1145. void Graphics::SetAlphaTest(bool enable, CompareMode mode, float alphaRef)
  1146. {
  1147. if (enable != alphaTest_)
  1148. {
  1149. impl_->device_->SetRenderState(D3DRS_ALPHATESTENABLE, enable ? TRUE : FALSE);
  1150. alphaTest_ = enable;
  1151. }
  1152. if (enable)
  1153. {
  1154. if (mode != alphaTestMode_)
  1155. {
  1156. impl_->device_->SetRenderState(D3DRS_ALPHAFUNC, d3dCmpFunc[mode]);
  1157. alphaTestMode_ = mode;
  1158. }
  1159. alphaRef = Clamp(alphaRef, 0.0f, 1.0f);
  1160. if (alphaRef != alphaRef_)
  1161. {
  1162. impl_->device_->SetRenderState(D3DRS_ALPHAREF, (DWORD)(alphaRef * 255.0f));
  1163. alphaRef_ = alphaRef;
  1164. }
  1165. }
  1166. }
  1167. void Graphics::SetTextureAnisotropy(unsigned level)
  1168. {
  1169. if (level < 1)
  1170. level = 1;
  1171. if (level != textureAnisotropy_)
  1172. {
  1173. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1174. impl_->device_->SetSamplerState(i, D3DSAMP_MAXANISOTROPY, level);
  1175. textureAnisotropy_ = level;
  1176. }
  1177. }
  1178. void Graphics::SetBlendMode(BlendMode mode)
  1179. {
  1180. if (mode != blendMode_)
  1181. {
  1182. if (d3dBlendEnable[mode] != impl_->blendEnable_)
  1183. {
  1184. impl_->device_->SetRenderState(D3DRS_ALPHABLENDENABLE, d3dBlendEnable[mode]);
  1185. impl_->blendEnable_ = d3dBlendEnable[mode];
  1186. }
  1187. if (impl_->blendEnable_)
  1188. {
  1189. if (d3dSrcBlend[mode] != impl_->srcBlend_)
  1190. {
  1191. impl_->device_->SetRenderState(D3DRS_SRCBLEND, d3dSrcBlend[mode]);
  1192. impl_->srcBlend_ = d3dSrcBlend[mode];
  1193. }
  1194. if (d3dDestBlend[mode] != impl_->destBlend_)
  1195. {
  1196. impl_->device_->SetRenderState(D3DRS_DESTBLEND, d3dDestBlend[mode]);
  1197. impl_->destBlend_ = d3dDestBlend[mode];
  1198. }
  1199. }
  1200. blendMode_ = mode;
  1201. }
  1202. }
  1203. void Graphics::SetColorWrite(bool enable)
  1204. {
  1205. if (enable != colorWrite_)
  1206. {
  1207. impl_->device_->SetRenderState(D3DRS_COLORWRITEENABLE, enable ? D3DCOLORWRITEENABLE_RED |
  1208. D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA : 0);
  1209. colorWrite_ = enable;
  1210. }
  1211. }
  1212. void Graphics::SetCullMode(CullMode mode)
  1213. {
  1214. if (mode != cullMode_)
  1215. {
  1216. impl_->device_->SetRenderState(D3DRS_CULLMODE, d3dCullMode[mode]);
  1217. cullMode_ = mode;
  1218. }
  1219. }
  1220. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1221. {
  1222. if (constantBias != constantDepthBias_)
  1223. {
  1224. impl_->device_->SetRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&constantBias));
  1225. constantDepthBias_ = constantBias;
  1226. }
  1227. if (slopeScaledBias != slopeScaledDepthBias_)
  1228. {
  1229. impl_->device_->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&slopeScaledBias));
  1230. slopeScaledDepthBias_ = slopeScaledBias;
  1231. }
  1232. }
  1233. void Graphics::SetDepthTest(CompareMode mode)
  1234. {
  1235. if (mode != depthTestMode_)
  1236. {
  1237. impl_->device_->SetRenderState(D3DRS_ZFUNC, d3dCmpFunc[mode]);
  1238. depthTestMode_ = mode;
  1239. }
  1240. }
  1241. void Graphics::SetDepthWrite(bool enable)
  1242. {
  1243. if (enable != depthWrite_)
  1244. {
  1245. impl_->device_->SetRenderState(D3DRS_ZWRITEENABLE, enable ? TRUE : FALSE);
  1246. depthWrite_ = enable;
  1247. }
  1248. }
  1249. void Graphics::SetFillMode(FillMode mode)
  1250. {
  1251. if (mode != fillMode_)
  1252. {
  1253. impl_->device_->SetRenderState(D3DRS_FILLMODE, d3dFillMode[mode]);
  1254. fillMode_ = mode;
  1255. }
  1256. }
  1257. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1258. {
  1259. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1260. // Disable scissor in that case to reduce state changes
  1261. if ((rect.min_.x_ <= 0.0f) && (rect.min_.y_ <= 0.0f) && (rect.max_.y_ >= 1.0f) && (rect.max_.y_ >= 1.0f))
  1262. enable = false;
  1263. // Check for illegal rect, disable in that case
  1264. if ((rect.max_.x_ < rect.min_.x_) || (rect.max_.y_ < rect.min_.y_))
  1265. enable = false;
  1266. if (enable)
  1267. {
  1268. IntVector2 rtSize(GetRenderTargetDimensions());
  1269. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1270. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1271. IntRect intRect;
  1272. int expand = borderInclusive ? 1 : 0;
  1273. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1274. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1275. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1276. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1277. if (intRect.right_ == intRect.left_)
  1278. intRect.right_++;
  1279. if (intRect.bottom_ == intRect.top_)
  1280. intRect.bottom_++;
  1281. if ((intRect.right_ < intRect.left_) || (intRect.bottom_ < intRect.top_))
  1282. enable = false;
  1283. if ((enable) && (scissorRect_ != intRect))
  1284. {
  1285. RECT d3dRect;
  1286. d3dRect.left = intRect.left_;
  1287. d3dRect.top = intRect.top_;
  1288. d3dRect.right = intRect.right_;
  1289. d3dRect.bottom = intRect.bottom_;
  1290. impl_->device_->SetScissorRect(&d3dRect);
  1291. scissorRect_ = intRect;
  1292. }
  1293. }
  1294. else
  1295. scissorRect_ = IntRect::ZERO;
  1296. if (enable != scissorTest_)
  1297. {
  1298. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1299. scissorTest_ = enable;
  1300. }
  1301. }
  1302. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1303. {
  1304. IntVector2 rtSize(GetRenderTargetDimensions());
  1305. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1306. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1307. // Full scissor is same as disabling the test
  1308. if ((rect.left_ <= 0) && (rect.right_ >= viewSize.x_) && (rect.top_ <= 0) && (rect.bottom_ >= viewSize.y_))
  1309. enable = false;
  1310. // Check for illegal rect, disable in that case
  1311. if ((rect.right_ < rect.left_) || (rect.bottom_ < rect.top_))
  1312. enable = false;
  1313. if (enable)
  1314. {
  1315. IntRect intRect;
  1316. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1317. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1318. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1319. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1320. if (intRect.right_ == intRect.left_)
  1321. intRect.right_++;
  1322. if (intRect.bottom_ == intRect.top_)
  1323. intRect.bottom_++;
  1324. if ((intRect.right_ < intRect.left_) || (intRect.bottom_ < intRect.top_))
  1325. enable = false;
  1326. if ((enable) && (scissorRect_ != intRect))
  1327. {
  1328. RECT d3dRect;
  1329. d3dRect.left = intRect.left_;
  1330. d3dRect.top = intRect.top_;
  1331. d3dRect.right = intRect.right_;
  1332. d3dRect.bottom = intRect.bottom_;
  1333. impl_->device_->SetScissorRect(&d3dRect);
  1334. scissorRect_ = intRect;
  1335. }
  1336. }
  1337. else
  1338. scissorRect_ = IntRect::ZERO;
  1339. if (enable != scissorTest_)
  1340. {
  1341. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1342. scissorTest_ = enable;
  1343. }
  1344. }
  1345. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned stencilMask)
  1346. {
  1347. if (enable != stencilTest_)
  1348. {
  1349. impl_->device_->SetRenderState(D3DRS_STENCILENABLE, enable ? TRUE : FALSE);
  1350. stencilTest_ = enable;
  1351. }
  1352. if (enable)
  1353. {
  1354. if (mode != stencilTestMode_)
  1355. {
  1356. impl_->device_->SetRenderState(D3DRS_STENCILFUNC, d3dCmpFunc[mode]);
  1357. stencilTestMode_ = mode;
  1358. }
  1359. if (pass != stencilPass_)
  1360. {
  1361. impl_->device_->SetRenderState(D3DRS_STENCILPASS, d3dStencilOp[pass]);
  1362. stencilPass_ = pass;
  1363. }
  1364. if (fail != stencilFail_)
  1365. {
  1366. impl_->device_->SetRenderState(D3DRS_STENCILFAIL, d3dStencilOp[fail]);
  1367. stencilFail_ = fail;
  1368. }
  1369. if (zFail != stencilZFail_)
  1370. {
  1371. impl_->device_->SetRenderState(D3DRS_STENCILZFAIL, d3dStencilOp[zFail]);
  1372. stencilZFail_ = zFail;
  1373. }
  1374. if (stencilRef != stencilRef_)
  1375. {
  1376. impl_->device_->SetRenderState(D3DRS_STENCILREF, stencilRef);
  1377. stencilRef_ = stencilRef;
  1378. }
  1379. if (stencilMask != stencilMask_)
  1380. {
  1381. impl_->device_->SetRenderState(D3DRS_STENCILMASK, stencilMask);
  1382. stencilMask_ = stencilMask;
  1383. }
  1384. }
  1385. }
  1386. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1387. {
  1388. if ((index < MAX_VERTEX_STREAMS) && (streamFrequencies_[index] != frequency))
  1389. {
  1390. impl_->device_->SetStreamSourceFreq(index, frequency);
  1391. streamFrequencies_[index] = frequency;
  1392. }
  1393. }
  1394. void Graphics::ResetStreamFrequencies()
  1395. {
  1396. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1397. {
  1398. if (streamFrequencies_[i] != 1)
  1399. {
  1400. impl_->device_->SetStreamSourceFreq(i, 1);
  1401. streamFrequencies_[i] = 1;
  1402. }
  1403. }
  1404. }
  1405. bool Graphics::BeginImmediate(PrimitiveType type, unsigned vertexCount, unsigned elementMask)
  1406. {
  1407. if (immediateBuffer_)
  1408. {
  1409. LOGERROR("New immediate draw operation started before ending the last one");
  1410. return false;
  1411. }
  1412. if (!(elementMask & MASK_POSITION))
  1413. {
  1414. LOGERROR("Immediate draw operation must contain vertex positions");
  1415. return false;
  1416. }
  1417. if (!vertexCount)
  1418. return true;
  1419. // Start from default size, ensure that buffer is big enough to hold the immediate draw operation
  1420. unsigned newSize = IMMEDIATE_BUFFER_DEFAULT_SIZE;
  1421. while (newSize < vertexCount)
  1422. newSize <<= 1;
  1423. // See if buffer exists for this vertex format. If not, create new
  1424. if (immediateVertexBuffers_.Find(elementMask) == immediateVertexBuffers_.End())
  1425. {
  1426. LOGDEBUG("Created immediate vertex buffer");
  1427. VertexBuffer* newBuffer = new VertexBuffer(context_);
  1428. newBuffer->SetSize(newSize, elementMask, true);
  1429. immediateVertexBuffers_[elementMask] = newBuffer;
  1430. immediateVertexBufferPos_[elementMask] = 0;
  1431. }
  1432. // Resize buffer if it is too small
  1433. VertexBuffer* buffer = immediateVertexBuffers_[elementMask];
  1434. if (buffer->GetVertexCount() < newSize)
  1435. {
  1436. LOGDEBUG("Resized immediate vertex buffer to " + String(newSize));
  1437. buffer->SetSize(newSize, elementMask);
  1438. immediateVertexBufferPos_[elementMask] = 0;
  1439. }
  1440. // Get the current lock position for the buffer
  1441. unsigned bufferPos = immediateVertexBufferPos_[elementMask];
  1442. if (bufferPos + vertexCount >= buffer->GetVertexCount())
  1443. bufferPos = 0;
  1444. LockMode lockMode = LOCK_DISCARD;
  1445. if (bufferPos != 0)
  1446. lockMode = LOCK_NOOVERWRITE;
  1447. // Note: the data pointer gets pre-decremented here, because the first call to DefineVertex() will increment it
  1448. immediateDataPtr_ = ((unsigned char*)buffer->Lock(bufferPos, vertexCount, lockMode)) - buffer->GetVertexSize();
  1449. immediateBuffer_ = buffer;
  1450. immediateType_= type;
  1451. immediateStartPos_ = bufferPos;
  1452. immediateVertexCount_ = vertexCount;
  1453. immediateCurrentVertex_ = 0;
  1454. // Store new buffer position for next lock into the same buffer
  1455. bufferPos += vertexCount;
  1456. if (bufferPos >= buffer->GetVertexCount())
  1457. bufferPos = 0;
  1458. immediateVertexBufferPos_[elementMask] = bufferPos;
  1459. return true;
  1460. }
  1461. bool Graphics::DefineVertex(const Vector3& vertex)
  1462. {
  1463. if ((!immediateBuffer_) || (immediateCurrentVertex_ >= immediateVertexCount_))
  1464. return false;
  1465. immediateDataPtr_ += immediateBuffer_->GetVertexSize();
  1466. ++immediateCurrentVertex_;
  1467. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_POSITION));
  1468. const float* src = vertex.GetData();
  1469. dest[0] = src[0];
  1470. dest[1] = src[1];
  1471. dest[2] = src[2];
  1472. return true;
  1473. }
  1474. bool Graphics::DefineNormal(const Vector3& normal)
  1475. {
  1476. if ((!immediateBuffer_) ||(!(immediateBuffer_->GetElementMask() & MASK_NORMAL)) || (!immediateCurrentVertex_))
  1477. return false;
  1478. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_NORMAL));
  1479. const float* src = normal.GetData();
  1480. dest[0] = src[0];
  1481. dest[1] = src[1];
  1482. dest[2] = src[2];
  1483. return true;
  1484. }
  1485. bool Graphics::DefineTexCoord(const Vector2& texCoord)
  1486. {
  1487. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_TEXCOORD1)) || (!immediateCurrentVertex_))
  1488. return false;
  1489. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_TEXCOORD1));
  1490. const float* src = texCoord.GetData();
  1491. dest[0] = src[0];
  1492. dest[1] = src[1];
  1493. return true;
  1494. }
  1495. bool Graphics::DefineColor(const Color& color)
  1496. {
  1497. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_COLOR)) || (!immediateCurrentVertex_))
  1498. return false;
  1499. unsigned* dest = (unsigned*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_COLOR));
  1500. *dest = color.ToUInt();
  1501. return true;
  1502. }
  1503. bool Graphics::DefineColor(unsigned color)
  1504. {
  1505. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_COLOR)) || (!immediateCurrentVertex_))
  1506. return false;
  1507. unsigned* dest = (unsigned*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_COLOR));
  1508. *dest = color;
  1509. return true;
  1510. }
  1511. void Graphics::EndImmediate()
  1512. {
  1513. if (immediateBuffer_)
  1514. {
  1515. immediateBuffer_->Unlock();
  1516. SetVertexBuffer(immediateBuffer_);
  1517. Draw(immediateType_, immediateStartPos_, immediateVertexCount_);
  1518. immediateBuffer_ = 0;
  1519. }
  1520. }
  1521. void Graphics::SetForceSM2(bool enable)
  1522. {
  1523. // Note: this only has effect before calling SetMode() for the first time
  1524. forceSM2_ = enable;
  1525. }
  1526. bool Graphics::IsInitialized() const
  1527. {
  1528. return (impl_->window_ != 0) && (impl_->GetDevice() != 0);
  1529. }
  1530. unsigned char* Graphics::GetImmediateDataPtr() const
  1531. {
  1532. if (!immediateBuffer_)
  1533. {
  1534. LOGERROR("Immediate draw operation not started");
  1535. return 0;
  1536. }
  1537. // Pointer was pre-decremented in BeginImmediate(). Undo that now
  1538. return immediateDataPtr_ + immediateBuffer_->GetVertexSize();
  1539. }
  1540. unsigned Graphics::GetWindowHandle() const
  1541. {
  1542. return (unsigned)impl_->window_;
  1543. }
  1544. PODVector<IntVector2> Graphics::GetResolutions() const
  1545. {
  1546. PODVector<IntVector2> ret;
  1547. if (!impl_->interface_)
  1548. return ret;
  1549. D3DFORMAT fullscreenFormat = impl_->GetDesktopFormat();
  1550. unsigned numModes = impl_->interface_->GetAdapterModeCount(impl_->adapter_, fullscreenFormat);
  1551. D3DDISPLAYMODE displayMode;
  1552. for (unsigned i = 0; i < numModes; ++i)
  1553. {
  1554. if (FAILED(impl_->interface_->EnumAdapterModes(impl_->adapter_, fullscreenFormat, i, &displayMode)))
  1555. continue;
  1556. if (displayMode.Format != fullscreenFormat)
  1557. continue;
  1558. IntVector2 newMode(displayMode.Width, displayMode.Height);
  1559. // Check for duplicate before storing
  1560. bool unique = true;
  1561. for (unsigned j = 0; j < ret.Size(); ++j)
  1562. {
  1563. if (ret[j] == newMode)
  1564. {
  1565. unique = false;
  1566. break;
  1567. }
  1568. }
  1569. if (unique)
  1570. ret.Push(newMode);
  1571. }
  1572. return ret;
  1573. }
  1574. PODVector<int> Graphics::GetMultiSampleLevels() const
  1575. {
  1576. PODVector<int> ret;
  1577. // No multisampling always supported
  1578. ret.Push(0);
  1579. if (!impl_->interface_)
  1580. return ret;
  1581. for (unsigned i = (int)D3DMULTISAMPLE_2_SAMPLES; i < (int)D3DMULTISAMPLE_16_SAMPLES; ++i)
  1582. {
  1583. if (SUCCEEDED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, D3DFMT_R8G8B8, FALSE,
  1584. (D3DMULTISAMPLE_TYPE)i, NULL)))
  1585. ret.Push(i);
  1586. }
  1587. return ret;
  1588. }
  1589. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1590. {
  1591. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1592. }
  1593. ShaderParameter Graphics::GetShaderParameter(const String& name)
  1594. {
  1595. Map<String, ShaderParameter>::Iterator i = shaderParameters_.Find(name);
  1596. if (i != shaderParameters_.End())
  1597. return i->second_;
  1598. else
  1599. return MAX_SHADER_PARAMETERS;
  1600. }
  1601. TextureUnit Graphics::GetTextureUnit(const String& name)
  1602. {
  1603. Map<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1604. if (i != textureUnits_.End())
  1605. return i->second_;
  1606. else
  1607. return MAX_TEXTURE_UNITS;
  1608. }
  1609. const String& Graphics::GetShaderParameterName(ShaderParameter parameter)
  1610. {
  1611. for (Map<String, ShaderParameter>::Iterator i = shaderParameters_.Begin(); i != shaderParameters_.End(); ++i)
  1612. {
  1613. if (i->second_ == parameter)
  1614. return i->first_;
  1615. }
  1616. return noParameter;
  1617. }
  1618. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1619. {
  1620. for (Map<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1621. {
  1622. if (i->second_ == unit)
  1623. return i->first_;
  1624. }
  1625. return noParameter;
  1626. }
  1627. Texture* Graphics::GetTexture(unsigned index) const
  1628. {
  1629. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1630. }
  1631. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1632. {
  1633. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1634. }
  1635. unsigned Graphics::GetStreamFrequency(unsigned index) const
  1636. {
  1637. return index < MAX_VERTEX_STREAMS ? streamFrequencies_[index] : 0;
  1638. }
  1639. IntVector2 Graphics::GetRenderTargetDimensions() const
  1640. {
  1641. int width, height;
  1642. if (renderTargets_[0])
  1643. {
  1644. width = renderTargets_[0]->GetWidth();
  1645. height = renderTargets_[0]->GetHeight();
  1646. }
  1647. else
  1648. {
  1649. width = width_;
  1650. height = height_;
  1651. }
  1652. return IntVector2(width, height);
  1653. }
  1654. void Graphics::AddGPUObject(GPUObject* object)
  1655. {
  1656. gpuObjects_.Push(object);
  1657. }
  1658. void Graphics::RemoveGPUObject(GPUObject* object)
  1659. {
  1660. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1661. {
  1662. if ((*i) == object)
  1663. {
  1664. gpuObjects_.Erase(i);
  1665. return;
  1666. }
  1667. }
  1668. }
  1669. unsigned Graphics::GetAlphaFormat()
  1670. {
  1671. return D3DFMT_A8;
  1672. }
  1673. unsigned Graphics::GetLuminanceFormat()
  1674. {
  1675. return D3DFMT_L8;
  1676. }
  1677. unsigned Graphics::GetLuminanceAlphaFormat()
  1678. {
  1679. return D3DFMT_A8L8;
  1680. }
  1681. unsigned Graphics::GetRGBFormat()
  1682. {
  1683. return D3DFMT_X8R8G8B8;
  1684. }
  1685. unsigned Graphics::GetRGBAFormat()
  1686. {
  1687. return D3DFMT_A8R8G8B8;
  1688. }
  1689. unsigned Graphics::GetDepthFormat()
  1690. {
  1691. return D3DFMT_R32F;
  1692. }
  1693. bool Graphics::OpenWindow(int width, int height)
  1694. {
  1695. WNDCLASS wc;
  1696. wc.style = CS_HREDRAW | CS_VREDRAW;
  1697. wc.lpfnWndProc = wndProc;
  1698. wc.cbClsExtra = 0;
  1699. wc.cbWndExtra = 0;
  1700. wc.hInstance = impl_->instance_;
  1701. wc.hIcon = LoadIcon(0, IDI_APPLICATION);
  1702. wc.hCursor = LoadCursor(0, IDC_ARROW);
  1703. wc.hbrBackground = 0;
  1704. wc.lpszMenuName = 0;
  1705. wc.lpszClassName = "D3DWindow";
  1706. RegisterClass(&wc);
  1707. RECT rect = {0, 0, width, height};
  1708. AdjustWindowRect(&rect, windowStyle, false);
  1709. impl_->window_ = CreateWindow("D3DWindow", windowTitle_.CString(), windowStyle, CW_USEDEFAULT, CW_USEDEFAULT,
  1710. rect.right, rect.bottom, 0, 0, impl_->instance_, 0);
  1711. if (!impl_->window_)
  1712. {
  1713. LOGERROR("Could not create window");
  1714. return false;
  1715. }
  1716. SetWindowLongPtr(impl_->window_, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
  1717. // Save window placement
  1718. WINDOWPLACEMENT wndpl;
  1719. wndpl.length = sizeof wndpl;
  1720. if (SUCCEEDED(GetWindowPlacement(impl_->window_, &wndpl)))
  1721. {
  1722. windowPosX_ = wndpl.rcNormalPosition.left;
  1723. windowPosY_ = wndpl.rcNormalPosition.top;
  1724. }
  1725. LOGINFO("Created application window");
  1726. return true;
  1727. }
  1728. bool Graphics::CreateInterface()
  1729. {
  1730. impl_->interface_ = Direct3DCreate9(D3D9b_SDK_VERSION);
  1731. if (!impl_->interface_)
  1732. {
  1733. LOGERROR("Could not create Direct3D9 interface");
  1734. return false;
  1735. }
  1736. if (FAILED(impl_->interface_->GetDeviceCaps(impl_->adapter_, impl_->deviceType_, &impl_->deviceCaps_)))
  1737. {
  1738. LOGERROR("Could not get Direct3D capabilities");
  1739. return false;
  1740. }
  1741. if (FAILED(impl_->interface_->GetAdapterIdentifier(impl_->adapter_, 0, &impl_->adapterIdentifier_)))
  1742. {
  1743. LOGERROR("Could not get Direct3D adapter identifier");
  1744. return false;
  1745. }
  1746. if (impl_->deviceCaps_.PixelShaderVersion < D3DPS_VERSION(2, 0))
  1747. {
  1748. LOGERROR("Shader model 2.0 display adapter is required");
  1749. return false;
  1750. }
  1751. // Check supported features: Shader Model 3, deferred / light prepass rendering, hardware depth texture, shadow map,
  1752. // dummy color surface, stream offset
  1753. if (!forceSM2_)
  1754. {
  1755. if ((impl_->deviceCaps_.VertexShaderVersion >= D3DVS_VERSION(3, 0)) && (impl_->deviceCaps_.PixelShaderVersion >=
  1756. D3DPS_VERSION(3, 0)))
  1757. hasSM3_ = true;
  1758. }
  1759. if (impl_->CheckFormatSupport(D3DFMT_R32F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1760. {
  1761. if (impl_->deviceCaps_.NumSimultaneousRTs >= 3)
  1762. deferredSupport_ = true;
  1763. if (impl_->deviceCaps_.NumSimultaneousRTs >= 2)
  1764. prepassSupport_ = true;
  1765. }
  1766. // Prefer NVIDIA style hardware depth Compared shadow maps if available
  1767. shadowMapFormat_ = D3DFMT_D16;
  1768. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1769. {
  1770. hardwareShadowSupport_ = true;
  1771. // Check for hires depth support
  1772. hiresShadowMapFormat_ = D3DFMT_D24X8;
  1773. if (impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1774. hiresShadowSupport_ = true;
  1775. else
  1776. hiresShadowMapFormat_ = shadowMapFormat_;
  1777. }
  1778. else
  1779. {
  1780. // ATI DF16 format needs manual depth compare in the shader
  1781. shadowMapFormat_ = MAKEFOURCC('D', 'F', '1', '6');
  1782. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1783. {
  1784. // Check for hires depth support
  1785. hiresShadowMapFormat_ = MAKEFOURCC('D', 'F', '2', '4');
  1786. if (impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1787. hiresShadowSupport_ = true;
  1788. else
  1789. hiresShadowMapFormat_ = shadowMapFormat_;
  1790. }
  1791. else
  1792. {
  1793. // No depth texture shadow map support -> no shadows at all
  1794. shadowMapFormat_ = 0;
  1795. hiresShadowMapFormat_ = 0;
  1796. }
  1797. }
  1798. // Check for Intel 4 Series with an old driver, enable manual shadow map compare in that case
  1799. if (shadowMapFormat_ == D3DFMT_D16)
  1800. {
  1801. if ((impl_->adapterIdentifier_.VendorId == 0x8086) && (impl_->adapterIdentifier_.DeviceId == 0x2a42) &&
  1802. (impl_->adapterIdentifier_.DriverVersion.QuadPart <= 0x0007000f000a05d0ULL))
  1803. hardwareShadowSupport_ = false;
  1804. }
  1805. dummyColorFormat_ = D3DFMT_A8R8G8B8;
  1806. D3DFORMAT nullFormat = (D3DFORMAT)MAKEFOURCC('N', 'U', 'L', 'L');
  1807. if (impl_->CheckFormatSupport(nullFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1808. dummyColorFormat_ = nullFormat;
  1809. else if (impl_->CheckFormatSupport(D3DFMT_R16F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1810. dummyColorFormat_ = D3DFMT_R16F;
  1811. else if (impl_->CheckFormatSupport(D3DFMT_R5G6B5, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1812. dummyColorFormat_ = D3DFMT_R5G6B5;
  1813. else if (impl_->CheckFormatSupport(D3DFMT_A4R4G4B4, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1814. dummyColorFormat_ = D3DFMT_A4R4G4B4;
  1815. if (impl_->deviceCaps_.DevCaps2 & D3DDEVCAPS2_STREAMOFFSET)
  1816. streamOffsetSupport_ = true;
  1817. return true;
  1818. }
  1819. bool Graphics::CreateDevice(unsigned adapter, unsigned deviceType)
  1820. {
  1821. DWORD behaviorFlags = 0;
  1822. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
  1823. {
  1824. behaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
  1825. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_PUREDEVICE)
  1826. behaviorFlags |= D3DCREATE_PUREDEVICE;
  1827. }
  1828. else
  1829. behaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  1830. if (FAILED(impl_->interface_->CreateDevice(
  1831. adapter, // adapter
  1832. (D3DDEVTYPE)deviceType, // device type
  1833. impl_->window_, // window associated with device
  1834. behaviorFlags, // vertex processing
  1835. &impl_->presentParams_, // present parameters
  1836. &impl_->device_))) // return created device
  1837. {
  1838. LOGERROR("Could not create Direct3D9 device");
  1839. return false;
  1840. }
  1841. impl_->adapter_ = adapter;
  1842. impl_->deviceType_ = (D3DDEVTYPE)deviceType;
  1843. OnDeviceReset();
  1844. LOGINFO("Created Direct3D9 device");
  1845. return true;
  1846. }
  1847. void Graphics::CreateRenderTargets()
  1848. {
  1849. if (mode_ != RENDER_FORWARD)
  1850. {
  1851. // In deferred rendering, the diffuse buffer stores diffuse albedo. In light prepass, it is used for light accumulation
  1852. if (!diffBuffer_)
  1853. {
  1854. diffBuffer_ = new Texture2D(context_);
  1855. diffBuffer_->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1856. }
  1857. if (!normalBuffer_)
  1858. {
  1859. normalBuffer_ = new Texture2D(context_);
  1860. normalBuffer_->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1861. }
  1862. if (!depthBuffer_)
  1863. {
  1864. depthBuffer_ = new Texture2D(context_);
  1865. depthBuffer_->SetSize(0, 0, GetDepthFormat(), TEXTURE_RENDERTARGET);
  1866. }
  1867. // If deferred mode temporal AA is used, reserve screen buffers
  1868. // (later we will probably want the screen buffer reserved in any case, to do for example distortion effects,
  1869. // which will also be useful in forward rendering)
  1870. if (multiSample_)
  1871. {
  1872. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1873. {
  1874. screenBuffers_[i] = new Texture2D(context_);
  1875. screenBuffers_[i]->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1876. }
  1877. }
  1878. else
  1879. {
  1880. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1881. screenBuffers_[i].Reset();
  1882. }
  1883. }
  1884. else
  1885. {
  1886. diffBuffer_.Reset();
  1887. normalBuffer_.Reset();
  1888. depthBuffer_.Reset();
  1889. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1890. screenBuffers_[i].Reset();
  1891. }
  1892. }
  1893. void Graphics::ResetDevice()
  1894. {
  1895. OnDeviceLost();
  1896. if (SUCCEEDED(impl_->device_->Reset(&impl_->presentParams_)))
  1897. {
  1898. deviceLost_ = false;
  1899. OnDeviceReset();
  1900. }
  1901. }
  1902. void Graphics::OnDeviceLost()
  1903. {
  1904. if (impl_->frameQuery_)
  1905. {
  1906. impl_->frameQuery_->Release();
  1907. impl_->frameQuery_ = 0;
  1908. }
  1909. if (impl_->defaultColorSurface_)
  1910. {
  1911. impl_->defaultColorSurface_->Release();
  1912. impl_->defaultColorSurface_ = 0;
  1913. }
  1914. if (impl_->defaultDepthStencilSurface_)
  1915. {
  1916. impl_->defaultDepthStencilSurface_->Release();
  1917. impl_->defaultDepthStencilSurface_ = 0;
  1918. }
  1919. for (unsigned i = 0; i < gpuObjects_.Size(); ++i)
  1920. gpuObjects_[i]->OnDeviceLost();
  1921. }
  1922. void Graphics::OnDeviceReset()
  1923. {
  1924. ResetCachedState();
  1925. // Create frame query
  1926. impl_->device_->CreateQuery(D3DQUERYTYPE_EVENT, &impl_->frameQuery_);
  1927. // Create deferred rendering buffers now
  1928. CreateRenderTargets();
  1929. for (unsigned i = 0; i < gpuObjects_.Size(); ++i)
  1930. gpuObjects_[i]->OnDeviceReset();
  1931. // Get default surfaces
  1932. impl_->device_->GetRenderTarget(0, &impl_->defaultColorSurface_);
  1933. impl_->device_->GetDepthStencilSurface(&impl_->defaultDepthStencilSurface_);
  1934. immediateBuffer_ = 0;
  1935. }
  1936. void Graphics::ResetCachedState()
  1937. {
  1938. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1939. {
  1940. vertexBuffers_[i] = 0;
  1941. streamOffsets_[i] = 0;
  1942. }
  1943. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1944. {
  1945. textures_[i] = 0;
  1946. impl_->minMagFilters_[i] = D3DTEXF_POINT;
  1947. impl_->mipFilters_[i] = D3DTEXF_NONE;
  1948. impl_->uAddressModes_[i] = D3DTADDRESS_WRAP;
  1949. impl_->vAddressModes_[i] = D3DTADDRESS_WRAP;
  1950. impl_->borderColors_[i] = Color(0.0f, 0.0f, 0.0f, 0.0f);
  1951. }
  1952. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1953. {
  1954. renderTargets_[i] = 0;
  1955. impl_->colorSurfaces_[i] = 0;
  1956. }
  1957. depthStencil_ = 0;
  1958. impl_->depthStencilSurface_ = 0;
  1959. viewport_ = IntRect(0, 0, width_, height_);
  1960. viewTexture_ = 0;
  1961. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1962. streamFrequencies_[i] = 1;
  1963. indexBuffer_ = 0;
  1964. vertexDeclaration_ = 0;
  1965. vertexShader_ = 0;
  1966. pixelShader_ = 0;
  1967. blendMode_ = BLEND_REPLACE;
  1968. alphaTest_ = false;
  1969. alphaTestMode_ = CMP_ALWAYS;
  1970. alphaRef_ = 0.0f;
  1971. textureAnisotropy_ = 1;
  1972. colorWrite_ = true;
  1973. cullMode_ = CULL_CCW;
  1974. constantDepthBias_ = 0.0f;
  1975. slopeScaledDepthBias_ = 0.0f;
  1976. depthTestMode_ = CMP_LESSEQUAL;
  1977. depthWrite_ = true;
  1978. fillMode_ = FILL_SOLID;
  1979. scissorTest_ = false;
  1980. scissorRect_ = IntRect::ZERO;
  1981. stencilTest_ = false;
  1982. stencilTestMode_ = CMP_ALWAYS;
  1983. stencilPass_ = OP_KEEP;
  1984. stencilFail_ = OP_KEEP;
  1985. stencilZFail_ = OP_KEEP;
  1986. stencilRef_ = 0;
  1987. stencilMask_ = M_MAX_UNSIGNED;
  1988. impl_->blendEnable_ = FALSE;
  1989. impl_->srcBlend_ = D3DBLEND_ONE;
  1990. impl_->destBlend_ = D3DBLEND_ZERO;
  1991. queryIssued_ = false;
  1992. }
  1993. void Graphics::InitializeShaderParameters()
  1994. {
  1995. // Initialize all parameters as unknown
  1996. for (unsigned i = 0; i < MAX_SHADER_PARAMETERS; ++i)
  1997. shaderRegisters_[i] = MAX_CONSTANT_REGISTERS;
  1998. // Map parameter names
  1999. shaderParameters_["CameraPos"] = VSP_CAMERAPOS;
  2000. shaderParameters_["CameraRot"] = VSP_CAMERAROT;
  2001. shaderParameters_["DepthMode"] = VSP_DEPTHMODE;
  2002. shaderParameters_["ElapsedTime"] = VSP_ELAPSEDTIME;
  2003. shaderParameters_["FrustumSize"] = VSP_FRUSTUMSIZE;
  2004. shaderParameters_["GBufferOffsets"] = VSP_GBUFFEROFFSETS;
  2005. shaderParameters_["Model"] = VSP_MODEL;
  2006. shaderParameters_["ShadowProj"] = VSP_SHADOWPROJ;
  2007. shaderParameters_["SpotProj"] = VSP_SPOTPROJ;
  2008. shaderParameters_["ViewProj"] = VSP_VIEWPROJ;
  2009. shaderParameters_["UOffset"] = VSP_UOFFSET;
  2010. shaderParameters_["VOffset"] = VSP_VOFFSET;
  2011. shaderParameters_["ViewRightVector"] = VSP_VIEWRIGHTVECTOR;
  2012. shaderParameters_["ViewUpVector"] = VSP_VIEWUPVECTOR;
  2013. shaderParameters_["SkinMatrices"] = VSP_SKINMATRICES;
  2014. shaderParameters_["AmbientColor"] = PSP_AMBIENTCOLOR;
  2015. shaderParameters_["AntiAliasWeights"] = PSP_ANTIALIASWEIGHTS;
  2016. shaderParameters_["CameraPosPS"] = PSP_CAMERAPOS;
  2017. shaderParameters_["ElapsedTimePS"] = PSP_ELAPSEDTIME;
  2018. shaderParameters_["FogColor"] = PSP_FOGCOLOR;
  2019. shaderParameters_["FogParams"] = PSP_FOGPARAMS;
  2020. shaderParameters_["GBufferOffsetsPS"] = PSP_GBUFFEROFFSETS;
  2021. shaderParameters_["GBufferViewport"] = PSP_GBUFFERVIEWPORT;
  2022. shaderParameters_["LightAtten"] = PSP_LIGHTATTEN;
  2023. shaderParameters_["LightColor"] = PSP_LIGHTCOLOR;
  2024. shaderParameters_["LightDir"] = PSP_LIGHTDIR;
  2025. shaderParameters_["LightPos"] = PSP_LIGHTPOS;
  2026. shaderParameters_["LightSplits"] = PSP_LIGHTSPLITS;
  2027. shaderParameters_["LightVecRot"] = PSP_LIGHTVECROT;
  2028. shaderParameters_["MatDiffColor"] = PSP_MATDIFFCOLOR;
  2029. shaderParameters_["MatEmissiveColor"] = PSP_MATEMISSIVECOLOR;
  2030. shaderParameters_["MatSpecProperties"] = PSP_MATSPECPROPERTIES;
  2031. shaderParameters_["SampleOffsets"] = PSP_SAMPLEOFFSETS;
  2032. shaderParameters_["ShadowIntensity"] = PSP_SHADOWINTENSITY;
  2033. shaderParameters_["ShadowProjPS"] = PSP_SHADOWPROJ;
  2034. shaderParameters_["SpotProjPS"] = PSP_SPOTPROJ;
  2035. shaderParameters_["ViewProjPS"] = PSP_VIEWPROJ;
  2036. // Map texture units
  2037. textureUnits_["NormalMap"] = TU_NORMAL;
  2038. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2039. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2040. textureUnits_["SpecMap"] = TU_SPECULAR;
  2041. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2042. textureUnits_["DetailMap"] = TU_DETAIL;
  2043. textureUnits_["EnvironmentMap"] = TU_ENVIRONMENT;
  2044. textureUnits_["EnvironmentCubeMap"] = TU_ENVIRONMENT;
  2045. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2046. textureUnits_["LightSpotMap"] = TU_LIGHTSPOT;
  2047. textureUnits_["LightCubeMap"] = TU_LIGHTSPOT;
  2048. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2049. textureUnits_["DiffBuffer"] = TU_DIFFBUFFER;
  2050. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  2051. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  2052. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  2053. }
  2054. void Graphics::HandleWindowMessage(StringHash eventType, VariantMap& eventData)
  2055. {
  2056. using namespace WindowMessage;
  2057. if (eventData[P_WINDOW].GetInt() != (int)impl_->window_)
  2058. return;
  2059. switch (eventData[P_MSG].GetInt())
  2060. {
  2061. case WM_CLOSE:
  2062. Close();
  2063. eventData[P_HANDLED] = true;
  2064. break;
  2065. case WM_DESTROY:
  2066. eventData[P_HANDLED] = true;
  2067. break;
  2068. }
  2069. }
  2070. LRESULT CALLBACK wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  2071. {
  2072. using namespace WindowMessage;
  2073. Graphics* graphics = reinterpret_cast<Graphics*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
  2074. if ((graphics) && (graphics->IsInitialized()))
  2075. {
  2076. VariantMap eventData;
  2077. eventData[P_WINDOW] = (int)hwnd;
  2078. eventData[P_MSG] = (int)msg;
  2079. eventData[P_WPARAM] = (int)wParam;
  2080. eventData[P_LPARAM] = (int)lParam;
  2081. eventData[P_HANDLED] = false;
  2082. graphics->SendEvent(E_WINDOWMESSAGE, eventData);
  2083. if (eventData[P_HANDLED].GetBool())
  2084. return 0;
  2085. }
  2086. return DefWindowProc(hwnd, msg, wParam, lParam);
  2087. }
  2088. void RegisterGraphicsLibrary(Context* context)
  2089. {
  2090. Animation::RegisterObject(context);
  2091. Material::RegisterObject(context);
  2092. Model::RegisterObject(context);
  2093. Shader::RegisterObject(context);
  2094. Technique::RegisterObject(context);
  2095. Texture2D::RegisterObject(context);
  2096. TextureCube::RegisterObject(context);
  2097. Camera::RegisterObject(context);
  2098. Drawable::RegisterObject(context);
  2099. Light::RegisterObject(context);
  2100. StaticModel::RegisterObject(context);
  2101. Skybox::RegisterObject(context);
  2102. AnimatedModel::RegisterObject(context);
  2103. AnimationController::RegisterObject(context);
  2104. BillboardSet::RegisterObject(context);
  2105. ParticleEmitter::RegisterObject(context);
  2106. DebugRenderer::RegisterObject(context);
  2107. Octree::RegisterObject(context);
  2108. Zone::RegisterObject(context);
  2109. }