OGLGraphics.cpp 74 KB

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