wrap_Graphics.cpp 102 KB

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