Graphics.cpp 81 KB

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