OGLGraphics.cpp 99 KB

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