OGLGraphics.cpp 81 KB

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