]> git.lizzy.rs Git - minetest.git/blob - src/script/common/c_content.cpp
Pass a errfunc to lua_pcall to get a traceback
[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==6){
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         // Set to true if paramtype used to be 'facedir_simple'
432         getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
433         // Set to true if wall_mounted used to be set to true
434         getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
435
436         // Sound table
437         lua_getfield(L, index, "sounds");
438         if(lua_istable(L, -1)){
439                 lua_getfield(L, -1, "footstep");
440                 read_soundspec(L, -1, f.sound_footstep);
441                 lua_pop(L, 1);
442                 lua_getfield(L, -1, "dig");
443                 read_soundspec(L, -1, f.sound_dig);
444                 lua_pop(L, 1);
445                 lua_getfield(L, -1, "dug");
446                 read_soundspec(L, -1, f.sound_dug);
447                 lua_pop(L, 1);
448         }
449         lua_pop(L, 1);
450
451         return f;
452 }
453
454 /******************************************************************************/
455 void read_server_sound_params(lua_State *L, int index,
456                 ServerSoundParams &params)
457 {
458         if(index < 0)
459                 index = lua_gettop(L) + 1 + index;
460         // Clear
461         params = ServerSoundParams();
462         if(lua_istable(L, index)){
463                 getfloatfield(L, index, "gain", params.gain);
464                 getstringfield(L, index, "to_player", params.to_player);
465                 lua_getfield(L, index, "pos");
466                 if(!lua_isnil(L, -1)){
467                         v3f p = read_v3f(L, -1)*BS;
468                         params.pos = p;
469                         params.type = ServerSoundParams::SSP_POSITIONAL;
470                 }
471                 lua_pop(L, 1);
472                 lua_getfield(L, index, "object");
473                 if(!lua_isnil(L, -1)){
474                         ObjectRef *ref = ObjectRef::checkobject(L, -1);
475                         ServerActiveObject *sao = ObjectRef::getobject(ref);
476                         if(sao){
477                                 params.object = sao->getId();
478                                 params.type = ServerSoundParams::SSP_OBJECT;
479                         }
480                 }
481                 lua_pop(L, 1);
482                 params.max_hear_distance = BS*getfloatfield_default(L, index,
483                                 "max_hear_distance", params.max_hear_distance/BS);
484                 getboolfield(L, index, "loop", params.loop);
485         }
486 }
487
488 /******************************************************************************/
489 void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
490 {
491         if(index < 0)
492                 index = lua_gettop(L) + 1 + index;
493         if(lua_isnil(L, index)){
494         } else if(lua_istable(L, index)){
495                 getstringfield(L, index, "name", spec.name);
496                 getfloatfield(L, index, "gain", spec.gain);
497         } else if(lua_isstring(L, index)){
498                 spec.name = lua_tostring(L, index);
499         }
500 }
501
502 /******************************************************************************/
503 NodeBox read_nodebox(lua_State *L, int index)
504 {
505         NodeBox nodebox;
506         if(lua_istable(L, -1)){
507                 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
508                                 ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR);
509
510                 lua_getfield(L, index, "fixed");
511                 if(lua_istable(L, -1))
512                         nodebox.fixed = read_aabb3f_vector(L, -1, BS);
513                 lua_pop(L, 1);
514
515                 lua_getfield(L, index, "wall_top");
516                 if(lua_istable(L, -1))
517                         nodebox.wall_top = read_aabb3f(L, -1, BS);
518                 lua_pop(L, 1);
519
520                 lua_getfield(L, index, "wall_bottom");
521                 if(lua_istable(L, -1))
522                         nodebox.wall_bottom = read_aabb3f(L, -1, BS);
523                 lua_pop(L, 1);
524
525                 lua_getfield(L, index, "wall_side");
526                 if(lua_istable(L, -1))
527                         nodebox.wall_side = read_aabb3f(L, -1, BS);
528                 lua_pop(L, 1);
529         }
530         return nodebox;
531 }
532
533 /******************************************************************************/
534 MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
535 {
536         lua_getfield(L, index, "name");
537         const char *name = luaL_checkstring(L, -1);
538         lua_pop(L, 1);
539         u8 param1;
540         lua_getfield(L, index, "param1");
541         if(lua_isnil(L, -1))
542                 param1 = 0;
543         else
544                 param1 = lua_tonumber(L, -1);
545         lua_pop(L, 1);
546         u8 param2;
547         lua_getfield(L, index, "param2");
548         if(lua_isnil(L, -1))
549                 param2 = 0;
550         else
551                 param2 = lua_tonumber(L, -1);
552         lua_pop(L, 1);
553         return MapNode(ndef, name, param1, param2);
554 }
555
556 /******************************************************************************/
557 void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
558 {
559         lua_newtable(L);
560         lua_pushstring(L, ndef->get(n).name.c_str());
561         lua_setfield(L, -2, "name");
562         lua_pushnumber(L, n.getParam1());
563         lua_setfield(L, -2, "param1");
564         lua_pushnumber(L, n.getParam2());
565         lua_setfield(L, -2, "param2");
566 }
567
568 /******************************************************************************/
569 void warn_if_field_exists(lua_State *L, int table,
570                 const char *fieldname, const std::string &message)
571 {
572         lua_getfield(L, table, fieldname);
573         if(!lua_isnil(L, -1)){
574 //TODO find way to access backtrace fct from here
575                 //              infostream<<script_get_backtrace(L)<<std::endl;
576                 infostream<<"WARNING: field \""<<fieldname<<"\": "
577                                 <<message<<std::endl;
578         }
579         lua_pop(L, 1);
580 }
581
582 /******************************************************************************/
583 int getenumfield(lua_State *L, int table,
584                 const char *fieldname, const EnumString *spec, int default_)
585 {
586         int result = default_;
587         string_to_enum(spec, result,
588                         getstringfield_default(L, table, fieldname, ""));
589         return result;
590 }
591
592 /******************************************************************************/
593 bool string_to_enum(const EnumString *spec, int &result,
594                 const std::string &str)
595 {
596         const EnumString *esp = spec;
597         while(esp->str){
598                 if(str == std::string(esp->str)){
599                         result = esp->num;
600                         return true;
601                 }
602                 esp++;
603         }
604         return false;
605 }
606
607 /******************************************************************************/
608 ItemStack read_item(lua_State* L, int index,Server* srv)
609 {
610         if(index < 0)
611                 index = lua_gettop(L) + 1 + index;
612
613         if(lua_isnil(L, index))
614         {
615                 return ItemStack();
616         }
617         else if(lua_isuserdata(L, index))
618         {
619                 // Convert from LuaItemStack
620                 LuaItemStack *o = LuaItemStack::checkobject(L, index);
621                 return o->getItem();
622         }
623         else if(lua_isstring(L, index))
624         {
625                 // Convert from itemstring
626                 std::string itemstring = lua_tostring(L, index);
627                 IItemDefManager *idef = srv->idef();
628                 try
629                 {
630                         ItemStack item;
631                         item.deSerialize(itemstring, idef);
632                         return item;
633                 }
634                 catch(SerializationError &e)
635                 {
636                         infostream<<"WARNING: unable to create item from itemstring"
637                                         <<": "<<itemstring<<std::endl;
638                         return ItemStack();
639                 }
640         }
641         else if(lua_istable(L, index))
642         {
643                 // Convert from table
644                 IItemDefManager *idef = srv->idef();
645                 std::string name = getstringfield_default(L, index, "name", "");
646                 int count = getintfield_default(L, index, "count", 1);
647                 int wear = getintfield_default(L, index, "wear", 0);
648                 std::string metadata = getstringfield_default(L, index, "metadata", "");
649                 return ItemStack(name, count, wear, metadata, idef);
650         }
651         else
652         {
653                 throw LuaError(L, "Expecting itemstack, itemstring, table or nil");
654         }
655 }
656
657 /******************************************************************************/
658 void push_tool_capabilities(lua_State *L,
659                 const ToolCapabilities &toolcap)
660 {
661         lua_newtable(L);
662         setfloatfield(L, -1, "full_punch_interval", toolcap.full_punch_interval);
663                 setintfield(L, -1, "max_drop_level", toolcap.max_drop_level);
664                 // Create groupcaps table
665                 lua_newtable(L);
666                 // For each groupcap
667                 for(std::map<std::string, ToolGroupCap>::const_iterator
668                                 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
669                         // Create groupcap table
670                         lua_newtable(L);
671                         const std::string &name = i->first;
672                         const ToolGroupCap &groupcap = i->second;
673                         // Create subtable "times"
674                         lua_newtable(L);
675                         for(std::map<int, float>::const_iterator
676                                         i = groupcap.times.begin(); i != groupcap.times.end(); i++){
677                                 int rating = i->first;
678                                 float time = i->second;
679                                 lua_pushinteger(L, rating);
680                                 lua_pushnumber(L, time);
681                                 lua_settable(L, -3);
682                         }
683                         // Set subtable "times"
684                         lua_setfield(L, -2, "times");
685                         // Set simple parameters
686                         setintfield(L, -1, "maxlevel", groupcap.maxlevel);
687                         setintfield(L, -1, "uses", groupcap.uses);
688                         // Insert groupcap table into groupcaps table
689                         lua_setfield(L, -2, name.c_str());
690                 }
691                 // Set groupcaps table
692                 lua_setfield(L, -2, "groupcaps");
693                 //Create damage_groups table
694                 lua_newtable(L);
695                 // For each damage group
696                 for(std::map<std::string, s16>::const_iterator
697                                 i = toolcap.damageGroups.begin(); i != toolcap.damageGroups.end(); i++){
698                         // Create damage group table
699                         lua_pushinteger(L, i->second);
700                         lua_setfield(L, -2, i->first.c_str());
701                 }
702                 lua_setfield(L, -2, "damage_groups");
703 }
704
705 /******************************************************************************/
706 void push_inventory_list(lua_State *L, Inventory *inv, const char *name)
707 {
708         InventoryList *invlist = inv->getList(name);
709         if(invlist == NULL){
710                 lua_pushnil(L);
711                 return;
712         }
713         std::vector<ItemStack> items;
714         for(u32 i=0; i<invlist->getSize(); i++)
715                 items.push_back(invlist->getItem(i));
716         push_items(L, items);
717 }
718
719 /******************************************************************************/
720 void read_inventory_list(lua_State *L, int tableindex,
721                 Inventory *inv, const char *name, Server* srv, int forcesize)
722 {
723         if(tableindex < 0)
724                 tableindex = lua_gettop(L) + 1 + tableindex;
725         // If nil, delete list
726         if(lua_isnil(L, tableindex)){
727                 inv->deleteList(name);
728                 return;
729         }
730         // Otherwise set list
731         std::vector<ItemStack> items = read_items(L, tableindex,srv);
732         int listsize = (forcesize != -1) ? forcesize : items.size();
733         InventoryList *invlist = inv->addList(name, listsize);
734         int index = 0;
735         for(std::vector<ItemStack>::const_iterator
736                         i = items.begin(); i != items.end(); i++){
737                 if(forcesize != -1 && index == forcesize)
738                         break;
739                 invlist->changeItem(index, *i);
740                 index++;
741         }
742         while(forcesize != -1 && index < forcesize){
743                 invlist->deleteItem(index);
744                 index++;
745         }
746 }
747
748 /******************************************************************************/
749 ToolCapabilities read_tool_capabilities(
750                 lua_State *L, int table)
751 {
752         ToolCapabilities toolcap;
753         getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
754         getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
755         lua_getfield(L, table, "groupcaps");
756         if(lua_istable(L, -1)){
757                 int table_groupcaps = lua_gettop(L);
758                 lua_pushnil(L);
759                 while(lua_next(L, table_groupcaps) != 0){
760                         // key at index -2 and value at index -1
761                         std::string groupname = luaL_checkstring(L, -2);
762                         if(lua_istable(L, -1)){
763                                 int table_groupcap = lua_gettop(L);
764                                 // This will be created
765                                 ToolGroupCap groupcap;
766                                 // Read simple parameters
767                                 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
768                                 getintfield(L, table_groupcap, "uses", groupcap.uses);
769                                 // DEPRECATED: maxwear
770                                 float maxwear = 0;
771                                 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
772                                         if(maxwear != 0)
773                                                 groupcap.uses = 1.0/maxwear;
774                                         else
775                                                 groupcap.uses = 0;
776                                         infostream<<script_get_backtrace(L)<<std::endl;
777                                         infostream<<"WARNING: field \"maxwear\" is deprecated; "
778                                                         <<"should replace with uses=1/maxwear"<<std::endl;
779                                 }
780                                 // Read "times" table
781                                 lua_getfield(L, table_groupcap, "times");
782                                 if(lua_istable(L, -1)){
783                                         int table_times = lua_gettop(L);
784                                         lua_pushnil(L);
785                                         while(lua_next(L, table_times) != 0){
786                                                 // key at index -2 and value at index -1
787                                                 int rating = luaL_checkinteger(L, -2);
788                                                 float time = luaL_checknumber(L, -1);
789                                                 groupcap.times[rating] = time;
790                                                 // removes value, keeps key for next iteration
791                                                 lua_pop(L, 1);
792                                         }
793                                 }
794                                 lua_pop(L, 1);
795                                 // Insert groupcap into toolcap
796                                 toolcap.groupcaps[groupname] = groupcap;
797                         }
798                         // removes value, keeps key for next iteration
799                         lua_pop(L, 1);
800                 }
801         }
802         lua_pop(L, 1);
803
804         lua_getfield(L, table, "damage_groups");
805         if(lua_istable(L, -1)){
806                 int table_damage_groups = lua_gettop(L);
807                 lua_pushnil(L);
808                 while(lua_next(L, table_damage_groups) != 0){
809                         // key at index -2 and value at index -1
810                         std::string groupname = luaL_checkstring(L, -2);
811                         u16 value = luaL_checkinteger(L, -1);
812                         toolcap.damageGroups[groupname] = value;
813                         // removes value, keeps key for next iteration
814                         lua_pop(L, 1);
815                 }
816         }
817         lua_pop(L, 1);
818         return toolcap;
819 }
820
821 /******************************************************************************/
822 void push_dig_params(lua_State *L,const DigParams &params)
823 {
824         lua_newtable(L);
825         setboolfield(L, -1, "diggable", params.diggable);
826         setfloatfield(L, -1, "time", params.time);
827         setintfield(L, -1, "wear", params.wear);
828 }
829
830 /******************************************************************************/
831 void push_hit_params(lua_State *L,const HitParams &params)
832 {
833         lua_newtable(L);
834         setintfield(L, -1, "hp", params.hp);
835         setintfield(L, -1, "wear", params.wear);
836 }
837
838 /******************************************************************************/
839 u32 getflagsfield(lua_State *L, int table,
840         const char *fieldname, FlagDesc *flagdesc) {
841         std::string flagstring;
842
843         flagstring = getstringfield_default(L, table, fieldname, "");
844         return readFlagString(flagstring, flagdesc);
845 }
846
847 /******************************************************************************/
848 /* Lua Stored data!                                                           */
849 /******************************************************************************/
850
851 /******************************************************************************/
852 void read_groups(lua_State *L, int index,
853                 std::map<std::string, int> &result)
854 {
855         if (!lua_istable(L,index))
856                 return;
857         result.clear();
858         lua_pushnil(L);
859         if(index < 0)
860                 index -= 1;
861         while(lua_next(L, index) != 0){
862                 // key at index -2 and value at index -1
863                 std::string name = luaL_checkstring(L, -2);
864                 int rating = luaL_checkinteger(L, -1);
865                 result[name] = rating;
866                 // removes value, keeps key for next iteration
867                 lua_pop(L, 1);
868         }
869 }
870
871 /******************************************************************************/
872 void push_items(lua_State *L, const std::vector<ItemStack> &items)
873 {
874         lua_pushcfunction(L, script_error_handler);
875         int errorhandler = lua_gettop(L);
876         // Get the table insert function
877         lua_getglobal(L, "table");
878         lua_getfield(L, -1, "insert");
879         int table_insert = lua_gettop(L);
880         // Create and fill table
881         lua_newtable(L);
882         int table = lua_gettop(L);
883         for(u32 i=0; i<items.size(); i++){
884                 ItemStack item = items[i];
885                 lua_pushvalue(L, table_insert);
886                 lua_pushvalue(L, table);
887                 LuaItemStack::create(L, item);
888                 if(lua_pcall(L, 2, 0, errorhandler))
889                         script_error(L);
890         }
891         lua_remove(L, -2); // Remove insert
892         lua_remove(L, -2); // Remove table
893         lua_remove(L, -2); // Remove error handler
894 }
895
896 /******************************************************************************/
897 std::vector<ItemStack> read_items(lua_State *L, int index,Server* srv)
898 {
899         if(index < 0)
900                 index = lua_gettop(L) + 1 + index;
901
902         std::vector<ItemStack> items;
903         luaL_checktype(L, index, LUA_TTABLE);
904         lua_pushnil(L);
905         while(lua_next(L, index) != 0){
906                 // key at index -2 and value at index -1
907                 items.push_back(read_item(L, -1, srv));
908                 // removes value, keeps key for next iteration
909                 lua_pop(L, 1);
910         }
911         return items;
912 }
913
914 /******************************************************************************/
915 void luaentity_get(lua_State *L, u16 id)
916 {
917         // Get minetest.luaentities[i]
918         lua_getglobal(L, "minetest");
919         lua_getfield(L, -1, "luaentities");
920         luaL_checktype(L, -1, LUA_TTABLE);
921         lua_pushnumber(L, id);
922         lua_gettable(L, -2);
923         lua_remove(L, -2); // luaentities
924         lua_remove(L, -2); // minetest
925 }
926
927 /******************************************************************************/
928 NoiseParams *read_noiseparams(lua_State *L, int index)
929 {
930         if (index < 0)
931                 index = lua_gettop(L) + 1 + index;
932
933         if (!lua_istable(L, index))
934                 return NULL;
935
936         NoiseParams *np = new NoiseParams;
937
938         np->offset  = getfloatfield_default(L, index, "offset", 0.0);
939         np->scale   = getfloatfield_default(L, index, "scale", 0.0);
940         lua_getfield(L, index, "spread");
941         np->spread  = read_v3f(L, -1);
942         lua_pop(L, 1);
943         np->seed    = getintfield_default(L, index, "seed", 0);
944         np->octaves = getintfield_default(L, index, "octaves", 0);
945         np->persist = getfloatfield_default(L, index, "persist", 0.0);
946
947         return np;
948 }
949
950 /******************************************************************************/
951 bool read_schematic(lua_State *L, int index, DecoSchematic *dschem, Server *server) {
952         if (index < 0)
953                 index = lua_gettop(L) + 1 + index;
954
955         INodeDefManager *ndef = server->getNodeDefManager();
956
957         if (lua_istable(L, index)) {
958                 lua_getfield(L, index, "size");
959                 v3s16 size = read_v3s16(L, -1);
960                 lua_pop(L, 1);
961                 
962                 int numnodes = size.X * size.Y * size.Z;
963                 MapNode *schemdata = new MapNode[numnodes];
964                 int i = 0;
965                 
966                 lua_getfield(L, index, "data");
967                 luaL_checktype(L, -1, LUA_TTABLE);
968                 
969                 lua_pushnil(L);
970                 while (lua_next(L, -2)) {
971                         if (i < numnodes) {
972                                 // same as readnode, except param1 default is MTSCHEM_PROB_CONST
973                                 lua_getfield(L, -1, "name");
974                                 const char *name = luaL_checkstring(L, -1);
975                                 lua_pop(L, 1);
976                                 
977                                 u8 param1;
978                                 lua_getfield(L, -1, "param1");
979                                 param1 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : MTSCHEM_PROB_ALWAYS;
980                                 lua_pop(L, 1);
981         
982                                 u8 param2;
983                                 lua_getfield(L, -1, "param2");
984                                 param2 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : 0;
985                                 lua_pop(L, 1);
986                                 
987                                 schemdata[i] = MapNode(ndef, name, param1, param2);
988                         }
989                         
990                         i++;
991                         lua_pop(L, 1);
992                 }
993                 
994                 dschem->size      = size;
995                 dschem->schematic = schemdata;
996                 
997                 if (i != numnodes) {
998                         errorstream << "read_schematic: incorrect number of "
999                                 "nodes provided in raw schematic data (got " << i <<
1000                                 ", expected " << numnodes << ")." << std::endl;
1001                         return false;
1002                 }
1003         } else if (lua_isstring(L, index)) {
1004                 dschem->filename = std::string(lua_tostring(L, index));
1005         } else {
1006                 errorstream << "read_schematic: missing schematic "
1007                         "filename or raw schematic data" << std::endl;
1008                 return false;
1009         }
1010         
1011         return true;
1012 }
1013
1014 /******************************************************************************/
1015 // Returns depth of json value tree
1016 static int push_json_value_getdepth(const Json::Value &value)
1017 {
1018         if (!value.isArray() && !value.isObject())
1019                 return 1;
1020
1021         int maxdepth = 0;
1022         for (Json::Value::const_iterator it = value.begin();
1023                         it != value.end(); ++it) {
1024                 int elemdepth = push_json_value_getdepth(*it);
1025                 if (elemdepth > maxdepth)
1026                         maxdepth = elemdepth;
1027         }
1028         return maxdepth + 1;
1029 }
1030 // Recursive function to convert JSON --> Lua table
1031 static bool push_json_value_helper(lua_State *L, const Json::Value &value,
1032                 int nullindex)
1033 {
1034         switch(value.type()) {
1035                 case Json::nullValue:
1036                 default:
1037                         lua_pushvalue(L, nullindex);
1038                         break;
1039                 case Json::intValue:
1040                         lua_pushinteger(L, value.asInt());
1041                         break;
1042                 case Json::uintValue:
1043                         lua_pushinteger(L, value.asUInt());
1044                         break;
1045                 case Json::realValue:
1046                         lua_pushnumber(L, value.asDouble());
1047                         break;
1048                 case Json::stringValue:
1049                         {
1050                                 const char *str = value.asCString();
1051                                 lua_pushstring(L, str ? str : "");
1052                         }
1053                         break;
1054                 case Json::booleanValue:
1055                         lua_pushboolean(L, value.asInt());
1056                         break;
1057                 case Json::arrayValue:
1058                         lua_newtable(L);
1059                         for (Json::Value::const_iterator it = value.begin();
1060                                         it != value.end(); ++it) {
1061                                 push_json_value_helper(L, *it, nullindex);
1062                                 lua_rawseti(L, -2, it.index() + 1);
1063                         }
1064                         break;
1065                 case Json::objectValue:
1066                         lua_newtable(L);
1067                         for (Json::Value::const_iterator it = value.begin();
1068                                         it != value.end(); ++it) {
1069                                 const char *str = it.memberName();
1070                                 lua_pushstring(L, str ? str : "");
1071                                 push_json_value_helper(L, *it, nullindex);
1072                                 lua_rawset(L, -3);
1073                         }
1074                         break;
1075         }
1076         return true;
1077 }
1078 // converts JSON --> Lua table; returns false if lua stack limit exceeded
1079 // nullindex: Lua stack index of value to use in place of JSON null
1080 bool push_json_value(lua_State *L, const Json::Value &value, int nullindex)
1081 {
1082         if(nullindex < 0)
1083                 nullindex = lua_gettop(L) + 1 + nullindex;
1084
1085         int depth = push_json_value_getdepth(value);
1086
1087         // The maximum number of Lua stack slots used at each recursion level
1088         // of push_json_value_helper is 2, so make sure there a depth * 2 slots
1089         if (lua_checkstack(L, depth * 2))
1090                 return push_json_value_helper(L, value, nullindex);
1091         else
1092                 return false;
1093 }