47bc9baf7bcc43858d7fa42b358cbf5c7c1467b1
[oweals/minetest.git] / src / script / lua_api / l_env.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "cpp_api/scriptapi.h"
21 #include "lua_api/l_base.h"
22 #include "lua_api/l_env.h"
23 #include "lua_api/l_vmanip.h"
24 #include "environment.h"
25 #include "server.h"
26 #include "daynightratio.h"
27 #include "util/pointedthing.h"
28 #include "content_sao.h"
29
30 #include "common/c_converter.h"
31 #include "common/c_content.h"
32 #include "common/c_internal.h"
33 #include "lua_api/l_nodemeta.h"
34 #include "lua_api/l_nodetimer.h"
35 #include "lua_api/l_noise.h"
36 #include "treegen.h"
37 #include "pathfinder.h"
38 #include "emerge.h"
39 #include "mapgen_v7.h"
40
41
42 #define GET_ENV_PTR ServerEnvironment* env =                                   \
43                                 dynamic_cast<ServerEnvironment*>(getEnv(L));                   \
44                                 if( env == NULL) return 0
45                                 
46 struct EnumString ModApiEnvMod::es_MapgenObject[] =
47 {
48         {MGOBJ_VMANIP,    "voxelmanip"},
49         {MGOBJ_HEIGHTMAP, "heightmap"},
50         {MGOBJ_BIOMEMAP,  "biomemap"},
51         {MGOBJ_HEATMAP,   "heatmap"},
52         {MGOBJ_HUMIDMAP,  "humiditymap"},
53         {0, NULL},
54 };
55
56
57 ///////////////////////////////////////////////////////////////////////////////
58
59
60 void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
61                 u32 active_object_count, u32 active_object_count_wider)
62 {
63         ScriptApi* scriptIface = SERVER_TO_SA(env);
64         scriptIface->realityCheck();
65
66         lua_State* L = scriptIface->getStack();
67         assert(lua_checkstack(L, 20));
68         StackUnroller stack_unroller(L);
69
70         // Get minetest.registered_abms
71         lua_getglobal(L, "minetest");
72         lua_getfield(L, -1, "registered_abms");
73         luaL_checktype(L, -1, LUA_TTABLE);
74         int registered_abms = lua_gettop(L);
75
76         // Get minetest.registered_abms[m_id]
77         lua_pushnumber(L, m_id);
78         lua_gettable(L, registered_abms);
79         if(lua_isnil(L, -1))
80                 assert(0);
81
82         // Call action
83         luaL_checktype(L, -1, LUA_TTABLE);
84         lua_getfield(L, -1, "action");
85         luaL_checktype(L, -1, LUA_TFUNCTION);
86         push_v3s16(L, p);
87         pushnode(L, n, env->getGameDef()->ndef());
88         lua_pushnumber(L, active_object_count);
89         lua_pushnumber(L, active_object_count_wider);
90         if(lua_pcall(L, 4, 0, 0))
91                 script_error(L, "error: %s", lua_tostring(L, -1));
92 }
93
94 // Exported functions
95
96 // minetest.set_node(pos, node)
97 // pos = {x=num, y=num, z=num}
98 int ModApiEnvMod::l_set_node(lua_State *L)
99 {
100         GET_ENV_PTR;
101
102         INodeDefManager *ndef = env->getGameDef()->ndef();
103         // parameters
104         v3s16 pos = read_v3s16(L, 1);
105         MapNode n = readnode(L, 2, ndef);
106         // Do it
107         bool succeeded = env->setNode(pos, n);
108         lua_pushboolean(L, succeeded);
109         return 1;
110 }
111
112 int ModApiEnvMod::l_add_node(lua_State *L)
113 {
114         return l_set_node(L);
115 }
116
117 // minetest.remove_node(pos)
118 // pos = {x=num, y=num, z=num}
119 int ModApiEnvMod::l_remove_node(lua_State *L)
120 {
121         GET_ENV_PTR;
122
123         // parameters
124         v3s16 pos = read_v3s16(L, 1);
125         // Do it
126         bool succeeded = env->removeNode(pos);
127         lua_pushboolean(L, succeeded);
128         return 1;
129 }
130
131 // minetest.get_node(pos)
132 // pos = {x=num, y=num, z=num}
133 int ModApiEnvMod::l_get_node(lua_State *L)
134 {
135         GET_ENV_PTR;
136
137         // pos
138         v3s16 pos = read_v3s16(L, 1);
139         // Do it
140         MapNode n = env->getMap().getNodeNoEx(pos);
141         // Return node
142         pushnode(L, n, env->getGameDef()->ndef());
143         return 1;
144 }
145
146 // minetest.get_node_or_nil(pos)
147 // pos = {x=num, y=num, z=num}
148 int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
149 {
150         GET_ENV_PTR;
151
152         // pos
153         v3s16 pos = read_v3s16(L, 1);
154         // Do it
155         try{
156                 MapNode n = env->getMap().getNode(pos);
157                 // Return node
158                 pushnode(L, n, env->getGameDef()->ndef());
159                 return 1;
160         } catch(InvalidPositionException &e)
161         {
162                 lua_pushnil(L);
163                 return 1;
164         }
165 }
166
167 // minetest.get_node_light(pos, timeofday)
168 // pos = {x=num, y=num, z=num}
169 // timeofday: nil = current time, 0 = night, 0.5 = day
170 int ModApiEnvMod::l_get_node_light(lua_State *L)
171 {
172         GET_ENV_PTR;
173
174         // Do it
175         v3s16 pos = read_v3s16(L, 1);
176         u32 time_of_day = env->getTimeOfDay();
177         if(lua_isnumber(L, 2))
178                 time_of_day = 24000.0 * lua_tonumber(L, 2);
179         time_of_day %= 24000;
180         u32 dnr = time_to_daynight_ratio(time_of_day, true);
181         try{
182                 MapNode n = env->getMap().getNode(pos);
183                 INodeDefManager *ndef = env->getGameDef()->ndef();
184                 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
185                 return 1;
186         } catch(InvalidPositionException &e)
187         {
188                 lua_pushnil(L);
189                 return 1;
190         }
191 }
192
193 // minetest.place_node(pos, node)
194 // pos = {x=num, y=num, z=num}
195 int ModApiEnvMod::l_place_node(lua_State *L)
196 {
197         GET_ENV_PTR;
198
199         v3s16 pos = read_v3s16(L, 1);
200         MapNode n = readnode(L, 2, env->getGameDef()->ndef());
201
202         // Don't attempt to load non-loaded area as of now
203         MapNode n_old = env->getMap().getNodeNoEx(pos);
204         if(n_old.getContent() == CONTENT_IGNORE){
205                 lua_pushboolean(L, false);
206                 return 1;
207         }
208         // Create item to place
209         INodeDefManager *ndef = getServer(L)->ndef();
210         IItemDefManager *idef = getServer(L)->idef();
211         ItemStack item(ndef->get(n).name, 1, 0, "", idef);
212         // Make pointed position
213         PointedThing pointed;
214         pointed.type = POINTEDTHING_NODE;
215         pointed.node_abovesurface = pos;
216         pointed.node_undersurface = pos + v3s16(0,-1,0);
217         // Place it with a NULL placer (appears in Lua as a non-functional
218         // ObjectRef)
219         bool success = get_scriptapi(L)->item_OnPlace(item, NULL, pointed);
220         lua_pushboolean(L, success);
221         return 1;
222 }
223
224 // minetest.dig_node(pos)
225 // pos = {x=num, y=num, z=num}
226 int ModApiEnvMod::l_dig_node(lua_State *L)
227 {
228         GET_ENV_PTR;
229
230         v3s16 pos = read_v3s16(L, 1);
231
232         // Don't attempt to load non-loaded area as of now
233         MapNode n = env->getMap().getNodeNoEx(pos);
234         if(n.getContent() == CONTENT_IGNORE){
235                 lua_pushboolean(L, false);
236                 return 1;
237         }
238         // Dig it out with a NULL digger (appears in Lua as a
239         // non-functional ObjectRef)
240         bool success = get_scriptapi(L)->node_on_dig(pos, n, NULL);
241         lua_pushboolean(L, success);
242         return 1;
243 }
244
245 // minetest.punch_node(pos)
246 // pos = {x=num, y=num, z=num}
247 int ModApiEnvMod::l_punch_node(lua_State *L)
248 {
249         GET_ENV_PTR;
250
251         v3s16 pos = read_v3s16(L, 1);
252
253         // Don't attempt to load non-loaded area as of now
254         MapNode n = env->getMap().getNodeNoEx(pos);
255         if(n.getContent() == CONTENT_IGNORE){
256                 lua_pushboolean(L, false);
257                 return 1;
258         }
259         // Punch it with a NULL puncher (appears in Lua as a non-functional
260         // ObjectRef)
261         bool success = get_scriptapi(L)->node_on_punch(pos, n, NULL);
262         lua_pushboolean(L, success);
263         return 1;
264 }
265
266 // minetest.get_node_max_level(pos)
267 // pos = {x=num, y=num, z=num}
268 int ModApiEnvMod::l_get_node_max_level(lua_State *L)
269 {
270         GET_ENV_PTR;
271
272         v3s16 pos = read_v3s16(L, 1);
273         MapNode n = env->getMap().getNodeNoEx(pos);
274         lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef()));
275         return 1;
276 }
277
278 // minetest.get_node_level(pos)
279 // pos = {x=num, y=num, z=num}
280 int ModApiEnvMod::l_get_node_level(lua_State *L)
281 {
282         GET_ENV_PTR;
283
284         v3s16 pos = read_v3s16(L, 1);
285         MapNode n = env->getMap().getNodeNoEx(pos);
286         lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef()));
287         return 1;
288 }
289
290 // minetest.set_node_level(pos, level)
291 // pos = {x=num, y=num, z=num}
292 // level: 0..63
293 int ModApiEnvMod::l_set_node_level(lua_State *L)
294 {
295         GET_ENV_PTR;
296
297         v3s16 pos = read_v3s16(L, 1);
298         u8 level = 1;
299         if(lua_isnumber(L, 2))
300                 level = lua_tonumber(L, 2);
301         MapNode n = env->getMap().getNodeNoEx(pos);
302         lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level));
303         env->setNode(pos, n);
304         return 1;
305 }
306
307 // minetest.add_node_level(pos, level)
308 // pos = {x=num, y=num, z=num}
309 // level: 0..63
310 int ModApiEnvMod::l_add_node_level(lua_State *L)
311 {
312         GET_ENV_PTR;
313
314         v3s16 pos = read_v3s16(L, 1);
315         u8 level = 1;
316         if(lua_isnumber(L, 2))
317                 level = lua_tonumber(L, 2);
318         MapNode n = env->getMap().getNodeNoEx(pos);
319         lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level));
320         env->setNode(pos, n);
321         return 1;
322 }
323
324
325 // minetest.get_meta(pos)
326 int ModApiEnvMod::l_get_meta(lua_State *L)
327 {
328         GET_ENV_PTR;
329
330         // Do it
331         v3s16 p = read_v3s16(L, 1);
332         NodeMetaRef::create(L, p, env);
333         return 1;
334 }
335
336 // minetest.get_node_timer(pos)
337 int ModApiEnvMod::l_get_node_timer(lua_State *L)
338 {
339         GET_ENV_PTR;
340
341         // Do it
342         v3s16 p = read_v3s16(L, 1);
343         NodeTimerRef::create(L, p, env);
344         return 1;
345 }
346
347 // minetest.add_entity(pos, entityname) -> ObjectRef or nil
348 // pos = {x=num, y=num, z=num}
349 int ModApiEnvMod::l_add_entity(lua_State *L)
350 {
351         GET_ENV_PTR;
352
353         // pos
354         v3f pos = checkFloatPos(L, 1);
355         // content
356         const char *name = luaL_checkstring(L, 2);
357         // Do it
358         ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
359         int objectid = env->addActiveObject(obj);
360         // If failed to add, return nothing (reads as nil)
361         if(objectid == 0)
362                 return 0;
363         // Return ObjectRef
364         get_scriptapi(L)->objectrefGetOrCreate(obj);
365         return 1;
366 }
367
368 // minetest.add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
369 // pos = {x=num, y=num, z=num}
370 int ModApiEnvMod::l_add_item(lua_State *L)
371 {
372         GET_ENV_PTR;
373
374         // pos
375         //v3f pos = checkFloatPos(L, 1);
376         // item
377         ItemStack item = read_item(L, 2,getServer(L));
378         if(item.empty() || !item.isKnown(getServer(L)->idef()))
379                 return 0;
380         // Use minetest.spawn_item to spawn a __builtin:item
381         lua_getglobal(L, "minetest");
382         lua_getfield(L, -1, "spawn_item");
383         if(lua_isnil(L, -1))
384                 return 0;
385         lua_pushvalue(L, 1);
386         lua_pushstring(L, item.getItemString().c_str());
387         if(lua_pcall(L, 2, 1, 0))
388                 script_error(L, "error: %s", lua_tostring(L, -1));
389         return 1;
390         /*lua_pushvalue(L, 1);
391         lua_pushstring(L, "__builtin:item");
392         lua_pushstring(L, item.getItemString().c_str());
393         return l_add_entity(L);*/
394         /*// Do it
395         ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
396         int objectid = env->addActiveObject(obj);
397         // If failed to add, return nothing (reads as nil)
398         if(objectid == 0)
399                 return 0;
400         // Return ObjectRef
401         objectrefGetOrCreate(L, obj);
402         return 1;*/
403 }
404
405 // minetest.get_player_by_name(name)
406 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
407 {
408         GET_ENV_PTR;
409
410         // Do it
411         const char *name = luaL_checkstring(L, 1);
412         Player *player = env->getPlayer(name);
413         if(player == NULL){
414                 lua_pushnil(L);
415                 return 1;
416         }
417         PlayerSAO *sao = player->getPlayerSAO();
418         if(sao == NULL){
419                 lua_pushnil(L);
420                 return 1;
421         }
422         // Put player on stack
423         get_scriptapi(L)->objectrefGetOrCreate(sao);
424         return 1;
425 }
426
427 // minetest.get_objects_inside_radius(pos, radius)
428 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
429 {
430         // Get the table insert function
431         lua_getglobal(L, "table");
432         lua_getfield(L, -1, "insert");
433         int table_insert = lua_gettop(L);
434
435         GET_ENV_PTR;
436
437         // Do it
438         v3f pos = checkFloatPos(L, 1);
439         float radius = luaL_checknumber(L, 2) * BS;
440         std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
441         lua_newtable(L);
442         int table = lua_gettop(L);
443         for(std::set<u16>::const_iterator
444                         i = ids.begin(); i != ids.end(); i++){
445                 ServerActiveObject *obj = env->getActiveObject(*i);
446                 // Insert object reference into table
447                 lua_pushvalue(L, table_insert);
448                 lua_pushvalue(L, table);
449                 get_scriptapi(L)->objectrefGetOrCreate(obj);
450                 if(lua_pcall(L, 2, 0, 0))
451                         script_error(L, "error: %s", lua_tostring(L, -1));
452         }
453         return 1;
454 }
455
456 // minetest.set_timeofday(val)
457 // val = 0...1
458 int ModApiEnvMod::l_set_timeofday(lua_State *L)
459 {
460         GET_ENV_PTR;
461
462         // Do it
463         float timeofday_f = luaL_checknumber(L, 1);
464         assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
465         int timeofday_mh = (int)(timeofday_f * 24000.0);
466         // This should be set directly in the environment but currently
467         // such changes aren't immediately sent to the clients, so call
468         // the server instead.
469         //env->setTimeOfDay(timeofday_mh);
470         getServer(L)->setTimeOfDay(timeofday_mh);
471         return 0;
472 }
473
474 // minetest.get_timeofday() -> 0...1
475 int ModApiEnvMod::l_get_timeofday(lua_State *L)
476 {
477         GET_ENV_PTR;
478
479         // Do it
480         int timeofday_mh = env->getTimeOfDay();
481         float timeofday_f = (float)timeofday_mh / 24000.0;
482         lua_pushnumber(L, timeofday_f);
483         return 1;
484 }
485
486
487 // minetest.find_node_near(pos, radius, nodenames) -> pos or nil
488 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
489 int ModApiEnvMod::l_find_node_near(lua_State *L)
490 {
491         GET_ENV_PTR;
492
493         INodeDefManager *ndef = getServer(L)->ndef();
494         v3s16 pos = read_v3s16(L, 1);
495         int radius = luaL_checkinteger(L, 2);
496         std::set<content_t> filter;
497         if(lua_istable(L, 3)){
498                 int table = 3;
499                 lua_pushnil(L);
500                 while(lua_next(L, table) != 0){
501                         // key at index -2 and value at index -1
502                         luaL_checktype(L, -1, LUA_TSTRING);
503                         ndef->getIds(lua_tostring(L, -1), filter);
504                         // removes value, keeps key for next iteration
505                         lua_pop(L, 1);
506                 }
507         } else if(lua_isstring(L, 3)){
508                 ndef->getIds(lua_tostring(L, 3), filter);
509         }
510
511         for(int d=1; d<=radius; d++){
512                 std::list<v3s16> list;
513                 getFacePositions(list, d);
514                 for(std::list<v3s16>::iterator i = list.begin();
515                                 i != list.end(); ++i){
516                         v3s16 p = pos + (*i);
517                         content_t c = env->getMap().getNodeNoEx(p).getContent();
518                         if(filter.count(c) != 0){
519                                 push_v3s16(L, p);
520                                 return 1;
521                         }
522                 }
523         }
524         return 0;
525 }
526
527 // minetest.find_nodes_in_area(minp, maxp, nodenames) -> list of positions
528 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
529 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
530 {
531         GET_ENV_PTR;
532
533         INodeDefManager *ndef = getServer(L)->ndef();
534         v3s16 minp = read_v3s16(L, 1);
535         v3s16 maxp = read_v3s16(L, 2);
536         std::set<content_t> filter;
537         if(lua_istable(L, 3)){
538                 int table = 3;
539                 lua_pushnil(L);
540                 while(lua_next(L, table) != 0){
541                         // key at index -2 and value at index -1
542                         luaL_checktype(L, -1, LUA_TSTRING);
543                         ndef->getIds(lua_tostring(L, -1), filter);
544                         // removes value, keeps key for next iteration
545                         lua_pop(L, 1);
546                 }
547         } else if(lua_isstring(L, 3)){
548                 ndef->getIds(lua_tostring(L, 3), filter);
549         }
550
551         // Get the table insert function
552         lua_getglobal(L, "table");
553         lua_getfield(L, -1, "insert");
554         int table_insert = lua_gettop(L);
555
556         lua_newtable(L);
557         int table = lua_gettop(L);
558         for(s16 x=minp.X; x<=maxp.X; x++)
559         for(s16 y=minp.Y; y<=maxp.Y; y++)
560         for(s16 z=minp.Z; z<=maxp.Z; z++)
561         {
562                 v3s16 p(x,y,z);
563                 content_t c = env->getMap().getNodeNoEx(p).getContent();
564                 if(filter.count(c) != 0){
565                         lua_pushvalue(L, table_insert);
566                         lua_pushvalue(L, table);
567                         push_v3s16(L, p);
568                         if(lua_pcall(L, 2, 0, 0))
569                                 script_error(L, "error: %s", lua_tostring(L, -1));
570                 }
571         }
572         return 1;
573 }
574
575 // minetest.get_perlin(seeddiff, octaves, persistence, scale)
576 // returns world-specific PerlinNoise
577 int ModApiEnvMod::l_get_perlin(lua_State *L)
578 {
579         GET_ENV_PTR;
580
581         int seeddiff = luaL_checkint(L, 1);
582         int octaves = luaL_checkint(L, 2);
583         float persistence = luaL_checknumber(L, 3);
584         float scale = luaL_checknumber(L, 4);
585
586         LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
587         *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
588         luaL_getmetatable(L, "PerlinNoise");
589         lua_setmetatable(L, -2);
590         return 1;
591 }
592
593 // minetest.get_perlin_map(noiseparams, size)
594 // returns world-specific PerlinNoiseMap
595 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
596 {
597         GET_ENV_PTR;
598
599         NoiseParams *np = read_noiseparams(L, 1);
600         if (!np)
601                 return 0;
602         v3s16 size = read_v3s16(L, 2);
603
604         int seed = (int)(env->getServerMap().getSeed());
605         LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(np, seed, size);
606         *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
607         luaL_getmetatable(L, "PerlinNoiseMap");
608         lua_setmetatable(L, -2);
609         return 1;
610 }
611
612 // minetest.get_voxel_manip()
613 // returns voxel manipulator
614 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
615 {
616         GET_ENV_PTR;
617
618         Map *map = &(env->getMap());
619         LuaVoxelManip *o = new LuaVoxelManip(map);
620         
621         *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
622         luaL_getmetatable(L, "VoxelManip");
623         lua_setmetatable(L, -2);
624         return 1;
625 }
626
627 // minetest.get_mapgen_object(objectname)
628 // returns the requested object used during map generation
629 int ModApiEnvMod::l_get_mapgen_object(lua_State *L)
630 {
631         const char *mgobjstr = lua_tostring(L, 1);
632         
633         int mgobjint;
634         if (!string_to_enum(es_MapgenObject, mgobjint, mgobjstr ? mgobjstr : ""))
635                 return 0;
636                 
637         enum MapgenObject mgobj = (MapgenObject)mgobjint;
638
639         EmergeManager *emerge = getServer(L)->getEmergeManager();
640         Mapgen *mg = emerge->getCurrentMapgen();
641         if (!mg)
642                 return 0;
643         
644         size_t maplen = mg->csize.X * mg->csize.Z;
645         
646         int nargs = 1;
647         
648         switch (mgobj) {
649                 case MGOBJ_VMANIP: {
650                         ManualMapVoxelManipulator *vm = mg->vm;
651                         
652                         // VoxelManip object
653                         LuaVoxelManip *o = new LuaVoxelManip(vm, true);
654                         *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
655                         luaL_getmetatable(L, "VoxelManip");
656                         lua_setmetatable(L, -2);
657                         
658                         // emerged min pos
659                         push_v3s16(L, vm->m_area.MinEdge);
660
661                         // emerged max pos
662                         push_v3s16(L, vm->m_area.MaxEdge);
663                         
664                         nargs = 3;
665                         
666                         break; }
667                 case MGOBJ_HEIGHTMAP: {
668                         if (!mg->heightmap)
669                                 return 0;
670                         
671                         lua_newtable(L);
672                         for (size_t i = 0; i != maplen; i++) {
673                                 lua_pushinteger(L, mg->heightmap[i]);
674                                 lua_rawseti(L, -2, i + 1);
675                         }
676                         break; }
677                 case MGOBJ_BIOMEMAP: {
678                         if (!mg->biomemap)
679                                 return 0;
680                         
681                         lua_newtable(L);
682                         for (size_t i = 0; i != maplen; i++) {
683                                 lua_pushinteger(L, mg->biomemap[i]);
684                                 lua_rawseti(L, -2, i + 1);
685                         }
686                         break; }
687                 case MGOBJ_HEATMAP: { // Mapgen V7 specific objects
688                 case MGOBJ_HUMIDMAP:
689                         if (strcmp(emerge->params->mg_name.c_str(), "v7"))
690                                 return 0;
691                         
692                         MapgenV7 *mgv7 = (MapgenV7 *)mg;
693
694                         float *arr = (mgobj == MGOBJ_HEATMAP) ? 
695                                 mgv7->noise_heat->result : mgv7->noise_humidity->result;
696                         if (!arr)
697                                 return 0;
698                         
699                         lua_newtable(L);
700                         for (size_t i = 0; i != maplen; i++) {
701                                 lua_pushnumber(L, arr[i]);
702                                 lua_rawseti(L, -2, i + 1);
703                         }
704                         break; }
705         }
706         
707         return nargs;
708 }
709
710 // minetest.set_mapgen_params(params)
711 // set mapgen parameters
712 int ModApiEnvMod::l_set_mapgen_params(lua_State *L)
713 {
714         if (!lua_istable(L, 1))
715                 return 0;
716
717         EmergeManager *emerge = getServer(L)->getEmergeManager();
718         if (emerge->mapgen.size())
719                 return 0;
720         
721         MapgenParams *oparams = new MapgenParams;
722         u32 paramsmodified = 0;
723         u32 flagmask = 0;
724         
725         lua_getfield(L, 1, "mgname");
726         if (lua_isstring(L, -1)) {
727                 oparams->mg_name = std::string(lua_tostring(L, -1));
728                 paramsmodified |= MGPARAMS_SET_MGNAME;
729         }
730         
731         lua_getfield(L, 1, "seed");
732         if (lua_isnumber(L, -1)) {
733                 oparams->seed = lua_tointeger(L, -1);
734                 paramsmodified |= MGPARAMS_SET_SEED;
735         }
736         
737         lua_getfield(L, 1, "water_level");
738         if (lua_isnumber(L, -1)) {
739                 oparams->water_level = lua_tointeger(L, -1);
740                 paramsmodified |= MGPARAMS_SET_WATER_LEVEL;
741         }
742
743         lua_getfield(L, 1, "flags");
744         if (lua_isstring(L, -1)) {
745                 std::string flagstr = std::string(lua_tostring(L, -1));
746                 oparams->flags = readFlagString(flagstr, flagdesc_mapgen);
747                 paramsmodified |= MGPARAMS_SET_FLAGS;
748         
749                 lua_getfield(L, 1, "flagmask");
750                 if (lua_isstring(L, -1)) {
751                         flagstr = std::string(lua_tostring(L, -1));
752                         flagmask = readFlagString(flagstr, flagdesc_mapgen);
753                 }
754         }
755         
756         emerge->luaoverride_params          = oparams;
757         emerge->luaoverride_params_modified = paramsmodified;
758         emerge->luaoverride_flagmask        = flagmask;
759         
760         return 0;
761 }
762
763 // minetest.clear_objects()
764 // clear all objects in the environment
765 int ModApiEnvMod::l_clear_objects(lua_State *L)
766 {
767         GET_ENV_PTR;
768
769         env->clearAllObjects();
770         return 0;
771 }
772
773 // minetest.line_of_sight(pos1, pos2, stepsize) -> true/false
774 int ModApiEnvMod::l_line_of_sight(lua_State *L) {
775         float stepsize = 1.0;
776
777         GET_ENV_PTR;
778
779         // read position 1 from lua
780         v3f pos1 = checkFloatPos(L, 1);
781         // read position 2 from lua
782         v3f pos2 = checkFloatPos(L, 2);
783         //read step size from lua
784         if (lua_isnumber(L, 3))
785                 stepsize = lua_tonumber(L, 3);
786
787         return (env->line_of_sight(pos1,pos2,stepsize));
788 }
789
790 // minetest.find_path(pos1, pos2, searchdistance,
791 //     max_jump, max_drop, algorithm) -> table containing path
792 int ModApiEnvMod::l_find_path(lua_State *L)
793 {
794         GET_ENV_PTR;
795
796         v3s16 pos1                  = read_v3s16(L, 1);
797         v3s16 pos2                  = read_v3s16(L, 2);
798         unsigned int searchdistance = luaL_checkint(L, 3);
799         unsigned int max_jump       = luaL_checkint(L, 4);
800         unsigned int max_drop       = luaL_checkint(L, 5);
801         algorithm algo              = A_PLAIN_NP;
802         if (!lua_isnil(L, 6)) {
803                 std::string algorithm = luaL_checkstring(L,6);
804
805                 if (algorithm == "A*")
806                         algo = A_PLAIN;
807
808                 if (algorithm == "Dijkstra")
809                         algo = DIJKSTRA;
810         }
811
812         std::vector<v3s16> path =
813                         get_Path(env,pos1,pos2,searchdistance,max_jump,max_drop,algo);
814
815         if (path.size() > 0)
816         {
817                 lua_newtable(L);
818                 int top = lua_gettop(L);
819                 unsigned int index = 1;
820                 for (std::vector<v3s16>::iterator i = path.begin(); i != path.end();i++)
821                 {
822                         lua_pushnumber(L,index);
823                         push_v3s16(L, *i);
824                         lua_settable(L, top);
825                         index++;
826                 }
827                 return 1;
828         }
829
830         return 0;
831 }
832
833 // minetest.spawn_tree(pos, treedef)
834 int ModApiEnvMod::l_spawn_tree(lua_State *L)
835 {
836         GET_ENV_PTR;
837
838         v3s16 p0 = read_v3s16(L, 1);
839
840         treegen::TreeDef tree_def;
841         std::string trunk,leaves,fruit;
842         INodeDefManager *ndef = env->getGameDef()->ndef();
843
844         if(lua_istable(L, 2))
845         {
846                 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
847                 getstringfield(L, 2, "rules_a", tree_def.rules_a);
848                 getstringfield(L, 2, "rules_b", tree_def.rules_b);
849                 getstringfield(L, 2, "rules_c", tree_def.rules_c);
850                 getstringfield(L, 2, "rules_d", tree_def.rules_d);
851                 getstringfield(L, 2, "trunk", trunk);
852                 tree_def.trunknode=ndef->getId(trunk);
853                 getstringfield(L, 2, "leaves", leaves);
854                 tree_def.leavesnode=ndef->getId(leaves);
855                 tree_def.leaves2_chance=0;
856                 getstringfield(L, 2, "leaves2", leaves);
857                 if (leaves !="")
858                 {
859                         tree_def.leaves2node=ndef->getId(leaves);
860                         getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
861                 }
862                 getintfield(L, 2, "angle", tree_def.angle);
863                 getintfield(L, 2, "iterations", tree_def.iterations);
864                 getintfield(L, 2, "random_level", tree_def.iterations_random_level);
865                 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
866                 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
867                 tree_def.fruit_chance=0;
868                 getstringfield(L, 2, "fruit", fruit);
869                 if (fruit != "")
870                 {
871                         tree_def.fruitnode=ndef->getId(fruit);
872                         getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
873                 }
874                 getintfield(L, 2, "seed", tree_def.seed);
875         }
876         else
877                 return 0;
878         treegen::spawn_ltree (env, p0, ndef, tree_def);
879         return 1;
880 }
881
882
883 // minetest.transforming_liquid_add(pos)
884 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
885 {
886         GET_ENV_PTR;
887
888         v3s16 p0 = read_v3s16(L, 1);
889         env->getMap().transforming_liquid_add(p0);
890         return 1;
891 }
892
893 // minetest.get_heat(pos)
894 // pos = {x=num, y=num, z=num}
895 int ModApiEnvMod::l_get_heat(lua_State *L)
896 {
897         GET_ENV_PTR;
898
899         v3s16 pos = read_v3s16(L, 1);
900         lua_pushnumber(L, env->getServerMap().getHeat(env, pos));
901         return 1;
902 }
903
904 // minetest.get_humidity(pos)
905 // pos = {x=num, y=num, z=num}
906 int ModApiEnvMod::l_get_humidity(lua_State *L)
907 {
908         GET_ENV_PTR;
909
910         v3s16 pos = read_v3s16(L, 1);
911         lua_pushnumber(L, env->getServerMap().getHumidity(env, pos));
912         return 1;
913 }
914
915
916 bool ModApiEnvMod::Initialize(lua_State *L,int top)
917 {
918
919         bool retval = true;
920
921         retval &= API_FCT(set_node);
922         retval &= API_FCT(add_node);
923         retval &= API_FCT(add_item);
924         retval &= API_FCT(remove_node);
925         retval &= API_FCT(get_node);
926         retval &= API_FCT(get_node_or_nil);
927         retval &= API_FCT(get_node_light);
928         retval &= API_FCT(place_node);
929         retval &= API_FCT(dig_node);
930         retval &= API_FCT(punch_node);
931         retval &= API_FCT(get_node_max_level);
932         retval &= API_FCT(get_node_level);
933         retval &= API_FCT(set_node_level);
934         retval &= API_FCT(add_node_level);
935         retval &= API_FCT(add_entity);
936         retval &= API_FCT(get_meta);
937         retval &= API_FCT(get_node_timer);
938         retval &= API_FCT(get_player_by_name);
939         retval &= API_FCT(get_objects_inside_radius);
940         retval &= API_FCT(set_timeofday);
941         retval &= API_FCT(get_timeofday);
942         retval &= API_FCT(find_node_near);
943         retval &= API_FCT(find_nodes_in_area);
944         retval &= API_FCT(get_perlin);
945         retval &= API_FCT(get_perlin_map);
946         retval &= API_FCT(get_voxel_manip);
947         retval &= API_FCT(get_mapgen_object);
948         retval &= API_FCT(set_mapgen_params);
949         retval &= API_FCT(clear_objects);
950         retval &= API_FCT(spawn_tree);
951         retval &= API_FCT(find_path);
952         retval &= API_FCT(line_of_sight);
953         retval &= API_FCT(transforming_liquid_add);
954         retval &= API_FCT(get_heat);
955         retval &= API_FCT(get_humidity);
956
957         return retval;
958 }
959
960 ModApiEnvMod modapienv_prototype;