Graphics.cpp 56 KB

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