OGLGraphics.cpp 104 KB

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