OGLGraphics.cpp 75 KB

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