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