OGLGraphics.cpp 97 KB

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