]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/lua_api/l_env.cpp
[CSM] Add core.get_timeofday & core.get_day_count env calls (#5401)
[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 // emerge_area(p1, p2, [callback, context])
851 // emerge mapblocks in area p1..p2, calls callback with context upon completion
852 int ModApiEnvMod::l_emerge_area(lua_State *L)
853 {
854         GET_ENV_PTR;
855
856         EmergeCompletionCallback callback = NULL;
857         ScriptCallbackState *state = NULL;
858
859         EmergeManager *emerge = getServer(L)->getEmergeManager();
860
861         v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
862         v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
863         sortBoxVerticies(bpmin, bpmax);
864
865         size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
866         assert(num_blocks != 0);
867
868         if (lua_isfunction(L, 3)) {
869                 callback = LuaEmergeAreaCallback;
870
871                 lua_pushvalue(L, 3);
872                 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
873
874                 lua_pushvalue(L, 4);
875                 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
876
877                 state = new ScriptCallbackState;
878                 state->script       = getServer(L)->getScriptIface();
879                 state->callback_ref = callback_ref;
880                 state->args_ref     = args_ref;
881                 state->refcount     = num_blocks;
882                 state->origin       = getScriptApiBase(L)->getOrigin();
883         }
884
885         for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
886         for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
887         for (s16 x = bpmin.X; x <= bpmax.X; x++) {
888                 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
889                         BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
890         }
891
892         return 0;
893 }
894
895 // delete_area(p1, p2)
896 // delete mapblocks in area p1..p2
897 int ModApiEnvMod::l_delete_area(lua_State *L)
898 {
899         GET_ENV_PTR;
900
901         v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
902         v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
903         sortBoxVerticies(bpmin, bpmax);
904
905         ServerMap &map = env->getServerMap();
906
907         MapEditEvent event;
908         event.type = MEET_OTHER;
909
910         bool success = true;
911         for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
912         for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
913         for (s16 x = bpmin.X; x <= bpmax.X; x++) {
914                 v3s16 bp(x, y, z);
915                 if (map.deleteBlock(bp)) {
916                         env->setStaticForActiveObjectsInBlock(bp, false);
917                         event.modified_blocks.insert(bp);
918                 } else {
919                         success = false;
920                 }
921         }
922
923         map.dispatchEvent(&event);
924         lua_pushboolean(L, success);
925         return 1;
926 }
927
928 // find_path(pos1, pos2, searchdistance,
929 //     max_jump, max_drop, algorithm) -> table containing path
930 int ModApiEnvMod::l_find_path(lua_State *L)
931 {
932         GET_ENV_PTR;
933
934         v3s16 pos1                  = read_v3s16(L, 1);
935         v3s16 pos2                  = read_v3s16(L, 2);
936         unsigned int searchdistance = luaL_checkint(L, 3);
937         unsigned int max_jump       = luaL_checkint(L, 4);
938         unsigned int max_drop       = luaL_checkint(L, 5);
939         PathAlgorithm algo          = PA_PLAIN_NP;
940         if (!lua_isnil(L, 6)) {
941                 std::string algorithm = luaL_checkstring(L,6);
942
943                 if (algorithm == "A*")
944                         algo = PA_PLAIN;
945
946                 if (algorithm == "Dijkstra")
947                         algo = PA_DIJKSTRA;
948         }
949
950         std::vector<v3s16> path = get_path(env, pos1, pos2,
951                 searchdistance, max_jump, max_drop, algo);
952
953         if (path.size() > 0)
954         {
955                 lua_newtable(L);
956                 int top = lua_gettop(L);
957                 unsigned int index = 1;
958                 for (std::vector<v3s16>::iterator i = path.begin(); i != path.end();i++)
959                 {
960                         lua_pushnumber(L,index);
961                         push_v3s16(L, *i);
962                         lua_settable(L, top);
963                         index++;
964                 }
965                 return 1;
966         }
967
968         return 0;
969 }
970
971 // spawn_tree(pos, treedef)
972 int ModApiEnvMod::l_spawn_tree(lua_State *L)
973 {
974         GET_ENV_PTR;
975
976         v3s16 p0 = read_v3s16(L, 1);
977
978         treegen::TreeDef tree_def;
979         std::string trunk,leaves,fruit;
980         INodeDefManager *ndef = env->getGameDef()->ndef();
981
982         if(lua_istable(L, 2))
983         {
984                 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
985                 getstringfield(L, 2, "rules_a", tree_def.rules_a);
986                 getstringfield(L, 2, "rules_b", tree_def.rules_b);
987                 getstringfield(L, 2, "rules_c", tree_def.rules_c);
988                 getstringfield(L, 2, "rules_d", tree_def.rules_d);
989                 getstringfield(L, 2, "trunk", trunk);
990                 tree_def.trunknode=ndef->getId(trunk);
991                 getstringfield(L, 2, "leaves", leaves);
992                 tree_def.leavesnode=ndef->getId(leaves);
993                 tree_def.leaves2_chance=0;
994                 getstringfield(L, 2, "leaves2", leaves);
995                 if (leaves !="")
996                 {
997                         tree_def.leaves2node=ndef->getId(leaves);
998                         getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
999                 }
1000                 getintfield(L, 2, "angle", tree_def.angle);
1001                 getintfield(L, 2, "iterations", tree_def.iterations);
1002                 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1003                         tree_def.iterations_random_level = 0;
1004                 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1005                 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1006                 tree_def.fruit_chance=0;
1007                 getstringfield(L, 2, "fruit", fruit);
1008                 if (fruit != "")
1009                 {
1010                         tree_def.fruitnode=ndef->getId(fruit);
1011                         getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
1012                 }
1013                 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1014         }
1015         else
1016                 return 0;
1017
1018         treegen::error e;
1019         if ((e = treegen::spawn_ltree (env, p0, ndef, tree_def)) != treegen::SUCCESS) {
1020                 if (e == treegen::UNBALANCED_BRACKETS) {
1021                         luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1022                 } else {
1023                         luaL_error(L, "spawn_tree(): unknown error");
1024                 }
1025         }
1026
1027         return 1;
1028 }
1029
1030 // transforming_liquid_add(pos)
1031 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1032 {
1033         GET_ENV_PTR;
1034
1035         v3s16 p0 = read_v3s16(L, 1);
1036         env->getMap().transforming_liquid_add(p0);
1037         return 1;
1038 }
1039
1040 // forceload_block(blockpos)
1041 // blockpos = {x=num, y=num, z=num}
1042 int ModApiEnvMod::l_forceload_block(lua_State *L)
1043 {
1044         GET_ENV_PTR;
1045
1046         v3s16 blockpos = read_v3s16(L, 1);
1047         env->getForceloadedBlocks()->insert(blockpos);
1048         return 0;
1049 }
1050
1051 // forceload_free_block(blockpos)
1052 // blockpos = {x=num, y=num, z=num}
1053 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1054 {
1055         GET_ENV_PTR;
1056
1057         v3s16 blockpos = read_v3s16(L, 1);
1058         env->getForceloadedBlocks()->erase(blockpos);
1059         return 0;
1060 }
1061
1062 void ModApiEnvMod::Initialize(lua_State *L, int top)
1063 {
1064         API_FCT(set_node);
1065         API_FCT(add_node);
1066         API_FCT(swap_node);
1067         API_FCT(add_item);
1068         API_FCT(remove_node);
1069         API_FCT(get_node);
1070         API_FCT(get_node_or_nil);
1071         API_FCT(get_node_light);
1072         API_FCT(place_node);
1073         API_FCT(dig_node);
1074         API_FCT(punch_node);
1075         API_FCT(get_node_max_level);
1076         API_FCT(get_node_level);
1077         API_FCT(set_node_level);
1078         API_FCT(add_node_level);
1079         API_FCT(add_entity);
1080         API_FCT(find_nodes_with_meta);
1081         API_FCT(get_meta);
1082         API_FCT(get_node_timer);
1083         API_FCT(get_player_by_name);
1084         API_FCT(get_objects_inside_radius);
1085         API_FCT(set_timeofday);
1086         API_FCT(get_timeofday);
1087         API_FCT(get_gametime);
1088         API_FCT(get_day_count);
1089         API_FCT(find_node_near);
1090         API_FCT(find_nodes_in_area);
1091         API_FCT(find_nodes_in_area_under_air);
1092         API_FCT(emerge_area);
1093         API_FCT(delete_area);
1094         API_FCT(get_perlin);
1095         API_FCT(get_perlin_map);
1096         API_FCT(get_voxel_manip);
1097         API_FCT(clear_objects);
1098         API_FCT(spawn_tree);
1099         API_FCT(find_path);
1100         API_FCT(line_of_sight);
1101         API_FCT(transforming_liquid_add);
1102         API_FCT(forceload_block);
1103         API_FCT(forceload_free_block);
1104 }
1105
1106 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1107 {
1108         API_FCT(get_timeofday);
1109         API_FCT(get_day_count);
1110         API_FCT(get_node_max_level);
1111         API_FCT(get_node_level);
1112         API_FCT(find_node_near);
1113 }