OGLGraphics.cpp 92 KB

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