OGLGraphics.cpp 85 KB

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