3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
20 #include "cpp_api/scriptapi.h"
21 #include "lua_api/l_base.h"
22 #include "lua_api/l_env.h"
23 #include "environment.h"
25 #include "daynightratio.h"
26 #include "util/pointedthing.h"
27 #include "content_sao.h"
29 #include "common/c_converter.h"
30 #include "common/c_content.h"
31 #include "common/c_internal.h"
32 #include "lua_api/l_nodemeta.h"
33 #include "lua_api/l_nodetimer.h"
34 #include "lua_api/l_noise.h"
36 #include "pathfinder.h"
39 #define GET_ENV_PTR ServerEnvironment* env = \
40 dynamic_cast<ServerEnvironment*>(getEnv(L)); \
41 if( env == NULL) return 0
43 void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
44 u32 active_object_count, u32 active_object_count_wider)
46 ScriptApi* scriptIface = SERVER_TO_SA(env);
47 scriptIface->realityCheck();
49 lua_State* L = scriptIface->getStack();
50 assert(lua_checkstack(L, 20));
51 StackUnroller stack_unroller(L);
53 // Get minetest.registered_abms
54 lua_getglobal(L, "minetest");
55 lua_getfield(L, -1, "registered_abms");
56 luaL_checktype(L, -1, LUA_TTABLE);
57 int registered_abms = lua_gettop(L);
59 // Get minetest.registered_abms[m_id]
60 lua_pushnumber(L, m_id);
61 lua_gettable(L, registered_abms);
66 luaL_checktype(L, -1, LUA_TTABLE);
67 lua_getfield(L, -1, "action");
68 luaL_checktype(L, -1, LUA_TFUNCTION);
70 pushnode(L, n, env->getGameDef()->ndef());
71 lua_pushnumber(L, active_object_count);
72 lua_pushnumber(L, active_object_count_wider);
73 if(lua_pcall(L, 4, 0, 0))
74 script_error(L, "error: %s", lua_tostring(L, -1));
79 // minetest.set_node(pos, node)
80 // pos = {x=num, y=num, z=num}
81 int ModApiEnvMod::l_set_node(lua_State *L)
85 INodeDefManager *ndef = env->getGameDef()->ndef();
87 v3s16 pos = read_v3s16(L, 1);
88 MapNode n = readnode(L, 2, ndef);
90 bool succeeded = env->setNode(pos, n);
91 lua_pushboolean(L, succeeded);
95 int ModApiEnvMod::l_add_node(lua_State *L)
100 // minetest.remove_node(pos)
101 // pos = {x=num, y=num, z=num}
102 int ModApiEnvMod::l_remove_node(lua_State *L)
107 v3s16 pos = read_v3s16(L, 1);
109 bool succeeded = env->removeNode(pos);
110 lua_pushboolean(L, succeeded);
114 // minetest.get_node(pos)
115 // pos = {x=num, y=num, z=num}
116 int ModApiEnvMod::l_get_node(lua_State *L)
121 v3s16 pos = read_v3s16(L, 1);
123 MapNode n = env->getMap().getNodeNoEx(pos);
125 pushnode(L, n, env->getGameDef()->ndef());
129 // minetest.get_node_or_nil(pos)
130 // pos = {x=num, y=num, z=num}
131 int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
136 v3s16 pos = read_v3s16(L, 1);
139 MapNode n = env->getMap().getNode(pos);
141 pushnode(L, n, env->getGameDef()->ndef());
143 } catch(InvalidPositionException &e)
150 // minetest.get_node_light(pos, timeofday)
151 // pos = {x=num, y=num, z=num}
152 // timeofday: nil = current time, 0 = night, 0.5 = day
153 int ModApiEnvMod::l_get_node_light(lua_State *L)
158 v3s16 pos = read_v3s16(L, 1);
159 u32 time_of_day = env->getTimeOfDay();
160 if(lua_isnumber(L, 2))
161 time_of_day = 24000.0 * lua_tonumber(L, 2);
162 time_of_day %= 24000;
163 u32 dnr = time_to_daynight_ratio(time_of_day, true);
165 MapNode n = env->getMap().getNode(pos);
166 INodeDefManager *ndef = env->getGameDef()->ndef();
167 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
169 } catch(InvalidPositionException &e)
176 // minetest.place_node(pos, node)
177 // pos = {x=num, y=num, z=num}
178 int ModApiEnvMod::l_place_node(lua_State *L)
182 v3s16 pos = read_v3s16(L, 1);
183 MapNode n = readnode(L, 2, env->getGameDef()->ndef());
185 // Don't attempt to load non-loaded area as of now
186 MapNode n_old = env->getMap().getNodeNoEx(pos);
187 if(n_old.getContent() == CONTENT_IGNORE){
188 lua_pushboolean(L, false);
191 // Create item to place
192 INodeDefManager *ndef = getServer(L)->ndef();
193 IItemDefManager *idef = getServer(L)->idef();
194 ItemStack item(ndef->get(n).name, 1, 0, "", idef);
195 // Make pointed position
196 PointedThing pointed;
197 pointed.type = POINTEDTHING_NODE;
198 pointed.node_abovesurface = pos;
199 pointed.node_undersurface = pos + v3s16(0,-1,0);
200 // Place it with a NULL placer (appears in Lua as a non-functional
202 bool success = get_scriptapi(L)->item_OnPlace(item, NULL, pointed);
203 lua_pushboolean(L, success);
207 // minetest.dig_node(pos)
208 // pos = {x=num, y=num, z=num}
209 int ModApiEnvMod::l_dig_node(lua_State *L)
213 v3s16 pos = read_v3s16(L, 1);
215 // Don't attempt to load non-loaded area as of now
216 MapNode n = env->getMap().getNodeNoEx(pos);
217 if(n.getContent() == CONTENT_IGNORE){
218 lua_pushboolean(L, false);
221 // Dig it out with a NULL digger (appears in Lua as a
222 // non-functional ObjectRef)
223 bool success = get_scriptapi(L)->node_on_dig(pos, n, NULL);
224 lua_pushboolean(L, success);
228 // minetest.punch_node(pos)
229 // pos = {x=num, y=num, z=num}
230 int ModApiEnvMod::l_punch_node(lua_State *L)
234 v3s16 pos = read_v3s16(L, 1);
236 // Don't attempt to load non-loaded area as of now
237 MapNode n = env->getMap().getNodeNoEx(pos);
238 if(n.getContent() == CONTENT_IGNORE){
239 lua_pushboolean(L, false);
242 // Punch it with a NULL puncher (appears in Lua as a non-functional
244 bool success = get_scriptapi(L)->node_on_punch(pos, n, NULL);
245 lua_pushboolean(L, success);
249 // minetest.get_meta(pos)
250 int ModApiEnvMod::l_get_meta(lua_State *L)
255 v3s16 p = read_v3s16(L, 1);
256 NodeMetaRef::create(L, p, env);
260 // minetest.get_node_timer(pos)
261 int ModApiEnvMod::l_get_node_timer(lua_State *L)
266 v3s16 p = read_v3s16(L, 1);
267 NodeTimerRef::create(L, p, env);
271 // minetest.add_entity(pos, entityname) -> ObjectRef or nil
272 // pos = {x=num, y=num, z=num}
273 int ModApiEnvMod::l_add_entity(lua_State *L)
278 v3f pos = checkFloatPos(L, 1);
280 const char *name = luaL_checkstring(L, 2);
282 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
283 int objectid = env->addActiveObject(obj);
284 // If failed to add, return nothing (reads as nil)
288 get_scriptapi(L)->objectrefGetOrCreate(obj);
292 // minetest.add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
293 // pos = {x=num, y=num, z=num}
294 int ModApiEnvMod::l_add_item(lua_State *L)
299 //v3f pos = checkFloatPos(L, 1);
301 ItemStack item = read_item(L, 2,getServer(L));
302 if(item.empty() || !item.isKnown(getServer(L)->idef()))
304 // Use minetest.spawn_item to spawn a __builtin:item
305 lua_getglobal(L, "minetest");
306 lua_getfield(L, -1, "spawn_item");
310 lua_pushstring(L, item.getItemString().c_str());
311 if(lua_pcall(L, 2, 1, 0))
312 script_error(L, "error: %s", lua_tostring(L, -1));
314 /*lua_pushvalue(L, 1);
315 lua_pushstring(L, "__builtin:item");
316 lua_pushstring(L, item.getItemString().c_str());
317 return l_add_entity(L);*/
319 ServerActiveObject *obj = createItemSAO(env, pos, item.getItemString());
320 int objectid = env->addActiveObject(obj);
321 // If failed to add, return nothing (reads as nil)
325 objectrefGetOrCreate(L, obj);
329 // minetest.get_player_by_name(name)
330 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
335 const char *name = luaL_checkstring(L, 1);
336 Player *player = env->getPlayer(name);
341 PlayerSAO *sao = player->getPlayerSAO();
346 // Put player on stack
347 get_scriptapi(L)->objectrefGetOrCreate(sao);
351 // minetest.get_objects_inside_radius(pos, radius)
352 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
354 // Get the table insert function
355 lua_getglobal(L, "table");
356 lua_getfield(L, -1, "insert");
357 int table_insert = lua_gettop(L);
362 v3f pos = checkFloatPos(L, 1);
363 float radius = luaL_checknumber(L, 2) * BS;
364 std::set<u16> ids = env->getObjectsInsideRadius(pos, radius);
366 int table = lua_gettop(L);
367 for(std::set<u16>::const_iterator
368 i = ids.begin(); i != ids.end(); i++){
369 ServerActiveObject *obj = env->getActiveObject(*i);
370 // Insert object reference into table
371 lua_pushvalue(L, table_insert);
372 lua_pushvalue(L, table);
373 get_scriptapi(L)->objectrefGetOrCreate(obj);
374 if(lua_pcall(L, 2, 0, 0))
375 script_error(L, "error: %s", lua_tostring(L, -1));
380 // minetest.set_timeofday(val)
382 int ModApiEnvMod::l_set_timeofday(lua_State *L)
387 float timeofday_f = luaL_checknumber(L, 1);
388 assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
389 int timeofday_mh = (int)(timeofday_f * 24000.0);
390 // This should be set directly in the environment but currently
391 // such changes aren't immediately sent to the clients, so call
392 // the server instead.
393 //env->setTimeOfDay(timeofday_mh);
394 getServer(L)->setTimeOfDay(timeofday_mh);
398 // minetest.get_timeofday() -> 0...1
399 int ModApiEnvMod::l_get_timeofday(lua_State *L)
404 int timeofday_mh = env->getTimeOfDay();
405 float timeofday_f = (float)timeofday_mh / 24000.0;
406 lua_pushnumber(L, timeofday_f);
411 // minetest.find_node_near(pos, radius, nodenames) -> pos or nil
412 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
413 int ModApiEnvMod::l_find_node_near(lua_State *L)
417 INodeDefManager *ndef = getServer(L)->ndef();
418 v3s16 pos = read_v3s16(L, 1);
419 int radius = luaL_checkinteger(L, 2);
420 std::set<content_t> filter;
421 if(lua_istable(L, 3)){
424 while(lua_next(L, table) != 0){
425 // key at index -2 and value at index -1
426 luaL_checktype(L, -1, LUA_TSTRING);
427 ndef->getIds(lua_tostring(L, -1), filter);
428 // removes value, keeps key for next iteration
431 } else if(lua_isstring(L, 3)){
432 ndef->getIds(lua_tostring(L, 3), filter);
435 for(int d=1; d<=radius; d++){
436 std::list<v3s16> list;
437 getFacePositions(list, d);
438 for(std::list<v3s16>::iterator i = list.begin();
439 i != list.end(); ++i){
440 v3s16 p = pos + (*i);
441 content_t c = env->getMap().getNodeNoEx(p).getContent();
442 if(filter.count(c) != 0){
451 // minetest.find_nodes_in_area(minp, maxp, nodenames) -> list of positions
452 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
453 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
457 INodeDefManager *ndef = getServer(L)->ndef();
458 v3s16 minp = read_v3s16(L, 1);
459 v3s16 maxp = read_v3s16(L, 2);
460 std::set<content_t> filter;
461 if(lua_istable(L, 3)){
464 while(lua_next(L, table) != 0){
465 // key at index -2 and value at index -1
466 luaL_checktype(L, -1, LUA_TSTRING);
467 ndef->getIds(lua_tostring(L, -1), filter);
468 // removes value, keeps key for next iteration
471 } else if(lua_isstring(L, 3)){
472 ndef->getIds(lua_tostring(L, 3), filter);
475 // Get the table insert function
476 lua_getglobal(L, "table");
477 lua_getfield(L, -1, "insert");
478 int table_insert = lua_gettop(L);
481 int table = lua_gettop(L);
482 for(s16 x=minp.X; x<=maxp.X; x++)
483 for(s16 y=minp.Y; y<=maxp.Y; y++)
484 for(s16 z=minp.Z; z<=maxp.Z; z++)
487 content_t c = env->getMap().getNodeNoEx(p).getContent();
488 if(filter.count(c) != 0){
489 lua_pushvalue(L, table_insert);
490 lua_pushvalue(L, table);
492 if(lua_pcall(L, 2, 0, 0))
493 script_error(L, "error: %s", lua_tostring(L, -1));
499 // minetest.get_perlin(seeddiff, octaves, persistence, scale)
500 // returns world-specific PerlinNoise
501 int ModApiEnvMod::l_get_perlin(lua_State *L)
505 int seeddiff = luaL_checkint(L, 1);
506 int octaves = luaL_checkint(L, 2);
507 float persistence = luaL_checknumber(L, 3);
508 float scale = luaL_checknumber(L, 4);
510 LuaPerlinNoise *n = new LuaPerlinNoise(seeddiff + int(env->getServerMap().getSeed()), octaves, persistence, scale);
511 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
512 luaL_getmetatable(L, "PerlinNoise");
513 lua_setmetatable(L, -2);
517 // minetest.get_perlin_map(noiseparams, size)
518 // returns world-specific PerlinNoiseMap
519 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
523 NoiseParams *np = read_noiseparams(L, 1);
526 v3s16 size = read_v3s16(L, 2);
528 int seed = (int)(env->getServerMap().getSeed());
529 LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(np, seed, size);
530 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
531 luaL_getmetatable(L, "PerlinNoiseMap");
532 lua_setmetatable(L, -2);
536 // minetest.clear_objects()
537 // clear all objects in the environment
538 int ModApiEnvMod::l_clear_objects(lua_State *L)
542 env->clearAllObjects();
546 // minetest.line_of_sight(pos1, pos2, stepsize) -> true/false
547 int ModApiEnvMod::l_line_of_sight(lua_State *L) {
548 float stepsize = 1.0;
552 // read position 1 from lua
553 v3f pos1 = checkFloatPos(L, 1);
554 // read position 2 from lua
555 v3f pos2 = checkFloatPos(L, 2);
556 //read step size from lua
557 if(lua_isnumber(L, 3))
558 stepsize = lua_tonumber(L, 3);
560 return (env->line_of_sight(pos1,pos2,stepsize));
563 // minetest.find_path(pos1, pos2, searchdistance,
564 // max_jump, max_drop, algorithm) -> table containing path
565 int ModApiEnvMod::l_find_path(lua_State *L)
569 v3s16 pos1 = read_v3s16(L, 1);
570 v3s16 pos2 = read_v3s16(L, 2);
571 unsigned int searchdistance = luaL_checkint(L, 3);
572 unsigned int max_jump = luaL_checkint(L, 4);
573 unsigned int max_drop = luaL_checkint(L, 5);
574 algorithm algo = A_PLAIN_NP;
575 if(! lua_isnil(L, 6)) {
576 std::string algorithm = luaL_checkstring(L,6);
578 if (algorithm == "A*")
581 if (algorithm == "Dijkstra")
585 std::vector<v3s16> path =
586 get_Path(env,pos1,pos2,searchdistance,max_jump,max_drop,algo);
591 int top = lua_gettop(L);
592 unsigned int index = 1;
593 for (std::vector<v3s16>::iterator i = path.begin(); i != path.end();i++)
595 lua_pushnumber(L,index);
597 lua_settable(L, top);
606 // minetest.spawn_tree(pos, treedef)
607 int ModApiEnvMod::l_spawn_tree(lua_State *L)
611 v3s16 p0 = read_v3s16(L, 1);
613 treegen::TreeDef tree_def;
614 std::string trunk,leaves,fruit;
615 INodeDefManager *ndef = env->getGameDef()->ndef();
617 if(lua_istable(L, 2))
619 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
620 getstringfield(L, 2, "rules_a", tree_def.rules_a);
621 getstringfield(L, 2, "rules_b", tree_def.rules_b);
622 getstringfield(L, 2, "rules_c", tree_def.rules_c);
623 getstringfield(L, 2, "rules_d", tree_def.rules_d);
624 getstringfield(L, 2, "trunk", trunk);
625 tree_def.trunknode=ndef->getId(trunk);
626 getstringfield(L, 2, "leaves", leaves);
627 tree_def.leavesnode=ndef->getId(leaves);
628 tree_def.leaves2_chance=0;
629 getstringfield(L, 2, "leaves2", leaves);
632 tree_def.leaves2node=ndef->getId(leaves);
633 getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
635 getintfield(L, 2, "angle", tree_def.angle);
636 getintfield(L, 2, "iterations", tree_def.iterations);
637 getintfield(L, 2, "random_level", tree_def.iterations_random_level);
638 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
639 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
640 tree_def.fruit_chance=0;
641 getstringfield(L, 2, "fruit", fruit);
644 tree_def.fruitnode=ndef->getId(fruit);
645 getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
647 getintfield(L, 2, "seed", tree_def.seed);
651 treegen::spawn_ltree (env, p0, ndef, tree_def);
655 bool ModApiEnvMod::Initialize(lua_State *L,int top)
660 retval &= API_FCT(set_node);
661 retval &= API_FCT(add_node);
662 retval &= API_FCT(add_item);
663 retval &= API_FCT(remove_node);
664 retval &= API_FCT(get_node);
665 retval &= API_FCT(get_node_or_nil);
666 retval &= API_FCT(get_node_light);
667 retval &= API_FCT(place_node);
668 retval &= API_FCT(dig_node);
669 retval &= API_FCT(punch_node);
670 retval &= API_FCT(add_entity);
671 retval &= API_FCT(get_meta);
672 retval &= API_FCT(get_node_timer);
673 retval &= API_FCT(get_player_by_name);
674 retval &= API_FCT(get_objects_inside_radius);
675 retval &= API_FCT(set_timeofday);
676 retval &= API_FCT(get_timeofday);
677 retval &= API_FCT(find_node_near);
678 retval &= API_FCT(find_nodes_in_area);
679 retval &= API_FCT(get_perlin);
680 retval &= API_FCT(get_perlin_map);
681 retval &= API_FCT(clear_objects);
682 retval &= API_FCT(spawn_tree);
683 retval &= API_FCT(find_path);
684 retval &= API_FCT(line_of_sight);
689 ModApiEnvMod modapienv_prototype;