OGLGraphics.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367
  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 "BillboardSet.h"
  28. #include "Camera.h"
  29. #include "Context.h"
  30. #include "DebugRenderer.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 "Mutex.h"
  39. #include "Octree.h"
  40. #include "ParticleEmitter.h"
  41. #include "ProcessUtils.h"
  42. #include "Profiler.h"
  43. #include "RenderSurface.h"
  44. #include "Shader.h"
  45. #include "ShaderProgram.h"
  46. #include "ShaderVariation.h"
  47. #include "Skybox.h"
  48. #include "Technique.h"
  49. #include "Texture2D.h"
  50. #include "TextureCube.h"
  51. #include "VertexBuffer.h"
  52. #include "Zone.h"
  53. #include <GLee.h>
  54. #include "DebugNew.h"
  55. #ifdef _MSC_VER
  56. #pragma warning(disable:4355)
  57. #endif
  58. static const unsigned glCmpFunc[] =
  59. {
  60. GL_ALWAYS,
  61. GL_EQUAL,
  62. GL_NOTEQUAL,
  63. GL_LESS,
  64. GL_LEQUAL,
  65. GL_GREATER,
  66. GL_GEQUAL
  67. };
  68. static const unsigned glSrcBlend[] =
  69. {
  70. GL_ONE,
  71. GL_ONE,
  72. GL_DST_COLOR,
  73. GL_SRC_ALPHA,
  74. GL_SRC_ALPHA,
  75. GL_ONE,
  76. GL_ONE_MINUS_DST_ALPHA
  77. };
  78. static const unsigned glDestBlend[] =
  79. {
  80. GL_ZERO,
  81. GL_ONE,
  82. GL_ZERO,
  83. GL_ONE_MINUS_SRC_ALPHA,
  84. GL_ONE,
  85. GL_ONE_MINUS_SRC_ALPHA,
  86. GL_DST_ALPHA
  87. };
  88. static const unsigned glStencilOps[] =
  89. {
  90. GL_KEEP,
  91. GL_ZERO,
  92. GL_REPLACE,
  93. GL_INCR,
  94. GL_DECR
  95. };
  96. static const String noParameter;
  97. static const DWORD windowStyle = WS_OVERLAPPEDWINDOW & ~WS_THICKFRAME & ~WS_MAXIMIZEBOX;
  98. static LRESULT CALLBACK wndProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam);
  99. OBJECTTYPESTATIC(Graphics);
  100. Graphics::Graphics(Context* context_) :
  101. Object(context_),
  102. impl_(new GraphicsImpl()),
  103. mode_(RENDER_FORWARD),
  104. width_(0),
  105. height_(0),
  106. multiSample_(0),
  107. windowPosX_(0),
  108. windowPosY_(0),
  109. fullscreen_(false),
  110. vsync_(false),
  111. flushGPU_(true),
  112. fullscreenModeSet_(false),
  113. inModeChange_(false),
  114. deferredSupport_(false),
  115. prepassSupport_(false),
  116. numPrimitives_(0),
  117. numBatches_(0),
  118. immediateBuffer_(0),
  119. defaultTextureFilterMode_(FILTER_BILINEAR),
  120. shadowMapFormat_(0),
  121. hiresShadowMapFormat_(0)
  122. {
  123. ResetCachedState();
  124. InitializeShaderParameters();
  125. SubscribeToEvent(E_WINDOWMESSAGE, HANDLER(Graphics, HandleWindowMessage));
  126. SubscribeToEvent(E_ACTIVATION, HANDLER(Graphics, HandleActivation));
  127. }
  128. Graphics::~Graphics()
  129. {
  130. Close();
  131. delete impl_;
  132. impl_ = 0;
  133. }
  134. void Graphics::MessagePump()
  135. {
  136. MSG msg;
  137. while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
  138. {
  139. TranslateMessage(&msg);
  140. DispatchMessage(&msg);
  141. }
  142. }
  143. void Graphics::SetWindowTitle(const String& windowTitle)
  144. {
  145. windowTitle_ = windowTitle;
  146. if (impl_->window_)
  147. SetWindowText(impl_->window_, windowTitle_.CString());
  148. }
  149. bool Graphics::SetMode(RenderMode mode, int width, int height, bool fullscreen, bool vsync, int multiSample)
  150. {
  151. PROFILE(SetScreenMode);
  152. /// \todo For now multisampling is not supported
  153. multiSample = 0;
  154. // If zero dimensions, use the desktop default
  155. if ((width <= 0) || (height <= 0))
  156. {
  157. if (fullscreen)
  158. {
  159. IntVector2 desktopResolution = impl_->GetDesktopResolution();
  160. width = desktopResolution.x_;
  161. height = desktopResolution.y_;
  162. }
  163. else
  164. {
  165. width = 800;
  166. height = 600;
  167. }
  168. }
  169. if ((mode == mode_) && (width == width_) && (height == height_) && (fullscreen == fullscreen_) && (vsync == vsync_)
  170. && (multiSample == multiSample_))
  171. return true;
  172. if (!impl_->window_)
  173. {
  174. if (!OpenWindow(width, height))
  175. return false;
  176. }
  177. // Save window placement if currently windowed
  178. if (!fullscreen_)
  179. {
  180. WINDOWPLACEMENT wndpl;
  181. wndpl.length = sizeof wndpl;
  182. if (SUCCEEDED(GetWindowPlacement(impl_->window_, &wndpl)))
  183. {
  184. windowPosX_ = wndpl.rcNormalPosition.left;
  185. windowPosY_ = wndpl.rcNormalPosition.top;
  186. }
  187. }
  188. // Create OpenGL context
  189. if (!impl_->renderContext_)
  190. {
  191. impl_->renderContext_ = wglCreateContext(impl_->deviceContext_);
  192. wglMakeCurrent(impl_->deviceContext_, impl_->renderContext_);
  193. // Query for extensions now. Needs to happen under lock as the function pointers are static
  194. {
  195. MutexLock lock(GetStaticMutex());
  196. GLeeInit();
  197. }
  198. if (!_GLEE_VERSION_2_0)
  199. {
  200. LOGERROR("OpenGL 2.0 is required");
  201. return false;
  202. }
  203. // Create the FBO if supported
  204. if (_GLEE_EXT_framebuffer_object)
  205. {
  206. glGenFramebuffersEXT(1, &impl_->fbo_);
  207. // If FBO is supported, shadows can be rendered
  208. shadowMapFormat_ = GL_DEPTH_COMPONENT16;
  209. hiresShadowMapFormat_ = GL_DEPTH_COMPONENT24;
  210. // Deferred and light prepass rendering require the ability to use a depth/stencil buffer with FBO,
  211. // for proper optimization and split point light masking
  212. if (_GLEE_EXT_packed_depth_stencil)
  213. {
  214. deferredSupport_ = true;
  215. prepassSupport_ = true;
  216. }
  217. }
  218. // Set initial state to match Direct3D
  219. glEnable(GL_DEPTH_TEST);
  220. SetCullMode(CULL_CCW);
  221. SetDepthTest(CMP_LESSEQUAL);
  222. }
  223. // Change/restore desktop resolution as necessary
  224. if (fullscreen)
  225. {
  226. if (!SetScreenMode(width, height))
  227. fullscreen = false;
  228. }
  229. else
  230. {
  231. if (fullscreen_)
  232. RestoreScreenMode();
  233. }
  234. AdjustWindow(width, height, fullscreen);
  235. #ifdef WIN32
  236. if (wglSwapIntervalEXT)
  237. wglSwapIntervalEXT(vsync ? 1 : 0);
  238. #endif
  239. glGetIntegerv(GL_DEPTH_BITS, &impl_->windowDepthBits_);
  240. impl_->depthBits_ = impl_->windowDepthBits_;
  241. // Clear all additional depth buffers now, as they are possibly not needed any more
  242. depthTextures_.Clear();
  243. width_ = width;
  244. height_ = height;
  245. fullscreen_ = fullscreen;
  246. vsync_ = vsync;
  247. mode_ = mode;
  248. // Reset rendertargets and viewport for the new screen mode
  249. ResetRenderTargets();
  250. viewTexture_ = 0;
  251. // Get the system depth buffer's bit depth
  252. glGetIntegerv(GL_DEPTH_BITS, &impl_->depthBits_);
  253. // Create rendering buffers
  254. CreateRenderTargets();
  255. // Let screen mode dependent GPU objects update themselves
  256. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  257. (*i)->OnDeviceReset();
  258. if (!multiSample)
  259. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed"));
  260. else
  261. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed") +
  262. " multisample " + String(multiSample));
  263. using namespace ScreenMode;
  264. VariantMap eventData;
  265. eventData[P_WIDTH] = width_;
  266. eventData[P_HEIGHT] = height_;
  267. eventData[P_FULLSCREEN] = fullscreen_;
  268. SendEvent(E_SCREENMODE, eventData);
  269. return true;
  270. }
  271. bool Graphics::SetMode(int width, int height)
  272. {
  273. return SetMode(mode_, width, height, fullscreen_, vsync_, multiSample_);
  274. }
  275. bool Graphics::SetMode(RenderMode mode)
  276. {
  277. return SetMode(mode, width_, height_, fullscreen_, vsync_, multiSample_);
  278. }
  279. bool Graphics::ToggleFullscreen()
  280. {
  281. return SetMode(mode_, width_, height_, !fullscreen_, vsync_, multiSample_);
  282. }
  283. void Graphics::Close()
  284. {
  285. // Release all GPU objects that still exist
  286. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  287. (*i)->Release();
  288. gpuObjects_.Clear();
  289. if (impl_->renderContext_)
  290. {
  291. if (impl_->fbo_)
  292. glDeleteFramebuffersEXT(1, &impl_->fbo_);
  293. wglMakeCurrent(NULL, NULL);
  294. wglDeleteContext(impl_->renderContext_);
  295. impl_->renderContext_ = 0;
  296. }
  297. if (impl_->deviceContext_)
  298. {
  299. ReleaseDC(impl_->window_, impl_->deviceContext_);
  300. impl_->deviceContext_ = 0;
  301. }
  302. if (impl_->window_)
  303. {
  304. RestoreScreenMode();
  305. DestroyWindow(impl_->window_);
  306. impl_->window_ = 0;
  307. }
  308. }
  309. bool Graphics::TakeScreenShot(Image& destImage)
  310. {
  311. PROFILE(TakeScreenShot);
  312. SetRenderTarget(0, (RenderSurface*)0);
  313. destImage.SetSize(width_, height_, 3);
  314. glReadPixels(0, 0, width_, height_, GL_RGB, GL_UNSIGNED_BYTE, destImage.GetData());
  315. return true;
  316. }
  317. void Graphics::SetFlushGPU(bool enable)
  318. {
  319. flushGPU_ = enable;
  320. }
  321. bool Graphics::BeginFrame()
  322. {
  323. PROFILE(BeginRendering);
  324. if (!IsInitialized())
  325. return false;
  326. // If we should be fullscreen, but the screen mode is not currently set, do not render
  327. if ((fullscreen_) && (!fullscreenModeSet_))
  328. return false;
  329. // Set default rendertarget and depth buffer
  330. ResetRenderTargets();
  331. viewTexture_ = 0;
  332. // Cleanup textures from previous frame
  333. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  334. SetTexture(i, 0);
  335. // Enable color and depth write
  336. SetColorWrite(true);
  337. SetDepthWrite(true);
  338. // Reset immediate mode vertex buffer positions
  339. for (Map<unsigned, unsigned>::Iterator i = immediateVertexBufferPos_.Begin(); i != immediateVertexBufferPos_.End(); ++i)
  340. i->second_ = 0;
  341. numPrimitives_ = 0;
  342. numBatches_ = 0;
  343. SendEvent(E_BEGINRENDER);
  344. return true;
  345. }
  346. void Graphics::EndFrame()
  347. {
  348. PROFILE(EndRendering);
  349. if (!IsInitialized())
  350. return;
  351. SendEvent(E_ENDRENDER);
  352. SwapBuffers(impl_->deviceContext_);
  353. }
  354. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  355. {
  356. bool oldColorWrite = colorWrite_;
  357. bool oldDepthWrite = depthWrite_;
  358. if ((flags & CLEAR_COLOR) && (!oldColorWrite))
  359. SetColorWrite(true);
  360. if ((flags & CLEAR_DEPTH) && (!oldDepthWrite))
  361. SetDepthWrite(true);
  362. unsigned glFlags = 0;
  363. if (flags & CLEAR_COLOR)
  364. {
  365. glFlags |= GL_COLOR_BUFFER_BIT;
  366. glClearColor(color.r_, color.g_, color.b_, color.a_);
  367. }
  368. if (flags & CLEAR_DEPTH)
  369. {
  370. glFlags |= GL_DEPTH_BUFFER_BIT;
  371. glClearDepth(depth);
  372. }
  373. if (flags & CLEAR_STENCIL)
  374. {
  375. glFlags |= GL_STENCIL_BUFFER_BIT;
  376. glClearStencil(stencil);
  377. }
  378. glClear(glFlags);
  379. SetColorWrite(oldColorWrite);
  380. SetDepthWrite(oldDepthWrite);
  381. }
  382. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  383. {
  384. if (!vertexCount)
  385. return;
  386. unsigned primitiveCount = 0;
  387. switch (type)
  388. {
  389. case TRIANGLE_LIST:
  390. primitiveCount = vertexCount / 3;
  391. glDrawArrays(GL_TRIANGLES, vertexStart, vertexCount);
  392. break;
  393. case LINE_LIST:
  394. primitiveCount = vertexCount / 2;
  395. glDrawArrays(GL_LINES, vertexStart, vertexCount);
  396. break;
  397. }
  398. numPrimitives_ += primitiveCount;
  399. ++numBatches_;
  400. }
  401. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  402. {
  403. if ((!indexCount) || (!indexBuffer_))
  404. return;
  405. unsigned primitiveCount = 0;
  406. unsigned indexSize = indexBuffer_->GetIndexSize();
  407. switch (type)
  408. {
  409. case TRIANGLE_LIST:
  410. primitiveCount = indexCount / 3;
  411. if (indexSize == sizeof(unsigned short))
  412. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (const GLvoid*)(indexStart * indexSize));
  413. else
  414. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, (const GLvoid*)(indexStart * indexSize));
  415. break;
  416. case LINE_LIST:
  417. primitiveCount = indexCount / 2;
  418. if (indexSize == sizeof(unsigned short))
  419. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_SHORT, (const GLvoid*)(indexStart * indexSize));
  420. else
  421. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_INT, (const GLvoid*)(indexStart * indexSize));
  422. break;
  423. }
  424. numPrimitives_ += primitiveCount;
  425. ++numBatches_;
  426. }
  427. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount, unsigned instanceCount)
  428. {
  429. }
  430. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  431. {
  432. Vector<VertexBuffer*> vertexBuffers(1);
  433. PODVector<unsigned> elementMasks(1);
  434. vertexBuffers[0] = buffer;
  435. elementMasks[0] = MASK_DEFAULT;
  436. SetVertexBuffers(vertexBuffers, elementMasks);
  437. }
  438. bool Graphics::SetVertexBuffers(const Vector<VertexBuffer*>& buffers, const PODVector<unsigned>& elementMasks,
  439. unsigned instanceOffset)
  440. {
  441. if (buffers.Size() > MAX_VERTEX_STREAMS)
  442. {
  443. LOGERROR("Too many vertex buffers");
  444. return false;
  445. }
  446. if (buffers.Size() != elementMasks.Size())
  447. {
  448. LOGERROR("Amount of element masks and vertex buffers does not match");
  449. return false;
  450. }
  451. // If no valid shader to determine the attribute bindings, can not set vertex buffers
  452. if (!shaderProgram_)
  453. return false;
  454. const int* attributeLocations = shaderProgram_->GetAttributeLocations();
  455. bool changed = false;
  456. unsigned newAttributes = 0;
  457. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  458. {
  459. VertexBuffer* buffer = 0;
  460. unsigned elementMask = 0;
  461. if (i < buffers.Size())
  462. {
  463. buffer = buffers[i];
  464. elementMask = elementMasks[i];
  465. if ((elementMask == MASK_DEFAULT) && (buffer))
  466. elementMask = buffers[i]->GetElementMask();
  467. }
  468. // If buffer and element mask have stayed the same, skip to the next buffer
  469. if ((buffer == vertexBuffers_[i]) && (elementMask == elementMasks_[i]))
  470. continue;
  471. vertexBuffers_[i] = buffer;
  472. elementMasks_[i] = elementMask;
  473. changed = true;
  474. if (!buffer)
  475. continue;
  476. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  477. unsigned vertexSize = buffer->GetVertexSize();
  478. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  479. {
  480. // If shader does not use the attribute, do not bind it (bandwidth optimization)
  481. int attributeIndex = attributeLocations[j];
  482. if (attributeIndex < 0)
  483. continue;
  484. unsigned elementBit = 1 << j;
  485. unsigned attributeBit = 1 << attributeIndex;
  486. if (elementMask & elementBit)
  487. {
  488. newAttributes |= attributeBit;
  489. // Enable attribute if not enabled yet
  490. if ((impl_->enabledAttributes_ & attributeBit) == 0)
  491. {
  492. glEnableVertexAttribArray(attributeIndex);
  493. impl_->enabledAttributes_ |= attributeBit;
  494. }
  495. // Set the attribute pointer
  496. glVertexAttribPointer(attributeIndex, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  497. VertexBuffer::elementNormalize[j], vertexSize, (const GLvoid*)(buffer->GetElementOffset((VertexElement)j)));
  498. }
  499. }
  500. }
  501. if (!changed)
  502. return true;
  503. // Now check which vertex attributes should be disabled
  504. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  505. int disableIndex = 0;
  506. while (disableAttributes)
  507. {
  508. if (disableAttributes & 1)
  509. {
  510. glDisableVertexAttribArray(disableIndex);
  511. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  512. }
  513. disableAttributes >>= 1;
  514. ++disableIndex;
  515. }
  516. return true;
  517. }
  518. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>&
  519. elementMasks, unsigned instanceOffset)
  520. {
  521. if (buffers.Size() > MAX_VERTEX_STREAMS)
  522. {
  523. LOGERROR("Too many vertex buffers");
  524. return false;
  525. }
  526. if (buffers.Size() != elementMasks.Size())
  527. {
  528. LOGERROR("Amount of element masks and vertex buffers does not match");
  529. return false;
  530. }
  531. // If no valid shader to determine the attribute bindings, can not set vertex buffers
  532. if (!shaderProgram_)
  533. return false;
  534. const int* attributeLocations = shaderProgram_->GetAttributeLocations();
  535. bool changed = false;
  536. unsigned newAttributes = 0;
  537. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  538. {
  539. VertexBuffer* buffer = 0;
  540. unsigned elementMask = 0;
  541. if (i < buffers.Size())
  542. {
  543. buffer = buffers[i];
  544. elementMask = elementMasks[i];
  545. if ((elementMask == MASK_DEFAULT) && (buffer))
  546. elementMask = buffers[i]->GetElementMask();
  547. }
  548. // If buffer and element mask have stayed the same, skip to the next buffer
  549. if ((buffer == vertexBuffers_[i]) && (elementMask == elementMasks_[i]))
  550. continue;
  551. vertexBuffers_[i] = buffer;
  552. elementMasks_[i] = elementMask;
  553. changed = true;
  554. if (!buffer)
  555. continue;
  556. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  557. unsigned vertexSize = buffer->GetVertexSize();
  558. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  559. {
  560. // If shader does not use the attribute, do not bind it (bandwidth optimization)
  561. int attributeIndex = attributeLocations[j];
  562. if (attributeIndex < 0)
  563. continue;
  564. unsigned elementBit = 1 << j;
  565. unsigned attributeBit = 1 << attributeIndex;
  566. if (elementMask & elementBit)
  567. {
  568. newAttributes |= attributeBit;
  569. // Enable attribute if not enabled yet
  570. if ((impl_->enabledAttributes_ & attributeBit) == 0)
  571. {
  572. glEnableVertexAttribArray(attributeIndex);
  573. impl_->enabledAttributes_ |= attributeBit;
  574. }
  575. // Set the attribute pointer
  576. glVertexAttribPointer(attributeIndex, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  577. VertexBuffer::elementNormalize[j], vertexSize, (const GLvoid*)(buffer->GetElementOffset((VertexElement)j)));
  578. }
  579. }
  580. }
  581. if (!changed)
  582. return true;
  583. // Now check which vertex attributes should be disabled
  584. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  585. int disableIndex = 0;
  586. while (disableAttributes)
  587. {
  588. if (disableAttributes & 1)
  589. {
  590. glDisableVertexAttribArray(disableIndex);
  591. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  592. }
  593. disableAttributes >>= 1;
  594. ++disableIndex;
  595. }
  596. return true;
  597. }
  598. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  599. {
  600. if (indexBuffer_ == buffer)
  601. return;
  602. if (buffer)
  603. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->GetGPUObject());
  604. else
  605. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  606. indexBuffer_ = buffer;
  607. }
  608. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  609. {
  610. if ((vs == vertexShader_) && (ps == pixelShader_))
  611. return;
  612. // All vertex attributes must be re-bound after shader change, and uniforms need to be reassigned
  613. ClearLastParameterSources();
  614. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  615. {
  616. vertexBuffers_[i] = 0;
  617. elementMasks_[i] = 0;
  618. }
  619. if ((!vs) || (!ps))
  620. {
  621. glUseProgram(0);
  622. vertexShader_ = 0;
  623. pixelShader_ = 0;
  624. shaderProgram_ = 0;
  625. }
  626. else
  627. {
  628. vertexShader_ = vs;
  629. pixelShader_ = ps;
  630. Pair<ShaderVariation*, ShaderVariation*> combination(vs, ps);
  631. ShaderProgramMap::Iterator i = shaderPrograms_.Find(combination);
  632. if (i != shaderPrograms_.End())
  633. {
  634. // Use the existing linked program
  635. if (i->second_->IsLinked())
  636. {
  637. glUseProgram(i->second_->GetGPUObject());
  638. shaderProgram_ = i->second_;
  639. }
  640. else
  641. {
  642. glUseProgram(0);
  643. shaderProgram_ = 0;
  644. }
  645. }
  646. else
  647. {
  648. // Link a new combination
  649. SharedPtr<ShaderProgram> newProgram(new ShaderProgram(this, vs, ps));
  650. if (!newProgram->Link())
  651. {
  652. LOGERROR("Failed to link shader " + vs->GetShader()->GetName() + ":\n" +
  653. newProgram->GetLinkerOutput());
  654. glUseProgram(0);
  655. shaderProgram_ = 0;
  656. }
  657. else
  658. {
  659. // Note: Link() calls glUseProgram() to set the texture sampler uniforms,
  660. // so it is not necessary to call it again
  661. shaderProgram_ = newProgram;
  662. }
  663. shaderPrograms_[combination] = newProgram;
  664. }
  665. }
  666. }
  667. void Graphics::SetShaderParameter(ShaderParameter param, const bool* data, unsigned count)
  668. {
  669. // Not supported
  670. }
  671. void Graphics::SetShaderParameter(ShaderParameter param, const float* data, unsigned count)
  672. {
  673. if (shaderProgram_)
  674. {
  675. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  676. if (info)
  677. {
  678. switch (info->type_)
  679. {
  680. case GL_FLOAT:
  681. glUniform1fv(info->location_, count, data);
  682. break;
  683. case GL_FLOAT_VEC2:
  684. glUniform2fv(info->location_, count / 2, data);
  685. break;
  686. case GL_FLOAT_VEC3:
  687. glUniform3fv(info->location_, count / 3, data);
  688. break;
  689. case GL_FLOAT_VEC4:
  690. glUniform4fv(info->location_, count / 4, data);
  691. break;
  692. case GL_FLOAT_MAT3:
  693. glUniformMatrix3fv(info->location_, count / 9, GL_TRUE, data);
  694. break;
  695. case GL_FLOAT_MAT4:
  696. glUniformMatrix4fv(info->location_, count / 16, GL_TRUE, data);
  697. break;
  698. }
  699. }
  700. }
  701. }
  702. void Graphics::SetShaderParameter(ShaderParameter param, const int* data, unsigned count)
  703. {
  704. if (shaderProgram_)
  705. {
  706. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  707. if (info)
  708. {
  709. switch (info->type_)
  710. {
  711. case GL_INT:
  712. glUniform1iv(info->location_, count, data);
  713. break;
  714. case GL_INT_VEC2:
  715. glUniform2iv(info->location_, count / 2, data);
  716. break;
  717. case GL_INT_VEC3:
  718. glUniform3iv(info->location_, count / 3, data);
  719. break;
  720. case GL_INT_VEC4:
  721. glUniform4iv(info->location_, count / 4, data);
  722. break;
  723. }
  724. }
  725. }
  726. }
  727. void Graphics::SetShaderParameter(ShaderParameter param, float value)
  728. {
  729. if (shaderProgram_)
  730. {
  731. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  732. if (info)
  733. glUniform1fv(info->location_, 1, &value);
  734. }
  735. }
  736. void Graphics::SetShaderParameter(ShaderParameter param, const Color& color)
  737. {
  738. SetShaderParameter(param, color.GetData(), 4);
  739. }
  740. void Graphics::SetShaderParameter(ShaderParameter param, const Matrix3& matrix)
  741. {
  742. if (shaderProgram_)
  743. {
  744. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  745. if (info)
  746. glUniformMatrix3fv(info->location_, 1, GL_TRUE, matrix.GetData());
  747. }
  748. }
  749. void Graphics::SetShaderParameter(ShaderParameter param, const Vector3& vector)
  750. {
  751. if (shaderProgram_)
  752. {
  753. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  754. if (info)
  755. {
  756. // Check the uniform type to avoid mismatch
  757. switch (info->type_)
  758. {
  759. case GL_FLOAT:
  760. glUniform1fv(info->location_, 1, vector.GetData());
  761. break;
  762. case GL_FLOAT_VEC2:
  763. glUniform2fv(info->location_, 1, vector.GetData());
  764. break;
  765. case GL_FLOAT_VEC3:
  766. glUniform3fv(info->location_, 1, vector.GetData());
  767. break;
  768. }
  769. }
  770. }
  771. }
  772. void Graphics::SetShaderParameter(ShaderParameter param, const Matrix4& matrix)
  773. {
  774. if (shaderProgram_)
  775. {
  776. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  777. if (info)
  778. glUniformMatrix4fv(info->location_, 1, GL_TRUE, matrix.GetData());
  779. }
  780. }
  781. void Graphics::SetShaderParameter(ShaderParameter param, const Vector4& vector)
  782. {
  783. if (shaderProgram_)
  784. {
  785. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  786. if (info)
  787. {
  788. // Check the uniform type to avoid mismatch
  789. switch (info->type_)
  790. {
  791. case GL_FLOAT:
  792. glUniform1fv(info->location_, 1, vector.GetData());
  793. break;
  794. case GL_FLOAT_VEC2:
  795. glUniform2fv(info->location_, 1, vector.GetData());
  796. break;
  797. case GL_FLOAT_VEC3:
  798. glUniform3fv(info->location_, 1, vector.GetData());
  799. break;
  800. case GL_FLOAT_VEC4:
  801. glUniform4fv(info->location_, 1, vector.GetData());
  802. break;
  803. }
  804. }
  805. }
  806. }
  807. void Graphics::SetShaderParameter(ShaderParameter param, const Matrix3x4& matrix)
  808. {
  809. if (shaderProgram_)
  810. {
  811. const UniformInfo* info = shaderProgram_->GetUniformInfo(param);
  812. if (info)
  813. {
  814. float data[16];
  815. data[0] = matrix.m00_;
  816. data[1] = matrix.m01_;
  817. data[2] = matrix.m02_;
  818. data[3] = matrix.m03_;
  819. data[4] = matrix.m10_;
  820. data[5] = matrix.m11_;
  821. data[6] = matrix.m12_;
  822. data[7] = matrix.m13_;
  823. data[8] = matrix.m20_;
  824. data[9] = matrix.m21_;
  825. data[10] = matrix.m22_;
  826. data[11] = matrix.m23_;
  827. data[12] = 0.0f;
  828. data[13] = 0.0f;
  829. data[14] = 0.0f;
  830. data[15] = 1.0f;
  831. glUniformMatrix4fv(info->location_, 1, GL_TRUE, data);
  832. }
  833. }
  834. }
  835. bool Graphics::NeedParameterUpdate(ShaderParameter param, const void* source)
  836. {
  837. if ((shaderProgram_) && (shaderProgram_->HasParameter(param)) && (lastShaderParameterSources_[param] != source))
  838. {
  839. lastShaderParameterSources_[param] = source;
  840. return true;
  841. }
  842. return false;
  843. }
  844. bool Graphics::NeedTextureUnit(TextureUnit unit)
  845. {
  846. if ((shaderProgram_) && (shaderProgram_->HasTextureUnit(unit)))
  847. return true;
  848. return false;
  849. }
  850. void Graphics::ClearLastParameterSources()
  851. {
  852. for (unsigned i = 0; i < MAX_SHADER_PARAMETERS; ++i)
  853. lastShaderParameterSources_[i] = (const void*)M_MAX_UNSIGNED;
  854. }
  855. void Graphics::ClearTransformSources()
  856. {
  857. lastShaderParameterSources_[VSP_MODEL] = (const void*)M_MAX_UNSIGNED;
  858. lastShaderParameterSources_[VSP_VIEWPROJ] = (const void*)M_MAX_UNSIGNED;
  859. }
  860. void Graphics::CleanupShaderPrograms()
  861. {
  862. for (ShaderProgramMap::Iterator i = shaderPrograms_.Begin(); i != shaderPrograms_.End();)
  863. {
  864. ShaderProgramMap::Iterator current = i++;
  865. if (!current->second_->GetGPUObject())
  866. {
  867. if (shaderProgram_ == current->second_)
  868. shaderProgram_ = 0;
  869. shaderPrograms_.Erase(current);
  870. }
  871. }
  872. }
  873. void Graphics::SetTexture(unsigned index, Texture* texture)
  874. {
  875. if (index >= MAX_TEXTURE_UNITS)
  876. return;
  877. // Check if texture is currently bound as a render target. In that case, use its backup texture, or blank if not defined
  878. if (texture)
  879. {
  880. if (((renderTargets_[0]) && (renderTargets_[0]->GetParentTexture() == texture)) ||
  881. ((depthStencil_) && (depthStencil_->GetParentTexture() == texture)))
  882. texture = texture->GetBackupTexture();
  883. // Check also for the view texture, in case a specific rendering pass does not bind the destination render target,
  884. // but should still not sample it either
  885. else if (texture == viewTexture_)
  886. texture = texture->GetBackupTexture();
  887. }
  888. if (textures_[index] != texture)
  889. {
  890. if (impl_->activeTexture_ != index)
  891. {
  892. glActiveTexture(GL_TEXTURE0 + index);
  893. impl_->activeTexture_ = index;
  894. }
  895. if (texture)
  896. {
  897. unsigned glType = texture->GetTextureType();
  898. if (glType != textureTypes_[index])
  899. {
  900. if (textureTypes_[index])
  901. glDisable(textureTypes_[index]);
  902. glEnable(glType);
  903. textureTypes_[index] = glType;
  904. }
  905. glBindTexture(glType, texture->GetGPUObject());
  906. if (texture->GetParametersDirty())
  907. texture->UpdateParameters();
  908. }
  909. else
  910. {
  911. if (textureTypes_[index])
  912. glBindTexture(textureTypes_[index], 0);
  913. }
  914. textures_[index] = texture;
  915. }
  916. else
  917. {
  918. if ((texture) && (texture->GetParametersDirty()))
  919. {
  920. if (impl_->activeTexture_ != index)
  921. {
  922. glActiveTexture(GL_TEXTURE0 + index);
  923. impl_->activeTexture_ = index;
  924. }
  925. glBindTexture(texture->GetTextureType(), texture->GetGPUObject());
  926. texture->UpdateParameters();
  927. }
  928. }
  929. }
  930. void Graphics::SetTextureForUpdate(Texture* texture)
  931. {
  932. if (impl_->activeTexture_ != 0)
  933. {
  934. glActiveTexture(GL_TEXTURE0);
  935. impl_->activeTexture_ = 0;
  936. }
  937. glBindTexture(texture->GetTextureType(), texture->GetGPUObject());
  938. textures_[0] = texture;
  939. }
  940. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  941. {
  942. if (mode != defaultTextureFilterMode_)
  943. {
  944. defaultTextureFilterMode_ = mode;
  945. SetTextureParametersDirty();
  946. }
  947. }
  948. void Graphics::SetTextureAnisotropy(unsigned level)
  949. {
  950. if (level != textureAnisotropy_)
  951. {
  952. textureAnisotropy_ = level;
  953. SetTextureParametersDirty();
  954. }
  955. }
  956. void Graphics::SetTextureParametersDirty()
  957. {
  958. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  959. {
  960. Texture* texture = dynamic_cast<Texture*>(*i);
  961. if (texture)
  962. texture->SetParametersDirty();
  963. }
  964. }
  965. void Graphics::ResetRenderTargets()
  966. {
  967. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  968. SetRenderTarget(i, (RenderSurface*)0);
  969. SetDepthStencil((RenderSurface*)0);
  970. }
  971. void Graphics::ResetRenderTarget(unsigned index)
  972. {
  973. SetRenderTarget(index, (RenderSurface*)0);
  974. }
  975. void Graphics::ResetDepthStencil()
  976. {
  977. SetDepthStencil((RenderSurface*)0);
  978. }
  979. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  980. {
  981. if ((index >= MAX_RENDERTARGETS) || (!impl_->fbo_))
  982. return;
  983. if (renderTarget != renderTargets_[index])
  984. {
  985. renderTargets_[index] = renderTarget;
  986. // If the rendertarget is also bound as a texture, replace with backup texture or null
  987. if (renderTarget)
  988. {
  989. Texture* parentTexture = renderTarget->GetParentTexture();
  990. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  991. {
  992. if (textures_[i] == parentTexture)
  993. SetTexture(i, textures_[i]->GetBackupTexture());
  994. }
  995. }
  996. // Bind the FBO to be able to make changes to it
  997. if (!impl_->fboBound_)
  998. {
  999. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->fbo_);
  1000. impl_->fboBound_ = true;
  1001. }
  1002. if (renderTarget)
  1003. {
  1004. Texture* texture = renderTarget->GetParentTexture();
  1005. // If texture's parameters are dirty, update before attaching
  1006. if (texture->GetParametersDirty())
  1007. {
  1008. SetTextureForUpdate(texture);
  1009. texture->UpdateParameters();
  1010. SetTexture(0, 0);
  1011. }
  1012. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, GL_TEXTURE_2D, texture->GetGPUObject(), 0);
  1013. }
  1014. else
  1015. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, GL_TEXTURE_2D, 0, 0);
  1016. // Disable color buffer writing/reading if only a depth texture is to be used:
  1017. // otherwise it is an OpenGL error (incomplete framebuffer)
  1018. SetDrawBuffers();
  1019. // If all rendertargets and the depth buffer are not textures, revert to backbuffer rendering
  1020. bool noFBO = (depthStencil_ == 0);
  1021. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1022. {
  1023. if (renderTargets_[i])
  1024. {
  1025. noFBO = false;
  1026. break;
  1027. }
  1028. }
  1029. if ((noFBO) && (impl_->fboBound_))
  1030. {
  1031. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1032. impl_->fboBound_ = false;
  1033. }
  1034. }
  1035. }
  1036. void Graphics::SetRenderTarget(unsigned index, Texture2D* renderTexture)
  1037. {
  1038. RenderSurface* renderTarget = 0;
  1039. if (renderTexture)
  1040. renderTarget = renderTexture->GetRenderSurface();
  1041. SetRenderTarget(index, renderTarget);
  1042. }
  1043. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1044. {
  1045. if ((impl_->fbo_) && (depthStencil != depthStencil_))
  1046. {
  1047. // If we are using a rendertarget texture, it is required in OpenGL to also have an own depth stencil
  1048. // Create a new depth stencil texture as necessary to be able to provide similar behaviour.
  1049. if ((renderTargets_[0]) && (!depthStencil))
  1050. {
  1051. int width = renderTargets_[0]->GetWidth();
  1052. int height = renderTargets_[0]->GetHeight();
  1053. // Reuse the deferred depth buffer if possible
  1054. if ((depthBuffer_) && (width == width_) && (height == height_))
  1055. depthStencil = depthBuffer_->GetRenderSurface();
  1056. else
  1057. {
  1058. int searchKey = (width << 16) | height;
  1059. Map<int, SharedPtr<Texture2D> >::Iterator i = depthTextures_.Find(searchKey);
  1060. if (i != depthTextures_.End())
  1061. depthStencil = i->second_->GetRenderSurface();
  1062. else
  1063. {
  1064. SharedPtr<Texture2D> newDepthTexture(new Texture2D(context_));
  1065. newDepthTexture->SetSize(width, height, GetDepthFormat(), TEXTURE_DEPTHSTENCIL);
  1066. depthTextures_[searchKey] = newDepthTexture;
  1067. depthStencil = newDepthTexture->GetRenderSurface();
  1068. }
  1069. }
  1070. }
  1071. /// \todo Should check if the texture actually is in depth format
  1072. depthStencil_ = depthStencil;
  1073. // Bind the FBO to be able to make changes to it
  1074. if (!impl_->fboBound_)
  1075. {
  1076. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->fbo_);
  1077. impl_->fboBound_ = true;
  1078. }
  1079. if (depthStencil)
  1080. {
  1081. Texture* texture = depthStencil->GetParentTexture();
  1082. // If texture's parameters are dirty, update before attaching
  1083. if (texture->GetParametersDirty())
  1084. {
  1085. SetTextureForUpdate(texture);
  1086. texture->UpdateParameters();
  1087. SetTexture(0, 0);
  1088. }
  1089. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, texture->GetGPUObject(), 0);
  1090. impl_->depthBits_ = texture->GetDepthBits();
  1091. }
  1092. else
  1093. {
  1094. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1095. impl_->depthBits_ = impl_->windowDepthBits_;
  1096. }
  1097. // Disable color buffer writing/reading if only a depth texture is to be used:
  1098. // otherwise it is an OpenGL error (incomplete framebuffer)
  1099. SetDrawBuffers();
  1100. // If all rendertargets and the depth buffer are not textures, revert to backbuffer rendering
  1101. bool noFBO = (depthStencil_ == 0);
  1102. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1103. {
  1104. if (renderTargets_[i])
  1105. {
  1106. noFBO = false;
  1107. break;
  1108. }
  1109. }
  1110. if ((noFBO) && (impl_->fboBound_))
  1111. {
  1112. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1113. impl_->fboBound_ = false;
  1114. }
  1115. }
  1116. // Reset viewport and scissor test
  1117. IntVector2 viewSize = GetRenderTargetDimensions();
  1118. SetViewport(IntRect(0, 0, viewSize.x_, viewSize.y_));
  1119. SetScissorTest(false);
  1120. }
  1121. void Graphics::SetDepthStencil(Texture2D* depthTexture)
  1122. {
  1123. RenderSurface* depthStencil = 0;
  1124. if (depthTexture)
  1125. depthStencil = depthTexture->GetRenderSurface();
  1126. SetDepthStencil(depthStencil);
  1127. }
  1128. void Graphics::SetViewport(const IntRect& rect)
  1129. {
  1130. IntVector2 rtSize = GetRenderTargetDimensions();
  1131. IntRect rectCopy = rect;
  1132. if (rectCopy.right_ <= rectCopy.left_)
  1133. rectCopy.right_ = rectCopy.left_ + 1;
  1134. if (rectCopy.bottom_ <= rectCopy.top_)
  1135. rectCopy.bottom_ = rectCopy.top_ + 1;
  1136. rectCopy.left_ = Clamp(rectCopy.left_, 0, rtSize.x_);
  1137. rectCopy.top_ = Clamp(rectCopy.top_, 0, rtSize.y_);
  1138. rectCopy.right_ = Clamp(rectCopy.right_, 0, rtSize.x_);
  1139. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, rtSize.y_);
  1140. if (rectCopy != viewport_)
  1141. {
  1142. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1143. glViewport(rectCopy.left_, rtSize.y_ - rectCopy.bottom_, rectCopy.right_ - rectCopy.left_, rectCopy.bottom_ - rectCopy.top_);
  1144. viewport_ = rectCopy;
  1145. }
  1146. // Disable scissor test, needs to be re-enabled by the user
  1147. SetScissorTest(false);
  1148. }
  1149. void Graphics::SetViewTexture(Texture* texture)
  1150. {
  1151. viewTexture_ = texture;
  1152. // Check for the view texture being currently bound
  1153. if (texture)
  1154. {
  1155. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1156. {
  1157. if (textures_[i] == texture)
  1158. SetTexture(i, textures_[i]->GetBackupTexture());
  1159. }
  1160. }
  1161. }
  1162. void Graphics::SetAlphaTest(bool enable, CompareMode mode, float alphaRef)
  1163. {
  1164. if (enable != alphaTest_)
  1165. {
  1166. if (enable)
  1167. glEnable(GL_ALPHA_TEST);
  1168. else
  1169. glDisable(GL_ALPHA_TEST);
  1170. alphaTest_ = enable;
  1171. }
  1172. if (enable)
  1173. {
  1174. alphaRef = Clamp(alphaRef, 0.0f, 1.0f);
  1175. if ((mode != alphaTestMode_) || (alphaRef != alphaRef_))
  1176. {
  1177. glAlphaFunc(glCmpFunc[mode], alphaRef);
  1178. alphaTestMode_ = mode;
  1179. alphaRef_ = alphaRef;
  1180. }
  1181. }
  1182. }
  1183. void Graphics::SetBlendMode(BlendMode mode)
  1184. {
  1185. if (mode != blendMode_)
  1186. {
  1187. if (mode == BLEND_REPLACE)
  1188. glDisable(GL_BLEND);
  1189. else
  1190. {
  1191. glEnable(GL_BLEND);
  1192. glBlendFunc(glSrcBlend[mode], glDestBlend[mode]);
  1193. }
  1194. blendMode_ = mode;
  1195. }
  1196. }
  1197. void Graphics::SetColorWrite(bool enable)
  1198. {
  1199. if (enable != colorWrite_)
  1200. {
  1201. if (enable)
  1202. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1203. else
  1204. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1205. colorWrite_ = enable;
  1206. }
  1207. }
  1208. void Graphics::SetCullMode(CullMode mode)
  1209. {
  1210. if (mode != cullMode_)
  1211. {
  1212. if (mode == CULL_NONE)
  1213. glDisable(GL_CULL_FACE);
  1214. else
  1215. {
  1216. // Use Direct3D convention, ie. clockwise vertices define a front face
  1217. glEnable(GL_CULL_FACE);
  1218. glCullFace(mode == CULL_CCW ? GL_FRONT : GL_BACK);
  1219. }
  1220. cullMode_ = mode;
  1221. }
  1222. }
  1223. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1224. {
  1225. // Bring the constant bias from Direct3D9 scale to OpenGL (depends on depth buffer bitdepth)
  1226. // Zero depth bits may be returned if using the packed depth stencil format. Assume 24bit in that case
  1227. int depthBits = min(impl_->depthBits_, 23);
  1228. if (!depthBits)
  1229. depthBits = 23;
  1230. float adjustedConstantBias = constantBias * (float)(1 << (depthBits - 1));
  1231. if ((adjustedConstantBias != constantDepthBias_) || (slopeScaledBias != slopeScaledDepthBias_))
  1232. {
  1233. if ((adjustedConstantBias != 0.0f) || (slopeScaledBias != 0.0f))
  1234. {
  1235. glEnable(GL_POLYGON_OFFSET_FILL);
  1236. glEnable(GL_POLYGON_OFFSET_LINE);
  1237. glPolygonOffset(slopeScaledBias, adjustedConstantBias);
  1238. }
  1239. else
  1240. {
  1241. glDisable(GL_POLYGON_OFFSET_FILL);
  1242. glDisable(GL_POLYGON_OFFSET_LINE);
  1243. }
  1244. constantDepthBias_ = adjustedConstantBias;
  1245. slopeScaledDepthBias_ = slopeScaledBias;
  1246. }
  1247. }
  1248. void Graphics::SetDepthTest(CompareMode mode)
  1249. {
  1250. if (mode != depthTestMode_)
  1251. {
  1252. glDepthFunc(glCmpFunc[mode]);
  1253. depthTestMode_ = mode;
  1254. }
  1255. }
  1256. void Graphics::SetDepthWrite(bool enable)
  1257. {
  1258. if (enable != depthWrite_)
  1259. {
  1260. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1261. depthWrite_ = enable;
  1262. }
  1263. }
  1264. void Graphics::SetFillMode(FillMode mode)
  1265. {
  1266. if (mode != fillMode_)
  1267. {
  1268. glPolygonMode(GL_FRONT_AND_BACK, mode == FILL_SOLID ? GL_FILL : GL_LINE);
  1269. fillMode_ = mode;
  1270. }
  1271. }
  1272. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1273. {
  1274. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1275. // Disable scissor in that case to reduce state changes
  1276. if ((rect.min_.x_ <= 0.0f) && (rect.min_.y_ <= 0.0f) && (rect.max_.y_ >= 1.0f) && (rect.max_.y_ >= 1.0f))
  1277. enable = false;
  1278. // Check for illegal rect, disable in that case
  1279. if ((rect.max_.x_ < rect.min_.x_) || (rect.max_.y_ < rect.min_.y_))
  1280. enable = false;
  1281. if (enable)
  1282. {
  1283. IntVector2 rtSize(GetRenderTargetDimensions());
  1284. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1285. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1286. IntRect intRect;
  1287. int expand = borderInclusive ? 1 : 0;
  1288. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1289. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1290. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1291. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1292. if (intRect.right_ == intRect.left_)
  1293. intRect.right_++;
  1294. if (intRect.bottom_ == intRect.top_)
  1295. intRect.bottom_++;
  1296. if ((intRect.right_ < intRect.left_) || (intRect.bottom_ < intRect.top_))
  1297. enable = false;
  1298. if ((enable) && (scissorRect_ != intRect))
  1299. {
  1300. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1301. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1302. scissorRect_ = intRect;
  1303. }
  1304. }
  1305. else
  1306. scissorRect_ = IntRect::ZERO;
  1307. if (enable != scissorTest_)
  1308. {
  1309. if (enable)
  1310. glEnable(GL_SCISSOR_TEST);
  1311. else
  1312. glDisable(GL_SCISSOR_TEST);
  1313. scissorTest_ = enable;
  1314. }
  1315. }
  1316. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1317. {
  1318. IntVector2 rtSize(GetRenderTargetDimensions());
  1319. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1320. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1321. // Full scissor is same as disabling the test
  1322. if ((rect.left_ <= 0) && (rect.right_ >= viewSize.x_) && (rect.top_ <= 0) && (rect.bottom_ >= viewSize.y_))
  1323. enable = false;
  1324. // Check for illegal rect, disable in that case
  1325. if ((rect.right_ < rect.left_) || (rect.bottom_ < rect.top_))
  1326. enable = false;
  1327. if (enable)
  1328. {
  1329. IntRect intRect;
  1330. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1331. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1332. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1333. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1334. if (intRect.right_ == intRect.left_)
  1335. intRect.right_++;
  1336. if (intRect.bottom_ == intRect.top_)
  1337. intRect.bottom_++;
  1338. if ((intRect.right_ < intRect.left_) || (intRect.bottom_ < intRect.top_))
  1339. enable = false;
  1340. if ((enable) && (scissorRect_ != intRect))
  1341. {
  1342. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1343. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1344. scissorRect_ = intRect;
  1345. }
  1346. }
  1347. else
  1348. scissorRect_ = IntRect::ZERO;
  1349. if (enable != scissorTest_)
  1350. {
  1351. if (enable)
  1352. glEnable(GL_SCISSOR_TEST);
  1353. else
  1354. glDisable(GL_SCISSOR_TEST);
  1355. scissorTest_ = enable;
  1356. }
  1357. }
  1358. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1359. {
  1360. }
  1361. void Graphics::ResetStreamFrequencies()
  1362. {
  1363. }
  1364. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned stencilMask)
  1365. {
  1366. if (enable != stencilTest_)
  1367. {
  1368. if (enable)
  1369. glEnable(GL_STENCIL_TEST);
  1370. else
  1371. glDisable(GL_STENCIL_TEST);
  1372. stencilTest_ = enable;
  1373. }
  1374. if (enable)
  1375. {
  1376. if ((mode != stencilTestMode_) || (stencilRef != stencilRef_) || (stencilMask != stencilMask_))
  1377. {
  1378. glStencilFunc(glCmpFunc[mode], stencilRef, stencilMask);
  1379. stencilTestMode_ = mode;
  1380. stencilRef_ = stencilRef;
  1381. stencilMask_ = stencilMask;
  1382. }
  1383. if ((pass != stencilPass_) || (fail != stencilFail_) || (!zFail != stencilZFail_))
  1384. {
  1385. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1386. stencilPass_ = pass;
  1387. stencilFail_ = fail;
  1388. stencilZFail_ = zFail;
  1389. }
  1390. }
  1391. }
  1392. bool Graphics::BeginImmediate(PrimitiveType type, unsigned vertexCount, unsigned elementMask)
  1393. {
  1394. if (immediateBuffer_)
  1395. {
  1396. LOGERROR("New immediate draw operation started before ending the last one");
  1397. return false;
  1398. }
  1399. if (!(elementMask & MASK_POSITION))
  1400. {
  1401. LOGERROR("Immediate draw operation must contain vertex positions");
  1402. return false;
  1403. }
  1404. if (!vertexCount)
  1405. return true;
  1406. // Start from default size, ensure that buffer is big enough to hold the immediate draw operation
  1407. unsigned newSize = IMMEDIATE_BUFFER_DEFAULT_SIZE;
  1408. while (newSize < vertexCount)
  1409. newSize <<= 1;
  1410. // See if buffer exists for this vertex format. If not, create new
  1411. if (immediateVertexBuffers_.Find(elementMask) == immediateVertexBuffers_.End())
  1412. {
  1413. LOGDEBUG("Created immediate vertex buffer");
  1414. VertexBuffer* newBuffer = new VertexBuffer(context_);
  1415. newBuffer->SetSize(newSize, elementMask, true);
  1416. immediateVertexBuffers_[elementMask] = newBuffer;
  1417. immediateVertexBufferPos_[elementMask] = 0;
  1418. }
  1419. // Resize buffer if it is too small
  1420. VertexBuffer* buffer = immediateVertexBuffers_[elementMask];
  1421. if (buffer->GetVertexCount() < newSize)
  1422. {
  1423. LOGDEBUG("Resized immediate vertex buffer to " + String(newSize));
  1424. buffer->SetSize(newSize, elementMask);
  1425. immediateVertexBufferPos_[elementMask] = 0;
  1426. }
  1427. // Get the current lock position for the buffer
  1428. unsigned bufferPos = immediateVertexBufferPos_[elementMask];
  1429. if (bufferPos + vertexCount >= buffer->GetVertexCount())
  1430. bufferPos = 0;
  1431. LockMode lockMode = LOCK_DISCARD;
  1432. if (bufferPos != 0)
  1433. lockMode = LOCK_NOOVERWRITE;
  1434. // Note: the data pointer gets pre-decremented here, because the first call to DefineVertex() will increment it
  1435. immediateDataPtr_ = ((unsigned char*)buffer->Lock(bufferPos, vertexCount, lockMode)) - buffer->GetVertexSize();
  1436. immediateBuffer_ = buffer;
  1437. immediateType_= type;
  1438. immediateStartPos_ = bufferPos;
  1439. immediateVertexCount_ = vertexCount;
  1440. immediateCurrentVertex_ = 0;
  1441. // Store new buffer position for next lock into the same buffer
  1442. bufferPos += vertexCount;
  1443. if (bufferPos >= buffer->GetVertexCount())
  1444. bufferPos = 0;
  1445. immediateVertexBufferPos_[elementMask] = bufferPos;
  1446. return true;
  1447. }
  1448. bool Graphics::DefineVertex(const Vector3& vertex)
  1449. {
  1450. if ((!immediateBuffer_) || (immediateCurrentVertex_ >= immediateVertexCount_))
  1451. return false;
  1452. immediateDataPtr_ += immediateBuffer_->GetVertexSize();
  1453. ++immediateCurrentVertex_;
  1454. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_POSITION));
  1455. const float* src = vertex.GetData();
  1456. dest[0] = src[0];
  1457. dest[1] = src[1];
  1458. dest[2] = src[2];
  1459. return true;
  1460. }
  1461. bool Graphics::DefineNormal(const Vector3& normal)
  1462. {
  1463. if ((!immediateBuffer_) ||(!(immediateBuffer_->GetElementMask() & MASK_NORMAL)) || (!immediateCurrentVertex_))
  1464. return false;
  1465. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_NORMAL));
  1466. const float* src = normal.GetData();
  1467. dest[0] = src[0];
  1468. dest[1] = src[1];
  1469. dest[2] = src[2];
  1470. return true;
  1471. }
  1472. bool Graphics::DefineTexCoord(const Vector2& texCoord)
  1473. {
  1474. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_TEXCOORD1)) || (!immediateCurrentVertex_))
  1475. return false;
  1476. float* dest = (float*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_TEXCOORD1));
  1477. const float* src = texCoord.GetData();
  1478. dest[0] = src[0];
  1479. dest[1] = src[1];
  1480. return true;
  1481. }
  1482. bool Graphics::DefineColor(const Color& color)
  1483. {
  1484. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_COLOR)) || (!immediateCurrentVertex_))
  1485. return false;
  1486. unsigned* dest = (unsigned*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_COLOR));
  1487. *dest = color.ToUInt();
  1488. return true;
  1489. }
  1490. bool Graphics::DefineColor(unsigned color)
  1491. {
  1492. if ((!immediateBuffer_) || (!(immediateBuffer_->GetElementMask() & MASK_COLOR)) || (!immediateCurrentVertex_))
  1493. return false;
  1494. unsigned* dest = (unsigned*)(immediateDataPtr_ + immediateBuffer_->GetElementOffset(ELEMENT_COLOR));
  1495. *dest = color;
  1496. return true;
  1497. }
  1498. void Graphics::EndImmediate()
  1499. {
  1500. if (immediateBuffer_)
  1501. {
  1502. immediateBuffer_->Unlock();
  1503. SetVertexBuffer(immediateBuffer_);
  1504. Draw(immediateType_, immediateStartPos_, immediateVertexCount_);
  1505. immediateBuffer_ = 0;
  1506. }
  1507. }
  1508. void Graphics::SetForceSM2(bool enable)
  1509. {
  1510. }
  1511. unsigned char* Graphics::GetImmediateDataPtr() const
  1512. {
  1513. if (!immediateBuffer_)
  1514. {
  1515. LOGERROR("Immediate draw operation not started");
  1516. return 0;
  1517. }
  1518. // Pointer was pre-decremented in BeginImmediate(). Undo that now
  1519. return immediateDataPtr_ + immediateBuffer_->GetVertexSize();
  1520. }
  1521. PODVector<IntVector2> Graphics::GetResolutions() const
  1522. {
  1523. PODVector<IntVector2> ret;
  1524. return ret;
  1525. }
  1526. PODVector<int> Graphics::GetMultiSampleLevels() const
  1527. {
  1528. PODVector<int> ret;
  1529. // No multisampling always supported
  1530. ret.Push(0);
  1531. return ret;
  1532. }
  1533. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1534. {
  1535. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1536. }
  1537. ShaderParameter Graphics::GetShaderParameter(const String& name)
  1538. {
  1539. Map<String, ShaderParameter>::Iterator i = shaderParameters_.Find(name);
  1540. if (i != shaderParameters_.End())
  1541. return i->second_;
  1542. else
  1543. return MAX_SHADER_PARAMETERS;
  1544. }
  1545. TextureUnit Graphics::GetTextureUnit(const String& name)
  1546. {
  1547. Map<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1548. if (i != textureUnits_.End())
  1549. return i->second_;
  1550. else
  1551. return MAX_TEXTURE_UNITS;
  1552. }
  1553. const String& Graphics::GetShaderParameterName(ShaderParameter parameter)
  1554. {
  1555. for (Map<String, ShaderParameter>::Iterator i = shaderParameters_.Begin(); i != shaderParameters_.End(); ++i)
  1556. {
  1557. if (i->second_ == parameter)
  1558. return i->first_;
  1559. }
  1560. return noParameter;
  1561. }
  1562. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1563. {
  1564. for (Map<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1565. {
  1566. if (i->second_ == unit)
  1567. return i->first_;
  1568. }
  1569. return noParameter;
  1570. }
  1571. Texture* Graphics::GetTexture(unsigned index) const
  1572. {
  1573. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1574. }
  1575. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1576. {
  1577. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1578. }
  1579. IntVector2 Graphics::GetRenderTargetDimensions() const
  1580. {
  1581. int width, height;
  1582. if (renderTargets_[0])
  1583. {
  1584. width = renderTargets_[0]->GetWidth();
  1585. height = renderTargets_[0]->GetHeight();
  1586. }
  1587. else if (depthStencil_)
  1588. {
  1589. width = depthStencil_->GetWidth();
  1590. height = depthStencil_->GetHeight();
  1591. }
  1592. else
  1593. {
  1594. width = width_;
  1595. height = height_;
  1596. }
  1597. return IntVector2(width, height);
  1598. }
  1599. void Graphics::AddGPUObject(GPUObject* object)
  1600. {
  1601. gpuObjects_.Push(object);
  1602. }
  1603. void Graphics::RemoveGPUObject(GPUObject* object)
  1604. {
  1605. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1606. {
  1607. if ((*i) == object)
  1608. {
  1609. gpuObjects_.Erase(i);
  1610. return;
  1611. }
  1612. }
  1613. }
  1614. unsigned Graphics::GetAlphaFormat()
  1615. {
  1616. return GL_ALPHA;
  1617. }
  1618. unsigned Graphics::GetLuminanceFormat()
  1619. {
  1620. return GL_LUMINANCE;
  1621. }
  1622. unsigned Graphics::GetLuminanceAlphaFormat()
  1623. {
  1624. return GL_LUMINANCE_ALPHA;
  1625. }
  1626. unsigned Graphics::GetRGBFormat()
  1627. {
  1628. return GL_RGB;
  1629. }
  1630. unsigned Graphics::GetRGBAFormat()
  1631. {
  1632. return GL_RGBA;
  1633. }
  1634. unsigned Graphics::GetDepthFormat()
  1635. {
  1636. // Note: this requires GLee static initialization to have completed to return the proper result
  1637. if (_GLEE_EXT_packed_depth_stencil)
  1638. return GL_DEPTH24_STENCIL8_EXT;
  1639. else
  1640. return GL_DEPTH_COMPONENT24;
  1641. }
  1642. bool Graphics::IsInitialized() const
  1643. {
  1644. return ((impl_->window_ != 0) && (impl_->renderContext_ != 0));
  1645. }
  1646. unsigned Graphics::GetWindowHandle() const
  1647. {
  1648. return (unsigned)impl_->window_;
  1649. }
  1650. bool Graphics::GetRenderTextureSupport() const
  1651. {
  1652. return impl_->fbo_ != 0;
  1653. }
  1654. bool Graphics::OpenWindow(int width, int height)
  1655. {
  1656. WNDCLASS wc;
  1657. wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
  1658. wc.lpfnWndProc = wndProc;
  1659. wc.cbClsExtra = 0;
  1660. wc.cbWndExtra = 0;
  1661. wc.hInstance = impl_->instance_;
  1662. wc.hIcon = LoadIcon(0, IDI_APPLICATION);
  1663. wc.hCursor = LoadCursor(0, IDC_ARROW);
  1664. wc.hbrBackground = 0;
  1665. wc.lpszMenuName = 0;
  1666. wc.lpszClassName = "OpenGL";
  1667. RegisterClass(&wc);
  1668. RECT rect = {0, 0, width, height};
  1669. AdjustWindowRect(&rect, windowStyle, false);
  1670. impl_->window_ = CreateWindow("OpenGL", windowTitle_.CString(), windowStyle, CW_USEDEFAULT, CW_USEDEFAULT,
  1671. rect.right, rect.bottom, 0, 0, impl_->instance_, 0);
  1672. if (!impl_->window_)
  1673. {
  1674. LOGERROR("Could not create window");
  1675. return false;
  1676. }
  1677. SetWindowLongPtr(impl_->window_, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
  1678. // Save window placement
  1679. WINDOWPLACEMENT wndpl;
  1680. wndpl.length = sizeof wndpl;
  1681. if (SUCCEEDED(GetWindowPlacement(impl_->window_, &wndpl)))
  1682. {
  1683. windowPosX_ = wndpl.rcNormalPosition.left;
  1684. windowPosY_ = wndpl.rcNormalPosition.top;
  1685. }
  1686. // Save the device context, then set the pixel format
  1687. impl_->deviceContext_ = GetDC(impl_->window_);
  1688. PIXELFORMATDESCRIPTOR pfd;
  1689. ZeroMemory(&pfd, sizeof(pfd));
  1690. pfd.nSize = sizeof(pfd);
  1691. pfd.nVersion = 1;
  1692. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_GENERIC_ACCELERATED | PFD_DOUBLEBUFFER;
  1693. pfd.iPixelType = PFD_TYPE_RGBA;
  1694. pfd.cColorBits = 24;
  1695. pfd.cDepthBits = 24;
  1696. pfd.cStencilBits = 8;
  1697. int iFormat = ChoosePixelFormat(impl_->deviceContext_, &pfd);
  1698. if (!iFormat)
  1699. {
  1700. LOGERROR("Failed to choose pixel format");
  1701. return false;
  1702. }
  1703. if (SetPixelFormat(impl_->deviceContext_, iFormat, &pfd) == FALSE)
  1704. {
  1705. LOGERROR("Failed to set pixel format");
  1706. return false;
  1707. }
  1708. LOGINFO("Created application window");
  1709. return true;
  1710. }
  1711. bool Graphics::SetScreenMode(int newWidth, int newHeight)
  1712. {
  1713. inModeChange_ = true;
  1714. bool success = true;
  1715. IntVector2 desktopResolution = impl_->GetDesktopResolution();
  1716. unsigned bitsPerPixel = impl_->GetDesktopBitsPerPixel();
  1717. // Switch resolution only if necessary
  1718. if ((desktopResolution.x_ != newWidth) || (desktopResolution.y_ != newHeight) || (bitsPerPixel != 32))
  1719. {
  1720. DEVMODE dmScreenSettings;
  1721. ZeroMemory(&dmScreenSettings, sizeof(dmScreenSettings));
  1722. dmScreenSettings.dmSize = sizeof(dmScreenSettings);
  1723. dmScreenSettings.dmPelsWidth = newWidth;
  1724. dmScreenSettings.dmPelsHeight = newHeight;
  1725. dmScreenSettings.dmBitsPerPel = 32;
  1726. dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
  1727. success = ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL;
  1728. if (success)
  1729. fullscreenModeSet_ = true;
  1730. }
  1731. else
  1732. fullscreenModeSet_ = true;
  1733. inModeChange_ = false;
  1734. return success;
  1735. }
  1736. void Graphics::RestoreScreenMode()
  1737. {
  1738. if (fullscreenModeSet_)
  1739. {
  1740. inModeChange_ = true;
  1741. ChangeDisplaySettings(NULL, 0);
  1742. fullscreenModeSet_ = false;
  1743. inModeChange_ = false;
  1744. }
  1745. }
  1746. void Graphics::AdjustWindow(int newWidth, int newHeight, bool newFullscreen)
  1747. {
  1748. inModeChange_ = true;
  1749. if (newFullscreen)
  1750. {
  1751. SetWindowLongPtr(impl_->window_, GWL_STYLE, WS_POPUP);
  1752. SetWindowPos(impl_->window_, HWND_TOP, 0, 0, newWidth, newHeight, SWP_NOZORDER | SWP_SHOWWINDOW);
  1753. }
  1754. else
  1755. {
  1756. RECT rect = {0, 0, newWidth, newHeight};
  1757. AdjustWindowRect(&rect, windowStyle, false);
  1758. SetWindowLongPtr(impl_->window_, GWL_STYLE, windowStyle);
  1759. SetWindowPos(impl_->window_, HWND_TOP, windowPosX_, windowPosY_, rect.right - rect.left, rect.bottom - rect.top,
  1760. SWP_NOZORDER | SWP_SHOWWINDOW);
  1761. // Clean up the desktop of the old window contents
  1762. InvalidateRect(0, 0, true);
  1763. }
  1764. inModeChange_ = false;
  1765. }
  1766. void Graphics::CreateRenderTargets()
  1767. {
  1768. if (mode_ != RENDER_FORWARD)
  1769. {
  1770. // In deferred rendering, the diffuse buffer stores diffuse albedo. In light prepass, it is used for light accumulation
  1771. if (!diffBuffer_)
  1772. {
  1773. diffBuffer_ = new Texture2D(context_);
  1774. diffBuffer_->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1775. }
  1776. if (!normalBuffer_)
  1777. {
  1778. normalBuffer_ = new Texture2D(context_);
  1779. normalBuffer_->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1780. }
  1781. if (!depthBuffer_)
  1782. {
  1783. depthBuffer_ = new Texture2D(context_);
  1784. depthBuffer_->SetSize(0, 0, GetDepthFormat(), TEXTURE_DEPTHSTENCIL);
  1785. }
  1786. // If deferred mode temporal AA is used, reserve screen buffers
  1787. // (later we will probably want the screen buffer reserved in any case, to do for example distortion effects,
  1788. // which will also be useful in forward rendering)
  1789. if (multiSample_)
  1790. {
  1791. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1792. {
  1793. screenBuffers_[i] = new Texture2D(context_);
  1794. screenBuffers_[i]->SetSize(0, 0, GetRGBAFormat(), TEXTURE_RENDERTARGET);
  1795. }
  1796. }
  1797. else
  1798. {
  1799. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1800. screenBuffers_[i].Reset();
  1801. }
  1802. }
  1803. else
  1804. {
  1805. diffBuffer_.Reset();
  1806. normalBuffer_.Reset();
  1807. depthBuffer_.Reset();
  1808. for (unsigned i = 0; i < NUM_SCREEN_BUFFERS; ++i)
  1809. screenBuffers_[i].Reset();
  1810. }
  1811. }
  1812. void Graphics::ResetCachedState()
  1813. {
  1814. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1815. {
  1816. vertexBuffers_[i] = 0;
  1817. elementMasks_[i] = 0;
  1818. }
  1819. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1820. {
  1821. textures_[i] = 0;
  1822. textureTypes_[i] = 0;
  1823. }
  1824. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1825. renderTargets_[i] = 0;
  1826. depthStencil_ = 0;
  1827. viewport_ = IntRect(0, 0, 0, 0);
  1828. viewTexture_ = 0;
  1829. indexBuffer_ = 0;
  1830. vertexShader_ = 0;
  1831. pixelShader_ = 0;
  1832. shaderProgram_ = 0;
  1833. blendMode_ = BLEND_REPLACE;
  1834. alphaTest_ = false;
  1835. alphaTestMode_ = CMP_ALWAYS;
  1836. alphaRef_ = 0.0f;
  1837. textureAnisotropy_ = 1;
  1838. colorWrite_ = true;
  1839. cullMode_ = CULL_NONE;
  1840. constantDepthBias_ = 0.0f;
  1841. slopeScaledDepthBias_ = 0.0f;
  1842. depthTestMode_ = CMP_ALWAYS;
  1843. depthWrite_ = true;
  1844. fillMode_ = FILL_SOLID;
  1845. scissorTest_ = false;
  1846. scissorRect_ = IntRect::ZERO;
  1847. stencilTest_ = false;
  1848. stencilTestMode_ = CMP_ALWAYS;
  1849. stencilPass_ = OP_KEEP;
  1850. stencilFail_ = OP_KEEP;
  1851. stencilZFail_ = OP_KEEP;
  1852. stencilRef_ = 0;
  1853. stencilMask_ = M_MAX_UNSIGNED;
  1854. }
  1855. void Graphics::SetDrawBuffers()
  1856. {
  1857. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  1858. unsigned newDrawBuffers = 0;
  1859. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1860. {
  1861. if (renderTargets_[i])
  1862. newDrawBuffers |= 1 << i;
  1863. }
  1864. if (newDrawBuffers == impl_->drawBuffers_)
  1865. return;
  1866. // Check for no color rendertargets (depth rendering only)
  1867. if (!newDrawBuffers)
  1868. glDrawBuffer(GL_NONE);
  1869. else
  1870. {
  1871. int drawBufferIds[4];
  1872. unsigned drawBufferCount = 0;
  1873. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1874. {
  1875. if (renderTargets_[i])
  1876. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + i;
  1877. }
  1878. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  1879. }
  1880. glReadBuffer(GL_NONE);
  1881. }
  1882. void Graphics::InitializeShaderParameters()
  1883. {
  1884. // Map parameter names
  1885. shaderParameters_["CameraPos"] = VSP_CAMERAPOS;
  1886. shaderParameters_["CameraRot"] = VSP_CAMERAROT;
  1887. shaderParameters_["DepthMode"] = VSP_DEPTHMODE;
  1888. shaderParameters_["ElapsedTime"] = VSP_ELAPSEDTIME;
  1889. shaderParameters_["FrustumSize"] = VSP_FRUSTUMSIZE;
  1890. shaderParameters_["GBufferOffsets"] = VSP_GBUFFEROFFSETS;
  1891. shaderParameters_["Model"] = VSP_MODEL;
  1892. shaderParameters_["ShadowProj"] = VSP_SHADOWPROJ;
  1893. shaderParameters_["SpotProj"] = VSP_SPOTPROJ;
  1894. shaderParameters_["ViewProj"] = VSP_VIEWPROJ;
  1895. shaderParameters_["UOffset"] = VSP_UOFFSET;
  1896. shaderParameters_["VOffset"] = VSP_VOFFSET;
  1897. shaderParameters_["ViewRightVector"] = VSP_VIEWRIGHTVECTOR;
  1898. shaderParameters_["ViewUpVector"] = VSP_VIEWUPVECTOR;
  1899. shaderParameters_["SkinMatrices"] = VSP_SKINMATRICES;
  1900. shaderParameters_["AmbientColor"] = PSP_AMBIENTCOLOR;
  1901. shaderParameters_["AntiAliasWeights"] = PSP_ANTIALIASWEIGHTS;
  1902. shaderParameters_["CameraPosPS"] = PSP_CAMERAPOS;
  1903. shaderParameters_["DepthReconstruct"] = PSP_DEPTHRECONSTRUCT;
  1904. shaderParameters_["ElapsedTimePS"] = PSP_ELAPSEDTIME;
  1905. shaderParameters_["FogColor"] = PSP_FOGCOLOR;
  1906. shaderParameters_["FogParams"] = PSP_FOGPARAMS;
  1907. shaderParameters_["GBufferOffsetsPS"] = PSP_GBUFFEROFFSETS;
  1908. shaderParameters_["GBufferViewport"] = PSP_GBUFFERVIEWPORT;
  1909. shaderParameters_["LightAtten"] = PSP_LIGHTATTEN;
  1910. shaderParameters_["LightColor"] = PSP_LIGHTCOLOR;
  1911. shaderParameters_["LightDir"] = PSP_LIGHTDIR;
  1912. shaderParameters_["LightPos"] = PSP_LIGHTPOS;
  1913. shaderParameters_["LightSplits"] = PSP_LIGHTSPLITS;
  1914. shaderParameters_["LightVecRot"] = PSP_LIGHTVECROT;
  1915. shaderParameters_["MatDiffColor"] = PSP_MATDIFFCOLOR;
  1916. shaderParameters_["MatEmissiveColor"] = PSP_MATEMISSIVECOLOR;
  1917. shaderParameters_["MatSpecProperties"] = PSP_MATSPECPROPERTIES;
  1918. shaderParameters_["SampleOffsets"] = PSP_SAMPLEOFFSETS;
  1919. shaderParameters_["ShadowIntensity"] = PSP_SHADOWINTENSITY;
  1920. shaderParameters_["ShadowProjPS"] = PSP_SHADOWPROJ;
  1921. shaderParameters_["SpotProjPS"] = PSP_SPOTPROJ;
  1922. shaderParameters_["ViewProjPS"] = PSP_VIEWPROJ;
  1923. // Map texture units
  1924. textureUnits_["NormalMap"] = TU_NORMAL;
  1925. textureUnits_["DiffMap"] = TU_DIFFUSE;
  1926. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  1927. textureUnits_["SpecMap"] = TU_SPECULAR;
  1928. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  1929. textureUnits_["DetailMap"] = TU_DETAIL;
  1930. textureUnits_["EnvironmentMap"] = TU_ENVIRONMENT;
  1931. textureUnits_["EnvironmentCubeMap"] = TU_ENVIRONMENT;
  1932. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  1933. textureUnits_["LightSpotMap"] = TU_LIGHTSPOT;
  1934. textureUnits_["LightCubeMap"] = TU_LIGHTSPOT;
  1935. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  1936. textureUnits_["DiffBuffer"] = TU_DIFFBUFFER;
  1937. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  1938. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  1939. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  1940. }
  1941. void Graphics::HandleWindowMessage(StringHash eventType, VariantMap& eventData)
  1942. {
  1943. using namespace WindowMessage;
  1944. if (eventData[P_WINDOW].GetInt() != (int)impl_->window_)
  1945. return;
  1946. switch (eventData[P_MSG].GetInt())
  1947. {
  1948. case WM_CLOSE:
  1949. Close();
  1950. eventData[P_HANDLED] = true;
  1951. break;
  1952. case WM_DESTROY:
  1953. eventData[P_HANDLED] = true;
  1954. break;
  1955. }
  1956. }
  1957. void Graphics::HandleActivation(StringHash eventType, VariantMap& eventData)
  1958. {
  1959. if ((inModeChange_) || (!impl_->window_) || (!fullscreen_))
  1960. return;
  1961. using namespace Activation;
  1962. if (eventData[P_ACTIVE].GetBool())
  1963. {
  1964. // If we were activated and are not minimized, change back to the custom mode
  1965. if ((!eventData[P_MINIMIZED].GetBool()) && (!fullscreenModeSet_))
  1966. {
  1967. if (!SetScreenMode(width_, height_))
  1968. fullscreen_ = false;
  1969. AdjustWindow(width_, height_, fullscreen_);
  1970. }
  1971. }
  1972. else
  1973. {
  1974. // Reset to desktop resolution on inactivation
  1975. inModeChange_ = true;
  1976. ShowWindow(impl_->window_, SW_MINIMIZE);
  1977. inModeChange_ = false;
  1978. RestoreScreenMode();
  1979. }
  1980. }
  1981. LRESULT CALLBACK wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
  1982. {
  1983. using namespace WindowMessage;
  1984. Graphics* graphics = reinterpret_cast<Graphics*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
  1985. if ((graphics) && (graphics->IsInitialized()))
  1986. {
  1987. VariantMap eventData;
  1988. eventData[P_WINDOW] = (int)hwnd;
  1989. eventData[P_MSG] = (int)msg;
  1990. eventData[P_WPARAM] = (int)wParam;
  1991. eventData[P_LPARAM] = (int)lParam;
  1992. eventData[P_HANDLED] = false;
  1993. graphics->SendEvent(E_WINDOWMESSAGE, eventData);
  1994. if (eventData[P_HANDLED].GetBool())
  1995. return 0;
  1996. }
  1997. return DefWindowProc(hwnd, msg, wParam, lParam);
  1998. }
  1999. void RegisterGraphicsLibrary(Context* context)
  2000. {
  2001. Animation::RegisterObject(context);
  2002. Material::RegisterObject(context);
  2003. Model::RegisterObject(context);
  2004. Shader::RegisterObject(context);
  2005. Technique::RegisterObject(context);
  2006. Texture2D::RegisterObject(context);
  2007. TextureCube::RegisterObject(context);
  2008. Camera::RegisterObject(context);
  2009. Drawable::RegisterObject(context);
  2010. Light::RegisterObject(context);
  2011. StaticModel::RegisterObject(context);
  2012. Skybox::RegisterObject(context);
  2013. AnimatedModel::RegisterObject(context);
  2014. AnimationController::RegisterObject(context);
  2015. BillboardSet::RegisterObject(context);
  2016. ParticleEmitter::RegisterObject(context);
  2017. DebugRenderer::RegisterObject(context);
  2018. Octree::RegisterObject(context);
  2019. Zone::RegisterObject(context);
  2020. }