OGLGraphics.cpp 78 KB

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