OGLGraphics.cpp 78 KB

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