OGLGraphics.cpp 89 KB

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