Graphics.cpp 40 KB

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