]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/lua_api/l_env.cpp
Merge branch 'master' into master
[dragonfireclient.git] / src / script / lua_api / l_env.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include <algorithm>
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"
31 #include "mapblock.h"
32 #include "server.h"
33 #include "nodedef.h"
34 #include "daynightratio.h"
35 #include "util/pointedthing.h"
36 #include "mapgen/treegen.h"
37 #include "emerge.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"
45 #ifndef SERVER
46 #include "client/client.h"
47 #endif
48
49 struct EnumString ModApiEnvMod::es_ClearObjectsMode[] = {
50                 {CLEAR_OBJECTS_MODE_FULL, "full"},
51                 {CLEAR_OBJECTS_MODE_QUICK, "quick"},
52                 {0, NULL},
53 };
54
55 ///////////////////////////////////////////////////////////////////////////////
56
57 void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n, u32 active_object_count,
58                 u32 active_object_count_wider)
59 {
60         ServerScripting *scriptIface = env->getScriptIface();
61         scriptIface->realityCheck();
62
63         lua_State *L = scriptIface->getStack();
64         sanity_check(lua_checkstack(L, 20));
65         StackUnroller stack_unroller(L);
66
67         int error_handler = PUSH_ERROR_HANDLER(L);
68
69         // Get registered_abms
70         lua_getglobal(L, "core");
71         lua_getfield(L, -1, "registered_abms");
72         luaL_checktype(L, -1, LUA_TTABLE);
73         lua_remove(L, -2); // Remove core
74
75         // Get registered_abms[m_id]
76         lua_pushinteger(L, m_id);
77         lua_gettable(L, -2);
78         if (lua_isnil(L, -1))
79                 FATAL_ERROR("");
80         lua_remove(L, -2); // Remove registered_abms
81
82         scriptIface->setOriginFromTable(-1);
83
84         // Call action
85         luaL_checktype(L, -1, LUA_TTABLE);
86         lua_getfield(L, -1, "action");
87         luaL_checktype(L, -1, LUA_TFUNCTION);
88         lua_remove(L, -2); // Remove registered_abms[m_id]
89         push_v3s16(L, p);
90         pushnode(L, n, env->getGameDef()->ndef());
91         lua_pushnumber(L, active_object_count);
92         lua_pushnumber(L, active_object_count_wider);
93
94         int result = lua_pcall(L, 4, 0, error_handler);
95         if (result)
96                 scriptIface->scriptError(result, "LuaABM::trigger");
97
98         lua_pop(L, 1); // Pop error handler
99 }
100
101 void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n)
102 {
103         ServerScripting *scriptIface = env->getScriptIface();
104         scriptIface->realityCheck();
105
106         lua_State *L = scriptIface->getStack();
107         sanity_check(lua_checkstack(L, 20));
108         StackUnroller stack_unroller(L);
109
110         int error_handler = PUSH_ERROR_HANDLER(L);
111
112         // Get registered_lbms
113         lua_getglobal(L, "core");
114         lua_getfield(L, -1, "registered_lbms");
115         luaL_checktype(L, -1, LUA_TTABLE);
116         lua_remove(L, -2); // Remove core
117
118         // Get registered_lbms[m_id]
119         lua_pushinteger(L, m_id);
120         lua_gettable(L, -2);
121         FATAL_ERROR_IF(lua_isnil(L, -1),
122                         "Entry with given id not found in registered_lbms table");
123         lua_remove(L, -2); // Remove registered_lbms
124
125         scriptIface->setOriginFromTable(-1);
126
127         // Call action
128         luaL_checktype(L, -1, LUA_TTABLE);
129         lua_getfield(L, -1, "action");
130         luaL_checktype(L, -1, LUA_TFUNCTION);
131         lua_remove(L, -2); // Remove registered_lbms[m_id]
132         push_v3s16(L, p);
133         pushnode(L, n, env->getGameDef()->ndef());
134
135         int result = lua_pcall(L, 2, 0, error_handler);
136         if (result)
137                 scriptIface->scriptError(result, "LuaLBM::trigger");
138
139         lua_pop(L, 1); // Pop error handler
140 }
141
142 int LuaRaycast::l_next(lua_State *L)
143 {
144         GET_PLAIN_ENV_PTR;
145
146         bool csm = false;
147 #ifndef SERVER
148         csm = getClient(L) != nullptr;
149 #endif
150
151         LuaRaycast *o = checkobject(L, 1);
152         PointedThing pointed;
153         env->continueRaycast(&o->state, &pointed);
154         if (pointed.type == POINTEDTHING_NOTHING)
155                 lua_pushnil(L);
156         else
157                 push_pointed_thing(L, pointed, csm, true);
158
159         return 1;
160 }
161
162 int LuaRaycast::create_object(lua_State *L)
163 {
164         NO_MAP_LOCK_REQUIRED;
165
166         bool objects = true;
167         bool liquids = false;
168
169         v3f pos1 = checkFloatPos(L, 1);
170         v3f pos2 = checkFloatPos(L, 2);
171         if (lua_isboolean(L, 3)) {
172                 objects = readParam<bool>(L, 3);
173         }
174         if (lua_isboolean(L, 4)) {
175                 liquids = readParam<bool>(L, 4);
176         }
177
178         LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2), objects, liquids);
179
180         *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
181         luaL_getmetatable(L, className);
182         lua_setmetatable(L, -2);
183         return 1;
184 }
185
186 LuaRaycast *LuaRaycast::checkobject(lua_State *L, int narg)
187 {
188         NO_MAP_LOCK_REQUIRED;
189
190         luaL_checktype(L, narg, LUA_TUSERDATA);
191         void *ud = luaL_checkudata(L, narg, className);
192         if (!ud)
193                 luaL_typerror(L, narg, className);
194         return *(LuaRaycast **)ud;
195 }
196
197 int LuaRaycast::gc_object(lua_State *L)
198 {
199         LuaRaycast *o = *(LuaRaycast **)(lua_touserdata(L, 1));
200         delete o;
201         return 0;
202 }
203
204 void LuaRaycast::Register(lua_State *L)
205 {
206         lua_newtable(L);
207         int methodtable = lua_gettop(L);
208         luaL_newmetatable(L, className);
209         int metatable = lua_gettop(L);
210
211         lua_pushliteral(L, "__metatable");
212         lua_pushvalue(L, methodtable);
213         lua_settable(L, metatable);
214
215         lua_pushliteral(L, "__index");
216         lua_pushvalue(L, methodtable);
217         lua_settable(L, metatable);
218
219         lua_pushliteral(L, "__gc");
220         lua_pushcfunction(L, gc_object);
221         lua_settable(L, metatable);
222
223         lua_pushliteral(L, "__call");
224         lua_pushcfunction(L, l_next);
225         lua_settable(L, metatable);
226
227         lua_pop(L, 1);
228
229         luaL_openlib(L, 0, methods, 0);
230         lua_pop(L, 1);
231
232         lua_register(L, className, create_object);
233 }
234
235 const char LuaRaycast::className[] = "Raycast";
236 const luaL_Reg LuaRaycast::methods[] = {luamethod(LuaRaycast, next), {0, 0}};
237
238 void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param)
239 {
240         ScriptCallbackState *state = (ScriptCallbackState *)param;
241         assert(state != NULL);
242         assert(state->script != NULL);
243         assert(state->refcount > 0);
244
245         // state must be protected by envlock
246         Server *server = state->script->getServer();
247         MutexAutoLock envlock(server->m_env_mutex);
248
249         state->refcount--;
250
251         state->script->on_emerge_area_completion(blockpos, action, state);
252
253         if (state->refcount == 0)
254                 delete state;
255 }
256
257 // Exported functions
258
259 // set_node(pos, node)
260 // pos = {x=num, y=num, z=num}
261 int ModApiEnvMod::l_set_node(lua_State *L)
262 {
263         GET_ENV_PTR;
264
265         const NodeDefManager *ndef = env->getGameDef()->ndef();
266         // parameters
267         v3s16 pos = read_v3s16(L, 1);
268         MapNode n = readnode(L, 2, ndef);
269         // Do it
270         bool succeeded = env->setNode(pos, n);
271         lua_pushboolean(L, succeeded);
272         return 1;
273 }
274
275 // bulk_set_node([pos1, pos2, ...], node)
276 // pos = {x=num, y=num, z=num}
277 int ModApiEnvMod::l_bulk_set_node(lua_State *L)
278 {
279         GET_ENV_PTR;
280
281         const NodeDefManager *ndef = env->getGameDef()->ndef();
282         // parameters
283         if (!lua_istable(L, 1)) {
284                 return 0;
285         }
286
287         s32 len = lua_objlen(L, 1);
288         if (len == 0) {
289                 lua_pushboolean(L, true);
290                 return 1;
291         }
292
293         MapNode n = readnode(L, 2, ndef);
294
295         // Do it
296         bool succeeded = true;
297         for (s32 i = 1; i <= len; i++) {
298                 lua_rawgeti(L, 1, i);
299                 if (!env->setNode(read_v3s16(L, -1), n))
300                         succeeded = false;
301                 lua_pop(L, 1);
302         }
303
304         lua_pushboolean(L, succeeded);
305         return 1;
306 }
307
308 int ModApiEnvMod::l_add_node(lua_State *L)
309 {
310         return l_set_node(L);
311 }
312
313 // remove_node(pos)
314 // pos = {x=num, y=num, z=num}
315 int ModApiEnvMod::l_remove_node(lua_State *L)
316 {
317         GET_ENV_PTR;
318
319         // parameters
320         v3s16 pos = read_v3s16(L, 1);
321         // Do it
322         bool succeeded = env->removeNode(pos);
323         lua_pushboolean(L, succeeded);
324         return 1;
325 }
326
327 // swap_node(pos, node)
328 // pos = {x=num, y=num, z=num}
329 int ModApiEnvMod::l_swap_node(lua_State *L)
330 {
331         GET_ENV_PTR;
332
333         const NodeDefManager *ndef = env->getGameDef()->ndef();
334         // parameters
335         v3s16 pos = read_v3s16(L, 1);
336         MapNode n = readnode(L, 2, ndef);
337         // Do it
338         bool succeeded = env->swapNode(pos, n);
339         lua_pushboolean(L, succeeded);
340         return 1;
341 }
342
343 // get_node(pos)
344 // pos = {x=num, y=num, z=num}
345 int ModApiEnvMod::l_get_node(lua_State *L)
346 {
347         GET_ENV_PTR;
348
349         // pos
350         v3s16 pos = read_v3s16(L, 1);
351         // Do it
352         MapNode n = env->getMap().getNode(pos);
353         // Return node
354         pushnode(L, n, env->getGameDef()->ndef());
355         return 1;
356 }
357
358 // get_node_or_nil(pos)
359 // pos = {x=num, y=num, z=num}
360 int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
361 {
362         GET_ENV_PTR;
363
364         // pos
365         v3s16 pos = read_v3s16(L, 1);
366         // Do it
367         bool pos_ok;
368         MapNode n = env->getMap().getNode(pos, &pos_ok);
369         if (pos_ok) {
370                 // Return node
371                 pushnode(L, n, env->getGameDef()->ndef());
372         } else {
373                 lua_pushnil(L);
374         }
375         return 1;
376 }
377
378 // get_node_light(pos, timeofday)
379 // pos = {x=num, y=num, z=num}
380 // timeofday: nil = current time, 0 = night, 0.5 = day
381 int ModApiEnvMod::l_get_node_light(lua_State *L)
382 {
383         GET_PLAIN_ENV_PTR;
384
385         // Do it
386         v3s16 pos = read_v3s16(L, 1);
387         u32 time_of_day = env->getTimeOfDay();
388         if (lua_isnumber(L, 2))
389                 time_of_day = 24000.0 * lua_tonumber(L, 2);
390         time_of_day %= 24000;
391         u32 dnr = time_to_daynight_ratio(time_of_day, true);
392
393         bool is_position_ok;
394         MapNode n = env->getMap().getNode(pos, &is_position_ok);
395         if (is_position_ok) {
396                 const NodeDefManager *ndef = env->getGameDef()->ndef();
397                 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
398         } else {
399                 lua_pushnil(L);
400         }
401         return 1;
402 }
403
404 // place_node(pos, node)
405 // pos = {x=num, y=num, z=num}
406 int ModApiEnvMod::l_place_node(lua_State *L)
407 {
408         GET_ENV_PTR;
409
410         ScriptApiItem *scriptIfaceItem = getScriptApi<ScriptApiItem>(L);
411         Server *server = getServer(L);
412         const NodeDefManager *ndef = server->ndef();
413         IItemDefManager *idef = server->idef();
414
415         v3s16 pos = read_v3s16(L, 1);
416         MapNode n = readnode(L, 2, ndef);
417
418         // Don't attempt to load non-loaded area as of now
419         MapNode n_old = env->getMap().getNode(pos);
420         if (n_old.getContent() == CONTENT_IGNORE) {
421                 lua_pushboolean(L, false);
422                 return 1;
423         }
424         // Create item to place
425         ItemStack item(ndef->get(n).name, 1, 0, idef);
426         // Make pointed position
427         PointedThing pointed;
428         pointed.type = POINTEDTHING_NODE;
429         pointed.node_abovesurface = pos;
430         pointed.node_undersurface = pos + v3s16(0, -1, 0);
431         // Place it with a NULL placer (appears in Lua as nil)
432         bool success = scriptIfaceItem->item_OnPlace(item, nullptr, pointed);
433         lua_pushboolean(L, success);
434         return 1;
435 }
436
437 // dig_node(pos)
438 // pos = {x=num, y=num, z=num}
439 int ModApiEnvMod::l_dig_node(lua_State *L)
440 {
441         GET_ENV_PTR;
442
443         ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
444
445         v3s16 pos = read_v3s16(L, 1);
446
447         // Don't attempt to load non-loaded area as of now
448         MapNode n = env->getMap().getNode(pos);
449         if (n.getContent() == CONTENT_IGNORE) {
450                 lua_pushboolean(L, false);
451                 return 1;
452         }
453         // Dig it out with a NULL digger (appears in Lua as a
454         // non-functional ObjectRef)
455         bool success = scriptIfaceNode->node_on_dig(pos, n, NULL);
456         lua_pushboolean(L, success);
457         return 1;
458 }
459
460 // punch_node(pos)
461 // pos = {x=num, y=num, z=num}
462 int ModApiEnvMod::l_punch_node(lua_State *L)
463 {
464         GET_ENV_PTR;
465
466         ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
467
468         v3s16 pos = read_v3s16(L, 1);
469
470         // Don't attempt to load non-loaded area as of now
471         MapNode n = env->getMap().getNode(pos);
472         if (n.getContent() == CONTENT_IGNORE) {
473                 lua_pushboolean(L, false);
474                 return 1;
475         }
476         // Punch it with a NULL puncher (appears in Lua as a non-functional
477         // ObjectRef)
478         bool success = scriptIfaceNode->node_on_punch(pos, n, NULL, PointedThing());
479         lua_pushboolean(L, success);
480         return 1;
481 }
482
483 // get_node_max_level(pos)
484 // pos = {x=num, y=num, z=num}
485 int ModApiEnvMod::l_get_node_max_level(lua_State *L)
486 {
487         GET_PLAIN_ENV_PTR;
488
489         v3s16 pos = read_v3s16(L, 1);
490         MapNode n = env->getMap().getNode(pos);
491         lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef()));
492         return 1;
493 }
494
495 // get_node_level(pos)
496 // pos = {x=num, y=num, z=num}
497 int ModApiEnvMod::l_get_node_level(lua_State *L)
498 {
499         GET_PLAIN_ENV_PTR;
500
501         v3s16 pos = read_v3s16(L, 1);
502         MapNode n = env->getMap().getNode(pos);
503         lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef()));
504         return 1;
505 }
506
507 // set_node_level(pos, level)
508 // pos = {x=num, y=num, z=num}
509 // level: 0..63
510 int ModApiEnvMod::l_set_node_level(lua_State *L)
511 {
512         GET_ENV_PTR;
513
514         v3s16 pos = read_v3s16(L, 1);
515         u8 level = 1;
516         if (lua_isnumber(L, 2))
517                 level = lua_tonumber(L, 2);
518         MapNode n = env->getMap().getNode(pos);
519         lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level));
520         env->setNode(pos, n);
521         return 1;
522 }
523
524 // add_node_level(pos, level)
525 // pos = {x=num, y=num, z=num}
526 // level: -127..127
527 int ModApiEnvMod::l_add_node_level(lua_State *L)
528 {
529         GET_ENV_PTR;
530
531         v3s16 pos = read_v3s16(L, 1);
532         s16 level = 1;
533         if (lua_isnumber(L, 2))
534                 level = lua_tonumber(L, 2);
535         MapNode n = env->getMap().getNode(pos);
536         lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level));
537         env->setNode(pos, n);
538         return 1;
539 }
540
541 // find_nodes_with_meta(pos1, pos2)
542 int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L)
543 {
544         GET_PLAIN_ENV_PTR;
545
546         std::vector<v3s16> positions = env->getMap().findNodesWithMetadata(
547                         check_v3s16(L, 1), check_v3s16(L, 2));
548
549         lua_createtable(L, positions.size(), 0);
550         for (size_t i = 0; i != positions.size(); i++) {
551                 push_v3s16(L, positions[i]);
552                 lua_rawseti(L, -2, i + 1);
553         }
554
555         return 1;
556 }
557
558 // get_meta(pos)
559 int ModApiEnvMod::l_get_meta(lua_State *L)
560 {
561         GET_ENV_PTR;
562
563         // Do it
564         v3s16 p = read_v3s16(L, 1);
565         NodeMetaRef::create(L, p, env);
566         return 1;
567 }
568
569 // get_node_timer(pos)
570 int ModApiEnvMod::l_get_node_timer(lua_State *L)
571 {
572         GET_ENV_PTR;
573
574         // Do it
575         v3s16 p = read_v3s16(L, 1);
576         NodeTimerRef::create(L, p, &env->getServerMap());
577         return 1;
578 }
579
580 // add_entity(pos, entityname, [staticdata]) -> ObjectRef or nil
581 // pos = {x=num, y=num, z=num}
582 int ModApiEnvMod::l_add_entity(lua_State *L)
583 {
584         GET_ENV_PTR;
585
586         v3f pos = checkFloatPos(L, 1);
587         const char *name = luaL_checkstring(L, 2);
588         const char *staticdata = luaL_optstring(L, 3, "");
589
590         ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata);
591         int objectid = env->addActiveObject(obj);
592         // If failed to add, return nothing (reads as nil)
593         if (objectid == 0)
594                 return 0;
595
596         // If already deleted (can happen in on_activate), return nil
597         if (obj->isGone())
598                 return 0;
599         getScriptApiBase(L)->objectrefGetOrCreate(L, obj);
600         return 1;
601 }
602
603 // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
604 // pos = {x=num, y=num, z=num}
605 int ModApiEnvMod::l_add_item(lua_State *L)
606 {
607         GET_ENV_PTR;
608
609         // pos
610         // v3f pos = checkFloatPos(L, 1);
611         // item
612         ItemStack item = read_item(L, 2, getServer(L)->idef());
613         if (item.empty() || !item.isKnown(getServer(L)->idef()))
614                 return 0;
615
616         int error_handler = PUSH_ERROR_HANDLER(L);
617
618         // Use spawn_item to spawn a __builtin:item
619         lua_getglobal(L, "core");
620         lua_getfield(L, -1, "spawn_item");
621         lua_remove(L, -2); // Remove core
622         if (lua_isnil(L, -1))
623                 return 0;
624         lua_pushvalue(L, 1);
625         lua_pushstring(L, item.getItemString().c_str());
626
627         PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler));
628
629         lua_remove(L, error_handler);
630         return 1;
631 }
632
633 // get_connected_players()
634 int ModApiEnvMod::l_get_connected_players(lua_State *L)
635 {
636         ServerEnvironment *env = (ServerEnvironment *)getEnv(L);
637         if (!env) {
638                 log_deprecated(L, "Calling get_connected_players() at mod load time"
639                                   " is deprecated");
640                 lua_createtable(L, 0, 0);
641                 return 1;
642         }
643
644         lua_createtable(L, env->getPlayerCount(), 0);
645         u32 i = 0;
646         for (RemotePlayer *player : env->getPlayers()) {
647                 if (player->getPeerId() == PEER_ID_INEXISTENT)
648                         continue;
649                 PlayerSAO *sao = player->getPlayerSAO();
650                 if (sao && !sao->isGone()) {
651                         getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
652                         lua_rawseti(L, -2, ++i);
653                 }
654         }
655         return 1;
656 }
657
658 // get_player_by_name(name)
659 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
660 {
661         GET_ENV_PTR;
662
663         // Do it
664         const char *name = luaL_checkstring(L, 1);
665         RemotePlayer *player = env->getPlayer(name);
666         if (!player || player->getPeerId() == PEER_ID_INEXISTENT)
667                 return 0;
668         PlayerSAO *sao = player->getPlayerSAO();
669         if (!sao || sao->isGone())
670                 return 0;
671         // Put player on stack
672         getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
673         return 1;
674 }
675
676 // get_objects_inside_radius(pos, radius)
677 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
678 {
679         GET_ENV_PTR;
680         ScriptApiBase *script = getScriptApiBase(L);
681
682         // Do it
683         v3f pos = checkFloatPos(L, 1);
684         float radius = readParam<float>(L, 2) * BS;
685         std::vector<ServerActiveObject *> objs;
686
687         auto include_obj_cb = [](ServerActiveObject *obj) { return !obj->isGone(); };
688         env->getObjectsInsideRadius(objs, pos, radius, include_obj_cb);
689
690         int i = 0;
691         lua_createtable(L, objs.size(), 0);
692         for (const auto obj : objs) {
693                 // Insert object reference into table
694                 script->objectrefGetOrCreate(L, obj);
695                 lua_rawseti(L, -2, ++i);
696         }
697         return 1;
698 }
699
700 // set_timeofday(val)
701 // val = 0...1
702 int ModApiEnvMod::l_set_timeofday(lua_State *L)
703 {
704         GET_ENV_PTR;
705
706         // Do it
707         float timeofday_f = readParam<float>(L, 1);
708         sanity_check(timeofday_f >= 0.0 && timeofday_f <= 1.0);
709         int timeofday_mh = (int)(timeofday_f * 24000.0);
710         // This should be set directly in the environment but currently
711         // such changes aren't immediately sent to the clients, so call
712         // the server instead.
713         // env->setTimeOfDay(timeofday_mh);
714         getServer(L)->setTimeOfDay(timeofday_mh);
715         return 0;
716 }
717
718 // get_timeofday() -> 0...1
719 int ModApiEnvMod::l_get_timeofday(lua_State *L)
720 {
721         GET_PLAIN_ENV_PTR;
722
723         // Do it
724         int timeofday_mh = env->getTimeOfDay();
725         float timeofday_f = (float)timeofday_mh / 24000.0f;
726         lua_pushnumber(L, timeofday_f);
727         return 1;
728 }
729
730 // get_day_count() -> int
731 int ModApiEnvMod::l_get_day_count(lua_State *L)
732 {
733         GET_PLAIN_ENV_PTR;
734
735         lua_pushnumber(L, env->getDayCount());
736         return 1;
737 }
738
739 // get_gametime()
740 int ModApiEnvMod::l_get_gametime(lua_State *L)
741 {
742         GET_ENV_PTR;
743
744         int game_time = env->getGameTime();
745         lua_pushnumber(L, game_time);
746         return 1;
747 }
748
749 void ModApiEnvMod::collectNodeIds(lua_State *L, int idx, const NodeDefManager *ndef,
750                 std::vector<content_t> &filter)
751 {
752         if (lua_istable(L, idx)) {
753                 lua_pushnil(L);
754                 while (lua_next(L, idx) != 0) {
755                         // key at index -2 and value at index -1
756                         luaL_checktype(L, -1, LUA_TSTRING);
757                         ndef->getIds(readParam<std::string>(L, -1), filter);
758                         // removes value, keeps key for next iteration
759                         lua_pop(L, 1);
760                 }
761         } else if (lua_isstring(L, idx)) {
762                 ndef->getIds(readParam<std::string>(L, 3), filter);
763         }
764 }
765
766 // find_node_near(pos, radius, nodenames, [search_center]) -> pos or nil
767 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
768 int ModApiEnvMod::l_find_node_near(lua_State *L)
769 {
770         GET_PLAIN_ENV_PTR;
771
772         const NodeDefManager *ndef = env->getGameDef()->ndef();
773         Map &map = env->getMap();
774
775         v3s16 pos = read_v3s16(L, 1);
776         int radius = luaL_checkinteger(L, 2);
777         std::vector<content_t> filter;
778         collectNodeIds(L, 3, ndef, filter);
779         int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
780
781 #ifndef SERVER
782         // Client API limitations
783         if (Client *client = getClient(L))
784                 radius = client->CSMClampRadius(pos, radius);
785 #endif
786
787         for (int d = start_radius; d <= radius; d++) {
788                 const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d);
789                 for (const v3s16 &i : list) {
790                         v3s16 p = pos + i;
791                         content_t c = map.getNode(p).getContent();
792                         if (CONTAINS(filter, c)) {
793                                 push_v3s16(L, p);
794                                 return 1;
795                         }
796                 }
797         }
798         return 0;
799 }
800
801 // find_nodes_near(pos, radius, nodenames, [search_center])
802 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
803 int ModApiEnvMod::l_find_nodes_near(lua_State *L)
804 {
805         GET_PLAIN_ENV_PTR;
806
807         const NodeDefManager *ndef = env->getGameDef()->ndef();
808         Map &map = env->getMap();
809
810         v3s16 pos = read_v3s16(L, 1);
811         int radius = luaL_checkinteger(L, 2);
812         std::vector<content_t> filter;
813         collectNodeIds(L, 3, ndef, filter);
814
815         int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
816
817 #ifndef SERVER
818         // Client API limitations
819         if (Client *client = getClient(L))
820                 radius = client->CSMClampRadius(pos, radius);
821 #endif
822
823         std::vector<u32> individual_count;
824         individual_count.resize(filter.size());
825
826         lua_newtable(L);
827         u32 i = 0;
828
829         for (int d = start_radius; d <= radius; d++) {
830                 const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d);
831                 for (const v3s16 &posi : list) {
832                         v3s16 p = pos + posi;
833                         content_t c = map.getNode(p).getContent();
834                         auto it = std::find(filter.begin(), filter.end(), c);
835                         if (it != filter.end()) {
836                                 push_v3s16(L, p);
837                                 lua_rawseti(L, -2, ++i);
838
839                                 u32 filt_index = it - filter.begin();
840                                 individual_count[filt_index]++;
841                         }
842                 }
843         }
844         lua_createtable(L, 0, filter.size());
845         for (u32 i = 0; i < filter.size(); i++) {
846                 lua_pushinteger(L, individual_count[i]);
847                 lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
848         }
849         return 2;
850 }
851
852 // find_nodes_near_under_air(pos, radius, nodenames, [search_center])
853 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
854 int ModApiEnvMod::l_find_nodes_near_under_air(lua_State *L)
855 {
856         GET_PLAIN_ENV_PTR;
857
858         const NodeDefManager *ndef = env->getGameDef()->ndef();
859         Map &map = env->getMap();
860
861         v3s16 pos = read_v3s16(L, 1);
862         int radius = luaL_checkinteger(L, 2);
863         std::vector<content_t> filter;
864         collectNodeIds(L, 3, ndef, filter);
865         int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
866
867 #ifndef SERVER
868         // Client API limitations
869         if (Client *client = getClient(L))
870                 radius = client->CSMClampRadius(pos, radius);
871 #endif
872
873         std::vector<u32> individual_count;
874         individual_count.resize(filter.size());
875
876         lua_newtable(L);
877         u32 i = 0;
878
879         for (int d = start_radius; d <= radius; d++) {
880                 const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d);
881                 for (const v3s16 &posi : list) {
882                         v3s16 p = pos + posi;
883                         content_t c = map.getNode(p).getContent();
884                         v3s16 psurf(p.X, p.Y + 1, p.Z);
885                         content_t csurf = map.getNode(psurf).getContent();
886                         if (c == CONTENT_AIR || csurf != CONTENT_AIR)
887                                 continue;
888                         auto it = std::find(filter.begin(), filter.end(), c);
889                         if (it != filter.end()) {
890                                 push_v3s16(L, p);
891                                 lua_rawseti(L, -2, ++i);
892
893                                 u32 filt_index = it - filter.begin();
894                                 individual_count[filt_index]++;
895                         }
896                 }
897         }
898         lua_createtable(L, 0, filter.size());
899         for (u32 i = 0; i < filter.size(); i++) {
900                 lua_pushinteger(L, individual_count[i]);
901                 lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
902         }
903         return 2;
904 }
905
906 // find_nodes_near_under_air_except(pos, radius, nodenames, [search_center])
907 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
908 int ModApiEnvMod::l_find_nodes_near_under_air_except(lua_State *L)
909 {
910         GET_PLAIN_ENV_PTR;
911
912         const NodeDefManager *ndef = env->getGameDef()->ndef();
913         Map &map = env->getMap();
914
915         v3s16 pos = read_v3s16(L, 1);
916         int radius = luaL_checkinteger(L, 2);
917         std::vector<content_t> filter;
918         collectNodeIds(L, 3, ndef, filter);
919         int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
920
921 #ifndef SERVER
922         // Client API limitations
923         if (Client *client = getClient(L))
924                 radius = client->CSMClampRadius(pos, radius);
925 #endif
926
927         std::vector<u32> individual_count;
928         individual_count.resize(filter.size());
929
930         lua_newtable(L);
931         u32 i = 0;
932
933         for (int d = start_radius; d <= radius; d++) {
934                 const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d);
935                 for (const v3s16 &posi : list) {
936                         v3s16 p = pos + posi;
937                         content_t c = map.getNode(p).getContent();
938                         v3s16 psurf(p.X, p.Y + 1, p.Z);
939                         content_t csurf = map.getNode(psurf).getContent();
940                         if (c == CONTENT_AIR || csurf != CONTENT_AIR)
941                                 continue;
942                         auto it = std::find(filter.begin(), filter.end(), c);
943                         if (it == filter.end()) {
944                                 push_v3s16(L, p);
945                                 lua_rawseti(L, -2, ++i);
946
947                                 u32 filt_index = it - filter.begin();
948                                 individual_count[filt_index]++;
949                         }
950                 }
951         }
952         lua_createtable(L, 0, filter.size());
953         for (u32 i = 0; i < filter.size(); i++) {
954                 lua_pushinteger(L, individual_count[i]);
955                 lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
956         }
957         return 2;
958 }
959
960 // find_nodes_in_area(minp, maxp, nodenames, [grouped])
961 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
962 {
963         GET_PLAIN_ENV_PTR;
964
965         v3s16 minp = read_v3s16(L, 1);
966         v3s16 maxp = read_v3s16(L, 2);
967         sortBoxVerticies(minp, maxp);
968
969         const NodeDefManager *ndef = env->getGameDef()->ndef();
970         Map &map = env->getMap();
971
972 #ifndef SERVER
973         if (Client *client = getClient(L)) {
974                 minp = client->CSMClampPos(minp);
975                 maxp = client->CSMClampPos(maxp);
976         }
977 #endif
978
979         v3s16 cube = maxp - minp + 1;
980         // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
981         if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) {
982                 luaL_error(L, "find_nodes_in_area(): area volume"
983                               " exceeds allowed value of 4096000");
984                 return 0;
985         }
986
987         std::vector<content_t> filter;
988         collectNodeIds(L, 3, ndef, filter);
989
990         bool grouped = lua_isboolean(L, 4) && readParam<bool>(L, 4);
991
992         if (grouped) {
993                 // create the table we will be returning
994                 lua_createtable(L, 0, filter.size());
995                 int base = lua_gettop(L);
996
997                 // create one table for each filter
998                 std::vector<u32> idx;
999                 idx.resize(filter.size());
1000                 for (u32 i = 0; i < filter.size(); i++)
1001                         lua_newtable(L);
1002
1003                 v3s16 p;
1004                 for (p.X = minp.X; p.X <= maxp.X; p.X++)
1005                         for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++)
1006                                 for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
1007                                         content_t c = map.getNode(p).getContent();
1008
1009                                         auto it = std::find(
1010                                                         filter.begin(), filter.end(), c);
1011                                         if (it != filter.end()) {
1012                                                 // Calculate index of the table and append
1013                                                 // the position
1014                                                 u32 filt_index = it - filter.begin();
1015                                                 push_v3s16(L, p);
1016                                                 lua_rawseti(L, base + 1 + filt_index,
1017                                                                 ++idx[filt_index]);
1018                                         }
1019                                 }
1020
1021                 // last filter table is at top of stack
1022                 u32 i = filter.size() - 1;
1023                 do {
1024                         if (idx[i] == 0) {
1025                                 // No such node found -> drop the empty table
1026                                 lua_pop(L, 1);
1027                         } else {
1028                                 // This node was found -> put table into the return table
1029                                 lua_setfield(L, base, ndef->get(filter[i]).name.c_str());
1030                         }
1031                 } while (i-- != 0);
1032
1033                 assert(lua_gettop(L) == base);
1034                 return 1;
1035         } else {
1036                 std::vector<u32> individual_count;
1037                 individual_count.resize(filter.size());
1038
1039                 lua_newtable(L);
1040                 u32 i = 0;
1041                 v3s16 p;
1042                 for (p.X = minp.X; p.X <= maxp.X; p.X++)
1043                         for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++)
1044                                 for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
1045                                         content_t c = env->getMap().getNode(p)
1046                                                                       .getContent();
1047
1048                                         auto it = std::find(
1049                                                         filter.begin(), filter.end(), c);
1050                                         if (it != filter.end()) {
1051                                                 push_v3s16(L, p);
1052                                                 lua_rawseti(L, -2, ++i);
1053
1054                                                 u32 filt_index = it - filter.begin();
1055                                                 individual_count[filt_index]++;
1056                                         }
1057                                 }
1058
1059                 lua_createtable(L, 0, filter.size());
1060                 for (u32 i = 0; i < filter.size(); i++) {
1061                         lua_pushinteger(L, individual_count[i]);
1062                         lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
1063                 }
1064                 return 2;
1065         }
1066 }
1067
1068 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
1069 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
1070 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
1071 {
1072         /* Note: A similar but generalized (and therefore slower) version of this
1073          * function could be created -- e.g. find_nodes_in_area_under -- which
1074          * would accept a node name (or ID?) or list of names that the "above node"
1075          * should be.
1076          * TODO
1077          */
1078
1079         GET_PLAIN_ENV_PTR;
1080
1081         v3s16 minp = read_v3s16(L, 1);
1082         v3s16 maxp = read_v3s16(L, 2);
1083         sortBoxVerticies(minp, maxp);
1084
1085         const NodeDefManager *ndef = env->getGameDef()->ndef();
1086         Map &map = env->getMap();
1087
1088 #ifndef SERVER
1089         if (Client *client = getClient(L)) {
1090                 minp = client->CSMClampPos(minp);
1091                 maxp = client->CSMClampPos(maxp);
1092         }
1093 #endif
1094
1095         v3s16 cube = maxp - minp + 1;
1096         // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
1097         if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) {
1098                 luaL_error(L, "find_nodes_in_area_under_air(): area volume"
1099                               " exceeds allowed value of 4096000");
1100                 return 0;
1101         }
1102
1103         std::vector<content_t> filter;
1104         collectNodeIds(L, 3, ndef, filter);
1105
1106         lua_newtable(L);
1107         u32 i = 0;
1108         v3s16 p;
1109         for (p.X = minp.X; p.X <= maxp.X; p.X++)
1110                 for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
1111                         p.Y = minp.Y;
1112                         content_t c = map.getNode(p).getContent();
1113                         for (; p.Y <= maxp.Y; p.Y++) {
1114                                 v3s16 psurf(p.X, p.Y + 1, p.Z);
1115                                 content_t csurf = map.getNode(psurf).getContent();
1116                                 if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
1117                                                 CONTAINS(filter, c)) {
1118                                         push_v3s16(L, p);
1119                                         lua_rawseti(L, -2, ++i);
1120                                 }
1121                                 c = csurf;
1122                         }
1123                 }
1124         return 1;
1125 }
1126
1127 // get_perlin(seeddiff, octaves, persistence, scale)
1128 // returns world-specific PerlinNoise
1129 int ModApiEnvMod::l_get_perlin(lua_State *L)
1130 {
1131         GET_ENV_PTR_NO_MAP_LOCK;
1132
1133         NoiseParams params;
1134
1135         if (lua_istable(L, 1)) {
1136                 read_noiseparams(L, 1, &params);
1137         } else {
1138                 params.seed = luaL_checkint(L, 1);
1139                 params.octaves = luaL_checkint(L, 2);
1140                 params.persist = readParam<float>(L, 3);
1141                 params.spread = v3f(1, 1, 1) * readParam<float>(L, 4);
1142         }
1143
1144         params.seed += (int)env->getServerMap().getSeed();
1145
1146         LuaPerlinNoise *n = new LuaPerlinNoise(&params);
1147         *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
1148         luaL_getmetatable(L, "PerlinNoise");
1149         lua_setmetatable(L, -2);
1150         return 1;
1151 }
1152
1153 // get_perlin_map(noiseparams, size)
1154 // returns world-specific PerlinNoiseMap
1155 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
1156 {
1157         GET_ENV_PTR_NO_MAP_LOCK;
1158
1159         NoiseParams np;
1160         if (!read_noiseparams(L, 1, &np))
1161                 return 0;
1162         v3s16 size = read_v3s16(L, 2);
1163
1164         s32 seed = (s32)(env->getServerMap().getSeed());
1165         LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
1166         *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
1167         luaL_getmetatable(L, "PerlinNoiseMap");
1168         lua_setmetatable(L, -2);
1169         return 1;
1170 }
1171
1172 // get_voxel_manip()
1173 // returns voxel manipulator
1174 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
1175 {
1176         GET_ENV_PTR;
1177
1178         Map *map = &(env->getMap());
1179         LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2))
1180                                            ? new LuaVoxelManip(map, read_v3s16(L, 1),
1181                                                              read_v3s16(L, 2))
1182                                            : new LuaVoxelManip(map);
1183
1184         *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1185         luaL_getmetatable(L, "VoxelManip");
1186         lua_setmetatable(L, -2);
1187         return 1;
1188 }
1189
1190 // clear_objects([options])
1191 // clear all objects in the environment
1192 // where options = {mode = "full" or "quick"}
1193 int ModApiEnvMod::l_clear_objects(lua_State *L)
1194 {
1195         GET_ENV_PTR;
1196
1197         ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK;
1198         if (lua_istable(L, 1)) {
1199                 mode = (ClearObjectsMode)getenumfield(
1200                                 L, 1, "mode", ModApiEnvMod::es_ClearObjectsMode, mode);
1201         }
1202
1203         env->clearObjects(mode);
1204         return 0;
1205 }
1206
1207 // line_of_sight(pos1, pos2) -> true/false, pos
1208 int ModApiEnvMod::l_line_of_sight(lua_State *L)
1209 {
1210         GET_PLAIN_ENV_PTR;
1211
1212         // read position 1 from lua
1213         v3f pos1 = checkFloatPos(L, 1);
1214         // read position 2 from lua
1215         v3f pos2 = checkFloatPos(L, 2);
1216
1217         v3s16 p;
1218
1219         bool success = env->line_of_sight(pos1, pos2, &p);
1220         lua_pushboolean(L, success);
1221         if (!success) {
1222                 push_v3s16(L, p);
1223                 return 2;
1224         }
1225         return 1;
1226 }
1227
1228 // fix_light(p1, p2)
1229 int ModApiEnvMod::l_fix_light(lua_State *L)
1230 {
1231         GET_ENV_PTR;
1232
1233         v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
1234         v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
1235         ServerMap &map = env->getServerMap();
1236         std::map<v3s16, MapBlock *> modified_blocks;
1237         bool success = true;
1238         v3s16 blockpos;
1239         for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
1240                 for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
1241                         for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z;
1242                                         blockpos.Z++) {
1243                                 success = success & map.repairBlockLight(blockpos,
1244                                                                     &modified_blocks);
1245                         }
1246         if (!modified_blocks.empty()) {
1247                 MapEditEvent event;
1248                 event.type = MEET_OTHER;
1249                 for (auto &modified_block : modified_blocks)
1250                         event.modified_blocks.insert(modified_block.first);
1251
1252                 map.dispatchEvent(event);
1253         }
1254         lua_pushboolean(L, success);
1255
1256         return 1;
1257 }
1258
1259 int ModApiEnvMod::l_raycast(lua_State *L)
1260 {
1261         return LuaRaycast::create_object(L);
1262 }
1263
1264 // load_area(p1, [p2])
1265 // load mapblocks in area p1..p2, but do not generate map
1266 int ModApiEnvMod::l_load_area(lua_State *L)
1267 {
1268         GET_ENV_PTR;
1269         MAP_LOCK_REQUIRED;
1270
1271         Map *map = &(env->getMap());
1272         v3s16 bp1 = getNodeBlockPos(check_v3s16(L, 1));
1273         if (!lua_istable(L, 2)) {
1274                 map->emergeBlock(bp1);
1275         } else {
1276                 v3s16 bp2 = getNodeBlockPos(check_v3s16(L, 2));
1277                 sortBoxVerticies(bp1, bp2);
1278                 for (s16 z = bp1.Z; z <= bp2.Z; z++)
1279                         for (s16 y = bp1.Y; y <= bp2.Y; y++)
1280                                 for (s16 x = bp1.X; x <= bp2.X; x++) {
1281                                         map->emergeBlock(v3s16(x, y, z));
1282                                 }
1283         }
1284
1285         return 0;
1286 }
1287
1288 // emerge_area(p1, p2, [callback, context])
1289 // emerge mapblocks in area p1..p2, calls callback with context upon completion
1290 int ModApiEnvMod::l_emerge_area(lua_State *L)
1291 {
1292         GET_ENV_PTR;
1293
1294         EmergeCompletionCallback callback = NULL;
1295         ScriptCallbackState *state = NULL;
1296
1297         EmergeManager *emerge = getServer(L)->getEmergeManager();
1298
1299         v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1300         v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1301         sortBoxVerticies(bpmin, bpmax);
1302
1303         size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
1304         assert(num_blocks != 0);
1305
1306         if (lua_isfunction(L, 3)) {
1307                 callback = LuaEmergeAreaCallback;
1308
1309                 lua_pushvalue(L, 3);
1310                 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1311
1312                 lua_pushvalue(L, 4);
1313                 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1314
1315                 state = new ScriptCallbackState;
1316                 state->script = getServer(L)->getScriptIface();
1317                 state->callback_ref = callback_ref;
1318                 state->args_ref = args_ref;
1319                 state->refcount = num_blocks;
1320                 state->origin = getScriptApiBase(L)->getOrigin();
1321         }
1322
1323         for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1324                 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1325                         for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1326                                 emerge->enqueueBlockEmergeEx(v3s16(x, y, z),
1327                                                 PEER_ID_INEXISTENT,
1328                                                 BLOCK_EMERGE_ALLOW_GEN |
1329                                                                 BLOCK_EMERGE_FORCE_QUEUE,
1330                                                 callback, state);
1331                         }
1332
1333         return 0;
1334 }
1335
1336 // delete_area(p1, p2)
1337 // delete mapblocks in area p1..p2
1338 int ModApiEnvMod::l_delete_area(lua_State *L)
1339 {
1340         GET_ENV_PTR;
1341
1342         v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1343         v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1344         sortBoxVerticies(bpmin, bpmax);
1345
1346         ServerMap &map = env->getServerMap();
1347
1348         MapEditEvent event;
1349         event.type = MEET_OTHER;
1350
1351         bool success = true;
1352         for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1353                 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1354                         for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1355                                 v3s16 bp(x, y, z);
1356                                 if (map.deleteBlock(bp)) {
1357                                         env->setStaticForActiveObjectsInBlock(bp, false);
1358                                         event.modified_blocks.insert(bp);
1359                                 } else {
1360                                         success = false;
1361                                 }
1362                         }
1363
1364         map.dispatchEvent(event);
1365         lua_pushboolean(L, success);
1366         return 1;
1367 }
1368
1369 // find_path(pos1, pos2, searchdistance,
1370 //     max_jump, max_drop, algorithm) -> table containing path
1371 int ModApiEnvMod::l_find_path(lua_State *L)
1372 {
1373         Environment *env = getEnv(L);
1374
1375         v3s16 pos1 = read_v3s16(L, 1);
1376         v3s16 pos2 = read_v3s16(L, 2);
1377         unsigned int searchdistance = luaL_checkint(L, 3);
1378         unsigned int max_jump = luaL_checkint(L, 4);
1379         unsigned int max_drop = luaL_checkint(L, 5);
1380         PathAlgorithm algo = PA_PLAIN_NP;
1381         if (!lua_isnoneornil(L, 6)) {
1382                 std::string algorithm = luaL_checkstring(L, 6);
1383
1384                 if (algorithm == "A*")
1385                         algo = PA_PLAIN;
1386
1387                 if (algorithm == "Dijkstra")
1388                         algo = PA_DIJKSTRA;
1389         }
1390
1391         std::vector<v3s16> path = get_path(&env->getMap(), env->getGameDef()->ndef(),
1392                         pos1, pos2, searchdistance, max_jump, max_drop, algo);
1393
1394         if (!path.empty()) {
1395                 lua_createtable(L, path.size(), 0);
1396                 int top = lua_gettop(L);
1397                 unsigned int index = 1;
1398                 for (const v3s16 &i : path) {
1399                         lua_pushnumber(L, index);
1400                         push_v3s16(L, i);
1401                         lua_settable(L, top);
1402                         index++;
1403                 }
1404                 return 1;
1405         }
1406
1407         return 0;
1408 }
1409
1410 // spawn_tree(pos, treedef)
1411 int ModApiEnvMod::l_spawn_tree(lua_State *L)
1412 {
1413         GET_ENV_PTR;
1414
1415         v3s16 p0 = read_v3s16(L, 1);
1416
1417         treegen::TreeDef tree_def;
1418         std::string trunk, leaves, fruit;
1419         const NodeDefManager *ndef = env->getGameDef()->ndef();
1420
1421         if (lua_istable(L, 2)) {
1422                 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
1423                 getstringfield(L, 2, "rules_a", tree_def.rules_a);
1424                 getstringfield(L, 2, "rules_b", tree_def.rules_b);
1425                 getstringfield(L, 2, "rules_c", tree_def.rules_c);
1426                 getstringfield(L, 2, "rules_d", tree_def.rules_d);
1427                 getstringfield(L, 2, "trunk", trunk);
1428                 tree_def.trunknode = ndef->getId(trunk);
1429                 getstringfield(L, 2, "leaves", leaves);
1430                 tree_def.leavesnode = ndef->getId(leaves);
1431                 tree_def.leaves2_chance = 0;
1432                 getstringfield(L, 2, "leaves2", leaves);
1433                 if (!leaves.empty()) {
1434                         tree_def.leaves2node = ndef->getId(leaves);
1435                         getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
1436                 }
1437                 getintfield(L, 2, "angle", tree_def.angle);
1438                 getintfield(L, 2, "iterations", tree_def.iterations);
1439                 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1440                         tree_def.iterations_random_level = 0;
1441                 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1442                 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1443                 tree_def.fruit_chance = 0;
1444                 getstringfield(L, 2, "fruit", fruit);
1445                 if (!fruit.empty()) {
1446                         tree_def.fruitnode = ndef->getId(fruit);
1447                         getintfield(L, 2, "fruit_chance", tree_def.fruit_chance);
1448                 }
1449                 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1450         } else
1451                 return 0;
1452
1453         ServerMap *map = &env->getServerMap();
1454         treegen::error e;
1455         if ((e = treegen::spawn_ltree(map, p0, ndef, tree_def)) != treegen::SUCCESS) {
1456                 if (e == treegen::UNBALANCED_BRACKETS) {
1457                         luaL_error(L, "spawn_tree(): closing ']' has no matching opening "
1458                                       "bracket");
1459                 } else {
1460                         luaL_error(L, "spawn_tree(): unknown error");
1461                 }
1462         }
1463
1464         return 1;
1465 }
1466
1467 // transforming_liquid_add(pos)
1468 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1469 {
1470         GET_ENV_PTR;
1471
1472         v3s16 p0 = read_v3s16(L, 1);
1473         env->getMap().transforming_liquid_add(p0);
1474         return 1;
1475 }
1476
1477 // forceload_block(blockpos)
1478 // blockpos = {x=num, y=num, z=num}
1479 int ModApiEnvMod::l_forceload_block(lua_State *L)
1480 {
1481         GET_ENV_PTR;
1482
1483         v3s16 blockpos = read_v3s16(L, 1);
1484         env->getForceloadedBlocks()->insert(blockpos);
1485         return 0;
1486 }
1487
1488 // forceload_free_block(blockpos)
1489 // blockpos = {x=num, y=num, z=num}
1490 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1491 {
1492         GET_ENV_PTR;
1493
1494         v3s16 blockpos = read_v3s16(L, 1);
1495         env->getForceloadedBlocks()->erase(blockpos);
1496         return 0;
1497 }
1498
1499 // get_translated_string(lang_code, string)
1500 int ModApiEnvMod::l_get_translated_string(lua_State *L)
1501 {
1502         GET_ENV_PTR;
1503         std::string lang_code = luaL_checkstring(L, 1);
1504         std::string string = luaL_checkstring(L, 2);
1505         getServer(L)->loadTranslationLanguage(lang_code);
1506         string = wide_to_utf8(translate_string(
1507                         utf8_to_wide(string), &(*g_server_translations)[lang_code]));
1508         lua_pushstring(L, string.c_str());
1509         return 1;
1510 }
1511
1512 void ModApiEnvMod::Initialize(lua_State *L, int top)
1513 {
1514         API_FCT(set_node);
1515         API_FCT(bulk_set_node);
1516         API_FCT(add_node);
1517         API_FCT(swap_node);
1518         API_FCT(add_item);
1519         API_FCT(remove_node);
1520         API_FCT(get_node);
1521         API_FCT(get_node_or_nil);
1522         API_FCT(get_node_light);
1523         API_FCT(place_node);
1524         API_FCT(dig_node);
1525         API_FCT(punch_node);
1526         API_FCT(get_node_max_level);
1527         API_FCT(get_node_level);
1528         API_FCT(set_node_level);
1529         API_FCT(add_node_level);
1530         API_FCT(add_entity);
1531         API_FCT(find_nodes_with_meta);
1532         API_FCT(get_meta);
1533         API_FCT(get_node_timer);
1534         API_FCT(get_connected_players);
1535         API_FCT(get_player_by_name);
1536         API_FCT(get_objects_inside_radius);
1537         API_FCT(set_timeofday);
1538         API_FCT(get_timeofday);
1539         API_FCT(get_gametime);
1540         API_FCT(get_day_count);
1541         API_FCT(find_node_near);
1542         API_FCT(find_nodes_in_area);
1543         API_FCT(find_nodes_in_area_under_air);
1544         API_FCT(fix_light);
1545         API_FCT(load_area);
1546         API_FCT(emerge_area);
1547         API_FCT(delete_area);
1548         API_FCT(get_perlin);
1549         API_FCT(get_perlin_map);
1550         API_FCT(get_voxel_manip);
1551         API_FCT(clear_objects);
1552         API_FCT(spawn_tree);
1553         API_FCT(find_path);
1554         API_FCT(line_of_sight);
1555         API_FCT(raycast);
1556         API_FCT(transforming_liquid_add);
1557         API_FCT(forceload_block);
1558         API_FCT(forceload_free_block);
1559         API_FCT(get_translated_string);
1560 }
1561
1562 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1563 {
1564         API_FCT(get_node_light);
1565         API_FCT(get_timeofday);
1566         API_FCT(get_node_max_level);
1567         API_FCT(get_node_level);
1568         API_FCT(find_nodes_with_meta);
1569         API_FCT(find_node_near);
1570         API_FCT(find_nodes_near);
1571         API_FCT(find_nodes_near_under_air);
1572         API_FCT(find_nodes_near_under_air_except);
1573         API_FCT(find_nodes_in_area);
1574         API_FCT(find_nodes_in_area_under_air);
1575         API_FCT(find_path);
1576         API_FCT(line_of_sight);
1577         API_FCT(raycast);
1578 }