OGLGraphics.cpp 88 KB

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