OGLGraphics.cpp 105 KB

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