OGLGraphics.cpp 80 KB

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