OGLGraphics.cpp 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439
  1. //
  2. // Copyright (c) 2008-2022 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 "../../Core/Context.h"
  24. #include "../../Core/Mutex.h"
  25. #include "../../Core/ProcessUtils.h"
  26. #include "../../Core/Profiler.h"
  27. #include "../../Graphics/Graphics.h"
  28. #include "../../Graphics/GraphicsEvents.h"
  29. #include "../../GraphicsAPI/ConstantBuffer.h"
  30. #include "../../GraphicsAPI/IndexBuffer.h"
  31. #include "../../GraphicsAPI/OpenGL/OGLGraphicsImpl.h"
  32. #include "../../GraphicsAPI/OpenGL/OGLShaderProgram.h"
  33. #include "../../GraphicsAPI/RenderSurface.h"
  34. #include "../../GraphicsAPI/Shader.h"
  35. #include "../../GraphicsAPI/ShaderPrecache.h"
  36. #include "../../GraphicsAPI/ShaderVariation.h"
  37. #include "../../GraphicsAPI/Texture2D.h"
  38. #include "../../GraphicsAPI/TextureCube.h"
  39. #include "../../GraphicsAPI/VertexBuffer.h"
  40. #include "../../IO/File.h"
  41. #include "../../IO/Log.h"
  42. #include "../../Resource/ResourceCache.h"
  43. #include <SDL/SDL.h>
  44. #include "../../DebugNew.h"
  45. #ifdef GL_ES_VERSION_2_0
  46. #define GL_DEPTH_COMPONENT24 GL_DEPTH_COMPONENT24_OES
  47. #define glClearDepth glClearDepthf
  48. #endif
  49. #ifdef __EMSCRIPTEN__
  50. #include "../../Input/Input.h"
  51. #include "../../UI/Cursor.h"
  52. #include "../../UI/UI.h"
  53. #include <emscripten/emscripten.h>
  54. #include <emscripten/bind.h>
  55. // Emscripten provides even all GL extension functions via static linking. However there is
  56. // no GLES2-specific extension header at the moment to include instanced rendering declarations,
  57. // so declare them manually from GLES3 gl2ext.h. Emscripten will provide these when linking final output.
  58. extern "C"
  59. {
  60. GL_APICALL void GL_APIENTRY glDrawArraysInstancedANGLE (GLenum mode, GLint first, GLsizei count, GLsizei primcount);
  61. GL_APICALL void GL_APIENTRY glDrawElementsInstancedANGLE (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount);
  62. GL_APICALL void GL_APIENTRY glVertexAttribDivisorANGLE (GLuint index, GLuint divisor);
  63. }
  64. // Helper functions to support emscripten canvas resolution change
  65. static const Urho3D::Context *appContext;
  66. static void JSCanvasSize(int width, int height, bool fullscreen, float scale)
  67. {
  68. URHO3D_LOGINFOF("JSCanvasSize: width=%d height=%d fullscreen=%d ui scale=%f", width, height, fullscreen, scale);
  69. using namespace Urho3D;
  70. if (appContext)
  71. {
  72. bool uiCursorVisible = false;
  73. bool systemCursorVisible = false;
  74. MouseMode mouseMode{};
  75. // Detect current system pointer state
  76. Input* input = appContext->GetSubsystem<Input>();
  77. if (input)
  78. {
  79. systemCursorVisible = input->IsMouseVisible();
  80. mouseMode = input->GetMouseMode();
  81. }
  82. UI* ui = appContext->GetSubsystem<UI>();
  83. if (ui)
  84. {
  85. ui->SetScale(scale);
  86. // Detect current UI pointer state
  87. Cursor* cursor = ui->GetCursor();
  88. if (cursor)
  89. uiCursorVisible = cursor->IsVisible();
  90. }
  91. // Apply new resolution
  92. appContext->GetSubsystem<Graphics>()->SetMode(width, height);
  93. // Reset the pointer state as it was before resolution change
  94. if (input)
  95. {
  96. if (uiCursorVisible)
  97. input->SetMouseVisible(false);
  98. else
  99. input->SetMouseVisible(systemCursorVisible);
  100. input->SetMouseMode(mouseMode);
  101. }
  102. if (ui)
  103. {
  104. Cursor* cursor = ui->GetCursor();
  105. if (cursor)
  106. {
  107. cursor->SetVisible(uiCursorVisible);
  108. IntVector2 pos = input->GetMousePosition();
  109. pos = ui->ConvertSystemToUI(pos);
  110. cursor->SetPosition(pos);
  111. }
  112. }
  113. }
  114. }
  115. using namespace emscripten;
  116. EMSCRIPTEN_BINDINGS(Module) {
  117. function("JSCanvasSize", &JSCanvasSize);
  118. }
  119. #endif
  120. namespace Urho3D
  121. {
  122. static const unsigned glCmpFunc[] =
  123. {
  124. GL_ALWAYS,
  125. GL_EQUAL,
  126. GL_NOTEQUAL,
  127. GL_LESS,
  128. GL_LEQUAL,
  129. GL_GREATER,
  130. GL_GEQUAL
  131. };
  132. static const unsigned glSrcBlend[] =
  133. {
  134. GL_ONE,
  135. GL_ONE,
  136. GL_DST_COLOR,
  137. GL_SRC_ALPHA,
  138. GL_SRC_ALPHA,
  139. GL_ONE,
  140. GL_ONE_MINUS_DST_ALPHA,
  141. GL_ONE,
  142. GL_SRC_ALPHA
  143. };
  144. static const unsigned glDestBlend[] =
  145. {
  146. GL_ZERO,
  147. GL_ONE,
  148. GL_ZERO,
  149. GL_ONE_MINUS_SRC_ALPHA,
  150. GL_ONE,
  151. GL_ONE_MINUS_SRC_ALPHA,
  152. GL_DST_ALPHA,
  153. GL_ONE,
  154. GL_ONE
  155. };
  156. static const unsigned glBlendOp[] =
  157. {
  158. GL_FUNC_ADD,
  159. GL_FUNC_ADD,
  160. GL_FUNC_ADD,
  161. GL_FUNC_ADD,
  162. GL_FUNC_ADD,
  163. GL_FUNC_ADD,
  164. GL_FUNC_ADD,
  165. GL_FUNC_REVERSE_SUBTRACT,
  166. GL_FUNC_REVERSE_SUBTRACT
  167. };
  168. #ifndef GL_ES_VERSION_2_0
  169. static const unsigned glFillMode[] =
  170. {
  171. GL_FILL,
  172. GL_LINE,
  173. GL_POINT
  174. };
  175. static const unsigned glStencilOps[] =
  176. {
  177. GL_KEEP,
  178. GL_ZERO,
  179. GL_REPLACE,
  180. GL_INCR_WRAP,
  181. GL_DECR_WRAP
  182. };
  183. #endif
  184. static const unsigned glElementTypes[] =
  185. {
  186. GL_INT,
  187. GL_FLOAT,
  188. GL_FLOAT,
  189. GL_FLOAT,
  190. GL_FLOAT,
  191. GL_UNSIGNED_BYTE,
  192. GL_UNSIGNED_BYTE
  193. };
  194. static const unsigned glElementComponents[] =
  195. {
  196. 1,
  197. 1,
  198. 2,
  199. 3,
  200. 4,
  201. 4,
  202. 4
  203. };
  204. #ifdef GL_ES_VERSION_2_0
  205. static unsigned glesDepthStencilFormat = GL_DEPTH_COMPONENT16;
  206. static unsigned glesReadableDepthFormat = GL_DEPTH_COMPONENT;
  207. #endif
  208. static String extensions;
  209. bool CheckExtension(const String& name)
  210. {
  211. if (extensions.Empty())
  212. extensions = (const char*)glGetString(GL_EXTENSIONS);
  213. return extensions.Contains(name);
  214. }
  215. static void GetGLPrimitiveType(unsigned elementCount, PrimitiveType type, unsigned& primitiveCount, GLenum& glPrimitiveType)
  216. {
  217. switch (type)
  218. {
  219. case TRIANGLE_LIST:
  220. primitiveCount = elementCount / 3;
  221. glPrimitiveType = GL_TRIANGLES;
  222. break;
  223. case LINE_LIST:
  224. primitiveCount = elementCount / 2;
  225. glPrimitiveType = GL_LINES;
  226. break;
  227. case POINT_LIST:
  228. primitiveCount = elementCount;
  229. glPrimitiveType = GL_POINTS;
  230. break;
  231. case TRIANGLE_STRIP:
  232. primitiveCount = elementCount - 2;
  233. glPrimitiveType = GL_TRIANGLE_STRIP;
  234. break;
  235. case LINE_STRIP:
  236. primitiveCount = elementCount - 1;
  237. glPrimitiveType = GL_LINE_STRIP;
  238. break;
  239. case TRIANGLE_FAN:
  240. primitiveCount = elementCount - 2;
  241. glPrimitiveType = GL_TRIANGLE_FAN;
  242. break;
  243. }
  244. }
  245. void Graphics::Constructor_OGL()
  246. {
  247. impl_ = new GraphicsImpl_OGL();
  248. position_ = IntVector2(SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED);
  249. shadowMapFormat_ = GL_DEPTH_COMPONENT16;
  250. hiresShadowMapFormat_ = GL_DEPTH_COMPONENT24;
  251. shaderPath_ = "Shaders/GLSL/";
  252. shaderExtension_ = ".glsl";
  253. orientations_ = "LandscapeLeft LandscapeRight";
  254. #ifndef GL_ES_VERSION_2_0
  255. apiName_ = "GL2";
  256. #else
  257. apiName_ = "GLES2";
  258. #endif
  259. Graphics::pixelUVOffset = Vector2(0.0f, 0.0f);
  260. Graphics::gl3Support = false;
  261. SetTextureUnitMappings_OGL();
  262. ResetCachedState_OGL();
  263. context_->RequireSDL(SDL_INIT_VIDEO);
  264. // Register Graphics library object factories
  265. RegisterGraphicsLibrary(context_);
  266. #ifdef __EMSCRIPTEN__
  267. appContext = context_;
  268. #endif
  269. }
  270. void Graphics::Destructor_OGL()
  271. {
  272. Close_OGL();
  273. delete impl_;
  274. impl_ = nullptr;
  275. context_->ReleaseSDL();
  276. }
  277. bool Graphics::SetScreenMode_OGL(int width, int height, const ScreenModeParams& params, bool maximize)
  278. {
  279. URHO3D_PROFILE(SetScreenMode_OGL);
  280. // Ensure that parameters are properly filled
  281. ScreenModeParams newParams = params;
  282. AdjustScreenMode(width, height, newParams, maximize);
  283. if (IsInitialized_OGL() && width == width_ && height == height_ && screenParams_ == newParams)
  284. return true;
  285. // If only vsync changes, do not destroy/recreate the context
  286. if (IsInitialized_OGL() && width == width_ && height == height_
  287. && screenParams_.EqualsExceptVSync(newParams) && screenParams_.vsync_ != newParams.vsync_)
  288. {
  289. SDL_GL_SetSwapInterval(newParams.vsync_ ? 1 : 0);
  290. screenParams_.vsync_ = newParams.vsync_;
  291. return true;
  292. }
  293. // Track if the window was repositioned and don't update window position in this case
  294. bool reposition = false;
  295. GraphicsImpl_OGL* impl = GetImpl_OGL();
  296. // With an external window, only the size can change after initial setup, so do not recreate context
  297. if (!externalWindow_ || !impl->context_)
  298. {
  299. // Close the existing window and OpenGL context, mark GPU objects as lost
  300. Release_OGL(false, true);
  301. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  302. #ifndef GL_ES_VERSION_2_0
  303. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
  304. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
  305. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
  306. if (externalWindow_)
  307. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
  308. else
  309. SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 0);
  310. SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
  311. if (!forceGL2_)
  312. {
  313. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
  314. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
  315. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
  316. }
  317. else
  318. {
  319. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  320. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  321. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, 0);
  322. }
  323. #else
  324. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  325. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  326. #endif
  327. SDL_Rect display_rect;
  328. SDL_GetDisplayBounds(newParams.monitor_, &display_rect);
  329. reposition = newParams.fullscreen_ || (newParams.borderless_ && width >= display_rect.w && height >= display_rect.h);
  330. const int x = reposition ? display_rect.x : position_.x_;
  331. const int y = reposition ? display_rect.y : position_.y_;
  332. unsigned flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
  333. if (newParams.fullscreen_)
  334. flags |= SDL_WINDOW_FULLSCREEN;
  335. if (newParams.borderless_)
  336. flags |= SDL_WINDOW_BORDERLESS;
  337. if (newParams.resizable_)
  338. flags |= SDL_WINDOW_RESIZABLE;
  339. #ifndef __EMSCRIPTEN__
  340. if (newParams.highDPI_)
  341. flags |= SDL_WINDOW_ALLOW_HIGHDPI;
  342. #endif
  343. SDL_SetHint(SDL_HINT_ORIENTATIONS, orientations_.CString());
  344. // Try 24-bit depth first, fallback to 16-bit
  345. for (const int depthSize : { 24, 16 })
  346. {
  347. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, depthSize);
  348. // Try requested multisample level first, fallback to lower levels and no multisample
  349. for (int multiSample = newParams.multiSample_; multiSample > 0; multiSample /= 2)
  350. {
  351. if (multiSample > 1)
  352. {
  353. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  354. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, multiSample);
  355. }
  356. else
  357. {
  358. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
  359. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
  360. }
  361. if (!externalWindow_)
  362. window_ = SDL_CreateWindow(windowTitle_.CString(), x, y, width, height, flags);
  363. else
  364. {
  365. #ifndef __EMSCRIPTEN__
  366. if (!window_)
  367. window_ = SDL_CreateWindowFrom(externalWindow_, SDL_WINDOW_OPENGL);
  368. newParams.fullscreen_ = false;
  369. #endif
  370. }
  371. if (window_)
  372. {
  373. // TODO: We probably want to keep depthSize as well
  374. newParams.multiSample_ = multiSample;
  375. break;
  376. }
  377. }
  378. if (window_)
  379. break;
  380. }
  381. if (!window_)
  382. {
  383. URHO3D_LOGERRORF("Could not create window, root cause: '%s'", SDL_GetError());
  384. return false;
  385. }
  386. // Reposition the window on the specified monitor
  387. if (reposition)
  388. SDL_SetWindowPosition(window_, display_rect.x, display_rect.y);
  389. CreateWindowIcon();
  390. if (maximize)
  391. {
  392. Maximize();
  393. SDL_GL_GetDrawableSize(window_, &width, &height);
  394. }
  395. // Create/restore context and GPU objects and set initial renderstate
  396. Restore_OGL();
  397. // Specific error message is already logged by Restore_OGL() when context creation or OpenGL extensions check fails
  398. if (!impl->context_)
  399. return false;
  400. }
  401. // Set vsync
  402. SDL_GL_SetSwapInterval(newParams.vsync_ ? 1 : 0);
  403. // Store the system FBO on iOS/tvOS now
  404. #if defined(IOS) || defined(TVOS)
  405. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&impl->systemFBO_);
  406. #endif
  407. screenParams_ = newParams;
  408. SDL_GL_GetDrawableSize(window_, &width_, &height_);
  409. if (!reposition)
  410. SDL_GetWindowPosition(window_, &position_.x_, &position_.y_);
  411. int logicalWidth, logicalHeight;
  412. SDL_GetWindowSize(window_, &logicalWidth, &logicalHeight);
  413. screenParams_.highDPI_ = (width_ != logicalWidth) || (height_ != logicalHeight);
  414. // Reset rendertargets and viewport for the new screen mode
  415. ResetRenderTargets_OGL();
  416. // Clear the initial window contents to black
  417. Clear_OGL(CLEAR_COLOR);
  418. SDL_GL_SwapWindow(window_);
  419. CheckFeatureSupport_OGL();
  420. #ifdef URHO3D_LOGGING
  421. URHO3D_LOGINFOF("Adapter used %s %s", (const char *) glGetString(GL_VENDOR), (const char *) glGetString(GL_RENDERER));
  422. #endif
  423. OnScreenModeChanged();
  424. return true;
  425. }
  426. void Graphics::SetSRGB_OGL(bool enable)
  427. {
  428. enable &= sRGBWriteSupport_;
  429. if (enable != sRGB_)
  430. {
  431. sRGB_ = enable;
  432. GetImpl_OGL()->fboDirty_ = true;
  433. }
  434. }
  435. void Graphics::SetDither_OGL(bool enable)
  436. {
  437. if (enable)
  438. glEnable(GL_DITHER);
  439. else
  440. glDisable(GL_DITHER);
  441. }
  442. void Graphics::SetFlushGPU_OGL(bool enable)
  443. {
  444. // Currently unimplemented on OpenGL
  445. }
  446. void Graphics::SetForceGL2_OGL(bool enable)
  447. {
  448. if (IsInitialized_OGL())
  449. {
  450. URHO3D_LOGERROR("OpenGL 2 can only be forced before setting the initial screen mode");
  451. return;
  452. }
  453. forceGL2_ = enable;
  454. }
  455. void Graphics::Close_OGL()
  456. {
  457. if (!IsInitialized_OGL())
  458. return;
  459. // Actually close the window
  460. Release_OGL(true, true);
  461. }
  462. bool Graphics::TakeScreenShot_OGL(Image& destImage)
  463. {
  464. URHO3D_PROFILE(TakeScreenShot_OGL);
  465. if (!IsInitialized_OGL())
  466. return false;
  467. if (IsDeviceLost_OGL())
  468. {
  469. URHO3D_LOGERROR("Can not take screenshot while device is lost");
  470. return false;
  471. }
  472. ResetRenderTargets_OGL();
  473. #ifndef GL_ES_VERSION_2_0
  474. destImage.SetSize(width_, height_, 3);
  475. glReadPixels(0, 0, width_, height_, GL_RGB, GL_UNSIGNED_BYTE, destImage.GetData());
  476. #else
  477. // Use RGBA format on OpenGL ES, as otherwise (at least on Android) the produced image is all black
  478. destImage.SetSize(width_, height_, 4);
  479. glReadPixels(0, 0, width_, height_, GL_RGBA, GL_UNSIGNED_BYTE, destImage.GetData());
  480. #endif
  481. // On OpenGL we need to flip the image vertically after reading
  482. destImage.FlipVertical();
  483. return true;
  484. }
  485. bool Graphics::BeginFrame_OGL()
  486. {
  487. if (!IsInitialized_OGL() || IsDeviceLost_OGL())
  488. return false;
  489. // If using an external window, check it for size changes, and reset screen mode if necessary
  490. if (externalWindow_)
  491. {
  492. int width, height;
  493. SDL_GL_GetDrawableSize(window_, &width, &height);
  494. if (width != width_ || height != height_)
  495. SetMode(width, height);
  496. }
  497. // Re-enable depth test and depth func in case a third party program has modified it
  498. glEnable(GL_DEPTH_TEST);
  499. glDepthFunc(glCmpFunc[depthTestMode_]);
  500. // Set default rendertarget and depth buffer
  501. ResetRenderTargets_OGL();
  502. // Cleanup textures from previous frame
  503. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  504. SetTexture_OGL(i, nullptr);
  505. // Enable color and depth write
  506. SetColorWrite_OGL(true);
  507. SetDepthWrite_OGL(true);
  508. numPrimitives_ = 0;
  509. numBatches_ = 0;
  510. SendEvent(E_BEGINRENDERING);
  511. return true;
  512. }
  513. void Graphics::EndFrame_OGL()
  514. {
  515. if (!IsInitialized_OGL())
  516. return;
  517. URHO3D_PROFILE(Present);
  518. SendEvent(E_ENDRENDERING);
  519. SDL_GL_SwapWindow(window_);
  520. // Clean up too large scratch buffers
  521. CleanupScratchBuffers();
  522. }
  523. void Graphics::Clear_OGL(ClearTargetFlags flags, const Color& color, float depth, unsigned stencil)
  524. {
  525. PrepareDraw_OGL();
  526. #ifdef GL_ES_VERSION_2_0
  527. flags &= ~CLEAR_STENCIL;
  528. #endif
  529. bool oldColorWrite = colorWrite_;
  530. bool oldDepthWrite = depthWrite_;
  531. if (flags & CLEAR_COLOR && !oldColorWrite)
  532. SetColorWrite_OGL(true);
  533. if (flags & CLEAR_DEPTH && !oldDepthWrite)
  534. SetDepthWrite_OGL(true);
  535. if (flags & CLEAR_STENCIL && stencilWriteMask_ != M_MAX_UNSIGNED)
  536. glStencilMask(M_MAX_UNSIGNED);
  537. unsigned glFlags = 0;
  538. if (flags & CLEAR_COLOR)
  539. {
  540. glFlags |= GL_COLOR_BUFFER_BIT;
  541. glClearColor(color.r_, color.g_, color.b_, color.a_);
  542. }
  543. if (flags & CLEAR_DEPTH)
  544. {
  545. glFlags |= GL_DEPTH_BUFFER_BIT;
  546. glClearDepth(depth);
  547. }
  548. if (flags & CLEAR_STENCIL)
  549. {
  550. glFlags |= GL_STENCIL_BUFFER_BIT;
  551. glClearStencil(stencil);
  552. }
  553. // If viewport is less than full screen, set a scissor to limit the clear
  554. /// \todo Any user-set scissor test will be lost
  555. IntVector2 viewSize = GetRenderTargetDimensions_OGL();
  556. if (viewport_.left_ != 0 || viewport_.top_ != 0 || viewport_.right_ != viewSize.x_ || viewport_.bottom_ != viewSize.y_)
  557. SetScissorTest_OGL(true, IntRect(0, 0, viewport_.Width(), viewport_.Height()));
  558. else
  559. SetScissorTest_OGL(false);
  560. glClear(glFlags);
  561. SetScissorTest_OGL(false);
  562. SetColorWrite_OGL(oldColorWrite);
  563. SetDepthWrite_OGL(oldDepthWrite);
  564. if (flags & CLEAR_STENCIL && stencilWriteMask_ != M_MAX_UNSIGNED)
  565. glStencilMask(stencilWriteMask_);
  566. }
  567. bool Graphics::ResolveToTexture_OGL(Texture2D* destination, const IntRect& viewport)
  568. {
  569. if (!destination || !destination->GetRenderSurface())
  570. return false;
  571. URHO3D_PROFILE(ResolveToTexture_OGL);
  572. IntRect vpCopy = viewport;
  573. if (vpCopy.right_ <= vpCopy.left_)
  574. vpCopy.right_ = vpCopy.left_ + 1;
  575. if (vpCopy.bottom_ <= vpCopy.top_)
  576. vpCopy.bottom_ = vpCopy.top_ + 1;
  577. vpCopy.left_ = Clamp(vpCopy.left_, 0, width_);
  578. vpCopy.top_ = Clamp(vpCopy.top_, 0, height_);
  579. vpCopy.right_ = Clamp(vpCopy.right_, 0, width_);
  580. vpCopy.bottom_ = Clamp(vpCopy.bottom_, 0, height_);
  581. // Make sure the FBO is not in use
  582. ResetRenderTargets_OGL();
  583. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  584. SetTextureForUpdate_OGL(destination);
  585. glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, vpCopy.left_, height_ - vpCopy.bottom_, vpCopy.Width(), vpCopy.Height());
  586. SetTexture_OGL(0, nullptr);
  587. return true;
  588. }
  589. bool Graphics::ResolveToTexture_OGL(Texture2D* texture)
  590. {
  591. #ifndef GL_ES_VERSION_2_0
  592. if (!texture)
  593. return false;
  594. RenderSurface* surface = texture->GetRenderSurface();
  595. if (!surface || !surface->GetRenderBuffer())
  596. return false;
  597. URHO3D_PROFILE(ResolveToTexture_OGL);
  598. texture->SetResolveDirty(false);
  599. surface->SetResolveDirty(false);
  600. GraphicsImpl_OGL* impl = GetImpl_OGL();
  601. // Use separate FBOs for resolve to not disturb the currently set rendertarget(s)
  602. if (!impl->resolveSrcFBO_)
  603. impl->resolveSrcFBO_ = CreateFramebuffer_OGL();
  604. if (!impl->resolveDestFBO_)
  605. impl->resolveDestFBO_ = CreateFramebuffer_OGL();
  606. if (!gl3Support)
  607. {
  608. glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, impl->resolveSrcFBO_);
  609. glFramebufferRenderbufferEXT(GL_READ_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT,
  610. surface->GetRenderBuffer());
  611. glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, impl->resolveDestFBO_);
  612. glFramebufferTexture2DEXT(GL_DRAW_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texture->GetGPUObjectName(),
  613. 0);
  614. glBlitFramebufferEXT(0, 0, texture->GetWidth(), texture->GetHeight(), 0, 0, texture->GetWidth(), texture->GetHeight(),
  615. GL_COLOR_BUFFER_BIT, GL_NEAREST);
  616. glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0);
  617. glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0);
  618. }
  619. else
  620. {
  621. glBindFramebuffer(GL_READ_FRAMEBUFFER, impl->resolveSrcFBO_);
  622. glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, surface->GetRenderBuffer());
  623. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, impl->resolveDestFBO_);
  624. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->GetGPUObjectName(), 0);
  625. glBlitFramebuffer(0, 0, texture->GetWidth(), texture->GetHeight(), 0, 0, texture->GetWidth(), texture->GetHeight(),
  626. GL_COLOR_BUFFER_BIT, GL_NEAREST);
  627. glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
  628. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  629. }
  630. // Restore previously bound FBO
  631. BindFramebuffer_OGL(impl->boundFBO_);
  632. return true;
  633. #else
  634. // Not supported on GLES
  635. return false;
  636. #endif
  637. }
  638. bool Graphics::ResolveToTexture_OGL(TextureCube* texture)
  639. {
  640. #ifndef GL_ES_VERSION_2_0
  641. if (!texture)
  642. return false;
  643. URHO3D_PROFILE(ResolveToTexture_OGL);
  644. texture->SetResolveDirty(false);
  645. GraphicsImpl_OGL* impl = GetImpl_OGL();
  646. // Use separate FBOs for resolve to not disturb the currently set rendertarget(s)
  647. if (!impl->resolveSrcFBO_)
  648. impl->resolveSrcFBO_ = CreateFramebuffer_OGL();
  649. if (!impl->resolveDestFBO_)
  650. impl->resolveDestFBO_ = CreateFramebuffer_OGL();
  651. if (!gl3Support)
  652. {
  653. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  654. {
  655. // Resolve only the surface(s) that were actually rendered to
  656. RenderSurface* surface = texture->GetRenderSurface((CubeMapFace)i);
  657. if (!surface->IsResolveDirty())
  658. continue;
  659. surface->SetResolveDirty(false);
  660. glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, impl->resolveSrcFBO_);
  661. glFramebufferRenderbufferEXT(GL_READ_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT,
  662. surface->GetRenderBuffer());
  663. glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, impl->resolveDestFBO_);
  664. glFramebufferTexture2DEXT(GL_DRAW_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
  665. texture->GetGPUObjectName(), 0);
  666. glBlitFramebufferEXT(0, 0, texture->GetWidth(), texture->GetHeight(), 0, 0, texture->GetWidth(), texture->GetHeight(),
  667. GL_COLOR_BUFFER_BIT, GL_NEAREST);
  668. }
  669. glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0);
  670. glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0);
  671. }
  672. else
  673. {
  674. for (unsigned i = 0; i < MAX_CUBEMAP_FACES; ++i)
  675. {
  676. RenderSurface* surface = texture->GetRenderSurface((CubeMapFace)i);
  677. if (!surface->IsResolveDirty())
  678. continue;
  679. surface->SetResolveDirty(false);
  680. glBindFramebuffer(GL_READ_FRAMEBUFFER, impl->resolveSrcFBO_);
  681. glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, surface->GetRenderBuffer());
  682. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, impl->resolveDestFBO_);
  683. glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
  684. texture->GetGPUObjectName(), 0);
  685. glBlitFramebuffer(0, 0, texture->GetWidth(), texture->GetHeight(), 0, 0, texture->GetWidth(), texture->GetHeight(),
  686. GL_COLOR_BUFFER_BIT, GL_NEAREST);
  687. }
  688. glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
  689. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  690. }
  691. // Restore previously bound FBO
  692. BindFramebuffer_OGL(impl->boundFBO_);
  693. return true;
  694. #else
  695. // Not supported on GLES
  696. return false;
  697. #endif
  698. }
  699. void Graphics::Draw_OGL(PrimitiveType type, unsigned vertexStart, unsigned vertexCount)
  700. {
  701. if (!vertexCount)
  702. return;
  703. PrepareDraw_OGL();
  704. unsigned primitiveCount;
  705. GLenum glPrimitiveType;
  706. GetGLPrimitiveType(vertexCount, type, primitiveCount, glPrimitiveType);
  707. glDrawArrays(glPrimitiveType, vertexStart, vertexCount);
  708. numPrimitives_ += primitiveCount;
  709. ++numBatches_;
  710. }
  711. void Graphics::Draw_OGL(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount)
  712. {
  713. if (!indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObjectName())
  714. return;
  715. PrepareDraw_OGL();
  716. unsigned indexSize = indexBuffer_->GetIndexSize();
  717. unsigned primitiveCount;
  718. GLenum glPrimitiveType;
  719. GetGLPrimitiveType(indexCount, type, primitiveCount, glPrimitiveType);
  720. GLenum indexType = indexSize == sizeof(unsigned short) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  721. glDrawElements(glPrimitiveType, indexCount, indexType, reinterpret_cast<const GLvoid*>(indexStart * indexSize));
  722. numPrimitives_ += primitiveCount;
  723. ++numBatches_;
  724. }
  725. void Graphics::Draw_OGL(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned baseVertexIndex, unsigned minVertex, unsigned vertexCount)
  726. {
  727. #ifndef GL_ES_VERSION_2_0
  728. if (!gl3Support || !indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObjectName())
  729. return;
  730. PrepareDraw_OGL();
  731. unsigned indexSize = indexBuffer_->GetIndexSize();
  732. unsigned primitiveCount;
  733. GLenum glPrimitiveType;
  734. GetGLPrimitiveType(indexCount, type, primitiveCount, glPrimitiveType);
  735. GLenum indexType = indexSize == sizeof(unsigned short) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  736. glDrawElementsBaseVertex(glPrimitiveType, indexCount, indexType, reinterpret_cast<GLvoid*>(indexStart * indexSize), baseVertexIndex);
  737. numPrimitives_ += primitiveCount;
  738. ++numBatches_;
  739. #endif
  740. }
  741. void Graphics::DrawInstanced_OGL(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned minVertex, unsigned vertexCount,
  742. unsigned instanceCount)
  743. {
  744. #if !defined(GL_ES_VERSION_2_0) || defined(__EMSCRIPTEN__)
  745. if (!indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObjectName() || !instancingSupport_)
  746. return;
  747. PrepareDraw_OGL();
  748. unsigned indexSize = indexBuffer_->GetIndexSize();
  749. unsigned primitiveCount;
  750. GLenum glPrimitiveType;
  751. GetGLPrimitiveType(indexCount, type, primitiveCount, glPrimitiveType);
  752. GLenum indexType = indexSize == sizeof(unsigned short) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  753. #ifdef __EMSCRIPTEN__
  754. glDrawElementsInstancedANGLE(glPrimitiveType, indexCount, indexType, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  755. instanceCount);
  756. #else
  757. if (gl3Support)
  758. {
  759. glDrawElementsInstanced(glPrimitiveType, indexCount, indexType, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  760. instanceCount);
  761. }
  762. else
  763. {
  764. glDrawElementsInstancedARB(glPrimitiveType, indexCount, indexType, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  765. instanceCount);
  766. }
  767. #endif
  768. numPrimitives_ += instanceCount * primitiveCount;
  769. ++numBatches_;
  770. #endif
  771. }
  772. void Graphics::DrawInstanced_OGL(PrimitiveType type, unsigned indexStart, unsigned indexCount, unsigned baseVertexIndex, unsigned minVertex,
  773. unsigned vertexCount, unsigned instanceCount)
  774. {
  775. #ifndef GL_ES_VERSION_2_0
  776. if (!gl3Support || !indexCount || !indexBuffer_ || !indexBuffer_->GetGPUObjectName() || !instancingSupport_)
  777. return;
  778. PrepareDraw_OGL();
  779. unsigned indexSize = indexBuffer_->GetIndexSize();
  780. unsigned primitiveCount;
  781. GLenum glPrimitiveType;
  782. GetGLPrimitiveType(indexCount, type, primitiveCount, glPrimitiveType);
  783. GLenum indexType = indexSize == sizeof(unsigned short) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  784. glDrawElementsInstancedBaseVertex(glPrimitiveType, indexCount, indexType, reinterpret_cast<const GLvoid*>(indexStart * indexSize),
  785. instanceCount, baseVertexIndex);
  786. numPrimitives_ += instanceCount * primitiveCount;
  787. ++numBatches_;
  788. #endif
  789. }
  790. void Graphics::SetVertexBuffer_OGL(VertexBuffer* buffer)
  791. {
  792. // Note: this is not multi-instance safe
  793. static PODVector<VertexBuffer*> vertexBuffers(1);
  794. vertexBuffers[0] = buffer;
  795. SetVertexBuffers_OGL(vertexBuffers);
  796. }
  797. bool Graphics::SetVertexBuffers_OGL(const PODVector<VertexBuffer*>& buffers, unsigned instanceOffset)
  798. {
  799. if (buffers.Size() > MAX_VERTEX_STREAMS)
  800. {
  801. URHO3D_LOGERROR("Too many vertex buffers");
  802. return false;
  803. }
  804. GraphicsImpl_OGL* impl = GetImpl_OGL();
  805. if (instanceOffset != impl->lastInstanceOffset_)
  806. {
  807. impl->lastInstanceOffset_ = instanceOffset;
  808. impl->vertexBuffersDirty_ = true;
  809. }
  810. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  811. {
  812. VertexBuffer* buffer = nullptr;
  813. if (i < buffers.Size())
  814. buffer = buffers[i];
  815. if (buffer != vertexBuffers_[i])
  816. {
  817. vertexBuffers_[i] = buffer;
  818. impl->vertexBuffersDirty_ = true;
  819. }
  820. }
  821. return true;
  822. }
  823. bool Graphics::SetVertexBuffers_OGL(const Vector<SharedPtr<VertexBuffer> >& buffers, unsigned instanceOffset)
  824. {
  825. return SetVertexBuffers_OGL(reinterpret_cast<const PODVector<VertexBuffer*>&>(buffers), instanceOffset);
  826. }
  827. void Graphics::SetIndexBuffer_OGL(IndexBuffer* buffer)
  828. {
  829. if (indexBuffer_ == buffer)
  830. return;
  831. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer ? buffer->GetGPUObjectName() : 0);
  832. indexBuffer_ = buffer;
  833. }
  834. void Graphics::SetShaders_OGL(ShaderVariation* vs, ShaderVariation* ps)
  835. {
  836. if (vs == vertexShader_ && ps == pixelShader_)
  837. return;
  838. // Compile the shaders now if not yet compiled. If already attempted, do not retry
  839. if (vs && !vs->GetGPUObjectName())
  840. {
  841. if (vs->GetCompilerOutput().Empty())
  842. {
  843. URHO3D_PROFILE(CompileVertexShader);
  844. bool success = vs->Create();
  845. if (success)
  846. URHO3D_LOGDEBUG("Compiled vertex shader " + vs->GetFullName());
  847. else
  848. {
  849. URHO3D_LOGERROR("Failed to compile vertex shader " + vs->GetFullName() + ":\n" + vs->GetCompilerOutput());
  850. vs = nullptr;
  851. }
  852. }
  853. else
  854. vs = nullptr;
  855. }
  856. if (ps && !ps->GetGPUObjectName())
  857. {
  858. if (ps->GetCompilerOutput().Empty())
  859. {
  860. URHO3D_PROFILE(CompilePixelShader);
  861. bool success = ps->Create();
  862. if (success)
  863. URHO3D_LOGDEBUG("Compiled pixel shader " + ps->GetFullName());
  864. else
  865. {
  866. URHO3D_LOGERROR("Failed to compile pixel shader " + ps->GetFullName() + ":\n" + ps->GetCompilerOutput());
  867. ps = nullptr;
  868. }
  869. }
  870. else
  871. ps = nullptr;
  872. }
  873. GraphicsImpl_OGL* impl = GetImpl_OGL();
  874. if (!vs || !ps)
  875. {
  876. glUseProgram(0);
  877. vertexShader_ = nullptr;
  878. pixelShader_ = nullptr;
  879. impl->shaderProgram_ = nullptr;
  880. }
  881. else
  882. {
  883. vertexShader_ = vs;
  884. pixelShader_ = ps;
  885. Pair<ShaderVariation*, ShaderVariation*> combination(vs, ps);
  886. ShaderProgramMap_OGL::Iterator i = impl->shaderPrograms_.Find(combination);
  887. if (i != impl->shaderPrograms_.End())
  888. {
  889. // Use the existing linked program
  890. if (i->second_->GetGPUObjectName())
  891. {
  892. glUseProgram(i->second_->GetGPUObjectName());
  893. impl->shaderProgram_ = i->second_;
  894. }
  895. else
  896. {
  897. glUseProgram(0);
  898. impl->shaderProgram_ = nullptr;
  899. }
  900. }
  901. else
  902. {
  903. // Link a new combination
  904. URHO3D_PROFILE(LinkShaders);
  905. SharedPtr<ShaderProgram_OGL> newProgram(new ShaderProgram_OGL(this, vs, ps));
  906. if (newProgram->Link())
  907. {
  908. URHO3D_LOGDEBUG("Linked vertex shader " + vs->GetFullName() + " and pixel shader " + ps->GetFullName());
  909. // Note: Link() calls glUseProgram() to set the texture sampler uniforms,
  910. // so it is not necessary to call it again
  911. impl->shaderProgram_ = newProgram;
  912. }
  913. else
  914. {
  915. URHO3D_LOGERROR("Failed to link vertex shader " + vs->GetFullName() + " and pixel shader " + ps->GetFullName() + ":\n" +
  916. newProgram->GetLinkerOutput());
  917. glUseProgram(0);
  918. impl->shaderProgram_ = nullptr;
  919. }
  920. impl->shaderPrograms_[combination] = newProgram;
  921. }
  922. }
  923. // Update the clip plane uniform on GL3, and set constant buffers
  924. #ifndef GL_ES_VERSION_2_0
  925. if (gl3Support && impl->shaderProgram_)
  926. {
  927. const SharedPtr<ConstantBuffer>* constantBuffers = impl->shaderProgram_->GetConstantBuffers();
  928. for (unsigned i = 0; i < MAX_SHADER_PARAMETER_GROUPS * 2; ++i)
  929. {
  930. ConstantBuffer* buffer = constantBuffers[i].Get();
  931. if (buffer != impl->constantBuffers_[i])
  932. {
  933. unsigned object = buffer ? buffer->GetGPUObjectName() : 0;
  934. glBindBufferBase(GL_UNIFORM_BUFFER, i, object);
  935. // Calling glBindBufferBase also affects the generic buffer binding point
  936. impl->boundUBO_ = object;
  937. impl->constantBuffers_[i] = buffer;
  938. ShaderProgram_OGL::ClearGlobalParameterSource((ShaderParameterGroup)(i % MAX_SHADER_PARAMETER_GROUPS));
  939. }
  940. }
  941. SetShaderParameter_OGL(VSP_CLIPPLANE, useClipPlane_ ? clipPlane_ : Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  942. }
  943. #endif
  944. // Store shader combination if shader dumping in progress
  945. if (shaderPrecache_)
  946. shaderPrecache_->StoreShaders(vertexShader_, pixelShader_);
  947. if (impl->shaderProgram_)
  948. {
  949. impl->usedVertexAttributes_ = impl->shaderProgram_->GetUsedVertexAttributes();
  950. impl->vertexAttributes_ = &impl->shaderProgram_->GetVertexAttributes();
  951. }
  952. else
  953. {
  954. impl->usedVertexAttributes_ = 0;
  955. impl->vertexAttributes_ = nullptr;
  956. }
  957. impl->vertexBuffersDirty_ = true;
  958. }
  959. void Graphics::SetShaderParameter_OGL(StringHash param, const float* data, unsigned count)
  960. {
  961. GraphicsImpl_OGL* impl = GetImpl_OGL();
  962. if (impl->shaderProgram_)
  963. {
  964. const ShaderParameter* info = impl->shaderProgram_->GetParameter(param);
  965. if (info)
  966. {
  967. if (info->bufferPtr_)
  968. {
  969. ConstantBuffer* buffer = info->bufferPtr_;
  970. if (!buffer->IsDirty())
  971. impl->dirtyConstantBuffers_.Push(buffer);
  972. buffer->SetParameter(info->offset_, (unsigned)(count * sizeof(float)), data);
  973. return;
  974. }
  975. switch (info->glType_)
  976. {
  977. case GL_FLOAT:
  978. glUniform1fv(info->location_, count, data);
  979. break;
  980. case GL_FLOAT_VEC2:
  981. glUniform2fv(info->location_, count / 2, data);
  982. break;
  983. case GL_FLOAT_VEC3:
  984. glUniform3fv(info->location_, count / 3, data);
  985. break;
  986. case GL_FLOAT_VEC4:
  987. glUniform4fv(info->location_, count / 4, data);
  988. break;
  989. case GL_FLOAT_MAT3:
  990. glUniformMatrix3fv(info->location_, count / 9, GL_FALSE, data);
  991. break;
  992. case GL_FLOAT_MAT4:
  993. glUniformMatrix4fv(info->location_, count / 16, GL_FALSE, data);
  994. break;
  995. default: break;
  996. }
  997. }
  998. }
  999. }
  1000. void Graphics::SetShaderParameter_OGL(StringHash param, float value)
  1001. {
  1002. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1003. if (impl->shaderProgram_)
  1004. {
  1005. const ShaderParameter* info = impl->shaderProgram_->GetParameter(param);
  1006. if (info)
  1007. {
  1008. if (info->bufferPtr_)
  1009. {
  1010. ConstantBuffer* buffer = info->bufferPtr_;
  1011. if (!buffer->IsDirty())
  1012. impl->dirtyConstantBuffers_.Push(buffer);
  1013. buffer->SetParameter(info->offset_, sizeof(float), &value);
  1014. return;
  1015. }
  1016. glUniform1fv(info->location_, 1, &value);
  1017. }
  1018. }
  1019. }
  1020. void Graphics::SetShaderParameter_OGL(StringHash param, int value)
  1021. {
  1022. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1023. if (impl->shaderProgram_)
  1024. {
  1025. const ShaderParameter* info = impl->shaderProgram_->GetParameter(param);
  1026. if (info)
  1027. {
  1028. if (info->bufferPtr_)
  1029. {
  1030. ConstantBuffer* buffer = info->bufferPtr_;
  1031. if (!buffer->IsDirty())
  1032. impl->dirtyConstantBuffers_.Push(buffer);
  1033. buffer->SetParameter(info->offset_, sizeof(int), &value);
  1034. return;
  1035. }
  1036. glUniform1i(info->location_, value);
  1037. }
  1038. }
  1039. }
  1040. void Graphics::SetShaderParameter_OGL(StringHash param, bool value)
  1041. {
  1042. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1043. // \todo Not tested
  1044. if (impl->shaderProgram_)
  1045. {
  1046. const ShaderParameter* info = impl->shaderProgram_->GetParameter(param);
  1047. if (info)
  1048. {
  1049. if (info->bufferPtr_)
  1050. {
  1051. ConstantBuffer* buffer = info->bufferPtr_;
  1052. if (!buffer->IsDirty())
  1053. impl->dirtyConstantBuffers_.Push(buffer);
  1054. buffer->SetParameter(info->offset_, sizeof(bool), &value);
  1055. return;
  1056. }
  1057. glUniform1i(info->location_, (int)value);
  1058. }
  1059. }
  1060. }
  1061. void Graphics::SetShaderParameter_OGL(StringHash param, const Color& color)
  1062. {
  1063. SetShaderParameter_OGL(param, color.Data(), 4);
  1064. }
  1065. void Graphics::SetShaderParameter_OGL(StringHash param, const Vector2& vector)
  1066. {
  1067. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1068. if (impl->shaderProgram_)
  1069. {
  1070. const ShaderParameter* info = impl->shaderProgram_->GetParameter(param);
  1071. if (info)
  1072. {
  1073. if (info->bufferPtr_)
  1074. {
  1075. ConstantBuffer* buffer = info->bufferPtr_;
  1076. if (!buffer->IsDirty())
  1077. impl->dirtyConstantBuffers_.Push(buffer);
  1078. buffer->SetParameter(info->offset_, sizeof(Vector2), &vector);
  1079. return;
  1080. }
  1081. // Check the uniform type to avoid mismatch
  1082. switch (info->glType_)
  1083. {
  1084. case GL_FLOAT:
  1085. glUniform1fv(info->location_, 1, vector.Data());
  1086. break;
  1087. case GL_FLOAT_VEC2:
  1088. glUniform2fv(info->location_, 1, vector.Data());
  1089. break;
  1090. default: break;
  1091. }
  1092. }
  1093. }
  1094. }
  1095. void Graphics::SetShaderParameter_OGL(StringHash param, const Matrix3& matrix)
  1096. {
  1097. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1098. if (impl->shaderProgram_)
  1099. {
  1100. const ShaderParameter* info = impl->shaderProgram_->GetParameter(param);
  1101. if (info)
  1102. {
  1103. if (info->bufferPtr_)
  1104. {
  1105. ConstantBuffer* buffer = info->bufferPtr_;
  1106. if (!buffer->IsDirty())
  1107. impl->dirtyConstantBuffers_.Push(buffer);
  1108. buffer->SetVector3ArrayParameter(info->offset_, 3, &matrix);
  1109. return;
  1110. }
  1111. glUniformMatrix3fv(info->location_, 1, GL_FALSE, matrix.Data());
  1112. }
  1113. }
  1114. }
  1115. void Graphics::SetShaderParameter_OGL(StringHash param, const Vector3& vector)
  1116. {
  1117. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1118. if (impl->shaderProgram_)
  1119. {
  1120. const ShaderParameter* info = impl->shaderProgram_->GetParameter(param);
  1121. if (info)
  1122. {
  1123. if (info->bufferPtr_)
  1124. {
  1125. ConstantBuffer* buffer = info->bufferPtr_;
  1126. if (!buffer->IsDirty())
  1127. impl->dirtyConstantBuffers_.Push(buffer);
  1128. buffer->SetParameter(info->offset_, sizeof(Vector3), &vector);
  1129. return;
  1130. }
  1131. // Check the uniform type to avoid mismatch
  1132. switch (info->glType_)
  1133. {
  1134. case GL_FLOAT:
  1135. glUniform1fv(info->location_, 1, vector.Data());
  1136. break;
  1137. case GL_FLOAT_VEC2:
  1138. glUniform2fv(info->location_, 1, vector.Data());
  1139. break;
  1140. case GL_FLOAT_VEC3:
  1141. glUniform3fv(info->location_, 1, vector.Data());
  1142. break;
  1143. default: break;
  1144. }
  1145. }
  1146. }
  1147. }
  1148. void Graphics::SetShaderParameter_OGL(StringHash param, const Matrix4& matrix)
  1149. {
  1150. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1151. if (impl->shaderProgram_)
  1152. {
  1153. const ShaderParameter* info = impl->shaderProgram_->GetParameter(param);
  1154. if (info)
  1155. {
  1156. if (info->bufferPtr_)
  1157. {
  1158. ConstantBuffer* buffer = info->bufferPtr_;
  1159. if (!buffer->IsDirty())
  1160. impl->dirtyConstantBuffers_.Push(buffer);
  1161. buffer->SetParameter(info->offset_, sizeof(Matrix4), &matrix);
  1162. return;
  1163. }
  1164. glUniformMatrix4fv(info->location_, 1, GL_FALSE, matrix.Data());
  1165. }
  1166. }
  1167. }
  1168. void Graphics::SetShaderParameter_OGL(StringHash param, const Vector4& vector)
  1169. {
  1170. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1171. if (impl->shaderProgram_)
  1172. {
  1173. const ShaderParameter* info = impl->shaderProgram_->GetParameter(param);
  1174. if (info)
  1175. {
  1176. if (info->bufferPtr_)
  1177. {
  1178. ConstantBuffer* buffer = info->bufferPtr_;
  1179. if (!buffer->IsDirty())
  1180. impl->dirtyConstantBuffers_.Push(buffer);
  1181. buffer->SetParameter(info->offset_, sizeof(Vector4), &vector);
  1182. return;
  1183. }
  1184. // Check the uniform type to avoid mismatch
  1185. switch (info->glType_)
  1186. {
  1187. case GL_FLOAT:
  1188. glUniform1fv(info->location_, 1, vector.Data());
  1189. break;
  1190. case GL_FLOAT_VEC2:
  1191. glUniform2fv(info->location_, 1, vector.Data());
  1192. break;
  1193. case GL_FLOAT_VEC3:
  1194. glUniform3fv(info->location_, 1, vector.Data());
  1195. break;
  1196. case GL_FLOAT_VEC4:
  1197. glUniform4fv(info->location_, 1, vector.Data());
  1198. break;
  1199. default: break;
  1200. }
  1201. }
  1202. }
  1203. }
  1204. void Graphics::SetShaderParameter_OGL(StringHash param, const Matrix3x4& matrix)
  1205. {
  1206. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1207. if (impl->shaderProgram_)
  1208. {
  1209. const ShaderParameter* info = impl->shaderProgram_->GetParameter(param);
  1210. if (info)
  1211. {
  1212. // Expand to a full Matrix4
  1213. static Matrix4 fullMatrix;
  1214. fullMatrix.m00_ = matrix.m00_;
  1215. fullMatrix.m01_ = matrix.m01_;
  1216. fullMatrix.m02_ = matrix.m02_;
  1217. fullMatrix.m03_ = matrix.m03_;
  1218. fullMatrix.m10_ = matrix.m10_;
  1219. fullMatrix.m11_ = matrix.m11_;
  1220. fullMatrix.m12_ = matrix.m12_;
  1221. fullMatrix.m13_ = matrix.m13_;
  1222. fullMatrix.m20_ = matrix.m20_;
  1223. fullMatrix.m21_ = matrix.m21_;
  1224. fullMatrix.m22_ = matrix.m22_;
  1225. fullMatrix.m23_ = matrix.m23_;
  1226. if (info->bufferPtr_)
  1227. {
  1228. ConstantBuffer* buffer = info->bufferPtr_;
  1229. if (!buffer->IsDirty())
  1230. impl->dirtyConstantBuffers_.Push(buffer);
  1231. buffer->SetParameter(info->offset_, sizeof(Matrix4), &fullMatrix);
  1232. return;
  1233. }
  1234. glUniformMatrix4fv(info->location_, 1, GL_FALSE, fullMatrix.Data());
  1235. }
  1236. }
  1237. }
  1238. bool Graphics::NeedParameterUpdate_OGL(ShaderParameterGroup group, const void* source)
  1239. {
  1240. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1241. return impl->shaderProgram_ ? impl->shaderProgram_->NeedParameterUpdate(group, source) : false;
  1242. }
  1243. bool Graphics::HasShaderParameter_OGL(StringHash param)
  1244. {
  1245. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1246. return impl->shaderProgram_ && impl->shaderProgram_->HasParameter(param);
  1247. }
  1248. bool Graphics::HasTextureUnit_OGL(TextureUnit unit)
  1249. {
  1250. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1251. return impl->shaderProgram_ && impl->shaderProgram_->HasTextureUnit(unit);
  1252. }
  1253. void Graphics::ClearParameterSource_OGL(ShaderParameterGroup group)
  1254. {
  1255. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1256. if (impl->shaderProgram_)
  1257. impl->shaderProgram_->ClearParameterSource(group);
  1258. }
  1259. void Graphics::ClearParameterSources_OGL()
  1260. {
  1261. ShaderProgram_OGL::ClearParameterSources();
  1262. }
  1263. void Graphics::ClearTransformSources_OGL()
  1264. {
  1265. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1266. if (impl->shaderProgram_)
  1267. {
  1268. impl->shaderProgram_->ClearParameterSource(SP_CAMERA);
  1269. impl->shaderProgram_->ClearParameterSource(SP_OBJECT);
  1270. }
  1271. }
  1272. void Graphics::SetTexture_OGL(unsigned index, Texture* texture)
  1273. {
  1274. if (index >= MAX_TEXTURE_UNITS)
  1275. return;
  1276. // Check if texture is currently bound as a rendertarget. In that case, use its backup texture, or blank if not defined
  1277. if (texture)
  1278. {
  1279. if (renderTargets_[0] && renderTargets_[0]->GetParentTexture() == texture)
  1280. texture = texture->GetBackupTexture();
  1281. else
  1282. {
  1283. // Resolve multisampled texture now as necessary
  1284. if (texture->GetMultiSample() > 1 && texture->GetAutoResolve() && texture->IsResolveDirty())
  1285. {
  1286. if (texture->GetType() == Texture2D::GetTypeStatic())
  1287. ResolveToTexture_OGL(static_cast<Texture2D*>(texture));
  1288. if (texture->GetType() == TextureCube::GetTypeStatic())
  1289. ResolveToTexture_OGL(static_cast<TextureCube*>(texture));
  1290. }
  1291. }
  1292. }
  1293. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1294. if (textures_[index] != texture)
  1295. {
  1296. if (impl->activeTexture_ != index)
  1297. {
  1298. glActiveTexture(GL_TEXTURE0 + index);
  1299. impl->activeTexture_ = index;
  1300. }
  1301. if (texture)
  1302. {
  1303. unsigned glType = texture->GetTarget();
  1304. // Unbind old texture type if necessary
  1305. if (impl->textureTypes_[index] && impl->textureTypes_[index] != glType)
  1306. glBindTexture(impl->textureTypes_[index], 0);
  1307. glBindTexture(glType, texture->GetGPUObjectName());
  1308. impl->textureTypes_[index] = glType;
  1309. if (texture->GetParametersDirty())
  1310. texture->UpdateParameters();
  1311. if (texture->GetLevelsDirty())
  1312. texture->RegenerateLevels();
  1313. }
  1314. else if (impl->textureTypes_[index])
  1315. {
  1316. glBindTexture(impl->textureTypes_[index], 0);
  1317. impl->textureTypes_[index] = 0;
  1318. }
  1319. textures_[index] = texture;
  1320. }
  1321. else
  1322. {
  1323. if (texture && (texture->GetParametersDirty() || texture->GetLevelsDirty()))
  1324. {
  1325. if (impl->activeTexture_ != index)
  1326. {
  1327. glActiveTexture(GL_TEXTURE0 + index);
  1328. impl->activeTexture_ = index;
  1329. }
  1330. glBindTexture(texture->GetTarget(), texture->GetGPUObjectName());
  1331. if (texture->GetParametersDirty())
  1332. texture->UpdateParameters();
  1333. if (texture->GetLevelsDirty())
  1334. texture->RegenerateLevels();
  1335. }
  1336. }
  1337. }
  1338. void Graphics::SetTextureForUpdate_OGL(Texture* texture)
  1339. {
  1340. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1341. if (impl->activeTexture_ != 0)
  1342. {
  1343. glActiveTexture(GL_TEXTURE0);
  1344. impl->activeTexture_ = 0;
  1345. }
  1346. unsigned glType = texture->GetTarget();
  1347. // Unbind old texture type if necessary
  1348. if (impl->textureTypes_[0] && impl->textureTypes_[0] != glType)
  1349. glBindTexture(impl->textureTypes_[0], 0);
  1350. glBindTexture(glType, texture->GetGPUObjectName());
  1351. impl->textureTypes_[0] = glType;
  1352. textures_[0] = texture;
  1353. }
  1354. void Graphics::SetDefaultTextureFilterMode_OGL(TextureFilterMode mode)
  1355. {
  1356. if (mode != defaultTextureFilterMode_)
  1357. {
  1358. defaultTextureFilterMode_ = mode;
  1359. SetTextureParametersDirty_OGL();
  1360. }
  1361. }
  1362. void Graphics::SetDefaultTextureAnisotropy_OGL(unsigned level)
  1363. {
  1364. level = Max(level, 1U);
  1365. if (level != defaultTextureAnisotropy_)
  1366. {
  1367. defaultTextureAnisotropy_ = level;
  1368. SetTextureParametersDirty_OGL();
  1369. }
  1370. }
  1371. void Graphics::SetTextureParametersDirty_OGL()
  1372. {
  1373. MutexLock lock(gpuObjectMutex_);
  1374. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1375. {
  1376. auto* texture = dynamic_cast<Texture*>(*i);
  1377. if (texture)
  1378. texture->SetParametersDirty();
  1379. }
  1380. }
  1381. void Graphics::ResetRenderTargets_OGL()
  1382. {
  1383. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  1384. SetRenderTarget_OGL(i, (RenderSurface*)nullptr);
  1385. SetDepthStencil_OGL((RenderSurface*)nullptr);
  1386. SetViewport_OGL(IntRect(0, 0, width_, height_));
  1387. }
  1388. void Graphics::ResetRenderTarget_OGL(unsigned index)
  1389. {
  1390. SetRenderTarget_OGL(index, (RenderSurface*)nullptr);
  1391. }
  1392. void Graphics::ResetDepthStencil_OGL()
  1393. {
  1394. SetDepthStencil_OGL((RenderSurface*)nullptr);
  1395. }
  1396. void Graphics::SetRenderTarget_OGL(unsigned index, RenderSurface* renderTarget)
  1397. {
  1398. if (index >= MAX_RENDERTARGETS)
  1399. return;
  1400. if (renderTarget != renderTargets_[index])
  1401. {
  1402. renderTargets_[index] = renderTarget;
  1403. // If the rendertarget is also bound as a texture, replace with backup texture or null
  1404. if (renderTarget)
  1405. {
  1406. Texture* parentTexture = renderTarget->GetParentTexture();
  1407. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1408. {
  1409. if (textures_[i] == parentTexture)
  1410. SetTexture_OGL(i, textures_[i]->GetBackupTexture());
  1411. }
  1412. // If multisampled, mark the texture & surface needing resolve
  1413. if (parentTexture->GetMultiSample() > 1 && parentTexture->GetAutoResolve())
  1414. {
  1415. parentTexture->SetResolveDirty(true);
  1416. renderTarget->SetResolveDirty(true);
  1417. }
  1418. // If mipmapped, mark the levels needing regeneration
  1419. if (parentTexture->GetLevels() > 1)
  1420. parentTexture->SetLevelsDirty();
  1421. }
  1422. GetImpl_OGL()->fboDirty_ = true;
  1423. }
  1424. }
  1425. void Graphics::SetRenderTarget_OGL(unsigned index, Texture2D* texture)
  1426. {
  1427. RenderSurface* renderTarget = nullptr;
  1428. if (texture)
  1429. renderTarget = texture->GetRenderSurface();
  1430. SetRenderTarget_OGL(index, renderTarget);
  1431. }
  1432. void Graphics::SetDepthStencil_OGL(RenderSurface* depthStencil)
  1433. {
  1434. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1435. // If we are using a rendertarget texture, it is required in OpenGL to also have an own depth-stencil
  1436. // Create a new depth-stencil texture as necessary to be able to provide similar behaviour as Direct3D9
  1437. // Only do this for non-multisampled rendertargets; when using multisampled target a similarly multisampled
  1438. // depth-stencil should also be provided (backbuffer depth isn't compatible)
  1439. if (renderTargets_[0] && renderTargets_[0]->GetMultiSample() == 1 && !depthStencil)
  1440. {
  1441. int width = renderTargets_[0]->GetWidth();
  1442. int height = renderTargets_[0]->GetHeight();
  1443. // Direct3D9 default depth-stencil can not be used when rendertarget is larger than the window.
  1444. // Check size similarly
  1445. if (width <= width_ && height <= height_)
  1446. {
  1447. unsigned searchKey = (width << 16u) | height;
  1448. HashMap<unsigned, SharedPtr<Texture2D> >::Iterator i = impl->depthTextures_.Find(searchKey);
  1449. if (i != impl->depthTextures_.End())
  1450. depthStencil = i->second_->GetRenderSurface();
  1451. else
  1452. {
  1453. SharedPtr<Texture2D> newDepthTexture(new Texture2D(context_));
  1454. newDepthTexture->SetSize(width, height, GetDepthStencilFormat_OGL(), TEXTURE_DEPTHSTENCIL);
  1455. impl->depthTextures_[searchKey] = newDepthTexture;
  1456. depthStencil = newDepthTexture->GetRenderSurface();
  1457. }
  1458. }
  1459. }
  1460. if (depthStencil != depthStencil_)
  1461. {
  1462. depthStencil_ = depthStencil;
  1463. impl->fboDirty_ = true;
  1464. }
  1465. }
  1466. void Graphics::SetDepthStencil_OGL(Texture2D* texture)
  1467. {
  1468. RenderSurface* depthStencil = nullptr;
  1469. if (texture)
  1470. depthStencil = texture->GetRenderSurface();
  1471. SetDepthStencil_OGL(depthStencil);
  1472. }
  1473. void Graphics::SetViewport_OGL(const IntRect& rect)
  1474. {
  1475. PrepareDraw_OGL();
  1476. IntVector2 rtSize = GetRenderTargetDimensions_OGL();
  1477. IntRect rectCopy = rect;
  1478. if (rectCopy.right_ <= rectCopy.left_)
  1479. rectCopy.right_ = rectCopy.left_ + 1;
  1480. if (rectCopy.bottom_ <= rectCopy.top_)
  1481. rectCopy.bottom_ = rectCopy.top_ + 1;
  1482. rectCopy.left_ = Clamp(rectCopy.left_, 0, rtSize.x_);
  1483. rectCopy.top_ = Clamp(rectCopy.top_, 0, rtSize.y_);
  1484. rectCopy.right_ = Clamp(rectCopy.right_, 0, rtSize.x_);
  1485. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, rtSize.y_);
  1486. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1487. glViewport(rectCopy.left_, rtSize.y_ - rectCopy.bottom_, rectCopy.Width(), rectCopy.Height());
  1488. viewport_ = rectCopy;
  1489. // Disable scissor test, needs to be re-enabled by the user
  1490. SetScissorTest_OGL(false);
  1491. }
  1492. void Graphics::SetBlendMode_OGL(BlendMode mode, bool alphaToCoverage)
  1493. {
  1494. if (mode != blendMode_)
  1495. {
  1496. if (mode == BLEND_REPLACE)
  1497. glDisable(GL_BLEND);
  1498. else
  1499. {
  1500. glEnable(GL_BLEND);
  1501. glBlendFunc(glSrcBlend[mode], glDestBlend[mode]);
  1502. glBlendEquation(glBlendOp[mode]);
  1503. }
  1504. blendMode_ = mode;
  1505. }
  1506. if (alphaToCoverage != alphaToCoverage_)
  1507. {
  1508. if (alphaToCoverage)
  1509. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1510. else
  1511. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1512. alphaToCoverage_ = alphaToCoverage;
  1513. }
  1514. }
  1515. void Graphics::SetColorWrite_OGL(bool enable)
  1516. {
  1517. if (enable != colorWrite_)
  1518. {
  1519. if (enable)
  1520. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1521. else
  1522. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1523. colorWrite_ = enable;
  1524. }
  1525. }
  1526. void Graphics::SetCullMode_OGL(CullMode mode)
  1527. {
  1528. if (mode != cullMode_)
  1529. {
  1530. if (mode == CULL_NONE)
  1531. glDisable(GL_CULL_FACE);
  1532. else
  1533. {
  1534. // Use Direct3D convention, ie. clockwise vertices define a front face
  1535. glEnable(GL_CULL_FACE);
  1536. glCullFace(mode == CULL_CCW ? GL_FRONT : GL_BACK);
  1537. }
  1538. cullMode_ = mode;
  1539. }
  1540. }
  1541. void Graphics::SetDepthBias_OGL(float constantBias, float slopeScaledBias)
  1542. {
  1543. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1544. {
  1545. #ifndef GL_ES_VERSION_2_0
  1546. if (slopeScaledBias != 0.0f)
  1547. {
  1548. // OpenGL constant bias is unreliable and dependent on depth buffer bitdepth, apply in the projection matrix instead
  1549. glEnable(GL_POLYGON_OFFSET_FILL);
  1550. glPolygonOffset(slopeScaledBias, 0.0f);
  1551. }
  1552. else
  1553. glDisable(GL_POLYGON_OFFSET_FILL);
  1554. #endif
  1555. constantDepthBias_ = constantBias;
  1556. slopeScaledDepthBias_ = slopeScaledBias;
  1557. // Force update of the projection matrix shader parameter
  1558. ClearParameterSource_OGL(SP_CAMERA);
  1559. }
  1560. }
  1561. void Graphics::SetDepthTest_OGL(CompareMode mode)
  1562. {
  1563. if (mode != depthTestMode_)
  1564. {
  1565. glDepthFunc(glCmpFunc[mode]);
  1566. depthTestMode_ = mode;
  1567. }
  1568. }
  1569. void Graphics::SetDepthWrite_OGL(bool enable)
  1570. {
  1571. if (enable != depthWrite_)
  1572. {
  1573. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1574. depthWrite_ = enable;
  1575. }
  1576. }
  1577. void Graphics::SetFillMode_OGL(FillMode mode)
  1578. {
  1579. #ifndef GL_ES_VERSION_2_0
  1580. if (mode != fillMode_)
  1581. {
  1582. glPolygonMode(GL_FRONT_AND_BACK, glFillMode[mode]);
  1583. fillMode_ = mode;
  1584. }
  1585. #endif
  1586. }
  1587. void Graphics::SetLineAntiAlias_OGL(bool enable)
  1588. {
  1589. #ifndef GL_ES_VERSION_2_0
  1590. if (enable != lineAntiAlias_)
  1591. {
  1592. if (enable)
  1593. glEnable(GL_LINE_SMOOTH);
  1594. else
  1595. glDisable(GL_LINE_SMOOTH);
  1596. lineAntiAlias_ = enable;
  1597. }
  1598. #endif
  1599. }
  1600. void Graphics::SetScissorTest_OGL(bool enable, const Rect& rect, bool borderInclusive)
  1601. {
  1602. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1603. // Disable scissor in that case to reduce state changes
  1604. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1605. enable = false;
  1606. if (enable)
  1607. {
  1608. IntVector2 rtSize(GetRenderTargetDimensions_OGL());
  1609. IntVector2 viewSize(viewport_.Size());
  1610. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1611. IntRect intRect;
  1612. int expand = borderInclusive ? 1 : 0;
  1613. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1614. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1615. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1616. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1617. if (intRect.right_ == intRect.left_)
  1618. intRect.right_++;
  1619. if (intRect.bottom_ == intRect.top_)
  1620. intRect.bottom_++;
  1621. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1622. enable = false;
  1623. if (enable && scissorRect_ != intRect)
  1624. {
  1625. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1626. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.Width(), intRect.Height());
  1627. scissorRect_ = intRect;
  1628. }
  1629. }
  1630. else
  1631. scissorRect_ = IntRect::ZERO;
  1632. if (enable != scissorTest_)
  1633. {
  1634. if (enable)
  1635. glEnable(GL_SCISSOR_TEST);
  1636. else
  1637. glDisable(GL_SCISSOR_TEST);
  1638. scissorTest_ = enable;
  1639. }
  1640. }
  1641. void Graphics::SetScissorTest_OGL(bool enable, const IntRect& rect)
  1642. {
  1643. IntVector2 rtSize(GetRenderTargetDimensions_OGL());
  1644. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1645. if (enable)
  1646. {
  1647. IntRect intRect;
  1648. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1649. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1650. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1651. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1652. if (intRect.right_ == intRect.left_)
  1653. intRect.right_++;
  1654. if (intRect.bottom_ == intRect.top_)
  1655. intRect.bottom_++;
  1656. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1657. enable = false;
  1658. if (enable && scissorRect_ != intRect)
  1659. {
  1660. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1661. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.Width(), intRect.Height());
  1662. scissorRect_ = intRect;
  1663. }
  1664. }
  1665. else
  1666. scissorRect_ = IntRect::ZERO;
  1667. if (enable != scissorTest_)
  1668. {
  1669. if (enable)
  1670. glEnable(GL_SCISSOR_TEST);
  1671. else
  1672. glDisable(GL_SCISSOR_TEST);
  1673. scissorTest_ = enable;
  1674. }
  1675. }
  1676. void Graphics::SetClipPlane_OGL(bool enable, const Plane& clipPlane, const Matrix3x4& view, const Matrix4& projection)
  1677. {
  1678. #ifndef GL_ES_VERSION_2_0
  1679. if (enable != useClipPlane_)
  1680. {
  1681. if (enable)
  1682. glEnable(GL_CLIP_PLANE0);
  1683. else
  1684. glDisable(GL_CLIP_PLANE0);
  1685. useClipPlane_ = enable;
  1686. }
  1687. if (enable)
  1688. {
  1689. Matrix4 viewProj = projection * view;
  1690. clipPlane_ = clipPlane.Transformed(viewProj).ToVector4();
  1691. if (!gl3Support)
  1692. {
  1693. GLdouble planeData[4];
  1694. planeData[0] = clipPlane_.x_;
  1695. planeData[1] = clipPlane_.y_;
  1696. planeData[2] = clipPlane_.z_;
  1697. planeData[3] = clipPlane_.w_;
  1698. glClipPlane(GL_CLIP_PLANE0, &planeData[0]);
  1699. }
  1700. }
  1701. #endif
  1702. }
  1703. void Graphics::SetStencilTest_OGL(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef,
  1704. unsigned compareMask, unsigned writeMask)
  1705. {
  1706. #ifndef GL_ES_VERSION_2_0
  1707. if (enable != stencilTest_)
  1708. {
  1709. if (enable)
  1710. glEnable(GL_STENCIL_TEST);
  1711. else
  1712. glDisable(GL_STENCIL_TEST);
  1713. stencilTest_ = enable;
  1714. }
  1715. if (enable)
  1716. {
  1717. if (mode != stencilTestMode_ || stencilRef != stencilRef_ || compareMask != stencilCompareMask_)
  1718. {
  1719. glStencilFunc(glCmpFunc[mode], stencilRef, compareMask);
  1720. stencilTestMode_ = mode;
  1721. stencilRef_ = stencilRef;
  1722. stencilCompareMask_ = compareMask;
  1723. }
  1724. if (writeMask != stencilWriteMask_)
  1725. {
  1726. glStencilMask(writeMask);
  1727. stencilWriteMask_ = writeMask;
  1728. }
  1729. if (pass != stencilPass_ || fail != stencilFail_ || zFail != stencilZFail_)
  1730. {
  1731. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1732. stencilPass_ = pass;
  1733. stencilFail_ = fail;
  1734. stencilZFail_ = zFail;
  1735. }
  1736. }
  1737. #endif
  1738. }
  1739. bool Graphics::IsInitialized_OGL() const
  1740. {
  1741. return window_ != nullptr;
  1742. }
  1743. bool Graphics::GetDither_OGL() const
  1744. {
  1745. return glIsEnabled(GL_DITHER) ? true : false;
  1746. }
  1747. bool Graphics::IsDeviceLost_OGL() const
  1748. {
  1749. // On iOS and tvOS treat window minimization as device loss, as it is forbidden to access OpenGL when minimized
  1750. #if defined(IOS) || defined(TVOS)
  1751. if (window_ && (SDL_GetWindowFlags(window_) & SDL_WINDOW_MINIMIZED) != 0)
  1752. return true;
  1753. #endif
  1754. return GetImpl_OGL()->context_ == nullptr;
  1755. }
  1756. PODVector<int> Graphics::GetMultiSampleLevels_OGL() const
  1757. {
  1758. PODVector<int> ret;
  1759. // No multisampling always supported
  1760. ret.Push(1);
  1761. #ifndef GL_ES_VERSION_2_0
  1762. int maxSamples = 0;
  1763. glGetIntegerv(GL_MAX_SAMPLES, &maxSamples);
  1764. for (int i = 2; i <= maxSamples && i <= 16; i *= 2)
  1765. ret.Push(i);
  1766. #endif
  1767. return ret;
  1768. }
  1769. unsigned Graphics::GetFormat_OGL(CompressedFormat format) const
  1770. {
  1771. switch (format)
  1772. {
  1773. case CF_RGBA:
  1774. return GL_RGBA;
  1775. case CF_DXT1:
  1776. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT1_EXT : 0;
  1777. #if !defined(GL_ES_VERSION_2_0) || defined(__EMSCRIPTEN__)
  1778. case CF_DXT3:
  1779. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT3_EXT : 0;
  1780. case CF_DXT5:
  1781. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT5_EXT : 0;
  1782. #endif
  1783. #ifdef GL_ES_VERSION_2_0
  1784. case CF_ETC1:
  1785. return etcTextureSupport_ ? GL_ETC1_RGB8_OES : 0;
  1786. case CF_ETC2_RGB:
  1787. return etc2TextureSupport_ ? GL_ETC2_RGB8_OES : 0;
  1788. case CF_ETC2_RGBA:
  1789. return etc2TextureSupport_ ? GL_ETC2_RGBA8_OES : 0;
  1790. case CF_PVRTC_RGB_2BPP:
  1791. return pvrtcTextureSupport_ ? COMPRESSED_RGB_PVRTC_2BPPV1_IMG : 0;
  1792. case CF_PVRTC_RGB_4BPP:
  1793. return pvrtcTextureSupport_ ? COMPRESSED_RGB_PVRTC_4BPPV1_IMG : 0;
  1794. case CF_PVRTC_RGBA_2BPP:
  1795. return pvrtcTextureSupport_ ? COMPRESSED_RGBA_PVRTC_2BPPV1_IMG : 0;
  1796. case CF_PVRTC_RGBA_4BPP:
  1797. return pvrtcTextureSupport_ ? COMPRESSED_RGBA_PVRTC_4BPPV1_IMG : 0;
  1798. #endif
  1799. default:
  1800. return 0;
  1801. }
  1802. }
  1803. unsigned Graphics::GetMaxBones_OGL()
  1804. {
  1805. #ifdef RPI
  1806. // At the moment all RPI GPUs are low powered and only have limited number of uniforms
  1807. return 32;
  1808. #else
  1809. return gl3Support ? 128 : 64;
  1810. #endif
  1811. }
  1812. bool Graphics::GetGL3Support_OGL()
  1813. {
  1814. return gl3Support;
  1815. }
  1816. ShaderVariation* Graphics::GetShader_OGL(ShaderType type, const String& name, const String& defines) const
  1817. {
  1818. return GetShader_OGL(type, name.CString(), defines.CString());
  1819. }
  1820. ShaderVariation* Graphics::GetShader_OGL(ShaderType type, const char* name, const char* defines) const
  1821. {
  1822. if (lastShaderName_ != name || !lastShader_)
  1823. {
  1824. auto* cache = GetSubsystem<ResourceCache>();
  1825. String fullShaderName = shaderPath_ + name + shaderExtension_;
  1826. // Try to reduce repeated error log prints because of missing shaders
  1827. if (lastShaderName_ == name && !cache->Exists(fullShaderName))
  1828. return nullptr;
  1829. lastShader_ = cache->GetResource<Shader>(fullShaderName);
  1830. lastShaderName_ = name;
  1831. }
  1832. return lastShader_ ? lastShader_->GetVariation(type, defines) : nullptr;
  1833. }
  1834. VertexBuffer* Graphics::GetVertexBuffer_OGL(unsigned index) const
  1835. {
  1836. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : nullptr;
  1837. }
  1838. ShaderProgram_OGL* Graphics::GetShaderProgram_OGL() const
  1839. {
  1840. return GetImpl_OGL()->shaderProgram_;
  1841. }
  1842. TextureUnit Graphics::GetTextureUnit_OGL(const String& name)
  1843. {
  1844. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1845. if (i != textureUnits_.End())
  1846. return i->second_;
  1847. else
  1848. return MAX_TEXTURE_UNITS;
  1849. }
  1850. const String& Graphics::GetTextureUnitName_OGL(TextureUnit unit)
  1851. {
  1852. for (HashMap<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1853. {
  1854. if (i->second_ == unit)
  1855. return i->first_;
  1856. }
  1857. return String::EMPTY;
  1858. }
  1859. Texture* Graphics::GetTexture_OGL(unsigned index) const
  1860. {
  1861. return index < MAX_TEXTURE_UNITS ? textures_[index] : nullptr;
  1862. }
  1863. RenderSurface* Graphics::GetRenderTarget_OGL(unsigned index) const
  1864. {
  1865. return index < MAX_RENDERTARGETS ? renderTargets_[index] : nullptr;
  1866. }
  1867. IntVector2 Graphics::GetRenderTargetDimensions_OGL() const
  1868. {
  1869. int width, height;
  1870. if (renderTargets_[0])
  1871. {
  1872. width = renderTargets_[0]->GetWidth();
  1873. height = renderTargets_[0]->GetHeight();
  1874. }
  1875. else if (depthStencil_)
  1876. {
  1877. width = depthStencil_->GetWidth();
  1878. height = depthStencil_->GetHeight();
  1879. }
  1880. else
  1881. {
  1882. width = width_;
  1883. height = height_;
  1884. }
  1885. return IntVector2(width, height);
  1886. }
  1887. void Graphics::OnWindowResized_OGL()
  1888. {
  1889. if (!window_)
  1890. return;
  1891. int newWidth, newHeight;
  1892. SDL_GL_GetDrawableSize(window_, &newWidth, &newHeight);
  1893. if (newWidth == width_ && newHeight == height_)
  1894. return;
  1895. width_ = newWidth;
  1896. height_ = newHeight;
  1897. int logicalWidth, logicalHeight;
  1898. SDL_GetWindowSize(window_, &logicalWidth, &logicalHeight);
  1899. screenParams_.highDPI_ = (width_ != logicalWidth) || (height_ != logicalHeight);
  1900. // Reset rendertargets and viewport for the new screen size. Also clean up any FBO's, as they may be screen size dependent
  1901. CleanupFramebuffers_OGL();
  1902. ResetRenderTargets_OGL();
  1903. URHO3D_LOGDEBUGF("Window was resized to %dx%d", width_, height_);
  1904. #ifdef __EMSCRIPTEN__
  1905. EM_ASM({
  1906. Module.SetRendererSize($0, $1);
  1907. }, width_, height_);
  1908. #endif
  1909. using namespace ScreenMode;
  1910. VariantMap& eventData = GetEventDataMap();
  1911. eventData[P_WIDTH] = width_;
  1912. eventData[P_HEIGHT] = height_;
  1913. eventData[P_FULLSCREEN] = screenParams_.fullscreen_;
  1914. eventData[P_RESIZABLE] = screenParams_.resizable_;
  1915. eventData[P_BORDERLESS] = screenParams_.borderless_;
  1916. eventData[P_HIGHDPI] = screenParams_.highDPI_;
  1917. SendEvent(E_SCREENMODE, eventData);
  1918. }
  1919. void Graphics::OnWindowMoved_OGL()
  1920. {
  1921. if (!window_ || screenParams_.fullscreen_)
  1922. return;
  1923. int newX, newY;
  1924. SDL_GetWindowPosition(window_, &newX, &newY);
  1925. if (newX == position_.x_ && newY == position_.y_)
  1926. return;
  1927. position_.x_ = newX;
  1928. position_.y_ = newY;
  1929. URHO3D_LOGTRACEF("Window was moved to %d,%d", position_.x_, position_.y_);
  1930. using namespace WindowPos;
  1931. VariantMap& eventData = GetEventDataMap();
  1932. eventData[P_X] = position_.x_;
  1933. eventData[P_Y] = position_.y_;
  1934. SendEvent(E_WINDOWPOS, eventData);
  1935. }
  1936. void Graphics::CleanupRenderSurface_OGL(RenderSurface* surface)
  1937. {
  1938. if (!surface)
  1939. return;
  1940. // Flush pending FBO changes first if any
  1941. PrepareDraw_OGL();
  1942. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1943. unsigned currentFBO = impl->boundFBO_;
  1944. // Go through all FBOs and clean up the surface from them
  1945. for (HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl->frameBuffers_.Begin();
  1946. i != impl->frameBuffers_.End(); ++i)
  1947. {
  1948. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1949. {
  1950. if (i->second_.colorAttachments_[j] == surface)
  1951. {
  1952. if (currentFBO != i->second_.fbo_)
  1953. {
  1954. BindFramebuffer_OGL(i->second_.fbo_);
  1955. currentFBO = i->second_.fbo_;
  1956. }
  1957. BindColorAttachment_OGL(j, GL_TEXTURE_2D, 0, false);
  1958. i->second_.colorAttachments_[j] = nullptr;
  1959. // Mark drawbuffer bits to need recalculation
  1960. i->second_.drawBuffers_ = M_MAX_UNSIGNED;
  1961. }
  1962. }
  1963. if (i->second_.depthAttachment_ == surface)
  1964. {
  1965. if (currentFBO != i->second_.fbo_)
  1966. {
  1967. BindFramebuffer_OGL(i->second_.fbo_);
  1968. currentFBO = i->second_.fbo_;
  1969. }
  1970. BindDepthAttachment_OGL(0, false);
  1971. BindStencilAttachment_OGL(0, false);
  1972. i->second_.depthAttachment_ = nullptr;
  1973. }
  1974. }
  1975. // Restore previously bound FBO now if needed
  1976. if (currentFBO != impl->boundFBO_)
  1977. BindFramebuffer_OGL(impl->boundFBO_);
  1978. }
  1979. void Graphics::CleanupShaderPrograms_OGL(ShaderVariation* variation)
  1980. {
  1981. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1982. for (ShaderProgramMap_OGL::Iterator i = impl->shaderPrograms_.Begin(); i != impl->shaderPrograms_.End();)
  1983. {
  1984. if (i->second_->GetVertexShader() == variation || i->second_->GetPixelShader() == variation)
  1985. i = impl->shaderPrograms_.Erase(i);
  1986. else
  1987. ++i;
  1988. }
  1989. if (vertexShader_ == variation || pixelShader_ == variation)
  1990. impl->shaderProgram_ = nullptr;
  1991. }
  1992. ConstantBuffer* Graphics::GetOrCreateConstantBuffer_OGL(ShaderType type, unsigned index, unsigned size)
  1993. {
  1994. // Note: shaderType parameter is not used on OpenGL, instead binding index should already use the PS range
  1995. // for PS constant buffers
  1996. GraphicsImpl_OGL* impl = GetImpl_OGL();
  1997. unsigned key = (index << 16u) | size;
  1998. HashMap<unsigned, SharedPtr<ConstantBuffer> >::Iterator i = impl->allConstantBuffers_.Find(key);
  1999. if (i == impl->allConstantBuffers_.End())
  2000. {
  2001. i = impl->allConstantBuffers_.Insert(MakePair(key, SharedPtr<ConstantBuffer>(new ConstantBuffer(context_))));
  2002. i->second_->SetSize(size);
  2003. }
  2004. return i->second_.Get();
  2005. }
  2006. void Graphics::Release_OGL(bool clearGPUObjects, bool closeWindow)
  2007. {
  2008. if (!window_)
  2009. return;
  2010. GraphicsImpl_OGL* impl = GetImpl_OGL();
  2011. {
  2012. MutexLock lock(gpuObjectMutex_);
  2013. if (clearGPUObjects)
  2014. {
  2015. // Shutting down: release all GPU objects that still exist
  2016. // Shader programs are also GPU objects; clear them first to avoid list modification during iteration
  2017. impl->shaderPrograms_.Clear();
  2018. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2019. (*i)->Release();
  2020. gpuObjects_.Clear();
  2021. }
  2022. else
  2023. {
  2024. // We are not shutting down, but recreating the context: mark GPU objects lost
  2025. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2026. (*i)->OnDeviceLost();
  2027. // In this case clear shader programs last so that they do not attempt to delete their OpenGL program
  2028. // from a context that may no longer exist
  2029. impl->shaderPrograms_.Clear();
  2030. SendEvent(E_DEVICELOST);
  2031. }
  2032. }
  2033. CleanupFramebuffers_OGL();
  2034. impl->depthTextures_.Clear();
  2035. // End fullscreen mode first to counteract transition and getting stuck problems on OS X
  2036. #if defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  2037. if (closeWindow && screenParams_.fullscreen_ && !externalWindow_)
  2038. SDL_SetWindowFullscreen(window_, 0);
  2039. #endif
  2040. if (impl->context_)
  2041. {
  2042. // Do not log this message if we are exiting
  2043. if (!clearGPUObjects)
  2044. URHO3D_LOGINFO("OpenGL context lost");
  2045. SDL_GL_DeleteContext(impl->context_);
  2046. impl->context_ = nullptr;
  2047. }
  2048. if (closeWindow)
  2049. {
  2050. SDL_ShowCursor(SDL_TRUE);
  2051. // Do not destroy external window except when shutting down
  2052. if (!externalWindow_ || clearGPUObjects)
  2053. {
  2054. SDL_DestroyWindow(window_);
  2055. window_ = nullptr;
  2056. }
  2057. }
  2058. }
  2059. void Graphics::Restore_OGL()
  2060. {
  2061. if (!window_)
  2062. return;
  2063. GraphicsImpl_OGL* impl = GetImpl_OGL();
  2064. #ifdef __ANDROID__
  2065. // On Android the context may be lost behind the scenes as the application is minimized
  2066. if (impl->context_ && !SDL_GL_GetCurrentContext())
  2067. {
  2068. impl->context_ = 0;
  2069. // Mark GPU objects lost without a current context. In this case they just mark their internal state lost
  2070. // but do not perform OpenGL commands to delete the GL objects
  2071. Release_OGL(false, false);
  2072. }
  2073. #endif
  2074. // Ensure first that the context exists
  2075. if (!impl->context_)
  2076. {
  2077. impl->context_ = SDL_GL_CreateContext(window_);
  2078. #ifndef GL_ES_VERSION_2_0
  2079. // If we're trying to use OpenGL 3, but context creation fails, retry with 2
  2080. if (!forceGL2_ && !impl->context_)
  2081. {
  2082. forceGL2_ = true;
  2083. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  2084. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  2085. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, 0);
  2086. impl->context_ = SDL_GL_CreateContext(window_);
  2087. }
  2088. #endif
  2089. #if defined(IOS) || defined(TVOS)
  2090. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&impl->systemFBO_);
  2091. #endif
  2092. if (!impl->context_)
  2093. {
  2094. URHO3D_LOGERRORF("Could not create OpenGL context, root cause '%s'", SDL_GetError());
  2095. return;
  2096. }
  2097. // Clear cached extensions string from the previous context
  2098. extensions.Clear();
  2099. // Initialize OpenGL extensions library (desktop only)
  2100. #ifndef GL_ES_VERSION_2_0
  2101. GLenum err = glewInit();
  2102. if (GLEW_OK != err)
  2103. {
  2104. URHO3D_LOGERRORF("Could not initialize OpenGL extensions, root cause: '%s'", glewGetErrorString(err));
  2105. return;
  2106. }
  2107. if (!forceGL2_ && GLEW_VERSION_3_2)
  2108. {
  2109. gl3Support = true;
  2110. apiName_ = "GL3";
  2111. // Create and bind a vertex array object that will stay in use throughout
  2112. unsigned vertexArrayObject;
  2113. glGenVertexArrays(1, &vertexArrayObject);
  2114. glBindVertexArray(vertexArrayObject);
  2115. }
  2116. else if (GLEW_VERSION_2_0)
  2117. {
  2118. if (!GLEW_EXT_framebuffer_object || !GLEW_EXT_packed_depth_stencil)
  2119. {
  2120. URHO3D_LOGERROR("EXT_framebuffer_object and EXT_packed_depth_stencil OpenGL extensions are required");
  2121. return;
  2122. }
  2123. gl3Support = false;
  2124. apiName_ = "GL2";
  2125. }
  2126. else
  2127. {
  2128. URHO3D_LOGERROR("OpenGL 2.0 is required");
  2129. return;
  2130. }
  2131. // Enable seamless cubemap if possible
  2132. // Note: even though we check the extension, this can lead to software fallback on some old GPU's
  2133. // See https://github.com/urho3d/Urho3D/issues/1380 or
  2134. // http://distrustsimplicity.net/articles/gl_texture_cube_map_seamless-on-os-x/
  2135. // In case of trouble or for wanting maximum compatibility, simply remove the glEnable below.
  2136. if (gl3Support || GLEW_ARB_seamless_cube_map)
  2137. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  2138. #endif
  2139. // Set up texture data read/write alignment. It is important that this is done before uploading any texture data
  2140. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  2141. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  2142. ResetCachedState_OGL();
  2143. }
  2144. {
  2145. MutexLock lock(gpuObjectMutex_);
  2146. for (PODVector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  2147. (*i)->OnDeviceReset();
  2148. }
  2149. SendEvent(E_DEVICERESET);
  2150. }
  2151. void Graphics::MarkFBODirty_OGL()
  2152. {
  2153. GetImpl_OGL()->fboDirty_ = true;
  2154. }
  2155. void Graphics::SetVBO_OGL(unsigned object)
  2156. {
  2157. GraphicsImpl_OGL* impl = GetImpl_OGL();
  2158. if (impl->boundVBO_ != object)
  2159. {
  2160. if (object)
  2161. glBindBuffer(GL_ARRAY_BUFFER, object);
  2162. impl->boundVBO_ = object;
  2163. }
  2164. }
  2165. void Graphics::SetUBO_OGL(unsigned object)
  2166. {
  2167. #ifndef GL_ES_VERSION_2_0
  2168. GraphicsImpl_OGL* impl = GetImpl_OGL();
  2169. if (impl->boundUBO_ != object)
  2170. {
  2171. if (object)
  2172. glBindBuffer(GL_UNIFORM_BUFFER, object);
  2173. impl->boundUBO_ = object;
  2174. }
  2175. #endif
  2176. }
  2177. unsigned Graphics::GetAlphaFormat_OGL()
  2178. {
  2179. #ifndef GL_ES_VERSION_2_0
  2180. // Alpha format is deprecated on OpenGL 3+
  2181. if (gl3Support)
  2182. return GL_R8;
  2183. #endif
  2184. return GL_ALPHA;
  2185. }
  2186. unsigned Graphics::GetLuminanceFormat_OGL()
  2187. {
  2188. #ifndef GL_ES_VERSION_2_0
  2189. // Luminance format is deprecated on OpenGL 3+
  2190. if (gl3Support)
  2191. return GL_R8;
  2192. #endif
  2193. return GL_LUMINANCE;
  2194. }
  2195. unsigned Graphics::GetLuminanceAlphaFormat_OGL()
  2196. {
  2197. #ifndef GL_ES_VERSION_2_0
  2198. // Luminance alpha format is deprecated on OpenGL 3+
  2199. if (gl3Support)
  2200. return GL_RG8;
  2201. #endif
  2202. return GL_LUMINANCE_ALPHA;
  2203. }
  2204. unsigned Graphics::GetRGBFormat_OGL()
  2205. {
  2206. return GL_RGB;
  2207. }
  2208. unsigned Graphics::GetRGBAFormat_OGL()
  2209. {
  2210. return GL_RGBA;
  2211. }
  2212. unsigned Graphics::GetRGBA16Format_OGL()
  2213. {
  2214. #ifndef GL_ES_VERSION_2_0
  2215. return GL_RGBA16;
  2216. #else
  2217. return GL_RGBA;
  2218. #endif
  2219. }
  2220. unsigned Graphics::GetRGBAFloat16Format_OGL()
  2221. {
  2222. #ifndef GL_ES_VERSION_2_0
  2223. return GL_RGBA16F_ARB;
  2224. #else
  2225. return GL_RGBA;
  2226. #endif
  2227. }
  2228. unsigned Graphics::GetRGBAFloat32Format_OGL()
  2229. {
  2230. #ifndef GL_ES_VERSION_2_0
  2231. return GL_RGBA32F_ARB;
  2232. #else
  2233. return GL_RGBA;
  2234. #endif
  2235. }
  2236. unsigned Graphics::GetRG16Format_OGL()
  2237. {
  2238. #ifndef GL_ES_VERSION_2_0
  2239. return GL_RG16;
  2240. #else
  2241. return GL_RGBA;
  2242. #endif
  2243. }
  2244. unsigned Graphics::GetRGFloat16Format_OGL()
  2245. {
  2246. #ifndef GL_ES_VERSION_2_0
  2247. return GL_RG16F;
  2248. #else
  2249. return GL_RGBA;
  2250. #endif
  2251. }
  2252. unsigned Graphics::GetRGFloat32Format_OGL()
  2253. {
  2254. #ifndef GL_ES_VERSION_2_0
  2255. return GL_RG32F;
  2256. #else
  2257. return GL_RGBA;
  2258. #endif
  2259. }
  2260. unsigned Graphics::GetFloat16Format_OGL()
  2261. {
  2262. #ifndef GL_ES_VERSION_2_0
  2263. return GL_R16F;
  2264. #else
  2265. return GL_LUMINANCE;
  2266. #endif
  2267. }
  2268. unsigned Graphics::GetFloat32Format_OGL()
  2269. {
  2270. #ifndef GL_ES_VERSION_2_0
  2271. return GL_R32F;
  2272. #else
  2273. return GL_LUMINANCE;
  2274. #endif
  2275. }
  2276. unsigned Graphics::GetLinearDepthFormat_OGL()
  2277. {
  2278. #ifndef GL_ES_VERSION_2_0
  2279. // OpenGL 3 can use different color attachment formats
  2280. if (gl3Support)
  2281. return GL_R32F;
  2282. #endif
  2283. // OpenGL 2 requires color attachments to have the same format, therefore encode deferred depth to RGBA manually
  2284. // if not using a readable hardware depth texture
  2285. return GL_RGBA;
  2286. }
  2287. unsigned Graphics::GetDepthStencilFormat_OGL()
  2288. {
  2289. #ifndef GL_ES_VERSION_2_0
  2290. return GL_DEPTH24_STENCIL8_EXT;
  2291. #else
  2292. return glesDepthStencilFormat;
  2293. #endif
  2294. }
  2295. unsigned Graphics::GetReadableDepthFormat_OGL()
  2296. {
  2297. #ifndef GL_ES_VERSION_2_0
  2298. return GL_DEPTH_COMPONENT24;
  2299. #else
  2300. return glesReadableDepthFormat;
  2301. #endif
  2302. }
  2303. unsigned Graphics::GetFormat_OGL(const String& formatName)
  2304. {
  2305. String nameLower = formatName.ToLower().Trimmed();
  2306. if (nameLower == "a")
  2307. return GetAlphaFormat_OGL();
  2308. if (nameLower == "l")
  2309. return GetLuminanceFormat_OGL();
  2310. if (nameLower == "la")
  2311. return GetLuminanceAlphaFormat_OGL();
  2312. if (nameLower == "rgb")
  2313. return GetRGBFormat_OGL();
  2314. if (nameLower == "rgba")
  2315. return GetRGBAFormat_OGL();
  2316. if (nameLower == "rgba16")
  2317. return GetRGBA16Format_OGL();
  2318. if (nameLower == "rgba16f")
  2319. return GetRGBAFloat16Format_OGL();
  2320. if (nameLower == "rgba32f")
  2321. return GetRGBAFloat32Format_OGL();
  2322. if (nameLower == "rg16")
  2323. return GetRG16Format_OGL();
  2324. if (nameLower == "rg16f")
  2325. return GetRGFloat16Format_OGL();
  2326. if (nameLower == "rg32f")
  2327. return GetRGFloat32Format_OGL();
  2328. if (nameLower == "r16f")
  2329. return GetFloat16Format_OGL();
  2330. if (nameLower == "r32f" || nameLower == "float")
  2331. return GetFloat32Format_OGL();
  2332. if (nameLower == "lineardepth" || nameLower == "depth")
  2333. return GetLinearDepthFormat_OGL();
  2334. if (nameLower == "d24s8")
  2335. return GetDepthStencilFormat_OGL();
  2336. if (nameLower == "readabledepth" || nameLower == "hwdepth")
  2337. return GetReadableDepthFormat_OGL();
  2338. return GetRGBFormat_OGL();
  2339. }
  2340. void Graphics::CheckFeatureSupport_OGL()
  2341. {
  2342. // Check supported features: light pre-pass, deferred rendering and hardware depth texture
  2343. lightPrepassSupport_ = false;
  2344. deferredSupport_ = false;
  2345. #ifndef GL_ES_VERSION_2_0
  2346. int numSupportedRTs = 1;
  2347. if (gl3Support)
  2348. {
  2349. // Work around GLEW failure to check extensions properly from a GL3 context
  2350. instancingSupport_ = glDrawElementsInstanced != nullptr && glVertexAttribDivisor != nullptr;
  2351. dxtTextureSupport_ = true;
  2352. anisotropySupport_ = true;
  2353. sRGBSupport_ = true;
  2354. sRGBWriteSupport_ = true;
  2355. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &numSupportedRTs);
  2356. }
  2357. else
  2358. {
  2359. instancingSupport_ = GLEW_ARB_instanced_arrays != 0;
  2360. dxtTextureSupport_ = GLEW_EXT_texture_compression_s3tc != 0;
  2361. anisotropySupport_ = GLEW_EXT_texture_filter_anisotropic != 0;
  2362. sRGBSupport_ = GLEW_EXT_texture_sRGB != 0;
  2363. sRGBWriteSupport_ = GLEW_EXT_framebuffer_sRGB != 0;
  2364. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &numSupportedRTs);
  2365. }
  2366. // Must support 2 rendertargets for light pre-pass, and 4 for deferred
  2367. if (numSupportedRTs >= 2)
  2368. lightPrepassSupport_ = true;
  2369. if (numSupportedRTs >= 4)
  2370. deferredSupport_ = true;
  2371. #if defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
  2372. // On macOS check for an Intel driver and use shadow map RGBA dummy color textures, because mixing
  2373. // depth-only FBO rendering and backbuffer rendering will bug, resulting in a black screen in full
  2374. // screen mode, and incomplete shadow maps in windowed mode
  2375. String renderer((const char*)glGetString(GL_RENDERER));
  2376. if (renderer.Contains("Intel", false))
  2377. dummyColorFormat_ = GetRGBAFormat_OGL();
  2378. #endif
  2379. #else
  2380. // Check for supported compressed texture formats
  2381. #ifdef __EMSCRIPTEN__
  2382. dxtTextureSupport_ = CheckExtension("WEBGL_compressed_texture_s3tc"); // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
  2383. etcTextureSupport_ = CheckExtension("WEBGL_compressed_texture_etc1"); // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_etc1/
  2384. pvrtcTextureSupport_ = CheckExtension("WEBGL_compressed_texture_pvrtc"); // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  2385. etc2TextureSupport_ = gl3Support || CheckExtension("WEBGL_compressed_texture_etc"); // https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_etc/
  2386. // Instancing is in core in WebGL 2, so the extension may not be present anymore. In WebGL 1, find https://www.khronos.org/registry/webgl/extensions/ANGLE_instanced_arrays/
  2387. // TODO: In the distant future, this may break if WebGL 3 is introduced, so either improve the GL_VERSION parsing here, or keep track of which WebGL version we attempted to initialize.
  2388. instancingSupport_ = (strstr((const char *)glGetString(GL_VERSION), "WebGL 2.") != 0) || CheckExtension("ANGLE_instanced_arrays");
  2389. #else
  2390. dxtTextureSupport_ = CheckExtension("EXT_texture_compression_dxt1");
  2391. etcTextureSupport_ = CheckExtension("OES_compressed_ETC1_RGB8_texture");
  2392. etc2TextureSupport_ = gl3Support || CheckExtension("OES_compressed_ETC2_RGBA8_texture");
  2393. pvrtcTextureSupport_ = CheckExtension("IMG_texture_compression_pvrtc");
  2394. #endif
  2395. // Check for best supported depth renderbuffer format for GLES2
  2396. if (CheckExtension("GL_OES_depth24"))
  2397. glesDepthStencilFormat = GL_DEPTH_COMPONENT24_OES;
  2398. if (CheckExtension("GL_OES_packed_depth_stencil"))
  2399. glesDepthStencilFormat = GL_DEPTH24_STENCIL8_OES;
  2400. #ifdef __EMSCRIPTEN__
  2401. if (!CheckExtension("WEBGL_depth_texture"))
  2402. #else
  2403. if (!CheckExtension("GL_OES_depth_texture"))
  2404. #endif
  2405. {
  2406. shadowMapFormat_ = 0;
  2407. hiresShadowMapFormat_ = 0;
  2408. glesReadableDepthFormat = 0;
  2409. }
  2410. else
  2411. {
  2412. #if defined(IOS) || defined(TVOS)
  2413. // iOS hack: depth renderbuffer seems to fail, so use depth textures for everything if supported
  2414. glesDepthStencilFormat = GL_DEPTH_COMPONENT;
  2415. #endif
  2416. shadowMapFormat_ = GL_DEPTH_COMPONENT;
  2417. hiresShadowMapFormat_ = 0;
  2418. // WebGL shadow map rendering seems to be extremely slow without an attached dummy color texture
  2419. #ifdef __EMSCRIPTEN__
  2420. dummyColorFormat_ = GetRGBAFormat_OGL();
  2421. #endif
  2422. }
  2423. #endif
  2424. // Consider OpenGL shadows always hardware sampled, if supported at all
  2425. hardwareShadowSupport_ = shadowMapFormat_ != 0;
  2426. }
  2427. void Graphics::PrepareDraw_OGL()
  2428. {
  2429. GraphicsImpl_OGL* impl = GetImpl_OGL();
  2430. #ifndef GL_ES_VERSION_2_0
  2431. if (gl3Support)
  2432. {
  2433. for (PODVector<ConstantBuffer*>::Iterator i = impl->dirtyConstantBuffers_.Begin(); i != impl->dirtyConstantBuffers_.End(); ++i)
  2434. (*i)->Apply();
  2435. impl->dirtyConstantBuffers_.Clear();
  2436. }
  2437. #endif
  2438. if (impl->fboDirty_)
  2439. {
  2440. impl->fboDirty_ = false;
  2441. // First check if no framebuffer is needed. In that case simply return to backbuffer rendering
  2442. bool noFbo = !depthStencil_;
  2443. if (noFbo)
  2444. {
  2445. for (auto& renderTarget : renderTargets_)
  2446. {
  2447. if (renderTarget)
  2448. {
  2449. noFbo = false;
  2450. break;
  2451. }
  2452. }
  2453. }
  2454. if (noFbo)
  2455. {
  2456. if (impl->boundFBO_ != impl->systemFBO_)
  2457. {
  2458. BindFramebuffer_OGL(impl->systemFBO_);
  2459. impl->boundFBO_ = impl->systemFBO_;
  2460. }
  2461. #ifndef GL_ES_VERSION_2_0
  2462. // Disable/enable sRGB write
  2463. if (sRGBWriteSupport_)
  2464. {
  2465. bool sRGBWrite = sRGB_;
  2466. if (sRGBWrite != impl->sRGBWrite_)
  2467. {
  2468. if (sRGBWrite)
  2469. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2470. else
  2471. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2472. impl->sRGBWrite_ = sRGBWrite;
  2473. }
  2474. }
  2475. #endif
  2476. return;
  2477. }
  2478. // Search for a new framebuffer based on format & size, or create new
  2479. IntVector2 rtSize = Graphics::GetRenderTargetDimensions_OGL();
  2480. unsigned format = 0;
  2481. if (renderTargets_[0])
  2482. format = renderTargets_[0]->GetParentTexture()->GetFormat();
  2483. else if (depthStencil_)
  2484. format = depthStencil_->GetParentTexture()->GetFormat();
  2485. auto fboKey = (unsigned long long)format << 32u | rtSize.x_ << 16u | rtSize.y_;
  2486. HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl->frameBuffers_.Find(fboKey);
  2487. if (i == impl->frameBuffers_.End())
  2488. {
  2489. FrameBufferObject newFbo;
  2490. newFbo.fbo_ = CreateFramebuffer_OGL();
  2491. i = impl->frameBuffers_.Insert(MakePair(fboKey, newFbo));
  2492. }
  2493. if (impl->boundFBO_ != i->second_.fbo_)
  2494. {
  2495. BindFramebuffer_OGL(i->second_.fbo_);
  2496. impl->boundFBO_ = i->second_.fbo_;
  2497. }
  2498. #ifndef GL_ES_VERSION_2_0
  2499. // Setup readbuffers & drawbuffers if needed
  2500. if (i->second_.readBuffers_ != GL_NONE)
  2501. {
  2502. glReadBuffer(GL_NONE);
  2503. i->second_.readBuffers_ = GL_NONE;
  2504. }
  2505. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  2506. unsigned newDrawBuffers = 0;
  2507. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  2508. {
  2509. if (renderTargets_[j])
  2510. newDrawBuffers |= 1u << j;
  2511. }
  2512. if (newDrawBuffers != i->second_.drawBuffers_)
  2513. {
  2514. // Check for no color rendertargets (depth rendering only)
  2515. if (!newDrawBuffers)
  2516. glDrawBuffer(GL_NONE);
  2517. else
  2518. {
  2519. int drawBufferIds[MAX_RENDERTARGETS];
  2520. unsigned drawBufferCount = 0;
  2521. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  2522. {
  2523. if (renderTargets_[j])
  2524. {
  2525. if (!gl3Support)
  2526. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + j;
  2527. else
  2528. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0 + j;
  2529. }
  2530. }
  2531. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  2532. }
  2533. i->second_.drawBuffers_ = newDrawBuffers;
  2534. }
  2535. #endif
  2536. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  2537. {
  2538. if (renderTargets_[j])
  2539. {
  2540. Texture* texture = renderTargets_[j]->GetParentTexture();
  2541. // Bind either a renderbuffer or texture, depending on what is available
  2542. unsigned renderBufferID = renderTargets_[j]->GetRenderBuffer();
  2543. if (!renderBufferID)
  2544. {
  2545. // If texture's parameters are dirty, update before attaching
  2546. if (texture->GetParametersDirty())
  2547. {
  2548. SetTextureForUpdate_OGL(texture);
  2549. texture->UpdateParameters();
  2550. SetTexture_OGL(0, nullptr);
  2551. }
  2552. if (i->second_.colorAttachments_[j] != renderTargets_[j])
  2553. {
  2554. BindColorAttachment_OGL(j, renderTargets_[j]->GetTarget(), texture->GetGPUObjectName(), false);
  2555. i->second_.colorAttachments_[j] = renderTargets_[j];
  2556. }
  2557. }
  2558. else
  2559. {
  2560. if (i->second_.colorAttachments_[j] != renderTargets_[j])
  2561. {
  2562. BindColorAttachment_OGL(j, renderTargets_[j]->GetTarget(), renderBufferID, true);
  2563. i->second_.colorAttachments_[j] = renderTargets_[j];
  2564. }
  2565. }
  2566. }
  2567. else
  2568. {
  2569. if (i->second_.colorAttachments_[j])
  2570. {
  2571. BindColorAttachment_OGL(j, GL_TEXTURE_2D, 0, false);
  2572. i->second_.colorAttachments_[j] = nullptr;
  2573. }
  2574. }
  2575. }
  2576. if (depthStencil_)
  2577. {
  2578. // Bind either a renderbuffer or a depth texture, depending on what is available
  2579. Texture* texture = depthStencil_->GetParentTexture();
  2580. #ifndef GL_ES_VERSION_2_0
  2581. bool hasStencil = texture->GetFormat() == GL_DEPTH24_STENCIL8_EXT;
  2582. #else
  2583. bool hasStencil = texture->GetFormat() == GL_DEPTH24_STENCIL8_OES;
  2584. #endif
  2585. unsigned renderBufferID = depthStencil_->GetRenderBuffer();
  2586. if (!renderBufferID)
  2587. {
  2588. // If texture's parameters are dirty, update before attaching
  2589. if (texture->GetParametersDirty())
  2590. {
  2591. SetTextureForUpdate_OGL(texture);
  2592. texture->UpdateParameters();
  2593. SetTexture_OGL(0, nullptr);
  2594. }
  2595. if (i->second_.depthAttachment_ != depthStencil_)
  2596. {
  2597. BindDepthAttachment_OGL(texture->GetGPUObjectName(), false);
  2598. BindStencilAttachment_OGL(hasStencil ? texture->GetGPUObjectName() : 0, false);
  2599. i->second_.depthAttachment_ = depthStencil_;
  2600. }
  2601. }
  2602. else
  2603. {
  2604. if (i->second_.depthAttachment_ != depthStencil_)
  2605. {
  2606. BindDepthAttachment_OGL(renderBufferID, true);
  2607. BindStencilAttachment_OGL(hasStencil ? renderBufferID : 0, true);
  2608. i->second_.depthAttachment_ = depthStencil_;
  2609. }
  2610. }
  2611. }
  2612. else
  2613. {
  2614. if (i->second_.depthAttachment_)
  2615. {
  2616. BindDepthAttachment_OGL(0, false);
  2617. BindStencilAttachment_OGL(0, false);
  2618. i->second_.depthAttachment_ = nullptr;
  2619. }
  2620. }
  2621. #ifndef GL_ES_VERSION_2_0
  2622. // Disable/enable sRGB write
  2623. if (sRGBWriteSupport_)
  2624. {
  2625. bool sRGBWrite = renderTargets_[0] ? renderTargets_[0]->GetParentTexture()->GetSRGB() : sRGB_;
  2626. if (sRGBWrite != impl->sRGBWrite_)
  2627. {
  2628. if (sRGBWrite)
  2629. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2630. else
  2631. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2632. impl->sRGBWrite_ = sRGBWrite;
  2633. }
  2634. }
  2635. #endif
  2636. }
  2637. if (impl->vertexBuffersDirty_)
  2638. {
  2639. // Go through currently bound vertex buffers and set the attribute pointers that are available & required
  2640. // Use reverse order so that elements from higher index buffers will override lower index buffers
  2641. unsigned assignedLocations = 0;
  2642. for (unsigned i = MAX_VERTEX_STREAMS - 1; i < MAX_VERTEX_STREAMS; --i)
  2643. {
  2644. VertexBuffer* buffer = vertexBuffers_[i];
  2645. // Beware buffers with missing OpenGL objects, as binding a zero buffer object means accessing CPU memory for vertex data,
  2646. // in which case the pointer will be invalid and cause a crash
  2647. if (!buffer || !buffer->GetGPUObjectName() || !impl->vertexAttributes_)
  2648. continue;
  2649. const PODVector<VertexElement>& elements = buffer->GetElements();
  2650. for (PODVector<VertexElement>::ConstIterator j = elements.Begin(); j != elements.End(); ++j)
  2651. {
  2652. const VertexElement& element = *j;
  2653. HashMap<Pair<unsigned char, unsigned char>, unsigned>::ConstIterator k =
  2654. impl->vertexAttributes_->Find(MakePair((unsigned char)element.semantic_, element.index_));
  2655. if (k != impl->vertexAttributes_->End())
  2656. {
  2657. unsigned location = k->second_;
  2658. unsigned locationMask = 1u << location;
  2659. if (assignedLocations & locationMask)
  2660. continue; // Already assigned by higher index vertex buffer
  2661. assignedLocations |= locationMask;
  2662. // Enable attribute if not enabled yet
  2663. if (!(impl->enabledVertexAttributes_ & locationMask))
  2664. {
  2665. glEnableVertexAttribArray(location);
  2666. impl->enabledVertexAttributes_ |= locationMask;
  2667. }
  2668. // Enable/disable instancing divisor as necessary
  2669. unsigned dataStart = element.offset_;
  2670. if (element.perInstance_)
  2671. {
  2672. dataStart += impl->lastInstanceOffset_ * buffer->GetVertexSize();
  2673. if (!(impl->instancingVertexAttributes_ & locationMask))
  2674. {
  2675. SetVertexAttribDivisor_OGL(location, 1);
  2676. impl->instancingVertexAttributes_ |= locationMask;
  2677. }
  2678. }
  2679. else
  2680. {
  2681. if (impl->instancingVertexAttributes_ & locationMask)
  2682. {
  2683. SetVertexAttribDivisor_OGL(location, 0);
  2684. impl->instancingVertexAttributes_ &= ~locationMask;
  2685. }
  2686. }
  2687. SetVBO_OGL(buffer->GetGPUObjectName());
  2688. glVertexAttribPointer(location, glElementComponents[element.type_], glElementTypes[element.type_],
  2689. element.type_ == TYPE_UBYTE4_NORM ? GL_TRUE : GL_FALSE, (unsigned)buffer->GetVertexSize(),
  2690. (const void *)(size_t)dataStart);
  2691. }
  2692. }
  2693. }
  2694. // Finally disable unnecessary vertex attributes
  2695. unsigned disableVertexAttributes = impl->enabledVertexAttributes_ & (~impl->usedVertexAttributes_);
  2696. unsigned location = 0;
  2697. while (disableVertexAttributes)
  2698. {
  2699. if (disableVertexAttributes & 1u)
  2700. {
  2701. glDisableVertexAttribArray(location);
  2702. impl->enabledVertexAttributes_ &= ~(1u << location);
  2703. }
  2704. ++location;
  2705. disableVertexAttributes >>= 1;
  2706. }
  2707. impl->vertexBuffersDirty_ = false;
  2708. }
  2709. }
  2710. void Graphics::CleanupFramebuffers_OGL()
  2711. {
  2712. GraphicsImpl_OGL* impl = GetImpl_OGL();
  2713. if (!IsDeviceLost_OGL())
  2714. {
  2715. BindFramebuffer_OGL(impl->systemFBO_);
  2716. impl->boundFBO_ = impl->systemFBO_;
  2717. impl->fboDirty_ = true;
  2718. for (HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl->frameBuffers_.Begin();
  2719. i != impl->frameBuffers_.End(); ++i)
  2720. DeleteFramebuffer_OGL(i->second_.fbo_);
  2721. if (impl->resolveSrcFBO_)
  2722. DeleteFramebuffer_OGL(impl->resolveSrcFBO_);
  2723. if (impl->resolveDestFBO_)
  2724. DeleteFramebuffer_OGL(impl->resolveDestFBO_);
  2725. }
  2726. else
  2727. impl->boundFBO_ = 0;
  2728. impl->resolveSrcFBO_ = 0;
  2729. impl->resolveDestFBO_ = 0;
  2730. impl->frameBuffers_.Clear();
  2731. }
  2732. void Graphics::ResetCachedState_OGL()
  2733. {
  2734. for (auto& vertexBuffer : vertexBuffers_)
  2735. vertexBuffer = nullptr;
  2736. GraphicsImpl_OGL* impl = GetImpl_OGL();
  2737. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  2738. {
  2739. textures_[i] = nullptr;
  2740. impl->textureTypes_[i] = 0;
  2741. }
  2742. for (auto& renderTarget : renderTargets_)
  2743. renderTarget = nullptr;
  2744. depthStencil_ = nullptr;
  2745. viewport_ = IntRect(0, 0, 0, 0);
  2746. indexBuffer_ = nullptr;
  2747. vertexShader_ = nullptr;
  2748. pixelShader_ = nullptr;
  2749. blendMode_ = BLEND_REPLACE;
  2750. alphaToCoverage_ = false;
  2751. colorWrite_ = true;
  2752. cullMode_ = CULL_NONE;
  2753. constantDepthBias_ = 0.0f;
  2754. slopeScaledDepthBias_ = 0.0f;
  2755. depthTestMode_ = CMP_ALWAYS;
  2756. depthWrite_ = false;
  2757. lineAntiAlias_ = false;
  2758. fillMode_ = FILL_SOLID;
  2759. scissorTest_ = false;
  2760. scissorRect_ = IntRect::ZERO;
  2761. stencilTest_ = false;
  2762. stencilTestMode_ = CMP_ALWAYS;
  2763. stencilPass_ = OP_KEEP;
  2764. stencilFail_ = OP_KEEP;
  2765. stencilZFail_ = OP_KEEP;
  2766. stencilRef_ = 0;
  2767. stencilCompareMask_ = M_MAX_UNSIGNED;
  2768. stencilWriteMask_ = M_MAX_UNSIGNED;
  2769. useClipPlane_ = false;
  2770. impl->shaderProgram_ = nullptr;
  2771. impl->lastInstanceOffset_ = 0;
  2772. impl->activeTexture_ = 0;
  2773. impl->enabledVertexAttributes_ = 0;
  2774. impl->usedVertexAttributes_ = 0;
  2775. impl->instancingVertexAttributes_ = 0;
  2776. impl->boundFBO_ = impl->systemFBO_;
  2777. impl->boundVBO_ = 0;
  2778. impl->boundUBO_ = 0;
  2779. impl->sRGBWrite_ = false;
  2780. // Set initial state to match Direct3D
  2781. if (impl->context_)
  2782. {
  2783. glEnable(GL_DEPTH_TEST);
  2784. SetCullMode_OGL(CULL_CCW);
  2785. SetDepthTest_OGL(CMP_LESSEQUAL);
  2786. SetDepthWrite_OGL(true);
  2787. }
  2788. for (auto& constantBuffer : impl->constantBuffers_)
  2789. constantBuffer = nullptr;
  2790. impl->dirtyConstantBuffers_.Clear();
  2791. }
  2792. void Graphics::SetTextureUnitMappings_OGL()
  2793. {
  2794. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2795. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2796. textureUnits_["AlbedoBuffer"] = TU_ALBEDOBUFFER;
  2797. textureUnits_["NormalMap"] = TU_NORMAL;
  2798. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  2799. textureUnits_["SpecMap"] = TU_SPECULAR;
  2800. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2801. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  2802. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  2803. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2804. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  2805. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  2806. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2807. #ifndef GL_ES_VERSION_2_0
  2808. textureUnits_["VolumeMap"] = TU_VOLUMEMAP;
  2809. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  2810. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  2811. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  2812. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  2813. textureUnits_["ZoneCubeMap"] = TU_ZONE;
  2814. textureUnits_["ZoneVolumeMap"] = TU_ZONE;
  2815. #endif
  2816. }
  2817. unsigned Graphics::CreateFramebuffer_OGL()
  2818. {
  2819. unsigned newFbo = 0;
  2820. #ifndef GL_ES_VERSION_2_0
  2821. if (!gl3Support)
  2822. glGenFramebuffersEXT(1, &newFbo);
  2823. else
  2824. #endif
  2825. glGenFramebuffers(1, &newFbo);
  2826. return newFbo;
  2827. }
  2828. void Graphics::DeleteFramebuffer_OGL(unsigned fbo)
  2829. {
  2830. #ifndef GL_ES_VERSION_2_0
  2831. if (!gl3Support)
  2832. glDeleteFramebuffersEXT(1, &fbo);
  2833. else
  2834. #endif
  2835. glDeleteFramebuffers(1, &fbo);
  2836. }
  2837. void Graphics::BindFramebuffer_OGL(unsigned fbo)
  2838. {
  2839. #ifndef GL_ES_VERSION_2_0
  2840. if (!gl3Support)
  2841. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
  2842. else
  2843. #endif
  2844. glBindFramebuffer(GL_FRAMEBUFFER, fbo);
  2845. }
  2846. void Graphics::BindColorAttachment_OGL(unsigned index, unsigned target, unsigned object, bool isRenderBuffer)
  2847. {
  2848. if (!object)
  2849. isRenderBuffer = false;
  2850. #ifndef GL_ES_VERSION_2_0
  2851. if (!gl3Support)
  2852. {
  2853. if (!isRenderBuffer)
  2854. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, target, object, 0);
  2855. else
  2856. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + index, GL_RENDERBUFFER_EXT, object);
  2857. }
  2858. else
  2859. #endif
  2860. {
  2861. if (!isRenderBuffer)
  2862. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + index, target, object, 0);
  2863. else
  2864. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + index, GL_RENDERBUFFER, object);
  2865. }
  2866. }
  2867. void Graphics::BindDepthAttachment_OGL(unsigned object, bool isRenderBuffer)
  2868. {
  2869. if (!object)
  2870. isRenderBuffer = false;
  2871. #ifndef GL_ES_VERSION_2_0
  2872. if (!gl3Support)
  2873. {
  2874. if (!isRenderBuffer)
  2875. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, object, 0);
  2876. else
  2877. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, object);
  2878. }
  2879. else
  2880. #endif
  2881. {
  2882. if (!isRenderBuffer)
  2883. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, object, 0);
  2884. else
  2885. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, object);
  2886. }
  2887. }
  2888. void Graphics::BindStencilAttachment_OGL(unsigned object, bool isRenderBuffer)
  2889. {
  2890. if (!object)
  2891. isRenderBuffer = false;
  2892. #ifndef GL_ES_VERSION_2_0
  2893. if (!gl3Support)
  2894. {
  2895. if (!isRenderBuffer)
  2896. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, object, 0);
  2897. else
  2898. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, object);
  2899. }
  2900. else
  2901. #endif
  2902. {
  2903. if (!isRenderBuffer)
  2904. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, object, 0);
  2905. else
  2906. glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, object);
  2907. }
  2908. }
  2909. bool Graphics::CheckFramebuffer_OGL()
  2910. {
  2911. #ifndef GL_ES_VERSION_2_0
  2912. if (!gl3Support)
  2913. return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) == GL_FRAMEBUFFER_COMPLETE_EXT;
  2914. else
  2915. #endif
  2916. return glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
  2917. }
  2918. void Graphics::SetVertexAttribDivisor_OGL(unsigned location, unsigned divisor)
  2919. {
  2920. #ifndef GL_ES_VERSION_2_0
  2921. if (gl3Support && instancingSupport_)
  2922. glVertexAttribDivisor(location, divisor);
  2923. else if (instancingSupport_)
  2924. glVertexAttribDivisorARB(location, divisor);
  2925. #else
  2926. #ifdef __EMSCRIPTEN__
  2927. if (instancingSupport_)
  2928. glVertexAttribDivisorANGLE(location, divisor);
  2929. #endif
  2930. #endif
  2931. }
  2932. }