wrap_Graphics.cpp 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726
  1. /**
  2. * Copyright (c) 2006-2021 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "common/config.h"
  21. #include "wrap_Graphics.h"
  22. #include "Texture.h"
  23. #include "image/ImageData.h"
  24. #include "image/Image.h"
  25. #include "font/Rasterizer.h"
  26. #include "filesystem/Filesystem.h"
  27. #include "filesystem/wrap_Filesystem.h"
  28. #include "video/VideoStream.h"
  29. #include "image/wrap_Image.h"
  30. #include "common/Reference.h"
  31. #include "math/wrap_Transform.h"
  32. #include "thread/wrap_Channel.h"
  33. #include "opengl/Graphics.h"
  34. #include <cassert>
  35. #include <cstring>
  36. #include <cstdlib>
  37. #include <sstream>
  38. #include <algorithm>
  39. // Shove the wrap_Graphics.lua code directly into a raw string literal.
  40. static const char graphics_lua[] =
  41. #include "wrap_Graphics.lua"
  42. ;
  43. namespace love
  44. {
  45. namespace graphics
  46. {
  47. #define instance() (Module::getInstance<Graphics>(Module::M_GRAPHICS))
  48. static int luax_checkgraphicscreated(lua_State *L)
  49. {
  50. if (!instance()->isCreated())
  51. return luaL_error(L, "love.graphics cannot function without a window!");
  52. return 0;
  53. }
  54. int w_reset(lua_State *)
  55. {
  56. instance()->reset();
  57. return 0;
  58. }
  59. int w_clear(lua_State *L)
  60. {
  61. OptionalColorD color(ColorD(0.0, 0.0, 0.0, 0.0));
  62. std::vector<OptionalColorD> colors;
  63. OptionalInt stencil(0);
  64. OptionalDouble depth(1.0);
  65. int argtype = lua_type(L, 1);
  66. int startidx = -1;
  67. if (argtype == LUA_TTABLE)
  68. {
  69. int maxn = lua_gettop(L);
  70. colors.reserve(maxn);
  71. for (int i = 0; i < maxn; i++)
  72. {
  73. argtype = lua_type(L, i + 1);
  74. if (argtype == LUA_TNUMBER || argtype == LUA_TBOOLEAN)
  75. {
  76. startidx = i + 1;
  77. break;
  78. }
  79. else if (argtype == LUA_TNIL || argtype == LUA_TNONE || luax_objlen(L, i + 1) == 0)
  80. {
  81. colors.push_back(OptionalColorD());
  82. continue;
  83. }
  84. for (int j = 1; j <= 4; j++)
  85. lua_rawgeti(L, i + 1, j);
  86. OptionalColorD c;
  87. c.hasValue = true;
  88. c.value.r = luaL_checknumber(L, -4);
  89. c.value.g = luaL_checknumber(L, -3);
  90. c.value.b = luaL_checknumber(L, -2);
  91. c.value.a = luaL_optnumber(L, -1, 1.0);
  92. colors.push_back(c);
  93. lua_pop(L, 4);
  94. }
  95. }
  96. else if (argtype == LUA_TBOOLEAN)
  97. {
  98. color.hasValue = luax_toboolean(L, 1);
  99. startidx = 2;
  100. }
  101. else if (argtype != LUA_TNONE && argtype != LUA_TNIL)
  102. {
  103. color.hasValue = true;
  104. color.value.r = (float) luaL_checknumber(L, 1);
  105. color.value.g = (float) luaL_checknumber(L, 2);
  106. color.value.b = (float) luaL_checknumber(L, 3);
  107. color.value.a = (float) luaL_optnumber(L, 4, 1.0);
  108. startidx = 5;
  109. }
  110. if (startidx >= 0)
  111. {
  112. argtype = lua_type(L, startidx);
  113. if (argtype == LUA_TBOOLEAN)
  114. stencil.hasValue = luax_toboolean(L, startidx);
  115. else if (argtype == LUA_TNUMBER)
  116. stencil.value = (int) luaL_checkinteger(L, startidx);
  117. argtype = lua_type(L, startidx + 1);
  118. if (argtype == LUA_TBOOLEAN)
  119. depth.hasValue = luax_toboolean(L, startidx + 1);
  120. else if (argtype == LUA_TNUMBER)
  121. depth.value = luaL_checknumber(L, startidx + 1);
  122. }
  123. if (colors.empty())
  124. luax_catchexcept(L, [&]() { instance()->clear(color, stencil, depth); });
  125. else
  126. luax_catchexcept(L, [&]() { instance()->clear(colors, stencil, depth); });
  127. return 0;
  128. }
  129. int w_discard(lua_State *L)
  130. {
  131. std::vector<bool> colorbuffers;
  132. if (lua_istable(L, 1))
  133. {
  134. for (size_t i = 1; i <= luax_objlen(L, 1); i++)
  135. {
  136. lua_rawgeti(L, 1, i);
  137. colorbuffers.push_back(luax_optboolean(L, -1, true));
  138. lua_pop(L, 1);
  139. }
  140. }
  141. else
  142. {
  143. bool discardcolor = luax_optboolean(L, 1, true);
  144. size_t numbuffers = std::max((size_t) 1, instance()->getRenderTargets().colors.size());
  145. colorbuffers = std::vector<bool>(numbuffers, discardcolor);
  146. }
  147. bool depthstencil = luax_optboolean(L, 2, true);
  148. instance()->discard(colorbuffers, depthstencil);
  149. return 0;
  150. }
  151. int w_present(lua_State *L)
  152. {
  153. luax_catchexcept(L, [&]() { instance()->present(L); });
  154. return 0;
  155. }
  156. int w_isCreated(lua_State *L)
  157. {
  158. luax_pushboolean(L, instance()->isCreated());
  159. return 1;
  160. }
  161. int w_isActive(lua_State *L)
  162. {
  163. luax_pushboolean(L, instance()->isActive());
  164. return 1;
  165. }
  166. int w_isGammaCorrect(lua_State *L)
  167. {
  168. luax_pushboolean(L, graphics::isGammaCorrect());
  169. return 1;
  170. }
  171. int w_getWidth(lua_State *L)
  172. {
  173. lua_pushinteger(L, instance()->getWidth());
  174. return 1;
  175. }
  176. int w_getHeight(lua_State *L)
  177. {
  178. lua_pushinteger(L, instance()->getHeight());
  179. return 1;
  180. }
  181. int w_getDimensions(lua_State *L)
  182. {
  183. lua_pushinteger(L, instance()->getWidth());
  184. lua_pushinteger(L, instance()->getHeight());
  185. return 2;
  186. }
  187. int w_getPixelWidth(lua_State *L)
  188. {
  189. lua_pushinteger(L, instance()->getPixelWidth());
  190. return 1;
  191. }
  192. int w_getPixelHeight(lua_State *L)
  193. {
  194. lua_pushinteger(L, instance()->getPixelHeight());
  195. return 1;
  196. }
  197. int w_getPixelDimensions(lua_State *L)
  198. {
  199. lua_pushinteger(L, instance()->getPixelWidth());
  200. lua_pushinteger(L, instance()->getPixelHeight());
  201. return 2;
  202. }
  203. int w_getDPIScale(lua_State *L)
  204. {
  205. lua_pushnumber(L, instance()->getScreenDPIScale());
  206. return 1;
  207. }
  208. static Graphics::RenderTarget checkRenderTarget(lua_State *L, int idx)
  209. {
  210. lua_rawgeti(L, idx, 1);
  211. Graphics::RenderTarget target(luax_checktexture(L, -1), 0);
  212. lua_pop(L, 1);
  213. TextureType type = target.texture->getTextureType();
  214. if (type == TEXTURE_2D_ARRAY || type == TEXTURE_VOLUME)
  215. target.slice = luax_checkintflag(L, idx, "layer") - 1;
  216. else if (type == TEXTURE_CUBE)
  217. target.slice = luax_checkintflag(L, idx, "face") - 1;
  218. target.mipmap = luax_intflag(L, idx, "mipmap", 1) - 1;
  219. return target;
  220. }
  221. int w_setCanvas(lua_State *L)
  222. {
  223. // Disable stencil writes.
  224. luax_catchexcept(L, [](){ instance()->stopDrawToStencilBuffer(); });
  225. // called with none -> reset to default buffer
  226. if (lua_isnoneornil(L, 1))
  227. {
  228. instance()->setRenderTarget();
  229. return 0;
  230. }
  231. bool is_table = lua_istable(L, 1);
  232. Graphics::RenderTargets targets;
  233. if (is_table)
  234. {
  235. lua_rawgeti(L, 1, 1);
  236. bool table_of_tables = lua_istable(L, -1);
  237. lua_pop(L, 1);
  238. for (int i = 1; i <= (int) luax_objlen(L, 1); i++)
  239. {
  240. lua_rawgeti(L, 1, i);
  241. if (table_of_tables)
  242. targets.colors.push_back(checkRenderTarget(L, -1));
  243. else
  244. {
  245. targets.colors.emplace_back(luax_checktexture(L, -1), 0);
  246. if (targets.colors.back().texture->getTextureType() != TEXTURE_2D)
  247. return luaL_error(L, "Non-2D textures must use the table-of-tables variant of setCanvas.");
  248. }
  249. lua_pop(L, 1);
  250. }
  251. uint32 tempdepthflag = Graphics::TEMPORARY_RT_DEPTH;
  252. uint32 tempstencilflag = Graphics::TEMPORARY_RT_STENCIL;
  253. lua_getfield(L, 1, "depthstencil");
  254. int dstype = lua_type(L, -1);
  255. if (dstype == LUA_TTABLE)
  256. targets.depthStencil = checkRenderTarget(L, -1);
  257. else if (dstype == LUA_TBOOLEAN)
  258. targets.temporaryRTFlags |= luax_toboolean(L, -1) ? (tempdepthflag | tempstencilflag) : 0;
  259. else if (dstype != LUA_TNONE && dstype != LUA_TNIL)
  260. targets.depthStencil.texture = luax_checktexture(L, -1);
  261. lua_pop(L, 1);
  262. if (targets.depthStencil.texture == nullptr && (targets.temporaryRTFlags & tempdepthflag) == 0)
  263. targets.temporaryRTFlags |= luax_boolflag(L, 1, "depth", false) ? tempdepthflag : 0;
  264. if (targets.depthStencil.texture == nullptr && (targets.temporaryRTFlags & tempstencilflag) == 0)
  265. targets.temporaryRTFlags |= luax_boolflag(L, 1, "stencil", false) ? tempstencilflag : 0;
  266. }
  267. else
  268. {
  269. for (int i = 1; i <= lua_gettop(L); i++)
  270. {
  271. Graphics::RenderTarget target(luax_checktexture(L, i), 0);
  272. TextureType type = target.texture->getTextureType();
  273. if (i == 1 && type != TEXTURE_2D)
  274. {
  275. target.slice = (int) luaL_checkinteger(L, i + 1) - 1;
  276. target.mipmap = (int) luaL_optinteger(L, i + 2, 1) - 1;
  277. targets.colors.push_back(target);
  278. break;
  279. }
  280. else if (type == TEXTURE_2D && lua_isnumber(L, i + 1))
  281. {
  282. target.mipmap = (int) luaL_optinteger(L, i + 1, 1) - 1;
  283. i++;
  284. }
  285. if (i > 1 && type != TEXTURE_2D)
  286. return luaL_error(L, "This variant of setCanvas only supports 2D texture types.");
  287. targets.colors.push_back(target);
  288. }
  289. }
  290. luax_catchexcept(L, [&]() {
  291. if (targets.getFirstTarget().texture != nullptr)
  292. instance()->setRenderTargets(targets);
  293. else
  294. instance()->setRenderTarget();
  295. });
  296. return 0;
  297. }
  298. static void pushRenderTarget(lua_State *L, const Graphics::RenderTarget &rt)
  299. {
  300. lua_createtable(L, 1, 2);
  301. luax_pushtype(L, rt.texture);
  302. lua_rawseti(L, -2, 1);
  303. TextureType type = rt.texture->getTextureType();
  304. if (type == TEXTURE_2D_ARRAY || type == TEXTURE_VOLUME)
  305. {
  306. lua_pushnumber(L, rt.slice + 1);
  307. lua_setfield(L, -2, "layer");
  308. }
  309. else if (type == TEXTURE_CUBE)
  310. {
  311. lua_pushnumber(L, rt.slice + 1);
  312. lua_setfield(L, -2, "face");
  313. }
  314. lua_pushnumber(L, rt.mipmap + 1);
  315. lua_setfield(L, -2, "mipmap");
  316. }
  317. int w_getCanvas(lua_State *L)
  318. {
  319. Graphics::RenderTargets targets = instance()->getRenderTargets();
  320. int ntargets = (int) targets.colors.size();
  321. if (ntargets == 0)
  322. {
  323. lua_pushnil(L);
  324. return 1;
  325. }
  326. bool shouldUseTablesVariant = targets.depthStencil.texture != nullptr;
  327. if (!shouldUseTablesVariant)
  328. {
  329. for (const auto &rt : targets.colors)
  330. {
  331. if (rt.mipmap != 0 || rt.texture->getTextureType() != TEXTURE_2D)
  332. {
  333. shouldUseTablesVariant = true;
  334. break;
  335. }
  336. }
  337. }
  338. if (shouldUseTablesVariant)
  339. {
  340. lua_createtable(L, ntargets, 0);
  341. for (int i = 0; i < ntargets; i++)
  342. {
  343. pushRenderTarget(L, targets.colors[i]);
  344. lua_rawseti(L, -2, i + 1);
  345. }
  346. if (targets.depthStencil.texture != nullptr)
  347. {
  348. pushRenderTarget(L, targets.depthStencil);
  349. lua_setfield(L, -2, "depthstencil");
  350. }
  351. return 1;
  352. }
  353. else
  354. {
  355. for (const auto &rt : targets.colors)
  356. luax_pushtype(L, rt.texture);
  357. return ntargets;
  358. }
  359. }
  360. static void screenshotFunctionCallback(const Graphics::ScreenshotInfo *info, love::image::ImageData *i, void *gd)
  361. {
  362. if (info == nullptr)
  363. return;
  364. lua_State *L = (lua_State *) gd;
  365. Reference *ref = (Reference *) info->data;
  366. if (i != nullptr && L != nullptr)
  367. {
  368. if (ref == nullptr)
  369. luaL_error(L, "Internal error in screenshot callback.");
  370. ref->push(L);
  371. delete ref;
  372. luax_pushtype(L, i);
  373. lua_call(L, 1, 0);
  374. }
  375. else
  376. delete ref;
  377. }
  378. struct ScreenshotFileInfo
  379. {
  380. std::string filename;
  381. image::FormatHandler::EncodedFormat format;
  382. };
  383. static void screenshotFileCallback(const Graphics::ScreenshotInfo *info, love::image::ImageData *i, void * /*gd*/)
  384. {
  385. if (info == nullptr)
  386. return;
  387. ScreenshotFileInfo *fileinfo = (ScreenshotFileInfo *) info->data;
  388. if (i != nullptr && fileinfo != nullptr)
  389. {
  390. try
  391. {
  392. i->encode(fileinfo->format, fileinfo->filename.c_str(), true);
  393. }
  394. catch (love::Exception &e)
  395. {
  396. printf("Screenshot encoding or saving failed: %s", e.what());
  397. // Do nothing...
  398. }
  399. }
  400. delete fileinfo;
  401. }
  402. static void screenshotChannelCallback(const Graphics::ScreenshotInfo *info, love::image::ImageData *i, void * /*gd*/)
  403. {
  404. if (info == nullptr)
  405. return;
  406. auto *channel = (love::thread::Channel *) info->data;
  407. if (channel != nullptr)
  408. {
  409. if (i != nullptr)
  410. channel->push(Variant(&love::image::ImageData::type, i));
  411. channel->release();
  412. }
  413. }
  414. int w_captureScreenshot(lua_State *L)
  415. {
  416. Graphics::ScreenshotInfo info;
  417. if (lua_isfunction(L, 1))
  418. {
  419. lua_pushvalue(L, 1);
  420. info.data = luax_refif(L, LUA_TFUNCTION);
  421. lua_pop(L, 1);
  422. info.callback = screenshotFunctionCallback;
  423. }
  424. else if (lua_isstring(L, 1))
  425. {
  426. std::string filename = luax_checkstring(L, 1);
  427. std::string ext;
  428. size_t dotpos = filename.rfind('.');
  429. if (dotpos != std::string::npos)
  430. ext = filename.substr(dotpos + 1);
  431. std::transform(ext.begin(), ext.end(), ext.begin(), tolower);
  432. image::FormatHandler::EncodedFormat format;
  433. if (!image::ImageData::getConstant(ext.c_str(), format))
  434. return luax_enumerror(L, "encoded image format", image::ImageData::getConstants(format), ext.c_str());
  435. ScreenshotFileInfo *fileinfo = new ScreenshotFileInfo;
  436. fileinfo->filename = filename;
  437. fileinfo->format = format;
  438. info.data = fileinfo;
  439. info.callback = screenshotFileCallback;
  440. }
  441. else if (luax_istype(L, 1, love::thread::Channel::type))
  442. {
  443. auto *channel = love::thread::luax_checkchannel(L, 1);
  444. channel->retain();
  445. info.data = channel;
  446. info.callback = screenshotChannelCallback;
  447. }
  448. else
  449. return luax_typerror(L, 1, "function, string, or Channel");
  450. luax_catchexcept(L,
  451. [&]() { instance()->captureScreenshot(info); },
  452. [&](bool except) { if (except) info.callback(&info, nullptr, nullptr); }
  453. );
  454. return 0;
  455. }
  456. int w_setScissor(lua_State *L)
  457. {
  458. int nargs = lua_gettop(L);
  459. if (nargs == 0 || (nargs == 4 && lua_isnil(L, 1) && lua_isnil(L, 2)
  460. && lua_isnil(L, 3) && lua_isnil(L, 4)))
  461. {
  462. instance()->setScissor();
  463. return 0;
  464. }
  465. Rect rect;
  466. rect.x = (int) luaL_checkinteger(L, 1);
  467. rect.y = (int) luaL_checkinteger(L, 2);
  468. rect.w = (int) luaL_checkinteger(L, 3);
  469. rect.h = (int) luaL_checkinteger(L, 4);
  470. if (rect.w < 0 || rect.h < 0)
  471. return luaL_error(L, "Can't set scissor with negative width and/or height.");
  472. instance()->setScissor(rect);
  473. return 0;
  474. }
  475. int w_intersectScissor(lua_State *L)
  476. {
  477. Rect rect;
  478. rect.x = (int) luaL_checkinteger(L, 1);
  479. rect.y = (int) luaL_checkinteger(L, 2);
  480. rect.w = (int) luaL_checkinteger(L, 3);
  481. rect.h = (int) luaL_checkinteger(L, 4);
  482. if (rect.w < 0 || rect.h < 0)
  483. return luaL_error(L, "Can't set scissor with negative width and/or height.");
  484. instance()->intersectScissor(rect);
  485. return 0;
  486. }
  487. int w_getScissor(lua_State *L)
  488. {
  489. Rect rect;
  490. if (!instance()->getScissor(rect))
  491. return 0;
  492. lua_pushinteger(L, rect.x);
  493. lua_pushinteger(L, rect.y);
  494. lua_pushinteger(L, rect.w);
  495. lua_pushinteger(L, rect.h);
  496. return 4;
  497. }
  498. int w_stencil(lua_State *L)
  499. {
  500. luaL_checktype(L, 1, LUA_TFUNCTION);
  501. StencilAction action = STENCIL_REPLACE;
  502. if (!lua_isnoneornil(L, 2))
  503. {
  504. const char *actionstr = luaL_checkstring(L, 2);
  505. if (!getConstant(actionstr, action))
  506. return luax_enumerror(L, "stencil draw action", getConstants(action), actionstr);
  507. }
  508. int stencilvalue = (int) luaL_optinteger(L, 3, 1);
  509. // Fourth argument: whether to keep the contents of the stencil buffer.
  510. OptionalInt stencilclear;
  511. int argtype = lua_type(L, 4);
  512. if (argtype == LUA_TNONE || argtype == LUA_TNIL || (argtype == LUA_TBOOLEAN && luax_toboolean(L, 4) == false))
  513. stencilclear.set(0);
  514. else if (argtype == LUA_TNUMBER)
  515. stencilclear.set((int) luaL_checkinteger(L, 4));
  516. else if (argtype != LUA_TBOOLEAN)
  517. luaL_checktype(L, 4, LUA_TBOOLEAN);
  518. if (stencilclear.hasValue)
  519. instance()->clear(OptionalColorD(), stencilclear, OptionalDouble());
  520. luax_catchexcept(L, [&](){ instance()->drawToStencilBuffer(action, stencilvalue); });
  521. // Call stencilfunc()
  522. lua_pushvalue(L, 1);
  523. lua_call(L, 0, 0);
  524. luax_catchexcept(L, [&](){ instance()->stopDrawToStencilBuffer(); });
  525. return 0;
  526. }
  527. int w_setStencilTest(lua_State *L)
  528. {
  529. // COMPARE_ALWAYS effectively disables stencil testing.
  530. CompareMode compare = COMPARE_ALWAYS;
  531. int comparevalue = 0;
  532. if (!lua_isnoneornil(L, 1))
  533. {
  534. const char *comparestr = luaL_checkstring(L, 1);
  535. if (!getConstant(comparestr, compare))
  536. return luax_enumerror(L, "compare mode", getConstants(compare), comparestr);
  537. comparevalue = (int) luaL_checkinteger(L, 2);
  538. }
  539. luax_catchexcept(L, [&](){ instance()->setStencilTest(compare, comparevalue); });
  540. return 0;
  541. }
  542. int w_getStencilTest(lua_State *L)
  543. {
  544. CompareMode compare = COMPARE_ALWAYS;
  545. int comparevalue = 1;
  546. instance()->getStencilTest(compare, comparevalue);
  547. const char *comparestr;
  548. if (!getConstant(compare, comparestr))
  549. return luaL_error(L, "Unknown compare mode.");
  550. lua_pushstring(L, comparestr);
  551. lua_pushnumber(L, comparevalue);
  552. return 2;
  553. }
  554. static void parseDPIScale(Data *d, float *dpiscale)
  555. {
  556. auto fd = dynamic_cast<love::filesystem::FileData *>(d);
  557. if (fd == nullptr)
  558. return;
  559. // Parse a density scale of 2.0 from "[email protected]".
  560. const std::string &fname = fd->getName();
  561. size_t namelen = fname.length();
  562. size_t atpos = fname.rfind('@');
  563. if (atpos != std::string::npos && atpos + 2 < namelen
  564. && (fname[namelen - 1] == 'x' || fname[namelen - 1] == 'X'))
  565. {
  566. char *end = nullptr;
  567. long density = strtol(fname.c_str() + atpos + 1, &end, 10);
  568. if (end != nullptr && density > 0 && dpiscale != nullptr)
  569. *dpiscale = (float) density;
  570. }
  571. }
  572. static std::pair<StrongRef<image::ImageData>, StrongRef<image::CompressedImageData>>
  573. getImageData(lua_State *L, int idx, bool allowcompressed, float *dpiscale)
  574. {
  575. StrongRef<image::ImageData> idata;
  576. StrongRef<image::CompressedImageData> cdata;
  577. if (luax_istype(L, idx, image::ImageData::type))
  578. idata.set(image::luax_checkimagedata(L, idx));
  579. else if (luax_istype(L, idx, image::CompressedImageData::type))
  580. cdata.set(image::luax_checkcompressedimagedata(L, idx));
  581. else if (filesystem::luax_cangetdata(L, idx))
  582. {
  583. // Convert to ImageData / CompressedImageData.
  584. auto imagemodule = Module::getInstance<image::Image>(Module::M_IMAGE);
  585. if (imagemodule == nullptr)
  586. luaL_error(L, "Cannot load images without the love.image module.");
  587. StrongRef<Data> fdata(filesystem::luax_getdata(L, idx), Acquire::NORETAIN);
  588. if (dpiscale != nullptr)
  589. parseDPIScale(fdata, dpiscale);
  590. if (allowcompressed && imagemodule->isCompressed(fdata))
  591. luax_catchexcept(L, [&]() { cdata.set(imagemodule->newCompressedData(fdata), Acquire::NORETAIN); });
  592. else
  593. luax_catchexcept(L, [&]() { idata.set(imagemodule->newImageData(fdata), Acquire::NORETAIN); });
  594. }
  595. else
  596. idata.set(image::luax_checkimagedata(L, idx));
  597. return std::make_pair(idata, cdata);
  598. }
  599. static int w__pushNewTexture(lua_State *L, Texture::Slices *slices, const Texture::Settings &settings)
  600. {
  601. StrongRef<Texture> i;
  602. luax_catchexcept(L,
  603. [&]() { i.set(instance()->newTexture(settings, slices), Acquire::NORETAIN); },
  604. [&](bool) { if (slices) slices->clear(); }
  605. );
  606. luax_pushtype(L, i);
  607. return 1;
  608. }
  609. static void luax_checktexturesettings(lua_State *L, int idx, bool opt, bool checkType, bool checkDimensions, OptionalBool forceRenderTarget, Texture::Settings &s, bool &setdpiscale)
  610. {
  611. setdpiscale = false;
  612. if (forceRenderTarget.hasValue)
  613. s.renderTarget = forceRenderTarget.value;
  614. if (opt && lua_isnoneornil(L, idx))
  615. return;
  616. luax_checktablefields<Texture::SettingType>(L, idx, "texture setting name", Texture::getConstant);
  617. if (!forceRenderTarget.hasValue)
  618. s.renderTarget = luax_boolflag(L, idx, Texture::getConstant(Texture::SETTING_RENDER_TARGET), s.renderTarget);
  619. lua_getfield(L, idx, Texture::getConstant(Texture::SETTING_FORMAT));
  620. if (!lua_isnoneornil(L, -1))
  621. {
  622. const char *str = luaL_checkstring(L, -1);
  623. if (!getConstant(str, s.format))
  624. luax_enumerror(L, "pixel format", str);
  625. }
  626. lua_pop(L, 1);
  627. if (checkType)
  628. {
  629. lua_getfield(L, idx, Texture::getConstant(Texture::SETTING_TYPE));
  630. if (!lua_isnoneornil(L, -1))
  631. {
  632. const char *str = luaL_checkstring(L, -1);
  633. if (!Texture::getConstant(str, s.type))
  634. luax_enumerror(L, "texture type", Texture::getConstants(s.type), str);
  635. }
  636. lua_pop(L, 1);
  637. }
  638. if (checkDimensions)
  639. {
  640. s.width = luax_checkintflag(L, idx, Texture::getConstant(Texture::SETTING_WIDTH));
  641. s.height = luax_checkintflag(L, idx, Texture::getConstant(Texture::SETTING_HEIGHT));
  642. if (s.type == TEXTURE_2D_ARRAY || s.type == TEXTURE_VOLUME)
  643. s.layers = luax_checkintflag(L, idx, Texture::getConstant(Texture::SETTING_LAYERS));
  644. }
  645. lua_getfield(L, idx, Texture::getConstant(Texture::SETTING_MIPMAPS));
  646. if (!lua_isnoneornil(L, -1))
  647. {
  648. if (lua_type(L, -1) == LUA_TBOOLEAN)
  649. s.mipmaps = luax_toboolean(L, -1) ? Texture::MIPMAPS_MANUAL : Texture::MIPMAPS_NONE;
  650. else
  651. {
  652. const char *str = luaL_checkstring(L, -1);
  653. if (!Texture::getConstant(str, s.mipmaps))
  654. luax_enumerror(L, "Texture mipmap mode", Texture::getConstants(s.mipmaps), str);
  655. }
  656. }
  657. lua_pop(L, 1);
  658. s.linear = luax_boolflag(L, idx, Texture::getConstant(Texture::SETTING_LINEAR), s.linear);
  659. s.msaa = luax_intflag(L, idx, Texture::getConstant(Texture::SETTING_MSAA), s.msaa);
  660. s.computeWrite = luax_boolflag(L, idx, Texture::getConstant(Texture::SETTING_COMPUTE_WRITE), s.computeWrite);
  661. lua_getfield(L, idx, Texture::getConstant(Texture::SETTING_READABLE));
  662. if (!lua_isnoneornil(L, -1))
  663. s.readable.set(luax_checkboolean(L, -1));
  664. lua_pop(L, 1);
  665. lua_getfield(L, idx, Texture::getConstant(Texture::SETTING_DPI_SCALE));
  666. if (lua_isnumber(L, -1))
  667. {
  668. s.dpiScale = (float) lua_tonumber(L, -1);
  669. setdpiscale = true;
  670. }
  671. lua_pop(L, 1);
  672. }
  673. int w_newCanvas(lua_State *L)
  674. {
  675. luax_checkgraphicscreated(L);
  676. Texture::Settings s;
  677. OptionalBool forceRenderTarget(true);
  678. bool setDPIScale = false;
  679. if (lua_istable(L, 1))
  680. {
  681. luax_checktexturesettings(L, 1, false, true, true, forceRenderTarget, s, setDPIScale);
  682. }
  683. else
  684. {
  685. // check if width and height are given. else default to screen dimensions.
  686. s.width = (int) luaL_optinteger(L, 1, instance()->getWidth());
  687. s.height = (int) luaL_optinteger(L, 2, instance()->getHeight());
  688. int startidx = 3;
  689. if (lua_isnumber(L, 3))
  690. {
  691. s.layers = (int) luaL_checkinteger(L, 3);
  692. s.type = TEXTURE_2D_ARRAY;
  693. startidx = 4;
  694. }
  695. luax_checktexturesettings(L, startidx, true, true, false, forceRenderTarget, s, setDPIScale);
  696. }
  697. // Default to the screen's current pixel density scale.
  698. if (!setDPIScale)
  699. s.dpiScale = instance()->getScreenDPIScale();
  700. Texture *texture = nullptr;
  701. luax_catchexcept(L, [&](){ texture = instance()->newTexture(s); });
  702. luax_pushtype(L, texture);
  703. texture->release();
  704. return 1;
  705. }
  706. int w_newTexture(lua_State *L)
  707. {
  708. luax_checkgraphicscreated(L);
  709. Texture::Slices slices(TEXTURE_2D);
  710. Texture::Slices *slicesref = &slices;
  711. Texture::Settings settings;
  712. settings.type = TEXTURE_2D;
  713. bool dpiscaleset = false;
  714. if (lua_type(L, 1) == LUA_TNUMBER)
  715. {
  716. slicesref = nullptr;
  717. settings.width = (int) luaL_checkinteger(L, 1);
  718. settings.height = (int) luaL_checkinteger(L, 2);
  719. int startidx = 3;
  720. if (lua_type(L, 3) == LUA_TNUMBER)
  721. {
  722. settings.layers = (int) luaL_checkinteger(L, 3);
  723. settings.type = TEXTURE_2D_ARRAY;
  724. startidx = 4;
  725. }
  726. luax_checktexturesettings(L, startidx, true, true, false, OptionalBool(), settings, dpiscaleset);
  727. }
  728. else
  729. {
  730. luax_checktexturesettings(L, 2, true, false, false, OptionalBool(), settings, dpiscaleset);
  731. float *autodpiscale = dpiscaleset ? nullptr : &settings.dpiScale;
  732. if (lua_istable(L, 1))
  733. {
  734. int n = std::max(1, (int) luax_objlen(L, 1));
  735. for (int i = 0; i < n; i++)
  736. {
  737. lua_rawgeti(L, 1, i + 1);
  738. auto data = getImageData(L, -1, true, i == 0 ? autodpiscale : nullptr);
  739. if (data.first.get())
  740. slices.set(0, i, data.first);
  741. else
  742. slices.set(0, i, data.second->getSlice(0, 0));
  743. }
  744. lua_pop(L, n);
  745. }
  746. else
  747. {
  748. auto data = getImageData(L, 1, true, autodpiscale);
  749. if (data.first.get())
  750. slices.set(0, 0, data.first);
  751. else
  752. slices.add(data.second, 0, 0, false, settings.mipmaps != Texture::MIPMAPS_NONE);
  753. }
  754. }
  755. return w__pushNewTexture(L, slicesref, settings);
  756. }
  757. int w_newCubeTexture(lua_State *L)
  758. {
  759. luax_checkgraphicscreated(L);
  760. Texture::Slices slices(TEXTURE_CUBE);
  761. Texture::Slices *slicesref = &slices;
  762. Texture::Settings settings;
  763. settings.type = TEXTURE_CUBE;
  764. bool dpiscaleset = false;
  765. if (lua_type(L, 1) == LUA_TNUMBER)
  766. {
  767. slicesref = nullptr;
  768. settings.width = settings.height = (int) luaL_checkinteger(L, 1);
  769. luax_checktexturesettings(L, 2, true, false, false, OptionalBool(), settings, dpiscaleset);
  770. }
  771. else
  772. {
  773. luax_checktexturesettings(L, 2, true, false, false, OptionalBool(), settings, dpiscaleset);
  774. float *autodpiscale = dpiscaleset ? nullptr : &settings.dpiScale;
  775. auto imagemodule = Module::getInstance<love::image::Image>(Module::M_IMAGE);
  776. if (!lua_istable(L, 1))
  777. {
  778. auto data = getImageData(L, 1, true, autodpiscale);
  779. std::vector<StrongRef<love::image::ImageData>> faces;
  780. if (data.first.get())
  781. {
  782. luax_catchexcept(L, [&](){ faces = imagemodule->newCubeFaces(data.first); });
  783. for (int i = 0; i < (int) faces.size(); i++)
  784. slices.set(i, 0, faces[i]);
  785. }
  786. else
  787. slices.add(data.second, 0, 0, true, settings.mipmaps != Texture::MIPMAPS_NONE);
  788. }
  789. else
  790. {
  791. int tlen = (int) luax_objlen(L, 1);
  792. if (luax_isarrayoftables(L, 1))
  793. {
  794. if (tlen != 6)
  795. return luaL_error(L, "Cubemap images must have 6 faces.");
  796. for (int face = 0; face < tlen; face++)
  797. {
  798. lua_rawgeti(L, 1, face + 1);
  799. luaL_checktype(L, -1, LUA_TTABLE);
  800. int miplen = std::max(1, (int) luax_objlen(L, -1));
  801. for (int mip = 0; mip < miplen; mip++)
  802. {
  803. lua_rawgeti(L, -1, mip + 1);
  804. auto data = getImageData(L, -1, true, face == 0 && mip == 0 ? autodpiscale : nullptr);
  805. if (data.first.get())
  806. slices.set(face, mip, data.first);
  807. else
  808. slices.set(face, mip, data.second->getSlice(0, 0));
  809. lua_pop(L, 1);
  810. }
  811. }
  812. }
  813. else
  814. {
  815. bool usemipmaps = false;
  816. for (int i = 0; i < tlen; i++)
  817. {
  818. lua_rawgeti(L, 1, i + 1);
  819. auto data = getImageData(L, -1, true, i == 0 ? autodpiscale : nullptr);
  820. if (data.first.get())
  821. {
  822. if (usemipmaps || data.first->getWidth() != data.first->getHeight())
  823. {
  824. usemipmaps = true;
  825. std::vector<StrongRef<love::image::ImageData>> faces;
  826. luax_catchexcept(L, [&](){ faces = imagemodule->newCubeFaces(data.first); });
  827. for (int face = 0; face < (int) faces.size(); face++)
  828. slices.set(face, i, faces[i]);
  829. }
  830. else
  831. slices.set(i, 0, data.first);
  832. }
  833. else
  834. slices.add(data.second, i, 0, false, settings.mipmaps != Texture::MIPMAPS_NONE);
  835. }
  836. }
  837. lua_pop(L, tlen);
  838. }
  839. }
  840. return w__pushNewTexture(L, slicesref, settings);
  841. }
  842. int w_newArrayTexture(lua_State *L)
  843. {
  844. luax_checkgraphicscreated(L);
  845. Texture::Slices slices(TEXTURE_2D_ARRAY);
  846. Texture::Slices *slicesref = &slices;
  847. Texture::Settings settings;
  848. settings.type = TEXTURE_2D_ARRAY;
  849. bool dpiscaleset = false;
  850. if (lua_type(L, 1) == LUA_TNUMBER)
  851. {
  852. slicesref = nullptr;
  853. settings.width = (int) luaL_checkinteger(L, 1);
  854. settings.height = (int) luaL_checkinteger(L, 2);
  855. settings.layers = (int) luaL_checkinteger(L, 3);
  856. luax_checktexturesettings(L, 4, true, false, false, OptionalBool(), settings, dpiscaleset);
  857. }
  858. else
  859. {
  860. luax_checktexturesettings(L, 2, true, false, false, OptionalBool(), settings, dpiscaleset);
  861. float *autodpiscale = dpiscaleset ? nullptr : &settings.dpiScale;
  862. if (lua_istable(L, 1))
  863. {
  864. int tlen = std::max(1, (int) luax_objlen(L, 1));
  865. if (luax_isarrayoftables(L, 1))
  866. {
  867. for (int slice = 0; slice < tlen; slice++)
  868. {
  869. lua_rawgeti(L, 1, slice + 1);
  870. luaL_checktype(L, -1, LUA_TTABLE);
  871. int miplen = std::max(1, (int) luax_objlen(L, -1));
  872. for (int mip = 0; mip < miplen; mip++)
  873. {
  874. lua_rawgeti(L, -1, mip + 1);
  875. auto data = getImageData(L, -1, true, slice == 0 && mip == 0 ? autodpiscale : nullptr);
  876. if (data.first.get())
  877. slices.set(slice, mip, data.first);
  878. else
  879. slices.set(slice, mip, data.second->getSlice(0, 0));
  880. lua_pop(L, 1);
  881. }
  882. }
  883. }
  884. else
  885. {
  886. for (int slice = 0; slice < tlen; slice++)
  887. {
  888. lua_rawgeti(L, 1, slice + 1);
  889. auto data = getImageData(L, -1, true, slice == 0 ? autodpiscale : nullptr);
  890. if (data.first.get())
  891. slices.set(slice, 0, data.first);
  892. else
  893. slices.add(data.second, slice, 0, false, settings.mipmaps != Texture::MIPMAPS_NONE);
  894. }
  895. }
  896. lua_pop(L, tlen);
  897. }
  898. else
  899. {
  900. auto data = getImageData(L, 1, true, autodpiscale);
  901. if (data.first.get())
  902. slices.set(0, 0, data.first);
  903. else
  904. slices.add(data.second, 0, 0, true, settings.mipmaps != Texture::MIPMAPS_NONE);
  905. }
  906. }
  907. return w__pushNewTexture(L, slicesref, settings);
  908. }
  909. int w_newVolumeTexture(lua_State *L)
  910. {
  911. luax_checkgraphicscreated(L);
  912. auto imagemodule = Module::getInstance<love::image::Image>(Module::M_IMAGE);
  913. Texture::Slices slices(TEXTURE_VOLUME);
  914. Texture::Slices *slicesref = &slices;
  915. Texture::Settings settings;
  916. settings.type = TEXTURE_VOLUME;
  917. bool dpiscaleset = false;
  918. if (lua_type(L, 1) == LUA_TNUMBER)
  919. {
  920. slicesref = nullptr;
  921. settings.width = (int) luaL_checkinteger(L, 1);
  922. settings.height = (int) luaL_checkinteger(L, 2);
  923. settings.layers = (int) luaL_checkinteger(L, 3);
  924. luax_checktexturesettings(L, 4, true, false, false, OptionalBool(), settings, dpiscaleset);
  925. }
  926. else
  927. {
  928. luax_checktexturesettings(L, 2, true, false, false, OptionalBool(), settings, dpiscaleset);
  929. float *autodpiscale = dpiscaleset ? nullptr : &settings.dpiScale;
  930. if (lua_istable(L, 1))
  931. {
  932. int tlen = std::max(1, (int) luax_objlen(L, 1));
  933. if (luax_isarrayoftables(L, 1))
  934. {
  935. for (int mip = 0; mip < tlen; mip++)
  936. {
  937. lua_rawgeti(L, 1, mip + 1);
  938. luaL_checktype(L, -1, LUA_TTABLE);
  939. int slicelen = std::max(1, (int) luax_objlen(L, -1));
  940. for (int slice = 0; slice < slicelen; slice++)
  941. {
  942. lua_rawgeti(L, -1, slice + 1);
  943. auto data = getImageData(L, -1, true, slice == 0 && mip == 0 ? autodpiscale : nullptr);
  944. if (data.first.get())
  945. slices.set(slice, mip, data.first);
  946. else
  947. slices.set(slice, mip, data.second->getSlice(0, 0));
  948. lua_pop(L, 1);
  949. }
  950. }
  951. }
  952. else
  953. {
  954. for (int layer = 0; layer < tlen; layer++)
  955. {
  956. lua_rawgeti(L, 1, layer + 1);
  957. auto data = getImageData(L, -1, true, layer == 0 ? autodpiscale : nullptr);
  958. if (data.first.get())
  959. slices.set(layer, 0, data.first);
  960. else
  961. slices.add(data.second, layer, 0, false, settings.mipmaps != Texture::MIPMAPS_NONE);
  962. }
  963. }
  964. lua_pop(L, tlen);
  965. }
  966. else
  967. {
  968. auto data = getImageData(L, 1, true, autodpiscale);
  969. if (data.first.get())
  970. {
  971. std::vector<StrongRef<love::image::ImageData>> layers;
  972. luax_catchexcept(L, [&](){ layers = imagemodule->newVolumeLayers(data.first); });
  973. for (int i = 0; i < (int) layers.size(); i++)
  974. slices.set(i, 0, layers[i]);
  975. }
  976. else
  977. slices.add(data.second, 0, 0, true, settings.mipmaps != Texture::MIPMAPS_NONE);
  978. }
  979. }
  980. return w__pushNewTexture(L, slicesref, settings);
  981. }
  982. int w_newImage(lua_State *L)
  983. {
  984. //luax_markdeprecated(L, 1, "love.graphics.newImage", API_FUNCTION, DEPRECATED_RENAMED, "love.graphics.newTexture");
  985. return w_newTexture(L);
  986. }
  987. int w_newCubeImage(lua_State *L)
  988. {
  989. //luax_markdeprecated(L, 1, "love.graphics.newCubeImage", API_FUNCTION, DEPRECATED_RENAMED, "love.graphics.newCubeTexture");
  990. return w_newCubeTexture(L);
  991. }
  992. int w_newArrayImage(lua_State *L)
  993. {
  994. //luax_markdeprecated(L, 1, "love.graphics.newArrayImage", API_FUNCTION, DEPRECATED_RENAMED, "love.graphics.newArrayTexture");
  995. return w_newArrayTexture(L);
  996. }
  997. int w_newVolumeImage(lua_State *L)
  998. {
  999. //luax_markdeprecated(L, 1, "love.graphics.newVolumeImage", API_FUNCTION, DEPRECATED_RENAMED, "love.graphics.newVolumeTexture");
  1000. return w_newVolumeTexture(L);
  1001. }
  1002. int w_newQuad(lua_State *L)
  1003. {
  1004. luax_checkgraphicscreated(L);
  1005. Quad::Viewport v;
  1006. v.x = luaL_checknumber(L, 1);
  1007. v.y = luaL_checknumber(L, 2);
  1008. v.w = luaL_checknumber(L, 3);
  1009. v.h = luaL_checknumber(L, 4);
  1010. double sw = 0.0f;
  1011. double sh = 0.0f;
  1012. int layer = 0;
  1013. if (luax_istype(L, 5, Texture::type))
  1014. {
  1015. Texture *texture = luax_checktexture(L, 5);
  1016. sw = texture->getWidth();
  1017. sh = texture->getHeight();
  1018. }
  1019. else if (luax_istype(L, 6, Texture::type))
  1020. {
  1021. layer = (int) luaL_checkinteger(L, 5) - 1;
  1022. Texture *texture = luax_checktexture(L, 6);
  1023. sw = texture->getWidth();
  1024. sh = texture->getHeight();
  1025. }
  1026. else if (!lua_isnoneornil(L, 7))
  1027. {
  1028. layer = (int) luaL_checkinteger(L, 5) - 1;
  1029. sw = luaL_checknumber(L, 6);
  1030. sh = luaL_checknumber(L, 7);
  1031. }
  1032. else
  1033. {
  1034. sw = luaL_checknumber(L, 5);
  1035. sh = luaL_checknumber(L, 6);
  1036. }
  1037. Quad *quad = instance()->newQuad(v, sw, sh);
  1038. quad->setLayer(layer);
  1039. luax_pushtype(L, quad);
  1040. quad->release();
  1041. return 1;
  1042. }
  1043. int w_newFont(lua_State *L)
  1044. {
  1045. luax_checkgraphicscreated(L);
  1046. graphics::Font *font = nullptr;
  1047. // Convert to Rasterizer, if necessary.
  1048. if (!luax_istype(L, 1, love::font::Rasterizer::type))
  1049. {
  1050. std::vector<int> idxs;
  1051. for (int i = 0; i < lua_gettop(L); i++)
  1052. idxs.push_back(i + 1);
  1053. luax_convobj(L, idxs, "font", "newRasterizer");
  1054. }
  1055. love::font::Rasterizer *rasterizer = luax_checktype<love::font::Rasterizer>(L, 1);
  1056. luax_catchexcept(L, [&]() {
  1057. font = instance()->newFont(rasterizer); }
  1058. );
  1059. // Push the type.
  1060. luax_pushtype(L, font);
  1061. font->release();
  1062. return 1;
  1063. }
  1064. int w_newImageFont(lua_State *L)
  1065. {
  1066. luax_checkgraphicscreated(L);
  1067. // Convert to Rasterizer if necessary.
  1068. if (!luax_istype(L, 1, love::font::Rasterizer::type))
  1069. {
  1070. luaL_checktype(L, 2, LUA_TSTRING);
  1071. std::vector<int> idxs;
  1072. for (int i = 0; i < lua_gettop(L); i++)
  1073. idxs.push_back(i + 1);
  1074. luax_convobj(L, idxs, "font", "newImageRasterizer");
  1075. }
  1076. love::font::Rasterizer *rasterizer = luax_checktype<love::font::Rasterizer>(L, 1);
  1077. // Create the font.
  1078. Font *font = instance()->newFont(rasterizer);
  1079. // Push the type.
  1080. luax_pushtype(L, font);
  1081. font->release();
  1082. return 1;
  1083. }
  1084. int w_newSpriteBatch(lua_State *L)
  1085. {
  1086. luax_checkgraphicscreated(L);
  1087. Texture *texture = luax_checktexture(L, 1);
  1088. int size = (int) luaL_optinteger(L, 2, 1000);
  1089. BufferDataUsage usage = BUFFERDATAUSAGE_DYNAMIC;
  1090. if (lua_gettop(L) > 2)
  1091. {
  1092. const char *usagestr = luaL_checkstring(L, 3);
  1093. if (!getConstant(usagestr, usage))
  1094. return luax_enumerror(L, "usage hint", getConstants(usage), usagestr);
  1095. }
  1096. SpriteBatch *t = nullptr;
  1097. luax_catchexcept(L,
  1098. [&](){ t = instance()->newSpriteBatch(texture, size, usage); }
  1099. );
  1100. luax_pushtype(L, t);
  1101. t->release();
  1102. return 1;
  1103. }
  1104. int w_newParticleSystem(lua_State *L)
  1105. {
  1106. luax_checkgraphicscreated(L);
  1107. Texture *texture = luax_checktexture(L, 1);
  1108. lua_Number size = luaL_optnumber(L, 2, 1000);
  1109. ParticleSystem *t = nullptr;
  1110. if (size < 1.0 || size > ParticleSystem::MAX_PARTICLES)
  1111. return luaL_error(L, "Invalid ParticleSystem size");
  1112. luax_catchexcept(L,
  1113. [&](){ t = instance()->newParticleSystem(texture, int(size)); }
  1114. );
  1115. luax_pushtype(L, t);
  1116. t->release();
  1117. return 1;
  1118. }
  1119. static int w_getShaderSource(lua_State *L, int startidx, std::vector<std::string> &stages)
  1120. {
  1121. using namespace love::filesystem;
  1122. luax_checkgraphicscreated(L);
  1123. auto fs = Module::getInstance<Filesystem>(Module::M_FILESYSTEM);
  1124. // read any filepath arguments
  1125. for (int i = startidx; i < startidx + 2; i++)
  1126. {
  1127. if (!lua_isstring(L, i))
  1128. {
  1129. if (luax_cangetfiledata(L, i))
  1130. {
  1131. FileData *fd = luax_getfiledata(L, i);
  1132. lua_pushlstring(L, (const char *) fd->getData(), fd->getSize());
  1133. fd->release();
  1134. lua_replace(L, i);
  1135. }
  1136. continue;
  1137. }
  1138. size_t slen = 0;
  1139. const char *str = lua_tolstring(L, i, &slen);
  1140. Filesystem::Info info = {};
  1141. if (fs != nullptr && fs->getInfo(str, info))
  1142. {
  1143. FileData *fd = nullptr;
  1144. luax_catchexcept(L, [&](){ fd = fs->read(str); });
  1145. lua_pushlstring(L, (const char *) fd->getData(), fd->getSize());
  1146. fd->release();
  1147. lua_replace(L, i);
  1148. }
  1149. else
  1150. {
  1151. // Check if the argument looks like a filepath - we want a nicer
  1152. // error for misspelled filepath arguments.
  1153. if (slen > 0 && slen < 64 && !strchr(str, '\n'))
  1154. {
  1155. const char *ext = strchr(str, '.');
  1156. if (ext != nullptr && !strchr(ext, ';') && !strchr(ext, ' '))
  1157. return luaL_error(L, "Could not open file %s. Does not exist.", str);
  1158. }
  1159. }
  1160. }
  1161. bool has_arg1 = lua_isstring(L, startidx + 0) != 0;
  1162. bool has_arg2 = lua_isstring(L, startidx + 1) != 0;
  1163. // require at least one string argument
  1164. if (!(has_arg1 || has_arg2))
  1165. luaL_checkstring(L, startidx);
  1166. if (has_arg1)
  1167. stages.push_back(luax_checkstring(L, startidx + 0));
  1168. if (has_arg2)
  1169. stages.push_back(luax_checkstring(L, startidx + 1));
  1170. return 0;
  1171. }
  1172. int w_newShader(lua_State *L)
  1173. {
  1174. std::vector<std::string> stages;
  1175. w_getShaderSource(L, 1, stages);
  1176. bool should_error = false;
  1177. try
  1178. {
  1179. Shader *shader = instance()->newShader(stages);
  1180. luax_pushtype(L, shader);
  1181. shader->release();
  1182. }
  1183. catch (love::Exception &e)
  1184. {
  1185. luax_getfunction(L, "graphics", "_transformGLSLErrorMessages");
  1186. lua_pushstring(L, e.what());
  1187. // Function pushes the new error string onto the stack.
  1188. lua_pcall(L, 1, 1, 0);
  1189. should_error = true;
  1190. }
  1191. if (should_error)
  1192. return lua_error(L);
  1193. return 1;
  1194. }
  1195. int w_newComputeShader(lua_State* L)
  1196. {
  1197. std::vector<std::string> stages;
  1198. w_getShaderSource(L, 1, stages);
  1199. bool should_error = false;
  1200. try
  1201. {
  1202. Shader *shader = instance()->newComputeShader(stages[0]);
  1203. luax_pushtype(L, shader);
  1204. shader->release();
  1205. }
  1206. catch (love::Exception &e)
  1207. {
  1208. luax_getfunction(L, "graphics", "_transformGLSLErrorMessages");
  1209. lua_pushstring(L, e.what());
  1210. // Function pushes the new error string onto the stack.
  1211. lua_pcall(L, 1, 1, 0);
  1212. should_error = true;
  1213. }
  1214. if (should_error)
  1215. return lua_error(L);
  1216. return 1;
  1217. }
  1218. int w_validateShader(lua_State *L)
  1219. {
  1220. bool gles = luax_checkboolean(L, 1);
  1221. std::vector<std::string> stages;
  1222. w_getShaderSource(L, 2, stages);
  1223. bool success = true;
  1224. std::string err;
  1225. try
  1226. {
  1227. success = instance()->validateShader(gles, stages, err);
  1228. }
  1229. catch (love::Exception &e)
  1230. {
  1231. success = false;
  1232. err = e.what();
  1233. }
  1234. luax_pushboolean(L, success);
  1235. if (!success)
  1236. {
  1237. luax_pushstring(L, err);
  1238. return 2;
  1239. }
  1240. return 1;
  1241. }
  1242. static BufferDataUsage luax_optdatausage(lua_State *L, int idx, BufferDataUsage def)
  1243. {
  1244. const char *usagestr = lua_isnoneornil(L, idx) ? nullptr : luaL_checkstring(L, idx);
  1245. if (usagestr && !getConstant(usagestr, def))
  1246. luax_enumerror(L, "usage hint", getConstants(def), usagestr);
  1247. return def;
  1248. }
  1249. static void luax_optbuffersettings(lua_State *L, int idx, Buffer::Settings &settings)
  1250. {
  1251. if (lua_isnoneornil(L, idx))
  1252. return;
  1253. luaL_checktype(L, idx, LUA_TTABLE);
  1254. lua_getfield(L, idx, "usage");
  1255. settings.dataUsage = luax_optdatausage(L, -1, settings.dataUsage);
  1256. lua_pop(L, 1);
  1257. }
  1258. static Buffer::DataDeclaration luax_checkdatadeclaration(lua_State* L, int formattableidx, int arrayindex, int declindex, bool requirename)
  1259. {
  1260. Buffer::DataDeclaration decl("", DATAFORMAT_MAX_ENUM);
  1261. lua_getfield(L, declindex, "name");
  1262. if (requirename && lua_type(L, -1) != LUA_TSTRING)
  1263. {
  1264. std::ostringstream ss;
  1265. ss << "'name' field expected in array element #";
  1266. ss << arrayindex;
  1267. ss << " of format table";
  1268. std::string str = ss.str();
  1269. luaL_argerror(L, formattableidx, str.c_str());
  1270. }
  1271. else if (!lua_isnoneornil(L, -1))
  1272. decl.name = luax_checkstring(L, -1);
  1273. lua_pop(L, 1);
  1274. lua_getfield(L, declindex, "format");
  1275. if (lua_type(L, -1) != LUA_TSTRING)
  1276. {
  1277. std::ostringstream ss;
  1278. ss << "'format' field expected in array element #";
  1279. ss << arrayindex;
  1280. ss << " of format table";
  1281. std::string str = ss.str();
  1282. luaL_argerror(L, formattableidx, str.c_str());
  1283. }
  1284. const char* formatstr = luaL_checkstring(L, -1);
  1285. if (!getConstant(formatstr, decl.format))
  1286. luax_enumerror(L, "data format", getConstants(decl.format), formatstr);
  1287. lua_pop(L, 1);
  1288. decl.arrayLength = luax_intflag(L, declindex, "arraylength", 0);
  1289. return decl;
  1290. }
  1291. static void luax_checkbufferformat(lua_State *L, int idx, std::vector<Buffer::DataDeclaration> &format)
  1292. {
  1293. if (lua_type(L, idx) == LUA_TSTRING)
  1294. {
  1295. Buffer::DataDeclaration decl("", DATAFORMAT_MAX_ENUM);
  1296. const char *formatstr = luaL_checkstring(L, idx);
  1297. if (!getConstant(formatstr, decl.format))
  1298. luax_enumerror(L, "data format", getConstants(decl.format), formatstr);
  1299. format.push_back(decl);
  1300. return;
  1301. }
  1302. luaL_checktype(L, idx, LUA_TTABLE);
  1303. int tablelen = luax_objlen(L, idx);
  1304. for (int i = 1; i <= tablelen; i++)
  1305. {
  1306. lua_rawgeti(L, idx, i);
  1307. luaL_checktype(L, -1, LUA_TTABLE);
  1308. Buffer::DataDeclaration decl = luax_checkdatadeclaration(L, idx, i, -1, false);
  1309. format.push_back(decl);
  1310. lua_pop(L, 1);
  1311. }
  1312. }
  1313. static Buffer *luax_newbuffer(lua_State *L, int idx, Buffer::Settings settings, const std::vector<Buffer::DataDeclaration> &format)
  1314. {
  1315. size_t arraylength = 0;
  1316. size_t bytesize = 0;
  1317. Data *data = nullptr;
  1318. const void *initialdata = nullptr;
  1319. int ncomponents = 0;
  1320. for (const Buffer::DataDeclaration &decl : format)
  1321. ncomponents += getDataFormatInfo(decl.format).components;
  1322. if (luax_istype(L, idx, Data::type))
  1323. {
  1324. data = luax_checktype<Data>(L, idx);
  1325. initialdata = data->getData();
  1326. bytesize = data->getSize();
  1327. }
  1328. bool tableoftables = false;
  1329. if (lua_istable(L, idx))
  1330. {
  1331. arraylength = luax_objlen(L, idx);
  1332. lua_rawgeti(L, idx, 1);
  1333. tableoftables = lua_istable(L, -1);
  1334. lua_pop(L, 1);
  1335. if (!tableoftables)
  1336. {
  1337. if (arraylength % ncomponents != 0)
  1338. luaL_error(L, "Array length in flat array variant of newBuffer must be a multiple of the total number of components (%d)", ncomponents);
  1339. arraylength /= ncomponents;
  1340. }
  1341. }
  1342. else if (data == nullptr)
  1343. {
  1344. lua_Integer len = luaL_checkinteger(L, idx);
  1345. if (len <= 0)
  1346. luaL_argerror(L, idx, "number of elements must be greater than 0");
  1347. arraylength = (size_t) len;
  1348. settings.zeroInitialize = true;
  1349. }
  1350. Buffer *b = nullptr;
  1351. luax_catchexcept(L, [&] { b = instance()->newBuffer(settings, format, initialdata, bytesize, arraylength); });
  1352. if (lua_istable(L, idx))
  1353. {
  1354. Buffer::Mapper mapper(*b);
  1355. char *data = (char *) mapper.data;
  1356. const auto &members = b->getDataMembers();
  1357. size_t stride = b->getArrayStride();
  1358. if (tableoftables)
  1359. {
  1360. for (size_t i = 0; i < arraylength; i++)
  1361. {
  1362. // get arraydata[index]
  1363. lua_rawgeti(L, 2, i + 1);
  1364. luaL_checktype(L, -1, LUA_TTABLE);
  1365. // get arraydata[index][j]
  1366. for (int j = 1; j <= ncomponents; j++)
  1367. lua_rawgeti(L, -j, j);
  1368. int idx = -ncomponents;
  1369. for (const Buffer::DataMember &member : members)
  1370. {
  1371. luax_writebufferdata(L, idx, member.decl.format, data + member.offset);
  1372. idx += member.info.components;
  1373. }
  1374. lua_pop(L, ncomponents + 1);
  1375. data += stride;
  1376. }
  1377. }
  1378. else // Flat array
  1379. {
  1380. for (size_t i = 0; i < arraylength; i++)
  1381. {
  1382. // get arraydata[arrayindex * ncomponents + componentindex]
  1383. for (int componentindex = 1; componentindex <= ncomponents; componentindex++)
  1384. lua_rawgeti(L, 2, i * ncomponents + componentindex);
  1385. int idx = -ncomponents;
  1386. for (const Buffer::DataMember &member : members)
  1387. {
  1388. luax_writebufferdata(L, idx, member.decl.format, data + member.offset);
  1389. idx += member.info.components;
  1390. }
  1391. lua_pop(L, ncomponents);
  1392. data += stride;
  1393. }
  1394. }
  1395. }
  1396. return b;
  1397. }
  1398. int w_newBuffer(lua_State *L)
  1399. {
  1400. Buffer::Settings settings(0, BUFFERDATAUSAGE_DYNAMIC);
  1401. luaL_checktype(L, 3, LUA_TTABLE);
  1402. for (int i = 0; i < BUFFERUSAGE_MAX_ENUM; i++)
  1403. {
  1404. BufferUsage bufferusage = (BufferUsage) i;
  1405. const char *tname = nullptr;
  1406. if (!getConstant(bufferusage, tname))
  1407. continue;
  1408. if (luax_boolflag(L, 3, tname, false))
  1409. settings.usageFlags = (BufferUsageFlags)(settings.usageFlags | (1u << i));
  1410. }
  1411. luax_optbuffersettings(L, 3, settings);
  1412. std::vector<Buffer::DataDeclaration> format;
  1413. luax_checkbufferformat(L, 1, format);
  1414. Buffer *b = luax_newbuffer(L, 2, settings, format);
  1415. luax_pushtype(L, b);
  1416. b->release();
  1417. return 1;
  1418. }
  1419. int w_newVertexBuffer(lua_State *L)
  1420. {
  1421. Buffer::Settings settings(BUFFERUSAGEFLAG_VERTEX, BUFFERDATAUSAGE_DYNAMIC);
  1422. luax_optbuffersettings(L, 3, settings);
  1423. std::vector<Buffer::DataDeclaration> format;
  1424. luax_checkbufferformat(L, 1, format);
  1425. Buffer *b = luax_newbuffer(L, 2, settings, format);
  1426. luax_pushtype(L, b);
  1427. b->release();
  1428. return 1;
  1429. }
  1430. int w_newIndexBuffer(lua_State *L)
  1431. {
  1432. Buffer::Settings settings(BUFFERUSAGEFLAG_INDEX, BUFFERDATAUSAGE_DYNAMIC);
  1433. luax_optbuffersettings(L, 3, settings);
  1434. size_t arraylength = 0;
  1435. size_t bytesize = 0;
  1436. DataFormat format = DATAFORMAT_UINT16;
  1437. Data *data = nullptr;
  1438. const void *initialdata = nullptr;
  1439. if (luax_istype(L, 1, Data::type))
  1440. {
  1441. data = luax_checktype<Data>(L, 1);
  1442. initialdata = data->getData();
  1443. bytesize = data->getSize();
  1444. }
  1445. if (lua_istable(L, 1))
  1446. {
  1447. arraylength = luax_objlen(L, 1);
  1448. // Scan array for invalid types and the max value.
  1449. lua_Integer maxvalue = 0;
  1450. for (size_t i = 0; i < arraylength; i++)
  1451. {
  1452. lua_rawgeti(L, 1, i + 1);
  1453. lua_Integer v = luaL_checkinteger(L, -1);
  1454. lua_pop(L, 1);
  1455. if (v < 0)
  1456. return luaL_argerror(L, 1, "expected positive integer values in array");
  1457. else
  1458. maxvalue = std::max(maxvalue, v);
  1459. }
  1460. format = getIndexDataFormat(getIndexDataTypeFromMax(maxvalue));
  1461. }
  1462. else if (data == nullptr)
  1463. {
  1464. lua_Integer len = luaL_checkinteger(L, 1);
  1465. if (len <= 0)
  1466. return luaL_argerror(L, 1, "number of elements must be greater than 0");
  1467. arraylength = (size_t) len;
  1468. settings.zeroInitialize = true;
  1469. }
  1470. if (data != nullptr || !lua_isnoneornil(L, 2))
  1471. {
  1472. const char *formatstr = luaL_checkstring(L, 2);
  1473. if (!getConstant(formatstr, format))
  1474. return luax_enumerror(L, "index data format", getConstants(format), formatstr);
  1475. }
  1476. Buffer *b = nullptr;
  1477. luax_catchexcept(L, [&] { b = instance()->newBuffer(settings, format, initialdata, bytesize, arraylength); });
  1478. if (lua_istable(L, 1))
  1479. {
  1480. Buffer::Mapper mapper(*b);
  1481. uint16 *u16data = (uint16 *) mapper.data;
  1482. uint32 *u32data = (uint32 *) mapper.data;
  1483. for (size_t i = 0; i < arraylength; i++)
  1484. {
  1485. lua_rawgeti(L, 1, i + 1);
  1486. lua_Integer v = luaL_checkinteger(L, -1);
  1487. lua_pop(L, 1);
  1488. if (format == DATAFORMAT_UINT16)
  1489. u16data[i] = (uint16) v;
  1490. else
  1491. u32data[i] = (uint32) v;
  1492. }
  1493. }
  1494. luax_pushtype(L, b);
  1495. b->release();
  1496. return 1;
  1497. }
  1498. static PrimitiveType luax_optmeshdrawmode(lua_State *L, int idx, PrimitiveType def)
  1499. {
  1500. const char *modestr = lua_isnoneornil(L, idx) ? nullptr : luaL_checkstring(L, idx);
  1501. if (modestr && !getConstant(modestr, def))
  1502. luax_enumerror(L, "mesh draw mode", getConstants(def), modestr);
  1503. return def;
  1504. }
  1505. static Mesh *newStandardMesh(lua_State *L)
  1506. {
  1507. Mesh *t = nullptr;
  1508. PrimitiveType drawmode = luax_optmeshdrawmode(L, 2, PRIMITIVE_TRIANGLE_FAN);
  1509. BufferDataUsage usage = luax_optdatausage(L, 3, BUFFERDATAUSAGE_DYNAMIC);
  1510. std::vector<Buffer::DataDeclaration> format = Mesh::getDefaultVertexFormat();
  1511. // First argument is a table of standard vertices, or the number of
  1512. // standard vertices.
  1513. if (lua_istable(L, 1))
  1514. {
  1515. size_t vertexcount = luax_objlen(L, 1);
  1516. std::vector<Vertex> vertices;
  1517. vertices.reserve(vertexcount);
  1518. // Get the vertices from the table.
  1519. for (size_t i = 1; i <= vertexcount; i++)
  1520. {
  1521. lua_rawgeti(L, 1, (int) i);
  1522. if (lua_type(L, -1) != LUA_TTABLE)
  1523. {
  1524. luax_typerror(L, 1, "table of tables");
  1525. return nullptr;
  1526. }
  1527. for (int j = 1; j <= 8; j++)
  1528. lua_rawgeti(L, -j, j);
  1529. Vertex v;
  1530. v.x = (float) luaL_checknumber(L, -8);
  1531. v.y = (float) luaL_checknumber(L, -7);
  1532. v.s = (float) luaL_optnumber(L, -6, 0.0);
  1533. v.t = (float) luaL_optnumber(L, -5, 0.0);
  1534. v.color.r = (unsigned char) (luax_optnumberclamped01(L, -4, 1.0) * 255.0);
  1535. v.color.g = (unsigned char) (luax_optnumberclamped01(L, -3, 1.0) * 255.0);
  1536. v.color.b = (unsigned char) (luax_optnumberclamped01(L, -2, 1.0) * 255.0);
  1537. v.color.a = (unsigned char) (luax_optnumberclamped01(L, -1, 1.0) * 255.0);
  1538. lua_pop(L, 9);
  1539. vertices.push_back(v);
  1540. }
  1541. luax_catchexcept(L, [&](){ t = instance()->newMesh(format, vertices.data(), vertices.size() * sizeof(Vertex), drawmode, usage); });
  1542. }
  1543. else
  1544. {
  1545. int count = (int) luaL_checkinteger(L, 1);
  1546. luax_catchexcept(L, [&](){ t = instance()->newMesh(format, count, drawmode, usage); });
  1547. }
  1548. return t;
  1549. }
  1550. static Mesh *newCustomMesh(lua_State *L)
  1551. {
  1552. Mesh *t = nullptr;
  1553. // First argument is the vertex format, second is a table of vertices or
  1554. // the number of vertices.
  1555. std::vector<Buffer::DataDeclaration> vertexformat;
  1556. PrimitiveType drawmode = luax_optmeshdrawmode(L, 3, PRIMITIVE_TRIANGLE_FAN);
  1557. BufferDataUsage usage = luax_optdatausage(L, 4, BUFFERDATAUSAGE_DYNAMIC);
  1558. lua_rawgeti(L, 1, 1);
  1559. if (!lua_istable(L, -1))
  1560. {
  1561. luaL_argerror(L, 1, "table of tables expected");
  1562. return nullptr;
  1563. }
  1564. lua_pop(L, 1);
  1565. // Per-vertex attribute data formats.
  1566. for (int i = 1; i <= (int) luax_objlen(L, 1); i++)
  1567. {
  1568. lua_rawgeti(L, 1, i);
  1569. Buffer::DataDeclaration decl("", DATAFORMAT_MAX_ENUM);
  1570. lua_getfield(L, -1, "format");
  1571. bool hasformatfield = !lua_isnoneornil(L, -1);
  1572. lua_pop(L, 1);
  1573. if (hasformatfield || luax_objlen(L, -1) == 0)
  1574. decl = luax_checkdatadeclaration(L, 1, i, -1, true);
  1575. else
  1576. {
  1577. // Legacy format arguments: {name, datatype, components}
  1578. for (int j = 1; j <= 3; j++)
  1579. lua_rawgeti(L, -j, j);
  1580. decl.name = luaL_checkstring(L, -3);
  1581. const char* tname = luaL_checkstring(L, -2);
  1582. int components = (int)luaL_checkinteger(L, -1);
  1583. // Check deprecated format names.
  1584. if (strcmp(tname, "byte") == 0 || strcmp(tname, "unorm8") == 0)
  1585. {
  1586. if (components == 4)
  1587. decl.format = DATAFORMAT_UNORM8_VEC4;
  1588. else
  1589. luaL_error(L, "Invalid component count (%d) for vertex data type %s", components, tname);
  1590. }
  1591. else if (strcmp(tname, "unorm16") == 0)
  1592. {
  1593. if (components == 2)
  1594. decl.format = DATAFORMAT_UNORM16_VEC2;
  1595. else if (components == 4)
  1596. decl.format = DATAFORMAT_UNORM16_VEC4;
  1597. else
  1598. luaL_error(L, "Invalid component count (%d) for vertex data type %s", components, tname);
  1599. }
  1600. else if (strcmp(tname, "float") == 0)
  1601. {
  1602. if (components == 1)
  1603. decl.format = DATAFORMAT_FLOAT;
  1604. else if (components == 2)
  1605. decl.format = DATAFORMAT_FLOAT_VEC2;
  1606. else if (components == 3)
  1607. decl.format = DATAFORMAT_FLOAT_VEC3;
  1608. else if (components == 4)
  1609. decl.format = DATAFORMAT_FLOAT_VEC4;
  1610. else
  1611. luaL_error(L, "Invalid component count (%d) for vertex data type %s", components, tname);
  1612. }
  1613. if (decl.format == DATAFORMAT_MAX_ENUM)
  1614. luax_enumerror(L, "vertex data format", getConstants(decl.format), tname);
  1615. lua_pop(L, 3);
  1616. luax_markdeprecated(L, 1, "vertex format array values in love.graphics.newMesh", API_CUSTOM, DEPRECATED_REPLACED, "named table fields 'format' and 'name'");
  1617. }
  1618. lua_pop(L, 1);
  1619. vertexformat.push_back(decl);
  1620. }
  1621. if (lua_isnumber(L, 2))
  1622. {
  1623. int vertexcount = (int) luaL_checkinteger(L, 2);
  1624. luax_catchexcept(L, [&](){ t = instance()->newMesh(vertexformat, vertexcount, drawmode, usage); });
  1625. }
  1626. else if (luax_istype(L, 2, Data::type))
  1627. {
  1628. // Vertex data comes directly from a Data object.
  1629. Data *data = luax_checktype<Data>(L, 2);
  1630. luax_catchexcept(L, [&](){ t = instance()->newMesh(vertexformat, data->getData(), data->getSize(), drawmode, usage); });
  1631. }
  1632. else
  1633. {
  1634. // Table of vertices.
  1635. lua_rawgeti(L, 2, 1);
  1636. if (!lua_istable(L, -1))
  1637. {
  1638. luaL_argerror(L, 2, "expected table of tables");
  1639. return nullptr;
  1640. }
  1641. lua_pop(L, 1);
  1642. size_t numvertices = luax_objlen(L, 2);
  1643. luax_catchexcept(L, [&](){ t = instance()->newMesh(vertexformat, numvertices, drawmode, usage); });
  1644. char *data = (char *) t->getVertexData();
  1645. size_t stride = t->getVertexStride();
  1646. const auto &members = t->getVertexFormat();
  1647. for (size_t vertindex = 0; vertindex < numvertices; vertindex++)
  1648. {
  1649. // get vertices[vertindex]
  1650. lua_rawgeti(L, 2, vertindex + 1);
  1651. luaL_checktype(L, -1, LUA_TTABLE);
  1652. int n = 0;
  1653. for (size_t i = 0; i < vertexformat.size(); i++)
  1654. {
  1655. const auto &member = members[i];
  1656. const auto &info = getDataFormatInfo(member.decl.format);
  1657. // get vertices[vertindex][n]
  1658. for (int c = 0; c < info.components; c++)
  1659. {
  1660. n++;
  1661. lua_rawgeti(L, -(c + 1), n);
  1662. }
  1663. size_t offset = vertindex * stride + member.offset;
  1664. // Fetch the values from Lua and store them in data buffer.
  1665. luax_writebufferdata(L, -info.components, member.decl.format, data + offset);
  1666. lua_pop(L, info.components);
  1667. }
  1668. lua_pop(L, 1); // pop vertices[vertindex]
  1669. }
  1670. t->setVertexDataModified(0, stride * numvertices);
  1671. t->flush();
  1672. }
  1673. return t;
  1674. }
  1675. int w_newMesh(lua_State *L)
  1676. {
  1677. luax_checkgraphicscreated(L);
  1678. // Check first argument: table or number of vertices.
  1679. int arg1type = lua_type(L, 1);
  1680. if (arg1type != LUA_TTABLE && arg1type != LUA_TNUMBER)
  1681. luaL_argerror(L, 1, "table or number expected");
  1682. Mesh *t = nullptr;
  1683. int arg2type = lua_type(L, 2);
  1684. if (arg1type == LUA_TTABLE && (arg2type == LUA_TTABLE || arg2type == LUA_TNUMBER || arg2type == LUA_TUSERDATA))
  1685. t = newCustomMesh(L);
  1686. else
  1687. t = newStandardMesh(L);
  1688. luax_pushtype(L, t);
  1689. t->release();
  1690. return 1;
  1691. }
  1692. int w_newText(lua_State *L)
  1693. {
  1694. luax_checkgraphicscreated(L);
  1695. graphics::Font *font = luax_checkfont(L, 1);
  1696. Text *t = nullptr;
  1697. if (lua_isnoneornil(L, 2))
  1698. luax_catchexcept(L, [&](){ t = instance()->newText(font); });
  1699. else
  1700. {
  1701. std::vector<Font::ColoredString> text;
  1702. luax_checkcoloredstring(L, 2, text);
  1703. luax_catchexcept(L, [&](){ t = instance()->newText(font, text); });
  1704. }
  1705. luax_pushtype(L, t);
  1706. t->release();
  1707. return 1;
  1708. }
  1709. int w_newVideo(lua_State *L)
  1710. {
  1711. luax_checkgraphicscreated(L);
  1712. if (!luax_istype(L, 1, love::video::VideoStream::type))
  1713. luax_convobj(L, 1, "video", "newVideoStream");
  1714. auto stream = luax_checktype<love::video::VideoStream>(L, 1);
  1715. float dpiscale = (float) luaL_optnumber(L, 2, 1.0);
  1716. Video *video = nullptr;
  1717. luax_catchexcept(L, [&]() { video = instance()->newVideo(stream, dpiscale); });
  1718. luax_pushtype(L, video);
  1719. video->release();
  1720. return 1;
  1721. }
  1722. int w_setColor(lua_State *L)
  1723. {
  1724. Colorf c;
  1725. if (lua_istable(L, 1))
  1726. {
  1727. for (int i = 1; i <= 4; i++)
  1728. lua_rawgeti(L, 1, i);
  1729. c.r = (float) luaL_checknumber(L, -4);
  1730. c.g = (float) luaL_checknumber(L, -3);
  1731. c.b = (float) luaL_checknumber(L, -2);
  1732. c.a = (float) luaL_optnumber(L, -1, 1.0);
  1733. lua_pop(L, 4);
  1734. }
  1735. else
  1736. {
  1737. c.r = (float) luaL_checknumber(L, 1);
  1738. c.g = (float) luaL_checknumber(L, 2);
  1739. c.b = (float) luaL_checknumber(L, 3);
  1740. c.a = (float) luaL_optnumber(L, 4, 1.0);
  1741. }
  1742. instance()->setColor(c);
  1743. return 0;
  1744. }
  1745. int w_getColor(lua_State *L)
  1746. {
  1747. Colorf c = instance()->getColor();
  1748. lua_pushnumber(L, c.r);
  1749. lua_pushnumber(L, c.g);
  1750. lua_pushnumber(L, c.b);
  1751. lua_pushnumber(L, c.a);
  1752. return 4;
  1753. }
  1754. int w_setBackgroundColor(lua_State *L)
  1755. {
  1756. Colorf c;
  1757. if (lua_istable(L, 1))
  1758. {
  1759. for (int i = 1; i <= 4; i++)
  1760. lua_rawgeti(L, 1, i);
  1761. c.r = (float) luaL_checknumber(L, -4);
  1762. c.g = (float) luaL_checknumber(L, -3);
  1763. c.b = (float) luaL_checknumber(L, -2);
  1764. c.a = (float) luaL_optnumber(L, -1, 1.0);
  1765. lua_pop(L, 4);
  1766. }
  1767. else
  1768. {
  1769. c.r = (float) luaL_checknumber(L, 1);
  1770. c.g = (float) luaL_checknumber(L, 2);
  1771. c.b = (float) luaL_checknumber(L, 3);
  1772. c.a = (float) luaL_optnumber(L, 4, 1.0);
  1773. }
  1774. instance()->setBackgroundColor(c);
  1775. return 0;
  1776. }
  1777. int w_getBackgroundColor(lua_State *L)
  1778. {
  1779. Colorf c = instance()->getBackgroundColor();
  1780. lua_pushnumber(L, c.r);
  1781. lua_pushnumber(L, c.g);
  1782. lua_pushnumber(L, c.b);
  1783. lua_pushnumber(L, c.a);
  1784. return 4;
  1785. }
  1786. int w_setNewFont(lua_State *L)
  1787. {
  1788. int ret = w_newFont(L);
  1789. Font *font = luax_checktype<Font>(L, -1);
  1790. instance()->setFont(font);
  1791. return ret;
  1792. }
  1793. int w_setFont(lua_State *L)
  1794. {
  1795. Font *font = luax_checktype<Font>(L, 1);
  1796. instance()->setFont(font);
  1797. return 0;
  1798. }
  1799. int w_getFont(lua_State *L)
  1800. {
  1801. Font *f = nullptr;
  1802. luax_catchexcept(L, [&](){ f = instance()->getFont(); });
  1803. luax_pushtype(L, f);
  1804. return 1;
  1805. }
  1806. int w_setColorMask(lua_State *L)
  1807. {
  1808. ColorChannelMask mask;
  1809. if (lua_gettop(L) <= 1 && lua_isnoneornil(L, 1))
  1810. {
  1811. // Enable all color components if no argument is given.
  1812. mask.r = mask.g = mask.b = mask.a = true;
  1813. }
  1814. else
  1815. {
  1816. mask.r = luax_checkboolean(L, 1);
  1817. mask.g = luax_checkboolean(L, 2);
  1818. mask.b = luax_checkboolean(L, 3);
  1819. mask.a = luax_checkboolean(L, 4);
  1820. }
  1821. instance()->setColorMask(mask);
  1822. return 0;
  1823. }
  1824. int w_getColorMask(lua_State *L)
  1825. {
  1826. ColorChannelMask mask = instance()->getColorMask();
  1827. luax_pushboolean(L, mask.r);
  1828. luax_pushboolean(L, mask.g);
  1829. luax_pushboolean(L, mask.b);
  1830. luax_pushboolean(L, mask.a);
  1831. return 4;
  1832. }
  1833. int w_setBlendMode(lua_State *L)
  1834. {
  1835. BlendMode mode;
  1836. const char *str = luaL_checkstring(L, 1);
  1837. if (!getConstant(str, mode))
  1838. return luax_enumerror(L, "blend mode", getConstants(mode), str);
  1839. BlendAlpha alphamode = BLENDALPHA_MULTIPLY;
  1840. if (!lua_isnoneornil(L, 2))
  1841. {
  1842. const char *alphastr = luaL_checkstring(L, 2);
  1843. if (!getConstant(alphastr, alphamode))
  1844. return luax_enumerror(L, "blend alpha mode", getConstants(alphamode), alphastr);
  1845. }
  1846. luax_catchexcept(L, [&](){ instance()->setBlendMode(mode, alphamode); });
  1847. return 0;
  1848. }
  1849. int w_getBlendMode(lua_State *L)
  1850. {
  1851. const char *str;
  1852. const char *alphastr;
  1853. BlendAlpha alphamode;
  1854. BlendMode mode = instance()->getBlendMode(alphamode);
  1855. if (!getConstant(mode, str))
  1856. return luaL_error(L, "Unknown blend mode");
  1857. if (!getConstant(alphamode, alphastr))
  1858. return luaL_error(L, "Unknown blend alpha mode");
  1859. lua_pushstring(L, str);
  1860. lua_pushstring(L, alphastr);
  1861. return 2;
  1862. }
  1863. static BlendOperation luax_checkblendop(lua_State *L, int idx)
  1864. {
  1865. BlendOperation op = BLENDOP_ADD;
  1866. const char *str = luaL_checkstring(L, idx);
  1867. if (!getConstant(str, op))
  1868. luax_enumerror(L, "blend operation", getConstants(op), str);
  1869. return op;
  1870. }
  1871. static BlendFactor luax_checkblendfactor(lua_State *L, int idx)
  1872. {
  1873. BlendFactor factor = BLENDFACTOR_ZERO;
  1874. const char *str = luaL_checkstring(L, idx);
  1875. if (!getConstant(str, factor))
  1876. luax_enumerror(L, "blend factor", getConstants(factor), str);
  1877. return factor;
  1878. }
  1879. static void luax_pushblendop(lua_State *L, BlendOperation op)
  1880. {
  1881. const char *str;
  1882. if (!getConstant(op, str))
  1883. luaL_error(L, "unknown blend operation");
  1884. lua_pushstring(L, str);
  1885. }
  1886. static void luax_pushblendfactor(lua_State *L, BlendFactor factor)
  1887. {
  1888. const char *str;
  1889. if (!getConstant(factor, str))
  1890. luaL_error(L, "unknown blend factor");
  1891. lua_pushstring(L, str);
  1892. }
  1893. int w_setBlendState(lua_State *L)
  1894. {
  1895. BlendState state;
  1896. if (!lua_isnoneornil(L, 1))
  1897. {
  1898. state.enable = true;
  1899. if (lua_gettop(L) >= 4)
  1900. {
  1901. state.operationRGB = luax_checkblendop(L, 1);
  1902. state.operationA = luax_checkblendop(L, 2);
  1903. state.srcFactorRGB = luax_checkblendfactor(L, 3);
  1904. state.srcFactorA = luax_checkblendfactor(L, 4);
  1905. state.dstFactorRGB = luax_checkblendfactor(L, 5);
  1906. state.dstFactorA = luax_checkblendfactor(L, 6);
  1907. }
  1908. else
  1909. {
  1910. state.operationRGB = state.operationA = luax_checkblendop(L, 1);
  1911. state.srcFactorRGB = state.srcFactorA = luax_checkblendfactor(L, 2);
  1912. state.dstFactorRGB = state.dstFactorA = luax_checkblendfactor(L, 3);
  1913. }
  1914. }
  1915. luax_catchexcept(L, [&](){ instance()->setBlendState(state); });
  1916. return 0;
  1917. }
  1918. int w_getBlendState(lua_State *L)
  1919. {
  1920. const BlendState &state = instance()->getBlendState();
  1921. if (state.enable)
  1922. {
  1923. luax_pushblendop(L, state.operationRGB);
  1924. luax_pushblendop(L, state.operationA);
  1925. luax_pushblendfactor(L, state.srcFactorRGB);
  1926. luax_pushblendfactor(L, state.srcFactorA);
  1927. luax_pushblendfactor(L, state.dstFactorRGB);
  1928. luax_pushblendfactor(L, state.dstFactorA);
  1929. }
  1930. else
  1931. {
  1932. for (int i = 0; i < 6; i++)
  1933. lua_pushnil(L);
  1934. }
  1935. return 6;
  1936. }
  1937. int w_setDefaultFilter(lua_State *L)
  1938. {
  1939. SamplerState s = instance()->getDefaultSamplerState();
  1940. const char *minstr = luaL_checkstring(L, 1);
  1941. const char *magstr = luaL_optstring(L, 2, minstr);
  1942. if (!SamplerState::getConstant(minstr, s.minFilter))
  1943. return luax_enumerror(L, "filter mode", SamplerState::getConstants(s.minFilter), minstr);
  1944. if (!SamplerState::getConstant(magstr, s.magFilter))
  1945. return luax_enumerror(L, "filter mode", SamplerState::getConstants(s.magFilter), magstr);
  1946. s.maxAnisotropy = std::min(std::max(1, (int) luaL_optnumber(L, 3, 1.0)), LOVE_UINT8_MAX);
  1947. instance()->setDefaultSamplerState(s);
  1948. return 0;
  1949. }
  1950. int w_getDefaultFilter(lua_State *L)
  1951. {
  1952. const SamplerState &s = instance()->getDefaultSamplerState();
  1953. const char *minstr;
  1954. const char *magstr;
  1955. if (!SamplerState::getConstant(s.minFilter, minstr))
  1956. return luaL_error(L, "Unknown minification filter mode");
  1957. if (!SamplerState::getConstant(s.magFilter, magstr))
  1958. return luaL_error(L, "Unknown magnification filter mode");
  1959. lua_pushstring(L, minstr);
  1960. lua_pushstring(L, magstr);
  1961. lua_pushnumber(L, s.maxAnisotropy);
  1962. return 3;
  1963. }
  1964. int w_setDefaultMipmapFilter(lua_State *L)
  1965. {
  1966. SamplerState s = instance()->getDefaultSamplerState();
  1967. s.mipmapFilter = SamplerState::MIPMAP_FILTER_NONE;
  1968. if (!lua_isnoneornil(L, 1))
  1969. {
  1970. const char *str = luaL_checkstring(L, 1);
  1971. if (!SamplerState::getConstant(str, s.mipmapFilter))
  1972. return luax_enumerror(L, "filter mode", SamplerState::getConstants(s.mipmapFilter), str);
  1973. }
  1974. s.lodBias = -((float) luaL_optnumber(L, 2, 0.0));
  1975. instance()->setDefaultSamplerState(s);
  1976. return 0;
  1977. }
  1978. int w_getDefaultMipmapFilter(lua_State *L)
  1979. {
  1980. const SamplerState &s = instance()->getDefaultSamplerState();
  1981. const char *str;
  1982. if (SamplerState::getConstant(s.mipmapFilter, str))
  1983. lua_pushstring(L, str);
  1984. else
  1985. lua_pushnil(L);
  1986. lua_pushnumber(L, -s.lodBias);
  1987. return 2;
  1988. }
  1989. int w_setLineWidth(lua_State *L)
  1990. {
  1991. float width = (float)luaL_checknumber(L, 1);
  1992. instance()->setLineWidth(width);
  1993. return 0;
  1994. }
  1995. int w_setLineStyle(lua_State *L)
  1996. {
  1997. Graphics::LineStyle style;
  1998. const char *str = luaL_checkstring(L, 1);
  1999. if (!Graphics::getConstant(str, style))
  2000. return luax_enumerror(L, "line style", Graphics::getConstants(style), str);
  2001. instance()->setLineStyle(style);
  2002. return 0;
  2003. }
  2004. int w_setLineJoin(lua_State *L)
  2005. {
  2006. Graphics::LineJoin join;
  2007. const char *str = luaL_checkstring(L, 1);
  2008. if (!Graphics::getConstant(str, join))
  2009. return luax_enumerror(L, "line join", Graphics::getConstants(join), str);
  2010. instance()->setLineJoin(join);
  2011. return 0;
  2012. }
  2013. int w_getLineWidth(lua_State *L)
  2014. {
  2015. lua_pushnumber(L, instance()->getLineWidth());
  2016. return 1;
  2017. }
  2018. int w_getLineStyle(lua_State *L)
  2019. {
  2020. Graphics::LineStyle style = instance()->getLineStyle();
  2021. const char *str;
  2022. if (!Graphics::getConstant(style, str))
  2023. return luaL_error(L, "Unknown line style");
  2024. lua_pushstring(L, str);
  2025. return 1;
  2026. }
  2027. int w_getLineJoin(lua_State *L)
  2028. {
  2029. Graphics::LineJoin join = instance()->getLineJoin();
  2030. const char *str;
  2031. if (!Graphics::getConstant(join, str))
  2032. return luaL_error(L, "Unknown line join");
  2033. lua_pushstring(L, str);
  2034. return 1;
  2035. }
  2036. int w_setPointSize(lua_State *L)
  2037. {
  2038. float size = (float)luaL_checknumber(L, 1);
  2039. instance()->setPointSize(size);
  2040. return 0;
  2041. }
  2042. int w_getPointSize(lua_State *L)
  2043. {
  2044. lua_pushnumber(L, instance()->getPointSize());
  2045. return 1;
  2046. }
  2047. int w_setDepthMode(lua_State *L)
  2048. {
  2049. if (lua_isnoneornil(L, 1) && lua_isnoneornil(L, 2))
  2050. luax_catchexcept(L, [&]() { instance()->setDepthMode(); });
  2051. else
  2052. {
  2053. CompareMode compare = COMPARE_ALWAYS;
  2054. const char *str = luaL_checkstring(L, 1);
  2055. bool write = luax_checkboolean(L, 2);
  2056. if (!getConstant(str, compare))
  2057. return luax_enumerror(L, "compare mode", getConstants(compare), str);
  2058. luax_catchexcept(L, [&]() { instance()->setDepthMode(compare, write); });
  2059. }
  2060. return 0;
  2061. }
  2062. int w_getDepthMode(lua_State *L)
  2063. {
  2064. CompareMode compare = COMPARE_ALWAYS;
  2065. bool write = false;
  2066. instance()->getDepthMode(compare, write);
  2067. const char *str;
  2068. if (!getConstant(compare, str))
  2069. return luaL_error(L, "Unknown compare mode");
  2070. lua_pushstring(L, str);
  2071. luax_pushboolean(L, write);
  2072. return 2;
  2073. }
  2074. int w_setMeshCullMode(lua_State *L)
  2075. {
  2076. const char *str = luaL_checkstring(L, 1);
  2077. CullMode mode;
  2078. if (!getConstant(str, mode))
  2079. return luax_enumerror(L, "cull mode", getConstants(mode), str);
  2080. luax_catchexcept(L, [&]() { instance()->setMeshCullMode(mode); });
  2081. return 0;
  2082. }
  2083. int w_getMeshCullMode(lua_State *L)
  2084. {
  2085. CullMode mode = instance()->getMeshCullMode();
  2086. const char *str;
  2087. if (!getConstant(mode, str))
  2088. return luaL_error(L, "Unknown cull mode");
  2089. lua_pushstring(L, str);
  2090. return 1;
  2091. }
  2092. int w_setFrontFaceWinding(lua_State *L)
  2093. {
  2094. const char *str = luaL_checkstring(L, 1);
  2095. Winding winding;
  2096. if (!getConstant(str, winding))
  2097. return luax_enumerror(L, "vertex winding", getConstants(winding), str);
  2098. luax_catchexcept(L, [&]() { instance()->setFrontFaceWinding(winding); });
  2099. return 0;
  2100. }
  2101. int w_getFrontFaceWinding(lua_State *L)
  2102. {
  2103. Winding winding = instance()->getFrontFaceWinding();
  2104. const char *str;
  2105. if (!getConstant(winding, str))
  2106. return luaL_error(L, "Unknown vertex winding");
  2107. lua_pushstring(L, str);
  2108. return 1;
  2109. }
  2110. int w_setWireframe(lua_State *L)
  2111. {
  2112. instance()->setWireframe(luax_checkboolean(L, 1));
  2113. return 0;
  2114. }
  2115. int w_isWireframe(lua_State *L)
  2116. {
  2117. luax_pushboolean(L, instance()->isWireframe());
  2118. return 1;
  2119. }
  2120. int w_setShader(lua_State *L)
  2121. {
  2122. if (lua_isnoneornil(L,1))
  2123. {
  2124. instance()->setShader();
  2125. return 0;
  2126. }
  2127. Shader *shader = luax_checkshader(L, 1);
  2128. instance()->setShader(shader);
  2129. return 0;
  2130. }
  2131. int w_getShader(lua_State *L)
  2132. {
  2133. Shader *shader = instance()->getShader();
  2134. if (shader)
  2135. luax_pushtype(L, shader);
  2136. else
  2137. lua_pushnil(L);
  2138. return 1;
  2139. }
  2140. int w_getSupported(lua_State *L)
  2141. {
  2142. const Graphics::Capabilities &caps = instance()->getCapabilities();
  2143. if (lua_istable(L, 1))
  2144. lua_pushvalue(L, 1);
  2145. else
  2146. lua_createtable(L, 0, (int) Graphics::FEATURE_MAX_ENUM);
  2147. for (int i = 0; i < (int) Graphics::FEATURE_MAX_ENUM; i++)
  2148. {
  2149. auto feature = (Graphics::Feature) i;
  2150. const char *name = nullptr;
  2151. if (!Graphics::getConstant(feature, name))
  2152. continue;
  2153. luax_pushboolean(L, caps.features[i]);
  2154. lua_setfield(L, -2, name);
  2155. }
  2156. return 1;
  2157. }
  2158. int w_getTextureFormats(lua_State *L)
  2159. {
  2160. luaL_checktype(L, 1, LUA_TTABLE);
  2161. bool rt = luax_checkboolflag(L, 1, Texture::getConstant(Texture::SETTING_RENDER_TARGET));
  2162. bool linear = luax_boolflag(L, 1, Texture::getConstant(Texture::SETTING_LINEAR), false);
  2163. bool computewrite = luax_boolflag(L, 1, Texture::getConstant(Texture::SETTING_COMPUTE_WRITE), false);
  2164. OptionalBool readable;
  2165. lua_getfield(L, 1, Texture::getConstant(Texture::SETTING_READABLE));
  2166. if (!lua_isnoneornil(L, -1))
  2167. readable.set(luax_checkboolean(L, -1));
  2168. lua_pop(L, 1);
  2169. if (lua_istable(L, 2))
  2170. lua_pushvalue(L, 2);
  2171. else
  2172. lua_createtable(L, 0, (int) PIXELFORMAT_MAX_ENUM);
  2173. for (int i = 0; i < (int) PIXELFORMAT_MAX_ENUM; i++)
  2174. {
  2175. PixelFormat format = (PixelFormat) i;
  2176. const char *name = nullptr;
  2177. if (format == PIXELFORMAT_UNKNOWN || !love::getConstant(format, name))
  2178. continue;
  2179. if (rt && isPixelFormatDepth(format))
  2180. continue;
  2181. bool sRGB = isGammaCorrect() && !linear;
  2182. uint32 usage = PIXELFORMATUSAGEFLAGS_NONE;
  2183. if (rt)
  2184. usage |= PIXELFORMATUSAGEFLAGS_RENDERTARGET;
  2185. if (readable.get(!isPixelFormatDepthStencil(format)))
  2186. usage |= PIXELFORMATUSAGEFLAGS_SAMPLE;
  2187. if (computewrite)
  2188. usage |= PIXELFORMATUSAGEFLAGS_COMPUTEWRITE;
  2189. luax_pushboolean(L, instance()->isPixelFormatSupported(format, (PixelFormatUsageFlags) usage, sRGB));
  2190. lua_setfield(L, -2, name);
  2191. }
  2192. return 1;
  2193. }
  2194. static int w__getFormats(lua_State *L, int idx, bool (*isFormatSupported)(PixelFormat), bool (*ignore)(PixelFormat))
  2195. {
  2196. if (lua_istable(L, idx))
  2197. lua_pushvalue(L, idx);
  2198. else
  2199. lua_createtable(L, 0, (int) PIXELFORMAT_MAX_ENUM);
  2200. for (int i = 0; i < (int) PIXELFORMAT_MAX_ENUM; i++)
  2201. {
  2202. PixelFormat format = (PixelFormat) i;
  2203. const char *name = nullptr;
  2204. if (format == PIXELFORMAT_UNKNOWN || !love::getConstant(format, name) || ignore(format))
  2205. continue;
  2206. luax_pushboolean(L, isFormatSupported(format));
  2207. lua_setfield(L, -2, name);
  2208. }
  2209. return 1;
  2210. }
  2211. int w_getCanvasFormats(lua_State *L)
  2212. {
  2213. luax_markdeprecated(L, 1, "love.graphics.getCanvasFormats", API_FUNCTION, DEPRECATED_REPLACED, "love.graphics.getTextureFormats");
  2214. bool (*supported)(PixelFormat);
  2215. int idx = 1;
  2216. if (lua_type(L, 1) == LUA_TBOOLEAN)
  2217. {
  2218. idx = 2;
  2219. if (luax_checkboolean(L, 1))
  2220. {
  2221. supported = [](PixelFormat format) -> bool
  2222. {
  2223. const uint32 usage = PIXELFORMATUSAGEFLAGS_SAMPLE | PIXELFORMATUSAGEFLAGS_RENDERTARGET;
  2224. return instance()->isPixelFormatSupported(format, (PixelFormatUsageFlags) usage, false);
  2225. };
  2226. }
  2227. else
  2228. {
  2229. supported = [](PixelFormat format) -> bool
  2230. {
  2231. return instance()->isPixelFormatSupported(format, PIXELFORMATUSAGEFLAGS_RENDERTARGET, false);
  2232. };
  2233. }
  2234. }
  2235. else
  2236. {
  2237. supported = [](PixelFormat format) -> bool
  2238. {
  2239. bool readable = !isPixelFormatDepthStencil(format);
  2240. uint32 usage = PIXELFORMATUSAGEFLAGS_RENDERTARGET;
  2241. if (readable)
  2242. usage |= PIXELFORMATUSAGEFLAGS_SAMPLE;
  2243. return instance()->isPixelFormatSupported(format, (PixelFormatUsageFlags) usage, false);
  2244. };
  2245. }
  2246. return w__getFormats(L, idx, supported, isPixelFormatCompressed);
  2247. }
  2248. int w_getImageFormats(lua_State *L)
  2249. {
  2250. luax_markdeprecated(L, 1, "love.graphics.getImageFormats", API_FUNCTION, DEPRECATED_REPLACED, "love.graphics.getTextureFormats");
  2251. const auto supported = [](PixelFormat format) -> bool
  2252. {
  2253. return instance()->isPixelFormatSupported(format, PIXELFORMATUSAGEFLAGS_SAMPLE, false);
  2254. };
  2255. const auto ignore = [](PixelFormat format) -> bool
  2256. {
  2257. return !(image::ImageData::validPixelFormat(format) || isPixelFormatCompressed(format));
  2258. };
  2259. return w__getFormats(L, 1, supported, ignore);
  2260. }
  2261. int w_getTextureTypes(lua_State *L)
  2262. {
  2263. const Graphics::Capabilities &caps = instance()->getCapabilities();
  2264. if (lua_istable(L, 1))
  2265. lua_pushvalue(L, 1);
  2266. else
  2267. lua_createtable(L, 0, (int) TEXTURE_MAX_ENUM);
  2268. for (int i = 0; i < (int) TEXTURE_MAX_ENUM; i++)
  2269. {
  2270. TextureType textype = (TextureType) i;
  2271. const char *name = nullptr;
  2272. if (!Texture::getConstant(textype, name))
  2273. continue;
  2274. luax_pushboolean(L, caps.textureTypes[i]);
  2275. lua_setfield(L, -2, name);
  2276. }
  2277. return 1;
  2278. }
  2279. int w_getRendererInfo(lua_State *L)
  2280. {
  2281. Graphics::RendererInfo info;
  2282. luax_catchexcept(L, [&](){ info = instance()->getRendererInfo(); });
  2283. luax_pushstring(L, info.name);
  2284. luax_pushstring(L, info.version);
  2285. luax_pushstring(L, info.vendor);
  2286. luax_pushstring(L, info.device);
  2287. return 4;
  2288. }
  2289. int w_getSystemLimits(lua_State *L)
  2290. {
  2291. const Graphics::Capabilities &caps = instance()->getCapabilities();
  2292. if (lua_istable(L, 1))
  2293. lua_pushvalue(L, 1);
  2294. else
  2295. lua_createtable(L, 0, (int) Graphics::LIMIT_MAX_ENUM);
  2296. for (int i = 0; i < (int) Graphics::LIMIT_MAX_ENUM; i++)
  2297. {
  2298. Graphics::SystemLimit limittype = (Graphics::SystemLimit) i;
  2299. const char *name = nullptr;
  2300. if (!Graphics::getConstant(limittype, name))
  2301. continue;
  2302. lua_pushnumber(L, caps.limits[i]);
  2303. lua_setfield(L, -2, name);
  2304. }
  2305. return 1;
  2306. }
  2307. int w_getStats(lua_State *L)
  2308. {
  2309. Graphics::Stats stats = instance()->getStats();
  2310. if (lua_istable(L, 1))
  2311. lua_pushvalue(L, 1);
  2312. else
  2313. lua_createtable(L, 0, 7);
  2314. lua_pushinteger(L, stats.drawCalls);
  2315. lua_setfield(L, -2, "drawcalls");
  2316. lua_pushinteger(L, stats.drawCallsBatched);
  2317. lua_setfield(L, -2, "drawcallsbatched");
  2318. lua_pushinteger(L, stats.renderTargetSwitches);
  2319. lua_setfield(L, -2, "canvasswitches");
  2320. lua_pushinteger(L, stats.shaderSwitches);
  2321. lua_setfield(L, -2, "shaderswitches");
  2322. lua_pushinteger(L, stats.textures);
  2323. lua_setfield(L, -2, "textures");
  2324. lua_pushinteger(L, stats.fonts);
  2325. lua_setfield(L, -2, "fonts");
  2326. lua_pushinteger(L, stats.textureMemory);
  2327. lua_setfield(L, -2, "texturememory");
  2328. return 1;
  2329. }
  2330. int w_draw(lua_State *L)
  2331. {
  2332. Drawable *drawable = nullptr;
  2333. Texture *texture = nullptr;
  2334. Quad *quad = nullptr;
  2335. int startidx = 2;
  2336. if (luax_istype(L, 2, Quad::type))
  2337. {
  2338. texture = luax_checktexture(L, 1);
  2339. quad = luax_totype<Quad>(L, 2);
  2340. startidx = 3;
  2341. }
  2342. else if (lua_isnil(L, 2) && !lua_isnoneornil(L, 3))
  2343. {
  2344. return luax_typerror(L, 2, "Quad");
  2345. }
  2346. else
  2347. {
  2348. drawable = luax_checktype<Drawable>(L, 1);
  2349. startidx = 2;
  2350. }
  2351. luax_checkstandardtransform(L, startidx, [&](const Matrix4 &m)
  2352. {
  2353. luax_catchexcept(L, [&]()
  2354. {
  2355. if (texture && quad)
  2356. instance()->draw(texture, quad, m);
  2357. else
  2358. instance()->draw(drawable, m);
  2359. });
  2360. });
  2361. return 0;
  2362. }
  2363. int w_drawLayer(lua_State *L)
  2364. {
  2365. Texture *texture = luax_checktexture(L, 1);
  2366. Quad *quad = nullptr;
  2367. int layer = (int) luaL_checkinteger(L, 2) - 1;
  2368. int startidx = 3;
  2369. if (luax_istype(L, startidx, Quad::type))
  2370. {
  2371. texture = luax_checktexture(L, 1);
  2372. quad = luax_totype<Quad>(L, startidx);
  2373. startidx++;
  2374. }
  2375. else if (lua_isnil(L, startidx) && !lua_isnoneornil(L, startidx + 1))
  2376. {
  2377. return luax_typerror(L, startidx, "Quad");
  2378. }
  2379. luax_checkstandardtransform(L, startidx, [&](const Matrix4 &m)
  2380. {
  2381. luax_catchexcept(L, [&]()
  2382. {
  2383. if (quad)
  2384. instance()->drawLayer(texture, layer, quad, m);
  2385. else
  2386. instance()->drawLayer(texture, layer, m);
  2387. });
  2388. });
  2389. return 0;
  2390. }
  2391. int w_drawInstanced(lua_State *L)
  2392. {
  2393. Mesh *t = luax_checkmesh(L, 1);
  2394. int instancecount = (int) luaL_checkinteger(L, 2);
  2395. luax_checkstandardtransform(L, 3, [&](const Matrix4 &m)
  2396. {
  2397. luax_catchexcept(L, [&]() { instance()->drawInstanced(t, m, instancecount); });
  2398. });
  2399. return 0;
  2400. }
  2401. int w_print(lua_State *L)
  2402. {
  2403. std::vector<Font::ColoredString> str;
  2404. luax_checkcoloredstring(L, 1, str);
  2405. if (luax_istype(L, 2, Font::type))
  2406. {
  2407. Font *font = luax_checkfont(L, 2);
  2408. luax_checkstandardtransform(L, 3, [&](const Matrix4 &m)
  2409. {
  2410. luax_catchexcept(L, [&](){ instance()->print(str, font, m); });
  2411. });
  2412. }
  2413. else
  2414. {
  2415. luax_checkstandardtransform(L, 2, [&](const Matrix4 &m)
  2416. {
  2417. luax_catchexcept(L, [&](){ instance()->print(str, m); });
  2418. });
  2419. }
  2420. return 0;
  2421. }
  2422. int w_printf(lua_State *L)
  2423. {
  2424. std::vector<Font::ColoredString> str;
  2425. luax_checkcoloredstring(L, 1, str);
  2426. Font *font = nullptr;
  2427. int startidx = 2;
  2428. if (luax_istype(L, startidx, Font::type))
  2429. {
  2430. font = luax_checkfont(L, startidx);
  2431. startidx++;
  2432. }
  2433. Font::AlignMode align = Font::ALIGN_LEFT;
  2434. Matrix4 m;
  2435. int formatidx = startidx + 2;
  2436. if (luax_istype(L, startidx, math::Transform::type))
  2437. {
  2438. math::Transform *tf = luax_totype<math::Transform>(L, startidx);
  2439. m = tf->getMatrix();
  2440. formatidx = startidx + 1;
  2441. }
  2442. else
  2443. {
  2444. float x = (float)luaL_checknumber(L, startidx + 0);
  2445. float y = (float)luaL_checknumber(L, startidx + 1);
  2446. float angle = (float) luaL_optnumber(L, startidx + 4, 0.0f);
  2447. float sx = (float) luaL_optnumber(L, startidx + 5, 1.0f);
  2448. float sy = (float) luaL_optnumber(L, startidx + 6, sx);
  2449. float ox = (float) luaL_optnumber(L, startidx + 7, 0.0f);
  2450. float oy = (float) luaL_optnumber(L, startidx + 8, 0.0f);
  2451. float kx = (float) luaL_optnumber(L, startidx + 9, 0.0f);
  2452. float ky = (float) luaL_optnumber(L, startidx + 10, 0.0f);
  2453. m = Matrix4(x, y, angle, sx, sy, ox, oy, kx, ky);
  2454. }
  2455. float wrap = (float)luaL_checknumber(L, formatidx);
  2456. const char *astr = lua_isnoneornil(L, formatidx + 1) ? nullptr : luaL_checkstring(L, formatidx + 1);
  2457. if (astr != nullptr && !Font::getConstant(astr, align))
  2458. return luax_enumerror(L, "alignment", Font::getConstants(align), astr);
  2459. if (font != nullptr)
  2460. luax_catchexcept(L, [&](){ instance()->printf(str, font, wrap, align, m); });
  2461. else
  2462. luax_catchexcept(L, [&](){ instance()->printf(str, wrap, align, m); });
  2463. return 0;
  2464. }
  2465. int w_points(lua_State *L)
  2466. {
  2467. // love.graphics.points has 3 variants:
  2468. // - points(x1, y1, x2, y2, ...)
  2469. // - points({x1, y1, x2, y2, ...})
  2470. // - points({{x1, y1 [, r, g, b, a]}, {x2, y2 [, r, g, b, a]}, ...})
  2471. int args = lua_gettop(L);
  2472. bool is_table = false;
  2473. bool is_table_of_tables = false;
  2474. if (args == 1 && lua_istable(L, 1))
  2475. {
  2476. is_table = true;
  2477. args = (int) luax_objlen(L, 1);
  2478. lua_rawgeti(L, 1, 1);
  2479. is_table_of_tables = lua_istable(L, -1);
  2480. lua_pop(L, 1);
  2481. }
  2482. if (args % 2 != 0 && !is_table_of_tables)
  2483. return luaL_error(L, "Number of vertex components must be a multiple of two");
  2484. int numpositions = args / 2;
  2485. if (is_table_of_tables)
  2486. numpositions = args;
  2487. Vector2 *positions = nullptr;
  2488. Colorf *colors = nullptr;
  2489. if (is_table_of_tables)
  2490. {
  2491. size_t datasize = (sizeof(Vector2) + sizeof(Colorf)) * numpositions;
  2492. uint8 *data = instance()->getScratchBuffer<uint8>(datasize);
  2493. positions = (Vector2 *) data;
  2494. colors = (Colorf *) (data + sizeof(Vector2) * numpositions);
  2495. }
  2496. else
  2497. positions = instance()->getScratchBuffer<Vector2>(numpositions);
  2498. if (is_table)
  2499. {
  2500. if (is_table_of_tables)
  2501. {
  2502. // points({{x1, y1 [, r, g, b, a]}, {x2, y2 [, r, g, b, a]}, ...})
  2503. for (int i = 0; i < args; i++)
  2504. {
  2505. lua_rawgeti(L, 1, i + 1);
  2506. for (int j = 1; j <= 6; j++)
  2507. lua_rawgeti(L, -j, j);
  2508. positions[i].x = luax_checkfloat(L, -6);
  2509. positions[i].y = luax_checkfloat(L, -5);
  2510. colors[i].r = (float) luax_optnumberclamped01(L, -4, 1.0);
  2511. colors[i].g = (float) luax_optnumberclamped01(L, -3, 1.0);
  2512. colors[i].b = (float) luax_optnumberclamped01(L, -2, 1.0);
  2513. colors[i].a = (float) luax_optnumberclamped01(L, -1, 1.0);
  2514. lua_pop(L, 7);
  2515. }
  2516. }
  2517. else
  2518. {
  2519. // points({x1, y1, x2, y2, ...})
  2520. for (int i = 0; i < numpositions; i++)
  2521. {
  2522. lua_rawgeti(L, 1, i * 2 + 1);
  2523. lua_rawgeti(L, 1, i * 2 + 2);
  2524. positions[i].x = luax_checkfloat(L, -2);
  2525. positions[i].y = luax_checkfloat(L, -1);
  2526. lua_pop(L, 2);
  2527. }
  2528. }
  2529. }
  2530. else
  2531. {
  2532. for (int i = 0; i < numpositions; i++)
  2533. {
  2534. positions[i].x = luax_checkfloat(L, i * 2 + 1);
  2535. positions[i].y = luax_checkfloat(L, i * 2 + 2);
  2536. }
  2537. }
  2538. luax_catchexcept(L, [&](){ instance()->points(positions, colors, numpositions); });
  2539. return 0;
  2540. }
  2541. int w_line(lua_State *L)
  2542. {
  2543. int args = lua_gettop(L);
  2544. int arg1type = lua_type(L, 1);
  2545. bool is_table = false;
  2546. if (args == 1 && arg1type == LUA_TTABLE)
  2547. {
  2548. args = (int) luax_objlen(L, 1);
  2549. is_table = true;
  2550. }
  2551. if (arg1type != LUA_TTABLE && arg1type != LUA_TNUMBER)
  2552. return luax_typerror(L, 1, "table or number");
  2553. else if (args % 2 != 0)
  2554. return luaL_error(L, "Number of vertex components must be a multiple of two.");
  2555. else if (args < 4)
  2556. return luaL_error(L, "Need at least two vertices to draw a line.");
  2557. int numvertices = args / 2;
  2558. Vector2 *coords = instance()->getScratchBuffer<Vector2>(numvertices);
  2559. if (is_table)
  2560. {
  2561. for (int i = 0; i < numvertices; ++i)
  2562. {
  2563. lua_rawgeti(L, 1, (i * 2) + 1);
  2564. lua_rawgeti(L, 1, (i * 2) + 2);
  2565. coords[i].x = luax_checkfloat(L, -2);
  2566. coords[i].y = luax_checkfloat(L, -1);
  2567. lua_pop(L, 2);
  2568. }
  2569. }
  2570. else
  2571. {
  2572. for (int i = 0; i < numvertices; ++i)
  2573. {
  2574. coords[i].x = luax_checkfloat(L, (i * 2) + 1);
  2575. coords[i].y = luax_checkfloat(L, (i * 2) + 2);
  2576. }
  2577. }
  2578. luax_catchexcept(L,
  2579. [&](){ instance()->polyline(coords, numvertices); }
  2580. );
  2581. return 0;
  2582. }
  2583. int w_rectangle(lua_State *L)
  2584. {
  2585. Graphics::DrawMode mode;
  2586. const char *str = luaL_checkstring(L, 1);
  2587. if (!Graphics::getConstant(str, mode))
  2588. return luax_enumerror(L, "draw mode", Graphics::getConstants(mode), str);
  2589. float x = (float)luaL_checknumber(L, 2);
  2590. float y = (float)luaL_checknumber(L, 3);
  2591. float w = (float)luaL_checknumber(L, 4);
  2592. float h = (float)luaL_checknumber(L, 5);
  2593. if (lua_isnoneornil(L, 6))
  2594. {
  2595. luax_catchexcept(L, [&](){ instance()->rectangle(mode, x, y, w, h); });
  2596. return 0;
  2597. }
  2598. float rx = (float)luaL_optnumber(L, 6, 0.0);
  2599. float ry = (float)luaL_optnumber(L, 7, rx);
  2600. if (lua_isnoneornil(L, 8))
  2601. luax_catchexcept(L, [&](){ instance()->rectangle(mode, x, y, w, h, rx, ry); });
  2602. else
  2603. {
  2604. int points = (int) luaL_checkinteger(L, 8);
  2605. luax_catchexcept(L, [&](){ instance()->rectangle(mode, x, y, w, h, rx, ry, points); });
  2606. }
  2607. return 0;
  2608. }
  2609. int w_circle(lua_State *L)
  2610. {
  2611. Graphics::DrawMode mode;
  2612. const char *str = luaL_checkstring(L, 1);
  2613. if (!Graphics::getConstant(str, mode))
  2614. return luax_enumerror(L, "draw mode", Graphics::getConstants(mode), str);
  2615. float x = (float)luaL_checknumber(L, 2);
  2616. float y = (float)luaL_checknumber(L, 3);
  2617. float radius = (float)luaL_checknumber(L, 4);
  2618. if (lua_isnoneornil(L, 5))
  2619. luax_catchexcept(L, [&](){ instance()->circle(mode, x, y, radius); });
  2620. else
  2621. {
  2622. int points = (int) luaL_checkinteger(L, 5);
  2623. luax_catchexcept(L, [&](){ instance()->circle(mode, x, y, radius, points); });
  2624. }
  2625. return 0;
  2626. }
  2627. int w_ellipse(lua_State *L)
  2628. {
  2629. Graphics::DrawMode mode;
  2630. const char *str = luaL_checkstring(L, 1);
  2631. if (!Graphics::getConstant(str, mode))
  2632. return luax_enumerror(L, "draw mode", Graphics::getConstants(mode), str);
  2633. float x = (float)luaL_checknumber(L, 2);
  2634. float y = (float)luaL_checknumber(L, 3);
  2635. float a = (float)luaL_checknumber(L, 4);
  2636. float b = (float)luaL_optnumber(L, 5, a);
  2637. if (lua_isnoneornil(L, 6))
  2638. luax_catchexcept(L, [&](){ instance()->ellipse(mode, x, y, a, b); });
  2639. else
  2640. {
  2641. int points = (int) luaL_checkinteger(L, 6);
  2642. luax_catchexcept(L, [&](){ instance()->ellipse(mode, x, y, a, b, points); });
  2643. }
  2644. return 0;
  2645. }
  2646. int w_arc(lua_State *L)
  2647. {
  2648. Graphics::DrawMode drawmode;
  2649. const char *drawstr = luaL_checkstring(L, 1);
  2650. if (!Graphics::getConstant(drawstr, drawmode))
  2651. return luax_enumerror(L, "draw mode", Graphics::getConstants(drawmode), drawstr);
  2652. int startidx = 2;
  2653. Graphics::ArcMode arcmode = Graphics::ARC_PIE;
  2654. if (lua_type(L, 2) == LUA_TSTRING)
  2655. {
  2656. const char *arcstr = luaL_checkstring(L, 2);
  2657. if (!Graphics::getConstant(arcstr, arcmode))
  2658. return luax_enumerror(L, "arc mode", Graphics::getConstants(arcmode), arcstr);
  2659. startidx = 3;
  2660. }
  2661. float x = (float) luaL_checknumber(L, startidx + 0);
  2662. float y = (float) luaL_checknumber(L, startidx + 1);
  2663. float radius = (float) luaL_checknumber(L, startidx + 2);
  2664. float angle1 = (float) luaL_checknumber(L, startidx + 3);
  2665. float angle2 = (float) luaL_checknumber(L, startidx + 4);
  2666. if (lua_isnoneornil(L, startidx + 5))
  2667. luax_catchexcept(L, [&](){ instance()->arc(drawmode, arcmode, x, y, radius, angle1, angle2); });
  2668. else
  2669. {
  2670. int points = (int) luaL_checkinteger(L, startidx + 5);
  2671. luax_catchexcept(L, [&](){ instance()->arc(drawmode, arcmode, x, y, radius, angle1, angle2, points); });
  2672. }
  2673. return 0;
  2674. }
  2675. int w_polygon(lua_State *L)
  2676. {
  2677. int args = lua_gettop(L) - 1;
  2678. Graphics::DrawMode mode;
  2679. const char *str = luaL_checkstring(L, 1);
  2680. if (!Graphics::getConstant(str, mode))
  2681. return luax_enumerror(L, "draw mode", Graphics::getConstants(mode), str);
  2682. bool is_table = false;
  2683. if (args == 1 && lua_istable(L, 2))
  2684. {
  2685. args = (int) luax_objlen(L, 2);
  2686. is_table = true;
  2687. }
  2688. if (args % 2 != 0)
  2689. return luaL_error(L, "Number of vertex components must be a multiple of two");
  2690. else if (args < 6)
  2691. return luaL_error(L, "Need at least three vertices to draw a polygon");
  2692. int numvertices = args / 2;
  2693. // fetch coords
  2694. Vector2 *coords = instance()->getScratchBuffer<Vector2>(numvertices + 1);
  2695. if (is_table)
  2696. {
  2697. for (int i = 0; i < numvertices; ++i)
  2698. {
  2699. lua_rawgeti(L, 2, (i * 2) + 1);
  2700. lua_rawgeti(L, 2, (i * 2) + 2);
  2701. coords[i].x = luax_checkfloat(L, -2);
  2702. coords[i].y = luax_checkfloat(L, -1);
  2703. lua_pop(L, 2);
  2704. }
  2705. }
  2706. else
  2707. {
  2708. for (int i = 0; i < numvertices; ++i)
  2709. {
  2710. coords[i].x = luax_checkfloat(L, (i * 2) + 2);
  2711. coords[i].y = luax_checkfloat(L, (i * 2) + 3);
  2712. }
  2713. }
  2714. // make a closed loop
  2715. coords[numvertices] = coords[0];
  2716. luax_catchexcept(L, [&](){ instance()->polygon(mode, coords, numvertices+1); });
  2717. return 0;
  2718. }
  2719. int w_dispatchThreadgroups(lua_State* L)
  2720. {
  2721. Shader *shader = luax_checkshader(L, 1);
  2722. int x = (int) luaL_checkinteger(L, 2);
  2723. int y = (int) luaL_optinteger(L, 3, 1);
  2724. int z = (int) luaL_optinteger(L, 4, 1);
  2725. luax_catchexcept(L, [&](){ instance()->dispatchThreadgroups(shader, x, y, z); });
  2726. return 0;
  2727. }
  2728. int w_copyBuffer(lua_State *L)
  2729. {
  2730. Buffer *source = luax_checkbuffer(L, 1);
  2731. Buffer *dest = luax_checkbuffer(L, 2);
  2732. ptrdiff_t sourceoffset = luaL_optinteger(L, 3, 0);
  2733. ptrdiff_t destoffset = luaL_optinteger(L, 4, 0);
  2734. ptrdiff_t size = std::min(source->getSize() - sourceoffset, dest->getSize() - destoffset);
  2735. if (!lua_isnoneornil(L, 5))
  2736. size = luaL_checkinteger(L, 5);
  2737. if (sourceoffset < 0 || destoffset < 0)
  2738. return luaL_error(L, "copyBuffer offsets cannot be negative.");
  2739. if (size <= 0)
  2740. return luaL_error(L, "copyBuffer size must be greater than 0.");
  2741. luax_catchexcept(L, [&](){ instance()->copyBuffer(source, dest, sourceoffset, destoffset, size); });
  2742. return 0;
  2743. }
  2744. int w_copyBufferToTexture(lua_State *L)
  2745. {
  2746. Buffer *source = luax_checkbuffer(L, 1);
  2747. Texture *dest = luax_checktexture(L, 2);
  2748. ptrdiff_t sourceoffset = luaL_optinteger(L, 3, 0);
  2749. if (sourceoffset < 0)
  2750. return luaL_error(L, "copyBufferToTexture source offset cannot be negative.");
  2751. int sourcewidth = (int) luaL_optinteger(L, 4, 0);
  2752. int slice = 0;
  2753. int mipmap = 0;
  2754. if (dest->getTextureType() != TEXTURE_2D)
  2755. slice = (int) luaL_checkinteger(L, 5) - 1;
  2756. mipmap = (int) luaL_optinteger(L, 6, 1) - 1;
  2757. Rect rect = {0, 0, dest->getPixelWidth(mipmap), dest->getPixelHeight(mipmap)};
  2758. if (!lua_isnoneornil(L, 7))
  2759. {
  2760. rect.x = (int) luaL_checkinteger(L, 7);
  2761. rect.y = (int) luaL_checkinteger(L, 8);
  2762. rect.w = (int) luaL_checkinteger(L, 9);
  2763. rect.h = (int) luaL_checkinteger(L, 10);
  2764. }
  2765. luax_catchexcept(L, [&](){ instance()->copyBufferToTexture(source, dest, sourceoffset, sourcewidth, slice, mipmap, rect); });
  2766. return 0;
  2767. }
  2768. int w_copyTextureToBuffer(lua_State *L)
  2769. {
  2770. Texture *source = luax_checktexture(L, 1);
  2771. Buffer *dest = luax_checkbuffer(L, 2);
  2772. int slice = 0;
  2773. int mipmap = 0;
  2774. if (source->getTextureType() != TEXTURE_2D)
  2775. slice = (int) luaL_checkinteger(L, 3) - 1;
  2776. mipmap = (int) luaL_optinteger(L, 4, 1) - 1;
  2777. Rect rect = {0, 0, source->getPixelWidth(mipmap), source->getPixelHeight(mipmap)};
  2778. if (!lua_isnoneornil(L, 5))
  2779. {
  2780. rect.x = (int) luaL_checkinteger(L, 5);
  2781. rect.y = (int) luaL_checkinteger(L, 6);
  2782. rect.w = (int) luaL_checkinteger(L, 7);
  2783. rect.h = (int) luaL_checkinteger(L, 8);
  2784. }
  2785. ptrdiff_t destoffset = luaL_optinteger(L, 9, 0);
  2786. if (destoffset < 0)
  2787. return luaL_error(L, "copyTextureToBuffer dest offset cannot be negative.");
  2788. int destwidth = (int) luaL_optinteger(L, 10, 0);
  2789. luax_catchexcept(L, [&](){ instance()->copyTextureToBuffer(source, dest, slice, mipmap, rect, destoffset, destwidth); });
  2790. return 0;
  2791. }
  2792. int w_flushBatch(lua_State *)
  2793. {
  2794. instance()->flushBatchedDraws();
  2795. return 0;
  2796. }
  2797. int w_getStackDepth(lua_State *L)
  2798. {
  2799. lua_pushnumber(L, instance()->getStackDepth());
  2800. return 1;
  2801. }
  2802. int w_push(lua_State *L)
  2803. {
  2804. Graphics::StackType stype = Graphics::STACK_TRANSFORM;
  2805. const char *sname = lua_isnoneornil(L, 1) ? nullptr : luaL_checkstring(L, 1);
  2806. if (sname && !Graphics::getConstant(sname, stype))
  2807. return luax_enumerror(L, "graphics stack type", Graphics::getConstants(stype), sname);
  2808. luax_catchexcept(L, [&](){ instance()->push(stype); });
  2809. if (luax_istype(L, 2, math::Transform::type))
  2810. {
  2811. math::Transform *t = luax_totype<math::Transform>(L, 2);
  2812. luax_catchexcept(L, [&]() { instance()->applyTransform(t); });
  2813. }
  2814. return 0;
  2815. }
  2816. int w_pop(lua_State *L)
  2817. {
  2818. luax_catchexcept(L, [&](){ instance()->pop(); });
  2819. return 0;
  2820. }
  2821. int w_rotate(lua_State *L)
  2822. {
  2823. float angle = (float)luaL_checknumber(L, 1);
  2824. instance()->rotate(angle);
  2825. return 0;
  2826. }
  2827. int w_scale(lua_State *L)
  2828. {
  2829. float sx = (float)luaL_optnumber(L, 1, 1.0f);
  2830. float sy = (float)luaL_optnumber(L, 2, sx);
  2831. instance()->scale(sx, sy);
  2832. return 0;
  2833. }
  2834. int w_translate(lua_State *L)
  2835. {
  2836. float x = (float)luaL_checknumber(L, 1);
  2837. float y = (float)luaL_checknumber(L, 2);
  2838. instance()->translate(x, y);
  2839. return 0;
  2840. }
  2841. int w_shear(lua_State *L)
  2842. {
  2843. float kx = (float)luaL_checknumber(L, 1);
  2844. float ky = (float)luaL_checknumber(L, 2);
  2845. instance()->shear(kx, ky);
  2846. return 0;
  2847. }
  2848. int w_origin(lua_State * /*L*/)
  2849. {
  2850. instance()->origin();
  2851. return 0;
  2852. }
  2853. int w_applyTransform(lua_State *L)
  2854. {
  2855. math::Transform *t = math::luax_checktransform(L, 1);
  2856. luax_catchexcept(L, [&]() { instance()->applyTransform(t); });
  2857. return 0;
  2858. }
  2859. int w_replaceTransform(lua_State *L)
  2860. {
  2861. math::Transform *t = math::luax_checktransform(L, 1);
  2862. luax_catchexcept(L, [&]() { instance()->replaceTransform(t); });
  2863. return 0;
  2864. }
  2865. int w_transformPoint(lua_State *L)
  2866. {
  2867. Vector2 p;
  2868. p.x = (float) luaL_checknumber(L, 1);
  2869. p.y = (float) luaL_checknumber(L, 2);
  2870. p = instance()->transformPoint(p);
  2871. lua_pushnumber(L, p.x);
  2872. lua_pushnumber(L, p.y);
  2873. return 2;
  2874. }
  2875. int w_inverseTransformPoint(lua_State *L)
  2876. {
  2877. Vector2 p;
  2878. p.x = (float) luaL_checknumber(L, 1);
  2879. p.y = (float) luaL_checknumber(L, 2);
  2880. p = instance()->inverseTransformPoint(p);
  2881. lua_pushnumber(L, p.x);
  2882. lua_pushnumber(L, p.y);
  2883. return 2;
  2884. }
  2885. // List of functions to wrap.
  2886. static const luaL_Reg functions[] =
  2887. {
  2888. { "reset", w_reset },
  2889. { "clear", w_clear },
  2890. { "discard", w_discard },
  2891. { "present", w_present },
  2892. { "newCanvas", w_newCanvas },
  2893. { "newTexture", w_newTexture },
  2894. { "newCubeTexture", w_newCubeTexture },
  2895. { "newArrayTexture", w_newArrayTexture },
  2896. { "newVolumeTexture", w_newVolumeTexture },
  2897. { "newQuad", w_newQuad },
  2898. { "newFont", w_newFont },
  2899. { "newImageFont", w_newImageFont },
  2900. { "newSpriteBatch", w_newSpriteBatch },
  2901. { "newParticleSystem", w_newParticleSystem },
  2902. { "newShader", w_newShader },
  2903. { "newComputeShader", w_newComputeShader },
  2904. { "newBuffer", w_newBuffer },
  2905. { "newVertexBuffer", w_newVertexBuffer },
  2906. { "newIndexBuffer", w_newIndexBuffer },
  2907. { "newMesh", w_newMesh },
  2908. { "newText", w_newText },
  2909. { "_newVideo", w_newVideo },
  2910. { "validateShader", w_validateShader },
  2911. { "setCanvas", w_setCanvas },
  2912. { "getCanvas", w_getCanvas },
  2913. { "setColor", w_setColor },
  2914. { "getColor", w_getColor },
  2915. { "setBackgroundColor", w_setBackgroundColor },
  2916. { "getBackgroundColor", w_getBackgroundColor },
  2917. { "setNewFont", w_setNewFont },
  2918. { "setFont", w_setFont },
  2919. { "getFont", w_getFont },
  2920. { "setColorMask", w_setColorMask },
  2921. { "getColorMask", w_getColorMask },
  2922. { "setBlendMode", w_setBlendMode },
  2923. { "getBlendMode", w_getBlendMode },
  2924. { "setBlendState", w_setBlendState },
  2925. { "getBlendState", w_getBlendState },
  2926. { "setDefaultFilter", w_setDefaultFilter },
  2927. { "getDefaultFilter", w_getDefaultFilter },
  2928. { "setDefaultMipmapFilter", w_setDefaultMipmapFilter },
  2929. { "getDefaultMipmapFilter", w_getDefaultMipmapFilter },
  2930. { "setLineWidth", w_setLineWidth },
  2931. { "setLineStyle", w_setLineStyle },
  2932. { "setLineJoin", w_setLineJoin },
  2933. { "getLineWidth", w_getLineWidth },
  2934. { "getLineStyle", w_getLineStyle },
  2935. { "getLineJoin", w_getLineJoin },
  2936. { "setPointSize", w_setPointSize },
  2937. { "getPointSize", w_getPointSize },
  2938. { "setDepthMode", w_setDepthMode },
  2939. { "getDepthMode", w_getDepthMode },
  2940. { "setMeshCullMode", w_setMeshCullMode },
  2941. { "getMeshCullMode", w_getMeshCullMode },
  2942. { "setFrontFaceWinding", w_setFrontFaceWinding },
  2943. { "getFrontFaceWinding", w_getFrontFaceWinding },
  2944. { "setWireframe", w_setWireframe },
  2945. { "isWireframe", w_isWireframe },
  2946. { "setShader", w_setShader },
  2947. { "getShader", w_getShader },
  2948. { "getSupported", w_getSupported },
  2949. { "getTextureFormats", w_getTextureFormats },
  2950. { "getRendererInfo", w_getRendererInfo },
  2951. { "getSystemLimits", w_getSystemLimits },
  2952. { "getTextureTypes", w_getTextureTypes },
  2953. { "getStats", w_getStats },
  2954. { "captureScreenshot", w_captureScreenshot },
  2955. { "draw", w_draw },
  2956. { "drawLayer", w_drawLayer },
  2957. { "drawInstanced", w_drawInstanced },
  2958. { "print", w_print },
  2959. { "printf", w_printf },
  2960. { "dispatchThreadgroups", w_dispatchThreadgroups },
  2961. { "copyBuffer", w_copyBuffer },
  2962. { "copyBufferToTexture", w_copyBufferToTexture },
  2963. { "copyTextureToBuffer", w_copyTextureToBuffer },
  2964. { "isCreated", w_isCreated },
  2965. { "isActive", w_isActive },
  2966. { "isGammaCorrect", w_isGammaCorrect },
  2967. { "getWidth", w_getWidth },
  2968. { "getHeight", w_getHeight },
  2969. { "getDimensions", w_getDimensions },
  2970. { "getPixelWidth", w_getPixelWidth },
  2971. { "getPixelHeight", w_getPixelHeight },
  2972. { "getPixelDimensions", w_getPixelDimensions },
  2973. { "getDPIScale", w_getDPIScale },
  2974. { "setScissor", w_setScissor },
  2975. { "intersectScissor", w_intersectScissor },
  2976. { "getScissor", w_getScissor },
  2977. { "stencil", w_stencil },
  2978. { "setStencilTest", w_setStencilTest },
  2979. { "getStencilTest", w_getStencilTest },
  2980. { "points", w_points },
  2981. { "line", w_line },
  2982. { "rectangle", w_rectangle },
  2983. { "circle", w_circle },
  2984. { "ellipse", w_ellipse },
  2985. { "arc", w_arc },
  2986. { "polygon", w_polygon },
  2987. { "flushBatch", w_flushBatch },
  2988. { "getStackDepth", w_getStackDepth },
  2989. { "push", w_push },
  2990. { "pop", w_pop },
  2991. { "rotate", w_rotate },
  2992. { "scale", w_scale },
  2993. { "translate", w_translate },
  2994. { "shear", w_shear },
  2995. { "origin", w_origin },
  2996. { "applyTransform", w_applyTransform },
  2997. { "replaceTransform", w_replaceTransform },
  2998. { "transformPoint", w_transformPoint },
  2999. { "inverseTransformPoint", w_inverseTransformPoint },
  3000. // Deprecated
  3001. { "newImage", w_newImage },
  3002. { "newArrayImage", w_newArrayImage },
  3003. { "newVolumeImage", w_newVolumeImage },
  3004. { "newCubeImage", w_newCubeImage },
  3005. { "getCanvasFormats", w_getCanvasFormats },
  3006. { "getImageFormats", w_getImageFormats },
  3007. { 0, 0 }
  3008. };
  3009. static int luaopen_drawable(lua_State *L)
  3010. {
  3011. return luax_register_type(L, &Drawable::type, nullptr);
  3012. }
  3013. // Types for this module.
  3014. static const lua_CFunction types[] =
  3015. {
  3016. luaopen_drawable,
  3017. luaopen_texture,
  3018. luaopen_font,
  3019. luaopen_quad,
  3020. luaopen_graphicsbuffer,
  3021. luaopen_spritebatch,
  3022. luaopen_particlesystem,
  3023. luaopen_shader,
  3024. luaopen_mesh,
  3025. luaopen_text,
  3026. luaopen_video,
  3027. 0
  3028. };
  3029. extern "C" int luaopen_love_graphics(lua_State *L)
  3030. {
  3031. Graphics *instance = Graphics::createInstance();
  3032. if (instance == nullptr)
  3033. {
  3034. printf("Cannot create graphics: no supported renderer on this system.\n");
  3035. return luaL_error(L, "Cannot create graphics: no supported renderer on this system.");
  3036. }
  3037. WrappedModule w;
  3038. w.module = instance;
  3039. w.name = "graphics";
  3040. w.type = &Graphics::type;
  3041. w.functions = functions;
  3042. w.types = types;
  3043. int n = luax_register_module(L, w);
  3044. if (luaL_loadbuffer(L, (const char *)graphics_lua, sizeof(graphics_lua), "=[love \"wrap_Graphics.lua\"]") == 0)
  3045. lua_call(L, 0, 0);
  3046. else
  3047. lua_error(L);
  3048. return n;
  3049. }
  3050. } // graphics
  3051. } // love