OGLGraphics.cpp 96 KB

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