OGLGraphics.cpp 89 KB

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