3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
19 #include "common/c_content.h"
20 #include "common/c_converter.h"
21 #include "common/c_types.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"
32 #include "serverobject.h"
34 #include "mg_schematic.h"
36 #include "json/json.h"
38 struct EnumString es_TileAnimationType[] =
41 {TAT_VERTICAL_FRAMES, "vertical_frames"},
45 /******************************************************************************/
46 ItemDefinition read_item_definition(lua_State* L,int index,
47 ItemDefinition default_def)
50 index = lua_gettop(L) + 1 + index;
52 // Read the item definition
53 ItemDefinition def = default_def;
55 def.type = (ItemType)getenumfield(L, index, "type",
56 es_ItemType, ITEM_NONE);
57 getstringfield(L, index, "name", def.name);
58 getstringfield(L, index, "description", def.description);
59 getstringfield(L, index, "inventory_image", def.inventory_image);
60 getstringfield(L, index, "wield_image", def.wield_image);
62 lua_getfield(L, index, "wield_scale");
63 if(lua_istable(L, -1)){
64 def.wield_scale = check_v3f(L, -1);
68 def.stack_max = getintfield_default(L, index, "stack_max", def.stack_max);
69 if(def.stack_max == 0)
72 lua_getfield(L, index, "on_use");
73 def.usable = lua_isfunction(L, -1);
76 getboolfield(L, index, "liquids_pointable", def.liquids_pointable);
78 warn_if_field_exists(L, index, "tool_digging_properties",
79 "deprecated: use tool_capabilities");
81 lua_getfield(L, index, "tool_capabilities");
82 if(lua_istable(L, -1)){
83 def.tool_capabilities = new ToolCapabilities(
84 read_tool_capabilities(L, -1));
87 // If name is "" (hand), ensure there are ToolCapabilities
88 // because it will be looked up there whenever any other item has
89 // no ToolCapabilities
90 if(def.name == "" && def.tool_capabilities == NULL){
91 def.tool_capabilities = new ToolCapabilities();
94 lua_getfield(L, index, "groups");
95 read_groups(L, -1, def.groups);
98 lua_getfield(L, index, "sounds");
99 if(lua_istable(L, -1)){
100 lua_getfield(L, -1, "place");
101 read_soundspec(L, -1, def.sound_place);
106 def.range = getfloatfield_default(L, index, "range", def.range);
108 // Client shall immediately place this node when player places the item.
109 // Server will update the precise end result a moment later.
110 // "" = no prediction
111 getstringfield(L, index, "node_placement_prediction",
112 def.node_placement_prediction);
117 /******************************************************************************/
118 void read_object_properties(lua_State *L, int index,
119 ObjectProperties *prop)
122 index = lua_gettop(L) + 1 + index;
123 if(!lua_istable(L, index))
126 prop->hp_max = getintfield_default(L, -1, "hp_max", 10);
128 getboolfield(L, -1, "physical", prop->physical);
129 getboolfield(L, -1, "collide_with_objects", prop->collideWithObjects);
131 getfloatfield(L, -1, "weight", prop->weight);
133 lua_getfield(L, -1, "collisionbox");
134 if(lua_istable(L, -1))
135 prop->collisionbox = read_aabb3f(L, -1, 1.0);
138 getstringfield(L, -1, "visual", prop->visual);
140 getstringfield(L, -1, "mesh", prop->mesh);
142 lua_getfield(L, -1, "visual_size");
143 if(lua_istable(L, -1))
144 prop->visual_size = read_v2f(L, -1);
147 lua_getfield(L, -1, "textures");
148 if(lua_istable(L, -1)){
149 prop->textures.clear();
150 int table = lua_gettop(L);
152 while(lua_next(L, table) != 0){
153 // key at index -2 and value at index -1
154 if(lua_isstring(L, -1))
155 prop->textures.push_back(lua_tostring(L, -1));
157 prop->textures.push_back("");
158 // removes value, keeps key for next iteration
164 lua_getfield(L, -1, "colors");
165 if(lua_istable(L, -1)){
166 prop->colors.clear();
167 int table = lua_gettop(L);
169 while(lua_next(L, table) != 0){
170 // key at index -2 and value at index -1
171 if(lua_isstring(L, -1))
172 prop->colors.push_back(readARGB8(L, -1));
174 prop->colors.push_back(video::SColor(255, 255, 255, 255));
175 // removes value, keeps key for next iteration
181 lua_getfield(L, -1, "spritediv");
182 if(lua_istable(L, -1))
183 prop->spritediv = read_v2s16(L, -1);
186 lua_getfield(L, -1, "initial_sprite_basepos");
187 if(lua_istable(L, -1))
188 prop->initial_sprite_basepos = read_v2s16(L, -1);
191 getboolfield(L, -1, "is_visible", prop->is_visible);
192 getboolfield(L, -1, "makes_footstep_sound", prop->makes_footstep_sound);
193 getfloatfield(L, -1, "automatic_rotate", prop->automatic_rotate);
194 if (getfloatfield(L, -1, "stepheight", prop->stepheight))
195 prop->stepheight *= BS;
196 lua_getfield(L, -1, "automatic_face_movement_dir");
197 if (lua_isnumber(L, -1)) {
198 prop->automatic_face_movement_dir = true;
199 prop->automatic_face_movement_dir_offset = luaL_checknumber(L, -1);
200 } else if (lua_isboolean(L, -1)) {
201 prop->automatic_face_movement_dir = lua_toboolean(L, -1);
202 prop->automatic_face_movement_dir_offset = 0.0;
207 /******************************************************************************/
208 TileDef read_tiledef(lua_State *L, int index)
211 index = lua_gettop(L) + 1 + index;
215 // key at index -2 and value at index
216 if(lua_isstring(L, index)){
217 // "default_lava.png"
218 tiledef.name = lua_tostring(L, index);
220 else if(lua_istable(L, index))
222 // {name="default_lava.png", animation={}}
224 getstringfield(L, index, "name", tiledef.name);
225 getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat.
226 tiledef.backface_culling = getboolfield_default(
227 L, index, "backface_culling", true);
229 lua_getfield(L, index, "animation");
230 if(lua_istable(L, -1)){
231 // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0}
232 tiledef.animation.type = (TileAnimationType)
233 getenumfield(L, -1, "type", es_TileAnimationType,
235 tiledef.animation.aspect_w =
236 getintfield_default(L, -1, "aspect_w", 16);
237 tiledef.animation.aspect_h =
238 getintfield_default(L, -1, "aspect_h", 16);
239 tiledef.animation.length =
240 getfloatfield_default(L, -1, "length", 1.0);
248 /******************************************************************************/
249 ContentFeatures read_content_features(lua_State *L, int index)
252 index = lua_gettop(L) + 1 + index;
256 /* Cache existence of some callbacks */
257 lua_getfield(L, index, "on_construct");
258 if(!lua_isnil(L, -1)) f.has_on_construct = true;
260 lua_getfield(L, index, "on_destruct");
261 if(!lua_isnil(L, -1)) f.has_on_destruct = true;
263 lua_getfield(L, index, "after_destruct");
264 if(!lua_isnil(L, -1)) f.has_after_destruct = true;
267 lua_getfield(L, index, "on_rightclick");
268 f.rightclickable = lua_isfunction(L, -1);
272 getstringfield(L, index, "name", f.name);
275 lua_getfield(L, index, "groups");
276 read_groups(L, -1, f.groups);
279 /* Visual definition */
281 f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype",
282 ScriptApiNode::es_DrawType,NDT_NORMAL);
283 getfloatfield(L, index, "visual_scale", f.visual_scale);
285 /* Meshnode model filename */
286 getstringfield(L, index, "mesh", f.mesh);
289 lua_getfield(L, index, "tiles");
290 // If nil, try the deprecated name "tile_images" instead
291 if(lua_isnil(L, -1)){
293 warn_if_field_exists(L, index, "tile_images",
294 "Deprecated; new name is \"tiles\".");
295 lua_getfield(L, index, "tile_images");
297 if(lua_istable(L, -1)){
298 int table = lua_gettop(L);
301 while(lua_next(L, table) != 0){
302 // Read tiledef from value
303 f.tiledef[i] = read_tiledef(L, -1);
304 // removes value, keeps key for next iteration
312 // Copy last value to all remaining textures
314 TileDef lasttile = f.tiledef[i-1];
316 f.tiledef[i] = lasttile;
323 // special_tiles = {}
324 lua_getfield(L, index, "special_tiles");
325 // If nil, try the deprecated name "special_materials" instead
326 if(lua_isnil(L, -1)){
328 warn_if_field_exists(L, index, "special_materials",
329 "Deprecated; new name is \"special_tiles\".");
330 lua_getfield(L, index, "special_materials");
332 if(lua_istable(L, -1)){
333 int table = lua_gettop(L);
336 while(lua_next(L, table) != 0){
337 // Read tiledef from value
338 f.tiledef_special[i] = read_tiledef(L, -1);
339 // removes value, keeps key for next iteration
342 if(i==CF_SPECIAL_COUNT){
350 f.alpha = getintfield_default(L, index, "alpha", 255);
352 bool usealpha = getboolfield_default(L, index,
353 "use_texture_alpha", false);
359 lua_getfield(L, index, "post_effect_color");
360 if(!lua_isnil(L, -1))
361 f.post_effect_color = readARGB8(L, -1);
364 f.param_type = (ContentParamType)getenumfield(L, index, "paramtype",
365 ScriptApiNode::es_ContentParamType, CPT_NONE);
366 f.param_type_2 = (ContentParamType2)getenumfield(L, index, "paramtype2",
367 ScriptApiNode::es_ContentParamType2, CPT2_NONE);
369 // Warn about some deprecated fields
370 warn_if_field_exists(L, index, "wall_mounted",
371 "deprecated: use paramtype2 = 'wallmounted'");
372 warn_if_field_exists(L, index, "light_propagates",
373 "deprecated: determined from paramtype");
374 warn_if_field_exists(L, index, "dug_item",
375 "deprecated: use 'drop' field");
376 warn_if_field_exists(L, index, "extra_dug_item",
377 "deprecated: use 'drop' field");
378 warn_if_field_exists(L, index, "extra_dug_item_rarity",
379 "deprecated: use 'drop' field");
380 warn_if_field_exists(L, index, "metadata_name",
381 "deprecated: use on_add and metadata callbacks");
383 // True for all ground-like things like stone and mud, false for eg. trees
384 getboolfield(L, index, "is_ground_content", f.is_ground_content);
385 f.light_propagates = (f.param_type == CPT_LIGHT);
386 getboolfield(L, index, "sunlight_propagates", f.sunlight_propagates);
387 // This is used for collision detection.
388 // Also for general solidness queries.
389 getboolfield(L, index, "walkable", f.walkable);
390 // Player can point to these
391 getboolfield(L, index, "pointable", f.pointable);
392 // Player can dig these
393 getboolfield(L, index, "diggable", f.diggable);
394 // Player can climb these
395 getboolfield(L, index, "climbable", f.climbable);
396 // Player can build on these
397 getboolfield(L, index, "buildable_to", f.buildable_to);
398 // Whether the node is non-liquid, source liquid or flowing liquid
399 f.liquid_type = (LiquidType)getenumfield(L, index, "liquidtype",
400 ScriptApiNode::es_LiquidType, LIQUID_NONE);
401 // If the content is liquid, this is the flowing version of the liquid.
402 getstringfield(L, index, "liquid_alternative_flowing",
403 f.liquid_alternative_flowing);
404 // If the content is liquid, this is the source version of the liquid.
405 getstringfield(L, index, "liquid_alternative_source",
406 f.liquid_alternative_source);
407 // Viscosity for fluid flow, ranging from 1 to 7, with
408 // 1 giving almost instantaneous propagation and 7 being
409 // the slowest possible
410 f.liquid_viscosity = getintfield_default(L, index,
411 "liquid_viscosity", f.liquid_viscosity);
412 f.liquid_range = getintfield_default(L, index,
413 "liquid_range", f.liquid_range);
414 f.leveled = getintfield_default(L, index, "leveled", f.leveled);
416 getboolfield(L, index, "liquid_renewable", f.liquid_renewable);
417 getstringfield(L, index, "freezemelt", f.freezemelt);
418 f.drowning = getintfield_default(L, index,
419 "drowning", f.drowning);
420 // Amount of light the node emits
421 f.light_source = getintfield_default(L, index,
422 "light_source", f.light_source);
423 f.damage_per_second = getintfield_default(L, index,
424 "damage_per_second", f.damage_per_second);
426 lua_getfield(L, index, "node_box");
427 if(lua_istable(L, -1))
428 f.node_box = read_nodebox(L, -1);
431 lua_getfield(L, index, "selection_box");
432 if(lua_istable(L, -1))
433 f.selection_box = read_nodebox(L, -1);
436 lua_getfield(L, index, "collision_box");
437 if(lua_istable(L, -1))
438 f.collision_box = read_nodebox(L, -1);
441 f.waving = getintfield_default(L, index,
444 // Set to true if paramtype used to be 'facedir_simple'
445 getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple);
446 // Set to true if wall_mounted used to be set to true
447 getboolfield(L, index, "legacy_wallmounted", f.legacy_wallmounted);
450 lua_getfield(L, index, "sounds");
451 if(lua_istable(L, -1)){
452 lua_getfield(L, -1, "footstep");
453 read_soundspec(L, -1, f.sound_footstep);
455 lua_getfield(L, -1, "dig");
456 read_soundspec(L, -1, f.sound_dig);
458 lua_getfield(L, -1, "dug");
459 read_soundspec(L, -1, f.sound_dug);
467 /******************************************************************************/
468 void read_server_sound_params(lua_State *L, int index,
469 ServerSoundParams ¶ms)
472 index = lua_gettop(L) + 1 + index;
474 params = ServerSoundParams();
475 if(lua_istable(L, index)){
476 getfloatfield(L, index, "gain", params.gain);
477 getstringfield(L, index, "to_player", params.to_player);
478 lua_getfield(L, index, "pos");
479 if(!lua_isnil(L, -1)){
480 v3f p = read_v3f(L, -1)*BS;
482 params.type = ServerSoundParams::SSP_POSITIONAL;
485 lua_getfield(L, index, "object");
486 if(!lua_isnil(L, -1)){
487 ObjectRef *ref = ObjectRef::checkobject(L, -1);
488 ServerActiveObject *sao = ObjectRef::getobject(ref);
490 params.object = sao->getId();
491 params.type = ServerSoundParams::SSP_OBJECT;
495 params.max_hear_distance = BS*getfloatfield_default(L, index,
496 "max_hear_distance", params.max_hear_distance/BS);
497 getboolfield(L, index, "loop", params.loop);
501 /******************************************************************************/
502 void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec)
505 index = lua_gettop(L) + 1 + index;
506 if(lua_isnil(L, index)){
507 } else if(lua_istable(L, index)){
508 getstringfield(L, index, "name", spec.name);
509 getfloatfield(L, index, "gain", spec.gain);
510 } else if(lua_isstring(L, index)){
511 spec.name = lua_tostring(L, index);
515 /******************************************************************************/
516 NodeBox read_nodebox(lua_State *L, int index)
519 if(lua_istable(L, -1)){
520 nodebox.type = (NodeBoxType)getenumfield(L, index, "type",
521 ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR);
523 lua_getfield(L, index, "fixed");
524 if(lua_istable(L, -1))
525 nodebox.fixed = read_aabb3f_vector(L, -1, BS);
528 lua_getfield(L, index, "wall_top");
529 if(lua_istable(L, -1))
530 nodebox.wall_top = read_aabb3f(L, -1, BS);
533 lua_getfield(L, index, "wall_bottom");
534 if(lua_istable(L, -1))
535 nodebox.wall_bottom = read_aabb3f(L, -1, BS);
538 lua_getfield(L, index, "wall_side");
539 if(lua_istable(L, -1))
540 nodebox.wall_side = read_aabb3f(L, -1, BS);
546 /******************************************************************************/
547 MapNode readnode(lua_State *L, int index, INodeDefManager *ndef)
549 lua_getfield(L, index, "name");
550 const char *name = luaL_checkstring(L, -1);
553 lua_getfield(L, index, "param1");
557 param1 = lua_tonumber(L, -1);
560 lua_getfield(L, index, "param2");
564 param2 = lua_tonumber(L, -1);
566 return MapNode(ndef, name, param1, param2);
569 /******************************************************************************/
570 void pushnode(lua_State *L, const MapNode &n, INodeDefManager *ndef)
573 lua_pushstring(L, ndef->get(n).name.c_str());
574 lua_setfield(L, -2, "name");
575 lua_pushnumber(L, n.getParam1());
576 lua_setfield(L, -2, "param1");
577 lua_pushnumber(L, n.getParam2());
578 lua_setfield(L, -2, "param2");
581 /******************************************************************************/
582 void warn_if_field_exists(lua_State *L, int table,
583 const char *fieldname, const std::string &message)
585 lua_getfield(L, table, fieldname);
586 if(!lua_isnil(L, -1)){
587 //TODO find way to access backtrace fct from here
588 // infostream<<script_get_backtrace(L)<<std::endl;
589 infostream<<"WARNING: field \""<<fieldname<<"\": "
590 <<message<<std::endl;
595 /******************************************************************************/
596 int getenumfield(lua_State *L, int table,
597 const char *fieldname, const EnumString *spec, int default_)
599 int result = default_;
600 string_to_enum(spec, result,
601 getstringfield_default(L, table, fieldname, ""));
605 /******************************************************************************/
606 bool string_to_enum(const EnumString *spec, int &result,
607 const std::string &str)
609 const EnumString *esp = spec;
611 if(str == std::string(esp->str)){
620 /******************************************************************************/
621 ItemStack read_item(lua_State* L, int index,Server* srv)
624 index = lua_gettop(L) + 1 + index;
626 if(lua_isnil(L, index))
630 else if(lua_isuserdata(L, index))
632 // Convert from LuaItemStack
633 LuaItemStack *o = LuaItemStack::checkobject(L, index);
636 else if(lua_isstring(L, index))
638 // Convert from itemstring
639 std::string itemstring = lua_tostring(L, index);
640 IItemDefManager *idef = srv->idef();
644 item.deSerialize(itemstring, idef);
647 catch(SerializationError &e)
649 infostream<<"WARNING: unable to create item from itemstring"
650 <<": "<<itemstring<<std::endl;
654 else if(lua_istable(L, index))
656 // Convert from table
657 IItemDefManager *idef = srv->idef();
658 std::string name = getstringfield_default(L, index, "name", "");
659 int count = getintfield_default(L, index, "count", 1);
660 int wear = getintfield_default(L, index, "wear", 0);
661 std::string metadata = getstringfield_default(L, index, "metadata", "");
662 return ItemStack(name, count, wear, metadata, idef);
666 throw LuaError("Expecting itemstack, itemstring, table or nil");
670 /******************************************************************************/
671 void push_tool_capabilities(lua_State *L,
672 const ToolCapabilities &toolcap)
675 setfloatfield(L, -1, "full_punch_interval", toolcap.full_punch_interval);
676 setintfield(L, -1, "max_drop_level", toolcap.max_drop_level);
677 // Create groupcaps table
680 for(std::map<std::string, ToolGroupCap>::const_iterator
681 i = toolcap.groupcaps.begin(); i != toolcap.groupcaps.end(); i++){
682 // Create groupcap table
684 const std::string &name = i->first;
685 const ToolGroupCap &groupcap = i->second;
686 // Create subtable "times"
688 for(std::map<int, float>::const_iterator
689 i = groupcap.times.begin(); i != groupcap.times.end(); i++){
690 int rating = i->first;
691 float time = i->second;
692 lua_pushinteger(L, rating);
693 lua_pushnumber(L, time);
696 // Set subtable "times"
697 lua_setfield(L, -2, "times");
698 // Set simple parameters
699 setintfield(L, -1, "maxlevel", groupcap.maxlevel);
700 setintfield(L, -1, "uses", groupcap.uses);
701 // Insert groupcap table into groupcaps table
702 lua_setfield(L, -2, name.c_str());
704 // Set groupcaps table
705 lua_setfield(L, -2, "groupcaps");
706 //Create damage_groups table
708 // For each damage group
709 for(std::map<std::string, s16>::const_iterator
710 i = toolcap.damageGroups.begin(); i != toolcap.damageGroups.end(); i++){
711 // Create damage group table
712 lua_pushinteger(L, i->second);
713 lua_setfield(L, -2, i->first.c_str());
715 lua_setfield(L, -2, "damage_groups");
718 /******************************************************************************/
719 void push_inventory_list(lua_State *L, Inventory *inv, const char *name)
721 InventoryList *invlist = inv->getList(name);
726 std::vector<ItemStack> items;
727 for(u32 i=0; i<invlist->getSize(); i++)
728 items.push_back(invlist->getItem(i));
729 push_items(L, items);
732 /******************************************************************************/
733 void read_inventory_list(lua_State *L, int tableindex,
734 Inventory *inv, const char *name, Server* srv, int forcesize)
737 tableindex = lua_gettop(L) + 1 + tableindex;
738 // If nil, delete list
739 if(lua_isnil(L, tableindex)){
740 inv->deleteList(name);
743 // Otherwise set list
744 std::vector<ItemStack> items = read_items(L, tableindex,srv);
745 int listsize = (forcesize != -1) ? forcesize : items.size();
746 InventoryList *invlist = inv->addList(name, listsize);
748 for(std::vector<ItemStack>::const_iterator
749 i = items.begin(); i != items.end(); i++){
750 if(forcesize != -1 && index == forcesize)
752 invlist->changeItem(index, *i);
755 while(forcesize != -1 && index < forcesize){
756 invlist->deleteItem(index);
761 /******************************************************************************/
762 ToolCapabilities read_tool_capabilities(
763 lua_State *L, int table)
765 ToolCapabilities toolcap;
766 getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval);
767 getintfield(L, table, "max_drop_level", toolcap.max_drop_level);
768 lua_getfield(L, table, "groupcaps");
769 if(lua_istable(L, -1)){
770 int table_groupcaps = lua_gettop(L);
772 while(lua_next(L, table_groupcaps) != 0){
773 // key at index -2 and value at index -1
774 std::string groupname = luaL_checkstring(L, -2);
775 if(lua_istable(L, -1)){
776 int table_groupcap = lua_gettop(L);
777 // This will be created
778 ToolGroupCap groupcap;
779 // Read simple parameters
780 getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel);
781 getintfield(L, table_groupcap, "uses", groupcap.uses);
782 // DEPRECATED: maxwear
784 if(getfloatfield(L, table_groupcap, "maxwear", maxwear)){
786 groupcap.uses = 1.0/maxwear;
789 infostream<<script_get_backtrace(L)<<std::endl;
790 infostream<<"WARNING: field \"maxwear\" is deprecated; "
791 <<"should replace with uses=1/maxwear"<<std::endl;
793 // Read "times" table
794 lua_getfield(L, table_groupcap, "times");
795 if(lua_istable(L, -1)){
796 int table_times = lua_gettop(L);
798 while(lua_next(L, table_times) != 0){
799 // key at index -2 and value at index -1
800 int rating = luaL_checkinteger(L, -2);
801 float time = luaL_checknumber(L, -1);
802 groupcap.times[rating] = time;
803 // removes value, keeps key for next iteration
808 // Insert groupcap into toolcap
809 toolcap.groupcaps[groupname] = groupcap;
811 // removes value, keeps key for next iteration
817 lua_getfield(L, table, "damage_groups");
818 if(lua_istable(L, -1)){
819 int table_damage_groups = lua_gettop(L);
821 while(lua_next(L, table_damage_groups) != 0){
822 // key at index -2 and value at index -1
823 std::string groupname = luaL_checkstring(L, -2);
824 u16 value = luaL_checkinteger(L, -1);
825 toolcap.damageGroups[groupname] = value;
826 // removes value, keeps key for next iteration
834 /******************************************************************************/
835 void push_dig_params(lua_State *L,const DigParams ¶ms)
838 setboolfield(L, -1, "diggable", params.diggable);
839 setfloatfield(L, -1, "time", params.time);
840 setintfield(L, -1, "wear", params.wear);
843 /******************************************************************************/
844 void push_hit_params(lua_State *L,const HitParams ¶ms)
847 setintfield(L, -1, "hp", params.hp);
848 setintfield(L, -1, "wear", params.wear);
851 /******************************************************************************/
853 bool getflagsfield(lua_State *L, int table, const char *fieldname,
854 FlagDesc *flagdesc, u32 *flags, u32 *flagmask)
856 lua_getfield(L, table, fieldname);
858 bool success = read_flags(L, -1, flagdesc, flags, flagmask);
865 bool read_flags(lua_State *L, int index, FlagDesc *flagdesc,
866 u32 *flags, u32 *flagmask)
868 if (lua_isstring(L, index)) {
869 std::string flagstr = lua_tostring(L, index);
870 *flags = readFlagString(flagstr, flagdesc, flagmask);
871 } else if (lua_istable(L, index)) {
872 *flags = read_flags_table(L, index, flagdesc, flagmask);
880 u32 read_flags_table(lua_State *L, int table, FlagDesc *flagdesc, u32 *flagmask)
882 u32 flags = 0, mask = 0;
883 char fnamebuf[64] = "no";
885 for (int i = 0; flagdesc[i].name; i++) {
888 if (getboolfield(L, table, flagdesc[i].name, result)) {
889 mask |= flagdesc[i].flag;
891 flags |= flagdesc[i].flag;
894 strlcpy(fnamebuf + 2, flagdesc[i].name, sizeof(fnamebuf) - 2);
895 if (getboolfield(L, table, fnamebuf, result))
896 mask |= flagdesc[i].flag;
905 /******************************************************************************/
906 /* Lua Stored data! */
907 /******************************************************************************/
909 /******************************************************************************/
910 void read_groups(lua_State *L, int index,
911 std::map<std::string, int> &result)
913 if (!lua_istable(L,index))
919 while(lua_next(L, index) != 0){
920 // key at index -2 and value at index -1
921 std::string name = luaL_checkstring(L, -2);
922 int rating = luaL_checkinteger(L, -1);
923 result[name] = rating;
924 // removes value, keeps key for next iteration
929 /******************************************************************************/
930 void push_items(lua_State *L, const std::vector<ItemStack> &items)
932 // Create and fill table
933 lua_createtable(L, items.size(), 0);
934 std::vector<ItemStack>::const_iterator iter = items.begin();
935 for (u32 i = 0; iter != items.end(); iter++) {
936 LuaItemStack::create(L, *iter);
937 lua_rawseti(L, -2, ++i);
941 /******************************************************************************/
942 std::vector<ItemStack> read_items(lua_State *L, int index, Server *srv)
945 index = lua_gettop(L) + 1 + index;
947 std::vector<ItemStack> items;
948 luaL_checktype(L, index, LUA_TTABLE);
950 while (lua_next(L, index)) {
951 s32 key = luaL_checkinteger(L, -2);
953 throw LuaError("Invalid inventory list index");
955 if (items.size() < (u32) key) {
958 items[key - 1] = read_item(L, -1, srv);
964 /******************************************************************************/
965 void luaentity_get(lua_State *L, u16 id)
967 // Get luaentities[i]
968 lua_getglobal(L, "core");
969 lua_getfield(L, -1, "luaentities");
970 luaL_checktype(L, -1, LUA_TTABLE);
971 lua_pushnumber(L, id);
973 lua_remove(L, -2); // Remove luaentities
974 lua_remove(L, -2); // Remove core
977 /******************************************************************************/
978 NoiseParams *read_noiseparams(lua_State *L, int index)
980 NoiseParams *np = new NoiseParams;
982 if (!read_noiseparams_nc(L, index, np)) {
990 bool read_noiseparams_nc(lua_State *L, int index, NoiseParams *np)
993 index = lua_gettop(L) + 1 + index;
995 if (!lua_istable(L, index))
998 np->offset = getfloatfield_default(L, index, "offset", 0.0);
999 np->scale = getfloatfield_default(L, index, "scale", 0.0);
1000 np->persist = getfloatfield_default(L, index, "persist", 0.0);
1001 np->seed = getintfield_default(L, index, "seed", 0);
1002 np->octaves = getintfield_default(L, index, "octaves", 0);
1003 np->eased = getboolfield_default(L, index, "eased", false);
1005 lua_getfield(L, index, "spread");
1006 np->spread = read_v3f(L, -1);
1012 /******************************************************************************/
1014 bool get_schematic(lua_State *L, int index, Schematic *schem,
1015 INodeDefManager *ndef, std::map<std::string, std::string> &replace_names)
1018 index = lua_gettop(L) + 1 + index;
1020 if (lua_istable(L, index)) {
1021 return read_schematic(L, index, schem, ndef, replace_names);
1022 } else if (lua_isstring(L, index)) {
1023 NodeResolver *resolver = ndef->getResolver();
1024 const char *filename = lua_tostring(L, index);
1025 return schem->loadSchematicFromFile(filename, resolver, replace_names);
1031 bool read_schematic(lua_State *L, int index, Schematic *schem,
1032 INodeDefManager *ndef, std::map<std::string, std::string> &replace_names)
1034 //// Get schematic size
1035 lua_getfield(L, index, "size");
1036 v3s16 size = read_v3s16(L, -1);
1039 //// Get schematic data
1040 lua_getfield(L, index, "data");
1041 luaL_checktype(L, -1, LUA_TTABLE);
1043 int numnodes = size.X * size.Y * size.Z;
1044 MapNode *schemdata = new MapNode[numnodes];
1048 while (lua_next(L, -2)) {
1050 // same as readnode, except param1 default is MTSCHEM_PROB_CONST
1051 lua_getfield(L, -1, "name");
1052 std::string name = luaL_checkstring(L, -1);
1056 lua_getfield(L, -1, "param1");
1057 param1 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : MTSCHEM_PROB_ALWAYS;
1061 lua_getfield(L, -1, "param2");
1062 param2 = !lua_isnil(L, -1) ? lua_tonumber(L, -1) : 0;
1065 std::map<std::string, std::string>::iterator it;
1066 it = replace_names.find(name);
1067 if (it != replace_names.end())
1070 schemdata[i] = MapNode(ndef, name, param1, param2);
1077 if (i != numnodes) {
1078 errorstream << "read_schematic: incorrect number of "
1079 "nodes provided in raw schematic data (got " << i <<
1080 ", expected " << numnodes << ")." << std::endl;
1084 //// Get Y-slice probability values (if present)
1085 u8 *slice_probs = new u8[size.Y];
1086 for (i = 0; i != size.Y; i++)
1087 slice_probs[i] = MTSCHEM_PROB_ALWAYS;
1089 lua_getfield(L, index, "yslice_prob");
1090 if (lua_istable(L, -1)) {
1092 while (lua_next(L, -2)) {
1093 if (getintfield(L, -1, "ypos", i) && i >= 0 && i < size.Y) {
1094 slice_probs[i] = getintfield_default(L, -1,
1095 "prob", MTSCHEM_PROB_ALWAYS);
1103 schem->schemdata = schemdata;
1104 schem->slice_probs = slice_probs;
1108 /******************************************************************************/
1109 // Returns depth of json value tree
1110 static int push_json_value_getdepth(const Json::Value &value)
1112 if (!value.isArray() && !value.isObject())
1116 for (Json::Value::const_iterator it = value.begin();
1117 it != value.end(); ++it) {
1118 int elemdepth = push_json_value_getdepth(*it);
1119 if (elemdepth > maxdepth)
1120 maxdepth = elemdepth;
1122 return maxdepth + 1;
1124 // Recursive function to convert JSON --> Lua table
1125 static bool push_json_value_helper(lua_State *L, const Json::Value &value,
1128 switch(value.type()) {
1129 case Json::nullValue:
1131 lua_pushvalue(L, nullindex);
1133 case Json::intValue:
1134 lua_pushinteger(L, value.asInt());
1136 case Json::uintValue:
1137 lua_pushinteger(L, value.asUInt());
1139 case Json::realValue:
1140 lua_pushnumber(L, value.asDouble());
1142 case Json::stringValue:
1144 const char *str = value.asCString();
1145 lua_pushstring(L, str ? str : "");
1148 case Json::booleanValue:
1149 lua_pushboolean(L, value.asInt());
1151 case Json::arrayValue:
1153 for (Json::Value::const_iterator it = value.begin();
1154 it != value.end(); ++it) {
1155 push_json_value_helper(L, *it, nullindex);
1156 lua_rawseti(L, -2, it.index() + 1);
1159 case Json::objectValue:
1161 for (Json::Value::const_iterator it = value.begin();
1162 it != value.end(); ++it) {
1163 const char *str = it.memberName();
1164 lua_pushstring(L, str ? str : "");
1165 push_json_value_helper(L, *it, nullindex);
1172 // converts JSON --> Lua table; returns false if lua stack limit exceeded
1173 // nullindex: Lua stack index of value to use in place of JSON null
1174 bool push_json_value(lua_State *L, const Json::Value &value, int nullindex)
1177 nullindex = lua_gettop(L) + 1 + nullindex;
1179 int depth = push_json_value_getdepth(value);
1181 // The maximum number of Lua stack slots used at each recursion level
1182 // of push_json_value_helper is 2, so make sure there a depth * 2 slots
1183 if (lua_checkstack(L, depth * 2))
1184 return push_json_value_helper(L, value, nullindex);
1189 // Converts Lua table --> JSON
1190 void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion)
1192 if (recursion > 16) {
1193 throw SerializationError("Maximum recursion depth exceeded");
1195 int type = lua_type(L, index);
1196 if (type == LUA_TBOOLEAN) {
1197 root = (bool) lua_toboolean(L, index);
1198 } else if (type == LUA_TNUMBER) {
1199 root = lua_tonumber(L, index);
1200 } else if (type == LUA_TSTRING) {
1202 const char *str = lua_tolstring(L, index, &len);
1203 root = std::string(str, len);
1204 } else if (type == LUA_TTABLE) {
1206 while (lua_next(L, index)) {
1207 // Key is at -2 and value is at -1
1209 read_json_value(L, value, lua_gettop(L), recursion + 1);
1211 Json::ValueType roottype = root.type();
1212 int keytype = lua_type(L, -1);
1213 if (keytype == LUA_TNUMBER) {
1214 lua_Number key = lua_tonumber(L, -1);
1215 if (roottype != Json::nullValue && roottype != Json::arrayValue) {
1216 throw SerializationError("Can't mix array and object values in JSON");
1217 } else if (key < 1) {
1218 throw SerializationError("Can't use zero-based or negative indexes in JSON");
1219 } else if (floor(key) != key) {
1220 throw SerializationError("Can't use indexes with a fractional part in JSON");
1222 root[(Json::ArrayIndex) key - 1] = value;
1223 } else if (keytype == LUA_TSTRING) {
1224 if (roottype != Json::nullValue && roottype != Json::objectValue) {
1225 throw SerializationError("Can't mix array and object values in JSON");
1227 root[lua_tostring(L, -1)] = value;
1229 throw SerializationError("Lua key to convert to JSON is not a string or number");
1232 } else if (type == LUA_TNIL) {
1233 root = Json::nullValue;
1235 throw SerializationError("Can only store booleans, numbers, strings, objects, arrays, and null in JSON");
1237 lua_pop(L, 1); // Pop value