Graphics.cpp 40 KB

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