OGLGraphics.cpp 76 KB

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