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