Graphics.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986
  1. /**
  2. * Copyright (c) 2006-2016 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 "graphics/Polyline.h"
  27. #include "math/MathModule.h"
  28. #include "window/Window.h"
  29. #include "libraries/xxHash/xxhash.h"
  30. // C++
  31. #include <vector>
  32. #include <sstream>
  33. #include <algorithm>
  34. #include <iterator>
  35. // C
  36. #include <cmath>
  37. #include <cstdio>
  38. #ifdef LOVE_IOS
  39. #include <SDL_syswm.h>
  40. #endif
  41. namespace love
  42. {
  43. namespace graphics
  44. {
  45. namespace opengl
  46. {
  47. Graphics::Graphics()
  48. : quadIndices(nullptr)
  49. , width(0)
  50. , height(0)
  51. , created(false)
  52. , active(true)
  53. , writingToStencil(false)
  54. , canvasSwitchCount(0)
  55. {
  56. gl = OpenGL();
  57. states.reserve(10);
  58. states.push_back(DisplayState());
  59. auto window = getInstance<love::window::Window>(M_WINDOW);
  60. if (window != nullptr)
  61. {
  62. window->setGraphics(this);
  63. if (window->isOpen())
  64. {
  65. int w = 0, h = 0;
  66. window->getPixelDimensions(w, h);
  67. setMode(w, h);
  68. }
  69. }
  70. }
  71. Graphics::~Graphics()
  72. {
  73. // We do this manually so the graphics objects are released before the window.
  74. states.clear();
  75. defaultFont.set(nullptr);
  76. if (Shader::defaultShader)
  77. {
  78. Shader::defaultShader->release();
  79. Shader::defaultShader = nullptr;
  80. }
  81. if (Shader::defaultVideoShader)
  82. {
  83. Shader::defaultVideoShader->release();
  84. Shader::defaultVideoShader = nullptr;
  85. }
  86. if (quadIndices)
  87. delete quadIndices;
  88. }
  89. const char *Graphics::getName() const
  90. {
  91. return "love.graphics.opengl";
  92. }
  93. void Graphics::restoreState(const DisplayState &s)
  94. {
  95. setColor(s.color);
  96. setBackgroundColor(s.backgroundColor);
  97. setBlendMode(s.blendMode, s.blendAlphaMode);
  98. setLineWidth(s.lineWidth);
  99. setLineStyle(s.lineStyle);
  100. setLineJoin(s.lineJoin);
  101. setPointSize(s.pointSize);
  102. if (s.scissor)
  103. setScissor(s.scissorRect);
  104. else
  105. setScissor();
  106. setStencilTest(s.stencilCompare, s.stencilTestValue);
  107. setFont(s.font.get());
  108. setShader(s.shader.get());
  109. setCanvas(s.canvases);
  110. setColorMask(s.colorMask);
  111. setWireframe(s.wireframe);
  112. setDefaultFilter(s.defaultFilter);
  113. setDefaultMipmapFilter(s.defaultMipmapFilter, s.defaultMipmapSharpness);
  114. }
  115. void Graphics::restoreStateChecked(const DisplayState &s)
  116. {
  117. const DisplayState &cur = states.back();
  118. if (s.color != cur.color)
  119. setColor(s.color);
  120. setBackgroundColor(s.backgroundColor);
  121. if (s.blendMode != cur.blendMode || s.blendAlphaMode != cur.blendAlphaMode)
  122. setBlendMode(s.blendMode, s.blendAlphaMode);
  123. // These are just simple assignments.
  124. setLineWidth(s.lineWidth);
  125. setLineStyle(s.lineStyle);
  126. setLineJoin(s.lineJoin);
  127. if (s.pointSize != cur.pointSize)
  128. setPointSize(s.pointSize);
  129. if (s.scissor != cur.scissor || (s.scissor && !(s.scissorRect == cur.scissorRect)))
  130. {
  131. if (s.scissor)
  132. setScissor(s.scissorRect);
  133. else
  134. setScissor();
  135. }
  136. if (s.stencilCompare != cur.stencilCompare || s.stencilTestValue != cur.stencilTestValue)
  137. setStencilTest(s.stencilCompare, s.stencilTestValue);
  138. setFont(s.font.get());
  139. setShader(s.shader.get());
  140. bool canvaseschanged = s.canvases.size() != cur.canvases.size();
  141. if (!canvaseschanged)
  142. {
  143. for (size_t i = 0; i < s.canvases.size() && i < cur.canvases.size(); i++)
  144. {
  145. if (s.canvases[i].get() != cur.canvases[i].get())
  146. {
  147. canvaseschanged = true;
  148. break;
  149. }
  150. }
  151. }
  152. if (canvaseschanged)
  153. setCanvas(s.canvases);
  154. if (s.colorMask != cur.colorMask)
  155. setColorMask(s.colorMask);
  156. if (s.wireframe != cur.wireframe)
  157. setWireframe(s.wireframe);
  158. setDefaultFilter(s.defaultFilter);
  159. setDefaultMipmapFilter(s.defaultMipmapFilter, s.defaultMipmapSharpness);
  160. }
  161. void Graphics::checkSetDefaultFont()
  162. {
  163. // We don't create or set the default Font if an existing font is in use.
  164. if (states.back().font.get() != nullptr)
  165. return;
  166. // Create a new default font if we don't have one yet.
  167. if (!defaultFont.get())
  168. {
  169. auto fontmodule = Module::getInstance<font::Font>(M_FONT);
  170. if (!fontmodule)
  171. throw love::Exception("Font module has not been loaded.");
  172. auto hinting = font::TrueTypeRasterizer::HINTING_NORMAL;
  173. StrongRef<font::Rasterizer> r(fontmodule->newTrueTypeRasterizer(12, hinting), Acquire::NORETAIN);
  174. defaultFont.set(newFont(r.get()), Acquire::NORETAIN);
  175. }
  176. states.back().font.set(defaultFont.get());
  177. }
  178. void Graphics::setViewportSize(int width, int height)
  179. {
  180. this->width = width;
  181. this->height = height;
  182. if (states.back().canvases.empty())
  183. {
  184. // Set the viewport to top-left corner.
  185. gl.setViewport({0, 0, width, height}, false);
  186. // Set up the projection matrix
  187. projectionMatrix = Matrix4::ortho(0.0, (float) width, (float) height, 0.0);
  188. }
  189. }
  190. bool Graphics::setMode(int width, int height)
  191. {
  192. this->width = width;
  193. this->height = height;
  194. // Okay, setup OpenGL.
  195. gl.initContext();
  196. gl.setupContext();
  197. created = true;
  198. // Enable blending
  199. glEnable(GL_BLEND);
  200. // Auto-generated mipmaps should be the best quality possible
  201. glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST);
  202. if (!GLAD_ES_VERSION_2_0)
  203. {
  204. // Make sure antialiasing works when set elsewhere
  205. glEnable(GL_MULTISAMPLE);
  206. // Enable texturing
  207. glEnable(GL_TEXTURE_2D);
  208. }
  209. gl.setTextureUnit(0);
  210. // Set pixel row alignment
  211. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  212. // Set whether drawing converts input from linear -> sRGB colorspace.
  213. if (GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_sRGB || GLAD_EXT_framebuffer_sRGB
  214. || GLAD_ES_VERSION_3_0 || GLAD_EXT_sRGB)
  215. {
  216. if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
  217. gl.setFramebufferSRGB(isGammaCorrect());
  218. }
  219. else
  220. setGammaCorrect(false);
  221. bool enabledebug = false;
  222. if (GLAD_VERSION_3_0)
  223. {
  224. // Enable OpenGL's debug output if a debug context has been created.
  225. GLint flags = 0;
  226. glGetIntegerv(GL_CONTEXT_FLAGS, &flags);
  227. enabledebug = (flags & GL_CONTEXT_FLAG_DEBUG_BIT) != 0;
  228. }
  229. setDebug(enabledebug);
  230. if (streamBufferState.vb[0] == nullptr)
  231. {
  232. // Initial sizes that should be good enough for most cases. It will
  233. // resize to fit if needed, later.
  234. streamBufferState.vb[0] = new StreamBuffer(StreamBuffer::MODE_VERTEX, 1024 * 1024 * 1);
  235. streamBufferState.vb[1] = new StreamBuffer(StreamBuffer::MODE_VERTEX, 256 * 1024 * 1);
  236. streamBufferState.indexBuffer = new StreamBuffer(StreamBuffer::MODE_INDEX, sizeof(uint16) * LOVE_UINT16_MAX);
  237. }
  238. // Reload all volatile objects.
  239. if (!Volatile::loadAll())
  240. ::printf("Could not reload all volatile objects.\n");
  241. // Create a quad indices object owned by love.graphics, so at least one
  242. // QuadIndices object is alive at all times while love.graphics is alive.
  243. // This makes sure there aren't too many expensive destruction/creations of
  244. // index buffer objects, since the shared index buffer used by QuadIndices
  245. // objects is destroyed when the last object is destroyed.
  246. if (quadIndices == nullptr)
  247. quadIndices = new QuadIndices(20);
  248. setViewportSize(width, height);
  249. // Restore the graphics state.
  250. restoreState(states.back());
  251. pixelScaleStack.clear();
  252. pixelScaleStack.reserve(5);
  253. pixelScaleStack.push_back(1);
  254. int gammacorrect = isGammaCorrect() ? 1 : 0;
  255. // We always need a default shader.
  256. if (!Shader::defaultShader)
  257. {
  258. Renderer renderer = GLAD_ES_VERSION_2_0 ? RENDERER_OPENGLES : RENDERER_OPENGL;
  259. Shader::defaultShader = newShader(Shader::defaultCode[renderer][gammacorrect]);
  260. }
  261. // and a default video shader.
  262. if (!Shader::defaultVideoShader)
  263. {
  264. Renderer renderer = GLAD_ES_VERSION_2_0 ? RENDERER_OPENGLES : RENDERER_OPENGL;
  265. Shader::defaultVideoShader = newShader(Shader::defaultVideoCode[renderer][gammacorrect]);
  266. }
  267. // A shader should always be active, but the default shader shouldn't be
  268. // returned by getShader(), so we don't do setShader(defaultShader).
  269. if (!Shader::current)
  270. Shader::defaultShader->attach();
  271. return true;
  272. }
  273. void Graphics::unSetMode()
  274. {
  275. if (!isCreated())
  276. return;
  277. flushStreamDraws();
  278. // Unload all volatile objects. These must be reloaded after the display
  279. // mode change.
  280. Volatile::unloadAll();
  281. for (const auto &pair : framebufferObjects)
  282. gl.deleteFramebuffer(pair.second);
  283. for (const CachedRenderbuffer &rb : stencilBuffers)
  284. glDeleteRenderbuffers(1, &rb.renderbuffer);
  285. framebufferObjects.clear();
  286. stencilBuffers.clear();
  287. gl.deInitContext();
  288. created = false;
  289. }
  290. void Graphics::setActive(bool enable)
  291. {
  292. flushStreamDraws();
  293. // Make sure all pending OpenGL commands have fully executed before
  294. // returning, when going from active to inactive. This is required on iOS.
  295. if (isCreated() && this->active && !enable)
  296. glFinish();
  297. active = enable;
  298. }
  299. bool Graphics::isActive() const
  300. {
  301. // The graphics module is only completely 'active' if there's a window, a
  302. // context, and the active variable is set.
  303. auto window = getInstance<love::window::Window>(M_WINDOW);
  304. return active && isCreated() && window != nullptr && window->isOpen();
  305. }
  306. void Graphics::flushStreamDraws()
  307. {
  308. using namespace vertex;
  309. const auto &sbstate = streamBufferState;
  310. if (sbstate.vertexCount == 0 && sbstate.indexCount == 0)
  311. return;
  312. OpenGL::TempDebugGroup debuggroup("Stream vertices flush and draw");
  313. uint32 attribs = 0;
  314. for (int i = 0; i < 2; i++)
  315. {
  316. if (sbstate.formats[i] == CommonFormat::NONE)
  317. continue;
  318. StreamBuffer *buffer = sbstate.vb[i];
  319. buffer->resetOffset();
  320. ptrdiff_t offset = (ptrdiff_t) buffer->getData();
  321. GLsizei stride = (GLsizei) getFormatStride(sbstate.formats[i]);
  322. gl.bindBuffer(BUFFER_VERTEX, 0);
  323. switch (sbstate.formats[i])
  324. {
  325. case CommonFormat::NONE:
  326. break;
  327. case CommonFormat::XYf:
  328. attribs |= ATTRIBFLAG_POS;
  329. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(offset));
  330. break;
  331. case CommonFormat::RGBAub:
  332. attribs |= ATTRIBFLAG_COLOR;
  333. glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, BUFFER_OFFSET(offset));
  334. break;
  335. case CommonFormat::XYf_STf:
  336. attribs |= ATTRIBFLAG_POS | ATTRIBFLAG_TEXCOORD;
  337. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(offset + offsetof(XYf_STf, x)));
  338. glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(offset + offsetof(XYf_STf, s)));
  339. break;
  340. case CommonFormat::XYf_STf_RGBAub:
  341. attribs |= ATTRIBFLAG_POS | ATTRIBFLAG_TEXCOORD | ATTRIBFLAG_COLOR;
  342. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(offset + offsetof(XYf_STf_RGBAub, x)));
  343. glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(offset + offsetof(XYf_STf_RGBAub, s)));
  344. glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, BUFFER_OFFSET(offset + offsetof(XYf_STf_RGBAub, color.r)));
  345. break;
  346. case CommonFormat::XYf_STus_RGBAub:
  347. attribs |= ATTRIBFLAG_POS | ATTRIBFLAG_TEXCOORD | ATTRIBFLAG_COLOR;
  348. glVertexAttribPointer(ATTRIB_POS, 2, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(offset + offsetof(XYf_STus_RGBAub, x)));
  349. glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_UNSIGNED_SHORT, GL_TRUE, stride, BUFFER_OFFSET(offset + offsetof(XYf_STus_RGBAub, s)));
  350. glVertexAttribPointer(ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, BUFFER_OFFSET(offset + offsetof(XYf_STus_RGBAub, color.r)));
  351. break;
  352. }
  353. }
  354. if (attribs == 0)
  355. return;
  356. GLenum glmode = GL_ZERO;
  357. switch (sbstate.primitiveMode)
  358. {
  359. case PrimitiveMode::TRIANGLES:
  360. glmode = GL_TRIANGLES;
  361. break;
  362. case PrimitiveMode::POINTS:
  363. glmode = GL_POINTS;
  364. break;
  365. }
  366. if (attribs & ATTRIBFLAG_COLOR)
  367. glVertexAttrib4f(ATTRIB_CONSTANTCOLOR, 1.0f, 1.0f, 1.0f, 1.0f);
  368. pushIdentityTransform();
  369. gl.prepareDraw();
  370. gl.bindTextureToUnit(sbstate.texture, 0, false);
  371. gl.useVertexAttribArrays(attribs);
  372. if (sbstate.indexCount > 0)
  373. {
  374. sbstate.indexBuffer->resetOffset();
  375. ptrdiff_t offset = (ptrdiff_t) sbstate.indexBuffer->getData();
  376. gl.bindBuffer(BUFFER_INDEX, 0);
  377. gl.drawElements(glmode, sbstate.indexCount, GL_UNSIGNED_SHORT, BUFFER_OFFSET(offset));
  378. }
  379. else
  380. gl.drawArrays(glmode, 0, sbstate.vertexCount);
  381. popTransform();
  382. if (attribs & ATTRIB_CONSTANTCOLOR)
  383. {
  384. Colorf nc = states.back().gammaCorrectedColor;
  385. glVertexAttrib4f(ATTRIB_CONSTANTCOLOR, nc.r, nc.g, nc.b, nc.a);
  386. }
  387. streamBufferState.vertexCount = 0;
  388. streamBufferState.indexCount = 0;
  389. }
  390. static void APIENTRY debugCB(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei /*len*/, const GLchar *msg, const GLvoid* /*usr*/)
  391. {
  392. // Human-readable strings for the debug info.
  393. const char *sourceStr = OpenGL::debugSourceString(source);
  394. const char *typeStr = OpenGL::debugTypeString(type);
  395. const char *severityStr = OpenGL::debugSeverityString(severity);
  396. const char *fmt = "OpenGL: %s [source=%s, type=%s, severity=%s, id=%d]\n";
  397. printf(fmt, msg, sourceStr, typeStr, severityStr, id);
  398. }
  399. void Graphics::setDebug(bool enable)
  400. {
  401. // Make sure debug output is supported. The AMD ext. is a bit different
  402. // so we don't make use of it, since AMD drivers now support KHR_debug.
  403. if (!(GLAD_VERSION_4_3 || GLAD_KHR_debug || GLAD_ARB_debug_output))
  404. return;
  405. // TODO: We don't support GL_KHR_debug in GLES yet.
  406. if (GLAD_ES_VERSION_2_0)
  407. return;
  408. // Ugly hack to reduce code duplication.
  409. if (GLAD_ARB_debug_output && !(GLAD_VERSION_4_3 || GLAD_KHR_debug))
  410. {
  411. fp_glDebugMessageCallback = (pfn_glDebugMessageCallback) fp_glDebugMessageCallbackARB;
  412. fp_glDebugMessageControl = (pfn_glDebugMessageControl) fp_glDebugMessageControlARB;
  413. }
  414. if (!enable)
  415. {
  416. // Disable the debug callback function.
  417. glDebugMessageCallback(nullptr, nullptr);
  418. // We can disable debug output entirely with KHR_debug.
  419. if (GLAD_VERSION_4_3 || GLAD_KHR_debug)
  420. glDisable(GL_DEBUG_OUTPUT);
  421. return;
  422. }
  423. // We don't want asynchronous debug output.
  424. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  425. glDebugMessageCallback(debugCB, nullptr);
  426. // Initially, enable everything.
  427. glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
  428. // Disable messages about deprecated OpenGL functionality.
  429. glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  430. glDebugMessageControl(GL_DEBUG_SOURCE_SHADER_COMPILER, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, GL_DONT_CARE, 0, 0, GL_FALSE);
  431. if (GLAD_VERSION_4_3 || GLAD_KHR_debug)
  432. glEnable(GL_DEBUG_OUTPUT);
  433. ::printf("OpenGL debug output enabled (LOVE_GRAPHICS_DEBUG=1)\n");
  434. }
  435. void Graphics::reset()
  436. {
  437. DisplayState s;
  438. stopDrawToStencilBuffer();
  439. restoreState(s);
  440. origin();
  441. }
  442. void Graphics::setCanvas(Canvas *canvas)
  443. {
  444. if (canvas == nullptr)
  445. return setCanvas();
  446. std::vector<Canvas *> canvases = {canvas};
  447. setCanvas(canvases);
  448. }
  449. void Graphics::setCanvas(const std::vector<Canvas *> &canvases)
  450. {
  451. DisplayState &state = states.back();
  452. int ncanvases = (int) canvases.size();
  453. if (ncanvases == 0)
  454. return setCanvas();
  455. if (ncanvases == (int) state.canvases.size())
  456. {
  457. bool modified = false;
  458. for (int i = 0; i < ncanvases; i++)
  459. {
  460. if (canvases[i] != state.canvases[i].get())
  461. {
  462. modified = true;
  463. break;
  464. }
  465. }
  466. if (!modified)
  467. return;
  468. }
  469. if (ncanvases > gl.getMaxRenderTargets())
  470. throw love::Exception("This system can't simultaneously render to %d canvases.", ncanvases);
  471. Canvas *firstcanvas = canvases[0];
  472. bool multiformatsupported = Canvas::isMultiFormatMultiCanvasSupported();
  473. PixelFormat firstformat = firstcanvas->getPixelFormat();
  474. bool hasSRGBcanvas = firstformat == PIXELFORMAT_sRGBA8;
  475. for (int i = 1; i < ncanvases; i++)
  476. {
  477. Canvas *c = canvases[i];
  478. if (c->getWidth() != firstcanvas->getWidth() || c->getHeight() != firstcanvas->getHeight())
  479. throw love::Exception("All canvases in must have the same dimensions.");
  480. if (!multiformatsupported && c->getPixelFormat() != firstformat)
  481. throw love::Exception("This system doesn't support multi-canvas rendering with different canvas formats.");
  482. if (c->getRequestedMSAA() != firstcanvas->getRequestedMSAA())
  483. throw love::Exception("All Canvases in must have the same requested MSAA value.");
  484. if (c->getPixelFormat() == PIXELFORMAT_sRGBA8)
  485. hasSRGBcanvas = true;
  486. }
  487. OpenGL::TempDebugGroup debuggroup("setCanvas(...)");
  488. endPass();
  489. bindCachedFBO(canvases);
  490. int w = firstcanvas->getWidth();
  491. int h = firstcanvas->getHeight();
  492. gl.setViewport({0, 0, w, h}, true);
  493. projectionMatrix = Matrix4::ortho(0.0, (float) w, 0.0, (float) h);
  494. // Make sure the correct sRGB setting is used when drawing to the canvases.
  495. if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
  496. {
  497. if (hasSRGBcanvas && !gl.hasFramebufferSRGB())
  498. gl.setFramebufferSRGB(true);
  499. else if (!hasSRGBcanvas && gl.hasFramebufferSRGB())
  500. gl.setFramebufferSRGB(false);
  501. }
  502. std::vector<StrongRef<Canvas>> canvasrefs;
  503. canvasrefs.reserve(canvases.size());
  504. for (Canvas *c : canvases)
  505. canvasrefs.push_back(c);
  506. std::swap(state.canvases, canvasrefs);
  507. canvasSwitchCount++;
  508. }
  509. void Graphics::setCanvas(const std::vector<StrongRef<Canvas>> &canvases)
  510. {
  511. std::vector<Canvas *> canvaslist;
  512. canvaslist.reserve(canvases.size());
  513. for (const StrongRef<Canvas> &c : canvases)
  514. canvaslist.push_back(c.get());
  515. return setCanvas(canvaslist);
  516. }
  517. void Graphics::setCanvas()
  518. {
  519. DisplayState &state = states.back();
  520. if (state.canvases.empty())
  521. return;
  522. OpenGL::TempDebugGroup debuggroup("setCanvas()");
  523. endPass();
  524. state.canvases.clear();
  525. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, gl.getDefaultFBO());
  526. gl.setViewport({0, 0, width, height}, false);
  527. // The projection matrix is flipped compared to rendering to a canvas, due
  528. // to OpenGL considering (0,0) bottom-left instead of top-left.
  529. projectionMatrix = Matrix4::ortho(0.0, (float) width, (float) height, 0.0);
  530. if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
  531. {
  532. if (isGammaCorrect() && !gl.hasFramebufferSRGB())
  533. gl.setFramebufferSRGB(true);
  534. else if (!isGammaCorrect() && gl.hasFramebufferSRGB())
  535. gl.setFramebufferSRGB(false);
  536. }
  537. canvasSwitchCount++;
  538. }
  539. std::vector<Canvas *> Graphics::getCanvas() const
  540. {
  541. std::vector<Canvas *> canvases;
  542. canvases.reserve(states.back().canvases.size());
  543. for (const StrongRef<Canvas> &c : states.back().canvases)
  544. canvases.push_back(c.get());
  545. return canvases;
  546. }
  547. void Graphics::endPass()
  548. {
  549. flushStreamDraws();
  550. // Discard the stencil buffer.
  551. discard({}, true);
  552. auto &canvases = states.back().canvases;
  553. // Resolve MSAA buffers.
  554. if (canvases.size() > 0 && canvases[0]->getMSAA() > 1)
  555. {
  556. int w = canvases[0]->getWidth();
  557. int h = canvases[0]->getHeight();
  558. for (int i = 0; i < (int) canvases.size(); i++)
  559. {
  560. glReadBuffer(GL_COLOR_ATTACHMENT0 + i);
  561. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, canvases[i]->getFBO());
  562. if (GLAD_APPLE_framebuffer_multisample)
  563. glResolveMultisampleFramebufferAPPLE();
  564. else
  565. glBlitFramebuffer(0, 0, w, h, 0, 0, w, h, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  566. }
  567. }
  568. }
  569. void Graphics::clear(Colorf c)
  570. {
  571. flushStreamDraws();
  572. gammaCorrectColor(c);
  573. glClearColor(c.r, c.g, c.b, c.a);
  574. glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  575. if (gl.bugs.clearRequiresDriverTextureStateUpdate && Shader::current)
  576. {
  577. // This seems to be enough to fix the bug for me. Other methods I've
  578. // tried (e.g. dummy draws) don't work in all cases.
  579. gl.useProgram(0);
  580. gl.useProgram(Shader::current->getProgram());
  581. }
  582. }
  583. void Graphics::clear(const std::vector<OptionalColorf> &colors)
  584. {
  585. if (colors.size() == 0)
  586. return;
  587. int ncanvases = (int) states.back().canvases.size();
  588. int ncolors = std::min((int) colors.size(), ncanvases);
  589. if (ncolors <= 1 && ncanvases <= 1)
  590. {
  591. if (colors[0].enabled)
  592. clear(colors[0].c);
  593. return;
  594. }
  595. flushStreamDraws();
  596. bool drawbuffersmodified = false;
  597. for (int i = 0; i < ncolors; i++)
  598. {
  599. if (!colors[i].enabled)
  600. continue;
  601. Colorf c = colors[i].c;
  602. gammaCorrectColor(c);
  603. if (GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0)
  604. {
  605. const GLfloat carray[] = {c.r, c.g, c.b, c.a};
  606. glClearBufferfv(GL_COLOR, i, carray);
  607. }
  608. else
  609. {
  610. glDrawBuffer(GL_COLOR_ATTACHMENT0 + i);
  611. glClearColor(c.r, c.g, c.b, c.a);
  612. glClear(GL_COLOR_BUFFER_BIT);
  613. drawbuffersmodified = true;
  614. }
  615. }
  616. // Revert to the expected draw buffers once we're done, if glClearBuffer
  617. // wasn't supported.
  618. if (drawbuffersmodified)
  619. {
  620. GLenum bufs[MAX_COLOR_RENDER_TARGETS];
  621. for (int i = 0; i < ncanvases; i++)
  622. bufs[i] = GL_COLOR_ATTACHMENT0 + i;
  623. glDrawBuffers(ncanvases, bufs);
  624. }
  625. glClear(GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  626. if (gl.bugs.clearRequiresDriverTextureStateUpdate && Shader::current)
  627. {
  628. // This seems to be enough to fix the bug for me. Other methods I've
  629. // tried (e.g. dummy draws) don't work in all cases.
  630. gl.useProgram(0);
  631. gl.useProgram(Shader::current->getProgram());
  632. }
  633. }
  634. bool Graphics::isCanvasActive() const
  635. {
  636. return !states.back().canvases.empty();
  637. }
  638. bool Graphics::isCanvasActive(Canvas *canvas) const
  639. {
  640. for (const auto &c : states.back().canvases)
  641. {
  642. if (c.get() == canvas)
  643. return true;
  644. }
  645. return false;
  646. }
  647. void Graphics::discard(const std::vector<bool> &colorbuffers, bool depthstencil)
  648. {
  649. flushStreamDraws();
  650. discard(OpenGL::FRAMEBUFFER_ALL, colorbuffers, depthstencil);
  651. }
  652. void Graphics::discard(OpenGL::FramebufferTarget target, const std::vector<bool> &colorbuffers, bool depthstencil)
  653. {
  654. if (!(GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0 || GLAD_EXT_discard_framebuffer))
  655. return;
  656. GLenum gltarget = GL_FRAMEBUFFER;
  657. if (target == OpenGL::FRAMEBUFFER_READ)
  658. gltarget = GL_READ_FRAMEBUFFER;
  659. else if (target == OpenGL::FRAMEBUFFER_DRAW)
  660. gltarget = GL_DRAW_FRAMEBUFFER;
  661. std::vector<GLenum> attachments;
  662. attachments.reserve(colorbuffers.size());
  663. // glDiscardFramebuffer uses different attachment enums for the default FBO.
  664. if (states.back().canvases.empty() && gl.getDefaultFBO() == 0)
  665. {
  666. if (colorbuffers.size() > 0 && colorbuffers[0])
  667. attachments.push_back(GL_COLOR);
  668. if (depthstencil)
  669. {
  670. attachments.push_back(GL_STENCIL);
  671. attachments.push_back(GL_DEPTH);
  672. }
  673. }
  674. else
  675. {
  676. int rendertargetcount = std::max((int) states.back().canvases.size(), 1);
  677. for (int i = 0; i < (int) colorbuffers.size(); i++)
  678. {
  679. if (colorbuffers[i] && i < rendertargetcount)
  680. attachments.push_back(GL_COLOR_ATTACHMENT0 + i);
  681. }
  682. if (depthstencil)
  683. {
  684. attachments.push_back(GL_STENCIL_ATTACHMENT);
  685. attachments.push_back(GL_DEPTH_ATTACHMENT);
  686. }
  687. }
  688. // Hint for the driver that it doesn't need to save these buffers.
  689. if (GLAD_VERSION_4_3 || GLAD_ARB_invalidate_subdata || GLAD_ES_VERSION_3_0)
  690. glInvalidateFramebuffer(gltarget, (GLint) attachments.size(), &attachments[0]);
  691. else if (GLAD_EXT_discard_framebuffer)
  692. glDiscardFramebufferEXT(gltarget, (GLint) attachments.size(), &attachments[0]);
  693. }
  694. void Graphics::bindCachedFBO(const std::vector<Canvas *> &canvases)
  695. {
  696. int ncanvases = (int) canvases.size();
  697. uint32 hash = XXH32(&canvases[0], sizeof(Canvas *) * ncanvases, 0);
  698. GLuint fbo = framebufferObjects[hash];
  699. if (fbo != 0)
  700. {
  701. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  702. }
  703. else
  704. {
  705. int w = canvases[0]->getWidth();
  706. int h = canvases[0]->getHeight();
  707. int msaa = std::max(canvases[0]->getMSAA(), 1);
  708. glGenFramebuffers(1, &fbo);
  709. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
  710. GLenum drawbuffers[MAX_COLOR_RENDER_TARGETS];
  711. for (int i = 0; i < ncanvases; i++)
  712. {
  713. drawbuffers[i] = GL_COLOR_ATTACHMENT0 + i;
  714. if (msaa > 1)
  715. {
  716. GLuint rbo = (GLuint) canvases[i]->getMSAAHandle();
  717. glFramebufferRenderbuffer(GL_FRAMEBUFFER, drawbuffers[i], GL_RENDERBUFFER, rbo);
  718. }
  719. else
  720. {
  721. GLuint tex = (GLuint) canvases[i]->getHandle();
  722. glFramebufferTexture2D(GL_FRAMEBUFFER, drawbuffers[i], GL_TEXTURE_2D, tex, 0);
  723. }
  724. }
  725. if (ncanvases > 1)
  726. glDrawBuffers(ncanvases, drawbuffers);
  727. GLuint stencil = attachCachedStencilBuffer(w, h, canvases[0]->getRequestedMSAA());
  728. if (stencil == 0)
  729. {
  730. gl.deleteFramebuffer(fbo);
  731. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, gl.getDefaultFBO());
  732. throw love::Exception("Could not create stencil buffer!");
  733. }
  734. GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  735. if (status != GL_FRAMEBUFFER_COMPLETE)
  736. {
  737. gl.deleteFramebuffer(fbo);
  738. const char *sstr = OpenGL::framebufferStatusString(status);
  739. throw love::Exception("Could not create Framebuffer Object! %s", sstr);
  740. }
  741. framebufferObjects[hash] = fbo;
  742. }
  743. }
  744. GLuint Graphics::attachCachedStencilBuffer(int w, int h, int samples)
  745. {
  746. samples = samples == 1 ? 0 : samples;
  747. for (const CachedRenderbuffer &rb : stencilBuffers)
  748. {
  749. if (rb.w == w && rb.h == h && rb.samples == samples)
  750. {
  751. // Attach the buffer to the framebuffer object.
  752. for (GLenum attachment : rb.attachments)
  753. {
  754. if (attachment != GL_NONE)
  755. glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, rb.renderbuffer);
  756. }
  757. return rb.renderbuffer;
  758. }
  759. }
  760. OpenGL::TempDebugGroup debuggroup("Create cached stencil buffer");
  761. CachedRenderbuffer rb;
  762. rb.w = w;
  763. rb.h = h;
  764. rb.samples = samples;
  765. rb.attachments[0] = GL_STENCIL_ATTACHMENT;
  766. rb.attachments[1] = GL_NONE;
  767. GLenum format = GL_STENCIL_INDEX8;
  768. // Prefer a combined depth/stencil buffer.
  769. if (GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_object)
  770. {
  771. format = GL_DEPTH24_STENCIL8;
  772. rb.attachments[0] = GL_DEPTH_STENCIL_ATTACHMENT;
  773. }
  774. else if (GLAD_EXT_packed_depth_stencil || GLAD_OES_packed_depth_stencil)
  775. {
  776. format = GL_DEPTH24_STENCIL8;
  777. rb.attachments[0] = GL_DEPTH_ATTACHMENT;
  778. rb.attachments[1] = GL_STENCIL_ATTACHMENT;
  779. }
  780. glGenRenderbuffers(1, &rb.renderbuffer);
  781. glBindRenderbuffer(GL_RENDERBUFFER, rb.renderbuffer);
  782. if (rb.samples > 1)
  783. glRenderbufferStorageMultisample(GL_RENDERBUFFER, rb.samples, format, rb.w, rb.h);
  784. else
  785. glRenderbufferStorage(GL_RENDERBUFFER, format, rb.w, rb.h);
  786. // Attach the buffer to the framebuffer object.
  787. for (GLenum attachment : rb.attachments)
  788. {
  789. if (attachment != GL_NONE)
  790. glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, rb.renderbuffer);
  791. }
  792. glBindRenderbuffer(GL_RENDERBUFFER, 0);
  793. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
  794. {
  795. glDeleteRenderbuffers(1, &rb.renderbuffer);
  796. rb.renderbuffer = 0;
  797. }
  798. if (rb.renderbuffer != 0)
  799. {
  800. glClear(GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  801. stencilBuffers.push_back(rb);
  802. }
  803. return rb.renderbuffer;
  804. }
  805. void Graphics::captureScreenshot(const ScreenshotInfo &info)
  806. {
  807. pendingScreenshotCallbacks.push_back(info);
  808. }
  809. void Graphics::present(void *screenshotCallbackData)
  810. {
  811. if (!isActive())
  812. return;
  813. if (!states.back().canvases.empty())
  814. throw love::Exception("present cannot be called while a Canvas is active.");
  815. endPass();
  816. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, gl.getDefaultFBO());
  817. if (!pendingScreenshotCallbacks.empty())
  818. {
  819. int w = getWidth();
  820. int h = getHeight();
  821. size_t row = 4 * w;
  822. size_t size = row * h;
  823. GLubyte *pixels = nullptr;
  824. GLubyte *screenshot = nullptr;
  825. try
  826. {
  827. pixels = new GLubyte[size];
  828. screenshot = new GLubyte[size];
  829. }
  830. catch (std::exception &)
  831. {
  832. delete[] pixels;
  833. delete[] screenshot;
  834. throw love::Exception("Out of memory.");
  835. }
  836. #ifdef LOVE_IOS
  837. SDL_SysWMinfo info = {};
  838. SDL_VERSION(&info.version);
  839. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  840. if (info.info.uikit.resolveFramebuffer != 0)
  841. {
  842. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, info.info.uikit.resolveFramebuffer);
  843. // We need to do an explicit MSAA resolve on iOS, because it uses GLES
  844. // FBOs rather than a system framebuffer.
  845. if (GLAD_ES_VERSION_3_0)
  846. glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
  847. else if (GLAD_APPLE_framebuffer_multisample)
  848. glResolveMultisampleFramebufferAPPLE();
  849. gl.bindFramebuffer(OpenGL::FRAMEBUFFER_READ, info.info.uikit.resolveFramebuffer);
  850. }
  851. #endif
  852. glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  853. // Replace alpha values with full opacity.
  854. for (size_t i = 3; i < size; i += 4)
  855. pixels[i] = 255;
  856. // OpenGL sucks and reads pixels from the lower-left. Let's fix that.
  857. GLubyte *src = pixels - row;
  858. GLubyte *dst = screenshot + size;
  859. for (int i = 0; i < h; ++i)
  860. memcpy(dst-=row, src+=row, row);
  861. delete[] pixels;
  862. auto imagemodule = Module::getInstance<love::image::Image>(M_IMAGE);
  863. for (int i = 0; i < (int) pendingScreenshotCallbacks.size(); i++)
  864. {
  865. const auto &info = pendingScreenshotCallbacks[i];
  866. image::ImageData *img = nullptr;
  867. try
  868. {
  869. img = imagemodule->newImageData(w, h, PIXELFORMAT_RGBA8, screenshot);
  870. }
  871. catch (love::Exception &)
  872. {
  873. delete[] screenshot;
  874. info.callback(nullptr, info.ref, nullptr);
  875. for (int j = i + 1; j < (int) pendingScreenshotCallbacks.size(); j++)
  876. {
  877. const auto &ninfo = pendingScreenshotCallbacks[j];
  878. ninfo.callback(nullptr, ninfo.ref, nullptr);
  879. }
  880. pendingScreenshotCallbacks.clear();
  881. throw;
  882. }
  883. info.callback(img, info.ref, screenshotCallbackData);
  884. img->release();
  885. }
  886. delete[] screenshot;
  887. pendingScreenshotCallbacks.clear();
  888. }
  889. #ifdef LOVE_IOS
  890. // Hack: SDL's color renderbuffer must be bound when swapBuffers is called.
  891. SDL_SysWMinfo info = {};
  892. SDL_VERSION(&info.version);
  893. SDL_GetWindowWMInfo(SDL_GL_GetCurrentWindow(), &info);
  894. glBindRenderbuffer(GL_RENDERBUFFER, info.info.uikit.colorbuffer);
  895. #endif
  896. auto window = getInstance<love::window::Window>(M_WINDOW);
  897. if (window != nullptr)
  898. window->swapBuffers();
  899. // Reset the per-frame stat counts.
  900. gl.stats.drawCalls = 0;
  901. gl.stats.shaderSwitches = 0;
  902. canvasSwitchCount = 0;
  903. }
  904. int Graphics::getWidth() const
  905. {
  906. return width;
  907. }
  908. int Graphics::getHeight() const
  909. {
  910. return height;
  911. }
  912. bool Graphics::isCreated() const
  913. {
  914. return created;
  915. }
  916. void Graphics::setScissor(const Rect &rect)
  917. {
  918. flushStreamDraws();
  919. DisplayState &state = states.back();
  920. glEnable(GL_SCISSOR_TEST);
  921. // OpenGL's reversed y-coordinate is compensated for in OpenGL::setScissor.
  922. gl.setScissor(rect, !state.canvases.empty());
  923. state.scissor = true;
  924. state.scissorRect = rect;
  925. }
  926. void Graphics::intersectScissor(const Rect &rect)
  927. {
  928. Rect currect = states.back().scissorRect;
  929. if (!states.back().scissor)
  930. {
  931. currect.x = 0;
  932. currect.y = 0;
  933. currect.w = std::numeric_limits<int>::max();
  934. currect.h = std::numeric_limits<int>::max();
  935. }
  936. int x1 = std::max(currect.x, rect.x);
  937. int y1 = std::max(currect.y, rect.y);
  938. int x2 = std::min(currect.x + currect.w, rect.x + rect.w);
  939. int y2 = std::min(currect.y + currect.h, rect.y + rect.h);
  940. Rect newrect = {x1, y1, std::max(0, x2 - x1), std::max(0, y2 - y1)};
  941. setScissor(newrect);
  942. }
  943. void Graphics::setScissor()
  944. {
  945. flushStreamDraws();
  946. states.back().scissor = false;
  947. glDisable(GL_SCISSOR_TEST);
  948. }
  949. bool Graphics::getScissor(Rect &rect) const
  950. {
  951. const DisplayState &state = states.back();
  952. rect = state.scissorRect;
  953. return state.scissor;
  954. }
  955. void Graphics::drawToStencilBuffer(StencilAction action, int value)
  956. {
  957. writingToStencil = true;
  958. // Disable color writes but don't save the state for it.
  959. glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  960. GLenum glaction = GL_REPLACE;
  961. switch (action)
  962. {
  963. case STENCIL_REPLACE:
  964. default:
  965. glaction = GL_REPLACE;
  966. break;
  967. case STENCIL_INCREMENT:
  968. glaction = GL_INCR;
  969. break;
  970. case STENCIL_DECREMENT:
  971. glaction = GL_DECR;
  972. break;
  973. case STENCIL_INCREMENT_WRAP:
  974. glaction = GL_INCR_WRAP;
  975. break;
  976. case STENCIL_DECREMENT_WRAP:
  977. glaction = GL_DECR_WRAP;
  978. break;
  979. case STENCIL_INVERT:
  980. glaction = GL_INVERT;
  981. break;
  982. }
  983. // The stencil test must be enabled in order to write to the stencil buffer.
  984. glEnable(GL_STENCIL_TEST);
  985. glStencilFunc(GL_ALWAYS, value, 0xFFFFFFFF);
  986. glStencilOp(GL_KEEP, GL_KEEP, glaction);
  987. }
  988. void Graphics::stopDrawToStencilBuffer()
  989. {
  990. if (!writingToStencil)
  991. return;
  992. flushStreamDraws();
  993. writingToStencil = false;
  994. const DisplayState &state = states.back();
  995. // Revert the color write mask.
  996. setColorMask(state.colorMask);
  997. // Use the user-set stencil test state when writes are disabled.
  998. setStencilTest(state.stencilCompare, state.stencilTestValue);
  999. }
  1000. void Graphics::setStencilTest(CompareMode compare, int value)
  1001. {
  1002. DisplayState &state = states.back();
  1003. state.stencilCompare = compare;
  1004. state.stencilTestValue = value;
  1005. if (writingToStencil)
  1006. return;
  1007. if (compare == COMPARE_ALWAYS)
  1008. {
  1009. glDisable(GL_STENCIL_TEST);
  1010. return;
  1011. }
  1012. GLenum glcompare = GL_EQUAL;
  1013. /**
  1014. * Q: Why are some of the compare modes inverted (e.g. COMPARE_LESS becomes
  1015. * GL_GREATER)?
  1016. *
  1017. * A: OpenGL / GPUs do the comparison in the opposite way that makes sense
  1018. * for this API. For example, if the compare function is GL_GREATER then the
  1019. * stencil test will pass if the reference value is greater than the value
  1020. * in the stencil buffer. With our API it's more intuitive to assume that
  1021. * setStencilTest(COMPARE_GREATER, 4) will make it pass if the stencil
  1022. * buffer has a value greater than 4.
  1023. **/
  1024. switch (compare)
  1025. {
  1026. case COMPARE_LESS:
  1027. glcompare = GL_GREATER;
  1028. break;
  1029. case COMPARE_LEQUAL:
  1030. glcompare = GL_GEQUAL;
  1031. break;
  1032. case COMPARE_EQUAL:
  1033. default:
  1034. glcompare = GL_EQUAL;
  1035. break;
  1036. case COMPARE_GEQUAL:
  1037. glcompare = GL_LEQUAL;
  1038. break;
  1039. case COMPARE_GREATER:
  1040. glcompare = GL_LESS;
  1041. break;
  1042. case COMPARE_NOTEQUAL:
  1043. glcompare = GL_NOTEQUAL;
  1044. break;
  1045. case COMPARE_ALWAYS:
  1046. glcompare = GL_ALWAYS;
  1047. break;
  1048. }
  1049. glEnable(GL_STENCIL_TEST);
  1050. glStencilFunc(glcompare, value, 0xFFFFFFFF);
  1051. glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  1052. }
  1053. void Graphics::setStencilTest()
  1054. {
  1055. setStencilTest(COMPARE_ALWAYS, 0);
  1056. }
  1057. void Graphics::getStencilTest(CompareMode &compare, int &value)
  1058. {
  1059. const DisplayState &state = states.back();
  1060. compare = state.stencilCompare;
  1061. value = state.stencilTestValue;
  1062. }
  1063. void Graphics::clearStencil()
  1064. {
  1065. glClear(GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  1066. }
  1067. Image *Graphics::newImage(const std::vector<love::image::ImageData *> &data, const Image::Flags &flags)
  1068. {
  1069. return new Image(data, flags);
  1070. }
  1071. Image *Graphics::newImage(const std::vector<love::image::CompressedImageData *> &cdata, const Image::Flags &flags)
  1072. {
  1073. return new Image(cdata, flags);
  1074. }
  1075. Quad *Graphics::newQuad(Quad::Viewport v, double sw, double sh)
  1076. {
  1077. return new Quad(v, sw, sh);
  1078. }
  1079. Font *Graphics::newFont(love::font::Rasterizer *r, const Texture::Filter &filter)
  1080. {
  1081. return new Font(r, filter);
  1082. }
  1083. SpriteBatch *Graphics::newSpriteBatch(Texture *texture, int size, Mesh::Usage usage)
  1084. {
  1085. return new SpriteBatch(texture, size, usage);
  1086. }
  1087. ParticleSystem *Graphics::newParticleSystem(Texture *texture, int size)
  1088. {
  1089. return new ParticleSystem(texture, size);
  1090. }
  1091. Canvas *Graphics::newCanvas(int width, int height, PixelFormat format, int msaa)
  1092. {
  1093. if (!Canvas::isSupported())
  1094. throw love::Exception("Canvases are not supported by your OpenGL drivers!");
  1095. if (!Canvas::isFormatSupported(format))
  1096. {
  1097. const char *fstr = "rgba8";
  1098. love::getConstant(Canvas::getSizedFormat(format), fstr);
  1099. throw love::Exception("The %s canvas format is not supported by your OpenGL drivers.", fstr);
  1100. }
  1101. if (width > gl.getMaxTextureSize())
  1102. throw Exception("Cannot create canvas: width of %d pixels is too large for this system.", width);
  1103. else if (height > gl.getMaxTextureSize())
  1104. throw Exception("Cannot create canvas: height of %d pixels is too large for this system.", height);
  1105. Canvas *canvas = new Canvas(width, height, format, msaa);
  1106. GLenum err = canvas->getStatus();
  1107. // everything ok, return canvas (early out)
  1108. if (err == GL_FRAMEBUFFER_COMPLETE)
  1109. return canvas;
  1110. canvas->release();
  1111. throw love::Exception("Cannot create Canvas: %s", OpenGL::framebufferStatusString(err));
  1112. return nullptr; // never reached
  1113. }
  1114. Shader *Graphics::newShader(const Shader::ShaderSource &source)
  1115. {
  1116. return new Shader(source);
  1117. }
  1118. Mesh *Graphics::newMesh(const std::vector<Vertex> &vertices, Mesh::DrawMode drawmode, Mesh::Usage usage)
  1119. {
  1120. return new Mesh(vertices, drawmode, usage);
  1121. }
  1122. Mesh *Graphics::newMesh(int vertexcount, Mesh::DrawMode drawmode, Mesh::Usage usage)
  1123. {
  1124. return new Mesh(vertexcount, drawmode, usage);
  1125. }
  1126. Mesh *Graphics::newMesh(const std::vector<Mesh::AttribFormat> &vertexformat, int vertexcount, Mesh::DrawMode drawmode, Mesh::Usage usage)
  1127. {
  1128. return new Mesh(vertexformat, vertexcount, drawmode, usage);
  1129. }
  1130. Mesh *Graphics::newMesh(const std::vector<Mesh::AttribFormat> &vertexformat, const void *data, size_t datasize, Mesh::DrawMode drawmode, Mesh::Usage usage)
  1131. {
  1132. return new Mesh(vertexformat, data, datasize, drawmode, usage);
  1133. }
  1134. Text *Graphics::newText(Font *font, const std::vector<Font::ColoredString> &text)
  1135. {
  1136. return new Text(font, text);
  1137. }
  1138. Video *Graphics::newVideo(love::video::VideoStream *stream)
  1139. {
  1140. return new Video(stream);
  1141. }
  1142. bool Graphics::isGammaCorrect() const
  1143. {
  1144. return love::graphics::isGammaCorrect();
  1145. }
  1146. void Graphics::setColor(Colorf c)
  1147. {
  1148. c.r = std::min(std::max(c.r, 0.0f), 1.0f);
  1149. c.g = std::min(std::max(c.g, 0.0f), 1.0f);
  1150. c.b = std::min(std::max(c.b, 0.0f), 1.0f);
  1151. c.a = std::min(std::max(c.a, 0.0f), 1.0f);
  1152. Colorf nc = c;
  1153. gammaCorrectColor(nc);
  1154. glVertexAttrib4f(ATTRIB_CONSTANTCOLOR, nc.r, nc.g, nc.b, nc.a);
  1155. states.back().color = c;
  1156. states.back().gammaCorrectedColor = nc;
  1157. }
  1158. Colorf Graphics::getColor() const
  1159. {
  1160. return states.back().color;
  1161. }
  1162. void Graphics::setBackgroundColor(Colorf c)
  1163. {
  1164. states.back().backgroundColor = c;
  1165. }
  1166. Colorf Graphics::getBackgroundColor() const
  1167. {
  1168. return states.back().backgroundColor;
  1169. }
  1170. void Graphics::setFont(Font *font)
  1171. {
  1172. // We don't need to set a default font here if null is passed in, since we
  1173. // only care about the default font in getFont and print.
  1174. DisplayState &state = states.back();
  1175. state.font.set(font);
  1176. }
  1177. Font *Graphics::getFont()
  1178. {
  1179. checkSetDefaultFont();
  1180. return states.back().font.get();
  1181. }
  1182. void Graphics::setShader(Shader *shader)
  1183. {
  1184. if (shader == nullptr)
  1185. return setShader();
  1186. flushStreamDraws();
  1187. DisplayState &state = states.back();
  1188. shader->attach();
  1189. state.shader.set(shader);
  1190. }
  1191. void Graphics::setShader()
  1192. {
  1193. flushStreamDraws();
  1194. DisplayState &state = states.back();
  1195. // This will activate the default shader.
  1196. Shader::detach();
  1197. state.shader.set(nullptr);
  1198. }
  1199. Shader *Graphics::getShader() const
  1200. {
  1201. return states.back().shader.get();
  1202. }
  1203. void Graphics::setColorMask(ColorMask mask)
  1204. {
  1205. flushStreamDraws();
  1206. glColorMask(mask.r, mask.g, mask.b, mask.a);
  1207. states.back().colorMask = mask;
  1208. }
  1209. Graphics::ColorMask Graphics::getColorMask() const
  1210. {
  1211. return states.back().colorMask;
  1212. }
  1213. void Graphics::setBlendMode(BlendMode mode, BlendAlpha alphamode)
  1214. {
  1215. flushStreamDraws();
  1216. GLenum func = GL_FUNC_ADD;
  1217. GLenum srcRGB = GL_ONE;
  1218. GLenum srcA = GL_ONE;
  1219. GLenum dstRGB = GL_ZERO;
  1220. GLenum dstA = GL_ZERO;
  1221. if (mode == BLEND_LIGHTEN || mode == BLEND_DARKEN)
  1222. {
  1223. if (!isSupported(FEATURE_LIGHTEN))
  1224. throw love::Exception("The 'lighten' and 'darken' blend modes are not supported on this system.");
  1225. }
  1226. if (alphamode != BLENDALPHA_PREMULTIPLIED)
  1227. {
  1228. const char *modestr = "unknown";
  1229. switch (mode)
  1230. {
  1231. case BLEND_LIGHTEN:
  1232. case BLEND_DARKEN:
  1233. case BLEND_MULTIPLY:
  1234. getConstant(mode, modestr);
  1235. throw love::Exception("The '%s' blend mode must be used with premultiplied alpha.", modestr);
  1236. break;
  1237. default:
  1238. break;
  1239. }
  1240. }
  1241. switch (mode)
  1242. {
  1243. case BLEND_ALPHA:
  1244. srcRGB = srcA = GL_ONE;
  1245. dstRGB = dstA = GL_ONE_MINUS_SRC_ALPHA;
  1246. break;
  1247. case BLEND_MULTIPLY:
  1248. srcRGB = srcA = GL_DST_COLOR;
  1249. dstRGB = dstA = GL_ZERO;
  1250. break;
  1251. case BLEND_SUBTRACT:
  1252. func = GL_FUNC_REVERSE_SUBTRACT;
  1253. case BLEND_ADD:
  1254. srcRGB = GL_ONE;
  1255. srcA = GL_ZERO;
  1256. dstRGB = dstA = GL_ONE;
  1257. break;
  1258. case BLEND_LIGHTEN:
  1259. func = GL_MAX;
  1260. break;
  1261. case BLEND_DARKEN:
  1262. func = GL_MIN;
  1263. break;
  1264. case BLEND_SCREEN:
  1265. srcRGB = srcA = GL_ONE;
  1266. dstRGB = dstA = GL_ONE_MINUS_SRC_COLOR;
  1267. break;
  1268. case BLEND_REPLACE:
  1269. case BLEND_NONE:
  1270. default:
  1271. srcRGB = srcA = GL_ONE;
  1272. dstRGB = dstA = GL_ZERO;
  1273. break;
  1274. }
  1275. // We can only do alpha-multiplication when srcRGB would have been unmodified.
  1276. if (srcRGB == GL_ONE && alphamode == BLENDALPHA_MULTIPLY && mode != BLEND_NONE)
  1277. srcRGB = GL_SRC_ALPHA;
  1278. glBlendEquation(func);
  1279. glBlendFuncSeparate(srcRGB, dstRGB, srcA, dstA);
  1280. states.back().blendMode = mode;
  1281. states.back().blendAlphaMode = alphamode;
  1282. }
  1283. Graphics::BlendMode Graphics::getBlendMode(BlendAlpha &alphamode) const
  1284. {
  1285. alphamode = states.back().blendAlphaMode;
  1286. return states.back().blendMode;
  1287. }
  1288. void Graphics::setDefaultFilter(const Texture::Filter &f)
  1289. {
  1290. Texture::setDefaultFilter(f);
  1291. states.back().defaultFilter = f;
  1292. }
  1293. const Texture::Filter &Graphics::getDefaultFilter() const
  1294. {
  1295. return Texture::getDefaultFilter();
  1296. }
  1297. void Graphics::setDefaultMipmapFilter(Texture::FilterMode filter, float sharpness)
  1298. {
  1299. Image::setDefaultMipmapFilter(filter);
  1300. Image::setDefaultMipmapSharpness(sharpness);
  1301. states.back().defaultMipmapFilter = filter;
  1302. states.back().defaultMipmapSharpness = sharpness;
  1303. }
  1304. void Graphics::getDefaultMipmapFilter(Texture::FilterMode *filter, float *sharpness) const
  1305. {
  1306. *filter = Image::getDefaultMipmapFilter();
  1307. *sharpness = Image::getDefaultMipmapSharpness();
  1308. }
  1309. void Graphics::setLineWidth(float width)
  1310. {
  1311. states.back().lineWidth = width;
  1312. }
  1313. void Graphics::setLineStyle(Graphics::LineStyle style)
  1314. {
  1315. states.back().lineStyle = style;
  1316. }
  1317. void Graphics::setLineJoin(Graphics::LineJoin join)
  1318. {
  1319. states.back().lineJoin = join;
  1320. }
  1321. float Graphics::getLineWidth() const
  1322. {
  1323. return states.back().lineWidth;
  1324. }
  1325. Graphics::LineStyle Graphics::getLineStyle() const
  1326. {
  1327. return states.back().lineStyle;
  1328. }
  1329. Graphics::LineJoin Graphics::getLineJoin() const
  1330. {
  1331. return states.back().lineJoin;
  1332. }
  1333. void Graphics::setPointSize(float size)
  1334. {
  1335. if (streamBufferState.primitiveMode == vertex::PrimitiveMode::POINTS)
  1336. flushStreamDraws();
  1337. gl.setPointSize(size);
  1338. states.back().pointSize = size;
  1339. }
  1340. float Graphics::getPointSize() const
  1341. {
  1342. return states.back().pointSize;
  1343. }
  1344. void Graphics::setWireframe(bool enable)
  1345. {
  1346. // Not supported in OpenGL ES.
  1347. if (GLAD_ES_VERSION_2_0)
  1348. return;
  1349. flushStreamDraws();
  1350. glPolygonMode(GL_FRONT_AND_BACK, enable ? GL_LINE : GL_FILL);
  1351. states.back().wireframe = enable;
  1352. }
  1353. bool Graphics::isWireframe() const
  1354. {
  1355. return states.back().wireframe;
  1356. }
  1357. void Graphics::draw(Drawable *drawable, const Matrix4 &m)
  1358. {
  1359. drawable->draw(this, m);
  1360. }
  1361. void Graphics::draw(Texture *texture, Quad *quad, const Matrix4 &m)
  1362. {
  1363. texture->drawq(this, quad, m);
  1364. }
  1365. void Graphics::print(const std::vector<Font::ColoredString> &str, const Matrix4 &m)
  1366. {
  1367. checkSetDefaultFont();
  1368. DisplayState &state = states.back();
  1369. if (state.font.get() != nullptr)
  1370. state.font->print(str, m);
  1371. }
  1372. void Graphics::printf(const std::vector<Font::ColoredString> &str, float wrap, Font::AlignMode align, const Matrix4 &m)
  1373. {
  1374. checkSetDefaultFont();
  1375. DisplayState &state = states.back();
  1376. if (state.font.get() != nullptr)
  1377. state.font->printf(str, wrap, align, m);
  1378. }
  1379. /**
  1380. * Primitives
  1381. **/
  1382. void Graphics::points(const float *coords, const Colorf *colors, size_t numpoints)
  1383. {
  1384. StreamDrawRequest req;
  1385. req.primitiveMode = vertex::PrimitiveMode::POINTS;
  1386. req.formats[0] = vertex::CommonFormat::XYf;
  1387. if (colors)
  1388. req.formats[1] = vertex::CommonFormat::RGBAub;
  1389. req.vertexCount = (int) numpoints;
  1390. StreamVertexData data = requestStreamDraw(req);
  1391. const Matrix4 &t = getTransform();
  1392. t.transform((Vector *) data.stream[0], (const Vector *) coords, req.vertexCount);
  1393. Color *colordata = (Color *) data.stream[1];
  1394. if (colors)
  1395. {
  1396. Colorf nc = getColor();
  1397. gammaCorrectColor(nc);
  1398. if (isGammaCorrect())
  1399. {
  1400. for (int i = 0; i < req.vertexCount; i++)
  1401. {
  1402. Colorf ci = colors[i];
  1403. gammaCorrectColor(ci);
  1404. ci *= nc;
  1405. unGammaCorrectColor(ci);
  1406. colordata[i] = toColor(ci);
  1407. }
  1408. }
  1409. else
  1410. {
  1411. for (int i = 0; i < req.vertexCount; i++)
  1412. colordata[i] = toColor(nc * colors[i]);
  1413. }
  1414. }
  1415. else
  1416. {
  1417. Color c = toColor(getColor());
  1418. for (int i = 0; i < req.vertexCount; i++)
  1419. colordata[i] = c;
  1420. }
  1421. }
  1422. Graphics::RendererInfo Graphics::getRendererInfo() const
  1423. {
  1424. RendererInfo info;
  1425. if (GLAD_ES_VERSION_2_0)
  1426. info.name = "OpenGL ES";
  1427. else
  1428. info.name = "OpenGL";
  1429. const char *str = (const char *) glGetString(GL_VERSION);
  1430. if (str)
  1431. info.version = str;
  1432. else
  1433. throw love::Exception("Cannot retrieve renderer version information.");
  1434. str = (const char *) glGetString(GL_VENDOR);
  1435. if (str)
  1436. info.vendor = str;
  1437. else
  1438. throw love::Exception("Cannot retrieve renderer vendor information.");
  1439. str = (const char *) glGetString(GL_RENDERER);
  1440. if (str)
  1441. info.device = str;
  1442. else
  1443. throw love::Exception("Cannot retrieve renderer device information.");
  1444. return info;
  1445. }
  1446. Graphics::Stats Graphics::getStats() const
  1447. {
  1448. int drawcalls = gl.stats.drawCalls;
  1449. if (streamBufferState.vertexCount > 0)
  1450. drawcalls++;
  1451. Stats stats;
  1452. stats.drawCalls = drawcalls;
  1453. stats.canvasSwitches = canvasSwitchCount;
  1454. stats.shaderSwitches = gl.stats.shaderSwitches;
  1455. stats.canvases = Canvas::canvasCount;
  1456. stats.images = Image::imageCount;
  1457. stats.fonts = Font::fontCount;
  1458. stats.textureMemory = gl.stats.textureMemory;
  1459. return stats;
  1460. }
  1461. double Graphics::getSystemLimit(SystemLimit limittype) const
  1462. {
  1463. switch (limittype)
  1464. {
  1465. case Graphics::LIMIT_POINT_SIZE:
  1466. return (double) gl.getMaxPointSize();
  1467. case Graphics::LIMIT_TEXTURE_SIZE:
  1468. return (double) gl.getMaxTextureSize();
  1469. case Graphics::LIMIT_MULTI_CANVAS:
  1470. return (double) gl.getMaxRenderTargets();
  1471. case Graphics::LIMIT_CANVAS_MSAA:
  1472. return (double) gl.getMaxRenderbufferSamples();
  1473. case Graphics::LIMIT_ANISOTROPY:
  1474. return (double) gl.getMaxAnisotropy();
  1475. default:
  1476. return 0.0;
  1477. }
  1478. }
  1479. bool Graphics::isSupported(Feature feature) const
  1480. {
  1481. switch (feature)
  1482. {
  1483. case FEATURE_MULTI_CANVAS_FORMATS:
  1484. return Canvas::isMultiFormatMultiCanvasSupported();
  1485. case FEATURE_CLAMP_ZERO:
  1486. return gl.isClampZeroTextureWrapSupported();
  1487. case FEATURE_LIGHTEN:
  1488. return GLAD_VERSION_1_4 || GLAD_ES_VERSION_3_0 || GLAD_EXT_blend_minmax;
  1489. case FEATURE_FULL_NPOT:
  1490. return GLAD_VERSION_2_0 || GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot;
  1491. case FEATURE_PIXEL_SHADER_HIGHP:
  1492. return gl.isPixelShaderHighpSupported();
  1493. default:
  1494. return false;
  1495. }
  1496. }
  1497. void Graphics::push(StackType type)
  1498. {
  1499. if (stackTypes.size() == MAX_USER_STACK_DEPTH)
  1500. throw Exception("Maximum stack depth reached (more pushes than pops?)");
  1501. pushTransform();
  1502. pixelScaleStack.push_back(pixelScaleStack.back());
  1503. if (type == STACK_ALL)
  1504. states.push_back(states.back());
  1505. stackTypes.push_back(type);
  1506. }
  1507. void Graphics::pop()
  1508. {
  1509. if (stackTypes.size() < 1)
  1510. throw Exception("Minimum stack depth reached (more pops than pushes?)");
  1511. popTransform();
  1512. pixelScaleStack.pop_back();
  1513. if (stackTypes.back() == STACK_ALL)
  1514. {
  1515. DisplayState &newstate = states[states.size() - 2];
  1516. restoreStateChecked(newstate);
  1517. // The last two states in the stack should be equal now.
  1518. states.pop_back();
  1519. }
  1520. stackTypes.pop_back();
  1521. }
  1522. void Graphics::rotate(float r)
  1523. {
  1524. transformStack.back().rotate(r);
  1525. }
  1526. void Graphics::scale(float x, float y)
  1527. {
  1528. transformStack.back().scale(x, y);
  1529. pixelScaleStack.back() *= (fabs(x) + fabs(y)) / 2.0;
  1530. }
  1531. void Graphics::translate(float x, float y)
  1532. {
  1533. transformStack.back().translate(x, y);
  1534. }
  1535. void Graphics::shear(float kx, float ky)
  1536. {
  1537. transformStack.back().shear(kx, ky);
  1538. }
  1539. void Graphics::origin()
  1540. {
  1541. transformStack.back().setIdentity();
  1542. pixelScaleStack.back() = 1;
  1543. }
  1544. void Graphics::applyTransform(love::math::Transform *transform)
  1545. {
  1546. Matrix4 &m = transformStack.back();
  1547. m *= transform->getMatrix();
  1548. float sx, sy;
  1549. m.getApproximateScale(sx, sy);
  1550. pixelScaleStack.back() = (sx + sy) / 2.0;
  1551. }
  1552. void Graphics::replaceTransform(love::math::Transform *transform)
  1553. {
  1554. const Matrix4 &m = transform->getMatrix();
  1555. transformStack.back() = m;
  1556. float sx, sy;
  1557. m.getApproximateScale(sx, sy);
  1558. pixelScaleStack.back() = (sx + sy) / 2.0;
  1559. }
  1560. Vector Graphics::transformPoint(Vector point)
  1561. {
  1562. Vector p;
  1563. transformStack.back().transform(&p, &point, 1);
  1564. return p;
  1565. }
  1566. Vector Graphics::inverseTransformPoint(Vector point)
  1567. {
  1568. Vector p;
  1569. // TODO: We should probably cache the inverse transform so we don't have to
  1570. // re-calculate it every time this is called.
  1571. transformStack.back().inverse().transform(&p, &point, 1);
  1572. return p;
  1573. }
  1574. } // opengl
  1575. } // graphics
  1576. } // love