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