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