Graphics.cpp 35 KB

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