]> git.lizzy.rs Git - minetest.git/blob - src/script/common/c_content.cpp
Add 'persistence' alias for Lua noiseparams and validate more vector parameters
[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         f.drowning = getintfield_default(L, index,
418                         "drowning", f.drowning);
419         // Amount of light the node emits
420         f.light_source = getintfield_default(L, index,
421                         "light_source", f.light_source);
422         f.damage_per_second = getintfield_default(L, index,
423                         "damage_per_second", f.damage_per_second);
424
425         lua_getfield(L, index, "node_box");
426         if(lua_istable(L, -1))
427                 f.node_box = read_nodebox(L, -1);
428         lua_pop(L, 1);
429
430         lua_getfield(L, index, "selection_box");
431         if(lua_istable(L, -1))
432                 f.selection_box = read_nodebox(L, -1);
433         lua_pop(L, 1);
434
435         lua_getfield(L, index, "collision_box");
436         if(lua_istable(L, -1))
437                 f.collision_box = read_nodebox(L, -1);
438         lua_pop(L, 1);
439
440         f.waving = getintfield_default(L, index,
441                         "waving", f.waving);
442
443         // Set to true if paramtype used to be 'facedir_simple'
444         getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
445         // Set to true if wall_mounted used to be set to true
446         getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
447
448         // Sound table
449         lua_getfield(L, index, "sounds");
450         if(lua_istable(L, -1)){
451                 lua_getfield(L, -1, "footstep");
452                 read_soundspec(L, -1, f.sound_footstep);
453                 lua_pop(L, 1);
454                 lua_getfield(L, -1, "dig");
455                 read_soundspec(L, -1, f.sound_dig);
456                 lua_pop(L, 1);
457                 lua_getfield(L, -1, "dug");
458                 read_soundspec(L, -1, f.sound_dug);
459                 lua_pop(L, 1);
460         }
461         lua_pop(L, 1);
462
463         return f;
464 }
465
466 /******************************************************************************/
467 void read_server_sound_params(lua_State *L, int index,
468                 ServerSoundParams &params)
469 {
470         if(index < 0)
471                 index = lua_gettop(L) + 1 + index;
472         // Clear
473         params = ServerSoundParams();
474         if(lua_istable(L, index)){
475                 getfloatfield(L, index, "gain", params.gain);
476                 getstringfield(L, index, "to_player", params.to_player);
477                 lua_getfield(L, index, "pos");
478                 if(!lua_isnil(L, -1)){
479                         v3f p = read_v3f(L, -1)*BS;
480                         params.pos = p;
481                         params.type = ServerSoundParams::SSP_POSITIONAL;
482                 }
483                 lua_pop(L, 1);
484                 lua_getfield(L, index, "object");
485                 if(!lua_isnil(L, -1)){
486                         ObjectRef *ref = ObjectRef::checkobject(L, -1);
487                         ServerActiveObject *sao = ObjectRef::getobject(ref);
488                         if(sao){
489                                 params.object = sao->getId();
490                                 params.type = ServerSoundParams::SSP_OBJECT;
491                         }
492                 }
493                 lua_pop(L, 1);
494                 params.max_hear_distance = BS*getfloatfield_default(L, index,
495                                 "max_hear_distance", params.max_hear_distance/BS);
496                 getboolfield(L, index, "loop", params.loop);
497         }
498 }
499
500 /******************************************************************************/
501 void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
502 {
503         if(index < 0)
504                 index = lua_gettop(L) + 1 + index;
505         if(lua_isnil(L, index)){
506         } else if(lua_istable(L, index)){
507                 getstringfield(L, index, "name", spec.name);
508                 getfloatfield(L, index, "gain", spec.gain);
509         } else if(lua_isstring(L, index)){
510                 spec.name = lua_tostring(L, index);
511         }
512 }
513
514 /******************************************************************************/
515 NodeBox read_nodebox(lua_State *L, int index)
516 {
517         NodeBox nodebox;
518         if(lua_istable(L, -1)){
519                 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
520                                 ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR);
521
522                 lua_getfield(L, index, "fixed");
523                 if(lua_istable(L, -1))
524                         nodebox.fixed = read_aabb3f_vector(L, -1, BS);
525                 lua_pop(L, 1);
526
527                 lua_getfield(L, index, "wall_top");
528                 if(lua_istable(L, -1))
529                         nodebox.wall_top = read_aabb3f(L, -1, BS);
530                 lua_pop(L, 1);
531
532                 lua_getfield(L, index, "wall_bottom");
533                 if(lua_istable(L, -1))
534                         nodebox.wall_bottom = read_aabb3f(L, -1, BS);
535                 lua_pop(L, 1);
536
537                 lua_getfield(L, index, "wall_side");
538                 if(lua_istable(L, -1))
539                         nodebox.wall_side = read_aabb3f(L, -1, BS);
540                 lua_pop(L, 1);
541         }
542         return nodebox;
543 }
544
545 /******************************************************************************/
546 MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
547 {
548         lua_getfield(L, index, "name");
549         if (!lua_isstring(L, -1))
550                 throw LuaError("Node name is not set or is not a string!");
551         const char *name = lua_tostring(L, -1);
552         lua_pop(L, 1);
553
554         u8 param1 = 0;
555         lua_getfield(L, index, "param1");
556         if (!lua_isnil(L, -1))
557                 param1 = lua_tonumber(L, -1);
558         lua_pop(L, 1);
559
560         u8 param2 = 0;
561         lua_getfield(L, index, "param2");
562         if (!lua_isnil(L, -1))
563                 param2 = lua_tonumber(L, -1);
564         lua_pop(L, 1);
565
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 bool read_noiseparams(lua_State *L, int index, NoiseParams *np)
979 {
980         if (index < 0)
981                 index = lua_gettop(L) + 1 + index;
982
983         if (!lua_istable(L, index))
984                 return false;
985
986         getfloatfield(L, index, "offset",      np->offset);
987         getfloatfield(L, index, "scale",       np->scale);
988         getfloatfield(L, index, "persist",     np->persist);
989         getfloatfield(L, index, "persistence", np->persist);
990         getfloatfield(L, index, "lacunarity",  np->lacunarity);
991         getintfield(L,   index, "seed",        np->seed);
992         getintfield(L,   index, "octaves",     np->octaves);
993
994         u32 flags    = 0;
995         u32 flagmask = 0;
996         np->flags = getflagsfield(L, index, "flags", flagdesc_noiseparams,
997                 &flags, &flagmask) ? flags : NOISE_FLAG_DEFAULTS;
998
999         lua_getfield(L, index, "spread");
1000         np->spread  = read_v3f(L, -1);
1001         lua_pop(L, 1);
1002
1003         return true;
1004 }
1005
1006 /******************************************************************************/
1007 // Returns depth of json value tree
1008 static int push_json_value_getdepth(const Json::Value &value)
1009 {
1010         if (!value.isArray() && !value.isObject())
1011                 return 1;
1012
1013         int maxdepth = 0;
1014         for (Json::Value::const_iterator it = value.begin();
1015                         it != value.end(); ++it) {
1016                 int elemdepth = push_json_value_getdepth(*it);
1017                 if (elemdepth > maxdepth)
1018                         maxdepth = elemdepth;
1019         }
1020         return maxdepth + 1;
1021 }
1022 // Recursive function to convert JSON --> Lua table
1023 static bool push_json_value_helper(lua_State *L, const Json::Value &value,
1024                 int nullindex)
1025 {
1026         switch(value.type()) {
1027                 case Json::nullValue:
1028                 default:
1029                         lua_pushvalue(L, nullindex);
1030                         break;
1031                 case Json::intValue:
1032                         lua_pushinteger(L, value.asInt());
1033                         break;
1034                 case Json::uintValue:
1035                         lua_pushinteger(L, value.asUInt());
1036                         break;
1037                 case Json::realValue:
1038                         lua_pushnumber(L, value.asDouble());
1039                         break;
1040                 case Json::stringValue:
1041                         {
1042                                 const char *str = value.asCString();
1043                                 lua_pushstring(L, str ? str : "");
1044                         }
1045                         break;
1046                 case Json::booleanValue:
1047                         lua_pushboolean(L, value.asInt());
1048                         break;
1049                 case Json::arrayValue:
1050                         lua_newtable(L);
1051                         for (Json::Value::const_iterator it = value.begin();
1052                                         it != value.end(); ++it) {
1053                                 push_json_value_helper(L, *it, nullindex);
1054                                 lua_rawseti(L, -2, it.index() + 1);
1055                         }
1056                         break;
1057                 case Json::objectValue:
1058                         lua_newtable(L);
1059                         for (Json::Value::const_iterator it = value.begin();
1060                                         it != value.end(); ++it) {
1061                                 const char *str = it.memberName();
1062                                 lua_pushstring(L, str ? str : "");
1063                                 push_json_value_helper(L, *it, nullindex);
1064                                 lua_rawset(L, -3);
1065                         }
1066                         break;
1067         }
1068         return true;
1069 }
1070 // converts JSON --> Lua table; returns false if lua stack limit exceeded
1071 // nullindex: Lua stack index of value to use in place of JSON null
1072 bool push_json_value(lua_State *L, const Json::Value &value, int nullindex)
1073 {
1074         if(nullindex < 0)
1075                 nullindex = lua_gettop(L) + 1 + nullindex;
1076
1077         int depth = push_json_value_getdepth(value);
1078
1079         // The maximum number of Lua stack slots used at each recursion level
1080         // of push_json_value_helper is 2, so make sure there a depth * 2 slots
1081         if (lua_checkstack(L, depth * 2))
1082                 return push_json_value_helper(L, value, nullindex);
1083         else
1084                 return false;
1085 }
1086
1087 // Converts Lua table --> JSON
1088 void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion)
1089 {
1090         if (recursion > 16) {
1091                 throw SerializationError("Maximum recursion depth exceeded");
1092         }
1093         int type = lua_type(L, index);
1094         if (type == LUA_TBOOLEAN) {
1095                 root = (bool) lua_toboolean(L, index);
1096         } else if (type == LUA_TNUMBER) {
1097                 root = lua_tonumber(L, index);
1098         } else if (type == LUA_TSTRING) {
1099                 size_t len;
1100                 const char *str = lua_tolstring(L, index, &len);
1101                 root = std::string(str, len);
1102         } else if (type == LUA_TTABLE) {
1103                 lua_pushnil(L);
1104                 while (lua_next(L, index)) {
1105                         // Key is at -2 and value is at -1
1106                         Json::Value value;
1107                         read_json_value(L, value, lua_gettop(L), recursion + 1);
1108
1109                         Json::ValueType roottype = root.type();
1110                         int keytype = lua_type(L, -1);
1111                         if (keytype == LUA_TNUMBER) {
1112                                 lua_Number key = lua_tonumber(L, -1);
1113                                 if (roottype != Json::nullValue && roottype != Json::arrayValue) {
1114                                         throw SerializationError("Can't mix array and object values in JSON");
1115                                 } else if (key < 1) {
1116                                         throw SerializationError("Can't use zero-based or negative indexes in JSON");
1117                                 } else if (floor(key) != key) {
1118                                         throw SerializationError("Can't use indexes with a fractional part in JSON");
1119                                 }
1120                                 root[(Json::ArrayIndex) key - 1] = value;
1121                         } else if (keytype == LUA_TSTRING) {
1122                                 if (roottype != Json::nullValue && roottype != Json::objectValue) {
1123                                         throw SerializationError("Can't mix array and object values in JSON");
1124                                 }
1125                                 root[lua_tostring(L, -1)] = value;
1126                         } else {
1127                                 throw SerializationError("Lua key to convert to JSON is not a string or number");
1128                         }
1129                 }
1130         } else if (type == LUA_TNIL) {
1131                 root = Json::nullValue;
1132         } else {
1133                 throw SerializationError("Can only store booleans, numbers, strings, objects, arrays, and null in JSON");
1134         }
1135         lua_pop(L, 1); // Pop value
1136 }
1137