OGLGraphics.cpp 91 KB

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