OGLGraphics.cpp 103 KB

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