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