OGLGraphics.cpp 82 KB

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