OGLGraphics.cpp 105 KB

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