l_env.cpp 36 KB

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