OGLGraphics.cpp 105 KB

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