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