OGLGraphics.cpp 69 KB

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