OGLGraphics.cpp 88 KB

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