D3D9Graphics.cpp 69 KB

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