Graphics.cpp 42 KB

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