]> git.lizzy.rs Git - minetest.git/blob - src/script/common/c_content.cpp
Schematics: Fix minetest.place_schematic() when defined by a Lua table
[minetest.git] / src / script / common / c_content.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19 #include "common/c_content.h"
20 #include "common/c_converter.h"
21 #include "common/c_types.h"
22 #include "nodedef.h"
23 #include "itemdef.h"
24 #include "object_properties.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 "serverobject.h"
33 #include "porting.h"
34 #include "mg_schematic.h"
35 #include "noise.h"
36 #include "json/json.h"
37
38 struct EnumString es_TileAnimationType[] =
39 {
40         {TAT_NONE, "none"},
41         {TAT_VERTICAL_FRAMES, "vertical_frames"},
42         {0, NULL},
43 };
44
45 /******************************************************************************/
46 ItemDefinition read_item_definition(lua_State* L,int index,
47                 ItemDefinition default_def)
48 {
49         if(index < 0)
50                 index = lua_gettop(L) + 1 + index;
51
52         // Read the item definition
53         ItemDefinition def = default_def;
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, "inventory_image", def.inventory_image);
60         getstringfield(L, index, "wield_image", def.wield_image);
61
62         lua_getfield(L, index, "wield_scale");
63         if(lua_istable(L, -1)){
64                 def.wield_scale = check_v3f(L, -1);
65         }
66         lua_pop(L, 1);
67
68         def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
69         if(def.stack_max == 0)
70                 def.stack_max = 1;
71
72         lua_getfield(L, index, "on_use");
73         def.usable = lua_isfunction(L, -1);
74         lua_pop(L, 1);
75
76         getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
77
78         warn_if_field_exists(L, index, "tool_digging_properties",
79                         "deprecated: use tool_capabilities");
80
81         lua_getfield(L, index, "tool_capabilities");
82         if(lua_istable(L, -1)){
83                 def.tool_capabilities = new ToolCapabilities(
84                                 read_tool_capabilities(L, -1));
85         }
86
87         // If name is "" (hand), ensure there are ToolCapabilities
88         // because it will be looked up there whenever any other item has
89         // no ToolCapabilities
90         if(def.name == "" && def.tool_capabilities == NULL){
91                 def.tool_capabilities = new ToolCapabilities();
92         }
93
94         lua_getfield(L, index, "groups");
95         read_groups(L, -1, def.groups);
96         lua_pop(L, 1);
97
98         lua_getfield(L, index, "sounds");
99         if(lua_istable(L, -1)){
100                 lua_getfield(L, -1, "place");
101                 read_soundspec(L, -1, def.sound_place);
102                 lua_pop(L, 1);
103         }
104         lua_pop(L, 1);
105
106         def.range = getfloatfield_default(L, index, "range", def.range);
107
108         // Client shall immediately place this node when player places the item.
109         // Server will update the precise end result a moment later.
110         // "" = no prediction
111         getstringfield(L, index, "node_placement_prediction",
112                         def.node_placement_prediction);
113
114         return def;
115 }
116
117 /******************************************************************************/
118 void read_object_properties(lua_State *L, int index,
119                 ObjectProperties *prop)
120 {
121         if(index < 0)
122                 index = lua_gettop(L) + 1 + index;
123         if(!lua_istable(L, index))
124                 return;
125
126         prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
127
128         getboolfield(L, -1, "physical", prop->physical);
129         getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects);
130
131         getfloatfield(L, -1, "weight", prop->weight);
132
133         lua_getfield(L, -1, "collisionbox");
134         if(lua_istable(L, -1))
135                 prop->collisionbox = read_aabb3f(L, -1, 1.0);
136         lua_pop(L, 1);
137
138         getstringfield(L, -1, "visual", prop->visual);
139
140         getstringfield(L, -1, "mesh", prop->mesh);
141
142         lua_getfield(L, -1, "visual_size");
143         if(lua_istable(L, -1))
144                 prop->visual_size = read_v2f(L, -1);
145         lua_pop(L, 1);
146
147         lua_getfield(L, -1, "textures");
148         if(lua_istable(L, -1)){
149                 prop->textures.clear();
150                 int table = lua_gettop(L);
151                 lua_pushnil(L);
152                 while(lua_next(L, table) != 0){
153                         // key at index -2 and value at index -1
154                         if(lua_isstring(L, -1))
155                                 prop->textures.push_back(lua_tostring(L, -1));
156                         else
157                                 prop->textures.push_back("");
158                         // removes value, keeps key for next iteration
159                         lua_pop(L, 1);
160                 }
161         }
162         lua_pop(L, 1);
163
164         lua_getfield(L, -1, "colors");
165         if(lua_istable(L, -1)){
166                 prop->colors.clear();
167                 int table = lua_gettop(L);
168                 lua_pushnil(L);
169                 while(lua_next(L, table) != 0){
170                         // key at index -2 and value at index -1
171                         if(lua_isstring(L, -1))
172                                 prop->colors.push_back(readARGB8(L, -1));
173                         else
174                                 prop->colors.push_back(video::SColor(255, 255, 255, 255));
175                         // removes value, keeps key for next iteration
176                         lua_pop(L, 1);
177                 }
178         }
179         lua_pop(L, 1);
180
181         lua_getfield(L, -1, "spritediv");
182         if(lua_istable(L, -1))
183                 prop->spritediv = read_v2s16(L, -1);
184         lua_pop(L, 1);
185
186         lua_getfield(L, -1, "initial_sprite_basepos");
187         if(lua_istable(L, -1))
188                 prop->initial_sprite_basepos = read_v2s16(L, -1);
189         lua_pop(L, 1);
190
191         getboolfield(L, -1, "is_visible", prop->is_visible);
192         getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
193         getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
194         if (getfloatfield(L, -1, "stepheight", prop->stepheight))
195                 prop->stepheight *= BS;
196         lua_getfield(L, -1, "automatic_face_movement_dir");
197         if (lua_isnumber(L, -1)) {
198                 prop->automatic_face_movement_dir = true;
199                 prop->automatic_face_movement_dir_offset = luaL_checknumber(L, -1);
200         } else if (lua_isboolean(L, -1)) {
201                 prop->automatic_face_movement_dir = lua_toboolean(L, -1);
202                 prop->automatic_face_movement_dir_offset = 0.0;
203         }
204         lua_pop(L, 1);
205 }
206
207 /******************************************************************************/
208 TileDef read_tiledef(lua_State *L, int index)
209 {
210         if(index < 0)
211                 index = lua_gettop(L) + 1 + index;
212
213         TileDef tiledef;
214
215         // key at index -2 and value at index
216         if(lua_isstring(L, index)){
217                 // "default_lava.png"
218                 tiledef.name = lua_tostring(L, index);
219         }
220         else if(lua_istable(L, index))
221         {
222                 // {name="default_lava.png", animation={}}
223                 tiledef.name = "";
224                 getstringfield(L, index, "name", tiledef.name);
225                 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
226                 tiledef.backface_culling = getboolfield_default(
227                                         L, index, "backface_culling", true);
228                 // animation = {}
229                 lua_getfield(L, index, "animation");
230                 if(lua_istable(L, -1)){
231                         // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
232                         tiledef.animation.type = (TileAnimationType)
233                                         getenumfield(L, -1, "type", es_TileAnimationType,
234                                         TAT_NONE);
235                         tiledef.animation.aspect_w =
236                                         getintfield_default(L, -1, "aspect_w", 16);
237                         tiledef.animation.aspect_h =
238                                         getintfield_default(L, -1, "aspect_h", 16);
239                         tiledef.animation.length =
240                                         getfloatfield_default(L, -1, "length", 1.0);
241                 }
242                 lua_pop(L, 1);
243         }
244
245         return tiledef;
246 }
247
248 /******************************************************************************/
249 ContentFeatures read_content_features(lua_State *L, int index)
250 {
251         if(index < 0)
252                 index = lua_gettop(L) + 1 + index;
253
254         ContentFeatures f;
255
256         /* Cache existence of some callbacks */
257         lua_getfield(L, index, "on_construct");
258         if(!lua_isnil(L, -1)) f.has_on_construct = true;
259         lua_pop(L, 1);
260         lua_getfield(L, index, "on_destruct");
261         if(!lua_isnil(L, -1)) f.has_on_destruct = true;
262         lua_pop(L, 1);
263         lua_getfield(L, index, "after_destruct");
264         if(!lua_isnil(L, -1)) f.has_after_destruct = true;
265         lua_pop(L, 1);
266
267         lua_getfield(L, index, "on_rightclick");
268         f.rightclickable = lua_isfunction(L, -1);
269         lua_pop(L, 1);
270
271         /* Name */
272         getstringfield(L, index, "name", f.name);
273
274         /* Groups */
275         lua_getfield(L, index, "groups");
276         read_groups(L, -1, f.groups);
277         lua_pop(L, 1);
278
279         /* Visual definition */
280
281         f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype",
282                         ScriptApiNode::es_DrawType,NDT_NORMAL);
283         getfloatfield(L, index, "visual_scale", f.visual_scale);
284
285         /* Meshnode model filename */
286         getstringfield(L, index, "mesh", f.mesh);
287
288         // tiles = {}
289         lua_getfield(L, index, "tiles");
290         // If nil, try the deprecated name "tile_images" instead
291         if(lua_isnil(L, -1)){
292                 lua_pop(L, 1);
293                 warn_if_field_exists(L, index, "tile_images",
294                                 "Deprecated; new name is \"tiles\".");
295                 lua_getfield(L, index, "tile_images");
296         }
297         if(lua_istable(L, -1)){
298                 int table = lua_gettop(L);
299                 lua_pushnil(L);
300                 int i = 0;
301                 while(lua_next(L, table) != 0){
302                         // Read tiledef from value
303                         f.tiledef[i] = read_tiledef(L, -1);
304                         // removes value, keeps key for next iteration
305                         lua_pop(L, 1);
306                         i++;
307                         if(i==6){
308                                 lua_pop(L, 1);
309                                 break;
310                         }
311                 }
312                 // Copy last value to all remaining textures
313                 if(i >= 1){
314                         TileDef lasttile = f.tiledef[i-1];
315                         while(i < 6){
316                                 f.tiledef[i] = lasttile;
317                                 i++;
318                         }
319                 }
320         }
321         lua_pop(L, 1);
322
323         // special_tiles = {}
324         lua_getfield(L, index, "special_tiles");
325         // If nil, try the deprecated name "special_materials" instead
326         if(lua_isnil(L, -1)){
327                 lua_pop(L, 1);
328                 warn_if_field_exists(L, index, "special_materials",
329                                 "Deprecated; new name is \"special_tiles\".");
330                 lua_getfield(L, index, "special_materials");
331         }
332         if(lua_istable(L, -1)){
333                 int table = lua_gettop(L);
334                 lua_pushnil(L);
335                 int i = 0;
336                 while(lua_next(L, table) != 0){
337                         // Read tiledef from value
338                         f.tiledef_special[i] = read_tiledef(L, -1);
339                         // removes value, keeps key for next iteration
340                         lua_pop(L, 1);
341                         i++;
342                         if(i==CF_SPECIAL_COUNT){
343                                 lua_pop(L, 1);
344                                 break;
345                         }
346                 }
347         }
348         lua_pop(L, 1);
349
350         f.alpha = getintfield_default(L, index, "alpha", 255);
351
352         bool usealpha = getboolfield_default(L, index,
353                         "use_texture_alpha", false);
354         if (usealpha)
355                 f.alpha = 0;
356
357         /* Other stuff */
358
359         lua_getfield(L, index, "post_effect_color");
360         if(!lua_isnil(L, -1))
361                 f.post_effect_color = readARGB8(L, -1);
362         lua_pop(L, 1);
363
364         f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
365                         ScriptApiNode::es_ContentParamType, CPT_NONE);
366         f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
367                         ScriptApiNode::es_ContentParamType2, CPT2_NONE);
368
369         // Warn about some deprecated fields
370         warn_if_field_exists(L, index, "wall_mounted",
371                         "deprecated: use paramtype2 = 'wallmounted'");
372         warn_if_field_exists(L, index, "light_propagates",
373                         "deprecated: determined from paramtype");
374         warn_if_field_exists(L, index, "dug_item",
375                         "deprecated: use 'drop' field");
376         warn_if_field_exists(L, index, "extra_dug_item",
377                         "deprecated: use 'drop' field");
378         warn_if_field_exists(L, index, "extra_dug_item_rarity",
379                         "deprecated: use 'drop' field");
380         warn_if_field_exists(L, index, "metadata_name",
381                         "deprecated: use on_add and metadata callbacks");
382
383         // True for all ground-like things like stone and mud, false for eg. trees
384         getboolfield(L, index, "is_ground_content", f.is_ground_content);
385         f.light_propagates = (f.param_type == CPT_LIGHT);
386         getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
387         // This is used for collision detection.
388         // Also for general solidness queries.
389         getboolfield(L, index, "walkable", f.walkable);
390         // Player can point to these
391         getboolfield(L, index, "pointable", f.pointable);
392         // Player can dig these
393         getboolfield(L, index, "diggable", f.diggable);
394         // Player can climb these
395         getboolfield(L, index, "climbable", f.climbable);
396         // Player can build on these
397         getboolfield(L, index, "buildable_to", f.buildable_to);
398         // Whether the node is non-liquid, source liquid or flowing liquid
399         f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
400                         ScriptApiNode::es_LiquidType, LIQUID_NONE);
401         // If the content is liquid, this is the flowing version of the liquid.
402         getstringfield(L, index, "liquid_alternative_flowing",
403                         f.liquid_alternative_flowing);
404         // If the content is liquid, this is the source version of the liquid.
405         getstringfield(L, index, "liquid_alternative_source",
406                         f.liquid_alternative_source);
407         // Viscosity for fluid flow, ranging from 1 to 7, with
408         // 1 giving almost instantaneous propagation and 7 being
409         // the slowest possible
410         f.liquid_viscosity = getintfield_default(L, index,
411                         "liquid_viscosity", f.liquid_viscosity);
412         f.liquid_range = getintfield_default(L, index,
413                         "liquid_range", f.liquid_range);
414         f.leveled = getintfield_default(L, index, "leveled", f.leveled);
415
416         getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
417         getstringfield(L, index, "freezemelt", f.freezemelt);
418         f.drowning = getintfield_default(L, index,
419                         "drowning", f.drowning);
420         // Amount of light the node emits
421         f.light_source = getintfield_default(L, index,
422                         "light_source", f.light_source);
423         f.damage_per_second = getintfield_default(L, index,
424                         "damage_per_second", f.damage_per_second);
425
426         lua_getfield(L, index, "node_box");
427         if(lua_istable(L, -1))
428                 f.node_box = read_nodebox(L, -1);
429         lua_pop(L, 1);
430
431         lua_getfield(L, index, "selection_box");
432         if(lua_istable(L, -1))
433                 f.selection_box = read_nodebox(L, -1);
434         lua_pop(L, 1);
435
436         lua_getfield(L, index, "collision_box");
437         if(lua_istable(L, -1))
438                 f.collision_box = read_nodebox(L, -1);
439         lua_pop(L, 1);
440
441         f.waving = getintfield_default(L, index,
442                         "waving", f.waving);
443
444         // Set to true if paramtype used to be 'facedir_simple'
445         getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
446         // Set to true if wall_mounted used to be set to true
447         getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
448
449         // Sound table
450         lua_getfield(L, index, "sounds");
451         if(lua_istable(L, -1)){
452                 lua_getfield(L, -1, "footstep");
453                 read_soundspec(L, -1, f.sound_footstep);
454                 lua_pop(L, 1);
455                 lua_getfield(L, -1, "dig");
456                 read_soundspec(L, -1, f.sound_dig);
457                 lua_pop(L, 1);
458                 lua_getfield(L, -1, "dug");
459                 read_soundspec(L, -1, f.sound_dug);
460                 lua_pop(L, 1);
461         }
462         lua_pop(L, 1);
463
464         return f;
465 }
466
467 /******************************************************************************/
468 void read_server_sound_params(lua_State *L, int index,
469                 ServerSoundParams &params)
470 {
471         if(index < 0)
472                 index = lua_gettop(L) + 1 + index;
473         // Clear
474         params = ServerSoundParams();
475         if(lua_istable(L, index)){
476                 getfloatfield(L, index, "gain", params.gain);
477                 getstringfield(L, index, "to_player", params.to_player);
478                 lua_getfield(L, index, "pos");
479                 if(!lua_isnil(L, -1)){
480                         v3f p = read_v3f(L, -1)*BS;
481                         params.pos = p;
482                         params.type = ServerSoundParams::SSP_POSITIONAL;
483                 }
484                 lua_pop(L, 1);
485                 lua_getfield(L, index, "object");
486                 if(!lua_isnil(L, -1)){
487                         ObjectRef *ref = ObjectRef::checkobject(L, -1);
488                         ServerActiveObject *sao = ObjectRef::getobject(ref);
489                         if(sao){
490                                 params.object = sao->getId();
491                                 params.type = ServerSoundParams::SSP_OBJECT;
492                         }
493                 }
494                 lua_pop(L, 1);
495                 params.max_hear_distance = BS*getfloatfield_default(L, index,
496                                 "max_hear_distance", params.max_hear_distance/BS);
497                 getboolfield(L, index, "loop", params.loop);
498         }
499 }
500
501 /******************************************************************************/
502 void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
503 {
504         if(index < 0)
505                 index = lua_gettop(L) + 1 + index;
506         if(lua_isnil(L, index)){
507         } else if(lua_istable(L, index)){
508                 getstringfield(L, index, "name", spec.name);
509                 getfloatfield(L, index, "gain", spec.gain);
510         } else if(lua_isstring(L, index)){
511                 spec.name = lua_tostring(L, index);
512         }
513 }
514
515 /******************************************************************************/
516 NodeBox read_nodebox(lua_State *L, int index)
517 {
518         NodeBox nodebox;
519         if(lua_istable(L, -1)){
520                 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
521                                 ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR);
522
523                 lua_getfield(L, index, "fixed");
524                 if(lua_istable(L, -1))
525                         nodebox.fixed = read_aabb3f_vector(L, -1, BS);
526                 lua_pop(L, 1);
527
528                 lua_getfield(L, index, "wall_top");
529                 if(lua_istable(L, -1))
530                         nodebox.wall_top = read_aabb3f(L, -1, BS);
531                 lua_pop(L, 1);
532
533                 lua_getfield(L, index, "wall_bottom");
534                 if(lua_istable(L, -1))
535                         nodebox.wall_bottom = read_aabb3f(L, -1, BS);
536                 lua_pop(L, 1);
537
538                 lua_getfield(L, index, "wall_side");
539                 if(lua_istable(L, -1))
540                         nodebox.wall_side = read_aabb3f(L, -1, BS);
541                 lua_pop(L, 1);
542         }
543         return nodebox;
544 }
545
546 /******************************************************************************/
547 MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
548 {
549         lua_getfield(L, index, "name");
550         const char *name = luaL_checkstring(L, -1);
551         lua_pop(L, 1);
552         u8 param1;
553         lua_getfield(L, index, "param1");
554         if(lua_isnil(L, -1))
555                 param1 = 0;
556         else
557                 param1 = lua_tonumber(L, -1);
558         lua_pop(L, 1);
559         u8 param2;
560         lua_getfield(L, index, "param2");
561         if(lua_isnil(L, -1))
562                 param2 = 0;
563         else
564                 param2 = lua_tonumber(L, -1);
565         lua_pop(L, 1);
566         return MapNode(ndef, name, param1, param2);
567 }
568
569 /******************************************************************************/
570 void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
571 {
572         lua_newtable(L);
573         lua_pushstring(L, ndef->get(n).name.c_str());
574         lua_setfield(L, -2, "name");
575         lua_pushnumber(L, n.getParam1());
576         lua_setfield(L, -2, "param1");
577         lua_pushnumber(L, n.getParam2());
578         lua_setfield(L, -2, "param2");
579 }
580
581 /******************************************************************************/
582 void warn_if_field_exists(lua_State *L, int table,
583                 const char *fieldname, const std::string &message)
584 {
585         lua_getfield(L, table, fieldname);
586         if(!lua_isnil(L, -1)){
587 //TODO find way to access backtrace fct from here
588                 //              infostream<<script_get_backtrace(L)<<std::endl;
589                 infostream<<"WARNING: field \""<<fieldname<<"\": "
590                                 <<message<<std::endl;
591         }
592         lua_pop(L, 1);
593 }
594
595 /******************************************************************************/
596 int getenumfield(lua_State *L, int table,
597                 const char *fieldname, const EnumString *spec, int default_)
598 {
599         int result = default_;
600         string_to_enum(spec, result,
601                         getstringfield_default(L, table, fieldname, ""));
602         return result;
603 }
604
605 /******************************************************************************/
606 bool string_to_enum(const EnumString *spec, int &result,
607                 const std::string &str)
608 {
609         const EnumString *esp = spec;
610         while(esp->str){
611                 if(str == std::string(esp->str)){
612                         result = esp->num;
613                         return true;
614                 }
615                 esp++;
616         }
617         return false;
618 }
619
620 /******************************************************************************/
621 ItemStack read_item(lua_State* L, int index,Server* srv)
622 {
623         if(index < 0)
624                 index = lua_gettop(L) + 1 + index;
625
626         if(lua_isnil(L, index))
627         {
628                 return ItemStack();
629         }
630         else if(lua_isuserdata(L, index))
631         {
632                 // Convert from LuaItemStack
633                 LuaItemStack *o = LuaItemStack::checkobject(L, index);
634                 return o->getItem();
635         }
636         else if(lua_isstring(L, index))
637         {
638                 // Convert from itemstring
639                 std::string itemstring = lua_tostring(L, index);
640                 IItemDefManager *idef = srv->idef();
641                 try
642                 {
643                         ItemStack item;
644                         item.deSerialize(itemstring, idef);
645                         return item;
646                 }
647                 catch(SerializationError &e)
648                 {
649                         infostream<<"WARNING: unable to create item from itemstring"
650                                         <<": "<<itemstring<<std::endl;
651                         return ItemStack();
652                 }
653         }
654         else if(lua_istable(L, index))
655         {
656                 // Convert from table
657                 IItemDefManager *idef = srv->idef();
658                 std::string name = getstringfield_default(L, index, "name", "");
659                 int count = getintfield_default(L, index, "count", 1);
660                 int wear = getintfield_default(L, index, "wear", 0);
661                 std::string metadata = getstringfield_default(L, index, "metadata", "");
662                 return ItemStack(name, count, wear, metadata, idef);
663         }
664         else
665         {
666                 throw LuaError("Expecting itemstack, itemstring, table or nil");
667         }
668 }
669
670 /******************************************************************************/
671 void push_tool_capabilities(lua_State *L,
672                 const ToolCapabilities &toolcap)
673 {
674         lua_newtable(L);
675         setfloatfield(L, -1, "full_punch_interval", toolcap.full_punch_interval);
676                 setintfield(L, -1, "max_drop_level", toolcap.max_drop_level);
677                 // Create groupcaps table
678                 lua_newtable(L);
679                 // For each groupcap
680                 for(std::map<std::string, ToolGroupCap>::const_iterator
681                                 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
682                         // Create groupcap table
683                         lua_newtable(L);
684                         const std::string &name = i->first;
685                         const ToolGroupCap &groupcap = i->second;
686                         // Create subtable "times"
687                         lua_newtable(L);
688                         for(std::map<int, float>::const_iterator
689                                         i = groupcap.times.begin(); i != groupcap.times.end(); i++){
690                                 int rating = i->first;
691                                 float time = i->second;
692                                 lua_pushinteger(L, rating);
693                                 lua_pushnumber(L, time);
694                                 lua_settable(L, -3);
695                         }
696                         // Set subtable "times"
697                         lua_setfield(L, -2, "times");
698                         // Set simple parameters
699                         setintfield(L, -1, "maxlevel", groupcap.maxlevel);
700                         setintfield(L, -1, "uses", groupcap.uses);
701                         // Insert groupcap table into groupcaps table
702                         lua_setfield(L, -2, name.c_str());
703                 }
704                 // Set groupcaps table
705                 lua_setfield(L, -2, "groupcaps");
706                 //Create damage_groups table
707                 lua_newtable(L);
708                 // For each damage group
709                 for(std::map<std::string, s16>::const_iterator
710                                 i = toolcap.damageGroups.begin(); i != toolcap.damageGroups.end(); i++){
711                         // Create damage group table
712                         lua_pushinteger(L, i->second);
713                         lua_setfield(L, -2, i->first.c_str());
714                 }
715                 lua_setfield(L, -2, "damage_groups");
716 }
717
718 /******************************************************************************/
719 void push_inventory_list(lua_State *L, Inventory *inv, const char *name)
720 {
721         InventoryList *invlist = inv->getList(name);
722         if(invlist == NULL){
723                 lua_pushnil(L);
724                 return;
725         }
726         std::vector<ItemStack> items;
727         for(u32 i=0; i<invlist->getSize(); i++)
728                 items.push_back(invlist->getItem(i));
729         push_items(L, items);
730 }
731
732 /******************************************************************************/
733 void read_inventory_list(lua_State *L, int tableindex,
734                 Inventory *inv, const char *name, Server* srv, int forcesize)
735 {
736         if(tableindex < 0)
737                 tableindex = lua_gettop(L) + 1 + tableindex;
738         // If nil, delete list
739         if(lua_isnil(L, tableindex)){
740                 inv->deleteList(name);
741                 return;
742         }
743         // Otherwise set list
744         std::vector<ItemStack> items = read_items(L, tableindex,srv);
745         int listsize = (forcesize != -1) ? forcesize : items.size();
746         InventoryList *invlist = inv->addList(name, listsize);
747         int index = 0;
748         for(std::vector<ItemStack>::const_iterator
749                         i = items.begin(); i != items.end(); i++){
750                 if(forcesize != -1 && index == forcesize)
751                         break;
752                 invlist->changeItem(index, *i);
753                 index++;
754         }
755         while(forcesize != -1 && index < forcesize){
756                 invlist->deleteItem(index);
757                 index++;
758         }
759 }
760
761 /******************************************************************************/
762 ToolCapabilities read_tool_capabilities(
763                 lua_State *L, int table)
764 {
765         ToolCapabilities toolcap;
766         getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
767         getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
768         lua_getfield(L, table, "groupcaps");
769         if(lua_istable(L, -1)){
770                 int table_groupcaps = lua_gettop(L);
771                 lua_pushnil(L);
772                 while(lua_next(L, table_groupcaps) != 0){
773                         // key at index -2 and value at index -1
774                         std::string groupname = luaL_checkstring(L, -2);
775                         if(lua_istable(L, -1)){
776                                 int table_groupcap = lua_gettop(L);
777                                 // This will be created
778                                 ToolGroupCap groupcap;
779                                 // Read simple parameters
780                                 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
781                                 getintfield(L, table_groupcap, "uses", groupcap.uses);
782                                 // DEPRECATED: maxwear
783                                 float maxwear = 0;
784                                 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
785                                         if(maxwear != 0)
786                                                 groupcap.uses = 1.0/maxwear;
787                                         else
788                                                 groupcap.uses = 0;
789                                         infostream<<script_get_backtrace(L)<<std::endl;
790                                         infostream<<"WARNING: field \"maxwear\" is deprecated; "
791                                                         <<"should replace with uses=1/maxwear"<<std::endl;
792                                 }
793                                 // Read "times" table
794                                 lua_getfield(L, table_groupcap, "times");
795                                 if(lua_istable(L, -1)){
796                                         int table_times = lua_gettop(L);
797                                         lua_pushnil(L);
798                                         while(lua_next(L, table_times) != 0){
799                                                 // key at index -2 and value at index -1
800                                                 int rating = luaL_checkinteger(L, -2);
801                                                 float time = luaL_checknumber(L, -1);
802                                                 groupcap.times[rating] = time;
803                                                 // removes value, keeps key for next iteration
804                                                 lua_pop(L, 1);
805                                         }
806                                 }
807                                 lua_pop(L, 1);
808                                 // Insert groupcap into toolcap
809                                 toolcap.groupcaps[groupname] = groupcap;
810                         }
811                         // removes value, keeps key for next iteration
812                         lua_pop(L, 1);
813                 }
814         }
815         lua_pop(L, 1);
816
817         lua_getfield(L, table, "damage_groups");
818         if(lua_istable(L, -1)){
819                 int table_damage_groups = lua_gettop(L);
820                 lua_pushnil(L);
821                 while(lua_next(L, table_damage_groups) != 0){
822                         // key at index -2 and value at index -1
823                         std::string groupname = luaL_checkstring(L, -2);
824                         u16 value = luaL_checkinteger(L, -1);
825                         toolcap.damageGroups[groupname] = value;
826                         // removes value, keeps key for next iteration
827                         lua_pop(L, 1);
828                 }
829         }
830         lua_pop(L, 1);
831         return toolcap;
832 }
833
834 /******************************************************************************/
835 void push_dig_params(lua_State *L,const DigParams &params)
836 {
837         lua_newtable(L);
838         setboolfield(L, -1, "diggable", params.diggable);
839         setfloatfield(L, -1, "time", params.time);
840         setintfield(L, -1, "wear", params.wear);
841 }
842
843 /******************************************************************************/
844 void push_hit_params(lua_State *L,const HitParams &params)
845 {
846         lua_newtable(L);
847         setintfield(L, -1, "hp", params.hp);
848         setintfield(L, -1, "wear", params.wear);
849 }
850
851 /******************************************************************************/
852
853 bool getflagsfield(lua_State *L, int table, const char *fieldname,
854         FlagDesc *flagdesc, u32 *flags, u32 *flagmask)
855 {
856         lua_getfield(L, table, fieldname);
857
858         bool success = read_flags(L, -1, flagdesc, flags, flagmask);
859
860         lua_pop(L, 1);
861
862         return success;
863 }
864
865 bool read_flags(lua_State *L, int index, FlagDesc *flagdesc,
866         u32 *flags, u32 *flagmask)
867 {
868         if (lua_isstring(L, index)) {
869                 std::string flagstr = lua_tostring(L, index);
870                 *flags = readFlagString(flagstr, flagdesc, flagmask);
871         } else if (lua_istable(L, index)) {
872                 *flags = read_flags_table(L, index, flagdesc, flagmask);
873         } else {
874                 return false;
875         }
876
877         return true;
878 }
879
880 u32 read_flags_table(lua_State *L, int table, FlagDesc *flagdesc, u32 *flagmask)
881 {
882         u32 flags = 0, mask = 0;
883         char fnamebuf[64] = "no";
884
885         for (int i = 0; flagdesc[i].name; i++) {
886                 bool result;
887
888                 if (getboolfield(L, table, flagdesc[i].name, result)) {
889                         mask |= flagdesc[i].flag;
890                         if (result)
891                                 flags |= flagdesc[i].flag;
892                 }
893
894                 strlcpy(fnamebuf + 2, flagdesc[i].name, sizeof(fnamebuf) - 2);
895                 if (getboolfield(L, table, fnamebuf, result))
896                         mask |= flagdesc[i].flag;
897         }
898
899         if (flagmask)
900                 *flagmask = mask;
901
902         return flags;
903 }
904
905 /******************************************************************************/
906 /* Lua Stored data!                                                           */
907 /******************************************************************************/
908
909 /******************************************************************************/
910 void read_groups(lua_State *L, int index,
911                 std::map<std::string, int> &result)
912 {
913         if (!lua_istable(L,index))
914                 return;
915         result.clear();
916         lua_pushnil(L);
917         if(index < 0)
918                 index -= 1;
919         while(lua_next(L, index) != 0){
920                 // key at index -2 and value at index -1
921                 std::string name = luaL_checkstring(L, -2);
922                 int rating = luaL_checkinteger(L, -1);
923                 result[name] = rating;
924                 // removes value, keeps key for next iteration
925                 lua_pop(L, 1);
926         }
927 }
928
929 /******************************************************************************/
930 void push_items(lua_State *L, const std::vector<ItemStack> &items)
931 {
932         // Create and fill table
933         lua_createtable(L, items.size(), 0);
934         std::vector<ItemStack>::const_iterator iter = items.begin();
935         for (u32 i = 0; iter != items.end(); iter++) {
936                 LuaItemStack::create(L, *iter);
937                 lua_rawseti(L, -2, ++i);
938         }
939 }
940
941 /******************************************************************************/
942 std::vector<ItemStack> read_items(lua_State *L, int index, Server *srv)
943 {
944         if(index < 0)
945                 index = lua_gettop(L) + 1 + index;
946
947         std::vector<ItemStack> items;
948         luaL_checktype(L, index, LUA_TTABLE);
949         lua_pushnil(L);
950         while (lua_next(L, index)) {
951                 s32 key = luaL_checkinteger(L, -2);
952                 if (key < 1) {
953                         throw LuaError("Invalid inventory list index");
954                 }
955                 if (items.size() < (u32) key) {
956                         items.resize(key);
957                 }
958                 items[key - 1] = read_item(L, -1, srv);
959                 lua_pop(L, 1);
960         }
961         return items;
962 }
963
964 /******************************************************************************/
965 void luaentity_get(lua_State *L, u16 id)
966 {
967         // Get luaentities[i]
968         lua_getglobal(L, "core");
969         lua_getfield(L, -1, "luaentities");
970         luaL_checktype(L, -1, LUA_TTABLE);
971         lua_pushnumber(L, id);
972         lua_gettable(L, -2);
973         lua_remove(L, -2); // Remove luaentities
974         lua_remove(L, -2); // Remove core
975 }
976
977 /******************************************************************************/
978 NoiseParams *read_noiseparams(lua_State *L, int index)
979 {
980         NoiseParams *np = new NoiseParams;
981
982         if (!read_noiseparams_nc(L, index, np)) {
983                 delete np;
984                 np = NULL;
985         }
986
987         return np;
988 }
989
990 bool read_noiseparams_nc(lua_State *L, int index, NoiseParams *np)
991 {
992         if (index < 0)
993                 index = lua_gettop(L) + 1 + index;
994
995         if (!lua_istable(L, index))
996                 return false;
997
998         np->offset  = getfloatfield_default(L, index, "offset",  0.0);
999         np->scale   = getfloatfield_default(L, index, "scale",   0.0);
1000         np->persist = getfloatfield_default(L, index, "persist", 0.0);
1001         np->seed    = getintfield_default(L,   index, "seed",    0);
1002         np->octaves = getintfield_default(L,   index, "octaves", 0);
1003         np->eased   = getboolfield_default(L,  index, "eased",   false);
1004
1005         lua_getfield(L, index, "spread");
1006         np->spread  = read_v3f(L, -1);
1007         lua_pop(L, 1);
1008
1009         return true;
1010 }
1011
1012 /******************************************************************************/
1013
1014 bool get_schematic(lua_State *L, int index, Schematic *schem,
1015         INodeDefManager *ndef, std::map<std::string, std::string> &replace_names)
1016 {
1017         if (index < 0)
1018                 index = lua_gettop(L) + 1 + index;
1019
1020         if (lua_istable(L, index)) {
1021                 return read_schematic(L, index, schem, ndef, replace_names);
1022         } else if (lua_isstring(L, index)) {
1023                 NodeResolver *resolver = ndef->getResolver();
1024                 const char *filename = lua_tostring(L, index);
1025                 return schem->loadSchematicFromFile(filename, resolver, replace_names);
1026         } else {
1027                 return false;
1028         }
1029 }
1030
1031 bool read_schematic(lua_State *L, int index, Schematic *schem,
1032         INodeDefManager *ndef, std::map<std::string, std::string> &replace_names)
1033 {
1034         //// Get schematic size
1035         lua_getfield(L, index, "size");
1036         v3s16 size = read_v3s16(L, -1);
1037         lua_pop(L, 1);
1038
1039         //// Get schematic data
1040         lua_getfield(L, index, "data");
1041         luaL_checktype(L, -1, LUA_TTABLE);
1042
1043         int numnodes = size.X * size.Y * size.Z;
1044         MapNode *schemdata = new MapNode[numnodes];
1045         int i = 0;
1046
1047         lua_pushnil(L);
1048         while (lua_next(L, -2)) {
1049                 if (i < numnodes) {
1050                         // same as readnode, except param1 default is MTSCHEM_PROB_CONST
1051                         lua_getfield(L, -1, "name");
1052                         std::string name = luaL_checkstring(L, -1);
1053                         lua_pop(L, 1);
1054
1055                         u8 param1;
1056                         lua_getfield(L, -1, "param1");
1057                         param1 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : MTSCHEM_PROB_ALWAYS;
1058                         lua_pop(L, 1);
1059
1060                         u8 param2;
1061                         lua_getfield(L, -1, "param2");
1062                         param2 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : 0;
1063                         lua_pop(L, 1);
1064
1065                         std::map<std::string, std::string>::iterator it;
1066                         it = replace_names.find(name);
1067                         if (it != replace_names.end())
1068                                 name = it->second;
1069
1070                         schemdata[i] = MapNode(ndef, name, param1, param2);
1071                 }
1072
1073                 i++;
1074                 lua_pop(L, 1);
1075         }
1076
1077         if (i != numnodes) {
1078                 errorstream << "read_schematic: incorrect number of "
1079                         "nodes provided in raw schematic data (got " << i <<
1080                         ", expected " << numnodes << ")." << std::endl;
1081                 return false;
1082         }
1083
1084         //// Get Y-slice probability values (if present)
1085         u8 *slice_probs = new u8[size.Y];
1086         for (i = 0; i != size.Y; i++)
1087                 slice_probs[i] = MTSCHEM_PROB_ALWAYS;
1088
1089         lua_getfield(L, index, "yslice_prob");
1090         if (lua_istable(L, -1)) {
1091                 lua_pushnil(L);
1092                 while (lua_next(L, -2)) {
1093                         if (getintfield(L, -1, "ypos", i) && i >= 0 && i < size.Y) {
1094                                 slice_probs[i] = getintfield_default(L, -1,
1095                                         "prob", MTSCHEM_PROB_ALWAYS);
1096                         }
1097                         lua_pop(L, 1);
1098                 }
1099         }
1100
1101         // Here, we read the nodes directly from the INodeDefManager - there is no
1102         // need for pending node resolutions so we'll mark this schematic as updated
1103         schem->flags       = SCHEM_CIDS_UPDATED;
1104
1105         schem->size        = size;
1106         schem->schemdata   = schemdata;
1107         schem->slice_probs = slice_probs;
1108         return true;
1109 }
1110
1111 /******************************************************************************/
1112 // Returns depth of json value tree
1113 static int push_json_value_getdepth(const Json::Value &value)
1114 {
1115         if (!value.isArray() && !value.isObject())
1116                 return 1;
1117
1118         int maxdepth = 0;
1119         for (Json::Value::const_iterator it = value.begin();
1120                         it != value.end(); ++it) {
1121                 int elemdepth = push_json_value_getdepth(*it);
1122                 if (elemdepth > maxdepth)
1123                         maxdepth = elemdepth;
1124         }
1125         return maxdepth + 1;
1126 }
1127 // Recursive function to convert JSON --> Lua table
1128 static bool push_json_value_helper(lua_State *L, const Json::Value &value,
1129                 int nullindex)
1130 {
1131         switch(value.type()) {
1132                 case Json::nullValue:
1133                 default:
1134                         lua_pushvalue(L, nullindex);
1135                         break;
1136                 case Json::intValue:
1137                         lua_pushinteger(L, value.asInt());
1138                         break;
1139                 case Json::uintValue:
1140                         lua_pushinteger(L, value.asUInt());
1141                         break;
1142                 case Json::realValue:
1143                         lua_pushnumber(L, value.asDouble());
1144                         break;
1145                 case Json::stringValue:
1146                         {
1147                                 const char *str = value.asCString();
1148                                 lua_pushstring(L, str ? str : "");
1149                         }
1150                         break;
1151                 case Json::booleanValue:
1152                         lua_pushboolean(L, value.asInt());
1153                         break;
1154                 case Json::arrayValue:
1155                         lua_newtable(L);
1156                         for (Json::Value::const_iterator it = value.begin();
1157                                         it != value.end(); ++it) {
1158                                 push_json_value_helper(L, *it, nullindex);
1159                                 lua_rawseti(L, -2, it.index() + 1);
1160                         }
1161                         break;
1162                 case Json::objectValue:
1163                         lua_newtable(L);
1164                         for (Json::Value::const_iterator it = value.begin();
1165                                         it != value.end(); ++it) {
1166                                 const char *str = it.memberName();
1167                                 lua_pushstring(L, str ? str : "");
1168                                 push_json_value_helper(L, *it, nullindex);
1169                                 lua_rawset(L, -3);
1170                         }
1171                         break;
1172         }
1173         return true;
1174 }
1175 // converts JSON --> Lua table; returns false if lua stack limit exceeded
1176 // nullindex: Lua stack index of value to use in place of JSON null
1177 bool push_json_value(lua_State *L, const Json::Value &value, int nullindex)
1178 {
1179         if(nullindex < 0)
1180                 nullindex = lua_gettop(L) + 1 + nullindex;
1181
1182         int depth = push_json_value_getdepth(value);
1183
1184         // The maximum number of Lua stack slots used at each recursion level
1185         // of push_json_value_helper is 2, so make sure there a depth * 2 slots
1186         if (lua_checkstack(L, depth * 2))
1187                 return push_json_value_helper(L, value, nullindex);
1188         else
1189                 return false;
1190 }
1191
1192 // Converts Lua table --> JSON
1193 void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion)
1194 {
1195         if (recursion > 16) {
1196                 throw SerializationError("Maximum recursion depth exceeded");
1197         }
1198         int type = lua_type(L, index);
1199         if (type == LUA_TBOOLEAN) {
1200                 root = (bool) lua_toboolean(L, index);
1201         } else if (type == LUA_TNUMBER) {
1202                 root = lua_tonumber(L, index);
1203         } else if (type == LUA_TSTRING) {
1204                 size_t len;
1205                 const char *str = lua_tolstring(L, index, &len);
1206                 root = std::string(str, len);
1207         } else if (type == LUA_TTABLE) {
1208                 lua_pushnil(L);
1209                 while (lua_next(L, index)) {
1210                         // Key is at -2 and value is at -1
1211                         Json::Value value;
1212                         read_json_value(L, value, lua_gettop(L), recursion + 1);
1213
1214                         Json::ValueType roottype = root.type();
1215                         int keytype = lua_type(L, -1);
1216                         if (keytype == LUA_TNUMBER) {
1217                                 lua_Number key = lua_tonumber(L, -1);
1218                                 if (roottype != Json::nullValue && roottype != Json::arrayValue) {
1219                                         throw SerializationError("Can't mix array and object values in JSON");
1220                                 } else if (key < 1) {
1221                                         throw SerializationError("Can't use zero-based or negative indexes in JSON");
1222                                 } else if (floor(key) != key) {
1223                                         throw SerializationError("Can't use indexes with a fractional part in JSON");
1224                                 }
1225                                 root[(Json::ArrayIndex) key - 1] = value;
1226                         } else if (keytype == LUA_TSTRING) {
1227                                 if (roottype != Json::nullValue && roottype != Json::objectValue) {
1228                                         throw SerializationError("Can't mix array and object values in JSON");
1229                                 }
1230                                 root[lua_tostring(L, -1)] = value;
1231                         } else {
1232                                 throw SerializationError("Lua key to convert to JSON is not a string or number");
1233                         }
1234                 }
1235         } else if (type == LUA_TNIL) {
1236                 root = Json::nullValue;
1237         } else {
1238                 throw SerializationError("Can only store booleans, numbers, strings, objects, arrays, and null in JSON");
1239         }
1240         lua_pop(L, 1); // Pop value
1241 }
1242