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