Graphics.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  1. /**
  2. * Copyright (c) 2006-2018 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 "math/MathModule.h"
  28. #include "window/Window.h"
  29. #include "Buffer.h"
  30. #include "ShaderStage.h"
  31. #include "libraries/xxHash/xxhash.h"
  32. // C++
  33. #include <vector>
  34. #include <sstream>
  35. #include <algorithm>
  36. #include <iterator>
  37. // C
  38. #include <cmath>
  39. #include <cstdio>
  40. #ifdef LOVE_IOS
  41. #include <SDL_syswm.h>
  42. #endif
  43. namespace love
  44. {
  45. namespace graphics
  46. {
  47. namespace opengl
  48. {
  49. Graphics::Graphics()
  50. : windowHasStencil(false)
  51. , mainVAO(0)
  52. {
  53. gl = OpenGL();
  54. Canvas::resetFormatSupport();
  55. auto window = getInstance<love::window::Window>(M_WINDOW);
  56. if (window != nullptr)
  57. {
  58. window->setGraphics(this);
  59. if (window->isOpen())
  60. {
  61. int w, h;
  62. love::window::WindowSettings settings;
  63. window->getWindow(w, h, settings);
  64. double dpiW = w;
  65. double dpiH = h;
  66. window->windowToDPICoords(&dpiW, &dpiH);
  67. setMode((int) dpiW, (int) dpiH, window->getPixelWidth(), window->getPixelHeight(), settings.stencil);
  68. }
  69. }
  70. }
  71. Graphics::~Graphics()
  72. {
  73. }
  74. const char *Graphics::getName() const
  75. {
  76. return "love.graphics.opengl";
  77. }
  78. love::graphics::StreamBuffer *Graphics::newStreamBuffer(BufferType type, size_t size)
  79. {
  80. return CreateStreamBuffer(type, size);
  81. }
  82. love::graphics::Image *Graphics::newImage(const Image::Slices &data, const Image::Settings &settings)
  83. {
  84. return new Image(data, settings);
  85. }
  86. love::graphics::Image *Graphics::newImage(TextureType textype, PixelFormat format, int width, int height, int slices, const Image::Settings &settings)
  87. {
  88. return new Image(textype, format, width, height, slices, settings);
  89. }
  90. love::graphics::Canvas *Graphics::newCanvas(const Canvas::Settings &settings)
  91. {
  92. return new Canvas(settings);
  93. }
  94. love::graphics::ShaderStage *Graphics::newShaderStageInternal(ShaderStage::StageType stage, const std::string &cachekey, const std::string &source, bool gles)
  95. {
  96. return new ShaderStage(this, stage, source, gles, cachekey);
  97. }
  98. love::graphics::Shader *Graphics::newShaderInternal(love::graphics::ShaderStage *vertex, love::graphics::ShaderStage *pixel)
  99. {
  100. return new Shader(vertex, pixel);
  101. }
  102. love::graphics::Buffer *Graphics::newBuffer(size_t size, const void *data, BufferType type, vertex::Usage usage, uint32 mapflags)
  103. {
  104. return new Buffer(size, data, type, usage, mapflags);
  105. }
  106. void Graphics::setViewportSize(int width, int height, int pixelwidth, int pixelheight)
  107. {
  108. this->width = width;
  109. this->height = height;
  110. this->pixelWidth = pixelwidth;
  111. this->pixelHeight = pixelheight;
  112. if (!isCanvasActive())
  113. {
  114. // Set the viewport to top-left corner.
  115. gl.setViewport({0, 0, pixelwidth, pixelheight});
  116. // Re-apply the scissor if it was active, since the rectangle passed to
  117. // glScissor is affected by the viewport dimensions.
  118. if (states.back().scissor)
  119. setScissor(states.back().scissorRect);
  120. // Set up the projection matrix
  121. projectionMatrix = Matrix4::ortho(0.0, (float) width, (float) height, 0.0, -10.0f, 10.0f);
  122. }
  123. }
  124. bool Graphics::setMode(int width, int height, int pixelwidth, int pixelheight, bool windowhasstencil)
  125. {
  126. this->width = width;
  127. this->height = height;
  128. this->windowHasStencil = windowhasstencil;
  129. // Okay, setup OpenGL.
  130. gl.initContext();
  131. if (gl.isCoreProfile())
  132. {
  133. glGenVertexArrays(1, &mainVAO);
  134. glBindVertexArray(mainVAO);
  135. }
  136. gl.setupContext();
  137. created = true;
  138. initCapabilities();
  139. setViewportSize(width, height, pixelwidth, pixelheight);
  140. // Enable blending
  141. glEnable(GL_BLEND);
  142. // Auto-generated mipmaps should be the best quality possible
  143. if (!gl.isCoreProfile())
  144. glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
  145. if (!GLAD_ES_VERSION_2_0 && !gl.isCoreProfile())
  146. {
  147. // Make sure antialiasing works when set elsewhere
  148. glEnable(GL_MULTISAMPLE);
  149. // Enable texturing
  150. glEnable(GL_TEXTURE_2D);
  151. }
  152. gl.setTextureUnit(0);
  153. // Set pixel row alignment
  154. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  155. // Always enable seamless cubemap filtering when possible.
  156. if (GLAD_VERSION_3_2 || GLAD_ARB_seamless_cube_map)
  157. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  158. // Set whether drawing converts input from linear -> sRGB colorspace.
  159. if (GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_sRGB || GLAD_EXT_framebuffer_sRGB
  160. || GLAD_ES_VERSION_3_0 || GLAD_EXT_sRGB)
  161. {
  162. if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
  163. gl.setEnableState(OpenGL::ENABLE_FRAMEBUFFER_SRGB, isGammaCorrect());
  164. }
  165. else
  166. setGammaCorrect(false);
  167. setDebug(isDebugEnabled());
  168. if (streamBufferState.vb[0] == nullptr)
  169. {
  170. // Initial sizes that should be good enough for most cases. It will
  171. // resize to fit if needed, later.
  172. streamBufferState.vb[0] = CreateStreamBuffer(BUFFER_VERTEX, 1024 * 1024 * 1);
  173. streamBufferState.vb[1] = CreateStreamBuffer(BUFFER_VERTEX, 256 * 1024 * 1);
  174. streamBufferState.indexBuffer = CreateStreamBuffer(BUFFER_INDEX, sizeof(uint16) * LOVE_UINT16_MAX);
  175. }
  176. // Reload all volatile objects.
  177. if (!Volatile::loadAll())
  178. ::printf("Could not reload all volatile objects.\n");
  179. createQuadIndexBuffer();
  180. // Restore the graphics state.
  181. restoreState(states.back());
  182. int gammacorrect = isGammaCorrect() ? 1 : 0;
  183. Shader::Language target = getShaderLanguageTarget();
  184. // We always need a default shader.
  185. for (int i = 0; i < Shader::STANDARD_MAX_ENUM; i++)
  186. {
  187. if (i == Shader::STANDARD_ARRAY && !capabilities.textureTypes[TEXTURE_2D_ARRAY])
  188. continue;
  189. // Apparently some intel GMA drivers on windows fail to compile shaders
  190. // which use array textures despite claiming support for the extension.
  191. try
  192. {
  193. if (!Shader::standardShaders[i])
  194. {
  195. const auto &code = defaultShaderCode[i][target][gammacorrect];
  196. Shader::standardShaders[i] = love::graphics::Graphics::newShader(code.source[ShaderStage::STAGE_VERTEX], code.source[ShaderStage::STAGE_PIXEL]);
  197. }
  198. }
  199. catch (love::Exception &)
  200. {
  201. if (i == Shader::STANDARD_ARRAY)
  202. capabilities.textureTypes[TEXTURE_2D_ARRAY] = false;
  203. else
  204. throw;
  205. }
  206. }
  207. // A shader should always be active, but the default shader shouldn't be
  208. // returned by getShader(), so we don't do setShader(defaultShader).
  209. if (!Shader::current)
  210. Shader::standardShaders[Shader::STANDARD_DEFAULT]->attach();
  211. return true;
  212. }
  213. void Graphics::unSetMode()
  214. {
  215. if (!isCreated())
  216. return;
  217. flushStreamDraws();
  218. // Unload all volatile objects. These must be reloaded after the display
  219. // mode change.
  220. Volatile::unloadAll();
  221. for (const auto &pair : framebufferObjects)
  222. gl.deleteFramebuffer(pair.second);
  223. for (auto temp : temporaryCanvases)
  224. temp.canvas->release();
  225. framebufferObjects.clear();
  226. temporaryCanvases.clear();
  227. if (mainVAO != 0)
  228. {
  229. glDeleteVertexArrays(1, &mainVAO);
  230. mainVAO = 0;
  231. }
  232. gl.deInitContext();
  233. created = false;
  234. }
  235. void Graphics::setActive(bool enable)
  236. {
  237. flushStreamDraws();
  238. // Make sure all pending OpenGL commands have fully executed before
  239. // returning, when going from active to inactive. This is required on iOS.
  240. if (isCreated() && this->active && !enable)
  241. glFinish();
  242. active = enable;
  243. }
  244. void Graphics::draw(const DrawCommand &cmd)
  245. {
  246. gl.prepareDraw();
  247. gl.setVertexAttributes(*cmd.attributes, *cmd.buffers);
  248. gl.bindTextureToUnit(cmd.texture, 0, false);
  249. gl.setCullMode(cmd.cullMode);
  250. GLenum glprimitivetype = OpenGL::getGLPrimitiveType(cmd.primitiveType);
  251. if (cmd.instanceCount > 1)
  252. glDrawArraysInstanced(glprimitivetype, cmd.vertexStart, cmd.vertexCount, cmd.instanceCount);
  253. else
  254. glDrawArrays(glprimitivetype, cmd.vertexStart, cmd.vertexCount);
  255. ++drawCalls;
  256. }
  257. void Graphics::draw(const DrawIndexedCommand &cmd)
  258. {
  259. gl.prepareDraw();
  260. gl.setVertexAttributes(*cmd.attributes, *cmd.buffers);
  261. gl.bindTextureToUnit(cmd.texture, 0, false);
  262. gl.setCullMode(cmd.cullMode);
  263. const void *gloffset = BUFFER_OFFSET(cmd.indexBufferOffset);
  264. GLenum glprimitivetype = OpenGL::getGLPrimitiveType(cmd.primitiveType);
  265. GLenum gldatatype = OpenGL::getGLIndexDataType(cmd.indexType);
  266. gl.bindBuffer(BUFFER_INDEX, cmd.indexBuffer->getHandle());
  267. if (cmd.instanceCount > 1)
  268. glDrawElementsInstanced(glprimitivetype, cmd.indexCount, gldatatype, gloffset, cmd.instanceCount);
  269. else
  270. glDrawElements(glprimitivetype, cmd.indexCount, gldatatype, gloffset);
  271. ++drawCalls;
  272. }
  273. static inline void advanceVertexOffsets(const vertex::Attributes &attributes, vertex::Buffers &buffers, int vertexcount)
  274. {
  275. // TODO: Figure out a better way to avoid touching the same buffer multiple
  276. // times, if multiple attributes share the buffer.
  277. uint32 touchedbuffers = 0;
  278. for (unsigned int i = 0; i < vertex::Attributes::MAX; i++)
  279. {
  280. if (!attributes.isEnabled(i))
  281. continue;
  282. auto &attrib = attributes.attribs[i];
  283. uint32 bufferbit = 1u << attrib.bufferindex;
  284. if ((touchedbuffers & bufferbit) == 0)
  285. {
  286. touchedbuffers |= bufferbit;
  287. buffers.info[attrib.bufferindex].offset += attrib.stride * vertexcount;
  288. }
  289. }
  290. }
  291. void Graphics::drawQuads(int start, int count, const vertex::Attributes &attributes, const vertex::Buffers &buffers, love::graphics::Texture *texture)
  292. {
  293. const int MAX_VERTICES_PER_DRAW = LOVE_UINT16_MAX;
  294. const int MAX_QUADS_PER_DRAW = MAX_VERTICES_PER_DRAW / 4;
  295. gl.prepareDraw();
  296. gl.bindTextureToUnit(texture, 0, false);
  297. gl.setCullMode(CULL_NONE);
  298. gl.bindBuffer(BUFFER_INDEX, quadIndexBuffer->getHandle());
  299. if (gl.isBaseVertexSupported())
  300. {
  301. gl.setVertexAttributes(attributes, buffers);
  302. int basevertex = start * 4;
  303. for (int quadindex = 0; quadindex < count; quadindex += MAX_QUADS_PER_DRAW)
  304. {
  305. int quadcount = std::min(MAX_QUADS_PER_DRAW, count - quadindex);
  306. glDrawElementsBaseVertex(GL_TRIANGLES, quadcount * 6, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0), basevertex);
  307. ++drawCalls;
  308. basevertex += quadcount * 4;
  309. }
  310. }
  311. else
  312. {
  313. vertex::Buffers bufferscopy = buffers;
  314. if (start > 0)
  315. advanceVertexOffsets(attributes, bufferscopy, start * 4);
  316. for (int quadindex = 0; quadindex < count; quadindex += MAX_QUADS_PER_DRAW)
  317. {
  318. gl.setVertexAttributes(attributes, bufferscopy);
  319. int quadcount = std::min(MAX_QUADS_PER_DRAW, count - quadindex);
  320. glDrawElements(GL_TRIANGLES, quadcount * 6, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));
  321. ++drawCalls;
  322. if (count > MAX_QUADS_PER_DRAW)
  323. advanceVertexOffsets(attributes, bufferscopy, quadcount * 4);
  324. }
  325. }
  326. }
  327. static void APIENTRY debugCB(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei /*len*/, const GLchar *msg, const GLvoid* /*usr*/)
  328. {
  329. // Human-readable strings for the debug info.
  330. const char *sourceStr = OpenGL::debugSourceString(source);
  331. const char *typeStr = OpenGL::debugTypeString(type);
  332. const char *severityStr = OpenGL::debugSeverityString(severity);
  333. const char *fmt = "OpenGL: %s [source=%s, type=%s, severity=%s, id=%d]\n";
  334. printf(fmt, msg, sourceStr, typeStr, severityStr, id);
  335. }
  336. void Graphics::setDebug(bool enable)
  337. {
  338. // Make sure debug output is supported. The AMD ext. is a bit different
  339. // so we don't make use of it, since AMD drivers now support KHR_debug.
  340. if (!(GLAD_VERSION_4_3 || GLAD_KHR_debug || GLAD_ARB_debug_output))
  341. return;
  342. // TODO: We don't support GL_KHR_debug in GLES yet.
  343. if (GLAD_ES_VERSION_2_0)
  344. return;
  345. // Ugly hack to reduce code duplication.
  346. if (GLAD_ARB_debug_output && !(GLAD_VERSION_4_3 || GLAD_KHR_debug))
  347. {
  348. fp_glDebugMessageCallback = (pfn_glDebugMessageCallback) fp_glDebugMessageCallbackARB;
  349. fp_glDebugMessageControl = (pfn_glDebugMessageControl) fp_glDebugMessageControlARB;
  350. }
  351. if (!enable)
  352. {
  353. // Disable the debug callback function.
  354. glDebugMessageCallback(nullptr, nullptr);
  355. // We can disable debug output entirely with KHR_debug.
  356. if (GLAD_VERSION_4_3 || GLAD_KHR_debug)
  357. glDisable(GL_DEBUG_OUTPUT);
  358. return;
  359. }
  360. // We don't want asynchronous debug output.
  361. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  362. glDebugMessageCallback(debugCB, nullptr);
  363. // Initially, enable everything.
  364. glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
  365. // Disable messages about deprecated OpenGL functionality.
  366. glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  367. glDebugMessageControl(GL_DEBUG_SOURCE_SHADER_COMPILER, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  368. if (GLAD_VERSION_4_3 || GLAD_KHR_debug)
  369. glEnable(GL_DEBUG_OUTPUT);
  370. ::printf("OpenGL debug output enabled (LOVE_GRAPHICS_DEBUG=1)\n");
  371. }
  372. void Graphics::setCanvasInternal(const RenderTargets &rts, int w, int h, int pixelw, int pixelh, bool hasSRGBcanvas)
  373. {
  374. const DisplayState &state = states.back();
  375. OpenGL::TempDebugGroup debuggroup("setCanvas");
  376. flushStreamDraws();
  377. endPass();
  378. bool iswindow = rts.getFirstTarget().canvas == nullptr;
  379. vertex::Winding vertexwinding = state.winding;
  380. if (iswindow)
  381. {
  382. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, gl.getDefaultFBO());
  383. // The projection matrix is flipped compared to rendering to a canvas, due
  384. // to OpenGL considering (0,0) bottom-left instead of top-left.
  385. projectionMatrix = Matrix4::ortho(0.0, (float) w, (float) h, 0.0, -10.0f, 10.0f);
  386. }
  387. else
  388. {
  389. bindCachedFBO(rts);
  390. projectionMatrix = Matrix4::ortho(0.0, (float) w, 0.0, (float) h, -10.0f, 10.0f);
  391. // Flip front face winding when rendering to a canvas, since our
  392. // projection matrix is flipped.
  393. vertexwinding = vertexwinding == vertex::WINDING_CW ? vertex::WINDING_CCW : vertex::WINDING_CW;
  394. }
  395. glFrontFace(vertexwinding == vertex::WINDING_CW ? GL_CW : GL_CCW);
  396. gl.setViewport({0, 0, pixelw, pixelh});
  397. // Re-apply the scissor if it was active, since the rectangle passed to
  398. // glScissor is affected by the viewport dimensions.
  399. if (state.scissor)
  400. setScissor(state.scissorRect);
  401. // Make sure the correct sRGB setting is used when drawing to the canvases.
  402. if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
  403. {
  404. if (hasSRGBcanvas != gl.isStateEnabled(OpenGL::ENABLE_FRAMEBUFFER_SRGB))
  405. gl.setEnableState(OpenGL::ENABLE_FRAMEBUFFER_SRGB, hasSRGBcanvas);
  406. }
  407. }
  408. void Graphics::endPass()
  409. {
  410. auto &rts = states.back().renderTargets;
  411. love::graphics::Canvas *depthstencil = rts.depthStencil.canvas.get();
  412. // Discard the depth/stencil buffer if we're using an internal cached one.
  413. if (depthstencil == nullptr && (rts.temporaryRTFlags & (TEMPORARY_RT_DEPTH | TEMPORARY_RT_STENCIL)) != 0)
  414. discard({}, true);
  415. // Resolve MSAA buffers. MSAA is only supported for 2D render targets so we
  416. // don't have to worry about resolving to slices.
  417. if (rts.colors.size() > 0 && rts.colors[0].canvas->getMSAA() > 1)
  418. {
  419. int mip = rts.colors[0].mipmap;
  420. int w = rts.colors[0].canvas->getPixelWidth(mip);
  421. int h = rts.colors[0].canvas->getPixelHeight(mip);
  422. for (int i = 0; i < (int) rts.colors.size(); i++)
  423. {
  424. Canvas *c = (Canvas *) rts.colors[i].canvas.get();
  425. if (!c->isReadable())
  426. continue;
  427. glReadBuffer(GL_COLOR_ATTACHMENT0 + i);
  428. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, c->getFBO());
  429. if (GLAD_APPLE_framebuffer_multisample)
  430. glResolveMultisampleFramebufferAPPLE();
  431. else
  432. glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  433. }
  434. }
  435. if (depthstencil != nullptr && depthstencil->getMSAA() > 1 && depthstencil->isReadable())
  436. {
  437. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, ((Canvas *) depthstencil)->getFBO());
  438. if (GLAD_APPLE_framebuffer_multisample)
  439. glResolveMultisampleFramebufferAPPLE();
  440. else
  441. {
  442. int mip = rts.depthStencil.mipmap;
  443. int w = depthstencil->getPixelWidth(mip);
  444. int h = depthstencil->getPixelHeight(mip);
  445. PixelFormat format = depthstencil->getPixelFormat();
  446. GLbitfield mask = 0;
  447. if (isPixelFormatDepth(format))
  448. mask |= GL_DEPTH_BUFFER_BIT;
  449. if (isPixelFormatStencil(format))
  450. mask |= GL_STENCIL_BUFFER_BIT;
  451. if (mask != 0)
  452. glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, mask, GL_NEAREST);
  453. }
  454. }
  455. for (const auto &rt : rts.colors)
  456. {
  457. if (rt.canvas->getMipmapMode() == Canvas::MIPMAPS_AUTO && rt.mipmap == 0)
  458. rt.canvas->generateMipmaps();
  459. }
  460. int dsmipmap = rts.depthStencil.mipmap;
  461. if (depthstencil != nullptr && depthstencil->getMipmapMode() == Canvas::MIPMAPS_AUTO && dsmipmap == 0)
  462. depthstencil->generateMipmaps();
  463. }
  464. void Graphics::clear(OptionalColorf c, OptionalInt stencil, OptionalDouble depth)
  465. {
  466. if (c.hasValue || stencil.hasValue || depth.hasValue)
  467. flushStreamDraws();
  468. GLbitfield flags = 0;
  469. if (c.hasValue)
  470. {
  471. gammaCorrectColor(c.value);
  472. glClearColor(c.value.r, c.value.g, c.value.b, c.value.a);
  473. flags |= GL_COLOR_BUFFER_BIT;
  474. }
  475. if (stencil.hasValue)
  476. {
  477. glClearStencil(stencil.value);
  478. flags |= GL_STENCIL_BUFFER_BIT;
  479. }
  480. bool hadDepthWrites = gl.hasDepthWrites();
  481. if (depth.hasValue)
  482. {
  483. if (!hadDepthWrites) // glDepthMask also affects glClear.
  484. gl.setDepthWrites(true);
  485. gl.clearDepth(depth.value);
  486. flags |= GL_DEPTH_BUFFER_BIT;
  487. }
  488. if (flags != 0)
  489. glClear(flags);
  490. if (depth.hasValue && !hadDepthWrites)
  491. gl.setDepthWrites(hadDepthWrites);
  492. if (c.hasValue && gl.bugs.clearRequiresDriverTextureStateUpdate && Shader::current)
  493. {
  494. // This seems to be enough to fix the bug for me. Other methods I've
  495. // tried (e.g. dummy draws) don't work in all cases.
  496. gl.useProgram(0);
  497. gl.useProgram((GLuint) Shader::current->getHandle());
  498. }
  499. }
  500. void Graphics::clear(const std::vector<OptionalColorf> &colors, OptionalInt stencil, OptionalDouble depth)
  501. {
  502. if (colors.size() == 0 && !stencil.hasValue && !depth.hasValue)
  503. return;
  504. int ncolorcanvases = (int) states.back().renderTargets.colors.size();
  505. int ncolors = (int) colors.size();
  506. if (ncolors <= 1 && ncolorcanvases <= 1)
  507. {
  508. clear(ncolors > 0 ? colors[0] : OptionalColorf(), stencil, depth);
  509. return;
  510. }
  511. flushStreamDraws();
  512. bool drawbuffersmodified = false;
  513. ncolors = std::min(ncolors, ncolorcanvases);
  514. for (int i = 0; i < ncolors; i++)
  515. {
  516. if (!colors[i].hasValue)
  517. continue;
  518. Colorf c = colors[i].value;
  519. gammaCorrectColor(c);
  520. if (GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0)
  521. {
  522. const GLfloat carray[] = {c.r, c.g, c.b, c.a};
  523. glClearBufferfv(GL_COLOR, i, carray);
  524. }
  525. else
  526. {
  527. glDrawBuffer(GL_COLOR_ATTACHMENT0 + i);
  528. glClearColor(c.r, c.g, c.b, c.a);
  529. glClear(GL_COLOR_BUFFER_BIT);
  530. drawbuffersmodified = true;
  531. }
  532. }
  533. // Revert to the expected draw buffers once we're done, if glClearBuffer
  534. // wasn't supported.
  535. if (drawbuffersmodified)
  536. {
  537. GLenum bufs[MAX_COLOR_RENDER_TARGETS];
  538. for (int i = 0; i < ncolorcanvases; i++)
  539. bufs[i] = GL_COLOR_ATTACHMENT0 + i;
  540. glDrawBuffers(ncolorcanvases, bufs);
  541. }
  542. GLbitfield flags = 0;
  543. if (stencil.hasValue)
  544. {
  545. glClearStencil(stencil.value);
  546. flags |= GL_STENCIL_BUFFER_BIT;
  547. }
  548. bool hadDepthWrites = gl.hasDepthWrites();
  549. if (depth.hasValue)
  550. {
  551. if (!hadDepthWrites) // glDepthMask also affects glClear.
  552. gl.setDepthWrites(true);
  553. gl.clearDepth(depth.value);
  554. flags |= GL_DEPTH_BUFFER_BIT;
  555. }
  556. if (flags != 0)
  557. glClear(flags);
  558. if (depth.hasValue && !hadDepthWrites)
  559. gl.setDepthWrites(hadDepthWrites);
  560. if (gl.bugs.clearRequiresDriverTextureStateUpdate && Shader::current)
  561. {
  562. // This seems to be enough to fix the bug for me. Other methods I've
  563. // tried (e.g. dummy draws) don't work in all cases.
  564. gl.useProgram(0);
  565. gl.useProgram((GLuint) Shader::current->getHandle());
  566. }
  567. }
  568. void Graphics::discard(const std::vector<bool> &colorbuffers, bool depthstencil)
  569. {
  570. flushStreamDraws();
  571. discard(OpenGL::FRAMEBUFFER_ALL, colorbuffers, depthstencil);
  572. }
  573. void Graphics::discard(OpenGL::FramebufferTarget target, const std::vector<bool> &colorbuffers, bool depthstencil)
  574. {
  575. if (!(GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0 || GLAD_EXT_discard_framebuffer))
  576. return;
  577. GLenum gltarget = GL_FRAMEBUFFER;
  578. if (target == OpenGL::FRAMEBUFFER_READ)
  579. gltarget = GL_READ_FRAMEBUFFER;
  580. else if (target == OpenGL::FRAMEBUFFER_DRAW)
  581. gltarget = GL_DRAW_FRAMEBUFFER;
  582. std::vector<GLenum> attachments;
  583. attachments.reserve(colorbuffers.size());
  584. // glDiscardFramebuffer uses different attachment enums for the default FBO.
  585. if (!isCanvasActive() && gl.getDefaultFBO() == 0)
  586. {
  587. if (colorbuffers.size() > 0 && colorbuffers[0])
  588. attachments.push_back(GL_COLOR);
  589. if (depthstencil)
  590. {
  591. attachments.push_back(GL_STENCIL);
  592. attachments.push_back(GL_DEPTH);
  593. }
  594. }
  595. else
  596. {
  597. int rendertargetcount = std::max((int) states.back().renderTargets.colors.size(), 1);
  598. for (int i = 0; i < (int) colorbuffers.size(); i++)
  599. {
  600. if (colorbuffers[i] && i < rendertargetcount)
  601. attachments.push_back(GL_COLOR_ATTACHMENT0 + i);
  602. }
  603. if (depthstencil)
  604. {
  605. attachments.push_back(GL_STENCIL_ATTACHMENT);
  606. attachments.push_back(GL_DEPTH_ATTACHMENT);
  607. }
  608. }
  609. // Hint for the driver that it doesn't need to save these buffers.
  610. if (GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0)
  611. glInvalidateFramebuffer(gltarget, (GLint) attachments.size(), &attachments[0]);
  612. else if (GLAD_EXT_discard_framebuffer)
  613. glDiscardFramebufferEXT(gltarget, (GLint) attachments.size(), &attachments[0]);
  614. }
  615. void Graphics::cleanupCanvas(Canvas *canvas)
  616. {
  617. for (auto it = framebufferObjects.begin(); it != framebufferObjects.end(); /**/)
  618. {
  619. bool hascanvas = false;
  620. const auto &rts = it->first;
  621. for (const RenderTarget &rt : rts.colors)
  622. {
  623. if (rt.canvas == canvas)
  624. {
  625. hascanvas = true;
  626. break;
  627. }
  628. }
  629. hascanvas = hascanvas || rts.depthStencil.canvas == canvas;
  630. if (hascanvas)
  631. {
  632. if (isCreated())
  633. gl.deleteFramebuffer(it->second);
  634. it = framebufferObjects.erase(it);
  635. }
  636. else
  637. ++it;
  638. }
  639. }
  640. void Graphics::bindCachedFBO(const RenderTargets &targets)
  641. {
  642. GLuint fbo = framebufferObjects[targets];
  643. if (fbo != 0)
  644. {
  645. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  646. }
  647. else
  648. {
  649. int msaa = targets.getFirstTarget().canvas->getMSAA();
  650. glGenFramebuffers(1, &fbo);
  651. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  652. int ncolortargets = 0;
  653. GLenum drawbuffers[MAX_COLOR_RENDER_TARGETS];
  654. auto attachCanvas = [&](const RenderTarget &rt)
  655. {
  656. bool renderbuffer = msaa > 1 || !rt.canvas->isReadable();
  657. bool srgb = false;
  658. OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(rt.canvas->getPixelFormat(), renderbuffer, srgb);
  659. if (fmt.framebufferAttachments[0] == GL_COLOR_ATTACHMENT0)
  660. {
  661. fmt.framebufferAttachments[0] = GL_COLOR_ATTACHMENT0 + ncolortargets;
  662. drawbuffers[ncolortargets] = fmt.framebufferAttachments[0];
  663. ncolortargets++;
  664. }
  665. GLuint handle = (GLuint) rt.canvas->getRenderTargetHandle();
  666. for (GLenum attachment : fmt.framebufferAttachments)
  667. {
  668. if (attachment == GL_NONE)
  669. continue;
  670. else if (renderbuffer)
  671. glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, handle);
  672. else
  673. {
  674. TextureType textype = rt.canvas->getTextureType();
  675. int layer = textype == TEXTURE_CUBE ? 0 : rt.slice;
  676. int face = textype == TEXTURE_CUBE ? rt.slice : 0;
  677. int level = rt.mipmap;
  678. gl.framebufferTexture(attachment, textype, handle, level, layer, face);
  679. }
  680. }
  681. };
  682. for (const auto &rt : targets.colors)
  683. attachCanvas(rt);
  684. if (targets.depthStencil.canvas != nullptr)
  685. attachCanvas(targets.depthStencil);
  686. if (ncolortargets > 1)
  687. glDrawBuffers(ncolortargets, drawbuffers);
  688. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  689. if (status != GL_FRAMEBUFFER_COMPLETE)
  690. {
  691. gl.deleteFramebuffer(fbo);
  692. const char *sstr = OpenGL::framebufferStatusString(status);
  693. throw love::Exception("Could not create Framebuffer Object! %s", sstr);
  694. }
  695. framebufferObjects[targets] = fbo;
  696. }
  697. }
  698. void Graphics::present(void *screenshotCallbackData)
  699. {
  700. if (!isActive())
  701. return;
  702. if (isCanvasActive())
  703. throw love::Exception("present cannot be called while a Canvas is active.");
  704. deprecations.draw(this);
  705. flushStreamDraws();
  706. endPass();
  707. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, gl.getDefaultFBO());
  708. if (!pendingScreenshotCallbacks.empty())
  709. {
  710. int w = getPixelWidth();
  711. int h = getPixelHeight();
  712. size_t row = 4 * w;
  713. size_t size = row * h;
  714. GLubyte *pixels = nullptr;
  715. GLubyte *screenshot = nullptr;
  716. try
  717. {
  718. pixels = new GLubyte[size];
  719. screenshot = new GLubyte[size];
  720. }
  721. catch (std::exception &)
  722. {
  723. delete[] pixels;
  724. delete[] screenshot;
  725. throw love::Exception("Out of memory.");
  726. }
  727. #ifdef LOVE_IOS
  728. SDL_SysWMinfo info = {};
  729. SDL_VERSION(&info.version);
  730. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  731. if (info.info.uikit.resolveFramebuffer != 0)
  732. {
  733. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, info.info.uikit.resolveFramebuffer);
  734. // We need to do an explicit MSAA resolve on iOS, because it uses
  735. // GLES FBOs rather than a system framebuffer.
  736. if (GLAD_ES_VERSION_3_0)
  737. glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  738. else if (GLAD_APPLE_framebuffer_multisample)
  739. glResolveMultisampleFramebufferAPPLE();
  740. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_READ, info.info.uikit.resolveFramebuffer);
  741. }
  742. #endif
  743. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  744. // Replace alpha values with full opacity.
  745. for (size_t i = 3; i < size; i += 4)
  746. pixels[i] = 255;
  747. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  748. GLubyte *src = pixels - row;
  749. GLubyte *dst = screenshot + size;
  750. for (int i = 0; i < h; ++i)
  751. memcpy(dst-=row, src+=row, row);
  752. delete[] pixels;
  753. auto imagemodule = Module::getInstance<love::image::Image>(M_IMAGE);
  754. for (int i = 0; i < (int) pendingScreenshotCallbacks.size(); i++)
  755. {
  756. const auto &info = pendingScreenshotCallbacks[i];
  757. image::ImageData *img = nullptr;
  758. try
  759. {
  760. img = imagemodule->newImageData(w, h, PIXELFORMAT_RGBA8, screenshot);
  761. }
  762. catch (love::Exception &)
  763. {
  764. delete[] screenshot;
  765. info.callback(&info, nullptr, nullptr);
  766. for (int j = i + 1; j < (int) pendingScreenshotCallbacks.size(); j++)
  767. {
  768. const auto &ninfo = pendingScreenshotCallbacks[j];
  769. ninfo.callback(&ninfo, nullptr, nullptr);
  770. }
  771. pendingScreenshotCallbacks.clear();
  772. throw;
  773. }
  774. info.callback(&info, img, screenshotCallbackData);
  775. img->release();
  776. }
  777. delete[] screenshot;
  778. pendingScreenshotCallbacks.clear();
  779. }
  780. #ifdef LOVE_IOS
  781. // Hack: SDL's color renderbuffer must be bound when swapBuffers is called.
  782. SDL_SysWMinfo info = {};
  783. SDL_VERSION(&info.version);
  784. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  785. glBindRenderbuffer(GL_RENDERBUFFER, info.info.uikit.colorbuffer);
  786. #endif
  787. for (StreamBuffer *buffer : streamBufferState.vb)
  788. buffer->nextFrame();
  789. streamBufferState.indexBuffer->nextFrame();
  790. auto window = getInstance<love::window::Window>(M_WINDOW);
  791. if (window != nullptr)
  792. window->swapBuffers();
  793. // Reset the per-frame stat counts.
  794. drawCalls = 0;
  795. gl.stats.shaderSwitches = 0;
  796. canvasSwitchCount = 0;
  797. drawCallsBatched = 0;
  798. // This assumes temporary canvases will only be used within a render pass.
  799. for (int i = (int) temporaryCanvases.size() - 1; i >= 0; i--)
  800. {
  801. if (temporaryCanvases[i].framesSinceUse >= MAX_TEMPORARY_CANVAS_UNUSED_FRAMES)
  802. {
  803. temporaryCanvases[i].canvas->release();
  804. temporaryCanvases[i] = temporaryCanvases.back();
  805. temporaryCanvases.pop_back();
  806. }
  807. else
  808. temporaryCanvases[i].framesSinceUse++;
  809. }
  810. }
  811. void Graphics::setScissor(const Rect &rect)
  812. {
  813. flushStreamDraws();
  814. DisplayState &state = states.back();
  815. if (!gl.isStateEnabled(OpenGL::ENABLE_SCISSOR_TEST))
  816. gl.setEnableState(OpenGL::ENABLE_SCISSOR_TEST, true);
  817. double dpiscale = getCurrentDPIScale();
  818. Rect glrect;
  819. glrect.x = (int) (rect.x * dpiscale);
  820. glrect.y = (int) (rect.y * dpiscale);
  821. glrect.w = (int) (rect.w * dpiscale);
  822. glrect.h = (int) (rect.h * dpiscale);
  823. // OpenGL's reversed y-coordinate is compensated for in OpenGL::setScissor.
  824. gl.setScissor(glrect, isCanvasActive());
  825. state.scissor = true;
  826. state.scissorRect = rect;
  827. }
  828. void Graphics::setScissor()
  829. {
  830. if (states.back().scissor)
  831. flushStreamDraws();
  832. states.back().scissor = false;
  833. if (gl.isStateEnabled(OpenGL::ENABLE_SCISSOR_TEST))
  834. gl.setEnableState(OpenGL::ENABLE_SCISSOR_TEST, false);
  835. }
  836. void Graphics::drawToStencilBuffer(StencilAction action, int value)
  837. {
  838. const auto &rts = states.back().renderTargets;
  839. love::graphics::Canvas *dscanvas = rts.depthStencil.canvas.get();
  840. if (!isCanvasActive() && !windowHasStencil)
  841. throw love::Exception("The window must have stenciling enabled to draw to the main screen's stencil buffer.");
  842. else if (isCanvasActive() && (rts.temporaryRTFlags & TEMPORARY_RT_STENCIL) == 0 && (dscanvas == nullptr || !isPixelFormatStencil(dscanvas->getPixelFormat())))
  843. throw love::Exception("Drawing to the stencil buffer with a Canvas active requires either stencil=true or a custom stencil-type Canvas to be used, in setCanvas.");
  844. flushStreamDraws();
  845. writingToStencil = true;
  846. // Disable color writes but don't save the state for it.
  847. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  848. GLenum glaction = GL_REPLACE;
  849. switch (action)
  850. {
  851. case STENCIL_REPLACE:
  852. default:
  853. glaction = GL_REPLACE;
  854. break;
  855. case STENCIL_INCREMENT:
  856. glaction = GL_INCR;
  857. break;
  858. case STENCIL_DECREMENT:
  859. glaction = GL_DECR;
  860. break;
  861. case STENCIL_INCREMENT_WRAP:
  862. glaction = GL_INCR_WRAP;
  863. break;
  864. case STENCIL_DECREMENT_WRAP:
  865. glaction = GL_DECR_WRAP;
  866. break;
  867. case STENCIL_INVERT:
  868. glaction = GL_INVERT;
  869. break;
  870. }
  871. // The stencil test must be enabled in order to write to the stencil buffer.
  872. if (!gl.isStateEnabled(OpenGL::ENABLE_STENCIL_TEST))
  873. gl.setEnableState(OpenGL::ENABLE_STENCIL_TEST, true);
  874. glStencilFunc(GL_ALWAYS, value, 0xFFFFFFFF);
  875. glStencilOp(GL_KEEP, GL_KEEP, glaction);
  876. }
  877. void Graphics::stopDrawToStencilBuffer()
  878. {
  879. if (!writingToStencil)
  880. return;
  881. flushStreamDraws();
  882. writingToStencil = false;
  883. const DisplayState &state = states.back();
  884. // Revert the color write mask.
  885. setColorMask(state.colorMask);
  886. // Use the user-set stencil test state when writes are disabled.
  887. setStencilTest(state.stencilCompare, state.stencilTestValue);
  888. }
  889. void Graphics::setStencilTest(CompareMode compare, int value)
  890. {
  891. DisplayState &state = states.back();
  892. if (state.stencilCompare != compare || state.stencilTestValue != value)
  893. flushStreamDraws();
  894. state.stencilCompare = compare;
  895. state.stencilTestValue = value;
  896. if (writingToStencil)
  897. return;
  898. if (compare == COMPARE_ALWAYS)
  899. {
  900. if (gl.isStateEnabled(OpenGL::ENABLE_STENCIL_TEST))
  901. gl.setEnableState(OpenGL::ENABLE_STENCIL_TEST, false);
  902. return;
  903. }
  904. /**
  905. * OpenGL / GPUs do the comparison in the opposite way that makes sense
  906. * for this API. For example, if the compare function is GL_GREATER then the
  907. * stencil test will pass if the reference value is greater than the value
  908. * in the stencil buffer. With our API it's more intuitive to assume that
  909. * setStencilTest(COMPARE_GREATER, 4) will make it pass if the stencil
  910. * buffer has a value greater than 4.
  911. **/
  912. GLenum glcompare = OpenGL::getGLCompareMode(getReversedCompareMode(compare));
  913. if (!gl.isStateEnabled(OpenGL::ENABLE_STENCIL_TEST))
  914. gl.setEnableState(OpenGL::ENABLE_STENCIL_TEST, true);
  915. glStencilFunc(glcompare, value, 0xFFFFFFFF);
  916. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  917. }
  918. void Graphics::setDepthMode(CompareMode compare, bool write)
  919. {
  920. DisplayState &state = states.back();
  921. if (state.depthTest != compare || state.depthWrite != write)
  922. flushStreamDraws();
  923. state.depthTest = compare;
  924. state.depthWrite = write;
  925. bool depthenable = compare != COMPARE_ALWAYS || write;
  926. if (depthenable != gl.isStateEnabled(OpenGL::ENABLE_DEPTH_TEST))
  927. gl.setEnableState(OpenGL::ENABLE_DEPTH_TEST, depthenable);
  928. if (depthenable)
  929. {
  930. glDepthFunc(OpenGL::getGLCompareMode(compare));
  931. gl.setDepthWrites(write);
  932. }
  933. }
  934. void Graphics::setFrontFaceWinding(vertex::Winding winding)
  935. {
  936. DisplayState &state = states.back();
  937. if (state.winding != winding)
  938. flushStreamDraws();
  939. state.winding = winding;
  940. if (isCanvasActive())
  941. winding = winding == vertex::WINDING_CW ? vertex::WINDING_CCW : vertex::WINDING_CW;
  942. glFrontFace(winding == vertex::WINDING_CW ? GL_CW : GL_CCW);
  943. }
  944. void Graphics::setColor(Colorf c)
  945. {
  946. c.r = std::min(std::max(c.r, 0.0f), 1.0f);
  947. c.g = std::min(std::max(c.g, 0.0f), 1.0f);
  948. c.b = std::min(std::max(c.b, 0.0f), 1.0f);
  949. c.a = std::min(std::max(c.a, 0.0f), 1.0f);
  950. gl.setConstantColor(c);
  951. states.back().color = c;
  952. }
  953. void Graphics::setColorMask(ColorMask mask)
  954. {
  955. flushStreamDraws();
  956. glColorMask(mask.r, mask.g, mask.b, mask.a);
  957. states.back().colorMask = mask;
  958. }
  959. void Graphics::setBlendMode(BlendMode mode, BlendAlpha alphamode)
  960. {
  961. if (mode != states.back().blendMode || alphamode != states.back().blendAlphaMode)
  962. flushStreamDraws();
  963. if (mode == BLEND_LIGHTEN || mode == BLEND_DARKEN)
  964. {
  965. if (!capabilities.features[FEATURE_LIGHTEN])
  966. throw love::Exception("The 'lighten' and 'darken' blend modes are not supported on this system.");
  967. }
  968. if (alphamode != BLENDALPHA_PREMULTIPLIED)
  969. {
  970. const char *modestr = "unknown";
  971. switch (mode)
  972. {
  973. case BLEND_LIGHTEN:
  974. case BLEND_DARKEN:
  975. case BLEND_MULTIPLY:
  976. getConstant(mode, modestr);
  977. throw love::Exception("The '%s' blend mode must be used with premultiplied alpha.", modestr);
  978. break;
  979. default:
  980. break;
  981. }
  982. }
  983. GLenum func = GL_FUNC_ADD;
  984. GLenum srcRGB = GL_ONE;
  985. GLenum srcA = GL_ONE;
  986. GLenum dstRGB = GL_ZERO;
  987. GLenum dstA = GL_ZERO;
  988. switch (mode)
  989. {
  990. case BLEND_ALPHA:
  991. srcRGB = srcA = GL_ONE;
  992. dstRGB = dstA = GL_ONE_MINUS_SRC_ALPHA;
  993. break;
  994. case BLEND_MULTIPLY:
  995. srcRGB = srcA = GL_DST_COLOR;
  996. dstRGB = dstA = GL_ZERO;
  997. break;
  998. case BLEND_SUBTRACT:
  999. func = GL_FUNC_REVERSE_SUBTRACT;
  1000. case BLEND_ADD:
  1001. srcRGB = GL_ONE;
  1002. srcA = GL_ZERO;
  1003. dstRGB = dstA = GL_ONE;
  1004. break;
  1005. case BLEND_LIGHTEN:
  1006. func = GL_MAX;
  1007. break;
  1008. case BLEND_DARKEN:
  1009. func = GL_MIN;
  1010. break;
  1011. case BLEND_SCREEN:
  1012. srcRGB = srcA = GL_ONE;
  1013. dstRGB = dstA = GL_ONE_MINUS_SRC_COLOR;
  1014. break;
  1015. case BLEND_REPLACE:
  1016. case BLEND_NONE:
  1017. default:
  1018. srcRGB = srcA = GL_ONE;
  1019. dstRGB = dstA = GL_ZERO;
  1020. break;
  1021. }
  1022. // We can only do alpha-multiplication when srcRGB would have been unmodified.
  1023. if (srcRGB == GL_ONE && alphamode == BLENDALPHA_MULTIPLY && mode != BLEND_NONE)
  1024. srcRGB = GL_SRC_ALPHA;
  1025. glBlendEquation(func);
  1026. glBlendFuncSeparate(srcRGB, dstRGB, srcA, dstA);
  1027. states.back().blendMode = mode;
  1028. states.back().blendAlphaMode = alphamode;
  1029. }
  1030. void Graphics::setPointSize(float size)
  1031. {
  1032. if (streamBufferState.primitiveMode == PRIMITIVE_POINTS)
  1033. flushStreamDraws();
  1034. gl.setPointSize(size * getCurrentDPIScale());
  1035. states.back().pointSize = size;
  1036. }
  1037. void Graphics::setWireframe(bool enable)
  1038. {
  1039. // Not supported in OpenGL ES.
  1040. if (GLAD_ES_VERSION_2_0)
  1041. return;
  1042. flushStreamDraws();
  1043. glPolygonMode(GL_FRONT_AND_BACK, enable ? GL_LINE : GL_FILL);
  1044. states.back().wireframe = enable;
  1045. }
  1046. Graphics::Renderer Graphics::getRenderer() const
  1047. {
  1048. return GLAD_ES_VERSION_2_0 ? RENDERER_OPENGLES : RENDERER_OPENGL;
  1049. }
  1050. Graphics::RendererInfo Graphics::getRendererInfo() const
  1051. {
  1052. RendererInfo info;
  1053. if (GLAD_ES_VERSION_2_0)
  1054. info.name = "OpenGL ES";
  1055. else
  1056. info.name = "OpenGL";
  1057. const char *str = (const char *) glGetString(GL_VERSION);
  1058. if (str)
  1059. info.version = str;
  1060. else
  1061. throw love::Exception("Cannot retrieve renderer version information.");
  1062. str = (const char *) glGetString(GL_VENDOR);
  1063. if (str)
  1064. info.vendor = str;
  1065. else
  1066. throw love::Exception("Cannot retrieve renderer vendor information.");
  1067. str = (const char *) glGetString(GL_RENDERER);
  1068. if (str)
  1069. info.device = str;
  1070. else
  1071. throw love::Exception("Cannot retrieve renderer device information.");
  1072. return info;
  1073. }
  1074. void Graphics::getAPIStats(int &shaderswitches) const
  1075. {
  1076. shaderswitches = gl.stats.shaderSwitches;
  1077. }
  1078. void Graphics::initCapabilities()
  1079. {
  1080. capabilities.features[FEATURE_MULTI_CANVAS_FORMATS] = Canvas::isMultiFormatMultiCanvasSupported();
  1081. capabilities.features[FEATURE_CLAMP_ZERO] = gl.isClampZeroTextureWrapSupported();
  1082. capabilities.features[FEATURE_LIGHTEN] = GLAD_VERSION_1_4 || GLAD_ES_VERSION_3_0 || GLAD_EXT_blend_minmax;
  1083. capabilities.features[FEATURE_FULL_NPOT] = GLAD_VERSION_2_0 || GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot;
  1084. capabilities.features[FEATURE_PIXEL_SHADER_HIGHP] = gl.isPixelShaderHighpSupported();
  1085. capabilities.features[FEATURE_SHADER_DERIVATIVES] = GLAD_VERSION_2_0 || GLAD_ES_VERSION_3_0 || GLAD_OES_standard_derivatives;
  1086. capabilities.features[FEATURE_GLSL3] = GLAD_ES_VERSION_3_0 || gl.isCoreProfile();
  1087. capabilities.features[FEATURE_INSTANCING] = gl.isInstancingSupported();
  1088. static_assert(FEATURE_MAX_ENUM == 8, "Graphics::initCapabilities must be updated when adding a new graphics feature!");
  1089. capabilities.limits[LIMIT_POINT_SIZE] = gl.getMaxPointSize();
  1090. capabilities.limits[LIMIT_TEXTURE_SIZE] = gl.getMax2DTextureSize();
  1091. capabilities.limits[LIMIT_TEXTURE_LAYERS] = gl.getMaxTextureLayers();
  1092. capabilities.limits[LIMIT_VOLUME_TEXTURE_SIZE] = gl.getMax3DTextureSize();
  1093. capabilities.limits[LIMIT_CUBE_TEXTURE_SIZE] = gl.getMaxCubeTextureSize();
  1094. capabilities.limits[LIMIT_MULTI_CANVAS] = gl.getMaxRenderTargets();
  1095. capabilities.limits[LIMIT_CANVAS_MSAA] = gl.getMaxRenderbufferSamples();
  1096. capabilities.limits[LIMIT_ANISOTROPY] = gl.getMaxAnisotropy();
  1097. static_assert(LIMIT_MAX_ENUM == 8, "Graphics::initCapabilities must be updated when adding a new system limit!");
  1098. for (int i = 0; i < TEXTURE_MAX_ENUM; i++)
  1099. capabilities.textureTypes[i] = gl.isTextureTypeSupported((TextureType) i);
  1100. }
  1101. bool Graphics::isCanvasFormatSupported(PixelFormat format) const
  1102. {
  1103. return Canvas::isFormatSupported(format);
  1104. }
  1105. bool Graphics::isCanvasFormatSupported(PixelFormat format, bool readable) const
  1106. {
  1107. return Canvas::isFormatSupported(format, readable);
  1108. }
  1109. bool Graphics::isImageFormatSupported(PixelFormat format) const
  1110. {
  1111. return Image::isFormatSupported(format);
  1112. }
  1113. Shader::Language Graphics::getShaderLanguageTarget() const
  1114. {
  1115. if (gl.isCoreProfile())
  1116. return Shader::LANGUAGE_GLSL3;
  1117. else if (GLAD_ES_VERSION_3_0)
  1118. return Shader::LANGUAGE_ESSL3;
  1119. else if (GLAD_ES_VERSION_2_0)
  1120. return Shader::LANGUAGE_ESSL1;
  1121. else
  1122. return Shader::LANGUAGE_GLSL1;
  1123. }
  1124. } // opengl
  1125. } // graphics
  1126. } // love