2
0

Graphics.cpp 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469
  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::SetShaderParameter(ShaderParameter param, const bool* data, unsigned count)
  795. {
  796. unsigned index = shaderRegisters_[param];
  797. if (index >= MAX_CONSTANT_REGISTERS)
  798. return;
  799. if (param < PSP_AMBIENTCOLOR)
  800. impl_->device_->SetVertexShaderConstantB(index, (const BOOL*)data, count);
  801. else
  802. impl_->device_->SetPixelShaderConstantB(index, (const BOOL*)data, count);
  803. }
  804. void Graphics::SetShaderParameter(ShaderParameter param, const float* data, unsigned count)
  805. {
  806. unsigned index = shaderRegisters_[param];
  807. if (index >= MAX_CONSTANT_REGISTERS)
  808. return;
  809. if (param < PSP_AMBIENTCOLOR)
  810. impl_->device_->SetVertexShaderConstantF(index, data, count / 4);
  811. else
  812. impl_->device_->SetPixelShaderConstantF(index, data, count / 4);
  813. }
  814. void Graphics::SetShaderParameter(ShaderParameter param, const int* data, unsigned count)
  815. {
  816. unsigned index = shaderRegisters_[param];
  817. if (index >= MAX_CONSTANT_REGISTERS)
  818. return;
  819. if (param < PSP_AMBIENTCOLOR)
  820. impl_->device_->SetVertexShaderConstantI(index, data, count / 4);
  821. else
  822. impl_->device_->SetPixelShaderConstantI(index, data, count / 4);
  823. }
  824. void Graphics::SetShaderParameter(ShaderParameter param, float value)
  825. {
  826. unsigned index = shaderRegisters_[param];
  827. if (index >= MAX_CONSTANT_REGISTERS)
  828. return;
  829. float data[4];
  830. data[0] = value;
  831. data[1] = 0.0f;
  832. data[2] = 0.0f;
  833. data[3] = 0.0f;
  834. if (param < PSP_AMBIENTCOLOR)
  835. impl_->device_->SetVertexShaderConstantF(index, &data[0], 1);
  836. else
  837. impl_->device_->SetPixelShaderConstantF(index, &data[0], 1);
  838. }
  839. void Graphics::SetShaderParameter(ShaderParameter param, const Color& color)
  840. {
  841. unsigned index = shaderRegisters_[param];
  842. if (index >= MAX_CONSTANT_REGISTERS)
  843. return;
  844. if (param < PSP_AMBIENTCOLOR)
  845. impl_->device_->SetVertexShaderConstantF(index, color.GetData(), 1);
  846. else
  847. impl_->device_->SetPixelShaderConstantF(index, color.GetData(), 1);
  848. }
  849. void Graphics::SetShaderParameter(ShaderParameter param, const Matrix3& matrix)
  850. {
  851. unsigned index = shaderRegisters_[param];
  852. if (index >= MAX_CONSTANT_REGISTERS)
  853. return;
  854. float data[12];
  855. data[0] = matrix.m00_;
  856. data[1] = matrix.m01_;
  857. data[2] = matrix.m02_;
  858. data[3] = 0.0f;
  859. data[4] = matrix.m10_;
  860. data[5] = matrix.m11_;
  861. data[6] = matrix.m12_;
  862. data[7] = 0.0f;
  863. data[8] = matrix.m20_;
  864. data[9] = matrix.m21_;
  865. data[10] = matrix.m22_;
  866. data[11] = 0.0f;
  867. if (param < PSP_AMBIENTCOLOR)
  868. impl_->device_->SetVertexShaderConstantF(index, &data[0], 3);
  869. else
  870. impl_->device_->SetPixelShaderConstantF(index, &data[0], 3);
  871. }
  872. void Graphics::SetShaderParameter(ShaderParameter param, const Vector3& vector)
  873. {
  874. unsigned index = shaderRegisters_[param];
  875. if (index >= MAX_CONSTANT_REGISTERS)
  876. return;
  877. float data[4];
  878. data[0] = vector.x_;
  879. data[1] = vector.y_;
  880. data[2] = vector.z_;
  881. data[3] = 0.0f;
  882. if (param < PSP_AMBIENTCOLOR)
  883. impl_->device_->SetVertexShaderConstantF(index, &data[0], 1);
  884. else
  885. impl_->device_->SetPixelShaderConstantF(index, &data[0], 1);
  886. }
  887. void Graphics::SetShaderParameter(ShaderParameter param, const Matrix4& matrix)
  888. {
  889. unsigned index = shaderRegisters_[param];
  890. if (index >= MAX_CONSTANT_REGISTERS)
  891. return;
  892. if (param < PSP_AMBIENTCOLOR)
  893. impl_->device_->SetVertexShaderConstantF(index, matrix.GetData(), 4);
  894. else
  895. impl_->device_->SetPixelShaderConstantF(index, matrix.GetData(), 4);
  896. }
  897. void Graphics::SetShaderParameter(ShaderParameter param, const Vector4& vector)
  898. {
  899. unsigned index = shaderRegisters_[param];
  900. if (index >= MAX_CONSTANT_REGISTERS)
  901. return;
  902. if (param < PSP_AMBIENTCOLOR)
  903. impl_->device_->SetVertexShaderConstantF(index, vector.GetData(), 1);
  904. else
  905. impl_->device_->SetPixelShaderConstantF(index, vector.GetData(), 1);
  906. }
  907. void Graphics::SetShaderParameter(ShaderParameter param, const Matrix3x4& matrix)
  908. {
  909. unsigned index = shaderRegisters_[param];
  910. if (index >= MAX_CONSTANT_REGISTERS)
  911. return;
  912. if (param < PSP_AMBIENTCOLOR)
  913. impl_->device_->SetVertexShaderConstantF(index, matrix.GetData(), 3);
  914. else
  915. impl_->device_->SetPixelShaderConstantF(index, matrix.GetData(), 3);
  916. }
  917. bool Graphics::NeedParameterUpdate(ShaderParameter parameter, const void* source)
  918. {
  919. if (parameter < PSP_AMBIENTCOLOR)
  920. {
  921. if ((vertexShader_) && (vertexShader_->HasParameter(parameter)) && (lastShaderParameterSources_[parameter] != source))
  922. {
  923. lastShaderParameterSources_[parameter] = source;
  924. return true;
  925. }
  926. }
  927. else
  928. {
  929. if ((pixelShader_) && (pixelShader_->HasParameter(parameter)) && (lastShaderParameterSources_[parameter] != source))
  930. {
  931. lastShaderParameterSources_[parameter] = source;
  932. return true;
  933. }
  934. }
  935. return false;
  936. }
  937. bool Graphics::NeedTextureUnit(TextureUnit unit)
  938. {
  939. return (pixelShader_) && (pixelShader_->HasTextureUnit(unit));
  940. }
  941. void Graphics::ClearLastParameterSources()
  942. {
  943. for (unsigned i = 0; i < MAX_SHADER_PARAMETERS; ++i)
  944. lastShaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  945. }
  946. void Graphics::ClearTransformSources()
  947. {
  948. lastShaderParameterSources_[VSP_MODEL] = (const void*)M_MAX_UNSIGNED;
  949. lastShaderParameterSources_[VSP_VIEWPROJ] = (const void*)M_MAX_UNSIGNED;
  950. }
  951. void Graphics::SetTexture(unsigned index, Texture* texture)
  952. {
  953. if (index >= MAX_TEXTURE_UNITS)
  954. return;
  955. // Check if texture is currently bound as a render target. In that case, use its backup texture, or blank if not defined
  956. if (texture)
  957. {
  958. if ((renderTarget_[0]) && (renderTarget_[0]->GetParentTexture() == texture))
  959. texture = texture->GetBackupTexture();
  960. // Check also for the view texture, in case a specific rendering pass does not bind the destination render target,
  961. // but should still not sample it either
  962. else if (texture == viewTexture_)
  963. texture = texture->GetBackupTexture();
  964. }
  965. if (texture != texture_[index])
  966. {
  967. if (texture)
  968. impl_->device_->SetTexture(index, (IDirect3DBaseTexture9*)texture->GetGPUObject());
  969. else
  970. impl_->device_->SetTexture(index, 0);
  971. texture_[index] = texture;
  972. }
  973. if (texture)
  974. {
  975. TextureFilterMode filterMode = texture->GetFilterMode();
  976. if (filterMode == FILTER_DEFAULT)
  977. filterMode = defaultTextureFilterMode_;
  978. D3DTEXTUREFILTERTYPE minMag, mip;
  979. minMag = d3dMinMagFilter[filterMode];
  980. if (minMag != impl_->minMagFilter_[index])
  981. {
  982. impl_->device_->SetSamplerState(index, D3DSAMP_MAGFILTER, minMag);
  983. impl_->device_->SetSamplerState(index, D3DSAMP_MINFILTER, minMag);
  984. impl_->minMagFilter_[index] = minMag;
  985. }
  986. mip = d3dMipFilter[filterMode];
  987. if (mip != impl_->mipFilter_[index])
  988. {
  989. impl_->device_->SetSamplerState(index, D3DSAMP_MIPFILTER, mip);
  990. impl_->mipFilter_[index] = mip;
  991. }
  992. D3DTEXTUREADDRESS u, v;
  993. u = d3dAddressMode[texture->GetAddressMode(COORD_U)];
  994. if (u != impl_->uAddressMode_[index])
  995. {
  996. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSU, u);
  997. impl_->uAddressMode_[index] = u;
  998. }
  999. v = d3dAddressMode[texture->GetAddressMode(COORD_V)];
  1000. if (v != impl_->vAddressMode_[index])
  1001. {
  1002. impl_->device_->SetSamplerState(index, D3DSAMP_ADDRESSV, v);
  1003. impl_->vAddressMode_[index] = v;
  1004. }
  1005. if ((u == D3DTADDRESS_BORDER) || (v == D3DTADDRESS_BORDER))
  1006. {
  1007. const Color& borderColor = texture->GetBorderColor();
  1008. if (borderColor != impl_->borderColor_[index])
  1009. {
  1010. impl_->device_->SetSamplerState(index, D3DSAMP_BORDERCOLOR, borderColor.ToUInt());
  1011. impl_->borderColor_[index] = borderColor;
  1012. }
  1013. }
  1014. }
  1015. }
  1016. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  1017. {
  1018. defaultTextureFilterMode_ = mode;
  1019. }
  1020. void Graphics::ResetRenderTargets()
  1021. {
  1022. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1023. SetRenderTarget(i, (RenderSurface*)0);
  1024. SetDepthStencil((RenderSurface*)0);
  1025. SetViewport(IntRect(0, 0, width_, height_));
  1026. }
  1027. void Graphics::ResetRenderTarget(unsigned index)
  1028. {
  1029. SetRenderTarget(index, (RenderSurface*)0);
  1030. }
  1031. void Graphics::ResetDepthStencil()
  1032. {
  1033. SetDepthStencil((RenderSurface*)0);
  1034. }
  1035. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  1036. {
  1037. if (index >= MAX_RENDERTARGETS)
  1038. return;
  1039. IDirect3DSurface9* newColorSurface = 0;
  1040. if (renderTarget)
  1041. {
  1042. if (renderTarget->GetUsage() != TEXTURE_RENDERTARGET)
  1043. return;
  1044. newColorSurface = (IDirect3DSurface9*)renderTarget->GetSurface();
  1045. }
  1046. else
  1047. {
  1048. if (!index)
  1049. newColorSurface = impl_->defaultColorSurface_;
  1050. }
  1051. renderTarget_[index] = renderTarget;
  1052. if (newColorSurface != impl_->colorSurface_[index])
  1053. {
  1054. impl_->device_->SetRenderTarget(index, newColorSurface);
  1055. impl_->colorSurface_[index] = newColorSurface;
  1056. }
  1057. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1058. if (renderTarget)
  1059. {
  1060. Texture* parentTexture = renderTarget->GetParentTexture();
  1061. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1062. {
  1063. if (texture_[i] == parentTexture)
  1064. SetTexture(i, texture_[i]->GetBackupTexture());
  1065. }
  1066. }
  1067. if (!index)
  1068. {
  1069. // Viewport has been reset
  1070. IntVector2 rtSize = GetRenderTargetDimensions();
  1071. viewport_ = IntRect(0, 0, rtSize.x_, rtSize.y_);
  1072. // Disable scissor test, needs to be re-enabled by the user
  1073. SetScissorTest(false);
  1074. }
  1075. }
  1076. void Graphics::SetRenderTarget(unsigned index, Texture2D* renderTexture)
  1077. {
  1078. RenderSurface* renderTarget = 0;
  1079. if (renderTexture)
  1080. renderTarget = renderTexture->GetRenderSurface();
  1081. SetRenderTarget(index, renderTarget);
  1082. }
  1083. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1084. {
  1085. IDirect3DSurface9* newDepthStencilSurface = 0;
  1086. if ((depthStencil) && (depthStencil->GetUsage() == TEXTURE_DEPTHSTENCIL))
  1087. {
  1088. newDepthStencilSurface = (IDirect3DSurface9*)depthStencil->GetSurface();
  1089. depthStencil_ = depthStencil;
  1090. }
  1091. if (!newDepthStencilSurface)
  1092. {
  1093. newDepthStencilSurface = impl_->defaultDepthStencilSurface_;
  1094. depthStencil_ = 0;
  1095. }
  1096. if (newDepthStencilSurface != impl_->depthStencilSurface_)
  1097. {
  1098. impl_->device_->SetDepthStencilSurface(newDepthStencilSurface);
  1099. impl_->depthStencilSurface_ = newDepthStencilSurface;
  1100. }
  1101. }
  1102. void Graphics::SetDepthStencil(Texture2D* depthTexture)
  1103. {
  1104. RenderSurface* depthStencil = 0;
  1105. if (depthTexture)
  1106. depthStencil = depthTexture->GetRenderSurface();
  1107. SetDepthStencil(depthStencil);
  1108. }
  1109. void Graphics::SetViewport(const IntRect& rect)
  1110. {
  1111. IntVector2 size = GetRenderTargetDimensions();
  1112. IntRect rectCopy = rect;
  1113. if (rectCopy.right_ <= rectCopy.left_)
  1114. rectCopy.right_ = rectCopy.left_ + 1;
  1115. if (rectCopy.bottom_ <= rectCopy.top_)
  1116. rectCopy.bottom_ = rectCopy.top_ + 1;
  1117. rectCopy.left_ = Clamp(rectCopy.left_, 0, size.x_);
  1118. rectCopy.top_ = Clamp(rectCopy.top_, 0, size.y_);
  1119. rectCopy.right_ = Clamp(rectCopy.right_, 0, size.x_);
  1120. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, size.y_);
  1121. D3DVIEWPORT9 vp;
  1122. vp.MinZ = 0.0f;
  1123. vp.MaxZ = 1.0f;
  1124. vp.X = rectCopy.left_;
  1125. vp.Y = rectCopy.top_;
  1126. vp.Width = rectCopy.right_ - rectCopy.left_;
  1127. vp.Height = rectCopy.bottom_ - rectCopy.top_;
  1128. impl_->device_->SetViewport(&vp);
  1129. viewport_ = rectCopy;
  1130. // Disable scissor test, needs to be re-enabled by the user
  1131. SetScissorTest(false);
  1132. }
  1133. void Graphics::SetViewTexture(Texture* texture)
  1134. {
  1135. viewTexture_ = texture;
  1136. // Check for the view texture being currently bound
  1137. if (texture)
  1138. {
  1139. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1140. {
  1141. if (texture_[i] == texture)
  1142. SetTexture(i, texture_[i]->GetBackupTexture());
  1143. }
  1144. }
  1145. }
  1146. void Graphics::SetAlphaTest(bool enable, CompareMode mode, float alphaRef)
  1147. {
  1148. if (enable != alphaTest_)
  1149. {
  1150. impl_->device_->SetRenderState(D3DRS_ALPHATESTENABLE, enable ? TRUE : FALSE);
  1151. alphaTest_ = enable;
  1152. }
  1153. if (enable)
  1154. {
  1155. if (mode != alphaTestMode_)
  1156. {
  1157. impl_->device_->SetRenderState(D3DRS_ALPHAFUNC, d3dCmpFunc[mode]);
  1158. alphaTestMode_ = mode;
  1159. }
  1160. if (alphaRef < 0.0f)
  1161. alphaRef = 0.0f;
  1162. if (alphaRef > 1.0f)
  1163. alphaRef = 1.0f;
  1164. if (alphaRef != alphaRef_)
  1165. {
  1166. impl_->device_->SetRenderState(D3DRS_ALPHAREF, (DWORD)(alphaRef * 255.0f));
  1167. alphaRef_ = alphaRef;
  1168. }
  1169. }
  1170. }
  1171. void Graphics::SetTextureAnisotropy(unsigned level)
  1172. {
  1173. if (level < 1)
  1174. level = 1;
  1175. if (level != textureAnisotropy_)
  1176. {
  1177. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1178. impl_->device_->SetSamplerState(i, D3DSAMP_MAXANISOTROPY, level);
  1179. textureAnisotropy_ = level;
  1180. }
  1181. }
  1182. void Graphics::SetBlendMode(BlendMode mode)
  1183. {
  1184. if (mode != blendMode_)
  1185. {
  1186. if (d3dBlendEnable[mode] != impl_->blendEnable_)
  1187. {
  1188. impl_->device_->SetRenderState(D3DRS_ALPHABLENDENABLE, d3dBlendEnable[mode]);
  1189. impl_->blendEnable_ = d3dBlendEnable[mode];
  1190. }
  1191. if (impl_->blendEnable_)
  1192. {
  1193. if (d3dSrcBlend[mode] != impl_->srcBlend_)
  1194. {
  1195. impl_->device_->SetRenderState(D3DRS_SRCBLEND, d3dSrcBlend[mode]);
  1196. impl_->srcBlend_ = d3dSrcBlend[mode];
  1197. }
  1198. if (d3dDestBlend[mode] != impl_->destBlend_)
  1199. {
  1200. impl_->device_->SetRenderState(D3DRS_DESTBLEND, d3dDestBlend[mode]);
  1201. impl_->destBlend_ = d3dDestBlend[mode];
  1202. }
  1203. }
  1204. blendMode_ = mode;
  1205. }
  1206. }
  1207. void Graphics::SetColorWrite(bool enable)
  1208. {
  1209. if (enable != colorWrite_)
  1210. {
  1211. impl_->device_->SetRenderState(D3DRS_COLORWRITEENABLE, enable ? D3DCOLORWRITEENABLE_RED |
  1212. D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA : 0);
  1213. colorWrite_ = enable;
  1214. }
  1215. }
  1216. void Graphics::SetCullMode(CullMode mode)
  1217. {
  1218. if (mode != cullMode_)
  1219. {
  1220. impl_->device_->SetRenderState(D3DRS_CULLMODE, d3dCullMode[mode]);
  1221. cullMode_ = mode;
  1222. }
  1223. }
  1224. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1225. {
  1226. if (constantBias != constantDepthBias_)
  1227. {
  1228. impl_->device_->SetRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&constantBias));
  1229. constantDepthBias_ = constantBias;
  1230. }
  1231. if (slopeScaledBias != slopeScaledDepthBias_)
  1232. {
  1233. impl_->device_->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&slopeScaledBias));
  1234. slopeScaledDepthBias_ = slopeScaledBias;
  1235. }
  1236. }
  1237. void Graphics::SetDepthTest(CompareMode mode)
  1238. {
  1239. if (mode != depthTestMode_)
  1240. {
  1241. impl_->device_->SetRenderState(D3DRS_ZFUNC, d3dCmpFunc[mode]);
  1242. depthTestMode_ = mode;
  1243. }
  1244. }
  1245. void Graphics::SetDepthWrite(bool enable)
  1246. {
  1247. if (enable != depthWrite_)
  1248. {
  1249. impl_->device_->SetRenderState(D3DRS_ZWRITEENABLE, enable ? TRUE : FALSE);
  1250. depthWrite_ = enable;
  1251. }
  1252. }
  1253. void Graphics::SetFillMode(FillMode mode)
  1254. {
  1255. if (mode != fillMode_)
  1256. {
  1257. impl_->device_->SetRenderState(D3DRS_FILLMODE, d3dFillMode[mode]);
  1258. fillMode_ = mode;
  1259. }
  1260. }
  1261. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1262. {
  1263. // During some light rendering loops, a full rect is Toggled on/off repeatedly.
  1264. // Disable scissor in that case to reduce state changes
  1265. if (rect == Rect::FULL)
  1266. enable = false;
  1267. // Check for illegal rect, disable in that case
  1268. if ((rect.max_.x_ < rect.min_.x_) || (rect.max_.y_ < rect.min_.y_))
  1269. enable = false;
  1270. if (enable)
  1271. {
  1272. IntVector2 rtSize(GetRenderTargetDimensions());
  1273. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1274. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1275. IntRect intRect;
  1276. int expand = borderInclusive ? 1 : 0;
  1277. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1278. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1279. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1280. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1281. if (intRect.right_ == intRect.left_)
  1282. intRect.right_++;
  1283. if (intRect.bottom_ == intRect.top_)
  1284. intRect.bottom_++;
  1285. if ((intRect.right_ < intRect.left_) || (intRect.bottom_ < intRect.top_))
  1286. enable = false;
  1287. if ((enable) && (scissorRect_ != intRect))
  1288. {
  1289. RECT d3dRect;
  1290. d3dRect.left = intRect.left_;
  1291. d3dRect.top = intRect.top_;
  1292. d3dRect.right = intRect.right_;
  1293. d3dRect.bottom = intRect.bottom_;
  1294. impl_->device_->SetScissorRect(&d3dRect);
  1295. scissorRect_ = intRect;
  1296. }
  1297. }
  1298. else
  1299. scissorRect_ = IntRect::ZERO;
  1300. if (enable != scissorTest_)
  1301. {
  1302. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1303. scissorTest_ = enable;
  1304. }
  1305. }
  1306. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1307. {
  1308. IntVector2 rtSize(GetRenderTargetDimensions());
  1309. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1310. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1311. // Full scissor is same as disabling the test
  1312. if ((rect.left_ <= 0) && (rect.right_ >= viewSize.x_) && (rect.top_ <= 0) && (rect.bottom_ >= viewSize.y_))
  1313. enable = false;
  1314. // Check for illegal rect, disable in that case
  1315. if ((rect.right_ < rect.left_) || (rect.bottom_ < rect.top_))
  1316. enable = false;
  1317. if (enable)
  1318. {
  1319. IntRect intRect;
  1320. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1321. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1322. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1323. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1324. if (intRect.right_ == intRect.left_)
  1325. intRect.right_++;
  1326. if (intRect.bottom_ == intRect.top_)
  1327. intRect.bottom_++;
  1328. if ((intRect.right_ < intRect.left_) || (intRect.bottom_ < intRect.top_))
  1329. enable = false;
  1330. if ((enable) && (scissorRect_ != intRect))
  1331. {
  1332. RECT d3dRect;
  1333. d3dRect.left = intRect.left_;
  1334. d3dRect.top = intRect.top_;
  1335. d3dRect.right = intRect.right_;
  1336. d3dRect.bottom = intRect.bottom_;
  1337. impl_->device_->SetScissorRect(&d3dRect);
  1338. scissorRect_ = intRect;
  1339. }
  1340. }
  1341. else
  1342. scissorRect_ = IntRect::ZERO;
  1343. if (enable != scissorTest_)
  1344. {
  1345. impl_->device_->SetRenderState(D3DRS_SCISSORTESTENABLE, enable ? TRUE : FALSE);
  1346. scissorTest_ = enable;
  1347. }
  1348. }
  1349. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned stencilMask)
  1350. {
  1351. if (enable != stencilTest_)
  1352. {
  1353. impl_->device_->SetRenderState(D3DRS_STENCILENABLE, enable ? TRUE : FALSE);
  1354. stencilTest_ = enable;
  1355. }
  1356. if (enable)
  1357. {
  1358. if (mode != stencilTestMode_)
  1359. {
  1360. impl_->device_->SetRenderState(D3DRS_STENCILFUNC, d3dCmpFunc[mode]);
  1361. stencilTestMode_ = mode;
  1362. }
  1363. if (pass != stencilPass_)
  1364. {
  1365. impl_->device_->SetRenderState(D3DRS_STENCILPASS, d3dStencilOp[pass]);
  1366. stencilPass_ = pass;
  1367. }
  1368. if (fail != stencilFail_)
  1369. {
  1370. impl_->device_->SetRenderState(D3DRS_STENCILFAIL, d3dStencilOp[fail]);
  1371. stencilFail_ = fail;
  1372. }
  1373. if (zFail != stencilZFail_)
  1374. {
  1375. impl_->device_->SetRenderState(D3DRS_STENCILZFAIL, d3dStencilOp[zFail]);
  1376. stencilZFail_ = zFail;
  1377. }
  1378. if (stencilRef != stencilRef_)
  1379. {
  1380. impl_->device_->SetRenderState(D3DRS_STENCILREF, stencilRef);
  1381. stencilRef_ = stencilRef;
  1382. }
  1383. if (stencilMask != stencilMask_)
  1384. {
  1385. impl_->device_->SetRenderState(D3DRS_STENCILMASK, stencilMask);
  1386. stencilMask_ = stencilMask;
  1387. }
  1388. }
  1389. }
  1390. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1391. {
  1392. if ((index < MAX_VERTEX_STREAMS) && (streamFrequency_[index] != frequency))
  1393. {
  1394. impl_->device_->SetStreamSourceFreq(index, frequency);
  1395. streamFrequency_[index] = frequency;
  1396. }
  1397. }
  1398. void Graphics::ResetStreamFrequencies()
  1399. {
  1400. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1401. {
  1402. if (streamFrequency_[i] != 1)
  1403. {
  1404. impl_->device_->SetStreamSourceFreq(i, 1);
  1405. streamFrequency_[i] = 1;
  1406. }
  1407. }
  1408. }
  1409. bool Graphics::BeginImmediate(PrimitiveType type, unsigned vertexCount, unsigned elementMask)
  1410. {
  1411. if (immediateBuffer_)
  1412. {
  1413. LOGERROR("New immediate draw operation started before ending the last one");
  1414. return false;
  1415. }
  1416. if (!(elementMask & MASK_POSITION))
  1417. {
  1418. LOGERROR("Immediate draw operation must contain vertex positions");
  1419. return false;
  1420. }
  1421. if (!vertexCount)
  1422. return true;
  1423. // Start from default size, ensure that buffer is big enough to hold the immediate draw operation
  1424. unsigned newSize = IMMEDIATE_BUFFER_DEFAULT_SIZE;
  1425. while (newSize < vertexCount)
  1426. newSize <<= 1;
  1427. // See if buffer exists for this vertex format. If not, create new
  1428. if (immediatevertexBuffer_.Find(elementMask) == immediatevertexBuffer_.End())
  1429. {
  1430. LOGDEBUG("Created immediate vertex buffer");
  1431. VertexBuffer* newBuffer = new VertexBuffer(context_);
  1432. newBuffer->SetSize(newSize, elementMask, true);
  1433. immediatevertexBuffer_[elementMask] = newBuffer;
  1434. immediateVertexBufferPos_[elementMask] = 0;
  1435. }
  1436. // Resize buffer if it is too small
  1437. VertexBuffer* buffer = immediatevertexBuffer_[elementMask];
  1438. if (buffer->GetVertexCount() < newSize)
  1439. {
  1440. LOGDEBUG("Resized immediate vertex buffer to " + String(newSize));
  1441. buffer->SetSize(newSize, elementMask);
  1442. immediateVertexBufferPos_[elementMask] = 0;
  1443. }
  1444. // Get the current lock position for the buffer
  1445. unsigned bufferPos = immediateVertexBufferPos_[elementMask];
  1446. if (bufferPos + vertexCount >= buffer->GetVertexCount())
  1447. bufferPos = 0;
  1448. LockMode lockMode = LOCK_DISCARD;
  1449. if (bufferPos != 0)
  1450. lockMode = LOCK_NOOVERWRITE;
  1451. // Note: the data pointer gets pre-decremented here, because the first call to DefineVertex() will increment it
  1452. immediateDataPtr_ = ((unsigned char*)buffer->Lock(bufferPos, vertexCount, lockMode)) - buffer->GetVertexSize();
  1453. immediateBuffer_ = buffer;
  1454. immediateType_= type;
  1455. immediateStartPos_ = bufferPos;
  1456. immediateVertexCount_ = vertexCount;
  1457. immediateCurrentVertex_ = 0;
  1458. // Store new buffer position for next lock into the same buffer
  1459. bufferPos += vertexCount;
  1460. if (bufferPos >= buffer->GetVertexCount())
  1461. bufferPos = 0;
  1462. immediateVertexBufferPos_[elementMask] = bufferPos;
  1463. return true;
  1464. }
  1465. bool Graphics::DefineVertex(const Vector3& vertex)
  1466. {
  1467. if ((!immediateBuffer_) || (immediateCurrentVertex_ >= immediateVertexCount_))
  1468. return false;
  1469. immediateDataPtr_ += immediateBuffer_->GetVertexSize();
  1470. ++immediateCurrentVertex_;
  1471. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_POSITION));
  1472. const float* src = vertex.GetData();
  1473. dest[0] = src[0];
  1474. dest[1] = src[1];
  1475. dest[2] = src[2];
  1476. return true;
  1477. }
  1478. bool Graphics::DefineNormal(const Vector3& normal)
  1479. {
  1480. if ((!immediateBuffer_) ||(!(immediateBuffer_->GetElementMask() & MASK_NORMAL)) || (!immediateCurrentVertex_))
  1481. return false;
  1482. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_NORMAL));
  1483. const float* src = normal.GetData();
  1484. dest[0] = src[0];
  1485. dest[1] = src[1];
  1486. dest[2] = src[2];
  1487. return true;
  1488. }
  1489. bool Graphics::DefineTexCoord(const Vector2& texCoord)
  1490. {
  1491. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_TEXCOORD1)) || (!immediateCurrentVertex_))
  1492. return false;
  1493. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_TEXCOORD1));
  1494. const float* src = texCoord.GetData();
  1495. dest[0] = src[0];
  1496. dest[1] = src[1];
  1497. return true;
  1498. }
  1499. bool Graphics::DefineColor(const Color& color)
  1500. {
  1501. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_COLOR)) || (!immediateCurrentVertex_))
  1502. return false;
  1503. unsigned* dest = (unsigned*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_COLOR));
  1504. *dest = color.ToUInt();
  1505. return true;
  1506. }
  1507. bool Graphics::DefineColor(unsigned color)
  1508. {
  1509. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_COLOR)) || (!immediateCurrentVertex_))
  1510. return false;
  1511. unsigned* dest = (unsigned*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_COLOR));
  1512. *dest = color;
  1513. return true;
  1514. }
  1515. void Graphics::EndImmediate()
  1516. {
  1517. if (immediateBuffer_)
  1518. {
  1519. immediateBuffer_->Unlock();
  1520. SetVertexBuffer(immediateBuffer_);
  1521. Draw(immediateType_, immediateStartPos_, immediateVertexCount_);
  1522. immediateBuffer_ = 0;
  1523. }
  1524. }
  1525. void Graphics::SetForceSM2(bool enable)
  1526. {
  1527. // Note: this only has effect before calling SetMode() for the first time
  1528. forceSM2_ = enable;
  1529. }
  1530. bool Graphics::IsInitialized() const
  1531. {
  1532. return (impl_->window_ != 0) && (impl_->GetDevice() != 0);
  1533. }
  1534. unsigned char* Graphics::GetImmediateDataPtr() const
  1535. {
  1536. if (!immediateBuffer_)
  1537. {
  1538. LOGERROR("Immediate draw operation not started");
  1539. return 0;
  1540. }
  1541. // Pointer was pre-decremented in BeginImmediate(). Undo that now
  1542. return immediateDataPtr_ + immediateBuffer_->GetVertexSize();
  1543. }
  1544. unsigned Graphics::GetWindowHandle() const
  1545. {
  1546. return (unsigned)impl_->window_;
  1547. }
  1548. PODVector<IntVector2> Graphics::GetResolutions() const
  1549. {
  1550. PODVector<IntVector2> ret;
  1551. if (!impl_->interface_)
  1552. return ret;
  1553. D3DFORMAT fullscreenFormat = impl_->GetDesktopFormat();
  1554. unsigned numModes = impl_->interface_->GetAdapterModeCount(impl_->adapter_, fullscreenFormat);
  1555. D3DDISPLAYMODE displayMode;
  1556. for (unsigned i = 0; i < numModes; ++i)
  1557. {
  1558. if (FAILED(impl_->interface_->EnumAdapterModes(impl_->adapter_, fullscreenFormat, i, &displayMode)))
  1559. continue;
  1560. if (displayMode.Format != fullscreenFormat)
  1561. continue;
  1562. IntVector2 newMode(displayMode.Width, displayMode.Height);
  1563. // Check for duplicate before storing
  1564. bool unique = true;
  1565. for (unsigned j = 0; j < ret.Size(); ++j)
  1566. {
  1567. if (ret[j] == newMode)
  1568. {
  1569. unique = false;
  1570. break;
  1571. }
  1572. }
  1573. if (unique)
  1574. ret.Push(newMode);
  1575. }
  1576. return ret;
  1577. }
  1578. PODVector<int> Graphics::GetMultiSampleLevels() const
  1579. {
  1580. PODVector<int> ret;
  1581. // No multisampling always supported
  1582. ret.Push(0);
  1583. if (!impl_->interface_)
  1584. return ret;
  1585. for (unsigned i = (int)D3DMULTISAMPLE_2_SAMPLES; i < (int)D3DMULTISAMPLE_16_SAMPLES; ++i)
  1586. {
  1587. if (SUCCEEDED(impl_->interface_->CheckDeviceMultiSampleType(impl_->adapter_, impl_->deviceType_, D3DFMT_R8G8B8, FALSE,
  1588. (D3DMULTISAMPLE_TYPE)i, NULL)))
  1589. ret.Push(i);
  1590. }
  1591. return ret;
  1592. }
  1593. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1594. {
  1595. return index < MAX_VERTEX_STREAMS ? vertexBuffer_[index] : 0;
  1596. }
  1597. ShaderParameter Graphics::GetShaderParameter(const String& name)
  1598. {
  1599. Map<String, ShaderParameter>::Iterator i = shaderParameters_.Find(name);
  1600. if (i != shaderParameters_.End())
  1601. return i->second_;
  1602. else
  1603. return MAX_SHADER_PARAMETERS;
  1604. }
  1605. TextureUnit Graphics::GetTextureUnit(const String& name)
  1606. {
  1607. Map<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1608. if (i != textureUnits_.End())
  1609. return i->second_;
  1610. else
  1611. return MAX_TEXTURE_UNITS;
  1612. }
  1613. const String& Graphics::GetShaderParameterName(ShaderParameter parameter)
  1614. {
  1615. for (Map<String, ShaderParameter>::Iterator i = shaderParameters_.Begin(); i != shaderParameters_.End(); ++i)
  1616. {
  1617. if (i->second_ == parameter)
  1618. return i->first_;
  1619. }
  1620. return noParameter;
  1621. }
  1622. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1623. {
  1624. for (Map<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1625. {
  1626. if (i->second_ == unit)
  1627. return i->first_;
  1628. }
  1629. return noParameter;
  1630. }
  1631. Texture* Graphics::GetTexture(unsigned index) const
  1632. {
  1633. return index < MAX_TEXTURE_UNITS ? texture_[index] : 0;
  1634. }
  1635. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1636. {
  1637. return index < MAX_RENDERTARGETS ? renderTarget_[index] : 0;
  1638. }
  1639. unsigned Graphics::GetStreamFrequency(unsigned index) const
  1640. {
  1641. return index < MAX_VERTEX_STREAMS ? streamFrequency_[index] : 0;
  1642. }
  1643. IntVector2 Graphics::GetRenderTargetDimensions() const
  1644. {
  1645. int width, height;
  1646. if (renderTarget_[0])
  1647. {
  1648. width = renderTarget_[0]->GetWidth();
  1649. height = renderTarget_[0]->GetHeight();
  1650. }
  1651. else
  1652. {
  1653. width = width_;
  1654. height = height_;
  1655. }
  1656. return IntVector2(width, height);
  1657. }
  1658. void Graphics::AddGPUObject(GPUObject* object)
  1659. {
  1660. gpuObjects_.Push(object);
  1661. }
  1662. void Graphics::RemoveGPUObject(GPUObject* object)
  1663. {
  1664. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1665. {
  1666. if ((*i) == object)
  1667. {
  1668. gpuObjects_.Erase(i);
  1669. return;
  1670. }
  1671. }
  1672. }
  1673. unsigned Graphics::GetAlphaFormat()
  1674. {
  1675. return D3DFMT_A8;
  1676. }
  1677. unsigned Graphics::GetLuminanceFormat()
  1678. {
  1679. return D3DFMT_L8;
  1680. }
  1681. unsigned Graphics::GetLuminanceAlphaFormat()
  1682. {
  1683. return D3DFMT_A8L8;
  1684. }
  1685. unsigned Graphics::GetRGBFormat()
  1686. {
  1687. return D3DFMT_X8R8G8B8;
  1688. }
  1689. unsigned Graphics::GetRGBAFormat()
  1690. {
  1691. return D3DFMT_A8R8G8B8;
  1692. }
  1693. unsigned Graphics::GetDepthFormat()
  1694. {
  1695. return D3DFMT_R32F;
  1696. }
  1697. bool Graphics::OpenWindow(int width, int height)
  1698. {
  1699. WNDCLASS wc;
  1700. wc.style = CS_HREDRAW | CS_VREDRAW;
  1701. wc.lpfnWndProc = wndProc;
  1702. wc.cbClsExtra = 0;
  1703. wc.cbWndExtra = 0;
  1704. wc.hInstance = impl_->instance_;
  1705. wc.hIcon = LoadIcon(0, IDI_APPLICATION);
  1706. wc.hCursor = LoadCursor(0, IDC_ARROW);
  1707. wc.hbrBackground = 0;
  1708. wc.lpszMenuName = 0;
  1709. wc.lpszClassName = "D3DWindow";
  1710. RegisterClass(&wc);
  1711. RECT rect = {0, 0, width, height};
  1712. AdjustWindowRect(&rect, windowStyle, false);
  1713. impl_->window_ = CreateWindow("D3DWindow", windowTitle_.CString(), windowStyle, CW_USEDEFAULT, CW_USEDEFAULT,
  1714. rect.right, rect.bottom, 0, 0, impl_->instance_, 0);
  1715. if (!impl_->window_)
  1716. {
  1717. LOGERROR("Could not create window");
  1718. return false;
  1719. }
  1720. SetWindowLongPtr(impl_->window_, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
  1721. // Save window placement
  1722. WINDOWPLACEMENT wndpl;
  1723. wndpl.length = sizeof wndpl;
  1724. if (SUCCEEDED(GetWindowPlacement(impl_->window_, &wndpl)))
  1725. {
  1726. windowPosX_ = wndpl.rcNormalPosition.left;
  1727. windowPosY_ = wndpl.rcNormalPosition.top;
  1728. }
  1729. LOGINFO("Created application window");
  1730. return true;
  1731. }
  1732. bool Graphics::CreateInterface()
  1733. {
  1734. impl_->interface_ = Direct3DCreate9(D3D9b_SDK_VERSION);
  1735. if (!impl_->interface_)
  1736. {
  1737. LOGERROR("Could not create Direct3D9 interface");
  1738. return false;
  1739. }
  1740. if (FAILED(impl_->interface_->GetDeviceCaps(impl_->adapter_, impl_->deviceType_, &impl_->deviceCaps_)))
  1741. {
  1742. LOGERROR("Could not get Direct3D capabilities");
  1743. return false;
  1744. }
  1745. if (FAILED(impl_->interface_->GetAdapterIdentifier(impl_->adapter_, 0, &impl_->adapterIdentifier_)))
  1746. {
  1747. LOGERROR("Could not get Direct3D adapter identifier");
  1748. return false;
  1749. }
  1750. if (impl_->deviceCaps_.PixelShaderVersion < D3DPS_VERSION(2, 0))
  1751. {
  1752. LOGERROR("Shader model 2.0 display adapter is required");
  1753. return false;
  1754. }
  1755. // Check supported features: Shader Model 3, deferred / light prepass rendering, hardware depth texture, shadow map,
  1756. // dummy color surface, stream offset
  1757. if (!forceSM2_)
  1758. {
  1759. if ((impl_->deviceCaps_.VertexShaderVersion >= D3DVS_VERSION(3, 0)) && (impl_->deviceCaps_.PixelShaderVersion >=
  1760. D3DPS_VERSION(3, 0)))
  1761. hasSM3_ = true;
  1762. }
  1763. if (impl_->CheckFormatSupport(D3DFMT_R32F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1764. {
  1765. if (impl_->deviceCaps_.NumSimultaneousRTs >= 3)
  1766. deferredSupport_ = true;
  1767. if (impl_->deviceCaps_.NumSimultaneousRTs >= 2)
  1768. prepassSupport_ = true;
  1769. }
  1770. // Prefer NVIDIA style hardware depth Compared shadow maps if available
  1771. shadowMapFormat_ = D3DFMT_D16;
  1772. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1773. {
  1774. hardwareShadowSupport_ = true;
  1775. // Check for hires depth support
  1776. hiresShadowMapFormat_ = D3DFMT_D24X8;
  1777. if (impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1778. hiresShadowSupport_ = true;
  1779. else
  1780. hiresShadowMapFormat_ = shadowMapFormat_;
  1781. }
  1782. else
  1783. {
  1784. // ATI DF16 format needs manual depth compare in the shader
  1785. shadowMapFormat_ = MAKEFOURCC('D', 'F', '1', '6');
  1786. if (impl_->CheckFormatSupport((D3DFORMAT)shadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1787. {
  1788. // Check for hires depth support
  1789. hiresShadowMapFormat_ = MAKEFOURCC('D', 'F', '2', '4');
  1790. if (impl_->CheckFormatSupport((D3DFORMAT)hiresShadowMapFormat_, D3DUSAGE_DEPTHSTENCIL, D3DRTYPE_TEXTURE))
  1791. hiresShadowSupport_ = true;
  1792. else
  1793. hiresShadowMapFormat_ = shadowMapFormat_;
  1794. }
  1795. else
  1796. {
  1797. // No depth texture shadow map support -> no shadows at all
  1798. shadowMapFormat_ = 0;
  1799. hiresShadowMapFormat_ = 0;
  1800. }
  1801. }
  1802. // Check for Intel 4 Series with an old driver, enable manual shadow map compare in that case
  1803. if (shadowMapFormat_ == D3DFMT_D16)
  1804. {
  1805. if ((impl_->adapterIdentifier_.VendorId == 0x8086) && (impl_->adapterIdentifier_.DeviceId == 0x2a42) &&
  1806. (impl_->adapterIdentifier_.DriverVersion.QuadPart <= 0x0007000f000a05d0ULL))
  1807. hardwareShadowSupport_ = false;
  1808. }
  1809. dummyColorFormat_ = D3DFMT_A8R8G8B8;
  1810. D3DFORMAT nullFormat = (D3DFORMAT)MAKEFOURCC('N', 'U', 'L', 'L');
  1811. if (impl_->CheckFormatSupport(nullFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1812. dummyColorFormat_ = nullFormat;
  1813. else if (impl_->CheckFormatSupport(D3DFMT_R16F, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1814. dummyColorFormat_ = D3DFMT_R16F;
  1815. else if (impl_->CheckFormatSupport(D3DFMT_R5G6B5, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1816. dummyColorFormat_ = D3DFMT_R5G6B5;
  1817. else if (impl_->CheckFormatSupport(D3DFMT_A4R4G4B4, D3DUSAGE_RENDERTARGET, D3DRTYPE_TEXTURE))
  1818. dummyColorFormat_ = D3DFMT_A4R4G4B4;
  1819. if (impl_->deviceCaps_.DevCaps2 & D3DDEVCAPS2_STREAMOFFSET)
  1820. streamOffsetSupport_ = true;
  1821. return true;
  1822. }
  1823. bool Graphics::CreateDevice(unsigned adapter, unsigned deviceType)
  1824. {
  1825. DWORD behaviorFlags = 0;
  1826. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
  1827. {
  1828. behaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING;
  1829. if (impl_->deviceCaps_.DevCaps & D3DDEVCAPS_PUREDEVICE)
  1830. behaviorFlags |= D3DCREATE_PUREDEVICE;
  1831. }
  1832. else
  1833. behaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
  1834. if (FAILED(impl_->interface_->CreateDevice(
  1835. adapter, // adapter
  1836. (D3DDEVTYPE)deviceType, // device type
  1837. impl_->window_, // window associated with device
  1838. behaviorFlags, // vertex processing
  1839. &impl_->presentParams_, // present parameters
  1840. &impl_->device_))) // return created device
  1841. {
  1842. LOGERROR("Could not create Direct3D9 device");
  1843. return false;
  1844. }
  1845. impl_->adapter_ = adapter;
  1846. impl_->deviceType_ = (D3DDEVTYPE)deviceType;
  1847. OnDeviceReset();
  1848. LOGINFO("Created Direct3D9 device");
  1849. return true;
  1850. }
  1851. void Graphics::CreateRenderTargets()
  1852. {
  1853. if (mode_ != RENDER_FORWARD)
  1854. {
  1855. // In deferred rendering, the diffuse buffer stores diffuse albedo. In light prepass, it is used for light accumulation
  1856. if (!diffBuffer_)
  1857. {
  1858. diffBuffer_ = new Texture2D(context_);
  1859. diffBuffer_->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1860. }
  1861. if (!normalBuffer_)
  1862. {
  1863. normalBuffer_ = new Texture2D(context_);
  1864. normalBuffer_->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1865. }
  1866. if (!depthBuffer_)
  1867. {
  1868. depthBuffer_ = new Texture2D(context_);
  1869. depthBuffer_->SetSize(0, 0, GetDepthFormat(), TEXTURE_RENDERTARGET);
  1870. }
  1871. // If deferred mode temporal AA is used, reserve screen buffers
  1872. // (later we will probably want the screen buffer reserved in any case, to do for example distortion effects,
  1873. // which will also be useful in forward rendering)
  1874. if (multiSample_)
  1875. {
  1876. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1877. {
  1878. screenBuffer_[i] = new Texture2D(context_);
  1879. screenBuffer_[i]->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1880. }
  1881. }
  1882. else
  1883. {
  1884. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1885. screenBuffer_[i].Reset();
  1886. }
  1887. }
  1888. else
  1889. {
  1890. diffBuffer_.Reset();
  1891. normalBuffer_.Reset();
  1892. depthBuffer_.Reset();
  1893. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1894. screenBuffer_[i].Reset();
  1895. }
  1896. }
  1897. void Graphics::ResetDevice()
  1898. {
  1899. OnDeviceLost();
  1900. if (SUCCEEDED(impl_->device_->Reset(&impl_->presentParams_)))
  1901. {
  1902. deviceLost_ = false;
  1903. OnDeviceReset();
  1904. }
  1905. }
  1906. void Graphics::OnDeviceLost()
  1907. {
  1908. if (impl_->frameQuery_)
  1909. {
  1910. impl_->frameQuery_->Release();
  1911. impl_->frameQuery_ = 0;
  1912. }
  1913. if (impl_->defaultColorSurface_)
  1914. {
  1915. impl_->defaultColorSurface_->Release();
  1916. impl_->defaultColorSurface_ = 0;
  1917. }
  1918. if (impl_->defaultDepthStencilSurface_)
  1919. {
  1920. impl_->defaultDepthStencilSurface_->Release();
  1921. impl_->defaultDepthStencilSurface_ = 0;
  1922. }
  1923. for (unsigned i = 0; i < gpuObjects_.Size(); ++i)
  1924. gpuObjects_[i]->OnDeviceLost();
  1925. }
  1926. void Graphics::OnDeviceReset()
  1927. {
  1928. ResetCachedState();
  1929. // Create frame query
  1930. impl_->device_->CreateQuery(D3DQUERYTYPE_EVENT, &impl_->frameQuery_);
  1931. // Create deferred rendering buffers now
  1932. CreateRenderTargets();
  1933. for (unsigned i = 0; i < gpuObjects_.Size(); ++i)
  1934. gpuObjects_[i]->OnDeviceReset();
  1935. // Get default surfaces
  1936. impl_->device_->GetRenderTarget(0, &impl_->defaultColorSurface_);
  1937. impl_->device_->GetDepthStencilSurface(&impl_->defaultDepthStencilSurface_);
  1938. immediateBuffer_ = 0;
  1939. }
  1940. void Graphics::ResetCachedState()
  1941. {
  1942. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1943. {
  1944. vertexBuffer_[i] = 0;
  1945. streamOffset_[i] = 0;
  1946. }
  1947. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1948. {
  1949. texture_[i] = 0;
  1950. impl_->minMagFilter_[i] = D3DTEXF_POINT;
  1951. impl_->mipFilter_[i] = D3DTEXF_NONE;
  1952. impl_->uAddressMode_[i] = D3DTADDRESS_WRAP;
  1953. impl_->vAddressMode_[i] = D3DTADDRESS_WRAP;
  1954. impl_->borderColor_[i] = Color(0.0f, 0.0f, 0.0f, 0.0f);
  1955. }
  1956. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1957. {
  1958. renderTarget_[i] = 0;
  1959. impl_->colorSurface_[i] = 0;
  1960. }
  1961. depthStencil_ = 0;
  1962. impl_->depthStencilSurface_ = 0;
  1963. viewport_ = IntRect(0, 0, width_, height_);
  1964. viewTexture_ = 0;
  1965. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1966. streamFrequency_[i] = 1;
  1967. indexBuffer_ = 0;
  1968. vertexDeclaration_ = 0;
  1969. vertexShader_ = 0;
  1970. pixelShader_ = 0;
  1971. blendMode_ = BLEND_REPLACE;
  1972. alphaTest_ = false;
  1973. alphaTestMode_ = CMP_ALWAYS;
  1974. alphaRef_ = 0.0f;
  1975. textureAnisotropy_ = 1;
  1976. colorWrite_ = true;
  1977. cullMode_ = CULL_CCW;
  1978. constantDepthBias_ = 0.0f;
  1979. slopeScaledDepthBias_ = 0.0f;
  1980. depthTestMode_ = CMP_LESSEQUAL;
  1981. depthWrite_ = true;
  1982. fillMode_ = FILL_SOLID;
  1983. scissorTest_ = false;
  1984. scissorRect_ = IntRect::ZERO;
  1985. stencilTest_ = false;
  1986. stencilTestMode_ = CMP_ALWAYS;
  1987. stencilPass_ = OP_KEEP;
  1988. stencilFail_ = OP_KEEP;
  1989. stencilZFail_ = OP_KEEP;
  1990. stencilRef_ = 0;
  1991. stencilMask_ = M_MAX_UNSIGNED;
  1992. impl_->blendEnable_ = FALSE;
  1993. impl_->srcBlend_ = D3DBLEND_ONE;
  1994. impl_->destBlend_ = D3DBLEND_ZERO;
  1995. queryIssued_ = false;
  1996. }
  1997. void Graphics::InitializeShaderParameters()
  1998. {
  1999. // Initialize all parameters as unknown
  2000. for (unsigned i = 0; i < MAX_SHADER_PARAMETERS; ++i)
  2001. shaderRegisters_[i] = MAX_CONSTANT_REGISTERS;
  2002. // Map parameter names
  2003. shaderParameters_["CameraPos"] = VSP_CAMERAPOS;
  2004. shaderParameters_["CameraRot"] = VSP_CAMERAROT;
  2005. shaderParameters_["DepthMode"] = VSP_DEPTHMODE;
  2006. shaderParameters_["ElapsedTime"] = VSP_ELAPSEDTIME;
  2007. shaderParameters_["FrustumSize"] = VSP_FRUSTUMSIZE;
  2008. shaderParameters_["GBufferOffsets"] = VSP_GBUFFEROFFSETS;
  2009. shaderParameters_["Model"] = VSP_MODEL;
  2010. shaderParameters_["ShadowProj"] = VSP_SHADOWPROJ;
  2011. shaderParameters_["SpotProj"] = VSP_SPOTPROJ;
  2012. shaderParameters_["ViewProj"] = VSP_VIEWPROJ;
  2013. shaderParameters_["UOffset"] = VSP_UOFFSET;
  2014. shaderParameters_["VOffset"] = VSP_VOFFSET;
  2015. shaderParameters_["ViewRightVector"] = VSP_VIEWRIGHTVECTOR;
  2016. shaderParameters_["ViewUpVector"] = VSP_VIEWUPVECTOR;
  2017. shaderParameters_["SkinMatrices"] = VSP_SKINMATRICES;
  2018. shaderParameters_["AmbientColor"] = PSP_AMBIENTCOLOR;
  2019. shaderParameters_["AntiAliasWeights"] = PSP_ANTIALIASWEIGHTS;
  2020. shaderParameters_["CameraPosPS"] = PSP_CAMERAPOS;
  2021. shaderParameters_["ElapsedTimePS"] = PSP_ELAPSEDTIME;
  2022. shaderParameters_["FogColor"] = PSP_FOGCOLOR;
  2023. shaderParameters_["FogParams"] = PSP_FOGPARAMS;
  2024. shaderParameters_["GBufferOffsetsPS"] = PSP_GBUFFEROFFSETS;
  2025. shaderParameters_["GBufferViewport"] = PSP_GBUFFERVIEWPORT;
  2026. shaderParameters_["LightAtten"] = PSP_LIGHTATTEN;
  2027. shaderParameters_["LightColor"] = PSP_LIGHTCOLOR;
  2028. shaderParameters_["LightDir"] = PSP_LIGHTDIR;
  2029. shaderParameters_["LightPos"] = PSP_LIGHTPOS;
  2030. shaderParameters_["LightSplits"] = PSP_LIGHTSPLITS;
  2031. shaderParameters_["LightVecRot"] = PSP_LIGHTVECROT;
  2032. shaderParameters_["MatDiffColor"] = PSP_MATDIFFCOLOR;
  2033. shaderParameters_["MatEmissiveColor"] = PSP_MATEMISSIVECOLOR;
  2034. shaderParameters_["MatSpecProperties"] = PSP_MATSPECPROPERTIES;
  2035. shaderParameters_["SampleOffsets"] = PSP_SAMPLEOFFSETS;
  2036. shaderParameters_["ShadowIntensity"] = PSP_SHADOWINTENSITY;
  2037. shaderParameters_["ShadowProjPS"] = PSP_SHADOWPROJ;
  2038. shaderParameters_["SpotProjPS"] = PSP_SPOTPROJ;
  2039. shaderParameters_["ViewProjPS"] = PSP_VIEWPROJ;
  2040. // Map texture units
  2041. textureUnits_["NormalMap"] = TU_NORMAL;
  2042. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2043. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2044. textureUnits_["SpecMap"] = TU_SPECULAR;
  2045. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2046. textureUnits_["DetailMap"] = TU_DETAIL;
  2047. textureUnits_["EnvironmentMap"] = TU_ENVIRONMENT;
  2048. textureUnits_["EnvironmentCubeMap"] = TU_ENVIRONMENT;
  2049. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2050. textureUnits_["LightSpotMap"] = TU_LIGHTSPOT;
  2051. textureUnits_["LightCubeMap"] = TU_LIGHTSPOT;
  2052. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2053. textureUnits_["DiffBuffer"] = TU_DIFFBUFFER;
  2054. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  2055. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  2056. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  2057. }
  2058. void Graphics::HandleWindowMessage(StringHash eventType, VariantMap& eventData)
  2059. {
  2060. using namespace WindowMessage;
  2061. if (eventData[P_WINDOW].GetInt() != (int)impl_->window_)
  2062. return;
  2063. switch (eventData[P_MSG].GetInt())
  2064. {
  2065. case WM_CLOSE:
  2066. Close();
  2067. eventData[P_HANDLED] = true;
  2068. break;
  2069. case WM_DESTROY:
  2070. eventData[P_HANDLED] = true;
  2071. break;
  2072. }
  2073. }
  2074. LRESULT CALLBACK wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  2075. {
  2076. using namespace WindowMessage;
  2077. Graphics* graphics = reinterpret_cast<Graphics*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
  2078. if ((graphics) && (graphics->IsInitialized()))
  2079. {
  2080. VariantMap eventData;
  2081. eventData[P_WINDOW] = (int)hwnd;
  2082. eventData[P_MSG] = (int)msg;
  2083. eventData[P_WPARAM] = (int)wParam;
  2084. eventData[P_LPARAM] = (int)lParam;
  2085. eventData[P_HANDLED] = false;
  2086. graphics->SendEvent(E_WINDOWMESSAGE, eventData);
  2087. if (eventData[P_HANDLED].GetBool())
  2088. return 0;
  2089. }
  2090. return DefWindowProc(hwnd, msg, wParam, lParam);
  2091. }
  2092. void RegisterGraphicsLibrary(Context* context)
  2093. {
  2094. Animation::RegisterObject(context);
  2095. Material::RegisterObject(context);
  2096. Model::RegisterObject(context);
  2097. Shader::RegisterObject(context);
  2098. Technique::RegisterObject(context);
  2099. Texture2D::RegisterObject(context);
  2100. TextureCube::RegisterObject(context);
  2101. Camera::RegisterObject(context);
  2102. Drawable::RegisterObject(context);
  2103. Light::RegisterObject(context);
  2104. StaticModel::RegisterObject(context);
  2105. Skybox::RegisterObject(context);
  2106. AnimatedModel::RegisterObject(context);
  2107. AnimationController::RegisterObject(context);
  2108. BillboardSet::RegisterObject(context);
  2109. ParticleEmitter::RegisterObject(context);
  2110. DebugRenderer::RegisterObject(context);
  2111. Octree::RegisterObject(context);
  2112. Zone::RegisterObject(context);
  2113. }