]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/lua_api/l_env.cpp
Modernize source code: last part (#6285)
[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                 // Insert object reference into table
646                 script->objectrefGetOrCreate(L, obj);
647                 lua_rawseti(L, -2, ++i);
648         }
649         return 1;
650 }
651
652 // set_timeofday(val)
653 // val = 0...1
654 int ModApiEnvMod::l_set_timeofday(lua_State *L)
655 {
656         GET_ENV_PTR;
657
658         // Do it
659         float timeofday_f = luaL_checknumber(L, 1);
660         sanity_check(timeofday_f >= 0.0 && timeofday_f <= 1.0);
661         int timeofday_mh = (int)(timeofday_f * 24000.0);
662         // This should be set directly in the environment but currently
663         // such changes aren't immediately sent to the clients, so call
664         // the server instead.
665         //env->setTimeOfDay(timeofday_mh);
666         getServer(L)->setTimeOfDay(timeofday_mh);
667         return 0;
668 }
669
670 // get_timeofday() -> 0...1
671 int ModApiEnvMod::l_get_timeofday(lua_State *L)
672 {
673         Environment *env = getEnv(L);
674         if (!env) {
675                 return 0;
676         }
677
678         // Do it
679         int timeofday_mh = env->getTimeOfDay();
680         float timeofday_f = (float)timeofday_mh / 24000.0f;
681         lua_pushnumber(L, timeofday_f);
682         return 1;
683 }
684
685 // get_day_count() -> int
686 int ModApiEnvMod::l_get_day_count(lua_State *L)
687 {
688         Environment *env = getEnv(L);
689         if (!env) {
690                 return 0;
691         }
692
693         lua_pushnumber(L, env->getDayCount());
694         return 1;
695 }
696
697 // get_gametime()
698 int ModApiEnvMod::l_get_gametime(lua_State *L)
699 {
700         GET_ENV_PTR;
701
702         int game_time = env->getGameTime();
703         lua_pushnumber(L, game_time);
704         return 1;
705 }
706
707
708 // find_node_near(pos, radius, nodenames, search_center) -> pos or nil
709 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
710 int ModApiEnvMod::l_find_node_near(lua_State *L)
711 {
712         Environment *env = getEnv(L);
713         if (!env) {
714                 return 0;
715         }
716
717         INodeDefManager *ndef = getGameDef(L)->ndef();
718         v3s16 pos = read_v3s16(L, 1);
719         int radius = luaL_checkinteger(L, 2);
720         std::set<content_t> filter;
721         if (lua_istable(L, 3)) {
722                 lua_pushnil(L);
723                 while (lua_next(L, 3) != 0) {
724                         // key at index -2 and value at index -1
725                         luaL_checktype(L, -1, LUA_TSTRING);
726                         ndef->getIds(lua_tostring(L, -1), filter);
727                         // removes value, keeps key for next iteration
728                         lua_pop(L, 1);
729                 }
730         } else if (lua_isstring(L, 3)) {
731                 ndef->getIds(lua_tostring(L, 3), filter);
732         }
733
734         int start_radius = (lua_toboolean(L, 4)) ? 0 : 1;
735
736 #ifndef SERVER
737         // Client API limitations
738         if (getClient(L) &&
739                         getClient(L)->checkCSMFlavourLimit(CSMFlavourLimit::CSM_FL_LOOKUP_NODES)) {
740                 radius = std::max<int>(radius, getClient(L)->getCSMNodeRangeLimit());
741         }
742 #endif
743
744         for (int d = start_radius; d <= radius; d++) {
745                 std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
746                 for (const v3s16 &i : list) {
747                         v3s16 p = pos + i;
748                         content_t c = env->getMap().getNodeNoEx(p).getContent();
749                         if (filter.count(c) != 0) {
750                                 push_v3s16(L, p);
751                                 return 1;
752                         }
753                 }
754         }
755         return 0;
756 }
757
758 // find_nodes_in_area(minp, maxp, nodenames) -> list of positions
759 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
760 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
761 {
762         GET_ENV_PTR;
763
764         INodeDefManager *ndef = getServer(L)->ndef();
765         v3s16 minp = read_v3s16(L, 1);
766         v3s16 maxp = read_v3s16(L, 2);
767         sortBoxVerticies(minp, maxp);
768
769         v3s16 cube = maxp - minp + 1;
770
771         /* Limit for too large areas, assume default values
772          * and give tolerances of 1 node on each side
773          * (chunksize * MAP_BLOCKSIZE + 2)^3 = 551368
774         */
775         if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 551368) {
776                 luaL_error(L, "find_nodes_in_area(): area volume"
777                                 " exceeds allowed value of 551368");
778                 return 0;
779         }
780
781         std::set<content_t> filter;
782         if (lua_istable(L, 3)) {
783                 lua_pushnil(L);
784                 while (lua_next(L, 3) != 0) {
785                         // key at index -2 and value at index -1
786                         luaL_checktype(L, -1, LUA_TSTRING);
787                         ndef->getIds(lua_tostring(L, -1), filter);
788                         // removes value, keeps key for next iteration
789                         lua_pop(L, 1);
790                 }
791         } else if (lua_isstring(L, 3)) {
792                 ndef->getIds(lua_tostring(L, 3), filter);
793         }
794
795         std::unordered_map<content_t, u32> individual_count;
796
797         lua_newtable(L);
798         u64 i = 0;
799         for (s16 x = minp.X; x <= maxp.X; x++)
800         for (s16 y = minp.Y; y <= maxp.Y; y++)
801         for (s16 z = minp.Z; z <= maxp.Z; z++) {
802                 v3s16 p(x, y, z);
803                 content_t c = env->getMap().getNodeNoEx(p).getContent();
804                 if (filter.count(c) != 0) {
805                         push_v3s16(L, p);
806                         lua_rawseti(L, -2, ++i);
807                         individual_count[c]++;
808                 }
809         }
810         lua_newtable(L);
811         for (content_t it : filter) {
812                 lua_pushnumber(L, individual_count[it]);
813                 lua_setfield(L, -2, ndef->get(it).name.c_str());
814         }
815         return 2;
816 }
817
818 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
819 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
820 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
821 {
822         /* Note: A similar but generalized (and therefore slower) version of this
823          * function could be created -- e.g. find_nodes_in_area_under -- which
824          * would accept a node name (or ID?) or list of names that the "above node"
825          * should be.
826          * TODO
827          */
828
829         GET_ENV_PTR;
830
831         INodeDefManager *ndef = getServer(L)->ndef();
832         v3s16 minp = read_v3s16(L, 1);
833         v3s16 maxp = read_v3s16(L, 2);
834         sortBoxVerticies(minp, maxp);
835
836         v3s16 cube = maxp - minp + 1;
837
838         /* Limit for too large areas, assume default values
839          * and give tolerances of 1 node on each side
840          * (chunksize * MAP_BLOCKSIZE + 2)^3 = 551368
841         */
842         if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 551368) {
843                 luaL_error(L, "find_nodes_in_area_under_air(): area volume"
844                                 " exceeds allowed value of 551368");
845                 return 0;
846         }
847
848         std::set<content_t> filter;
849
850         if (lua_istable(L, 3)) {
851                 lua_pushnil(L);
852                 while (lua_next(L, 3) != 0) {
853                         // key at index -2 and value at index -1
854                         luaL_checktype(L, -1, LUA_TSTRING);
855                         ndef->getIds(lua_tostring(L, -1), filter);
856                         // removes value, keeps key for next iteration
857                         lua_pop(L, 1);
858                 }
859         } else if (lua_isstring(L, 3)) {
860                 ndef->getIds(lua_tostring(L, 3), filter);
861         }
862
863         lua_newtable(L);
864         u64 i = 0;
865         for (s16 x = minp.X; x <= maxp.X; x++)
866         for (s16 z = minp.Z; z <= maxp.Z; z++) {
867                 s16 y = minp.Y;
868                 v3s16 p(x, y, z);
869                 content_t c = env->getMap().getNodeNoEx(p).getContent();
870                 for (; y <= maxp.Y; y++) {
871                         v3s16 psurf(x, y + 1, z);
872                         content_t csurf = env->getMap().getNodeNoEx(psurf).getContent();
873                         if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
874                                         filter.count(c) != 0) {
875                                 push_v3s16(L, v3s16(x, y, z));
876                                 lua_rawseti(L, -2, ++i);
877                         }
878                         c = csurf;
879                 }
880         }
881         return 1;
882 }
883
884 // get_perlin(seeddiff, octaves, persistence, scale)
885 // returns world-specific PerlinNoise
886 int ModApiEnvMod::l_get_perlin(lua_State *L)
887 {
888         GET_ENV_PTR_NO_MAP_LOCK;
889
890         NoiseParams params;
891
892         if (lua_istable(L, 1)) {
893                 read_noiseparams(L, 1, &params);
894         } else {
895                 params.seed    = luaL_checkint(L, 1);
896                 params.octaves = luaL_checkint(L, 2);
897                 params.persist = luaL_checknumber(L, 3);
898                 params.spread  = v3f(1, 1, 1) * luaL_checknumber(L, 4);
899         }
900
901         params.seed += (int)env->getServerMap().getSeed();
902
903         LuaPerlinNoise *n = new LuaPerlinNoise(&params);
904         *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
905         luaL_getmetatable(L, "PerlinNoise");
906         lua_setmetatable(L, -2);
907         return 1;
908 }
909
910 // get_perlin_map(noiseparams, size)
911 // returns world-specific PerlinNoiseMap
912 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
913 {
914         GET_ENV_PTR_NO_MAP_LOCK;
915
916         NoiseParams np;
917         if (!read_noiseparams(L, 1, &np))
918                 return 0;
919         v3s16 size = read_v3s16(L, 2);
920
921         s32 seed = (s32)(env->getServerMap().getSeed());
922         LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
923         *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
924         luaL_getmetatable(L, "PerlinNoiseMap");
925         lua_setmetatable(L, -2);
926         return 1;
927 }
928
929 // get_voxel_manip()
930 // returns voxel manipulator
931 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
932 {
933         GET_ENV_PTR;
934
935         Map *map = &(env->getMap());
936         LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
937                 new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
938                 new LuaVoxelManip(map);
939
940         *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
941         luaL_getmetatable(L, "VoxelManip");
942         lua_setmetatable(L, -2);
943         return 1;
944 }
945
946 // clear_objects([options])
947 // clear all objects in the environment
948 // where options = {mode = "full" or "quick"}
949 int ModApiEnvMod::l_clear_objects(lua_State *L)
950 {
951         GET_ENV_PTR;
952
953         ClearObjectsMode mode = CLEAR_OBJECTS_MODE_FULL;
954         if (lua_istable(L, 1)) {
955                 mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
956                         ModApiEnvMod::es_ClearObjectsMode, mode);
957         }
958
959         env->clearObjects(mode);
960         return 0;
961 }
962
963 // line_of_sight(pos1, pos2, stepsize) -> true/false, pos
964 int ModApiEnvMod::l_line_of_sight(lua_State *L)
965 {
966         float stepsize = 1.0;
967
968         GET_ENV_PTR;
969
970         // read position 1 from lua
971         v3f pos1 = checkFloatPos(L, 1);
972         // read position 2 from lua
973         v3f pos2 = checkFloatPos(L, 2);
974         //read step size from lua
975         if (lua_isnumber(L, 3)) {
976                 stepsize = lua_tonumber(L, 3);
977         }
978
979         v3s16 p;
980         bool success = env->line_of_sight(pos1, pos2, stepsize, &p);
981         lua_pushboolean(L, success);
982         if (!success) {
983                 push_v3s16(L, p);
984                 return 2;
985         }
986         return 1;
987 }
988
989 // fix_light(p1, p2)
990 int ModApiEnvMod::l_fix_light(lua_State *L)
991 {
992         GET_ENV_PTR;
993
994         v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
995         v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
996         ServerMap &map = env->getServerMap();
997         std::map<v3s16, MapBlock *> modified_blocks;
998         bool success = true;
999         v3s16 blockpos;
1000         for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
1001         for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
1002         for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
1003                 success = success & map.repairBlockLight(blockpos, &modified_blocks);
1004         }
1005         if (!modified_blocks.empty()) {
1006                 MapEditEvent event;
1007                 event.type = MEET_OTHER;
1008                 for (auto &modified_block : modified_blocks)
1009                         event.modified_blocks.insert(modified_block.first);
1010
1011                 map.dispatchEvent(&event);
1012         }
1013         lua_pushboolean(L, success);
1014
1015         return 1;
1016 }
1017
1018 int ModApiEnvMod::l_raycast(lua_State *L)
1019 {
1020         return LuaRaycast::create_object(L);
1021 }
1022
1023 // emerge_area(p1, p2, [callback, context])
1024 // emerge mapblocks in area p1..p2, calls callback with context upon completion
1025 int ModApiEnvMod::l_emerge_area(lua_State *L)
1026 {
1027         GET_ENV_PTR;
1028
1029         EmergeCompletionCallback callback = NULL;
1030         ScriptCallbackState *state = NULL;
1031
1032         EmergeManager *emerge = getServer(L)->getEmergeManager();
1033
1034         v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1035         v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1036         sortBoxVerticies(bpmin, bpmax);
1037
1038         size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
1039         assert(num_blocks != 0);
1040
1041         if (lua_isfunction(L, 3)) {
1042                 callback = LuaEmergeAreaCallback;
1043
1044                 lua_pushvalue(L, 3);
1045                 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1046
1047                 lua_pushvalue(L, 4);
1048                 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1049
1050                 state = new ScriptCallbackState;
1051                 state->script       = getServer(L)->getScriptIface();
1052                 state->callback_ref = callback_ref;
1053                 state->args_ref     = args_ref;
1054                 state->refcount     = num_blocks;
1055                 state->origin       = getScriptApiBase(L)->getOrigin();
1056         }
1057
1058         for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1059         for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1060         for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1061                 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
1062                         BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
1063         }
1064
1065         return 0;
1066 }
1067
1068 // delete_area(p1, p2)
1069 // delete mapblocks in area p1..p2
1070 int ModApiEnvMod::l_delete_area(lua_State *L)
1071 {
1072         GET_ENV_PTR;
1073
1074         v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1075         v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1076         sortBoxVerticies(bpmin, bpmax);
1077
1078         ServerMap &map = env->getServerMap();
1079
1080         MapEditEvent event;
1081         event.type = MEET_OTHER;
1082
1083         bool success = true;
1084         for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1085         for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1086         for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1087                 v3s16 bp(x, y, z);
1088                 if (map.deleteBlock(bp)) {
1089                         env->setStaticForActiveObjectsInBlock(bp, false);
1090                         event.modified_blocks.insert(bp);
1091                 } else {
1092                         success = false;
1093                 }
1094         }
1095
1096         map.dispatchEvent(&event);
1097         lua_pushboolean(L, success);
1098         return 1;
1099 }
1100
1101 // find_path(pos1, pos2, searchdistance,
1102 //     max_jump, max_drop, algorithm) -> table containing path
1103 int ModApiEnvMod::l_find_path(lua_State *L)
1104 {
1105         GET_ENV_PTR;
1106
1107         v3s16 pos1                  = read_v3s16(L, 1);
1108         v3s16 pos2                  = read_v3s16(L, 2);
1109         unsigned int searchdistance = luaL_checkint(L, 3);
1110         unsigned int max_jump       = luaL_checkint(L, 4);
1111         unsigned int max_drop       = luaL_checkint(L, 5);
1112         PathAlgorithm algo          = PA_PLAIN_NP;
1113         if (!lua_isnil(L, 6)) {
1114                 std::string algorithm = luaL_checkstring(L,6);
1115
1116                 if (algorithm == "A*")
1117                         algo = PA_PLAIN;
1118
1119                 if (algorithm == "Dijkstra")
1120                         algo = PA_DIJKSTRA;
1121         }
1122
1123         std::vector<v3s16> path = get_path(env, pos1, pos2,
1124                 searchdistance, max_jump, max_drop, algo);
1125
1126         if (!path.empty()) {
1127                 lua_newtable(L);
1128                 int top = lua_gettop(L);
1129                 unsigned int index = 1;
1130                 for (const v3s16 &i : path) {
1131                         lua_pushnumber(L,index);
1132                         push_v3s16(L, i);
1133                         lua_settable(L, top);
1134                         index++;
1135                 }
1136                 return 1;
1137         }
1138
1139         return 0;
1140 }
1141
1142 // spawn_tree(pos, treedef)
1143 int ModApiEnvMod::l_spawn_tree(lua_State *L)
1144 {
1145         GET_ENV_PTR;
1146
1147         v3s16 p0 = read_v3s16(L, 1);
1148
1149         treegen::TreeDef tree_def;
1150         std::string trunk,leaves,fruit;
1151         INodeDefManager *ndef = env->getGameDef()->ndef();
1152
1153         if(lua_istable(L, 2))
1154         {
1155                 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
1156                 getstringfield(L, 2, "rules_a", tree_def.rules_a);
1157                 getstringfield(L, 2, "rules_b", tree_def.rules_b);
1158                 getstringfield(L, 2, "rules_c", tree_def.rules_c);
1159                 getstringfield(L, 2, "rules_d", tree_def.rules_d);
1160                 getstringfield(L, 2, "trunk", trunk);
1161                 tree_def.trunknode=ndef->getId(trunk);
1162                 getstringfield(L, 2, "leaves", leaves);
1163                 tree_def.leavesnode=ndef->getId(leaves);
1164                 tree_def.leaves2_chance=0;
1165                 getstringfield(L, 2, "leaves2", leaves);
1166                 if (!leaves.empty()) {
1167                         tree_def.leaves2node=ndef->getId(leaves);
1168                         getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
1169                 }
1170                 getintfield(L, 2, "angle", tree_def.angle);
1171                 getintfield(L, 2, "iterations", tree_def.iterations);
1172                 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1173                         tree_def.iterations_random_level = 0;
1174                 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1175                 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1176                 tree_def.fruit_chance=0;
1177                 getstringfield(L, 2, "fruit", fruit);
1178                 if (!fruit.empty()) {
1179                         tree_def.fruitnode=ndef->getId(fruit);
1180                         getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
1181                 }
1182                 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1183         }
1184         else
1185                 return 0;
1186
1187         treegen::error e;
1188         if ((e = treegen::spawn_ltree (env, p0, ndef, tree_def)) != treegen::SUCCESS) {
1189                 if (e == treegen::UNBALANCED_BRACKETS) {
1190                         luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1191                 } else {
1192                         luaL_error(L, "spawn_tree(): unknown error");
1193                 }
1194         }
1195
1196         return 1;
1197 }
1198
1199 // transforming_liquid_add(pos)
1200 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1201 {
1202         GET_ENV_PTR;
1203
1204         v3s16 p0 = read_v3s16(L, 1);
1205         env->getMap().transforming_liquid_add(p0);
1206         return 1;
1207 }
1208
1209 // forceload_block(blockpos)
1210 // blockpos = {x=num, y=num, z=num}
1211 int ModApiEnvMod::l_forceload_block(lua_State *L)
1212 {
1213         GET_ENV_PTR;
1214
1215         v3s16 blockpos = read_v3s16(L, 1);
1216         env->getForceloadedBlocks()->insert(blockpos);
1217         return 0;
1218 }
1219
1220 // forceload_free_block(blockpos)
1221 // blockpos = {x=num, y=num, z=num}
1222 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1223 {
1224         GET_ENV_PTR;
1225
1226         v3s16 blockpos = read_v3s16(L, 1);
1227         env->getForceloadedBlocks()->erase(blockpos);
1228         return 0;
1229 }
1230
1231 void ModApiEnvMod::Initialize(lua_State *L, int top)
1232 {
1233         API_FCT(set_node);
1234         API_FCT(add_node);
1235         API_FCT(swap_node);
1236         API_FCT(add_item);
1237         API_FCT(remove_node);
1238         API_FCT(get_node);
1239         API_FCT(get_node_or_nil);
1240         API_FCT(get_node_light);
1241         API_FCT(place_node);
1242         API_FCT(dig_node);
1243         API_FCT(punch_node);
1244         API_FCT(get_node_max_level);
1245         API_FCT(get_node_level);
1246         API_FCT(set_node_level);
1247         API_FCT(add_node_level);
1248         API_FCT(add_entity);
1249         API_FCT(find_nodes_with_meta);
1250         API_FCT(get_meta);
1251         API_FCT(get_node_timer);
1252         API_FCT(get_player_by_name);
1253         API_FCT(get_objects_inside_radius);
1254         API_FCT(set_timeofday);
1255         API_FCT(get_timeofday);
1256         API_FCT(get_gametime);
1257         API_FCT(get_day_count);
1258         API_FCT(find_node_near);
1259         API_FCT(find_nodes_in_area);
1260         API_FCT(find_nodes_in_area_under_air);
1261         API_FCT(fix_light);
1262         API_FCT(emerge_area);
1263         API_FCT(delete_area);
1264         API_FCT(get_perlin);
1265         API_FCT(get_perlin_map);
1266         API_FCT(get_voxel_manip);
1267         API_FCT(clear_objects);
1268         API_FCT(spawn_tree);
1269         API_FCT(find_path);
1270         API_FCT(line_of_sight);
1271         API_FCT(raycast);
1272         API_FCT(transforming_liquid_add);
1273         API_FCT(forceload_block);
1274         API_FCT(forceload_free_block);
1275 }
1276
1277 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1278 {
1279         API_FCT(get_timeofday);
1280         API_FCT(get_day_count);
1281         API_FCT(get_node_max_level);
1282         API_FCT(get_node_level);
1283         API_FCT(find_node_near);
1284 }