OGLGraphics.cpp 98 KB

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