3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "lua_api/l_env.h"
22 #include "lua_api/l_internal.h"
23 #include "lua_api/l_nodemeta.h"
24 #include "lua_api/l_nodetimer.h"
25 #include "lua_api/l_noise.h"
26 #include "lua_api/l_vmanip.h"
27 #include "common/c_converter.h"
28 #include "common/c_content.h"
29 #include "scripting_server.h"
30 #include "environment.h"
34 #include "daynightratio.h"
35 #include "util/pointedthing.h"
36 #include "mapgen/treegen.h"
38 #include "pathfinder.h"
39 #include "face_position_cache.h"
40 #include "remoteplayer.h"
41 #include "server/luaentity_sao.h"
42 #include "server/player_sao.h"
43 #include "util/string.h"
44 #include "translation.h"
46 #include "client/client.h"
49 struct EnumString ModApiEnvMod::es_ClearObjectsMode[] =
51 {CLEAR_OBJECTS_MODE_FULL, "full"},
52 {CLEAR_OBJECTS_MODE_QUICK, "quick"},
56 ///////////////////////////////////////////////////////////////////////////////
59 void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
60 u32 active_object_count, u32 active_object_count_wider)
62 ServerScripting *scriptIface = env->getScriptIface();
63 scriptIface->realityCheck();
65 lua_State *L = scriptIface->getStack();
66 sanity_check(lua_checkstack(L, 20));
67 StackUnroller stack_unroller(L);
69 int error_handler = PUSH_ERROR_HANDLER(L);
71 // Get registered_abms
72 lua_getglobal(L, "core");
73 lua_getfield(L, -1, "registered_abms");
74 luaL_checktype(L, -1, LUA_TTABLE);
75 lua_remove(L, -2); // Remove core
77 // Get registered_abms[m_id]
78 lua_pushinteger(L, m_id);
82 lua_remove(L, -2); // Remove registered_abms
84 scriptIface->setOriginFromTable(-1);
87 luaL_checktype(L, -1, LUA_TTABLE);
88 lua_getfield(L, -1, "action");
89 luaL_checktype(L, -1, LUA_TFUNCTION);
90 lua_remove(L, -2); // Remove registered_abms[m_id]
92 pushnode(L, n, env->getGameDef()->ndef());
93 lua_pushnumber(L, active_object_count);
94 lua_pushnumber(L, active_object_count_wider);
96 int result = lua_pcall(L, 4, 0, error_handler);
98 scriptIface->scriptError(result, "LuaABM::trigger");
100 lua_pop(L, 1); // Pop error handler
103 void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n)
105 ServerScripting *scriptIface = env->getScriptIface();
106 scriptIface->realityCheck();
108 lua_State *L = scriptIface->getStack();
109 sanity_check(lua_checkstack(L, 20));
110 StackUnroller stack_unroller(L);
112 int error_handler = PUSH_ERROR_HANDLER(L);
114 // Get registered_lbms
115 lua_getglobal(L, "core");
116 lua_getfield(L, -1, "registered_lbms");
117 luaL_checktype(L, -1, LUA_TTABLE);
118 lua_remove(L, -2); // Remove core
120 // Get registered_lbms[m_id]
121 lua_pushinteger(L, m_id);
123 FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table");
124 lua_remove(L, -2); // Remove registered_lbms
126 scriptIface->setOriginFromTable(-1);
129 luaL_checktype(L, -1, LUA_TTABLE);
130 lua_getfield(L, -1, "action");
131 luaL_checktype(L, -1, LUA_TFUNCTION);
132 lua_remove(L, -2); // Remove registered_lbms[m_id]
134 pushnode(L, n, env->getGameDef()->ndef());
136 int result = lua_pcall(L, 2, 0, error_handler);
138 scriptIface->scriptError(result, "LuaLBM::trigger");
140 lua_pop(L, 1); // Pop error handler
143 int LuaRaycast::l_next(lua_State *L)
149 csm = getClient(L) != nullptr;
152 LuaRaycast *o = checkobject(L, 1);
153 PointedThing pointed;
154 env->continueRaycast(&o->state, &pointed);
155 if (pointed.type == POINTEDTHING_NOTHING)
158 push_pointed_thing(L, pointed, csm, true);
163 int LuaRaycast::create_object(lua_State *L)
165 NO_MAP_LOCK_REQUIRED;
168 bool liquids = false;
170 v3f pos1 = checkFloatPos(L, 1);
171 v3f pos2 = checkFloatPos(L, 2);
172 if (lua_isboolean(L, 3)) {
173 objects = readParam<bool>(L, 3);
175 if (lua_isboolean(L, 4)) {
176 liquids = readParam<bool>(L, 4);
179 LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2),
182 *(void **) (lua_newuserdata(L, sizeof(void *))) = o;
183 luaL_getmetatable(L, className);
184 lua_setmetatable(L, -2);
188 LuaRaycast *LuaRaycast::checkobject(lua_State *L, int narg)
190 NO_MAP_LOCK_REQUIRED;
192 luaL_checktype(L, narg, LUA_TUSERDATA);
193 void *ud = luaL_checkudata(L, narg, className);
195 luaL_typerror(L, narg, className);
196 return *(LuaRaycast **) ud;
199 int LuaRaycast::gc_object(lua_State *L)
201 LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1));
206 void LuaRaycast::Register(lua_State *L)
209 int methodtable = lua_gettop(L);
210 luaL_newmetatable(L, className);
211 int metatable = lua_gettop(L);
213 lua_pushliteral(L, "__metatable");
214 lua_pushvalue(L, methodtable);
215 lua_settable(L, metatable);
217 lua_pushliteral(L, "__index");
218 lua_pushvalue(L, methodtable);
219 lua_settable(L, metatable);
221 lua_pushliteral(L, "__gc");
222 lua_pushcfunction(L, gc_object);
223 lua_settable(L, metatable);
225 lua_pushliteral(L, "__call");
226 lua_pushcfunction(L, l_next);
227 lua_settable(L, metatable);
231 luaL_openlib(L, 0, methods, 0);
234 lua_register(L, className, create_object);
237 const char LuaRaycast::className[] = "Raycast";
238 const luaL_Reg LuaRaycast::methods[] =
240 luamethod(LuaRaycast, next),
244 void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param)
246 ScriptCallbackState *state = (ScriptCallbackState *)param;
247 assert(state != NULL);
248 assert(state->script != NULL);
249 assert(state->refcount > 0);
251 // state must be protected by envlock
252 Server *server = state->script->getServer();
253 MutexAutoLock envlock(server->m_env_mutex);
257 state->script->on_emerge_area_completion(blockpos, action, state);
259 if (state->refcount == 0)
263 // Exported functions
265 // set_node(pos, node)
266 // pos = {x=num, y=num, z=num}
267 int ModApiEnvMod::l_set_node(lua_State *L)
271 const NodeDefManager *ndef = env->getGameDef()->ndef();
273 v3s16 pos = read_v3s16(L, 1);
274 MapNode n = readnode(L, 2, ndef);
276 bool succeeded = env->setNode(pos, n);
277 lua_pushboolean(L, succeeded);
281 // bulk_set_node([pos1, pos2, ...], node)
282 // pos = {x=num, y=num, z=num}
283 int ModApiEnvMod::l_bulk_set_node(lua_State *L)
287 const NodeDefManager *ndef = env->getGameDef()->ndef();
289 if (!lua_istable(L, 1)) {
293 s32 len = lua_objlen(L, 1);
295 lua_pushboolean(L, true);
299 MapNode n = readnode(L, 2, ndef);
302 bool succeeded = true;
303 for (s32 i = 1; i <= len; i++) {
304 lua_rawgeti(L, 1, i);
305 if (!env->setNode(read_v3s16(L, -1), n))
310 lua_pushboolean(L, succeeded);
314 int ModApiEnvMod::l_add_node(lua_State *L)
316 return l_set_node(L);
320 // pos = {x=num, y=num, z=num}
321 int ModApiEnvMod::l_remove_node(lua_State *L)
326 v3s16 pos = read_v3s16(L, 1);
328 bool succeeded = env->removeNode(pos);
329 lua_pushboolean(L, succeeded);
333 // swap_node(pos, node)
334 // pos = {x=num, y=num, z=num}
335 int ModApiEnvMod::l_swap_node(lua_State *L)
339 const NodeDefManager *ndef = env->getGameDef()->ndef();
341 v3s16 pos = read_v3s16(L, 1);
342 MapNode n = readnode(L, 2, ndef);
344 bool succeeded = env->swapNode(pos, n);
345 lua_pushboolean(L, succeeded);
350 // pos = {x=num, y=num, z=num}
351 int ModApiEnvMod::l_get_node(lua_State *L)
356 v3s16 pos = read_v3s16(L, 1);
358 MapNode n = env->getMap().getNode(pos);
360 pushnode(L, n, env->getGameDef()->ndef());
364 // get_node_or_nil(pos)
365 // pos = {x=num, y=num, z=num}
366 int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
371 v3s16 pos = read_v3s16(L, 1);
374 MapNode n = env->getMap().getNode(pos, &pos_ok);
377 pushnode(L, n, env->getGameDef()->ndef());
384 // get_node_light(pos, timeofday)
385 // pos = {x=num, y=num, z=num}
386 // timeofday: nil = current time, 0 = night, 0.5 = day
387 int ModApiEnvMod::l_get_node_light(lua_State *L)
392 v3s16 pos = read_v3s16(L, 1);
393 u32 time_of_day = env->getTimeOfDay();
394 if(lua_isnumber(L, 2))
395 time_of_day = 24000.0 * lua_tonumber(L, 2);
396 time_of_day %= 24000;
397 u32 dnr = time_to_daynight_ratio(time_of_day, true);
400 MapNode n = env->getMap().getNode(pos, &is_position_ok);
401 if (is_position_ok) {
402 const NodeDefManager *ndef = env->getGameDef()->ndef();
403 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
410 // place_node(pos, node)
411 // pos = {x=num, y=num, z=num}
412 int ModApiEnvMod::l_place_node(lua_State *L)
416 ScriptApiItem *scriptIfaceItem = getScriptApi<ScriptApiItem>(L);
417 Server *server = getServer(L);
418 const NodeDefManager *ndef = server->ndef();
419 IItemDefManager *idef = server->idef();
421 v3s16 pos = read_v3s16(L, 1);
422 MapNode n = readnode(L, 2, ndef);
424 // Don't attempt to load non-loaded area as of now
425 MapNode n_old = env->getMap().getNode(pos);
426 if(n_old.getContent() == CONTENT_IGNORE){
427 lua_pushboolean(L, false);
430 // Create item to place
431 ItemStack item(ndef->get(n).name, 1, 0, idef);
432 // Make pointed position
433 PointedThing pointed;
434 pointed.type = POINTEDTHING_NODE;
435 pointed.node_abovesurface = pos;
436 pointed.node_undersurface = pos + v3s16(0,-1,0);
437 // Place it with a NULL placer (appears in Lua as nil)
438 bool success = scriptIfaceItem->item_OnPlace(item, nullptr, pointed);
439 lua_pushboolean(L, success);
444 // pos = {x=num, y=num, z=num}
445 int ModApiEnvMod::l_dig_node(lua_State *L)
449 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
451 v3s16 pos = read_v3s16(L, 1);
453 // Don't attempt to load non-loaded area as of now
454 MapNode n = env->getMap().getNode(pos);
455 if(n.getContent() == CONTENT_IGNORE){
456 lua_pushboolean(L, false);
459 // Dig it out with a NULL digger (appears in Lua as a
460 // non-functional ObjectRef)
461 bool success = scriptIfaceNode->node_on_dig(pos, n, NULL);
462 lua_pushboolean(L, success);
467 // pos = {x=num, y=num, z=num}
468 int ModApiEnvMod::l_punch_node(lua_State *L)
472 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
474 v3s16 pos = read_v3s16(L, 1);
476 // Don't attempt to load non-loaded area as of now
477 MapNode n = env->getMap().getNode(pos);
478 if(n.getContent() == CONTENT_IGNORE){
479 lua_pushboolean(L, false);
482 // Punch it with a NULL puncher (appears in Lua as a non-functional
484 bool success = scriptIfaceNode->node_on_punch(pos, n, NULL, PointedThing());
485 lua_pushboolean(L, success);
489 // get_node_max_level(pos)
490 // pos = {x=num, y=num, z=num}
491 int ModApiEnvMod::l_get_node_max_level(lua_State *L)
495 v3s16 pos = read_v3s16(L, 1);
496 MapNode n = env->getMap().getNode(pos);
497 lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef()));
501 // get_node_level(pos)
502 // pos = {x=num, y=num, z=num}
503 int ModApiEnvMod::l_get_node_level(lua_State *L)
507 v3s16 pos = read_v3s16(L, 1);
508 MapNode n = env->getMap().getNode(pos);
509 lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef()));
513 // set_node_level(pos, level)
514 // pos = {x=num, y=num, z=num}
516 int ModApiEnvMod::l_set_node_level(lua_State *L)
520 v3s16 pos = read_v3s16(L, 1);
522 if(lua_isnumber(L, 2))
523 level = lua_tonumber(L, 2);
524 MapNode n = env->getMap().getNode(pos);
525 lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level));
526 env->setNode(pos, n);
530 // add_node_level(pos, level)
531 // pos = {x=num, y=num, z=num}
533 int ModApiEnvMod::l_add_node_level(lua_State *L)
537 v3s16 pos = read_v3s16(L, 1);
539 if(lua_isnumber(L, 2))
540 level = lua_tonumber(L, 2);
541 MapNode n = env->getMap().getNode(pos);
542 lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level));
543 env->setNode(pos, n);
547 // find_nodes_with_meta(pos1, pos2)
548 int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L)
552 std::vector<v3s16> positions = env->getMap().findNodesWithMetadata(
553 check_v3s16(L, 1), check_v3s16(L, 2));
555 lua_createtable(L, positions.size(), 0);
556 for (size_t i = 0; i != positions.size(); i++) {
557 push_v3s16(L, positions[i]);
558 lua_rawseti(L, -2, i + 1);
565 int ModApiEnvMod::l_get_meta(lua_State *L)
570 v3s16 p = read_v3s16(L, 1);
571 NodeMetaRef::create(L, p, env);
575 // get_node_timer(pos)
576 int ModApiEnvMod::l_get_node_timer(lua_State *L)
581 v3s16 p = read_v3s16(L, 1);
582 NodeTimerRef::create(L, p, &env->getServerMap());
586 // add_entity(pos, entityname, [staticdata]) -> ObjectRef or nil
587 // pos = {x=num, y=num, z=num}
588 int ModApiEnvMod::l_add_entity(lua_State *L)
592 v3f pos = checkFloatPos(L, 1);
593 const char *name = luaL_checkstring(L, 2);
594 const char *staticdata = luaL_optstring(L, 3, "");
596 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata);
597 int objectid = env->addActiveObject(obj);
598 // If failed to add, return nothing (reads as nil)
602 // If already deleted (can happen in on_activate), return nil
605 getScriptApiBase(L)->objectrefGetOrCreate(L, obj);
609 // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
610 // pos = {x=num, y=num, z=num}
611 int ModApiEnvMod::l_add_item(lua_State *L)
616 //v3f pos = checkFloatPos(L, 1);
618 ItemStack item = read_item(L, 2,getServer(L)->idef());
619 if(item.empty() || !item.isKnown(getServer(L)->idef()))
622 int error_handler = PUSH_ERROR_HANDLER(L);
624 // Use spawn_item to spawn a __builtin:item
625 lua_getglobal(L, "core");
626 lua_getfield(L, -1, "spawn_item");
627 lua_remove(L, -2); // Remove core
631 lua_pushstring(L, item.getItemString().c_str());
633 PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler));
635 lua_remove(L, error_handler);
639 // get_connected_players()
640 int ModApiEnvMod::l_get_connected_players(lua_State *L)
642 ServerEnvironment *env = (ServerEnvironment *) getEnv(L);
644 log_deprecated(L, "Calling get_connected_players() at mod load time"
646 lua_createtable(L, 0, 0);
650 lua_createtable(L, env->getPlayerCount(), 0);
652 for (RemotePlayer *player : env->getPlayers()) {
653 if (player->getPeerId() == PEER_ID_INEXISTENT)
655 PlayerSAO *sao = player->getPlayerSAO();
656 if (sao && !sao->isGone()) {
657 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
658 lua_rawseti(L, -2, ++i);
664 // get_player_by_name(name)
665 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
670 const char *name = luaL_checkstring(L, 1);
671 RemotePlayer *player = env->getPlayer(name);
672 if (!player || player->getPeerId() == PEER_ID_INEXISTENT)
674 PlayerSAO *sao = player->getPlayerSAO();
675 if (!sao || sao->isGone())
677 // Put player on stack
678 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
682 // get_objects_inside_radius(pos, radius)
683 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
686 ScriptApiBase *script = getScriptApiBase(L);
689 v3f pos = checkFloatPos(L, 1);
690 float radius = readParam<float>(L, 2) * BS;
691 std::vector<ServerActiveObject *> objs;
693 auto include_obj_cb = [](ServerActiveObject *obj){ return !obj->isGone(); };
694 env->getObjectsInsideRadius(objs, pos, radius, include_obj_cb);
697 lua_createtable(L, objs.size(), 0);
698 for (const auto obj : objs) {
699 // Insert object reference into table
700 script->objectrefGetOrCreate(L, obj);
701 lua_rawseti(L, -2, ++i);
706 // set_timeofday(val)
708 int ModApiEnvMod::l_set_timeofday(lua_State *L)
713 float timeofday_f = readParam<float>(L, 1);
714 sanity_check(timeofday_f >= 0.0 && timeofday_f <= 1.0);
715 int timeofday_mh = (int)(timeofday_f * 24000.0);
716 // This should be set directly in the environment but currently
717 // such changes aren't immediately sent to the clients, so call
718 // the server instead.
719 //env->setTimeOfDay(timeofday_mh);
720 getServer(L)->setTimeOfDay(timeofday_mh);
724 // get_timeofday() -> 0...1
725 int ModApiEnvMod::l_get_timeofday(lua_State *L)
730 int timeofday_mh = env->getTimeOfDay();
731 float timeofday_f = (float)timeofday_mh / 24000.0f;
732 lua_pushnumber(L, timeofday_f);
736 // get_day_count() -> int
737 int ModApiEnvMod::l_get_day_count(lua_State *L)
741 lua_pushnumber(L, env->getDayCount());
746 int ModApiEnvMod::l_get_gametime(lua_State *L)
750 int game_time = env->getGameTime();
751 lua_pushnumber(L, game_time);
756 // find_node_near(pos, radius, nodenames, search_center) -> pos or nil
757 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
758 int ModApiEnvMod::l_find_node_near(lua_State *L)
762 const NodeDefManager *ndef = env->getGameDef()->ndef();
763 v3s16 pos = read_v3s16(L, 1);
764 int radius = luaL_checkinteger(L, 2);
765 std::vector<content_t> filter;
766 if (lua_istable(L, 3)) {
768 while (lua_next(L, 3) != 0) {
769 // key at index -2 and value at index -1
770 luaL_checktype(L, -1, LUA_TSTRING);
771 ndef->getIds(readParam<std::string>(L, -1), filter);
772 // removes value, keeps key for next iteration
775 } else if (lua_isstring(L, 3)) {
776 ndef->getIds(readParam<std::string>(L, 3), filter);
779 int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
782 // Client API limitations
783 if (Client *client = getClient(L))
784 radius = client->CSMClampRadius(pos, radius);
787 for (int d = start_radius; d <= radius; d++) {
788 std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
789 for (const v3s16 &i : list) {
791 content_t c = env->getMap().getNode(p).getContent();
792 if (CONTAINS(filter, c)) {
801 // find_nodes_in_area(minp, maxp, nodenames) -> list of positions
802 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
803 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
807 v3s16 minp = read_v3s16(L, 1);
808 v3s16 maxp = read_v3s16(L, 2);
809 sortBoxVerticies(minp, maxp);
811 const NodeDefManager *ndef = env->getGameDef()->ndef();
814 if (Client *client = getClient(L)) {
815 minp = client->CSMClampPos(minp);
816 maxp = client->CSMClampPos(maxp);
820 v3s16 cube = maxp - minp + 1;
821 // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
822 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) {
823 luaL_error(L, "find_nodes_in_area(): area volume"
824 " exceeds allowed value of 4096000");
828 std::vector<content_t> filter;
829 if (lua_istable(L, 3)) {
831 while (lua_next(L, 3) != 0) {
832 // key at index -2 and value at index -1
833 luaL_checktype(L, -1, LUA_TSTRING);
834 ndef->getIds(readParam<std::string>(L, -1), filter);
835 // removes value, keeps key for next iteration
838 } else if (lua_isstring(L, 3)) {
839 ndef->getIds(readParam<std::string>(L, 3), filter);
842 std::vector<u32> individual_count;
843 individual_count.resize(filter.size());
847 for (s16 x = minp.X; x <= maxp.X; x++)
848 for (s16 y = minp.Y; y <= maxp.Y; y++)
849 for (s16 z = minp.Z; z <= maxp.Z; z++) {
851 content_t c = env->getMap().getNode(p).getContent();
853 std::vector<content_t>::iterator it = std::find(filter.begin(), filter.end(), c);
854 if (it != filter.end()) {
856 lua_rawseti(L, -2, ++i);
858 u32 filt_index = it - filter.begin();
859 individual_count[filt_index]++;
863 for (u32 i = 0; i < filter.size(); i++) {
864 lua_pushnumber(L, individual_count[i]);
865 lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
870 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
871 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
872 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
874 /* Note: A similar but generalized (and therefore slower) version of this
875 * function could be created -- e.g. find_nodes_in_area_under -- which
876 * would accept a node name (or ID?) or list of names that the "above node"
883 v3s16 minp = read_v3s16(L, 1);
884 v3s16 maxp = read_v3s16(L, 2);
885 sortBoxVerticies(minp, maxp);
887 const NodeDefManager *ndef = env->getGameDef()->ndef();
890 if (Client *client = getClient(L)) {
891 minp = client->CSMClampPos(minp);
892 maxp = client->CSMClampPos(maxp);
896 v3s16 cube = maxp - minp + 1;
897 // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
898 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) {
899 luaL_error(L, "find_nodes_in_area_under_air(): area volume"
900 " exceeds allowed value of 4096000");
904 std::vector<content_t> filter;
906 if (lua_istable(L, 3)) {
908 while (lua_next(L, 3) != 0) {
909 // key at index -2 and value at index -1
910 luaL_checktype(L, -1, LUA_TSTRING);
911 ndef->getIds(readParam<std::string>(L, -1), filter);
912 // removes value, keeps key for next iteration
915 } else if (lua_isstring(L, 3)) {
916 ndef->getIds(readParam<std::string>(L, 3), filter);
921 for (s16 x = minp.X; x <= maxp.X; x++)
922 for (s16 z = minp.Z; z <= maxp.Z; z++) {
925 content_t c = env->getMap().getNode(p).getContent();
926 for (; y <= maxp.Y; y++) {
927 v3s16 psurf(x, y + 1, z);
928 content_t csurf = env->getMap().getNode(psurf).getContent();
929 if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
930 CONTAINS(filter, c)) {
931 push_v3s16(L, v3s16(x, y, z));
932 lua_rawseti(L, -2, ++i);
940 // get_perlin(seeddiff, octaves, persistence, scale)
941 // returns world-specific PerlinNoise
942 int ModApiEnvMod::l_get_perlin(lua_State *L)
944 GET_ENV_PTR_NO_MAP_LOCK;
948 if (lua_istable(L, 1)) {
949 read_noiseparams(L, 1, ¶ms);
951 params.seed = luaL_checkint(L, 1);
952 params.octaves = luaL_checkint(L, 2);
953 params.persist = readParam<float>(L, 3);
954 params.spread = v3f(1, 1, 1) * readParam<float>(L, 4);
957 params.seed += (int)env->getServerMap().getSeed();
959 LuaPerlinNoise *n = new LuaPerlinNoise(¶ms);
960 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
961 luaL_getmetatable(L, "PerlinNoise");
962 lua_setmetatable(L, -2);
966 // get_perlin_map(noiseparams, size)
967 // returns world-specific PerlinNoiseMap
968 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
970 GET_ENV_PTR_NO_MAP_LOCK;
973 if (!read_noiseparams(L, 1, &np))
975 v3s16 size = read_v3s16(L, 2);
977 s32 seed = (s32)(env->getServerMap().getSeed());
978 LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
979 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
980 luaL_getmetatable(L, "PerlinNoiseMap");
981 lua_setmetatable(L, -2);
986 // returns voxel manipulator
987 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
991 Map *map = &(env->getMap());
992 LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
993 new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
994 new LuaVoxelManip(map);
996 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
997 luaL_getmetatable(L, "VoxelManip");
998 lua_setmetatable(L, -2);
1002 // clear_objects([options])
1003 // clear all objects in the environment
1004 // where options = {mode = "full" or "quick"}
1005 int ModApiEnvMod::l_clear_objects(lua_State *L)
1009 ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK;
1010 if (lua_istable(L, 1)) {
1011 mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
1012 ModApiEnvMod::es_ClearObjectsMode, mode);
1015 env->clearObjects(mode);
1019 // line_of_sight(pos1, pos2) -> true/false, pos
1020 int ModApiEnvMod::l_line_of_sight(lua_State *L)
1024 // read position 1 from lua
1025 v3f pos1 = checkFloatPos(L, 1);
1026 // read position 2 from lua
1027 v3f pos2 = checkFloatPos(L, 2);
1031 bool success = env->line_of_sight(pos1, pos2, &p);
1032 lua_pushboolean(L, success);
1040 // fix_light(p1, p2)
1041 int ModApiEnvMod::l_fix_light(lua_State *L)
1045 v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
1046 v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
1047 ServerMap &map = env->getServerMap();
1048 std::map<v3s16, MapBlock *> modified_blocks;
1049 bool success = true;
1051 for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
1052 for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
1053 for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
1054 success = success & map.repairBlockLight(blockpos, &modified_blocks);
1056 if (!modified_blocks.empty()) {
1058 event.type = MEET_OTHER;
1059 for (auto &modified_block : modified_blocks)
1060 event.modified_blocks.insert(modified_block.first);
1062 map.dispatchEvent(event);
1064 lua_pushboolean(L, success);
1069 int ModApiEnvMod::l_raycast(lua_State *L)
1071 return LuaRaycast::create_object(L);
1074 // load_area(p1, [p2])
1075 // load mapblocks in area p1..p2, but do not generate map
1076 int ModApiEnvMod::l_load_area(lua_State *L)
1081 Map *map = &(env->getMap());
1082 v3s16 bp1 = getNodeBlockPos(check_v3s16(L, 1));
1083 if (!lua_istable(L, 2)) {
1084 map->emergeBlock(bp1);
1086 v3s16 bp2 = getNodeBlockPos(check_v3s16(L, 2));
1087 sortBoxVerticies(bp1, bp2);
1088 for (s16 z = bp1.Z; z <= bp2.Z; z++)
1089 for (s16 y = bp1.Y; y <= bp2.Y; y++)
1090 for (s16 x = bp1.X; x <= bp2.X; x++) {
1091 map->emergeBlock(v3s16(x, y, z));
1098 // emerge_area(p1, p2, [callback, context])
1099 // emerge mapblocks in area p1..p2, calls callback with context upon completion
1100 int ModApiEnvMod::l_emerge_area(lua_State *L)
1104 EmergeCompletionCallback callback = NULL;
1105 ScriptCallbackState *state = NULL;
1107 EmergeManager *emerge = getServer(L)->getEmergeManager();
1109 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1110 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1111 sortBoxVerticies(bpmin, bpmax);
1113 size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
1114 assert(num_blocks != 0);
1116 if (lua_isfunction(L, 3)) {
1117 callback = LuaEmergeAreaCallback;
1119 lua_pushvalue(L, 3);
1120 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1122 lua_pushvalue(L, 4);
1123 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1125 state = new ScriptCallbackState;
1126 state->script = getServer(L)->getScriptIface();
1127 state->callback_ref = callback_ref;
1128 state->args_ref = args_ref;
1129 state->refcount = num_blocks;
1130 state->origin = getScriptApiBase(L)->getOrigin();
1133 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1134 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1135 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1136 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
1137 BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
1143 // delete_area(p1, p2)
1144 // delete mapblocks in area p1..p2
1145 int ModApiEnvMod::l_delete_area(lua_State *L)
1149 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1150 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1151 sortBoxVerticies(bpmin, bpmax);
1153 ServerMap &map = env->getServerMap();
1156 event.type = MEET_OTHER;
1158 bool success = true;
1159 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1160 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1161 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1163 if (map.deleteBlock(bp)) {
1164 env->setStaticForActiveObjectsInBlock(bp, false);
1165 event.modified_blocks.insert(bp);
1171 map.dispatchEvent(event);
1172 lua_pushboolean(L, success);
1176 // find_path(pos1, pos2, searchdistance,
1177 // max_jump, max_drop, algorithm) -> table containing path
1178 int ModApiEnvMod::l_find_path(lua_State *L)
1182 v3s16 pos1 = read_v3s16(L, 1);
1183 v3s16 pos2 = read_v3s16(L, 2);
1184 unsigned int searchdistance = luaL_checkint(L, 3);
1185 unsigned int max_jump = luaL_checkint(L, 4);
1186 unsigned int max_drop = luaL_checkint(L, 5);
1187 PathAlgorithm algo = PA_PLAIN_NP;
1188 if (!lua_isnoneornil(L, 6)) {
1189 std::string algorithm = luaL_checkstring(L,6);
1191 if (algorithm == "A*")
1194 if (algorithm == "Dijkstra")
1198 std::vector<v3s16> path = get_path(&env->getServerMap(), env->getGameDef()->ndef(), pos1, pos2,
1199 searchdistance, max_jump, max_drop, algo);
1201 if (!path.empty()) {
1202 lua_createtable(L, path.size(), 0);
1203 int top = lua_gettop(L);
1204 unsigned int index = 1;
1205 for (const v3s16 &i : path) {
1206 lua_pushnumber(L,index);
1208 lua_settable(L, top);
1217 // spawn_tree(pos, treedef)
1218 int ModApiEnvMod::l_spawn_tree(lua_State *L)
1222 v3s16 p0 = read_v3s16(L, 1);
1224 treegen::TreeDef tree_def;
1225 std::string trunk,leaves,fruit;
1226 const NodeDefManager *ndef = env->getGameDef()->ndef();
1228 if(lua_istable(L, 2))
1230 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
1231 getstringfield(L, 2, "rules_a", tree_def.rules_a);
1232 getstringfield(L, 2, "rules_b", tree_def.rules_b);
1233 getstringfield(L, 2, "rules_c", tree_def.rules_c);
1234 getstringfield(L, 2, "rules_d", tree_def.rules_d);
1235 getstringfield(L, 2, "trunk", trunk);
1236 tree_def.trunknode=ndef->getId(trunk);
1237 getstringfield(L, 2, "leaves", leaves);
1238 tree_def.leavesnode=ndef->getId(leaves);
1239 tree_def.leaves2_chance=0;
1240 getstringfield(L, 2, "leaves2", leaves);
1241 if (!leaves.empty()) {
1242 tree_def.leaves2node=ndef->getId(leaves);
1243 getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
1245 getintfield(L, 2, "angle", tree_def.angle);
1246 getintfield(L, 2, "iterations", tree_def.iterations);
1247 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1248 tree_def.iterations_random_level = 0;
1249 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1250 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1251 tree_def.fruit_chance=0;
1252 getstringfield(L, 2, "fruit", fruit);
1253 if (!fruit.empty()) {
1254 tree_def.fruitnode=ndef->getId(fruit);
1255 getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
1257 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1262 ServerMap *map = &env->getServerMap();
1264 if ((e = treegen::spawn_ltree (map, p0, ndef, tree_def)) != treegen::SUCCESS) {
1265 if (e == treegen::UNBALANCED_BRACKETS) {
1266 luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1268 luaL_error(L, "spawn_tree(): unknown error");
1275 // transforming_liquid_add(pos)
1276 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1280 v3s16 p0 = read_v3s16(L, 1);
1281 env->getMap().transforming_liquid_add(p0);
1285 // forceload_block(blockpos)
1286 // blockpos = {x=num, y=num, z=num}
1287 int ModApiEnvMod::l_forceload_block(lua_State *L)
1291 v3s16 blockpos = read_v3s16(L, 1);
1292 env->getForceloadedBlocks()->insert(blockpos);
1296 // forceload_free_block(blockpos)
1297 // blockpos = {x=num, y=num, z=num}
1298 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1302 v3s16 blockpos = read_v3s16(L, 1);
1303 env->getForceloadedBlocks()->erase(blockpos);
1307 // get_translated_string(lang_code, string)
1308 int ModApiEnvMod::l_get_translated_string(lua_State * L)
1311 std::string lang_code = luaL_checkstring(L, 1);
1312 std::string string = luaL_checkstring(L, 2);
1313 getServer(L)->loadTranslationLanguage(lang_code);
1314 string = wide_to_utf8(translate_string(utf8_to_wide(string),
1315 &(*g_server_translations)[lang_code]));
1316 lua_pushstring(L, string.c_str());
1320 void ModApiEnvMod::Initialize(lua_State *L, int top)
1323 API_FCT(bulk_set_node);
1327 API_FCT(remove_node);
1329 API_FCT(get_node_or_nil);
1330 API_FCT(get_node_light);
1331 API_FCT(place_node);
1333 API_FCT(punch_node);
1334 API_FCT(get_node_max_level);
1335 API_FCT(get_node_level);
1336 API_FCT(set_node_level);
1337 API_FCT(add_node_level);
1338 API_FCT(add_entity);
1339 API_FCT(find_nodes_with_meta);
1341 API_FCT(get_node_timer);
1342 API_FCT(get_connected_players);
1343 API_FCT(get_player_by_name);
1344 API_FCT(get_objects_inside_radius);
1345 API_FCT(set_timeofday);
1346 API_FCT(get_timeofday);
1347 API_FCT(get_gametime);
1348 API_FCT(get_day_count);
1349 API_FCT(find_node_near);
1350 API_FCT(find_nodes_in_area);
1351 API_FCT(find_nodes_in_area_under_air);
1354 API_FCT(emerge_area);
1355 API_FCT(delete_area);
1356 API_FCT(get_perlin);
1357 API_FCT(get_perlin_map);
1358 API_FCT(get_voxel_manip);
1359 API_FCT(clear_objects);
1360 API_FCT(spawn_tree);
1362 API_FCT(line_of_sight);
1364 API_FCT(transforming_liquid_add);
1365 API_FCT(forceload_block);
1366 API_FCT(forceload_free_block);
1367 API_FCT(get_translated_string);
1370 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1372 API_FCT(get_node_light);
1373 API_FCT(get_timeofday);
1374 API_FCT(get_node_max_level);
1375 API_FCT(get_node_level);
1376 API_FCT(find_nodes_with_meta);
1377 API_FCT(find_node_near);
1378 API_FCT(find_nodes_in_area);
1379 API_FCT(find_nodes_in_area_under_air);
1380 API_FCT(line_of_sight);