l_env.cpp 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include <algorithm>
  17. #include "lua_api/l_env.h"
  18. #include "lua_api/l_internal.h"
  19. #include "lua_api/l_nodemeta.h"
  20. #include "lua_api/l_nodetimer.h"
  21. #include "lua_api/l_noise.h"
  22. #include "lua_api/l_vmanip.h"
  23. #include "common/c_converter.h"
  24. #include "common/c_content.h"
  25. #include "scripting_server.h"
  26. #include "environment.h"
  27. #include "mapblock.h"
  28. #include "server.h"
  29. #include "nodedef.h"
  30. #include "daynightratio.h"
  31. #include "util/pointedthing.h"
  32. #include "mapgen/treegen.h"
  33. #include "emerge.h"
  34. #include "pathfinder.h"
  35. #include "face_position_cache.h"
  36. #include "remoteplayer.h"
  37. #include "server/luaentity_sao.h"
  38. #include "server/player_sao.h"
  39. #include "util/string.h"
  40. #include "translation.h"
  41. #ifndef SERVER
  42. #include "client/client.h"
  43. #endif
  44. const EnumString ModApiEnvMod::es_ClearObjectsMode[] =
  45. {
  46. {CLEAR_OBJECTS_MODE_FULL, "full"},
  47. {CLEAR_OBJECTS_MODE_QUICK, "quick"},
  48. {0, NULL},
  49. };
  50. const EnumString ModApiEnvMod::es_BlockStatusType[] =
  51. {
  52. {ServerEnvironment::BS_UNKNOWN, "unknown"},
  53. {ServerEnvironment::BS_EMERGING, "emerging"},
  54. {ServerEnvironment::BS_LOADED, "loaded"},
  55. {ServerEnvironment::BS_ACTIVE, "active"},
  56. {0, NULL},
  57. };
  58. ///////////////////////////////////////////////////////////////////////////////
  59. void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
  60. u32 active_object_count, u32 active_object_count_wider)
  61. {
  62. ServerScripting *scriptIface = env->getScriptIface();
  63. scriptIface->realityCheck();
  64. lua_State *L = scriptIface->getStack();
  65. sanity_check(lua_checkstack(L, 20));
  66. StackUnroller stack_unroller(L);
  67. int error_handler = PUSH_ERROR_HANDLER(L);
  68. // Get registered_abms
  69. lua_getglobal(L, "core");
  70. lua_getfield(L, -1, "registered_abms");
  71. luaL_checktype(L, -1, LUA_TTABLE);
  72. lua_remove(L, -2); // Remove core
  73. // Get registered_abms[m_id]
  74. lua_pushinteger(L, m_id);
  75. lua_gettable(L, -2);
  76. if(lua_isnil(L, -1))
  77. FATAL_ERROR("");
  78. lua_remove(L, -2); // Remove registered_abms
  79. scriptIface->setOriginFromTable(-1);
  80. // Call action
  81. luaL_checktype(L, -1, LUA_TTABLE);
  82. lua_getfield(L, -1, "action");
  83. luaL_checktype(L, -1, LUA_TFUNCTION);
  84. lua_remove(L, -2); // Remove registered_abms[m_id]
  85. push_v3s16(L, p);
  86. pushnode(L, n);
  87. lua_pushnumber(L, active_object_count);
  88. lua_pushnumber(L, active_object_count_wider);
  89. int result = lua_pcall(L, 4, 0, error_handler);
  90. if (result)
  91. scriptIface->scriptError(result, "LuaABM::trigger");
  92. lua_pop(L, 1); // Pop error handler
  93. }
  94. void LuaLBM::trigger(ServerEnvironment *env, v3s16 p,
  95. const MapNode n, const float dtime_s)
  96. {
  97. ServerScripting *scriptIface = env->getScriptIface();
  98. scriptIface->realityCheck();
  99. lua_State *L = scriptIface->getStack();
  100. sanity_check(lua_checkstack(L, 20));
  101. StackUnroller stack_unroller(L);
  102. int error_handler = PUSH_ERROR_HANDLER(L);
  103. // Get registered_lbms
  104. lua_getglobal(L, "core");
  105. lua_getfield(L, -1, "registered_lbms");
  106. luaL_checktype(L, -1, LUA_TTABLE);
  107. lua_remove(L, -2); // Remove core
  108. // Get registered_lbms[m_id]
  109. lua_pushinteger(L, m_id);
  110. lua_gettable(L, -2);
  111. FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table");
  112. lua_remove(L, -2); // Remove registered_lbms
  113. scriptIface->setOriginFromTable(-1);
  114. // Call action
  115. luaL_checktype(L, -1, LUA_TTABLE);
  116. lua_getfield(L, -1, "action");
  117. luaL_checktype(L, -1, LUA_TFUNCTION);
  118. lua_remove(L, -2); // Remove registered_lbms[m_id]
  119. push_v3s16(L, p);
  120. pushnode(L, n);
  121. lua_pushnumber(L, dtime_s);
  122. int result = lua_pcall(L, 3, 0, error_handler);
  123. if (result)
  124. scriptIface->scriptError(result, "LuaLBM::trigger");
  125. lua_pop(L, 1); // Pop error handler
  126. }
  127. int LuaRaycast::l_next(lua_State *L)
  128. {
  129. GET_PLAIN_ENV_PTR;
  130. bool csm = false;
  131. #ifndef SERVER
  132. csm = getClient(L) != nullptr;
  133. #endif
  134. LuaRaycast *o = checkObject<LuaRaycast>(L, 1);
  135. PointedThing pointed;
  136. env->continueRaycast(&o->state, &pointed);
  137. if (pointed.type == POINTEDTHING_NOTHING)
  138. lua_pushnil(L);
  139. else
  140. push_pointed_thing(L, pointed, csm, true);
  141. return 1;
  142. }
  143. int LuaRaycast::create_object(lua_State *L)
  144. {
  145. NO_MAP_LOCK_REQUIRED;
  146. bool objects = true;
  147. bool liquids = false;
  148. v3f pos1 = checkFloatPos(L, 1);
  149. v3f pos2 = checkFloatPos(L, 2);
  150. if (lua_isboolean(L, 3)) {
  151. objects = readParam<bool>(L, 3);
  152. }
  153. if (lua_isboolean(L, 4)) {
  154. liquids = readParam<bool>(L, 4);
  155. }
  156. LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2),
  157. objects, liquids);
  158. *(void **) (lua_newuserdata(L, sizeof(void *))) = o;
  159. luaL_getmetatable(L, className);
  160. lua_setmetatable(L, -2);
  161. return 1;
  162. }
  163. int LuaRaycast::gc_object(lua_State *L)
  164. {
  165. LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1));
  166. delete o;
  167. return 0;
  168. }
  169. void LuaRaycast::Register(lua_State *L)
  170. {
  171. static const luaL_Reg metamethods[] = {
  172. {"__call", l_next},
  173. {"__gc", gc_object},
  174. {0, 0}
  175. };
  176. registerClass(L, className, methods, metamethods);
  177. lua_register(L, className, create_object);
  178. }
  179. const char LuaRaycast::className[] = "Raycast";
  180. const luaL_Reg LuaRaycast::methods[] =
  181. {
  182. luamethod(LuaRaycast, next),
  183. { 0, 0 }
  184. };
  185. void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param)
  186. {
  187. ScriptCallbackState *state = (ScriptCallbackState *)param;
  188. assert(state != NULL);
  189. assert(state->script != NULL);
  190. assert(state->refcount > 0);
  191. // state must be protected by envlock
  192. Server *server = state->script->getServer();
  193. MutexAutoLock envlock(server->m_env_mutex);
  194. state->refcount--;
  195. state->script->on_emerge_area_completion(blockpos, action, state);
  196. if (state->refcount == 0)
  197. delete state;
  198. }
  199. // Exported functions
  200. // set_node(pos, node)
  201. // pos = {x=num, y=num, z=num}
  202. int ModApiEnvMod::l_set_node(lua_State *L)
  203. {
  204. GET_ENV_PTR;
  205. // parameters
  206. v3s16 pos = read_v3s16(L, 1);
  207. MapNode n = readnode(L, 2);
  208. // Do it
  209. bool succeeded = env->setNode(pos, n);
  210. lua_pushboolean(L, succeeded);
  211. return 1;
  212. }
  213. // bulk_set_node([pos1, pos2, ...], node)
  214. // pos = {x=num, y=num, z=num}
  215. int ModApiEnvMod::l_bulk_set_node(lua_State *L)
  216. {
  217. GET_ENV_PTR;
  218. // parameters
  219. if (!lua_istable(L, 1)) {
  220. return 0;
  221. }
  222. s32 len = lua_objlen(L, 1);
  223. if (len == 0) {
  224. lua_pushboolean(L, true);
  225. return 1;
  226. }
  227. MapNode n = readnode(L, 2);
  228. // Do it
  229. bool succeeded = true;
  230. for (s32 i = 1; i <= len; i++) {
  231. lua_rawgeti(L, 1, i);
  232. if (!env->setNode(read_v3s16(L, -1), n))
  233. succeeded = false;
  234. lua_pop(L, 1);
  235. }
  236. lua_pushboolean(L, succeeded);
  237. return 1;
  238. }
  239. int ModApiEnvMod::l_add_node(lua_State *L)
  240. {
  241. return l_set_node(L);
  242. }
  243. // remove_node(pos)
  244. // pos = {x=num, y=num, z=num}
  245. int ModApiEnvMod::l_remove_node(lua_State *L)
  246. {
  247. GET_ENV_PTR;
  248. // parameters
  249. v3s16 pos = read_v3s16(L, 1);
  250. // Do it
  251. bool succeeded = env->removeNode(pos);
  252. lua_pushboolean(L, succeeded);
  253. return 1;
  254. }
  255. // swap_node(pos, node)
  256. // pos = {x=num, y=num, z=num}
  257. int ModApiEnvMod::l_swap_node(lua_State *L)
  258. {
  259. GET_ENV_PTR;
  260. // parameters
  261. v3s16 pos = read_v3s16(L, 1);
  262. MapNode n = readnode(L, 2);
  263. // Do it
  264. bool succeeded = env->swapNode(pos, n);
  265. lua_pushboolean(L, succeeded);
  266. return 1;
  267. }
  268. // get_node(pos)
  269. // pos = {x=num, y=num, z=num}
  270. int ModApiEnvMod::l_get_node(lua_State *L)
  271. {
  272. GET_ENV_PTR;
  273. // pos
  274. v3s16 pos = read_v3s16(L, 1);
  275. // Do it
  276. MapNode n = env->getMap().getNode(pos);
  277. // Return node
  278. pushnode(L, n);
  279. return 1;
  280. }
  281. // get_node_or_nil(pos)
  282. // pos = {x=num, y=num, z=num}
  283. int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
  284. {
  285. GET_ENV_PTR;
  286. // pos
  287. v3s16 pos = read_v3s16(L, 1);
  288. // Do it
  289. bool pos_ok;
  290. MapNode n = env->getMap().getNode(pos, &pos_ok);
  291. if (pos_ok) {
  292. // Return node
  293. pushnode(L, n);
  294. } else {
  295. lua_pushnil(L);
  296. }
  297. return 1;
  298. }
  299. // get_node_light(pos, timeofday)
  300. // pos = {x=num, y=num, z=num}
  301. // timeofday: nil = current time, 0 = night, 0.5 = day
  302. int ModApiEnvMod::l_get_node_light(lua_State *L)
  303. {
  304. GET_PLAIN_ENV_PTR;
  305. // Do it
  306. v3s16 pos = read_v3s16(L, 1);
  307. u32 time_of_day = env->getTimeOfDay();
  308. if(lua_isnumber(L, 2))
  309. time_of_day = 24000.0 * lua_tonumber(L, 2);
  310. time_of_day %= 24000;
  311. u32 dnr = time_to_daynight_ratio(time_of_day, true);
  312. bool is_position_ok;
  313. MapNode n = env->getMap().getNode(pos, &is_position_ok);
  314. if (is_position_ok) {
  315. const NodeDefManager *ndef = env->getGameDef()->ndef();
  316. lua_pushinteger(L, n.getLightBlend(dnr, ndef->getLightingFlags(n)));
  317. } else {
  318. lua_pushnil(L);
  319. }
  320. return 1;
  321. }
  322. // get_natural_light(pos, timeofday)
  323. // pos = {x=num, y=num, z=num}
  324. // timeofday: nil = current time, 0 = night, 0.5 = day
  325. int ModApiEnvMod::l_get_natural_light(lua_State *L)
  326. {
  327. GET_ENV_PTR;
  328. v3s16 pos = read_v3s16(L, 1);
  329. bool is_position_ok;
  330. MapNode n = env->getMap().getNode(pos, &is_position_ok);
  331. if (!is_position_ok)
  332. return 0;
  333. // If the daylight is 0, nothing needs to be calculated
  334. u8 daylight = n.param1 & 0x0f;
  335. if (daylight == 0) {
  336. lua_pushinteger(L, 0);
  337. return 1;
  338. }
  339. u32 time_of_day;
  340. if (lua_isnumber(L, 2)) {
  341. time_of_day = 24000.0 * lua_tonumber(L, 2);
  342. time_of_day %= 24000;
  343. } else {
  344. time_of_day = env->getTimeOfDay();
  345. }
  346. u32 dnr = time_to_daynight_ratio(time_of_day, true);
  347. // If it's the same as the artificial light, the sunlight needs to be
  348. // searched for because the value may not emanate from the sun
  349. if (daylight == n.param1 >> 4)
  350. daylight = env->findSunlight(pos);
  351. lua_pushinteger(L, dnr * daylight / 1000);
  352. return 1;
  353. }
  354. // place_node(pos, node)
  355. // pos = {x=num, y=num, z=num}
  356. int ModApiEnvMod::l_place_node(lua_State *L)
  357. {
  358. GET_ENV_PTR;
  359. ScriptApiItem *scriptIfaceItem = getScriptApi<ScriptApiItem>(L);
  360. Server *server = getServer(L);
  361. const NodeDefManager *ndef = server->ndef();
  362. IItemDefManager *idef = server->idef();
  363. v3s16 pos = read_v3s16(L, 1);
  364. MapNode n = readnode(L, 2);
  365. // Don't attempt to load non-loaded area as of now
  366. MapNode n_old = env->getMap().getNode(pos);
  367. if(n_old.getContent() == CONTENT_IGNORE){
  368. lua_pushboolean(L, false);
  369. return 1;
  370. }
  371. // Create item to place
  372. Optional<ItemStack> item = ItemStack(ndef->get(n).name, 1, 0, idef);
  373. // Make pointed position
  374. PointedThing pointed;
  375. pointed.type = POINTEDTHING_NODE;
  376. pointed.node_abovesurface = pos;
  377. pointed.node_undersurface = pos + v3s16(0,-1,0);
  378. // Place it with a NULL placer (appears in Lua as nil)
  379. bool success = scriptIfaceItem->item_OnPlace(item, nullptr, pointed);
  380. lua_pushboolean(L, success);
  381. return 1;
  382. }
  383. // dig_node(pos)
  384. // pos = {x=num, y=num, z=num}
  385. int ModApiEnvMod::l_dig_node(lua_State *L)
  386. {
  387. GET_ENV_PTR;
  388. ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
  389. v3s16 pos = read_v3s16(L, 1);
  390. // Don't attempt to load non-loaded area as of now
  391. MapNode n = env->getMap().getNode(pos);
  392. if(n.getContent() == CONTENT_IGNORE){
  393. lua_pushboolean(L, false);
  394. return 1;
  395. }
  396. // Dig it out with a NULL digger (appears in Lua as a
  397. // non-functional ObjectRef)
  398. bool success = scriptIfaceNode->node_on_dig(pos, n, NULL);
  399. lua_pushboolean(L, success);
  400. return 1;
  401. }
  402. // punch_node(pos)
  403. // pos = {x=num, y=num, z=num}
  404. int ModApiEnvMod::l_punch_node(lua_State *L)
  405. {
  406. GET_ENV_PTR;
  407. ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
  408. v3s16 pos = read_v3s16(L, 1);
  409. // Don't attempt to load non-loaded area as of now
  410. MapNode n = env->getMap().getNode(pos);
  411. if(n.getContent() == CONTENT_IGNORE){
  412. lua_pushboolean(L, false);
  413. return 1;
  414. }
  415. // Punch it with a NULL puncher (appears in Lua as a non-functional
  416. // ObjectRef)
  417. bool success = scriptIfaceNode->node_on_punch(pos, n, NULL, PointedThing());
  418. lua_pushboolean(L, success);
  419. return 1;
  420. }
  421. // get_node_max_level(pos)
  422. // pos = {x=num, y=num, z=num}
  423. int ModApiEnvMod::l_get_node_max_level(lua_State *L)
  424. {
  425. GET_PLAIN_ENV_PTR;
  426. v3s16 pos = read_v3s16(L, 1);
  427. MapNode n = env->getMap().getNode(pos);
  428. lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef()));
  429. return 1;
  430. }
  431. // get_node_level(pos)
  432. // pos = {x=num, y=num, z=num}
  433. int ModApiEnvMod::l_get_node_level(lua_State *L)
  434. {
  435. GET_PLAIN_ENV_PTR;
  436. v3s16 pos = read_v3s16(L, 1);
  437. MapNode n = env->getMap().getNode(pos);
  438. lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef()));
  439. return 1;
  440. }
  441. // set_node_level(pos, level)
  442. // pos = {x=num, y=num, z=num}
  443. // level: 0..63
  444. int ModApiEnvMod::l_set_node_level(lua_State *L)
  445. {
  446. GET_ENV_PTR;
  447. v3s16 pos = read_v3s16(L, 1);
  448. u8 level = 1;
  449. if(lua_isnumber(L, 2))
  450. level = lua_tonumber(L, 2);
  451. MapNode n = env->getMap().getNode(pos);
  452. lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level));
  453. env->setNode(pos, n);
  454. return 1;
  455. }
  456. // add_node_level(pos, level)
  457. // pos = {x=num, y=num, z=num}
  458. // level: -127..127
  459. int ModApiEnvMod::l_add_node_level(lua_State *L)
  460. {
  461. GET_ENV_PTR;
  462. v3s16 pos = read_v3s16(L, 1);
  463. s16 level = 1;
  464. if(lua_isnumber(L, 2))
  465. level = lua_tonumber(L, 2);
  466. MapNode n = env->getMap().getNode(pos);
  467. lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level));
  468. env->setNode(pos, n);
  469. return 1;
  470. }
  471. // find_nodes_with_meta(pos1, pos2)
  472. int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L)
  473. {
  474. GET_PLAIN_ENV_PTR;
  475. std::vector<v3s16> positions = env->getMap().findNodesWithMetadata(
  476. check_v3s16(L, 1), check_v3s16(L, 2));
  477. lua_createtable(L, positions.size(), 0);
  478. for (size_t i = 0; i != positions.size(); i++) {
  479. push_v3s16(L, positions[i]);
  480. lua_rawseti(L, -2, i + 1);
  481. }
  482. return 1;
  483. }
  484. // get_meta(pos)
  485. int ModApiEnvMod::l_get_meta(lua_State *L)
  486. {
  487. GET_ENV_PTR;
  488. // Do it
  489. v3s16 p = read_v3s16(L, 1);
  490. NodeMetaRef::create(L, p, env);
  491. return 1;
  492. }
  493. // get_node_timer(pos)
  494. int ModApiEnvMod::l_get_node_timer(lua_State *L)
  495. {
  496. GET_ENV_PTR;
  497. // Do it
  498. v3s16 p = read_v3s16(L, 1);
  499. NodeTimerRef::create(L, p, &env->getServerMap());
  500. return 1;
  501. }
  502. // add_entity(pos, entityname, [staticdata]) -> ObjectRef or nil
  503. // pos = {x=num, y=num, z=num}
  504. int ModApiEnvMod::l_add_entity(lua_State *L)
  505. {
  506. GET_ENV_PTR;
  507. v3f pos = checkFloatPos(L, 1);
  508. const char *name = luaL_checkstring(L, 2);
  509. std::string staticdata = readParam<std::string>(L, 3, "");
  510. ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata);
  511. int objectid = env->addActiveObject(obj);
  512. // If failed to add, return nothing (reads as nil)
  513. if(objectid == 0)
  514. return 0;
  515. // If already deleted (can happen in on_activate), return nil
  516. if (obj->isGone())
  517. return 0;
  518. getScriptApiBase(L)->objectrefGetOrCreate(L, obj);
  519. return 1;
  520. }
  521. // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
  522. // pos = {x=num, y=num, z=num}
  523. int ModApiEnvMod::l_add_item(lua_State *L)
  524. {
  525. GET_ENV_PTR;
  526. // pos
  527. //v3f pos = checkFloatPos(L, 1);
  528. // item
  529. ItemStack item = read_item(L, 2,getServer(L)->idef());
  530. if(item.empty() || !item.isKnown(getServer(L)->idef()))
  531. return 0;
  532. int error_handler = PUSH_ERROR_HANDLER(L);
  533. // Use spawn_item to spawn a __builtin:item
  534. lua_getglobal(L, "core");
  535. lua_getfield(L, -1, "spawn_item");
  536. lua_remove(L, -2); // Remove core
  537. if(lua_isnil(L, -1))
  538. return 0;
  539. lua_pushvalue(L, 1);
  540. lua_pushstring(L, item.getItemString().c_str());
  541. PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler));
  542. lua_remove(L, error_handler);
  543. return 1;
  544. }
  545. // get_connected_players()
  546. int ModApiEnvMod::l_get_connected_players(lua_State *L)
  547. {
  548. ServerEnvironment *env = (ServerEnvironment *) getEnv(L);
  549. if (!env) {
  550. log_deprecated(L, "Calling get_connected_players() at mod load time"
  551. " is deprecated");
  552. lua_createtable(L, 0, 0);
  553. return 1;
  554. }
  555. lua_createtable(L, env->getPlayerCount(), 0);
  556. u32 i = 0;
  557. for (RemotePlayer *player : env->getPlayers()) {
  558. if (player->getPeerId() == PEER_ID_INEXISTENT)
  559. continue;
  560. PlayerSAO *sao = player->getPlayerSAO();
  561. if (sao && !sao->isGone()) {
  562. getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
  563. lua_rawseti(L, -2, ++i);
  564. }
  565. }
  566. return 1;
  567. }
  568. // get_player_by_name(name)
  569. int ModApiEnvMod::l_get_player_by_name(lua_State *L)
  570. {
  571. GET_ENV_PTR;
  572. // Do it
  573. const char *name = luaL_checkstring(L, 1);
  574. RemotePlayer *player = env->getPlayer(name);
  575. if (!player || player->getPeerId() == PEER_ID_INEXISTENT)
  576. return 0;
  577. PlayerSAO *sao = player->getPlayerSAO();
  578. if (!sao || sao->isGone())
  579. return 0;
  580. // Put player on stack
  581. getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
  582. return 1;
  583. }
  584. // get_objects_inside_radius(pos, radius)
  585. int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
  586. {
  587. GET_ENV_PTR;
  588. ScriptApiBase *script = getScriptApiBase(L);
  589. // Do it
  590. v3f pos = checkFloatPos(L, 1);
  591. float radius = readParam<float>(L, 2) * BS;
  592. std::vector<ServerActiveObject *> objs;
  593. auto include_obj_cb = [](ServerActiveObject *obj){ return !obj->isGone(); };
  594. env->getObjectsInsideRadius(objs, pos, radius, include_obj_cb);
  595. int i = 0;
  596. lua_createtable(L, objs.size(), 0);
  597. for (const auto obj : objs) {
  598. // Insert object reference into table
  599. script->objectrefGetOrCreate(L, obj);
  600. lua_rawseti(L, -2, ++i);
  601. }
  602. return 1;
  603. }
  604. // get_objects_in_area(pos, minp, maxp)
  605. int ModApiEnvMod::l_get_objects_in_area(lua_State *L)
  606. {
  607. GET_ENV_PTR;
  608. ScriptApiBase *script = getScriptApiBase(L);
  609. v3f minp = read_v3f(L, 1) * BS;
  610. v3f maxp = read_v3f(L, 2) * BS;
  611. aabb3f box(minp, maxp);
  612. box.repair();
  613. std::vector<ServerActiveObject *> objs;
  614. auto include_obj_cb = [](ServerActiveObject *obj){ return !obj->isGone(); };
  615. env->getObjectsInArea(objs, box, include_obj_cb);
  616. int i = 0;
  617. lua_createtable(L, objs.size(), 0);
  618. for (const auto obj : objs) {
  619. // Insert object reference into table
  620. script->objectrefGetOrCreate(L, obj);
  621. lua_rawseti(L, -2, ++i);
  622. }
  623. return 1;
  624. }
  625. // set_timeofday(val)
  626. // val = 0...1
  627. int ModApiEnvMod::l_set_timeofday(lua_State *L)
  628. {
  629. GET_ENV_PTR;
  630. // Do it
  631. float timeofday_f = readParam<float>(L, 1);
  632. luaL_argcheck(L, timeofday_f >= 0.0f && timeofday_f <= 1.0f, 1,
  633. "value must be between 0 and 1");
  634. int timeofday_mh = (int)(timeofday_f * 24000.0f);
  635. // This should be set directly in the environment but currently
  636. // such changes aren't immediately sent to the clients, so call
  637. // the server instead.
  638. //env->setTimeOfDay(timeofday_mh);
  639. getServer(L)->setTimeOfDay(timeofday_mh);
  640. return 0;
  641. }
  642. // get_timeofday() -> 0...1
  643. int ModApiEnvMod::l_get_timeofday(lua_State *L)
  644. {
  645. GET_PLAIN_ENV_PTR;
  646. // Do it
  647. int timeofday_mh = env->getTimeOfDay();
  648. float timeofday_f = (float)timeofday_mh / 24000.0f;
  649. lua_pushnumber(L, timeofday_f);
  650. return 1;
  651. }
  652. // get_day_count() -> int
  653. int ModApiEnvMod::l_get_day_count(lua_State *L)
  654. {
  655. GET_PLAIN_ENV_PTR;
  656. lua_pushnumber(L, env->getDayCount());
  657. return 1;
  658. }
  659. // get_gametime()
  660. int ModApiEnvMod::l_get_gametime(lua_State *L)
  661. {
  662. GET_ENV_PTR;
  663. int game_time = env->getGameTime();
  664. lua_pushnumber(L, game_time);
  665. return 1;
  666. }
  667. void ModApiEnvMod::collectNodeIds(lua_State *L, int idx, const NodeDefManager *ndef,
  668. std::vector<content_t> &filter)
  669. {
  670. if (lua_istable(L, idx)) {
  671. lua_pushnil(L);
  672. while (lua_next(L, idx) != 0) {
  673. // key at index -2 and value at index -1
  674. luaL_checktype(L, -1, LUA_TSTRING);
  675. ndef->getIds(readParam<std::string>(L, -1), filter);
  676. // removes value, keeps key for next iteration
  677. lua_pop(L, 1);
  678. }
  679. } else if (lua_isstring(L, idx)) {
  680. ndef->getIds(readParam<std::string>(L, 3), filter);
  681. }
  682. }
  683. // find_node_near(pos, radius, nodenames, [search_center]) -> pos or nil
  684. // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
  685. int ModApiEnvMod::l_find_node_near(lua_State *L)
  686. {
  687. GET_PLAIN_ENV_PTR;
  688. const NodeDefManager *ndef = env->getGameDef()->ndef();
  689. Map &map = env->getMap();
  690. v3s16 pos = read_v3s16(L, 1);
  691. int radius = luaL_checkinteger(L, 2);
  692. std::vector<content_t> filter;
  693. collectNodeIds(L, 3, ndef, filter);
  694. int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
  695. #ifndef SERVER
  696. // Client API limitations
  697. if (Client *client = getClient(L))
  698. radius = client->CSMClampRadius(pos, radius);
  699. #endif
  700. for (int d = start_radius; d <= radius; d++) {
  701. const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d);
  702. for (const v3s16 &i : list) {
  703. v3s16 p = pos + i;
  704. content_t c = map.getNode(p).getContent();
  705. if (CONTAINS(filter, c)) {
  706. push_v3s16(L, p);
  707. return 1;
  708. }
  709. }
  710. }
  711. return 0;
  712. }
  713. static void checkArea(v3s16 &minp, v3s16 &maxp)
  714. {
  715. auto volume = VoxelArea(minp, maxp).getVolume();
  716. // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
  717. if (volume > 4096000) {
  718. throw LuaError("Area volume exceeds allowed value of 4096000");
  719. }
  720. // Clamp to map range to avoid problems
  721. #define CLAMP(arg) core::clamp(arg, (s16)-MAX_MAP_GENERATION_LIMIT, (s16)MAX_MAP_GENERATION_LIMIT)
  722. minp = v3s16(CLAMP(minp.X), CLAMP(minp.Y), CLAMP(minp.Z));
  723. maxp = v3s16(CLAMP(maxp.X), CLAMP(maxp.Y), CLAMP(maxp.Z));
  724. #undef CLAMP
  725. }
  726. // find_nodes_in_area(minp, maxp, nodenames, [grouped])
  727. int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
  728. {
  729. GET_PLAIN_ENV_PTR;
  730. v3s16 minp = read_v3s16(L, 1);
  731. v3s16 maxp = read_v3s16(L, 2);
  732. sortBoxVerticies(minp, maxp);
  733. const NodeDefManager *ndef = env->getGameDef()->ndef();
  734. Map &map = env->getMap();
  735. #ifndef SERVER
  736. if (Client *client = getClient(L)) {
  737. minp = client->CSMClampPos(minp);
  738. maxp = client->CSMClampPos(maxp);
  739. }
  740. #endif
  741. checkArea(minp, maxp);
  742. std::vector<content_t> filter;
  743. collectNodeIds(L, 3, ndef, filter);
  744. bool grouped = lua_isboolean(L, 4) && readParam<bool>(L, 4);
  745. if (grouped) {
  746. // create the table we will be returning
  747. lua_createtable(L, 0, filter.size());
  748. int base = lua_gettop(L);
  749. // create one table for each filter
  750. std::vector<u32> idx;
  751. idx.resize(filter.size());
  752. for (u32 i = 0; i < filter.size(); i++)
  753. lua_newtable(L);
  754. map.forEachNodeInArea(minp, maxp, [&](v3s16 p, MapNode n) -> bool {
  755. content_t c = n.getContent();
  756. auto it = std::find(filter.begin(), filter.end(), c);
  757. if (it != filter.end()) {
  758. // Calculate index of the table and append the position
  759. u32 filt_index = it - filter.begin();
  760. push_v3s16(L, p);
  761. lua_rawseti(L, base + 1 + filt_index, ++idx[filt_index]);
  762. }
  763. return true;
  764. });
  765. // last filter table is at top of stack
  766. u32 i = filter.size() - 1;
  767. do {
  768. if (idx[i] == 0) {
  769. // No such node found -> drop the empty table
  770. lua_pop(L, 1);
  771. } else {
  772. // This node was found -> put table into the return table
  773. lua_setfield(L, base, ndef->get(filter[i]).name.c_str());
  774. }
  775. } while (i-- != 0);
  776. assert(lua_gettop(L) == base);
  777. return 1;
  778. } else {
  779. std::vector<u32> individual_count;
  780. individual_count.resize(filter.size());
  781. lua_newtable(L);
  782. u32 i = 0;
  783. map.forEachNodeInArea(minp, maxp, [&](v3s16 p, MapNode n) -> bool {
  784. content_t c = n.getContent();
  785. auto it = std::find(filter.begin(), filter.end(), c);
  786. if (it != filter.end()) {
  787. push_v3s16(L, p);
  788. lua_rawseti(L, -2, ++i);
  789. u32 filt_index = it - filter.begin();
  790. individual_count[filt_index]++;
  791. }
  792. return true;
  793. });
  794. lua_createtable(L, 0, filter.size());
  795. for (u32 i = 0; i < filter.size(); i++) {
  796. lua_pushinteger(L, individual_count[i]);
  797. lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
  798. }
  799. return 2;
  800. }
  801. }
  802. // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
  803. // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
  804. int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
  805. {
  806. /* Note: A similar but generalized (and therefore slower) version of this
  807. * function could be created -- e.g. find_nodes_in_area_under -- which
  808. * would accept a node name (or ID?) or list of names that the "above node"
  809. * should be.
  810. * TODO
  811. */
  812. GET_PLAIN_ENV_PTR;
  813. v3s16 minp = read_v3s16(L, 1);
  814. v3s16 maxp = read_v3s16(L, 2);
  815. sortBoxVerticies(minp, maxp);
  816. const NodeDefManager *ndef = env->getGameDef()->ndef();
  817. Map &map = env->getMap();
  818. #ifndef SERVER
  819. if (Client *client = getClient(L)) {
  820. minp = client->CSMClampPos(minp);
  821. maxp = client->CSMClampPos(maxp);
  822. }
  823. #endif
  824. checkArea(minp, maxp);
  825. std::vector<content_t> filter;
  826. collectNodeIds(L, 3, ndef, filter);
  827. lua_newtable(L);
  828. u32 i = 0;
  829. v3s16 p;
  830. for (p.X = minp.X; p.X <= maxp.X; p.X++)
  831. for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
  832. p.Y = minp.Y;
  833. content_t c = map.getNode(p).getContent();
  834. for (; p.Y <= maxp.Y; p.Y++) {
  835. v3s16 psurf(p.X, p.Y + 1, p.Z);
  836. content_t csurf = map.getNode(psurf).getContent();
  837. if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
  838. CONTAINS(filter, c)) {
  839. push_v3s16(L, p);
  840. lua_rawseti(L, -2, ++i);
  841. }
  842. c = csurf;
  843. }
  844. }
  845. return 1;
  846. }
  847. // get_perlin(seeddiff, octaves, persistence, scale)
  848. // returns world-specific PerlinNoise
  849. int ModApiEnvMod::l_get_perlin(lua_State *L)
  850. {
  851. GET_ENV_PTR_NO_MAP_LOCK;
  852. NoiseParams params;
  853. if (lua_istable(L, 1)) {
  854. read_noiseparams(L, 1, &params);
  855. } else {
  856. params.seed = luaL_checkint(L, 1);
  857. params.octaves = luaL_checkint(L, 2);
  858. params.persist = readParam<float>(L, 3);
  859. params.spread = v3f(1, 1, 1) * readParam<float>(L, 4);
  860. }
  861. params.seed += (int)env->getServerMap().getSeed();
  862. LuaPerlinNoise *n = new LuaPerlinNoise(&params);
  863. *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
  864. luaL_getmetatable(L, "PerlinNoise");
  865. lua_setmetatable(L, -2);
  866. return 1;
  867. }
  868. // get_perlin_map(noiseparams, size)
  869. // returns world-specific PerlinNoiseMap
  870. int ModApiEnvMod::l_get_perlin_map(lua_State *L)
  871. {
  872. GET_ENV_PTR_NO_MAP_LOCK;
  873. NoiseParams np;
  874. if (!read_noiseparams(L, 1, &np))
  875. return 0;
  876. v3s16 size = read_v3s16(L, 2);
  877. s32 seed = (s32)(env->getServerMap().getSeed());
  878. LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
  879. *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
  880. luaL_getmetatable(L, "PerlinNoiseMap");
  881. lua_setmetatable(L, -2);
  882. return 1;
  883. }
  884. // get_voxel_manip()
  885. // returns voxel manipulator
  886. int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
  887. {
  888. GET_ENV_PTR;
  889. Map *map = &(env->getMap());
  890. LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
  891. new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
  892. new LuaVoxelManip(map);
  893. *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
  894. luaL_getmetatable(L, "VoxelManip");
  895. lua_setmetatable(L, -2);
  896. return 1;
  897. }
  898. // clear_objects([options])
  899. // clear all objects in the environment
  900. // where options = {mode = "full" or "quick"}
  901. int ModApiEnvMod::l_clear_objects(lua_State *L)
  902. {
  903. GET_ENV_PTR;
  904. ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK;
  905. if (lua_istable(L, 1)) {
  906. mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
  907. ModApiEnvMod::es_ClearObjectsMode, mode);
  908. }
  909. env->clearObjects(mode);
  910. return 0;
  911. }
  912. // line_of_sight(pos1, pos2) -> true/false, pos
  913. int ModApiEnvMod::l_line_of_sight(lua_State *L)
  914. {
  915. GET_PLAIN_ENV_PTR;
  916. // read position 1 from lua
  917. v3f pos1 = checkFloatPos(L, 1);
  918. // read position 2 from lua
  919. v3f pos2 = checkFloatPos(L, 2);
  920. v3s16 p;
  921. bool success = env->line_of_sight(pos1, pos2, &p);
  922. lua_pushboolean(L, success);
  923. if (!success) {
  924. push_v3s16(L, p);
  925. return 2;
  926. }
  927. return 1;
  928. }
  929. // fix_light(p1, p2)
  930. int ModApiEnvMod::l_fix_light(lua_State *L)
  931. {
  932. GET_ENV_PTR;
  933. v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
  934. v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
  935. ServerMap &map = env->getServerMap();
  936. std::map<v3s16, MapBlock *> modified_blocks;
  937. bool success = true;
  938. v3s16 blockpos;
  939. for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
  940. for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
  941. for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
  942. success = success & map.repairBlockLight(blockpos, &modified_blocks);
  943. }
  944. if (!modified_blocks.empty()) {
  945. MapEditEvent event;
  946. event.type = MEET_OTHER;
  947. event.setModifiedBlocks(modified_blocks);
  948. map.dispatchEvent(event);
  949. }
  950. lua_pushboolean(L, success);
  951. return 1;
  952. }
  953. int ModApiEnvMod::l_raycast(lua_State *L)
  954. {
  955. return LuaRaycast::create_object(L);
  956. }
  957. // load_area(p1, [p2])
  958. // load mapblocks in area p1..p2, but do not generate map
  959. int ModApiEnvMod::l_load_area(lua_State *L)
  960. {
  961. GET_ENV_PTR;
  962. MAP_LOCK_REQUIRED;
  963. Map *map = &(env->getMap());
  964. v3s16 bp1 = getNodeBlockPos(check_v3s16(L, 1));
  965. if (!lua_istable(L, 2)) {
  966. map->emergeBlock(bp1);
  967. } else {
  968. v3s16 bp2 = getNodeBlockPos(check_v3s16(L, 2));
  969. sortBoxVerticies(bp1, bp2);
  970. for (s16 z = bp1.Z; z <= bp2.Z; z++)
  971. for (s16 y = bp1.Y; y <= bp2.Y; y++)
  972. for (s16 x = bp1.X; x <= bp2.X; x++) {
  973. map->emergeBlock(v3s16(x, y, z));
  974. }
  975. }
  976. return 0;
  977. }
  978. // emerge_area(p1, p2, [callback, context])
  979. // emerge mapblocks in area p1..p2, calls callback with context upon completion
  980. int ModApiEnvMod::l_emerge_area(lua_State *L)
  981. {
  982. GET_ENV_PTR;
  983. EmergeCompletionCallback callback = NULL;
  984. ScriptCallbackState *state = NULL;
  985. EmergeManager *emerge = getServer(L)->getEmergeManager();
  986. v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
  987. v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
  988. sortBoxVerticies(bpmin, bpmax);
  989. size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
  990. if (num_blocks == 0)
  991. return 0;
  992. if (lua_isfunction(L, 3)) {
  993. callback = LuaEmergeAreaCallback;
  994. lua_pushvalue(L, 3);
  995. int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  996. lua_pushvalue(L, 4);
  997. int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
  998. state = new ScriptCallbackState;
  999. state->script = getServer(L)->getScriptIface();
  1000. state->callback_ref = callback_ref;
  1001. state->args_ref = args_ref;
  1002. state->refcount = num_blocks;
  1003. state->origin = getScriptApiBase(L)->getOrigin();
  1004. }
  1005. for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
  1006. for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
  1007. for (s16 x = bpmin.X; x <= bpmax.X; x++) {
  1008. emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
  1009. BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
  1010. }
  1011. return 0;
  1012. }
  1013. // delete_area(p1, p2)
  1014. // delete mapblocks in area p1..p2
  1015. int ModApiEnvMod::l_delete_area(lua_State *L)
  1016. {
  1017. GET_ENV_PTR;
  1018. v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
  1019. v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
  1020. sortBoxVerticies(bpmin, bpmax);
  1021. ServerMap &map = env->getServerMap();
  1022. MapEditEvent event;
  1023. event.type = MEET_OTHER;
  1024. bool success = true;
  1025. for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
  1026. for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
  1027. for (s16 x = bpmin.X; x <= bpmax.X; x++) {
  1028. v3s16 bp(x, y, z);
  1029. if (map.deleteBlock(bp)) {
  1030. env->setStaticForActiveObjectsInBlock(bp, false);
  1031. event.modified_blocks.push_back(bp);
  1032. } else {
  1033. success = false;
  1034. }
  1035. }
  1036. map.dispatchEvent(event);
  1037. lua_pushboolean(L, success);
  1038. return 1;
  1039. }
  1040. // find_path(pos1, pos2, searchdistance,
  1041. // max_jump, max_drop, algorithm) -> table containing path
  1042. int ModApiEnvMod::l_find_path(lua_State *L)
  1043. {
  1044. GET_ENV_PTR;
  1045. v3s16 pos1 = read_v3s16(L, 1);
  1046. v3s16 pos2 = read_v3s16(L, 2);
  1047. unsigned int searchdistance = luaL_checkint(L, 3);
  1048. unsigned int max_jump = luaL_checkint(L, 4);
  1049. unsigned int max_drop = luaL_checkint(L, 5);
  1050. PathAlgorithm algo = PA_PLAIN_NP;
  1051. if (!lua_isnoneornil(L, 6)) {
  1052. std::string algorithm = luaL_checkstring(L,6);
  1053. if (algorithm == "A*")
  1054. algo = PA_PLAIN;
  1055. if (algorithm == "Dijkstra")
  1056. algo = PA_DIJKSTRA;
  1057. }
  1058. std::vector<v3s16> path = get_path(&env->getServerMap(), env->getGameDef()->ndef(), pos1, pos2,
  1059. searchdistance, max_jump, max_drop, algo);
  1060. if (!path.empty()) {
  1061. lua_createtable(L, path.size(), 0);
  1062. int top = lua_gettop(L);
  1063. unsigned int index = 1;
  1064. for (const v3s16 &i : path) {
  1065. lua_pushnumber(L,index);
  1066. push_v3s16(L, i);
  1067. lua_settable(L, top);
  1068. index++;
  1069. }
  1070. return 1;
  1071. }
  1072. return 0;
  1073. }
  1074. // spawn_tree(pos, treedef)
  1075. int ModApiEnvMod::l_spawn_tree(lua_State *L)
  1076. {
  1077. GET_ENV_PTR;
  1078. v3s16 p0 = read_v3s16(L, 1);
  1079. treegen::TreeDef tree_def;
  1080. std::string trunk,leaves,fruit;
  1081. const NodeDefManager *ndef = env->getGameDef()->ndef();
  1082. if(lua_istable(L, 2))
  1083. {
  1084. getstringfield(L, 2, "axiom", tree_def.initial_axiom);
  1085. getstringfield(L, 2, "rules_a", tree_def.rules_a);
  1086. getstringfield(L, 2, "rules_b", tree_def.rules_b);
  1087. getstringfield(L, 2, "rules_c", tree_def.rules_c);
  1088. getstringfield(L, 2, "rules_d", tree_def.rules_d);
  1089. getstringfield(L, 2, "trunk", trunk);
  1090. tree_def.trunknode=ndef->getId(trunk);
  1091. getstringfield(L, 2, "leaves", leaves);
  1092. tree_def.leavesnode=ndef->getId(leaves);
  1093. tree_def.leaves2_chance=0;
  1094. getstringfield(L, 2, "leaves2", leaves);
  1095. if (!leaves.empty()) {
  1096. tree_def.leaves2node=ndef->getId(leaves);
  1097. getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
  1098. }
  1099. getintfield(L, 2, "angle", tree_def.angle);
  1100. getintfield(L, 2, "iterations", tree_def.iterations);
  1101. if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
  1102. tree_def.iterations_random_level = 0;
  1103. getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
  1104. getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
  1105. tree_def.fruit_chance=0;
  1106. getstringfield(L, 2, "fruit", fruit);
  1107. if (!fruit.empty()) {
  1108. tree_def.fruitnode=ndef->getId(fruit);
  1109. getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
  1110. }
  1111. tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
  1112. }
  1113. else
  1114. return 0;
  1115. ServerMap *map = &env->getServerMap();
  1116. treegen::error e;
  1117. if ((e = treegen::spawn_ltree (map, p0, ndef, tree_def)) != treegen::SUCCESS) {
  1118. if (e == treegen::UNBALANCED_BRACKETS) {
  1119. luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
  1120. } else {
  1121. luaL_error(L, "spawn_tree(): unknown error");
  1122. }
  1123. }
  1124. return 1;
  1125. }
  1126. // transforming_liquid_add(pos)
  1127. int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
  1128. {
  1129. GET_ENV_PTR;
  1130. v3s16 p0 = read_v3s16(L, 1);
  1131. env->getServerMap().transforming_liquid_add(p0);
  1132. return 1;
  1133. }
  1134. // forceload_block(blockpos)
  1135. // blockpos = {x=num, y=num, z=num}
  1136. int ModApiEnvMod::l_forceload_block(lua_State *L)
  1137. {
  1138. GET_ENV_PTR;
  1139. v3s16 blockpos = read_v3s16(L, 1);
  1140. env->getForceloadedBlocks()->insert(blockpos);
  1141. return 0;
  1142. }
  1143. // compare_block_status(nodepos)
  1144. int ModApiEnvMod::l_compare_block_status(lua_State *L)
  1145. {
  1146. GET_ENV_PTR;
  1147. v3s16 nodepos = check_v3s16(L, 1);
  1148. std::string condition_s = luaL_checkstring(L, 2);
  1149. auto status = env->getBlockStatus(getNodeBlockPos(nodepos));
  1150. int condition_i = -1;
  1151. if (!string_to_enum(es_BlockStatusType, condition_i, condition_s))
  1152. return 0; // Unsupported
  1153. lua_pushboolean(L, status >= condition_i);
  1154. return 1;
  1155. }
  1156. // forceload_free_block(blockpos)
  1157. // blockpos = {x=num, y=num, z=num}
  1158. int ModApiEnvMod::l_forceload_free_block(lua_State *L)
  1159. {
  1160. GET_ENV_PTR;
  1161. v3s16 blockpos = read_v3s16(L, 1);
  1162. env->getForceloadedBlocks()->erase(blockpos);
  1163. return 0;
  1164. }
  1165. // get_translated_string(lang_code, string)
  1166. int ModApiEnvMod::l_get_translated_string(lua_State * L)
  1167. {
  1168. GET_ENV_PTR;
  1169. std::string lang_code = luaL_checkstring(L, 1);
  1170. std::string string = luaL_checkstring(L, 2);
  1171. auto *translations = getServer(L)->getTranslationLanguage(lang_code);
  1172. string = wide_to_utf8(translate_string(utf8_to_wide(string), translations));
  1173. lua_pushstring(L, string.c_str());
  1174. return 1;
  1175. }
  1176. void ModApiEnvMod::Initialize(lua_State *L, int top)
  1177. {
  1178. API_FCT(set_node);
  1179. API_FCT(bulk_set_node);
  1180. API_FCT(add_node);
  1181. API_FCT(swap_node);
  1182. API_FCT(add_item);
  1183. API_FCT(remove_node);
  1184. API_FCT(get_node);
  1185. API_FCT(get_node_or_nil);
  1186. API_FCT(get_node_light);
  1187. API_FCT(get_natural_light);
  1188. API_FCT(place_node);
  1189. API_FCT(dig_node);
  1190. API_FCT(punch_node);
  1191. API_FCT(get_node_max_level);
  1192. API_FCT(get_node_level);
  1193. API_FCT(set_node_level);
  1194. API_FCT(add_node_level);
  1195. API_FCT(add_entity);
  1196. API_FCT(find_nodes_with_meta);
  1197. API_FCT(get_meta);
  1198. API_FCT(get_node_timer);
  1199. API_FCT(get_connected_players);
  1200. API_FCT(get_player_by_name);
  1201. API_FCT(get_objects_in_area);
  1202. API_FCT(get_objects_inside_radius);
  1203. API_FCT(set_timeofday);
  1204. API_FCT(get_timeofday);
  1205. API_FCT(get_gametime);
  1206. API_FCT(get_day_count);
  1207. API_FCT(find_node_near);
  1208. API_FCT(find_nodes_in_area);
  1209. API_FCT(find_nodes_in_area_under_air);
  1210. API_FCT(fix_light);
  1211. API_FCT(load_area);
  1212. API_FCT(emerge_area);
  1213. API_FCT(delete_area);
  1214. API_FCT(get_perlin);
  1215. API_FCT(get_perlin_map);
  1216. API_FCT(get_voxel_manip);
  1217. API_FCT(clear_objects);
  1218. API_FCT(spawn_tree);
  1219. API_FCT(find_path);
  1220. API_FCT(line_of_sight);
  1221. API_FCT(raycast);
  1222. API_FCT(transforming_liquid_add);
  1223. API_FCT(forceload_block);
  1224. API_FCT(forceload_free_block);
  1225. API_FCT(compare_block_status);
  1226. API_FCT(get_translated_string);
  1227. }
  1228. void ModApiEnvMod::InitializeClient(lua_State *L, int top)
  1229. {
  1230. API_FCT(get_node_light);
  1231. API_FCT(get_timeofday);
  1232. API_FCT(get_node_max_level);
  1233. API_FCT(get_node_level);
  1234. API_FCT(find_nodes_with_meta);
  1235. API_FCT(find_node_near);
  1236. API_FCT(find_nodes_in_area);
  1237. API_FCT(find_nodes_in_area_under_air);
  1238. API_FCT(line_of_sight);
  1239. API_FCT(raycast);
  1240. }