Graphics.cpp 76 KB

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