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