OGLGraphics.cpp 106 KB

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