wrap_Graphics.cpp 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092
  1. /**
  2. * Copyright (c) 2006-2018 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 <algorithm>
  38. // Shove the wrap_Graphics.lua code directly into a raw string literal.
  39. static const char graphics_lua[] =
  40. #include "wrap_Graphics.lua"
  41. ;
  42. // This is in a separate file because VS2013 has a 16KB limit for raw strings..
  43. static const char graphics_shader_lua[] =
  44. #include "wrap_GraphicsShader.lua"
  45. ;
  46. namespace love
  47. {
  48. namespace graphics
  49. {
  50. #define instance() (Module::getInstance<Graphics>(Module::M_GRAPHICS))
  51. static int luax_checkgraphicscreated(lua_State *L)
  52. {
  53. if (!instance()->isCreated())
  54. return luaL_error(L, "love.graphics cannot function without a window!");
  55. return 0;
  56. }
  57. int w_reset(lua_State *)
  58. {
  59. instance()->reset();
  60. return 0;
  61. }
  62. int w_clear(lua_State *L)
  63. {
  64. OptionalColorf color(Colorf(0.0f, 0.0f, 0.0f, 0.0f));
  65. std::vector<OptionalColorf> colors;
  66. OptionalInt stencil(0);
  67. OptionalDouble depth(1.0);
  68. int argtype = lua_type(L, 1);
  69. int startidx = -1;
  70. if (argtype == LUA_TTABLE)
  71. {
  72. int maxn = lua_gettop(L);
  73. colors.reserve(maxn);
  74. for (int i = 0; i < maxn; i++)
  75. {
  76. argtype = lua_type(L, i + 1);
  77. if (argtype == LUA_TNUMBER || argtype == LUA_TBOOLEAN)
  78. {
  79. startidx = i + 1;
  80. break;
  81. }
  82. else if (argtype == LUA_TNIL || argtype == LUA_TNONE || luax_objlen(L, i + 1) == 0)
  83. {
  84. colors.push_back(OptionalColorf());
  85. continue;
  86. }
  87. for (int j = 1; j <= 4; j++)
  88. lua_rawgeti(L, i + 1, j);
  89. OptionalColorf c;
  90. c.hasValue = true;
  91. c.value.r = (float) luaL_checknumber(L, -4);
  92. c.value.g = (float) luaL_checknumber(L, -3);
  93. c.value.b = (float) luaL_checknumber(L, -2);
  94. c.value.a = (float) luaL_optnumber(L, -1, 1.0);
  95. colors.push_back(c);
  96. lua_pop(L, 4);
  97. }
  98. }
  99. else if (argtype == LUA_TBOOLEAN)
  100. {
  101. color.hasValue = luax_toboolean(L, 1);
  102. startidx = 2;
  103. }
  104. else if (argtype != LUA_TNONE && argtype != LUA_TNIL)
  105. {
  106. color.hasValue = true;
  107. color.value.r = (float) luaL_checknumber(L, 1);
  108. color.value.g = (float) luaL_checknumber(L, 2);
  109. color.value.b = (float) luaL_checknumber(L, 3);
  110. color.value.a = (float) luaL_optnumber(L, 4, 1.0);
  111. startidx = 5;
  112. }
  113. if (startidx >= 0)
  114. {
  115. argtype = lua_type(L, startidx);
  116. if (argtype == LUA_TBOOLEAN)
  117. stencil.hasValue = luax_toboolean(L, startidx);
  118. else if (argtype == LUA_TNUMBER)
  119. stencil.value = (int) luaL_checkinteger(L, startidx);
  120. argtype = lua_type(L, startidx + 1);
  121. if (argtype == LUA_TBOOLEAN)
  122. depth.hasValue = luax_toboolean(L, startidx + 1);
  123. else if (argtype == LUA_TNUMBER)
  124. depth.value = luaL_checknumber(L, startidx + 1);
  125. }
  126. if (colors.empty())
  127. luax_catchexcept(L, [&]() { instance()->clear(color, stencil, depth); });
  128. else
  129. luax_catchexcept(L, [&]() { instance()->clear(colors, stencil, depth); });
  130. return 0;
  131. }
  132. int w_discard(lua_State *L)
  133. {
  134. std::vector<bool> colorbuffers;
  135. if (lua_istable(L, 1))
  136. {
  137. for (size_t i = 1; i <= luax_objlen(L, 1); i++)
  138. {
  139. lua_rawgeti(L, 1, i);
  140. colorbuffers.push_back(luax_optboolean(L, -1, true));
  141. lua_pop(L, 1);
  142. }
  143. }
  144. else
  145. {
  146. bool discardcolor = luax_optboolean(L, 1, true);
  147. size_t numbuffers = std::max((size_t) 1, instance()->getCanvas().colors.size());
  148. colorbuffers = std::vector<bool>(numbuffers, discardcolor);
  149. }
  150. bool depthstencil = luax_optboolean(L, 2, true);
  151. instance()->discard(colorbuffers, depthstencil);
  152. return 0;
  153. }
  154. int w_present(lua_State *L)
  155. {
  156. luax_catchexcept(L, [&]() { instance()->present(L); });
  157. return 0;
  158. }
  159. int w_isCreated(lua_State *L)
  160. {
  161. luax_pushboolean(L, instance()->isCreated());
  162. return 1;
  163. }
  164. int w_isActive(lua_State *L)
  165. {
  166. luax_pushboolean(L, instance()->isActive());
  167. return 1;
  168. }
  169. int w_isGammaCorrect(lua_State *L)
  170. {
  171. luax_pushboolean(L, graphics::isGammaCorrect());
  172. return 1;
  173. }
  174. int w_getWidth(lua_State *L)
  175. {
  176. lua_pushinteger(L, instance()->getWidth());
  177. return 1;
  178. }
  179. int w_getHeight(lua_State *L)
  180. {
  181. lua_pushinteger(L, instance()->getHeight());
  182. return 1;
  183. }
  184. int w_getDimensions(lua_State *L)
  185. {
  186. lua_pushinteger(L, instance()->getWidth());
  187. lua_pushinteger(L, instance()->getHeight());
  188. return 2;
  189. }
  190. int w_getPixelWidth(lua_State *L)
  191. {
  192. lua_pushinteger(L, instance()->getPixelWidth());
  193. return 1;
  194. }
  195. int w_getPixelHeight(lua_State *L)
  196. {
  197. lua_pushinteger(L, instance()->getPixelHeight());
  198. return 1;
  199. }
  200. int w_getPixelDimensions(lua_State *L)
  201. {
  202. lua_pushinteger(L, instance()->getPixelWidth());
  203. lua_pushinteger(L, instance()->getPixelHeight());
  204. return 2;
  205. }
  206. int w_getDPIScale(lua_State *L)
  207. {
  208. lua_pushnumber(L, instance()->getScreenDPIScale());
  209. return 1;
  210. }
  211. static Graphics::RenderTarget checkRenderTarget(lua_State *L, int idx)
  212. {
  213. lua_rawgeti(L, idx, 1);
  214. Graphics::RenderTarget target(luax_checkcanvas(L, -1), 0);
  215. lua_pop(L, 1);
  216. TextureType type = target.canvas->getTextureType();
  217. if (type == TEXTURE_2D_ARRAY || type == TEXTURE_VOLUME)
  218. target.slice = luax_checkintflag(L, idx, "layer") - 1;
  219. else if (type == TEXTURE_CUBE)
  220. target.slice = luax_checkintflag(L, idx, "face") - 1;
  221. target.mipmap = luax_intflag(L, idx, "mipmap", 1) - 1;
  222. return target;
  223. }
  224. int w_setCanvas(lua_State *L)
  225. {
  226. // Disable stencil writes.
  227. luax_catchexcept(L, [](){ instance()->stopDrawToStencilBuffer(); });
  228. // called with none -> reset to default buffer
  229. if (lua_isnoneornil(L, 1))
  230. {
  231. instance()->setCanvas();
  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_checkcanvas(L, -1), 0);
  249. if (targets.colors.back().canvas->getTextureType() != TEXTURE_2D)
  250. return luaL_error(L, "Non-2D canvases 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.canvas = luax_checkcanvas(L, -1);
  264. lua_pop(L, 1);
  265. if (targets.depthStencil.canvas == nullptr && (targets.temporaryRTFlags & tempdepthflag) == 0)
  266. targets.temporaryRTFlags |= luax_boolflag(L, 1, "depth", false) ? tempdepthflag : 0;
  267. if (targets.depthStencil.canvas == 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_checkcanvas(L, i), 0);
  275. TextureType type = target.canvas->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().canvas != nullptr)
  295. instance()->setCanvas(targets);
  296. else
  297. instance()->setCanvas();
  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.canvas);
  305. lua_rawseti(L, -2, 1);
  306. TextureType type = rt.canvas->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()->getCanvas();
  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.canvas != nullptr;
  330. if (!shouldUseTablesVariant)
  331. {
  332. for (const auto &rt : targets.colors)
  333. {
  334. if (rt.mipmap != 0 || rt.canvas->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.canvas != 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.canvas);
  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_stencil(lua_State *L)
  502. {
  503. luaL_checktype(L, 1, LUA_TFUNCTION);
  504. StencilAction action = STENCIL_REPLACE;
  505. if (!lua_isnoneornil(L, 2))
  506. {
  507. const char *actionstr = luaL_checkstring(L, 2);
  508. if (!getConstant(actionstr, action))
  509. return luax_enumerror(L, "stencil draw action", getConstants(action), actionstr);
  510. }
  511. int stencilvalue = (int) luaL_optinteger(L, 3, 1);
  512. // Fourth argument: whether to keep the contents of the stencil buffer.
  513. OptionalInt stencilclear;
  514. int argtype = lua_type(L, 4);
  515. if (argtype == LUA_TNONE || argtype == LUA_TNIL || (argtype == LUA_TBOOLEAN && luax_toboolean(L, 4) == false))
  516. stencilclear.set(0);
  517. else if (argtype == LUA_TNUMBER)
  518. stencilclear.set((int) luaL_checkinteger(L, 4));
  519. else if (argtype != LUA_TBOOLEAN)
  520. luaL_checktype(L, 4, LUA_TBOOLEAN);
  521. if (stencilclear.hasValue)
  522. instance()->clear(OptionalColorf(), stencilclear, OptionalDouble());
  523. luax_catchexcept(L, [&](){ instance()->drawToStencilBuffer(action, stencilvalue); });
  524. // Call stencilfunc()
  525. lua_pushvalue(L, 1);
  526. lua_call(L, 0, 0);
  527. luax_catchexcept(L, [&](){ instance()->stopDrawToStencilBuffer(); });
  528. return 0;
  529. }
  530. int w_setStencilTest(lua_State *L)
  531. {
  532. // COMPARE_ALWAYS effectively disables stencil testing.
  533. CompareMode compare = COMPARE_ALWAYS;
  534. int comparevalue = 0;
  535. if (!lua_isnoneornil(L, 1))
  536. {
  537. const char *comparestr = luaL_checkstring(L, 1);
  538. if (!getConstant(comparestr, compare))
  539. return luax_enumerror(L, "compare mode", getConstants(compare), comparestr);
  540. comparevalue = (int) luaL_checkinteger(L, 2);
  541. }
  542. luax_catchexcept(L, [&](){ instance()->setStencilTest(compare, comparevalue); });
  543. return 0;
  544. }
  545. int w_getStencilTest(lua_State *L)
  546. {
  547. CompareMode compare = COMPARE_ALWAYS;
  548. int comparevalue = 1;
  549. instance()->getStencilTest(compare, comparevalue);
  550. const char *comparestr;
  551. if (!getConstant(compare, comparestr))
  552. return luaL_error(L, "Unknown compare mode.");
  553. lua_pushstring(L, comparestr);
  554. lua_pushnumber(L, comparevalue);
  555. return 2;
  556. }
  557. static void parseDPIScale(Data *d, float *dpiscale)
  558. {
  559. auto fd = dynamic_cast<love::filesystem::FileData *>(d);
  560. if (fd == nullptr)
  561. return;
  562. // Parse a density scale of 2.0 from "[email protected]".
  563. const std::string &fname = fd->getName();
  564. size_t namelen = fname.length();
  565. size_t atpos = fname.rfind('@');
  566. if (atpos != std::string::npos && atpos + 2 < namelen
  567. && (fname[namelen - 1] == 'x' || fname[namelen - 1] == 'X'))
  568. {
  569. char *end = nullptr;
  570. long density = strtol(fname.c_str() + atpos + 1, &end, 10);
  571. if (end != nullptr && density > 0 && dpiscale != nullptr)
  572. *dpiscale = (float) density;
  573. }
  574. }
  575. static Image::Settings w__optImageSettings(lua_State *L, int idx, bool &setdpiscale)
  576. {
  577. Image::Settings s;
  578. setdpiscale = false;
  579. if (!lua_isnoneornil(L, idx))
  580. {
  581. luax_checktablefields<Image::SettingType>(L, idx, "image setting name", Image::getConstant);
  582. s.mipmaps = luax_boolflag(L, idx, Image::getConstant(Image::SETTING_MIPMAPS), s.mipmaps);
  583. s.linear = luax_boolflag(L, idx, Image::getConstant(Image::SETTING_LINEAR), s.linear);
  584. lua_getfield(L, idx, Image::getConstant(Image::SETTING_DPI_SCALE));
  585. if (lua_isnumber(L, -1))
  586. {
  587. s.dpiScale = (float) lua_tonumber(L, -1);
  588. setdpiscale = true;
  589. }
  590. lua_pop(L, 1);
  591. }
  592. return s;
  593. }
  594. static std::pair<StrongRef<image::ImageData>, StrongRef<image::CompressedImageData>>
  595. getImageData(lua_State *L, int idx, bool allowcompressed, float *dpiscale)
  596. {
  597. StrongRef<image::ImageData> idata;
  598. StrongRef<image::CompressedImageData> cdata;
  599. if (luax_istype(L, idx, image::ImageData::type))
  600. idata.set(image::luax_checkimagedata(L, idx));
  601. else if (luax_istype(L, idx, image::CompressedImageData::type))
  602. cdata.set(image::luax_checkcompressedimagedata(L, idx));
  603. else if (filesystem::luax_cangetdata(L, idx))
  604. {
  605. // Convert to ImageData / CompressedImageData.
  606. auto imagemodule = Module::getInstance<image::Image>(Module::M_IMAGE);
  607. if (imagemodule == nullptr)
  608. luaL_error(L, "Cannot load images without the love.image module.");
  609. StrongRef<Data> fdata(filesystem::luax_getdata(L, idx), Acquire::NORETAIN);
  610. if (dpiscale != nullptr)
  611. parseDPIScale(fdata, dpiscale);
  612. if (allowcompressed && imagemodule->isCompressed(fdata))
  613. luax_catchexcept(L, [&]() { cdata.set(imagemodule->newCompressedData(fdata), Acquire::NORETAIN); });
  614. else
  615. luax_catchexcept(L, [&]() { idata.set(imagemodule->newImageData(fdata), Acquire::NORETAIN); });
  616. }
  617. else
  618. idata.set(image::luax_checkimagedata(L, idx));
  619. return std::make_pair(idata, cdata);
  620. }
  621. static int w__pushNewImage(lua_State *L, Image::Slices &slices, const Image::Settings &settings)
  622. {
  623. StrongRef<Image> i;
  624. luax_catchexcept(L,
  625. [&]() { i.set(instance()->newImage(slices, settings), Acquire::NORETAIN); },
  626. [&](bool) { slices.clear(); }
  627. );
  628. luax_pushtype(L, i);
  629. return 1;
  630. }
  631. int w_newCubeImage(lua_State *L)
  632. {
  633. luax_checkgraphicscreated(L);
  634. Image::Slices slices(TEXTURE_CUBE);
  635. bool dpiscaleset = false;
  636. Image::Settings settings = w__optImageSettings(L, 2, dpiscaleset);
  637. float *autodpiscale = dpiscaleset ? nullptr : &settings.dpiScale;
  638. auto imagemodule = Module::getInstance<love::image::Image>(Module::M_IMAGE);
  639. if (!lua_istable(L, 1))
  640. {
  641. auto data = getImageData(L, 1, true, autodpiscale);
  642. std::vector<StrongRef<love::image::ImageData>> faces;
  643. if (data.first.get())
  644. {
  645. luax_catchexcept(L, [&](){ faces = imagemodule->newCubeFaces(data.first); });
  646. for (int i = 0; i < (int) faces.size(); i++)
  647. slices.set(i, 0, faces[i]);
  648. }
  649. else
  650. slices.add(data.second, 0, 0, true, settings.mipmaps);
  651. }
  652. else
  653. {
  654. int tlen = (int) luax_objlen(L, 1);
  655. if (luax_isarrayoftables(L, 1))
  656. {
  657. if (tlen != 6)
  658. return luaL_error(L, "Cubemap images must have 6 faces.");
  659. for (int face = 0; face < tlen; face++)
  660. {
  661. lua_rawgeti(L, 1, face + 1);
  662. luaL_checktype(L, -1, LUA_TTABLE);
  663. int miplen = std::max(1, (int) luax_objlen(L, -1));
  664. for (int mip = 0; mip < miplen; mip++)
  665. {
  666. lua_rawgeti(L, -1, mip + 1);
  667. auto data = getImageData(L, -1, true, face == 0 && mip == 0 ? autodpiscale : nullptr);
  668. if (data.first.get())
  669. slices.set(face, mip, data.first);
  670. else
  671. slices.set(face, mip, data.second->getSlice(0, 0));
  672. lua_pop(L, 1);
  673. }
  674. }
  675. }
  676. else
  677. {
  678. bool usemipmaps = false;
  679. for (int i = 0; i < tlen; i++)
  680. {
  681. lua_rawgeti(L, 1, i + 1);
  682. auto data = getImageData(L, -1, true, i == 0 ? autodpiscale : nullptr);
  683. if (data.first.get())
  684. {
  685. if (usemipmaps || data.first->getWidth() != data.first->getHeight())
  686. {
  687. usemipmaps = true;
  688. std::vector<StrongRef<love::image::ImageData>> faces;
  689. luax_catchexcept(L, [&](){ faces = imagemodule->newCubeFaces(data.first); });
  690. for (int face = 0; face < (int) faces.size(); face++)
  691. slices.set(face, i, faces[i]);
  692. }
  693. else
  694. slices.set(i, 0, data.first);
  695. }
  696. else
  697. slices.add(data.second, i, 0, false, settings.mipmaps);
  698. }
  699. }
  700. lua_pop(L, tlen);
  701. }
  702. return w__pushNewImage(L, slices, settings);
  703. }
  704. int w_newArrayImage(lua_State *L)
  705. {
  706. luax_checkgraphicscreated(L);
  707. Image::Slices slices(TEXTURE_2D_ARRAY);
  708. bool dpiscaleset = false;
  709. Image::Settings settings = w__optImageSettings(L, 2, dpiscaleset);
  710. float *autodpiscale = dpiscaleset ? nullptr : &settings.dpiScale;
  711. if (lua_istable(L, 1))
  712. {
  713. int tlen = std::max(1, (int) luax_objlen(L, 1));
  714. if (luax_isarrayoftables(L, 1))
  715. {
  716. for (int slice = 0; slice < tlen; slice++)
  717. {
  718. lua_rawgeti(L, 1, slice + 1);
  719. luaL_checktype(L, -1, LUA_TTABLE);
  720. int miplen = std::max(1, (int) luax_objlen(L, -1));
  721. for (int mip = 0; mip < miplen; mip++)
  722. {
  723. lua_rawgeti(L, -1, mip + 1);
  724. auto data = getImageData(L, -1, true, slice == 0 && mip == 0 ? autodpiscale : nullptr);
  725. if (data.first.get())
  726. slices.set(slice, mip, data.first);
  727. else
  728. slices.set(slice, mip, data.second->getSlice(0, 0));
  729. lua_pop(L, 1);
  730. }
  731. }
  732. }
  733. else
  734. {
  735. for (int slice = 0; slice < tlen; slice++)
  736. {
  737. lua_rawgeti(L, 1, slice + 1);
  738. auto data = getImageData(L, -1, true, slice == 0 ? autodpiscale : nullptr);
  739. if (data.first.get())
  740. slices.set(slice, 0, data.first);
  741. else
  742. slices.add(data.second, slice, 0, false, settings.mipmaps);
  743. }
  744. }
  745. lua_pop(L, tlen);
  746. }
  747. else
  748. {
  749. auto data = getImageData(L, 1, true, autodpiscale);
  750. if (data.first.get())
  751. slices.set(0, 0, data.first);
  752. else
  753. slices.add(data.second, 0, 0, true, settings.mipmaps);
  754. }
  755. return w__pushNewImage(L, slices, settings);
  756. }
  757. int w_newVolumeImage(lua_State *L)
  758. {
  759. luax_checkgraphicscreated(L);
  760. auto imagemodule = Module::getInstance<love::image::Image>(Module::M_IMAGE);
  761. Image::Slices slices(TEXTURE_VOLUME);
  762. bool dpiscaleset = false;
  763. Image::Settings settings = w__optImageSettings(L, 2, dpiscaleset);
  764. float *autodpiscale = dpiscaleset ? nullptr : &settings.dpiScale;
  765. if (lua_istable(L, 1))
  766. {
  767. int tlen = std::max(1, (int) luax_objlen(L, 1));
  768. if (luax_isarrayoftables(L, 1))
  769. {
  770. for (int mip = 0; mip < tlen; mip++)
  771. {
  772. lua_rawgeti(L, 1, mip + 1);
  773. luaL_checktype(L, -1, LUA_TTABLE);
  774. int slicelen = std::max(1, (int) luax_objlen(L, -1));
  775. for (int slice = 0; slice < slicelen; slice++)
  776. {
  777. lua_rawgeti(L, -1, mip + 1);
  778. auto data = getImageData(L, -1, true, slice == 0 && mip == 0 ? autodpiscale : nullptr);
  779. if (data.first.get())
  780. slices.set(slice, mip, data.first);
  781. else
  782. slices.set(slice, mip, data.second->getSlice(0, 0));
  783. lua_pop(L, 1);
  784. }
  785. }
  786. }
  787. else
  788. {
  789. for (int layer = 0; layer < tlen; layer++)
  790. {
  791. lua_rawgeti(L, 1, layer + 1);
  792. auto data = getImageData(L, -1, true, layer == 0 ? autodpiscale : nullptr);
  793. if (data.first.get())
  794. slices.set(layer, 0, data.first);
  795. else
  796. slices.add(data.second, layer, 0, false, settings.mipmaps);
  797. }
  798. }
  799. lua_pop(L, tlen);
  800. }
  801. else
  802. {
  803. auto data = getImageData(L, 1, true, autodpiscale);
  804. if (data.first.get())
  805. {
  806. std::vector<StrongRef<love::image::ImageData>> layers;
  807. luax_catchexcept(L, [&](){ layers = imagemodule->newVolumeLayers(data.first); });
  808. for (int i = 0; i < (int) layers.size(); i++)
  809. slices.set(i, 0, layers[i]);
  810. }
  811. else
  812. slices.add(data.second, 0, 0, true, settings.mipmaps);
  813. }
  814. return w__pushNewImage(L, slices, settings);
  815. }
  816. int w_newImage(lua_State *L)
  817. {
  818. luax_checkgraphicscreated(L);
  819. Image::Slices slices(TEXTURE_2D);
  820. bool dpiscaleset = false;
  821. Image::Settings settings = w__optImageSettings(L, 2, dpiscaleset);
  822. float *autodpiscale = dpiscaleset ? nullptr : &settings.dpiScale;
  823. if (lua_istable(L, 1))
  824. {
  825. int n = std::max(1, (int) luax_objlen(L, 1));
  826. for (int i = 0; i < n; i++)
  827. {
  828. lua_rawgeti(L, 1, i + 1);
  829. auto data = getImageData(L, -1, true, i == 0 ? autodpiscale : nullptr);
  830. if (data.first.get())
  831. slices.set(0, i, data.first);
  832. else
  833. slices.set(0, i, data.second->getSlice(0, 0));
  834. }
  835. lua_pop(L, n);
  836. }
  837. else
  838. {
  839. auto data = getImageData(L, 1, true, autodpiscale);
  840. if (data.first.get())
  841. slices.set(0, 0, data.first);
  842. else
  843. slices.add(data.second, 0, 0, false, settings.mipmaps);
  844. }
  845. return w__pushNewImage(L, slices, settings);
  846. }
  847. int w_newQuad(lua_State *L)
  848. {
  849. luax_checkgraphicscreated(L);
  850. Quad::Viewport v;
  851. v.x = luaL_checknumber(L, 1);
  852. v.y = luaL_checknumber(L, 2);
  853. v.w = luaL_checknumber(L, 3);
  854. v.h = luaL_checknumber(L, 4);
  855. double sw = 0.0f;
  856. double sh = 0.0f;
  857. int layer = 0;
  858. if (luax_istype(L, 5, Texture::type))
  859. {
  860. Texture *texture = luax_checktexture(L, 5);
  861. sw = texture->getWidth();
  862. sh = texture->getHeight();
  863. }
  864. else if (luax_istype(L, 6, Texture::type))
  865. {
  866. layer = (int) luaL_checkinteger(L, 5) - 1;
  867. Texture *texture = luax_checktexture(L, 6);
  868. sw = texture->getWidth();
  869. sh = texture->getHeight();
  870. }
  871. else if (!lua_isnoneornil(L, 7))
  872. {
  873. layer = (int) luaL_checkinteger(L, 5) - 1;
  874. sw = luaL_checknumber(L, 6);
  875. sh = luaL_checknumber(L, 7);
  876. }
  877. else
  878. {
  879. sw = luaL_checknumber(L, 5);
  880. sh = luaL_checknumber(L, 6);
  881. }
  882. Quad *quad = instance()->newQuad(v, sw, sh);
  883. quad->setLayer(layer);
  884. luax_pushtype(L, quad);
  885. quad->release();
  886. return 1;
  887. }
  888. int w_newFont(lua_State *L)
  889. {
  890. luax_checkgraphicscreated(L);
  891. graphics::Font *font = nullptr;
  892. // Convert to Rasterizer, if necessary.
  893. if (!luax_istype(L, 1, love::font::Rasterizer::type))
  894. {
  895. std::vector<int> idxs;
  896. for (int i = 0; i < lua_gettop(L); i++)
  897. idxs.push_back(i + 1);
  898. luax_convobj(L, idxs, "font", "newRasterizer");
  899. }
  900. love::font::Rasterizer *rasterizer = luax_checktype<love::font::Rasterizer>(L, 1);
  901. luax_catchexcept(L, [&]() {
  902. font = instance()->newFont(rasterizer, instance()->getDefaultFilter()); }
  903. );
  904. // Push the type.
  905. luax_pushtype(L, font);
  906. font->release();
  907. return 1;
  908. }
  909. int w_newImageFont(lua_State *L)
  910. {
  911. luax_checkgraphicscreated(L);
  912. // filter for glyphs
  913. Texture::Filter filter = instance()->getDefaultFilter();
  914. // Convert to Rasterizer if necessary.
  915. if (!luax_istype(L, 1, love::font::Rasterizer::type))
  916. {
  917. luaL_checktype(L, 2, LUA_TSTRING);
  918. std::vector<int> idxs;
  919. for (int i = 0; i < lua_gettop(L); i++)
  920. idxs.push_back(i + 1);
  921. luax_convobj(L, idxs, "font", "newImageRasterizer");
  922. }
  923. love::font::Rasterizer *rasterizer = luax_checktype<love::font::Rasterizer>(L, 1);
  924. // Create the font.
  925. Font *font = instance()->newFont(rasterizer, filter);
  926. // Push the type.
  927. luax_pushtype(L, font);
  928. font->release();
  929. return 1;
  930. }
  931. int w_newSpriteBatch(lua_State *L)
  932. {
  933. luax_checkgraphicscreated(L);
  934. Texture *texture = luax_checktexture(L, 1);
  935. int size = (int) luaL_optinteger(L, 2, 1000);
  936. vertex::Usage usage = vertex::USAGE_DYNAMIC;
  937. if (lua_gettop(L) > 2)
  938. {
  939. const char *usagestr = luaL_checkstring(L, 3);
  940. if (!vertex::getConstant(usagestr, usage))
  941. return luax_enumerror(L, "usage hint", vertex::getConstants(usage), usagestr);
  942. }
  943. SpriteBatch *t = nullptr;
  944. luax_catchexcept(L,
  945. [&](){ t = instance()->newSpriteBatch(texture, size, usage); }
  946. );
  947. luax_pushtype(L, t);
  948. t->release();
  949. return 1;
  950. }
  951. int w_newParticleSystem(lua_State *L)
  952. {
  953. luax_checkgraphicscreated(L);
  954. Texture *texture = luax_checktexture(L, 1);
  955. lua_Number size = luaL_optnumber(L, 2, 1000);
  956. ParticleSystem *t = nullptr;
  957. if (size < 1.0 || size > ParticleSystem::MAX_PARTICLES)
  958. return luaL_error(L, "Invalid ParticleSystem size");
  959. luax_catchexcept(L,
  960. [&](){ t = instance()->newParticleSystem(texture, int(size)); }
  961. );
  962. luax_pushtype(L, t);
  963. t->release();
  964. return 1;
  965. }
  966. int w_newCanvas(lua_State *L)
  967. {
  968. luax_checkgraphicscreated(L);
  969. Canvas::Settings settings;
  970. // check if width and height are given. else default to screen dimensions.
  971. settings.width = (int) luaL_optinteger(L, 1, instance()->getWidth());
  972. settings.height = (int) luaL_optinteger(L, 2, instance()->getHeight());
  973. // Default to the screen's current pixel density scale.
  974. settings.dpiScale = instance()->getScreenDPIScale();
  975. int startidx = 3;
  976. if (lua_isnumber(L, 3))
  977. {
  978. settings.layers = (int) luaL_checkinteger(L, 3);
  979. settings.type = TEXTURE_2D_ARRAY;
  980. startidx = 4;
  981. }
  982. if (!lua_isnoneornil(L, startidx))
  983. {
  984. luax_checktablefields<Canvas::SettingType>(L, startidx, "canvas setting name", Canvas::getConstant);
  985. settings.dpiScale = (float) luax_numberflag(L, startidx, Canvas::getConstant(Canvas::SETTING_DPI_SCALE), settings.dpiScale);
  986. settings.msaa = luax_intflag(L, startidx, Canvas::getConstant(Canvas::SETTING_MSAA), settings.msaa);
  987. lua_getfield(L, startidx, Canvas::getConstant(Canvas::SETTING_FORMAT));
  988. if (!lua_isnoneornil(L, -1))
  989. {
  990. const char *str = luaL_checkstring(L, -1);
  991. if (!getConstant(str, settings.format))
  992. return luax_enumerror(L, "pixel format", str);
  993. }
  994. lua_pop(L, 1);
  995. lua_getfield(L, startidx, Canvas::getConstant(Canvas::SETTING_TYPE));
  996. if (!lua_isnoneornil(L, -1))
  997. {
  998. const char *str = luaL_checkstring(L, -1);
  999. if (!Texture::getConstant(str, settings.type))
  1000. return luax_enumerror(L, "texture type", Texture::getConstants(settings.type), str);
  1001. }
  1002. lua_pop(L, 1);
  1003. lua_getfield(L, startidx, Canvas::getConstant(Canvas::SETTING_READABLE));
  1004. if (!lua_isnoneornil(L, -1))
  1005. {
  1006. settings.readable.hasValue = true;
  1007. settings.readable.value = luax_checkboolean(L, -1);
  1008. }
  1009. lua_pop(L, 1);
  1010. lua_getfield(L, startidx, Canvas::getConstant(Canvas::SETTING_MIPMAPS));
  1011. if (!lua_isnoneornil(L, -1))
  1012. {
  1013. const char *str = luaL_checkstring(L, -1);
  1014. if (!Canvas::getConstant(str, settings.mipmaps))
  1015. return luax_enumerror(L, "Canvas mipmap mode", Canvas::getConstants(settings.mipmaps), str);
  1016. }
  1017. lua_pop(L, 1);
  1018. }
  1019. Canvas *canvas = nullptr;
  1020. luax_catchexcept(L, [&](){ canvas = instance()->newCanvas(settings); });
  1021. luax_pushtype(L, canvas);
  1022. canvas->release();
  1023. return 1;
  1024. }
  1025. static int w_getShaderSource(lua_State *L, int startidx, bool gles, std::string &vertexsource, std::string &pixelsource)
  1026. {
  1027. using namespace love::filesystem;
  1028. luax_checkgraphicscreated(L);
  1029. auto fs = Module::getInstance<Filesystem>(Module::M_FILESYSTEM);
  1030. // read any filepath arguments
  1031. for (int i = startidx; i < startidx + 2; i++)
  1032. {
  1033. if (!lua_isstring(L, i))
  1034. {
  1035. if (luax_cangetfiledata(L, i))
  1036. {
  1037. FileData *fd = luax_getfiledata(L, i);
  1038. lua_pushlstring(L, (const char *) fd->getData(), fd->getSize());
  1039. fd->release();
  1040. lua_replace(L, i);
  1041. }
  1042. continue;
  1043. }
  1044. size_t slen = 0;
  1045. const char *str = lua_tolstring(L, i, &slen);
  1046. Filesystem::Info info = {};
  1047. if (fs != nullptr && fs->getInfo(str, info))
  1048. {
  1049. FileData *fd = nullptr;
  1050. luax_catchexcept(L, [&](){ fd = fs->read(str); });
  1051. lua_pushlstring(L, (const char *) fd->getData(), fd->getSize());
  1052. fd->release();
  1053. lua_replace(L, i);
  1054. }
  1055. else
  1056. {
  1057. // Check if the argument looks like a filepath - we want a nicer
  1058. // error for misspelled filepath arguments.
  1059. if (slen > 0 && slen < 64 && !strchr(str, '\n'))
  1060. {
  1061. const char *ext = strchr(str, '.');
  1062. if (ext != nullptr && !strchr(ext, ';') && !strchr(ext, ' '))
  1063. return luaL_error(L, "Could not open file %s. Does not exist.", str);
  1064. }
  1065. }
  1066. }
  1067. bool has_arg1 = lua_isstring(L, startidx + 0) != 0;
  1068. bool has_arg2 = lua_isstring(L, startidx + 1) != 0;
  1069. // require at least one string argument
  1070. if (!(has_arg1 || has_arg2))
  1071. luaL_checkstring(L, startidx);
  1072. luax_getfunction(L, "graphics", "_shaderCodeToGLSL");
  1073. // push vertexcode and pixelcode strings to the top of the stack
  1074. lua_pushboolean(L, gles);
  1075. if (has_arg1)
  1076. lua_pushvalue(L, startidx + 0);
  1077. else
  1078. lua_pushnil(L);
  1079. if (has_arg2)
  1080. lua_pushvalue(L, startidx + 1);
  1081. else
  1082. lua_pushnil(L);
  1083. // call effectCodeToGLSL, returned values will be at the top of the stack
  1084. if (lua_pcall(L, 3, 2, 0) != 0)
  1085. return luaL_error(L, "%s", lua_tostring(L, -1));
  1086. // vertex shader code
  1087. if (lua_isstring(L, -2))
  1088. vertexsource = luax_checkstring(L, -2);
  1089. else if (has_arg1 && has_arg2)
  1090. return luaL_error(L, "Could not parse vertex shader code (missing 'position' function?)");
  1091. // pixel shader code
  1092. if (lua_isstring(L, -1))
  1093. pixelsource = luax_checkstring(L, -1);
  1094. else if (has_arg1 && has_arg2)
  1095. return luaL_error(L, "Could not parse pixel shader code (missing 'effect' function?)");
  1096. if (vertexsource.empty() && pixelsource.empty())
  1097. {
  1098. // Original args had source code, but effectCodeToGLSL couldn't translate it
  1099. for (int i = startidx; i < startidx + 2; i++)
  1100. {
  1101. if (lua_isstring(L, i))
  1102. return luaL_argerror(L, i, "missing 'position' or 'effect' function?");
  1103. }
  1104. }
  1105. return 0;
  1106. }
  1107. int w_newShader(lua_State *L)
  1108. {
  1109. bool gles = instance()->getRenderer() == Graphics::RENDERER_OPENGLES;
  1110. std::string vertexsource, pixelsource;
  1111. w_getShaderSource(L, 1, gles, vertexsource, pixelsource);
  1112. bool should_error = false;
  1113. try
  1114. {
  1115. Shader *shader = instance()->newShader(vertexsource, pixelsource);
  1116. luax_pushtype(L, shader);
  1117. shader->release();
  1118. }
  1119. catch (love::Exception &e)
  1120. {
  1121. luax_getfunction(L, "graphics", "_transformGLSLErrorMessages");
  1122. lua_pushstring(L, e.what());
  1123. // Function pushes the new error string onto the stack.
  1124. lua_pcall(L, 1, 1, 0);
  1125. should_error = true;
  1126. }
  1127. if (should_error)
  1128. return lua_error(L);
  1129. return 1;
  1130. }
  1131. int w_validateShader(lua_State *L)
  1132. {
  1133. bool gles = luax_checkboolean(L, 1);
  1134. std::string vertexsource, pixelsource;
  1135. w_getShaderSource(L, 2, gles, vertexsource, pixelsource);
  1136. bool success = true;
  1137. std::string err;
  1138. try
  1139. {
  1140. success = instance()->validateShader(gles, vertexsource, pixelsource, err);
  1141. }
  1142. catch (love::Exception &e)
  1143. {
  1144. success = false;
  1145. err = e.what();
  1146. }
  1147. luax_pushboolean(L, success);
  1148. if (!success)
  1149. {
  1150. luax_pushstring(L, err);
  1151. return 2;
  1152. }
  1153. return 1;
  1154. }
  1155. static vertex::Usage luax_optmeshusage(lua_State *L, int idx, vertex::Usage def)
  1156. {
  1157. const char *usagestr = lua_isnoneornil(L, idx) ? nullptr : luaL_checkstring(L, idx);
  1158. if (usagestr && !vertex::getConstant(usagestr, def))
  1159. luax_enumerror(L, "usage hint", vertex::getConstants(def), usagestr);
  1160. return def;
  1161. }
  1162. static PrimitiveType luax_optmeshdrawmode(lua_State *L, int idx, PrimitiveType def)
  1163. {
  1164. const char *modestr = lua_isnoneornil(L, idx) ? nullptr : luaL_checkstring(L, idx);
  1165. if (modestr && !vertex::getConstant(modestr, def))
  1166. luax_enumerror(L, "mesh draw mode", vertex::getConstants(def), modestr);
  1167. return def;
  1168. }
  1169. static Mesh *newStandardMesh(lua_State *L)
  1170. {
  1171. Mesh *t = nullptr;
  1172. PrimitiveType drawmode = luax_optmeshdrawmode(L, 2, PRIMITIVE_TRIANGLE_FAN);
  1173. vertex::Usage usage = luax_optmeshusage(L, 3, vertex::USAGE_DYNAMIC);
  1174. // First argument is a table of standard vertices, or the number of
  1175. // standard vertices.
  1176. if (lua_istable(L, 1))
  1177. {
  1178. size_t vertexcount = luax_objlen(L, 1);
  1179. std::vector<Vertex> vertices;
  1180. vertices.reserve(vertexcount);
  1181. // Get the vertices from the table.
  1182. for (size_t i = 1; i <= vertexcount; i++)
  1183. {
  1184. lua_rawgeti(L, 1, (int) i);
  1185. if (lua_type(L, -1) != LUA_TTABLE)
  1186. {
  1187. luax_typerror(L, 1, "table of tables");
  1188. return nullptr;
  1189. }
  1190. for (int j = 1; j <= 8; j++)
  1191. lua_rawgeti(L, -j, j);
  1192. Vertex v;
  1193. v.x = (float) luaL_checknumber(L, -8);
  1194. v.y = (float) luaL_checknumber(L, -7);
  1195. v.s = (float) luaL_optnumber(L, -6, 0.0);
  1196. v.t = (float) luaL_optnumber(L, -5, 0.0);
  1197. v.color.r = (unsigned char) (luax_optnumberclamped01(L, -4, 1.0) * 255.0);
  1198. v.color.g = (unsigned char) (luax_optnumberclamped01(L, -3, 1.0) * 255.0);
  1199. v.color.b = (unsigned char) (luax_optnumberclamped01(L, -2, 1.0) * 255.0);
  1200. v.color.a = (unsigned char) (luax_optnumberclamped01(L, -1, 1.0) * 255.0);
  1201. lua_pop(L, 9);
  1202. vertices.push_back(v);
  1203. }
  1204. luax_catchexcept(L, [&](){ t = instance()->newMesh(vertices, drawmode, usage); });
  1205. }
  1206. else
  1207. {
  1208. int count = (int) luaL_checkinteger(L, 1);
  1209. luax_catchexcept(L, [&](){ t = instance()->newMesh(count, drawmode, usage); });
  1210. }
  1211. return t;
  1212. }
  1213. static Mesh *newCustomMesh(lua_State *L)
  1214. {
  1215. Mesh *t = nullptr;
  1216. // First argument is the vertex format, second is a table of vertices or
  1217. // the number of vertices.
  1218. std::vector<Mesh::AttribFormat> vertexformat;
  1219. PrimitiveType drawmode = luax_optmeshdrawmode(L, 3, PRIMITIVE_TRIANGLE_FAN);
  1220. vertex::Usage usage = luax_optmeshusage(L, 4, vertex::USAGE_DYNAMIC);
  1221. lua_rawgeti(L, 1, 1);
  1222. if (!lua_istable(L, -1))
  1223. {
  1224. luaL_argerror(L, 1, "table of tables expected");
  1225. return nullptr;
  1226. }
  1227. lua_pop(L, 1);
  1228. // Per-vertex attribute formats.
  1229. for (int i = 1; i <= (int) luax_objlen(L, 1); i++)
  1230. {
  1231. lua_rawgeti(L, 1, i);
  1232. // {name, datatype, components}
  1233. for (int j = 1; j <= 3; j++)
  1234. lua_rawgeti(L, -j, j);
  1235. Mesh::AttribFormat format;
  1236. format.name = luaL_checkstring(L, -3);
  1237. const char *tname = luaL_checkstring(L, -2);
  1238. if (!vertex::getConstant(tname, format.type))
  1239. {
  1240. luax_enumerror(L, "Mesh vertex data type name", vertex::getConstants(format.type), tname);
  1241. return nullptr;
  1242. }
  1243. format.components = (int) luaL_checkinteger(L, -1);
  1244. if (format.components <= 0 || format.components > 4)
  1245. {
  1246. luaL_error(L, "Number of vertex attribute components must be between 1 and 4 (got %d)", format.components);
  1247. return nullptr;
  1248. }
  1249. lua_pop(L, 4);
  1250. vertexformat.push_back(format);
  1251. }
  1252. if (lua_isnumber(L, 2))
  1253. {
  1254. int vertexcount = (int) luaL_checkinteger(L, 2);
  1255. luax_catchexcept(L, [&](){ t = instance()->newMesh(vertexformat, vertexcount, drawmode, usage); });
  1256. }
  1257. else if (luax_istype(L, 2, Data::type))
  1258. {
  1259. // Vertex data comes directly from a Data object.
  1260. Data *data = luax_checktype<Data>(L, 2);
  1261. luax_catchexcept(L, [&](){ t = instance()->newMesh(vertexformat, data->getData(), data->getSize(), drawmode, usage); });
  1262. }
  1263. else
  1264. {
  1265. // Table of vertices.
  1266. lua_rawgeti(L, 2, 1);
  1267. if (!lua_istable(L, -1))
  1268. {
  1269. luaL_argerror(L, 2, "expected table of tables");
  1270. return nullptr;
  1271. }
  1272. lua_pop(L, 1);
  1273. int vertexcomponents = 0;
  1274. for (const Mesh::AttribFormat &format : vertexformat)
  1275. vertexcomponents += format.components;
  1276. size_t numvertices = luax_objlen(L, 2);
  1277. luax_catchexcept(L, [&](){ t = instance()->newMesh(vertexformat, numvertices, drawmode, usage); });
  1278. // Maximum possible data size for a single vertex attribute.
  1279. char data[sizeof(float) * 4];
  1280. for (size_t vertindex = 0; vertindex < numvertices; vertindex++)
  1281. {
  1282. // get vertices[vertindex]
  1283. lua_rawgeti(L, 2, vertindex + 1);
  1284. luaL_checktype(L, -1, LUA_TTABLE);
  1285. int n = 0;
  1286. for (size_t i = 0; i < vertexformat.size(); i++)
  1287. {
  1288. int components = vertexformat[i].components;
  1289. // get vertices[vertindex][n]
  1290. for (int c = 0; c < components; c++)
  1291. {
  1292. n++;
  1293. lua_rawgeti(L, -(c + 1), n);
  1294. }
  1295. // Fetch the values from Lua and store them in data buffer.
  1296. luax_writeAttributeData(L, -components, vertexformat[i].type, components, data);
  1297. lua_pop(L, components);
  1298. luax_catchexcept(L,
  1299. [&](){ t->setVertexAttribute(vertindex, i, data, sizeof(float) * 4); },
  1300. [&](bool diderror){ if (diderror) t->release(); }
  1301. );
  1302. }
  1303. lua_pop(L, 1); // pop vertices[vertindex]
  1304. }
  1305. t->flush();
  1306. }
  1307. return t;
  1308. }
  1309. int w_newMesh(lua_State *L)
  1310. {
  1311. luax_checkgraphicscreated(L);
  1312. // Check first argument: table or number of vertices.
  1313. int arg1type = lua_type(L, 1);
  1314. if (arg1type != LUA_TTABLE && arg1type != LUA_TNUMBER)
  1315. luaL_argerror(L, 1, "table or number expected");
  1316. Mesh *t = nullptr;
  1317. int arg2type = lua_type(L, 2);
  1318. if (arg1type == LUA_TTABLE && (arg2type == LUA_TTABLE || arg2type == LUA_TNUMBER || arg2type == LUA_TUSERDATA))
  1319. t = newCustomMesh(L);
  1320. else
  1321. t = newStandardMesh(L);
  1322. luax_pushtype(L, t);
  1323. t->release();
  1324. return 1;
  1325. }
  1326. int w_newText(lua_State *L)
  1327. {
  1328. luax_checkgraphicscreated(L);
  1329. graphics::Font *font = luax_checkfont(L, 1);
  1330. Text *t = nullptr;
  1331. if (lua_isnoneornil(L, 2))
  1332. luax_catchexcept(L, [&](){ t = instance()->newText(font); });
  1333. else
  1334. {
  1335. std::vector<Font::ColoredString> text;
  1336. luax_checkcoloredstring(L, 2, text);
  1337. luax_catchexcept(L, [&](){ t = instance()->newText(font, text); });
  1338. }
  1339. luax_pushtype(L, t);
  1340. t->release();
  1341. return 1;
  1342. }
  1343. int w_newVideo(lua_State *L)
  1344. {
  1345. luax_checkgraphicscreated(L);
  1346. if (!luax_istype(L, 1, love::video::VideoStream::type))
  1347. luax_convobj(L, 1, "video", "newVideoStream");
  1348. auto stream = luax_checktype<love::video::VideoStream>(L, 1);
  1349. float dpiscale = (float) luaL_optnumber(L, 2, 1.0);
  1350. Video *video = nullptr;
  1351. luax_catchexcept(L, [&]() { video = instance()->newVideo(stream, dpiscale); });
  1352. luax_pushtype(L, video);
  1353. video->release();
  1354. return 1;
  1355. }
  1356. int w_setColor(lua_State *L)
  1357. {
  1358. Colorf c;
  1359. if (lua_istable(L, 1))
  1360. {
  1361. for (int i = 1; i <= 4; i++)
  1362. lua_rawgeti(L, 1, i);
  1363. c.r = (float) luaL_checknumber(L, -4);
  1364. c.g = (float) luaL_checknumber(L, -3);
  1365. c.b = (float) luaL_checknumber(L, -2);
  1366. c.a = (float) luaL_optnumber(L, -1, 1.0);
  1367. lua_pop(L, 4);
  1368. }
  1369. else
  1370. {
  1371. c.r = (float) luaL_checknumber(L, 1);
  1372. c.g = (float) luaL_checknumber(L, 2);
  1373. c.b = (float) luaL_checknumber(L, 3);
  1374. c.a = (float) luaL_optnumber(L, 4, 1.0);
  1375. }
  1376. instance()->setColor(c);
  1377. return 0;
  1378. }
  1379. int w_getColor(lua_State *L)
  1380. {
  1381. Colorf c = instance()->getColor();
  1382. lua_pushnumber(L, c.r);
  1383. lua_pushnumber(L, c.g);
  1384. lua_pushnumber(L, c.b);
  1385. lua_pushnumber(L, c.a);
  1386. return 4;
  1387. }
  1388. int w_setBackgroundColor(lua_State *L)
  1389. {
  1390. Colorf c;
  1391. if (lua_istable(L, 1))
  1392. {
  1393. for (int i = 1; i <= 4; i++)
  1394. lua_rawgeti(L, 1, i);
  1395. c.r = (float) luaL_checknumber(L, -4);
  1396. c.g = (float) luaL_checknumber(L, -3);
  1397. c.b = (float) luaL_checknumber(L, -2);
  1398. c.a = (float) luaL_optnumber(L, -1, 1.0);
  1399. lua_pop(L, 4);
  1400. }
  1401. else
  1402. {
  1403. c.r = (float) luaL_checknumber(L, 1);
  1404. c.g = (float) luaL_checknumber(L, 2);
  1405. c.b = (float) luaL_checknumber(L, 3);
  1406. c.a = (float) luaL_optnumber(L, 4, 1.0);
  1407. }
  1408. instance()->setBackgroundColor(c);
  1409. return 0;
  1410. }
  1411. int w_getBackgroundColor(lua_State *L)
  1412. {
  1413. Colorf c = instance()->getBackgroundColor();
  1414. lua_pushnumber(L, c.r);
  1415. lua_pushnumber(L, c.g);
  1416. lua_pushnumber(L, c.b);
  1417. lua_pushnumber(L, c.a);
  1418. return 4;
  1419. }
  1420. int w_setNewFont(lua_State *L)
  1421. {
  1422. int ret = w_newFont(L);
  1423. Font *font = luax_checktype<Font>(L, -1);
  1424. instance()->setFont(font);
  1425. return ret;
  1426. }
  1427. int w_setFont(lua_State *L)
  1428. {
  1429. Font *font = luax_checktype<Font>(L, 1);
  1430. instance()->setFont(font);
  1431. return 0;
  1432. }
  1433. int w_getFont(lua_State *L)
  1434. {
  1435. Font *f = nullptr;
  1436. luax_catchexcept(L, [&](){ f = instance()->getFont(); });
  1437. luax_pushtype(L, f);
  1438. return 1;
  1439. }
  1440. int w_setColorMask(lua_State *L)
  1441. {
  1442. Graphics::ColorMask mask;
  1443. if (lua_gettop(L) <= 1 && lua_isnoneornil(L, 1))
  1444. {
  1445. // Enable all color components if no argument is given.
  1446. mask.r = mask.g = mask.b = mask.a = true;
  1447. }
  1448. else
  1449. {
  1450. mask.r = luax_checkboolean(L, 1);
  1451. mask.g = luax_checkboolean(L, 2);
  1452. mask.b = luax_checkboolean(L, 3);
  1453. mask.a = luax_checkboolean(L, 4);
  1454. }
  1455. instance()->setColorMask(mask);
  1456. return 0;
  1457. }
  1458. int w_getColorMask(lua_State *L)
  1459. {
  1460. Graphics::ColorMask mask = instance()->getColorMask();
  1461. luax_pushboolean(L, mask.r);
  1462. luax_pushboolean(L, mask.g);
  1463. luax_pushboolean(L, mask.b);
  1464. luax_pushboolean(L, mask.a);
  1465. return 4;
  1466. }
  1467. int w_setBlendMode(lua_State *L)
  1468. {
  1469. Graphics::BlendMode mode;
  1470. const char *str = luaL_checkstring(L, 1);
  1471. if (!Graphics::getConstant(str, mode))
  1472. return luax_enumerror(L, "blend mode", Graphics::getConstants(mode), str);
  1473. Graphics::BlendAlpha alphamode = Graphics::BLENDALPHA_MULTIPLY;
  1474. if (!lua_isnoneornil(L, 2))
  1475. {
  1476. const char *alphastr = luaL_checkstring(L, 2);
  1477. if (!Graphics::getConstant(alphastr, alphamode))
  1478. return luax_enumerror(L, "blend alpha mode", Graphics::getConstants(alphamode), alphastr);
  1479. }
  1480. luax_catchexcept(L, [&](){ instance()->setBlendMode(mode, alphamode); });
  1481. return 0;
  1482. }
  1483. int w_getBlendMode(lua_State *L)
  1484. {
  1485. const char *str;
  1486. const char *alphastr;
  1487. Graphics::BlendAlpha alphamode;
  1488. Graphics::BlendMode mode = instance()->getBlendMode(alphamode);
  1489. if (!Graphics::getConstant(mode, str))
  1490. return luaL_error(L, "Unknown blend mode");
  1491. if (!Graphics::getConstant(alphamode, alphastr))
  1492. return luaL_error(L, "Unknown blend alpha mode");
  1493. lua_pushstring(L, str);
  1494. lua_pushstring(L, alphastr);
  1495. return 2;
  1496. }
  1497. int w_setDefaultFilter(lua_State *L)
  1498. {
  1499. Texture::Filter f;
  1500. const char *minstr = luaL_checkstring(L, 1);
  1501. const char *magstr = luaL_optstring(L, 2, minstr);
  1502. if (!Texture::getConstant(minstr, f.min))
  1503. return luax_enumerror(L, "filter mode", Texture::getConstants(f.min), minstr);
  1504. if (!Texture::getConstant(magstr, f.mag))
  1505. return luax_enumerror(L, "filter mode", Texture::getConstants(f.mag), magstr);
  1506. f.anisotropy = (float) luaL_optnumber(L, 3, 1.0);
  1507. instance()->setDefaultFilter(f);
  1508. return 0;
  1509. }
  1510. int w_getDefaultFilter(lua_State *L)
  1511. {
  1512. const Texture::Filter &f = instance()->getDefaultFilter();
  1513. const char *minstr;
  1514. const char *magstr;
  1515. if (!Texture::getConstant(f.min, minstr))
  1516. return luaL_error(L, "Unknown minification filter mode");
  1517. if (!Texture::getConstant(f.mag, magstr))
  1518. return luaL_error(L, "Unknown magnification filter mode");
  1519. lua_pushstring(L, minstr);
  1520. lua_pushstring(L, magstr);
  1521. lua_pushnumber(L, f.anisotropy);
  1522. return 3;
  1523. }
  1524. int w_setDefaultMipmapFilter(lua_State *L)
  1525. {
  1526. Texture::FilterMode filter = Texture::FILTER_NONE;
  1527. if (!lua_isnoneornil(L, 1))
  1528. {
  1529. const char *str = luaL_checkstring(L, 1);
  1530. if (!Texture::getConstant(str, filter))
  1531. return luax_enumerror(L, "filter mode", Texture::getConstants(filter), str);
  1532. }
  1533. float sharpness = (float) luaL_optnumber(L, 2, 0);
  1534. instance()->setDefaultMipmapFilter(filter, sharpness);
  1535. return 0;
  1536. }
  1537. int w_getDefaultMipmapFilter(lua_State *L)
  1538. {
  1539. Texture::FilterMode filter;
  1540. float sharpness;
  1541. instance()->getDefaultMipmapFilter(&filter, &sharpness);
  1542. const char *str;
  1543. if (Texture::getConstant(filter, str))
  1544. lua_pushstring(L, str);
  1545. else
  1546. lua_pushnil(L);
  1547. lua_pushnumber(L, sharpness);
  1548. return 2;
  1549. }
  1550. int w_setLineWidth(lua_State *L)
  1551. {
  1552. float width = (float)luaL_checknumber(L, 1);
  1553. instance()->setLineWidth(width);
  1554. return 0;
  1555. }
  1556. int w_setLineStyle(lua_State *L)
  1557. {
  1558. Graphics::LineStyle style;
  1559. const char *str = luaL_checkstring(L, 1);
  1560. if (!Graphics::getConstant(str, style))
  1561. return luax_enumerror(L, "line style", Graphics::getConstants(style), str);
  1562. instance()->setLineStyle(style);
  1563. return 0;
  1564. }
  1565. int w_setLineJoin(lua_State *L)
  1566. {
  1567. Graphics::LineJoin join;
  1568. const char *str = luaL_checkstring(L, 1);
  1569. if (!Graphics::getConstant(str, join))
  1570. return luax_enumerror(L, "line join", Graphics::getConstants(join), str);
  1571. instance()->setLineJoin(join);
  1572. return 0;
  1573. }
  1574. int w_getLineWidth(lua_State *L)
  1575. {
  1576. lua_pushnumber(L, instance()->getLineWidth());
  1577. return 1;
  1578. }
  1579. int w_getLineStyle(lua_State *L)
  1580. {
  1581. Graphics::LineStyle style = instance()->getLineStyle();
  1582. const char *str;
  1583. if (!Graphics::getConstant(style, str))
  1584. return luaL_error(L, "Unknown line style");
  1585. lua_pushstring(L, str);
  1586. return 1;
  1587. }
  1588. int w_getLineJoin(lua_State *L)
  1589. {
  1590. Graphics::LineJoin join = instance()->getLineJoin();
  1591. const char *str;
  1592. if (!Graphics::getConstant(join, str))
  1593. return luaL_error(L, "Unknown line join");
  1594. lua_pushstring(L, str);
  1595. return 1;
  1596. }
  1597. int w_setPointSize(lua_State *L)
  1598. {
  1599. float size = (float)luaL_checknumber(L, 1);
  1600. instance()->setPointSize(size);
  1601. return 0;
  1602. }
  1603. int w_getPointSize(lua_State *L)
  1604. {
  1605. lua_pushnumber(L, instance()->getPointSize());
  1606. return 1;
  1607. }
  1608. int w_setDepthMode(lua_State *L)
  1609. {
  1610. if (lua_isnoneornil(L, 1) && lua_isnoneornil(L, 2))
  1611. luax_catchexcept(L, [&]() { instance()->setDepthMode(); });
  1612. else
  1613. {
  1614. CompareMode compare = COMPARE_ALWAYS;
  1615. const char *str = luaL_checkstring(L, 1);
  1616. bool write = luax_checkboolean(L, 2);
  1617. if (!getConstant(str, compare))
  1618. return luax_enumerror(L, "compare mode", getConstants(compare), str);
  1619. luax_catchexcept(L, [&]() { instance()->setDepthMode(compare, write); });
  1620. }
  1621. return 0;
  1622. }
  1623. int w_getDepthMode(lua_State *L)
  1624. {
  1625. CompareMode compare = COMPARE_ALWAYS;
  1626. bool write = false;
  1627. instance()->getDepthMode(compare, write);
  1628. const char *str;
  1629. if (!getConstant(compare, str))
  1630. return luaL_error(L, "Unknown compare mode");
  1631. lua_pushstring(L, str);
  1632. luax_pushboolean(L, write);
  1633. return 2;
  1634. }
  1635. int w_setMeshCullMode(lua_State *L)
  1636. {
  1637. const char *str = luaL_checkstring(L, 1);
  1638. CullMode mode;
  1639. if (!vertex::getConstant(str, mode))
  1640. return luax_enumerror(L, "cull mode", vertex::getConstants(mode), str);
  1641. luax_catchexcept(L, [&]() { instance()->setMeshCullMode(mode); });
  1642. return 0;
  1643. }
  1644. int w_getMeshCullMode(lua_State *L)
  1645. {
  1646. CullMode mode = instance()->getMeshCullMode();
  1647. const char *str;
  1648. if (!vertex::getConstant(mode, str))
  1649. return luaL_error(L, "Unknown cull mode");
  1650. lua_pushstring(L, str);
  1651. return 1;
  1652. }
  1653. int w_setFrontFaceWinding(lua_State *L)
  1654. {
  1655. const char *str = luaL_checkstring(L, 1);
  1656. vertex::Winding winding;
  1657. if (!vertex::getConstant(str, winding))
  1658. return luax_enumerror(L, "vertex winding", vertex::getConstants(winding), str);
  1659. luax_catchexcept(L, [&]() { instance()->setFrontFaceWinding(winding); });
  1660. return 0;
  1661. }
  1662. int w_getFrontFaceWinding(lua_State *L)
  1663. {
  1664. vertex::Winding winding = instance()->getFrontFaceWinding();
  1665. const char *str;
  1666. if (!vertex::getConstant(winding, str))
  1667. return luaL_error(L, "Unknown vertex winding");
  1668. lua_pushstring(L, str);
  1669. return 1;
  1670. }
  1671. int w_setWireframe(lua_State *L)
  1672. {
  1673. instance()->setWireframe(luax_checkboolean(L, 1));
  1674. return 0;
  1675. }
  1676. int w_isWireframe(lua_State *L)
  1677. {
  1678. luax_pushboolean(L, instance()->isWireframe());
  1679. return 1;
  1680. }
  1681. int w_setShader(lua_State *L)
  1682. {
  1683. if (lua_isnoneornil(L,1))
  1684. {
  1685. instance()->setShader();
  1686. return 0;
  1687. }
  1688. Shader *shader = luax_checkshader(L, 1);
  1689. instance()->setShader(shader);
  1690. return 0;
  1691. }
  1692. int w_getShader(lua_State *L)
  1693. {
  1694. Shader *shader = instance()->getShader();
  1695. if (shader)
  1696. luax_pushtype(L, shader);
  1697. else
  1698. lua_pushnil(L);
  1699. return 1;
  1700. }
  1701. int w_setDefaultShaderCode(lua_State *L)
  1702. {
  1703. for (int i = 0; i < 2; i++)
  1704. {
  1705. luaL_checktype(L, i + 1, LUA_TTABLE);
  1706. for (int lang = 0; lang < Shader::LANGUAGE_MAX_ENUM; lang++)
  1707. {
  1708. const char *langname;
  1709. if (!Shader::getConstant((Shader::Language) lang, langname))
  1710. continue;
  1711. lua_getfield(L, i + 1, langname);
  1712. lua_getfield(L, -1, "vertex");
  1713. lua_getfield(L, -2, "pixel");
  1714. lua_getfield(L, -3, "videopixel");
  1715. lua_getfield(L, -4, "arraypixel");
  1716. std::string vertex = luax_checkstring(L, -4);
  1717. std::string pixel = luax_checkstring(L, -3);
  1718. std::string videopixel = luax_checkstring(L, -2);
  1719. std::string arraypixel = luax_checkstring(L, -1);
  1720. lua_pop(L, 5);
  1721. Graphics::defaultShaderCode[Shader::STANDARD_DEFAULT][lang][i].source[ShaderStage::STAGE_VERTEX] = vertex;
  1722. Graphics::defaultShaderCode[Shader::STANDARD_DEFAULT][lang][i].source[ShaderStage::STAGE_PIXEL] = pixel;
  1723. Graphics::defaultShaderCode[Shader::STANDARD_VIDEO][lang][i].source[ShaderStage::STAGE_VERTEX] = vertex;
  1724. Graphics::defaultShaderCode[Shader::STANDARD_VIDEO][lang][i].source[ShaderStage::STAGE_PIXEL] = videopixel;
  1725. Graphics::defaultShaderCode[Shader::STANDARD_ARRAY][lang][i].source[ShaderStage::STAGE_VERTEX] = vertex;
  1726. Graphics::defaultShaderCode[Shader::STANDARD_ARRAY][lang][i].source[ShaderStage::STAGE_PIXEL] = arraypixel;
  1727. }
  1728. }
  1729. return 0;
  1730. }
  1731. int w_getSupported(lua_State *L)
  1732. {
  1733. const Graphics::Capabilities &caps = instance()->getCapabilities();
  1734. if (lua_istable(L, 1))
  1735. lua_pushvalue(L, 1);
  1736. else
  1737. lua_createtable(L, 0, (int) Graphics::FEATURE_MAX_ENUM);
  1738. for (int i = 0; i < (int) Graphics::FEATURE_MAX_ENUM; i++)
  1739. {
  1740. auto feature = (Graphics::Feature) i;
  1741. const char *name = nullptr;
  1742. if (!Graphics::getConstant(feature, name))
  1743. continue;
  1744. luax_pushboolean(L, caps.features[i]);
  1745. lua_setfield(L, -2, name);
  1746. }
  1747. return 1;
  1748. }
  1749. static int w__getFormats(lua_State *L, int idx, bool (*isFormatSupported)(PixelFormat), bool (*ignore)(PixelFormat))
  1750. {
  1751. if (lua_istable(L, idx))
  1752. lua_pushvalue(L, idx);
  1753. else
  1754. lua_createtable(L, 0, (int) PIXELFORMAT_MAX_ENUM);
  1755. for (int i = 0; i < (int) PIXELFORMAT_MAX_ENUM; i++)
  1756. {
  1757. PixelFormat format = (PixelFormat) i;
  1758. const char *name = nullptr;
  1759. if (format == PIXELFORMAT_UNKNOWN || !love::getConstant(format, name) || ignore(format))
  1760. continue;
  1761. luax_pushboolean(L, isFormatSupported(format));
  1762. lua_setfield(L, -2, name);
  1763. }
  1764. return 1;
  1765. }
  1766. int w_getCanvasFormats(lua_State *L)
  1767. {
  1768. bool (*supported)(PixelFormat);
  1769. int idx = 1;
  1770. if (lua_type(L, 1) == LUA_TBOOLEAN)
  1771. {
  1772. idx = 2;
  1773. if (luax_checkboolean(L, 1))
  1774. {
  1775. supported = [](PixelFormat format) -> bool
  1776. {
  1777. return instance()->isCanvasFormatSupported(format, true);
  1778. };
  1779. }
  1780. else
  1781. {
  1782. supported = [](PixelFormat format) -> bool
  1783. {
  1784. return instance()->isCanvasFormatSupported(format, false);
  1785. };
  1786. }
  1787. }
  1788. else
  1789. {
  1790. supported = [](PixelFormat format) -> bool
  1791. {
  1792. return instance()->isCanvasFormatSupported(format);
  1793. };
  1794. }
  1795. return w__getFormats(L, idx, supported, isPixelFormatCompressed);
  1796. }
  1797. int w_getImageFormats(lua_State *L)
  1798. {
  1799. const auto supported = [](PixelFormat format) -> bool
  1800. {
  1801. return instance()->isImageFormatSupported(format);
  1802. };
  1803. const auto ignore = [](PixelFormat format) -> bool
  1804. {
  1805. return !(image::ImageData::validPixelFormat(format) || isPixelFormatCompressed(format));
  1806. };
  1807. return w__getFormats(L, 1, supported, ignore);
  1808. }
  1809. int w_getTextureTypes(lua_State *L)
  1810. {
  1811. const Graphics::Capabilities &caps = instance()->getCapabilities();
  1812. if (lua_istable(L, 1))
  1813. lua_pushvalue(L, 1);
  1814. else
  1815. lua_createtable(L, 0, (int) TEXTURE_MAX_ENUM);
  1816. for (int i = 0; i < (int) TEXTURE_MAX_ENUM; i++)
  1817. {
  1818. TextureType textype = (TextureType) i;
  1819. const char *name = nullptr;
  1820. if (!Texture::getConstant(textype, name))
  1821. continue;
  1822. lua_pushnumber(L, caps.textureTypes[i]);
  1823. lua_setfield(L, -2, name);
  1824. }
  1825. return 1;
  1826. }
  1827. int w_getRendererInfo(lua_State *L)
  1828. {
  1829. Graphics::RendererInfo info;
  1830. luax_catchexcept(L, [&](){ info = instance()->getRendererInfo(); });
  1831. luax_pushstring(L, info.name);
  1832. luax_pushstring(L, info.version);
  1833. luax_pushstring(L, info.vendor);
  1834. luax_pushstring(L, info.device);
  1835. return 4;
  1836. }
  1837. int w_getSystemLimits(lua_State *L)
  1838. {
  1839. const Graphics::Capabilities &caps = instance()->getCapabilities();
  1840. if (lua_istable(L, 1))
  1841. lua_pushvalue(L, 1);
  1842. else
  1843. lua_createtable(L, 0, (int) Graphics::LIMIT_MAX_ENUM);
  1844. for (int i = 0; i < (int) Graphics::LIMIT_MAX_ENUM; i++)
  1845. {
  1846. Graphics::SystemLimit limittype = (Graphics::SystemLimit) i;
  1847. const char *name = nullptr;
  1848. if (!Graphics::getConstant(limittype, name))
  1849. continue;
  1850. lua_pushnumber(L, caps.limits[i]);
  1851. lua_setfield(L, -2, name);
  1852. }
  1853. return 1;
  1854. }
  1855. int w_getStats(lua_State *L)
  1856. {
  1857. Graphics::Stats stats = instance()->getStats();
  1858. if (lua_istable(L, 1))
  1859. lua_pushvalue(L, 1);
  1860. else
  1861. lua_createtable(L, 0, 7);
  1862. lua_pushinteger(L, stats.drawCalls);
  1863. lua_setfield(L, -2, "drawcalls");
  1864. lua_pushinteger(L, stats.drawCallsBatched);
  1865. lua_setfield(L, -2, "drawcallsbatched");
  1866. lua_pushinteger(L, stats.canvasSwitches);
  1867. lua_setfield(L, -2, "canvasswitches");
  1868. lua_pushinteger(L, stats.shaderSwitches);
  1869. lua_setfield(L, -2, "shaderswitches");
  1870. lua_pushinteger(L, stats.canvases);
  1871. lua_setfield(L, -2, "canvases");
  1872. lua_pushinteger(L, stats.images);
  1873. lua_setfield(L, -2, "images");
  1874. lua_pushinteger(L, stats.fonts);
  1875. lua_setfield(L, -2, "fonts");
  1876. lua_pushinteger(L, stats.textureMemory);
  1877. lua_setfield(L, -2, "texturememory");
  1878. return 1;
  1879. }
  1880. int w_draw(lua_State *L)
  1881. {
  1882. Drawable *drawable = nullptr;
  1883. Texture *texture = nullptr;
  1884. Quad *quad = nullptr;
  1885. int startidx = 2;
  1886. if (luax_istype(L, 2, Quad::type))
  1887. {
  1888. texture = luax_checktexture(L, 1);
  1889. quad = luax_totype<Quad>(L, 2);
  1890. startidx = 3;
  1891. }
  1892. else if (lua_isnil(L, 2) && !lua_isnoneornil(L, 3))
  1893. {
  1894. return luax_typerror(L, 2, "Quad");
  1895. }
  1896. else
  1897. {
  1898. drawable = luax_checktype<Drawable>(L, 1);
  1899. startidx = 2;
  1900. }
  1901. luax_checkstandardtransform(L, startidx, [&](const Matrix4 &m)
  1902. {
  1903. luax_catchexcept(L, [&]()
  1904. {
  1905. if (texture && quad)
  1906. instance()->draw(texture, quad, m);
  1907. else
  1908. instance()->draw(drawable, m);
  1909. });
  1910. });
  1911. return 0;
  1912. }
  1913. int w_drawLayer(lua_State *L)
  1914. {
  1915. Texture *texture = luax_checktexture(L, 1);
  1916. Quad *quad = nullptr;
  1917. int layer = (int) luaL_checkinteger(L, 2) - 1;
  1918. int startidx = 3;
  1919. if (luax_istype(L, startidx, Quad::type))
  1920. {
  1921. texture = luax_checktexture(L, 1);
  1922. quad = luax_totype<Quad>(L, startidx);
  1923. startidx++;
  1924. }
  1925. else if (lua_isnil(L, startidx) && !lua_isnoneornil(L, startidx + 1))
  1926. {
  1927. return luax_typerror(L, startidx, "Quad");
  1928. }
  1929. luax_checkstandardtransform(L, startidx, [&](const Matrix4 &m)
  1930. {
  1931. luax_catchexcept(L, [&]()
  1932. {
  1933. if (quad)
  1934. instance()->drawLayer(texture, layer, quad, m);
  1935. else
  1936. instance()->drawLayer(texture, layer, m);
  1937. });
  1938. });
  1939. return 0;
  1940. }
  1941. int w_drawInstanced(lua_State *L)
  1942. {
  1943. Mesh *t = luax_checkmesh(L, 1);
  1944. int instancecount = (int) luaL_checkinteger(L, 2);
  1945. luax_checkstandardtransform(L, 3, [&](const Matrix4 &m)
  1946. {
  1947. luax_catchexcept(L, [&]() { instance()->drawInstanced(t, m, instancecount); });
  1948. });
  1949. return 0;
  1950. }
  1951. int w_print(lua_State *L)
  1952. {
  1953. std::vector<Font::ColoredString> str;
  1954. luax_checkcoloredstring(L, 1, str);
  1955. if (luax_istype(L, 2, Font::type))
  1956. {
  1957. Font *font = luax_checkfont(L, 2);
  1958. luax_checkstandardtransform(L, 3, [&](const Matrix4 &m)
  1959. {
  1960. luax_catchexcept(L, [&](){ instance()->print(str, font, m); });
  1961. });
  1962. }
  1963. else
  1964. {
  1965. luax_checkstandardtransform(L, 2, [&](const Matrix4 &m)
  1966. {
  1967. luax_catchexcept(L, [&](){ instance()->print(str, m); });
  1968. });
  1969. }
  1970. return 0;
  1971. }
  1972. int w_printf(lua_State *L)
  1973. {
  1974. std::vector<Font::ColoredString> str;
  1975. luax_checkcoloredstring(L, 1, str);
  1976. Font *font = nullptr;
  1977. int startidx = 2;
  1978. if (luax_istype(L, startidx, Font::type))
  1979. {
  1980. font = luax_checkfont(L, startidx);
  1981. startidx++;
  1982. }
  1983. Font::AlignMode align = Font::ALIGN_LEFT;
  1984. Matrix4 m;
  1985. int formatidx = startidx + 2;
  1986. if (luax_istype(L, startidx, math::Transform::type))
  1987. {
  1988. math::Transform *tf = luax_totype<math::Transform>(L, startidx);
  1989. m = tf->getMatrix();
  1990. formatidx = startidx + 1;
  1991. }
  1992. else
  1993. {
  1994. float x = (float)luaL_checknumber(L, startidx + 0);
  1995. float y = (float)luaL_checknumber(L, startidx + 1);
  1996. float angle = (float) luaL_optnumber(L, startidx + 4, 0.0f);
  1997. float sx = (float) luaL_optnumber(L, startidx + 5, 1.0f);
  1998. float sy = (float) luaL_optnumber(L, startidx + 6, sx);
  1999. float ox = (float) luaL_optnumber(L, startidx + 7, 0.0f);
  2000. float oy = (float) luaL_optnumber(L, startidx + 8, 0.0f);
  2001. float kx = (float) luaL_optnumber(L, startidx + 9, 0.0f);
  2002. float ky = (float) luaL_optnumber(L, startidx + 10, 0.0f);
  2003. m = Matrix4(x, y, angle, sx, sy, ox, oy, kx, ky);
  2004. }
  2005. float wrap = (float)luaL_checknumber(L, formatidx);
  2006. const char *astr = lua_isnoneornil(L, formatidx + 1) ? nullptr : luaL_checkstring(L, formatidx + 1);
  2007. if (astr != nullptr && !Font::getConstant(astr, align))
  2008. return luax_enumerror(L, "alignment", Font::getConstants(align), astr);
  2009. if (font != nullptr)
  2010. luax_catchexcept(L, [&](){ instance()->printf(str, font, wrap, align, m); });
  2011. else
  2012. luax_catchexcept(L, [&](){ instance()->printf(str, wrap, align, m); });
  2013. return 0;
  2014. }
  2015. int w_points(lua_State *L)
  2016. {
  2017. // love.graphics.points has 3 variants:
  2018. // - points(x1, y1, x2, y2, ...)
  2019. // - points({x1, y1, x2, y2, ...})
  2020. // - points({{x1, y1 [, r, g, b, a]}, {x2, y2 [, r, g, b, a]}, ...})
  2021. int args = lua_gettop(L);
  2022. bool is_table = false;
  2023. bool is_table_of_tables = false;
  2024. if (args == 1 && lua_istable(L, 1))
  2025. {
  2026. is_table = true;
  2027. args = (int) luax_objlen(L, 1);
  2028. lua_rawgeti(L, 1, 1);
  2029. is_table_of_tables = lua_istable(L, -1);
  2030. lua_pop(L, 1);
  2031. }
  2032. if (args % 2 != 0 && !is_table_of_tables)
  2033. return luaL_error(L, "Number of vertex components must be a multiple of two");
  2034. int numpositions = args / 2;
  2035. if (is_table_of_tables)
  2036. numpositions = args;
  2037. Vector2 *positions = nullptr;
  2038. Colorf *colors = nullptr;
  2039. if (is_table_of_tables)
  2040. {
  2041. size_t datasize = (sizeof(Vector2) + sizeof(Colorf)) * numpositions;
  2042. uint8 *data = instance()->getScratchBuffer<uint8>(datasize);
  2043. positions = (Vector2 *) data;
  2044. colors = (Colorf *) (data + sizeof(Vector2) * numpositions);
  2045. }
  2046. else
  2047. positions = instance()->getScratchBuffer<Vector2>(numpositions);
  2048. if (is_table)
  2049. {
  2050. if (is_table_of_tables)
  2051. {
  2052. // points({{x1, y1 [, r, g, b, a]}, {x2, y2 [, r, g, b, a]}, ...})
  2053. for (int i = 0; i < args; i++)
  2054. {
  2055. lua_rawgeti(L, 1, i + 1);
  2056. for (int j = 1; j <= 6; j++)
  2057. lua_rawgeti(L, -j, j);
  2058. positions[i].x = luax_checkfloat(L, -6);
  2059. positions[i].y = luax_checkfloat(L, -5);
  2060. colors[i].r = (float) luax_optnumberclamped01(L, -4, 1.0);
  2061. colors[i].g = (float) luax_optnumberclamped01(L, -3, 1.0);
  2062. colors[i].b = (float) luax_optnumberclamped01(L, -2, 1.0);
  2063. colors[i].a = (float) luax_optnumberclamped01(L, -1, 1.0);
  2064. lua_pop(L, 7);
  2065. }
  2066. }
  2067. else
  2068. {
  2069. // points({x1, y1, x2, y2, ...})
  2070. for (int i = 0; i < numpositions; i++)
  2071. {
  2072. lua_rawgeti(L, 1, i * 2 + 1);
  2073. lua_rawgeti(L, 1, i * 2 + 2);
  2074. positions[i].x = luax_checkfloat(L, -2);
  2075. positions[i].y = luax_checkfloat(L, -1);
  2076. lua_pop(L, 2);
  2077. }
  2078. }
  2079. }
  2080. else
  2081. {
  2082. for (int i = 0; i < numpositions; i++)
  2083. {
  2084. positions[i].x = luax_checkfloat(L, i * 2 + 1);
  2085. positions[i].y = luax_checkfloat(L, i * 2 + 2);
  2086. }
  2087. }
  2088. luax_catchexcept(L, [&](){ instance()->points(positions, colors, numpositions); });
  2089. return 0;
  2090. }
  2091. int w_line(lua_State *L)
  2092. {
  2093. int args = lua_gettop(L);
  2094. int arg1type = lua_type(L, 1);
  2095. bool is_table = false;
  2096. if (args == 1 && arg1type == LUA_TTABLE)
  2097. {
  2098. args = (int) luax_objlen(L, 1);
  2099. is_table = true;
  2100. }
  2101. if (arg1type != LUA_TTABLE && arg1type != LUA_TNUMBER)
  2102. return luax_typerror(L, 1, "table or number");
  2103. else if (args % 2 != 0)
  2104. return luaL_error(L, "Number of vertex components must be a multiple of two.");
  2105. else if (args < 4)
  2106. return luaL_error(L, "Need at least two vertices to draw a line.");
  2107. int numvertices = args / 2;
  2108. Vector2 *coords = instance()->getScratchBuffer<Vector2>(numvertices);
  2109. if (is_table)
  2110. {
  2111. for (int i = 0; i < numvertices; ++i)
  2112. {
  2113. lua_rawgeti(L, 1, (i * 2) + 1);
  2114. lua_rawgeti(L, 1, (i * 2) + 2);
  2115. coords[i].x = luax_checkfloat(L, -2);
  2116. coords[i].y = luax_checkfloat(L, -1);
  2117. lua_pop(L, 2);
  2118. }
  2119. }
  2120. else
  2121. {
  2122. for (int i = 0; i < numvertices; ++i)
  2123. {
  2124. coords[i].x = luax_checkfloat(L, (i * 2) + 1);
  2125. coords[i].y = luax_checkfloat(L, (i * 2) + 2);
  2126. }
  2127. }
  2128. luax_catchexcept(L,
  2129. [&](){ instance()->polyline(coords, numvertices); }
  2130. );
  2131. return 0;
  2132. }
  2133. int w_rectangle(lua_State *L)
  2134. {
  2135. Graphics::DrawMode mode;
  2136. const char *str = luaL_checkstring(L, 1);
  2137. if (!Graphics::getConstant(str, mode))
  2138. return luax_enumerror(L, "draw mode", Graphics::getConstants(mode), str);
  2139. float x = (float)luaL_checknumber(L, 2);
  2140. float y = (float)luaL_checknumber(L, 3);
  2141. float w = (float)luaL_checknumber(L, 4);
  2142. float h = (float)luaL_checknumber(L, 5);
  2143. if (lua_isnoneornil(L, 6))
  2144. {
  2145. instance()->rectangle(mode, x, y, w, h);
  2146. return 0;
  2147. }
  2148. float rx = (float)luaL_optnumber(L, 6, 0.0);
  2149. float ry = (float)luaL_optnumber(L, 7, rx);
  2150. if (lua_isnoneornil(L, 8))
  2151. luax_catchexcept(L, [&](){ instance()->rectangle(mode, x, y, w, h, rx, ry); });
  2152. else
  2153. {
  2154. int points = (int) luaL_checkinteger(L, 8);
  2155. luax_catchexcept(L, [&](){ instance()->rectangle(mode, x, y, w, h, rx, ry, points); });
  2156. }
  2157. return 0;
  2158. }
  2159. int w_circle(lua_State *L)
  2160. {
  2161. Graphics::DrawMode mode;
  2162. const char *str = luaL_checkstring(L, 1);
  2163. if (!Graphics::getConstant(str, mode))
  2164. return luax_enumerror(L, "draw mode", Graphics::getConstants(mode), str);
  2165. float x = (float)luaL_checknumber(L, 2);
  2166. float y = (float)luaL_checknumber(L, 3);
  2167. float radius = (float)luaL_checknumber(L, 4);
  2168. if (lua_isnoneornil(L, 5))
  2169. luax_catchexcept(L, [&](){ instance()->circle(mode, x, y, radius); });
  2170. else
  2171. {
  2172. int points = (int) luaL_checkinteger(L, 5);
  2173. luax_catchexcept(L, [&](){ instance()->circle(mode, x, y, radius, points); });
  2174. }
  2175. return 0;
  2176. }
  2177. int w_ellipse(lua_State *L)
  2178. {
  2179. Graphics::DrawMode mode;
  2180. const char *str = luaL_checkstring(L, 1);
  2181. if (!Graphics::getConstant(str, mode))
  2182. return luax_enumerror(L, "draw mode", Graphics::getConstants(mode), str);
  2183. float x = (float)luaL_checknumber(L, 2);
  2184. float y = (float)luaL_checknumber(L, 3);
  2185. float a = (float)luaL_checknumber(L, 4);
  2186. float b = (float)luaL_optnumber(L, 5, a);
  2187. if (lua_isnoneornil(L, 6))
  2188. luax_catchexcept(L, [&](){ instance()->ellipse(mode, x, y, a, b); });
  2189. else
  2190. {
  2191. int points = (int) luaL_checkinteger(L, 6);
  2192. luax_catchexcept(L, [&](){ instance()->ellipse(mode, x, y, a, b, points); });
  2193. }
  2194. return 0;
  2195. }
  2196. int w_arc(lua_State *L)
  2197. {
  2198. Graphics::DrawMode drawmode;
  2199. const char *drawstr = luaL_checkstring(L, 1);
  2200. if (!Graphics::getConstant(drawstr, drawmode))
  2201. return luax_enumerror(L, "draw mode", Graphics::getConstants(drawmode), drawstr);
  2202. int startidx = 2;
  2203. Graphics::ArcMode arcmode = Graphics::ARC_PIE;
  2204. if (lua_type(L, 2) == LUA_TSTRING)
  2205. {
  2206. const char *arcstr = luaL_checkstring(L, 2);
  2207. if (!Graphics::getConstant(arcstr, arcmode))
  2208. return luax_enumerror(L, "arc mode", Graphics::getConstants(arcmode), arcstr);
  2209. startidx = 3;
  2210. }
  2211. float x = (float) luaL_checknumber(L, startidx + 0);
  2212. float y = (float) luaL_checknumber(L, startidx + 1);
  2213. float radius = (float) luaL_checknumber(L, startidx + 2);
  2214. float angle1 = (float) luaL_checknumber(L, startidx + 3);
  2215. float angle2 = (float) luaL_checknumber(L, startidx + 4);
  2216. if (lua_isnoneornil(L, startidx + 5))
  2217. luax_catchexcept(L, [&](){ instance()->arc(drawmode, arcmode, x, y, radius, angle1, angle2); });
  2218. else
  2219. {
  2220. int points = (int) luaL_checkinteger(L, startidx + 5);
  2221. luax_catchexcept(L, [&](){ instance()->arc(drawmode, arcmode, x, y, radius, angle1, angle2, points); });
  2222. }
  2223. return 0;
  2224. }
  2225. int w_polygon(lua_State *L)
  2226. {
  2227. int args = lua_gettop(L) - 1;
  2228. Graphics::DrawMode mode;
  2229. const char *str = luaL_checkstring(L, 1);
  2230. if (!Graphics::getConstant(str, mode))
  2231. return luax_enumerror(L, "draw mode", Graphics::getConstants(mode), str);
  2232. bool is_table = false;
  2233. if (args == 1 && lua_istable(L, 2))
  2234. {
  2235. args = (int) luax_objlen(L, 2);
  2236. is_table = true;
  2237. }
  2238. if (args % 2 != 0)
  2239. return luaL_error(L, "Number of vertex components must be a multiple of two");
  2240. else if (args < 6)
  2241. return luaL_error(L, "Need at least three vertices to draw a polygon");
  2242. int numvertices = args / 2;
  2243. // fetch coords
  2244. Vector2 *coords = instance()->getScratchBuffer<Vector2>(numvertices + 1);
  2245. if (is_table)
  2246. {
  2247. for (int i = 0; i < numvertices; ++i)
  2248. {
  2249. lua_rawgeti(L, 2, (i * 2) + 1);
  2250. lua_rawgeti(L, 2, (i * 2) + 2);
  2251. coords[i].x = luax_checkfloat(L, -2);
  2252. coords[i].y = luax_checkfloat(L, -1);
  2253. lua_pop(L, 2);
  2254. }
  2255. }
  2256. else
  2257. {
  2258. for (int i = 0; i < numvertices; ++i)
  2259. {
  2260. coords[i].x = luax_checkfloat(L, (i * 2) + 2);
  2261. coords[i].y = luax_checkfloat(L, (i * 2) + 3);
  2262. }
  2263. }
  2264. // make a closed loop
  2265. coords[numvertices] = coords[0];
  2266. luax_catchexcept(L, [&](){ instance()->polygon(mode, coords, numvertices+1); });
  2267. return 0;
  2268. }
  2269. int w_flushBatch(lua_State *)
  2270. {
  2271. instance()->flushStreamDraws();
  2272. return 0;
  2273. }
  2274. int w_getStackDepth(lua_State *L)
  2275. {
  2276. lua_pushnumber(L, instance()->getStackDepth());
  2277. return 1;
  2278. }
  2279. int w_push(lua_State *L)
  2280. {
  2281. Graphics::StackType stype = Graphics::STACK_TRANSFORM;
  2282. const char *sname = lua_isnoneornil(L, 1) ? nullptr : luaL_checkstring(L, 1);
  2283. if (sname && !Graphics::getConstant(sname, stype))
  2284. return luax_enumerror(L, "graphics stack type", Graphics::getConstants(stype), sname);
  2285. luax_catchexcept(L, [&](){ instance()->push(stype); });
  2286. if (luax_istype(L, 2, math::Transform::type))
  2287. {
  2288. math::Transform *t = luax_totype<math::Transform>(L, 2);
  2289. luax_catchexcept(L, [&]() { instance()->applyTransform(t); });
  2290. }
  2291. return 0;
  2292. }
  2293. int w_pop(lua_State *L)
  2294. {
  2295. luax_catchexcept(L, [&](){ instance()->pop(); });
  2296. return 0;
  2297. }
  2298. int w_rotate(lua_State *L)
  2299. {
  2300. float angle = (float)luaL_checknumber(L, 1);
  2301. instance()->rotate(angle);
  2302. return 0;
  2303. }
  2304. int w_scale(lua_State *L)
  2305. {
  2306. float sx = (float)luaL_optnumber(L, 1, 1.0f);
  2307. float sy = (float)luaL_optnumber(L, 2, sx);
  2308. instance()->scale(sx, sy);
  2309. return 0;
  2310. }
  2311. int w_translate(lua_State *L)
  2312. {
  2313. float x = (float)luaL_checknumber(L, 1);
  2314. float y = (float)luaL_checknumber(L, 2);
  2315. instance()->translate(x, y);
  2316. return 0;
  2317. }
  2318. int w_shear(lua_State *L)
  2319. {
  2320. float kx = (float)luaL_checknumber(L, 1);
  2321. float ky = (float)luaL_checknumber(L, 2);
  2322. instance()->shear(kx, ky);
  2323. return 0;
  2324. }
  2325. int w_origin(lua_State * /*L*/)
  2326. {
  2327. instance()->origin();
  2328. return 0;
  2329. }
  2330. int w_applyTransform(lua_State *L)
  2331. {
  2332. math::Transform *t = math::luax_checktransform(L, 1);
  2333. luax_catchexcept(L, [&]() { instance()->applyTransform(t); });
  2334. return 0;
  2335. }
  2336. int w_replaceTransform(lua_State *L)
  2337. {
  2338. math::Transform *t = math::luax_checktransform(L, 1);
  2339. luax_catchexcept(L, [&]() { instance()->replaceTransform(t); });
  2340. return 0;
  2341. }
  2342. int w_transformPoint(lua_State *L)
  2343. {
  2344. Vector2 p;
  2345. p.x = (float) luaL_checknumber(L, 1);
  2346. p.y = (float) luaL_checknumber(L, 2);
  2347. p = instance()->transformPoint(p);
  2348. lua_pushnumber(L, p.x);
  2349. lua_pushnumber(L, p.y);
  2350. return 2;
  2351. }
  2352. int w_inverseTransformPoint(lua_State *L)
  2353. {
  2354. Vector2 p;
  2355. p.x = (float) luaL_checknumber(L, 1);
  2356. p.y = (float) luaL_checknumber(L, 2);
  2357. p = instance()->inverseTransformPoint(p);
  2358. lua_pushnumber(L, p.x);
  2359. lua_pushnumber(L, p.y);
  2360. return 2;
  2361. }
  2362. // List of functions to wrap.
  2363. static const luaL_Reg functions[] =
  2364. {
  2365. { "reset", w_reset },
  2366. { "clear", w_clear },
  2367. { "discard", w_discard },
  2368. { "present", w_present },
  2369. { "newImage", w_newImage },
  2370. { "newArrayImage", w_newArrayImage },
  2371. { "newVolumeImage", w_newVolumeImage },
  2372. { "newCubeImage", w_newCubeImage },
  2373. { "newQuad", w_newQuad },
  2374. { "newFont", w_newFont },
  2375. { "newImageFont", w_newImageFont },
  2376. { "newSpriteBatch", w_newSpriteBatch },
  2377. { "newParticleSystem", w_newParticleSystem },
  2378. { "newCanvas", w_newCanvas },
  2379. { "newShader", w_newShader },
  2380. { "newMesh", w_newMesh },
  2381. { "newText", w_newText },
  2382. { "_newVideo", w_newVideo },
  2383. { "validateShader", w_validateShader },
  2384. { "setCanvas", w_setCanvas },
  2385. { "getCanvas", w_getCanvas },
  2386. { "setColor", w_setColor },
  2387. { "getColor", w_getColor },
  2388. { "setBackgroundColor", w_setBackgroundColor },
  2389. { "getBackgroundColor", w_getBackgroundColor },
  2390. { "setNewFont", w_setNewFont },
  2391. { "setFont", w_setFont },
  2392. { "getFont", w_getFont },
  2393. { "setColorMask", w_setColorMask },
  2394. { "getColorMask", w_getColorMask },
  2395. { "setBlendMode", w_setBlendMode },
  2396. { "getBlendMode", w_getBlendMode },
  2397. { "setDefaultFilter", w_setDefaultFilter },
  2398. { "getDefaultFilter", w_getDefaultFilter },
  2399. { "setDefaultMipmapFilter", w_setDefaultMipmapFilter },
  2400. { "getDefaultMipmapFilter", w_getDefaultMipmapFilter },
  2401. { "setLineWidth", w_setLineWidth },
  2402. { "setLineStyle", w_setLineStyle },
  2403. { "setLineJoin", w_setLineJoin },
  2404. { "getLineWidth", w_getLineWidth },
  2405. { "getLineStyle", w_getLineStyle },
  2406. { "getLineJoin", w_getLineJoin },
  2407. { "setPointSize", w_setPointSize },
  2408. { "getPointSize", w_getPointSize },
  2409. { "setDepthMode", w_setDepthMode },
  2410. { "getDepthMode", w_getDepthMode },
  2411. { "setMeshCullMode", w_setMeshCullMode },
  2412. { "getMeshCullMode", w_getMeshCullMode },
  2413. { "setFrontFaceWinding", w_setFrontFaceWinding },
  2414. { "getFrontFaceWinding", w_getFrontFaceWinding },
  2415. { "setWireframe", w_setWireframe },
  2416. { "isWireframe", w_isWireframe },
  2417. { "setShader", w_setShader },
  2418. { "getShader", w_getShader },
  2419. { "_setDefaultShaderCode", w_setDefaultShaderCode },
  2420. { "getSupported", w_getSupported },
  2421. { "getCanvasFormats", w_getCanvasFormats },
  2422. { "getImageFormats", w_getImageFormats },
  2423. { "getRendererInfo", w_getRendererInfo },
  2424. { "getSystemLimits", w_getSystemLimits },
  2425. { "getTextureTypes", w_getTextureTypes },
  2426. { "getStats", w_getStats },
  2427. { "captureScreenshot", w_captureScreenshot },
  2428. { "draw", w_draw },
  2429. { "drawLayer", w_drawLayer },
  2430. { "drawInstanced", w_drawInstanced },
  2431. { "print", w_print },
  2432. { "printf", w_printf },
  2433. { "isCreated", w_isCreated },
  2434. { "isActive", w_isActive },
  2435. { "isGammaCorrect", w_isGammaCorrect },
  2436. { "getWidth", w_getWidth },
  2437. { "getHeight", w_getHeight },
  2438. { "getDimensions", w_getDimensions },
  2439. { "getPixelWidth", w_getPixelWidth },
  2440. { "getPixelHeight", w_getPixelHeight },
  2441. { "getPixelDimensions", w_getPixelDimensions },
  2442. { "getDPIScale", w_getDPIScale },
  2443. { "setScissor", w_setScissor },
  2444. { "intersectScissor", w_intersectScissor },
  2445. { "getScissor", w_getScissor },
  2446. { "stencil", w_stencil },
  2447. { "setStencilTest", w_setStencilTest },
  2448. { "getStencilTest", w_getStencilTest },
  2449. { "points", w_points },
  2450. { "line", w_line },
  2451. { "rectangle", w_rectangle },
  2452. { "circle", w_circle },
  2453. { "ellipse", w_ellipse },
  2454. { "arc", w_arc },
  2455. { "polygon", w_polygon },
  2456. { "flushBatch", w_flushBatch },
  2457. { "getStackDepth", w_getStackDepth },
  2458. { "push", w_push },
  2459. { "pop", w_pop },
  2460. { "rotate", w_rotate },
  2461. { "scale", w_scale },
  2462. { "translate", w_translate },
  2463. { "shear", w_shear },
  2464. { "origin", w_origin },
  2465. { "applyTransform", w_applyTransform },
  2466. { "replaceTransform", w_replaceTransform },
  2467. { "transformPoint", w_transformPoint },
  2468. { "inverseTransformPoint", w_inverseTransformPoint },
  2469. { 0, 0 }
  2470. };
  2471. static int luaopen_drawable(lua_State *L)
  2472. {
  2473. return luax_register_type(L, &Drawable::type, nullptr);
  2474. }
  2475. // Types for this module.
  2476. static const lua_CFunction types[] =
  2477. {
  2478. luaopen_drawable,
  2479. luaopen_texture,
  2480. luaopen_font,
  2481. luaopen_image,
  2482. luaopen_quad,
  2483. luaopen_spritebatch,
  2484. luaopen_particlesystem,
  2485. luaopen_canvas,
  2486. luaopen_shader,
  2487. luaopen_mesh,
  2488. luaopen_text,
  2489. luaopen_video,
  2490. 0
  2491. };
  2492. extern "C" int luaopen_love_graphics(lua_State *L)
  2493. {
  2494. Graphics *instance = instance();
  2495. if (instance == nullptr)
  2496. {
  2497. luax_catchexcept(L, [&](){ instance = new love::graphics::opengl::Graphics(); });
  2498. }
  2499. else
  2500. instance->retain();
  2501. WrappedModule w;
  2502. w.module = instance;
  2503. w.name = "graphics";
  2504. w.type = &Graphics::type;
  2505. w.functions = functions;
  2506. w.types = types;
  2507. int n = luax_register_module(L, w);
  2508. if (luaL_loadbuffer(L, (const char *)graphics_lua, sizeof(graphics_lua), "wrap_Graphics.lua") == 0)
  2509. lua_call(L, 0, 0);
  2510. else
  2511. lua_error(L);
  2512. if (luaL_loadbuffer(L, (const char *)graphics_shader_lua, sizeof(graphics_shader_lua), "wrap_GraphicsShader.lua") == 0)
  2513. lua_call(L, 0, 0);
  2514. else
  2515. lua_error(L);
  2516. return n;
  2517. }
  2518. } // graphics
  2519. } // love