OGLGraphics.cpp 82 KB

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