Graphics.cpp 76 KB

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