OGLGraphics.cpp 97 KB

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