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