wrap_Graphics.cpp 105 KB

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