OGLGraphics.cpp 70 KB

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