Graphics.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926
  1. /**
  2. * Copyright (c) 2006-2020 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. // LOVE
  21. #include "Graphics.h"
  22. #include "Buffer.h"
  23. #include "math/MathModule.h"
  24. #include "data/DataModule.h"
  25. #include "Polyline.h"
  26. #include "font/Font.h"
  27. #include "window/Window.h"
  28. #include "SpriteBatch.h"
  29. #include "ParticleSystem.h"
  30. #include "Font.h"
  31. #include "Video.h"
  32. #include "Text.h"
  33. #include "common/deprecation.h"
  34. // C++
  35. #include <algorithm>
  36. #include <stdlib.h>
  37. namespace love
  38. {
  39. namespace graphics
  40. {
  41. static bool gammaCorrect = false;
  42. static bool debugMode = false;
  43. static bool debugModeQueried = false;
  44. void setGammaCorrect(bool gammacorrect)
  45. {
  46. gammaCorrect = gammacorrect;
  47. }
  48. bool isGammaCorrect()
  49. {
  50. return gammaCorrect;
  51. }
  52. void gammaCorrectColor(Colorf &c)
  53. {
  54. if (isGammaCorrect())
  55. {
  56. c.r = math::gammaToLinear(c.r);
  57. c.g = math::gammaToLinear(c.g);
  58. c.b = math::gammaToLinear(c.b);
  59. }
  60. }
  61. Colorf gammaCorrectColor(const Colorf &c)
  62. {
  63. Colorf r = c;
  64. gammaCorrectColor(r);
  65. return r;
  66. }
  67. void unGammaCorrectColor(Colorf &c)
  68. {
  69. if (isGammaCorrect())
  70. {
  71. c.r = math::linearToGamma(c.r);
  72. c.g = math::linearToGamma(c.g);
  73. c.b = math::linearToGamma(c.b);
  74. }
  75. }
  76. Colorf unGammaCorrectColor(const Colorf &c)
  77. {
  78. Colorf r = c;
  79. unGammaCorrectColor(r);
  80. return r;
  81. }
  82. bool isDebugEnabled()
  83. {
  84. if (!debugModeQueried)
  85. {
  86. const char *debugenv = getenv("LOVE_GRAPHICS_DEBUG");
  87. debugMode = debugenv != nullptr && debugenv[0] != '0';
  88. debugModeQueried = true;
  89. }
  90. return debugMode;
  91. }
  92. love::Type Graphics::type("graphics", &Module::type);
  93. Graphics::DefaultShaderCode Graphics::defaultShaderCode[Shader::STANDARD_MAX_ENUM][Shader::LANGUAGE_MAX_ENUM][2];
  94. Graphics::Graphics()
  95. : width(0)
  96. , height(0)
  97. , pixelWidth(0)
  98. , pixelHeight(0)
  99. , created(false)
  100. , active(true)
  101. , writingToStencil(false)
  102. , streamBufferState()
  103. , projectionMatrix()
  104. , renderTargetSwitchCount(0)
  105. , drawCalls(0)
  106. , drawCallsBatched(0)
  107. , quadIndexBuffer(nullptr)
  108. , capabilities()
  109. , cachedShaderStages()
  110. {
  111. transformStack.reserve(16);
  112. transformStack.push_back(Matrix4());
  113. pixelScaleStack.reserve(16);
  114. pixelScaleStack.push_back(1);
  115. states.reserve(10);
  116. states.push_back(DisplayState());
  117. if (!Shader::initialize())
  118. throw love::Exception("Shader support failed to initialize!");
  119. }
  120. Graphics::~Graphics()
  121. {
  122. delete quadIndexBuffer;
  123. // Clean up standard shaders before the active shader. If we do it after,
  124. // the active shader may try to activate a standard shader when deactivating
  125. // itself, which will cause problems since it calls Graphics methods in the
  126. // Graphics destructor.
  127. for (int i = 0; i < Shader::STANDARD_MAX_ENUM; i++)
  128. {
  129. if (Shader::standardShaders[i])
  130. {
  131. Shader::standardShaders[i]->release();
  132. Shader::standardShaders[i] = nullptr;
  133. }
  134. }
  135. states.clear();
  136. defaultFont.set(nullptr);
  137. delete streamBufferState.vb[0];
  138. delete streamBufferState.vb[1];
  139. delete streamBufferState.indexBuffer;
  140. for (int i = 0; i < (int) ShaderStage::STAGE_MAX_ENUM; i++)
  141. cachedShaderStages[i].clear();
  142. Shader::deinitialize();
  143. }
  144. void Graphics::createQuadIndexBuffer()
  145. {
  146. if (quadIndexBuffer != nullptr)
  147. return;
  148. size_t size = sizeof(uint16) * (LOVE_UINT16_MAX / 4) * 6;
  149. quadIndexBuffer = newBuffer(size, nullptr, BUFFER_INDEX, vertex::USAGE_STATIC, 0);
  150. Buffer::Mapper map(*quadIndexBuffer);
  151. vertex::fillIndices(vertex::TriangleIndexMode::QUADS, 0, LOVE_UINT16_MAX, (uint16 *) map.get());
  152. }
  153. Quad *Graphics::newQuad(Quad::Viewport v, double sw, double sh)
  154. {
  155. return new Quad(v, sw, sh);
  156. }
  157. Font *Graphics::newFont(love::font::Rasterizer *data)
  158. {
  159. return new Font(data, states.back().defaultSamplerState);
  160. }
  161. Font *Graphics::newDefaultFont(int size, font::TrueTypeRasterizer::Hinting hinting)
  162. {
  163. auto fontmodule = Module::getInstance<font::Font>(M_FONT);
  164. if (!fontmodule)
  165. throw love::Exception("Font module has not been loaded.");
  166. StrongRef<font::Rasterizer> r(fontmodule->newTrueTypeRasterizer(size, hinting), Acquire::NORETAIN);
  167. return newFont(r.get());
  168. }
  169. Video *Graphics::newVideo(love::video::VideoStream *stream, float dpiscale)
  170. {
  171. return new Video(this, stream, dpiscale);
  172. }
  173. love::graphics::SpriteBatch *Graphics::newSpriteBatch(Texture *texture, int size, vertex::Usage usage)
  174. {
  175. return new SpriteBatch(this, texture, size, usage);
  176. }
  177. love::graphics::ParticleSystem *Graphics::newParticleSystem(Texture *texture, int size)
  178. {
  179. return new ParticleSystem(texture, size);
  180. }
  181. ShaderStage *Graphics::newShaderStage(ShaderStage::StageType stage, const std::string &optsource)
  182. {
  183. if (stage == ShaderStage::STAGE_MAX_ENUM)
  184. throw love::Exception("Invalid shader stage.");
  185. const std::string &source = optsource.empty() ? getCurrentDefaultShaderCode().source[stage] : optsource;
  186. ShaderStage *s = nullptr;
  187. std::string cachekey;
  188. if (!source.empty())
  189. {
  190. data::HashFunction::Value hashvalue;
  191. data::hash(data::HashFunction::FUNCTION_SHA1, source.c_str(), source.size(), hashvalue);
  192. cachekey = std::string(hashvalue.data, hashvalue.size);
  193. auto it = cachedShaderStages[stage].find(cachekey);
  194. if (it != cachedShaderStages[stage].end())
  195. {
  196. s = it->second;
  197. s->retain();
  198. }
  199. }
  200. if (s == nullptr)
  201. {
  202. s = newShaderStageInternal(stage, cachekey, source, getRenderer() == RENDERER_OPENGLES);
  203. if (!cachekey.empty())
  204. cachedShaderStages[stage][cachekey] = s;
  205. }
  206. return s;
  207. }
  208. Shader *Graphics::newShader(const std::string &vertex, const std::string &pixel)
  209. {
  210. if (vertex.empty() && pixel.empty())
  211. throw love::Exception("Error creating shader: no source code!");
  212. StrongRef<ShaderStage> vertexstage(newShaderStage(ShaderStage::STAGE_VERTEX, vertex), Acquire::NORETAIN);
  213. StrongRef<ShaderStage> pixelstage(newShaderStage(ShaderStage::STAGE_PIXEL, pixel), Acquire::NORETAIN);
  214. return newShaderInternal(vertexstage.get(), pixelstage.get());
  215. }
  216. Mesh *Graphics::newMesh(const std::vector<Vertex> &vertices, PrimitiveType drawmode, vertex::Usage usage)
  217. {
  218. return newMesh(Mesh::getDefaultVertexFormat(), &vertices[0], vertices.size() * sizeof(Vertex), drawmode, usage);
  219. }
  220. Mesh *Graphics::newMesh(int vertexcount, PrimitiveType drawmode, vertex::Usage usage)
  221. {
  222. return newMesh(Mesh::getDefaultVertexFormat(), vertexcount, drawmode, usage);
  223. }
  224. love::graphics::Mesh *Graphics::newMesh(const std::vector<Mesh::AttribFormat> &vertexformat, int vertexcount, PrimitiveType drawmode, vertex::Usage usage)
  225. {
  226. return new Mesh(this, vertexformat, vertexcount, drawmode, usage);
  227. }
  228. love::graphics::Mesh *Graphics::newMesh(const std::vector<Mesh::AttribFormat> &vertexformat, const void *data, size_t datasize, PrimitiveType drawmode, vertex::Usage usage)
  229. {
  230. return new Mesh(this, vertexformat, data, datasize, drawmode, usage);
  231. }
  232. love::graphics::Text *Graphics::newText(graphics::Font *font, const std::vector<Font::ColoredString> &text)
  233. {
  234. return new Text(font, text);
  235. }
  236. void Graphics::cleanupCachedShaderStage(ShaderStage::StageType type, const std::string &hashkey)
  237. {
  238. cachedShaderStages[type].erase(hashkey);
  239. }
  240. bool Graphics::validateShader(bool gles, const std::string &vertex, const std::string &pixel, std::string &err)
  241. {
  242. if (vertex.empty() && pixel.empty())
  243. {
  244. err = "Error validating shader: no source code!";
  245. return false;
  246. }
  247. StrongRef<ShaderStage> vertexstage;
  248. StrongRef<ShaderStage> pixelstage;
  249. // Don't use cached shader stages, since the gles flag may not match the
  250. // current renderer.
  251. if (!vertex.empty())
  252. vertexstage.set(new ShaderStageForValidation(this, ShaderStage::STAGE_VERTEX, vertex, gles), Acquire::NORETAIN);
  253. if (!pixel.empty())
  254. pixelstage.set(new ShaderStageForValidation(this, ShaderStage::STAGE_PIXEL, pixel, gles), Acquire::NORETAIN);
  255. return Shader::validate(vertexstage.get(), pixelstage.get(), err);
  256. }
  257. int Graphics::getWidth() const
  258. {
  259. return width;
  260. }
  261. int Graphics::getHeight() const
  262. {
  263. return height;
  264. }
  265. int Graphics::getPixelWidth() const
  266. {
  267. return pixelWidth;
  268. }
  269. int Graphics::getPixelHeight() const
  270. {
  271. return pixelHeight;
  272. }
  273. double Graphics::getCurrentDPIScale() const
  274. {
  275. const auto &rt = states.back().renderTargets.getFirstTarget();
  276. if (rt.texture.get())
  277. return rt.texture->getDPIScale();
  278. return getScreenDPIScale();
  279. }
  280. double Graphics::getScreenDPIScale() const
  281. {
  282. return (double) getPixelHeight() / (double) getHeight();
  283. }
  284. bool Graphics::isCreated() const
  285. {
  286. return created;
  287. }
  288. bool Graphics::isActive() const
  289. {
  290. // The graphics module is only completely 'active' if there's a window, a
  291. // context, and the active variable is set.
  292. auto window = getInstance<love::window::Window>(M_WINDOW);
  293. return active && isCreated() && window != nullptr && window->isOpen();
  294. }
  295. void Graphics::reset()
  296. {
  297. DisplayState s;
  298. stopDrawToStencilBuffer();
  299. restoreState(s);
  300. origin();
  301. }
  302. /**
  303. * State functions.
  304. **/
  305. void Graphics::restoreState(const DisplayState &s)
  306. {
  307. setColor(s.color);
  308. setBackgroundColor(s.backgroundColor);
  309. setBlendState(s.blend);
  310. setLineWidth(s.lineWidth);
  311. setLineStyle(s.lineStyle);
  312. setLineJoin(s.lineJoin);
  313. setPointSize(s.pointSize);
  314. if (s.scissor)
  315. setScissor(s.scissorRect);
  316. else
  317. setScissor();
  318. setStencilTest(s.stencilCompare, s.stencilTestValue);
  319. setDepthMode(s.depthTest, s.depthWrite);
  320. setMeshCullMode(s.meshCullMode);
  321. setFrontFaceWinding(s.winding);
  322. setFont(s.font.get());
  323. setShader(s.shader.get());
  324. setRenderTargets(s.renderTargets);
  325. setColorMask(s.colorMask);
  326. setWireframe(s.wireframe);
  327. setDefaultSamplerState(s.defaultSamplerState);
  328. }
  329. void Graphics::restoreStateChecked(const DisplayState &s)
  330. {
  331. const DisplayState &cur = states.back();
  332. if (s.color != cur.color)
  333. setColor(s.color);
  334. setBackgroundColor(s.backgroundColor);
  335. if (!(s.blend == cur.blend))
  336. setBlendState(s.blend);
  337. // These are just simple assignments.
  338. setLineWidth(s.lineWidth);
  339. setLineStyle(s.lineStyle);
  340. setLineJoin(s.lineJoin);
  341. if (s.pointSize != cur.pointSize)
  342. setPointSize(s.pointSize);
  343. if (s.scissor != cur.scissor || (s.scissor && !(s.scissorRect == cur.scissorRect)))
  344. {
  345. if (s.scissor)
  346. setScissor(s.scissorRect);
  347. else
  348. setScissor();
  349. }
  350. if (s.stencilCompare != cur.stencilCompare || s.stencilTestValue != cur.stencilTestValue)
  351. setStencilTest(s.stencilCompare, s.stencilTestValue);
  352. if (s.depthTest != cur.depthTest || s.depthWrite != cur.depthWrite)
  353. setDepthMode(s.depthTest, s.depthWrite);
  354. setMeshCullMode(s.meshCullMode);
  355. if (s.winding != cur.winding)
  356. setFrontFaceWinding(s.winding);
  357. setFont(s.font.get());
  358. setShader(s.shader.get());
  359. const auto &sRTs = s.renderTargets;
  360. const auto &curRTs = cur.renderTargets;
  361. bool rtschanged = sRTs.colors.size() != curRTs.colors.size();
  362. if (!rtschanged)
  363. {
  364. for (size_t i = 0; i < sRTs.colors.size() && i < curRTs.colors.size(); i++)
  365. {
  366. if (sRTs.colors[i] != curRTs.colors[i])
  367. {
  368. rtschanged = true;
  369. break;
  370. }
  371. }
  372. if (!rtschanged && sRTs.depthStencil != curRTs.depthStencil)
  373. rtschanged = true;
  374. if (sRTs.temporaryRTFlags != curRTs.temporaryRTFlags)
  375. rtschanged = true;
  376. }
  377. if (rtschanged)
  378. setRenderTargets(s.renderTargets);
  379. if (s.colorMask != cur.colorMask)
  380. setColorMask(s.colorMask);
  381. if (s.wireframe != cur.wireframe)
  382. setWireframe(s.wireframe);
  383. setDefaultSamplerState(s.defaultSamplerState);
  384. }
  385. Colorf Graphics::getColor() const
  386. {
  387. return states.back().color;
  388. }
  389. void Graphics::setBackgroundColor(Colorf c)
  390. {
  391. states.back().backgroundColor = c;
  392. }
  393. Colorf Graphics::getBackgroundColor() const
  394. {
  395. return states.back().backgroundColor;
  396. }
  397. void Graphics::checkSetDefaultFont()
  398. {
  399. // We don't create or set the default Font if an existing font is in use.
  400. if (states.back().font.get() != nullptr)
  401. return;
  402. // Create a new default font if we don't have one yet.
  403. if (!defaultFont.get())
  404. defaultFont.set(newDefaultFont(12, font::TrueTypeRasterizer::HINTING_NORMAL), Acquire::NORETAIN);
  405. states.back().font.set(defaultFont.get());
  406. }
  407. void Graphics::setFont(love::graphics::Font *font)
  408. {
  409. // We don't need to set a default font here if null is passed in, since we
  410. // only care about the default font in getFont and print.
  411. DisplayState &state = states.back();
  412. state.font.set(font);
  413. }
  414. love::graphics::Font *Graphics::getFont()
  415. {
  416. checkSetDefaultFont();
  417. return states.back().font.get();
  418. }
  419. void Graphics::setShader(love::graphics::Shader *shader)
  420. {
  421. if (shader == nullptr)
  422. return setShader();
  423. shader->attach();
  424. states.back().shader.set(shader);
  425. }
  426. void Graphics::setShader()
  427. {
  428. Shader::attachDefault(Shader::STANDARD_DEFAULT);
  429. states.back().shader.set(nullptr);
  430. }
  431. love::graphics::Shader *Graphics::getShader() const
  432. {
  433. return states.back().shader.get();
  434. }
  435. void Graphics::setRenderTarget(RenderTarget rt, uint32 temporaryRTFlags)
  436. {
  437. if (rt.texture == nullptr)
  438. return setRenderTarget();
  439. RenderTargets rts;
  440. rts.colors.push_back(rt);
  441. rts.temporaryRTFlags = temporaryRTFlags;
  442. setRenderTargets(rts);
  443. }
  444. void Graphics::setRenderTargets(const RenderTargetsStrongRef &rts)
  445. {
  446. RenderTargets targets;
  447. targets.colors.reserve(rts.colors.size());
  448. for (const auto &rt : rts.colors)
  449. targets.colors.emplace_back(rt.texture.get(), rt.slice, rt.mipmap);
  450. targets.depthStencil = RenderTarget(rts.depthStencil.texture, rts.depthStencil.slice, rts.depthStencil.mipmap);
  451. targets.temporaryRTFlags = rts.temporaryRTFlags;
  452. return setRenderTargets(targets);
  453. }
  454. void Graphics::setRenderTargets(const RenderTargets &rts)
  455. {
  456. DisplayState &state = states.back();
  457. int rtcount = (int) rts.colors.size();
  458. RenderTarget firsttarget = rts.getFirstTarget();
  459. Texture *firsttex = firsttarget.texture;
  460. if (firsttex == nullptr)
  461. return setRenderTarget();
  462. const auto &prevRTs = state.renderTargets;
  463. if (rtcount == (int) prevRTs.colors.size())
  464. {
  465. bool modified = false;
  466. for (int i = 0; i < rtcount; i++)
  467. {
  468. if (rts.colors[i] != prevRTs.colors[i])
  469. {
  470. modified = true;
  471. break;
  472. }
  473. }
  474. if (!modified && rts.depthStencil != prevRTs.depthStencil)
  475. modified = true;
  476. if (rts.temporaryRTFlags != prevRTs.temporaryRTFlags)
  477. modified = true;
  478. if (!modified)
  479. return;
  480. }
  481. if (rtcount > capabilities.limits[LIMIT_MULTI_CANVAS])
  482. throw love::Exception("This system can't simultaneously render to %d textures.", rtcount);
  483. bool multiformatsupported = capabilities.features[FEATURE_MULTI_CANVAS_FORMATS];
  484. PixelFormat firstcolorformat = PIXELFORMAT_UNKNOWN;
  485. if (!rts.colors.empty())
  486. firstcolorformat = rts.colors[0].texture->getPixelFormat();
  487. if (!firsttex->isRenderTarget())
  488. throw love::Exception("Texture must be created as a render target to be used in setRenderTargets.");
  489. if (isPixelFormatDepthStencil(firstcolorformat))
  490. throw love::Exception("Depth/stencil format textures must be used with the 'depthstencil' field of the table passed into setRenderTargets.");
  491. if (firsttarget.mipmap < 0 || firsttarget.mipmap >= firsttex->getMipmapCount())
  492. throw love::Exception("Invalid mipmap level %d.", firsttarget.mipmap + 1);
  493. if (!firsttex->isValidSlice(firsttarget.slice))
  494. throw love::Exception("Invalid slice index: %d.", firsttarget.slice + 1);
  495. bool hasSRGBtexture = firstcolorformat == PIXELFORMAT_sRGBA8_UNORM;
  496. int pixelw = firsttex->getPixelWidth(firsttarget.mipmap);
  497. int pixelh = firsttex->getPixelHeight(firsttarget.mipmap);
  498. int reqmsaa = firsttex->getRequestedMSAA();
  499. for (int i = 1; i < rtcount; i++)
  500. {
  501. Texture *c = rts.colors[i].texture;
  502. PixelFormat format = c->getPixelFormat();
  503. int mip = rts.colors[i].mipmap;
  504. int slice = rts.colors[i].slice;
  505. if (!c->isRenderTarget())
  506. throw love::Exception("Texture must be created as a render target to be used in setRenderTargets.");
  507. if (mip < 0 || mip >= c->getMipmapCount())
  508. throw love::Exception("Invalid mipmap level %d.", mip + 1);
  509. if (!c->isValidSlice(slice))
  510. throw love::Exception("Invalid slice index: %d.", slice + 1);
  511. if (c->getPixelWidth(mip) != pixelw || c->getPixelHeight(mip) != pixelh)
  512. throw love::Exception("All textures must have the same pixel dimensions.");
  513. if (!multiformatsupported && format != firstcolorformat)
  514. throw love::Exception("This system doesn't support multi-render-target rendering with different texture formats.");
  515. if (c->getRequestedMSAA() != reqmsaa)
  516. throw love::Exception("All textures must have the same MSAA value.");
  517. if (isPixelFormatDepthStencil(format))
  518. throw love::Exception("Depth/stencil format textures must be used with the 'depthstencil' field of the table passed into setRenderTargets.");
  519. if (format == PIXELFORMAT_sRGBA8_UNORM)
  520. hasSRGBtexture = true;
  521. }
  522. if (rts.depthStencil.texture != nullptr)
  523. {
  524. Texture *c = rts.depthStencil.texture;
  525. int mip = rts.depthStencil.mipmap;
  526. int slice = rts.depthStencil.slice;
  527. if (!c->isRenderTarget())
  528. throw love::Exception("Texture must be created as a render target to be used in setRenderTargets.");
  529. if (!isPixelFormatDepthStencil(c->getPixelFormat()))
  530. throw love::Exception("Only depth/stencil format textures can be used with the 'depthstencil' field of the table passed into setRenderTargets.");
  531. if (c->getPixelWidth(mip) != pixelw || c->getPixelHeight(mip) != pixelh)
  532. throw love::Exception("All Textures must have the same pixel dimensions.");
  533. if (c->getRequestedMSAA() != firsttex->getRequestedMSAA())
  534. throw love::Exception("All Textures must have the same MSAA value.");
  535. if (mip < 0 || mip >= c->getMipmapCount())
  536. throw love::Exception("Invalid mipmap level %d.", mip + 1);
  537. if (!c->isValidSlice(slice))
  538. throw love::Exception("Invalid slice index: %d.", slice + 1);
  539. }
  540. int w = firsttex->getWidth(firsttarget.mipmap);
  541. int h = firsttex->getHeight(firsttarget.mipmap);
  542. flushStreamDraws();
  543. if (rts.depthStencil.texture == nullptr && rts.temporaryRTFlags != 0)
  544. {
  545. bool wantsdepth = (rts.temporaryRTFlags & TEMPORARY_RT_DEPTH) != 0;
  546. bool wantsstencil = (rts.temporaryRTFlags & TEMPORARY_RT_STENCIL) != 0;
  547. PixelFormat dsformat = PIXELFORMAT_STENCIL8;
  548. if (wantsdepth && wantsstencil)
  549. dsformat = PIXELFORMAT_DEPTH24_UNORM_STENCIL8;
  550. else if (wantsdepth && isPixelFormatSupported(PIXELFORMAT_DEPTH24_UNORM, true, false, false))
  551. dsformat = PIXELFORMAT_DEPTH24_UNORM;
  552. else if (wantsdepth)
  553. dsformat = PIXELFORMAT_DEPTH16_UNORM;
  554. else if (wantsstencil)
  555. dsformat = PIXELFORMAT_STENCIL8;
  556. // We want setRenderTargetsInternal to have a pointer to the temporary RT,
  557. // but we don't want to directly store it in the main graphics state.
  558. RenderTargets realRTs = rts;
  559. realRTs.depthStencil.texture = getTemporaryTexture(dsformat, pixelw, pixelh, reqmsaa);
  560. realRTs.depthStencil.slice = 0;
  561. setRenderTargetsInternal(realRTs, w, h, pixelw, pixelh, hasSRGBtexture);
  562. }
  563. else
  564. setRenderTargetsInternal(rts, w, h, pixelw, pixelh, hasSRGBtexture);
  565. RenderTargetsStrongRef refs;
  566. refs.colors.reserve(rts.colors.size());
  567. for (auto c : rts.colors)
  568. refs.colors.emplace_back(c.texture, c.slice, c.mipmap);
  569. refs.depthStencil = RenderTargetStrongRef(rts.depthStencil.texture, rts.depthStencil.slice);
  570. refs.temporaryRTFlags = rts.temporaryRTFlags;
  571. std::swap(state.renderTargets, refs);
  572. renderTargetSwitchCount++;
  573. }
  574. void Graphics::setRenderTarget()
  575. {
  576. DisplayState &state = states.back();
  577. if (state.renderTargets.colors.empty() && state.renderTargets.depthStencil.texture == nullptr)
  578. return;
  579. flushStreamDraws();
  580. setRenderTargetsInternal(RenderTargets(), width, height, pixelWidth, pixelHeight, isGammaCorrect());
  581. state.renderTargets = RenderTargetsStrongRef();
  582. renderTargetSwitchCount++;
  583. }
  584. Graphics::RenderTargets Graphics::getRenderTargets() const
  585. {
  586. const auto &curRTs = states.back().renderTargets;
  587. RenderTargets rts;
  588. rts.colors.reserve(curRTs.colors.size());
  589. for (const auto &rt : curRTs.colors)
  590. rts.colors.emplace_back(rt.texture.get(), rt.slice, rt.mipmap);
  591. rts.depthStencil = RenderTarget(curRTs.depthStencil.texture, curRTs.depthStencil.slice, curRTs.depthStencil.mipmap);
  592. rts.temporaryRTFlags = curRTs.temporaryRTFlags;
  593. return rts;
  594. }
  595. bool Graphics::isRenderTargetActive() const
  596. {
  597. const auto &rts = states.back().renderTargets;
  598. return !rts.colors.empty() || rts.depthStencil.texture != nullptr;
  599. }
  600. bool Graphics::isRenderTargetActive(Texture *texture) const
  601. {
  602. const auto &rts = states.back().renderTargets;
  603. for (const auto &rt : rts.colors)
  604. {
  605. if (rt.texture.get() == texture)
  606. return true;
  607. }
  608. if (rts.depthStencil.texture.get() == texture)
  609. return true;
  610. return false;
  611. }
  612. bool Graphics::isRenderTargetActive(Texture *texture, int slice) const
  613. {
  614. const auto &rts = states.back().renderTargets;
  615. for (const auto &rt : rts.colors)
  616. {
  617. if (rt.texture.get() == texture && rt.slice == slice)
  618. return true;
  619. }
  620. if (rts.depthStencil.texture.get() == texture && rts.depthStencil.slice == slice)
  621. return true;
  622. return false;
  623. }
  624. Texture *Graphics::getTemporaryTexture(PixelFormat format, int w, int h, int samples)
  625. {
  626. Texture *texture = nullptr;
  627. for (TemporaryTexture &temp : temporaryTextures)
  628. {
  629. Texture *c = temp.texture;
  630. if (c->getPixelFormat() == format && c->getPixelWidth() == w
  631. && c->getPixelHeight() == h && c->getRequestedMSAA() == samples)
  632. {
  633. texture = c;
  634. temp.framesSinceUse = 0;
  635. break;
  636. }
  637. }
  638. if (texture == nullptr)
  639. {
  640. Texture::Settings settings;
  641. settings.renderTarget = true;
  642. settings.format = format;
  643. settings.width = w;
  644. settings.height = h;
  645. settings.msaa = samples;
  646. texture = newTexture(settings);
  647. temporaryTextures.emplace_back(texture);
  648. }
  649. return texture;
  650. }
  651. void Graphics::intersectScissor(const Rect &rect)
  652. {
  653. Rect currect = states.back().scissorRect;
  654. if (!states.back().scissor)
  655. {
  656. currect.x = 0;
  657. currect.y = 0;
  658. currect.w = std::numeric_limits<int>::max();
  659. currect.h = std::numeric_limits<int>::max();
  660. }
  661. int x1 = std::max(currect.x, rect.x);
  662. int y1 = std::max(currect.y, rect.y);
  663. int x2 = std::min(currect.x + currect.w, rect.x + rect.w);
  664. int y2 = std::min(currect.y + currect.h, rect.y + rect.h);
  665. Rect newrect = {x1, y1, std::max(0, x2 - x1), std::max(0, y2 - y1)};
  666. setScissor(newrect);
  667. }
  668. bool Graphics::getScissor(Rect &rect) const
  669. {
  670. const DisplayState &state = states.back();
  671. rect = state.scissorRect;
  672. return state.scissor;
  673. }
  674. void Graphics::setStencilTest()
  675. {
  676. setStencilTest(COMPARE_ALWAYS, 0);
  677. }
  678. void Graphics::getStencilTest(CompareMode &compare, int &value) const
  679. {
  680. const DisplayState &state = states.back();
  681. compare = state.stencilCompare;
  682. value = state.stencilTestValue;
  683. }
  684. void Graphics::setDepthMode()
  685. {
  686. setDepthMode(COMPARE_ALWAYS, false);
  687. }
  688. void Graphics::getDepthMode(CompareMode &compare, bool &write) const
  689. {
  690. const DisplayState &state = states.back();
  691. compare = state.depthTest;
  692. write = state.depthWrite;
  693. }
  694. void Graphics::setMeshCullMode(CullMode cull)
  695. {
  696. // Handled inside the draw() graphics API implementations.
  697. states.back().meshCullMode = cull;
  698. }
  699. CullMode Graphics::getMeshCullMode() const
  700. {
  701. return states.back().meshCullMode;
  702. }
  703. vertex::Winding Graphics::getFrontFaceWinding() const
  704. {
  705. return states.back().winding;
  706. }
  707. ColorChannelMask Graphics::getColorMask() const
  708. {
  709. return states.back().colorMask;
  710. }
  711. void Graphics::setBlendMode(BlendMode mode, BlendAlpha alphamode)
  712. {
  713. if (alphamode == BLENDALPHA_MULTIPLY && !isAlphaMultiplyBlendSupported(mode))
  714. {
  715. const char *modestr = "unknown";
  716. love::graphics::getConstant(mode, modestr);
  717. throw love::Exception("The '%s' blend mode must be used with premultiplied alpha.", modestr);
  718. }
  719. setBlendState(computeBlendState(mode, alphamode));
  720. }
  721. BlendMode Graphics::getBlendMode(BlendAlpha &alphamode) const
  722. {
  723. return computeBlendMode(states.back().blend, alphamode);
  724. }
  725. const BlendState &Graphics::getBlendState() const
  726. {
  727. return states.back().blend;
  728. }
  729. void Graphics::setDefaultSamplerState(const SamplerState &s)
  730. {
  731. states.back().defaultSamplerState = s;
  732. }
  733. const SamplerState &Graphics::getDefaultSamplerState() const
  734. {
  735. return states.back().defaultSamplerState;
  736. }
  737. void Graphics::setLineWidth(float width)
  738. {
  739. states.back().lineWidth = width;
  740. }
  741. void Graphics::setLineStyle(Graphics::LineStyle style)
  742. {
  743. states.back().lineStyle = style;
  744. }
  745. void Graphics::setLineJoin(Graphics::LineJoin join)
  746. {
  747. states.back().lineJoin = join;
  748. }
  749. float Graphics::getLineWidth() const
  750. {
  751. return states.back().lineWidth;
  752. }
  753. Graphics::LineStyle Graphics::getLineStyle() const
  754. {
  755. return states.back().lineStyle;
  756. }
  757. Graphics::LineJoin Graphics::getLineJoin() const
  758. {
  759. return states.back().lineJoin;
  760. }
  761. float Graphics::getPointSize() const
  762. {
  763. return states.back().pointSize;
  764. }
  765. bool Graphics::isWireframe() const
  766. {
  767. return states.back().wireframe;
  768. }
  769. void Graphics::captureScreenshot(const ScreenshotInfo &info)
  770. {
  771. pendingScreenshotCallbacks.push_back(info);
  772. }
  773. Graphics::StreamVertexData Graphics::requestStreamDraw(const StreamDrawCommand &cmd)
  774. {
  775. using namespace vertex;
  776. StreamBufferState &state = streamBufferState;
  777. bool shouldflush = false;
  778. bool shouldresize = false;
  779. if (cmd.primitiveMode != state.primitiveMode
  780. || cmd.formats[0] != state.formats[0] || cmd.formats[1] != state.formats[1]
  781. || ((cmd.indexMode != TriangleIndexMode::NONE) != (state.indexCount > 0))
  782. || cmd.texture != state.texture
  783. || cmd.standardShaderType != state.standardShaderType)
  784. {
  785. shouldflush = true;
  786. }
  787. int totalvertices = state.vertexCount + cmd.vertexCount;
  788. // We only support uint16 index buffers for now.
  789. if (totalvertices > LOVE_UINT16_MAX && cmd.indexMode != TriangleIndexMode::NONE)
  790. shouldflush = true;
  791. int reqIndexCount = getIndexCount(cmd.indexMode, cmd.vertexCount);
  792. size_t reqIndexSize = reqIndexCount * sizeof(uint16);
  793. size_t newdatasizes[2] = {0, 0};
  794. size_t buffersizes[3] = {0, 0, 0};
  795. for (int i = 0; i < 2; i++)
  796. {
  797. if (cmd.formats[i] == CommonFormat::NONE)
  798. continue;
  799. size_t stride = getFormatStride(cmd.formats[i]);
  800. size_t datasize = stride * totalvertices;
  801. if (state.vbMap[i].data != nullptr && datasize > state.vbMap[i].size)
  802. shouldflush = true;
  803. if (datasize > state.vb[i]->getUsableSize())
  804. {
  805. buffersizes[i] = std::max(datasize, state.vb[i]->getSize() * 2);
  806. shouldresize = true;
  807. }
  808. newdatasizes[i] = stride * cmd.vertexCount;
  809. }
  810. if (cmd.indexMode != TriangleIndexMode::NONE)
  811. {
  812. size_t datasize = (state.indexCount + reqIndexCount) * sizeof(uint16);
  813. if (state.indexBufferMap.data != nullptr && datasize > state.indexBufferMap.size)
  814. shouldflush = true;
  815. if (datasize > state.indexBuffer->getUsableSize())
  816. {
  817. buffersizes[2] = std::max(datasize, state.indexBuffer->getSize() * 2);
  818. shouldresize = true;
  819. }
  820. }
  821. if (shouldflush || shouldresize)
  822. {
  823. flushStreamDraws();
  824. state.primitiveMode = cmd.primitiveMode;
  825. state.formats[0] = cmd.formats[0];
  826. state.formats[1] = cmd.formats[1];
  827. state.texture = cmd.texture;
  828. state.standardShaderType = cmd.standardShaderType;
  829. }
  830. if (state.vertexCount == 0 && Shader::isDefaultActive())
  831. Shader::attachDefault(state.standardShaderType);
  832. if (state.vertexCount == 0 && Shader::current != nullptr && cmd.texture != nullptr)
  833. Shader::current->checkMainTexture(cmd.texture);
  834. if (shouldresize)
  835. {
  836. for (int i = 0; i < 2; i++)
  837. {
  838. if (state.vb[i]->getSize() < buffersizes[i])
  839. {
  840. delete state.vb[i];
  841. state.vb[i] = newStreamBuffer(BUFFER_VERTEX, buffersizes[i]);
  842. }
  843. }
  844. if (state.indexBuffer->getSize() < buffersizes[2])
  845. {
  846. delete state.indexBuffer;
  847. state.indexBuffer = newStreamBuffer(BUFFER_INDEX, buffersizes[2]);
  848. }
  849. }
  850. if (cmd.indexMode != TriangleIndexMode::NONE)
  851. {
  852. if (state.indexBufferMap.data == nullptr)
  853. state.indexBufferMap = state.indexBuffer->map(reqIndexSize);
  854. uint16 *indices = (uint16 *) state.indexBufferMap.data;
  855. fillIndices(cmd.indexMode, state.vertexCount, cmd.vertexCount, indices);
  856. state.indexBufferMap.data += reqIndexSize;
  857. }
  858. StreamVertexData d;
  859. for (int i = 0; i < 2; i++)
  860. {
  861. if (newdatasizes[i] > 0)
  862. {
  863. if (state.vbMap[i].data == nullptr)
  864. state.vbMap[i] = state.vb[i]->map(newdatasizes[i]);
  865. d.stream[i] = state.vbMap[i].data;
  866. state.vbMap[i].data += newdatasizes[i];
  867. }
  868. }
  869. if (state.vertexCount > 0)
  870. drawCallsBatched++;
  871. state.vertexCount += cmd.vertexCount;
  872. state.indexCount += reqIndexCount;
  873. return d;
  874. }
  875. void Graphics::flushStreamDraws()
  876. {
  877. using namespace vertex;
  878. auto &sbstate = streamBufferState;
  879. if (sbstate.vertexCount == 0 && sbstate.indexCount == 0)
  880. return;
  881. Attributes attributes;
  882. BufferBindings buffers;
  883. size_t usedsizes[3] = {0, 0, 0};
  884. for (int i = 0; i < 2; i++)
  885. {
  886. if (sbstate.formats[i] == CommonFormat::NONE)
  887. continue;
  888. attributes.setCommonFormat(sbstate.formats[i], (uint8) i);
  889. usedsizes[i] = getFormatStride(sbstate.formats[i]) * sbstate.vertexCount;
  890. size_t offset = sbstate.vb[i]->unmap(usedsizes[i]);
  891. buffers.set(i, sbstate.vb[i], offset);
  892. sbstate.vbMap[i] = StreamBuffer::MapInfo();
  893. }
  894. if (attributes.enableBits == 0)
  895. return;
  896. Colorf nc = getColor();
  897. if (attributes.isEnabled(ATTRIB_COLOR))
  898. setColor(Colorf(1.0f, 1.0f, 1.0f, 1.0f));
  899. pushIdentityTransform();
  900. if (sbstate.indexCount > 0)
  901. {
  902. usedsizes[2] = sizeof(uint16) * sbstate.indexCount;
  903. DrawIndexedCommand cmd(&attributes, &buffers, sbstate.indexBuffer);
  904. cmd.primitiveType = sbstate.primitiveMode;
  905. cmd.indexCount = sbstate.indexCount;
  906. cmd.indexType = INDEX_UINT16;
  907. cmd.indexBufferOffset = sbstate.indexBuffer->unmap(usedsizes[2]);
  908. cmd.texture = sbstate.texture;
  909. draw(cmd);
  910. sbstate.indexBufferMap = StreamBuffer::MapInfo();
  911. }
  912. else
  913. {
  914. DrawCommand cmd(&attributes, &buffers);
  915. cmd.primitiveType = sbstate.primitiveMode;
  916. cmd.vertexStart = 0;
  917. cmd.vertexCount = sbstate.vertexCount;
  918. cmd.texture = sbstate.texture;
  919. draw(cmd);
  920. }
  921. for (int i = 0; i < 2; i++)
  922. {
  923. if (usedsizes[i] > 0)
  924. sbstate.vb[i]->markUsed(usedsizes[i]);
  925. }
  926. if (usedsizes[2] > 0)
  927. sbstate.indexBuffer->markUsed(usedsizes[2]);
  928. popTransform();
  929. if (attributes.isEnabled(ATTRIB_COLOR))
  930. setColor(nc);
  931. streamBufferState.vertexCount = 0;
  932. streamBufferState.indexCount = 0;
  933. }
  934. void Graphics::flushStreamDrawsGlobal()
  935. {
  936. Graphics *instance = getInstance<Graphics>(M_GRAPHICS);
  937. if (instance != nullptr)
  938. instance->flushStreamDraws();
  939. }
  940. /**
  941. * Drawing
  942. **/
  943. void Graphics::draw(Drawable *drawable, const Matrix4 &m)
  944. {
  945. drawable->draw(this, m);
  946. }
  947. void Graphics::draw(Texture *texture, Quad *quad, const Matrix4 &m)
  948. {
  949. texture->draw(this, quad, m);
  950. }
  951. void Graphics::drawLayer(Texture *texture, int layer, const Matrix4 &m)
  952. {
  953. texture->drawLayer(this, layer, m);
  954. }
  955. void Graphics::drawLayer(Texture *texture, int layer, Quad *quad, const Matrix4 &m)
  956. {
  957. texture->drawLayer(this, layer, quad, m);
  958. }
  959. void Graphics::drawInstanced(Mesh *mesh, const Matrix4 &m, int instancecount)
  960. {
  961. mesh->drawInstanced(this, m, instancecount);
  962. }
  963. void Graphics::print(const std::vector<Font::ColoredString> &str, const Matrix4 &m)
  964. {
  965. checkSetDefaultFont();
  966. if (states.back().font.get() != nullptr)
  967. print(str, states.back().font.get(), m);
  968. }
  969. void Graphics::print(const std::vector<Font::ColoredString> &str, Font *font, const Matrix4 &m)
  970. {
  971. font->print(this, str, m, states.back().color);
  972. }
  973. void Graphics::printf(const std::vector<Font::ColoredString> &str, float wrap, Font::AlignMode align, const Matrix4 &m)
  974. {
  975. checkSetDefaultFont();
  976. if (states.back().font.get() != nullptr)
  977. printf(str, states.back().font.get(), wrap, align, m);
  978. }
  979. void Graphics::printf(const std::vector<Font::ColoredString> &str, Font *font, float wrap, Font::AlignMode align, const Matrix4 &m)
  980. {
  981. font->printf(this, str, wrap, align, m, states.back().color);
  982. }
  983. /**
  984. * Primitives (points, shapes, lines).
  985. **/
  986. void Graphics::points(const Vector2 *positions, const Colorf *colors, size_t numpoints)
  987. {
  988. const Matrix4 &t = getTransform();
  989. bool is2D = t.isAffine2DTransform();
  990. StreamDrawCommand cmd;
  991. cmd.primitiveMode = PRIMITIVE_POINTS;
  992. cmd.formats[0] = vertex::getSinglePositionFormat(is2D);
  993. cmd.formats[1] = vertex::CommonFormat::RGBAub;
  994. cmd.vertexCount = (int) numpoints;
  995. StreamVertexData data = requestStreamDraw(cmd);
  996. if (is2D)
  997. t.transformXY((Vector2 *) data.stream[0], positions, cmd.vertexCount);
  998. else
  999. t.transformXY0((Vector3 *) data.stream[0], positions, cmd.vertexCount);
  1000. Color32 *colordata = (Color32 *) data.stream[1];
  1001. if (colors)
  1002. {
  1003. Colorf nc = getColor();
  1004. gammaCorrectColor(nc);
  1005. if (isGammaCorrect())
  1006. {
  1007. for (int i = 0; i < cmd.vertexCount; i++)
  1008. {
  1009. Colorf ci = colors[i];
  1010. gammaCorrectColor(ci);
  1011. ci *= nc;
  1012. unGammaCorrectColor(ci);
  1013. colordata[i] = toColor32(ci);
  1014. }
  1015. }
  1016. else
  1017. {
  1018. for (int i = 0; i < cmd.vertexCount; i++)
  1019. colordata[i] = toColor32(nc * colors[i]);
  1020. }
  1021. }
  1022. else
  1023. {
  1024. Color32 c = toColor32(getColor());
  1025. for (int i = 0; i < cmd.vertexCount; i++)
  1026. colordata[i] = c;
  1027. }
  1028. }
  1029. int Graphics::calculateEllipsePoints(float rx, float ry) const
  1030. {
  1031. int points = (int) sqrtf(((rx + ry) / 2.0f) * 20.0f * (float) pixelScaleStack.back());
  1032. return std::max(points, 8);
  1033. }
  1034. void Graphics::polyline(const Vector2 *vertices, size_t count)
  1035. {
  1036. float halfwidth = getLineWidth() * 0.5f;
  1037. LineJoin linejoin = getLineJoin();
  1038. LineStyle linestyle = getLineStyle();
  1039. float pixelsize = 1.0f / std::max((float) pixelScaleStack.back(), 0.000001f);
  1040. if (linejoin == LINE_JOIN_NONE)
  1041. {
  1042. NoneJoinPolyline line;
  1043. line.render(vertices, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  1044. line.draw(this);
  1045. }
  1046. else if (linejoin == LINE_JOIN_BEVEL)
  1047. {
  1048. BevelJoinPolyline line;
  1049. line.render(vertices, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  1050. line.draw(this);
  1051. }
  1052. else if (linejoin == LINE_JOIN_MITER)
  1053. {
  1054. MiterJoinPolyline line;
  1055. line.render(vertices, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  1056. line.draw(this);
  1057. }
  1058. }
  1059. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  1060. {
  1061. Vector2 coords[] = {Vector2(x,y), Vector2(x,y+h), Vector2(x+w,y+h), Vector2(x+w,y), Vector2(x,y)};
  1062. polygon(mode, coords, 5);
  1063. }
  1064. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry, int points)
  1065. {
  1066. if (rx == 0 || ry == 0)
  1067. {
  1068. rectangle(mode, x, y, w, h);
  1069. return;
  1070. }
  1071. // Radius values that are more than half the rectangle's size aren't handled
  1072. // correctly (for now)...
  1073. if (w >= 0.02f)
  1074. rx = std::min(rx, w / 2.0f - 0.01f);
  1075. if (h >= 0.02f)
  1076. ry = std::min(ry, h / 2.0f - 0.01f);
  1077. points = std::max(points / 4, 1);
  1078. const float half_pi = static_cast<float>(LOVE_M_PI / 2);
  1079. float angle_shift = half_pi / ((float) points + 1.0f);
  1080. int num_coords = (points + 2) * 4;
  1081. Vector2 *coords = getScratchBuffer<Vector2>(num_coords + 1);
  1082. float phi = .0f;
  1083. for (int i = 0; i <= points + 2; ++i, phi += angle_shift)
  1084. {
  1085. coords[i].x = x + rx * (1 - cosf(phi));
  1086. coords[i].y = y + ry * (1 - sinf(phi));
  1087. }
  1088. phi = half_pi;
  1089. for (int i = points + 2; i <= 2 * (points + 2); ++i, phi += angle_shift)
  1090. {
  1091. coords[i].x = x + w - rx * (1 + cosf(phi));
  1092. coords[i].y = y + ry * (1 - sinf(phi));
  1093. }
  1094. phi = 2 * half_pi;
  1095. for (int i = 2 * (points + 2); i <= 3 * (points + 2); ++i, phi += angle_shift)
  1096. {
  1097. coords[i].x = x + w - rx * (1 + cosf(phi));
  1098. coords[i].y = y + h - ry * (1 + sinf(phi));
  1099. }
  1100. phi = 3 * half_pi;
  1101. for (int i = 3 * (points + 2); i <= 4 * (points + 2); ++i, phi += angle_shift)
  1102. {
  1103. coords[i].x = x + rx * (1 - cosf(phi));
  1104. coords[i].y = y + h - ry * (1 + sinf(phi));
  1105. }
  1106. coords[num_coords] = coords[0];
  1107. polygon(mode, coords, num_coords + 1);
  1108. }
  1109. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry)
  1110. {
  1111. rectangle(mode, x, y, w, h, rx, ry, calculateEllipsePoints(rx, ry));
  1112. }
  1113. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  1114. {
  1115. ellipse(mode, x, y, radius, radius, points);
  1116. }
  1117. void Graphics::circle(DrawMode mode, float x, float y, float radius)
  1118. {
  1119. ellipse(mode, x, y, radius, radius);
  1120. }
  1121. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b, int points)
  1122. {
  1123. float two_pi = (float) (LOVE_M_PI * 2);
  1124. if (points <= 0) points = 1;
  1125. float angle_shift = (two_pi / points);
  1126. float phi = .0f;
  1127. // 1 extra point at the end for a closed loop, and 1 extra point at the
  1128. // start in filled mode for the vertex in the center of the ellipse.
  1129. int extrapoints = 1 + (mode == DRAW_FILL ? 1 : 0);
  1130. Vector2 *polygoncoords = getScratchBuffer<Vector2>(points + extrapoints);
  1131. Vector2 *coords = polygoncoords;
  1132. if (mode == DRAW_FILL)
  1133. {
  1134. coords[0].x = x;
  1135. coords[0].y = y;
  1136. coords++;
  1137. }
  1138. for (int i = 0; i < points; ++i, phi += angle_shift)
  1139. {
  1140. coords[i].x = x + a * cosf(phi);
  1141. coords[i].y = y + b * sinf(phi);
  1142. }
  1143. coords[points] = coords[0];
  1144. // Last argument to polygon(): don't skip the last vertex in fill mode.
  1145. polygon(mode, polygoncoords, points + extrapoints, false);
  1146. }
  1147. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b)
  1148. {
  1149. ellipse(mode, x, y, a, b, calculateEllipsePoints(a, b));
  1150. }
  1151. void Graphics::arc(DrawMode drawmode, ArcMode arcmode, float x, float y, float radius, float angle1, float angle2, int points)
  1152. {
  1153. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  1154. if (points <= 0 || angle1 == angle2)
  1155. return;
  1156. // Oh, you want to draw a circle?
  1157. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  1158. {
  1159. circle(drawmode, x, y, radius, points);
  1160. return;
  1161. }
  1162. float angle_shift = (angle2 - angle1) / points;
  1163. // Bail on precision issues.
  1164. if (angle_shift == 0.0)
  1165. return;
  1166. // Prevent the connecting line from being drawn if a closed line arc has a
  1167. // small angle. Avoids some visual issues when connected lines are at sharp
  1168. // angles, due to the miter line join drawing code.
  1169. if (drawmode == DRAW_LINE && arcmode == ARC_CLOSED && fabsf(angle1 - angle2) < LOVE_TORAD(4))
  1170. arcmode = ARC_OPEN;
  1171. // Quick fix for the last part of a filled open arc not being drawn (because
  1172. // polygon(DRAW_FILL, ...) doesn't work without a closed loop of vertices.)
  1173. if (drawmode == DRAW_FILL && arcmode == ARC_OPEN)
  1174. arcmode = ARC_CLOSED;
  1175. float phi = angle1;
  1176. Vector2 *coords = nullptr;
  1177. int num_coords = 0;
  1178. const auto createPoints = [&](Vector2 *coordinates)
  1179. {
  1180. for (int i = 0; i <= points; ++i, phi += angle_shift)
  1181. {
  1182. coordinates[i].x = x + radius * cosf(phi);
  1183. coordinates[i].y = y + radius * sinf(phi);
  1184. }
  1185. };
  1186. if (arcmode == ARC_PIE)
  1187. {
  1188. num_coords = points + 3;
  1189. coords = getScratchBuffer<Vector2>(num_coords);
  1190. coords[0] = coords[num_coords - 1] = Vector2(x, y);
  1191. createPoints(coords + 1);
  1192. }
  1193. else if (arcmode == ARC_OPEN)
  1194. {
  1195. num_coords = points + 1;
  1196. coords = getScratchBuffer<Vector2>(num_coords);
  1197. createPoints(coords);
  1198. }
  1199. else // ARC_CLOSED
  1200. {
  1201. num_coords = points + 2;
  1202. coords = getScratchBuffer<Vector2>(num_coords);
  1203. createPoints(coords);
  1204. // Connect the ends of the arc.
  1205. coords[num_coords - 1] = coords[0];
  1206. }
  1207. polygon(drawmode, coords, num_coords);
  1208. }
  1209. void Graphics::arc(DrawMode drawmode, ArcMode arcmode, float x, float y, float radius, float angle1, float angle2)
  1210. {
  1211. float points = (float) calculateEllipsePoints(radius, radius);
  1212. // The amount of points is based on the fraction of the circle created by the arc.
  1213. float angle = fabsf(angle1 - angle2);
  1214. if (angle < 2.0f * (float) LOVE_M_PI)
  1215. points *= angle / (2.0f * (float) LOVE_M_PI);
  1216. arc(drawmode, arcmode, x, y, radius, angle1, angle2, (int) (points + 0.5f));
  1217. }
  1218. void Graphics::polygon(DrawMode mode, const Vector2 *coords, size_t count, bool skipLastFilledVertex)
  1219. {
  1220. // coords is an array of a closed loop of vertices, i.e.
  1221. // coords[count-1] == coords[0]
  1222. if (mode == DRAW_LINE)
  1223. {
  1224. polyline(coords, count);
  1225. }
  1226. else
  1227. {
  1228. const Matrix4 &t = getTransform();
  1229. bool is2D = t.isAffine2DTransform();
  1230. StreamDrawCommand cmd;
  1231. cmd.formats[0] = vertex::getSinglePositionFormat(is2D);
  1232. cmd.formats[1] = vertex::CommonFormat::RGBAub;
  1233. cmd.indexMode = vertex::TriangleIndexMode::FAN;
  1234. cmd.vertexCount = (int)count - (skipLastFilledVertex ? 1 : 0);
  1235. StreamVertexData data = requestStreamDraw(cmd);
  1236. if (is2D)
  1237. t.transformXY((Vector2 *) data.stream[0], coords, cmd.vertexCount);
  1238. else
  1239. t.transformXY0((Vector3 *) data.stream[0], coords, cmd.vertexCount);
  1240. Color32 c = toColor32(getColor());
  1241. Color32 *colordata = (Color32 *) data.stream[1];
  1242. for (int i = 0; i < cmd.vertexCount; i++)
  1243. colordata[i] = c;
  1244. }
  1245. }
  1246. const Graphics::Capabilities &Graphics::getCapabilities() const
  1247. {
  1248. return capabilities;
  1249. }
  1250. Graphics::Stats Graphics::getStats() const
  1251. {
  1252. Stats stats;
  1253. getAPIStats(stats.shaderSwitches);
  1254. stats.drawCalls = drawCalls;
  1255. if (streamBufferState.vertexCount > 0)
  1256. stats.drawCalls++;
  1257. stats.renderTargetSwitches = renderTargetSwitchCount;
  1258. stats.drawCallsBatched = drawCallsBatched;
  1259. stats.textures = Texture::textureCount;
  1260. stats.fonts = Font::fontCount;
  1261. stats.textureMemory = Texture::totalGraphicsMemory;
  1262. return stats;
  1263. }
  1264. size_t Graphics::getStackDepth() const
  1265. {
  1266. return stackTypeStack.size();
  1267. }
  1268. void Graphics::push(StackType type)
  1269. {
  1270. if (stackTypeStack.size() == MAX_USER_STACK_DEPTH)
  1271. throw Exception("Maximum stack depth reached (more pushes than pops?)");
  1272. pushTransform();
  1273. pixelScaleStack.push_back(pixelScaleStack.back());
  1274. if (type == STACK_ALL)
  1275. states.push_back(states.back());
  1276. stackTypeStack.push_back(type);
  1277. }
  1278. void Graphics::pop()
  1279. {
  1280. if (stackTypeStack.size() < 1)
  1281. throw Exception("Minimum stack depth reached (more pops than pushes?)");
  1282. popTransform();
  1283. pixelScaleStack.pop_back();
  1284. if (stackTypeStack.back() == STACK_ALL)
  1285. {
  1286. DisplayState &newstate = states[states.size() - 2];
  1287. restoreStateChecked(newstate);
  1288. // The last two states in the stack should be equal now.
  1289. states.pop_back();
  1290. }
  1291. stackTypeStack.pop_back();
  1292. }
  1293. /**
  1294. * Transform and stack functions.
  1295. **/
  1296. const Matrix4 &Graphics::getTransform() const
  1297. {
  1298. return transformStack.back();
  1299. }
  1300. const Matrix4 &Graphics::getProjection() const
  1301. {
  1302. return projectionMatrix;
  1303. }
  1304. void Graphics::pushTransform()
  1305. {
  1306. transformStack.push_back(transformStack.back());
  1307. }
  1308. void Graphics::pushIdentityTransform()
  1309. {
  1310. transformStack.push_back(Matrix4());
  1311. }
  1312. void Graphics::popTransform()
  1313. {
  1314. transformStack.pop_back();
  1315. }
  1316. void Graphics::rotate(float r)
  1317. {
  1318. transformStack.back().rotate(r);
  1319. }
  1320. void Graphics::scale(float x, float y)
  1321. {
  1322. transformStack.back().scale(x, y);
  1323. pixelScaleStack.back() *= (fabs(x) + fabs(y)) / 2.0;
  1324. }
  1325. void Graphics::translate(float x, float y)
  1326. {
  1327. transformStack.back().translate(x, y);
  1328. }
  1329. void Graphics::shear(float kx, float ky)
  1330. {
  1331. transformStack.back().shear(kx, ky);
  1332. }
  1333. void Graphics::origin()
  1334. {
  1335. transformStack.back().setIdentity();
  1336. pixelScaleStack.back() = 1;
  1337. }
  1338. void Graphics::applyTransform(love::math::Transform *transform)
  1339. {
  1340. Matrix4 &m = transformStack.back();
  1341. m *= transform->getMatrix();
  1342. float sx, sy;
  1343. m.getApproximateScale(sx, sy);
  1344. pixelScaleStack.back() = (sx + sy) / 2.0;
  1345. }
  1346. void Graphics::replaceTransform(love::math::Transform *transform)
  1347. {
  1348. const Matrix4 &m = transform->getMatrix();
  1349. transformStack.back() = m;
  1350. float sx, sy;
  1351. m.getApproximateScale(sx, sy);
  1352. pixelScaleStack.back() = (sx + sy) / 2.0;
  1353. }
  1354. Vector2 Graphics::transformPoint(Vector2 point)
  1355. {
  1356. Vector2 p;
  1357. transformStack.back().transformXY(&p, &point, 1);
  1358. return p;
  1359. }
  1360. Vector2 Graphics::inverseTransformPoint(Vector2 point)
  1361. {
  1362. Vector2 p;
  1363. // TODO: We should probably cache the inverse transform so we don't have to
  1364. // re-calculate it every time this is called.
  1365. transformStack.back().inverse().transformXY(&p, &point, 1);
  1366. return p;
  1367. }
  1368. const Graphics::DefaultShaderCode &Graphics::getCurrentDefaultShaderCode() const
  1369. {
  1370. int languageindex = (int) getShaderLanguageTarget();
  1371. int gammaindex = isGammaCorrect() ? 1 : 0;
  1372. return defaultShaderCode[Shader::STANDARD_DEFAULT][languageindex][gammaindex];
  1373. }
  1374. /**
  1375. * Constants.
  1376. **/
  1377. bool Graphics::getConstant(const char *in, DrawMode &out)
  1378. {
  1379. return drawModes.find(in, out);
  1380. }
  1381. bool Graphics::getConstant(DrawMode in, const char *&out)
  1382. {
  1383. return drawModes.find(in, out);
  1384. }
  1385. std::vector<std::string> Graphics::getConstants(DrawMode)
  1386. {
  1387. return drawModes.getNames();
  1388. }
  1389. bool Graphics::getConstant(const char *in, ArcMode &out)
  1390. {
  1391. return arcModes.find(in, out);
  1392. }
  1393. bool Graphics::getConstant(ArcMode in, const char *&out)
  1394. {
  1395. return arcModes.find(in, out);
  1396. }
  1397. std::vector<std::string> Graphics::getConstants(ArcMode)
  1398. {
  1399. return arcModes.getNames();
  1400. }
  1401. bool Graphics::getConstant(const char *in, LineStyle &out)
  1402. {
  1403. return lineStyles.find(in, out);
  1404. }
  1405. bool Graphics::getConstant(LineStyle in, const char *&out)
  1406. {
  1407. return lineStyles.find(in, out);
  1408. }
  1409. std::vector<std::string> Graphics::getConstants(LineStyle)
  1410. {
  1411. return lineStyles.getNames();
  1412. }
  1413. bool Graphics::getConstant(const char *in, LineJoin &out)
  1414. {
  1415. return lineJoins.find(in, out);
  1416. }
  1417. bool Graphics::getConstant(LineJoin in, const char *&out)
  1418. {
  1419. return lineJoins.find(in, out);
  1420. }
  1421. std::vector<std::string> Graphics::getConstants(LineJoin)
  1422. {
  1423. return lineJoins.getNames();
  1424. }
  1425. bool Graphics::getConstant(const char *in, Feature &out)
  1426. {
  1427. return features.find(in, out);
  1428. }
  1429. bool Graphics::getConstant(Feature in, const char *&out)
  1430. {
  1431. return features.find(in, out);
  1432. }
  1433. bool Graphics::getConstant(const char *in, SystemLimit &out)
  1434. {
  1435. return systemLimits.find(in, out);
  1436. }
  1437. bool Graphics::getConstant(SystemLimit in, const char *&out)
  1438. {
  1439. return systemLimits.find(in, out);
  1440. }
  1441. bool Graphics::getConstant(const char *in, StackType &out)
  1442. {
  1443. return stackTypes.find(in, out);
  1444. }
  1445. bool Graphics::getConstant(StackType in, const char *&out)
  1446. {
  1447. return stackTypes.find(in, out);
  1448. }
  1449. std::vector<std::string> Graphics::getConstants(StackType)
  1450. {
  1451. return stackTypes.getNames();
  1452. }
  1453. StringMap<Graphics::DrawMode, Graphics::DRAW_MAX_ENUM>::Entry Graphics::drawModeEntries[] =
  1454. {
  1455. { "line", DRAW_LINE },
  1456. { "fill", DRAW_FILL },
  1457. };
  1458. StringMap<Graphics::DrawMode, Graphics::DRAW_MAX_ENUM> Graphics::drawModes(Graphics::drawModeEntries, sizeof(Graphics::drawModeEntries));
  1459. StringMap<Graphics::ArcMode, Graphics::ARC_MAX_ENUM>::Entry Graphics::arcModeEntries[] =
  1460. {
  1461. { "open", ARC_OPEN },
  1462. { "closed", ARC_CLOSED },
  1463. { "pie", ARC_PIE },
  1464. };
  1465. StringMap<Graphics::ArcMode, Graphics::ARC_MAX_ENUM> Graphics::arcModes(Graphics::arcModeEntries, sizeof(Graphics::arcModeEntries));
  1466. StringMap<Graphics::LineStyle, Graphics::LINE_MAX_ENUM>::Entry Graphics::lineStyleEntries[] =
  1467. {
  1468. { "smooth", LINE_SMOOTH },
  1469. { "rough", LINE_ROUGH }
  1470. };
  1471. StringMap<Graphics::LineStyle, Graphics::LINE_MAX_ENUM> Graphics::lineStyles(Graphics::lineStyleEntries, sizeof(Graphics::lineStyleEntries));
  1472. StringMap<Graphics::LineJoin, Graphics::LINE_JOIN_MAX_ENUM>::Entry Graphics::lineJoinEntries[] =
  1473. {
  1474. { "none", LINE_JOIN_NONE },
  1475. { "miter", LINE_JOIN_MITER },
  1476. { "bevel", LINE_JOIN_BEVEL }
  1477. };
  1478. StringMap<Graphics::LineJoin, Graphics::LINE_JOIN_MAX_ENUM> Graphics::lineJoins(Graphics::lineJoinEntries, sizeof(Graphics::lineJoinEntries));
  1479. StringMap<Graphics::Feature, Graphics::FEATURE_MAX_ENUM>::Entry Graphics::featureEntries[] =
  1480. {
  1481. { "multicanvasformats", FEATURE_MULTI_CANVAS_FORMATS },
  1482. { "clampzero", FEATURE_CLAMP_ZERO },
  1483. { "blendminmax", FEATURE_BLENDMINMAX },
  1484. { "lighten", FEATURE_LIGHTEN },
  1485. { "fullnpot", FEATURE_FULL_NPOT },
  1486. { "pixelshaderhighp", FEATURE_PIXEL_SHADER_HIGHP },
  1487. { "shaderderivatives", FEATURE_SHADER_DERIVATIVES },
  1488. { "glsl3", FEATURE_GLSL3 },
  1489. { "glsl4", FEATURE_GLSL4 },
  1490. { "instancing", FEATURE_INSTANCING },
  1491. };
  1492. StringMap<Graphics::Feature, Graphics::FEATURE_MAX_ENUM> Graphics::features(Graphics::featureEntries, sizeof(Graphics::featureEntries));
  1493. StringMap<Graphics::SystemLimit, Graphics::LIMIT_MAX_ENUM>::Entry Graphics::systemLimitEntries[] =
  1494. {
  1495. { "pointsize", LIMIT_POINT_SIZE },
  1496. { "texturesize", LIMIT_TEXTURE_SIZE },
  1497. { "texturelayers", LIMIT_TEXTURE_LAYERS },
  1498. { "volumetexturesize", LIMIT_VOLUME_TEXTURE_SIZE },
  1499. { "cubetexturesize", LIMIT_CUBE_TEXTURE_SIZE },
  1500. { "multicanvas", LIMIT_MULTI_CANVAS },
  1501. { "canvasmsaa", LIMIT_CANVAS_MSAA },
  1502. { "anisotropy", LIMIT_ANISOTROPY },
  1503. };
  1504. StringMap<Graphics::SystemLimit, Graphics::LIMIT_MAX_ENUM> Graphics::systemLimits(Graphics::systemLimitEntries, sizeof(Graphics::systemLimitEntries));
  1505. StringMap<Graphics::StackType, Graphics::STACK_MAX_ENUM>::Entry Graphics::stackTypeEntries[] =
  1506. {
  1507. { "all", STACK_ALL },
  1508. { "transform", STACK_TRANSFORM },
  1509. };
  1510. StringMap<Graphics::StackType, Graphics::STACK_MAX_ENUM> Graphics::stackTypes(Graphics::stackTypeEntries, sizeof(Graphics::stackTypeEntries));
  1511. } // graphics
  1512. } // love