OGLGraphics.cpp 107 KB

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