OGLGraphics.cpp 82 KB

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