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