]> git.lizzy.rs Git - dragonfireclient.git/blob - src/scriptapi.cpp
83efef670e62631568f124107796f831fc1fdaad
[dragonfireclient.git] / src / scriptapi.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2011 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 "scriptapi.h"
21
22 #include <iostream>
23 #include <list>
24 extern "C" {
25 #include <lua.h>
26 #include <lualib.h>
27 #include <lauxlib.h>
28 }
29
30 #include "log.h"
31 #include "server.h"
32 #include "porting.h"
33 #include "filesys.h"
34 #include "serverobject.h"
35 #include "script.h"
36 //#include "luna.h"
37 #include "luaentity_common.h"
38 #include "content_sao.h" // For LuaEntitySAO
39 #include "tooldef.h"
40 #include "nodedef.h"
41 #include "craftdef.h"
42 #include "craftitemdef.h"
43 #include "main.h" // For g_settings
44 #include "settings.h" // For accessing g_settings
45 #include "nodemetadata.h"
46 #include "mapblock.h" // For getNodeBlockPos
47 #include "content_nodemeta.h"
48 #include "utility.h"
49
50 static void stackDump(lua_State *L, std::ostream &o)
51 {
52   int i;
53   int top = lua_gettop(L);
54   for (i = 1; i <= top; i++) {  /* repeat for each level */
55         int t = lua_type(L, i);
56         switch (t) {
57
58           case LUA_TSTRING:  /* strings */
59                 o<<"\""<<lua_tostring(L, i)<<"\"";
60                 break;
61
62           case LUA_TBOOLEAN:  /* booleans */
63                 o<<(lua_toboolean(L, i) ? "true" : "false");
64                 break;
65
66           case LUA_TNUMBER:  /* numbers */ {
67                 char buf[10];
68                 snprintf(buf, 10, "%g", lua_tonumber(L, i));
69                 o<<buf;
70                 break; }
71
72           default:  /* other values */
73                 o<<lua_typename(L, t);
74                 break;
75
76         }
77         o<<" ";
78   }
79   o<<std::endl;
80 }
81
82 static void realitycheck(lua_State *L)
83 {
84         int top = lua_gettop(L);
85         if(top >= 30){
86                 dstream<<"Stack is over 30:"<<std::endl;
87                 stackDump(L, dstream);
88                 script_error(L, "Stack is over 30 (reality check)");
89         }
90 }
91
92 class StackUnroller
93 {
94 private:
95         lua_State *m_lua;
96         int m_original_top;
97 public:
98         StackUnroller(lua_State *L):
99                 m_lua(L),
100                 m_original_top(-1)
101         {
102                 m_original_top = lua_gettop(m_lua); // store stack height
103         }
104         ~StackUnroller()
105         {
106                 lua_settop(m_lua, m_original_top); // restore stack height
107         }
108 };
109
110 static v3f readFloatPos(lua_State *L, int index)
111 {
112         v3f pos;
113         luaL_checktype(L, index, LUA_TTABLE);
114         lua_getfield(L, index, "x");
115         pos.X = lua_tonumber(L, -1);
116         lua_pop(L, 1);
117         lua_getfield(L, index, "y");
118         pos.Y = lua_tonumber(L, -1);
119         lua_pop(L, 1);
120         lua_getfield(L, index, "z");
121         pos.Z = lua_tonumber(L, -1);
122         lua_pop(L, 1);
123         pos *= BS; // Scale to internal format
124         return pos;
125 }
126
127 static void pushFloatPos(lua_State *L, v3f p)
128 {
129         p /= BS;
130         lua_newtable(L);
131         lua_pushnumber(L, p.X);
132         lua_setfield(L, -2, "x");
133         lua_pushnumber(L, p.Y);
134         lua_setfield(L, -2, "y");
135         lua_pushnumber(L, p.Z);
136         lua_setfield(L, -2, "z");
137 }
138
139 static void pushpos(lua_State *L, v3s16 p)
140 {
141         lua_newtable(L);
142         lua_pushnumber(L, p.X);
143         lua_setfield(L, -2, "x");
144         lua_pushnumber(L, p.Y);
145         lua_setfield(L, -2, "y");
146         lua_pushnumber(L, p.Z);
147         lua_setfield(L, -2, "z");
148 }
149
150 static v3s16 readpos(lua_State *L, int index)
151 {
152         // Correct rounding at <0
153         v3f pf = readFloatPos(L, index);
154         return floatToInt(pf, BS);
155 }
156
157 static void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
158 {
159         lua_newtable(L);
160         lua_pushstring(L, ndef->get(n).name.c_str());
161         lua_setfield(L, -2, "name");
162         lua_pushnumber(L, n.getParam1());
163         lua_setfield(L, -2, "param1");
164         lua_pushnumber(L, n.getParam2());
165         lua_setfield(L, -2, "param2");
166 }
167
168 static MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
169 {
170         lua_getfield(L, index, "name");
171         const char *name = lua_tostring(L, -1);
172         lua_pop(L, 1);
173         u8 param1;
174         lua_getfield(L, index, "param1");
175         if(lua_isnil(L, -1))
176                 param1 = 0;
177         else
178                 param1 = lua_tonumber(L, -1);
179         lua_pop(L, 1);
180         u8 param2;
181         lua_getfield(L, index, "param2");
182         if(lua_isnil(L, -1))
183                 param2 = 0;
184         else
185                 param2 = lua_tonumber(L, -1);
186         lua_pop(L, 1);
187         return MapNode(ndef, name, param1, param2);
188 }
189
190 static video::SColor readARGB8(lua_State *L, int index)
191 {
192         video::SColor color;
193         luaL_checktype(L, index, LUA_TTABLE);
194         lua_getfield(L, index, "a");
195         if(lua_isnumber(L, -1))
196                 color.setAlpha(lua_tonumber(L, -1));
197         lua_pop(L, 1);
198         lua_getfield(L, index, "r");
199         color.setRed(lua_tonumber(L, -1));
200         lua_pop(L, 1);
201         lua_getfield(L, index, "g");
202         color.setGreen(lua_tonumber(L, -1));
203         lua_pop(L, 1);
204         lua_getfield(L, index, "b");
205         color.setBlue(lua_tonumber(L, -1));
206         lua_pop(L, 1);
207         return color;
208 }
209
210 static core::aabbox3d<f32> read_aabbox3df32(lua_State *L, int index, f32 scale)
211 {
212         core::aabbox3d<f32> box;
213         if(lua_istable(L, -1)){
214                 lua_rawgeti(L, -1, 1);
215                 box.MinEdge.X = lua_tonumber(L, -1) * scale;
216                 lua_pop(L, 1);
217                 lua_rawgeti(L, -1, 2);
218                 box.MinEdge.Y = lua_tonumber(L, -1) * scale;
219                 lua_pop(L, 1);
220                 lua_rawgeti(L, -1, 3);
221                 box.MinEdge.Z = lua_tonumber(L, -1) * scale;
222                 lua_pop(L, 1);
223                 lua_rawgeti(L, -1, 4);
224                 box.MaxEdge.X = lua_tonumber(L, -1) * scale;
225                 lua_pop(L, 1);
226                 lua_rawgeti(L, -1, 5);
227                 box.MaxEdge.Y = lua_tonumber(L, -1) * scale;
228                 lua_pop(L, 1);
229                 lua_rawgeti(L, -1, 6);
230                 box.MaxEdge.Z = lua_tonumber(L, -1) * scale;
231                 lua_pop(L, 1);
232         }
233         return box;
234 }
235
236 static v2s16 read_v2s16(lua_State *L, int index)
237 {
238         v2s16 p;
239         luaL_checktype(L, index, LUA_TTABLE);
240         lua_getfield(L, index, "x");
241         p.X = lua_tonumber(L, -1);
242         lua_pop(L, 1);
243         lua_getfield(L, index, "y");
244         p.Y = lua_tonumber(L, -1);
245         lua_pop(L, 1);
246         return p;
247 }
248
249 static v2f read_v2f(lua_State *L, int index)
250 {
251         v2f p;
252         luaL_checktype(L, index, LUA_TTABLE);
253         lua_getfield(L, index, "x");
254         p.X = lua_tonumber(L, -1);
255         lua_pop(L, 1);
256         lua_getfield(L, index, "y");
257         p.Y = lua_tonumber(L, -1);
258         lua_pop(L, 1);
259         return p;
260 }
261
262 static bool getstringfield(lua_State *L, int table,
263                 const char *fieldname, std::string &result)
264 {
265         lua_getfield(L, table, fieldname);
266         bool got = false;
267         if(lua_isstring(L, -1)){
268                 result = lua_tostring(L, -1);
269                 got = true;
270         }
271         lua_pop(L, 1);
272         return got;
273 }
274
275 static bool getintfield(lua_State *L, int table,
276                 const char *fieldname, int &result)
277 {
278         lua_getfield(L, table, fieldname);
279         bool got = false;
280         if(lua_isnumber(L, -1)){
281                 result = lua_tonumber(L, -1);
282                 got = true;
283         }
284         lua_pop(L, 1);
285         return got;
286 }
287
288 static bool getfloatfield(lua_State *L, int table,
289                 const char *fieldname, float &result)
290 {
291         lua_getfield(L, table, fieldname);
292         bool got = false;
293         if(lua_isnumber(L, -1)){
294                 result = lua_tonumber(L, -1);
295                 got = true;
296         }
297         lua_pop(L, 1);
298         return got;
299 }
300
301 static bool getboolfield(lua_State *L, int table,
302                 const char *fieldname, bool &result)
303 {
304         lua_getfield(L, table, fieldname);
305         bool got = false;
306         if(lua_isboolean(L, -1)){
307                 result = lua_toboolean(L, -1);
308                 got = true;
309         }
310         lua_pop(L, 1);
311         return got;
312 }
313
314 static std::string getstringfield_default(lua_State *L, int table,
315                 const char *fieldname, const std::string &default_)
316 {
317         std::string result = default_;
318         getstringfield(L, table, fieldname, result);
319         return result;
320 }
321
322 static int getintfield_default(lua_State *L, int table,
323                 const char *fieldname, int default_)
324 {
325         int result = default_;
326         getintfield(L, table, fieldname, result);
327         return result;
328 }
329
330 /*static float getfloatfield_default(lua_State *L, int table,
331                 const char *fieldname, float default_)
332 {
333         float result = default_;
334         getfloatfield(L, table, fieldname, result);
335         return result;
336 }*/
337
338 static bool getboolfield_default(lua_State *L, int table,
339                 const char *fieldname, bool default_)
340 {
341         bool result = default_;
342         getboolfield(L, table, fieldname, result);
343         return result;
344 }
345
346 struct EnumString
347 {
348         int num;
349         const char *str;
350 };
351
352 static bool string_to_enum(const EnumString *spec, int &result,
353                 const std::string &str)
354 {
355         const EnumString *esp = spec;
356         while(esp->str){
357                 if(str == std::string(esp->str)){
358                         result = esp->num;
359                         return true;
360                 }
361                 esp++;
362         }
363         return false;
364 }
365
366 /*static bool enum_to_string(const EnumString *spec, std::string &result,
367                 int num)
368 {
369         const EnumString *esp = spec;
370         while(esp){
371                 if(num == esp->num){
372                         result = esp->str;
373                         return true;
374                 }
375                 esp++;
376         }
377         return false;
378 }*/
379
380 static int getenumfield(lua_State *L, int table,
381                 const char *fieldname, const EnumString *spec, int default_)
382 {
383         int result = default_;
384         string_to_enum(spec, result,
385                         getstringfield_default(L, table, fieldname, ""));
386         return result;
387 }
388
389 struct EnumString es_DrawType[] =
390 {
391         {NDT_NORMAL, "normal"},
392         {NDT_AIRLIKE, "airlike"},
393         {NDT_LIQUID, "liquid"},
394         {NDT_FLOWINGLIQUID, "flowingliquid"},
395         {NDT_GLASSLIKE, "glasslike"},
396         {NDT_ALLFACES, "allfaces"},
397         {NDT_ALLFACES_OPTIONAL, "allfaces_optional"},
398         {NDT_TORCHLIKE, "torchlike"},
399         {NDT_SIGNLIKE, "signlike"},
400         {NDT_PLANTLIKE, "plantlike"},
401         {NDT_FENCELIKE, "fencelike"},
402         {NDT_RAILLIKE, "raillike"},
403         {0, NULL},
404 };
405
406 struct EnumString es_ContentParamType[] =
407 {
408         {CPT_NONE, "none"},
409         {CPT_LIGHT, "light"},
410         {CPT_MINERAL, "mineral"},
411         {CPT_FACEDIR_SIMPLE, "facedir_simple"},
412         {0, NULL},
413 };
414
415 struct EnumString es_LiquidType[] =
416 {
417         {LIQUID_NONE, "none"},
418         {LIQUID_FLOWING, "flowing"},
419         {LIQUID_SOURCE, "source"},
420         {0, NULL},
421 };
422
423 struct EnumString es_NodeBoxType[] =
424 {
425         {NODEBOX_REGULAR, "regular"},
426         {NODEBOX_FIXED, "fixed"},
427         {NODEBOX_WALLMOUNTED, "wallmounted"},
428         {0, NULL},
429 };
430
431 struct EnumString es_Diggability[] =
432 {
433         {DIGGABLE_NOT, "not"},
434         {DIGGABLE_NORMAL, "normal"},
435         {DIGGABLE_CONSTANT, "constant"},
436         {0, NULL},
437 };
438
439 /*
440         Global functions
441 */
442
443 static int l_register_nodedef_defaults(lua_State *L)
444 {
445         luaL_checktype(L, 1, LUA_TTABLE);
446
447         lua_pushvalue(L, 1); // Explicitly put parameter 1 on top of stack
448         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_nodedef_default");
449
450         return 0;
451 }
452
453 // Register new object prototype
454 // register_entity(name, prototype)
455 static int l_register_entity(lua_State *L)
456 {
457         const char *name = luaL_checkstring(L, 1);
458         infostream<<"register_entity: "<<name<<std::endl;
459         luaL_checktype(L, 2, LUA_TTABLE);
460
461         // Get minetest.registered_entities
462         lua_getglobal(L, "minetest");
463         lua_getfield(L, -1, "registered_entities");
464         luaL_checktype(L, -1, LUA_TTABLE);
465         int registered_entities = lua_gettop(L);
466         lua_pushvalue(L, 2); // Object = param 2 -> stack top
467         // registered_entities[name] = object
468         lua_setfield(L, registered_entities, name);
469         
470         // Get registered object to top of stack
471         lua_pushvalue(L, 2);
472         
473         // Set __index to point to itself
474         lua_pushvalue(L, -1);
475         lua_setfield(L, -2, "__index");
476
477         // Set metatable.__index = metatable
478         luaL_getmetatable(L, "minetest.entity");
479         lua_pushvalue(L, -1); // duplicate metatable
480         lua_setfield(L, -2, "__index");
481         // Set object metatable
482         lua_setmetatable(L, -2);
483
484         return 0; /* number of results */
485 }
486
487 class LuaABM : public ActiveBlockModifier
488 {
489 private:
490         lua_State *m_lua;
491         int m_id;
492
493         std::set<std::string> m_trigger_contents;
494         float m_trigger_interval;
495         u32 m_trigger_chance;
496 public:
497         LuaABM(lua_State *L, int id,
498                         const std::set<std::string> &trigger_contents,
499                         float trigger_interval, u32 trigger_chance):
500                 m_lua(L),
501                 m_id(id),
502                 m_trigger_contents(trigger_contents),
503                 m_trigger_interval(trigger_interval),
504                 m_trigger_chance(trigger_chance)
505         {
506         }
507         virtual std::set<std::string> getTriggerContents()
508         {
509                 return m_trigger_contents;
510         }
511         virtual float getTriggerInterval()
512         {
513                 return m_trigger_interval;
514         }
515         virtual u32 getTriggerChance()
516         {
517                 return m_trigger_chance;
518         }
519         virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n,
520                         u32 active_object_count, u32 active_object_count_wider)
521         {
522                 lua_State *L = m_lua;
523         
524                 realitycheck(L);
525                 assert(lua_checkstack(L, 20));
526                 StackUnroller stack_unroller(L);
527
528                 // Get minetest.registered_abms
529                 lua_getglobal(L, "minetest");
530                 lua_getfield(L, -1, "registered_abms");
531                 luaL_checktype(L, -1, LUA_TTABLE);
532                 int registered_abms = lua_gettop(L);
533
534                 // Get minetest.registered_abms[m_id]
535                 lua_pushnumber(L, m_id);
536                 lua_gettable(L, registered_abms);
537                 if(lua_isnil(L, -1))
538                         assert(0);
539                 
540                 // Call action
541                 luaL_checktype(L, -1, LUA_TTABLE);
542                 lua_getfield(L, -1, "action");
543                 luaL_checktype(L, -1, LUA_TFUNCTION);
544                 pushpos(L, p);
545                 pushnode(L, n, env->getGameDef()->ndef());
546                 lua_pushnumber(L, active_object_count);
547                 lua_pushnumber(L, active_object_count_wider);
548                 if(lua_pcall(L, 4, 0, 0))
549                         script_error(L, "error: %s\n", lua_tostring(L, -1));
550         }
551 };
552
553 // register_abm({...})
554 static int l_register_abm(lua_State *L)
555 {
556         infostream<<"register_abm"<<std::endl;
557         luaL_checktype(L, 1, LUA_TTABLE);
558
559         // Get minetest.registered_abms
560         lua_getglobal(L, "minetest");
561         lua_getfield(L, -1, "registered_abms");
562         luaL_checktype(L, -1, LUA_TTABLE);
563         int registered_abms = lua_gettop(L);
564
565         int id = 1;
566         // Find free id
567         for(;;){
568                 lua_pushnumber(L, id);
569                 lua_gettable(L, registered_abms);
570                 if(lua_isnil(L, -1))
571                         break;
572                 lua_pop(L, 1);
573                 id++;
574         }
575         lua_pop(L, 1);
576
577         infostream<<"register_abm: id="<<id<<std::endl;
578
579         // registered_abms[id] = spec
580         lua_pushnumber(L, id);
581         lua_pushvalue(L, 1);
582         lua_settable(L, registered_abms);
583         
584         return 0; /* number of results */
585 }
586
587 // register_tool(name, {lots of stuff})
588 static int l_register_tool(lua_State *L)
589 {
590         const char *name = luaL_checkstring(L, 1);
591         infostream<<"register_tool: "<<name<<std::endl;
592         luaL_checktype(L, 2, LUA_TTABLE);
593         int table = 2;
594
595         // Get server from registry
596         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
597         Server *server = (Server*)lua_touserdata(L, -1);
598         // And get the writable tool definition manager from the server
599         IWritableToolDefManager *tooldef =
600                         server->getWritableToolDefManager();
601         
602         ToolDefinition def;
603         
604         getstringfield(L, table, "image", def.imagename);
605         getfloatfield(L, table, "basetime", def.properties.basetime);
606         getfloatfield(L, table, "dt_weight", def.properties.dt_weight);
607         getfloatfield(L, table, "dt_crackiness", def.properties.dt_crackiness);
608         getfloatfield(L, table, "dt_crumbliness", def.properties.dt_crumbliness);
609         getfloatfield(L, table, "dt_cuttability", def.properties.dt_cuttability);
610         getfloatfield(L, table, "basedurability", def.properties.basedurability);
611         getfloatfield(L, table, "dd_weight", def.properties.dd_weight);
612         getfloatfield(L, table, "dd_crackiness", def.properties.dd_crackiness);
613         getfloatfield(L, table, "dd_crumbliness", def.properties.dd_crumbliness);
614         getfloatfield(L, table, "dd_cuttability", def.properties.dd_cuttability);
615
616         tooldef->registerTool(name, def);
617         return 0; /* number of results */
618 }
619
620 // register_craftitem(name, {lots of stuff})
621 static int l_register_craftitem(lua_State *L)
622 {
623         const char *name = luaL_checkstring(L, 1);
624         infostream<<"register_craftitem: "<<name<<std::endl;
625         luaL_checktype(L, 2, LUA_TTABLE);
626         int table = 2;
627
628         // Get server from registry
629         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
630         Server *server = (Server*)lua_touserdata(L, -1);
631         // And get the writable CraftItem definition manager from the server
632         IWritableCraftItemDefManager *craftitemdef =
633                         server->getWritableCraftItemDefManager();
634         
635         // Check if on_drop is defined
636         lua_getfield(L, table, "on_drop");
637         bool got_on_drop = !lua_isnil(L, -1);
638         lua_pop(L, 1);
639
640         // Check if on_use is defined
641         lua_getfield(L, table, "on_use");
642         bool got_on_use = !lua_isnil(L, -1);
643         lua_pop(L, 1);
644
645         CraftItemDefinition def;
646         
647         getstringfield(L, table, "image", def.imagename);
648         getstringfield(L, table, "cookresult_item", def.cookresult_item);
649         getfloatfield(L, table, "furnace_cooktime", def.furnace_cooktime);
650         getfloatfield(L, table, "furnace_burntime", def.furnace_burntime);
651         def.usable = getboolfield_default(L, table, "usable", got_on_use);
652         getboolfield(L, table, "liquids_pointable", def.liquids_pointable);
653         def.dropcount = getintfield_default(L, table, "dropcount", def.dropcount);
654         def.stack_max = getintfield_default(L, table, "stack_max", def.stack_max);
655
656         // If an on_drop callback is defined, force dropcount to 1
657         if (got_on_drop)
658                 def.dropcount = 1;
659
660         // Register it
661         craftitemdef->registerCraftItem(name, def);
662
663         lua_pushvalue(L, table);
664         scriptapi_add_craftitem(L, name);
665
666         return 0; /* number of results */
667 }
668
669 // register_node(name, {lots of stuff})
670 static int l_register_node(lua_State *L)
671 {
672         const char *name = luaL_checkstring(L, 1);
673         infostream<<"register_node: "<<name<<std::endl;
674         luaL_checktype(L, 2, LUA_TTABLE);
675         int nodedef_table = 2;
676
677         // Get server from registry
678         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
679         Server *server = (Server*)lua_touserdata(L, -1);
680         // And get the writable node definition manager from the server
681         IWritableNodeDefManager *nodedef =
682                         server->getWritableNodeDefManager();
683         
684         // Get default node definition from registry
685         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_nodedef_default");
686         int nodedef_default = lua_gettop(L);
687
688         /*
689                 Add to minetest.registered_nodes with default as metatable
690         */
691         
692         // Get the node definition table given as parameter
693         lua_pushvalue(L, nodedef_table);
694
695         // Set __index to point to itself
696         lua_pushvalue(L, -1);
697         lua_setfield(L, -2, "__index");
698
699         // Set nodedef_default as metatable for the definition
700         lua_pushvalue(L, nodedef_default);
701         lua_setmetatable(L, nodedef_table);
702         
703         // minetest.registered_nodes[name] = nodedef
704         lua_getglobal(L, "minetest");
705         lua_getfield(L, -1, "registered_nodes");
706         luaL_checktype(L, -1, LUA_TTABLE);
707         lua_pushstring(L, name);
708         lua_pushvalue(L, nodedef_table);
709         lua_settable(L, -3);
710
711         /*
712                 Create definition
713         */
714         
715         ContentFeatures f;
716
717         // Default to getting the corresponding NodeItem when dug
718         f.dug_item = std::string("NodeItem \"")+name+"\" 1";
719         
720         // Default to unknown_block.png as all textures
721         f.setAllTextures("unknown_block.png");
722
723         /*
724                 Read definiton from Lua
725         */
726
727         f.name = name;
728         
729         /* Visual definition */
730
731         f.drawtype = (NodeDrawType)getenumfield(L, nodedef_table, "drawtype", es_DrawType,
732                         NDT_NORMAL);
733         getfloatfield(L, nodedef_table, "visual_scale", f.visual_scale);
734
735         lua_getfield(L, nodedef_table, "tile_images");
736         if(lua_istable(L, -1)){
737                 int table = lua_gettop(L);
738                 lua_pushnil(L);
739                 int i = 0;
740                 while(lua_next(L, table) != 0){
741                         // key at index -2 and value at index -1
742                         if(lua_isstring(L, -1))
743                                 f.tname_tiles[i] = lua_tostring(L, -1);
744                         else
745                                 f.tname_tiles[i] = "";
746                         // removes value, keeps key for next iteration
747                         lua_pop(L, 1);
748                         i++;
749                         if(i==6){
750                                 lua_pop(L, 1);
751                                 break;
752                         }
753                 }
754                 // Copy last value to all remaining textures
755                 if(i >= 1){
756                         std::string lastname = f.tname_tiles[i-1];
757                         while(i < 6){
758                                 f.tname_tiles[i] = lastname;
759                                 i++;
760                         }
761                 }
762         }
763         lua_pop(L, 1);
764
765         getstringfield(L, nodedef_table, "inventory_image", f.tname_inventory);
766
767         lua_getfield(L, nodedef_table, "special_materials");
768         if(lua_istable(L, -1)){
769                 int table = lua_gettop(L);
770                 lua_pushnil(L);
771                 int i = 0;
772                 while(lua_next(L, table) != 0){
773                         // key at index -2 and value at index -1
774                         int smtable = lua_gettop(L);
775                         std::string tname = getstringfield_default(
776                                         L, smtable, "image", "");
777                         bool backface_culling = getboolfield_default(
778                                         L, smtable, "backface_culling", true);
779                         MaterialSpec mspec(tname, backface_culling);
780                         f.setSpecialMaterial(i, mspec);
781                         // removes value, keeps key for next iteration
782                         lua_pop(L, 1);
783                         i++;
784                         if(i==6){
785                                 lua_pop(L, 1);
786                                 break;
787                         }
788                 }
789         }
790         lua_pop(L, 1);
791
792         f.alpha = getintfield_default(L, nodedef_table, "alpha", 255);
793
794         /* Other stuff */
795         
796         lua_getfield(L, nodedef_table, "post_effect_color");
797         if(!lua_isnil(L, -1))
798                 f.post_effect_color = readARGB8(L, -1);
799         lua_pop(L, 1);
800
801         f.param_type = (ContentParamType)getenumfield(L, nodedef_table, "paramtype",
802                         es_ContentParamType, CPT_NONE);
803         
804         // True for all ground-like things like stone and mud, false for eg. trees
805         getboolfield(L, nodedef_table, "is_ground_content", f.is_ground_content);
806         getboolfield(L, nodedef_table, "light_propagates", f.light_propagates);
807         getboolfield(L, nodedef_table, "sunlight_propagates", f.sunlight_propagates);
808         // This is used for collision detection.
809         // Also for general solidness queries.
810         getboolfield(L, nodedef_table, "walkable", f.walkable);
811         // Player can point to these
812         getboolfield(L, nodedef_table, "pointable", f.pointable);
813         // Player can dig these
814         getboolfield(L, nodedef_table, "diggable", f.diggable);
815         // Player can climb these
816         getboolfield(L, nodedef_table, "climbable", f.climbable);
817         // Player can build on these
818         getboolfield(L, nodedef_table, "buildable_to", f.buildable_to);
819         // If true, param2 is set to direction when placed. Used for torches.
820         // NOTE: the direction format is quite inefficient and should be changed
821         getboolfield(L, nodedef_table, "wall_mounted", f.wall_mounted);
822         // Whether this content type often contains mineral.
823         // Used for texture atlas creation.
824         // Currently only enabled for CONTENT_STONE.
825         getboolfield(L, nodedef_table, "often_contains_mineral", f.often_contains_mineral);
826         // Inventory item string as which the node appears in inventory when dug.
827         // Mineral overrides this.
828         getstringfield(L, nodedef_table, "dug_item", f.dug_item);
829         // Extra dug item and its rarity
830         getstringfield(L, nodedef_table, "extra_dug_item", f.extra_dug_item);
831         // Usual get interval for extra dug item
832         getintfield(L, nodedef_table, "extra_dug_item_rarity", f.extra_dug_item_rarity);
833         // Metadata name of node (eg. "furnace")
834         getstringfield(L, nodedef_table, "metadata_name", f.metadata_name);
835         // Whether the node is non-liquid, source liquid or flowing liquid
836         f.liquid_type = (LiquidType)getenumfield(L, nodedef_table, "liquidtype",
837                         es_LiquidType, LIQUID_NONE);
838         // If the content is liquid, this is the flowing version of the liquid.
839         getstringfield(L, nodedef_table, "liquid_alternative_flowing",
840                         f.liquid_alternative_flowing);
841         // If the content is liquid, this is the source version of the liquid.
842         getstringfield(L, nodedef_table, "liquid_alternative_source",
843                         f.liquid_alternative_source);
844         // Viscosity for fluid flow, ranging from 1 to 7, with
845         // 1 giving almost instantaneous propagation and 7 being
846         // the slowest possible
847         f.liquid_viscosity = getintfield_default(L, nodedef_table,
848                         "liquid_viscosity", f.liquid_viscosity);
849         // Amount of light the node emits
850         f.light_source = getintfield_default(L, nodedef_table,
851                         "light_source", f.light_source);
852         f.damage_per_second = getintfield_default(L, nodedef_table,
853                         "damage_per_second", f.damage_per_second);
854         
855         lua_getfield(L, nodedef_table, "selection_box");
856         if(lua_istable(L, -1)){
857                 f.selection_box.type = (NodeBoxType)getenumfield(L, -1, "type",
858                                 es_NodeBoxType, NODEBOX_REGULAR);
859
860                 lua_getfield(L, -1, "fixed");
861                 if(lua_istable(L, -1))
862                         f.selection_box.fixed = read_aabbox3df32(L, -1, BS);
863                 lua_pop(L, 1);
864
865                 lua_getfield(L, -1, "wall_top");
866                 if(lua_istable(L, -1))
867                         f.selection_box.wall_top = read_aabbox3df32(L, -1, BS);
868                 lua_pop(L, 1);
869
870                 lua_getfield(L, -1, "wall_bottom");
871                 if(lua_istable(L, -1))
872                         f.selection_box.wall_bottom = read_aabbox3df32(L, -1, BS);
873                 lua_pop(L, 1);
874
875                 lua_getfield(L, -1, "wall_side");
876                 if(lua_istable(L, -1))
877                         f.selection_box.wall_side = read_aabbox3df32(L, -1, BS);
878                 lua_pop(L, 1);
879         }
880         lua_pop(L, 1);
881
882         lua_getfield(L, nodedef_table, "material");
883         if(lua_istable(L, -1)){
884                 f.material.diggability = (Diggability)getenumfield(L, -1, "diggability",
885                                 es_Diggability, DIGGABLE_NORMAL);
886                 
887                 getfloatfield(L, -1, "constant_time", f.material.constant_time);
888                 getfloatfield(L, -1, "weight", f.material.weight);
889                 getfloatfield(L, -1, "crackiness", f.material.crackiness);
890                 getfloatfield(L, -1, "crumbliness", f.material.crumbliness);
891                 getfloatfield(L, -1, "cuttability", f.material.cuttability);
892                 getfloatfield(L, -1, "flammability", f.material.flammability);
893         }
894         lua_pop(L, 1);
895
896         getstringfield(L, nodedef_table, "cookresult_item", f.cookresult_item);
897         getfloatfield(L, nodedef_table, "furnace_cooktime", f.furnace_cooktime);
898         getfloatfield(L, nodedef_table, "furnace_burntime", f.furnace_burntime);
899         
900         /*
901                 Register it
902         */
903         
904         nodedef->set(name, f);
905         
906         return 0; /* number of results */
907 }
908
909 // register_craft({output=item, recipe={{item00,item10},{item01,item11}})
910 static int l_register_craft(lua_State *L)
911 {
912         infostream<<"register_craft"<<std::endl;
913         luaL_checktype(L, 1, LUA_TTABLE);
914         int table0 = 1;
915
916         // Get server from registry
917         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
918         Server *server = (Server*)lua_touserdata(L, -1);
919         // And get the writable craft definition manager from the server
920         IWritableCraftDefManager *craftdef =
921                         server->getWritableCraftDefManager();
922         
923         std::string output;
924         int width = 0;
925         std::vector<std::string> input;
926
927         lua_getfield(L, table0, "output");
928         luaL_checktype(L, -1, LUA_TSTRING);
929         if(lua_isstring(L, -1))
930                 output = lua_tostring(L, -1);
931         lua_pop(L, 1);
932
933         lua_getfield(L, table0, "recipe");
934         luaL_checktype(L, -1, LUA_TTABLE);
935         if(lua_istable(L, -1)){
936                 int table1 = lua_gettop(L);
937                 lua_pushnil(L);
938                 int rowcount = 0;
939                 while(lua_next(L, table1) != 0){
940                         int colcount = 0;
941                         // key at index -2 and value at index -1
942                         luaL_checktype(L, -1, LUA_TTABLE);
943                         if(lua_istable(L, -1)){
944                                 int table2 = lua_gettop(L);
945                                 lua_pushnil(L);
946                                 while(lua_next(L, table2) != 0){
947                                         // key at index -2 and value at index -1
948                                         luaL_checktype(L, -1, LUA_TSTRING);
949                                         input.push_back(lua_tostring(L, -1));
950                                         // removes value, keeps key for next iteration
951                                         lua_pop(L, 1);
952                                         colcount++;
953                                 }
954                         }
955                         if(rowcount == 0){
956                                 width = colcount;
957                         } else {
958                                 if(colcount != width){
959                                         script_error(L, "error: %s\n", "Invalid crafting recipe");
960                                 }
961                         }
962                         // removes value, keeps key for next iteration
963                         lua_pop(L, 1);
964                         rowcount++;
965                 }
966         }
967         lua_pop(L, 1);
968
969         CraftDefinition def(output, width, input);
970         craftdef->registerCraft(def);
971
972         return 0; /* number of results */
973 }
974
975 // setting_get(name)
976 static int l_setting_get(lua_State *L)
977 {
978         const char *name = luaL_checkstring(L, 1);
979         try{
980                 std::string value = g_settings->get(name);
981                 lua_pushstring(L, value.c_str());
982         } catch(SettingNotFoundException &e){
983                 lua_pushnil(L);
984         }
985         return 1;
986 }
987
988 // setting_getbool(name)
989 static int l_setting_getbool(lua_State *L)
990 {
991         const char *name = luaL_checkstring(L, 1);
992         try{
993                 bool value = g_settings->getBool(name);
994                 lua_pushboolean(L, value);
995         } catch(SettingNotFoundException &e){
996                 lua_pushnil(L);
997         }
998         return 1;
999 }
1000
1001 // chat_send_all(text)
1002 static int l_chat_send_all(lua_State *L)
1003 {
1004         const char *text = luaL_checkstring(L, 1);
1005         // Get server from registry
1006         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
1007         Server *server = (Server*)lua_touserdata(L, -1);
1008         // Send
1009         server->notifyPlayers(narrow_to_wide(text));
1010         return 0;
1011 }
1012
1013 // chat_send_player(name, text)
1014 static int l_chat_send_player(lua_State *L)
1015 {
1016         const char *name = luaL_checkstring(L, 1);
1017         const char *text = luaL_checkstring(L, 2);
1018         // Get server from registry
1019         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
1020         Server *server = (Server*)lua_touserdata(L, -1);
1021         // Send
1022         server->notifyPlayer(name, narrow_to_wide(text));
1023         return 0;
1024 }
1025
1026 static const struct luaL_Reg minetest_f [] = {
1027         {"register_nodedef_defaults", l_register_nodedef_defaults},
1028         {"register_entity", l_register_entity},
1029         {"register_tool", l_register_tool},
1030         {"register_craftitem", l_register_craftitem},
1031         {"register_node", l_register_node},
1032         {"register_craft", l_register_craft},
1033         {"register_abm", l_register_abm},
1034         {"setting_get", l_setting_get},
1035         {"setting_getbool", l_setting_getbool},
1036         {"chat_send_all", l_chat_send_all},
1037         {"chat_send_player", l_chat_send_player},
1038         {NULL, NULL}
1039 };
1040
1041 /*
1042         LuaEntity functions
1043 */
1044
1045 static const struct luaL_Reg minetest_entity_m [] = {
1046         {NULL, NULL}
1047 };
1048
1049 /*
1050         Getters for stuff in main tables
1051 */
1052
1053 static void objectref_get(lua_State *L, u16 id)
1054 {
1055         // Get minetest.object_refs[i]
1056         lua_getglobal(L, "minetest");
1057         lua_getfield(L, -1, "object_refs");
1058         luaL_checktype(L, -1, LUA_TTABLE);
1059         lua_pushnumber(L, id);
1060         lua_gettable(L, -2);
1061         lua_remove(L, -2); // object_refs
1062         lua_remove(L, -2); // minetest
1063 }
1064
1065 static void luaentity_get(lua_State *L, u16 id)
1066 {
1067         // Get minetest.luaentities[i]
1068         lua_getglobal(L, "minetest");
1069         lua_getfield(L, -1, "luaentities");
1070         luaL_checktype(L, -1, LUA_TTABLE);
1071         lua_pushnumber(L, id);
1072         lua_gettable(L, -2);
1073         lua_remove(L, -2); // luaentities
1074         lua_remove(L, -2); // minetest
1075 }
1076
1077 /*
1078         Reference wrappers
1079 */
1080
1081 #define method(class, name) {#name, class::l_##name}
1082
1083 /*
1084         NodeMetaRef
1085 */
1086
1087 class NodeMetaRef
1088 {
1089 private:
1090         v3s16 m_p;
1091         ServerEnvironment *m_env;
1092
1093         static const char className[];
1094         static const luaL_reg methods[];
1095
1096         static NodeMetaRef *checkobject(lua_State *L, int narg)
1097         {
1098                 luaL_checktype(L, narg, LUA_TUSERDATA);
1099                 void *ud = luaL_checkudata(L, narg, className);
1100                 if(!ud) luaL_typerror(L, narg, className);
1101                 return *(NodeMetaRef**)ud;  // unbox pointer
1102         }
1103         
1104         static NodeMetadata* getmeta(NodeMetaRef *ref)
1105         {
1106                 NodeMetadata *meta = ref->m_env->getMap().getNodeMetadata(ref->m_p);
1107                 return meta;
1108         }
1109
1110         /*static IGenericNodeMetadata* getgenericmeta(NodeMetaRef *ref)
1111         {
1112                 NodeMetadata *meta = getmeta(ref);
1113                 if(meta == NULL)
1114                         return NULL;
1115                 if(meta->typeId() != NODEMETA_GENERIC)
1116                         return NULL;
1117                 return (IGenericNodeMetadata*)meta;
1118         }*/
1119
1120         static void reportMetadataChange(NodeMetaRef *ref)
1121         {
1122                 // Inform other things that the metadata has changed
1123                 v3s16 blockpos = getNodeBlockPos(ref->m_p);
1124                 MapEditEvent event;
1125                 event.type = MEET_BLOCK_NODE_METADATA_CHANGED;
1126                 event.p = blockpos;
1127                 ref->m_env->getMap().dispatchEvent(&event);
1128                 // Set the block to be saved
1129                 MapBlock *block = ref->m_env->getMap().getBlockNoCreateNoEx(blockpos);
1130                 if(block)
1131                         block->raiseModified(MOD_STATE_WRITE_NEEDED,
1132                                         "NodeMetaRef::reportMetadataChange");
1133         }
1134         
1135         // Exported functions
1136         
1137         // garbage collector
1138         static int gc_object(lua_State *L) {
1139                 NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1));
1140                 delete o;
1141                 return 0;
1142         }
1143
1144         // get_type(self)
1145         static int l_get_type(lua_State *L)
1146         {
1147                 NodeMetaRef *ref = checkobject(L, 1);
1148                 NodeMetadata *meta = getmeta(ref);
1149                 if(meta == NULL){
1150                         lua_pushnil(L);
1151                         return 1;
1152                 }
1153                 // Do it
1154                 lua_pushstring(L, meta->typeName());
1155                 return 1;
1156         }
1157
1158         // allows_text_input(self)
1159         static int l_allows_text_input(lua_State *L)
1160         {
1161                 NodeMetaRef *ref = checkobject(L, 1);
1162                 NodeMetadata *meta = getmeta(ref);
1163                 if(meta == NULL) return 0;
1164                 // Do it
1165                 lua_pushboolean(L, meta->allowsTextInput());
1166                 return 1;
1167         }
1168
1169         // set_text(self, text)
1170         static int l_set_text(lua_State *L)
1171         {
1172                 NodeMetaRef *ref = checkobject(L, 1);
1173                 NodeMetadata *meta = getmeta(ref);
1174                 if(meta == NULL) return 0;
1175                 // Do it
1176                 std::string text = lua_tostring(L, 2);
1177                 meta->setText(text);
1178                 reportMetadataChange(ref);
1179                 return 0;
1180         }
1181
1182         // get_text(self)
1183         static int l_get_text(lua_State *L)
1184         {
1185                 NodeMetaRef *ref = checkobject(L, 1);
1186                 NodeMetadata *meta = getmeta(ref);
1187                 if(meta == NULL) return 0;
1188                 // Do it
1189                 std::string text = meta->getText();
1190                 lua_pushstring(L, text.c_str());
1191                 return 1;
1192         }
1193
1194         // get_owner(self)
1195         static int l_get_owner(lua_State *L)
1196         {
1197                 NodeMetaRef *ref = checkobject(L, 1);
1198                 NodeMetadata *meta = getmeta(ref);
1199                 if(meta == NULL) return 0;
1200                 // Do it
1201                 std::string owner = meta->getOwner();
1202                 lua_pushstring(L, owner.c_str());
1203                 return 1;
1204         }
1205
1206         /* IGenericNodeMetadata interface */
1207         
1208         // set_infotext(self, text)
1209         static int l_set_infotext(lua_State *L)
1210         {
1211                 infostream<<__FUNCTION_NAME<<std::endl;
1212                 NodeMetaRef *ref = checkobject(L, 1);
1213                 NodeMetadata *meta = getmeta(ref);
1214                 if(meta == NULL) return 0;
1215                 // Do it
1216                 std::string text = lua_tostring(L, 2);
1217                 meta->setInfoText(text);
1218                 reportMetadataChange(ref);
1219                 return 0;
1220         }
1221
1222         // inventory_set_list(self, name, {item1, item2, ...})
1223         static int l_inventory_set_list(lua_State *L)
1224         {
1225                 NodeMetaRef *ref = checkobject(L, 1);
1226                 NodeMetadata *meta = getmeta(ref);
1227                 if(meta == NULL) return 0;
1228                 // Do it
1229                 Inventory *inv = meta->getInventory();
1230                 std::string name = lua_tostring(L, 2);
1231                 // If nil, delete list
1232                 if(lua_isnil(L, 3)){
1233                         inv->deleteList(name);
1234                         return 0;
1235                 }
1236                 // Otherwise set list
1237                 std::list<std::string> items;
1238                 luaL_checktype(L, 3, LUA_TTABLE);
1239                 int table = 3;
1240                 lua_pushnil(L);
1241                 infostream<<"items: ";
1242                 while(lua_next(L, table) != 0){
1243                         // key at index -2 and value at index -1
1244                         luaL_checktype(L, -1, LUA_TSTRING);
1245                         std::string itemstring = lua_tostring(L, -1);
1246                         infostream<<"\""<<itemstring<<"\" ";
1247                         items.push_back(itemstring);
1248                         // removes value, keeps key for next iteration
1249                         lua_pop(L, 1);
1250                 }
1251                 infostream<<std::endl;
1252                 InventoryList *invlist = inv->addList(name, items.size());
1253                 int index = 0;
1254                 for(std::list<std::string>::const_iterator
1255                                 i = items.begin(); i != items.end(); i++){
1256                         const std::string &itemstring = *i;
1257                         InventoryItem *newitem = NULL;
1258                         if(itemstring != "")
1259                                 newitem = InventoryItem::deSerialize(itemstring,
1260                                                 ref->m_env->getGameDef());
1261                         InventoryItem *olditem = invlist->changeItem(index, newitem);
1262                         delete olditem;
1263                         index++;
1264                 }
1265                 reportMetadataChange(ref);
1266                 return 0;
1267         }
1268
1269         // inventory_get_list(self, name)
1270         static int l_inventory_get_list(lua_State *L)
1271         {
1272                 NodeMetaRef *ref = checkobject(L, 1);
1273                 NodeMetadata *meta = getmeta(ref);
1274                 if(meta == NULL) return 0;
1275                 // Do it
1276                 Inventory *inv = meta->getInventory();
1277                 std::string name = lua_tostring(L, 2);
1278                 InventoryList *invlist = inv->getList(name);
1279                 if(invlist == NULL){
1280                         lua_pushnil(L);
1281                         return 1;
1282                 }
1283                 // Get the table insert function
1284                 lua_getglobal(L, "table");
1285                 lua_getfield(L, -1, "insert");
1286                 int table_insert = lua_gettop(L);
1287                 // Create and fill table
1288                 lua_newtable(L);
1289                 int table = lua_gettop(L);
1290                 for(u32 i=0; i<invlist->getSize(); i++){
1291                         InventoryItem *item = invlist->getItem(i);
1292                         lua_pushvalue(L, table_insert);
1293                         lua_pushvalue(L, table);
1294                         if(item == NULL){
1295                                 lua_pushnil(L);
1296                         } else {
1297                                 lua_pushstring(L, item->getItemString().c_str());
1298                         }
1299                         if(lua_pcall(L, 2, 0, 0))
1300                                 script_error(L, "error: %s\n", lua_tostring(L, -1));
1301                 }
1302                 return 1;
1303         }
1304
1305         // set_inventory_draw_spec(self, text)
1306         static int l_set_inventory_draw_spec(lua_State *L)
1307         {
1308                 NodeMetaRef *ref = checkobject(L, 1);
1309                 NodeMetadata *meta = getmeta(ref);
1310                 if(meta == NULL) return 0;
1311                 // Do it
1312                 std::string text = lua_tostring(L, 2);
1313                 meta->setInventoryDrawSpec(text);
1314                 reportMetadataChange(ref);
1315                 return 0;
1316         }
1317
1318         // set_allow_text_input(self, text)
1319         static int l_set_allow_text_input(lua_State *L)
1320         {
1321                 NodeMetaRef *ref = checkobject(L, 1);
1322                 NodeMetadata *meta = getmeta(ref);
1323                 if(meta == NULL) return 0;
1324                 // Do it
1325                 bool b = lua_toboolean(L, 2);
1326                 meta->setAllowTextInput(b);
1327                 reportMetadataChange(ref);
1328                 return 0;
1329         }
1330
1331         // set_allow_removal(self, text)
1332         static int l_set_allow_removal(lua_State *L)
1333         {
1334                 NodeMetaRef *ref = checkobject(L, 1);
1335                 NodeMetadata *meta = getmeta(ref);
1336                 if(meta == NULL) return 0;
1337                 // Do it
1338                 bool b = lua_toboolean(L, 2);
1339                 meta->setRemovalDisabled(!b);
1340                 reportMetadataChange(ref);
1341                 return 0;
1342         }
1343
1344         // set_enforce_owner(self, text)
1345         static int l_set_enforce_owner(lua_State *L)
1346         {
1347                 NodeMetaRef *ref = checkobject(L, 1);
1348                 NodeMetadata *meta = getmeta(ref);
1349                 if(meta == NULL) return 0;
1350                 // Do it
1351                 bool b = lua_toboolean(L, 2);
1352                 meta->setEnforceOwner(b);
1353                 reportMetadataChange(ref);
1354                 return 0;
1355         }
1356
1357         // is_inventory_modified(self)
1358         static int l_is_inventory_modified(lua_State *L)
1359         {
1360                 NodeMetaRef *ref = checkobject(L, 1);
1361                 NodeMetadata *meta = getmeta(ref);
1362                 if(meta == NULL) return 0;
1363                 // Do it
1364                 lua_pushboolean(L, meta->isInventoryModified());
1365                 return 1;
1366         }
1367
1368         // reset_inventory_modified(self)
1369         static int l_reset_inventory_modified(lua_State *L)
1370         {
1371                 NodeMetaRef *ref = checkobject(L, 1);
1372                 NodeMetadata *meta = getmeta(ref);
1373                 if(meta == NULL) return 0;
1374                 // Do it
1375                 meta->resetInventoryModified();
1376                 reportMetadataChange(ref);
1377                 return 0;
1378         }
1379
1380         // is_text_modified(self)
1381         static int l_is_text_modified(lua_State *L)
1382         {
1383                 NodeMetaRef *ref = checkobject(L, 1);
1384                 NodeMetadata *meta = getmeta(ref);
1385                 if(meta == NULL) return 0;
1386                 // Do it
1387                 lua_pushboolean(L, meta->isTextModified());
1388                 return 1;
1389         }
1390
1391         // reset_text_modified(self)
1392         static int l_reset_text_modified(lua_State *L)
1393         {
1394                 NodeMetaRef *ref = checkobject(L, 1);
1395                 NodeMetadata *meta = getmeta(ref);
1396                 if(meta == NULL) return 0;
1397                 // Do it
1398                 meta->resetTextModified();
1399                 reportMetadataChange(ref);
1400                 return 0;
1401         }
1402
1403         // set_string(self, name, var)
1404         static int l_set_string(lua_State *L)
1405         {
1406                 NodeMetaRef *ref = checkobject(L, 1);
1407                 NodeMetadata *meta = getmeta(ref);
1408                 if(meta == NULL) return 0;
1409                 // Do it
1410                 std::string name = lua_tostring(L, 2);
1411                 size_t len = 0;
1412                 const char *s = lua_tolstring(L, 3, &len);
1413                 std::string str(s, len);
1414                 meta->setString(name, str);
1415                 reportMetadataChange(ref);
1416                 return 0;
1417         }
1418
1419         // get_string(self, name)
1420         static int l_get_string(lua_State *L)
1421         {
1422                 NodeMetaRef *ref = checkobject(L, 1);
1423                 NodeMetadata *meta = getmeta(ref);
1424                 if(meta == NULL) return 0;
1425                 // Do it
1426                 std::string name = lua_tostring(L, 2);
1427                 std::string str = meta->getString(name);
1428                 lua_pushlstring(L, str.c_str(), str.size());
1429                 return 1;
1430         }
1431
1432 public:
1433         NodeMetaRef(v3s16 p, ServerEnvironment *env):
1434                 m_p(p),
1435                 m_env(env)
1436         {
1437         }
1438
1439         ~NodeMetaRef()
1440         {
1441         }
1442
1443         // Creates an NodeMetaRef and leaves it on top of stack
1444         // Not callable from Lua; all references are created on the C side.
1445         static void create(lua_State *L, v3s16 p, ServerEnvironment *env)
1446         {
1447                 NodeMetaRef *o = new NodeMetaRef(p, env);
1448                 //infostream<<"NodeMetaRef::create: o="<<o<<std::endl;
1449                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1450                 luaL_getmetatable(L, className);
1451                 lua_setmetatable(L, -2);
1452         }
1453
1454         static void Register(lua_State *L)
1455         {
1456                 lua_newtable(L);
1457                 int methodtable = lua_gettop(L);
1458                 luaL_newmetatable(L, className);
1459                 int metatable = lua_gettop(L);
1460
1461                 lua_pushliteral(L, "__metatable");
1462                 lua_pushvalue(L, methodtable);
1463                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
1464
1465                 lua_pushliteral(L, "__index");
1466                 lua_pushvalue(L, methodtable);
1467                 lua_settable(L, metatable);
1468
1469                 lua_pushliteral(L, "__gc");
1470                 lua_pushcfunction(L, gc_object);
1471                 lua_settable(L, metatable);
1472
1473                 lua_pop(L, 1);  // drop metatable
1474
1475                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
1476                 lua_pop(L, 1);  // drop methodtable
1477
1478                 // Cannot be created from Lua
1479                 //lua_register(L, className, create_object);
1480         }
1481 };
1482 const char NodeMetaRef::className[] = "NodeMetaRef";
1483 const luaL_reg NodeMetaRef::methods[] = {
1484         method(NodeMetaRef, get_type),
1485         method(NodeMetaRef, allows_text_input),
1486         method(NodeMetaRef, set_text),
1487         method(NodeMetaRef, get_text),
1488         method(NodeMetaRef, get_owner),
1489         method(NodeMetaRef, set_infotext),
1490         method(NodeMetaRef, inventory_set_list),
1491         method(NodeMetaRef, inventory_get_list),
1492         method(NodeMetaRef, set_inventory_draw_spec),
1493         method(NodeMetaRef, set_allow_text_input),
1494         method(NodeMetaRef, set_allow_removal),
1495         method(NodeMetaRef, set_enforce_owner),
1496         method(NodeMetaRef, is_inventory_modified),
1497         method(NodeMetaRef, reset_inventory_modified),
1498         method(NodeMetaRef, is_text_modified),
1499         method(NodeMetaRef, reset_text_modified),
1500         method(NodeMetaRef, set_string),
1501         method(NodeMetaRef, get_string),
1502         {0,0}
1503 };
1504
1505 /*
1506         EnvRef
1507 */
1508
1509 class EnvRef
1510 {
1511 private:
1512         ServerEnvironment *m_env;
1513
1514         static const char className[];
1515         static const luaL_reg methods[];
1516
1517         static EnvRef *checkobject(lua_State *L, int narg)
1518         {
1519                 luaL_checktype(L, narg, LUA_TUSERDATA);
1520                 void *ud = luaL_checkudata(L, narg, className);
1521                 if(!ud) luaL_typerror(L, narg, className);
1522                 return *(EnvRef**)ud;  // unbox pointer
1523         }
1524         
1525         // Exported functions
1526
1527         // EnvRef:add_node(pos, node)
1528         // pos = {x=num, y=num, z=num}
1529         static int l_add_node(lua_State *L)
1530         {
1531                 //infostream<<"EnvRef::l_add_node()"<<std::endl;
1532                 EnvRef *o = checkobject(L, 1);
1533                 ServerEnvironment *env = o->m_env;
1534                 if(env == NULL) return 0;
1535                 // pos
1536                 v3s16 pos = readpos(L, 2);
1537                 // content
1538                 MapNode n = readnode(L, 3, env->getGameDef()->ndef());
1539                 // Do it
1540                 bool succeeded = env->getMap().addNodeWithEvent(pos, n);
1541                 lua_pushboolean(L, succeeded);
1542                 return 1;
1543         }
1544
1545         // EnvRef:remove_node(pos)
1546         // pos = {x=num, y=num, z=num}
1547         static int l_remove_node(lua_State *L)
1548         {
1549                 //infostream<<"EnvRef::l_remove_node()"<<std::endl;
1550                 EnvRef *o = checkobject(L, 1);
1551                 ServerEnvironment *env = o->m_env;
1552                 if(env == NULL) return 0;
1553                 // pos
1554                 v3s16 pos = readpos(L, 2);
1555                 // Do it
1556                 bool succeeded = env->getMap().removeNodeWithEvent(pos);
1557                 lua_pushboolean(L, succeeded);
1558                 return 1;
1559         }
1560
1561         // EnvRef:get_node(pos)
1562         // pos = {x=num, y=num, z=num}
1563         static int l_get_node(lua_State *L)
1564         {
1565                 //infostream<<"EnvRef::l_get_node()"<<std::endl;
1566                 EnvRef *o = checkobject(L, 1);
1567                 ServerEnvironment *env = o->m_env;
1568                 if(env == NULL) return 0;
1569                 // pos
1570                 v3s16 pos = readpos(L, 2);
1571                 // Do it
1572                 MapNode n = env->getMap().getNodeNoEx(pos);
1573                 // Return node
1574                 pushnode(L, n, env->getGameDef()->ndef());
1575                 return 1;
1576         }
1577
1578         // EnvRef:add_luaentity(pos, entityname)
1579         // pos = {x=num, y=num, z=num}
1580         static int l_add_luaentity(lua_State *L)
1581         {
1582                 //infostream<<"EnvRef::l_add_luaentity()"<<std::endl;
1583                 EnvRef *o = checkobject(L, 1);
1584                 ServerEnvironment *env = o->m_env;
1585                 if(env == NULL) return 0;
1586                 // pos
1587                 v3f pos = readFloatPos(L, 2);
1588                 // content
1589                 const char *name = lua_tostring(L, 3);
1590                 // Do it
1591                 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, "");
1592                 env->addActiveObject(obj);
1593                 return 0;
1594         }
1595
1596         // EnvRef:add_item(pos, inventorystring)
1597         // pos = {x=num, y=num, z=num}
1598         static int l_add_item(lua_State *L)
1599         {
1600                 infostream<<"EnvRef::l_add_item()"<<std::endl;
1601                 EnvRef *o = checkobject(L, 1);
1602                 ServerEnvironment *env = o->m_env;
1603                 if(env == NULL) return 0;
1604                 // pos
1605                 v3f pos = readFloatPos(L, 2);
1606                 // inventorystring
1607                 const char *inventorystring = lua_tostring(L, 3);
1608                 // Do it
1609                 ServerActiveObject *obj = new ItemSAO(env, pos, inventorystring);
1610                 env->addActiveObject(obj);
1611                 return 0;
1612         }
1613
1614         // EnvRef:add_rat(pos)
1615         // pos = {x=num, y=num, z=num}
1616         static int l_add_rat(lua_State *L)
1617         {
1618                 infostream<<"EnvRef::l_add_rat()"<<std::endl;
1619                 EnvRef *o = checkobject(L, 1);
1620                 ServerEnvironment *env = o->m_env;
1621                 if(env == NULL) return 0;
1622                 // pos
1623                 v3f pos = readFloatPos(L, 2);
1624                 // Do it
1625                 ServerActiveObject *obj = new RatSAO(env, pos);
1626                 env->addActiveObject(obj);
1627                 return 0;
1628         }
1629
1630         // EnvRef:add_firefly(pos)
1631         // pos = {x=num, y=num, z=num}
1632         static int l_add_firefly(lua_State *L)
1633         {
1634                 infostream<<"EnvRef::l_add_firefly()"<<std::endl;
1635                 EnvRef *o = checkobject(L, 1);
1636                 ServerEnvironment *env = o->m_env;
1637                 if(env == NULL) return 0;
1638                 // pos
1639                 v3f pos = readFloatPos(L, 2);
1640                 // Do it
1641                 ServerActiveObject *obj = new FireflySAO(env, pos);
1642                 env->addActiveObject(obj);
1643                 return 0;
1644         }
1645
1646         // EnvRef:get_meta(pos)
1647         static int l_get_meta(lua_State *L)
1648         {
1649                 //infostream<<"EnvRef::l_get_meta()"<<std::endl;
1650                 EnvRef *o = checkobject(L, 1);
1651                 ServerEnvironment *env = o->m_env;
1652                 if(env == NULL) return 0;
1653                 // Do it
1654                 v3s16 p = readpos(L, 2);
1655                 NodeMetaRef::create(L, p, env);
1656                 return 1;
1657         }
1658
1659         static int gc_object(lua_State *L) {
1660                 EnvRef *o = *(EnvRef **)(lua_touserdata(L, 1));
1661                 delete o;
1662                 return 0;
1663         }
1664
1665 public:
1666         EnvRef(ServerEnvironment *env):
1667                 m_env(env)
1668         {
1669                 infostream<<"EnvRef created"<<std::endl;
1670         }
1671
1672         ~EnvRef()
1673         {
1674                 infostream<<"EnvRef destructing"<<std::endl;
1675         }
1676
1677         // Creates an EnvRef and leaves it on top of stack
1678         // Not callable from Lua; all references are created on the C side.
1679         static void create(lua_State *L, ServerEnvironment *env)
1680         {
1681                 EnvRef *o = new EnvRef(env);
1682                 //infostream<<"EnvRef::create: o="<<o<<std::endl;
1683                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1684                 luaL_getmetatable(L, className);
1685                 lua_setmetatable(L, -2);
1686         }
1687
1688         static void set_null(lua_State *L)
1689         {
1690                 EnvRef *o = checkobject(L, -1);
1691                 o->m_env = NULL;
1692         }
1693         
1694         static void Register(lua_State *L)
1695         {
1696                 lua_newtable(L);
1697                 int methodtable = lua_gettop(L);
1698                 luaL_newmetatable(L, className);
1699                 int metatable = lua_gettop(L);
1700
1701                 lua_pushliteral(L, "__metatable");
1702                 lua_pushvalue(L, methodtable);
1703                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
1704
1705                 lua_pushliteral(L, "__index");
1706                 lua_pushvalue(L, methodtable);
1707                 lua_settable(L, metatable);
1708
1709                 lua_pushliteral(L, "__gc");
1710                 lua_pushcfunction(L, gc_object);
1711                 lua_settable(L, metatable);
1712
1713                 lua_pop(L, 1);  // drop metatable
1714
1715                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
1716                 lua_pop(L, 1);  // drop methodtable
1717
1718                 // Cannot be created from Lua
1719                 //lua_register(L, className, create_object);
1720         }
1721 };
1722 const char EnvRef::className[] = "EnvRef";
1723 const luaL_reg EnvRef::methods[] = {
1724         method(EnvRef, add_node),
1725         method(EnvRef, remove_node),
1726         method(EnvRef, get_node),
1727         method(EnvRef, add_luaentity),
1728         method(EnvRef, add_item),
1729         method(EnvRef, add_rat),
1730         method(EnvRef, add_firefly),
1731         method(EnvRef, get_meta),
1732         {0,0}
1733 };
1734
1735 /*
1736         ObjectRef
1737 */
1738
1739 class ObjectRef
1740 {
1741 private:
1742         ServerActiveObject *m_object;
1743
1744         static const char className[];
1745         static const luaL_reg methods[];
1746
1747         static ObjectRef *checkobject(lua_State *L, int narg)
1748         {
1749                 luaL_checktype(L, narg, LUA_TUSERDATA);
1750                 void *ud = luaL_checkudata(L, narg, className);
1751                 if(!ud) luaL_typerror(L, narg, className);
1752                 return *(ObjectRef**)ud;  // unbox pointer
1753         }
1754         
1755         static ServerActiveObject* getobject(ObjectRef *ref)
1756         {
1757                 ServerActiveObject *co = ref->m_object;
1758                 return co;
1759         }
1760         
1761         static LuaEntitySAO* getluaobject(ObjectRef *ref)
1762         {
1763                 ServerActiveObject *obj = getobject(ref);
1764                 if(obj == NULL)
1765                         return NULL;
1766                 if(obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY)
1767                         return NULL;
1768                 return (LuaEntitySAO*)obj;
1769         }
1770         
1771         static ServerRemotePlayer* getplayer(ObjectRef *ref)
1772         {
1773                 ServerActiveObject *obj = getobject(ref);
1774                 if(obj == NULL)
1775                         return NULL;
1776                 if(obj->getType() != ACTIVEOBJECT_TYPE_PLAYER)
1777                         return NULL;
1778                 return static_cast<ServerRemotePlayer*>(obj);
1779         }
1780         
1781         // Exported functions
1782         
1783         // garbage collector
1784         static int gc_object(lua_State *L) {
1785                 ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1));
1786                 //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl;
1787                 delete o;
1788                 return 0;
1789         }
1790
1791         // remove(self)
1792         static int l_remove(lua_State *L)
1793         {
1794                 ObjectRef *ref = checkobject(L, 1);
1795                 ServerActiveObject *co = getobject(ref);
1796                 if(co == NULL) return 0;
1797                 infostream<<"ObjectRef::l_remove(): id="<<co->getId()<<std::endl;
1798                 co->m_removed = true;
1799                 return 0;
1800         }
1801         
1802         // getpos(self)
1803         // returns: {x=num, y=num, z=num}
1804         static int l_getpos(lua_State *L)
1805         {
1806                 ObjectRef *ref = checkobject(L, 1);
1807                 ServerActiveObject *co = getobject(ref);
1808                 if(co == NULL) return 0;
1809                 v3f pos = co->getBasePosition() / BS;
1810                 lua_newtable(L);
1811                 lua_pushnumber(L, pos.X);
1812                 lua_setfield(L, -2, "x");
1813                 lua_pushnumber(L, pos.Y);
1814                 lua_setfield(L, -2, "y");
1815                 lua_pushnumber(L, pos.Z);
1816                 lua_setfield(L, -2, "z");
1817                 return 1;
1818         }
1819         
1820         // setpos(self, pos)
1821         static int l_setpos(lua_State *L)
1822         {
1823                 ObjectRef *ref = checkobject(L, 1);
1824                 //LuaEntitySAO *co = getluaobject(ref);
1825                 ServerActiveObject *co = getobject(ref);
1826                 if(co == NULL) return 0;
1827                 // pos
1828                 v3f pos = readFloatPos(L, 2);
1829                 // Do it
1830                 co->setPos(pos);
1831                 return 0;
1832         }
1833         
1834         // moveto(self, pos, continuous=false)
1835         static int l_moveto(lua_State *L)
1836         {
1837                 ObjectRef *ref = checkobject(L, 1);
1838                 //LuaEntitySAO *co = getluaobject(ref);
1839                 ServerActiveObject *co = getobject(ref);
1840                 if(co == NULL) return 0;
1841                 // pos
1842                 v3f pos = readFloatPos(L, 2);
1843                 // continuous
1844                 bool continuous = lua_toboolean(L, 3);
1845                 // Do it
1846                 co->moveTo(pos, continuous);
1847                 return 0;
1848         }
1849
1850         // setvelocity(self, velocity)
1851         static int l_setvelocity(lua_State *L)
1852         {
1853                 ObjectRef *ref = checkobject(L, 1);
1854                 LuaEntitySAO *co = getluaobject(ref);
1855                 if(co == NULL) return 0;
1856                 // pos
1857                 v3f pos = readFloatPos(L, 2);
1858                 // Do it
1859                 co->setVelocity(pos);
1860                 return 0;
1861         }
1862         
1863         // setacceleration(self, acceleration)
1864         static int l_setacceleration(lua_State *L)
1865         {
1866                 ObjectRef *ref = checkobject(L, 1);
1867                 LuaEntitySAO *co = getluaobject(ref);
1868                 if(co == NULL) return 0;
1869                 // pos
1870                 v3f pos = readFloatPos(L, 2);
1871                 // Do it
1872                 co->setAcceleration(pos);
1873                 return 0;
1874         }
1875         
1876         // getacceleration(self)
1877         static int l_getacceleration(lua_State *L)
1878         {
1879                 ObjectRef *ref = checkobject(L, 1);
1880                 LuaEntitySAO *co = getluaobject(ref);
1881                 if(co == NULL) return 0;
1882                 // Do it
1883                 v3f v = co->getAcceleration();
1884                 pushFloatPos(L, v);
1885                 return 1;
1886         }
1887         
1888         // add_to_inventory(self, itemstring)
1889         // returns: true if item was added, false otherwise
1890         static int l_add_to_inventory(lua_State *L)
1891         {
1892                 ObjectRef *ref = checkobject(L, 1);
1893                 luaL_checkstring(L, 2);
1894                 ServerActiveObject *co = getobject(ref);
1895                 if(co == NULL) return 0;
1896                 // itemstring
1897                 const char *itemstring = lua_tostring(L, 2);
1898                 infostream<<"ObjectRef::l_add_to_inventory(): id="<<co->getId()
1899                                 <<" itemstring=\""<<itemstring<<"\""<<std::endl;
1900                 // Do it
1901                 std::istringstream is(itemstring, std::ios::binary);
1902                 ServerEnvironment *env = co->getEnv();
1903                 assert(env);
1904                 IGameDef *gamedef = env->getGameDef();
1905                 InventoryItem *item = InventoryItem::deSerialize(is, gamedef);
1906                 infostream<<"item="<<env<<std::endl;
1907                 bool fits = co->addToInventory(item);
1908                 // Return
1909                 lua_pushboolean(L, fits);
1910                 return 1;
1911         }
1912
1913         // add_to_inventory_later(self, itemstring)
1914         // returns: nil
1915         static int l_add_to_inventory_later(lua_State *L)
1916         {
1917                 ObjectRef *ref = checkobject(L, 1);
1918                 luaL_checkstring(L, 2);
1919                 ServerActiveObject *co = getobject(ref);
1920                 if(co == NULL) return 0;
1921                 // itemstring
1922                 const char *itemstring = lua_tostring(L, 2);
1923                 infostream<<"ObjectRef::l_add_to_inventory_later(): id="<<co->getId()
1924                                 <<" itemstring=\""<<itemstring<<"\""<<std::endl;
1925                 // Do it
1926                 std::istringstream is(itemstring, std::ios::binary);
1927                 ServerEnvironment *env = co->getEnv();
1928                 assert(env);
1929                 IGameDef *gamedef = env->getGameDef();
1930                 InventoryItem *item = InventoryItem::deSerialize(is, gamedef);
1931                 infostream<<"item="<<env<<std::endl;
1932                 co->addToInventoryLater(item);
1933                 // Return
1934                 return 0;
1935         }
1936
1937         // get_hp(self)
1938         // returns: number of hitpoints (2 * number of hearts)
1939         // 0 if not applicable to this type of object
1940         static int l_get_hp(lua_State *L)
1941         {
1942                 ObjectRef *ref = checkobject(L, 1);
1943                 ServerActiveObject *co = getobject(ref);
1944                 if(co == NULL) return 0;
1945                 int hp = co->getHP();
1946                 infostream<<"ObjectRef::l_get_hp(): id="<<co->getId()
1947                                 <<" hp="<<hp<<std::endl;
1948                 // Return
1949                 lua_pushnumber(L, hp);
1950                 return 1;
1951         }
1952
1953         // set_hp(self, hp)
1954         // hp = number of hitpoints (2 * number of hearts)
1955         // returns: nil
1956         static int l_set_hp(lua_State *L)
1957         {
1958                 ObjectRef *ref = checkobject(L, 1);
1959                 luaL_checknumber(L, 2);
1960                 ServerActiveObject *co = getobject(ref);
1961                 if(co == NULL) return 0;
1962                 int hp = lua_tonumber(L, 2);
1963                 infostream<<"ObjectRef::l_set_hp(): id="<<co->getId()
1964                                 <<" hp="<<hp<<std::endl;
1965                 // Do it
1966                 co->setHP(hp);
1967                 // Return
1968                 return 0;
1969         }
1970
1971         // settexturemod(self, mod)
1972         static int l_settexturemod(lua_State *L)
1973         {
1974                 ObjectRef *ref = checkobject(L, 1);
1975                 LuaEntitySAO *co = getluaobject(ref);
1976                 if(co == NULL) return 0;
1977                 // Do it
1978                 std::string mod = lua_tostring(L, 2);
1979                 co->setTextureMod(mod);
1980                 return 0;
1981         }
1982         
1983         // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2,
1984         //           select_horiz_by_yawpitch=false)
1985         static int l_setsprite(lua_State *L)
1986         {
1987                 ObjectRef *ref = checkobject(L, 1);
1988                 LuaEntitySAO *co = getluaobject(ref);
1989                 if(co == NULL) return 0;
1990                 // Do it
1991                 v2s16 p(0,0);
1992                 if(!lua_isnil(L, 2))
1993                         p = read_v2s16(L, 2);
1994                 int num_frames = 1;
1995                 if(!lua_isnil(L, 3))
1996                         num_frames = lua_tonumber(L, 3);
1997                 float framelength = 0.2;
1998                 if(!lua_isnil(L, 4))
1999                         framelength = lua_tonumber(L, 4);
2000                 bool select_horiz_by_yawpitch = false;
2001                 if(!lua_isnil(L, 5))
2002                         select_horiz_by_yawpitch = lua_toboolean(L, 5);
2003                 co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch);
2004                 return 0;
2005         }
2006         
2007 public:
2008         ObjectRef(ServerActiveObject *object):
2009                 m_object(object)
2010         {
2011                 //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl;
2012         }
2013
2014         ~ObjectRef()
2015         {
2016                 /*if(m_object)
2017                         infostream<<"ObjectRef destructing for id="
2018                                         <<m_object->getId()<<std::endl;
2019                 else
2020                         infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/
2021         }
2022
2023         // Creates an ObjectRef and leaves it on top of stack
2024         // Not callable from Lua; all references are created on the C side.
2025         static void create(lua_State *L, ServerActiveObject *object)
2026         {
2027                 ObjectRef *o = new ObjectRef(object);
2028                 //infostream<<"ObjectRef::create: o="<<o<<std::endl;
2029                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
2030                 luaL_getmetatable(L, className);
2031                 lua_setmetatable(L, -2);
2032         }
2033
2034         static void set_null(lua_State *L)
2035         {
2036                 ObjectRef *o = checkobject(L, -1);
2037                 o->m_object = NULL;
2038         }
2039         
2040         static void Register(lua_State *L)
2041         {
2042                 lua_newtable(L);
2043                 int methodtable = lua_gettop(L);
2044                 luaL_newmetatable(L, className);
2045                 int metatable = lua_gettop(L);
2046
2047                 lua_pushliteral(L, "__metatable");
2048                 lua_pushvalue(L, methodtable);
2049                 lua_settable(L, metatable);  // hide metatable from Lua getmetatable()
2050
2051                 lua_pushliteral(L, "__index");
2052                 lua_pushvalue(L, methodtable);
2053                 lua_settable(L, metatable);
2054
2055                 lua_pushliteral(L, "__gc");
2056                 lua_pushcfunction(L, gc_object);
2057                 lua_settable(L, metatable);
2058
2059                 lua_pop(L, 1);  // drop metatable
2060
2061                 luaL_openlib(L, 0, methods, 0);  // fill methodtable
2062                 lua_pop(L, 1);  // drop methodtable
2063
2064                 // Cannot be created from Lua
2065                 //lua_register(L, className, create_object);
2066         }
2067 };
2068 const char ObjectRef::className[] = "ObjectRef";
2069 const luaL_reg ObjectRef::methods[] = {
2070         method(ObjectRef, remove),
2071         method(ObjectRef, getpos),
2072         method(ObjectRef, setpos),
2073         method(ObjectRef, moveto),
2074         method(ObjectRef, setvelocity),
2075         method(ObjectRef, setacceleration),
2076         method(ObjectRef, add_to_inventory),
2077         method(ObjectRef, add_to_inventory_later),
2078         method(ObjectRef, get_hp),
2079         method(ObjectRef, set_hp),
2080         method(ObjectRef, settexturemod),
2081         method(ObjectRef, setsprite),
2082         {0,0}
2083 };
2084
2085 // Creates a new anonymous reference if id=0
2086 static void objectref_get_or_create(lua_State *L,
2087                 ServerActiveObject *cobj)
2088 {
2089         if(cobj->getId() == 0){
2090                 ObjectRef::create(L, cobj);
2091         } else {
2092                 objectref_get(L, cobj->getId());
2093         }
2094 }
2095
2096 /*
2097         Main export function
2098 */
2099
2100 void scriptapi_export(lua_State *L, Server *server)
2101 {
2102         realitycheck(L);
2103         assert(lua_checkstack(L, 20));
2104         infostream<<"scriptapi_export"<<std::endl;
2105         StackUnroller stack_unroller(L);
2106
2107         // Store server as light userdata in registry
2108         lua_pushlightuserdata(L, server);
2109         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_server");
2110
2111         // Store nil as minetest_nodedef_defaults in registry
2112         lua_pushnil(L);
2113         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_nodedef_default");
2114         
2115         // Register global functions in table minetest
2116         lua_newtable(L);
2117         luaL_register(L, NULL, minetest_f);
2118         lua_setglobal(L, "minetest");
2119         
2120         // Get the main minetest table
2121         lua_getglobal(L, "minetest");
2122
2123         // Add tables to minetest
2124         
2125         lua_newtable(L);
2126         lua_setfield(L, -2, "registered_nodes");
2127         lua_newtable(L);
2128         lua_setfield(L, -2, "registered_entities");
2129         lua_newtable(L);
2130         lua_setfield(L, -2, "registered_craftitems");
2131         lua_newtable(L);
2132         lua_setfield(L, -2, "registered_abms");
2133         
2134         lua_newtable(L);
2135         lua_setfield(L, -2, "object_refs");
2136         lua_newtable(L);
2137         lua_setfield(L, -2, "luaentities");
2138
2139         // Create entity prototype
2140         luaL_newmetatable(L, "minetest.entity");
2141         // metatable.__index = metatable
2142         lua_pushvalue(L, -1); // Duplicate metatable
2143         lua_setfield(L, -2, "__index");
2144         // Put functions in metatable
2145         luaL_register(L, NULL, minetest_entity_m);
2146         // Put other stuff in metatable
2147         
2148         // Register reference wrappers
2149         NodeMetaRef::Register(L);
2150         EnvRef::Register(L);
2151         ObjectRef::Register(L);
2152 }
2153
2154 void scriptapi_add_environment(lua_State *L, ServerEnvironment *env)
2155 {
2156         realitycheck(L);
2157         assert(lua_checkstack(L, 20));
2158         infostream<<"scriptapi_add_environment"<<std::endl;
2159         StackUnroller stack_unroller(L);
2160
2161         // Create EnvRef on stack
2162         EnvRef::create(L, env);
2163         int envref = lua_gettop(L);
2164
2165         // minetest.env = envref
2166         lua_getglobal(L, "minetest");
2167         luaL_checktype(L, -1, LUA_TTABLE);
2168         lua_pushvalue(L, envref);
2169         lua_setfield(L, -2, "env");
2170
2171         // Store environment as light userdata in registry
2172         lua_pushlightuserdata(L, env);
2173         lua_setfield(L, LUA_REGISTRYINDEX, "minetest_env");
2174
2175         /* Add ActiveBlockModifiers to environment */
2176
2177         // Get minetest.registered_abms
2178         lua_getglobal(L, "minetest");
2179         lua_getfield(L, -1, "registered_abms");
2180         luaL_checktype(L, -1, LUA_TTABLE);
2181         int registered_abms = lua_gettop(L);
2182         
2183         if(lua_istable(L, registered_abms)){
2184                 int table = lua_gettop(L);
2185                 lua_pushnil(L);
2186                 while(lua_next(L, table) != 0){
2187                         // key at index -2 and value at index -1
2188                         int id = lua_tonumber(L, -2);
2189                         int current_abm = lua_gettop(L);
2190
2191                         std::set<std::string> trigger_contents;
2192                         lua_getfield(L, current_abm, "nodenames");
2193                         if(lua_istable(L, -1)){
2194                                 int table = lua_gettop(L);
2195                                 lua_pushnil(L);
2196                                 while(lua_next(L, table) != 0){
2197                                         // key at index -2 and value at index -1
2198                                         luaL_checktype(L, -1, LUA_TSTRING);
2199                                         trigger_contents.insert(lua_tostring(L, -1));
2200                                         // removes value, keeps key for next iteration
2201                                         lua_pop(L, 1);
2202                                 }
2203                         }
2204                         lua_pop(L, 1);
2205
2206                         float trigger_interval = 10.0;
2207                         getfloatfield(L, current_abm, "interval", trigger_interval);
2208
2209                         int trigger_chance = 50;
2210                         getintfield(L, current_abm, "chance", trigger_chance);
2211
2212                         LuaABM *abm = new LuaABM(L, id, trigger_contents,
2213                                         trigger_interval, trigger_chance);
2214                         
2215                         env->addActiveBlockModifier(abm);
2216
2217                         // removes value, keeps key for next iteration
2218                         lua_pop(L, 1);
2219                 }
2220         }
2221         lua_pop(L, 1);
2222 }
2223
2224 #if 0
2225 // Dump stack top with the dump2 function
2226 static void dump2(lua_State *L, const char *name)
2227 {
2228         // Dump object (debug)
2229         lua_getglobal(L, "dump2");
2230         luaL_checktype(L, -1, LUA_TFUNCTION);
2231         lua_pushvalue(L, -2); // Get previous stack top as first parameter
2232         lua_pushstring(L, name);
2233         if(lua_pcall(L, 2, 0, 0))
2234                 script_error(L, "error: %s\n", lua_tostring(L, -1));
2235 }
2236 #endif
2237
2238 /*
2239         object_reference
2240 */
2241
2242 void scriptapi_add_object_reference(lua_State *L, ServerActiveObject *cobj)
2243 {
2244         realitycheck(L);
2245         assert(lua_checkstack(L, 20));
2246         //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl;
2247         StackUnroller stack_unroller(L);
2248
2249         // Create object on stack
2250         ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack
2251         int object = lua_gettop(L);
2252
2253         // Get minetest.object_refs table
2254         lua_getglobal(L, "minetest");
2255         lua_getfield(L, -1, "object_refs");
2256         luaL_checktype(L, -1, LUA_TTABLE);
2257         int objectstable = lua_gettop(L);
2258         
2259         // object_refs[id] = object
2260         lua_pushnumber(L, cobj->getId()); // Push id
2261         lua_pushvalue(L, object); // Copy object to top of stack
2262         lua_settable(L, objectstable);
2263 }
2264
2265 void scriptapi_rm_object_reference(lua_State *L, ServerActiveObject *cobj)
2266 {
2267         realitycheck(L);
2268         assert(lua_checkstack(L, 20));
2269         //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl;
2270         StackUnroller stack_unroller(L);
2271
2272         // Get minetest.object_refs table
2273         lua_getglobal(L, "minetest");
2274         lua_getfield(L, -1, "object_refs");
2275         luaL_checktype(L, -1, LUA_TTABLE);
2276         int objectstable = lua_gettop(L);
2277         
2278         // Get object_refs[id]
2279         lua_pushnumber(L, cobj->getId()); // Push id
2280         lua_gettable(L, objectstable);
2281         // Set object reference to NULL
2282         ObjectRef::set_null(L);
2283         lua_pop(L, 1); // pop object
2284
2285         // Set object_refs[id] = nil
2286         lua_pushnumber(L, cobj->getId()); // Push id
2287         lua_pushnil(L);
2288         lua_settable(L, objectstable);
2289 }
2290
2291 bool scriptapi_on_chat_message(lua_State *L, const std::string &name,
2292                 const std::string &message)
2293 {
2294         realitycheck(L);
2295         assert(lua_checkstack(L, 20));
2296         StackUnroller stack_unroller(L);
2297
2298         // Get minetest.registered_on_chat_messages
2299         lua_getglobal(L, "minetest");
2300         lua_getfield(L, -1, "registered_on_chat_messages");
2301         luaL_checktype(L, -1, LUA_TTABLE);
2302         int table = lua_gettop(L);
2303         // Foreach
2304         lua_pushnil(L);
2305         while(lua_next(L, table) != 0){
2306                 // key at index -2 and value at index -1
2307                 luaL_checktype(L, -1, LUA_TFUNCTION);
2308                 // Call function
2309                 lua_pushstring(L, name.c_str());
2310                 lua_pushstring(L, message.c_str());
2311                 if(lua_pcall(L, 2, 1, 0))
2312                         script_error(L, "error: %s\n", lua_tostring(L, -1));
2313                 bool ate = lua_toboolean(L, -1);
2314                 lua_pop(L, 1);
2315                 if(ate)
2316                         return true;
2317                 // value removed, keep key for next iteration
2318         }
2319         return false;
2320 }
2321
2322 /*
2323         misc
2324 */
2325
2326 void scriptapi_on_newplayer(lua_State *L, ServerActiveObject *player)
2327 {
2328         realitycheck(L);
2329         assert(lua_checkstack(L, 20));
2330         StackUnroller stack_unroller(L);
2331
2332         // Get minetest.registered_on_newplayers
2333         lua_getglobal(L, "minetest");
2334         lua_getfield(L, -1, "registered_on_newplayers");
2335         luaL_checktype(L, -1, LUA_TTABLE);
2336         int table = lua_gettop(L);
2337         // Foreach
2338         lua_pushnil(L);
2339         while(lua_next(L, table) != 0){
2340                 // key at index -2 and value at index -1
2341                 luaL_checktype(L, -1, LUA_TFUNCTION);
2342                 // Call function
2343                 objectref_get_or_create(L, player);
2344                 if(lua_pcall(L, 1, 0, 0))
2345                         script_error(L, "error: %s\n", lua_tostring(L, -1));
2346                 // value removed, keep key for next iteration
2347         }
2348 }
2349 bool scriptapi_on_respawnplayer(lua_State *L, ServerActiveObject *player)
2350 {
2351         realitycheck(L);
2352         assert(lua_checkstack(L, 20));
2353         StackUnroller stack_unroller(L);
2354
2355         bool positioning_handled_by_some = false;
2356
2357         // Get minetest.registered_on_respawnplayers
2358         lua_getglobal(L, "minetest");
2359         lua_getfield(L, -1, "registered_on_respawnplayers");
2360         luaL_checktype(L, -1, LUA_TTABLE);
2361         int table = lua_gettop(L);
2362         // Foreach
2363         lua_pushnil(L);
2364         while(lua_next(L, table) != 0){
2365                 // key at index -2 and value at index -1
2366                 luaL_checktype(L, -1, LUA_TFUNCTION);
2367                 // Call function
2368                 objectref_get_or_create(L, player);
2369                 if(lua_pcall(L, 1, 1, 0))
2370                         script_error(L, "error: %s\n", lua_tostring(L, -1));
2371                 bool positioning_handled = lua_toboolean(L, -1);
2372                 lua_pop(L, 1);
2373                 if(positioning_handled)
2374                         positioning_handled_by_some = true;
2375                 // value removed, keep key for next iteration
2376         }
2377         return positioning_handled_by_some;
2378 }
2379
2380 /*
2381         craftitem
2382 */
2383
2384 static void pushPointedThing(lua_State *L, const PointedThing& pointed)
2385 {
2386         lua_newtable(L);
2387         if(pointed.type == POINTEDTHING_NODE)
2388         {
2389                 lua_pushstring(L, "node");
2390                 lua_setfield(L, -2, "type");
2391                 pushpos(L, pointed.node_undersurface);
2392                 lua_setfield(L, -2, "under");
2393                 pushpos(L, pointed.node_abovesurface);
2394                 lua_setfield(L, -2, "above");
2395         }
2396         else if(pointed.type == POINTEDTHING_OBJECT)
2397         {
2398                 lua_pushstring(L, "object");
2399                 lua_setfield(L, -2, "type");
2400                 objectref_get(L, pointed.object_id);
2401                 lua_setfield(L, -2, "ref");
2402         }
2403         else
2404         {
2405                 lua_pushstring(L, "nothing");
2406                 lua_setfield(L, -2, "type");
2407         }
2408 }
2409
2410 void scriptapi_add_craftitem(lua_State *L, const char *name)
2411 {
2412         StackUnroller stack_unroller(L);
2413         assert(lua_gettop(L) > 0);
2414
2415         // Set minetest.registered_craftitems[name] = table on top of stack
2416         lua_getglobal(L, "minetest");
2417         lua_getfield(L, -1, "registered_craftitems");
2418         luaL_checktype(L, -1, LUA_TTABLE);
2419         lua_pushvalue(L, -3); // push another reference to the table to be registered
2420         lua_setfield(L, -2, name); // set minetest.registered_craftitems[name]
2421 }
2422
2423 static bool get_craftitem_callback(lua_State *L, const char *name,
2424                 const char *callbackname)
2425 {
2426         // Get minetest.registered_craftitems[name][callbackname]
2427         // If that is nil or on error, return false and stack is unchanged
2428         // If that is a function, returns true and pushes the
2429         // function onto the stack
2430
2431         lua_getglobal(L, "minetest");
2432         lua_getfield(L, -1, "registered_craftitems");
2433         lua_remove(L, -2);
2434         luaL_checktype(L, -1, LUA_TTABLE);
2435         lua_getfield(L, -1, name);
2436         lua_remove(L, -2);
2437         // Should be a table
2438         if(lua_type(L, -1) != LUA_TTABLE)
2439         {
2440                 errorstream<<"CraftItem name \""<<name<<"\" not defined"<<std::endl;
2441                 lua_pop(L, 1);
2442                 return false;
2443         }
2444         lua_getfield(L, -1, callbackname);
2445         lua_remove(L, -2);
2446         // Should be a function or nil
2447         if(lua_type(L, -1) == LUA_TFUNCTION)
2448         {
2449                 return true;
2450         }
2451         else if(lua_isnil(L, -1))
2452         {
2453                 lua_pop(L, 1);
2454                 return false;
2455         }
2456         else
2457         {
2458                 errorstream<<"CraftItem name \""<<name<<"\" callback \""
2459                         <<callbackname<<" is not a function"<<std::endl;
2460                 lua_pop(L, 1);
2461                 return false;
2462         }
2463 }
2464
2465 bool scriptapi_craftitem_on_drop(lua_State *L, const char *name,
2466                 ServerActiveObject *dropper, v3f pos,
2467                 bool &callback_exists)
2468 {
2469         realitycheck(L);
2470         assert(lua_checkstack(L, 20));
2471         //infostream<<"scriptapi_craftitem_on_drop"<<std::endl;
2472         StackUnroller stack_unroller(L);
2473
2474         bool result = false;
2475         callback_exists = get_craftitem_callback(L, name, "on_drop");
2476         if(callback_exists)
2477         {
2478                 // Call function
2479                 lua_pushstring(L, name);
2480                 objectref_get_or_create(L, dropper);
2481                 pushFloatPos(L, pos);
2482                 if(lua_pcall(L, 3, 1, 0))
2483                         script_error(L, "error: %s\n", lua_tostring(L, -1));
2484                 result = lua_toboolean(L, -1);
2485         }
2486         return result;
2487 }
2488
2489 bool scriptapi_craftitem_on_place_on_ground(lua_State *L, const char *name,
2490                 ServerActiveObject *placer, v3f pos,
2491                 bool &callback_exists)
2492 {
2493         realitycheck(L);
2494         assert(lua_checkstack(L, 20));
2495         //infostream<<"scriptapi_craftitem_on_place_on_ground"<<std::endl;
2496         StackUnroller stack_unroller(L);
2497
2498         bool result = false;
2499         callback_exists = get_craftitem_callback(L, name, "on_place_on_ground");
2500         if(callback_exists)
2501         {
2502                 // Call function
2503                 lua_pushstring(L, name);
2504                 objectref_get_or_create(L, placer);
2505                 pushFloatPos(L, pos);
2506                 if(lua_pcall(L, 3, 1, 0))
2507                         script_error(L, "error: %s\n", lua_tostring(L, -1));
2508                 result = lua_toboolean(L, -1);
2509         }
2510         return result;
2511 }
2512
2513 bool scriptapi_craftitem_on_use(lua_State *L, const char *name,
2514                 ServerActiveObject *user, const PointedThing& pointed,
2515                 bool &callback_exists)
2516 {
2517         realitycheck(L);
2518         assert(lua_checkstack(L, 20));
2519         //infostream<<"scriptapi_craftitem_on_use"<<std::endl;
2520         StackUnroller stack_unroller(L);
2521
2522         bool result = false;
2523         callback_exists = get_craftitem_callback(L, name, "on_use");
2524         if(callback_exists)
2525         {
2526                 // Call function
2527                 lua_pushstring(L, name);
2528                 objectref_get_or_create(L, user);
2529                 pushPointedThing(L, pointed);
2530                 if(lua_pcall(L, 3, 1, 0))
2531                         script_error(L, "error: %s\n", lua_tostring(L, -1));
2532                 result = lua_toboolean(L, -1);
2533         }
2534         return result;
2535 }
2536
2537 /*
2538         environment
2539 */
2540
2541 void scriptapi_environment_step(lua_State *L, float dtime)
2542 {
2543         realitycheck(L);
2544         assert(lua_checkstack(L, 20));
2545         //infostream<<"scriptapi_environment_step"<<std::endl;
2546         StackUnroller stack_unroller(L);
2547
2548         // Get minetest.registered_globalsteps
2549         lua_getglobal(L, "minetest");
2550         lua_getfield(L, -1, "registered_globalsteps");
2551         luaL_checktype(L, -1, LUA_TTABLE);
2552         int table = lua_gettop(L);
2553         // Foreach
2554         lua_pushnil(L);
2555         while(lua_next(L, table) != 0){
2556                 // key at index -2 and value at index -1
2557                 luaL_checktype(L, -1, LUA_TFUNCTION);
2558                 // Call function
2559                 lua_pushnumber(L, dtime);
2560                 if(lua_pcall(L, 1, 0, 0))
2561                         script_error(L, "error: %s\n", lua_tostring(L, -1));
2562                 // value removed, keep key for next iteration
2563         }
2564 }
2565
2566 void scriptapi_environment_on_placenode(lua_State *L, v3s16 p, MapNode newnode,
2567                 ServerActiveObject *placer)
2568 {
2569         realitycheck(L);
2570         assert(lua_checkstack(L, 20));
2571         //infostream<<"scriptapi_environment_on_placenode"<<std::endl;
2572         StackUnroller stack_unroller(L);
2573
2574         // Get server from registry
2575         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
2576         Server *server = (Server*)lua_touserdata(L, -1);
2577         // And get the writable node definition manager from the server
2578         IWritableNodeDefManager *ndef =
2579                         server->getWritableNodeDefManager();
2580         
2581         // Get minetest.registered_on_placenodes
2582         lua_getglobal(L, "minetest");
2583         lua_getfield(L, -1, "registered_on_placenodes");
2584         luaL_checktype(L, -1, LUA_TTABLE);
2585         int table = lua_gettop(L);
2586         // Foreach
2587         lua_pushnil(L);
2588         while(lua_next(L, table) != 0){
2589                 // key at index -2 and value at index -1
2590                 luaL_checktype(L, -1, LUA_TFUNCTION);
2591                 // Call function
2592                 pushpos(L, p);
2593                 pushnode(L, newnode, ndef);
2594                 objectref_get_or_create(L, placer);
2595                 if(lua_pcall(L, 3, 0, 0))
2596                         script_error(L, "error: %s\n", lua_tostring(L, -1));
2597                 // value removed, keep key for next iteration
2598         }
2599 }
2600
2601 void scriptapi_environment_on_dignode(lua_State *L, v3s16 p, MapNode oldnode,
2602                 ServerActiveObject *digger)
2603 {
2604         realitycheck(L);
2605         assert(lua_checkstack(L, 20));
2606         //infostream<<"scriptapi_environment_on_dignode"<<std::endl;
2607         StackUnroller stack_unroller(L);
2608
2609         // Get server from registry
2610         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
2611         Server *server = (Server*)lua_touserdata(L, -1);
2612         // And get the writable node definition manager from the server
2613         IWritableNodeDefManager *ndef =
2614                         server->getWritableNodeDefManager();
2615         
2616         // Get minetest.registered_on_dignodes
2617         lua_getglobal(L, "minetest");
2618         lua_getfield(L, -1, "registered_on_dignodes");
2619         luaL_checktype(L, -1, LUA_TTABLE);
2620         int table = lua_gettop(L);
2621         // Foreach
2622         lua_pushnil(L);
2623         while(lua_next(L, table) != 0){
2624                 // key at index -2 and value at index -1
2625                 luaL_checktype(L, -1, LUA_TFUNCTION);
2626                 // Call function
2627                 pushpos(L, p);
2628                 pushnode(L, oldnode, ndef);
2629                 objectref_get_or_create(L, digger);
2630                 if(lua_pcall(L, 3, 0, 0))
2631                         script_error(L, "error: %s\n", lua_tostring(L, -1));
2632                 // value removed, keep key for next iteration
2633         }
2634 }
2635
2636 void scriptapi_environment_on_punchnode(lua_State *L, v3s16 p, MapNode node,
2637                 ServerActiveObject *puncher)
2638 {
2639         realitycheck(L);
2640         assert(lua_checkstack(L, 20));
2641         //infostream<<"scriptapi_environment_on_punchnode"<<std::endl;
2642         StackUnroller stack_unroller(L);
2643
2644         // Get server from registry
2645         lua_getfield(L, LUA_REGISTRYINDEX, "minetest_server");
2646         Server *server = (Server*)lua_touserdata(L, -1);
2647         // And get the writable node definition manager from the server
2648         IWritableNodeDefManager *ndef =
2649                         server->getWritableNodeDefManager();
2650         
2651         // Get minetest.registered_on_punchnodes
2652         lua_getglobal(L, "minetest");
2653         lua_getfield(L, -1, "registered_on_punchnodes");
2654         luaL_checktype(L, -1, LUA_TTABLE);
2655         int table = lua_gettop(L);
2656         // Foreach
2657         lua_pushnil(L);
2658         while(lua_next(L, table) != 0){
2659                 // key at index -2 and value at index -1
2660                 luaL_checktype(L, -1, LUA_TFUNCTION);
2661                 // Call function
2662                 pushpos(L, p);
2663                 pushnode(L, node, ndef);
2664                 objectref_get_or_create(L, puncher);
2665                 if(lua_pcall(L, 3, 0, 0))
2666                         script_error(L, "error: %s\n", lua_tostring(L, -1));
2667                 // value removed, keep key for next iteration
2668         }
2669 }
2670
2671 void scriptapi_environment_on_generated(lua_State *L, v3s16 minp, v3s16 maxp)
2672 {
2673         realitycheck(L);
2674         assert(lua_checkstack(L, 20));
2675         //infostream<<"scriptapi_environment_on_generated"<<std::endl;
2676         StackUnroller stack_unroller(L);
2677
2678         // Get minetest.registered_on_generateds
2679         lua_getglobal(L, "minetest");
2680         lua_getfield(L, -1, "registered_on_generateds");
2681         luaL_checktype(L, -1, LUA_TTABLE);
2682         int table = lua_gettop(L);
2683         // Foreach
2684         lua_pushnil(L);
2685         while(lua_next(L, table) != 0){
2686                 // key at index -2 and value at index -1
2687                 luaL_checktype(L, -1, LUA_TFUNCTION);
2688                 // Call function
2689                 pushpos(L, minp);
2690                 pushpos(L, maxp);
2691                 if(lua_pcall(L, 2, 0, 0))
2692                         script_error(L, "error: %s\n", lua_tostring(L, -1));
2693                 // value removed, keep key for next iteration
2694         }
2695 }
2696
2697 /*
2698         luaentity
2699 */
2700
2701 bool scriptapi_luaentity_add(lua_State *L, u16 id, const char *name,
2702                 const std::string &staticdata)
2703 {
2704         realitycheck(L);
2705         assert(lua_checkstack(L, 20));
2706         infostream<<"scriptapi_luaentity_add: id="<<id<<" name=\""
2707                         <<name<<"\""<<std::endl;
2708         StackUnroller stack_unroller(L);
2709         
2710         // Get minetest.registered_entities[name]
2711         lua_getglobal(L, "minetest");
2712         lua_getfield(L, -1, "registered_entities");
2713         luaL_checktype(L, -1, LUA_TTABLE);
2714         lua_pushstring(L, name);
2715         lua_gettable(L, -2);
2716         // Should be a table, which we will use as a prototype
2717         //luaL_checktype(L, -1, LUA_TTABLE);
2718         if(lua_type(L, -1) != LUA_TTABLE){
2719                 errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl;
2720                 return false;
2721         }
2722         int prototype_table = lua_gettop(L);
2723         //dump2(L, "prototype_table");
2724         
2725         // Create entity object
2726         lua_newtable(L);
2727         int object = lua_gettop(L);
2728
2729         // Set object metatable
2730         lua_pushvalue(L, prototype_table);
2731         lua_setmetatable(L, -2);
2732         
2733         // Add object reference
2734         // This should be userdata with metatable ObjectRef
2735         objectref_get(L, id);
2736         luaL_checktype(L, -1, LUA_TUSERDATA);
2737         if(!luaL_checkudata(L, -1, "ObjectRef"))
2738                 luaL_typerror(L, -1, "ObjectRef");
2739         lua_setfield(L, -2, "object");
2740
2741         // minetest.luaentities[id] = object
2742         lua_getglobal(L, "minetest");
2743         lua_getfield(L, -1, "luaentities");
2744         luaL_checktype(L, -1, LUA_TTABLE);
2745         lua_pushnumber(L, id); // Push id
2746         lua_pushvalue(L, object); // Copy object to top of stack
2747         lua_settable(L, -3);
2748         
2749         // Get on_activate function
2750         lua_pushvalue(L, object);
2751         lua_getfield(L, -1, "on_activate");
2752         if(!lua_isnil(L, -1)){
2753                 luaL_checktype(L, -1, LUA_TFUNCTION);
2754                 lua_pushvalue(L, object); // self
2755                 lua_pushlstring(L, staticdata.c_str(), staticdata.size());
2756                 // Call with 2 arguments, 0 results
2757                 if(lua_pcall(L, 2, 0, 0))
2758                         script_error(L, "error running function %s:on_activate: %s\n",
2759                                         name, lua_tostring(L, -1));
2760         }
2761         
2762         return true;
2763 }
2764
2765 void scriptapi_luaentity_rm(lua_State *L, u16 id)
2766 {
2767         realitycheck(L);
2768         assert(lua_checkstack(L, 20));
2769         infostream<<"scriptapi_luaentity_rm: id="<<id<<std::endl;
2770
2771         // Get minetest.luaentities table
2772         lua_getglobal(L, "minetest");
2773         lua_getfield(L, -1, "luaentities");
2774         luaL_checktype(L, -1, LUA_TTABLE);
2775         int objectstable = lua_gettop(L);
2776         
2777         // Set luaentities[id] = nil
2778         lua_pushnumber(L, id); // Push id
2779         lua_pushnil(L);
2780         lua_settable(L, objectstable);
2781         
2782         lua_pop(L, 2); // pop luaentities, minetest
2783 }
2784
2785 std::string scriptapi_luaentity_get_staticdata(lua_State *L, u16 id)
2786 {
2787         realitycheck(L);
2788         assert(lua_checkstack(L, 20));
2789         infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl;
2790         StackUnroller stack_unroller(L);
2791
2792         // Get minetest.luaentities[id]
2793         luaentity_get(L, id);
2794         int object = lua_gettop(L);
2795         
2796         // Get get_staticdata function
2797         lua_pushvalue(L, object);
2798         lua_getfield(L, -1, "get_staticdata");
2799         if(lua_isnil(L, -1))
2800                 return "";
2801         
2802         luaL_checktype(L, -1, LUA_TFUNCTION);
2803         lua_pushvalue(L, object); // self
2804         // Call with 1 arguments, 1 results
2805         if(lua_pcall(L, 1, 1, 0))
2806                 script_error(L, "error running function get_staticdata: %s\n",
2807                                 lua_tostring(L, -1));
2808         
2809         size_t len=0;
2810         const char *s = lua_tolstring(L, -1, &len);
2811         return std::string(s, len);
2812 }
2813
2814 void scriptapi_luaentity_get_properties(lua_State *L, u16 id,
2815                 LuaEntityProperties *prop)
2816 {
2817         realitycheck(L);
2818         assert(lua_checkstack(L, 20));
2819         infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl;
2820         StackUnroller stack_unroller(L);
2821
2822         // Get minetest.luaentities[id]
2823         luaentity_get(L, id);
2824         //int object = lua_gettop(L);
2825
2826         /* Read stuff */
2827         
2828         getboolfield(L, -1, "physical", prop->physical);
2829
2830         getfloatfield(L, -1, "weight", prop->weight);
2831
2832         lua_getfield(L, -1, "collisionbox");
2833         if(lua_istable(L, -1))
2834                 prop->collisionbox = read_aabbox3df32(L, -1, 1.0);
2835         lua_pop(L, 1);
2836
2837         getstringfield(L, -1, "visual", prop->visual);
2838         
2839         lua_getfield(L, -1, "visual_size");
2840         if(lua_istable(L, -1))
2841                 prop->visual_size = read_v2f(L, -1);
2842         lua_pop(L, 1);
2843
2844         lua_getfield(L, -1, "textures");
2845         if(lua_istable(L, -1)){
2846                 prop->textures.clear();
2847                 int table = lua_gettop(L);
2848                 lua_pushnil(L);
2849                 while(lua_next(L, table) != 0){
2850                         // key at index -2 and value at index -1
2851                         if(lua_isstring(L, -1))
2852                                 prop->textures.push_back(lua_tostring(L, -1));
2853                         else
2854                                 prop->textures.push_back("");
2855                         // removes value, keeps key for next iteration
2856                         lua_pop(L, 1);
2857                 }
2858         }
2859         lua_pop(L, 1);
2860         
2861         lua_getfield(L, -1, "spritediv");
2862         if(lua_istable(L, -1))
2863                 prop->spritediv = read_v2s16(L, -1);
2864         lua_pop(L, 1);
2865
2866         lua_getfield(L, -1, "initial_sprite_basepos");
2867         if(lua_istable(L, -1))
2868                 prop->initial_sprite_basepos = read_v2s16(L, -1);
2869         lua_pop(L, 1);
2870 }
2871
2872 void scriptapi_luaentity_step(lua_State *L, u16 id, float dtime)
2873 {
2874         realitycheck(L);
2875         assert(lua_checkstack(L, 20));
2876         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
2877         StackUnroller stack_unroller(L);
2878
2879         // Get minetest.luaentities[id]
2880         luaentity_get(L, id);
2881         int object = lua_gettop(L);
2882         // State: object is at top of stack
2883         // Get step function
2884         lua_getfield(L, -1, "on_step");
2885         if(lua_isnil(L, -1))
2886                 return;
2887         luaL_checktype(L, -1, LUA_TFUNCTION);
2888         lua_pushvalue(L, object); // self
2889         lua_pushnumber(L, dtime); // dtime
2890         // Call with 2 arguments, 0 results
2891         if(lua_pcall(L, 2, 0, 0))
2892                 script_error(L, "error running function 'on_step': %s\n", lua_tostring(L, -1));
2893 }
2894
2895 // Calls entity:on_punch(ObjectRef puncher)
2896 void scriptapi_luaentity_punch(lua_State *L, u16 id,
2897                 ServerActiveObject *puncher)
2898 {
2899         realitycheck(L);
2900         assert(lua_checkstack(L, 20));
2901         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
2902         StackUnroller stack_unroller(L);
2903
2904         // Get minetest.luaentities[id]
2905         luaentity_get(L, id);
2906         int object = lua_gettop(L);
2907         // State: object is at top of stack
2908         // Get function
2909         lua_getfield(L, -1, "on_punch");
2910         if(lua_isnil(L, -1))
2911                 return;
2912         luaL_checktype(L, -1, LUA_TFUNCTION);
2913         lua_pushvalue(L, object); // self
2914         objectref_get_or_create(L, puncher); // Clicker reference
2915         // Call with 2 arguments, 0 results
2916         if(lua_pcall(L, 2, 0, 0))
2917                 script_error(L, "error running function 'on_punch': %s\n", lua_tostring(L, -1));
2918 }
2919
2920 // Calls entity:on_rightclick(ObjectRef clicker)
2921 void scriptapi_luaentity_rightclick(lua_State *L, u16 id,
2922                 ServerActiveObject *clicker)
2923 {
2924         realitycheck(L);
2925         assert(lua_checkstack(L, 20));
2926         //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl;
2927         StackUnroller stack_unroller(L);
2928
2929         // Get minetest.luaentities[id]
2930         luaentity_get(L, id);
2931         int object = lua_gettop(L);
2932         // State: object is at top of stack
2933         // Get function
2934         lua_getfield(L, -1, "on_rightclick");
2935         if(lua_isnil(L, -1))
2936                 return;
2937         luaL_checktype(L, -1, LUA_TFUNCTION);
2938         lua_pushvalue(L, object); // self
2939         objectref_get_or_create(L, clicker); // Clicker reference
2940         // Call with 2 arguments, 0 results
2941         if(lua_pcall(L, 2, 0, 0))
2942                 script_error(L, "error running function 'on_rightclick': %s\n", lua_tostring(L, -1));
2943 }
2944