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