OGLGraphics.cpp 91 KB

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