Graphics.cpp 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977
  1. /**
  2. * Copyright (c) 2006-2024 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 "TextBatch.h"
  33. #include "common/deprecation.h"
  34. #include "common/config.h"
  35. // C++
  36. #include <algorithm>
  37. #include <stdlib.h>
  38. namespace love
  39. {
  40. namespace graphics
  41. {
  42. static bool gammaCorrect = false;
  43. static bool lowPowerPreferred = false;
  44. static bool debugMode = false;
  45. static bool debugModeQueried = false;
  46. void setGammaCorrect(bool gammacorrect)
  47. {
  48. gammaCorrect = gammacorrect;
  49. }
  50. bool isGammaCorrect()
  51. {
  52. return gammaCorrect;
  53. }
  54. void gammaCorrectColor(Colorf &c)
  55. {
  56. if (isGammaCorrect())
  57. {
  58. c.r = math::gammaToLinear(c.r);
  59. c.g = math::gammaToLinear(c.g);
  60. c.b = math::gammaToLinear(c.b);
  61. }
  62. }
  63. Colorf gammaCorrectColor(const Colorf &c)
  64. {
  65. Colorf r = c;
  66. gammaCorrectColor(r);
  67. return r;
  68. }
  69. void unGammaCorrectColor(Colorf &c)
  70. {
  71. if (isGammaCorrect())
  72. {
  73. c.r = math::linearToGamma(c.r);
  74. c.g = math::linearToGamma(c.g);
  75. c.b = math::linearToGamma(c.b);
  76. }
  77. }
  78. Colorf unGammaCorrectColor(const Colorf &c)
  79. {
  80. Colorf r = c;
  81. unGammaCorrectColor(r);
  82. return r;
  83. }
  84. bool isDebugEnabled()
  85. {
  86. if (!debugModeQueried)
  87. {
  88. const char *debugenv = getenv("LOVE_GRAPHICS_DEBUG");
  89. debugMode = debugenv != nullptr && debugenv[0] != '0';
  90. debugModeQueried = true;
  91. }
  92. return debugMode;
  93. }
  94. love::Type Graphics::type("graphics", &Module::type);
  95. namespace opengl { extern love::graphics::Graphics *createInstance(); }
  96. #ifdef LOVE_GRAPHICS_METAL
  97. namespace metal { extern love::graphics::Graphics *createInstance(); }
  98. #endif
  99. #ifdef LOVE_GRAPHICS_VULKAN
  100. namespace vulkan { extern love::graphics::Graphics *createInstance(); }
  101. #endif
  102. static const Renderer rendererOrder[] = {
  103. RENDERER_METAL,
  104. #ifdef LOVE_ANDROID
  105. // Don't enable vulkan by default yet on android - it needs more testing.
  106. RENDERER_OPENGL,
  107. RENDERER_VULKAN,
  108. #else
  109. RENDERER_VULKAN,
  110. RENDERER_OPENGL,
  111. #endif
  112. };
  113. static std::vector<Renderer> defaultRenderers =
  114. {
  115. RENDERER_METAL,
  116. RENDERER_VULKAN,
  117. RENDERER_OPENGL,
  118. };
  119. static std::vector<Renderer> _renderers = defaultRenderers;
  120. const std::vector<Renderer> &getDefaultRenderers()
  121. {
  122. return defaultRenderers;
  123. }
  124. const std::vector<Renderer> &getRenderers()
  125. {
  126. return _renderers;
  127. }
  128. void setRenderers(const std::vector<Renderer> &renderers)
  129. {
  130. _renderers = renderers;
  131. }
  132. void setLowPowerPreferred(bool preferred)
  133. {
  134. lowPowerPreferred = preferred;
  135. }
  136. bool isLowPowerPreferred()
  137. {
  138. return lowPowerPreferred;
  139. }
  140. Graphics *Graphics::createInstance()
  141. {
  142. Graphics *instance = Module::getInstance<Graphics>(M_GRAPHICS);
  143. if (instance != nullptr)
  144. instance->retain();
  145. else
  146. {
  147. for (auto r : rendererOrder)
  148. {
  149. if (std::find(_renderers.begin(), _renderers.end(), r) == _renderers.end())
  150. continue;
  151. #ifdef LOVE_GRAPHICS_VULKAN
  152. if (r == RENDERER_VULKAN)
  153. instance = vulkan::createInstance();
  154. #endif
  155. if (r == RENDERER_OPENGL)
  156. instance = opengl::createInstance();
  157. #ifdef LOVE_GRAPHICS_METAL
  158. if (r == RENDERER_METAL)
  159. instance = metal::createInstance();
  160. #endif
  161. if (instance != nullptr)
  162. break;
  163. }
  164. }
  165. return instance;
  166. }
  167. Graphics::DisplayState::DisplayState()
  168. {
  169. defaultSamplerState.mipmapFilter = SamplerState::MIPMAP_FILTER_LINEAR;
  170. }
  171. Graphics::Graphics(const char *name)
  172. : Module(M_GRAPHICS, name)
  173. , width(0)
  174. , height(0)
  175. , pixelWidth(0)
  176. , pixelHeight(0)
  177. , backbufferHasStencil(false)
  178. , backbufferHasDepth(false)
  179. , created(false)
  180. , active(true)
  181. , batchedDrawState()
  182. , deviceProjectionMatrix()
  183. , renderTargetSwitchCount(0)
  184. , drawCalls(0)
  185. , drawCallsBatched(0)
  186. , quadIndexBuffer(nullptr)
  187. , fanIndexBuffer(nullptr)
  188. , capabilities()
  189. , defaultTextures()
  190. , defaultTexelBuffers()
  191. , defaultStorageBuffer(nullptr)
  192. , cachedShaderStages()
  193. {
  194. transformStack.reserve(16);
  195. transformStack.push_back(Matrix4());
  196. pixelScaleStack.reserve(16);
  197. pixelScaleStack.push_back(1);
  198. states.reserve(10);
  199. states.push_back(DisplayState());
  200. noAttributesID = registerVertexAttributes(VertexAttributes());
  201. if (!Shader::initialize())
  202. throw love::Exception("Shader support failed to initialize.");
  203. }
  204. Graphics::~Graphics()
  205. {
  206. if (quadIndexBuffer != nullptr)
  207. quadIndexBuffer->release();
  208. if (fanIndexBuffer != nullptr)
  209. fanIndexBuffer->release();
  210. releaseDefaultResources();
  211. // Clean up standard shaders before the active shader. If we do it after,
  212. // the active shader may try to activate a standard shader when deactivating
  213. // itself, which will cause problems since it calls Graphics methods in the
  214. // Graphics destructor.
  215. for (int i = 0; i < Shader::STANDARD_MAX_ENUM; i++)
  216. {
  217. if (Shader::standardShaders[i])
  218. {
  219. Shader::standardShaders[i]->release();
  220. Shader::standardShaders[i] = nullptr;
  221. }
  222. }
  223. states.clear();
  224. defaultFont.set(nullptr);
  225. if (batchedDrawState.vb[0])
  226. batchedDrawState.vb[0]->release();
  227. if (batchedDrawState.vb[1])
  228. batchedDrawState.vb[1]->release();
  229. if (batchedDrawState.indexBuffer)
  230. batchedDrawState.indexBuffer->release();
  231. for (int i = 0; i < (int) SHADERSTAGE_MAX_ENUM; i++)
  232. cachedShaderStages[i].clear();
  233. pendingReadbacks.clear();
  234. clearTemporaryResources();
  235. Shader::deinitialize();
  236. }
  237. void Graphics::createQuadIndexBuffer()
  238. {
  239. if (quadIndexBuffer != nullptr)
  240. return;
  241. size_t size = sizeof(uint16) * getIndexCount(TRIANGLEINDEX_QUADS, LOVE_UINT16_MAX);
  242. Buffer::Settings settings(BUFFERUSAGEFLAG_INDEX, BUFFERDATAUSAGE_STATIC);
  243. quadIndexBuffer = newBuffer(settings, DATAFORMAT_UINT16, nullptr, size, 0);
  244. {
  245. Buffer::Mapper map(*quadIndexBuffer);
  246. fillIndices(TRIANGLEINDEX_QUADS, 0, LOVE_UINT16_MAX, (uint16 *) map.data);
  247. }
  248. quadIndexBuffer->setImmutable(true);
  249. }
  250. void Graphics::createFanIndexBuffer()
  251. {
  252. if (fanIndexBuffer != nullptr)
  253. return;
  254. size_t size = sizeof(uint16) * getIndexCount(TRIANGLEINDEX_FAN, LOVE_UINT16_MAX);
  255. Buffer::Settings settings(BUFFERUSAGEFLAG_INDEX, BUFFERDATAUSAGE_STATIC);
  256. fanIndexBuffer = newBuffer(settings, DATAFORMAT_UINT16, nullptr, size, 0);
  257. Buffer::Mapper map(*fanIndexBuffer);
  258. fillIndices(TRIANGLEINDEX_FAN, 0, LOVE_UINT16_MAX, (uint16 *) map.data);
  259. fanIndexBuffer->setImmutable(true);
  260. }
  261. Quad *Graphics::newQuad(Quad::Viewport v, double sw, double sh)
  262. {
  263. return new Quad(v, sw, sh);
  264. }
  265. Font *Graphics::newFont(love::font::Rasterizer *data)
  266. {
  267. return new Font(data, states.back().defaultSamplerState);
  268. }
  269. Font *Graphics::newDefaultFont(int size, const font::TrueTypeRasterizer::Settings &settings)
  270. {
  271. auto fontmodule = Module::getInstance<font::Font>(M_FONT);
  272. if (!fontmodule)
  273. throw love::Exception("Font module has not been loaded.");
  274. StrongRef<font::Rasterizer> r(fontmodule->newTrueTypeRasterizer(size, settings), Acquire::NORETAIN);
  275. return newFont(r.get());
  276. }
  277. Video *Graphics::newVideo(love::video::VideoStream *stream, float dpiscale)
  278. {
  279. return new Video(this, stream, dpiscale);
  280. }
  281. love::graphics::SpriteBatch *Graphics::newSpriteBatch(Texture *texture, int size, BufferDataUsage usage)
  282. {
  283. return new SpriteBatch(this, texture, size, usage);
  284. }
  285. love::graphics::ParticleSystem *Graphics::newParticleSystem(Texture *texture, int size)
  286. {
  287. return new ParticleSystem(texture, size);
  288. }
  289. ShaderStage *Graphics::newShaderStage(ShaderStageType stage, const std::string &source, const Shader::CompileOptions &options, const Shader::SourceInfo &info, bool cache)
  290. {
  291. ShaderStage *s = nullptr;
  292. std::string cachekey;
  293. // Never cache if there are custom defines set... because hashing would get
  294. // more complicated/expensive, and there shouldn't be a lot of duplicate
  295. // shader stages with custom defines anyway.
  296. if (!options.defines.empty())
  297. cache = false;
  298. if (cache && !source.empty())
  299. {
  300. data::HashFunction::Value hashvalue;
  301. data::hash(data::HashFunction::FUNCTION_SHA1, source.c_str(), source.size(), hashvalue);
  302. cachekey = std::string(hashvalue.data, hashvalue.size);
  303. auto it = cachedShaderStages[stage].find(cachekey);
  304. if (it != cachedShaderStages[stage].end())
  305. {
  306. s = it->second;
  307. s->retain();
  308. }
  309. }
  310. if (s == nullptr)
  311. {
  312. bool glsles = usesGLSLES();
  313. std::string glsl = Shader::createShaderStageCode(this, stage, source, options, info, glsles, true);
  314. s = newShaderStageInternal(stage, cachekey, glsl, glsles);
  315. if (cache && !cachekey.empty())
  316. cachedShaderStages[stage][cachekey] = s;
  317. }
  318. return s;
  319. }
  320. Shader *Graphics::newShader(const std::vector<std::string> &stagessource, const Shader::CompileOptions &options)
  321. {
  322. StrongRef<ShaderStage> stages[SHADERSTAGE_MAX_ENUM] = {};
  323. bool validstages[SHADERSTAGE_MAX_ENUM] = {};
  324. validstages[SHADERSTAGE_VERTEX] = true;
  325. validstages[SHADERSTAGE_PIXEL] = true;
  326. for (const std::string &source : stagessource)
  327. {
  328. Shader::SourceInfo info = Shader::getSourceInfo(source);
  329. bool isanystage = false;
  330. for (int i = 0; i < SHADERSTAGE_MAX_ENUM; i++)
  331. {
  332. if (!validstages[i])
  333. continue;
  334. if (info.stages[i] != Shader::ENTRYPOINT_NONE)
  335. {
  336. isanystage = true;
  337. stages[i].set(newShaderStage((ShaderStageType) i, source, options, info, true), Acquire::NORETAIN);
  338. }
  339. }
  340. if (!isanystage)
  341. throw love::Exception("Could not parse shader code (missing shader entry point function such as 'position' or 'effect')");
  342. }
  343. for (int i = 0; i < SHADERSTAGE_MAX_ENUM; i++)
  344. {
  345. auto stype = (ShaderStageType) i;
  346. if (validstages[i] && stages[i].get() == nullptr)
  347. {
  348. const std::string &source = Shader::getDefaultCode(Shader::STANDARD_DEFAULT, stype);
  349. Shader::SourceInfo info = Shader::getSourceInfo(source);
  350. Shader::CompileOptions opts;
  351. stages[i].set(newShaderStage(stype, source, opts, info, true), Acquire::NORETAIN);
  352. }
  353. }
  354. return newShaderInternal(stages, options);
  355. }
  356. Shader *Graphics::newComputeShader(const std::string &source, const Shader::CompileOptions &options)
  357. {
  358. Shader::SourceInfo info = Shader::getSourceInfo(source);
  359. if (info.stages[SHADERSTAGE_COMPUTE] == Shader::ENTRYPOINT_NONE)
  360. throw love::Exception("Could not parse compute shader code (missing 'computemain' function?)");
  361. StrongRef<ShaderStage> stages[SHADERSTAGE_MAX_ENUM];
  362. // Don't bother caching compute shader intermediate source, since there
  363. // shouldn't be much reuse.
  364. stages[SHADERSTAGE_COMPUTE].set(newShaderStage(SHADERSTAGE_COMPUTE, source, options, info, false));
  365. return newShaderInternal(stages, options);
  366. }
  367. Buffer *Graphics::newBuffer(const Buffer::Settings &settings, DataFormat format, const void *data, size_t size, size_t arraylength)
  368. {
  369. std::vector<Buffer::DataDeclaration> dataformat = {{"", format, 0}};
  370. return newBuffer(settings, dataformat, data, size, arraylength);
  371. }
  372. Mesh *Graphics::newMesh(const std::vector<Buffer::DataDeclaration> &vertexformat, int vertexcount, PrimitiveType drawmode, BufferDataUsage usage)
  373. {
  374. return new Mesh(this, vertexformat, vertexcount, drawmode, usage);
  375. }
  376. Mesh *Graphics::newMesh(const std::vector<Buffer::DataDeclaration> &vertexformat, const void *data, size_t datasize, PrimitiveType drawmode, BufferDataUsage usage)
  377. {
  378. return new Mesh(this, vertexformat, data, datasize, drawmode, usage);
  379. }
  380. Mesh *Graphics::newMesh(const std::vector<Mesh::BufferAttribute> &attributes, PrimitiveType drawmode)
  381. {
  382. return new Mesh(attributes, drawmode);
  383. }
  384. love::graphics::TextBatch *Graphics::newTextBatch(graphics::Font *font, const std::vector<love::font::ColoredString> &text)
  385. {
  386. return new TextBatch(font, text);
  387. }
  388. love::data::ByteData *Graphics::readbackBuffer(Buffer *buffer, size_t offset, size_t size, data::ByteData *dest, size_t destoffset)
  389. {
  390. StrongRef<GraphicsReadback> readback;
  391. readback.set(newReadbackInternal(READBACK_IMMEDIATE, buffer, offset, size, dest, destoffset), Acquire::NORETAIN);
  392. auto data = readback->getBufferData();
  393. if (data == nullptr)
  394. throw love::Exception("love.graphics.readbackBuffer failed.");
  395. data->retain();
  396. return data;
  397. }
  398. GraphicsReadback *Graphics::readbackBufferAsync(Buffer *buffer, size_t offset, size_t size, data::ByteData *dest, size_t destoffset)
  399. {
  400. auto readback = newReadbackInternal(READBACK_ASYNC, buffer, offset, size, dest, destoffset);
  401. pendingReadbacks.push_back(readback);
  402. return readback;
  403. }
  404. image::ImageData *Graphics::readbackTexture(Texture *texture, int slice, int mipmap, const Rect &rect, image::ImageData *dest, int destx, int desty)
  405. {
  406. StrongRef<GraphicsReadback> readback;
  407. readback.set(newReadbackInternal(READBACK_IMMEDIATE, texture, slice, mipmap, rect, dest, destx, desty), Acquire::NORETAIN);
  408. auto imagedata = readback->getImageData();
  409. if (imagedata == nullptr)
  410. throw love::Exception("love.graphics.readbackTexture failed.");
  411. imagedata->retain();
  412. return imagedata;
  413. }
  414. GraphicsReadback *Graphics::readbackTextureAsync(Texture *texture, int slice, int mipmap, const Rect &rect, image::ImageData *dest, int destx, int desty)
  415. {
  416. auto readback = newReadbackInternal(READBACK_ASYNC, texture, slice, mipmap, rect, dest, destx, desty);
  417. pendingReadbacks.push_back(readback);
  418. return readback;
  419. }
  420. void Graphics::cleanupCachedShaderStage(ShaderStageType type, const std::string &hashkey)
  421. {
  422. cachedShaderStages[type].erase(hashkey);
  423. }
  424. bool Graphics::validateShader(bool gles, const std::vector<std::string> &stagessource, const Shader::CompileOptions &options, std::string &err)
  425. {
  426. StrongRef<ShaderStage> stages[SHADERSTAGE_MAX_ENUM] = {};
  427. bool validstages[SHADERSTAGE_MAX_ENUM] = {};
  428. validstages[SHADERSTAGE_VERTEX] = true;
  429. validstages[SHADERSTAGE_PIXEL] = true;
  430. validstages[SHADERSTAGE_COMPUTE] = true;
  431. // Don't use cached shader stages, since the gles flag may not match the
  432. // current renderer.
  433. for (const std::string &source : stagessource)
  434. {
  435. Shader::SourceInfo info = Shader::getSourceInfo(source);
  436. bool isanystage = false;
  437. for (int i = 0; i < SHADERSTAGE_MAX_ENUM; i++)
  438. {
  439. auto stype = (ShaderStageType) i;
  440. if (!validstages[i])
  441. continue;
  442. if (info.stages[i] != Shader::ENTRYPOINT_NONE)
  443. {
  444. isanystage = true;
  445. std::string glsl = Shader::createShaderStageCode(this, stype, source, options, info, gles, false);
  446. stages[i].set(new ShaderStageForValidation(this, stype, glsl, gles), Acquire::NORETAIN);
  447. }
  448. }
  449. if (!isanystage)
  450. {
  451. err = "Could not parse shader code (missing 'position' or 'effect' function?)";
  452. return false;
  453. }
  454. }
  455. return Shader::validate(stages, err);
  456. }
  457. Texture *Graphics::getDefaultTexture(TextureType type, DataBaseType dataType, bool depthSample)
  458. {
  459. uint32 depthsampleindex = depthSample ? 1 : 0;
  460. Texture *tex = defaultTextures[type][dataType][depthsampleindex];
  461. if (tex != nullptr)
  462. return tex;
  463. Texture::Settings settings;
  464. settings.type = type;
  465. settings.readable.set(true);
  466. switch (dataType)
  467. {
  468. case DATA_BASETYPE_INT:
  469. settings.format = PIXELFORMAT_RGBA8_INT;
  470. break;
  471. case DATA_BASETYPE_UINT:
  472. settings.format = PIXELFORMAT_RGBA8_UINT;
  473. break;
  474. case DATA_BASETYPE_FLOAT:
  475. default:
  476. settings.format = PIXELFORMAT_RGBA8_UNORM;
  477. break;
  478. }
  479. if (depthSample)
  480. {
  481. settings.renderTarget = true;
  482. if (isPixelFormatSupported(PIXELFORMAT_DEPTH16_UNORM, PIXELFORMATUSAGE_SAMPLE))
  483. settings.format = PIXELFORMAT_DEPTH16_UNORM;
  484. else if (isPixelFormatSupported(PIXELFORMAT_DEPTH24_UNORM, PIXELFORMATUSAGE_SAMPLE))
  485. settings.format = PIXELFORMAT_DEPTH24_UNORM;
  486. else if (isPixelFormatSupported(PIXELFORMAT_DEPTH32_FLOAT, PIXELFORMATUSAGE_SAMPLE))
  487. settings.format = PIXELFORMAT_DEPTH32_FLOAT;
  488. else // TODO?
  489. settings.format = PIXELFORMAT_DEPTH24_UNORM;
  490. }
  491. std::string name = "default_";
  492. const char *tname = "unknown";
  493. Texture::getConstant(type, tname);
  494. name += tname;
  495. const char *formatname = "unknown";
  496. love::getConstant(settings.format, formatname);
  497. name += std::string("_") + formatname;
  498. settings.debugName = name;
  499. tex = newTexture(settings);
  500. SamplerState s;
  501. s.minFilter = s.magFilter = SamplerState::FILTER_NEAREST;
  502. s.wrapU = s.wrapV = s.wrapW = SamplerState::WRAP_CLAMP;
  503. if (depthSample)
  504. s.depthSampleMode.set(COMPARE_ALWAYS);
  505. tex->setSamplerState(s);
  506. if (!depthSample)
  507. {
  508. uint8 pixel[] = {255, 255, 255, 255};
  509. if (isPixelFormatInteger(settings.format))
  510. pixel[0] = pixel[1] = pixel[2] = pixel[3] = 1;
  511. for (int slice = 0; slice < (type == TEXTURE_CUBE ? 6 : 1); slice++)
  512. tex->replacePixels(pixel, sizeof(pixel), slice, 0, {0, 0, 1, 1}, false);
  513. }
  514. defaultTextures[type][dataType][depthsampleindex] = tex;
  515. return tex;
  516. }
  517. Buffer *Graphics::getDefaultTexelBuffer(DataBaseType dataType)
  518. {
  519. Buffer *buffer = defaultTexelBuffers[dataType];
  520. if (buffer != nullptr)
  521. return buffer;
  522. Buffer::Settings settings(BUFFERUSAGEFLAG_TEXEL, BUFFERDATAUSAGE_STATIC);
  523. settings.zeroInitialize = true;
  524. settings.debugName = "default_texelbuffer_";
  525. DataFormat format = DATAFORMAT_FLOAT;
  526. switch (dataType)
  527. {
  528. case DATA_BASETYPE_FLOAT:
  529. default:
  530. format = DATAFORMAT_FLOAT;
  531. settings.debugName += "float";
  532. break;
  533. case DATA_BASETYPE_INT:
  534. format = DATAFORMAT_INT32;
  535. settings.debugName += "int";
  536. break;
  537. case DATA_BASETYPE_UINT:
  538. format = DATAFORMAT_UINT32;
  539. settings.debugName += "uint";
  540. break;
  541. }
  542. buffer = newBuffer(settings, format, nullptr, sizeof(float), 1);
  543. defaultTexelBuffers[dataType] = buffer;
  544. return buffer;
  545. }
  546. Buffer *Graphics::getDefaultStorageBuffer()
  547. {
  548. if (defaultStorageBuffer != nullptr)
  549. return defaultStorageBuffer;
  550. Buffer::Settings settings(BUFFERUSAGEFLAG_SHADER_STORAGE, BUFFERDATAUSAGE_STATIC);
  551. settings.zeroInitialize = true;
  552. settings.debugName = "default_storagebuffer";
  553. defaultStorageBuffer = newBuffer(settings, DATAFORMAT_FLOAT, nullptr, Buffer::SHADER_STORAGE_BUFFER_MAX_STRIDE, 0);
  554. return defaultStorageBuffer;
  555. }
  556. void Graphics::releaseDefaultResources()
  557. {
  558. for (int type = 0; type < TEXTURE_MAX_ENUM; type++)
  559. {
  560. for (int dataType = 0; dataType < DATA_BASETYPE_MAX_ENUM; dataType++)
  561. {
  562. for (int depthsample = 0; depthsample < 2; depthsample++)
  563. {
  564. if (defaultTextures[type][dataType][depthsample])
  565. defaultTextures[type][dataType][depthsample]->release();
  566. defaultTextures[type][dataType][depthsample] = nullptr;
  567. }
  568. }
  569. }
  570. for (int dataType = 0; dataType < DATA_BASETYPE_MAX_ENUM; dataType++)
  571. {
  572. if (defaultTexelBuffers[dataType])
  573. defaultTexelBuffers[dataType]->release();
  574. defaultTexelBuffers[dataType] = nullptr;
  575. }
  576. if (defaultStorageBuffer)
  577. defaultStorageBuffer->release();
  578. defaultStorageBuffer = nullptr;
  579. }
  580. Texture *Graphics::getTextureOrDefaultForActiveShader(Texture *tex)
  581. {
  582. if (tex != nullptr)
  583. return tex;
  584. Shader *shader = Shader::current;
  585. if (shader != nullptr)
  586. {
  587. auto texinfo = shader->getMainTextureInfo();
  588. if (texinfo != nullptr && texinfo->textureType != TEXTURE_MAX_ENUM)
  589. return getDefaultTexture(texinfo->textureType, texinfo->dataBaseType, texinfo->isDepthSampler);
  590. }
  591. return getDefaultTexture(TEXTURE_2D, DATA_BASETYPE_FLOAT, false);
  592. }
  593. void Graphics::validateStencilState(const StencilState &s) const
  594. {
  595. if (s.action != STENCIL_KEEP)
  596. {
  597. const auto &rts = states.back().renderTargets;
  598. love::graphics::Texture *dstexture = rts.depthStencil.texture.get();
  599. if (!isRenderTargetActive() && !backbufferHasStencil)
  600. throw love::Exception("The window must have stenciling enabled to draw to the main screen's stencil buffer.");
  601. else if (isRenderTargetActive() && (rts.temporaryRTFlags & TEMPORARY_RT_STENCIL) == 0 && (dstexture == nullptr || !isPixelFormatStencil(dstexture->getPixelFormat())))
  602. throw love::Exception("Drawing to the stencil buffer with a Canvas active requires either stencil=true or a custom stencil-type Canvas to be used, in setCanvas.");
  603. }
  604. }
  605. void Graphics::validateDepthState(bool depthwrite) const
  606. {
  607. if (depthwrite)
  608. {
  609. const auto &rts = states.back().renderTargets;
  610. love::graphics::Texture *dstexture = rts.depthStencil.texture.get();
  611. if (!isRenderTargetActive() && !backbufferHasDepth)
  612. throw love::Exception("The window must have depth enabled to draw to the main screen's depth buffer.");
  613. else if (isRenderTargetActive() && (rts.temporaryRTFlags & TEMPORARY_RT_DEPTH) == 0 && (dstexture == nullptr || !isPixelFormatDepth(dstexture->getPixelFormat())))
  614. throw love::Exception("Drawing to the depth buffer with a Canvas active requires either depth=true or a custom depth-type Canvas to be used, in setCanvas.");
  615. }
  616. }
  617. int Graphics::getWidth() const
  618. {
  619. return width;
  620. }
  621. int Graphics::getHeight() const
  622. {
  623. return height;
  624. }
  625. int Graphics::getPixelWidth() const
  626. {
  627. return pixelWidth;
  628. }
  629. int Graphics::getPixelHeight() const
  630. {
  631. return pixelHeight;
  632. }
  633. double Graphics::getCurrentDPIScale() const
  634. {
  635. const auto &rt = states.back().renderTargets.getFirstTarget();
  636. if (rt.texture.get())
  637. return rt.texture->getDPIScale();
  638. return getScreenDPIScale();
  639. }
  640. double Graphics::getScreenDPIScale() const
  641. {
  642. return (double) getPixelHeight() / (double) getHeight();
  643. }
  644. bool Graphics::isCreated() const
  645. {
  646. return created;
  647. }
  648. bool Graphics::isActive() const
  649. {
  650. // The graphics module is only completely 'active' if there's a window, a
  651. // context, and the active variable is set.
  652. auto window = getInstance<love::window::Window>(M_WINDOW);
  653. return active && isCreated() && window != nullptr && window->isOpen();
  654. }
  655. void Graphics::reset()
  656. {
  657. DisplayState s;
  658. restoreState(s);
  659. origin();
  660. }
  661. void Graphics::backbufferChanged(int width, int height, int pixelwidth, int pixelheight)
  662. {
  663. backbufferChanged(width, height, pixelwidth, pixelheight, backbufferHasStencil, backbufferHasDepth, getRequestedBackbufferMSAA());
  664. }
  665. /**
  666. * State functions.
  667. **/
  668. void Graphics::restoreState(const DisplayState &s)
  669. {
  670. setColor(s.color);
  671. setBackgroundColor(s.backgroundColor);
  672. setBlendState(s.blend);
  673. setLineWidth(s.lineWidth);
  674. setLineStyle(s.lineStyle);
  675. setLineJoin(s.lineJoin);
  676. setPointSize(s.pointSize);
  677. if (s.scissor)
  678. setScissor(s.scissorRect);
  679. else
  680. setScissor();
  681. setMeshCullMode(s.meshCullMode);
  682. setFrontFaceWinding(s.winding);
  683. setFont(s.font.get());
  684. setShader(s.shader.get());
  685. setRenderTargets(s.renderTargets);
  686. setStencilState(s.stencil);
  687. setDepthMode(s.depthTest, s.depthWrite);
  688. setColorMask(s.colorMask);
  689. setWireframe(s.wireframe);
  690. setDefaultSamplerState(s.defaultSamplerState);
  691. if (s.useCustomProjection)
  692. updateDeviceProjection(s.customProjection);
  693. else
  694. resetProjection();
  695. }
  696. void Graphics::restoreStateChecked(const DisplayState &s)
  697. {
  698. const DisplayState &cur = states.back();
  699. if (s.color != cur.color)
  700. setColor(s.color);
  701. setBackgroundColor(s.backgroundColor);
  702. if (!(s.blend == cur.blend))
  703. setBlendState(s.blend);
  704. // These are just simple assignments.
  705. setLineWidth(s.lineWidth);
  706. setLineStyle(s.lineStyle);
  707. setLineJoin(s.lineJoin);
  708. if (s.pointSize != cur.pointSize)
  709. setPointSize(s.pointSize);
  710. if (s.scissor != cur.scissor || (s.scissor && !(s.scissorRect == cur.scissorRect)))
  711. {
  712. if (s.scissor)
  713. setScissor(s.scissorRect);
  714. else
  715. setScissor();
  716. }
  717. setMeshCullMode(s.meshCullMode);
  718. if (s.winding != cur.winding)
  719. setFrontFaceWinding(s.winding);
  720. setFont(s.font.get());
  721. setShader(s.shader.get());
  722. const auto &sRTs = s.renderTargets;
  723. const auto &curRTs = cur.renderTargets;
  724. bool rtschanged = sRTs.colors.size() != curRTs.colors.size();
  725. if (!rtschanged)
  726. {
  727. for (size_t i = 0; i < sRTs.colors.size() && i < curRTs.colors.size(); i++)
  728. {
  729. if (sRTs.colors[i] != curRTs.colors[i])
  730. {
  731. rtschanged = true;
  732. break;
  733. }
  734. }
  735. if (!rtschanged && sRTs.depthStencil != curRTs.depthStencil)
  736. rtschanged = true;
  737. if (sRTs.temporaryRTFlags != curRTs.temporaryRTFlags)
  738. rtschanged = true;
  739. }
  740. if (rtschanged)
  741. setRenderTargets(s.renderTargets);
  742. if (!(s.stencil == cur.stencil))
  743. setStencilState(s.stencil);
  744. if (s.depthTest != cur.depthTest || s.depthWrite != cur.depthWrite)
  745. setDepthMode(s.depthTest, s.depthWrite);
  746. if (s.colorMask != cur.colorMask)
  747. setColorMask(s.colorMask);
  748. if (s.wireframe != cur.wireframe)
  749. setWireframe(s.wireframe);
  750. setDefaultSamplerState(s.defaultSamplerState);
  751. if (s.useCustomProjection)
  752. setProjection(s.customProjection);
  753. else if (cur.useCustomProjection)
  754. resetProjection();
  755. }
  756. Colorf Graphics::getColor() const
  757. {
  758. return states.back().color;
  759. }
  760. void Graphics::setBackgroundColor(Colorf c)
  761. {
  762. states.back().backgroundColor = c;
  763. }
  764. Colorf Graphics::getBackgroundColor() const
  765. {
  766. return states.back().backgroundColor;
  767. }
  768. void Graphics::checkSetDefaultFont()
  769. {
  770. // We don't create or set the default Font if an existing font is in use.
  771. if (states.back().font.get() != nullptr)
  772. return;
  773. // Create a new default font if we don't have one yet.
  774. if (!defaultFont.get())
  775. {
  776. font::TrueTypeRasterizer::Settings settings;
  777. defaultFont.set(newDefaultFont(13, settings), Acquire::NORETAIN);
  778. }
  779. states.back().font.set(defaultFont.get());
  780. }
  781. void Graphics::setFont(love::graphics::Font *font)
  782. {
  783. // We don't need to set a default font here if null is passed in, since we
  784. // only care about the default font in getFont and print.
  785. DisplayState &state = states.back();
  786. state.font.set(font);
  787. }
  788. love::graphics::Font *Graphics::getFont()
  789. {
  790. checkSetDefaultFont();
  791. return states.back().font.get();
  792. }
  793. void Graphics::setShader(love::graphics::Shader *shader)
  794. {
  795. if (shader == nullptr)
  796. return setShader();
  797. shader->attach();
  798. states.back().shader.set(shader);
  799. }
  800. void Graphics::setShader()
  801. {
  802. Shader::attachDefault(Shader::STANDARD_DEFAULT);
  803. states.back().shader.set(nullptr);
  804. }
  805. love::graphics::Shader *Graphics::getShader() const
  806. {
  807. return states.back().shader.get();
  808. }
  809. void Graphics::setRenderTarget(RenderTarget rt, uint32 temporaryRTFlags)
  810. {
  811. if (rt.texture == nullptr)
  812. return setRenderTarget();
  813. RenderTargets rts;
  814. rts.colors.push_back(rt);
  815. rts.temporaryRTFlags = temporaryRTFlags;
  816. setRenderTargets(rts);
  817. }
  818. void Graphics::setRenderTargets(const RenderTargetsStrongRef &rts)
  819. {
  820. RenderTargets targets;
  821. targets.colors.reserve(rts.colors.size());
  822. for (const auto &rt : rts.colors)
  823. targets.colors.emplace_back(rt.texture.get(), rt.slice, rt.mipmap);
  824. targets.depthStencil = RenderTarget(rts.depthStencil.texture, rts.depthStencil.slice, rts.depthStencil.mipmap);
  825. targets.temporaryRTFlags = rts.temporaryRTFlags;
  826. return setRenderTargets(targets);
  827. }
  828. void Graphics::setRenderTargets(const RenderTargets &rts)
  829. {
  830. DisplayState &state = states.back();
  831. int rtcount = (int) rts.colors.size();
  832. RenderTarget firsttarget = rts.getFirstTarget();
  833. Texture *firsttex = firsttarget.texture;
  834. if (firsttex == nullptr)
  835. return setRenderTarget();
  836. const auto &prevRTsRef = state.renderTargets;
  837. if (rtcount == (int) prevRTsRef.colors.size())
  838. {
  839. bool modified = false;
  840. for (int i = 0; i < rtcount; i++)
  841. {
  842. if (rts.colors[i] != prevRTsRef.colors[i])
  843. {
  844. modified = true;
  845. break;
  846. }
  847. }
  848. if (!modified && rts.depthStencil != prevRTsRef.depthStencil)
  849. modified = true;
  850. if (rts.temporaryRTFlags != prevRTsRef.temporaryRTFlags)
  851. modified = true;
  852. if (!modified)
  853. return;
  854. }
  855. const RenderTargetsStrongRef prevRTs = prevRTsRef;
  856. if (rtcount > capabilities.limits[LIMIT_RENDER_TARGETS])
  857. throw love::Exception("This system can't simultaneously render to %d textures.", rtcount);
  858. bool hasSRGBtexture = false;
  859. int pixelw = firsttex->getPixelWidth(firsttarget.mipmap);
  860. int pixelh = firsttex->getPixelHeight(firsttarget.mipmap);
  861. int reqmsaa = firsttex->getRequestedMSAA();
  862. for (int i = 0; i < rtcount; i++)
  863. {
  864. Texture *c = rts.colors[i].texture;
  865. PixelFormat format = c->getPixelFormat();
  866. int mip = rts.colors[i].mipmap;
  867. int slice = rts.colors[i].slice;
  868. if (!c->isRenderTarget())
  869. throw love::Exception("Texture must be created as a canvas to be used in setCanvas.");
  870. if (mip < 0 || mip >= c->getMipmapCount())
  871. throw love::Exception("Invalid mipmap level %d.", mip + 1);
  872. if (!c->isValidSlice(slice, mip))
  873. throw love::Exception("Invalid slice index: %d.", slice + 1);
  874. if (c->getPixelWidth(mip) != pixelw || c->getPixelHeight(mip) != pixelh)
  875. throw love::Exception("All textures must have the same pixel dimensions.");
  876. if (c->getRequestedMSAA() != reqmsaa)
  877. throw love::Exception("All textures must have the same MSAA value.");
  878. if (isPixelFormatDepthStencil(format))
  879. throw love::Exception("Depth/stencil format textures must be used with the 'depthstencil' field of the table passed into setCanvas.");
  880. if (isPixelFormatSRGB(format))
  881. hasSRGBtexture = true;
  882. }
  883. if (rts.depthStencil.texture != nullptr)
  884. {
  885. Texture *c = rts.depthStencil.texture;
  886. int mip = rts.depthStencil.mipmap;
  887. int slice = rts.depthStencil.slice;
  888. if (!c->isRenderTarget())
  889. throw love::Exception("Texture must be created as a canvas to be used in setCanvas.");
  890. if (!isPixelFormatDepthStencil(c->getPixelFormat()))
  891. throw love::Exception("Only depth/stencil format textures can be used with the 'depthstencil' field of the table passed into setCanvas.");
  892. if (c->getPixelWidth(mip) != pixelw || c->getPixelHeight(mip) != pixelh)
  893. throw love::Exception("All Textures must have the same pixel dimensions.");
  894. if (c->getRequestedMSAA() != firsttex->getRequestedMSAA())
  895. throw love::Exception("All Textures must have the same MSAA value.");
  896. if (mip < 0 || mip >= c->getMipmapCount())
  897. throw love::Exception("Invalid mipmap level %d.", mip + 1);
  898. if (!c->isValidSlice(slice, mip))
  899. throw love::Exception("Invalid slice index: %d.", slice + 1);
  900. }
  901. flushBatchedDraws();
  902. if (rts.depthStencil.texture == nullptr && rts.temporaryRTFlags != 0)
  903. {
  904. bool wantsdepth = (rts.temporaryRTFlags & TEMPORARY_RT_DEPTH) != 0;
  905. bool wantsstencil = (rts.temporaryRTFlags & TEMPORARY_RT_STENCIL) != 0;
  906. PixelFormat dsformat = PIXELFORMAT_STENCIL8;
  907. if (wantsdepth && wantsstencil)
  908. dsformat = PIXELFORMAT_DEPTH24_UNORM_STENCIL8;
  909. else if (wantsdepth && isPixelFormatSupported(PIXELFORMAT_DEPTH24_UNORM, PIXELFORMATUSAGEFLAGS_RENDERTARGET))
  910. dsformat = PIXELFORMAT_DEPTH24_UNORM;
  911. else if (wantsdepth)
  912. dsformat = PIXELFORMAT_DEPTH16_UNORM;
  913. else if (wantsstencil)
  914. dsformat = PIXELFORMAT_STENCIL8;
  915. // We want setRenderTargetsInternal to have a pointer to the temporary RT,
  916. // but we don't want to directly store it in the main graphics state.
  917. RenderTargets realRTs = rts;
  918. realRTs.depthStencil.texture = getTemporaryTexture(dsformat, pixelw, pixelh, reqmsaa);
  919. realRTs.depthStencil.slice = 0;
  920. // TODO: fix this to call release at the right time.
  921. // This only works here because nothing else calls getTemporaryTexture.
  922. releaseTemporaryTexture(realRTs.depthStencil.texture);
  923. setRenderTargetsInternal(realRTs, pixelw, pixelh, hasSRGBtexture);
  924. }
  925. else
  926. setRenderTargetsInternal(rts, pixelw, pixelh, hasSRGBtexture);
  927. RenderTargetsStrongRef refs;
  928. refs.colors.reserve(rts.colors.size());
  929. for (auto c : rts.colors)
  930. refs.colors.emplace_back(c.texture, c.slice, c.mipmap);
  931. refs.depthStencil = RenderTargetStrongRef(rts.depthStencil.texture, rts.depthStencil.slice);
  932. refs.temporaryRTFlags = rts.temporaryRTFlags;
  933. std::swap(state.renderTargets, refs);
  934. renderTargetSwitchCount++;
  935. resetProjection();
  936. // generateMipmaps can't be used for depth/stencil textures.
  937. for (const auto &rt : prevRTs.colors)
  938. {
  939. if (rt.texture && rt.texture->getMipmapsMode() == Texture::MIPMAPS_AUTO && rt.mipmap == 0)
  940. rt.texture->generateMipmaps();
  941. }
  942. // Clear/reset the temporary depth/stencil buffers.
  943. // TODO: make this deferred somehow to avoid double clearing if the user
  944. // also calls love.graphics.clear after setCanvas.
  945. if (rts.depthStencil.texture == nullptr && rts.temporaryRTFlags != 0)
  946. {
  947. OptionalColorD clearcolor;
  948. OptionalInt clearstencil(0);
  949. OptionalDouble cleardepth(1.0);
  950. clear(clearcolor, clearstencil, cleardepth);
  951. }
  952. }
  953. void Graphics::setRenderTarget()
  954. {
  955. DisplayState &state = states.back();
  956. if (state.renderTargets.colors.empty() && state.renderTargets.depthStencil.texture == nullptr)
  957. return;
  958. const RenderTargetsStrongRef prevRTs = state.renderTargets;
  959. flushBatchedDraws();
  960. setRenderTargetsInternal(RenderTargets(), pixelWidth, pixelHeight, isGammaCorrect());
  961. state.renderTargets = RenderTargetsStrongRef();
  962. renderTargetSwitchCount++;
  963. resetProjection();
  964. // generateMipmaps can't be used for depth/stencil textures.
  965. for (const auto& rt : prevRTs.colors)
  966. {
  967. if (rt.texture && rt.texture->getMipmapsMode() == Texture::MIPMAPS_AUTO && rt.mipmap == 0)
  968. rt.texture->generateMipmaps();
  969. }
  970. }
  971. Graphics::RenderTargets Graphics::getRenderTargets() const
  972. {
  973. const auto &curRTs = states.back().renderTargets;
  974. RenderTargets rts;
  975. rts.colors.reserve(curRTs.colors.size());
  976. for (const auto &rt : curRTs.colors)
  977. rts.colors.emplace_back(rt.texture.get(), rt.slice, rt.mipmap);
  978. rts.depthStencil = RenderTarget(curRTs.depthStencil.texture, curRTs.depthStencil.slice, curRTs.depthStencil.mipmap);
  979. rts.temporaryRTFlags = curRTs.temporaryRTFlags;
  980. return rts;
  981. }
  982. bool Graphics::isRenderTargetActive() const
  983. {
  984. const auto &rts = states.back().renderTargets;
  985. return !rts.colors.empty() || rts.depthStencil.texture != nullptr;
  986. }
  987. bool Graphics::isRenderTargetActive(Texture *texture) const
  988. {
  989. Texture *roottexture = texture->getRootViewInfo().texture;
  990. const auto &rts = states.back().renderTargets;
  991. for (const auto &rt : rts.colors)
  992. {
  993. if (rt.texture.get() && rt.texture->getRootViewInfo().texture == roottexture)
  994. return true;
  995. }
  996. if (rts.depthStencil.texture.get() && rts.depthStencil.texture->getRootViewInfo().texture == roottexture)
  997. return true;
  998. return false;
  999. }
  1000. bool Graphics::isRenderTargetActive(Texture *texture, int slice) const
  1001. {
  1002. const auto &rootinfo = texture->getRootViewInfo();
  1003. slice += rootinfo.startLayer;
  1004. const auto &rts = states.back().renderTargets;
  1005. for (const auto &rt : rts.colors)
  1006. {
  1007. if (rt.texture.get())
  1008. {
  1009. const auto &info = rt.texture->getRootViewInfo();
  1010. if (rootinfo.texture == info.texture && rt.slice + info.startLayer == slice)
  1011. return true;
  1012. }
  1013. }
  1014. if (rts.depthStencil.texture.get())
  1015. {
  1016. const auto &info = rts.depthStencil.texture->getRootViewInfo();
  1017. if (rootinfo.texture == info.texture && rts.depthStencil.slice + info.startLayer == slice)
  1018. return true;
  1019. }
  1020. return false;
  1021. }
  1022. Texture *Graphics::getTemporaryTexture(PixelFormat format, int w, int h, int samples)
  1023. {
  1024. Texture *texture = nullptr;
  1025. for (TemporaryTexture &temp : temporaryTextures)
  1026. {
  1027. if (temp.framesSinceUse < 0)
  1028. continue;
  1029. Texture *c = temp.texture;
  1030. if (c->getPixelFormat() == format && c->getPixelWidth() == w
  1031. && c->getPixelHeight() == h && c->getRequestedMSAA() == samples)
  1032. {
  1033. texture = c;
  1034. temp.framesSinceUse = -1;
  1035. break;
  1036. }
  1037. }
  1038. if (texture == nullptr)
  1039. {
  1040. Texture::Settings settings;
  1041. settings.renderTarget = true;
  1042. settings.format = format;
  1043. settings.width = w;
  1044. settings.height = h;
  1045. settings.msaa = samples;
  1046. texture = newTexture(settings);
  1047. temporaryTextures.emplace_back(texture);
  1048. }
  1049. return texture;
  1050. }
  1051. void Graphics::releaseTemporaryTexture(Texture *texture)
  1052. {
  1053. for (TemporaryTexture &temp : temporaryTextures)
  1054. {
  1055. if (temp.texture == texture)
  1056. {
  1057. temp.framesSinceUse = 0;
  1058. break;
  1059. }
  1060. }
  1061. }
  1062. Buffer *Graphics::getTemporaryBuffer(size_t size, DataFormat format, uint32 usageflags, BufferDataUsage datausage)
  1063. {
  1064. Buffer *buffer = nullptr;
  1065. for (TemporaryBuffer &temp : temporaryBuffers)
  1066. {
  1067. if (temp.framesSinceUse < 0)
  1068. continue;
  1069. Buffer *b = temp.buffer;
  1070. if (temp.size == size && b->getDataMember(0).decl.format == format
  1071. && b->getUsageFlags() == usageflags && b->getDataUsage() == datausage)
  1072. {
  1073. buffer = b;
  1074. temp.framesSinceUse = -1;
  1075. break;
  1076. }
  1077. }
  1078. if (buffer == nullptr)
  1079. {
  1080. Buffer::Settings settings(usageflags, datausage);
  1081. buffer = newBuffer(settings, format, nullptr, size, 0);
  1082. temporaryBuffers.emplace_back(buffer, size);
  1083. }
  1084. return buffer;
  1085. }
  1086. void Graphics::releaseTemporaryBuffer(Buffer *buffer)
  1087. {
  1088. for (TemporaryBuffer &temp : temporaryBuffers)
  1089. {
  1090. if (temp.buffer == buffer)
  1091. {
  1092. temp.framesSinceUse = 0;
  1093. break;
  1094. }
  1095. }
  1096. }
  1097. void Graphics::updateTemporaryResources()
  1098. {
  1099. for (int i = (int) temporaryTextures.size() - 1; i >= 0; i--)
  1100. {
  1101. auto &t = temporaryTextures[i];
  1102. if (t.framesSinceUse >= MAX_TEMPORARY_RESOURCE_UNUSED_FRAMES)
  1103. {
  1104. t.texture->release();
  1105. t = temporaryTextures.back();
  1106. temporaryTextures.pop_back();
  1107. }
  1108. else if (t.framesSinceUse >= 0)
  1109. t.framesSinceUse++;
  1110. }
  1111. for (int i = (int) temporaryBuffers.size() - 1; i >= 0; i--)
  1112. {
  1113. auto &t = temporaryBuffers[i];
  1114. if (t.framesSinceUse >= MAX_TEMPORARY_RESOURCE_UNUSED_FRAMES)
  1115. {
  1116. t.buffer->release();
  1117. t = temporaryBuffers.back();
  1118. temporaryBuffers.pop_back();
  1119. }
  1120. else if (t.framesSinceUse >= 0)
  1121. t.framesSinceUse++;
  1122. }
  1123. }
  1124. void Graphics::clearTemporaryResources()
  1125. {
  1126. for (auto temp :temporaryBuffers)
  1127. temp.buffer->release();
  1128. for (auto temp : temporaryTextures)
  1129. temp.texture->release();
  1130. temporaryBuffers.clear();
  1131. temporaryTextures.clear();
  1132. }
  1133. void Graphics::updatePendingReadbacks()
  1134. {
  1135. for (int i = (int)pendingReadbacks.size() - 1; i >= 0; i--)
  1136. {
  1137. pendingReadbacks[i]->update();
  1138. if (pendingReadbacks[i]->isComplete())
  1139. {
  1140. pendingReadbacks[i] = pendingReadbacks.back();
  1141. pendingReadbacks.pop_back();
  1142. }
  1143. }
  1144. }
  1145. VertexAttributesID Graphics::registerVertexAttributes(const VertexAttributes &attributes)
  1146. {
  1147. for (size_t i = 0; i < vertexAttributesDatabase.size(); i++)
  1148. {
  1149. if (attributes == vertexAttributesDatabase[i])
  1150. return { (int)i + 1 };
  1151. }
  1152. vertexAttributesDatabase.push_back(attributes);
  1153. return { (int)vertexAttributesDatabase.size() };
  1154. }
  1155. bool Graphics::findVertexAttributes(VertexAttributesID id, VertexAttributes &attributes)
  1156. {
  1157. int index = id.id - 1;
  1158. if (index < 0 || index >= (int)vertexAttributesDatabase.size())
  1159. return false;
  1160. attributes = vertexAttributesDatabase[index];
  1161. return true;
  1162. }
  1163. void Graphics::intersectScissor(const Rect &rect)
  1164. {
  1165. Rect currect = states.back().scissorRect;
  1166. if (!states.back().scissor)
  1167. {
  1168. currect.x = 0;
  1169. currect.y = 0;
  1170. currect.w = std::numeric_limits<int>::max();
  1171. currect.h = std::numeric_limits<int>::max();
  1172. }
  1173. int x1 = std::max(currect.x, rect.x);
  1174. int y1 = std::max(currect.y, rect.y);
  1175. int x2 = std::min(currect.x + currect.w, rect.x + rect.w);
  1176. int y2 = std::min(currect.y + currect.h, rect.y + rect.h);
  1177. Rect newrect = {x1, y1, std::max(0, x2 - x1), std::max(0, y2 - y1)};
  1178. setScissor(newrect);
  1179. }
  1180. bool Graphics::getScissor(Rect &rect) const
  1181. {
  1182. const DisplayState &state = states.back();
  1183. rect = state.scissorRect;
  1184. return state.scissor;
  1185. }
  1186. void Graphics::setStencilMode(StencilMode mode, int value)
  1187. {
  1188. setStencilState(computeStencilState(mode, value));
  1189. if (mode == STENCIL_MODE_DRAW)
  1190. setColorMask({ false, false, false, false });
  1191. else
  1192. setColorMask({ true, true, true, true });
  1193. }
  1194. void Graphics::setStencilMode()
  1195. {
  1196. setStencilState(computeStencilState(STENCIL_MODE_OFF, 0));
  1197. setColorMask({ true, true, true, true });
  1198. }
  1199. StencilMode Graphics::getStencilMode(int &value) const
  1200. {
  1201. const DisplayState& state = states.back();
  1202. StencilMode mode = computeStencilMode(state.stencil);
  1203. value = state.stencil.value;
  1204. return mode;
  1205. }
  1206. void Graphics::setStencilState()
  1207. {
  1208. StencilState s;
  1209. setStencilState(s);
  1210. }
  1211. const StencilState &Graphics::getStencilState() const
  1212. {
  1213. const DisplayState &state = states.back();
  1214. return state.stencil;
  1215. }
  1216. void Graphics::setDepthMode()
  1217. {
  1218. setDepthMode(COMPARE_ALWAYS, false);
  1219. }
  1220. void Graphics::getDepthMode(CompareMode &compare, bool &write) const
  1221. {
  1222. const DisplayState &state = states.back();
  1223. compare = state.depthTest;
  1224. write = state.depthWrite;
  1225. }
  1226. void Graphics::setMeshCullMode(CullMode cull)
  1227. {
  1228. // Handled inside the draw() graphics API implementations.
  1229. states.back().meshCullMode = cull;
  1230. }
  1231. CullMode Graphics::getMeshCullMode() const
  1232. {
  1233. return states.back().meshCullMode;
  1234. }
  1235. Winding Graphics::getFrontFaceWinding() const
  1236. {
  1237. return states.back().winding;
  1238. }
  1239. ColorChannelMask Graphics::getColorMask() const
  1240. {
  1241. return states.back().colorMask;
  1242. }
  1243. void Graphics::setBlendMode(BlendMode mode, BlendAlpha alphamode)
  1244. {
  1245. if (alphamode == BLENDALPHA_MULTIPLY && !isAlphaMultiplyBlendSupported(mode))
  1246. {
  1247. const char *modestr = "unknown";
  1248. love::graphics::getConstant(mode, modestr);
  1249. throw love::Exception("The '%s' blend mode must be used with premultiplied alpha.", modestr);
  1250. }
  1251. setBlendState(computeBlendState(mode, alphamode));
  1252. }
  1253. BlendMode Graphics::getBlendMode(BlendAlpha &alphamode) const
  1254. {
  1255. return computeBlendMode(states.back().blend, alphamode);
  1256. }
  1257. const BlendState &Graphics::getBlendState() const
  1258. {
  1259. return states.back().blend;
  1260. }
  1261. void Graphics::setDefaultSamplerState(const SamplerState &s)
  1262. {
  1263. states.back().defaultSamplerState = s;
  1264. }
  1265. const SamplerState &Graphics::getDefaultSamplerState() const
  1266. {
  1267. return states.back().defaultSamplerState;
  1268. }
  1269. void Graphics::setLineWidth(float width)
  1270. {
  1271. states.back().lineWidth = width;
  1272. }
  1273. void Graphics::setLineStyle(Graphics::LineStyle style)
  1274. {
  1275. states.back().lineStyle = style;
  1276. }
  1277. void Graphics::setLineJoin(Graphics::LineJoin join)
  1278. {
  1279. states.back().lineJoin = join;
  1280. }
  1281. float Graphics::getLineWidth() const
  1282. {
  1283. return states.back().lineWidth;
  1284. }
  1285. Graphics::LineStyle Graphics::getLineStyle() const
  1286. {
  1287. return states.back().lineStyle;
  1288. }
  1289. Graphics::LineJoin Graphics::getLineJoin() const
  1290. {
  1291. return states.back().lineJoin;
  1292. }
  1293. float Graphics::getPointSize() const
  1294. {
  1295. return states.back().pointSize;
  1296. }
  1297. bool Graphics::isWireframe() const
  1298. {
  1299. return states.back().wireframe;
  1300. }
  1301. void Graphics::captureScreenshot(const ScreenshotInfo &info)
  1302. {
  1303. pendingScreenshotCallbacks.push_back(info);
  1304. }
  1305. void Graphics::copyBuffer(Buffer *source, Buffer *dest, size_t sourceoffset, size_t destoffset, size_t size)
  1306. {
  1307. Range sourcerange(sourceoffset, size);
  1308. Range destrange(destoffset, size);
  1309. if (dest->getDataUsage() == BUFFERDATAUSAGE_STREAM)
  1310. throw love::Exception("Buffers created with 'stream' data usage cannot be used as a copy destination.");
  1311. if (source->getDataUsage() == BUFFERDATAUSAGE_READBACK)
  1312. throw love::Exception("Buffers created with 'readback' data usage cannot be used as a copy source.");
  1313. if (sourcerange.getMax() >= source->getSize())
  1314. throw love::Exception("Buffer copy source offset and size doesn't fit within the source Buffer's size.");
  1315. if (destrange.getMax() >= dest->getSize())
  1316. throw love::Exception("Buffer copy destination offset and size doesn't fit within the destination buffer's size.");
  1317. if (source == dest && sourcerange.intersects(destrange))
  1318. throw love::Exception("Copying a portion of a buffer to the same buffer requires non-overlapping source and destination offsets.");
  1319. if (dest->isImmutable())
  1320. throw love::Exception("Cannot copy to an immutable buffer.");
  1321. if (sourceoffset % 4 != 0 || destoffset % 4 != 0 || size % 4 != 0)
  1322. throw love::Exception("Buffer copy source offset, destination offset, and size parameters must be multiples of 4 bytes.");
  1323. source->copyTo(dest, sourceoffset, destoffset, size);
  1324. }
  1325. void Graphics::copyTextureToBuffer(Texture *source, Buffer *dest, int slice, int mipmap, const Rect &rect, size_t destoffset, int destwidth)
  1326. {
  1327. if (!capabilities.features[FEATURE_COPY_TEXTURE_TO_BUFFER])
  1328. {
  1329. if (!source->isRenderTarget())
  1330. throw love::Exception("Copying a non-render target Texture to a Buffer is not supported on this system.");
  1331. }
  1332. PixelFormat format = source->getPixelFormat();
  1333. if (isPixelFormatDepthStencil(format))
  1334. throw love::Exception("Copying a depth/stencil Texture to a Buffer is not supported.");
  1335. if (!source->isReadable())
  1336. throw love::Exception("copyTextureToBuffer can only be called on readable Textures.");
  1337. if (dest->getDataUsage() == BUFFERDATAUSAGE_STREAM)
  1338. throw love::Exception("Buffers created with 'stream' data usage cannot be used as a copy destination.");
  1339. if (dest->isImmutable())
  1340. throw love::Exception("Cannot copy to an immutable buffer.");
  1341. if (isRenderTargetActive(source))
  1342. throw love::Exception("copyTextureToBuffer cannot be called while the Texture is an active render target.");
  1343. if (mipmap < 0 || mipmap >= source->getMipmapCount())
  1344. throw love::Exception("Invalid texture mipmap index %d.", mipmap + 1);
  1345. TextureType textype = source->getTextureType();
  1346. if (slice < 0 || (textype == TEXTURE_CUBE && slice >= 6)
  1347. || (textype == TEXTURE_VOLUME && slice >= source->getDepth(mipmap))
  1348. || (textype == TEXTURE_2D_ARRAY && slice >= source->getLayerCount()))
  1349. {
  1350. throw love::Exception("Invalid texture slice index %d.", slice + 1);
  1351. }
  1352. int mipw = source->getPixelWidth(mipmap);
  1353. int miph = source->getPixelHeight(mipmap);
  1354. if (rect.x < 0 || rect.y < 0 || rect.w <= 0 || rect.h <= 0
  1355. || (rect.x + rect.w) > mipw || (rect.y + rect.h) > miph)
  1356. {
  1357. 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);
  1358. }
  1359. if (destwidth <= 0)
  1360. destwidth = rect.w;
  1361. size_t size = 0;
  1362. if (isPixelFormatCompressed(format))
  1363. {
  1364. if (destwidth != rect.w) // OpenGL limitation...
  1365. throw love::Exception("Copying a compressed texture to a buffer cannot use a custom destination width.");
  1366. const PixelFormatInfo &info = getPixelFormatInfo(format);
  1367. int bw = (int) info.blockWidth;
  1368. int bh = (int) info.blockHeight;
  1369. if (rect.x % bw != 0 || rect.y % bh != 0 ||
  1370. ((rect.w % bw != 0 || rect.h % bh != 0) && rect.x + rect.w != source->getPixelWidth(mipmap)))
  1371. {
  1372. const char *name = nullptr;
  1373. love::getConstant(format, name);
  1374. 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);
  1375. }
  1376. // Note: this will need to change if destwidth == rect.w restriction
  1377. // is removed.
  1378. size = getPixelFormatSliceSize(format, destwidth, rect.h);
  1379. }
  1380. else
  1381. {
  1382. // Not the cleanest, but should work since uncompressed formats always
  1383. // have 1x1 blocks.
  1384. int pixels = (rect.h - 1) * destwidth + rect.w;
  1385. size = getPixelFormatUncompressedRowSize(format, pixels);
  1386. }
  1387. Range destrange(destoffset, size);
  1388. if (destoffset % 4 != 0 || size % 4 != 0)
  1389. throw love::Exception("Buffer copy destination offset and computed byte size must be multiples of 4 bytes.");
  1390. if (destrange.getMax() >= dest->getSize())
  1391. throw love::Exception("Buffer copy destination offset and width/height doesn't fit within the destination Buffer.");
  1392. source->copyToBuffer(dest, slice, mipmap, rect, destoffset, destwidth, size);
  1393. }
  1394. void Graphics::copyBufferToTexture(Buffer *source, Texture *dest, size_t sourceoffset, int sourcewidth, int slice, int mipmap, const Rect &rect)
  1395. {
  1396. if (source->getDataUsage() == BUFFERDATAUSAGE_READBACK)
  1397. throw love::Exception("Buffers created with 'readback' data usage cannot be used as a copy source.");
  1398. PixelFormat format = dest->getPixelFormat();
  1399. if (isPixelFormatDepthStencil(format))
  1400. throw love::Exception("Copying a Buffer to a depth/stencil Texture is not supported.");
  1401. if (!dest->isReadable())
  1402. throw love::Exception("copyBufferToTexture can only be called on readable Textures.");
  1403. if (isRenderTargetActive(dest))
  1404. throw love::Exception("copyBufferToTexture cannot be called while the Texture is an active render target.");
  1405. if (mipmap < 0 || mipmap >= dest->getMipmapCount())
  1406. throw love::Exception("Invalid texture mipmap index %d.", mipmap + 1);
  1407. TextureType textype = dest->getTextureType();
  1408. if (slice < 0 || (textype == TEXTURE_CUBE && slice >= 6)
  1409. || (textype == TEXTURE_VOLUME && slice >= dest->getDepth(mipmap))
  1410. || (textype == TEXTURE_2D_ARRAY && slice >= dest->getLayerCount()))
  1411. {
  1412. throw love::Exception("Invalid texture slice index %d.", slice + 1);
  1413. }
  1414. int mipw = dest->getPixelWidth(mipmap);
  1415. int miph = dest->getPixelHeight(mipmap);
  1416. if (rect.x < 0 || rect.y < 0 || rect.w <= 0 || rect.h <= 0
  1417. || (rect.x + rect.w) > mipw || (rect.y + rect.h) > miph)
  1418. {
  1419. 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);
  1420. }
  1421. if (sourcewidth <= 0)
  1422. sourcewidth = rect.w;
  1423. size_t size = 0;
  1424. if (isPixelFormatCompressed(format))
  1425. {
  1426. if (sourcewidth != rect.w) // OpenGL limitation...
  1427. throw love::Exception("Copying a buffer to a compressed texture cannot use a custom source width.");
  1428. const PixelFormatInfo &info = getPixelFormatInfo(format);
  1429. int bw = (int) info.blockWidth;
  1430. int bh = (int) info.blockHeight;
  1431. if (rect.x % bw != 0 || rect.y % bh != 0 ||
  1432. ((rect.w % bw != 0 || rect.h % bh != 0) && rect.x + rect.w != dest->getPixelWidth(mipmap)))
  1433. {
  1434. const char *name = nullptr;
  1435. love::getConstant(format, name);
  1436. 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);
  1437. }
  1438. // Note: this will need to change if sourcewidth == rect.w restriction
  1439. // is removed.
  1440. size = getPixelFormatSliceSize(format, sourcewidth, rect.h);
  1441. }
  1442. else
  1443. {
  1444. // Not the cleanest, but should work since uncompressed formats always
  1445. // have 1x1 blocks.
  1446. int pixels = (rect.h - 1) * sourcewidth + rect.w;
  1447. size = getPixelFormatUncompressedRowSize(format, pixels);
  1448. }
  1449. Range sourcerange(sourceoffset, size);
  1450. if (sourceoffset % 4 != 0 || size % 4 != 0)
  1451. throw love::Exception("Buffer copy source offset and computed byte size must be multiples of 4 bytes.");
  1452. if (sourcerange.getMax() >= source->getSize())
  1453. throw love::Exception("Buffer copy source offset and width/height doesn't fit within the source Buffer.");
  1454. dest->copyFromBuffer(source, sourceoffset, sourcewidth, size, slice, mipmap, rect);
  1455. }
  1456. static const char *getIndirectArgsTypeName(Graphics::IndirectArgsType argstype)
  1457. {
  1458. switch (argstype)
  1459. {
  1460. case Graphics::INDIRECT_ARGS_DISPATCH: return "Compute shader threadgroup argument data";
  1461. case Graphics::INDIRECT_ARGS_DRAW_VERTICES: return "Draw vertices argument data";
  1462. case Graphics::INDIRECT_ARGS_DRAW_INDICES: return "Draw indices argument data";
  1463. }
  1464. return "(Unknown argument data)";
  1465. }
  1466. void Graphics::validateIndirectArgsBuffer(IndirectArgsType argstype, Buffer *indirectargs, int argsindex)
  1467. {
  1468. if (!capabilities.features[FEATURE_INDIRECT_DRAW])
  1469. throw love::Exception("Indirect draws and compute dispatches are not supported on this system.");
  1470. if ((indirectargs->getUsageFlags() & BUFFERUSAGEFLAG_INDIRECT_ARGUMENTS) == 0)
  1471. throw love::Exception("The given Buffer must be created with the indirectarguments usage flag set, to be used for indirect arguments.");
  1472. if (argsindex < 0)
  1473. throw love::Exception("The given indirect argument index cannot be negative.");
  1474. size_t argelements = 0;
  1475. if (argstype == INDIRECT_ARGS_DISPATCH)
  1476. argelements = 3;
  1477. else if (argstype == INDIRECT_ARGS_DRAW_VERTICES)
  1478. argelements = 4;
  1479. else if (argstype == INDIRECT_ARGS_DRAW_INDICES)
  1480. argelements = 5;
  1481. size_t totalmembers = indirectargs->getArrayLength() * indirectargs->getDataMembers().size();
  1482. if (totalmembers % argelements != 0)
  1483. throw love::Exception("%s requires the given indirect argument Buffer to have a multiple of %ld int or uint values.", getIndirectArgsTypeName(argstype), argelements);
  1484. size_t argsoffset = argsindex * indirectargs->getArrayStride();
  1485. if (indirectargs->getSize() < argsoffset + sizeof(uint32) * argelements)
  1486. throw love::Exception("The given index into the indirect argument Buffer does not fit within the Buffer's size.");
  1487. }
  1488. void Graphics::dispatchThreadgroups(Shader *shader, int x, int y, int z)
  1489. {
  1490. if (!shader->hasStage(SHADERSTAGE_COMPUTE))
  1491. throw love::Exception("Only compute shaders can have threads dispatched.");
  1492. if (x <= 0 || y <= 0 || z <= 0)
  1493. throw love::Exception("Threadgroup dispatch size must be positive.");
  1494. if (x > capabilities.limits[LIMIT_THREADGROUPS_X]
  1495. || y > capabilities.limits[LIMIT_THREADGROUPS_Y]
  1496. || z > capabilities.limits[LIMIT_THREADGROUPS_Z])
  1497. {
  1498. throw love::Exception("Too many threadgroups dispatched.");
  1499. }
  1500. flushBatchedDraws();
  1501. auto prevshader = Shader::current;
  1502. shader->attach();
  1503. bool success = dispatch(shader, x, y, z);
  1504. if (prevshader != nullptr)
  1505. prevshader->attach();
  1506. if (!success)
  1507. throw love::Exception("Compute shader must have resources bound to all writable texture and buffer variables.");
  1508. }
  1509. void Graphics::dispatchIndirect(Shader *shader, Buffer *indirectargs, int argsindex)
  1510. {
  1511. if (!shader->hasStage(SHADERSTAGE_COMPUTE))
  1512. throw love::Exception("Only compute shaders can have threads dispatched.");
  1513. validateIndirectArgsBuffer(INDIRECT_ARGS_DISPATCH, indirectargs, argsindex);
  1514. flushBatchedDraws();
  1515. auto prevshader = Shader::current;
  1516. shader->attach();
  1517. bool success = dispatch(shader, indirectargs, argsindex * indirectargs->getArrayStride());
  1518. if (prevshader != nullptr)
  1519. prevshader->attach();
  1520. if (!success)
  1521. throw love::Exception("Compute shader must have resources bound to all writable texture and buffer variables.");
  1522. }
  1523. Graphics::BatchedVertexData Graphics::requestBatchedDraw(const BatchedDrawCommand &cmd)
  1524. {
  1525. BatchedDrawState &state = batchedDrawState;
  1526. bool shouldflush = false;
  1527. bool shouldresize = false;
  1528. if (cmd.primitiveMode != state.primitiveMode
  1529. || cmd.formats[0] != state.formats[0] || cmd.formats[1] != state.formats[1]
  1530. || ((cmd.indexMode != TRIANGLEINDEX_NONE) != (state.indexCount > 0))
  1531. || cmd.texture != state.texture
  1532. || cmd.standardShaderType != state.standardShaderType)
  1533. {
  1534. shouldflush = true;
  1535. }
  1536. int totalvertices = state.vertexCount + cmd.vertexCount;
  1537. // We only support uint16 index buffers for now.
  1538. if (totalvertices > LOVE_UINT16_MAX && cmd.indexMode != TRIANGLEINDEX_NONE)
  1539. shouldflush = true;
  1540. int reqIndexCount = getIndexCount(cmd.indexMode, cmd.vertexCount);
  1541. size_t reqIndexSize = reqIndexCount * sizeof(uint16);
  1542. size_t newdatasizes[2] = {0, 0};
  1543. size_t buffersizes[3] = {0, 0, 0};
  1544. for (int i = 0; i < 2; i++)
  1545. {
  1546. if (cmd.formats[i] == CommonFormat::NONE)
  1547. continue;
  1548. size_t stride = getFormatStride(cmd.formats[i]);
  1549. size_t datasize = stride * totalvertices;
  1550. if (state.vbMap[i].data != nullptr && datasize > state.vbMap[i].size)
  1551. shouldflush = true;
  1552. if (datasize > state.vb[i]->getUsableSize())
  1553. {
  1554. buffersizes[i] = std::max(datasize, state.vb[i]->getSize() * 2);
  1555. shouldresize = true;
  1556. }
  1557. newdatasizes[i] = stride * cmd.vertexCount;
  1558. }
  1559. if (cmd.indexMode != TRIANGLEINDEX_NONE)
  1560. {
  1561. size_t datasize = (state.indexCount + reqIndexCount) * sizeof(uint16);
  1562. if (state.indexBufferMap.data != nullptr && datasize > state.indexBufferMap.size)
  1563. shouldflush = true;
  1564. if (datasize > state.indexBuffer->getUsableSize())
  1565. {
  1566. buffersizes[2] = std::max(datasize, state.indexBuffer->getSize() * 2);
  1567. shouldresize = true;
  1568. }
  1569. }
  1570. if (shouldflush || shouldresize)
  1571. {
  1572. flushBatchedDraws();
  1573. state.primitiveMode = cmd.primitiveMode;
  1574. state.formats[0] = cmd.formats[0];
  1575. state.formats[1] = cmd.formats[1];
  1576. state.texture = cmd.texture;
  1577. state.standardShaderType = cmd.standardShaderType;
  1578. }
  1579. if (state.vertexCount == 0)
  1580. {
  1581. if (Shader::isDefaultActive())
  1582. Shader::attachDefault(state.standardShaderType);
  1583. if (Shader::current != nullptr)
  1584. Shader::current->validateDrawState(cmd.primitiveMode, cmd.texture);
  1585. }
  1586. if (shouldresize)
  1587. {
  1588. for (int i = 0; i < 2; i++)
  1589. {
  1590. if (state.vb[i]->getSize() < buffersizes[i])
  1591. {
  1592. state.vb[i]->release();
  1593. state.vb[i] = newStreamBuffer(BUFFERUSAGE_VERTEX, buffersizes[i]);
  1594. }
  1595. }
  1596. if (state.indexBuffer->getSize() < buffersizes[2])
  1597. {
  1598. state.indexBuffer->release();
  1599. state.indexBuffer = newStreamBuffer(BUFFERUSAGE_INDEX, buffersizes[2]);
  1600. }
  1601. }
  1602. if (cmd.indexMode != TRIANGLEINDEX_NONE)
  1603. {
  1604. if (state.indexBufferMap.data == nullptr)
  1605. state.indexBufferMap = state.indexBuffer->map(reqIndexSize);
  1606. uint16 *indices = (uint16 *) state.indexBufferMap.data;
  1607. fillIndices(cmd.indexMode, state.vertexCount, cmd.vertexCount, indices);
  1608. state.indexBufferMap.data += reqIndexSize;
  1609. }
  1610. BatchedVertexData d;
  1611. for (int i = 0; i < 2; i++)
  1612. {
  1613. if (newdatasizes[i] > 0)
  1614. {
  1615. if (state.vbMap[i].data == nullptr)
  1616. state.vbMap[i] = state.vb[i]->map(newdatasizes[i]);
  1617. d.stream[i] = state.vbMap[i].data;
  1618. state.vbMap[i].data += newdatasizes[i];
  1619. }
  1620. }
  1621. if (state.vertexCount > 0)
  1622. drawCallsBatched++;
  1623. state.vertexCount += cmd.vertexCount;
  1624. state.indexCount += reqIndexCount;
  1625. return d;
  1626. }
  1627. void Graphics::flushBatchedDraws()
  1628. {
  1629. auto &sbstate = batchedDrawState;
  1630. if ((sbstate.vertexCount == 0 && sbstate.indexCount == 0) || sbstate.flushing)
  1631. return;
  1632. VertexAttributes attributes;
  1633. BufferBindings buffers;
  1634. VertexAttributesID attributesID = sbstate.attributesIDs[(int)sbstate.formats[0]][(int)sbstate.formats[1]];
  1635. if (!findVertexAttributes(attributesID, attributes))
  1636. {
  1637. for (int i = 0; i < 2; i++)
  1638. attributes.setCommonFormat(sbstate.formats[i], (uint8)i);
  1639. attributesID = registerVertexAttributes(attributes);
  1640. sbstate.attributesIDs[(int)sbstate.formats[0]][(int)sbstate.formats[1]] = attributesID;
  1641. }
  1642. size_t usedsizes[3] = {0, 0, 0};
  1643. for (int i = 0; i < 2; i++)
  1644. {
  1645. if (sbstate.formats[i] == CommonFormat::NONE)
  1646. continue;
  1647. usedsizes[i] = getFormatStride(sbstate.formats[i]) * sbstate.vertexCount;
  1648. size_t offset = sbstate.vb[i]->unmap(usedsizes[i]);
  1649. buffers.set(i, sbstate.vb[i], offset);
  1650. sbstate.vbMap[i] = StreamBuffer::MapInfo();
  1651. }
  1652. if (attributes.enableBits == 0)
  1653. return;
  1654. sbstate.flushing = true;
  1655. Colorf nc = getColor();
  1656. if (attributes.isEnabled(ATTRIB_COLOR))
  1657. setColor(Colorf(1.0f, 1.0f, 1.0f, 1.0f));
  1658. pushIdentityTransform();
  1659. if (sbstate.indexCount > 0)
  1660. {
  1661. usedsizes[2] = sizeof(uint16) * sbstate.indexCount;
  1662. DrawIndexedCommand cmd(attributesID, &buffers, sbstate.indexBuffer);
  1663. cmd.primitiveType = sbstate.primitiveMode;
  1664. cmd.indexCount = sbstate.indexCount;
  1665. cmd.indexType = INDEX_UINT16;
  1666. cmd.indexBufferOffset = sbstate.indexBuffer->unmap(usedsizes[2]);
  1667. cmd.texture = getTextureOrDefaultForActiveShader(sbstate.texture);
  1668. draw(cmd);
  1669. sbstate.indexBufferMap = StreamBuffer::MapInfo();
  1670. }
  1671. else
  1672. {
  1673. DrawCommand cmd(attributesID, &buffers);
  1674. cmd.primitiveType = sbstate.primitiveMode;
  1675. cmd.vertexStart = 0;
  1676. cmd.vertexCount = sbstate.vertexCount;
  1677. cmd.texture = getTextureOrDefaultForActiveShader(sbstate.texture);
  1678. draw(cmd);
  1679. }
  1680. for (int i = 0; i < 2; i++)
  1681. {
  1682. if (usedsizes[i] > 0)
  1683. sbstate.vb[i]->markUsed(usedsizes[i]);
  1684. }
  1685. if (usedsizes[2] > 0)
  1686. sbstate.indexBuffer->markUsed(usedsizes[2]);
  1687. popTransform();
  1688. if (attributes.isEnabled(ATTRIB_COLOR))
  1689. setColor(nc);
  1690. sbstate.vertexCount = 0;
  1691. sbstate.indexCount = 0;
  1692. sbstate.flushing = false;
  1693. }
  1694. void Graphics::flushBatchedDrawsGlobal()
  1695. {
  1696. Graphics *instance = getInstance<Graphics>(M_GRAPHICS);
  1697. if (instance != nullptr)
  1698. instance->flushBatchedDraws();
  1699. }
  1700. /**
  1701. * Drawing
  1702. **/
  1703. void Graphics::draw(Drawable *drawable, const Matrix4 &m)
  1704. {
  1705. drawable->draw(this, m);
  1706. }
  1707. void Graphics::draw(Texture *texture, Quad *quad, const Matrix4 &m)
  1708. {
  1709. texture->draw(this, quad, m);
  1710. }
  1711. void Graphics::drawLayer(Texture *texture, int layer, const Matrix4 &m)
  1712. {
  1713. texture->drawLayer(this, layer, m);
  1714. }
  1715. void Graphics::drawLayer(Texture *texture, int layer, Quad *quad, const Matrix4 &m)
  1716. {
  1717. texture->drawLayer(this, layer, quad, m);
  1718. }
  1719. void Graphics::drawInstanced(Mesh *mesh, const Matrix4 &m, int instancecount)
  1720. {
  1721. mesh->drawInstanced(this, m, instancecount);
  1722. }
  1723. void Graphics::drawIndirect(Mesh *mesh, const Matrix4 &m, Buffer *indirectargs, int argsindex)
  1724. {
  1725. mesh->drawIndirect(this, m, indirectargs, argsindex);
  1726. }
  1727. void Graphics::drawFromShader(PrimitiveType primtype, int vertexcount, int instancecount, Texture *maintexture)
  1728. {
  1729. if (primtype == PRIMITIVE_TRIANGLE_FAN && vertexcount > LOVE_UINT16_MAX)
  1730. throw love::Exception("drawFromShader cannot draw more than %d vertices when the 'fan' draw mode is used.", LOVE_UINT16_MAX);
  1731. // Emulated triangle fan via an index buffer.
  1732. if (primtype == PRIMITIVE_TRIANGLE_FAN && getFanIndexBuffer())
  1733. {
  1734. int indexcount = getIndexCount(TRIANGLEINDEX_FAN, vertexcount);
  1735. drawFromShader(getFanIndexBuffer(), indexcount, instancecount, 0, maintexture);
  1736. return;
  1737. }
  1738. flushBatchedDraws();
  1739. if (Shader::isDefaultActive() || !Shader::current)
  1740. throw love::Exception("drawFromShader can only be used with a custom shader.");
  1741. if (vertexcount < 0 || instancecount < 0)
  1742. throw love::Exception("drawFromShader vertex and instance count parameters must not be negative.");
  1743. Shader::current->validateDrawState(primtype, maintexture);
  1744. BufferBindings buffers;
  1745. DrawCommand cmd(noAttributesID, &buffers);
  1746. cmd.primitiveType = primtype;
  1747. cmd.vertexCount = vertexcount;
  1748. cmd.instanceCount = std::max(1, instancecount);
  1749. cmd.texture = getTextureOrDefaultForActiveShader(maintexture);
  1750. draw(cmd);
  1751. }
  1752. void Graphics::drawFromShader(Buffer *indexbuffer, int indexcount, int instancecount, int startindex, Texture *maintexture)
  1753. {
  1754. flushBatchedDraws();
  1755. if (!(indexbuffer->getUsageFlags() & BUFFERUSAGEFLAG_INDEX))
  1756. throw love::Exception("The buffer passed to drawFromShader must be an index buffer.");
  1757. if (startindex < 0)
  1758. throw love::Exception("drawFromShader startindex parameter must not be negative.");
  1759. if (indexcount < 0 || instancecount < 0)
  1760. throw love::Exception("drawFromShader index and instance count parameters must not be negative.");
  1761. if ((size_t)(startindex + indexcount) > indexbuffer->getArrayLength() * indexbuffer->getDataMembers().size())
  1762. throw love::Exception("drawFromShader startindex and index count parameters do not fit in the given index buffer.");
  1763. if (Shader::isDefaultActive() || !Shader::current)
  1764. throw love::Exception("drawFromShader can only be used with a custom shader.");
  1765. Shader::current->validateDrawState(PRIMITIVE_TRIANGLES, maintexture);
  1766. BufferBindings buffers;
  1767. DrawIndexedCommand cmd(noAttributesID, &buffers, indexbuffer);
  1768. cmd.primitiveType = PRIMITIVE_TRIANGLES;
  1769. cmd.indexCount = indexcount;
  1770. cmd.instanceCount = std::max(1, instancecount);
  1771. cmd.indexType = getIndexDataType(indexbuffer->getDataMember(0).decl.format);
  1772. cmd.indexBufferOffset = startindex * getIndexDataSize(cmd.indexType);
  1773. cmd.texture = getTextureOrDefaultForActiveShader(maintexture);
  1774. draw(cmd);
  1775. }
  1776. void Graphics::drawFromShaderIndirect(PrimitiveType primtype, Buffer *indirectargs, int argsindex, Texture *maintexture)
  1777. {
  1778. flushBatchedDraws();
  1779. if (primtype == PRIMITIVE_TRIANGLE_FAN)
  1780. throw love::Exception("The fan draw mode is not supported in indirect draws.");
  1781. if (Shader::isDefaultActive() || !Shader::current)
  1782. throw love::Exception("drawFromShaderIndirect can only be used with a custom shader.");
  1783. validateIndirectArgsBuffer(INDIRECT_ARGS_DRAW_VERTICES, indirectargs, argsindex);
  1784. Shader::current->validateDrawState(primtype, maintexture);
  1785. BufferBindings buffers;
  1786. DrawCommand cmd(noAttributesID, &buffers);
  1787. cmd.primitiveType = primtype;
  1788. cmd.indirectBuffer = indirectargs;
  1789. cmd.indirectBufferOffset = argsindex * indirectargs->getArrayStride();
  1790. cmd.texture = getTextureOrDefaultForActiveShader(maintexture);
  1791. draw(cmd);
  1792. }
  1793. void Graphics::drawFromShaderIndirect(Buffer *indexbuffer, Buffer *indirectargs, int argsindex, Texture *maintexture)
  1794. {
  1795. flushBatchedDraws();
  1796. if (!(indexbuffer->getUsageFlags() & BUFFERUSAGEFLAG_INDEX))
  1797. throw love::Exception("The buffer passed to the indexed variant of drawFromShaderIndirect must be an index buffer.");
  1798. if (Shader::isDefaultActive() || !Shader::current)
  1799. throw love::Exception("drawFromShaderIndirect can only be used with a custom shader.");
  1800. validateIndirectArgsBuffer(INDIRECT_ARGS_DRAW_INDICES, indirectargs, argsindex);
  1801. Shader::current->validateDrawState(PRIMITIVE_TRIANGLES, maintexture);
  1802. BufferBindings buffers;
  1803. DrawIndexedCommand cmd(noAttributesID, &buffers, indexbuffer);
  1804. cmd.primitiveType = PRIMITIVE_TRIANGLES;
  1805. cmd.indexType = getIndexDataType(indexbuffer->getDataMember(0).decl.format);
  1806. cmd.indirectBuffer = indirectargs;
  1807. cmd.indexBufferOffset = argsindex * indirectargs->getArrayStride();
  1808. cmd.texture = getTextureOrDefaultForActiveShader(maintexture);
  1809. draw(cmd);
  1810. }
  1811. void Graphics::print(const std::vector<love::font::ColoredString> &str, const Matrix4 &m)
  1812. {
  1813. checkSetDefaultFont();
  1814. if (states.back().font.get() != nullptr)
  1815. print(str, states.back().font.get(), m);
  1816. }
  1817. void Graphics::print(const std::vector<love::font::ColoredString> &str, Font *font, const Matrix4 &m)
  1818. {
  1819. font->print(this, str, m, states.back().color);
  1820. }
  1821. void Graphics::printf(const std::vector<love::font::ColoredString> &str, float wrap, Font::AlignMode align, const Matrix4 &m)
  1822. {
  1823. checkSetDefaultFont();
  1824. if (states.back().font.get() != nullptr)
  1825. printf(str, states.back().font.get(), wrap, align, m);
  1826. }
  1827. void Graphics::printf(const std::vector<love::font::ColoredString> &str, Font *font, float wrap, Font::AlignMode align, const Matrix4 &m)
  1828. {
  1829. font->printf(this, str, wrap, align, m, states.back().color);
  1830. }
  1831. /**
  1832. * Primitives (points, shapes, lines).
  1833. **/
  1834. void Graphics::points(const Vector2 *positions, const Colorf *colors, size_t numpoints)
  1835. {
  1836. const Matrix4 &t = getTransform();
  1837. bool is2D = t.isAffine2DTransform();
  1838. BatchedDrawCommand cmd;
  1839. cmd.primitiveMode = PRIMITIVE_POINTS;
  1840. cmd.formats[0] = getSinglePositionFormat(is2D);
  1841. cmd.formats[1] = CommonFormat::RGBAub;
  1842. cmd.vertexCount = (int) numpoints;
  1843. cmd.standardShaderType = Shader::STANDARD_POINTS;
  1844. BatchedVertexData data = requestBatchedDraw(cmd);
  1845. if (is2D)
  1846. t.transformXY((Vector2 *) data.stream[0], positions, cmd.vertexCount);
  1847. else
  1848. t.transformXY0((Vector3 *) data.stream[0], positions, cmd.vertexCount);
  1849. Color32 *colordata = (Color32 *) data.stream[1];
  1850. if (colors)
  1851. {
  1852. Colorf nc = getColor();
  1853. gammaCorrectColor(nc);
  1854. if (isGammaCorrect())
  1855. {
  1856. for (int i = 0; i < cmd.vertexCount; i++)
  1857. {
  1858. Colorf ci = colors[i];
  1859. gammaCorrectColor(ci);
  1860. ci *= nc;
  1861. unGammaCorrectColor(ci);
  1862. colordata[i] = toColor32(ci);
  1863. }
  1864. }
  1865. else
  1866. {
  1867. for (int i = 0; i < cmd.vertexCount; i++)
  1868. colordata[i] = toColor32(nc * colors[i]);
  1869. }
  1870. }
  1871. else
  1872. {
  1873. Color32 c = toColor32(getColor());
  1874. for (int i = 0; i < cmd.vertexCount; i++)
  1875. colordata[i] = c;
  1876. }
  1877. }
  1878. int Graphics::calculateEllipsePoints(float rx, float ry) const
  1879. {
  1880. int points = (int) sqrtf(((rx + ry) / 2.0f) * 20.0f * (float) pixelScaleStack.back());
  1881. return std::max(points, 8);
  1882. }
  1883. void Graphics::polyline(const Vector2 *vertices, size_t count)
  1884. {
  1885. float halfwidth = getLineWidth() * 0.5f;
  1886. LineJoin linejoin = getLineJoin();
  1887. LineStyle linestyle = getLineStyle();
  1888. float pixelsize = 1.0f / std::max((float) pixelScaleStack.back(), 0.000001f);
  1889. if (linejoin == LINE_JOIN_NONE)
  1890. {
  1891. NoneJoinPolyline line;
  1892. line.render(vertices, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  1893. line.draw(this);
  1894. }
  1895. else if (linejoin == LINE_JOIN_BEVEL)
  1896. {
  1897. BevelJoinPolyline line;
  1898. line.render(vertices, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  1899. line.draw(this);
  1900. }
  1901. else if (linejoin == LINE_JOIN_MITER)
  1902. {
  1903. MiterJoinPolyline line;
  1904. line.render(vertices, count, halfwidth, pixelsize, linestyle == LINE_SMOOTH);
  1905. line.draw(this);
  1906. }
  1907. }
  1908. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h)
  1909. {
  1910. Vector2 coords[] = {Vector2(x,y), Vector2(x,y+h), Vector2(x+w,y+h), Vector2(x+w,y), Vector2(x,y)};
  1911. polygon(mode, coords, 5);
  1912. }
  1913. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry, int points)
  1914. {
  1915. if (rx <= 0 || ry <= 0)
  1916. {
  1917. rectangle(mode, x, y, w, h);
  1918. return;
  1919. }
  1920. // Radius values that are more than half the rectangle's size aren't handled
  1921. // correctly (for now)...
  1922. if (w >= 0.02f)
  1923. rx = std::min(rx, w / 2.0f - 0.01f);
  1924. if (h >= 0.02f)
  1925. ry = std::min(ry, h / 2.0f - 0.01f);
  1926. points = std::max(points / 4, 1);
  1927. const float half_pi = static_cast<float>(LOVE_M_PI / 2);
  1928. float angle_shift = half_pi / ((float) points + 1.0f);
  1929. int num_coords = (points + 2) * 4;
  1930. Vector2 *coords = getScratchBuffer<Vector2>(num_coords + 1);
  1931. float phi = .0f;
  1932. for (int i = 0; i <= points + 2; ++i, phi += angle_shift)
  1933. {
  1934. coords[i].x = x + rx * (1 - cosf(phi));
  1935. coords[i].y = y + ry * (1 - sinf(phi));
  1936. }
  1937. phi = half_pi;
  1938. for (int i = points + 2; i <= 2 * (points + 2); ++i, phi += angle_shift)
  1939. {
  1940. coords[i].x = x + w - rx * (1 + cosf(phi));
  1941. coords[i].y = y + ry * (1 - sinf(phi));
  1942. }
  1943. phi = 2 * half_pi;
  1944. for (int i = 2 * (points + 2); i <= 3 * (points + 2); ++i, phi += angle_shift)
  1945. {
  1946. coords[i].x = x + w - rx * (1 + cosf(phi));
  1947. coords[i].y = y + h - ry * (1 + sinf(phi));
  1948. }
  1949. phi = 3 * half_pi;
  1950. for (int i = 3 * (points + 2); i <= 4 * (points + 2); ++i, phi += angle_shift)
  1951. {
  1952. coords[i].x = x + rx * (1 - cosf(phi));
  1953. coords[i].y = y + h - ry * (1 + sinf(phi));
  1954. }
  1955. coords[num_coords] = coords[0];
  1956. polygon(mode, coords, num_coords + 1);
  1957. }
  1958. void Graphics::rectangle(DrawMode mode, float x, float y, float w, float h, float rx, float ry)
  1959. {
  1960. int points = calculateEllipsePoints(std::min(rx, std::abs(w/2)), std::min(ry, std::abs(h/2)));
  1961. rectangle(mode, x, y, w, h, rx, ry, points);
  1962. }
  1963. void Graphics::circle(DrawMode mode, float x, float y, float radius, int points)
  1964. {
  1965. ellipse(mode, x, y, radius, radius, points);
  1966. }
  1967. void Graphics::circle(DrawMode mode, float x, float y, float radius)
  1968. {
  1969. ellipse(mode, x, y, radius, radius);
  1970. }
  1971. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b, int points)
  1972. {
  1973. float two_pi = (float) (LOVE_M_PI * 2);
  1974. if (points <= 0) points = 1;
  1975. float angle_shift = (two_pi / points);
  1976. float phi = .0f;
  1977. // 1 extra point at the end for a closed loop, and 1 extra point at the
  1978. // start in filled mode for the vertex in the center of the ellipse.
  1979. int extrapoints = 1 + (mode == DRAW_FILL ? 1 : 0);
  1980. Vector2 *polygoncoords = getScratchBuffer<Vector2>(points + extrapoints);
  1981. Vector2 *coords = polygoncoords;
  1982. if (mode == DRAW_FILL)
  1983. {
  1984. coords[0].x = x;
  1985. coords[0].y = y;
  1986. coords++;
  1987. }
  1988. for (int i = 0; i < points; ++i, phi += angle_shift)
  1989. {
  1990. coords[i].x = x + a * cosf(phi);
  1991. coords[i].y = y + b * sinf(phi);
  1992. }
  1993. coords[points] = coords[0];
  1994. // Last argument to polygon(): don't skip the last vertex in fill mode.
  1995. polygon(mode, polygoncoords, points + extrapoints, false);
  1996. }
  1997. void Graphics::ellipse(DrawMode mode, float x, float y, float a, float b)
  1998. {
  1999. ellipse(mode, x, y, a, b, calculateEllipsePoints(a, b));
  2000. }
  2001. void Graphics::arc(DrawMode drawmode, ArcMode arcmode, float x, float y, float radius, float angle1, float angle2, int points)
  2002. {
  2003. // Nothing to display with no points or equal angles. (Or is there with line mode?)
  2004. if (points <= 0 || angle1 == angle2)
  2005. return;
  2006. // Oh, you want to draw a circle?
  2007. if (fabs(angle1 - angle2) >= 2.0f * (float) LOVE_M_PI)
  2008. {
  2009. circle(drawmode, x, y, radius, points);
  2010. return;
  2011. }
  2012. float angle_shift = (angle2 - angle1) / points;
  2013. // Bail on precision issues.
  2014. if (angle_shift == 0.0)
  2015. return;
  2016. // Prevent the connecting line from being drawn if a closed line arc has a
  2017. // small angle. Avoids some visual issues when connected lines are at sharp
  2018. // angles, due to the miter line join drawing code.
  2019. if (drawmode == DRAW_LINE && arcmode == ARC_CLOSED && fabsf(angle1 - angle2) < LOVE_TORAD(4))
  2020. arcmode = ARC_OPEN;
  2021. // Quick fix for the last part of a filled open arc not being drawn (because
  2022. // polygon(DRAW_FILL, ...) doesn't work without a closed loop of vertices.)
  2023. if (drawmode == DRAW_FILL && arcmode == ARC_OPEN)
  2024. arcmode = ARC_CLOSED;
  2025. float phi = angle1;
  2026. Vector2 *coords = nullptr;
  2027. int num_coords = 0;
  2028. const auto createPoints = [&](Vector2 *coordinates)
  2029. {
  2030. for (int i = 0; i <= points; ++i, phi += angle_shift)
  2031. {
  2032. coordinates[i].x = x + radius * cosf(phi);
  2033. coordinates[i].y = y + radius * sinf(phi);
  2034. }
  2035. };
  2036. if (arcmode == ARC_PIE)
  2037. {
  2038. num_coords = points + 3;
  2039. coords = getScratchBuffer<Vector2>(num_coords);
  2040. coords[0] = coords[num_coords - 1] = Vector2(x, y);
  2041. createPoints(coords + 1);
  2042. }
  2043. else if (arcmode == ARC_OPEN)
  2044. {
  2045. num_coords = points + 1;
  2046. coords = getScratchBuffer<Vector2>(num_coords);
  2047. createPoints(coords);
  2048. }
  2049. else // ARC_CLOSED
  2050. {
  2051. num_coords = points + 2;
  2052. coords = getScratchBuffer<Vector2>(num_coords);
  2053. createPoints(coords);
  2054. // Connect the ends of the arc.
  2055. coords[num_coords - 1] = coords[0];
  2056. }
  2057. polygon(drawmode, coords, num_coords);
  2058. }
  2059. void Graphics::arc(DrawMode drawmode, ArcMode arcmode, float x, float y, float radius, float angle1, float angle2)
  2060. {
  2061. float points = (float) calculateEllipsePoints(radius, radius);
  2062. // The amount of points is based on the fraction of the circle created by the arc.
  2063. float angle = fabsf(angle1 - angle2);
  2064. if (angle < 2.0f * (float) LOVE_M_PI)
  2065. points *= angle / (2.0f * (float) LOVE_M_PI);
  2066. arc(drawmode, arcmode, x, y, radius, angle1, angle2, (int) (points + 0.5f));
  2067. }
  2068. void Graphics::polygon(DrawMode mode, const Vector2 *coords, size_t count, bool skipLastFilledVertex)
  2069. {
  2070. // coords is an array of a closed loop of vertices, i.e.
  2071. // coords[count-1] == coords[0]
  2072. if (mode == DRAW_LINE)
  2073. {
  2074. polyline(coords, count);
  2075. }
  2076. else
  2077. {
  2078. const Matrix4 &t = getTransform();
  2079. bool is2D = t.isAffine2DTransform();
  2080. BatchedDrawCommand cmd;
  2081. cmd.formats[0] = getSinglePositionFormat(is2D);
  2082. cmd.formats[1] = CommonFormat::STf_RGBAub;
  2083. cmd.indexMode = TRIANGLEINDEX_FAN;
  2084. cmd.vertexCount = (int)count - (skipLastFilledVertex ? 1 : 0);
  2085. BatchedVertexData data = requestBatchedDraw(cmd);
  2086. // Compute texture coordinates.
  2087. constexpr float inf = std::numeric_limits<float>::infinity();
  2088. Vector2 mincoord(inf, inf);
  2089. Vector2 maxcoord(-inf, -inf);
  2090. for (int i = 0; i < cmd.vertexCount; i++)
  2091. {
  2092. Vector2 v = coords[i];
  2093. mincoord.x = std::min(mincoord.x, v.x);
  2094. mincoord.y = std::min(mincoord.y, v.y);
  2095. maxcoord.x = std::max(maxcoord.x, v.x);
  2096. maxcoord.y = std::max(maxcoord.y, v.y);
  2097. }
  2098. Vector2 invsize(1.0f / (maxcoord.x - mincoord.x), 1.0f / (maxcoord.y - mincoord.y));
  2099. Vector2 start(mincoord.x * invsize.x, mincoord.y * invsize.y);
  2100. Color32 c = toColor32(getColor());
  2101. STf_RGBAub *attributes = (STf_RGBAub *) data.stream[1];
  2102. for (int i = 0; i < cmd.vertexCount; i++)
  2103. {
  2104. attributes[i].s = coords[i].x * invsize.x - start.x;
  2105. attributes[i].t = coords[i].y * invsize.y - start.y;
  2106. attributes[i].color = c;
  2107. }
  2108. if (is2D)
  2109. t.transformXY((Vector2*)data.stream[0], coords, cmd.vertexCount);
  2110. else
  2111. t.transformXY0((Vector3*)data.stream[0], coords, cmd.vertexCount);
  2112. }
  2113. }
  2114. const Graphics::Capabilities &Graphics::getCapabilities() const
  2115. {
  2116. return capabilities;
  2117. }
  2118. PixelFormat Graphics::getSizedFormat(PixelFormat format) const
  2119. {
  2120. switch (format)
  2121. {
  2122. case PIXELFORMAT_NORMAL:
  2123. if (isGammaCorrect())
  2124. return PIXELFORMAT_RGBA8_sRGB;
  2125. else
  2126. return PIXELFORMAT_RGBA8_UNORM;
  2127. case PIXELFORMAT_HDR:
  2128. return PIXELFORMAT_RGBA16_FLOAT;
  2129. default:
  2130. return format;
  2131. }
  2132. }
  2133. Graphics::Stats Graphics::getStats() const
  2134. {
  2135. Stats stats;
  2136. getAPIStats(stats.shaderSwitches);
  2137. stats.drawCalls = drawCalls;
  2138. if (batchedDrawState.vertexCount > 0)
  2139. stats.drawCalls++;
  2140. stats.renderTargetSwitches = renderTargetSwitchCount;
  2141. stats.drawCallsBatched = drawCallsBatched;
  2142. stats.textures = Texture::textureCount;
  2143. stats.fonts = Font::fontCount;
  2144. stats.buffers = Buffer::bufferCount;
  2145. stats.textureMemory = Texture::totalGraphicsMemory;
  2146. stats.bufferMemory = Buffer::totalGraphicsMemory;
  2147. return stats;
  2148. }
  2149. size_t Graphics::getStackDepth() const
  2150. {
  2151. return stackTypeStack.size();
  2152. }
  2153. void Graphics::push(StackType type)
  2154. {
  2155. if (stackTypeStack.size() == MAX_USER_STACK_DEPTH)
  2156. throw Exception("Maximum stack depth reached (more pushes than pops?)");
  2157. pushTransform();
  2158. pixelScaleStack.push_back(pixelScaleStack.back());
  2159. if (type == STACK_ALL)
  2160. states.push_back(states.back());
  2161. stackTypeStack.push_back(type);
  2162. }
  2163. void Graphics::pop()
  2164. {
  2165. if (stackTypeStack.size() < 1)
  2166. throw Exception("Minimum stack depth reached (more pops than pushes?)");
  2167. popTransform();
  2168. pixelScaleStack.pop_back();
  2169. if (stackTypeStack.back() == STACK_ALL)
  2170. {
  2171. DisplayState &newstate = states[states.size() - 2];
  2172. restoreStateChecked(newstate);
  2173. // The last two states in the stack should be equal now.
  2174. states.pop_back();
  2175. }
  2176. stackTypeStack.pop_back();
  2177. }
  2178. /**
  2179. * Transform and stack functions.
  2180. **/
  2181. const Matrix4 &Graphics::getTransform() const
  2182. {
  2183. return transformStack.back();
  2184. }
  2185. const Matrix4 &Graphics::getDeviceProjection() const
  2186. {
  2187. return deviceProjectionMatrix;
  2188. }
  2189. void Graphics::pushTransform()
  2190. {
  2191. transformStack.push_back(transformStack.back());
  2192. }
  2193. void Graphics::pushIdentityTransform()
  2194. {
  2195. transformStack.push_back(Matrix4());
  2196. }
  2197. void Graphics::popTransform()
  2198. {
  2199. transformStack.pop_back();
  2200. }
  2201. void Graphics::rotate(float r)
  2202. {
  2203. transformStack.back().rotate(r);
  2204. }
  2205. void Graphics::scale(float x, float y)
  2206. {
  2207. transformStack.back().scale(x, y);
  2208. pixelScaleStack.back() *= (fabs(x) + fabs(y)) / 2.0;
  2209. }
  2210. void Graphics::translate(float x, float y)
  2211. {
  2212. transformStack.back().translate(x, y);
  2213. }
  2214. void Graphics::shear(float kx, float ky)
  2215. {
  2216. transformStack.back().shear(kx, ky);
  2217. }
  2218. void Graphics::origin()
  2219. {
  2220. transformStack.back().setIdentity();
  2221. pixelScaleStack.back() = 1;
  2222. }
  2223. void Graphics::applyTransform(const Matrix4 &m)
  2224. {
  2225. Matrix4 &current = transformStack.back();
  2226. current *= m;
  2227. float sx, sy;
  2228. current.getApproximateScale(sx, sy);
  2229. pixelScaleStack.back() = (sx + sy) / 2.0;
  2230. }
  2231. void Graphics::replaceTransform(const Matrix4 &m)
  2232. {
  2233. transformStack.back() = m;
  2234. float sx, sy;
  2235. m.getApproximateScale(sx, sy);
  2236. pixelScaleStack.back() = (sx + sy) / 2.0;
  2237. }
  2238. Vector2 Graphics::transformPoint(Vector2 point)
  2239. {
  2240. Vector2 p;
  2241. transformStack.back().transformXY(&p, &point, 1);
  2242. return p;
  2243. }
  2244. Vector2 Graphics::inverseTransformPoint(Vector2 point)
  2245. {
  2246. Vector2 p;
  2247. // TODO: We should probably cache the inverse transform so we don't have to
  2248. // re-calculate it every time this is called.
  2249. transformStack.back().inverse().transformXY(&p, &point, 1);
  2250. return p;
  2251. }
  2252. void Graphics::setProjection(const Matrix4 &m)
  2253. {
  2254. flushBatchedDraws();
  2255. auto &state = states.back();
  2256. state.useCustomProjection = true;
  2257. state.customProjection = m;
  2258. updateDeviceProjection(m);
  2259. }
  2260. void Graphics::resetProjection()
  2261. {
  2262. flushBatchedDraws();
  2263. auto &state = states.back();
  2264. int w = getWidth();
  2265. int h = getHeight();
  2266. const auto &rt = state.renderTargets.getFirstTarget();
  2267. if (rt.texture.get())
  2268. {
  2269. w = rt.texture->getWidth(rt.mipmap);
  2270. h = rt.texture->getHeight(rt.mipmap);
  2271. }
  2272. state.useCustomProjection = false;
  2273. // NDC is y-up. The ortho() parameter names assume that as well. We want
  2274. // a y-down projection, so we set bottom to h and top to 0.
  2275. updateDeviceProjection(Matrix4::ortho(0.0f, w, h, 0.0f, -10.0f, 10.0f));
  2276. }
  2277. void Graphics::updateDeviceProjection(const Matrix4 &projection)
  2278. {
  2279. deviceProjectionMatrix = projection;
  2280. }
  2281. STRINGMAP_CLASS_BEGIN(Graphics, Graphics::DrawMode, Graphics::DRAW_MAX_ENUM, drawMode)
  2282. {
  2283. { "line", Graphics::DRAW_LINE },
  2284. { "fill", Graphics::DRAW_FILL },
  2285. }
  2286. STRINGMAP_CLASS_END(Graphics, Graphics::DrawMode, Graphics::DRAW_MAX_ENUM, drawMode)
  2287. STRINGMAP_CLASS_BEGIN(Graphics, Graphics::ArcMode, Graphics::ARC_MAX_ENUM, arcMode)
  2288. {
  2289. { "open", Graphics::ARC_OPEN },
  2290. { "closed", Graphics::ARC_CLOSED },
  2291. { "pie", Graphics::ARC_PIE },
  2292. }
  2293. STRINGMAP_CLASS_END(Graphics, Graphics::ArcMode, Graphics::ARC_MAX_ENUM, arcMode)
  2294. STRINGMAP_CLASS_BEGIN(Graphics, Graphics::LineStyle, Graphics::LINE_MAX_ENUM, lineStyle)
  2295. {
  2296. { "smooth", Graphics::LINE_SMOOTH },
  2297. { "rough", Graphics::LINE_ROUGH }
  2298. }
  2299. STRINGMAP_CLASS_END(Graphics, Graphics::LineStyle, Graphics::LINE_MAX_ENUM, lineStyle)
  2300. STRINGMAP_CLASS_BEGIN(Graphics, Graphics::LineJoin, Graphics::LINE_JOIN_MAX_ENUM, lineJoin)
  2301. {
  2302. { "none", Graphics::LINE_JOIN_NONE },
  2303. { "miter", Graphics::LINE_JOIN_MITER },
  2304. { "bevel", Graphics::LINE_JOIN_BEVEL }
  2305. }
  2306. STRINGMAP_CLASS_END(Graphics, Graphics::LineJoin, Graphics::LINE_JOIN_MAX_ENUM, lineJoin)
  2307. STRINGMAP_CLASS_BEGIN(Graphics, Graphics::Feature, Graphics::FEATURE_MAX_ENUM, feature)
  2308. {
  2309. { "multicanvasformats", Graphics::FEATURE_MULTI_RENDER_TARGET_FORMATS },
  2310. { "clampzero", Graphics::FEATURE_CLAMP_ZERO },
  2311. { "clampone", Graphics::FEATURE_CLAMP_ONE },
  2312. { "lighten", Graphics::FEATURE_LIGHTEN },
  2313. { "fullnpot", Graphics::FEATURE_FULL_NPOT },
  2314. { "pixelshaderhighp", Graphics::FEATURE_PIXEL_SHADER_HIGHP },
  2315. { "shaderderivatives", Graphics::FEATURE_SHADER_DERIVATIVES },
  2316. { "glsl3", Graphics::FEATURE_GLSL3 },
  2317. { "glsl4", Graphics::FEATURE_GLSL4 },
  2318. { "instancing", Graphics::FEATURE_INSTANCING },
  2319. { "texelbuffer", Graphics::FEATURE_TEXEL_BUFFER },
  2320. { "copytexturetobuffer", Graphics::FEATURE_COPY_TEXTURE_TO_BUFFER },
  2321. { "indirectdraw", Graphics::FEATURE_INDIRECT_DRAW },
  2322. }
  2323. STRINGMAP_CLASS_END(Graphics, Graphics::Feature, Graphics::FEATURE_MAX_ENUM, feature)
  2324. STRINGMAP_CLASS_BEGIN(Graphics, Graphics::SystemLimit, Graphics::LIMIT_MAX_ENUM, systemLimit)
  2325. {
  2326. { "pointsize", Graphics::LIMIT_POINT_SIZE },
  2327. { "texturesize", Graphics::LIMIT_TEXTURE_SIZE },
  2328. { "texturelayers", Graphics::LIMIT_TEXTURE_LAYERS },
  2329. { "volumetexturesize", Graphics::LIMIT_VOLUME_TEXTURE_SIZE },
  2330. { "cubetexturesize", Graphics::LIMIT_CUBE_TEXTURE_SIZE },
  2331. { "texelbuffersize", Graphics::LIMIT_TEXEL_BUFFER_SIZE },
  2332. { "shaderstoragebuffersize", Graphics::LIMIT_SHADER_STORAGE_BUFFER_SIZE },
  2333. { "threadgroupsx", Graphics::LIMIT_THREADGROUPS_X },
  2334. { "threadgroupsy", Graphics::LIMIT_THREADGROUPS_Y },
  2335. { "threadgroupsz", Graphics::LIMIT_THREADGROUPS_Z },
  2336. { "multicanvas", Graphics::LIMIT_RENDER_TARGETS },
  2337. { "texturemsaa", Graphics::LIMIT_TEXTURE_MSAA },
  2338. { "anisotropy", Graphics::LIMIT_ANISOTROPY },
  2339. }
  2340. STRINGMAP_CLASS_END(Graphics, Graphics::SystemLimit, Graphics::LIMIT_MAX_ENUM, systemLimit)
  2341. STRINGMAP_CLASS_BEGIN(Graphics, Graphics::StackType, Graphics::STACK_MAX_ENUM, stackType)
  2342. {
  2343. { "all", Graphics::STACK_ALL },
  2344. { "transform", Graphics::STACK_TRANSFORM },
  2345. }
  2346. STRINGMAP_CLASS_END(Graphics, Graphics::StackType, Graphics::STACK_MAX_ENUM, stackType)
  2347. STRINGMAP_BEGIN(Renderer, RENDERER_MAX_ENUM, renderer)
  2348. {
  2349. { "opengl", RENDERER_OPENGL },
  2350. { "vulkan", RENDERER_VULKAN },
  2351. { "metal", RENDERER_METAL },
  2352. }
  2353. STRINGMAP_END(Renderer, RENDERER_MAX_ENUM, renderer)
  2354. } // graphics
  2355. } // love