Graphics.cpp 47 KB

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