OGLGraphics.cpp 96 KB

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