OGLGraphics.cpp 102 KB

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