Graphics.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801
  1. /**
  2. * Copyright (c) 2006-2024 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. // LOVE
  21. #include "common/config.h"
  22. #include "common/math.h"
  23. #include "common/Vector.h"
  24. #include "Graphics.h"
  25. #include "font/Font.h"
  26. #include "StreamBuffer.h"
  27. #include "GraphicsReadback.h"
  28. #include "math/MathModule.h"
  29. #include "window/Window.h"
  30. #include "Buffer.h"
  31. #include "ShaderStage.h"
  32. #include "libraries/xxHash/xxhash.h"
  33. // C++
  34. #include <vector>
  35. #include <sstream>
  36. #include <algorithm>
  37. #include <iterator>
  38. // C
  39. #include <cmath>
  40. #include <cstdio>
  41. #ifdef LOVE_IOS
  42. #include <SDL_syswm.h>
  43. #endif
  44. namespace love
  45. {
  46. namespace graphics
  47. {
  48. namespace opengl
  49. {
  50. static GLenum getGLBlendOperation(BlendOperation op)
  51. {
  52. switch (op)
  53. {
  54. case BLENDOP_ADD: return GL_FUNC_ADD;
  55. case BLENDOP_SUBTRACT: return GL_FUNC_SUBTRACT;
  56. case BLENDOP_REVERSE_SUBTRACT: return GL_FUNC_REVERSE_SUBTRACT;
  57. case BLENDOP_MIN: return GL_MIN;
  58. case BLENDOP_MAX: return GL_MAX;
  59. case BLENDOP_MAX_ENUM: return 0;
  60. }
  61. return 0;
  62. }
  63. static GLenum getGLBlendFactor(BlendFactor factor)
  64. {
  65. switch (factor)
  66. {
  67. case BLENDFACTOR_ZERO: return GL_ZERO;
  68. case BLENDFACTOR_ONE: return GL_ONE;
  69. case BLENDFACTOR_SRC_COLOR: return GL_SRC_COLOR;
  70. case BLENDFACTOR_ONE_MINUS_SRC_COLOR: return GL_ONE_MINUS_SRC_COLOR;
  71. case BLENDFACTOR_SRC_ALPHA: return GL_SRC_ALPHA;
  72. case BLENDFACTOR_ONE_MINUS_SRC_ALPHA: return GL_ONE_MINUS_SRC_ALPHA;
  73. case BLENDFACTOR_DST_COLOR: return GL_DST_COLOR;
  74. case BLENDFACTOR_ONE_MINUS_DST_COLOR: return GL_ONE_MINUS_DST_COLOR;
  75. case BLENDFACTOR_DST_ALPHA: return GL_DST_ALPHA;
  76. case BLENDFACTOR_ONE_MINUS_DST_ALPHA: return GL_ONE_MINUS_DST_ALPHA;
  77. case BLENDFACTOR_SRC_ALPHA_SATURATED: return GL_SRC_ALPHA_SATURATE;
  78. case BLENDFACTOR_MAX_ENUM: return 0;
  79. }
  80. return 0;
  81. }
  82. love::graphics::Graphics *createInstance()
  83. {
  84. love::graphics::Graphics *instance = nullptr;
  85. try
  86. {
  87. instance = new Graphics();
  88. }
  89. catch (love::Exception &e)
  90. {
  91. printf("Cannot create OpenGL renderer: %s\n", e.what());
  92. }
  93. return instance;
  94. }
  95. Graphics::Graphics()
  96. : love::graphics::Graphics("love.graphics.opengl")
  97. , windowHasStencil(false)
  98. , mainVAO(0)
  99. , internalBackbufferFBO(0)
  100. , requestedBackbufferMSAA(0)
  101. , bufferMapMemory(nullptr)
  102. , bufferMapMemorySize(2 * 1024 * 1024)
  103. , pixelFormatUsage()
  104. {
  105. gl = OpenGL();
  106. try
  107. {
  108. bufferMapMemory = new char[bufferMapMemorySize];
  109. }
  110. catch (std::exception &)
  111. {
  112. // Handled in getBufferMapMemory.
  113. }
  114. auto window = getInstance<love::window::Window>(M_WINDOW);
  115. if (window != nullptr)
  116. {
  117. window->setGraphics(this);
  118. // Recreate the window using the current renderer, if needed.
  119. if (window->isOpen())
  120. {
  121. int w, h;
  122. love::window::WindowSettings settings;
  123. window->getWindow(w, h, settings);
  124. window->setWindow(w, h, &settings);
  125. }
  126. }
  127. }
  128. Graphics::~Graphics()
  129. {
  130. delete[] bufferMapMemory;
  131. }
  132. love::graphics::StreamBuffer *Graphics::newStreamBuffer(BufferUsage type, size_t size)
  133. {
  134. return CreateStreamBuffer(type, size);
  135. }
  136. love::graphics::Texture *Graphics::newTexture(const Texture::Settings &settings, const Texture::Slices *data)
  137. {
  138. return new Texture(this, settings, data);
  139. }
  140. love::graphics::Texture *Graphics::newTextureView(love::graphics::Texture *base, const Texture::ViewSettings &viewsettings)
  141. {
  142. return new Texture(this, base, viewsettings);
  143. }
  144. love::graphics::ShaderStage *Graphics::newShaderStageInternal(ShaderStageType stage, const std::string &cachekey, const std::string &source, bool gles)
  145. {
  146. return new ShaderStage(this, stage, source, gles, cachekey);
  147. }
  148. love::graphics::Shader *Graphics::newShaderInternal(StrongRef<love::graphics::ShaderStage> stages[SHADERSTAGE_MAX_ENUM], const Shader::CompileOptions &options)
  149. {
  150. return new Shader(stages, options);
  151. }
  152. love::graphics::Buffer *Graphics::newBuffer(const Buffer::Settings &settings, const std::vector<Buffer::DataDeclaration> &format, const void *data, size_t size, size_t arraylength)
  153. {
  154. return new Buffer(this, settings, format, data, size, arraylength);
  155. }
  156. love::graphics::GraphicsReadback *Graphics::newReadbackInternal(ReadbackMethod method, love::graphics::Buffer *buffer, size_t offset, size_t size, data::ByteData *dest, size_t destoffset)
  157. {
  158. return new GraphicsReadback(this, method, buffer, offset, size, dest, destoffset);
  159. }
  160. love::graphics::GraphicsReadback *Graphics::newReadbackInternal(ReadbackMethod method, love::graphics::Texture *texture, int slice, int mipmap, const Rect &rect, image::ImageData *dest, int destx, int desty)
  161. {
  162. return new GraphicsReadback(this, method, texture, slice, mipmap, rect, dest, destx, desty);
  163. }
  164. Matrix4 Graphics::computeDeviceProjection(const Matrix4 &projection, bool rendertotexture) const
  165. {
  166. uint32 flags = DEVICE_PROJECTION_DEFAULT;
  167. // The projection matrix is flipped compared to rendering to a texture, due
  168. // to OpenGL considering (0,0) bottom-left instead of top-left.
  169. if (!rendertotexture)
  170. flags |= DEVICE_PROJECTION_FLIP_Y;
  171. return calculateDeviceProjection(projection, flags);
  172. }
  173. void Graphics::backbufferChanged(int width, int height, int pixelwidth, int pixelheight, bool backbufferstencil, bool backbufferdepth, int msaa)
  174. {
  175. bool changed = width != this->width || height != this->height
  176. || pixelwidth != this->pixelWidth || pixelheight != this->pixelHeight;
  177. changed |= backbufferstencil != this->backbufferHasStencil || backbufferdepth != this->backbufferHasDepth;
  178. changed |= msaa != this->requestedBackbufferMSAA;
  179. this->width = width;
  180. this->height = height;
  181. this->pixelWidth = pixelwidth;
  182. this->pixelHeight = pixelheight;
  183. this->backbufferHasStencil = backbufferstencil;
  184. this->backbufferHasDepth = backbufferdepth;
  185. this->requestedBackbufferMSAA = msaa;
  186. if (!isRenderTargetActive())
  187. {
  188. // Set the viewport to top-left corner.
  189. gl.setViewport({0, 0, pixelwidth, pixelheight});
  190. // Re-apply the scissor if it was active, since the rectangle passed to
  191. // glScissor is affected by the viewport dimensions.
  192. if (states.back().scissor)
  193. setScissor(states.back().scissorRect);
  194. resetProjection();
  195. }
  196. if (!changed)
  197. return;
  198. bool useinternalbackbuffer = false;
  199. if (msaa > 1)
  200. useinternalbackbuffer = true;
  201. // Our internal backbuffer code needs glBlitFramebuffer.
  202. if (!(GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_object || GLAD_ES_VERSION_3_0
  203. || GLAD_EXT_framebuffer_blit || GLAD_ANGLE_framebuffer_blit || GLAD_NV_framebuffer_blit))
  204. {
  205. if (!(msaa > 1 && GLAD_APPLE_framebuffer_multisample))
  206. useinternalbackbuffer = false;
  207. }
  208. GLuint prevFBO = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  209. bool restoreFBO = prevFBO != getInternalBackbufferFBO();
  210. if (useinternalbackbuffer)
  211. {
  212. Texture::Settings settings;
  213. settings.width = width;
  214. settings.height = height;
  215. settings.dpiScale = (float)pixelheight / (float)height;
  216. settings.msaa = msaa;
  217. settings.renderTarget = true;
  218. settings.readable.set(false);
  219. settings.format = isGammaCorrect() ? PIXELFORMAT_RGBA8_sRGB : PIXELFORMAT_RGBA8_UNORM;
  220. internalBackbuffer.set(newTexture(settings), Acquire::NORETAIN);
  221. internalBackbufferDepthStencil.set(nullptr);
  222. if (backbufferstencil || backbufferdepth)
  223. {
  224. if (backbufferstencil && backbufferdepth)
  225. settings.format = PIXELFORMAT_DEPTH24_UNORM_STENCIL8;
  226. else if (backbufferstencil)
  227. settings.format = PIXELFORMAT_STENCIL8;
  228. else if (backbufferdepth)
  229. settings.format = PIXELFORMAT_DEPTH24_UNORM;
  230. internalBackbufferDepthStencil.set(newTexture(settings), Acquire::NORETAIN);
  231. }
  232. RenderTargets rts;
  233. rts.colors.push_back(internalBackbuffer.get());
  234. rts.depthStencil.texture = internalBackbufferDepthStencil;
  235. internalBackbufferFBO = bindCachedFBO(rts);
  236. }
  237. else
  238. {
  239. internalBackbuffer.set(nullptr);
  240. internalBackbufferDepthStencil.set(nullptr);
  241. internalBackbufferFBO = 0;
  242. }
  243. if (restoreFBO)
  244. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, prevFBO);
  245. }
  246. GLuint Graphics::getInternalBackbufferFBO() const
  247. {
  248. if (internalBackbufferFBO != 0)
  249. return internalBackbufferFBO;
  250. else
  251. return getSystemBackbufferFBO();
  252. }
  253. GLuint Graphics::getSystemBackbufferFBO() const
  254. {
  255. #ifdef LOVE_IOS
  256. // Hack: iOS uses a custom FBO.
  257. SDL_SysWMinfo info = {};
  258. SDL_VERSION(&info.version);
  259. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  260. if (info.info.uikit.resolveFramebuffer != 0)
  261. return info.info.uikit.resolveFramebuffer;
  262. else
  263. return info.info.uikit.framebuffer;
  264. #else
  265. return 0;
  266. #endif
  267. }
  268. bool Graphics::setMode(void */*context*/, int width, int height, int pixelwidth, int pixelheight, bool backbufferstencil, bool backbufferdepth, int msaa)
  269. {
  270. // Okay, setup OpenGL.
  271. gl.initContext();
  272. if (gl.isCoreProfile())
  273. {
  274. glGenVertexArrays(1, &mainVAO);
  275. glBindVertexArray(mainVAO);
  276. }
  277. gl.setupContext();
  278. created = true;
  279. initCapabilities();
  280. // Enable blending
  281. gl.setEnableState(OpenGL::ENABLE_BLEND, true);
  282. // Auto-generated mipmaps should be the best quality possible
  283. if (!gl.isCoreProfile())
  284. glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
  285. if (!GLAD_ES_VERSION_2_0 && !gl.isCoreProfile())
  286. {
  287. // Make sure antialiasing works when set elsewhere
  288. glEnable(GL_MULTISAMPLE);
  289. // Enable texturing
  290. glEnable(GL_TEXTURE_2D);
  291. }
  292. if (!GLAD_ES_VERSION_2_0)
  293. glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
  294. gl.setTextureUnit(0);
  295. // Set pixel row alignment - code that calls glTexSubImage and glReadPixels
  296. // assumes there's no row alignment, but OpenGL defaults to 4 bytes.
  297. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  298. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  299. // Always enable seamless cubemap filtering when possible.
  300. if (GLAD_VERSION_3_2 || GLAD_ARB_seamless_cube_map)
  301. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  302. // Set whether drawing converts input from linear -> sRGB colorspace.
  303. if (!gl.bugs.brokenSRGB && (GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_sRGB
  304. || GLAD_EXT_framebuffer_sRGB || GLAD_ES_VERSION_3_0))
  305. {
  306. if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
  307. gl.setEnableState(OpenGL::ENABLE_FRAMEBUFFER_SRGB, isGammaCorrect());
  308. }
  309. else
  310. setGammaCorrect(false);
  311. setDebug(isDebugEnabled());
  312. backbufferChanged(width, height, pixelwidth, pixelheight, backbufferstencil, backbufferdepth, msaa);
  313. if (batchedDrawState.vb[0] == nullptr)
  314. {
  315. // Initial sizes that should be good enough for most cases. It will
  316. // resize to fit if needed, later.
  317. batchedDrawState.vb[0] = CreateStreamBuffer(BUFFERUSAGE_VERTEX, 1024 * 1024 * 1);
  318. batchedDrawState.vb[1] = CreateStreamBuffer(BUFFERUSAGE_VERTEX, 256 * 1024 * 1);
  319. batchedDrawState.indexBuffer = CreateStreamBuffer(BUFFERUSAGE_INDEX, sizeof(uint16) * LOVE_UINT16_MAX);
  320. }
  321. // Reload all volatile objects.
  322. if (!Volatile::loadAll())
  323. ::printf("Could not reload all volatile objects.\n");
  324. createQuadIndexBuffer();
  325. // Restore the graphics state.
  326. restoreState(states.back());
  327. // We always need a default shader.
  328. for (int i = 0; i < Shader::STANDARD_MAX_ENUM; i++)
  329. {
  330. auto stype = (Shader::StandardShader) i;
  331. if (i == Shader::STANDARD_ARRAY && !capabilities.textureTypes[TEXTURE_2D_ARRAY])
  332. continue;
  333. // Apparently some intel GMA drivers on windows fail to compile shaders
  334. // which use array textures despite claiming support for the extension.
  335. try
  336. {
  337. if (!Shader::standardShaders[i])
  338. {
  339. std::vector<std::string> stages;
  340. Shader::CompileOptions opts;
  341. stages.push_back(Shader::getDefaultCode(stype, SHADERSTAGE_VERTEX));
  342. stages.push_back(Shader::getDefaultCode(stype, SHADERSTAGE_PIXEL));
  343. Shader::standardShaders[i] = newShader(stages, opts);
  344. }
  345. }
  346. catch (love::Exception &)
  347. {
  348. if (i == Shader::STANDARD_ARRAY)
  349. capabilities.textureTypes[TEXTURE_2D_ARRAY] = false;
  350. else
  351. throw;
  352. }
  353. }
  354. // A shader should always be active, but the default shader shouldn't be
  355. // returned by getShader(), so we don't do setShader(defaultShader).
  356. if (!Shader::current)
  357. Shader::standardShaders[Shader::STANDARD_DEFAULT]->attach();
  358. return true;
  359. }
  360. void Graphics::unSetMode()
  361. {
  362. if (!isCreated())
  363. return;
  364. flushBatchedDraws();
  365. internalBackbuffer.set(nullptr);
  366. internalBackbufferDepthStencil.set(nullptr);
  367. // Unload all volatile objects. These must be reloaded after the display
  368. // mode change.
  369. Volatile::unloadAll();
  370. clearTemporaryResources();
  371. for (const auto &pair : framebufferObjects)
  372. gl.deleteFramebuffer(pair.second);
  373. framebufferObjects.clear();
  374. if (mainVAO != 0)
  375. {
  376. glDeleteVertexArrays(1, &mainVAO);
  377. mainVAO = 0;
  378. }
  379. gl.deInitContext();
  380. created = false;
  381. }
  382. void Graphics::setActive(bool enable)
  383. {
  384. flushBatchedDraws();
  385. // Make sure all pending OpenGL commands have fully executed before
  386. // returning, when going from active to inactive. This is required on iOS.
  387. if (isCreated() && this->active && !enable)
  388. glFinish();
  389. active = enable;
  390. }
  391. static bool computeDispatchBarriers(Shader *shader, GLbitfield &preDispatchBarriers, GLbitfield &postDispatchBarriers)
  392. {
  393. for (auto buffer : shader->getActiveWritableStorageBuffers())
  394. {
  395. if (buffer == nullptr)
  396. return false;
  397. auto usage = buffer->getUsageFlags();
  398. postDispatchBarriers |= GL_BUFFER_UPDATE_BARRIER_BIT;
  399. if (usage & BUFFERUSAGEFLAG_SHADER_STORAGE)
  400. {
  401. preDispatchBarriers |= GL_SHADER_STORAGE_BARRIER_BIT;
  402. postDispatchBarriers |= GL_SHADER_STORAGE_BARRIER_BIT;
  403. }
  404. // TODO: does this need a pre dispatch barrier too?
  405. if (usage & BUFFERUSAGEFLAG_INDIRECT_ARGUMENTS)
  406. postDispatchBarriers |= GL_COMMAND_BARRIER_BIT;
  407. if (usage & BUFFERUSAGEFLAG_TEXEL)
  408. postDispatchBarriers |= GL_TEXTURE_FETCH_BARRIER_BIT;
  409. if (usage & BUFFERUSAGEFLAG_INDEX)
  410. postDispatchBarriers |= GL_ELEMENT_ARRAY_BARRIER_BIT;
  411. if (usage & BUFFERUSAGEFLAG_VERTEX)
  412. postDispatchBarriers |= GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT;
  413. postDispatchBarriers |= GL_PIXEL_BUFFER_BARRIER_BIT;
  414. }
  415. for (const auto &binding : shader->getStorageTextureBindings())
  416. {
  417. if (binding.texture == nullptr)
  418. return false;
  419. if (binding.access == GL_READ_ONLY)
  420. continue;
  421. preDispatchBarriers |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT;
  422. postDispatchBarriers |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT
  423. | GL_TEXTURE_UPDATE_BARRIER_BIT
  424. | GL_TEXTURE_FETCH_BARRIER_BIT;
  425. if (binding.texture->isRenderTarget())
  426. postDispatchBarriers |= GL_FRAMEBUFFER_BARRIER_BIT;
  427. }
  428. return true;
  429. }
  430. bool Graphics::dispatch(love::graphics::Shader *s, int x, int y, int z)
  431. {
  432. auto shader = (Shader *) s;
  433. GLbitfield preDispatchBarriers = 0;
  434. GLbitfield postDispatchBarriers = 0;
  435. if (!computeDispatchBarriers(shader, preDispatchBarriers, postDispatchBarriers))
  436. return false;
  437. // glMemoryBarrier before dispatch to make sure non-compute-read ->
  438. // compute-write is synced.
  439. // TODO: is this needed? spec language around GL_SHADER_IMAGE_ACCESS_BARRIER_BIT
  440. // makes me think so.
  441. // This is overly conservative (dispatch -> dispatch will have redundant
  442. // barriers).
  443. if (preDispatchBarriers != 0)
  444. glMemoryBarrier(preDispatchBarriers);
  445. glDispatchCompute(x, y, z);
  446. // Not as (theoretically) efficient as issuing the barrier right before
  447. // they're used later, but much less complicated.
  448. if (postDispatchBarriers != 0)
  449. glMemoryBarrier(postDispatchBarriers);
  450. return true;
  451. }
  452. bool Graphics::dispatch(love::graphics::Shader *s, love::graphics::Buffer *indirectargs, size_t argsoffset)
  453. {
  454. auto shader = (Shader *) s;
  455. GLbitfield preDispatchBarriers = 0;
  456. GLbitfield postDispatchBarriers = 0;
  457. if (!computeDispatchBarriers(shader, preDispatchBarriers, postDispatchBarriers))
  458. return false;
  459. if (preDispatchBarriers != 0)
  460. glMemoryBarrier(preDispatchBarriers);
  461. // Note: OpenGL has separate bind points for draw versus dispatch indirect
  462. // buffers. Our gl.bindBuffer wrapper uses the draw bind point, so we can't
  463. // use it here.
  464. glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, (GLuint)indirectargs->getHandle());
  465. glDispatchComputeIndirect(argsoffset);
  466. // Not as (theoretically) efficient as issuing the barrier right before
  467. // they're used later, but much less complicated.
  468. if (postDispatchBarriers != 0)
  469. glMemoryBarrier(postDispatchBarriers);
  470. return true;
  471. }
  472. void Graphics::draw(const DrawCommand &cmd)
  473. {
  474. gl.prepareDraw(this);
  475. gl.setVertexAttributes(*cmd.attributes, *cmd.buffers);
  476. gl.bindTextureToUnit(cmd.texture, 0, false);
  477. gl.setCullMode(cmd.cullMode);
  478. GLenum glprimitivetype = OpenGL::getGLPrimitiveType(cmd.primitiveType);
  479. if (cmd.indirectBuffer != nullptr)
  480. {
  481. gl.bindBuffer(BUFFERUSAGE_INDIRECT_ARGUMENTS, (GLuint) cmd.indirectBuffer->getHandle());
  482. glDrawArraysIndirect(glprimitivetype, BUFFER_OFFSET(cmd.indirectBufferOffset));
  483. }
  484. else if (cmd.instanceCount > 1)
  485. glDrawArraysInstanced(glprimitivetype, cmd.vertexStart, cmd.vertexCount, cmd.instanceCount);
  486. else
  487. glDrawArrays(glprimitivetype, cmd.vertexStart, cmd.vertexCount);
  488. ++drawCalls;
  489. }
  490. void Graphics::draw(const DrawIndexedCommand &cmd)
  491. {
  492. gl.prepareDraw(this);
  493. gl.setVertexAttributes(*cmd.attributes, *cmd.buffers);
  494. gl.bindTextureToUnit(cmd.texture, 0, false);
  495. gl.setCullMode(cmd.cullMode);
  496. const void *gloffset = BUFFER_OFFSET(cmd.indexBufferOffset);
  497. GLenum glprimitivetype = OpenGL::getGLPrimitiveType(cmd.primitiveType);
  498. GLenum gldatatype = OpenGL::getGLIndexDataType(cmd.indexType);
  499. gl.bindBuffer(BUFFERUSAGE_INDEX, cmd.indexBuffer->getHandle());
  500. if (cmd.indirectBuffer != nullptr)
  501. {
  502. // Note: OpenGL doesn't support indirect indexed draws with a non-zero
  503. // index buffer offset.
  504. gl.bindBuffer(BUFFERUSAGE_INDIRECT_ARGUMENTS, (GLuint) cmd.indirectBuffer->getHandle());
  505. glDrawElementsIndirect(glprimitivetype, gldatatype, BUFFER_OFFSET(cmd.indirectBufferOffset));
  506. }
  507. else if (cmd.instanceCount > 1)
  508. glDrawElementsInstanced(glprimitivetype, cmd.indexCount, gldatatype, gloffset, cmd.instanceCount);
  509. else
  510. glDrawElements(glprimitivetype, cmd.indexCount, gldatatype, gloffset);
  511. ++drawCalls;
  512. }
  513. static inline void advanceVertexOffsets(const VertexAttributes &attributes, BufferBindings &buffers, int vertexcount)
  514. {
  515. // TODO: Figure out a better way to avoid touching the same buffer multiple
  516. // times, if multiple attributes share the buffer.
  517. uint32 touchedbuffers = 0;
  518. for (unsigned int i = 0; i < VertexAttributes::MAX; i++)
  519. {
  520. if (!attributes.isEnabled(i))
  521. continue;
  522. auto &attrib = attributes.attribs[i];
  523. uint32 bufferbit = 1u << attrib.bufferIndex;
  524. if ((touchedbuffers & bufferbit) == 0)
  525. {
  526. touchedbuffers |= bufferbit;
  527. const auto &layout = attributes.bufferLayouts[attrib.bufferIndex];
  528. buffers.info[attrib.bufferIndex].offset += layout.stride * vertexcount;
  529. }
  530. }
  531. }
  532. void Graphics::drawQuads(int start, int count, const VertexAttributes &attributes, const BufferBindings &buffers, love::graphics::Texture *texture)
  533. {
  534. const int MAX_VERTICES_PER_DRAW = LOVE_UINT16_MAX;
  535. const int MAX_QUADS_PER_DRAW = MAX_VERTICES_PER_DRAW / 4;
  536. gl.prepareDraw(this);
  537. gl.bindTextureToUnit(texture, 0, false);
  538. gl.setCullMode(CULL_NONE);
  539. gl.bindBuffer(BUFFERUSAGE_INDEX, quadIndexBuffer->getHandle());
  540. if (gl.isBaseVertexSupported())
  541. {
  542. gl.setVertexAttributes(attributes, buffers);
  543. int basevertex = start * 4;
  544. for (int quadindex = 0; quadindex < count; quadindex += MAX_QUADS_PER_DRAW)
  545. {
  546. int quadcount = std::min(MAX_QUADS_PER_DRAW, count - quadindex);
  547. glDrawElementsBaseVertex(GL_TRIANGLES, quadcount * 6, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0), basevertex);
  548. ++drawCalls;
  549. basevertex += quadcount * 4;
  550. }
  551. }
  552. else
  553. {
  554. BufferBindings bufferscopy = buffers;
  555. if (start > 0)
  556. advanceVertexOffsets(attributes, bufferscopy, start * 4);
  557. for (int quadindex = 0; quadindex < count; quadindex += MAX_QUADS_PER_DRAW)
  558. {
  559. gl.setVertexAttributes(attributes, bufferscopy);
  560. int quadcount = std::min(MAX_QUADS_PER_DRAW, count - quadindex);
  561. glDrawElements(GL_TRIANGLES, quadcount * 6, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));
  562. ++drawCalls;
  563. if (count > MAX_QUADS_PER_DRAW)
  564. advanceVertexOffsets(attributes, bufferscopy, quadcount * 4);
  565. }
  566. }
  567. }
  568. static void APIENTRY debugCB(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei /*len*/, const GLchar *msg, const GLvoid* /*usr*/)
  569. {
  570. if (severity == GL_DEBUG_SEVERITY_NOTIFICATION)
  571. return;
  572. // Human-readable strings for the debug info.
  573. const char *sourceStr = OpenGL::debugSourceString(source);
  574. const char *typeStr = OpenGL::debugTypeString(type);
  575. const char *severityStr = OpenGL::debugSeverityString(severity);
  576. const char *fmt = "OpenGL: [source=%s, type=%s, severity=%s, id=%d]: %s\n";
  577. printf(fmt, sourceStr, typeStr, severityStr, id, msg);
  578. }
  579. void Graphics::setDebug(bool enable)
  580. {
  581. // Make sure debug output is supported. The AMD ext. is a bit different
  582. // so we don't make use of it, since AMD drivers now support KHR_debug.
  583. if (!(GLAD_VERSION_4_3 || GLAD_ES_VERSION_3_2 || GLAD_KHR_debug || GLAD_ARB_debug_output))
  584. return;
  585. // TODO: We don't support GL_KHR_debug in GLES yet.
  586. if (GLAD_ES_VERSION_2_0 && !GLAD_ES_VERSION_3_2)
  587. return;
  588. // Ugly hack to reduce code duplication.
  589. if (GLAD_ARB_debug_output && !(GLAD_VERSION_4_3 || GLAD_KHR_debug))
  590. {
  591. fp_glDebugMessageCallback = (pfn_glDebugMessageCallback) fp_glDebugMessageCallbackARB;
  592. fp_glDebugMessageControl = (pfn_glDebugMessageControl) fp_glDebugMessageControlARB;
  593. }
  594. if (!enable)
  595. {
  596. // Disable the debug callback function.
  597. glDebugMessageCallback(nullptr, nullptr);
  598. // We can disable debug output entirely with KHR_debug.
  599. if (GLAD_VERSION_4_3 || GLAD_ES_VERSION_3_2 || GLAD_KHR_debug)
  600. glDisable(GL_DEBUG_OUTPUT);
  601. return;
  602. }
  603. // We don't want asynchronous debug output.
  604. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  605. glDebugMessageCallback(debugCB, nullptr);
  606. // Initially, enable everything.
  607. glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
  608. // Disable messages about deprecated OpenGL functionality.
  609. glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  610. glDebugMessageControl(GL_DEBUG_SOURCE_SHADER_COMPILER, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  611. if (GLAD_VERSION_4_3 || GLAD_ES_VERSION_3_2 || GLAD_KHR_debug)
  612. glEnable(GL_DEBUG_OUTPUT);
  613. ::printf("OpenGL debug output enabled (LOVE_GRAPHICS_DEBUG=1)\n");
  614. }
  615. void Graphics::setRenderTargetsInternal(const RenderTargets &rts, int pixelw, int pixelh, bool hasSRGBtexture)
  616. {
  617. const DisplayState &state = states.back();
  618. OpenGL::TempDebugGroup debuggroup("setRenderTargets");
  619. endPass(false);
  620. bool iswindow = rts.getFirstTarget().texture == nullptr;
  621. Winding vertexwinding = state.winding;
  622. if (iswindow)
  623. {
  624. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getInternalBackbufferFBO());
  625. }
  626. else
  627. {
  628. bindCachedFBO(rts);
  629. // Flip front face winding when rendering to a texture, since our
  630. // projection matrix is flipped.
  631. // Note: projection matrix is set at a higher level.
  632. vertexwinding = vertexwinding == WINDING_CW ? WINDING_CCW : WINDING_CW;
  633. }
  634. glFrontFace(vertexwinding == WINDING_CW ? GL_CW : GL_CCW);
  635. gl.setViewport({0, 0, pixelw, pixelh});
  636. // Re-apply the scissor if it was active, since the rectangle passed to
  637. // glScissor is affected by the viewport dimensions.
  638. if (state.scissor)
  639. setScissor(state.scissorRect);
  640. // Make sure the correct sRGB setting is used when drawing to the textures.
  641. if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
  642. {
  643. if (hasSRGBtexture != gl.isStateEnabled(OpenGL::ENABLE_FRAMEBUFFER_SRGB))
  644. gl.setEnableState(OpenGL::ENABLE_FRAMEBUFFER_SRGB, hasSRGBtexture);
  645. }
  646. }
  647. void Graphics::endPass(bool presenting)
  648. {
  649. auto &rts = states.back().renderTargets;
  650. love::graphics::Texture *depthstencil = rts.depthStencil.texture.get();
  651. // Discard the depth/stencil buffer if we're using an internal cached one,
  652. // or if we're presenting the backbuffer to the display.
  653. if ((depthstencil == nullptr && (rts.temporaryRTFlags & (TEMPORARY_RT_DEPTH | TEMPORARY_RT_STENCIL)) != 0)
  654. || (presenting && !rts.getFirstTarget().texture.get()))
  655. {
  656. discard({}, true);
  657. }
  658. // Resolve MSAA buffers. MSAA is only supported for 2D render targets so we
  659. // don't have to worry about resolving to slices.
  660. if (rts.colors.size() > 0 && rts.colors[0].texture->getMSAA() > 1)
  661. {
  662. int mip = rts.colors[0].mipmap;
  663. int w = rts.colors[0].texture->getPixelWidth(mip);
  664. int h = rts.colors[0].texture->getPixelHeight(mip);
  665. for (int i = 0; i < (int) rts.colors.size(); i++)
  666. {
  667. Texture *c = (Texture *) rts.colors[i].texture.get();
  668. if (!c->isReadable())
  669. continue;
  670. glReadBuffer(GL_COLOR_ATTACHMENT0 + i);
  671. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, c->getFBO());
  672. if (GLAD_APPLE_framebuffer_multisample)
  673. glResolveMultisampleFramebufferAPPLE();
  674. else
  675. glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  676. }
  677. }
  678. if (depthstencil != nullptr && depthstencil->getMSAA() > 1 && depthstencil->isReadable())
  679. {
  680. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, ((Texture *) depthstencil)->getFBO());
  681. if (GLAD_APPLE_framebuffer_multisample)
  682. glResolveMultisampleFramebufferAPPLE();
  683. else
  684. {
  685. int mip = rts.depthStencil.mipmap;
  686. int w = depthstencil->getPixelWidth(mip);
  687. int h = depthstencil->getPixelHeight(mip);
  688. PixelFormat format = depthstencil->getPixelFormat();
  689. GLbitfield mask = 0;
  690. if (isPixelFormatDepth(format))
  691. mask |= GL_DEPTH_BUFFER_BIT;
  692. if (isPixelFormatStencil(format))
  693. mask |= GL_STENCIL_BUFFER_BIT;
  694. if (mask != 0)
  695. glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, mask, GL_NEAREST);
  696. }
  697. }
  698. // generateMipmaps can't be used for depth/stencil textures.
  699. for (const auto &rt : rts.colors)
  700. {
  701. if (rt.texture->getMipmapsMode() == Texture::MIPMAPS_AUTO && rt.mipmap == 0)
  702. rt.texture->generateMipmaps();
  703. }
  704. }
  705. void Graphics::clear(OptionalColorD c, OptionalInt stencil, OptionalDouble depth)
  706. {
  707. if (c.hasValue)
  708. {
  709. bool hasintegerformat = false;
  710. const auto &rts = states.back().renderTargets;
  711. for (const auto &rt : rts.colors)
  712. {
  713. if (rt.texture.get() && isPixelFormatInteger(rt.texture->getPixelFormat()))
  714. hasintegerformat = true;
  715. }
  716. // This variant of clear() uses glClear() which can't clear integer formats,
  717. // so we switch to the MRT variant if needed.
  718. if (hasintegerformat)
  719. {
  720. std::vector<OptionalColorD> colors(rts.colors.size());
  721. for (size_t i = 0; i < colors.size(); i++)
  722. colors[i] = c;
  723. clear(colors, stencil, depth);
  724. return;
  725. }
  726. }
  727. if (c.hasValue || stencil.hasValue || depth.hasValue)
  728. flushBatchedDraws();
  729. GLbitfield flags = 0;
  730. if (c.hasValue)
  731. {
  732. Colorf cf((float)c.value.r, (float)c.value.g, (float)c.value.b, (float)c.value.a);
  733. gammaCorrectColor(cf);
  734. glClearColor(cf.r, cf.g, cf.b, cf.a);
  735. flags |= GL_COLOR_BUFFER_BIT;
  736. }
  737. if (stencil.hasValue)
  738. {
  739. glClearStencil(stencil.value);
  740. flags |= GL_STENCIL_BUFFER_BIT;
  741. }
  742. if (depth.hasValue)
  743. {
  744. gl.clearDepth(depth.value);
  745. flags |= GL_DEPTH_BUFFER_BIT;
  746. }
  747. if (flags != 0)
  748. {
  749. OpenGL::CleanClearState cs(flags);
  750. glClear(flags);
  751. }
  752. if (c.hasValue && gl.bugs.clearRequiresDriverTextureStateUpdate && Shader::current)
  753. {
  754. // This seems to be enough to fix the bug for me. Other methods I've
  755. // tried (e.g. dummy draws) don't work in all cases.
  756. gl.useProgram(0);
  757. gl.useProgram((GLuint) Shader::current->getHandle());
  758. }
  759. }
  760. void Graphics::clear(const std::vector<OptionalColorD> &colors, OptionalInt stencil, OptionalDouble depth)
  761. {
  762. if (colors.size() == 0 && !stencil.hasValue && !depth.hasValue)
  763. return;
  764. const auto &rts = states.back().renderTargets.colors;
  765. int ncolorRTs = (int) rts.size();
  766. int ncolors = (int) colors.size();
  767. if (ncolors <= 1 && (ncolorRTs == 0 || (ncolorRTs == 1 && rts[0].texture != nullptr && !isPixelFormatInteger(rts[0].texture->getPixelFormat()))))
  768. {
  769. clear(ncolors > 0 ? colors[0] : OptionalColorD(), stencil, depth);
  770. return;
  771. }
  772. flushBatchedDraws();
  773. bool drawbuffersmodified = false;
  774. ncolors = std::min(ncolors, ncolorRTs);
  775. for (int i = 0; i < ncolors; i++)
  776. {
  777. if (!colors[i].hasValue)
  778. continue;
  779. PixelFormatType datatype = PIXELFORMATTYPE_UNORM;
  780. if (rts[i].texture != nullptr)
  781. datatype = getPixelFormatInfo(rts[i].texture->getPixelFormat()).dataType;
  782. ColorD c = colors[i].value;
  783. if (GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0)
  784. {
  785. if (datatype == PIXELFORMATTYPE_SINT)
  786. {
  787. const GLint carray[] = {(GLint)c.r, (GLint)c.g, (GLint)c.b, (GLint)c.a};
  788. glClearBufferiv(GL_COLOR, i, carray);
  789. }
  790. else if (datatype == PIXELFORMATTYPE_UINT)
  791. {
  792. const GLuint carray[] = {(GLuint)c.r, (GLuint)c.g, (GLuint)c.b, (GLuint)c.a};
  793. glClearBufferuiv(GL_COLOR, i, carray);
  794. }
  795. else
  796. {
  797. Colorf cf((float)c.r, (float)c.g, (float)c.b, (float)c.a);
  798. gammaCorrectColor(cf);
  799. const GLfloat carray[] = {cf.r, cf.g, cf.b, cf.a};
  800. glClearBufferfv(GL_COLOR, i, carray);
  801. }
  802. }
  803. else
  804. {
  805. Colorf cf((float)c.r, (float)c.g, (float)c.b, (float)c.a);
  806. gammaCorrectColor(cf);
  807. glDrawBuffer(GL_COLOR_ATTACHMENT0 + i);
  808. glClearColor(cf.r, cf.g, cf.b, cf.a);
  809. glClear(GL_COLOR_BUFFER_BIT);
  810. drawbuffersmodified = true;
  811. }
  812. }
  813. // Revert to the expected draw buffers once we're done, if glClearBuffer
  814. // wasn't supported.
  815. if (drawbuffersmodified)
  816. {
  817. GLenum bufs[MAX_COLOR_RENDER_TARGETS];
  818. for (int i = 0; i < ncolorRTs; i++)
  819. bufs[i] = GL_COLOR_ATTACHMENT0 + i;
  820. glDrawBuffers(ncolorRTs, bufs);
  821. }
  822. GLbitfield flags = 0;
  823. if (stencil.hasValue)
  824. {
  825. glClearStencil(stencil.value);
  826. flags |= GL_STENCIL_BUFFER_BIT;
  827. }
  828. if (depth.hasValue)
  829. {
  830. gl.clearDepth(depth.value);
  831. flags |= GL_DEPTH_BUFFER_BIT;
  832. }
  833. if (flags != 0)
  834. {
  835. OpenGL::CleanClearState cs(flags);
  836. glClear(flags);
  837. }
  838. if (gl.bugs.clearRequiresDriverTextureStateUpdate && Shader::current)
  839. {
  840. // This seems to be enough to fix the bug for me. Other methods I've
  841. // tried (e.g. dummy draws) don't work in all cases.
  842. gl.useProgram(0);
  843. gl.useProgram((GLuint) Shader::current->getHandle());
  844. }
  845. }
  846. void Graphics::discard(const std::vector<bool> &colorbuffers, bool depthstencil)
  847. {
  848. flushBatchedDraws();
  849. discard(OpenGL::FRAMEBUFFER_ALL, colorbuffers, depthstencil);
  850. }
  851. void Graphics::discard(OpenGL::FramebufferTarget target, const std::vector<bool> &colorbuffers, bool depthstencil)
  852. {
  853. if (!(GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0 || GLAD_EXT_discard_framebuffer))
  854. return;
  855. GLenum gltarget = GL_FRAMEBUFFER;
  856. if (target == OpenGL::FRAMEBUFFER_READ)
  857. gltarget = GL_READ_FRAMEBUFFER;
  858. else if (target == OpenGL::FRAMEBUFFER_DRAW)
  859. gltarget = GL_DRAW_FRAMEBUFFER;
  860. std::vector<GLenum> attachments;
  861. attachments.reserve(colorbuffers.size());
  862. // glDiscardFramebuffer uses different attachment enums for the default FBO.
  863. if (!isRenderTargetActive() && getInternalBackbufferFBO() == 0)
  864. {
  865. if (colorbuffers.size() > 0 && colorbuffers[0])
  866. attachments.push_back(GL_COLOR);
  867. if (depthstencil)
  868. {
  869. attachments.push_back(GL_STENCIL);
  870. attachments.push_back(GL_DEPTH);
  871. }
  872. }
  873. else
  874. {
  875. int rendertargetcount = std::max((int) states.back().renderTargets.colors.size(), 1);
  876. for (int i = 0; i < (int) colorbuffers.size(); i++)
  877. {
  878. if (colorbuffers[i] && i < rendertargetcount)
  879. attachments.push_back(GL_COLOR_ATTACHMENT0 + i);
  880. }
  881. if (depthstencil)
  882. {
  883. attachments.push_back(GL_STENCIL_ATTACHMENT);
  884. attachments.push_back(GL_DEPTH_ATTACHMENT);
  885. }
  886. }
  887. // Hint for the driver that it doesn't need to save these buffers.
  888. if (GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0)
  889. glInvalidateFramebuffer(gltarget, (GLint) attachments.size(), &attachments[0]);
  890. else if (GLAD_EXT_discard_framebuffer)
  891. glDiscardFramebufferEXT(gltarget, (GLint) attachments.size(), &attachments[0]);
  892. }
  893. void Graphics::cleanupRenderTexture(love::graphics::Texture *texture)
  894. {
  895. if (!texture->isRenderTarget())
  896. return;
  897. for (auto it = framebufferObjects.begin(); it != framebufferObjects.end(); /**/)
  898. {
  899. bool hastexture = false;
  900. const auto &rts = it->first;
  901. for (const RenderTarget &rt : rts.colors)
  902. {
  903. if (rt.texture == texture)
  904. {
  905. hastexture = true;
  906. break;
  907. }
  908. }
  909. hastexture = hastexture || rts.depthStencil.texture == texture;
  910. if (hastexture)
  911. {
  912. if (isCreated())
  913. gl.deleteFramebuffer(it->second);
  914. it = framebufferObjects.erase(it);
  915. }
  916. else
  917. ++it;
  918. }
  919. }
  920. GLuint Graphics::bindCachedFBO(const RenderTargets &targets)
  921. {
  922. GLuint fbo = framebufferObjects[targets];
  923. if (fbo != 0)
  924. {
  925. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  926. }
  927. else
  928. {
  929. int msaa = targets.getFirstTarget().texture->getMSAA();
  930. bool hasDS = targets.depthStencil.texture != nullptr;
  931. glGenFramebuffers(1, &fbo);
  932. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  933. int ncolortargets = 0;
  934. GLenum drawbuffers[MAX_COLOR_RENDER_TARGETS];
  935. auto attachRT = [&](const RenderTarget &rt)
  936. {
  937. bool renderbuffer = msaa > 1 || !rt.texture->isReadable();
  938. OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(rt.texture->getPixelFormat(), renderbuffer);
  939. if (fmt.framebufferAttachments[0] == GL_COLOR_ATTACHMENT0)
  940. {
  941. fmt.framebufferAttachments[0] = GL_COLOR_ATTACHMENT0 + ncolortargets;
  942. drawbuffers[ncolortargets] = fmt.framebufferAttachments[0];
  943. ncolortargets++;
  944. }
  945. GLuint handle = (GLuint) rt.texture->getRenderTargetHandle();
  946. for (GLenum attachment : fmt.framebufferAttachments)
  947. {
  948. if (attachment == GL_NONE)
  949. continue;
  950. else if (renderbuffer)
  951. glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, handle);
  952. else
  953. {
  954. TextureType textype = rt.texture->getTextureType();
  955. int layer = textype == TEXTURE_CUBE ? 0 : rt.slice;
  956. int face = textype == TEXTURE_CUBE ? rt.slice : 0;
  957. int level = rt.mipmap;
  958. gl.framebufferTexture(attachment, textype, handle, level, layer, face);
  959. }
  960. }
  961. };
  962. for (const auto &rt : targets.colors)
  963. attachRT(rt);
  964. if (hasDS)
  965. attachRT(targets.depthStencil);
  966. if (ncolortargets > 1)
  967. glDrawBuffers(ncolortargets, drawbuffers);
  968. else if (ncolortargets == 0 && hasDS && (GLAD_ES_VERSION_3_0 || !GLAD_ES_VERSION_2_0))
  969. {
  970. // glDrawBuffers is an ext in GL2. glDrawBuffer doesn't exist in ES3.
  971. GLenum none = GL_NONE;
  972. if (GLAD_ES_VERSION_3_0)
  973. glDrawBuffers(1, &none);
  974. else
  975. glDrawBuffer(GL_NONE);
  976. glReadBuffer(GL_NONE);
  977. }
  978. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  979. if (status != GL_FRAMEBUFFER_COMPLETE)
  980. {
  981. gl.deleteFramebuffer(fbo);
  982. const char *sstr = OpenGL::framebufferStatusString(status);
  983. throw love::Exception("Could not create Framebuffer Object! %s", sstr);
  984. }
  985. framebufferObjects[targets] = fbo;
  986. }
  987. return fbo;
  988. }
  989. void Graphics::present(void *screenshotCallbackData)
  990. {
  991. if (!isActive())
  992. return;
  993. if (isRenderTargetActive())
  994. throw love::Exception("present cannot be called while a render target is active.");
  995. deprecations.draw(this);
  996. flushBatchedDraws();
  997. endPass(true);
  998. int w = getPixelWidth();
  999. int h = getPixelHeight();
  1000. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getInternalBackbufferFBO());
  1001. // Copy internal backbuffer to system backbuffer. When MSAA is used this
  1002. // is a direct MSAA resolve.
  1003. if (internalBackbuffer.get())
  1004. {
  1005. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, getSystemBackbufferFBO());
  1006. // Discard system backbuffer to prevent it from copying its contents
  1007. // from VRAM to chip memory.
  1008. discard(OpenGL::FRAMEBUFFER_DRAW, {true}, true);
  1009. // updateBackbuffer checks for glBlitFramebuffer support.
  1010. if (GLAD_APPLE_framebuffer_multisample && internalBackbuffer->getMSAA() > 1)
  1011. glResolveMultisampleFramebufferAPPLE();
  1012. else
  1013. glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  1014. // Discarding the internal backbuffer directly after resolving it should
  1015. // eliminate any copy back to vram it might need to do.
  1016. discard(OpenGL::FRAMEBUFFER_READ, {true}, false);
  1017. }
  1018. if (!pendingScreenshotCallbacks.empty())
  1019. {
  1020. size_t row = 4 * w;
  1021. size_t size = row * h;
  1022. GLubyte *pixels = nullptr;
  1023. GLubyte *screenshot = nullptr;
  1024. try
  1025. {
  1026. pixels = new GLubyte[size];
  1027. screenshot = new GLubyte[size];
  1028. }
  1029. catch (std::exception &)
  1030. {
  1031. delete[] pixels;
  1032. delete[] screenshot;
  1033. throw love::Exception("Out of memory.");
  1034. }
  1035. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getSystemBackbufferFBO());
  1036. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  1037. // Replace alpha values with full opacity.
  1038. for (size_t i = 3; i < size; i += 4)
  1039. pixels[i] = 255;
  1040. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  1041. GLubyte *src = pixels - row;
  1042. GLubyte *dst = screenshot + size;
  1043. for (int i = 0; i < h; ++i)
  1044. memcpy(dst-=row, src+=row, row);
  1045. delete[] pixels;
  1046. auto imagemodule = Module::getInstance<love::image::Image>(M_IMAGE);
  1047. for (int i = 0; i < (int) pendingScreenshotCallbacks.size(); i++)
  1048. {
  1049. const auto &info = pendingScreenshotCallbacks[i];
  1050. image::ImageData *img = nullptr;
  1051. try
  1052. {
  1053. img = imagemodule->newImageData(w, h, PIXELFORMAT_RGBA8_UNORM, screenshot);
  1054. }
  1055. catch (love::Exception &)
  1056. {
  1057. delete[] screenshot;
  1058. info.callback(&info, nullptr, nullptr);
  1059. for (int j = i + 1; j < (int) pendingScreenshotCallbacks.size(); j++)
  1060. {
  1061. const auto &ninfo = pendingScreenshotCallbacks[j];
  1062. ninfo.callback(&ninfo, nullptr, nullptr);
  1063. }
  1064. pendingScreenshotCallbacks.clear();
  1065. throw;
  1066. }
  1067. info.callback(&info, img, screenshotCallbackData);
  1068. img->release();
  1069. }
  1070. delete[] screenshot;
  1071. pendingScreenshotCallbacks.clear();
  1072. }
  1073. #ifdef LOVE_IOS
  1074. // Hack: SDL's color renderbuffer must be bound when swapBuffers is called.
  1075. SDL_SysWMinfo info = {};
  1076. SDL_VERSION(&info.version);
  1077. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  1078. glBindRenderbuffer(GL_RENDERBUFFER, info.info.uikit.colorbuffer);
  1079. #endif
  1080. for (StreamBuffer *buffer : batchedDrawState.vb)
  1081. buffer->nextFrame();
  1082. batchedDrawState.indexBuffer->nextFrame();
  1083. auto window = getInstance<love::window::Window>(M_WINDOW);
  1084. if (window != nullptr)
  1085. window->swapBuffers();
  1086. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getInternalBackbufferFBO());
  1087. // Reset the per-frame stat counts.
  1088. drawCalls = 0;
  1089. gl.stats.shaderSwitches = 0;
  1090. renderTargetSwitchCount = 0;
  1091. drawCallsBatched = 0;
  1092. updatePendingReadbacks();
  1093. updateTemporaryResources();
  1094. }
  1095. int Graphics::getRequestedBackbufferMSAA() const
  1096. {
  1097. return requestedBackbufferMSAA;
  1098. }
  1099. int Graphics::getBackbufferMSAA() const
  1100. {
  1101. return internalBackbuffer.get() ? internalBackbuffer->getMSAA() : 0;
  1102. }
  1103. void Graphics::setScissor(const Rect &rect)
  1104. {
  1105. flushBatchedDraws();
  1106. DisplayState &state = states.back();
  1107. if (!gl.isStateEnabled(OpenGL::ENABLE_SCISSOR_TEST))
  1108. gl.setEnableState(OpenGL::ENABLE_SCISSOR_TEST, true);
  1109. double dpiscale = getCurrentDPIScale();
  1110. Rect glrect;
  1111. glrect.x = (int) (rect.x * dpiscale);
  1112. glrect.y = (int) (rect.y * dpiscale);
  1113. glrect.w = (int) (rect.w * dpiscale);
  1114. glrect.h = (int) (rect.h * dpiscale);
  1115. // OpenGL's reversed y-coordinate is compensated for in OpenGL::setScissor.
  1116. gl.setScissor(glrect, isRenderTargetActive());
  1117. state.scissor = true;
  1118. state.scissorRect = rect;
  1119. }
  1120. void Graphics::setScissor()
  1121. {
  1122. if (states.back().scissor)
  1123. flushBatchedDraws();
  1124. states.back().scissor = false;
  1125. if (gl.isStateEnabled(OpenGL::ENABLE_SCISSOR_TEST))
  1126. gl.setEnableState(OpenGL::ENABLE_SCISSOR_TEST, false);
  1127. }
  1128. void Graphics::setStencilState(const StencilState &s)
  1129. {
  1130. validateStencilState(s);
  1131. flushBatchedDraws();
  1132. bool enablestencil = s.action != STENCIL_KEEP || s.compare != COMPARE_ALWAYS;
  1133. if (enablestencil != gl.isStateEnabled(OpenGL::ENABLE_STENCIL_TEST))
  1134. gl.setEnableState(OpenGL::ENABLE_STENCIL_TEST, enablestencil);
  1135. GLenum glaction = GL_KEEP;
  1136. switch (s.action)
  1137. {
  1138. case STENCIL_KEEP:
  1139. glaction = GL_KEEP;
  1140. break;
  1141. case STENCIL_ZERO:
  1142. glaction = GL_ZERO;
  1143. break;
  1144. case STENCIL_REPLACE:
  1145. glaction = GL_REPLACE;
  1146. break;
  1147. case STENCIL_INCREMENT:
  1148. glaction = GL_INCR;
  1149. break;
  1150. case STENCIL_DECREMENT:
  1151. glaction = GL_DECR;
  1152. break;
  1153. case STENCIL_INCREMENT_WRAP:
  1154. glaction = GL_INCR_WRAP;
  1155. break;
  1156. case STENCIL_DECREMENT_WRAP:
  1157. glaction = GL_DECR_WRAP;
  1158. break;
  1159. case STENCIL_INVERT:
  1160. glaction = GL_INVERT;
  1161. break;
  1162. case STENCIL_MAX_ENUM:
  1163. glaction = GL_KEEP;
  1164. break;
  1165. }
  1166. /**
  1167. * GPUs do the comparison opposite to what makes sense for love's API. For
  1168. * example, if the compare function is GREATER then the stencil test will
  1169. * pass if the reference value is greater than the value in the stencil
  1170. * buffer. With our API it's more intuitive to assume that
  1171. * setStencilState(STENCIL_KEEP, COMPARE_GREATER, 4) will make it pass if the
  1172. * stencil buffer has a value greater than 4.
  1173. **/
  1174. GLenum glcompare = OpenGL::getGLCompareMode(getReversedCompareMode(s.compare));
  1175. if (enablestencil)
  1176. {
  1177. glStencilFunc(glcompare, s.value, s.readMask);
  1178. glStencilOp(GL_KEEP, GL_KEEP, glaction);
  1179. }
  1180. if (s.writeMask != gl.getStencilWriteMask())
  1181. gl.setStencilWriteMask(s.writeMask);
  1182. states.back().stencil = s;
  1183. }
  1184. void Graphics::setDepthMode(CompareMode compare, bool write)
  1185. {
  1186. validateDepthState(write);
  1187. DisplayState &state = states.back();
  1188. if (state.depthTest != compare || state.depthWrite != write)
  1189. flushBatchedDraws();
  1190. state.depthTest = compare;
  1191. state.depthWrite = write;
  1192. bool depthenable = compare != COMPARE_ALWAYS || write;
  1193. if (depthenable != gl.isStateEnabled(OpenGL::ENABLE_DEPTH_TEST))
  1194. gl.setEnableState(OpenGL::ENABLE_DEPTH_TEST, depthenable);
  1195. if (depthenable)
  1196. {
  1197. glDepthFunc(OpenGL::getGLCompareMode(compare));
  1198. gl.setDepthWrites(write);
  1199. }
  1200. }
  1201. void Graphics::setFrontFaceWinding(Winding winding)
  1202. {
  1203. DisplayState &state = states.back();
  1204. if (state.winding != winding)
  1205. flushBatchedDraws();
  1206. state.winding = winding;
  1207. if (isRenderTargetActive())
  1208. winding = winding == WINDING_CW ? WINDING_CCW : WINDING_CW;
  1209. glFrontFace(winding == WINDING_CW ? GL_CW : GL_CCW);
  1210. }
  1211. void Graphics::setColor(Colorf c)
  1212. {
  1213. c.r = std::min(std::max(c.r, 0.0f), 1.0f);
  1214. c.g = std::min(std::max(c.g, 0.0f), 1.0f);
  1215. c.b = std::min(std::max(c.b, 0.0f), 1.0f);
  1216. c.a = std::min(std::max(c.a, 0.0f), 1.0f);
  1217. states.back().color = c;
  1218. }
  1219. void Graphics::setColorMask(ColorChannelMask mask)
  1220. {
  1221. flushBatchedDraws();
  1222. uint32 maskbits =
  1223. ((mask.r ? 1 : 0) << 0) | ((mask.g ? 1 : 0) << 1) |
  1224. ((mask.b ? 1 : 0) << 2) | ((mask.a ? 1 : 0) << 3);
  1225. gl.setColorWriteMask(maskbits);
  1226. states.back().colorMask = mask;
  1227. }
  1228. void Graphics::setBlendState(const BlendState &blend)
  1229. {
  1230. if (!(blend == states.back().blend))
  1231. flushBatchedDraws();
  1232. if (blend.operationRGB == BLENDOP_MAX || blend.operationA == BLENDOP_MAX
  1233. || blend.operationRGB == BLENDOP_MIN || blend.operationA == BLENDOP_MIN)
  1234. {
  1235. if (!capabilities.features[FEATURE_BLEND_MINMAX])
  1236. throw love::Exception("The 'min' and 'max' blend operations are not supported on this system.");
  1237. }
  1238. if (blend.enable != gl.isStateEnabled(OpenGL::ENABLE_BLEND))
  1239. gl.setEnableState(OpenGL::ENABLE_BLEND, blend.enable);
  1240. if (blend.enable)
  1241. {
  1242. GLenum opRGB = getGLBlendOperation(blend.operationRGB);
  1243. GLenum opA = getGLBlendOperation(blend.operationA);
  1244. GLenum srcRGB = getGLBlendFactor(blend.srcFactorRGB);
  1245. GLenum srcA = getGLBlendFactor(blend.srcFactorA);
  1246. GLenum dstRGB = getGLBlendFactor(blend.dstFactorRGB);
  1247. GLenum dstA = getGLBlendFactor(blend.dstFactorA);
  1248. glBlendEquationSeparate(opRGB, opA);
  1249. glBlendFuncSeparate(srcRGB, dstRGB, srcA, dstA);
  1250. }
  1251. states.back().blend = blend;
  1252. }
  1253. void Graphics::setPointSize(float size)
  1254. {
  1255. if (size != states.back().pointSize)
  1256. flushBatchedDraws();
  1257. states.back().pointSize = size;
  1258. }
  1259. void Graphics::setWireframe(bool enable)
  1260. {
  1261. // Not supported in OpenGL ES.
  1262. if (GLAD_ES_VERSION_2_0)
  1263. return;
  1264. flushBatchedDraws();
  1265. glPolygonMode(GL_FRONT_AND_BACK, enable ? GL_LINE : GL_FILL);
  1266. states.back().wireframe = enable;
  1267. }
  1268. void *Graphics::getBufferMapMemory(size_t size)
  1269. {
  1270. // We don't need anything more complicated because get/release calls are
  1271. // never interleaved (as of when this comment was written.)
  1272. if (bufferMapMemory == nullptr || size > bufferMapMemorySize)
  1273. return malloc(size);
  1274. return bufferMapMemory;
  1275. }
  1276. void Graphics::releaseBufferMapMemory(void *mem)
  1277. {
  1278. if (mem != bufferMapMemory)
  1279. free(mem);
  1280. }
  1281. Renderer Graphics::getRenderer() const
  1282. {
  1283. return RENDERER_OPENGL;
  1284. }
  1285. bool Graphics::usesGLSLES() const
  1286. {
  1287. return GLAD_ES_VERSION_2_0;
  1288. }
  1289. Graphics::RendererInfo Graphics::getRendererInfo() const
  1290. {
  1291. RendererInfo info;
  1292. if (GLAD_ES_VERSION_2_0)
  1293. info.name = "OpenGL ES";
  1294. else
  1295. info.name = "OpenGL";
  1296. const char *str = (const char *) glGetString(GL_VERSION);
  1297. if (str)
  1298. info.version = str;
  1299. else
  1300. throw love::Exception("Cannot retrieve renderer version information.");
  1301. str = (const char *) glGetString(GL_VENDOR);
  1302. if (str)
  1303. info.vendor = str;
  1304. else
  1305. throw love::Exception("Cannot retrieve renderer vendor information.");
  1306. str = (const char *) glGetString(GL_RENDERER);
  1307. if (str)
  1308. info.device = str;
  1309. else
  1310. throw love::Exception("Cannot retrieve renderer device information.");
  1311. return info;
  1312. }
  1313. void Graphics::getAPIStats(int &shaderswitches) const
  1314. {
  1315. shaderswitches = gl.stats.shaderSwitches;
  1316. }
  1317. void Graphics::initCapabilities()
  1318. {
  1319. capabilities.features[FEATURE_MULTI_RENDER_TARGET_FORMATS] = gl.isMultiFormatMRTSupported();
  1320. capabilities.features[FEATURE_CLAMP_ZERO] = gl.isClampZeroOneTextureWrapSupported();
  1321. capabilities.features[FEATURE_CLAMP_ONE] = gl.isClampZeroOneTextureWrapSupported();
  1322. capabilities.features[FEATURE_BLEND_MINMAX] = GLAD_VERSION_1_4 || GLAD_ES_VERSION_3_0 || GLAD_EXT_blend_minmax;
  1323. capabilities.features[FEATURE_LIGHTEN] = capabilities.features[FEATURE_BLEND_MINMAX];
  1324. capabilities.features[FEATURE_FULL_NPOT] = GLAD_VERSION_2_0 || GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot;
  1325. capabilities.features[FEATURE_PIXEL_SHADER_HIGHP] = gl.isPixelShaderHighpSupported();
  1326. capabilities.features[FEATURE_SHADER_DERIVATIVES] = GLAD_VERSION_2_0 || GLAD_ES_VERSION_3_0 || GLAD_OES_standard_derivatives;
  1327. capabilities.features[FEATURE_GLSL3] = GLAD_ES_VERSION_3_0 || gl.isCoreProfile();
  1328. capabilities.features[FEATURE_GLSL4] = GLAD_ES_VERSION_3_1 || (gl.isCoreProfile() && GLAD_VERSION_4_3);
  1329. capabilities.features[FEATURE_INSTANCING] = gl.isInstancingSupported();
  1330. capabilities.features[FEATURE_TEXEL_BUFFER] = gl.isBufferUsageSupported(BUFFERUSAGE_TEXEL);
  1331. capabilities.features[FEATURE_INDEX_BUFFER_32BIT] = GLAD_VERSION_1_1 || GLAD_ES_VERSION_3_0 || GLAD_OES_element_index_uint;
  1332. capabilities.features[FEATURE_COPY_BUFFER] = gl.isCopyBufferSupported();
  1333. capabilities.features[FEATURE_COPY_BUFFER_TO_TEXTURE] = gl.isCopyBufferToTextureSupported();
  1334. capabilities.features[FEATURE_COPY_TEXTURE_TO_BUFFER] = gl.isCopyTextureToBufferSupported();
  1335. capabilities.features[FEATURE_COPY_RENDER_TARGET_TO_BUFFER] = gl.isCopyRenderTargetToBufferSupported();
  1336. capabilities.features[FEATURE_MIPMAP_RANGE] = GLAD_VERSION_1_2 || GLAD_ES_VERSION_3_0;
  1337. capabilities.features[FEATURE_INDIRECT_DRAW] = capabilities.features[FEATURE_GLSL4];
  1338. static_assert(FEATURE_MAX_ENUM == 19, "Graphics::initCapabilities must be updated when adding a new graphics feature!");
  1339. capabilities.limits[LIMIT_POINT_SIZE] = gl.getMaxPointSize();
  1340. capabilities.limits[LIMIT_TEXTURE_SIZE] = gl.getMax2DTextureSize();
  1341. capabilities.limits[LIMIT_TEXTURE_LAYERS] = gl.getMaxTextureLayers();
  1342. capabilities.limits[LIMIT_VOLUME_TEXTURE_SIZE] = gl.getMax3DTextureSize();
  1343. capabilities.limits[LIMIT_CUBE_TEXTURE_SIZE] = gl.getMaxCubeTextureSize();
  1344. capabilities.limits[LIMIT_TEXEL_BUFFER_SIZE] = gl.getMaxTexelBufferSize();
  1345. capabilities.limits[LIMIT_SHADER_STORAGE_BUFFER_SIZE] = gl.getMaxShaderStorageBufferSize();
  1346. capabilities.limits[LIMIT_THREADGROUPS_X] = gl.getMaxComputeWorkGroupsX();
  1347. capabilities.limits[LIMIT_THREADGROUPS_Y] = gl.getMaxComputeWorkGroupsY();
  1348. capabilities.limits[LIMIT_THREADGROUPS_Z] = gl.getMaxComputeWorkGroupsZ();
  1349. capabilities.limits[LIMIT_RENDER_TARGETS] = gl.getMaxRenderTargets();
  1350. capabilities.limits[LIMIT_TEXTURE_MSAA] = gl.getMaxSamples();
  1351. capabilities.limits[LIMIT_ANISOTROPY] = gl.getMaxAnisotropy();
  1352. static_assert(LIMIT_MAX_ENUM == 13, "Graphics::initCapabilities must be updated when adding a new system limit!");
  1353. for (int i = 0; i < TEXTURE_MAX_ENUM; i++)
  1354. capabilities.textureTypes[i] = gl.isTextureTypeSupported((TextureType) i);
  1355. for (int i = 0; i < PIXELFORMAT_MAX_ENUM; i++)
  1356. {
  1357. auto format = (PixelFormat) i;
  1358. pixelFormatUsage[i][0] = computePixelFormatUsage(format, false);
  1359. pixelFormatUsage[i][1] = computePixelFormatUsage(format, true);
  1360. }
  1361. #ifdef LOVE_ANDROID
  1362. // This can't be done in initContext with the rest of the bug checks because
  1363. // isPixelFormatSupported relies on state initialized here / after init.
  1364. if (GLAD_ES_VERSION_3_0 && !isPixelFormatSupported(PIXELFORMAT_R8_UNORM, PIXELFORMATUSAGEFLAGS_SAMPLE | PIXELFORMATUSAGEFLAGS_RENDERTARGET))
  1365. {
  1366. gl.bugs.brokenR8PixelFormat = true;
  1367. pixelFormatUsage[PIXELFORMAT_R8_UNORM][0] = computePixelFormatUsage(PIXELFORMAT_R8_UNORM, false);
  1368. pixelFormatUsage[PIXELFORMAT_R8_UNORM][1] = computePixelFormatUsage(PIXELFORMAT_R8_UNORM, true);
  1369. }
  1370. #endif
  1371. }
  1372. uint32 Graphics::computePixelFormatUsage(PixelFormat format, bool readable)
  1373. {
  1374. uint32 usage = OpenGL::getPixelFormatUsageFlags(format);
  1375. if (readable && (usage & PIXELFORMATUSAGEFLAGS_SAMPLE) == 0)
  1376. return 0;
  1377. // Even though we might have the necessary OpenGL version or extension,
  1378. // drivers are still allowed to throw FRAMEBUFFER_UNSUPPORTED when attaching
  1379. // a texture to a FBO whose format the driver doesn't like. So we should
  1380. // test with an actual FBO.
  1381. // Avoid the test for depth/stencil formats - not every GL version
  1382. // guarantees support for depth/stencil-only render targets (which we would
  1383. // need for the test below to work), and we already do some finagling in
  1384. // convertPixelFormat to try to use the best-supported internal
  1385. // depth/stencil format for a particular driver.
  1386. if ((usage & PIXELFORMATUSAGEFLAGS_RENDERTARGET) != 0 && !isPixelFormatDepthStencil(format))
  1387. {
  1388. GLuint texture = 0;
  1389. GLuint renderbuffer = 0;
  1390. OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(format, !readable);
  1391. GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
  1392. GLuint fbo = 0;
  1393. glGenFramebuffers(1, &fbo);
  1394. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  1395. // Make sure at least something is bound to a color attachment. I believe
  1396. // this is required on ES2 but I'm not positive.
  1397. if (isPixelFormatDepthStencil(format))
  1398. {
  1399. love::graphics::Texture *tex = getDefaultTexture(TEXTURE_2D, DATA_BASETYPE_FLOAT);
  1400. gl.framebufferTexture(GL_COLOR_ATTACHMENT0, TEXTURE_2D, (GLuint) tex->getHandle(), 0, 0, 0);
  1401. }
  1402. if (readable)
  1403. {
  1404. glGenTextures(1, &texture);
  1405. gl.bindTextureToUnit(TEXTURE_2D, texture, 0, false);
  1406. SamplerState s;
  1407. s.minFilter = s.magFilter = SamplerState::FILTER_NEAREST;
  1408. gl.setSamplerState(TEXTURE_2D, s);
  1409. gl.rawTexStorage(TEXTURE_2D, 1, format, 1, 1);
  1410. }
  1411. else
  1412. {
  1413. glGenRenderbuffers(1, &renderbuffer);
  1414. glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
  1415. glRenderbufferStorage(GL_RENDERBUFFER, fmt.internalformat, 1, 1);
  1416. }
  1417. for (GLenum attachment : fmt.framebufferAttachments)
  1418. {
  1419. if (attachment == GL_NONE)
  1420. continue;
  1421. if (readable)
  1422. gl.framebufferTexture(attachment, TEXTURE_2D, texture, 0, 0, 0);
  1423. else
  1424. glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, renderbuffer);
  1425. }
  1426. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
  1427. usage &= ~PIXELFORMATUSAGEFLAGS_RENDERTARGET;
  1428. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
  1429. gl.deleteFramebuffer(fbo);
  1430. if (texture != 0)
  1431. gl.deleteTexture(texture);
  1432. if (renderbuffer != 0)
  1433. glDeleteRenderbuffers(1, &renderbuffer);
  1434. }
  1435. return usage;
  1436. }
  1437. bool Graphics::isPixelFormatSupported(PixelFormat format, uint32 usage)
  1438. {
  1439. format = getSizedFormat(format);
  1440. bool readable = (usage & PIXELFORMATUSAGEFLAGS_SAMPLE) != 0;
  1441. return (usage & pixelFormatUsage[format][readable ? 1 : 0]) == usage;
  1442. }
  1443. } // opengl
  1444. } // graphics
  1445. } // love