OGLGraphics.cpp 96 KB

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