D3D9Graphics.cpp 73 KB

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