OGLGraphics.cpp 81 KB

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