Graphics.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614
  1. /**
  2. * Copyright (c) 2006-2015 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 "Polyline.h"
  27. // C++
  28. #include <vector>
  29. #include <sstream>
  30. #include <algorithm>
  31. #include <iterator>
  32. // C
  33. #include <cmath>
  34. #include <cstdio>
  35. #ifdef LOVE_IOS
  36. #include <SDL_syswm.h>
  37. #endif
  38. namespace love
  39. {
  40. namespace graphics
  41. {
  42. namespace opengl
  43. {
  44. Graphics::Graphics()
  45. : currentWindow(Module::getInstance<love::window::Window>(Module::M_WINDOW))
  46. , quadIndices(nullptr)
  47. , width(0)
  48. , height(0)
  49. , created(false)
  50. , active(true)
  51. , writingToStencil(false)
  52. {
  53. gl = OpenGL();
  54. states.reserve(10);
  55. states.push_back(DisplayState());
  56. if (currentWindow.get())
  57. {
  58. int w, h;
  59. love::window::WindowSettings wsettings;
  60. currentWindow->getWindow(w, h, wsettings);
  61. if (currentWindow->isOpen())
  62. setMode(w, h, wsettings.sRGB);
  63. }
  64. }
  65. Graphics::~Graphics()
  66. {
  67. // We do this manually so the graphics objects are released before the window.
  68. states.clear();
  69. defaultFont.set(nullptr);
  70. if (Shader::defaultShader)
  71. {
  72. Shader::defaultShader->release();
  73. Shader::defaultShader = nullptr;
  74. }
  75. if (quadIndices)
  76. delete quadIndices;
  77. }
  78. const char *Graphics::getName() const
  79. {
  80. return "love.graphics.opengl";
  81. }
  82. void Graphics::restoreState(const DisplayState &s)
  83. {
  84. setColor(s.color);
  85. setBackgroundColor(s.backgroundColor);
  86. setBlendMode(s.blendMode, s.blendMultiplyAlpha);
  87. setLineWidth(s.lineWidth);
  88. setLineStyle(s.lineStyle);
  89. setLineJoin(s.lineJoin);
  90. setPointSize(s.pointSize);
  91. if (s.scissor)
  92. setScissor(s.scissorBox.x, s.scissorBox.y, s.scissorBox.w, s.scissorBox.h);
  93. else
  94. setScissor();
  95. setStencilTest(s.stencilTest, s.stencilInvert);
  96. setFont(s.font.get());
  97. setShader(s.shader.get());
  98. setCanvas(s.canvases);
  99. setColorMask(s.colorMask);
  100. setWireframe(s.wireframe);
  101. setDefaultFilter(s.defaultFilter);
  102. setDefaultMipmapFilter(s.defaultMipmapFilter, s.defaultMipmapSharpness);
  103. }
  104. void Graphics::restoreStateChecked(const DisplayState &s)
  105. {
  106. const DisplayState &cur = states.back();
  107. if (*(uint32 *) &s.color.r != *(uint32 *) &cur.color.r)
  108. setColor(s.color);
  109. if (*(uint32 *) &s.backgroundColor.r != *(uint32 *) &cur.backgroundColor.r)
  110. setBackgroundColor(s.backgroundColor);
  111. if (s.blendMode != cur.blendMode || s.blendMultiplyAlpha != cur.blendMultiplyAlpha)
  112. setBlendMode(s.blendMode, s.blendMultiplyAlpha);
  113. // These are just simple assignments.
  114. setLineWidth(s.lineWidth);
  115. setLineStyle(s.lineStyle);
  116. setLineJoin(s.lineJoin);
  117. if (s.pointSize != cur.pointSize)
  118. setPointSize(s.pointSize);
  119. if (s.scissor != cur.scissor || (s.scissor && !(s.scissorBox == cur.scissorBox)))
  120. {
  121. if (s.scissor)
  122. setScissor(s.scissorBox.x, s.scissorBox.y, s.scissorBox.w, s.scissorBox.h);
  123. else
  124. setScissor();
  125. }
  126. if (s.stencilTest != cur.stencilTest || s.stencilInvert != cur.stencilInvert)
  127. setStencilTest(s.stencilTest, s.stencilInvert);
  128. setFont(s.font.get());
  129. setShader(s.shader.get());
  130. bool canvaseschanged = s.canvases.size() != cur.canvases.size();
  131. for (size_t i = 0; i < s.canvases.size() && i < cur.canvases.size(); i++)
  132. {
  133. if (s.canvases[i].get() != cur.canvases[i].get())
  134. {
  135. canvaseschanged = true;
  136. break;
  137. }
  138. }
  139. if (canvaseschanged)
  140. setCanvas(s.canvases);
  141. if (s.colorMask != cur.colorMask)
  142. setColorMask(s.colorMask);
  143. if (s.wireframe != cur.wireframe)
  144. setWireframe(s.wireframe);
  145. setDefaultFilter(s.defaultFilter);
  146. setDefaultMipmapFilter(s.defaultMipmapFilter, s.defaultMipmapSharpness);
  147. }
  148. void Graphics::checkSetDefaultFont()
  149. {
  150. // We don't create or set the default Font if an existing font is in use.
  151. if (states.back().font.get() != nullptr)
  152. return;
  153. // Create a new default font if we don't have one yet.
  154. if (!defaultFont.get())
  155. {
  156. auto fontmodule = Module::getInstance<font::Font>(M_FONT);
  157. if (!fontmodule)
  158. throw love::Exception("Font module has not been loaded.");
  159. StrongRef<font::Rasterizer> r(fontmodule->newTrueTypeRasterizer(12, font::TrueTypeRasterizer::HINTING_NORMAL));
  160. r->release();
  161. defaultFont.set(newFont(r.get()));
  162. defaultFont->release();
  163. }
  164. states.back().font.set(defaultFont.get());
  165. }
  166. void Graphics::setViewportSize(int width, int height)
  167. {
  168. this->width = width;
  169. this->height = height;
  170. if (!isCreated())
  171. return;
  172. // We want to affect the main screen, not any Canvas that's currently active
  173. // (not that any *should* be active when this is called.)
  174. std::vector<StrongRef<Canvas>> canvases = states.back().canvases;
  175. setCanvas();
  176. // Set the viewport to top-left corner.
  177. gl.setViewport({0, 0, width, height});
  178. // If a canvas was bound before this function was called, it needs to be
  179. // made aware of the new system viewport size.
  180. Canvas::systemViewport = gl.getViewport();
  181. // Set up the projection matrix
  182. gl.matrices.projection.back() = Matrix4::ortho(0.0, (float) width, (float) height, 0.0);
  183. // Restore the previously active Canvas.
  184. setCanvas(canvases);
  185. }
  186. bool Graphics::setMode(int width, int height, bool &sRGB)
  187. {
  188. currentWindow.set(Module::getInstance<love::window::Window>(Module::M_WINDOW));
  189. this->width = width;
  190. this->height = height;
  191. // Okay, setup OpenGL.
  192. gl.initContext();
  193. gl.setupContext();
  194. created = true;
  195. setViewportSize(width, height);
  196. // Enable blending
  197. glEnable(GL_BLEND);
  198. // Auto-generated mipmaps should be the best quality possible
  199. glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
  200. if (!GLAD_ES_VERSION_2_0)
  201. {
  202. // Make sure antialiasing works when set elsewhere
  203. glEnable(GL_MULTISAMPLE);
  204. // Enable texturing
  205. glEnable(GL_TEXTURE_2D);
  206. }
  207. gl.setTextureUnit(0);
  208. // Set pixel row alignment
  209. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  210. // Set whether drawing converts input from linear -> sRGB colorspace.
  211. if (GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_sRGB || GLAD_EXT_framebuffer_sRGB
  212. || GLAD_ES_VERSION_3_0 || GLAD_EXT_sRGB)
  213. {
  214. if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
  215. gl.setFramebufferSRGB(sRGB);
  216. }
  217. else
  218. sRGB = false;
  219. Canvas::screenHasSRGB = sRGB;
  220. bool enabledebug = false;
  221. if (GLAD_VERSION_3_0)
  222. {
  223. // Enable OpenGL's debug output if a debug context has been created.
  224. GLint flags = 0;
  225. glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
  226. enabledebug = (flags & GL_CONTEXT_FLAG_DEBUG_BIT) != 0;
  227. }
  228. setDebug(enabledebug);
  229. // Create a quad indices object owned by love.graphics, so at least one
  230. // QuadIndices object is alive at all times while love.graphics is alive.
  231. // This makes sure there aren't too many expensive destruction/creations of
  232. // index buffer objects, since the shared index buffer used by QuadIndices
  233. // objects is destroyed when the last object is destroyed.
  234. if (quadIndices == nullptr)
  235. quadIndices = new QuadIndices(20);
  236. // Reload all volatile objects.
  237. if (!Volatile::loadAll())
  238. ::printf("Could not reload all volatile objects.\n");
  239. // Restore the graphics state.
  240. restoreState(states.back());
  241. pixelSizeStack.clear();
  242. pixelSizeStack.reserve(5);
  243. pixelSizeStack.push_back(1);
  244. // We always need a default shader.
  245. if (!Shader::defaultShader)
  246. {
  247. Renderer renderer = GLAD_ES_VERSION_2_0 ? RENDERER_OPENGLES : RENDERER_OPENGL;
  248. Shader::defaultShader = newShader(Shader::defaultCode[renderer]);
  249. }
  250. // A shader should always be active, but the default shader shouldn't be
  251. // returned by getShader(), so we don't do setShader(defaultShader).
  252. if (!Shader::current)
  253. Shader::defaultShader->attach();
  254. return true;
  255. }
  256. void Graphics::unSetMode()
  257. {
  258. if (!isCreated())
  259. return;
  260. // Unload all volatile objects. These must be reloaded after the display
  261. // mode change.
  262. Volatile::unloadAll();
  263. gl.deInitContext();
  264. created = false;
  265. }
  266. void Graphics::setActive(bool enable)
  267. {
  268. // Make sure all pending OpenGL commands have fully executed before
  269. // returning, if we're going from active to inactive.
  270. if (isCreated() && this->active && !enable)
  271. glFinish();
  272. active = enable;
  273. }
  274. bool Graphics::isActive() const
  275. {
  276. // The graphics module is only completely 'active' if there's a window, a
  277. // context, and the active variable is set.
  278. return active && isCreated() && currentWindow.get() && currentWindow->isOpen();
  279. }
  280. static void APIENTRY debugCB(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei /*len*/, const GLchar *msg, const GLvoid* /*usr*/)
  281. {
  282. // Human-readable strings for the debug info.
  283. const char *sourceStr = OpenGL::debugSourceString(source);
  284. const char *typeStr = OpenGL::debugTypeString(type);
  285. const char *severityStr = OpenGL::debugSeverityString(severity);
  286. const char *fmt = "OpenGL: %s [source=%s, type=%s, severity=%s, id=%d]\n";
  287. printf(fmt, msg, sourceStr, typeStr, severityStr, id);
  288. }
  289. void Graphics::setDebug(bool enable)
  290. {
  291. // Make sure debug output is supported. The AMD ext. is a bit different
  292. // so we don't make use of it, since AMD drivers now support KHR_debug.
  293. if (!(GLAD_VERSION_4_3 || GLAD_KHR_debug || GLAD_ARB_debug_output))
  294. return;
  295. // TODO: We don't support GL_KHR_debug in GLES yet.
  296. if (GLAD_ES_VERSION_2_0)
  297. return;
  298. // Ugly hack to reduce code duplication.
  299. if (GLAD_ARB_debug_output && !(GLAD_VERSION_4_3 || GLAD_KHR_debug))
  300. {
  301. fp_glDebugMessageCallback = (pfn_glDebugMessageCallback) fp_glDebugMessageCallbackARB;
  302. fp_glDebugMessageControl = (pfn_glDebugMessageControl) fp_glDebugMessageControlARB;
  303. }
  304. if (!enable)
  305. {
  306. // Disable the debug callback function.
  307. glDebugMessageCallback(nullptr, nullptr);
  308. // We can disable debug output entirely with KHR_debug.
  309. if (GLAD_VERSION_4_3 || GLAD_KHR_debug)
  310. glDisable(GL_DEBUG_OUTPUT);
  311. return;
  312. }
  313. // We don't want asynchronous debug output.
  314. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  315. glDebugMessageCallback(debugCB, nullptr);
  316. // Initially, enable everything.
  317. glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
  318. // Disable messages about deprecated OpenGL functionality.
  319. glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  320. glDebugMessageControl(GL_DEBUG_SOURCE_SHADER_COMPILER, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  321. if (GLAD_VERSION_4_3 || GLAD_KHR_debug)
  322. glEnable(GL_DEBUG_OUTPUT);
  323. ::printf("OpenGL debug output enabled (LOVE_GRAPHICS_DEBUG=1)\n");
  324. }
  325. void Graphics::reset()
  326. {
  327. DisplayState s;
  328. drawToStencilBuffer(false);
  329. restoreState(s);
  330. origin();
  331. }
  332. void Graphics::clear(Color c)
  333. {
  334. glClearColor(c.r / 255.0f, c.g / 255.0f, c.b / 255.0f, c.a / 255.0f);
  335. glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  336. }
  337. void Graphics::clear(const std::vector<Color> &colors)
  338. {
  339. if (colors.size() == 0)
  340. return;
  341. if (states.back().canvases.size() == 0)
  342. return clear(colors[0]);
  343. if (colors.size() != states.back().canvases.size())
  344. throw love::Exception("Number of clear colors must match the number of active canvases (%ld)", states.back().canvases.size());
  345. std::vector<GLenum> bufs;
  346. for (int i = 0; i < (int) colors.size(); i++)
  347. {
  348. const GLfloat c[] = {colors[i].r/255.f, colors[i].g/255.f, colors[i].b/255.f, colors[i].a/255.f};
  349. if (GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0)
  350. glClearBufferfv(GL_COLOR, i, c);
  351. else
  352. {
  353. bufs.push_back(GL_COLOR_ATTACHMENT0 + i);
  354. glDrawBuffer(GL_COLOR_ATTACHMENT0 + i);
  355. glClearColor(c[0], c[1], c[2], c[3]);
  356. glClear(GL_COLOR_BUFFER_BIT);
  357. }
  358. }
  359. glClear(GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  360. // Revert to the expected draw buffers once we're done, if glClearBuffer
  361. // wasn't supported.
  362. if (!(GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0))
  363. {
  364. if (bufs.size() > 1)
  365. glDrawBuffers((int) bufs.size(), &bufs[0]);
  366. else
  367. glDrawBuffer(GL_COLOR_ATTACHMENT0);
  368. }
  369. }
  370. void Graphics::discard(const std::vector<bool> &colorbuffers, bool stencil)
  371. {
  372. if (!(GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0 || GLAD_EXT_discard_framebuffer))
  373. return;
  374. std::vector<GLenum> attachments;
  375. attachments.reserve(colorbuffers.size());
  376. // glDiscardFramebuffer uses different attachment enums for the default FBO.
  377. if (!Canvas::current && gl.getDefaultFBO() == 0)
  378. {
  379. if (colorbuffers.size() > 0 && colorbuffers[0])
  380. attachments.push_back(GL_COLOR);
  381. if (stencil)
  382. {
  383. attachments.push_back(GL_STENCIL);
  384. attachments.push_back(GL_DEPTH);
  385. }
  386. }
  387. else
  388. {
  389. int rendertargetcount = 1;
  390. if (Canvas::current)
  391. rendertargetcount = (int) states.back().canvases.size();
  392. for (int i = 0; i < (int) colorbuffers.size(); i++)
  393. {
  394. if (colorbuffers[i] && i < rendertargetcount)
  395. attachments.push_back(GL_COLOR_ATTACHMENT0 + i);
  396. }
  397. if (stencil)
  398. {
  399. attachments.push_back(GL_STENCIL_ATTACHMENT);
  400. attachments.push_back(GL_DEPTH_ATTACHMENT);
  401. }
  402. }
  403. // Hint for the driver that it doesn't need to save these buffers.
  404. if (GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0)
  405. glInvalidateFramebuffer(GL_FRAMEBUFFER, (GLint) attachments.size(), &attachments[0]);
  406. else if (GLAD_EXT_discard_framebuffer)
  407. glDiscardFramebufferEXT(GL_FRAMEBUFFER, (GLint) attachments.size(), &attachments[0]);
  408. }
  409. void Graphics::present()
  410. {
  411. if (!isActive())
  412. return;
  413. // Make sure we don't have a canvas active.
  414. std::vector<StrongRef<Canvas>> canvases = states.back().canvases;
  415. setCanvas();
  416. // Discard the stencil buffer before swapping.
  417. discard({}, true);
  418. #ifdef LOVE_IOS
  419. // Hack: SDL's color renderbuffer must be bound when swapBuffers is called.
  420. SDL_SysWMinfo info = {};
  421. SDL_VERSION(&info.version);
  422. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  423. glBindRenderbuffer(GL_RENDERBUFFER, info.info.uikit.colorbuffer);
  424. #endif
  425. if (currentWindow.get())
  426. currentWindow->swapBuffers();
  427. // Restore the currently active canvas, if there is one.
  428. setCanvas(canvases);
  429. // Reset the per-frame stat counts.
  430. gl.stats.drawCalls = 0;
  431. gl.stats.framebufferBinds = 0;
  432. }
  433. int Graphics::getWidth() const
  434. {
  435. return width;
  436. }
  437. int Graphics::getHeight() const
  438. {
  439. return height;
  440. }
  441. bool Graphics::isCreated() const
  442. {
  443. return created;
  444. }
  445. void Graphics::setScissor(int x, int y, int width, int height)
  446. {
  447. OpenGL::Viewport box = {x, y, width, height};
  448. glEnable(GL_SCISSOR_TEST);
  449. // OpenGL's reversed y-coordinate is compensated for in OpenGL::setScissor.
  450. gl.setScissor(box);
  451. states.back().scissor = true;
  452. states.back().scissorBox = box;
  453. }
  454. void Graphics::setScissor()
  455. {
  456. states.back().scissor = false;
  457. glDisable(GL_SCISSOR_TEST);
  458. }
  459. bool Graphics::getScissor(int &x, int &y, int &width, int &height) const
  460. {
  461. const DisplayState &state = states.back();
  462. x = state.scissorBox.x;
  463. y = state.scissorBox.y;
  464. width = state.scissorBox.w;
  465. height = state.scissorBox.h;
  466. return state.scissor;
  467. }
  468. void Graphics::drawToStencilBuffer(bool enable)
  469. {
  470. if (writingToStencil == enable)
  471. return;
  472. writingToStencil = enable;
  473. if (!enable)
  474. {
  475. const DisplayState &state = states.back();
  476. // Revert the color write mask.
  477. setColorMask(state.colorMask);
  478. // Use the user-set stencil test state when writes are disabled.
  479. setStencilTest(state.stencilTest, state.stencilInvert);
  480. return;
  481. }
  482. // Make sure the active canvas has a stencil buffer.
  483. if (Canvas::current)
  484. Canvas::current->checkCreateStencil();
  485. // Disable color writes but don't save the state for it.
  486. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  487. // The stencil test must be enabled in order to write to the stencil buffer.
  488. glEnable(GL_STENCIL_TEST);
  489. glStencilFunc(GL_ALWAYS, 1, 1);
  490. glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
  491. }
  492. void Graphics::setStencilTest(bool enable, bool invert)
  493. {
  494. DisplayState &state = states.back();
  495. state.stencilTest = enable;
  496. state.stencilInvert = invert;
  497. if (writingToStencil)
  498. return;
  499. if (!enable)
  500. {
  501. glDisable(GL_STENCIL_TEST);
  502. return;
  503. }
  504. // Make sure the active canvas has a stencil buffer.
  505. if (Canvas::current)
  506. Canvas::current->checkCreateStencil();
  507. glEnable(GL_STENCIL_TEST);
  508. glStencilFunc(GL_EQUAL, invert ? 0 : 1, 1);
  509. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  510. }
  511. void Graphics::getStencilTest(bool &enable, bool &invert)
  512. {
  513. const DisplayState &state = states.back();
  514. enable = state.stencilTest;
  515. invert = state.stencilInvert;
  516. }
  517. void Graphics::clearStencil()
  518. {
  519. glClear(GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  520. }
  521. Image *Graphics::newImage(const std::vector<love::image::ImageData *> &data, const Image::Flags &flags)
  522. {
  523. return new Image(data, flags);
  524. }
  525. Image *Graphics::newImage(const std::vector<love::image::CompressedImageData *> &cdata, const Image::Flags &flags)
  526. {
  527. return new Image(cdata, flags);
  528. }
  529. Quad *Graphics::newQuad(Quad::Viewport v, float sw, float sh)
  530. {
  531. return new Quad(v, sw, sh);
  532. }
  533. Font *Graphics::newFont(love::font::Rasterizer *r, const Texture::Filter &filter)
  534. {
  535. return new Font(r, filter);
  536. }
  537. SpriteBatch *Graphics::newSpriteBatch(Texture *texture, int size, Mesh::Usage usage)
  538. {
  539. return new SpriteBatch(texture, size, usage);
  540. }
  541. ParticleSystem *Graphics::newParticleSystem(Texture *texture, int size)
  542. {
  543. return new ParticleSystem(texture, size);
  544. }
  545. Canvas *Graphics::newCanvas(int width, int height, Canvas::Format format, int msaa)
  546. {
  547. if (!Canvas::isFormatSupported(format))
  548. {
  549. const char *fstr = "rgba8";
  550. Canvas::getConstant(format, fstr);
  551. throw love::Exception("The %s canvas format is not supported by your OpenGL implementation.", fstr);
  552. }
  553. if (width > gl.getMaxTextureSize())
  554. throw Exception("Cannot create canvas: width of %d pixels is too large for this system.", width);
  555. else if (height > gl.getMaxTextureSize())
  556. throw Exception("Cannot create canvas: height of %d pixels is too large for this system.", height);
  557. while (GL_NO_ERROR != glGetError())
  558. /* clear opengl error flag */;
  559. Canvas *canvas = new Canvas(width, height, format, msaa);
  560. GLenum err = canvas->getStatus();
  561. // everything ok, return canvas (early out)
  562. if (err == GL_FRAMEBUFFER_COMPLETE)
  563. return canvas;
  564. // create error message
  565. std::stringstream error_string;
  566. error_string << "Cannot create canvas: ";
  567. switch (err)
  568. {
  569. case GL_FRAMEBUFFER_UNSUPPORTED:
  570. error_string << "Not supported by your OpenGL implementation.";
  571. break;
  572. case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  573. error_string << "Texture format cannot be rendered to on this system.";
  574. break;
  575. // remaining error codes are highly unlikely:
  576. case GL_FRAMEBUFFER_UNDEFINED:
  577. case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  578. case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:
  579. case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
  580. case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
  581. error_string << "Error in implementation.";
  582. break;
  583. default:
  584. // my intel hda card wrongly returns 0 to glCheckFramebufferStatus() but sets
  585. // no error flag. I think it meant to return GL_FRAMEBUFFER_UNSUPPORTED, but who
  586. // knows.
  587. if (glGetError() == GL_NO_ERROR)
  588. error_string << "May not be supported by your OpenGL implementation.";
  589. // the remaining error is an indication of a serious fuckup since it should
  590. // only be returned if glCheckFramebufferStatus() was called with the wrong
  591. // arguments.
  592. else
  593. error_string << "Cannot create canvas: Aliens did it (OpenGL error code: " << glGetError() << ")";
  594. }
  595. canvas->release();
  596. throw Exception("%s", error_string.str().c_str());
  597. return nullptr; // never reached
  598. }
  599. Shader *Graphics::newShader(const Shader::ShaderSource &source)
  600. {
  601. return new Shader(source);
  602. }
  603. Mesh *Graphics::newMesh(const std::vector<Vertex> &vertices, Mesh::DrawMode drawmode, Mesh::Usage usage)
  604. {
  605. return new Mesh(vertices, drawmode, usage);
  606. }
  607. Mesh *Graphics::newMesh(int vertexcount, Mesh::DrawMode drawmode, Mesh::Usage usage)
  608. {
  609. return new Mesh(vertexcount, drawmode, usage);
  610. }
  611. Mesh *Graphics::newMesh(const std::vector<Mesh::AttribFormat> &vertexformat, int vertexcount, Mesh::DrawMode drawmode, Mesh::Usage usage)
  612. {
  613. return new Mesh(vertexformat, vertexcount, drawmode, usage);
  614. }
  615. Mesh *Graphics::newMesh(const std::vector<Mesh::AttribFormat> &vertexformat, const void *data, size_t datasize, Mesh::DrawMode drawmode, Mesh::Usage usage)
  616. {
  617. return new Mesh(vertexformat, data, datasize, drawmode, usage);
  618. }
  619. Text *Graphics::newText(Font *font, const std::string &text)
  620. {
  621. return new Text(font, text);
  622. }
  623. void Graphics::setColor(Color c)
  624. {
  625. glVertexAttrib4f(ATTRIB_CONSTANTCOLOR, c.r/255.0f, c.g/255.0f, c.b/255.0f, c.a/255.0f);
  626. states.back().color = c;
  627. }
  628. Color Graphics::getColor() const
  629. {
  630. return states.back().color;
  631. }
  632. void Graphics::setBackgroundColor(Color c)
  633. {
  634. states.back().backgroundColor = c;
  635. }
  636. Color Graphics::getBackgroundColor() const
  637. {
  638. return states.back().backgroundColor;
  639. }
  640. void Graphics::setFont(Font *font)
  641. {
  642. // We don't need to set a default font here if null is passed in, since we
  643. // only care about the default font in getFont and print.
  644. DisplayState &state = states.back();
  645. state.font.set(font);
  646. }
  647. Font *Graphics::getFont()
  648. {
  649. checkSetDefaultFont();
  650. return states.back().font.get();
  651. }
  652. void Graphics::setShader(Shader *shader)
  653. {
  654. if (shader == nullptr)
  655. return setShader();
  656. DisplayState &state = states.back();
  657. shader->attach();
  658. state.shader.set(shader);
  659. }
  660. void Graphics::setShader()
  661. {
  662. DisplayState &state = states.back();
  663. // This will activate the default shader.
  664. Shader::detach();
  665. state.shader.set(nullptr);
  666. }
  667. Shader *Graphics::getShader() const
  668. {
  669. return states.back().shader.get();
  670. }
  671. void Graphics::setCanvas(Canvas *canvas)
  672. {
  673. if (canvas == nullptr)
  674. return setCanvas();
  675. DisplayState &state = states.back();
  676. canvas->startGrab();
  677. std::vector<StrongRef<Canvas>> canvasref;
  678. canvasref.push_back(canvas);
  679. std::swap(state.canvases, canvasref);
  680. }
  681. void Graphics::setCanvas(const std::vector<Canvas *> &canvases)
  682. {
  683. if (canvases.size() == 0)
  684. return setCanvas();
  685. else if (canvases.size() == 1)
  686. return setCanvas(canvases[0]);
  687. DisplayState &state = states.back();
  688. auto attachments = std::vector<Canvas *>(canvases.begin() + 1, canvases.end());
  689. canvases[0]->startGrab(attachments);
  690. std::vector<StrongRef<Canvas>> canvasrefs;
  691. canvasrefs.reserve(canvases.size());
  692. for (Canvas *c : canvases)
  693. canvasrefs.push_back(c);
  694. std::swap(state.canvases, canvasrefs);
  695. }
  696. void Graphics::setCanvas(const std::vector<StrongRef<Canvas>> &canvases)
  697. {
  698. std::vector<Canvas *> canvaslist;
  699. canvaslist.reserve(canvases.size());
  700. for (const StrongRef<Canvas> &c : canvases)
  701. canvaslist.push_back(c.get());
  702. return setCanvas(canvaslist);
  703. }
  704. void Graphics::setCanvas()
  705. {
  706. DisplayState &state = states.back();
  707. if (Canvas::current != nullptr)
  708. Canvas::current->stopGrab();
  709. state.canvases.clear();
  710. }
  711. std::vector<Canvas *> Graphics::getCanvas() const
  712. {
  713. std::vector<Canvas *> canvases;
  714. canvases.reserve(states.back().canvases.size());
  715. for (const StrongRef<Canvas> &c : states.back().canvases)
  716. canvases.push_back(c.get());
  717. return canvases;
  718. }
  719. void Graphics::setColorMask(ColorMask mask)
  720. {
  721. glColorMask(mask.r, mask.g, mask.b, mask.a);
  722. states.back().colorMask = mask;
  723. }
  724. Graphics::ColorMask Graphics::getColorMask() const
  725. {
  726. return states.back().colorMask;
  727. }
  728. void Graphics::setBlendMode(BlendMode mode, bool multiplyalpha)
  729. {
  730. GLenum func = GL_FUNC_ADD;
  731. GLenum srcRGB = GL_ONE;
  732. GLenum srcA = GL_ONE;
  733. GLenum dstRGB = GL_ZERO;
  734. GLenum dstA = GL_ZERO;
  735. switch (mode)
  736. {
  737. case BLEND_ALPHA:
  738. srcRGB = srcA = GL_ONE;
  739. dstRGB = dstA = GL_ONE_MINUS_SRC_ALPHA;
  740. break;
  741. case BLEND_MULTIPLY:
  742. srcRGB = srcA = GL_DST_COLOR;
  743. dstRGB = dstA = GL_ZERO;
  744. break;
  745. case BLEND_SUBTRACT:
  746. func = GL_FUNC_REVERSE_SUBTRACT;
  747. case BLEND_ADD:
  748. srcRGB = GL_ONE;
  749. srcA = GL_ZERO;
  750. dstRGB = dstA = GL_ONE;
  751. break;
  752. case BLEND_SCREEN:
  753. srcRGB = srcA = GL_ONE;
  754. dstRGB = dstA = GL_ONE_MINUS_SRC_COLOR;
  755. break;
  756. case BLEND_REPLACE:
  757. default:
  758. srcRGB = srcA = GL_ONE;
  759. dstRGB = dstA = GL_ZERO;
  760. break;
  761. }
  762. // We can only do alpha-multiplication when srcRGB would have been unmodified.
  763. if (srcRGB == GL_ONE && multiplyalpha)
  764. srcRGB = GL_SRC_ALPHA;
  765. glBlendEquation(func);
  766. glBlendFuncSeparate(srcRGB, dstRGB, srcA, dstA);
  767. states.back().blendMode = mode;
  768. states.back().blendMultiplyAlpha = multiplyalpha;
  769. }
  770. Graphics::BlendMode Graphics::getBlendMode(bool &multiplyalpha) const
  771. {
  772. multiplyalpha = states.back().blendMultiplyAlpha;
  773. return states.back().blendMode;
  774. }
  775. void Graphics::setDefaultFilter(const Texture::Filter &f)
  776. {
  777. Texture::setDefaultFilter(f);
  778. states.back().defaultFilter = f;
  779. }
  780. const Texture::Filter &Graphics::getDefaultFilter() const
  781. {
  782. return Texture::getDefaultFilter();
  783. }
  784. void Graphics::setDefaultMipmapFilter(Texture::FilterMode filter, float sharpness)
  785. {
  786. Image::setDefaultMipmapFilter(filter);
  787. Image::setDefaultMipmapSharpness(sharpness);
  788. states.back().defaultMipmapFilter = filter;
  789. states.back().defaultMipmapSharpness = sharpness;
  790. }
  791. void Graphics::getDefaultMipmapFilter(Texture::FilterMode *filter, float *sharpness) const
  792. {
  793. *filter = Image::getDefaultMipmapFilter();
  794. *sharpness = Image::getDefaultMipmapSharpness();
  795. }
  796. void Graphics::setLineWidth(float width)
  797. {
  798. states.back().lineWidth = width;
  799. }
  800. void Graphics::setLineStyle(Graphics::LineStyle style)
  801. {
  802. states.back().lineStyle = style;
  803. }
  804. void Graphics::setLineJoin(Graphics::LineJoin join)
  805. {
  806. states.back().lineJoin = join;
  807. }
  808. float Graphics::getLineWidth() const
  809. {
  810. return states.back().lineWidth;
  811. }
  812. Graphics::LineStyle Graphics::getLineStyle() const
  813. {
  814. return states.back().lineStyle;
  815. }
  816. Graphics::LineJoin Graphics::getLineJoin() const
  817. {
  818. return states.back().lineJoin;
  819. }
  820. void Graphics::setPointSize(float size)
  821. {
  822. gl.setPointSize(size);
  823. states.back().pointSize = size;
  824. }
  825. float Graphics::getPointSize() const
  826. {
  827. return states.back().pointSize;
  828. }
  829. void Graphics::setWireframe(bool enable)
  830. {
  831. // Not supported in OpenGL ES.
  832. if (GLAD_ES_VERSION_2_0)
  833. return;
  834. glPolygonMode(GL_FRONT_AND_BACK, enable ? GL_LINE : GL_FILL);
  835. states.back().wireframe = enable;
  836. }
  837. bool Graphics::isWireframe() const
  838. {
  839. return states.back().wireframe;
  840. }
  841. void Graphics::print(const std::string &str, float x, float y , float angle, float sx, float sy, float ox, float oy, float kx, float ky)
  842. {
  843. checkSetDefaultFont();
  844. DisplayState &state = states.back();
  845. if (state.font.get() != nullptr)
  846. state.font->print(str, x, y, angle, sx, sy, ox, oy, kx, ky);
  847. }
  848. void Graphics::printf(const std::string &str, float x, float y, float wrap, Font::AlignMode align, float angle, float sx, float sy, float ox, float oy, float kx, float ky)
  849. {
  850. checkSetDefaultFont();
  851. DisplayState &state = states.back();
  852. if (state.font.get() != nullptr)
  853. state.font->printf(str, x, y, wrap, align, angle, sx, sy, ox, oy, kx, ky);
  854. }
  855. /**
  856. * Primitives
  857. **/
  858. void Graphics::point(float x, float y)
  859. {
  860. OpenGL::TempDebugGroup debuggroup("Graphics point draw");
  861. GLfloat coord[] = {x, y};
  862. gl.prepareDraw();
  863. gl.bindTexture(gl.getDefaultTexture());
  864. gl.useVertexAttribArrays(ATTRIBFLAG_POS);
  865. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, 0, coord);
  866. gl.drawArrays(GL_POINTS, 0, 1);
  867. }
  868. void Graphics::polyline(const float *coords, size_t count)
  869. {
  870. const DisplayState &state = states.back();
  871. if (state.lineJoin == LINE_JOIN_NONE)
  872. {
  873. NoneJoinPolyline line;
  874. line.render(coords, count, state.lineWidth * .5f, float(pixelSizeStack.back()), state.lineStyle == LINE_SMOOTH);
  875. line.draw();
  876. }
  877. else if (state.lineJoin == LINE_JOIN_BEVEL)
  878. {
  879. BevelJoinPolyline line;
  880. line.render(coords, count, state.lineWidth * .5f, float(pixelSizeStack.back()), state.lineStyle == LINE_SMOOTH);
  881. line.draw();
  882. }
  883. else // LINE_JOIN_MITER
  884. {
  885. MiterJoinPolyline line;
  886. line.render(coords, count, state.lineWidth * .5f, float(pixelSizeStack.back()), state.lineStyle == LINE_SMOOTH);
  887. line.draw();
  888. }
  889. }
  890. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  891. {
  892. float coords[] = {x,y, x,y+h, x+w,y+h, x+w,y, x,y};
  893. polygon(mode, coords, 5 * 2);
  894. }
  895. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry, int points)
  896. {
  897. if (rx == 0 || ry == 0)
  898. {
  899. rectangle(mode, x, y, w, h);
  900. return;
  901. }
  902. // Radius values that are more than half the rectangle's size aren't handled
  903. // correctly (for now)...
  904. if (w >= 0.02f)
  905. rx = std::min(rx, w / 2.0f - 0.01f);
  906. if (h >= 0.02f)
  907. ry = std::min(ry, h / 2.0f - 0.01f);
  908. points = std::max(points, 1);
  909. const float half_pi = static_cast<float>(LOVE_M_PI / 2);
  910. float angle_shift = half_pi / ((float) points + 1.0f);
  911. int num_coords = (points + 2) * 8;
  912. float *coords = new float[num_coords + 2];
  913. float phi = .0f;
  914. for (int i = 0; i <= points + 2; ++i, phi += angle_shift)
  915. {
  916. coords[2 * i + 0] = x + rx * (1 - cosf(phi));
  917. coords[2 * i + 1] = y + ry * (1 - sinf(phi));
  918. }
  919. phi = half_pi;
  920. for (int i = points + 2; i <= 2 * (points + 2); ++i, phi += angle_shift)
  921. {
  922. coords[2 * i + 0] = x + w - rx * (1 + cosf(phi));
  923. coords[2 * i + 1] = y + ry * (1 - sinf(phi));
  924. }
  925. phi = 2 * half_pi;
  926. for (int i = 2 * (points + 2); i <= 3 * (points + 2); ++i, phi += angle_shift)
  927. {
  928. coords[2 * i + 0] = x + w - rx * (1 + cosf(phi));
  929. coords[2 * i + 1] = y + h - ry * (1 + sinf(phi));
  930. }
  931. phi = 3 * half_pi;
  932. for (int i = 3 * (points + 2); i <= 4 * (points + 2); ++i, phi += angle_shift)
  933. {
  934. coords[2 * i + 0] = x + rx * (1 - cosf(phi));
  935. coords[2 * i + 1] = y + h - ry * (1 + sinf(phi));
  936. }
  937. coords[num_coords + 0] = coords[0];
  938. coords[num_coords + 1] = coords[1];
  939. polygon(mode, coords, num_coords + 2);
  940. delete[] coords;
  941. }
  942. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  943. {
  944. ellipse(mode, x, y, radius, radius, points);
  945. }
  946. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b, int points)
  947. {
  948. float two_pi = static_cast<float>(LOVE_M_PI * 2);
  949. if (points <= 0) points = 1;
  950. float angle_shift = (two_pi / points);
  951. float phi = .0f;
  952. float *coords = new float[2 * (points + 1)];
  953. for (int i = 0; i < points; ++i, phi += angle_shift)
  954. {
  955. coords[2*i+0] = x + a * cosf(phi);
  956. coords[2*i+1] = y + b * sinf(phi);
  957. }
  958. coords[2*points+0] = coords[0];
  959. coords[2*points+1] = coords[1];
  960. polygon(mode, coords, (points + 1) * 2);
  961. delete[] coords;
  962. }
  963. void Graphics::arc(DrawMode mode, float x, float y, float radius, float angle1, float angle2, int points)
  964. {
  965. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  966. if (points <= 0 || angle1 == angle2)
  967. return;
  968. // Oh, you want to draw a circle?
  969. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  970. {
  971. circle(mode, x, y, radius, points);
  972. return;
  973. }
  974. float angle_shift = (angle2 - angle1) / points;
  975. // Bail on precision issues.
  976. if (angle_shift == 0.0)
  977. return;
  978. float phi = angle1;
  979. int num_coords = (points + 3) * 2;
  980. float *coords = new float[num_coords];
  981. coords[0] = coords[num_coords - 2] = x;
  982. coords[1] = coords[num_coords - 1] = y;
  983. for (int i = 0; i <= points; ++i, phi += angle_shift)
  984. {
  985. coords[2 * (i+1)] = x + radius * cosf(phi);
  986. coords[2 * (i+1) + 1] = y + radius * sinf(phi);
  987. }
  988. // GL_POLYGON can only fill-draw convex polygons, so we need to do stuff manually here
  989. if (mode == DRAW_LINE)
  990. {
  991. polyline(coords, num_coords); // Artifacts at sharp angles if set to looping.
  992. }
  993. else
  994. {
  995. OpenGL::TempDebugGroup debuggroup("Filled arc draw");
  996. gl.prepareDraw();
  997. gl.bindTexture(gl.getDefaultTexture());
  998. gl.useVertexAttribArrays(ATTRIBFLAG_POS);
  999. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, 0, coords);
  1000. gl.drawArrays(GL_TRIANGLE_FAN, 0, points + 2);
  1001. }
  1002. delete[] coords;
  1003. }
  1004. /// @param mode the draw mode
  1005. /// @param coords the coordinate array
  1006. /// @param count the number of coordinates/size of the array
  1007. void Graphics::polygon(DrawMode mode, const float *coords, size_t count)
  1008. {
  1009. // coords is an array of a closed loop of vertices, i.e.
  1010. // coords[count-2] = coords[0], coords[count-1] = coords[1]
  1011. if (mode == DRAW_LINE)
  1012. {
  1013. polyline(coords, count);
  1014. }
  1015. else
  1016. {
  1017. OpenGL::TempDebugGroup debuggroup("Filled polygon draw");
  1018. gl.prepareDraw();
  1019. gl.bindTexture(gl.getDefaultTexture());
  1020. gl.useVertexAttribArrays(ATTRIBFLAG_POS);
  1021. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, 0, coords);
  1022. gl.drawArrays(GL_TRIANGLE_FAN, 0, (int)count/2-1); // opengl will close the polygon for us
  1023. }
  1024. }
  1025. love::image::ImageData *Graphics::newScreenshot(love::image::Image *image, bool copyAlpha)
  1026. {
  1027. // Temporarily unbind the currently active canvas (glReadPixels reads the
  1028. // active framebuffer, not the main one.)
  1029. std::vector<StrongRef<Canvas>> canvases = states.back().canvases;
  1030. setCanvas();
  1031. int w = getWidth();
  1032. int h = getHeight();
  1033. int row = 4 * w;
  1034. int size = row * h;
  1035. GLubyte *pixels = nullptr;
  1036. GLubyte *screenshot = nullptr;
  1037. try
  1038. {
  1039. pixels = new GLubyte[size];
  1040. screenshot = new GLubyte[size];
  1041. }
  1042. catch (std::exception &)
  1043. {
  1044. delete[] pixels;
  1045. delete[] screenshot;
  1046. setCanvas(canvases);
  1047. throw love::Exception("Out of memory.");
  1048. }
  1049. #ifdef LOVE_IOS
  1050. SDL_SysWMinfo info = {};
  1051. SDL_VERSION(&info.version);
  1052. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  1053. if (info.info.uikit.resolveFramebuffer != 0)
  1054. {
  1055. glBindFramebuffer(GL_DRAW_FRAMEBUFFER, info.info.uikit.resolveFramebuffer);
  1056. // We need to do an explicit MSAA resolve on iOS, because it uses GLES
  1057. // FBOs rather than a system framebuffer.
  1058. if (GLAD_ES_VERSION_3_0)
  1059. glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  1060. else if (GLAD_APPLE_framebuffer_multisample)
  1061. glResolveMultisampleFramebufferAPPLE();
  1062. glBindFramebuffer(GL_READ_FRAMEBUFFER, info.info.uikit.resolveFramebuffer);
  1063. }
  1064. #endif
  1065. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  1066. #ifdef LOVE_IOS
  1067. // Restore the previous binding for the main framebuffer.
  1068. if (info.info.uikit.resolveFramebuffer != 0)
  1069. glBindFramebuffer(GL_FRAMEBUFFER, gl.getDefaultFBO());
  1070. #endif
  1071. if (!copyAlpha)
  1072. {
  1073. // Replace alpha values with full opacity.
  1074. for (int i = 3; i < size; i += 4)
  1075. pixels[i] = 255;
  1076. }
  1077. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  1078. GLubyte *src = pixels - row;
  1079. GLubyte *dst = screenshot + size;
  1080. for (int i = 0; i < h; ++i)
  1081. memcpy(dst-=row, src+=row, row);
  1082. delete[] pixels;
  1083. love::image::ImageData *img = nullptr;
  1084. try
  1085. {
  1086. // Tell the new ImageData that it owns the screenshot data, so we don't
  1087. // need to delete it here.
  1088. img = image->newImageData(w, h, (void *) screenshot, true);
  1089. }
  1090. catch (love::Exception &)
  1091. {
  1092. delete[] screenshot;
  1093. setCanvas(canvases);
  1094. throw;
  1095. }
  1096. // Re-bind the active canvas, if necessary.
  1097. setCanvas(canvases);
  1098. return img;
  1099. }
  1100. Graphics::RendererInfo Graphics::getRendererInfo() const
  1101. {
  1102. RendererInfo info;
  1103. if (GLAD_ES_VERSION_2_0)
  1104. info.name = "OpenGL ES";
  1105. else
  1106. info.name = "OpenGL";
  1107. const char *str = (const char *) glGetString(GL_VERSION);
  1108. if (str)
  1109. info.version = str;
  1110. else
  1111. throw love::Exception("Cannot retrieve renderer version information.");
  1112. str = (const char *) glGetString(GL_VENDOR);
  1113. if (str)
  1114. info.vendor = str;
  1115. else
  1116. throw love::Exception("Cannot retrieve renderer vendor information.");
  1117. str = (const char *) glGetString(GL_RENDERER);
  1118. if (str)
  1119. info.device = str;
  1120. else
  1121. throw love::Exception("Cannot retrieve renderer device information.");
  1122. return info;
  1123. }
  1124. Graphics::Stats Graphics::getStats() const
  1125. {
  1126. Stats stats;
  1127. stats.drawCalls = gl.stats.drawCalls;
  1128. stats.canvasSwitches = gl.stats.framebufferBinds;
  1129. stats.canvases = Canvas::canvasCount;
  1130. stats.images = Image::imageCount;
  1131. stats.fonts = Font::fontCount;
  1132. stats.textureMemory = gl.stats.textureMemory;
  1133. return stats;
  1134. }
  1135. double Graphics::getSystemLimit(SystemLimit limittype) const
  1136. {
  1137. switch (limittype)
  1138. {
  1139. case Graphics::LIMIT_POINT_SIZE:
  1140. {
  1141. GLfloat limits[2];
  1142. glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, limits);
  1143. return (double) limits[1];
  1144. }
  1145. case Graphics::LIMIT_TEXTURE_SIZE:
  1146. return (double) gl.getMaxTextureSize();
  1147. case Graphics::LIMIT_MULTI_CANVAS:
  1148. return (double) gl.getMaxRenderTargets();
  1149. case Graphics::LIMIT_CANVAS_MSAA:
  1150. return (double) gl.getMaxRenderbufferSamples();
  1151. default:
  1152. return 0.0;
  1153. }
  1154. }
  1155. bool Graphics::isSupported(Support feature) const
  1156. {
  1157. switch (feature)
  1158. {
  1159. case SUPPORT_MULTI_CANVAS:
  1160. return Canvas::isMultiCanvasSupported();
  1161. case SUPPORT_MULTI_CANVAS_FORMATS:
  1162. return Canvas::isMultiFormatMultiCanvasSupported();
  1163. case SUPPORT_SRGB:
  1164. // sRGB support for the screen is guaranteed if it's supported as a
  1165. // Canvas format.
  1166. return Canvas::isFormatSupported(Canvas::FORMAT_SRGB);
  1167. default:
  1168. return false;
  1169. }
  1170. }
  1171. void Graphics::push(StackType type)
  1172. {
  1173. if (stackTypes.size() == MAX_USER_STACK_DEPTH)
  1174. throw Exception("Maximum stack depth reached (more pushes than pops?)");
  1175. gl.pushTransform();
  1176. pixelSizeStack.push_back(pixelSizeStack.back());
  1177. if (type == STACK_ALL)
  1178. states.push_back(states.back());
  1179. stackTypes.push_back(type);
  1180. }
  1181. void Graphics::pop()
  1182. {
  1183. if (stackTypes.size() < 1)
  1184. throw Exception("Minimum stack depth reached (more pops than pushes?)");
  1185. gl.popTransform();
  1186. pixelSizeStack.pop_back();
  1187. if (stackTypes.back() == STACK_ALL)
  1188. {
  1189. DisplayState &newstate = states[states.size() - 2];
  1190. restoreStateChecked(newstate);
  1191. // The last two states in the stack should be equal now.
  1192. states.pop_back();
  1193. }
  1194. stackTypes.pop_back();
  1195. }
  1196. void Graphics::rotate(float r)
  1197. {
  1198. gl.getTransform().rotate(r);
  1199. }
  1200. void Graphics::scale(float x, float y)
  1201. {
  1202. gl.getTransform().scale(x, y);
  1203. pixelSizeStack.back() *= 2. / (fabs(x) + fabs(y));
  1204. }
  1205. void Graphics::translate(float x, float y)
  1206. {
  1207. gl.getTransform().translate(x, y);
  1208. }
  1209. void Graphics::shear(float kx, float ky)
  1210. {
  1211. gl.getTransform().shear(kx, ky);
  1212. }
  1213. void Graphics::origin()
  1214. {
  1215. gl.getTransform().setIdentity();
  1216. pixelSizeStack.back() = 1;
  1217. }
  1218. Graphics::DisplayState::DisplayState()
  1219. : color(255, 255, 255, 255)
  1220. , backgroundColor(0, 0, 0, 255)
  1221. , blendMode(BLEND_ALPHA)
  1222. , blendMultiplyAlpha(true)
  1223. , lineWidth(1.0f)
  1224. , lineStyle(LINE_SMOOTH)
  1225. , lineJoin(LINE_JOIN_MITER)
  1226. , pointSize(1.0f)
  1227. , scissor(false)
  1228. , scissorBox()
  1229. , stencilTest(false)
  1230. , stencilInvert(false)
  1231. , font(nullptr)
  1232. , shader(nullptr)
  1233. , colorMask({true, true, true, true})
  1234. , wireframe(false)
  1235. , defaultFilter()
  1236. , defaultMipmapFilter(Texture::FILTER_NEAREST)
  1237. , defaultMipmapSharpness(0.0f)
  1238. {
  1239. }
  1240. Graphics::DisplayState::DisplayState(const DisplayState &other)
  1241. : color(other.color)
  1242. , backgroundColor(other.backgroundColor)
  1243. , blendMode(other.blendMode)
  1244. , blendMultiplyAlpha(other.blendMultiplyAlpha)
  1245. , lineWidth(other.lineWidth)
  1246. , lineStyle(other.lineStyle)
  1247. , lineJoin(other.lineJoin)
  1248. , pointSize(other.pointSize)
  1249. , scissor(other.scissor)
  1250. , scissorBox(other.scissorBox)
  1251. , stencilTest(other.stencilTest)
  1252. , stencilInvert(other.stencilInvert)
  1253. , font(other.font)
  1254. , shader(other.shader)
  1255. , canvases(other.canvases)
  1256. , colorMask(other.colorMask)
  1257. , wireframe(other.wireframe)
  1258. , defaultFilter(other.defaultFilter)
  1259. , defaultMipmapFilter(other.defaultMipmapFilter)
  1260. , defaultMipmapSharpness(other.defaultMipmapSharpness)
  1261. {
  1262. }
  1263. Graphics::DisplayState::~DisplayState()
  1264. {
  1265. }
  1266. Graphics::DisplayState &Graphics::DisplayState::operator = (const DisplayState &other)
  1267. {
  1268. color = other.color;
  1269. backgroundColor = other.backgroundColor;
  1270. blendMode = other.blendMode;
  1271. blendMultiplyAlpha = other.blendMultiplyAlpha;
  1272. lineWidth = other.lineWidth;
  1273. lineStyle = other.lineStyle;
  1274. lineJoin = other.lineJoin;
  1275. pointSize = other.pointSize;
  1276. scissor = other.scissor;
  1277. scissorBox = other.scissorBox;
  1278. stencilTest = other.stencilTest;
  1279. stencilInvert = other.stencilInvert;
  1280. font = other.font;
  1281. shader = other.shader;
  1282. canvases = other.canvases;
  1283. colorMask = other.colorMask;
  1284. wireframe = other.wireframe;
  1285. defaultFilter = other.defaultFilter;
  1286. defaultMipmapFilter = other.defaultMipmapFilter;
  1287. defaultMipmapSharpness = other.defaultMipmapSharpness;
  1288. return *this;
  1289. }
  1290. } // opengl
  1291. } // graphics
  1292. } // love