OGLGraphics.cpp 83 KB

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