OGLGraphics.cpp 59 KB

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