OGLGraphics.cpp 97 KB

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