OGLGraphics.cpp 84 KB

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