OGLGraphics.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035
  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 "StringUtils.h"
  49. #include "Technique.h"
  50. #include "Texture2D.h"
  51. #include "TextureCube.h"
  52. #include "VertexBuffer.h"
  53. #include "Zone.h"
  54. #include <stdio.h>
  55. #include "DebugNew.h"
  56. static const unsigned glCmpFunc[] =
  57. {
  58. GL_ALWAYS,
  59. GL_EQUAL,
  60. GL_NOTEQUAL,
  61. GL_LESS,
  62. GL_LEQUAL,
  63. GL_GREATER,
  64. GL_GEQUAL
  65. };
  66. static const unsigned glSrcBlend[] =
  67. {
  68. GL_ONE,
  69. GL_ONE,
  70. GL_DST_COLOR,
  71. GL_SRC_ALPHA,
  72. GL_SRC_ALPHA,
  73. GL_ONE,
  74. GL_ONE_MINUS_DST_ALPHA
  75. };
  76. static const unsigned glDestBlend[] =
  77. {
  78. GL_ZERO,
  79. GL_ONE,
  80. GL_ZERO,
  81. GL_ONE_MINUS_SRC_ALPHA,
  82. GL_ONE,
  83. GL_ONE_MINUS_SRC_ALPHA,
  84. GL_DST_ALPHA
  85. };
  86. static const unsigned glStencilOps[] =
  87. {
  88. GL_KEEP,
  89. GL_ZERO,
  90. GL_REPLACE,
  91. GL_INCR_WRAP,
  92. GL_DECR_WRAP
  93. };
  94. static unsigned numInstances = 0;
  95. static const String noParameter;
  96. int CloseCallback(GLFWwindow window)
  97. {
  98. // Do not let GLFW close the window, rather do it ourselves in a controlled fashion
  99. Context* context = GetWindowContext(window);
  100. if (context)
  101. {
  102. Graphics* graphics = context->GetSubsystem<Graphics>();
  103. if (graphics)
  104. graphics->Close();
  105. }
  106. return GL_FALSE;
  107. }
  108. OBJECTTYPESTATIC(Graphics);
  109. Graphics::Graphics(Context* context_) :
  110. Object(context_),
  111. impl_(new GraphicsImpl()),
  112. width_(0),
  113. height_(0),
  114. multiSample_(1),
  115. fullscreen_(false),
  116. vsync_(false),
  117. tripleBuffer_(false),
  118. flushGPU_(true),
  119. lightPrepassSupport_(false),
  120. hardwareDepthSupport_(false),
  121. numPrimitives_(0),
  122. numBatches_(0),
  123. defaultTextureFilterMode_(FILTER_BILINEAR),
  124. shadowMapFormat_(GL_DEPTH_COMPONENT16),
  125. hiresShadowMapFormat_(GL_DEPTH_COMPONENT24),
  126. shaderParameterFrame_(0)
  127. {
  128. ResetCachedState();
  129. SetTextureUnitMappings();
  130. {
  131. MutexLock lock(GetStaticMutex());
  132. if (!numInstances)
  133. glfwInit();
  134. ++numInstances;
  135. }
  136. }
  137. Graphics::~Graphics()
  138. {
  139. Close();
  140. delete impl_;
  141. impl_ = 0;
  142. {
  143. MutexLock lock(GetStaticMutex());
  144. --numInstances;
  145. if (!numInstances)
  146. glfwTerminate();
  147. }
  148. }
  149. void Graphics::SetWindowTitle(const String& windowTitle)
  150. {
  151. windowTitle_ = windowTitle;
  152. if (impl_->window_)
  153. glfwSetWindowTitle(impl_->window_, windowTitle_.CString());
  154. }
  155. bool Graphics::SetMode(int width, int height, bool fullscreen, bool vsync, bool tripleBuffer, int multiSample)
  156. {
  157. PROFILE(SetScreenMode);
  158. multiSample = Clamp(multiSample, 1, 16);
  159. if (IsInitialized() && width == width_ && height == height_ && fullscreen == fullscreen_ &&
  160. vsync == vsync_ && tripleBuffer == tripleBuffer_ && multiSample == multiSample_)
  161. return true;
  162. // If only vsync changes, do not destroy/recreate the context
  163. if (IsInitialized() && width == width_ && height == height_ && fullscreen == fullscreen_ &&
  164. tripleBuffer == tripleBuffer_ && multiSample == multiSample_ && vsync != vsync_)
  165. {
  166. glfwSwapInterval(vsync ? 1 : 0);
  167. vsync_ = vsync;
  168. return true;
  169. }
  170. // If zero dimensions in windowed mode, set default. If zero in fullscreen, use desktop mode
  171. if (!width || !height)
  172. {
  173. if (!fullscreen)
  174. {
  175. width = 800;
  176. height = 600;
  177. }
  178. else
  179. {
  180. GLFWvidmode mode;
  181. glfwGetDesktopMode(&mode);
  182. width = mode.width;
  183. height = mode.height;
  184. }
  185. }
  186. // Close the existing window
  187. Release();
  188. {
  189. // GLFW window parameters and the window list are static, so need to operate under static lock
  190. MutexLock lock(GetStaticMutex());
  191. glfwOpenWindowHint(GLFW_RED_BITS, 8);
  192. glfwOpenWindowHint(GLFW_GREEN_BITS, 8);
  193. glfwOpenWindowHint(GLFW_BLUE_BITS, 8);
  194. glfwOpenWindowHint(GLFW_ALPHA_BITS, 0);
  195. glfwOpenWindowHint(GLFW_DEPTH_BITS, 24);
  196. glfwOpenWindowHint(GLFW_STENCIL_BITS, 8);
  197. glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
  198. if (multiSample > 1)
  199. glfwOpenWindowHint(GLFW_FSAA_SAMPLES, multiSample);
  200. else
  201. glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 0);
  202. impl_->window_ = glfwOpenWindow(width, height, fullscreen ? GLFW_FULLSCREEN : GLFW_WINDOWED, windowTitle_.CString(), 0);
  203. if (!impl_->window_)
  204. {
  205. LOGERROR("Could not open window");
  206. return false;
  207. }
  208. // If OpenGL extensions not yet initialized, initialize now
  209. if (!GLeeInitialized())
  210. GLeeInit();
  211. if (!_GLEE_VERSION_2_0)
  212. {
  213. LOGERROR("OpenGL 2.0 is required");
  214. glfwCloseWindow(impl_->window_);
  215. return false;
  216. }
  217. if (!_GLEE_EXT_framebuffer_object || !_GLEE_EXT_packed_depth_stencil || !_GLEE_EXT_texture_compression_s3tc ||
  218. !_GLEE_EXT_texture_filter_anisotropic)
  219. {
  220. LOGERROR("EXT_framebuffer_object, EXT_packed_depth_stencil, EXT_texture_compression_s3tc and "
  221. "EXT_texture_filter_anisotropic OpenGL extensions are required");
  222. glfwCloseWindow(impl_->window_);
  223. return false;
  224. }
  225. // Set window close callback
  226. glfwSetWindowCloseCallback(CloseCallback);
  227. // Associate GLFW window with the execution context
  228. SetWindowContext(impl_->window_, context_);
  229. }
  230. // Set vsync
  231. glfwSwapInterval(vsync ? 1 : 0);
  232. // Query for system backbuffer depth
  233. glGetIntegerv(GL_DEPTH_BITS, &impl_->windowDepthBits_);
  234. impl_->depthBits_ = impl_->windowDepthBits_;
  235. // Create the FBO
  236. glGenFramebuffersEXT(1, &impl_->fbo_);
  237. // Set initial state to match Direct3D
  238. glEnable(GL_DEPTH_TEST);
  239. SetCullMode(CULL_CCW);
  240. SetDepthTest(CMP_LESSEQUAL);
  241. glfwGetWindowSize(impl_->window_, &width_, &height_);
  242. fullscreen_ = fullscreen;
  243. vsync_ = vsync;
  244. tripleBuffer_ = tripleBuffer;
  245. multiSample_ = multiSample;
  246. // Reset render targets and viewport for the new screen mode
  247. ResetRenderTargets();
  248. // Clear the window to black now, because GPU object restore may take time
  249. Clear(CLEAR_COLOR);
  250. glfwSwapBuffers();
  251. // Let GPU objects restore themselves
  252. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  253. (*i)->OnDeviceReset();
  254. CheckFeatureSupport();
  255. if (multiSample > 1)
  256. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed") +
  257. " multisample " + String(multiSample));
  258. else
  259. LOGINFO("Set screen mode " + String(width_) + "x" + String(height_) + " " + (fullscreen_ ? "fullscreen" : "windowed"));
  260. using namespace ScreenMode;
  261. VariantMap eventData;
  262. eventData[P_WIDTH] = width_;
  263. eventData[P_HEIGHT] = height_;
  264. eventData[P_FULLSCREEN] = fullscreen_;
  265. SendEvent(E_SCREENMODE, eventData);
  266. return true;
  267. }
  268. bool Graphics::SetMode(int width, int height)
  269. {
  270. return SetMode(width, height, fullscreen_, vsync_, tripleBuffer_, multiSample_);
  271. }
  272. bool Graphics::ToggleFullscreen()
  273. {
  274. return SetMode(width_, height_, !fullscreen_, vsync_, tripleBuffer_, multiSample_);
  275. }
  276. void Graphics::Close()
  277. {
  278. if (!IsInitialized())
  279. return;
  280. // Release all GPU objects that still exist
  281. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  282. (*i)->Release();
  283. gpuObjects_.Clear();
  284. // Actually close the window
  285. Release();
  286. }
  287. bool Graphics::TakeScreenShot(Image& destImage)
  288. {
  289. PROFILE(TakeScreenShot);
  290. ResetRenderTargets();
  291. destImage.SetSize(width_, height_, 3);
  292. glReadPixels(0, 0, width_, height_, GL_RGB, GL_UNSIGNED_BYTE, destImage.GetData());
  293. return true;
  294. }
  295. void Graphics::SetFlushGPU(bool enable)
  296. {
  297. flushGPU_ = enable;
  298. }
  299. bool Graphics::BeginFrame()
  300. {
  301. PROFILE(BeginRendering);
  302. if (!IsInitialized())
  303. return false;
  304. // If we should be fullscreen, but are not currently active, do not render
  305. if (fullscreen_ && (!glfwGetWindowParam(impl_->window_, GLFW_ACTIVE) || glfwGetWindowParam(impl_->window_, GLFW_ICONIFIED)))
  306. return false;
  307. // Set default render target and depth buffer
  308. ResetRenderTargets();
  309. // Cleanup textures from previous frame
  310. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  311. SetTexture(i, 0);
  312. // Enable color and depth write
  313. SetColorWrite(true);
  314. SetDepthWrite(true);
  315. numPrimitives_ = 0;
  316. numBatches_ = 0;
  317. SendEvent(E_BEGINRENDERING);
  318. return true;
  319. }
  320. void Graphics::EndFrame()
  321. {
  322. PROFILE(EndRendering);
  323. if (!IsInitialized())
  324. return;
  325. SendEvent(E_ENDRENDERING);
  326. glfwSwapBuffers();
  327. }
  328. void Graphics::Clear(unsigned flags, const Color& color, float depth, unsigned stencil)
  329. {
  330. bool oldColorWrite = colorWrite_;
  331. bool oldDepthWrite = depthWrite_;
  332. if (flags & CLEAR_COLOR && !oldColorWrite)
  333. SetColorWrite(true);
  334. if (flags & CLEAR_DEPTH && !oldDepthWrite)
  335. SetDepthWrite(true);
  336. unsigned glFlags = 0;
  337. if (flags & CLEAR_COLOR)
  338. {
  339. glFlags |= GL_COLOR_BUFFER_BIT;
  340. glClearColor(color.r_, color.g_, color.b_, color.a_);
  341. }
  342. if (flags & CLEAR_DEPTH)
  343. {
  344. glFlags |= GL_DEPTH_BUFFER_BIT;
  345. glClearDepth(depth);
  346. }
  347. if (flags & CLEAR_STENCIL)
  348. {
  349. glFlags |= GL_STENCIL_BUFFER_BIT;
  350. glClearStencil(stencil);
  351. }
  352. // If viewport is less than full screen, set a scissor to limit the clear
  353. /// \todo Any user-set scissor test will be lost
  354. IntVector2 viewSize = GetRenderTargetDimensions();
  355. if (viewport_.left_ != 0 || viewport_.top_ != 0 || viewport_.right_ != viewSize.x_ || viewport_.bottom_ != viewSize.y_)
  356. SetScissorTest(true, IntRect(0, 0, viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_));
  357. else
  358. SetScissorTest(false);
  359. glClear(glFlags);
  360. SetScissorTest(false);
  361. SetColorWrite(oldColorWrite);
  362. SetDepthWrite(oldDepthWrite);
  363. }
  364. void Graphics::Draw(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  365. {
  366. if (!vertexCount)
  367. return;
  368. unsigned primitiveCount = 0;
  369. switch (type)
  370. {
  371. case TRIANGLE_LIST:
  372. primitiveCount = vertexCount / 3;
  373. glDrawArrays(GL_TRIANGLES, vertexStart, vertexCount);
  374. break;
  375. case LINE_LIST:
  376. primitiveCount = vertexCount / 2;
  377. glDrawArrays(GL_LINES, vertexStart, vertexCount);
  378. break;
  379. }
  380. numPrimitives_ += primitiveCount;
  381. ++numBatches_;
  382. }
  383. void Graphics::Draw(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  384. {
  385. if (!indexCount || !indexBuffer_)
  386. return;
  387. unsigned primitiveCount = 0;
  388. unsigned indexSize = indexBuffer_->GetIndexSize();
  389. switch (type)
  390. {
  391. case TRIANGLE_LIST:
  392. primitiveCount = indexCount / 3;
  393. if (indexSize == sizeof(unsigned short))
  394. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (const GLvoid*)(indexStart * indexSize));
  395. else
  396. glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, (const GLvoid*)(indexStart * indexSize));
  397. break;
  398. case LINE_LIST:
  399. primitiveCount = indexCount / 2;
  400. if (indexSize == sizeof(unsigned short))
  401. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_SHORT, (const GLvoid*)(indexStart * indexSize));
  402. else
  403. glDrawElements(GL_LINES, indexCount, GL_UNSIGNED_INT, (const GLvoid*)(indexStart * indexSize));
  404. break;
  405. }
  406. numPrimitives_ += primitiveCount;
  407. ++numBatches_;
  408. }
  409. void Graphics::DrawInstanced(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount, unsigned instanceCount)
  410. {
  411. }
  412. void Graphics::SetVertexBuffer(VertexBuffer* buffer)
  413. {
  414. Vector<VertexBuffer*> vertexBuffers(1);
  415. PODVector<unsigned> elementMasks(1);
  416. vertexBuffers[0] = buffer;
  417. elementMasks[0] = MASK_DEFAULT;
  418. SetVertexBuffers(vertexBuffers, elementMasks);
  419. }
  420. bool Graphics::SetVertexBuffers(const Vector<VertexBuffer*>& buffers, const PODVector<unsigned>& elementMasks,
  421. unsigned instanceOffset)
  422. {
  423. if (buffers.Size() > MAX_VERTEX_STREAMS)
  424. {
  425. LOGERROR("Too many vertex buffers");
  426. return false;
  427. }
  428. if (buffers.Size() != elementMasks.Size())
  429. {
  430. LOGERROR("Amount of element masks and vertex buffers does not match");
  431. return false;
  432. }
  433. // If no valid shader to determine the attribute bindings, can not set vertex buffers
  434. if (!shaderProgram_)
  435. return false;
  436. const int* attributeLocations = shaderProgram_->GetAttributeLocations();
  437. bool changed = false;
  438. unsigned newAttributes = 0;
  439. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  440. {
  441. VertexBuffer* buffer = 0;
  442. unsigned elementMask = 0;
  443. if (i < buffers.Size())
  444. {
  445. buffer = buffers[i];
  446. elementMask = elementMasks[i];
  447. if (elementMask == MASK_DEFAULT && buffer)
  448. elementMask = buffers[i]->GetElementMask();
  449. }
  450. // If buffer and element mask have stayed the same, skip to the next buffer
  451. if (buffer == vertexBuffers_[i] && elementMask == elementMasks_[i])
  452. continue;
  453. vertexBuffers_[i] = buffer;
  454. elementMasks_[i] = elementMask;
  455. changed = true;
  456. if (!buffer)
  457. continue;
  458. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  459. unsigned vertexSize = buffer->GetVertexSize();
  460. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  461. {
  462. // If shader does not use the attribute, do not bind it (bandwidth optimization)
  463. int attributeIndex = attributeLocations[j];
  464. if (attributeIndex < 0)
  465. continue;
  466. unsigned elementBit = 1 << j;
  467. unsigned attributeBit = 1 << attributeIndex;
  468. if (elementMask & elementBit)
  469. {
  470. newAttributes |= attributeBit;
  471. // Enable attribute if not enabled yet
  472. if ((impl_->enabledAttributes_ & attributeBit) == 0)
  473. {
  474. glEnableVertexAttribArray(attributeIndex);
  475. impl_->enabledAttributes_ |= attributeBit;
  476. }
  477. // Set the attribute pointer
  478. glVertexAttribPointer(attributeIndex, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  479. VertexBuffer::elementNormalize[j], vertexSize, (const GLvoid*)(buffer->GetElementOffset((VertexElement)j)));
  480. }
  481. }
  482. }
  483. if (!changed)
  484. return true;
  485. // Now check which vertex attributes should be disabled
  486. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  487. int disableIndex = 0;
  488. while (disableAttributes)
  489. {
  490. if (disableAttributes & 1)
  491. {
  492. glDisableVertexAttribArray(disableIndex);
  493. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  494. }
  495. disableAttributes >>= 1;
  496. ++disableIndex;
  497. }
  498. return true;
  499. }
  500. bool Graphics::SetVertexBuffers(const Vector<SharedPtr<VertexBuffer> >& buffers, const PODVector<unsigned>&
  501. elementMasks, unsigned instanceOffset)
  502. {
  503. if (buffers.Size() > MAX_VERTEX_STREAMS)
  504. {
  505. LOGERROR("Too many vertex buffers");
  506. return false;
  507. }
  508. if (buffers.Size() != elementMasks.Size())
  509. {
  510. LOGERROR("Amount of element masks and vertex buffers does not match");
  511. return false;
  512. }
  513. // If no valid shader to determine the attribute bindings, can not set vertex buffers
  514. if (!shaderProgram_)
  515. return false;
  516. const int* attributeLocations = shaderProgram_->GetAttributeLocations();
  517. bool changed = false;
  518. unsigned newAttributes = 0;
  519. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  520. {
  521. VertexBuffer* buffer = 0;
  522. unsigned elementMask = 0;
  523. if (i < buffers.Size())
  524. {
  525. buffer = buffers[i];
  526. elementMask = elementMasks[i];
  527. if (elementMask == MASK_DEFAULT && buffer)
  528. elementMask = buffers[i]->GetElementMask();
  529. }
  530. // If buffer and element mask have stayed the same, skip to the next buffer
  531. if (buffer == vertexBuffers_[i] && elementMask == elementMasks_[i])
  532. continue;
  533. vertexBuffers_[i] = buffer;
  534. elementMasks_[i] = elementMask;
  535. changed = true;
  536. if (!buffer)
  537. continue;
  538. glBindBuffer(GL_ARRAY_BUFFER, buffer->GetGPUObject());
  539. unsigned vertexSize = buffer->GetVertexSize();
  540. for (unsigned j = 0; j < MAX_VERTEX_ELEMENTS; ++j)
  541. {
  542. // If shader does not use the attribute, do not bind it (bandwidth optimization)
  543. int attributeIndex = attributeLocations[j];
  544. if (attributeIndex < 0)
  545. continue;
  546. unsigned elementBit = 1 << j;
  547. unsigned attributeBit = 1 << attributeIndex;
  548. if (elementMask & elementBit)
  549. {
  550. newAttributes |= attributeBit;
  551. // Enable attribute if not enabled yet
  552. if ((impl_->enabledAttributes_ & attributeBit) == 0)
  553. {
  554. glEnableVertexAttribArray(attributeIndex);
  555. impl_->enabledAttributes_ |= attributeBit;
  556. }
  557. // Set the attribute pointer
  558. glVertexAttribPointer(attributeIndex, VertexBuffer::elementComponents[j], VertexBuffer::elementType[j],
  559. VertexBuffer::elementNormalize[j], vertexSize, (const GLvoid*)(buffer->GetElementOffset((VertexElement)j)));
  560. }
  561. }
  562. }
  563. if (!changed)
  564. return true;
  565. // Now check which vertex attributes should be disabled
  566. unsigned disableAttributes = impl_->enabledAttributes_ & (~newAttributes);
  567. int disableIndex = 0;
  568. while (disableAttributes)
  569. {
  570. if (disableAttributes & 1)
  571. {
  572. glDisableVertexAttribArray(disableIndex);
  573. impl_->enabledAttributes_ &= ~(1 << disableIndex);
  574. }
  575. disableAttributes >>= 1;
  576. ++disableIndex;
  577. }
  578. return true;
  579. }
  580. void Graphics::SetIndexBuffer(IndexBuffer* buffer)
  581. {
  582. if (indexBuffer_ == buffer)
  583. return;
  584. if (buffer)
  585. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->GetGPUObject());
  586. else
  587. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
  588. indexBuffer_ = buffer;
  589. }
  590. void Graphics::SetShaders(ShaderVariation* vs, ShaderVariation* ps)
  591. {
  592. if (vs == vertexShader_ && ps == pixelShader_)
  593. return;
  594. // Compile the shaders now if not yet compiled. If already attempted, do not retry
  595. if (vs && !vs->IsCompiled())
  596. {
  597. if (vs->GetCompilerOutput().Empty())
  598. {
  599. PROFILE(CompileVertexShader);
  600. bool success = vs->Create();
  601. if (success)
  602. LOGDEBUG("Compiled vertex shader " + vs->GetName());
  603. else
  604. {
  605. LOGERROR("Failed to compile vertex shader " + vs->GetName() + ":\n" + vs->GetCompilerOutput());
  606. vs = 0;
  607. }
  608. }
  609. else
  610. vs = 0;
  611. }
  612. if (ps && !ps->IsCompiled())
  613. {
  614. if (ps->GetCompilerOutput().Empty())
  615. {
  616. PROFILE(CompilePixelShader);
  617. bool success = ps->Create();
  618. if (success)
  619. LOGDEBUG("Compiled pixel shader " + ps->GetName());
  620. else
  621. {
  622. LOGERROR("Failed to compile pixel shader " + ps->GetName() + ":\n" + ps->GetCompilerOutput());
  623. ps = 0;
  624. }
  625. }
  626. else
  627. ps = 0;
  628. }
  629. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  630. {
  631. vertexBuffers_[i] = 0;
  632. elementMasks_[i] = 0;
  633. }
  634. if (!vs || !ps)
  635. {
  636. glUseProgram(0);
  637. vertexShader_ = 0;
  638. pixelShader_ = 0;
  639. shaderProgram_ = 0;
  640. }
  641. else
  642. {
  643. vertexShader_ = vs;
  644. pixelShader_ = ps;
  645. Pair<ShaderVariation*, ShaderVariation*> combination(vs, ps);
  646. ShaderProgramMap::Iterator i = shaderPrograms_.Find(combination);
  647. if (i != shaderPrograms_.End())
  648. {
  649. // Use the existing linked program
  650. if (i->second_->IsLinked())
  651. {
  652. glUseProgram(i->second_->GetGPUObject());
  653. shaderProgram_ = i->second_;
  654. }
  655. else
  656. {
  657. glUseProgram(0);
  658. shaderProgram_ = 0;
  659. }
  660. }
  661. else
  662. {
  663. // Link a new combination
  664. SharedPtr<ShaderProgram> newProgram(new ShaderProgram(this, vs, ps));
  665. if (newProgram->Link())
  666. {
  667. LOGDEBUG("Linked vertex shader " + vs->GetName() + " and pixel shader " + ps->GetName());
  668. // Note: Link() calls glUseProgram() to set the texture sampler uniforms,
  669. // so it is not necessary to call it again
  670. shaderProgram_ = newProgram;
  671. }
  672. else
  673. {
  674. LOGERROR("Failed to link vertex shader " + vs->GetName() + " and pixel shader " + ps->GetName() + ":\n" +
  675. newProgram->GetLinkerOutput());
  676. glUseProgram(0);
  677. shaderProgram_ = 0;
  678. }
  679. shaderPrograms_[combination] = newProgram;
  680. }
  681. }
  682. }
  683. void Graphics::SetShaderParameter(StringHash param, const float* data, unsigned count)
  684. {
  685. if (shaderProgram_)
  686. {
  687. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  688. if (info)
  689. {
  690. switch (info->type_)
  691. {
  692. case GL_FLOAT:
  693. glUniform1fv(info->location_, count, data);
  694. break;
  695. case GL_FLOAT_VEC2:
  696. glUniform2fv(info->location_, count / 2, data);
  697. break;
  698. case GL_FLOAT_VEC3:
  699. glUniform3fv(info->location_, count / 3, data);
  700. break;
  701. case GL_FLOAT_VEC4:
  702. glUniform4fv(info->location_, count / 4, data);
  703. break;
  704. case GL_FLOAT_MAT3:
  705. glUniformMatrix3fv(info->location_, count / 9, GL_TRUE, data);
  706. break;
  707. case GL_FLOAT_MAT4:
  708. glUniformMatrix4fv(info->location_, count / 16, GL_TRUE, data);
  709. break;
  710. }
  711. }
  712. }
  713. }
  714. void Graphics::SetShaderParameter(StringHash param, float value)
  715. {
  716. if (shaderProgram_)
  717. {
  718. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  719. if (info)
  720. glUniform1fv(info->location_, 1, &value);
  721. }
  722. }
  723. void Graphics::SetShaderParameter(StringHash param, const Color& color)
  724. {
  725. SetShaderParameter(param, color.GetData(), 4);
  726. }
  727. void Graphics::SetShaderParameter(StringHash param, const Matrix3& matrix)
  728. {
  729. if (shaderProgram_)
  730. {
  731. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  732. if (info)
  733. glUniformMatrix3fv(info->location_, 1, GL_TRUE, matrix.GetData());
  734. }
  735. }
  736. void Graphics::SetShaderParameter(StringHash param, const Vector3& vector)
  737. {
  738. if (shaderProgram_)
  739. {
  740. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  741. if (info)
  742. {
  743. // Check the uniform type to avoid mismatch
  744. switch (info->type_)
  745. {
  746. case GL_FLOAT:
  747. glUniform1fv(info->location_, 1, vector.GetData());
  748. break;
  749. case GL_FLOAT_VEC2:
  750. glUniform2fv(info->location_, 1, vector.GetData());
  751. break;
  752. case GL_FLOAT_VEC3:
  753. glUniform3fv(info->location_, 1, vector.GetData());
  754. break;
  755. }
  756. }
  757. }
  758. }
  759. void Graphics::SetShaderParameter(StringHash param, const Matrix4& matrix)
  760. {
  761. if (shaderProgram_)
  762. {
  763. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  764. if (info)
  765. glUniformMatrix4fv(info->location_, 1, GL_TRUE, matrix.GetData());
  766. }
  767. }
  768. void Graphics::SetShaderParameter(StringHash param, const Vector4& vector)
  769. {
  770. if (shaderProgram_)
  771. {
  772. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  773. if (info)
  774. {
  775. // Check the uniform type to avoid mismatch
  776. switch (info->type_)
  777. {
  778. case GL_FLOAT:
  779. glUniform1fv(info->location_, 1, vector.GetData());
  780. break;
  781. case GL_FLOAT_VEC2:
  782. glUniform2fv(info->location_, 1, vector.GetData());
  783. break;
  784. case GL_FLOAT_VEC3:
  785. glUniform3fv(info->location_, 1, vector.GetData());
  786. break;
  787. case GL_FLOAT_VEC4:
  788. glUniform4fv(info->location_, 1, vector.GetData());
  789. break;
  790. }
  791. }
  792. }
  793. }
  794. void Graphics::SetShaderParameter(StringHash param, const Matrix3x4& matrix)
  795. {
  796. if (shaderProgram_)
  797. {
  798. const ShaderParameter* info = shaderProgram_->GetParameter(param);
  799. if (info)
  800. {
  801. float data[16];
  802. data[0] = matrix.m00_;
  803. data[1] = matrix.m01_;
  804. data[2] = matrix.m02_;
  805. data[3] = matrix.m03_;
  806. data[4] = matrix.m10_;
  807. data[5] = matrix.m11_;
  808. data[6] = matrix.m12_;
  809. data[7] = matrix.m13_;
  810. data[8] = matrix.m20_;
  811. data[9] = matrix.m21_;
  812. data[10] = matrix.m22_;
  813. data[11] = matrix.m23_;
  814. data[12] = 0.0f;
  815. data[13] = 0.0f;
  816. data[14] = 0.0f;
  817. data[15] = 1.0f;
  818. glUniformMatrix4fv(info->location_, 1, GL_TRUE, data);
  819. }
  820. }
  821. }
  822. bool Graphics::NeedParameterUpdate(StringHash param, const void* source)
  823. {
  824. if (shaderProgram_)
  825. return shaderProgram_->NeedParameterUpdate(param, source, shaderParameterFrame_);
  826. return false;
  827. }
  828. bool Graphics::NeedTextureUnit(TextureUnit unit)
  829. {
  830. if (shaderProgram_ && shaderProgram_->HasTextureUnit(unit))
  831. return true;
  832. return false;
  833. }
  834. void Graphics::ClearParameterSource(StringHash param)
  835. {
  836. if (shaderProgram_)
  837. shaderProgram_->ClearParameterSource(param);
  838. }
  839. void Graphics::ClearParameterSources()
  840. {
  841. ++shaderParameterFrame_;
  842. }
  843. void Graphics::ClearTransformSources()
  844. {
  845. if (shaderProgram_)
  846. {
  847. shaderProgram_->ClearParameterSource(VSP_MODEL);
  848. shaderProgram_->ClearParameterSource(VSP_VIEWPROJ);
  849. }
  850. }
  851. void Graphics::CleanupShaderPrograms()
  852. {
  853. for (ShaderProgramMap::Iterator i = shaderPrograms_.Begin(); i != shaderPrograms_.End();)
  854. {
  855. ShaderProgramMap::Iterator current = i++;
  856. ShaderVariation* vs = current->second_->GetVertexShader();
  857. ShaderVariation* ps = current->second_->GetPixelShader();
  858. if (!vs || !ps || !vs->GetGPUObject() || !ps->GetGPUObject())
  859. shaderPrograms_.Erase(current);
  860. }
  861. }
  862. void Graphics::SetTexture(unsigned index, Texture* texture)
  863. {
  864. if (index >= MAX_TEXTURE_UNITS)
  865. return;
  866. // Check if texture is currently bound as a render target. In that case, use its backup texture, or blank if not defined
  867. if (texture)
  868. {
  869. if (texture == viewTexture_ || (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture))
  870. texture = texture->GetBackupTexture();
  871. }
  872. if (textures_[index] != texture)
  873. {
  874. if (impl_->activeTexture_ != index)
  875. {
  876. glActiveTexture(GL_TEXTURE0 + index);
  877. impl_->activeTexture_ = index;
  878. }
  879. if (texture)
  880. {
  881. unsigned glType = texture->GetTarget();
  882. if (glType != textureTypes_[index])
  883. {
  884. if (textureTypes_[index])
  885. glDisable(textureTypes_[index]);
  886. glEnable(glType);
  887. textureTypes_[index] = glType;
  888. }
  889. glBindTexture(glType, texture->GetGPUObject());
  890. if (texture->GetParametersDirty())
  891. texture->UpdateParameters();
  892. }
  893. else
  894. {
  895. if (textureTypes_[index])
  896. glBindTexture(textureTypes_[index], 0);
  897. }
  898. textures_[index] = texture;
  899. }
  900. else
  901. {
  902. if (texture && texture->GetParametersDirty())
  903. {
  904. if (impl_->activeTexture_ != index)
  905. {
  906. glActiveTexture(GL_TEXTURE0 + index);
  907. impl_->activeTexture_ = index;
  908. }
  909. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  910. texture->UpdateParameters();
  911. }
  912. }
  913. }
  914. void Graphics::SetTextureForUpdate(Texture* texture)
  915. {
  916. if (impl_->activeTexture_ != 0)
  917. {
  918. glActiveTexture(GL_TEXTURE0);
  919. impl_->activeTexture_ = 0;
  920. }
  921. glBindTexture(texture->GetTarget(), texture->GetGPUObject());
  922. textures_[0] = texture;
  923. }
  924. void Graphics::SetDefaultTextureFilterMode(TextureFilterMode mode)
  925. {
  926. if (mode != defaultTextureFilterMode_)
  927. {
  928. defaultTextureFilterMode_ = mode;
  929. SetTextureParametersDirty();
  930. }
  931. }
  932. void Graphics::SetTextureAnisotropy(unsigned level)
  933. {
  934. if (level != textureAnisotropy_)
  935. {
  936. textureAnisotropy_ = level;
  937. SetTextureParametersDirty();
  938. }
  939. }
  940. void Graphics::SetTextureParametersDirty()
  941. {
  942. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  943. {
  944. Texture* texture = dynamic_cast<Texture*>(*i);
  945. if (texture)
  946. texture->SetParametersDirty();
  947. }
  948. }
  949. void Graphics::ResetRenderTargets()
  950. {
  951. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  952. SetRenderTarget(i, (RenderSurface*)0);
  953. SetDepthStencil((RenderSurface*)0);
  954. }
  955. void Graphics::ResetRenderTarget(unsigned index)
  956. {
  957. SetRenderTarget(index, (RenderSurface*)0);
  958. }
  959. void Graphics::ResetDepthStencil()
  960. {
  961. SetDepthStencil((RenderSurface*)0);
  962. }
  963. void Graphics::SetRenderTarget(unsigned index, RenderSurface* renderTarget)
  964. {
  965. if (index >= MAX_RENDERTARGETS)
  966. return;
  967. if (renderTarget != renderTargets_[index])
  968. {
  969. renderTargets_[index] = renderTarget;
  970. // If the render target is also bound as a texture, replace with backup texture or null
  971. if (renderTarget)
  972. {
  973. Texture* parentTexture = renderTarget->GetParentTexture();
  974. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  975. {
  976. if (textures_[i] == parentTexture)
  977. SetTexture(i, textures_[i]->GetBackupTexture());
  978. }
  979. }
  980. // Bind the FBO to be able to make changes to it
  981. if (!impl_->fboBound_)
  982. {
  983. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->fbo_);
  984. impl_->fboBound_ = true;
  985. }
  986. if (renderTarget)
  987. {
  988. Texture* texture = renderTarget->GetParentTexture();
  989. // If texture's parameters are dirty, update before attaching
  990. if (texture->GetParametersDirty())
  991. {
  992. SetTextureForUpdate(texture);
  993. texture->UpdateParameters();
  994. SetTexture(0, 0);
  995. }
  996. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, renderTarget->GetTarget(), texture->GetGPUObject(), 0);
  997. }
  998. else
  999. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, GL_TEXTURE_2D, 0, 0);
  1000. // Disable color buffer writing/reading if only a depth texture is to be used:
  1001. // otherwise it is an OpenGL error (incomplete framebuffer)
  1002. SetDrawBuffers();
  1003. // If all render targets and the depth buffer are not textures, revert to backbuffer rendering
  1004. bool noFBO = (depthStencil_ == 0);
  1005. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1006. {
  1007. if (renderTargets_[i])
  1008. {
  1009. noFBO = false;
  1010. break;
  1011. }
  1012. }
  1013. if (noFBO && impl_->fboBound_)
  1014. {
  1015. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1016. impl_->fboBound_ = false;
  1017. }
  1018. }
  1019. }
  1020. void Graphics::SetRenderTarget(unsigned index, Texture2D* texture)
  1021. {
  1022. RenderSurface* renderTarget = 0;
  1023. if (texture)
  1024. renderTarget = texture->GetRenderSurface();
  1025. SetRenderTarget(index, renderTarget);
  1026. }
  1027. void Graphics::SetDepthStencil(RenderSurface* depthStencil)
  1028. {
  1029. // If we are using a render target texture, it is required in OpenGL to also have an own depth stencil
  1030. // Create a new depth stencil texture as necessary to be able to provide similar behaviour as Direct3D9
  1031. if (renderTargets_[0] && !depthStencil)
  1032. {
  1033. int width = renderTargets_[0]->GetWidth();
  1034. int height = renderTargets_[0]->GetHeight();
  1035. // Direct3D9 default depth stencil can not be used when render target is larger than the window.
  1036. // Check size similarly
  1037. if (width <= width_ && height <= height_)
  1038. {
  1039. int searchKey = (width << 16) | height;
  1040. HashMap<int, SharedPtr<Texture2D> >::Iterator i = depthTextures_.Find(searchKey);
  1041. if (i != depthTextures_.End())
  1042. depthStencil = i->second_->GetRenderSurface();
  1043. else
  1044. {
  1045. SharedPtr<Texture2D> newDepthTexture(new Texture2D(context_));
  1046. newDepthTexture->SetSize(width, height, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1047. depthTextures_[searchKey] = newDepthTexture;
  1048. depthStencil = newDepthTexture->GetRenderSurface();
  1049. }
  1050. }
  1051. }
  1052. if (depthStencil != depthStencil_)
  1053. {
  1054. /// \todo Should check that the texture actually is in depth format
  1055. depthStencil_ = depthStencil;
  1056. // Bind the FBO to be able to make changes to it
  1057. if (!impl_->fboBound_)
  1058. {
  1059. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->fbo_);
  1060. impl_->fboBound_ = true;
  1061. }
  1062. if (depthStencil)
  1063. {
  1064. // Bind either a renderbuffer or a depth texture, depending on what is available
  1065. Texture* texture = depthStencil->GetParentTexture();
  1066. bool hasStencil = texture->GetFormat() == GetDepthStencilFormat();
  1067. unsigned renderBufferID = depthStencil->GetRenderBuffer();
  1068. if (!renderBufferID)
  1069. {
  1070. // If texture's parameters are dirty, update before attaching
  1071. if (texture->GetParametersDirty())
  1072. {
  1073. SetTextureForUpdate(texture);
  1074. texture->UpdateParameters();
  1075. SetTexture(0, 0);
  1076. }
  1077. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, texture->GetGPUObject(), 0);
  1078. if (hasStencil)
  1079. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, texture->GetGPUObject(), 0);
  1080. else
  1081. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1082. impl_->depthBits_ = texture->GetDepthBits();
  1083. }
  1084. else
  1085. {
  1086. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBufferID);
  1087. if (hasStencil)
  1088. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBufferID);
  1089. else
  1090. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1091. impl_->depthBits_ = 24;
  1092. }
  1093. }
  1094. else
  1095. {
  1096. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1097. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1098. impl_->depthBits_ = impl_->windowDepthBits_;
  1099. }
  1100. // Disable color buffer writing/reading if only a depth texture is to be used:
  1101. // otherwise it is an OpenGL error (incomplete framebuffer)
  1102. SetDrawBuffers();
  1103. // If all render targets and the depth buffer are not textures, revert to backbuffer rendering
  1104. bool noFBO = (depthStencil_ == 0);
  1105. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1106. {
  1107. if (renderTargets_[i])
  1108. {
  1109. noFBO = false;
  1110. break;
  1111. }
  1112. }
  1113. if (noFBO && impl_->fboBound_)
  1114. {
  1115. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  1116. impl_->fboBound_ = false;
  1117. }
  1118. }
  1119. // Reset viewport and scissor test
  1120. IntVector2 viewSize = GetRenderTargetDimensions();
  1121. SetViewport(IntRect(0, 0, viewSize.x_, viewSize.y_));
  1122. }
  1123. void Graphics::SetDepthStencil(Texture2D* texture)
  1124. {
  1125. RenderSurface* depthStencil = 0;
  1126. if (texture)
  1127. depthStencil = texture->GetRenderSurface();
  1128. SetDepthStencil(depthStencil);
  1129. }
  1130. void Graphics::SetViewTexture(Texture* texture)
  1131. {
  1132. viewTexture_ = texture;
  1133. if (viewTexture_)
  1134. {
  1135. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1136. {
  1137. if (textures_[i] == viewTexture_)
  1138. SetTexture(i, textures_[i]->GetBackupTexture());
  1139. }
  1140. }
  1141. }
  1142. void Graphics::SetViewport(const IntRect& rect)
  1143. {
  1144. IntVector2 rtSize = GetRenderTargetDimensions();
  1145. IntRect rectCopy = rect;
  1146. if (rectCopy.right_ <= rectCopy.left_)
  1147. rectCopy.right_ = rectCopy.left_ + 1;
  1148. if (rectCopy.bottom_ <= rectCopy.top_)
  1149. rectCopy.bottom_ = rectCopy.top_ + 1;
  1150. rectCopy.left_ = Clamp(rectCopy.left_, 0, rtSize.x_);
  1151. rectCopy.top_ = Clamp(rectCopy.top_, 0, rtSize.y_);
  1152. rectCopy.right_ = Clamp(rectCopy.right_, 0, rtSize.x_);
  1153. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, rtSize.y_);
  1154. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1155. glViewport(rectCopy.left_, rtSize.y_ - rectCopy.bottom_, rectCopy.right_ - rectCopy.left_, rectCopy.bottom_ - rectCopy.top_);
  1156. viewport_ = rectCopy;
  1157. // Disable scissor test, needs to be re-enabled by the user
  1158. SetScissorTest(false);
  1159. }
  1160. void Graphics::SetAlphaTest(bool enable, CompareMode mode, float alphaRef)
  1161. {
  1162. if (enable != alphaTest_)
  1163. {
  1164. if (enable)
  1165. glEnable(GL_ALPHA_TEST);
  1166. else
  1167. glDisable(GL_ALPHA_TEST);
  1168. alphaTest_ = enable;
  1169. }
  1170. if (enable)
  1171. {
  1172. alphaRef = Clamp(alphaRef, 0.0f, 1.0f);
  1173. if (mode != alphaTestMode_ || alphaRef != alphaRef_)
  1174. {
  1175. glAlphaFunc(glCmpFunc[mode], alphaRef);
  1176. alphaTestMode_ = mode;
  1177. alphaRef_ = alphaRef;
  1178. }
  1179. }
  1180. }
  1181. void Graphics::SetBlendMode(BlendMode mode)
  1182. {
  1183. if (mode != blendMode_)
  1184. {
  1185. if (mode == BLEND_REPLACE)
  1186. glDisable(GL_BLEND);
  1187. else
  1188. {
  1189. glEnable(GL_BLEND);
  1190. glBlendFunc(glSrcBlend[mode], glDestBlend[mode]);
  1191. }
  1192. blendMode_ = mode;
  1193. }
  1194. }
  1195. void Graphics::SetColorWrite(bool enable)
  1196. {
  1197. if (enable != colorWrite_)
  1198. {
  1199. if (enable)
  1200. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1201. else
  1202. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1203. colorWrite_ = enable;
  1204. }
  1205. }
  1206. void Graphics::SetCullMode(CullMode mode)
  1207. {
  1208. if (mode != cullMode_)
  1209. {
  1210. if (mode == CULL_NONE)
  1211. glDisable(GL_CULL_FACE);
  1212. else
  1213. {
  1214. // Use Direct3D convention, ie. clockwise vertices define a front face
  1215. glEnable(GL_CULL_FACE);
  1216. glCullFace(mode == CULL_CCW ? GL_FRONT : GL_BACK);
  1217. }
  1218. cullMode_ = mode;
  1219. }
  1220. }
  1221. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1222. {
  1223. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1224. {
  1225. if (constantBias != 0.0f || slopeScaledBias != 0.0f)
  1226. {
  1227. // Bring the constant bias from Direct3D9 scale to OpenGL (depends on depth buffer bitdepth)
  1228. // Zero depth bits may be returned if using the packed depth stencil format. Assume 24bit in that case
  1229. int depthBits = Min(impl_->depthBits_, 23);
  1230. if (!depthBits)
  1231. depthBits = 23;
  1232. float adjustedConstantBias = constantBias * (float)(1 << (depthBits - 1));
  1233. float adjustedSlopeScaledBias = slopeScaledBias + 1.0f;
  1234. glEnable(GL_POLYGON_OFFSET_FILL);
  1235. glEnable(GL_POLYGON_OFFSET_LINE);
  1236. glPolygonOffset(adjustedSlopeScaledBias, adjustedConstantBias);
  1237. }
  1238. else
  1239. {
  1240. glDisable(GL_POLYGON_OFFSET_FILL);
  1241. glDisable(GL_POLYGON_OFFSET_LINE);
  1242. }
  1243. constantDepthBias_ = constantBias;
  1244. slopeScaledDepthBias_ = slopeScaledBias;
  1245. }
  1246. }
  1247. void Graphics::SetDepthTest(CompareMode mode)
  1248. {
  1249. if (mode != depthTestMode_)
  1250. {
  1251. glDepthFunc(glCmpFunc[mode]);
  1252. depthTestMode_ = mode;
  1253. }
  1254. }
  1255. void Graphics::SetDepthWrite(bool enable)
  1256. {
  1257. if (enable != depthWrite_)
  1258. {
  1259. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1260. depthWrite_ = enable;
  1261. }
  1262. }
  1263. void Graphics::SetFillMode(FillMode mode)
  1264. {
  1265. if (mode != fillMode_)
  1266. {
  1267. glPolygonMode(GL_FRONT_AND_BACK, mode == FILL_SOLID ? GL_FILL : GL_LINE);
  1268. fillMode_ = mode;
  1269. }
  1270. }
  1271. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1272. {
  1273. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1274. // Disable scissor in that case to reduce state changes
  1275. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1276. enable = false;
  1277. if (enable)
  1278. {
  1279. IntVector2 rtSize(GetRenderTargetDimensions());
  1280. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1281. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1282. IntRect intRect;
  1283. int expand = borderInclusive ? 1 : 0;
  1284. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1285. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1286. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1287. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1288. if (intRect.right_ == intRect.left_)
  1289. intRect.right_++;
  1290. if (intRect.bottom_ == intRect.top_)
  1291. intRect.bottom_++;
  1292. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1293. enable = false;
  1294. if (enable && scissorRect_ != intRect)
  1295. {
  1296. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1297. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1298. scissorRect_ = intRect;
  1299. }
  1300. }
  1301. else
  1302. scissorRect_ = IntRect::ZERO;
  1303. if (enable != scissorTest_)
  1304. {
  1305. if (enable)
  1306. glEnable(GL_SCISSOR_TEST);
  1307. else
  1308. glDisable(GL_SCISSOR_TEST);
  1309. scissorTest_ = enable;
  1310. }
  1311. }
  1312. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1313. {
  1314. IntVector2 rtSize(GetRenderTargetDimensions());
  1315. IntVector2 viewSize(viewport_.right_ - viewport_.left_, viewport_.bottom_ - viewport_.top_);
  1316. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  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. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1333. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.right_ - intRect.left_, intRect.bottom_ - intRect.top_);
  1334. scissorRect_ = intRect;
  1335. }
  1336. }
  1337. else
  1338. scissorRect_ = IntRect::ZERO;
  1339. if (enable != scissorTest_)
  1340. {
  1341. if (enable)
  1342. glEnable(GL_SCISSOR_TEST);
  1343. else
  1344. glDisable(GL_SCISSOR_TEST);
  1345. scissorTest_ = enable;
  1346. }
  1347. }
  1348. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1349. {
  1350. }
  1351. void Graphics::ResetStreamFrequencies()
  1352. {
  1353. }
  1354. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned stencilMask)
  1355. {
  1356. if (enable != stencilTest_)
  1357. {
  1358. if (enable)
  1359. glEnable(GL_STENCIL_TEST);
  1360. else
  1361. glDisable(GL_STENCIL_TEST);
  1362. stencilTest_ = enable;
  1363. }
  1364. if (enable)
  1365. {
  1366. if (mode != stencilTestMode_ || stencilRef != stencilRef_ || stencilMask != stencilMask_)
  1367. {
  1368. glStencilFunc(glCmpFunc[mode], stencilRef, stencilMask);
  1369. stencilTestMode_ = mode;
  1370. stencilRef_ = stencilRef;
  1371. stencilMask_ = stencilMask;
  1372. }
  1373. if (pass != stencilPass_ || fail != stencilFail_ || zFail != stencilZFail_)
  1374. {
  1375. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1376. stencilPass_ = pass;
  1377. stencilFail_ = fail;
  1378. stencilZFail_ = zFail;
  1379. }
  1380. }
  1381. }
  1382. void Graphics::SetForceSM2(bool enable)
  1383. {
  1384. }
  1385. void Graphics::SetForceFallback(bool enable)
  1386. {
  1387. }
  1388. bool Graphics::IsInitialized() const
  1389. {
  1390. return impl_->window_ != 0;
  1391. }
  1392. void* Graphics::GetWindowHandle() const
  1393. {
  1394. return impl_->window_;
  1395. }
  1396. PODVector<IntVector2> Graphics::GetResolutions() const
  1397. {
  1398. static const unsigned MAX_MODES = 256;
  1399. GLFWvidmode modes[MAX_MODES];
  1400. unsigned count = glfwGetVideoModes(modes, MAX_MODES);
  1401. PODVector<IntVector2> ret;
  1402. for (unsigned i = 0; i < count; ++i)
  1403. {
  1404. int width = modes[i].width;
  1405. int height = modes[i].height;
  1406. // Store mode if unique
  1407. bool unique = true;
  1408. for (unsigned j = 0; j < ret.Size(); ++i)
  1409. {
  1410. if (ret[j].x_ == width && ret[j].y_ == height)
  1411. {
  1412. unique = false;
  1413. break;
  1414. }
  1415. }
  1416. if (unique)
  1417. ret.Push(IntVector2(width, height));
  1418. }
  1419. return ret;
  1420. }
  1421. PODVector<int> Graphics::GetMultiSampleLevels() const
  1422. {
  1423. PODVector<int> ret;
  1424. // No multisampling always supported
  1425. ret.Push(1);
  1426. /// \todo Implement properly, if possible
  1427. return ret;
  1428. }
  1429. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1430. {
  1431. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1432. }
  1433. TextureUnit Graphics::GetTextureUnit(const String& name)
  1434. {
  1435. Map<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1436. if (i != textureUnits_.End())
  1437. return i->second_;
  1438. else
  1439. return MAX_TEXTURE_UNITS;
  1440. }
  1441. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1442. {
  1443. for (Map<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1444. {
  1445. if (i->second_ == unit)
  1446. return i->first_;
  1447. }
  1448. return noParameter;
  1449. }
  1450. Texture* Graphics::GetTexture(unsigned index) const
  1451. {
  1452. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1453. }
  1454. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1455. {
  1456. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1457. }
  1458. IntVector2 Graphics::GetRenderTargetDimensions() const
  1459. {
  1460. int width, height;
  1461. if (renderTargets_[0])
  1462. {
  1463. width = renderTargets_[0]->GetWidth();
  1464. height = renderTargets_[0]->GetHeight();
  1465. }
  1466. else if (depthStencil_)
  1467. {
  1468. width = depthStencil_->GetWidth();
  1469. height = depthStencil_->GetHeight();
  1470. }
  1471. else
  1472. {
  1473. width = width_;
  1474. height = height_;
  1475. }
  1476. return IntVector2(width, height);
  1477. }
  1478. void Graphics::AddGPUObject(GPUObject* object)
  1479. {
  1480. gpuObjects_.Push(object);
  1481. }
  1482. void Graphics::RemoveGPUObject(GPUObject* object)
  1483. {
  1484. Vector<GPUObject*>::Iterator i = gpuObjects_.Find(object);
  1485. if (i != gpuObjects_.End())
  1486. gpuObjects_.Erase(i);
  1487. }
  1488. void* Graphics::ReserveDiscardLockBuffer(unsigned size)
  1489. {
  1490. // First check for a free buffer that is large enough
  1491. for (Vector<DiscardLockBuffer>::Iterator i = discardLockBuffers_.Begin(); i != discardLockBuffers_.End(); ++i)
  1492. {
  1493. if (!i->reserved_ && i->size_ >= size)
  1494. {
  1495. i->reserved_ = true;
  1496. return i->data_.Get();
  1497. }
  1498. }
  1499. // Then check if a free buffer can be resized
  1500. for (Vector<DiscardLockBuffer>::Iterator i = discardLockBuffers_.Begin(); i != discardLockBuffers_.End(); ++i)
  1501. {
  1502. if (!i->reserved_)
  1503. {
  1504. i->data_ = new unsigned char[size];
  1505. i->size_ = size;
  1506. i->reserved_ = true;
  1507. return i->data_.Get();
  1508. }
  1509. }
  1510. // Finally allocate a new buffer
  1511. DiscardLockBuffer newBuffer;
  1512. newBuffer.data_ = new unsigned char[size];
  1513. newBuffer.size_ = size;
  1514. newBuffer.reserved_ = true;
  1515. discardLockBuffers_.Push(newBuffer);
  1516. return newBuffer.data_.Get();
  1517. }
  1518. void Graphics::FreeDiscardLockBuffer(void* buffer)
  1519. {
  1520. for (Vector<DiscardLockBuffer>::Iterator i = discardLockBuffers_.Begin(); i != discardLockBuffers_.End(); ++i)
  1521. {
  1522. if (i->reserved_ && i->data_.Get() == buffer)
  1523. {
  1524. i->reserved_ = false;
  1525. return;
  1526. }
  1527. }
  1528. LOGWARNING("Reserved discard lock buffer " + ToStringHex((unsigned)buffer) + " not found");
  1529. }
  1530. unsigned Graphics::GetAlphaFormat()
  1531. {
  1532. return GL_ALPHA;
  1533. }
  1534. unsigned Graphics::GetLuminanceFormat()
  1535. {
  1536. return GL_LUMINANCE;
  1537. }
  1538. unsigned Graphics::GetLuminanceAlphaFormat()
  1539. {
  1540. return GL_LUMINANCE_ALPHA;
  1541. }
  1542. unsigned Graphics::GetRGBFormat()
  1543. {
  1544. return GL_RGB;
  1545. }
  1546. unsigned Graphics::GetRGBAFormat()
  1547. {
  1548. return GL_RGBA;
  1549. }
  1550. unsigned Graphics::GetLinearDepthFormat()
  1551. {
  1552. // OpenGL FBO specs state that color attachments must have the same format; therefore must encode linear depth to RGBA
  1553. // manually if not using a readable hardware depth texture
  1554. return GL_RGBA;
  1555. }
  1556. unsigned Graphics::GetDepthStencilFormat()
  1557. {
  1558. return GL_DEPTH24_STENCIL8_EXT;
  1559. }
  1560. void Graphics::CheckFeatureSupport()
  1561. {
  1562. // Check supported features: light pre-pass rendering and hardware depth texture
  1563. lightPrepassSupport_ = false;
  1564. hardwareDepthSupport_ = false;
  1565. // For now hardware depth texture is only tested for on NVIDIA hardware because of visual artifacts and slowdown on ATI
  1566. String vendorString = String((const char*)glGetString(GL_VENDOR)).ToUpper();
  1567. if (vendorString.Find("NVIDIA") != String::NPOS)
  1568. {
  1569. SharedPtr<Texture2D> depthTexture(new Texture2D(context_));
  1570. hardwareDepthSupport_ = true;
  1571. // Note: Texture2D::SetSize() requires hardwareDepthSupport_ == true to create a texture instead of a renderbuffer
  1572. depthTexture->SetSize(256, 256, GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);
  1573. SetDepthStencil(depthTexture);
  1574. // If hardware depth textures work, this means also light pre-pass is automatically supported
  1575. if (CheckFramebuffer())
  1576. lightPrepassSupport_ = true;
  1577. else
  1578. hardwareDepthSupport_ = false;
  1579. ResetDepthStencil();
  1580. }
  1581. if (!hardwareDepthSupport_)
  1582. {
  1583. // If hardware depth is not supported, must support 2 render targets for light pre-pass
  1584. int numSupportedRTs = 1;
  1585. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &numSupportedRTs);
  1586. if (numSupportedRTs >= 2)
  1587. lightPrepassSupport_ = true;
  1588. }
  1589. }
  1590. void Graphics::SetDrawBuffers()
  1591. {
  1592. // Calculate the bit combination of non-zero color render targets to first check if the combination changed
  1593. unsigned newDrawBuffers = 0;
  1594. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1595. {
  1596. if (renderTargets_[i])
  1597. newDrawBuffers |= 1 << i;
  1598. }
  1599. if (newDrawBuffers == impl_->drawBuffers_)
  1600. return;
  1601. // Check for no color render targets (depth rendering only)
  1602. if (!newDrawBuffers)
  1603. glDrawBuffer(GL_NONE);
  1604. else
  1605. {
  1606. int drawBufferIds[4];
  1607. unsigned drawBufferCount = 0;
  1608. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1609. {
  1610. if (renderTargets_[i])
  1611. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + i;
  1612. }
  1613. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  1614. }
  1615. glReadBuffer(GL_NONE);
  1616. }
  1617. bool Graphics::CheckFramebuffer()
  1618. {
  1619. return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) == GL_FRAMEBUFFER_COMPLETE_EXT;
  1620. }
  1621. void Graphics::ResetCachedState()
  1622. {
  1623. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  1624. {
  1625. vertexBuffers_[i] = 0;
  1626. elementMasks_[i] = 0;
  1627. }
  1628. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1629. {
  1630. textures_[i] = 0;
  1631. textureTypes_[i] = 0;
  1632. }
  1633. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1634. renderTargets_[i] = 0;
  1635. depthStencil_ = 0;
  1636. viewTexture_ = 0;
  1637. viewport_ = IntRect(0, 0, 0, 0);
  1638. indexBuffer_ = 0;
  1639. vertexShader_ = 0;
  1640. pixelShader_ = 0;
  1641. shaderProgram_ = 0;
  1642. blendMode_ = BLEND_REPLACE;
  1643. alphaTest_ = false;
  1644. alphaTestMode_ = CMP_ALWAYS;
  1645. alphaRef_ = 0.0f;
  1646. textureAnisotropy_ = 1;
  1647. colorWrite_ = true;
  1648. cullMode_ = CULL_NONE;
  1649. constantDepthBias_ = 0.0f;
  1650. slopeScaledDepthBias_ = 0.0f;
  1651. depthTestMode_ = CMP_ALWAYS;
  1652. depthWrite_ = true;
  1653. fillMode_ = FILL_SOLID;
  1654. scissorTest_ = false;
  1655. scissorRect_ = IntRect::ZERO;
  1656. stencilTest_ = false;
  1657. stencilTestMode_ = CMP_ALWAYS;
  1658. stencilPass_ = OP_KEEP;
  1659. stencilFail_ = OP_KEEP;
  1660. stencilZFail_ = OP_KEEP;
  1661. stencilRef_ = 0;
  1662. stencilMask_ = M_MAX_UNSIGNED;
  1663. impl_->activeTexture_ = 0;
  1664. impl_->drawBuffers_ = M_MAX_UNSIGNED;
  1665. impl_->enabledAttributes_ = 0;
  1666. impl_->fboBound_ = false;
  1667. }
  1668. void Graphics::Release()
  1669. {
  1670. if (!impl_->window_)
  1671. return;
  1672. depthTextures_.Clear();
  1673. // If GPU objects exist ie. it's a context delete/recreate, not Close(), tell them to save and release themselves
  1674. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1675. (*i)->OnDeviceLost();
  1676. if (impl_->fbo_)
  1677. {
  1678. glDeleteFramebuffersEXT(1, &impl_->fbo_);
  1679. impl_->fbo_ = 0;
  1680. }
  1681. // When the new context is initialized, it will have default state again
  1682. ResetCachedState();
  1683. ClearParameterSources();
  1684. {
  1685. MutexLock lock(GetStaticMutex());
  1686. SetWindowContext(impl_->window_, 0);
  1687. glfwCloseWindow(impl_->window_);
  1688. impl_->window_ = 0;
  1689. }
  1690. }
  1691. void Graphics::SetTextureUnitMappings()
  1692. {
  1693. textureUnits_["DiffMap"] = TU_DIFFUSE;
  1694. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  1695. textureUnits_["NormalMap"] = TU_NORMAL;
  1696. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  1697. textureUnits_["DetailMap"] = TU_DETAIL;
  1698. textureUnits_["EnvironmentMap"] = TU_ENVIRONMENT;
  1699. textureUnits_["EnvironmentCubeMap"] = TU_ENVIRONMENT;
  1700. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  1701. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  1702. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  1703. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  1704. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  1705. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  1706. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  1707. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  1708. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  1709. }
  1710. void RegisterGraphicsLibrary(Context* context)
  1711. {
  1712. Animation::RegisterObject(context);
  1713. Material::RegisterObject(context);
  1714. Model::RegisterObject(context);
  1715. Shader::RegisterObject(context);
  1716. Technique::RegisterObject(context);
  1717. Texture2D::RegisterObject(context);
  1718. TextureCube::RegisterObject(context);
  1719. Camera::RegisterObject(context);
  1720. Drawable::RegisterObject(context);
  1721. Light::RegisterObject(context);
  1722. StaticModel::RegisterObject(context);
  1723. Skybox::RegisterObject(context);
  1724. AnimatedModel::RegisterObject(context);
  1725. AnimationController::RegisterObject(context);
  1726. BillboardSet::RegisterObject(context);
  1727. ParticleEmitter::RegisterObject(context);
  1728. DebugRenderer::RegisterObject(context);
  1729. Octree::RegisterObject(context);
  1730. Zone::RegisterObject(context);
  1731. }