OGLGraphics.cpp 98 KB

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