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