OGLGraphics.cpp 63 KB

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