]> git.lizzy.rs Git - minetest.git/blob - src/script/common/c_content.cpp
Consolidate API object code (#12728)
[minetest.git] / src / script / common / c_content.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19 #include "common/c_content.h"
20 #include "common/c_converter.h"
21 #include "common/c_types.h"
22 #include "nodedef.h"
23 #include "object_properties.h"
24 #include "collision.h"
25 #include "cpp_api/s_node.h"
26 #include "lua_api/l_object.h"
27 #include "lua_api/l_item.h"
28 #include "common/c_internal.h"
29 #include "server.h"
30 #include "log.h"
31 #include "tool.h"
32 #include "porting.h"
33 #include "mapgen/mg_schematic.h"
34 #include "noise.h"
35 #include "server/player_sao.h"
36 #include "util/pointedthing.h"
37 #include "debug.h" // For FATAL_ERROR
38 #include <json/json.h>
39
40 struct EnumString es_TileAnimationType[] =
41 {
42         {TAT_NONE, "none"},
43         {TAT_VERTICAL_FRAMES, "vertical_frames"},
44         {TAT_SHEET_2D, "sheet_2d"},
45         {0, nullptr},
46 };
47
48 /******************************************************************************/
49 void read_item_definition(lua_State* L, int index,
50                 const ItemDefinition &default_def, ItemDefinition &def)
51 {
52         if (index < 0)
53                 index = lua_gettop(L) + 1 + index;
54
55         def.type = (ItemType)getenumfield(L, index, "type",
56                         es_ItemType, ITEM_NONE);
57         getstringfield(L, index, "name", def.name);
58         getstringfield(L, index, "description", def.description);
59         getstringfield(L, index, "short_description", def.short_description);
60         getstringfield(L, index, "inventory_image", def.inventory_image);
61         getstringfield(L, index, "inventory_overlay", def.inventory_overlay);
62         getstringfield(L, index, "wield_image", def.wield_image);
63         getstringfield(L, index, "wield_overlay", def.wield_overlay);
64         getstringfield(L, index, "palette", def.palette_image);
65
66         // Read item color.
67         lua_getfield(L, index, "color");
68         read_color(L, -1, &def.color);
69         lua_pop(L, 1);
70
71         lua_getfield(L, index, "wield_scale");
72         if(lua_istable(L, -1)){
73                 def.wield_scale = check_v3f(L, -1);
74         }
75         lua_pop(L, 1);
76
77         int stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
78         def.stack_max = rangelim(stack_max, 1, U16_MAX);
79
80         lua_getfield(L, index, "on_use");
81         def.usable = lua_isfunction(L, -1);
82         lua_pop(L, 1);
83
84         getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
85
86         lua_getfield(L, index, "tool_capabilities");
87         if(lua_istable(L, -1)){
88                 def.tool_capabilities = new ToolCapabilities(
89                                 read_tool_capabilities(L, -1));
90         }
91
92         // If name is "" (hand), ensure there are ToolCapabilities
93         // because it will be looked up there whenever any other item has
94         // no ToolCapabilities
95         if (def.name.empty() && def.tool_capabilities == NULL){
96                 def.tool_capabilities = new ToolCapabilities();
97         }
98
99         lua_getfield(L, index, "groups");
100         read_groups(L, -1, def.groups);
101         lua_pop(L, 1);
102
103         lua_getfield(L, index, "sounds");
104         if (!lua_isnil(L, -1)) {
105                 luaL_checktype(L, -1, LUA_TTABLE);
106                 lua_getfield(L, -1, "place");
107                 read_soundspec(L, -1, def.sound_place);
108                 lua_pop(L, 1);
109                 lua_getfield(L, -1, "place_failed");
110                 read_soundspec(L, -1, def.sound_place_failed);
111                 lua_pop(L, 1);
112         }
113         lua_pop(L, 1);
114
115         // No, this is not a mistake. Item sounds are in "sound", node sounds in "sounds".
116         lua_getfield(L, index, "sound");
117         if (!lua_isnil(L, -1)) {
118                 luaL_checktype(L, -1, LUA_TTABLE);
119                 lua_getfield(L, -1, "punch_use");
120                 read_soundspec(L, -1, def.sound_use);
121                 lua_pop(L, 1);
122                 lua_getfield(L, -1, "punch_use_air");
123                 read_soundspec(L, -1, def.sound_use_air);
124                 lua_pop(L, 1);
125         }
126         lua_pop(L, 1);
127
128         def.range = getfloatfield_default(L, index, "range", def.range);
129
130         // Client shall immediately place this node when player places the item.
131         // Server will update the precise end result a moment later.
132         // "" = no prediction
133         getstringfield(L, index, "node_placement_prediction",
134                         def.node_placement_prediction);
135
136         getintfield(L, index, "place_param2", def.place_param2);
137 }
138
139 /******************************************************************************/
140 void push_item_definition(lua_State *L, const ItemDefinition &i)
141 {
142         lua_newtable(L);
143         lua_pushstring(L, i.name.c_str());
144         lua_setfield(L, -2, "name");
145         lua_pushstring(L, i.description.c_str());
146         lua_setfield(L, -2, "description");
147 }
148
149 void push_item_definition_full(lua_State *L, const ItemDefinition &i)
150 {
151         std::string type(es_ItemType[(int)i.type].str);
152
153         lua_newtable(L);
154         lua_pushstring(L, i.name.c_str());
155         lua_setfield(L, -2, "name");
156         lua_pushstring(L, i.description.c_str());
157         lua_setfield(L, -2, "description");
158         if (!i.short_description.empty()) {
159                 lua_pushstring(L, i.short_description.c_str());
160                 lua_setfield(L, -2, "short_description");
161         }
162         lua_pushstring(L, type.c_str());
163         lua_setfield(L, -2, "type");
164         lua_pushstring(L, i.inventory_image.c_str());
165         lua_setfield(L, -2, "inventory_image");
166         lua_pushstring(L, i.inventory_overlay.c_str());
167         lua_setfield(L, -2, "inventory_overlay");
168         lua_pushstring(L, i.wield_image.c_str());
169         lua_setfield(L, -2, "wield_image");
170         lua_pushstring(L, i.wield_overlay.c_str());
171         lua_setfield(L, -2, "wield_overlay");
172         lua_pushstring(L, i.palette_image.c_str());
173         lua_setfield(L, -2, "palette_image");
174         push_ARGB8(L, i.color);
175         lua_setfield(L, -2, "color");
176         push_v3f(L, i.wield_scale);
177         lua_setfield(L, -2, "wield_scale");
178         lua_pushinteger(L, i.stack_max);
179         lua_setfield(L, -2, "stack_max");
180         lua_pushboolean(L, i.usable);
181         lua_setfield(L, -2, "usable");
182         lua_pushboolean(L, i.liquids_pointable);
183         lua_setfield(L, -2, "liquids_pointable");
184         if (i.tool_capabilities) {
185                 push_tool_capabilities(L, *i.tool_capabilities);
186                 lua_setfield(L, -2, "tool_capabilities");
187         }
188         push_groups(L, i.groups);
189         lua_setfield(L, -2, "groups");
190         push_soundspec(L, i.sound_place);
191         lua_setfield(L, -2, "sound_place");
192         push_soundspec(L, i.sound_place_failed);
193         lua_setfield(L, -2, "sound_place_failed");
194         lua_pushstring(L, i.node_placement_prediction.c_str());
195         lua_setfield(L, -2, "node_placement_prediction");
196 }
197
198 /******************************************************************************/
199 void read_object_properties(lua_State *L, int index,
200                 ServerActiveObject *sao, ObjectProperties *prop, IItemDefManager *idef)
201 {
202         if(index < 0)
203                 index = lua_gettop(L) + 1 + index;
204         if (lua_isnil(L, index))
205                 return;
206
207         luaL_checktype(L, -1, LUA_TTABLE);
208
209         int hp_max = 0;
210         if (getintfield(L, -1, "hp_max", hp_max)) {
211                 prop->hp_max = (u16)rangelim(hp_max, 0, U16_MAX);
212                 // hp_max = 0 is sometimes used as a hack to keep players dead, only validate for entities
213                 if (prop->hp_max == 0 && sao->getType() != ACTIVEOBJECT_TYPE_PLAYER)
214                         throw LuaError("The hp_max property may not be 0 for entities!");
215
216                 if (prop->hp_max < sao->getHP()) {
217                         PlayerHPChangeReason reason(PlayerHPChangeReason::SET_HP_MAX);
218                         sao->setHP(prop->hp_max, reason);
219                 }
220         }
221
222         if (getintfield(L, -1, "breath_max", prop->breath_max)) {
223                 if (sao->getType() == ACTIVEOBJECT_TYPE_PLAYER) {
224                         PlayerSAO *player = (PlayerSAO *)sao;
225                         if (prop->breath_max < player->getBreath())
226                                 player->setBreath(prop->breath_max);
227                 }
228         }
229         getboolfield(L, -1, "physical", prop->physical);
230         getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects);
231
232         lua_getfield(L, -1, "collisionbox");
233         bool collisionbox_defined = lua_istable(L, -1);
234         if (collisionbox_defined)
235                 prop->collisionbox = read_aabb3f(L, -1, 1.0);
236         lua_pop(L, 1);
237
238         lua_getfield(L, -1, "selectionbox");
239         if (lua_istable(L, -1))
240                 prop->selectionbox = read_aabb3f(L, -1, 1.0);
241         else if (collisionbox_defined)
242                 prop->selectionbox = prop->collisionbox;
243         lua_pop(L, 1);
244
245         getboolfield(L, -1, "pointable", prop->pointable);
246         getstringfield(L, -1, "visual", prop->visual);
247
248         getstringfield(L, -1, "mesh", prop->mesh);
249
250         lua_getfield(L, -1, "visual_size");
251         if (lua_istable(L, -1)) {
252                 // Backwards compatibility: Also accept { x = ?, y = ? }
253                 v2f scale_xy = read_v2f(L, -1);
254
255                 f32 scale_z = scale_xy.X;
256                 lua_getfield(L, -1, "z");
257                 if (lua_isnumber(L, -1))
258                         scale_z = lua_tonumber(L, -1);
259                 lua_pop(L, 1);
260
261                 prop->visual_size = v3f(scale_xy.X, scale_xy.Y, scale_z);
262         }
263         lua_pop(L, 1);
264
265         lua_getfield(L, -1, "textures");
266         if(lua_istable(L, -1)){
267                 prop->textures.clear();
268                 int table = lua_gettop(L);
269                 lua_pushnil(L);
270                 while(lua_next(L, table) != 0){
271                         // key at index -2 and value at index -1
272                         if(lua_isstring(L, -1))
273                                 prop->textures.emplace_back(lua_tostring(L, -1));
274                         else
275                                 prop->textures.emplace_back("");
276                         // removes value, keeps key for next iteration
277                         lua_pop(L, 1);
278                 }
279         }
280         lua_pop(L, 1);
281
282         lua_getfield(L, -1, "colors");
283         if (lua_istable(L, -1)) {
284                 int table = lua_gettop(L);
285                 prop->colors.clear();
286                 for (lua_pushnil(L); lua_next(L, table); lua_pop(L, 1)) {
287                         video::SColor color(255, 255, 255, 255);
288                         read_color(L, -1, &color);
289                         prop->colors.push_back(color);
290                 }
291         }
292         lua_pop(L, 1);
293
294         lua_getfield(L, -1, "spritediv");
295         if(lua_istable(L, -1))
296                 prop->spritediv = read_v2s16(L, -1);
297         lua_pop(L, 1);
298
299         lua_getfield(L, -1, "initial_sprite_basepos");
300         if(lua_istable(L, -1))
301                 prop->initial_sprite_basepos = read_v2s16(L, -1);
302         lua_pop(L, 1);
303
304         getboolfield(L, -1, "is_visible", prop->is_visible);
305         getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
306         if (getfloatfield(L, -1, "stepheight", prop->stepheight))
307                 prop->stepheight *= BS;
308         getfloatfield(L, -1, "eye_height", prop->eye_height);
309
310         getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
311         lua_getfield(L, -1, "automatic_face_movement_dir");
312         if (lua_isnumber(L, -1)) {
313                 prop->automatic_face_movement_dir = true;
314                 prop->automatic_face_movement_dir_offset = luaL_checknumber(L, -1);
315         } else if (lua_isboolean(L, -1)) {
316                 prop->automatic_face_movement_dir = lua_toboolean(L, -1);
317                 prop->automatic_face_movement_dir_offset = 0.0;
318         }
319         lua_pop(L, 1);
320         getboolfield(L, -1, "backface_culling", prop->backface_culling);
321         getintfield(L, -1, "glow", prop->glow);
322
323         getstringfield(L, -1, "nametag", prop->nametag);
324         lua_getfield(L, -1, "nametag_color");
325         if (!lua_isnil(L, -1)) {
326                 video::SColor color = prop->nametag_color;
327                 if (read_color(L, -1, &color))
328                         prop->nametag_color = color;
329         }
330         lua_pop(L, 1);
331         lua_getfield(L, -1, "nametag_bgcolor");
332         if (!lua_isnil(L, -1)) {
333                 if (lua_toboolean(L, -1)) {
334                         video::SColor color;
335                         if (read_color(L, -1, &color))
336                                 prop->nametag_bgcolor = color;
337                 } else {
338                         prop->nametag_bgcolor = nullopt;
339                 }
340         }
341         lua_pop(L, 1);
342
343         lua_getfield(L, -1, "automatic_face_movement_max_rotation_per_sec");
344         if (lua_isnumber(L, -1)) {
345                 prop->automatic_face_movement_max_rotation_per_sec = luaL_checknumber(L, -1);
346         }
347         lua_pop(L, 1);
348
349         getstringfield(L, -1, "infotext", prop->infotext);
350         getboolfield(L, -1, "static_save", prop->static_save);
351
352         lua_getfield(L, -1, "wield_item");
353         if (!lua_isnil(L, -1))
354                 prop->wield_item = read_item(L, -1, idef).getItemString();
355         lua_pop(L, 1);
356
357         getfloatfield(L, -1, "zoom_fov", prop->zoom_fov);
358         getboolfield(L, -1, "use_texture_alpha", prop->use_texture_alpha);
359         getboolfield(L, -1, "shaded", prop->shaded);
360         getboolfield(L, -1, "show_on_minimap", prop->show_on_minimap);
361
362         getstringfield(L, -1, "damage_texture_modifier", prop->damage_texture_modifier);
363 }
364
365 /******************************************************************************/
366 void push_object_properties(lua_State *L, ObjectProperties *prop)
367 {
368         lua_newtable(L);
369         lua_pushnumber(L, prop->hp_max);
370         lua_setfield(L, -2, "hp_max");
371         lua_pushnumber(L, prop->breath_max);
372         lua_setfield(L, -2, "breath_max");
373         lua_pushboolean(L, prop->physical);
374         lua_setfield(L, -2, "physical");
375         lua_pushboolean(L, prop->collideWithObjects);
376         lua_setfield(L, -2, "collide_with_objects");
377         push_aabb3f(L, prop->collisionbox);
378         lua_setfield(L, -2, "collisionbox");
379         push_aabb3f(L, prop->selectionbox);
380         lua_setfield(L, -2, "selectionbox");
381         lua_pushboolean(L, prop->pointable);
382         lua_setfield(L, -2, "pointable");
383         lua_pushlstring(L, prop->visual.c_str(), prop->visual.size());
384         lua_setfield(L, -2, "visual");
385         lua_pushlstring(L, prop->mesh.c_str(), prop->mesh.size());
386         lua_setfield(L, -2, "mesh");
387         push_v3f(L, prop->visual_size);
388         lua_setfield(L, -2, "visual_size");
389
390         lua_createtable(L, prop->textures.size(), 0);
391         u16 i = 1;
392         for (const std::string &texture : prop->textures) {
393                 lua_pushlstring(L, texture.c_str(), texture.size());
394                 lua_rawseti(L, -2, i++);
395         }
396         lua_setfield(L, -2, "textures");
397
398         lua_createtable(L, prop->colors.size(), 0);
399         i = 1;
400         for (const video::SColor &color : prop->colors) {
401                 push_ARGB8(L, color);
402                 lua_rawseti(L, -2, i++);
403         }
404         lua_setfield(L, -2, "colors");
405
406         push_v2s16(L, prop->spritediv);
407         lua_setfield(L, -2, "spritediv");
408         push_v2s16(L, prop->initial_sprite_basepos);
409         lua_setfield(L, -2, "initial_sprite_basepos");
410         lua_pushboolean(L, prop->is_visible);
411         lua_setfield(L, -2, "is_visible");
412         lua_pushboolean(L, prop->makes_footstep_sound);
413         lua_setfield(L, -2, "makes_footstep_sound");
414         lua_pushnumber(L, prop->stepheight / BS);
415         lua_setfield(L, -2, "stepheight");
416         lua_pushnumber(L, prop->eye_height);
417         lua_setfield(L, -2, "eye_height");
418         lua_pushnumber(L, prop->automatic_rotate);
419         lua_setfield(L, -2, "automatic_rotate");
420         if (prop->automatic_face_movement_dir)
421                 lua_pushnumber(L, prop->automatic_face_movement_dir_offset);
422         else
423                 lua_pushboolean(L, false);
424         lua_setfield(L, -2, "automatic_face_movement_dir");
425         lua_pushboolean(L, prop->backface_culling);
426         lua_setfield(L, -2, "backface_culling");
427         lua_pushnumber(L, prop->glow);
428         lua_setfield(L, -2, "glow");
429         lua_pushlstring(L, prop->nametag.c_str(), prop->nametag.size());
430         lua_setfield(L, -2, "nametag");
431         push_ARGB8(L, prop->nametag_color);
432         lua_setfield(L, -2, "nametag_color");
433         if (prop->nametag_bgcolor) {
434                 push_ARGB8(L, prop->nametag_bgcolor.value());
435                 lua_setfield(L, -2, "nametag_bgcolor");
436         } else {
437                 lua_pushboolean(L, false);
438                 lua_setfield(L, -2, "nametag_bgcolor");
439         }
440         lua_pushnumber(L, prop->automatic_face_movement_max_rotation_per_sec);
441         lua_setfield(L, -2, "automatic_face_movement_max_rotation_per_sec");
442         lua_pushlstring(L, prop->infotext.c_str(), prop->infotext.size());
443         lua_setfield(L, -2, "infotext");
444         lua_pushboolean(L, prop->static_save);
445         lua_setfield(L, -2, "static_save");
446         lua_pushlstring(L, prop->wield_item.c_str(), prop->wield_item.size());
447         lua_setfield(L, -2, "wield_item");
448         lua_pushnumber(L, prop->zoom_fov);
449         lua_setfield(L, -2, "zoom_fov");
450         lua_pushboolean(L, prop->use_texture_alpha);
451         lua_setfield(L, -2, "use_texture_alpha");
452         lua_pushboolean(L, prop->shaded);
453         lua_setfield(L, -2, "shaded");
454         lua_pushlstring(L, prop->damage_texture_modifier.c_str(), prop->damage_texture_modifier.size());
455         lua_setfield(L, -2, "damage_texture_modifier");
456         lua_pushboolean(L, prop->show_on_minimap);
457         lua_setfield(L, -2, "show_on_minimap");
458 }
459
460 /******************************************************************************/
461 TileDef read_tiledef(lua_State *L, int index, u8 drawtype)
462 {
463         if(index < 0)
464                 index = lua_gettop(L) + 1 + index;
465
466         TileDef tiledef;
467
468         bool default_tiling = true;
469         bool default_culling = true;
470         switch (drawtype) {
471                 case NDT_PLANTLIKE:
472                 case NDT_PLANTLIKE_ROOTED:
473                 case NDT_FIRELIKE:
474                         default_tiling = false;
475                         // "break" is omitted here intentionaly, as PLANTLIKE
476                         // FIRELIKE drawtype both should default to having
477                         // backface_culling to false.
478                 case NDT_MESH:
479                 case NDT_LIQUID:
480                         default_culling = false;
481                         break;
482                 default:
483                         break;
484         }
485
486         // key at index -2 and value at index
487         if(lua_isstring(L, index)){
488                 // "default_lava.png"
489                 tiledef.name = lua_tostring(L, index);
490                 tiledef.tileable_vertical = default_tiling;
491                 tiledef.tileable_horizontal = default_tiling;
492                 tiledef.backface_culling = default_culling;
493         }
494         else if(lua_istable(L, index))
495         {
496                 // name="default_lava.png"
497                 tiledef.name.clear();
498                 getstringfield(L, index, "name", tiledef.name);
499                 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
500                 tiledef.backface_culling = getboolfield_default(
501                         L, index, "backface_culling", default_culling);
502                 tiledef.tileable_horizontal = getboolfield_default(
503                         L, index, "tileable_horizontal", default_tiling);
504                 tiledef.tileable_vertical = getboolfield_default(
505                         L, index, "tileable_vertical", default_tiling);
506                 std::string align_style;
507                 if (getstringfield(L, index, "align_style", align_style)) {
508                         if (align_style == "user")
509                                 tiledef.align_style = ALIGN_STYLE_USER_DEFINED;
510                         else if (align_style == "world")
511                                 tiledef.align_style = ALIGN_STYLE_WORLD;
512                         else
513                                 tiledef.align_style = ALIGN_STYLE_NODE;
514                 }
515                 tiledef.scale = getintfield_default(L, index, "scale", 0);
516                 // color = ...
517                 lua_getfield(L, index, "color");
518                 tiledef.has_color = read_color(L, -1, &tiledef.color);
519                 lua_pop(L, 1);
520                 // animation = {}
521                 lua_getfield(L, index, "animation");
522                 tiledef.animation = read_animation_definition(L, -1);
523                 lua_pop(L, 1);
524         }
525
526         return tiledef;
527 }
528
529 /******************************************************************************/
530 void read_content_features(lua_State *L, ContentFeatures &f, int index)
531 {
532         if(index < 0)
533                 index = lua_gettop(L) + 1 + index;
534
535         /* Cache existence of some callbacks */
536         lua_getfield(L, index, "on_construct");
537         if(!lua_isnil(L, -1)) f.has_on_construct = true;
538         lua_pop(L, 1);
539         lua_getfield(L, index, "on_destruct");
540         if(!lua_isnil(L, -1)) f.has_on_destruct = true;
541         lua_pop(L, 1);
542         lua_getfield(L, index, "after_destruct");
543         if(!lua_isnil(L, -1)) f.has_after_destruct = true;
544         lua_pop(L, 1);
545
546         lua_getfield(L, index, "on_rightclick");
547         f.rightclickable = lua_isfunction(L, -1);
548         lua_pop(L, 1);
549
550         /* Name */
551         getstringfield(L, index, "name", f.name);
552
553         /* Groups */
554         lua_getfield(L, index, "groups");
555         read_groups(L, -1, f.groups);
556         lua_pop(L, 1);
557
558         /* Visual definition */
559
560         f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype",
561                         ScriptApiNode::es_DrawType,NDT_NORMAL);
562         getfloatfield(L, index, "visual_scale", f.visual_scale);
563
564         /* Meshnode model filename */
565         getstringfield(L, index, "mesh", f.mesh);
566
567         // tiles = {}
568         lua_getfield(L, index, "tiles");
569         if(lua_istable(L, -1)){
570                 int table = lua_gettop(L);
571                 lua_pushnil(L);
572                 int i = 0;
573                 while(lua_next(L, table) != 0){
574                         // Read tiledef from value
575                         f.tiledef[i] = read_tiledef(L, -1, f.drawtype);
576                         // removes value, keeps key for next iteration
577                         lua_pop(L, 1);
578                         i++;
579                         if(i==6){
580                                 lua_pop(L, 1);
581                                 break;
582                         }
583                 }
584                 // Copy last value to all remaining textures
585                 if(i >= 1){
586                         TileDef lasttile = f.tiledef[i-1];
587                         while(i < 6){
588                                 f.tiledef[i] = lasttile;
589                                 i++;
590                         }
591                 }
592         }
593         lua_pop(L, 1);
594
595         // overlay_tiles = {}
596         lua_getfield(L, index, "overlay_tiles");
597         if (lua_istable(L, -1)) {
598                 int table = lua_gettop(L);
599                 lua_pushnil(L);
600                 int i = 0;
601                 while (lua_next(L, table) != 0) {
602                         // Read tiledef from value
603                         f.tiledef_overlay[i] = read_tiledef(L, -1, f.drawtype);
604                         // removes value, keeps key for next iteration
605                         lua_pop(L, 1);
606                         i++;
607                         if (i == 6) {
608                                 lua_pop(L, 1);
609                                 break;
610                         }
611                 }
612                 // Copy last value to all remaining textures
613                 if (i >= 1) {
614                         TileDef lasttile = f.tiledef_overlay[i - 1];
615                         while (i < 6) {
616                                 f.tiledef_overlay[i] = lasttile;
617                                 i++;
618                         }
619                 }
620         }
621         lua_pop(L, 1);
622
623         // special_tiles = {}
624         lua_getfield(L, index, "special_tiles");
625         if(lua_istable(L, -1)){
626                 int table = lua_gettop(L);
627                 lua_pushnil(L);
628                 int i = 0;
629                 while(lua_next(L, table) != 0){
630                         // Read tiledef from value
631                         f.tiledef_special[i] = read_tiledef(L, -1, f.drawtype);
632                         // removes value, keeps key for next iteration
633                         lua_pop(L, 1);
634                         i++;
635                         if(i==CF_SPECIAL_COUNT){
636                                 lua_pop(L, 1);
637                                 break;
638                         }
639                 }
640         }
641         lua_pop(L, 1);
642
643         /* alpha & use_texture_alpha */
644         // This is a bit complicated due to compatibility
645
646         f.setDefaultAlphaMode();
647
648         warn_if_field_exists(L, index, "alpha",
649                 "Obsolete, only limited compatibility provided; "
650                 "replaced by \"use_texture_alpha\"");
651         if (getintfield_default(L, index, "alpha", 255) != 255)
652                 f.alpha = ALPHAMODE_BLEND;
653
654         lua_getfield(L, index, "use_texture_alpha");
655         if (lua_isboolean(L, -1)) {
656                 warn_if_field_exists(L, index, "use_texture_alpha",
657                         "Boolean values are deprecated; use the new choices");
658                 if (lua_toboolean(L, -1))
659                         f.alpha = (f.drawtype == NDT_NORMAL) ? ALPHAMODE_CLIP : ALPHAMODE_BLEND;
660         } else if (check_field_or_nil(L, -1, LUA_TSTRING, "use_texture_alpha")) {
661                 int result = f.alpha;
662                 string_to_enum(ScriptApiNode::es_TextureAlphaMode, result,
663                                 std::string(lua_tostring(L, -1)));
664                 f.alpha = static_cast<enum AlphaMode>(result);
665         }
666         lua_pop(L, 1);
667
668         /* Other stuff */
669
670         lua_getfield(L, index, "color");
671         read_color(L, -1, &f.color);
672         lua_pop(L, 1);
673
674         getstringfield(L, index, "palette", f.palette_name);
675
676         lua_getfield(L, index, "post_effect_color");
677         read_color(L, -1, &f.post_effect_color);
678         lua_pop(L, 1);
679
680         f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
681                         ScriptApiNode::es_ContentParamType, CPT_NONE);
682         f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
683                         ScriptApiNode::es_ContentParamType2, CPT2_NONE);
684
685         if (!f.palette_name.empty() &&
686                         !(f.param_type_2 == CPT2_COLOR ||
687                         f.param_type_2 == CPT2_COLORED_FACEDIR ||
688                         f.param_type_2 == CPT2_COLORED_WALLMOUNTED ||
689                         f.param_type_2 == CPT2_COLORED_DEGROTATE ||
690                         f.param_type_2 == CPT2_COLORED_4DIR))
691                 warningstream << "Node " << f.name.c_str()
692                         << " has a palette, but not a suitable paramtype2." << std::endl;
693
694         // True for all ground-like things like stone and mud, false for eg. trees
695         getboolfield(L, index, "is_ground_content", f.is_ground_content);
696         f.light_propagates = (f.param_type == CPT_LIGHT);
697         getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
698         // This is used for collision detection.
699         // Also for general solidness queries.
700         getboolfield(L, index, "walkable", f.walkable);
701         // Player can point to these
702         getboolfield(L, index, "pointable", f.pointable);
703         // Player can dig these
704         getboolfield(L, index, "diggable", f.diggable);
705         // Player can climb these
706         getboolfield(L, index, "climbable", f.climbable);
707         // Player can build on these
708         getboolfield(L, index, "buildable_to", f.buildable_to);
709         // Liquids flow into and replace node
710         getboolfield(L, index, "floodable", f.floodable);
711         // Whether the node is non-liquid, source liquid or flowing liquid
712         f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
713                         ScriptApiNode::es_LiquidType, LIQUID_NONE);
714         // If the content is liquid, this is the flowing version of the liquid.
715         getstringfield(L, index, "liquid_alternative_flowing",
716                         f.liquid_alternative_flowing);
717         // If the content is liquid, this is the source version of the liquid.
718         getstringfield(L, index, "liquid_alternative_source",
719                         f.liquid_alternative_source);
720         // Viscosity for fluid flow, ranging from 1 to 7, with
721         // 1 giving almost instantaneous propagation and 7 being
722         // the slowest possible
723         f.liquid_viscosity = getintfield_default(L, index,
724                         "liquid_viscosity", f.liquid_viscosity);
725         // If move_resistance is not set explicitly,
726         // move_resistance is equal to liquid_viscosity
727         f.move_resistance = f.liquid_viscosity;
728         f.liquid_range = getintfield_default(L, index,
729                         "liquid_range", f.liquid_range);
730         f.leveled = getintfield_default(L, index, "leveled", f.leveled);
731         f.leveled_max = getintfield_default(L, index,
732                         "leveled_max", f.leveled_max);
733
734         getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
735         f.drowning = getintfield_default(L, index,
736                         "drowning", f.drowning);
737         // Amount of light the node emits
738         f.light_source = getintfield_default(L, index,
739                         "light_source", f.light_source);
740         if (f.light_source > LIGHT_MAX) {
741                 warningstream << "Node " << f.name.c_str()
742                         << " had greater light_source than " << LIGHT_MAX
743                         << ", it was reduced." << std::endl;
744                 f.light_source = LIGHT_MAX;
745         }
746         f.damage_per_second = getintfield_default(L, index,
747                         "damage_per_second", f.damage_per_second);
748
749         lua_getfield(L, index, "node_box");
750         if(lua_istable(L, -1))
751                 f.node_box = read_nodebox(L, -1);
752         lua_pop(L, 1);
753
754         lua_getfield(L, index, "connects_to");
755         if (lua_istable(L, -1)) {
756                 int table = lua_gettop(L);
757                 lua_pushnil(L);
758                 while (lua_next(L, table) != 0) {
759                         // Value at -1
760                         f.connects_to.emplace_back(lua_tostring(L, -1));
761                         lua_pop(L, 1);
762                 }
763         }
764         lua_pop(L, 1);
765
766         lua_getfield(L, index, "connect_sides");
767         if (lua_istable(L, -1)) {
768                 int table = lua_gettop(L);
769                 lua_pushnil(L);
770                 while (lua_next(L, table) != 0) {
771                         // Value at -1
772                         std::string side(lua_tostring(L, -1));
773                         // Note faces are flipped to make checking easier
774                         if (side == "top")
775                                 f.connect_sides |= 2;
776                         else if (side == "bottom")
777                                 f.connect_sides |= 1;
778                         else if (side == "front")
779                                 f.connect_sides |= 16;
780                         else if (side == "left")
781                                 f.connect_sides |= 32;
782                         else if (side == "back")
783                                 f.connect_sides |= 4;
784                         else if (side == "right")
785                                 f.connect_sides |= 8;
786                         else
787                                 warningstream << "Unknown value for \"connect_sides\": "
788                                         << side << std::endl;
789                         lua_pop(L, 1);
790                 }
791         }
792         lua_pop(L, 1);
793
794         lua_getfield(L, index, "selection_box");
795         if(lua_istable(L, -1))
796                 f.selection_box = read_nodebox(L, -1);
797         lua_pop(L, 1);
798
799         lua_getfield(L, index, "collision_box");
800         if(lua_istable(L, -1))
801                 f.collision_box = read_nodebox(L, -1);
802         lua_pop(L, 1);
803
804         f.waving = getintfield_default(L, index,
805                         "waving", f.waving);
806
807         // Set to true if paramtype used to be 'facedir_simple'
808         getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
809         // Set to true if wall_mounted used to be set to true
810         getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
811
812         // Sound table
813         lua_getfield(L, index, "sounds");
814         if(lua_istable(L, -1)){
815                 lua_getfield(L, -1, "footstep");
816                 read_soundspec(L, -1, f.sound_footstep);
817                 lua_pop(L, 1);
818                 lua_getfield(L, -1, "dig");
819                 read_soundspec(L, -1, f.sound_dig);
820                 lua_pop(L, 1);
821                 lua_getfield(L, -1, "dug");
822                 read_soundspec(L, -1, f.sound_dug);
823                 lua_pop(L, 1);
824         }
825         lua_pop(L, 1);
826
827         // Node immediately placed by client when node is dug
828         getstringfield(L, index, "node_dig_prediction",
829                 f.node_dig_prediction);
830
831         // How much the node slows down players, ranging from 1 to 7,
832         // the higher, the slower.
833         f.move_resistance = getintfield_default(L, index,
834                         "move_resistance", f.move_resistance);
835
836         // Whether e.g. players in this node will have liquid movement physics
837         lua_getfield(L, index, "liquid_move_physics");
838         if(lua_isboolean(L, -1)) {
839                 f.liquid_move_physics = lua_toboolean(L, -1);
840         } else if(lua_isnil(L, -1)) {
841                 f.liquid_move_physics = f.liquid_type != LIQUID_NONE;
842         } else {
843                 errorstream << "Field \"liquid_move_physics\": Invalid type!" << std::endl;
844         }
845         lua_pop(L, 1);
846 }
847
848 void push_content_features(lua_State *L, const ContentFeatures &c)
849 {
850         std::string paramtype(ScriptApiNode::es_ContentParamType[(int)c.param_type].str);
851         std::string paramtype2(ScriptApiNode::es_ContentParamType2[(int)c.param_type_2].str);
852         std::string drawtype(ScriptApiNode::es_DrawType[(int)c.drawtype].str);
853         std::string liquid_type(ScriptApiNode::es_LiquidType[(int)c.liquid_type].str);
854
855         /* Missing "tiles" because I don't see a usecase (at least not yet). */
856
857         lua_newtable(L);
858         lua_pushboolean(L, c.has_on_construct);
859         lua_setfield(L, -2, "has_on_construct");
860         lua_pushboolean(L, c.has_on_destruct);
861         lua_setfield(L, -2, "has_on_destruct");
862         lua_pushboolean(L, c.has_after_destruct);
863         lua_setfield(L, -2, "has_after_destruct");
864         lua_pushstring(L, c.name.c_str());
865         lua_setfield(L, -2, "name");
866         push_groups(L, c.groups);
867         lua_setfield(L, -2, "groups");
868         lua_pushstring(L, paramtype.c_str());
869         lua_setfield(L, -2, "paramtype");
870         lua_pushstring(L, paramtype2.c_str());
871         lua_setfield(L, -2, "paramtype2");
872         lua_pushstring(L, drawtype.c_str());
873         lua_setfield(L, -2, "drawtype");
874         if (!c.mesh.empty()) {
875                 lua_pushstring(L, c.mesh.c_str());
876                 lua_setfield(L, -2, "mesh");
877         }
878 #ifndef SERVER
879         push_ARGB8(L, c.minimap_color);       // I know this is not set-able w/ register_node,
880         lua_setfield(L, -2, "minimap_color"); // but the people need to know!
881 #endif
882         lua_pushnumber(L, c.visual_scale);
883         lua_setfield(L, -2, "visual_scale");
884         lua_pushnumber(L, c.alpha);
885         lua_setfield(L, -2, "alpha");
886         if (!c.palette_name.empty()) {
887                 push_ARGB8(L, c.color);
888                 lua_setfield(L, -2, "color");
889
890                 lua_pushstring(L, c.palette_name.c_str());
891                 lua_setfield(L, -2, "palette_name");
892
893                 push_palette(L, c.palette);
894                 lua_setfield(L, -2, "palette");
895         }
896         lua_pushnumber(L, c.waving);
897         lua_setfield(L, -2, "waving");
898         lua_pushnumber(L, c.connect_sides);
899         lua_setfield(L, -2, "connect_sides");
900
901         lua_createtable(L, c.connects_to.size(), 0);
902         u16 i = 1;
903         for (const std::string &it : c.connects_to) {
904                 lua_pushlstring(L, it.c_str(), it.size());
905                 lua_rawseti(L, -2, i++);
906         }
907         lua_setfield(L, -2, "connects_to");
908
909         push_ARGB8(L, c.post_effect_color);
910         lua_setfield(L, -2, "post_effect_color");
911         lua_pushnumber(L, c.leveled);
912         lua_setfield(L, -2, "leveled");
913         lua_pushnumber(L, c.leveled_max);
914         lua_setfield(L, -2, "leveled_max");
915         lua_pushboolean(L, c.sunlight_propagates);
916         lua_setfield(L, -2, "sunlight_propagates");
917         lua_pushnumber(L, c.light_source);
918         lua_setfield(L, -2, "light_source");
919         lua_pushboolean(L, c.is_ground_content);
920         lua_setfield(L, -2, "is_ground_content");
921         lua_pushboolean(L, c.walkable);
922         lua_setfield(L, -2, "walkable");
923         lua_pushboolean(L, c.pointable);
924         lua_setfield(L, -2, "pointable");
925         lua_pushboolean(L, c.diggable);
926         lua_setfield(L, -2, "diggable");
927         lua_pushboolean(L, c.climbable);
928         lua_setfield(L, -2, "climbable");
929         lua_pushboolean(L, c.buildable_to);
930         lua_setfield(L, -2, "buildable_to");
931         lua_pushboolean(L, c.rightclickable);
932         lua_setfield(L, -2, "rightclickable");
933         lua_pushnumber(L, c.damage_per_second);
934         lua_setfield(L, -2, "damage_per_second");
935         if (c.isLiquid()) {
936                 lua_pushstring(L, liquid_type.c_str());
937                 lua_setfield(L, -2, "liquid_type");
938                 lua_pushstring(L, c.liquid_alternative_flowing.c_str());
939                 lua_setfield(L, -2, "liquid_alternative_flowing");
940                 lua_pushstring(L, c.liquid_alternative_source.c_str());
941                 lua_setfield(L, -2, "liquid_alternative_source");
942                 lua_pushnumber(L, c.liquid_viscosity);
943                 lua_setfield(L, -2, "liquid_viscosity");
944                 lua_pushboolean(L, c.liquid_renewable);
945                 lua_setfield(L, -2, "liquid_renewable");
946                 lua_pushnumber(L, c.liquid_range);
947                 lua_setfield(L, -2, "liquid_range");
948         }
949         lua_pushnumber(L, c.drowning);
950         lua_setfield(L, -2, "drowning");
951         lua_pushboolean(L, c.floodable);
952         lua_setfield(L, -2, "floodable");
953         push_nodebox(L, c.node_box);
954         lua_setfield(L, -2, "node_box");
955         push_nodebox(L, c.selection_box);
956         lua_setfield(L, -2, "selection_box");
957         push_nodebox(L, c.collision_box);
958         lua_setfield(L, -2, "collision_box");
959         lua_newtable(L);
960         push_soundspec(L, c.sound_footstep);
961         lua_setfield(L, -2, "sound_footstep");
962         push_soundspec(L, c.sound_dig);
963         lua_setfield(L, -2, "sound_dig");
964         push_soundspec(L, c.sound_dug);
965         lua_setfield(L, -2, "sound_dug");
966         lua_setfield(L, -2, "sounds");
967         lua_pushboolean(L, c.legacy_facedir_simple);
968         lua_setfield(L, -2, "legacy_facedir_simple");
969         lua_pushboolean(L, c.legacy_wallmounted);
970         lua_setfield(L, -2, "legacy_wallmounted");
971         lua_pushstring(L, c.node_dig_prediction.c_str());
972         lua_setfield(L, -2, "node_dig_prediction");
973         lua_pushnumber(L, c.move_resistance);
974         lua_setfield(L, -2, "move_resistance");
975         lua_pushboolean(L, c.liquid_move_physics);
976         lua_setfield(L, -2, "liquid_move_physics");
977 }
978
979 /******************************************************************************/
980 void push_nodebox(lua_State *L, const NodeBox &box)
981 {
982         lua_newtable(L);
983         switch (box.type)
984         {
985                 case NODEBOX_REGULAR:
986                         lua_pushstring(L, "regular");
987                         lua_setfield(L, -2, "type");
988                         break;
989                 case NODEBOX_LEVELED:
990                 case NODEBOX_FIXED:
991                         lua_pushstring(L, "fixed");
992                         lua_setfield(L, -2, "type");
993                         push_box(L, box.fixed);
994                         lua_setfield(L, -2, "fixed");
995                         break;
996                 case NODEBOX_WALLMOUNTED:
997                         lua_pushstring(L, "wallmounted");
998                         lua_setfield(L, -2, "type");
999                         push_aabb3f(L, box.wall_top);
1000                         lua_setfield(L, -2, "wall_top");
1001                         push_aabb3f(L, box.wall_bottom);
1002                         lua_setfield(L, -2, "wall_bottom");
1003                         push_aabb3f(L, box.wall_side);
1004                         lua_setfield(L, -2, "wall_side");
1005                         break;
1006                 case NODEBOX_CONNECTED: {
1007                         lua_pushstring(L, "connected");
1008                         lua_setfield(L, -2, "type");
1009                         const auto &c = box.getConnected();
1010                         push_box(L, c.connect_top);
1011                         lua_setfield(L, -2, "connect_top");
1012                         push_box(L, c.connect_bottom);
1013                         lua_setfield(L, -2, "connect_bottom");
1014                         push_box(L, c.connect_front);
1015                         lua_setfield(L, -2, "connect_front");
1016                         push_box(L, c.connect_back);
1017                         lua_setfield(L, -2, "connect_back");
1018                         push_box(L, c.connect_left);
1019                         lua_setfield(L, -2, "connect_left");
1020                         push_box(L, c.connect_right);
1021                         lua_setfield(L, -2, "connect_right");
1022                         // half the boxes are missing here?
1023                         break;
1024                 }
1025                 default:
1026                         FATAL_ERROR("Invalid box.type");
1027                         break;
1028         }
1029 }
1030
1031 void push_box(lua_State *L, const std::vector<aabb3f> &box)
1032 {
1033         lua_createtable(L, box.size(), 0);
1034         u8 i = 1;
1035         for (const aabb3f &it : box) {
1036                 push_aabb3f(L, it);
1037                 lua_rawseti(L, -2, i++);
1038         }
1039 }
1040
1041 /******************************************************************************/
1042 void push_palette(lua_State *L, const std::vector<video::SColor> *palette)
1043 {
1044         lua_createtable(L, palette->size(), 0);
1045         int newTable = lua_gettop(L);
1046         int index = 1;
1047         std::vector<video::SColor>::const_iterator iter;
1048         for (iter = palette->begin(); iter != palette->end(); ++iter) {
1049                 push_ARGB8(L, (*iter));
1050                 lua_rawseti(L, newTable, index);
1051                 index++;
1052         }
1053 }
1054
1055 /******************************************************************************/
1056 void read_server_sound_params(lua_State *L, int index,
1057                 ServerPlayingSound &params)
1058 {
1059         if(index < 0)
1060                 index = lua_gettop(L) + 1 + index;
1061
1062         if(lua_istable(L, index)){
1063                 // Functional overlap: this may modify SimpleSoundSpec contents
1064                 getfloatfield(L, index, "fade", params.spec.fade);
1065                 getfloatfield(L, index, "pitch", params.spec.pitch);
1066                 getboolfield(L, index, "loop", params.spec.loop);
1067
1068                 getfloatfield(L, index, "gain", params.gain);
1069
1070                 // Handle positional information
1071                 getstringfield(L, index, "to_player", params.to_player);
1072                 lua_getfield(L, index, "pos");
1073                 if(!lua_isnil(L, -1)){
1074                         v3f p = read_v3f(L, -1)*BS;
1075                         params.pos = p;
1076                         params.type = SoundLocation::Position;
1077                 }
1078                 lua_pop(L, 1);
1079                 lua_getfield(L, index, "object");
1080                 if(!lua_isnil(L, -1)){
1081                         ObjectRef *ref = ModApiBase::checkObject<ObjectRef>(L, -1);
1082                         ServerActiveObject *sao = ObjectRef::getobject(ref);
1083                         if(sao){
1084                                 params.object = sao->getId();
1085                                 params.type = SoundLocation::Object;
1086                         }
1087                 }
1088                 lua_pop(L, 1);
1089                 params.max_hear_distance = BS*getfloatfield_default(L, index,
1090                                 "max_hear_distance", params.max_hear_distance/BS);
1091                 getstringfield(L, index, "exclude_player", params.exclude_player);
1092         }
1093 }
1094
1095 /******************************************************************************/
1096 void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
1097 {
1098         if(index < 0)
1099                 index = lua_gettop(L) + 1 + index;
1100         if (lua_isnil(L, index))
1101                 return;
1102
1103         if (lua_istable(L, index)) {
1104                 getstringfield(L, index, "name", spec.name);
1105                 getfloatfield(L, index, "gain", spec.gain);
1106                 getfloatfield(L, index, "fade", spec.fade);
1107                 getfloatfield(L, index, "pitch", spec.pitch);
1108         } else if (lua_isstring(L, index)) {
1109                 spec.name = lua_tostring(L, index);
1110         }
1111 }
1112
1113 void push_soundspec(lua_State *L, const SimpleSoundSpec &spec)
1114 {
1115         lua_createtable(L, 0, 3);
1116         lua_pushstring(L, spec.name.c_str());
1117         lua_setfield(L, -2, "name");
1118         lua_pushnumber(L, spec.gain);
1119         lua_setfield(L, -2, "gain");
1120         lua_pushnumber(L, spec.fade);
1121         lua_setfield(L, -2, "fade");
1122         lua_pushnumber(L, spec.pitch);
1123         lua_setfield(L, -2, "pitch");
1124 }
1125
1126 /******************************************************************************/
1127 NodeBox read_nodebox(lua_State *L, int index)
1128 {
1129         NodeBox nodebox;
1130         if (lua_isnil(L, -1))
1131                 return nodebox;
1132
1133         luaL_checktype(L, -1, LUA_TTABLE);
1134
1135         nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
1136                         ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR);
1137
1138 #define NODEBOXREAD(n, s){ \
1139                 lua_getfield(L, index, (s)); \
1140                 if (lua_istable(L, -1)) \
1141                         (n) = read_aabb3f(L, -1, BS); \
1142                 lua_pop(L, 1); \
1143         }
1144
1145 #define NODEBOXREADVEC(n, s) \
1146         lua_getfield(L, index, (s)); \
1147         if (lua_istable(L, -1)) \
1148                 (n) = read_aabb3f_vector(L, -1, BS); \
1149         lua_pop(L, 1);
1150
1151         NODEBOXREADVEC(nodebox.fixed, "fixed");
1152         NODEBOXREAD(nodebox.wall_top, "wall_top");
1153         NODEBOXREAD(nodebox.wall_bottom, "wall_bottom");
1154         NODEBOXREAD(nodebox.wall_side, "wall_side");
1155
1156         if (nodebox.type == NODEBOX_CONNECTED) {
1157                 auto &c = nodebox.getConnected();
1158                 NODEBOXREADVEC(c.connect_top, "connect_top");
1159                 NODEBOXREADVEC(c.connect_bottom, "connect_bottom");
1160                 NODEBOXREADVEC(c.connect_front, "connect_front");
1161                 NODEBOXREADVEC(c.connect_left, "connect_left");
1162                 NODEBOXREADVEC(c.connect_back, "connect_back");
1163                 NODEBOXREADVEC(c.connect_right, "connect_right");
1164                 NODEBOXREADVEC(c.disconnected_top, "disconnected_top");
1165                 NODEBOXREADVEC(c.disconnected_bottom, "disconnected_bottom");
1166                 NODEBOXREADVEC(c.disconnected_front, "disconnected_front");
1167                 NODEBOXREADVEC(c.disconnected_left, "disconnected_left");
1168                 NODEBOXREADVEC(c.disconnected_back, "disconnected_back");
1169                 NODEBOXREADVEC(c.disconnected_right, "disconnected_right");
1170                 NODEBOXREADVEC(c.disconnected, "disconnected");
1171                 NODEBOXREADVEC(c.disconnected_sides, "disconnected_sides");
1172         }
1173
1174         return nodebox;
1175 }
1176
1177 /******************************************************************************/
1178 MapNode readnode(lua_State *L, int index, const NodeDefManager *ndef)
1179 {
1180         lua_getfield(L, index, "name");
1181         if (!lua_isstring(L, -1))
1182                 throw LuaError("Node name is not set or is not a string!");
1183         std::string name = lua_tostring(L, -1);
1184         lua_pop(L, 1);
1185
1186         u8 param1 = 0;
1187         lua_getfield(L, index, "param1");
1188         if (!lua_isnil(L, -1))
1189                 param1 = lua_tonumber(L, -1);
1190         lua_pop(L, 1);
1191
1192         u8 param2 = 0;
1193         lua_getfield(L, index, "param2");
1194         if (!lua_isnil(L, -1))
1195                 param2 = lua_tonumber(L, -1);
1196         lua_pop(L, 1);
1197
1198         content_t id = CONTENT_IGNORE;
1199         if (!ndef->getId(name, id))
1200                 throw LuaError("\"" + name + "\" is not a registered node!");
1201
1202         return {id, param1, param2};
1203 }
1204
1205 /******************************************************************************/
1206 void pushnode(lua_State *L, const MapNode &n, const NodeDefManager *ndef)
1207 {
1208         lua_createtable(L, 0, 3);
1209         lua_pushstring(L, ndef->get(n).name.c_str());
1210         lua_setfield(L, -2, "name");
1211         lua_pushinteger(L, n.getParam1());
1212         lua_setfield(L, -2, "param1");
1213         lua_pushinteger(L, n.getParam2());
1214         lua_setfield(L, -2, "param2");
1215 }
1216
1217 /******************************************************************************/
1218 void warn_if_field_exists(lua_State *L, int table,
1219                 const char *name, const std::string &message)
1220 {
1221         lua_getfield(L, table, name);
1222         if (!lua_isnil(L, -1)) {
1223                 warningstream << "Field \"" << name << "\": "
1224                                 << message << std::endl;
1225                 infostream << script_get_backtrace(L) << std::endl;
1226         }
1227         lua_pop(L, 1);
1228 }
1229
1230 /******************************************************************************/
1231 int getenumfield(lua_State *L, int table,
1232                 const char *fieldname, const EnumString *spec, int default_)
1233 {
1234         int result = default_;
1235         string_to_enum(spec, result,
1236                         getstringfield_default(L, table, fieldname, ""));
1237         return result;
1238 }
1239
1240 /******************************************************************************/
1241 bool string_to_enum(const EnumString *spec, int &result,
1242                 const std::string &str)
1243 {
1244         const EnumString *esp = spec;
1245         while(esp->str){
1246                 if (!strcmp(str.c_str(), esp->str)) {
1247                         result = esp->num;
1248                         return true;
1249                 }
1250                 esp++;
1251         }
1252         return false;
1253 }
1254
1255 /******************************************************************************/
1256 ItemStack read_item(lua_State* L, int index, IItemDefManager *idef)
1257 {
1258         if(index < 0)
1259                 index = lua_gettop(L) + 1 + index;
1260
1261         if (lua_isnil(L, index)) {
1262                 return ItemStack();
1263         }
1264
1265         if (lua_isuserdata(L, index)) {
1266                 // Convert from LuaItemStack
1267                 LuaItemStack *o = ModApiBase::checkObject<LuaItemStack>(L, index);
1268                 return o->getItem();
1269         }
1270
1271         if (lua_isstring(L, index)) {
1272                 // Convert from itemstring
1273                 std::string itemstring = lua_tostring(L, index);
1274                 try
1275                 {
1276                         ItemStack item;
1277                         item.deSerialize(itemstring, idef);
1278                         return item;
1279                 }
1280                 catch(SerializationError &e)
1281                 {
1282                         warningstream<<"unable to create item from itemstring"
1283                                         <<": "<<itemstring<<std::endl;
1284                         return ItemStack();
1285                 }
1286         }
1287         else if(lua_istable(L, index))
1288         {
1289                 // Convert from table
1290                 std::string name = getstringfield_default(L, index, "name", "");
1291                 int count = getintfield_default(L, index, "count", 1);
1292                 int wear = getintfield_default(L, index, "wear", 0);
1293
1294                 ItemStack istack(name, count, wear, idef);
1295
1296                 // BACKWARDS COMPATIBLITY
1297                 std::string value = getstringfield_default(L, index, "metadata", "");
1298                 istack.metadata.setString("", value);
1299
1300                 // Get meta
1301                 lua_getfield(L, index, "meta");
1302                 int fieldstable = lua_gettop(L);
1303                 if (lua_istable(L, fieldstable)) {
1304                         lua_pushnil(L);
1305                         while (lua_next(L, fieldstable) != 0) {
1306                                 // key at index -2 and value at index -1
1307                                 std::string key = lua_tostring(L, -2);
1308                                 size_t value_len;
1309                                 const char *value_cs = lua_tolstring(L, -1, &value_len);
1310                                 std::string value(value_cs, value_len);
1311                                 istack.metadata.setString(key, value);
1312                                 lua_pop(L, 1); // removes value, keeps key for next iteration
1313                         }
1314                 }
1315
1316                 return istack;
1317         } else {
1318                 throw LuaError("Expecting itemstack, itemstring, table or nil");
1319         }
1320 }
1321
1322 /******************************************************************************/
1323 void push_tool_capabilities(lua_State *L,
1324                 const ToolCapabilities &toolcap)
1325 {
1326         lua_newtable(L);
1327         setfloatfield(L, -1, "full_punch_interval", toolcap.full_punch_interval);
1328         setintfield(L, -1, "max_drop_level", toolcap.max_drop_level);
1329         setintfield(L, -1, "punch_attack_uses", toolcap.punch_attack_uses);
1330                 // Create groupcaps table
1331                 lua_newtable(L);
1332                 // For each groupcap
1333                 for (const auto &gc_it : toolcap.groupcaps) {
1334                         // Create groupcap table
1335                         lua_newtable(L);
1336                         const std::string &name = gc_it.first;
1337                         const ToolGroupCap &groupcap = gc_it.second;
1338                         // Create subtable "times"
1339                         lua_newtable(L);
1340                         for (auto time : groupcap.times) {
1341                                 lua_pushinteger(L, time.first);
1342                                 lua_pushnumber(L, time.second);
1343                                 lua_settable(L, -3);
1344                         }
1345                         // Set subtable "times"
1346                         lua_setfield(L, -2, "times");
1347                         // Set simple parameters
1348                         setintfield(L, -1, "maxlevel", groupcap.maxlevel);
1349                         setintfield(L, -1, "uses", groupcap.uses);
1350                         // Insert groupcap table into groupcaps table
1351                         lua_setfield(L, -2, name.c_str());
1352                 }
1353                 // Set groupcaps table
1354                 lua_setfield(L, -2, "groupcaps");
1355                 //Create damage_groups table
1356                 lua_newtable(L);
1357                 // For each damage group
1358                 for (const auto &damageGroup : toolcap.damageGroups) {
1359                         // Create damage group table
1360                         lua_pushinteger(L, damageGroup.second);
1361                         lua_setfield(L, -2, damageGroup.first.c_str());
1362                 }
1363                 lua_setfield(L, -2, "damage_groups");
1364 }
1365
1366 /******************************************************************************/
1367 void push_inventory_list(lua_State *L, const InventoryList &invlist)
1368 {
1369         push_items(L, invlist.getItems());
1370 }
1371
1372 /******************************************************************************/
1373 void push_inventory_lists(lua_State *L, const Inventory &inv)
1374 {
1375         const auto &lists = inv.getLists();
1376         lua_createtable(L, 0, lists.size());
1377         for(const InventoryList *list : lists) {
1378                 const std::string &name = list->getName();
1379                 lua_pushlstring(L, name.c_str(), name.size());
1380                 push_inventory_list(L, *list);
1381                 lua_rawset(L, -3);
1382         }
1383 }
1384
1385 /******************************************************************************/
1386 void read_inventory_list(lua_State *L, int tableindex,
1387                 Inventory *inv, const char *name, IGameDef *gdef, int forcesize)
1388 {
1389         if(tableindex < 0)
1390                 tableindex = lua_gettop(L) + 1 + tableindex;
1391
1392         // If nil, delete list
1393         if(lua_isnil(L, tableindex)){
1394                 inv->deleteList(name);
1395                 return;
1396         }
1397
1398         // Get Lua-specified items to insert into the list
1399         std::vector<ItemStack> items = read_items(L, tableindex, gdef);
1400         size_t listsize = (forcesize >= 0) ? forcesize : items.size();
1401
1402         // Create or resize/clear list
1403         InventoryList *invlist = inv->addList(name, listsize);
1404         if (!invlist) {
1405                 luaL_error(L, "inventory list: cannot create list named '%s'", name);
1406                 return;
1407         }
1408
1409         for (size_t i = 0; i < items.size(); ++i) {
1410                 if (i == listsize)
1411                         break; // Truncate provided list of items
1412                 invlist->changeItem(i, items[i]);
1413         }
1414 }
1415
1416 /******************************************************************************/
1417 struct TileAnimationParams read_animation_definition(lua_State *L, int index)
1418 {
1419         if(index < 0)
1420                 index = lua_gettop(L) + 1 + index;
1421
1422         struct TileAnimationParams anim;
1423         anim.type = TAT_NONE;
1424         if (!lua_istable(L, index))
1425                 return anim;
1426
1427         anim.type = (TileAnimationType)
1428                 getenumfield(L, index, "type", es_TileAnimationType,
1429                 TAT_NONE);
1430         if (anim.type == TAT_VERTICAL_FRAMES) {
1431                 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
1432                 anim.vertical_frames.aspect_w =
1433                         getintfield_default(L, index, "aspect_w", 16);
1434                 anim.vertical_frames.aspect_h =
1435                         getintfield_default(L, index, "aspect_h", 16);
1436                 anim.vertical_frames.length =
1437                         getfloatfield_default(L, index, "length", 1.0);
1438         } else if (anim.type == TAT_SHEET_2D) {
1439                 // {type="sheet_2d", frames_w=5, frames_h=3, frame_length=0.5}
1440                 getintfield(L, index, "frames_w",
1441                         anim.sheet_2d.frames_w);
1442                 getintfield(L, index, "frames_h",
1443                         anim.sheet_2d.frames_h);
1444                 getfloatfield(L, index, "frame_length",
1445                         anim.sheet_2d.frame_length);
1446         }
1447
1448         return anim;
1449 }
1450
1451 /******************************************************************************/
1452 ToolCapabilities read_tool_capabilities(
1453                 lua_State *L, int table)
1454 {
1455         ToolCapabilities toolcap;
1456         getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
1457         getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
1458         getintfield(L, table, "punch_attack_uses", toolcap.punch_attack_uses);
1459         lua_getfield(L, table, "groupcaps");
1460         if(lua_istable(L, -1)){
1461                 int table_groupcaps = lua_gettop(L);
1462                 lua_pushnil(L);
1463                 while(lua_next(L, table_groupcaps) != 0){
1464                         // key at index -2 and value at index -1
1465                         std::string groupname = luaL_checkstring(L, -2);
1466                         if(lua_istable(L, -1)){
1467                                 int table_groupcap = lua_gettop(L);
1468                                 // This will be created
1469                                 ToolGroupCap groupcap;
1470                                 // Read simple parameters
1471                                 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
1472                                 getintfield(L, table_groupcap, "uses", groupcap.uses);
1473                                 // DEPRECATED: maxwear
1474                                 float maxwear = 0;
1475                                 if (getfloatfield(L, table_groupcap, "maxwear", maxwear)){
1476                                         if (maxwear != 0)
1477                                                 groupcap.uses = 1.0/maxwear;
1478                                         else
1479                                                 groupcap.uses = 0;
1480                                         warningstream << "Field \"maxwear\" is deprecated; "
1481                                                         << "replace with uses=1/maxwear" << std::endl;
1482                                         infostream << script_get_backtrace(L) << std::endl;
1483                                 }
1484                                 // Read "times" table
1485                                 lua_getfield(L, table_groupcap, "times");
1486                                 if(lua_istable(L, -1)){
1487                                         int table_times = lua_gettop(L);
1488                                         lua_pushnil(L);
1489                                         while(lua_next(L, table_times) != 0){
1490                                                 // key at index -2 and value at index -1
1491                                                 int rating = luaL_checkinteger(L, -2);
1492                                                 float time = luaL_checknumber(L, -1);
1493                                                 groupcap.times[rating] = time;
1494                                                 // removes value, keeps key for next iteration
1495                                                 lua_pop(L, 1);
1496                                         }
1497                                 }
1498                                 lua_pop(L, 1);
1499                                 // Insert groupcap into toolcap
1500                                 toolcap.groupcaps[groupname] = groupcap;
1501                         }
1502                         // removes value, keeps key for next iteration
1503                         lua_pop(L, 1);
1504                 }
1505         }
1506         lua_pop(L, 1);
1507
1508         lua_getfield(L, table, "damage_groups");
1509         if(lua_istable(L, -1)){
1510                 int table_damage_groups = lua_gettop(L);
1511                 lua_pushnil(L);
1512                 while(lua_next(L, table_damage_groups) != 0){
1513                         // key at index -2 and value at index -1
1514                         std::string groupname = luaL_checkstring(L, -2);
1515                         u16 value = luaL_checkinteger(L, -1);
1516                         toolcap.damageGroups[groupname] = value;
1517                         // removes value, keeps key for next iteration
1518                         lua_pop(L, 1);
1519                 }
1520         }
1521         lua_pop(L, 1);
1522         return toolcap;
1523 }
1524
1525 /******************************************************************************/
1526 void push_dig_params(lua_State *L,const DigParams &params)
1527 {
1528         lua_createtable(L, 0, 3);
1529         setboolfield(L, -1, "diggable", params.diggable);
1530         setfloatfield(L, -1, "time", params.time);
1531         setintfield(L, -1, "wear", params.wear);
1532 }
1533
1534 /******************************************************************************/
1535 void push_hit_params(lua_State *L,const HitParams &params)
1536 {
1537         lua_createtable(L, 0, 3);
1538         setintfield(L, -1, "hp", params.hp);
1539         setintfield(L, -1, "wear", params.wear);
1540 }
1541
1542 /******************************************************************************/
1543
1544 bool getflagsfield(lua_State *L, int table, const char *fieldname,
1545         FlagDesc *flagdesc, u32 *flags, u32 *flagmask)
1546 {
1547         lua_getfield(L, table, fieldname);
1548
1549         bool success = read_flags(L, -1, flagdesc, flags, flagmask);
1550
1551         lua_pop(L, 1);
1552
1553         return success;
1554 }
1555
1556 bool read_flags(lua_State *L, int index, FlagDesc *flagdesc,
1557         u32 *flags, u32 *flagmask)
1558 {
1559         if (lua_isstring(L, index)) {
1560                 std::string flagstr = lua_tostring(L, index);
1561                 *flags = readFlagString(flagstr, flagdesc, flagmask);
1562         } else if (lua_istable(L, index)) {
1563                 *flags = read_flags_table(L, index, flagdesc, flagmask);
1564         } else {
1565                 return false;
1566         }
1567
1568         return true;
1569 }
1570
1571 u32 read_flags_table(lua_State *L, int table, FlagDesc *flagdesc, u32 *flagmask)
1572 {
1573         u32 flags = 0, mask = 0;
1574         char fnamebuf[64] = "no";
1575
1576         for (int i = 0; flagdesc[i].name; i++) {
1577                 bool result;
1578
1579                 if (getboolfield(L, table, flagdesc[i].name, result)) {
1580                         mask |= flagdesc[i].flag;
1581                         if (result)
1582                                 flags |= flagdesc[i].flag;
1583                 }
1584
1585                 strlcpy(fnamebuf + 2, flagdesc[i].name, sizeof(fnamebuf) - 2);
1586                 if (getboolfield(L, table, fnamebuf, result))
1587                         mask |= flagdesc[i].flag;
1588         }
1589
1590         if (flagmask)
1591                 *flagmask = mask;
1592
1593         return flags;
1594 }
1595
1596 void push_flags_string(lua_State *L, FlagDesc *flagdesc, u32 flags, u32 flagmask)
1597 {
1598         std::string flagstring = writeFlagString(flags, flagdesc, flagmask);
1599         lua_pushlstring(L, flagstring.c_str(), flagstring.size());
1600 }
1601
1602 /******************************************************************************/
1603 /* Lua Stored data!                                                           */
1604 /******************************************************************************/
1605
1606 /******************************************************************************/
1607 void read_groups(lua_State *L, int index, ItemGroupList &result)
1608 {
1609         if (lua_isnil(L, index))
1610                 return;
1611
1612         luaL_checktype(L, index, LUA_TTABLE);
1613
1614         result.clear();
1615         lua_pushnil(L);
1616         if (index < 0)
1617                 index -= 1;
1618         while (lua_next(L, index) != 0) {
1619                 // key at index -2 and value at index -1
1620                 std::string name = luaL_checkstring(L, -2);
1621                 int rating = luaL_checkinteger(L, -1);
1622                 // zero rating indicates not in the group
1623                 if (rating != 0)
1624                         result[name] = rating;
1625                 // removes value, keeps key for next iteration
1626                 lua_pop(L, 1);
1627         }
1628 }
1629
1630 /******************************************************************************/
1631 void push_groups(lua_State *L, const ItemGroupList &groups)
1632 {
1633         lua_createtable(L, 0, groups.size());
1634         for (const auto &group : groups) {
1635                 lua_pushinteger(L, group.second);
1636                 lua_setfield(L, -2, group.first.c_str());
1637         }
1638 }
1639
1640 /******************************************************************************/
1641 void push_items(lua_State *L, const std::vector<ItemStack> &items)
1642 {
1643         lua_createtable(L, items.size(), 0);
1644         for (u32 i = 0; i != items.size(); i++) {
1645                 LuaItemStack::create(L, items[i]);
1646                 lua_rawseti(L, -2, i + 1);
1647         }
1648 }
1649
1650 /******************************************************************************/
1651 std::vector<ItemStack> read_items(lua_State *L, int index, IGameDef *gdef)
1652 {
1653         if(index < 0)
1654                 index = lua_gettop(L) + 1 + index;
1655
1656         std::vector<ItemStack> items;
1657         luaL_checktype(L, index, LUA_TTABLE);
1658         lua_pushnil(L);
1659         while (lua_next(L, index)) {
1660                 s32 key = luaL_checkinteger(L, -2);
1661                 if (key < 1) {
1662                         throw LuaError("Invalid inventory list index");
1663                 }
1664                 if (items.size() < (u32) key) {
1665                         items.resize(key);
1666                 }
1667                 items[key - 1] = read_item(L, -1, gdef->idef());
1668                 lua_pop(L, 1);
1669         }
1670         return items;
1671 }
1672
1673 /******************************************************************************/
1674 void luaentity_get(lua_State *L, u16 id)
1675 {
1676         // Get luaentities[i]
1677         lua_getglobal(L, "core");
1678         lua_getfield(L, -1, "luaentities");
1679         luaL_checktype(L, -1, LUA_TTABLE);
1680         lua_pushinteger(L, id);
1681         lua_gettable(L, -2);
1682         lua_remove(L, -2); // Remove luaentities
1683         lua_remove(L, -2); // Remove core
1684 }
1685
1686 /******************************************************************************/
1687 bool read_noiseparams(lua_State *L, int index, NoiseParams *np)
1688 {
1689         if (index < 0)
1690                 index = lua_gettop(L) + 1 + index;
1691
1692         if (!lua_istable(L, index))
1693                 return false;
1694
1695         getfloatfield(L, index, "offset",      np->offset);
1696         getfloatfield(L, index, "scale",       np->scale);
1697         getfloatfield(L, index, "persist",     np->persist);
1698         getfloatfield(L, index, "persistence", np->persist);
1699         getfloatfield(L, index, "lacunarity",  np->lacunarity);
1700         getintfield(L,   index, "seed",        np->seed);
1701         getintfield(L,   index, "octaves",     np->octaves);
1702
1703         u32 flags    = 0;
1704         u32 flagmask = 0;
1705         np->flags = getflagsfield(L, index, "flags", flagdesc_noiseparams,
1706                 &flags, &flagmask) ? flags : NOISE_FLAG_DEFAULTS;
1707
1708         lua_getfield(L, index, "spread");
1709         np->spread  = read_v3f(L, -1);
1710         lua_pop(L, 1);
1711
1712         return true;
1713 }
1714
1715 void push_noiseparams(lua_State *L, NoiseParams *np)
1716 {
1717         lua_newtable(L);
1718         setfloatfield(L, -1, "offset",      np->offset);
1719         setfloatfield(L, -1, "scale",       np->scale);
1720         setfloatfield(L, -1, "persist",     np->persist);
1721         setfloatfield(L, -1, "persistence", np->persist);
1722         setfloatfield(L, -1, "lacunarity",  np->lacunarity);
1723         setintfield(  L, -1, "seed",        np->seed);
1724         setintfield(  L, -1, "octaves",     np->octaves);
1725
1726         push_flags_string(L, flagdesc_noiseparams, np->flags,
1727                 np->flags);
1728         lua_setfield(L, -2, "flags");
1729
1730         push_v3f(L, np->spread);
1731         lua_setfield(L, -2, "spread");
1732 }
1733
1734 /******************************************************************************/
1735 // Returns depth of json value tree
1736 static int push_json_value_getdepth(const Json::Value &value)
1737 {
1738         if (!value.isArray() && !value.isObject())
1739                 return 1;
1740
1741         int maxdepth = 0;
1742         for (const auto &it : value) {
1743                 int elemdepth = push_json_value_getdepth(it);
1744                 if (elemdepth > maxdepth)
1745                         maxdepth = elemdepth;
1746         }
1747         return maxdepth + 1;
1748 }
1749 // Recursive function to convert JSON --> Lua table
1750 static bool push_json_value_helper(lua_State *L, const Json::Value &value,
1751                 int nullindex)
1752 {
1753         switch(value.type()) {
1754                 case Json::nullValue:
1755                 default:
1756                         lua_pushvalue(L, nullindex);
1757                         break;
1758                 case Json::intValue:
1759                         lua_pushinteger(L, value.asLargestInt());
1760                         break;
1761                 case Json::uintValue:
1762                         lua_pushinteger(L, value.asLargestUInt());
1763                         break;
1764                 case Json::realValue:
1765                         lua_pushnumber(L, value.asDouble());
1766                         break;
1767                 case Json::stringValue:
1768                         {
1769                                 const char *str = value.asCString();
1770                                 lua_pushstring(L, str ? str : "");
1771                         }
1772                         break;
1773                 case Json::booleanValue:
1774                         lua_pushboolean(L, value.asInt());
1775                         break;
1776                 case Json::arrayValue:
1777                         lua_createtable(L, value.size(), 0);
1778                         for (Json::Value::const_iterator it = value.begin();
1779                                         it != value.end(); ++it) {
1780                                 push_json_value_helper(L, *it, nullindex);
1781                                 lua_rawseti(L, -2, it.index() + 1);
1782                         }
1783                         break;
1784                 case Json::objectValue:
1785                         lua_createtable(L, 0, value.size());
1786                         for (Json::Value::const_iterator it = value.begin();
1787                                         it != value.end(); ++it) {
1788 #if !defined(JSONCPP_STRING) && (JSONCPP_VERSION_MAJOR < 1 || JSONCPP_VERSION_MINOR < 9)
1789                                 const char *str = it.memberName();
1790                                 lua_pushstring(L, str ? str : "");
1791 #else
1792                                 std::string str = it.name();
1793                                 lua_pushstring(L, str.c_str());
1794 #endif
1795                                 push_json_value_helper(L, *it, nullindex);
1796                                 lua_rawset(L, -3);
1797                         }
1798                         break;
1799         }
1800         return true;
1801 }
1802 // converts JSON --> Lua table; returns false if lua stack limit exceeded
1803 // nullindex: Lua stack index of value to use in place of JSON null
1804 bool push_json_value(lua_State *L, const Json::Value &value, int nullindex)
1805 {
1806         if(nullindex < 0)
1807                 nullindex = lua_gettop(L) + 1 + nullindex;
1808
1809         int depth = push_json_value_getdepth(value);
1810
1811         // The maximum number of Lua stack slots used at each recursion level
1812         // of push_json_value_helper is 2, so make sure there a depth * 2 slots
1813         if (lua_checkstack(L, depth * 2))
1814                 return push_json_value_helper(L, value, nullindex);
1815
1816         return false;
1817 }
1818
1819 // Converts Lua table --> JSON
1820 void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion)
1821 {
1822         if (recursion > 16) {
1823                 throw SerializationError("Maximum recursion depth exceeded");
1824         }
1825         int type = lua_type(L, index);
1826         if (type == LUA_TBOOLEAN) {
1827                 root = (bool) lua_toboolean(L, index);
1828         } else if (type == LUA_TNUMBER) {
1829                 root = lua_tonumber(L, index);
1830         } else if (type == LUA_TSTRING) {
1831                 size_t len;
1832                 const char *str = lua_tolstring(L, index, &len);
1833                 root = std::string(str, len);
1834         } else if (type == LUA_TTABLE) {
1835                 lua_pushnil(L);
1836                 while (lua_next(L, index)) {
1837                         // Key is at -2 and value is at -1
1838                         Json::Value value;
1839                         read_json_value(L, value, lua_gettop(L), recursion + 1);
1840
1841                         Json::ValueType roottype = root.type();
1842                         int keytype = lua_type(L, -1);
1843                         if (keytype == LUA_TNUMBER) {
1844                                 lua_Number key = lua_tonumber(L, -1);
1845                                 if (roottype != Json::nullValue && roottype != Json::arrayValue) {
1846                                         throw SerializationError("Can't mix array and object values in JSON");
1847                                 } else if (key < 1) {
1848                                         throw SerializationError("Can't use zero-based or negative indexes in JSON");
1849                                 } else if (floor(key) != key) {
1850                                         throw SerializationError("Can't use indexes with a fractional part in JSON");
1851                                 }
1852                                 root[(Json::ArrayIndex) key - 1] = value;
1853                         } else if (keytype == LUA_TSTRING) {
1854                                 if (roottype != Json::nullValue && roottype != Json::objectValue) {
1855                                         throw SerializationError("Can't mix array and object values in JSON");
1856                                 }
1857                                 root[lua_tostring(L, -1)] = value;
1858                         } else {
1859                                 throw SerializationError("Lua key to convert to JSON is not a string or number");
1860                         }
1861                 }
1862         } else if (type == LUA_TNIL) {
1863                 root = Json::nullValue;
1864         } else {
1865                 throw SerializationError("Can only store booleans, numbers, strings, objects, arrays, and null in JSON");
1866         }
1867         lua_pop(L, 1); // Pop value
1868 }
1869
1870 void push_pointed_thing(lua_State *L, const PointedThing &pointed, bool csm,
1871         bool hitpoint)
1872 {
1873         lua_newtable(L);
1874         if (pointed.type == POINTEDTHING_NODE) {
1875                 lua_pushstring(L, "node");
1876                 lua_setfield(L, -2, "type");
1877                 push_v3s16(L, pointed.node_undersurface);
1878                 lua_setfield(L, -2, "under");
1879                 push_v3s16(L, pointed.node_abovesurface);
1880                 lua_setfield(L, -2, "above");
1881         } else if (pointed.type == POINTEDTHING_OBJECT) {
1882                 lua_pushstring(L, "object");
1883                 lua_setfield(L, -2, "type");
1884
1885                 if (csm) {
1886                         lua_pushinteger(L, pointed.object_id);
1887                         lua_setfield(L, -2, "id");
1888                 } else {
1889                         push_objectRef(L, pointed.object_id);
1890                         lua_setfield(L, -2, "ref");
1891                 }
1892         } else {
1893                 lua_pushstring(L, "nothing");
1894                 lua_setfield(L, -2, "type");
1895         }
1896         if (hitpoint && (pointed.type != POINTEDTHING_NOTHING)) {
1897                 push_v3f(L, pointed.intersection_point / BS); // convert to node coords
1898                 lua_setfield(L, -2, "intersection_point");
1899                 push_v3s16(L, pointed.intersection_normal);
1900                 lua_setfield(L, -2, "intersection_normal");
1901                 lua_pushinteger(L, pointed.box_id + 1); // change to Lua array index
1902                 lua_setfield(L, -2, "box_id");
1903         }
1904 }
1905
1906 void push_objectRef(lua_State *L, const u16 id)
1907 {
1908         // Get core.object_refs[i]
1909         lua_getglobal(L, "core");
1910         lua_getfield(L, -1, "object_refs");
1911         luaL_checktype(L, -1, LUA_TTABLE);
1912         lua_pushinteger(L, id);
1913         lua_gettable(L, -2);
1914         lua_remove(L, -2); // object_refs
1915         lua_remove(L, -2); // core
1916 }
1917
1918 void read_hud_element(lua_State *L, HudElement *elem)
1919 {
1920         elem->type = (HudElementType)getenumfield(L, 2, "hud_elem_type",
1921                                                                         es_HudElementType, HUD_ELEM_TEXT);
1922
1923         lua_getfield(L, 2, "position");
1924         elem->pos = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
1925         lua_pop(L, 1);
1926
1927         lua_getfield(L, 2, "scale");
1928         elem->scale = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
1929         lua_pop(L, 1);
1930
1931         lua_getfield(L, 2, "size");
1932         elem->size = lua_istable(L, -1) ? read_v2s32(L, -1) : v2s32();
1933         lua_pop(L, 1);
1934
1935         elem->name    = getstringfield_default(L, 2, "name", "");
1936         elem->text    = getstringfield_default(L, 2, "text", "");
1937         elem->number  = getintfield_default(L, 2, "number", 0);
1938         if (elem->type == HUD_ELEM_WAYPOINT)
1939                 // waypoints reuse the item field to store precision, item = precision + 1
1940                 elem->item = getintfield_default(L, 2, "precision", -1) + 1;
1941         else
1942                 elem->item = getintfield_default(L, 2, "item", 0);
1943         elem->dir     = getintfield_default(L, 2, "direction", 0);
1944         elem->z_index = MYMAX(S16_MIN, MYMIN(S16_MAX,
1945                         getintfield_default(L, 2, "z_index", 0)));
1946         elem->text2   = getstringfield_default(L, 2, "text2", "");
1947
1948         // Deprecated, only for compatibility's sake
1949         if (elem->dir == 0)
1950                 elem->dir = getintfield_default(L, 2, "dir", 0);
1951
1952         lua_getfield(L, 2, "alignment");
1953         elem->align = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
1954         lua_pop(L, 1);
1955
1956         lua_getfield(L, 2, "offset");
1957         elem->offset = lua_istable(L, -1) ? read_v2f(L, -1) : v2f();
1958         lua_pop(L, 1);
1959
1960         lua_getfield(L, 2, "world_pos");
1961         elem->world_pos = lua_istable(L, -1) ? read_v3f(L, -1) : v3f();
1962         lua_pop(L, 1);
1963
1964         elem->style = getintfield_default(L, 2, "style", 0);
1965
1966         /* check for known deprecated element usage */
1967         if ((elem->type  == HUD_ELEM_STATBAR) && (elem->size == v2s32()))
1968                 log_deprecated(L,"Deprecated usage of statbar without size!");
1969 }
1970
1971 void push_hud_element(lua_State *L, HudElement *elem)
1972 {
1973         lua_newtable(L);
1974
1975         lua_pushstring(L, es_HudElementType[(u8)elem->type].str);
1976         lua_setfield(L, -2, "type");
1977
1978         push_v2f(L, elem->pos);
1979         lua_setfield(L, -2, "position");
1980
1981         lua_pushstring(L, elem->name.c_str());
1982         lua_setfield(L, -2, "name");
1983
1984         push_v2f(L, elem->scale);
1985         lua_setfield(L, -2, "scale");
1986
1987         lua_pushstring(L, elem->text.c_str());
1988         lua_setfield(L, -2, "text");
1989
1990         lua_pushnumber(L, elem->number);
1991         lua_setfield(L, -2, "number");
1992
1993         if (elem->type == HUD_ELEM_WAYPOINT) {
1994                 // waypoints reuse the item field to store precision, precision = item - 1
1995                 lua_pushnumber(L, elem->item - 1);
1996                 lua_setfield(L, -2, "precision");
1997         }
1998         // push the item field for waypoints as well for backwards compatibility
1999         lua_pushnumber(L, elem->item);
2000         lua_setfield(L, -2, "item");
2001
2002         lua_pushnumber(L, elem->dir);
2003         lua_setfield(L, -2, "direction");
2004
2005         push_v2f(L, elem->offset);
2006         lua_setfield(L, -2, "offset");
2007
2008         push_v2f(L, elem->align);
2009         lua_setfield(L, -2, "alignment");
2010
2011         push_v2s32(L, elem->size);
2012         lua_setfield(L, -2, "size");
2013
2014         // Deprecated, only for compatibility's sake
2015         lua_pushnumber(L, elem->dir);
2016         lua_setfield(L, -2, "dir");
2017
2018         push_v3f(L, elem->world_pos);
2019         lua_setfield(L, -2, "world_pos");
2020
2021         lua_pushnumber(L, elem->z_index);
2022         lua_setfield(L, -2, "z_index");
2023
2024         lua_pushstring(L, elem->text2.c_str());
2025         lua_setfield(L, -2, "text2");
2026
2027         lua_pushinteger(L, elem->style);
2028         lua_setfield(L, -2, "style");
2029 }
2030
2031 bool read_hud_change(lua_State *L, HudElementStat &stat, HudElement *elem, void **value)
2032 {
2033         std::string statstr = lua_tostring(L, 3);
2034         {
2035                 int statint;
2036                 if (!string_to_enum(es_HudElementStat, statint, statstr)) {
2037                         script_log_unique(L, "Unknown HUD stat type: " + statstr, warningstream);
2038                         return false;
2039                 }
2040
2041                 stat = (HudElementStat)statint;
2042         }
2043
2044         switch (stat) {
2045                 case HUD_STAT_POS:
2046                         elem->pos = read_v2f(L, 4);
2047                         *value = &elem->pos;
2048                         break;
2049                 case HUD_STAT_NAME:
2050                         elem->name = luaL_checkstring(L, 4);
2051                         *value = &elem->name;
2052                         break;
2053                 case HUD_STAT_SCALE:
2054                         elem->scale = read_v2f(L, 4);
2055                         *value = &elem->scale;
2056                         break;
2057                 case HUD_STAT_TEXT:
2058                         elem->text = luaL_checkstring(L, 4);
2059                         *value = &elem->text;
2060                         break;
2061                 case HUD_STAT_NUMBER:
2062                         elem->number = luaL_checknumber(L, 4);
2063                         *value = &elem->number;
2064                         break;
2065                 case HUD_STAT_ITEM:
2066                         elem->item = luaL_checknumber(L, 4);
2067                         if (elem->type == HUD_ELEM_WAYPOINT && statstr == "precision")
2068                                 elem->item++;
2069                         *value = &elem->item;
2070                         break;
2071                 case HUD_STAT_DIR:
2072                         elem->dir = luaL_checknumber(L, 4);
2073                         *value = &elem->dir;
2074                         break;
2075                 case HUD_STAT_ALIGN:
2076                         elem->align = read_v2f(L, 4);
2077                         *value = &elem->align;
2078                         break;
2079                 case HUD_STAT_OFFSET:
2080                         elem->offset = read_v2f(L, 4);
2081                         *value = &elem->offset;
2082                         break;
2083                 case HUD_STAT_WORLD_POS:
2084                         elem->world_pos = read_v3f(L, 4);
2085                         *value = &elem->world_pos;
2086                         break;
2087                 case HUD_STAT_SIZE:
2088                         elem->size = read_v2s32(L, 4);
2089                         *value = &elem->size;
2090                         break;
2091                 case HUD_STAT_Z_INDEX:
2092                         elem->z_index = MYMAX(S16_MIN, MYMIN(S16_MAX, luaL_checknumber(L, 4)));
2093                         *value = &elem->z_index;
2094                         break;
2095                 case HUD_STAT_TEXT2:
2096                         elem->text2 = luaL_checkstring(L, 4);
2097                         *value = &elem->text2;
2098                         break;
2099                 case HUD_STAT_STYLE:
2100                         elem->style = luaL_checknumber(L, 4);
2101                         *value = &elem->style;
2102                         break;
2103         }
2104
2105         return true;
2106 }
2107
2108 /******************************************************************************/
2109
2110 // Indices must match values in `enum CollisionType` exactly!!
2111 static const char *collision_type_str[] = {
2112         "node",
2113         "object",
2114 };
2115
2116 // Indices must match values in `enum CollisionAxis` exactly!!
2117 static const char *collision_axis_str[] = {
2118         "x",
2119         "y",
2120         "z",
2121 };
2122
2123 void push_collision_move_result(lua_State *L, const collisionMoveResult &res)
2124 {
2125         lua_createtable(L, 0, 4);
2126
2127         setboolfield(L, -1, "touching_ground", res.touching_ground);
2128         setboolfield(L, -1, "collides", res.collides);
2129         setboolfield(L, -1, "standing_on_object", res.standing_on_object);
2130
2131         /* collisions */
2132         lua_createtable(L, res.collisions.size(), 0);
2133         int i = 1;
2134         for (const auto &c : res.collisions) {
2135                 lua_createtable(L, 0, 5);
2136
2137                 lua_pushstring(L, collision_type_str[c.type]);
2138                 lua_setfield(L, -2, "type");
2139
2140                 assert(c.axis != COLLISION_AXIS_NONE);
2141                 lua_pushstring(L, collision_axis_str[c.axis]);
2142                 lua_setfield(L, -2, "axis");
2143
2144                 if (c.type == COLLISION_NODE) {
2145                         push_v3s16(L, c.node_p);
2146                         lua_setfield(L, -2, "node_pos");
2147                 } else if (c.type == COLLISION_OBJECT) {
2148                         push_objectRef(L, c.object->getId());
2149                         lua_setfield(L, -2, "object");
2150                 }
2151
2152                 push_v3f(L, c.old_speed / BS);
2153                 lua_setfield(L, -2, "old_velocity");
2154
2155                 push_v3f(L, c.new_speed / BS);
2156                 lua_setfield(L, -2, "new_velocity");
2157
2158                 lua_rawseti(L, -2, i++);
2159         }
2160         lua_setfield(L, -2, "collisions");
2161         /**/
2162 }
2163
2164
2165 void push_mod_spec(lua_State *L, const ModSpec &spec, bool include_unsatisfied)
2166 {
2167         lua_newtable(L);
2168
2169         lua_pushstring(L, spec.name.c_str());
2170         lua_setfield(L, -2, "name");
2171
2172         lua_pushstring(L, spec.author.c_str());
2173         lua_setfield(L, -2, "author");
2174
2175         lua_pushinteger(L, spec.release);
2176         lua_setfield(L, -2, "release");
2177
2178         lua_pushstring(L, spec.desc.c_str());
2179         lua_setfield(L, -2, "description");
2180
2181         lua_pushstring(L, spec.path.c_str());
2182         lua_setfield(L, -2, "path");
2183
2184         lua_pushstring(L, spec.virtual_path.c_str());
2185         lua_setfield(L, -2, "virtual_path");
2186
2187         lua_newtable(L);
2188         int i = 1;
2189         for (const auto &dep : spec.unsatisfied_depends) {
2190                 lua_pushstring(L, dep.c_str());
2191                 lua_rawseti(L, -2, i++);
2192         }
2193         lua_setfield(L, -2, "unsatisfied_depends");
2194 }