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