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