OGLGraphics.cpp 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889
  1. //
  2. // Copyright (c) 2008-2013 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 (texture == viewTexture_ || (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::SetViewTexture(Texture* texture)
  1344. {
  1345. viewTexture_ = texture;
  1346. if (viewTexture_)
  1347. {
  1348. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  1349. {
  1350. if (textures_[i] == viewTexture_)
  1351. SetTexture(i, textures_[i]->GetBackupTexture());
  1352. }
  1353. }
  1354. }
  1355. void Graphics::SetViewport(const IntRect& rect)
  1356. {
  1357. if (impl_->fboDirty_)
  1358. CommitFramebuffer();
  1359. IntVector2 rtSize = GetRenderTargetDimensions();
  1360. IntRect rectCopy = rect;
  1361. if (rectCopy.right_ <= rectCopy.left_)
  1362. rectCopy.right_ = rectCopy.left_ + 1;
  1363. if (rectCopy.bottom_ <= rectCopy.top_)
  1364. rectCopy.bottom_ = rectCopy.top_ + 1;
  1365. rectCopy.left_ = Clamp(rectCopy.left_, 0, rtSize.x_);
  1366. rectCopy.top_ = Clamp(rectCopy.top_, 0, rtSize.y_);
  1367. rectCopy.right_ = Clamp(rectCopy.right_, 0, rtSize.x_);
  1368. rectCopy.bottom_ = Clamp(rectCopy.bottom_, 0, rtSize.y_);
  1369. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1370. glViewport(rectCopy.left_, rtSize.y_ - rectCopy.bottom_, rectCopy.Width(), rectCopy.Height());
  1371. viewport_ = rectCopy;
  1372. // Disable scissor test, needs to be re-enabled by the user
  1373. SetScissorTest(false);
  1374. }
  1375. void Graphics::SetBlendMode(BlendMode mode)
  1376. {
  1377. if (mode != blendMode_)
  1378. {
  1379. if (mode == BLEND_REPLACE)
  1380. glDisable(GL_BLEND);
  1381. else
  1382. {
  1383. glEnable(GL_BLEND);
  1384. glBlendFunc(glSrcBlend[mode], glDestBlend[mode]);
  1385. }
  1386. blendMode_ = mode;
  1387. }
  1388. }
  1389. void Graphics::SetColorWrite(bool enable)
  1390. {
  1391. if (enable != colorWrite_)
  1392. {
  1393. if (enable)
  1394. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1395. else
  1396. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  1397. colorWrite_ = enable;
  1398. }
  1399. }
  1400. void Graphics::SetCullMode(CullMode mode)
  1401. {
  1402. if (mode != cullMode_)
  1403. {
  1404. if (mode == CULL_NONE)
  1405. glDisable(GL_CULL_FACE);
  1406. else
  1407. {
  1408. // Use Direct3D convention, ie. clockwise vertices define a front face
  1409. glEnable(GL_CULL_FACE);
  1410. glCullFace(mode == CULL_CCW ? GL_FRONT : GL_BACK);
  1411. }
  1412. cullMode_ = mode;
  1413. }
  1414. }
  1415. void Graphics::SetDepthBias(float constantBias, float slopeScaledBias)
  1416. {
  1417. if (constantBias != constantDepthBias_ || slopeScaledBias != slopeScaledDepthBias_)
  1418. {
  1419. #ifndef GL_ES_VERSION_2_0
  1420. if (slopeScaledBias != 0.0f)
  1421. {
  1422. // OpenGL constant bias is unreliable and dependant on depth buffer bitdepth, apply in the projection matrix instead
  1423. float adjustedSlopeScaledBias = slopeScaledBias + 1.0f;
  1424. glEnable(GL_POLYGON_OFFSET_FILL);
  1425. glPolygonOffset(adjustedSlopeScaledBias, 0.0f);
  1426. }
  1427. else
  1428. glDisable(GL_POLYGON_OFFSET_FILL);
  1429. #endif
  1430. constantDepthBias_ = constantBias;
  1431. slopeScaledDepthBias_ = slopeScaledBias;
  1432. shaderParameterSources_[SP_CAMERA] = (const void*)M_MAX_UNSIGNED;
  1433. }
  1434. }
  1435. void Graphics::SetDepthTest(CompareMode mode)
  1436. {
  1437. if (mode != depthTestMode_)
  1438. {
  1439. glDepthFunc(glCmpFunc[mode]);
  1440. depthTestMode_ = mode;
  1441. }
  1442. }
  1443. void Graphics::SetDepthWrite(bool enable)
  1444. {
  1445. if (enable != depthWrite_)
  1446. {
  1447. glDepthMask(enable ? GL_TRUE : GL_FALSE);
  1448. depthWrite_ = enable;
  1449. }
  1450. }
  1451. void Graphics::SetFillMode(FillMode mode)
  1452. {
  1453. #ifndef GL_ES_VERSION_2_0
  1454. if (mode != fillMode_)
  1455. {
  1456. glPolygonMode(GL_FRONT_AND_BACK, glFillMode[mode]);
  1457. fillMode_ = mode;
  1458. }
  1459. #endif
  1460. }
  1461. void Graphics::SetScissorTest(bool enable, const Rect& rect, bool borderInclusive)
  1462. {
  1463. // During some light rendering loops, a full rect is toggled on/off repeatedly.
  1464. // Disable scissor in that case to reduce state changes
  1465. if (rect.min_.x_ <= 0.0f && rect.min_.y_ <= 0.0f && rect.max_.x_ >= 1.0f && rect.max_.y_ >= 1.0f)
  1466. enable = false;
  1467. if (enable)
  1468. {
  1469. IntVector2 rtSize(GetRenderTargetDimensions());
  1470. IntVector2 viewSize(viewport_.Size());
  1471. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1472. IntRect intRect;
  1473. int expand = borderInclusive ? 1 : 0;
  1474. intRect.left_ = Clamp((int)((rect.min_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_, 0, rtSize.x_ - 1);
  1475. intRect.top_ = Clamp((int)((-rect.max_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_, 0, rtSize.y_ - 1);
  1476. intRect.right_ = Clamp((int)((rect.max_.x_ + 1.0f) * 0.5f * viewSize.x_) + viewPos.x_ + expand, 0, rtSize.x_);
  1477. intRect.bottom_ = Clamp((int)((-rect.min_.y_ + 1.0f) * 0.5f * viewSize.y_) + viewPos.y_ + expand, 0, rtSize.y_);
  1478. if (intRect.right_ == intRect.left_)
  1479. intRect.right_++;
  1480. if (intRect.bottom_ == intRect.top_)
  1481. intRect.bottom_++;
  1482. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1483. enable = false;
  1484. if (enable && scissorRect_ != intRect)
  1485. {
  1486. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1487. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.Width(), intRect.Height());
  1488. scissorRect_ = intRect;
  1489. }
  1490. }
  1491. else
  1492. scissorRect_ = IntRect::ZERO;
  1493. if (enable != scissorTest_)
  1494. {
  1495. if (enable)
  1496. glEnable(GL_SCISSOR_TEST);
  1497. else
  1498. glDisable(GL_SCISSOR_TEST);
  1499. scissorTest_ = enable;
  1500. }
  1501. }
  1502. void Graphics::SetScissorTest(bool enable, const IntRect& rect)
  1503. {
  1504. IntVector2 rtSize(GetRenderTargetDimensions());
  1505. IntVector2 viewPos(viewport_.left_, viewport_.top_);
  1506. if (enable)
  1507. {
  1508. IntRect intRect;
  1509. intRect.left_ = Clamp(rect.left_ + viewPos.x_, 0, rtSize.x_ - 1);
  1510. intRect.top_ = Clamp(rect.top_ + viewPos.y_, 0, rtSize.y_ - 1);
  1511. intRect.right_ = Clamp(rect.right_ + viewPos.x_, 0, rtSize.x_);
  1512. intRect.bottom_ = Clamp(rect.bottom_ + viewPos.y_, 0, rtSize.y_);
  1513. if (intRect.right_ == intRect.left_)
  1514. intRect.right_++;
  1515. if (intRect.bottom_ == intRect.top_)
  1516. intRect.bottom_++;
  1517. if (intRect.right_ < intRect.left_ || intRect.bottom_ < intRect.top_)
  1518. enable = false;
  1519. if (enable && scissorRect_ != intRect)
  1520. {
  1521. // Use Direct3D convention with the vertical coordinates ie. 0 is top
  1522. glScissor(intRect.left_, rtSize.y_ - intRect.bottom_, intRect.Width(), intRect.Height());
  1523. scissorRect_ = intRect;
  1524. }
  1525. }
  1526. else
  1527. scissorRect_ = IntRect::ZERO;
  1528. if (enable != scissorTest_)
  1529. {
  1530. if (enable)
  1531. glEnable(GL_SCISSOR_TEST);
  1532. else
  1533. glDisable(GL_SCISSOR_TEST);
  1534. scissorTest_ = enable;
  1535. }
  1536. }
  1537. void Graphics::SetClipPlane(bool enable, const Plane& clipPlane, const Matrix3x4& view, const Matrix4& projection)
  1538. {
  1539. #ifndef GL_ES_VERSION_2_0
  1540. if (enable != useClipPlane_)
  1541. {
  1542. if (enable)
  1543. glEnable(GL_CLIP_PLANE0);
  1544. else
  1545. glDisable(GL_CLIP_PLANE0);
  1546. useClipPlane_ = enable;
  1547. }
  1548. if (enable)
  1549. {
  1550. Matrix4 viewProj = projection * view;
  1551. Vector4 planeVec = clipPlane.Transformed(viewProj).ToVector4();
  1552. GLdouble planeData[4];
  1553. planeData[0] = planeVec.x_;
  1554. planeData[1] = planeVec.y_;
  1555. planeData[2] = planeVec.z_;
  1556. planeData[3] = planeVec.w_;
  1557. glClipPlane(GL_CLIP_PLANE0, &planeData[0]);
  1558. }
  1559. #endif
  1560. }
  1561. void Graphics::SetStreamFrequency(unsigned index, unsigned frequency)
  1562. {
  1563. }
  1564. void Graphics::ResetStreamFrequencies()
  1565. {
  1566. }
  1567. void Graphics::SetStencilTest(bool enable, CompareMode mode, StencilOp pass, StencilOp fail, StencilOp zFail, unsigned stencilRef, unsigned compareMask, unsigned writeMask)
  1568. {
  1569. #ifndef GL_ES_VERSION_2_0
  1570. if (enable != stencilTest_)
  1571. {
  1572. if (enable)
  1573. glEnable(GL_STENCIL_TEST);
  1574. else
  1575. glDisable(GL_STENCIL_TEST);
  1576. stencilTest_ = enable;
  1577. }
  1578. if (enable)
  1579. {
  1580. if (mode != stencilTestMode_ || stencilRef != stencilRef_ || compareMask != stencilCompareMask_)
  1581. {
  1582. glStencilFunc(glCmpFunc[mode], stencilRef, compareMask);
  1583. stencilTestMode_ = mode;
  1584. stencilRef_ = stencilRef;
  1585. stencilCompareMask_ = compareMask;
  1586. }
  1587. if (writeMask != stencilWriteMask_)
  1588. {
  1589. glStencilMask(writeMask);
  1590. stencilWriteMask_ = writeMask;
  1591. }
  1592. if (pass != stencilPass_ || fail != stencilFail_ || zFail != stencilZFail_)
  1593. {
  1594. glStencilOp(glStencilOps[fail], glStencilOps[zFail], glStencilOps[pass]);
  1595. stencilPass_ = pass;
  1596. stencilFail_ = fail;
  1597. stencilZFail_ = zFail;
  1598. }
  1599. }
  1600. #endif
  1601. }
  1602. void Graphics::SetForceSM2(bool enable)
  1603. {
  1604. }
  1605. bool Graphics::IsInitialized() const
  1606. {
  1607. return impl_->window_ != 0;
  1608. }
  1609. bool Graphics::IsDeviceLost() const
  1610. {
  1611. // On iOS treat window minimization as device loss, as it is forbidden to access OpenGL when minimized
  1612. #ifdef IOS
  1613. if (impl_->window_ && (SDL_GetWindowFlags(impl_->window_) & SDL_WINDOW_MINIMIZED) != 0)
  1614. return true;
  1615. #endif
  1616. return impl_->context_ == 0;
  1617. }
  1618. IntVector2 Graphics::GetWindowPosition() const
  1619. {
  1620. IntVector2 ret(IntVector2::ZERO);
  1621. if (impl_->window_)
  1622. SDL_GetWindowPosition(impl_->window_, &ret.x_, &ret.y_);
  1623. return ret;
  1624. }
  1625. PODVector<IntVector2> Graphics::GetResolutions() const
  1626. {
  1627. PODVector<IntVector2> ret;
  1628. unsigned numModes = SDL_GetNumDisplayModes(0);
  1629. for (unsigned i = 0; i < numModes; ++i)
  1630. {
  1631. SDL_DisplayMode mode;
  1632. SDL_GetDisplayMode(0, i, &mode);
  1633. int width = mode.w;
  1634. int height = mode.h;
  1635. // Store mode if unique
  1636. bool unique = true;
  1637. for (unsigned j = 0; j < ret.Size(); ++j)
  1638. {
  1639. if (ret[j].x_ == width && ret[j].y_ == height)
  1640. {
  1641. unique = false;
  1642. break;
  1643. }
  1644. }
  1645. if (unique)
  1646. ret.Push(IntVector2(width, height));
  1647. }
  1648. return ret;
  1649. }
  1650. PODVector<int> Graphics::GetMultiSampleLevels() const
  1651. {
  1652. PODVector<int> ret;
  1653. // No multisampling always supported
  1654. ret.Push(1);
  1655. /// \todo Implement properly, if possible
  1656. return ret;
  1657. }
  1658. IntVector2 Graphics::GetDesktopResolution() const
  1659. {
  1660. #if !defined(ANDROID) && !defined(IOS)
  1661. SDL_DisplayMode mode;
  1662. SDL_GetDesktopDisplayMode(0, &mode);
  1663. return IntVector2(mode.w, mode.h);
  1664. #else
  1665. // SDL_GetDesktopDisplayMode() may not work correctly on mobile platforms. Rather return the window size
  1666. return IntVector2(width_, height_);
  1667. #endif
  1668. }
  1669. unsigned Graphics::GetFormat(CompressedFormat format) const
  1670. {
  1671. switch (format)
  1672. {
  1673. case CF_DXT1:
  1674. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT1_EXT : 0;
  1675. #ifndef GL_ES_VERSION_2_0
  1676. case CF_DXT3:
  1677. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT3_EXT : 0;
  1678. case CF_DXT5:
  1679. return dxtTextureSupport_ ? GL_COMPRESSED_RGBA_S3TC_DXT5_EXT : 0;
  1680. #else
  1681. case CF_ETC1:
  1682. return etcTextureSupport_ ? GL_ETC1_RGB8_OES : 0;
  1683. case CF_PVRTC_RGB_2BPP:
  1684. return pvrtcTextureSupport_ ? COMPRESSED_RGB_PVRTC_2BPPV1_IMG : 0;
  1685. case CF_PVRTC_RGB_4BPP:
  1686. return pvrtcTextureSupport_ ? COMPRESSED_RGB_PVRTC_4BPPV1_IMG : 0;
  1687. case CF_PVRTC_RGBA_2BPP:
  1688. return pvrtcTextureSupport_ ? COMPRESSED_RGBA_PVRTC_2BPPV1_IMG : 0;
  1689. case CF_PVRTC_RGBA_4BPP:
  1690. return pvrtcTextureSupport_ ? COMPRESSED_RGBA_PVRTC_4BPPV1_IMG : 0;
  1691. #endif
  1692. default:
  1693. return 0;
  1694. }
  1695. }
  1696. VertexBuffer* Graphics::GetVertexBuffer(unsigned index) const
  1697. {
  1698. return index < MAX_VERTEX_STREAMS ? vertexBuffers_[index] : 0;
  1699. }
  1700. TextureUnit Graphics::GetTextureUnit(const String& name)
  1701. {
  1702. HashMap<String, TextureUnit>::Iterator i = textureUnits_.Find(name);
  1703. if (i != textureUnits_.End())
  1704. return i->second_;
  1705. else
  1706. return MAX_TEXTURE_UNITS;
  1707. }
  1708. const String& Graphics::GetTextureUnitName(TextureUnit unit)
  1709. {
  1710. for (HashMap<String, TextureUnit>::Iterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  1711. {
  1712. if (i->second_ == unit)
  1713. return i->first_;
  1714. }
  1715. return String::EMPTY;
  1716. }
  1717. Texture* Graphics::GetTexture(unsigned index) const
  1718. {
  1719. return index < MAX_TEXTURE_UNITS ? textures_[index] : 0;
  1720. }
  1721. RenderSurface* Graphics::GetRenderTarget(unsigned index) const
  1722. {
  1723. return index < MAX_RENDERTARGETS ? renderTargets_[index] : 0;
  1724. }
  1725. IntVector2 Graphics::GetRenderTargetDimensions() const
  1726. {
  1727. int width, height;
  1728. if (renderTargets_[0])
  1729. {
  1730. width = renderTargets_[0]->GetWidth();
  1731. height = renderTargets_[0]->GetHeight();
  1732. }
  1733. else if (depthStencil_)
  1734. {
  1735. width = depthStencil_->GetWidth();
  1736. height = depthStencil_->GetHeight();
  1737. }
  1738. else
  1739. {
  1740. width = width_;
  1741. height = height_;
  1742. }
  1743. return IntVector2(width, height);
  1744. }
  1745. void Graphics::WindowResized()
  1746. {
  1747. if (!impl_->window_)
  1748. return;
  1749. int newWidth, newHeight;
  1750. SDL_GetWindowSize(impl_->window_, &newWidth, &newHeight);
  1751. if (newWidth == width_ && newHeight == height_)
  1752. return;
  1753. width_ = newWidth;
  1754. height_ = newHeight;
  1755. // Reset rendertargets and viewport for the new screen size
  1756. ResetRenderTargets();
  1757. LOGDEBUGF("Window was resized to %dx%d", width_, height_);
  1758. using namespace ScreenMode;
  1759. VariantMap& eventData = GetEventDataMap();
  1760. eventData[P_WIDTH] = width_;
  1761. eventData[P_HEIGHT] = height_;
  1762. eventData[P_FULLSCREEN] = fullscreen_;
  1763. eventData[P_RESIZABLE] = resizable_;
  1764. eventData[P_BORDERLESS] = borderless_;
  1765. SendEvent(E_SCREENMODE, eventData);
  1766. }
  1767. void Graphics::AddGPUObject(GPUObject* object)
  1768. {
  1769. gpuObjects_.Push(object);
  1770. }
  1771. void Graphics::RemoveGPUObject(GPUObject* object)
  1772. {
  1773. gpuObjects_.Remove(object);
  1774. }
  1775. void* Graphics::ReserveScratchBuffer(unsigned size)
  1776. {
  1777. if (!size)
  1778. return 0;
  1779. if (size > maxScratchBufferRequest_)
  1780. maxScratchBufferRequest_ = size;
  1781. // First check for a free buffer that is large enough
  1782. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1783. {
  1784. if (!i->reserved_ && i->size_ >= size)
  1785. {
  1786. i->reserved_ = true;
  1787. return i->data_.Get();
  1788. }
  1789. }
  1790. // Then check if a free buffer can be resized
  1791. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1792. {
  1793. if (!i->reserved_)
  1794. {
  1795. i->data_ = new unsigned char[size];
  1796. i->size_ = size;
  1797. i->reserved_ = true;
  1798. return i->data_.Get();
  1799. }
  1800. }
  1801. // Finally allocate a new buffer
  1802. ScratchBuffer newBuffer;
  1803. newBuffer.data_ = new unsigned char[size];
  1804. newBuffer.size_ = size;
  1805. newBuffer.reserved_ = true;
  1806. scratchBuffers_.Push(newBuffer);
  1807. return newBuffer.data_.Get();
  1808. }
  1809. void Graphics::FreeScratchBuffer(void* buffer)
  1810. {
  1811. if (!buffer)
  1812. return;
  1813. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1814. {
  1815. if (i->reserved_ && i->data_.Get() == buffer)
  1816. {
  1817. i->reserved_ = false;
  1818. return;
  1819. }
  1820. }
  1821. LOGWARNING("Reserved scratch buffer " + ToStringHex((unsigned)(size_t)buffer) + " not found");
  1822. }
  1823. void Graphics::CleanupScratchBuffers()
  1824. {
  1825. for (Vector<ScratchBuffer>::Iterator i = scratchBuffers_.Begin(); i != scratchBuffers_.End(); ++i)
  1826. {
  1827. if (!i->reserved_ && i->size_ > maxScratchBufferRequest_ * 2)
  1828. {
  1829. i->data_ = maxScratchBufferRequest_ > 0 ? new unsigned char[maxScratchBufferRequest_] : 0;
  1830. i->size_ = maxScratchBufferRequest_;
  1831. }
  1832. }
  1833. maxScratchBufferRequest_ = 0;
  1834. }
  1835. void Graphics::Release(bool clearGPUObjects, bool closeWindow)
  1836. {
  1837. if (!impl_->window_)
  1838. return;
  1839. releasingGPUObjects_ = true;
  1840. if (clearGPUObjects)
  1841. {
  1842. // Shutting down: release all GPU objects that still exist
  1843. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1844. (*i)->Release();
  1845. gpuObjects_.Clear();
  1846. }
  1847. else
  1848. {
  1849. // We are not shutting down, but recreating the context: mark GPU objects lost
  1850. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1851. (*i)->OnDeviceLost();
  1852. }
  1853. releasingGPUObjects_ = false;
  1854. CleanupFramebuffers(true);
  1855. depthTextures_.Clear();
  1856. shaderPrograms_.Clear();
  1857. // End fullscreen mode first to counteract transition and getting stuck problems on OS X
  1858. #if defined(__APPLE__) && !defined(IOS)
  1859. if (closeWindow && fullscreen_ && !externalWindow_)
  1860. SDL_SetWindowFullscreen(impl_->window_, SDL_FALSE);
  1861. #endif
  1862. if (impl_->context_)
  1863. {
  1864. // Do not log this message if we are exiting
  1865. if (!clearGPUObjects)
  1866. LOGINFO("OpenGL context lost");
  1867. SDL_GL_DeleteContext(impl_->context_);
  1868. impl_->context_ = 0;
  1869. }
  1870. if (closeWindow)
  1871. {
  1872. SDL_ShowCursor(SDL_TRUE);
  1873. // Do not destroy external window except when shutting down
  1874. if (!externalWindow_ || clearGPUObjects)
  1875. {
  1876. SDL_DestroyWindow(impl_->window_);
  1877. impl_->window_ = 0;
  1878. }
  1879. }
  1880. }
  1881. void Graphics::Restore()
  1882. {
  1883. if (!impl_->window_)
  1884. return;
  1885. #ifdef ANDROID
  1886. // On Android the context may be lost behind the scenes as the application is minimized
  1887. if (impl_->context_ && !SDL_GL_GetCurrentContext())
  1888. {
  1889. impl_->context_ = 0;
  1890. // Mark GPU objects lost without a current context. In this case they just mark their internal state lost
  1891. // but do not perform OpenGL commands to delete the GL objects
  1892. Release(false, false);
  1893. }
  1894. #endif
  1895. // Ensure first that the context exists
  1896. if (!impl_->context_)
  1897. {
  1898. impl_->context_ = SDL_GL_CreateContext(impl_->window_);
  1899. #ifdef IOS
  1900. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&impl_->systemFbo_);
  1901. #endif
  1902. ResetCachedState();
  1903. }
  1904. if (!impl_->context_)
  1905. return;
  1906. for (Vector<GPUObject*>::Iterator i = gpuObjects_.Begin(); i != gpuObjects_.End(); ++i)
  1907. (*i)->OnDeviceReset();
  1908. }
  1909. void Graphics::Maximize()
  1910. {
  1911. if (!impl_->window_)
  1912. return;
  1913. SDL_MaximizeWindow(impl_->window_);
  1914. }
  1915. void Graphics::Minimize()
  1916. {
  1917. if (!impl_->window_)
  1918. return;
  1919. SDL_MinimizeWindow(impl_->window_);
  1920. }
  1921. void Graphics::CleanupRenderSurface(RenderSurface* surface)
  1922. {
  1923. if (!surface)
  1924. return;
  1925. // Flush pending FBO changes first if any
  1926. CommitFramebuffer();
  1927. unsigned currentFbo = impl_->boundFbo_;
  1928. // Go through all FBOs and clean up the surface from them
  1929. for (HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin();
  1930. i != impl_->frameBuffers_.End(); ++i)
  1931. {
  1932. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  1933. {
  1934. if (i->second_.colorAttachments_[j] == surface)
  1935. {
  1936. if (currentFbo != i->second_.fbo_)
  1937. {
  1938. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1939. currentFbo = i->second_.fbo_;
  1940. }
  1941. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, GL_TEXTURE_2D, 0, 0);
  1942. i->second_.colorAttachments_[j] = 0;
  1943. // Mark drawbuffer bits to need recalculation
  1944. i->second_.drawBuffers_ = M_MAX_UNSIGNED;
  1945. }
  1946. }
  1947. if (i->second_.depthAttachment_ == surface)
  1948. {
  1949. if (currentFbo != i->second_.fbo_)
  1950. {
  1951. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  1952. currentFbo = i->second_.fbo_;
  1953. }
  1954. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1955. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  1956. i->second_.depthAttachment_ = 0;
  1957. }
  1958. }
  1959. // Restore previously bound FBO now if needed
  1960. if (currentFbo != impl_->boundFbo_)
  1961. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->boundFbo_);
  1962. }
  1963. void Graphics::MarkFBODirty()
  1964. {
  1965. impl_->fboDirty_ = true;
  1966. }
  1967. unsigned Graphics::GetAlphaFormat()
  1968. {
  1969. return GL_ALPHA;
  1970. }
  1971. unsigned Graphics::GetLuminanceFormat()
  1972. {
  1973. return GL_LUMINANCE;
  1974. }
  1975. unsigned Graphics::GetLuminanceAlphaFormat()
  1976. {
  1977. return GL_LUMINANCE_ALPHA;
  1978. }
  1979. unsigned Graphics::GetRGBFormat()
  1980. {
  1981. return GL_RGB;
  1982. }
  1983. unsigned Graphics::GetRGBAFormat()
  1984. {
  1985. return GL_RGBA;
  1986. }
  1987. unsigned Graphics::GetRGBA16Format()
  1988. {
  1989. #ifndef GL_ES_VERSION_2_0
  1990. return GL_RGBA16;
  1991. #else
  1992. return GL_RGBA;
  1993. #endif
  1994. }
  1995. unsigned Graphics::GetRGBAFloat16Format()
  1996. {
  1997. #ifndef GL_ES_VERSION_2_0
  1998. return GL_RGBA16F_ARB;
  1999. #else
  2000. return GL_RGBA;
  2001. #endif
  2002. }
  2003. unsigned Graphics::GetRGBAFloat32Format()
  2004. {
  2005. #ifndef GL_ES_VERSION_2_0
  2006. return GL_RGBA32F_ARB;
  2007. #else
  2008. return GL_RGBA;
  2009. #endif
  2010. }
  2011. unsigned Graphics::GetRG16Format()
  2012. {
  2013. #ifndef GL_ES_VERSION_2_0
  2014. return GL_RG16;
  2015. #else
  2016. return GL_RGBA;
  2017. #endif
  2018. }
  2019. unsigned Graphics::GetRGFloat16Format()
  2020. {
  2021. #ifndef GL_ES_VERSION_2_0
  2022. return GL_RG16F;
  2023. #else
  2024. return GL_RGBA;
  2025. #endif
  2026. }
  2027. unsigned Graphics::GetRGFloat32Format()
  2028. {
  2029. #ifndef GL_ES_VERSION_2_0
  2030. return GL_RG32F;
  2031. #else
  2032. return GL_RGBA;
  2033. #endif
  2034. }
  2035. unsigned Graphics::GetFloat16Format()
  2036. {
  2037. #ifndef GL_ES_VERSION_2_0
  2038. return GL_LUMINANCE16F_ARB;
  2039. #else
  2040. return GL_LUMINANCE;
  2041. #endif
  2042. }
  2043. unsigned Graphics::GetFloat32Format()
  2044. {
  2045. #ifndef GL_ES_VERSION_2_0
  2046. return GL_LUMINANCE32F_ARB;
  2047. #else
  2048. return GL_LUMINANCE;
  2049. #endif
  2050. }
  2051. unsigned Graphics::GetLinearDepthFormat()
  2052. {
  2053. // OpenGL FBO specs state that color attachments must have the same format; therefore must encode linear depth to RGBA
  2054. // manually if not using a readable hardware depth texture
  2055. return GL_RGBA;
  2056. }
  2057. unsigned Graphics::GetDepthStencilFormat()
  2058. {
  2059. #ifndef GL_ES_VERSION_2_0
  2060. return GL_DEPTH24_STENCIL8_EXT;
  2061. #else
  2062. return glesDepthStencilFormat;
  2063. #endif
  2064. }
  2065. unsigned Graphics::GetFormat(const String& formatName)
  2066. {
  2067. String nameLower = formatName.ToLower().Trimmed();
  2068. if (nameLower == "a")
  2069. return GetAlphaFormat();
  2070. if (nameLower == "l")
  2071. return GetLuminanceFormat();
  2072. if (nameLower == "la")
  2073. return GetLuminanceAlphaFormat();
  2074. if (nameLower == "rgb")
  2075. return GetRGBFormat();
  2076. if (nameLower == "rgba")
  2077. return GetRGBAFormat();
  2078. if (nameLower == "rgba16")
  2079. return GetRGBA16Format();
  2080. if (nameLower == "rgba16f")
  2081. return GetRGBAFloat16Format();
  2082. if (nameLower == "rgba32f")
  2083. return GetRGBAFloat32Format();
  2084. if (nameLower == "rg16")
  2085. return GetRG16Format();
  2086. if (nameLower == "rg16f")
  2087. return GetRGFloat16Format();
  2088. if (nameLower == "rg32f")
  2089. return GetRGFloat32Format();
  2090. if (nameLower == "r16f")
  2091. return GetFloat16Format();
  2092. if (nameLower == "r32f" || nameLower == "float")
  2093. return GetFloat32Format();
  2094. if (nameLower == "lineardepth" || nameLower == "depth")
  2095. return GetLinearDepthFormat();
  2096. if (nameLower == "d24s8")
  2097. return GetDepthStencilFormat();
  2098. return GetRGBFormat();
  2099. }
  2100. void Graphics::CreateWindowIcon()
  2101. {
  2102. if (windowIcon_)
  2103. {
  2104. SDL_Surface* surface = windowIcon_->GetSDLSurface();
  2105. if (surface)
  2106. {
  2107. SDL_SetWindowIcon(impl_->window_, surface);
  2108. SDL_FreeSurface(surface);
  2109. }
  2110. }
  2111. }
  2112. void Graphics::CheckFeatureSupport(String& extensions)
  2113. {
  2114. // Check supported features: light pre-pass, deferred rendering and hardware depth texture
  2115. lightPrepassSupport_ = false;
  2116. deferredSupport_ = false;
  2117. int numSupportedRTs = 1;
  2118. #ifndef GL_ES_VERSION_2_0
  2119. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &numSupportedRTs);
  2120. // If hardware depth is not supported, must support 2 rendertargets for light pre-pass, and 4 for deferred
  2121. if (numSupportedRTs >= 2)
  2122. lightPrepassSupport_ = true;
  2123. if (numSupportedRTs >= 4)
  2124. deferredSupport_ = true;
  2125. #else
  2126. // Check for best supported depth renderbuffer format for GLES2
  2127. if (CheckExtension(extensions, "GL_OES_depth24"))
  2128. glesDepthStencilFormat = GL_DEPTH_COMPONENT24_OES;
  2129. if (CheckExtension(extensions, "GL_OES_packed_depth_stencil"))
  2130. glesDepthStencilFormat = GL_DEPTH24_STENCIL8_OES;
  2131. if (!CheckExtension(extensions, "GL_OES_depth_texture"))
  2132. {
  2133. shadowMapFormat_ = 0;
  2134. hiresShadowMapFormat_ = 0;
  2135. }
  2136. else
  2137. {
  2138. #ifdef IOS
  2139. // iOS hack: depth renderbuffer seems to fail, so use depth textures for everything
  2140. // if supported
  2141. glesDepthStencilFormat = GL_DEPTH_COMPONENT;
  2142. #endif
  2143. shadowMapFormat_ = GL_DEPTH_COMPONENT;
  2144. hiresShadowMapFormat_ = 0;
  2145. }
  2146. #endif
  2147. }
  2148. void Graphics::CommitFramebuffer()
  2149. {
  2150. if (!impl_->fboDirty_)
  2151. return;
  2152. impl_->fboDirty_ = false;
  2153. // First check if no framebuffer is needed. In that case simply return to backbuffer rendering
  2154. bool noFbo = !depthStencil_;
  2155. if (noFbo)
  2156. {
  2157. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2158. {
  2159. if (renderTargets_[i])
  2160. {
  2161. noFbo = false;
  2162. break;
  2163. }
  2164. }
  2165. }
  2166. if (noFbo)
  2167. {
  2168. if (impl_->boundFbo_ != impl_->systemFbo_)
  2169. {
  2170. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, impl_->systemFbo_);
  2171. impl_->boundFbo_ = impl_->systemFbo_;
  2172. }
  2173. #ifndef GL_ES_VERSION_2_0
  2174. // Disable/enable sRGB write
  2175. if (sRGBWriteSupport_)
  2176. {
  2177. bool sRGBWrite = sRGB_;
  2178. if (sRGBWrite != impl_->sRGBWrite_)
  2179. {
  2180. if (sRGBWrite)
  2181. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2182. else
  2183. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2184. impl_->sRGBWrite_ = sRGBWrite;
  2185. }
  2186. }
  2187. #endif
  2188. return;
  2189. }
  2190. // Search for a new framebuffer based on format & size, or create new
  2191. IntVector2 rtSize = Graphics::GetRenderTargetDimensions();
  2192. unsigned format = 0;
  2193. if (renderTargets_[0])
  2194. format = renderTargets_[0]->GetParentTexture()->GetFormat();
  2195. else if (depthStencil_)
  2196. format = depthStencil_->GetParentTexture()->GetFormat();
  2197. unsigned long long fboKey = (rtSize.x_ << 16 | rtSize.y_) | (((unsigned long long)format) << 32);
  2198. HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Find(fboKey);
  2199. if (i == impl_->frameBuffers_.End())
  2200. {
  2201. FrameBufferObject newFbo;
  2202. glGenFramebuffersEXT(1, &newFbo.fbo_);
  2203. i = impl_->frameBuffers_.Insert(MakePair(fboKey, newFbo));
  2204. }
  2205. i->second_.useTimer_.Reset();
  2206. if (impl_->boundFbo_ != i->second_.fbo_)
  2207. {
  2208. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, i->second_.fbo_);
  2209. impl_->boundFbo_ = i->second_.fbo_;
  2210. }
  2211. #ifndef GL_ES_VERSION_2_0
  2212. // Setup readbuffers & drawbuffers if needed
  2213. if (i->second_.readBuffers_ != GL_NONE)
  2214. {
  2215. glReadBuffer(GL_NONE);
  2216. i->second_.readBuffers_ = GL_NONE;
  2217. }
  2218. // Calculate the bit combination of non-zero color rendertargets to first check if the combination changed
  2219. unsigned newDrawBuffers = 0;
  2220. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2221. {
  2222. if (renderTargets_[i])
  2223. newDrawBuffers |= 1 << i;
  2224. }
  2225. if (newDrawBuffers != i->second_.drawBuffers_)
  2226. {
  2227. // Check for no color rendertargets (depth rendering only)
  2228. if (!newDrawBuffers)
  2229. glDrawBuffer(GL_NONE);
  2230. else
  2231. {
  2232. int drawBufferIds[MAX_RENDERTARGETS];
  2233. unsigned drawBufferCount = 0;
  2234. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2235. {
  2236. if (renderTargets_[i])
  2237. drawBufferIds[drawBufferCount++] = GL_COLOR_ATTACHMENT0_EXT + i;
  2238. }
  2239. glDrawBuffers(drawBufferCount, (const GLenum*)drawBufferIds);
  2240. }
  2241. i->second_.drawBuffers_ = newDrawBuffers;
  2242. }
  2243. #endif
  2244. for (unsigned j = 0; j < MAX_RENDERTARGETS; ++j)
  2245. {
  2246. if (renderTargets_[j])
  2247. {
  2248. Texture* texture = renderTargets_[j]->GetParentTexture();
  2249. // If texture's parameters are dirty, update before attaching
  2250. if (texture->GetParametersDirty())
  2251. {
  2252. SetTextureForUpdate(texture);
  2253. texture->UpdateParameters();
  2254. SetTexture(0, 0);
  2255. }
  2256. if (i->second_.colorAttachments_[j] != renderTargets_[j])
  2257. {
  2258. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, renderTargets_[j]->GetTarget(),
  2259. texture->GetGPUObject(), 0);
  2260. i->second_.colorAttachments_[j] = renderTargets_[j];
  2261. }
  2262. }
  2263. else
  2264. {
  2265. if (i->second_.colorAttachments_[j])
  2266. {
  2267. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT + j, GL_TEXTURE_2D, 0, 0);
  2268. i->second_.colorAttachments_[j] = 0;
  2269. }
  2270. }
  2271. }
  2272. if (depthStencil_)
  2273. {
  2274. // Bind either a renderbuffer or a depth texture, depending on what is available
  2275. Texture* texture = depthStencil_->GetParentTexture();
  2276. #ifndef GL_ES_VERSION_2_0
  2277. bool hasStencil = texture->GetFormat() == GL_DEPTH24_STENCIL8_EXT;
  2278. #else
  2279. bool hasStencil = texture->GetFormat() == GL_DEPTH24_STENCIL8_OES;
  2280. #endif
  2281. unsigned renderBufferID = depthStencil_->GetRenderBuffer();
  2282. if (!renderBufferID)
  2283. {
  2284. // If texture's parameters are dirty, update before attaching
  2285. if (texture->GetParametersDirty())
  2286. {
  2287. SetTextureForUpdate(texture);
  2288. texture->UpdateParameters();
  2289. SetTexture(0, 0);
  2290. }
  2291. if (i->second_.depthAttachment_ != depthStencil_)
  2292. {
  2293. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, texture->GetGPUObject(), 0);
  2294. if (hasStencil)
  2295. {
  2296. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D,
  2297. texture->GetGPUObject(), 0);
  2298. }
  2299. else
  2300. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  2301. i->second_.depthAttachment_ = depthStencil_;
  2302. }
  2303. }
  2304. else
  2305. {
  2306. if (i->second_.depthAttachment_ != depthStencil_)
  2307. {
  2308. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, renderBufferID);
  2309. if (hasStencil)
  2310. {
  2311. glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT,
  2312. renderBufferID);
  2313. }
  2314. else
  2315. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  2316. i->second_.depthAttachment_ = depthStencil_;
  2317. }
  2318. }
  2319. }
  2320. else
  2321. {
  2322. if (i->second_.depthAttachment_)
  2323. {
  2324. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  2325. glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0);
  2326. i->second_.depthAttachment_ = 0;
  2327. }
  2328. }
  2329. #ifndef GL_ES_VERSION_2_0
  2330. // Disable/enable sRGB write
  2331. if (sRGBWriteSupport_)
  2332. {
  2333. bool sRGBWrite = renderTargets_[0] ? renderTargets_[0]->GetParentTexture()->GetSRGB() : sRGB_;
  2334. if (sRGBWrite != impl_->sRGBWrite_)
  2335. {
  2336. if (sRGBWrite)
  2337. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  2338. else
  2339. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  2340. impl_->sRGBWrite_ = sRGBWrite;
  2341. }
  2342. }
  2343. #endif
  2344. }
  2345. bool Graphics::CheckFramebuffer()
  2346. {
  2347. return glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) == GL_FRAMEBUFFER_COMPLETE_EXT;
  2348. }
  2349. void Graphics::CleanupFramebuffers(bool force)
  2350. {
  2351. if (!IsDeviceLost())
  2352. {
  2353. for (HashMap<unsigned long long, FrameBufferObject>::Iterator i = impl_->frameBuffers_.Begin();
  2354. i != impl_->frameBuffers_.End();)
  2355. {
  2356. if (i->second_.fbo_ != impl_->boundFbo_ && (force || i->second_.useTimer_.GetMSec(false) >
  2357. MAX_FRAMEBUFFER_AGE))
  2358. {
  2359. glDeleteFramebuffersEXT(1, &i->second_.fbo_);
  2360. i = impl_->frameBuffers_.Erase(i);
  2361. }
  2362. else
  2363. ++i;
  2364. }
  2365. }
  2366. else
  2367. {
  2368. impl_->boundFbo_ = 0;
  2369. impl_->frameBuffers_.Clear();
  2370. }
  2371. }
  2372. void Graphics::ResetCachedState()
  2373. {
  2374. for (unsigned i = 0; i < MAX_VERTEX_STREAMS; ++i)
  2375. {
  2376. vertexBuffers_[i] = 0;
  2377. elementMasks_[i] = 0;
  2378. }
  2379. for (unsigned i = 0; i < MAX_TEXTURE_UNITS; ++i)
  2380. {
  2381. textures_[i] = 0;
  2382. textureTypes_[i] = 0;
  2383. }
  2384. for (unsigned i = 0; i < MAX_RENDERTARGETS; ++i)
  2385. renderTargets_[i] = 0;
  2386. depthStencil_ = 0;
  2387. viewTexture_ = 0;
  2388. viewport_ = IntRect(0, 0, 0, 0);
  2389. indexBuffer_ = 0;
  2390. vertexShader_ = 0;
  2391. pixelShader_ = 0;
  2392. shaderProgram_ = 0;
  2393. blendMode_ = BLEND_REPLACE;
  2394. textureAnisotropy_ = 1;
  2395. colorWrite_ = true;
  2396. cullMode_ = CULL_NONE;
  2397. constantDepthBias_ = 0.0f;
  2398. slopeScaledDepthBias_ = 0.0f;
  2399. depthTestMode_ = CMP_ALWAYS;
  2400. depthWrite_ = false;
  2401. fillMode_ = FILL_SOLID;
  2402. scissorTest_ = false;
  2403. scissorRect_ = IntRect::ZERO;
  2404. stencilTest_ = false;
  2405. stencilTestMode_ = CMP_ALWAYS;
  2406. stencilPass_ = OP_KEEP;
  2407. stencilFail_ = OP_KEEP;
  2408. stencilZFail_ = OP_KEEP;
  2409. stencilRef_ = 0;
  2410. stencilCompareMask_ = M_MAX_UNSIGNED;
  2411. stencilWriteMask_ = M_MAX_UNSIGNED;
  2412. lastInstanceOffset_ = 0;
  2413. useClipPlane_ = false;
  2414. impl_->activeTexture_ = 0;
  2415. impl_->enabledAttributes_ = 0;
  2416. impl_->boundFbo_ = impl_->systemFbo_;
  2417. impl_->sRGBWrite_ = false;
  2418. // Set initial state to match Direct3D
  2419. if (impl_->context_)
  2420. {
  2421. glEnable(GL_DEPTH_TEST);
  2422. SetCullMode(CULL_CCW);
  2423. SetDepthTest(CMP_LESSEQUAL);
  2424. SetDepthWrite(true);
  2425. }
  2426. }
  2427. void Graphics::SetTextureUnitMappings()
  2428. {
  2429. textureUnits_["DiffMap"] = TU_DIFFUSE;
  2430. textureUnits_["DiffCubeMap"] = TU_DIFFUSE;
  2431. textureUnits_["NormalMap"] = TU_NORMAL;
  2432. textureUnits_["SpecMap"] = TU_SPECULAR;
  2433. textureUnits_["EmissiveMap"] = TU_EMISSIVE;
  2434. textureUnits_["EnvMap"] = TU_ENVIRONMENT;
  2435. textureUnits_["EnvCubeMap"] = TU_ENVIRONMENT;
  2436. textureUnits_["LightRampMap"] = TU_LIGHTRAMP;
  2437. textureUnits_["LightSpotMap"] = TU_LIGHTSHAPE;
  2438. textureUnits_["LightCubeMap"] = TU_LIGHTSHAPE;
  2439. textureUnits_["ShadowMap"] = TU_SHADOWMAP;
  2440. textureUnits_["FaceSelectCubeMap"] = TU_FACESELECT;
  2441. textureUnits_["IndirectionCubeMap"] = TU_INDIRECTION;
  2442. textureUnits_["AlbedoBuffer"] = TU_ALBEDOBUFFER;
  2443. textureUnits_["NormalBuffer"] = TU_NORMALBUFFER;
  2444. textureUnits_["DepthBuffer"] = TU_DEPTHBUFFER;
  2445. textureUnits_["LightBuffer"] = TU_LIGHTBUFFER;
  2446. textureUnits_["VolumeMap"] = TU_VOLUMEMAP;
  2447. }
  2448. void RegisterGraphicsLibrary(Context* context)
  2449. {
  2450. Animation::RegisterObject(context);
  2451. Material::RegisterObject(context);
  2452. Model::RegisterObject(context);
  2453. Shader::RegisterObject(context);
  2454. Technique::RegisterObject(context);
  2455. Texture2D::RegisterObject(context);
  2456. Texture3D::RegisterObject(context);
  2457. TextureCube::RegisterObject(context);
  2458. Camera::RegisterObject(context);
  2459. Drawable::RegisterObject(context);
  2460. Light::RegisterObject(context);
  2461. StaticModel::RegisterObject(context);
  2462. StaticModelGroup::RegisterObject(context);
  2463. Skybox::RegisterObject(context);
  2464. AnimatedModel::RegisterObject(context);
  2465. AnimationController::RegisterObject(context);
  2466. BillboardSet::RegisterObject(context);
  2467. ParticleEmitter::RegisterObject(context);
  2468. CustomGeometry::RegisterObject(context);
  2469. DecalSet::RegisterObject(context);
  2470. Terrain::RegisterObject(context);
  2471. TerrainPatch::RegisterObject(context);
  2472. DebugRenderer::RegisterObject(context);
  2473. Octree::RegisterObject(context);
  2474. Zone::RegisterObject(context);
  2475. }
  2476. }