Graphics.cpp 42 KB

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