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.
20 #include "lua_api/l_env.h"
21 #include "lua_api/l_internal.h"
22 #include "lua_api/l_nodemeta.h"
23 #include "lua_api/l_nodetimer.h"
24 #include "lua_api/l_noise.h"
25 #include "lua_api/l_vmanip.h"
26 #include "common/c_converter.h"
27 #include "common/c_content.h"
28 #include "scripting_server.h"
29 #include "environment.h"
32 #include "daynightratio.h"
33 #include "util/pointedthing.h"
34 #include "content_sao.h"
37 #include "pathfinder.h"
38 #include "face_position_cache.h"
40 struct EnumString ModApiEnvMod::es_ClearObjectsMode[] =
42 {CLEAR_OBJECTS_MODE_FULL, "full"},
43 {CLEAR_OBJECTS_MODE_QUICK, "quick"},
47 ///////////////////////////////////////////////////////////////////////////////
50 void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
51 u32 active_object_count, u32 active_object_count_wider)
53 ServerScripting *scriptIface = env->getScriptIface();
54 scriptIface->realityCheck();
56 lua_State *L = scriptIface->getStack();
57 sanity_check(lua_checkstack(L, 20));
58 StackUnroller stack_unroller(L);
60 int error_handler = PUSH_ERROR_HANDLER(L);
62 // Get registered_abms
63 lua_getglobal(L, "core");
64 lua_getfield(L, -1, "registered_abms");
65 luaL_checktype(L, -1, LUA_TTABLE);
66 lua_remove(L, -2); // Remove core
68 // Get registered_abms[m_id]
69 lua_pushnumber(L, m_id);
73 lua_remove(L, -2); // Remove registered_abms
75 scriptIface->setOriginFromTable(-1);
78 luaL_checktype(L, -1, LUA_TTABLE);
79 lua_getfield(L, -1, "action");
80 luaL_checktype(L, -1, LUA_TFUNCTION);
81 lua_remove(L, -2); // Remove registered_abms[m_id]
83 pushnode(L, n, env->getGameDef()->ndef());
84 lua_pushnumber(L, active_object_count);
85 lua_pushnumber(L, active_object_count_wider);
87 int result = lua_pcall(L, 4, 0, error_handler);
89 scriptIface->scriptError(result, "LuaABM::trigger");
91 lua_pop(L, 1); // Pop error handler
94 void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n)
96 ServerScripting *scriptIface = env->getScriptIface();
97 scriptIface->realityCheck();
99 lua_State *L = scriptIface->getStack();
100 sanity_check(lua_checkstack(L, 20));
101 StackUnroller stack_unroller(L);
103 int error_handler = PUSH_ERROR_HANDLER(L);
105 // Get registered_lbms
106 lua_getglobal(L, "core");
107 lua_getfield(L, -1, "registered_lbms");
108 luaL_checktype(L, -1, LUA_TTABLE);
109 lua_remove(L, -2); // Remove core
111 // Get registered_lbms[m_id]
112 lua_pushnumber(L, m_id);
114 FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table");
115 lua_remove(L, -2); // Remove registered_lbms
117 scriptIface->setOriginFromTable(-1);
120 luaL_checktype(L, -1, LUA_TTABLE);
121 lua_getfield(L, -1, "action");
122 luaL_checktype(L, -1, LUA_TFUNCTION);
123 lua_remove(L, -2); // Remove registered_lbms[m_id]
125 pushnode(L, n, env->getGameDef()->ndef());
127 int result = lua_pcall(L, 2, 0, error_handler);
129 scriptIface->scriptError(result, "LuaLBM::trigger");
131 lua_pop(L, 1); // Pop error handler
134 int LuaRaycast::l_next(lua_State *L)
138 ScriptApiItem *script = getScriptApi<ScriptApiItem>(L);
141 LuaRaycast *o = checkobject(L, 1);
142 PointedThing pointed;
143 env->continueRaycast(&o->state, &pointed);
144 if (pointed.type == POINTEDTHING_NOTHING)
147 script->pushPointedThing(pointed);
152 int LuaRaycast::create_object(lua_State *L)
154 NO_MAP_LOCK_REQUIRED;
157 bool liquids = false;
159 v3f pos1 = checkFloatPos(L, 1);
160 v3f pos2 = checkFloatPos(L, 2);
161 if (lua_isboolean(L, 3)) {
162 objects = lua_toboolean(L, 3);
164 if (lua_isboolean(L, 4)) {
165 liquids = lua_toboolean(L, 4);
168 LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2),
171 *(void **) (lua_newuserdata(L, sizeof(void *))) = o;
172 luaL_getmetatable(L, className);
173 lua_setmetatable(L, -2);
177 LuaRaycast *LuaRaycast::checkobject(lua_State *L, int narg)
179 NO_MAP_LOCK_REQUIRED;
181 luaL_checktype(L, narg, LUA_TUSERDATA);
182 void *ud = luaL_checkudata(L, narg, className);
184 luaL_typerror(L, narg, className);
185 return *(LuaRaycast **) ud;
188 int LuaRaycast::gc_object(lua_State *L)
190 LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1));
195 void LuaRaycast::Register(lua_State *L)
198 int methodtable = lua_gettop(L);
199 luaL_newmetatable(L, className);
200 int metatable = lua_gettop(L);
202 lua_pushliteral(L, "__metatable");
203 lua_pushvalue(L, methodtable);
204 lua_settable(L, metatable);
206 lua_pushliteral(L, "__index");
207 lua_pushvalue(L, methodtable);
208 lua_settable(L, metatable);
210 lua_pushliteral(L, "__gc");
211 lua_pushcfunction(L, gc_object);
212 lua_settable(L, metatable);
214 lua_pushliteral(L, "__call");
215 lua_pushcfunction(L, l_next);
216 lua_settable(L, metatable);
220 luaL_openlib(L, 0, methods, 0);
223 lua_register(L, className, create_object);
226 const char LuaRaycast::className[] = "Raycast";
227 const luaL_Reg LuaRaycast::methods[] =
229 luamethod(LuaRaycast, next),
233 void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param)
235 ScriptCallbackState *state = (ScriptCallbackState *)param;
236 assert(state != NULL);
237 assert(state->script != NULL);
238 assert(state->refcount > 0);
240 // state must be protected by envlock
241 Server *server = state->script->getServer();
242 MutexAutoLock envlock(server->m_env_mutex);
246 state->script->on_emerge_area_completion(blockpos, action, state);
248 if (state->refcount == 0)
252 // Exported functions
254 // set_node(pos, node)
255 // pos = {x=num, y=num, z=num}
256 int ModApiEnvMod::l_set_node(lua_State *L)
260 INodeDefManager *ndef = env->getGameDef()->ndef();
262 v3s16 pos = read_v3s16(L, 1);
263 MapNode n = readnode(L, 2, ndef);
265 bool succeeded = env->setNode(pos, n);
266 lua_pushboolean(L, succeeded);
270 int ModApiEnvMod::l_add_node(lua_State *L)
272 return l_set_node(L);
276 // pos = {x=num, y=num, z=num}
277 int ModApiEnvMod::l_remove_node(lua_State *L)
282 v3s16 pos = read_v3s16(L, 1);
284 bool succeeded = env->removeNode(pos);
285 lua_pushboolean(L, succeeded);
289 // swap_node(pos, node)
290 // pos = {x=num, y=num, z=num}
291 int ModApiEnvMod::l_swap_node(lua_State *L)
295 INodeDefManager *ndef = env->getGameDef()->ndef();
297 v3s16 pos = read_v3s16(L, 1);
298 MapNode n = readnode(L, 2, ndef);
300 bool succeeded = env->swapNode(pos, n);
301 lua_pushboolean(L, succeeded);
306 // pos = {x=num, y=num, z=num}
307 int ModApiEnvMod::l_get_node(lua_State *L)
312 v3s16 pos = read_v3s16(L, 1);
314 MapNode n = env->getMap().getNodeNoEx(pos);
316 pushnode(L, n, env->getGameDef()->ndef());
320 // get_node_or_nil(pos)
321 // pos = {x=num, y=num, z=num}
322 int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
327 v3s16 pos = read_v3s16(L, 1);
330 MapNode n = env->getMap().getNodeNoEx(pos, &pos_ok);
333 pushnode(L, n, env->getGameDef()->ndef());
340 // get_node_light(pos, timeofday)
341 // pos = {x=num, y=num, z=num}
342 // timeofday: nil = current time, 0 = night, 0.5 = day
343 int ModApiEnvMod::l_get_node_light(lua_State *L)
348 v3s16 pos = read_v3s16(L, 1);
349 u32 time_of_day = env->getTimeOfDay();
350 if(lua_isnumber(L, 2))
351 time_of_day = 24000.0 * lua_tonumber(L, 2);
352 time_of_day %= 24000;
353 u32 dnr = time_to_daynight_ratio(time_of_day, true);
356 MapNode n = env->getMap().getNodeNoEx(pos, &is_position_ok);
357 if (is_position_ok) {
358 INodeDefManager *ndef = env->getGameDef()->ndef();
359 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
366 // place_node(pos, node)
367 // pos = {x=num, y=num, z=num}
368 int ModApiEnvMod::l_place_node(lua_State *L)
372 ScriptApiItem *scriptIfaceItem = getScriptApi<ScriptApiItem>(L);
373 Server *server = getServer(L);
374 INodeDefManager *ndef = server->ndef();
375 IItemDefManager *idef = server->idef();
377 v3s16 pos = read_v3s16(L, 1);
378 MapNode n = readnode(L, 2, ndef);
380 // Don't attempt to load non-loaded area as of now
381 MapNode n_old = env->getMap().getNodeNoEx(pos);
382 if(n_old.getContent() == CONTENT_IGNORE){
383 lua_pushboolean(L, false);
386 // Create item to place
387 ItemStack item(ndef->get(n).name, 1, 0, idef);
388 // Make pointed position
389 PointedThing pointed;
390 pointed.type = POINTEDTHING_NODE;
391 pointed.node_abovesurface = pos;
392 pointed.node_undersurface = pos + v3s16(0,-1,0);
393 // Place it with a NULL placer (appears in Lua as a non-functional
395 bool success = scriptIfaceItem->item_OnPlace(item, NULL, pointed);
396 lua_pushboolean(L, success);
401 // pos = {x=num, y=num, z=num}
402 int ModApiEnvMod::l_dig_node(lua_State *L)
406 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
408 v3s16 pos = read_v3s16(L, 1);
410 // Don't attempt to load non-loaded area as of now
411 MapNode n = env->getMap().getNodeNoEx(pos);
412 if(n.getContent() == CONTENT_IGNORE){
413 lua_pushboolean(L, false);
416 // Dig it out with a NULL digger (appears in Lua as a
417 // non-functional ObjectRef)
418 bool success = scriptIfaceNode->node_on_dig(pos, n, NULL);
419 lua_pushboolean(L, success);
424 // pos = {x=num, y=num, z=num}
425 int ModApiEnvMod::l_punch_node(lua_State *L)
429 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
431 v3s16 pos = read_v3s16(L, 1);
433 // Don't attempt to load non-loaded area as of now
434 MapNode n = env->getMap().getNodeNoEx(pos);
435 if(n.getContent() == CONTENT_IGNORE){
436 lua_pushboolean(L, false);
439 // Punch it with a NULL puncher (appears in Lua as a non-functional
441 bool success = scriptIfaceNode->node_on_punch(pos, n, NULL, PointedThing());
442 lua_pushboolean(L, success);
446 // get_node_max_level(pos)
447 // pos = {x=num, y=num, z=num}
448 int ModApiEnvMod::l_get_node_max_level(lua_State *L)
450 Environment *env = getEnv(L);
455 v3s16 pos = read_v3s16(L, 1);
456 MapNode n = env->getMap().getNodeNoEx(pos);
457 lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef()));
461 // get_node_level(pos)
462 // pos = {x=num, y=num, z=num}
463 int ModApiEnvMod::l_get_node_level(lua_State *L)
465 Environment *env = getEnv(L);
470 v3s16 pos = read_v3s16(L, 1);
471 MapNode n = env->getMap().getNodeNoEx(pos);
472 lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef()));
476 // set_node_level(pos, level)
477 // pos = {x=num, y=num, z=num}
479 int ModApiEnvMod::l_set_node_level(lua_State *L)
483 v3s16 pos = read_v3s16(L, 1);
485 if(lua_isnumber(L, 2))
486 level = lua_tonumber(L, 2);
487 MapNode n = env->getMap().getNodeNoEx(pos);
488 lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level));
489 env->setNode(pos, n);
493 // add_node_level(pos, level)
494 // pos = {x=num, y=num, z=num}
496 int ModApiEnvMod::l_add_node_level(lua_State *L)
500 v3s16 pos = read_v3s16(L, 1);
502 if(lua_isnumber(L, 2))
503 level = lua_tonumber(L, 2);
504 MapNode n = env->getMap().getNodeNoEx(pos);
505 lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level));
506 env->setNode(pos, n);
510 // find_nodes_with_meta(pos1, pos2)
511 int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L)
515 std::vector<v3s16> positions = env->getMap().findNodesWithMetadata(
516 check_v3s16(L, 1), check_v3s16(L, 2));
519 for (size_t i = 0; i != positions.size(); i++) {
520 push_v3s16(L, positions[i]);
521 lua_rawseti(L, -2, i + 1);
528 int ModApiEnvMod::l_get_meta(lua_State *L)
533 v3s16 p = read_v3s16(L, 1);
534 NodeMetaRef::create(L, p, env);
538 // get_node_timer(pos)
539 int ModApiEnvMod::l_get_node_timer(lua_State *L)
544 v3s16 p = read_v3s16(L, 1);
545 NodeTimerRef::create(L, p, env);
549 // add_entity(pos, entityname, [staticdata]) -> ObjectRef or nil
550 // pos = {x=num, y=num, z=num}
551 int ModApiEnvMod::l_add_entity(lua_State *L)
556 v3f pos = checkFloatPos(L, 1);
558 const char *name = luaL_checkstring(L, 2);
560 const char *staticdata = luaL_optstring(L, 3, "");
562 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata);
563 int objectid = env->addActiveObject(obj);
564 // If failed to add, return nothing (reads as nil)
568 getScriptApiBase(L)->objectrefGetOrCreate(L, obj);
572 // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
573 // pos = {x=num, y=num, z=num}
574 int ModApiEnvMod::l_add_item(lua_State *L)
579 //v3f pos = checkFloatPos(L, 1);
581 ItemStack item = read_item(L, 2,getServer(L)->idef());
582 if(item.empty() || !item.isKnown(getServer(L)->idef()))
585 int error_handler = PUSH_ERROR_HANDLER(L);
587 // Use spawn_item to spawn a __builtin:item
588 lua_getglobal(L, "core");
589 lua_getfield(L, -1, "spawn_item");
590 lua_remove(L, -2); // Remove core
594 lua_pushstring(L, item.getItemString().c_str());
596 PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler));
598 lua_remove(L, error_handler);
602 // get_player_by_name(name)
603 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
608 const char *name = luaL_checkstring(L, 1);
609 RemotePlayer *player = dynamic_cast<RemotePlayer *>(env->getPlayer(name));
614 PlayerSAO *sao = player->getPlayerSAO();
619 // Put player on stack
620 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
624 // get_objects_inside_radius(pos, radius)
625 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
630 v3f pos = checkFloatPos(L, 1);
631 float radius = luaL_checknumber(L, 2) * BS;
632 std::vector<u16> ids;
633 env->getObjectsInsideRadius(ids, pos, radius);
634 ScriptApiBase *script = getScriptApiBase(L);
635 lua_createtable(L, ids.size(), 0);
636 std::vector<u16>::const_iterator iter = ids.begin();
637 for(u32 i = 0; iter != ids.end(); ++iter) {
638 ServerActiveObject *obj = env->getActiveObject(*iter);
639 // Insert object reference into table
640 script->objectrefGetOrCreate(L, obj);
641 lua_rawseti(L, -2, ++i);
646 // set_timeofday(val)
648 int ModApiEnvMod::l_set_timeofday(lua_State *L)
653 float timeofday_f = luaL_checknumber(L, 1);
654 sanity_check(timeofday_f >= 0.0 && timeofday_f <= 1.0);
655 int timeofday_mh = (int)(timeofday_f * 24000.0);
656 // This should be set directly in the environment but currently
657 // such changes aren't immediately sent to the clients, so call
658 // the server instead.
659 //env->setTimeOfDay(timeofday_mh);
660 getServer(L)->setTimeOfDay(timeofday_mh);
664 // get_timeofday() -> 0...1
665 int ModApiEnvMod::l_get_timeofday(lua_State *L)
667 Environment *env = getEnv(L);
673 int timeofday_mh = env->getTimeOfDay();
674 float timeofday_f = (float)timeofday_mh / 24000.0f;
675 lua_pushnumber(L, timeofday_f);
679 // get_day_count() -> int
680 int ModApiEnvMod::l_get_day_count(lua_State *L)
682 Environment *env = getEnv(L);
687 lua_pushnumber(L, env->getDayCount());
692 int ModApiEnvMod::l_get_gametime(lua_State *L)
696 int game_time = env->getGameTime();
697 lua_pushnumber(L, game_time);
702 // find_node_near(pos, radius, nodenames, search_center) -> pos or nil
703 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
704 int ModApiEnvMod::l_find_node_near(lua_State *L)
706 Environment *env = getEnv(L);
711 INodeDefManager *ndef = getGameDef(L)->ndef();
712 v3s16 pos = read_v3s16(L, 1);
713 int radius = luaL_checkinteger(L, 2);
714 std::set<content_t> filter;
715 if (lua_istable(L, 3)) {
717 while (lua_next(L, 3) != 0) {
718 // key at index -2 and value at index -1
719 luaL_checktype(L, -1, LUA_TSTRING);
720 ndef->getIds(lua_tostring(L, -1), filter);
721 // removes value, keeps key for next iteration
724 } else if (lua_isstring(L, 3)) {
725 ndef->getIds(lua_tostring(L, 3), filter);
728 int start_radius = (lua_toboolean(L, 4)) ? 0 : 1;
729 for (int d = start_radius; d <= radius; d++) {
730 std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
731 for (std::vector<v3s16>::iterator i = list.begin();
732 i != list.end(); ++i) {
733 v3s16 p = pos + (*i);
734 content_t c = env->getMap().getNodeNoEx(p).getContent();
735 if (filter.count(c) != 0) {
744 // find_nodes_in_area(minp, maxp, nodenames) -> list of positions
745 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
746 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
750 INodeDefManager *ndef = getServer(L)->ndef();
751 v3s16 minp = read_v3s16(L, 1);
752 v3s16 maxp = read_v3s16(L, 2);
753 sortBoxVerticies(minp, maxp);
755 v3s16 cube = maxp - minp + 1;
757 /* Limit for too large areas, assume default values
758 * and give tolerances of 1 node on each side
759 * (chunksize * MAP_BLOCKSIZE + 2)^3 = 551368
761 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 551368) {
762 luaL_error(L, "find_nodes_in_area(): area volume"
763 " exceeds allowed value of 551368");
767 std::set<content_t> filter;
768 if (lua_istable(L, 3)) {
770 while (lua_next(L, 3) != 0) {
771 // key at index -2 and value at index -1
772 luaL_checktype(L, -1, LUA_TSTRING);
773 ndef->getIds(lua_tostring(L, -1), filter);
774 // removes value, keeps key for next iteration
777 } else if (lua_isstring(L, 3)) {
778 ndef->getIds(lua_tostring(L, 3), filter);
781 std::unordered_map<content_t, u32> individual_count;
785 for (s16 x = minp.X; x <= maxp.X; x++)
786 for (s16 y = minp.Y; y <= maxp.Y; y++)
787 for (s16 z = minp.Z; z <= maxp.Z; z++) {
789 content_t c = env->getMap().getNodeNoEx(p).getContent();
790 if (filter.count(c) != 0) {
792 lua_rawseti(L, -2, ++i);
793 individual_count[c]++;
797 for (std::set<content_t>::const_iterator it = filter.begin();
798 it != filter.end(); ++it) {
799 lua_pushnumber(L, individual_count[*it]);
800 lua_setfield(L, -2, ndef->get(*it).name.c_str());
805 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
806 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
807 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
809 /* Note: A similar but generalized (and therefore slower) version of this
810 * function could be created -- e.g. find_nodes_in_area_under -- which
811 * would accept a node name (or ID?) or list of names that the "above node"
818 INodeDefManager *ndef = getServer(L)->ndef();
819 v3s16 minp = read_v3s16(L, 1);
820 v3s16 maxp = read_v3s16(L, 2);
821 sortBoxVerticies(minp, maxp);
823 v3s16 cube = maxp - minp + 1;
825 /* Limit for too large areas, assume default values
826 * and give tolerances of 1 node on each side
827 * (chunksize * MAP_BLOCKSIZE + 2)^3 = 551368
829 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 551368) {
830 luaL_error(L, "find_nodes_in_area_under_air(): area volume"
831 " exceeds allowed value of 551368");
835 std::set<content_t> filter;
837 if (lua_istable(L, 3)) {
839 while (lua_next(L, 3) != 0) {
840 // key at index -2 and value at index -1
841 luaL_checktype(L, -1, LUA_TSTRING);
842 ndef->getIds(lua_tostring(L, -1), filter);
843 // removes value, keeps key for next iteration
846 } else if (lua_isstring(L, 3)) {
847 ndef->getIds(lua_tostring(L, 3), filter);
852 for (s16 x = minp.X; x <= maxp.X; x++)
853 for (s16 z = minp.Z; z <= maxp.Z; z++) {
856 content_t c = env->getMap().getNodeNoEx(p).getContent();
857 for (; y <= maxp.Y; y++) {
858 v3s16 psurf(x, y + 1, z);
859 content_t csurf = env->getMap().getNodeNoEx(psurf).getContent();
860 if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
861 filter.count(c) != 0) {
862 push_v3s16(L, v3s16(x, y, z));
863 lua_rawseti(L, -2, ++i);
871 // get_perlin(seeddiff, octaves, persistence, scale)
872 // returns world-specific PerlinNoise
873 int ModApiEnvMod::l_get_perlin(lua_State *L)
875 GET_ENV_PTR_NO_MAP_LOCK;
879 if (lua_istable(L, 1)) {
880 read_noiseparams(L, 1, ¶ms);
882 params.seed = luaL_checkint(L, 1);
883 params.octaves = luaL_checkint(L, 2);
884 params.persist = luaL_checknumber(L, 3);
885 params.spread = v3f(1, 1, 1) * luaL_checknumber(L, 4);
888 params.seed += (int)env->getServerMap().getSeed();
890 LuaPerlinNoise *n = new LuaPerlinNoise(¶ms);
891 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
892 luaL_getmetatable(L, "PerlinNoise");
893 lua_setmetatable(L, -2);
897 // get_perlin_map(noiseparams, size)
898 // returns world-specific PerlinNoiseMap
899 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
901 GET_ENV_PTR_NO_MAP_LOCK;
904 if (!read_noiseparams(L, 1, &np))
906 v3s16 size = read_v3s16(L, 2);
908 s32 seed = (s32)(env->getServerMap().getSeed());
909 LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
910 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
911 luaL_getmetatable(L, "PerlinNoiseMap");
912 lua_setmetatable(L, -2);
917 // returns voxel manipulator
918 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
922 Map *map = &(env->getMap());
923 LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
924 new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
925 new LuaVoxelManip(map);
927 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
928 luaL_getmetatable(L, "VoxelManip");
929 lua_setmetatable(L, -2);
933 // clear_objects([options])
934 // clear all objects in the environment
935 // where options = {mode = "full" or "quick"}
936 int ModApiEnvMod::l_clear_objects(lua_State *L)
940 ClearObjectsMode mode = CLEAR_OBJECTS_MODE_FULL;
941 if (lua_istable(L, 1)) {
942 mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
943 ModApiEnvMod::es_ClearObjectsMode, mode);
946 env->clearObjects(mode);
950 // line_of_sight(pos1, pos2, stepsize) -> true/false, pos
951 int ModApiEnvMod::l_line_of_sight(lua_State *L)
953 float stepsize = 1.0;
957 // read position 1 from lua
958 v3f pos1 = checkFloatPos(L, 1);
959 // read position 2 from lua
960 v3f pos2 = checkFloatPos(L, 2);
961 //read step size from lua
962 if (lua_isnumber(L, 3)) {
963 stepsize = lua_tonumber(L, 3);
967 bool success = env->line_of_sight(pos1, pos2, stepsize, &p);
968 lua_pushboolean(L, success);
977 int ModApiEnvMod::l_fix_light(lua_State *L)
981 v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
982 v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
983 ServerMap &map = env->getServerMap();
984 std::map<v3s16, MapBlock *> modified_blocks;
987 for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
988 for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
989 for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
990 success = success & map.repairBlockLight(blockpos, &modified_blocks);
992 if (modified_blocks.size() > 0) {
994 event.type = MEET_OTHER;
995 for (std::map<v3s16, MapBlock *>::iterator it = modified_blocks.begin();
996 it != modified_blocks.end(); ++it)
997 event.modified_blocks.insert(it->first);
999 map.dispatchEvent(&event);
1001 lua_pushboolean(L, success);
1006 int ModApiEnvMod::l_raycast(lua_State *L)
1008 return LuaRaycast::create_object(L);
1011 // emerge_area(p1, p2, [callback, context])
1012 // emerge mapblocks in area p1..p2, calls callback with context upon completion
1013 int ModApiEnvMod::l_emerge_area(lua_State *L)
1017 EmergeCompletionCallback callback = NULL;
1018 ScriptCallbackState *state = NULL;
1020 EmergeManager *emerge = getServer(L)->getEmergeManager();
1022 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1023 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1024 sortBoxVerticies(bpmin, bpmax);
1026 size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
1027 assert(num_blocks != 0);
1029 if (lua_isfunction(L, 3)) {
1030 callback = LuaEmergeAreaCallback;
1032 lua_pushvalue(L, 3);
1033 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1035 lua_pushvalue(L, 4);
1036 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1038 state = new ScriptCallbackState;
1039 state->script = getServer(L)->getScriptIface();
1040 state->callback_ref = callback_ref;
1041 state->args_ref = args_ref;
1042 state->refcount = num_blocks;
1043 state->origin = getScriptApiBase(L)->getOrigin();
1046 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1047 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1048 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1049 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
1050 BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
1056 // delete_area(p1, p2)
1057 // delete mapblocks in area p1..p2
1058 int ModApiEnvMod::l_delete_area(lua_State *L)
1062 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1063 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1064 sortBoxVerticies(bpmin, bpmax);
1066 ServerMap &map = env->getServerMap();
1069 event.type = MEET_OTHER;
1071 bool success = true;
1072 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1073 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1074 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1076 if (map.deleteBlock(bp)) {
1077 env->setStaticForActiveObjectsInBlock(bp, false);
1078 event.modified_blocks.insert(bp);
1084 map.dispatchEvent(&event);
1085 lua_pushboolean(L, success);
1089 // find_path(pos1, pos2, searchdistance,
1090 // max_jump, max_drop, algorithm) -> table containing path
1091 int ModApiEnvMod::l_find_path(lua_State *L)
1095 v3s16 pos1 = read_v3s16(L, 1);
1096 v3s16 pos2 = read_v3s16(L, 2);
1097 unsigned int searchdistance = luaL_checkint(L, 3);
1098 unsigned int max_jump = luaL_checkint(L, 4);
1099 unsigned int max_drop = luaL_checkint(L, 5);
1100 PathAlgorithm algo = PA_PLAIN_NP;
1101 if (!lua_isnil(L, 6)) {
1102 std::string algorithm = luaL_checkstring(L,6);
1104 if (algorithm == "A*")
1107 if (algorithm == "Dijkstra")
1111 std::vector<v3s16> path = get_path(env, pos1, pos2,
1112 searchdistance, max_jump, max_drop, algo);
1114 if (path.size() > 0)
1117 int top = lua_gettop(L);
1118 unsigned int index = 1;
1119 for (std::vector<v3s16>::iterator i = path.begin(); i != path.end(); ++i) {
1120 lua_pushnumber(L,index);
1122 lua_settable(L, top);
1131 // spawn_tree(pos, treedef)
1132 int ModApiEnvMod::l_spawn_tree(lua_State *L)
1136 v3s16 p0 = read_v3s16(L, 1);
1138 treegen::TreeDef tree_def;
1139 std::string trunk,leaves,fruit;
1140 INodeDefManager *ndef = env->getGameDef()->ndef();
1142 if(lua_istable(L, 2))
1144 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
1145 getstringfield(L, 2, "rules_a", tree_def.rules_a);
1146 getstringfield(L, 2, "rules_b", tree_def.rules_b);
1147 getstringfield(L, 2, "rules_c", tree_def.rules_c);
1148 getstringfield(L, 2, "rules_d", tree_def.rules_d);
1149 getstringfield(L, 2, "trunk", trunk);
1150 tree_def.trunknode=ndef->getId(trunk);
1151 getstringfield(L, 2, "leaves", leaves);
1152 tree_def.leavesnode=ndef->getId(leaves);
1153 tree_def.leaves2_chance=0;
1154 getstringfield(L, 2, "leaves2", leaves);
1157 tree_def.leaves2node=ndef->getId(leaves);
1158 getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
1160 getintfield(L, 2, "angle", tree_def.angle);
1161 getintfield(L, 2, "iterations", tree_def.iterations);
1162 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1163 tree_def.iterations_random_level = 0;
1164 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1165 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1166 tree_def.fruit_chance=0;
1167 getstringfield(L, 2, "fruit", fruit);
1170 tree_def.fruitnode=ndef->getId(fruit);
1171 getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
1173 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1179 if ((e = treegen::spawn_ltree (env, p0, ndef, tree_def)) != treegen::SUCCESS) {
1180 if (e == treegen::UNBALANCED_BRACKETS) {
1181 luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1183 luaL_error(L, "spawn_tree(): unknown error");
1190 // transforming_liquid_add(pos)
1191 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1195 v3s16 p0 = read_v3s16(L, 1);
1196 env->getMap().transforming_liquid_add(p0);
1200 // forceload_block(blockpos)
1201 // blockpos = {x=num, y=num, z=num}
1202 int ModApiEnvMod::l_forceload_block(lua_State *L)
1206 v3s16 blockpos = read_v3s16(L, 1);
1207 env->getForceloadedBlocks()->insert(blockpos);
1211 // forceload_free_block(blockpos)
1212 // blockpos = {x=num, y=num, z=num}
1213 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1217 v3s16 blockpos = read_v3s16(L, 1);
1218 env->getForceloadedBlocks()->erase(blockpos);
1222 void ModApiEnvMod::Initialize(lua_State *L, int top)
1228 API_FCT(remove_node);
1230 API_FCT(get_node_or_nil);
1231 API_FCT(get_node_light);
1232 API_FCT(place_node);
1234 API_FCT(punch_node);
1235 API_FCT(get_node_max_level);
1236 API_FCT(get_node_level);
1237 API_FCT(set_node_level);
1238 API_FCT(add_node_level);
1239 API_FCT(add_entity);
1240 API_FCT(find_nodes_with_meta);
1242 API_FCT(get_node_timer);
1243 API_FCT(get_player_by_name);
1244 API_FCT(get_objects_inside_radius);
1245 API_FCT(set_timeofday);
1246 API_FCT(get_timeofday);
1247 API_FCT(get_gametime);
1248 API_FCT(get_day_count);
1249 API_FCT(find_node_near);
1250 API_FCT(find_nodes_in_area);
1251 API_FCT(find_nodes_in_area_under_air);
1253 API_FCT(emerge_area);
1254 API_FCT(delete_area);
1255 API_FCT(get_perlin);
1256 API_FCT(get_perlin_map);
1257 API_FCT(get_voxel_manip);
1258 API_FCT(clear_objects);
1259 API_FCT(spawn_tree);
1261 API_FCT(line_of_sight);
1263 API_FCT(transforming_liquid_add);
1264 API_FCT(forceload_block);
1265 API_FCT(forceload_free_block);
1268 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1270 API_FCT(get_timeofday);
1271 API_FCT(get_day_count);
1272 API_FCT(get_node_max_level);
1273 API_FCT(get_node_level);
1274 API_FCT(find_node_near);