OGLGraphics.cpp 90 KB

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