diff options
Diffstat (limited to 'src/script')
84 files changed, 3326 insertions, 2985 deletions
diff --git a/src/script/common/c_content.cpp b/src/script/common/c_content.cpp index 9e99d5673..7d4c1e748 100644 --- a/src/script/common/c_content.cpp +++ b/src/script/common/c_content.cpp @@ -38,21 +38,23 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "debug.h" // For FATAL_ERROR #include <json/json.h> -struct EnumString es_TileAnimationType[] = { - {TAT_NONE, "none"}, - {TAT_VERTICAL_FRAMES, "vertical_frames"}, - {TAT_SHEET_2D, "sheet_2d"}, - {0, NULL}, +struct EnumString es_TileAnimationType[] = +{ + {TAT_NONE, "none"}, + {TAT_VERTICAL_FRAMES, "vertical_frames"}, + {TAT_SHEET_2D, "sheet_2d"}, + {0, NULL}, }; /******************************************************************************/ -void read_item_definition(lua_State *L, int index, const ItemDefinition &default_def, - ItemDefinition &def) +void read_item_definition(lua_State* L, int index, + const ItemDefinition &default_def, ItemDefinition &def) { if (index < 0) index = lua_gettop(L) + 1 + index; - def.type = (ItemType)getenumfield(L, index, "type", es_ItemType, ITEM_NONE); + def.type = (ItemType)getenumfield(L, index, "type", + es_ItemType, ITEM_NONE); getstringfield(L, index, "name", def.name); getstringfield(L, index, "description", def.description); getstringfield(L, index, "inventory_image", def.inventory_image); @@ -67,7 +69,7 @@ void read_item_definition(lua_State *L, int index, const ItemDefinition &default lua_pop(L, 1); lua_getfield(L, index, "wield_scale"); - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ def.wield_scale = check_v3f(L, -1); } lua_pop(L, 1); @@ -85,15 +87,15 @@ void read_item_definition(lua_State *L, int index, const ItemDefinition &default "Obsolete; use tool_capabilities"); lua_getfield(L, index, "tool_capabilities"); - if (lua_istable(L, -1)) { - def.tool_capabilities = - new ToolCapabilities(read_tool_capabilities(L, -1)); + if(lua_istable(L, -1)){ + def.tool_capabilities = new ToolCapabilities( + read_tool_capabilities(L, -1)); } // If name is "" (hand), ensure there are ToolCapabilities // because it will be looked up there whenever any other item has // no ToolCapabilities - if (def.name.empty() && def.tool_capabilities == NULL) { + if (def.name.empty() && def.tool_capabilities == NULL){ def.tool_capabilities = new ToolCapabilities(); } @@ -180,10 +182,10 @@ void push_item_definition_full(lua_State *L, const ItemDefinition &i) } /******************************************************************************/ -void read_object_properties(lua_State *L, int index, ServerActiveObject *sao, - ObjectProperties *prop, IItemDefManager *idef) +void read_object_properties(lua_State *L, int index, + ServerActiveObject *sao, ObjectProperties *prop, IItemDefManager *idef) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; if (lua_isnil(L, index)) return; @@ -198,8 +200,7 @@ void read_object_properties(lua_State *L, int index, ServerActiveObject *sao, PlayerHPChangeReason reason(PlayerHPChangeReason::SET_HP); sao->setHP(prop->hp_max, reason); if (sao->getType() == ACTIVEOBJECT_TYPE_PLAYER) - sao->getEnv()->getGameDef()->SendPlayerHPOrDie( - (PlayerSAO *)sao, reason); + sao->getEnv()->getGameDef()->SendPlayerHPOrDie((PlayerSAO *)sao, reason); } } @@ -247,13 +248,13 @@ void read_object_properties(lua_State *L, int index, ServerActiveObject *sao, lua_pop(L, 1); lua_getfield(L, -1, "textures"); - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ prop->textures.clear(); int table = lua_gettop(L); lua_pushnil(L); - while (lua_next(L, table) != 0) { + while(lua_next(L, table) != 0){ // key at index -2 and value at index -1 - if (lua_isstring(L, -1)) + if(lua_isstring(L, -1)) prop->textures.emplace_back(lua_tostring(L, -1)); else prop->textures.emplace_back(""); @@ -276,12 +277,12 @@ void read_object_properties(lua_State *L, int index, ServerActiveObject *sao, lua_pop(L, 1); lua_getfield(L, -1, "spritediv"); - if (lua_istable(L, -1)) + if(lua_istable(L, -1)) prop->spritediv = read_v2s16(L, -1); lua_pop(L, 1); lua_getfield(L, -1, "initial_sprite_basepos"); - if (lua_istable(L, -1)) + if(lua_istable(L, -1)) prop->initial_sprite_basepos = read_v2s16(L, -1); lua_pop(L, 1); @@ -315,8 +316,7 @@ void read_object_properties(lua_State *L, int index, ServerActiveObject *sao, lua_getfield(L, -1, "automatic_face_movement_max_rotation_per_sec"); if (lua_isnumber(L, -1)) { - prop->automatic_face_movement_max_rotation_per_sec = - luaL_checknumber(L, -1); + prop->automatic_face_movement_max_rotation_per_sec = luaL_checknumber(L, -1); } lua_pop(L, 1); @@ -417,15 +417,14 @@ void push_object_properties(lua_State *L, ObjectProperties *prop) lua_setfield(L, -2, "use_texture_alpha"); lua_pushboolean(L, prop->shaded); lua_setfield(L, -2, "shaded"); - lua_pushlstring(L, prop->damage_texture_modifier.c_str(), - prop->damage_texture_modifier.size()); + lua_pushlstring(L, prop->damage_texture_modifier.c_str(), prop->damage_texture_modifier.size()); lua_setfield(L, -2, "damage_texture_modifier"); } /******************************************************************************/ TileDef read_tiledef(lua_State *L, int index, u8 drawtype) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; TileDef tiledef; @@ -433,39 +432,41 @@ TileDef read_tiledef(lua_State *L, int index, u8 drawtype) bool default_tiling = true; bool default_culling = true; switch (drawtype) { - case NDT_PLANTLIKE: - case NDT_PLANTLIKE_ROOTED: - case NDT_FIRELIKE: - default_tiling = false; - // "break" is omitted here intentionaly, as PLANTLIKE - // FIRELIKE drawtype both should default to having - // backface_culling to false. - case NDT_MESH: - case NDT_LIQUID: - default_culling = false; - break; - default: - break; + case NDT_PLANTLIKE: + case NDT_PLANTLIKE_ROOTED: + case NDT_FIRELIKE: + default_tiling = false; + // "break" is omitted here intentionaly, as PLANTLIKE + // FIRELIKE drawtype both should default to having + // backface_culling to false. + case NDT_MESH: + case NDT_LIQUID: + default_culling = false; + break; + default: + break; } // key at index -2 and value at index - if (lua_isstring(L, index)) { + if(lua_isstring(L, index)){ // "default_lava.png" tiledef.name = lua_tostring(L, index); tiledef.tileable_vertical = default_tiling; tiledef.tileable_horizontal = default_tiling; tiledef.backface_culling = default_culling; - } else if (lua_istable(L, index)) { + } + else if(lua_istable(L, index)) + { // name="default_lava.png" tiledef.name = ""; getstringfield(L, index, "name", tiledef.name); getstringfield(L, index, "image", tiledef.name); // MaterialSpec compat. tiledef.backface_culling = getboolfield_default( - L, index, "backface_culling", default_culling); + L, index, "backface_culling", default_culling); tiledef.tileable_horizontal = getboolfield_default( - L, index, "tileable_horizontal", default_tiling); + L, index, "tileable_horizontal", default_tiling); tiledef.tileable_vertical = getboolfield_default( - L, index, "tileable_vertical", default_tiling); + L, index, "tileable_vertical", default_tiling); std::string align_style; if (getstringfield(L, index, "align_style", align_style)) { if (align_style == "user") @@ -492,23 +493,20 @@ TileDef read_tiledef(lua_State *L, int index, u8 drawtype) /******************************************************************************/ ContentFeatures read_content_features(lua_State *L, int index) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; ContentFeatures f; /* Cache existence of some callbacks */ lua_getfield(L, index, "on_construct"); - if (!lua_isnil(L, -1)) - f.has_on_construct = true; + if(!lua_isnil(L, -1)) f.has_on_construct = true; lua_pop(L, 1); lua_getfield(L, index, "on_destruct"); - if (!lua_isnil(L, -1)) - f.has_on_destruct = true; + if(!lua_isnil(L, -1)) f.has_on_destruct = true; lua_pop(L, 1); lua_getfield(L, index, "after_destruct"); - if (!lua_isnil(L, -1)) - f.has_after_destruct = true; + if(!lua_isnil(L, -1)) f.has_after_destruct = true; lua_pop(L, 1); lua_getfield(L, index, "on_rightclick"); @@ -525,8 +523,8 @@ ContentFeatures read_content_features(lua_State *L, int index) /* Visual definition */ - f.drawtype = (NodeDrawType)getenumfield( - L, index, "drawtype", ScriptApiNode::es_DrawType, NDT_NORMAL); + f.drawtype = (NodeDrawType)getenumfield(L, index, "drawtype", + ScriptApiNode::es_DrawType,NDT_NORMAL); getfloatfield(L, index, "visual_scale", f.visual_scale); /* Meshnode model filename */ @@ -535,31 +533,31 @@ ContentFeatures read_content_features(lua_State *L, int index) // tiles = {} lua_getfield(L, index, "tiles"); // If nil, try the deprecated name "tile_images" instead - if (lua_isnil(L, -1)) { + if(lua_isnil(L, -1)){ lua_pop(L, 1); warn_if_field_exists(L, index, "tile_images", "Deprecated; new name is \"tiles\"."); lua_getfield(L, index, "tile_images"); } - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ int table = lua_gettop(L); lua_pushnil(L); int i = 0; - while (lua_next(L, table) != 0) { + while(lua_next(L, table) != 0){ // Read tiledef from value f.tiledef[i] = read_tiledef(L, -1, f.drawtype); // removes value, keeps key for next iteration lua_pop(L, 1); i++; - if (i == 6) { + if(i==6){ lua_pop(L, 1); break; } } // Copy last value to all remaining textures - if (i >= 1) { - TileDef lasttile = f.tiledef[i - 1]; - while (i < 6) { + if(i >= 1){ + TileDef lasttile = f.tiledef[i-1]; + while(i < 6){ f.tiledef[i] = lasttile; i++; } @@ -598,23 +596,23 @@ ContentFeatures read_content_features(lua_State *L, int index) // special_tiles = {} lua_getfield(L, index, "special_tiles"); // If nil, try the deprecated name "special_materials" instead - if (lua_isnil(L, -1)) { + if(lua_isnil(L, -1)){ lua_pop(L, 1); warn_if_field_exists(L, index, "special_materials", "Deprecated; new name is \"special_tiles\"."); lua_getfield(L, index, "special_materials"); } - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ int table = lua_gettop(L); lua_pushnil(L); int i = 0; - while (lua_next(L, table) != 0) { + while(lua_next(L, table) != 0){ // Read tiledef from value f.tiledef_special[i] = read_tiledef(L, -1, f.drawtype); // removes value, keeps key for next iteration lua_pop(L, 1); i++; - if (i == CF_SPECIAL_COUNT) { + if(i==CF_SPECIAL_COUNT){ lua_pop(L, 1); break; } @@ -624,7 +622,8 @@ ContentFeatures read_content_features(lua_State *L, int index) f.alpha = getintfield_default(L, index, "alpha", 255); - bool usealpha = getboolfield_default(L, index, "use_texture_alpha", false); + bool usealpha = getboolfield_default(L, index, + "use_texture_alpha", false); if (usealpha) f.alpha = 0; @@ -648,21 +647,22 @@ ContentFeatures read_content_features(lua_State *L, int index) if (!f.palette_name.empty() && !(f.param_type_2 == CPT2_COLOR || - f.param_type_2 == CPT2_COLORED_FACEDIR || - f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) + f.param_type_2 == CPT2_COLORED_FACEDIR || + f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) warningstream << "Node " << f.name.c_str() - << " has a palette, but not a suitable paramtype2." - << std::endl; + << " has a palette, but not a suitable paramtype2." << std::endl; // Warn about some obsolete fields warn_if_field_exists(L, index, "wall_mounted", "Obsolete; use paramtype2 = 'wallmounted'"); warn_if_field_exists(L, index, "light_propagates", "Obsolete; determined from paramtype"); - warn_if_field_exists(L, index, "dug_item", "Obsolete; use 'drop' field"); - warn_if_field_exists(L, index, "extra_dug_item", "Obsolete; use 'drop' field"); - warn_if_field_exists( - L, index, "extra_dug_item_rarity", "Obsolete; use 'drop' field"); + warn_if_field_exists(L, index, "dug_item", + "Obsolete; use 'drop' field"); + warn_if_field_exists(L, index, "extra_dug_item", + "Obsolete; use 'drop' field"); + warn_if_field_exists(L, index, "extra_dug_item_rarity", + "Obsolete; use 'drop' field"); warn_if_field_exists(L, index, "metadata_name", "Obsolete; use on_add and metadata callbacks"); @@ -695,27 +695,31 @@ ContentFeatures read_content_features(lua_State *L, int index) // Viscosity for fluid flow, ranging from 1 to 7, with // 1 giving almost instantaneous propagation and 7 being // the slowest possible - f.liquid_viscosity = getintfield_default( - L, index, "liquid_viscosity", f.liquid_viscosity); - f.liquid_range = getintfield_default(L, index, "liquid_range", f.liquid_range); + f.liquid_viscosity = getintfield_default(L, index, + "liquid_viscosity", f.liquid_viscosity); + f.liquid_range = getintfield_default(L, index, + "liquid_range", f.liquid_range); f.leveled = getintfield_default(L, index, "leveled", f.leveled); - f.leveled_max = getintfield_default(L, index, "leveled_max", f.leveled_max); + f.leveled_max = getintfield_default(L, index, + "leveled_max", f.leveled_max); getboolfield(L, index, "liquid_renewable", f.liquid_renewable); - f.drowning = getintfield_default(L, index, "drowning", f.drowning); + f.drowning = getintfield_default(L, index, + "drowning", f.drowning); // Amount of light the node emits - f.light_source = getintfield_default(L, index, "light_source", f.light_source); + f.light_source = getintfield_default(L, index, + "light_source", f.light_source); if (f.light_source > LIGHT_MAX) { warningstream << "Node " << f.name.c_str() - << " had greater light_source than " << LIGHT_MAX - << ", it was reduced." << std::endl; + << " had greater light_source than " << LIGHT_MAX + << ", it was reduced." << std::endl; f.light_source = LIGHT_MAX; } - f.damage_per_second = getintfield_default( - L, index, "damage_per_second", f.damage_per_second); + f.damage_per_second = getintfield_default(L, index, + "damage_per_second", f.damage_per_second); lua_getfield(L, index, "node_box"); - if (lua_istable(L, -1)) + if(lua_istable(L, -1)) f.node_box = read_nodebox(L, -1); lua_pop(L, 1); @@ -753,23 +757,24 @@ ContentFeatures read_content_features(lua_State *L, int index) f.connect_sides |= 8; else warningstream << "Unknown value for \"connect_sides\": " - << side << std::endl; + << side << std::endl; lua_pop(L, 1); } } lua_pop(L, 1); lua_getfield(L, index, "selection_box"); - if (lua_istable(L, -1)) + if(lua_istable(L, -1)) f.selection_box = read_nodebox(L, -1); - lua_pop(L, 1); + lua_pop(L, 1); lua_getfield(L, index, "collision_box"); - if (lua_istable(L, -1)) + if(lua_istable(L, -1)) f.collision_box = read_nodebox(L, -1); lua_pop(L, 1); - f.waving = getintfield_default(L, index, "waving", f.waving); + f.waving = getintfield_default(L, index, + "waving", f.waving); // Set to true if paramtype used to be 'facedir_simple' getboolfield(L, index, "legacy_facedir_simple", f.legacy_facedir_simple); @@ -778,7 +783,7 @@ ContentFeatures read_content_features(lua_State *L, int index) // Sound table lua_getfield(L, index, "sounds"); - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ lua_getfield(L, -1, "footstep"); read_soundspec(L, -1, f.sound_footstep); lua_pop(L, 1); @@ -792,7 +797,8 @@ ContentFeatures read_content_features(lua_State *L, int index) lua_pop(L, 1); // Node immediately placed by client when node is dug - getstringfield(L, index, "node_dig_prediction", f.node_dig_prediction); + getstringfield(L, index, "node_dig_prediction", + f.node_dig_prediction); return f; } @@ -800,8 +806,7 @@ ContentFeatures read_content_features(lua_State *L, int index) void push_content_features(lua_State *L, const ContentFeatures &c) { std::string paramtype(ScriptApiNode::es_ContentParamType[(int)c.param_type].str); - std::string paramtype2( - ScriptApiNode::es_ContentParamType2[(int)c.param_type_2].str); + std::string paramtype2(ScriptApiNode::es_ContentParamType2[(int)c.param_type_2].str); std::string drawtype(ScriptApiNode::es_DrawType[(int)c.drawtype].str); std::string liquid_type(ScriptApiNode::es_LiquidType[(int)c.liquid_type].str); @@ -829,7 +834,7 @@ void push_content_features(lua_State *L, const ContentFeatures &c) lua_setfield(L, -2, "mesh"); } #ifndef SERVER - push_ARGB8(L, c.minimap_color); // I know this is not set-able w/ register_node, + push_ARGB8(L, c.minimap_color); // I know this is not set-able w/ register_node, lua_setfield(L, -2, "minimap_color"); // but the people need to know! #endif lua_pushnumber(L, c.visual_scale); @@ -929,47 +934,48 @@ void push_content_features(lua_State *L, const ContentFeatures &c) void push_nodebox(lua_State *L, const NodeBox &box) { lua_newtable(L); - switch (box.type) { - case NODEBOX_REGULAR: - lua_pushstring(L, "regular"); - lua_setfield(L, -2, "type"); - break; - case NODEBOX_LEVELED: - case NODEBOX_FIXED: - lua_pushstring(L, "fixed"); - lua_setfield(L, -2, "type"); - push_box(L, box.fixed); - lua_setfield(L, -2, "fixed"); - break; - case NODEBOX_WALLMOUNTED: - lua_pushstring(L, "wallmounted"); - lua_setfield(L, -2, "type"); - push_aabb3f(L, box.wall_top); - lua_setfield(L, -2, "wall_top"); - push_aabb3f(L, box.wall_bottom); - lua_setfield(L, -2, "wall_bottom"); - push_aabb3f(L, box.wall_side); - lua_setfield(L, -2, "wall_side"); - break; - case NODEBOX_CONNECTED: - lua_pushstring(L, "connected"); - lua_setfield(L, -2, "type"); - push_box(L, box.connect_top); - lua_setfield(L, -2, "connect_top"); - push_box(L, box.connect_bottom); - lua_setfield(L, -2, "connect_bottom"); - push_box(L, box.connect_front); - lua_setfield(L, -2, "connect_front"); - push_box(L, box.connect_back); - lua_setfield(L, -2, "connect_back"); - push_box(L, box.connect_left); - lua_setfield(L, -2, "connect_left"); - push_box(L, box.connect_right); - lua_setfield(L, -2, "connect_right"); - break; - default: - FATAL_ERROR("Invalid box.type"); - break; + switch (box.type) + { + case NODEBOX_REGULAR: + lua_pushstring(L, "regular"); + lua_setfield(L, -2, "type"); + break; + case NODEBOX_LEVELED: + case NODEBOX_FIXED: + lua_pushstring(L, "fixed"); + lua_setfield(L, -2, "type"); + push_box(L, box.fixed); + lua_setfield(L, -2, "fixed"); + break; + case NODEBOX_WALLMOUNTED: + lua_pushstring(L, "wallmounted"); + lua_setfield(L, -2, "type"); + push_aabb3f(L, box.wall_top); + lua_setfield(L, -2, "wall_top"); + push_aabb3f(L, box.wall_bottom); + lua_setfield(L, -2, "wall_bottom"); + push_aabb3f(L, box.wall_side); + lua_setfield(L, -2, "wall_side"); + break; + case NODEBOX_CONNECTED: + lua_pushstring(L, "connected"); + lua_setfield(L, -2, "type"); + push_box(L, box.connect_top); + lua_setfield(L, -2, "connect_top"); + push_box(L, box.connect_bottom); + lua_setfield(L, -2, "connect_bottom"); + push_box(L, box.connect_front); + lua_setfield(L, -2, "connect_front"); + push_box(L, box.connect_back); + lua_setfield(L, -2, "connect_back"); + push_box(L, box.connect_left); + lua_setfield(L, -2, "connect_left"); + push_box(L, box.connect_right); + lua_setfield(L, -2, "connect_right"); + break; + default: + FATAL_ERROR("Invalid box.type"); + break; } } @@ -998,37 +1004,37 @@ void push_palette(lua_State *L, const std::vector<video::SColor> *palette) } /******************************************************************************/ -void read_server_sound_params(lua_State *L, int index, ServerSoundParams ¶ms) +void read_server_sound_params(lua_State *L, int index, + ServerSoundParams ¶ms) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; // Clear params = ServerSoundParams(); - if (lua_istable(L, index)) { + if(lua_istable(L, index)){ getfloatfield(L, index, "gain", params.gain); getstringfield(L, index, "to_player", params.to_player); getfloatfield(L, index, "fade", params.fade); getfloatfield(L, index, "pitch", params.pitch); lua_getfield(L, index, "pos"); - if (!lua_isnil(L, -1)) { - v3f p = read_v3f(L, -1) * BS; + if(!lua_isnil(L, -1)){ + v3f p = read_v3f(L, -1)*BS; params.pos = p; params.type = ServerSoundParams::SSP_POSITIONAL; } lua_pop(L, 1); lua_getfield(L, index, "object"); - if (!lua_isnil(L, -1)) { + if(!lua_isnil(L, -1)){ ObjectRef *ref = ObjectRef::checkobject(L, -1); ServerActiveObject *sao = ObjectRef::getobject(ref); - if (sao) { + if(sao){ params.object = sao->getId(); params.type = ServerSoundParams::SSP_OBJECT; } } lua_pop(L, 1); - params.max_hear_distance = - BS * getfloatfield_default(L, index, "max_hear_distance", - params.max_hear_distance / BS); + params.max_hear_distance = BS*getfloatfield_default(L, index, + "max_hear_distance", params.max_hear_distance/BS); getboolfield(L, index, "loop", params.loop); getstringfield(L, index, "exclude_player", params.exclude_player); } @@ -1037,7 +1043,7 @@ void read_server_sound_params(lua_State *L, int index, ServerSoundParams ¶ms /******************************************************************************/ void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; if (lua_isnil(L, index)) return; @@ -1074,21 +1080,20 @@ NodeBox read_nodebox(lua_State *L, int index) luaL_checktype(L, -1, LUA_TTABLE); - nodebox.type = (NodeBoxType)getenumfield( - L, index, "type", ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR); + nodebox.type = (NodeBoxType)getenumfield(L, index, "type", + ScriptApiNode::es_NodeBoxType, NODEBOX_REGULAR); -#define NODEBOXREAD(n, s) \ - { \ - lua_getfield(L, index, (s)); \ - if (lua_istable(L, -1)) \ - (n) = read_aabb3f(L, -1, BS); \ - lua_pop(L, 1); \ +#define NODEBOXREAD(n, s){ \ + lua_getfield(L, index, (s)); \ + if (lua_istable(L, -1)) \ + (n) = read_aabb3f(L, -1, BS); \ + lua_pop(L, 1); \ } -#define NODEBOXREADVEC(n, s) \ - lua_getfield(L, index, (s)); \ - if (lua_istable(L, -1)) \ - (n) = read_aabb3f_vector(L, -1, BS); \ +#define NODEBOXREADVEC(n, s) \ + lua_getfield(L, index, (s)); \ + if (lua_istable(L, -1)) \ + (n) = read_aabb3f_vector(L, -1, BS); \ lua_pop(L, 1); NODEBOXREADVEC(nodebox.fixed, "fixed"); @@ -1154,31 +1159,34 @@ void pushnode(lua_State *L, const MapNode &n, const NodeDefManager *ndef) } /******************************************************************************/ -void warn_if_field_exists( - lua_State *L, int table, const char *name, const std::string &message) +void warn_if_field_exists(lua_State *L, int table, + const char *name, const std::string &message) { lua_getfield(L, table, name); if (!lua_isnil(L, -1)) { - warningstream << "Field \"" << name << "\": " << message << std::endl; + warningstream << "Field \"" << name << "\": " + << message << std::endl; infostream << script_get_backtrace(L) << std::endl; } lua_pop(L, 1); } /******************************************************************************/ -int getenumfield(lua_State *L, int table, const char *fieldname, const EnumString *spec, - int default_) +int getenumfield(lua_State *L, int table, + const char *fieldname, const EnumString *spec, int default_) { int result = default_; - string_to_enum(spec, result, getstringfield_default(L, table, fieldname, "")); + string_to_enum(spec, result, + getstringfield_default(L, table, fieldname, "")); return result; } /******************************************************************************/ -bool string_to_enum(const EnumString *spec, int &result, const std::string &str) +bool string_to_enum(const EnumString *spec, int &result, + const std::string &str) { const EnumString *esp = spec; - while (esp->str) { + while(esp->str){ if (!strcmp(str.c_str(), esp->str)) { result = esp->num; return true; @@ -1189,9 +1197,9 @@ bool string_to_enum(const EnumString *spec, int &result, const std::string &str) } /******************************************************************************/ -ItemStack read_item(lua_State *L, int index, IItemDefManager *idef) +ItemStack read_item(lua_State* L, int index, IItemDefManager *idef) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; if (lua_isnil(L, index)) { @@ -1207,16 +1215,21 @@ ItemStack read_item(lua_State *L, int index, IItemDefManager *idef) if (lua_isstring(L, index)) { // Convert from itemstring std::string itemstring = lua_tostring(L, index); - try { + try + { ItemStack item; item.deSerialize(itemstring, idef); return item; - } catch (SerializationError &e) { - warningstream << "unable to create item from itemstring" - << ": " << itemstring << std::endl; + } + catch(SerializationError &e) + { + warningstream<<"unable to create item from itemstring" + <<": "<<itemstring<<std::endl; return ItemStack(); } - } else if (lua_istable(L, index)) { + } + else if(lua_istable(L, index)) + { // Convert from table std::string name = getstringfield_default(L, index, "name", ""); int count = getintfield_default(L, index, "count", 1); @@ -1240,8 +1253,7 @@ ItemStack read_item(lua_State *L, int index, IItemDefManager *idef) const char *value_cs = lua_tolstring(L, -1, &value_len); std::string value(value_cs, value_len); istack.metadata.setString(key, value); - lua_pop(L, 1); // removes value, keeps key for next - // iteration + lua_pop(L, 1); // removes value, keeps key for next iteration } } @@ -1252,56 +1264,57 @@ ItemStack read_item(lua_State *L, int index, IItemDefManager *idef) } /******************************************************************************/ -void push_tool_capabilities(lua_State *L, const ToolCapabilities &toolcap) +void push_tool_capabilities(lua_State *L, + const ToolCapabilities &toolcap) { lua_newtable(L); setfloatfield(L, -1, "full_punch_interval", toolcap.full_punch_interval); setintfield(L, -1, "max_drop_level", toolcap.max_drop_level); setintfield(L, -1, "punch_attack_uses", toolcap.punch_attack_uses); - // Create groupcaps table - lua_newtable(L); - // For each groupcap - for (const auto &gc_it : toolcap.groupcaps) { - // Create groupcap table + // Create groupcaps table lua_newtable(L); - const std::string &name = gc_it.first; - const ToolGroupCap &groupcap = gc_it.second; - // Create subtable "times" + // For each groupcap + for (const auto &gc_it : toolcap.groupcaps) { + // Create groupcap table + lua_newtable(L); + const std::string &name = gc_it.first; + const ToolGroupCap &groupcap = gc_it.second; + // Create subtable "times" + lua_newtable(L); + for (auto time : groupcap.times) { + lua_pushinteger(L, time.first); + lua_pushnumber(L, time.second); + lua_settable(L, -3); + } + // Set subtable "times" + lua_setfield(L, -2, "times"); + // Set simple parameters + setintfield(L, -1, "maxlevel", groupcap.maxlevel); + setintfield(L, -1, "uses", groupcap.uses); + // Insert groupcap table into groupcaps table + lua_setfield(L, -2, name.c_str()); + } + // Set groupcaps table + lua_setfield(L, -2, "groupcaps"); + //Create damage_groups table lua_newtable(L); - for (auto time : groupcap.times) { - lua_pushinteger(L, time.first); - lua_pushnumber(L, time.second); - lua_settable(L, -3); + // For each damage group + for (const auto &damageGroup : toolcap.damageGroups) { + // Create damage group table + lua_pushinteger(L, damageGroup.second); + lua_setfield(L, -2, damageGroup.first.c_str()); } - // Set subtable "times" - lua_setfield(L, -2, "times"); - // Set simple parameters - setintfield(L, -1, "maxlevel", groupcap.maxlevel); - setintfield(L, -1, "uses", groupcap.uses); - // Insert groupcap table into groupcaps table - lua_setfield(L, -2, name.c_str()); - } - // Set groupcaps table - lua_setfield(L, -2, "groupcaps"); - // Create damage_groups table - lua_newtable(L); - // For each damage group - for (const auto &damageGroup : toolcap.damageGroups) { - // Create damage group table - lua_pushinteger(L, damageGroup.second); - lua_setfield(L, -2, damageGroup.first.c_str()); - } - lua_setfield(L, -2, "damage_groups"); + lua_setfield(L, -2, "damage_groups"); } /******************************************************************************/ void push_inventory(lua_State *L, Inventory *inventory) { - std::vector<const InventoryList *> lists = inventory->getLists(); - std::vector<const InventoryList *>::iterator iter = lists.begin(); + std::vector<const InventoryList*> lists = inventory->getLists(); + std::vector<const InventoryList*>::iterator iter = lists.begin(); lua_createtable(L, 0, lists.size()); for (; iter != lists.end(); iter++) { - const char *name = (*iter)->getName().c_str(); + const char* name = (*iter)->getName().c_str(); lua_pushstring(L, name); push_inventory_list(L, inventory, name); lua_rawset(L, -3); @@ -1312,40 +1325,40 @@ void push_inventory(lua_State *L, Inventory *inventory) void push_inventory_list(lua_State *L, Inventory *inv, const char *name) { InventoryList *invlist = inv->getList(name); - if (invlist == NULL) { + if(invlist == NULL){ lua_pushnil(L); return; } std::vector<ItemStack> items; - for (u32 i = 0; i < invlist->getSize(); i++) + for(u32 i=0; i<invlist->getSize(); i++) items.push_back(invlist->getItem(i)); push_items(L, items); } /******************************************************************************/ -void read_inventory_list(lua_State *L, int tableindex, Inventory *inv, const char *name, - Server *srv, int forcesize) +void read_inventory_list(lua_State *L, int tableindex, + Inventory *inv, const char *name, Server* srv, int forcesize) { - if (tableindex < 0) + if(tableindex < 0) tableindex = lua_gettop(L) + 1 + tableindex; // If nil, delete list - if (lua_isnil(L, tableindex)) { + if(lua_isnil(L, tableindex)){ inv->deleteList(name); return; } // Otherwise set list - std::vector<ItemStack> items = read_items(L, tableindex, srv); + std::vector<ItemStack> items = read_items(L, tableindex,srv); int listsize = (forcesize != -1) ? forcesize : items.size(); InventoryList *invlist = inv->addList(name, listsize); int index = 0; - for (std::vector<ItemStack>::const_iterator i = items.begin(); i != items.end(); - ++i) { - if (forcesize != -1 && index == forcesize) + for(std::vector<ItemStack>::const_iterator + i = items.begin(); i != items.end(); ++i){ + if(forcesize != -1 && index == forcesize) break; invlist->changeItem(index, *i); index++; } - while (forcesize != -1 && index < forcesize) { + while(forcesize != -1 && index < forcesize){ invlist->deleteItem(index); index++; } @@ -1354,7 +1367,7 @@ void read_inventory_list(lua_State *L, int tableindex, Inventory *inv, const cha /******************************************************************************/ struct TileAnimationParams read_animation_definition(lua_State *L, int index) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; struct TileAnimationParams anim; @@ -1362,75 +1375,74 @@ struct TileAnimationParams read_animation_definition(lua_State *L, int index) if (!lua_istable(L, index)) return anim; - anim.type = (TileAnimationType)getenumfield( - L, index, "type", es_TileAnimationType, TAT_NONE); + anim.type = (TileAnimationType) + getenumfield(L, index, "type", es_TileAnimationType, + TAT_NONE); if (anim.type == TAT_VERTICAL_FRAMES) { // {type="vertical_frames", aspect_w=16, aspect_h=16, length=2.0} anim.vertical_frames.aspect_w = - getintfield_default(L, index, "aspect_w", 16); + getintfield_default(L, index, "aspect_w", 16); anim.vertical_frames.aspect_h = - getintfield_default(L, index, "aspect_h", 16); + getintfield_default(L, index, "aspect_h", 16); anim.vertical_frames.length = - getfloatfield_default(L, index, "length", 1.0); + getfloatfield_default(L, index, "length", 1.0); } else if (anim.type == TAT_SHEET_2D) { // {type="sheet_2d", frames_w=5, frames_h=3, frame_length=0.5} - getintfield(L, index, "frames_w", anim.sheet_2d.frames_w); - getintfield(L, index, "frames_h", anim.sheet_2d.frames_h); - getfloatfield(L, index, "frame_length", anim.sheet_2d.frame_length); + getintfield(L, index, "frames_w", + anim.sheet_2d.frames_w); + getintfield(L, index, "frames_h", + anim.sheet_2d.frames_h); + getfloatfield(L, index, "frame_length", + anim.sheet_2d.frame_length); } return anim; } /******************************************************************************/ -ToolCapabilities read_tool_capabilities(lua_State *L, int table) +ToolCapabilities read_tool_capabilities( + lua_State *L, int table) { ToolCapabilities toolcap; getfloatfield(L, table, "full_punch_interval", toolcap.full_punch_interval); getintfield(L, table, "max_drop_level", toolcap.max_drop_level); getintfield(L, table, "punch_attack_uses", toolcap.punch_attack_uses); lua_getfield(L, table, "groupcaps"); - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ int table_groupcaps = lua_gettop(L); lua_pushnil(L); - while (lua_next(L, table_groupcaps) != 0) { + while(lua_next(L, table_groupcaps) != 0){ // key at index -2 and value at index -1 std::string groupname = luaL_checkstring(L, -2); - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ int table_groupcap = lua_gettop(L); // This will be created ToolGroupCap groupcap; // Read simple parameters - getintfield(L, table_groupcap, "maxlevel", - groupcap.maxlevel); + getintfield(L, table_groupcap, "maxlevel", groupcap.maxlevel); getintfield(L, table_groupcap, "uses", groupcap.uses); // DEPRECATED: maxwear float maxwear = 0; - if (getfloatfield(L, table_groupcap, "maxwear", - maxwear)) { + if (getfloatfield(L, table_groupcap, "maxwear", maxwear)){ if (maxwear != 0) - groupcap.uses = 1.0 / maxwear; + groupcap.uses = 1.0/maxwear; else groupcap.uses = 0; - warningstream << "Field \"maxwear\" is " - "deprecated; " - << "replace with uses=1/maxwear" - << std::endl; - infostream << script_get_backtrace(L) - << std::endl; + warningstream << "Field \"maxwear\" is deprecated; " + << "replace with uses=1/maxwear" << std::endl; + infostream << script_get_backtrace(L) << std::endl; } // Read "times" table lua_getfield(L, table_groupcap, "times"); - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ int table_times = lua_gettop(L); lua_pushnil(L); - while (lua_next(L, table_times) != 0) { + while(lua_next(L, table_times) != 0){ // key at index -2 and value at index -1 int rating = luaL_checkinteger(L, -2); float time = luaL_checknumber(L, -1); groupcap.times[rating] = time; - // removes value, keeps key for next - // iteration + // removes value, keeps key for next iteration lua_pop(L, 1); } } @@ -1445,10 +1457,10 @@ ToolCapabilities read_tool_capabilities(lua_State *L, int table) lua_pop(L, 1); lua_getfield(L, table, "damage_groups"); - if (lua_istable(L, -1)) { + if(lua_istable(L, -1)){ int table_damage_groups = lua_gettop(L); lua_pushnil(L); - while (lua_next(L, table_damage_groups) != 0) { + while(lua_next(L, table_damage_groups) != 0){ // key at index -2 and value at index -1 std::string groupname = luaL_checkstring(L, -2); u16 value = luaL_checkinteger(L, -1); @@ -1462,7 +1474,7 @@ ToolCapabilities read_tool_capabilities(lua_State *L, int table) } /******************************************************************************/ -void push_dig_params(lua_State *L, const DigParams ¶ms) +void push_dig_params(lua_State *L,const DigParams ¶ms) { lua_createtable(L, 0, 3); setboolfield(L, -1, "diggable", params.diggable); @@ -1471,7 +1483,7 @@ void push_dig_params(lua_State *L, const DigParams ¶ms) } /******************************************************************************/ -void push_hit_params(lua_State *L, const HitParams ¶ms) +void push_hit_params(lua_State *L,const HitParams ¶ms) { lua_createtable(L, 0, 3); setintfield(L, -1, "hp", params.hp); @@ -1480,8 +1492,8 @@ void push_hit_params(lua_State *L, const HitParams ¶ms) /******************************************************************************/ -bool getflagsfield(lua_State *L, int table, const char *fieldname, FlagDesc *flagdesc, - u32 *flags, u32 *flagmask) +bool getflagsfield(lua_State *L, int table, const char *fieldname, + FlagDesc *flagdesc, u32 *flags, u32 *flagmask) { lua_getfield(L, table, fieldname); @@ -1492,7 +1504,8 @@ bool getflagsfield(lua_State *L, int table, const char *fieldname, FlagDesc *fla return success; } -bool read_flags(lua_State *L, int index, FlagDesc *flagdesc, u32 *flags, u32 *flagmask) +bool read_flags(lua_State *L, int index, FlagDesc *flagdesc, + u32 *flags, u32 *flagmask) { if (lua_isstring(L, index)) { std::string flagstr = lua_tostring(L, index); @@ -1588,7 +1601,7 @@ void push_items(lua_State *L, const std::vector<ItemStack> &items) /******************************************************************************/ std::vector<ItemStack> read_items(lua_State *L, int index, Server *srv) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; std::vector<ItemStack> items; @@ -1599,7 +1612,7 @@ std::vector<ItemStack> read_items(lua_State *L, int index, Server *srv) if (key < 1) { throw LuaError("Invalid inventory list index"); } - if (items.size() < (u32)key) { + if (items.size() < (u32) key) { items.resize(key); } items[key - 1] = read_item(L, -1, srv->idef()); @@ -1630,23 +1643,21 @@ bool read_noiseparams(lua_State *L, int index, NoiseParams *np) if (!lua_istable(L, index)) return false; - getfloatfield(L, index, "offset", np->offset); - getfloatfield(L, index, "scale", np->scale); - getfloatfield(L, index, "persist", np->persist); + getfloatfield(L, index, "offset", np->offset); + getfloatfield(L, index, "scale", np->scale); + getfloatfield(L, index, "persist", np->persist); getfloatfield(L, index, "persistence", np->persist); - getfloatfield(L, index, "lacunarity", np->lacunarity); - getintfield(L, index, "seed", np->seed); - getintfield(L, index, "octaves", np->octaves); + getfloatfield(L, index, "lacunarity", np->lacunarity); + getintfield(L, index, "seed", np->seed); + getintfield(L, index, "octaves", np->octaves); - u32 flags = 0; + u32 flags = 0; u32 flagmask = 0; - np->flags = getflagsfield(L, index, "flags", flagdesc_noiseparams, &flags, - &flagmask) - ? flags - : NOISE_FLAG_DEFAULTS; + np->flags = getflagsfield(L, index, "flags", flagdesc_noiseparams, + &flags, &flagmask) ? flags : NOISE_FLAG_DEFAULTS; lua_getfield(L, index, "spread"); - np->spread = read_v3f(L, -1); + np->spread = read_v3f(L, -1); lua_pop(L, 1); return true; @@ -1668,7 +1679,8 @@ void push_noiseparams(lua_State *L, NoiseParams *np) lua_pushnumber(L, np->octaves); lua_setfield(L, -2, "octaves"); - push_flags_string(L, flagdesc_noiseparams, np->flags, np->flags); + push_flags_string(L, flagdesc_noiseparams, np->flags, + np->flags); lua_setfield(L, -2, "flags"); push_v3_float_string(L, np->spread); @@ -1691,52 +1703,55 @@ static int push_json_value_getdepth(const Json::Value &value) return maxdepth + 1; } // Recursive function to convert JSON --> Lua table -static bool push_json_value_helper(lua_State *L, const Json::Value &value, int nullindex) +static bool push_json_value_helper(lua_State *L, const Json::Value &value, + int nullindex) { - switch (value.type()) { - case Json::nullValue: - default: - lua_pushvalue(L, nullindex); - break; - case Json::intValue: - lua_pushinteger(L, value.asLargestInt()); - break; - case Json::uintValue: - lua_pushinteger(L, value.asLargestUInt()); - break; - case Json::realValue: - lua_pushnumber(L, value.asDouble()); - break; - case Json::stringValue: { - const char *str = value.asCString(); - lua_pushstring(L, str ? str : ""); - } break; - case Json::booleanValue: - lua_pushboolean(L, value.asInt()); - break; - case Json::arrayValue: - lua_createtable(L, value.size(), 0); - for (Json::Value::const_iterator it = value.begin(); it != value.end(); - ++it) { - push_json_value_helper(L, *it, nullindex); - lua_rawseti(L, -2, it.index() + 1); - } - break; - case Json::objectValue: - lua_createtable(L, 0, value.size()); - for (Json::Value::const_iterator it = value.begin(); it != value.end(); - ++it) { + switch(value.type()) { + case Json::nullValue: + default: + lua_pushvalue(L, nullindex); + break; + case Json::intValue: + lua_pushinteger(L, value.asLargestInt()); + break; + case Json::uintValue: + lua_pushinteger(L, value.asLargestUInt()); + break; + case Json::realValue: + lua_pushnumber(L, value.asDouble()); + break; + case Json::stringValue: + { + const char *str = value.asCString(); + lua_pushstring(L, str ? str : ""); + } + break; + case Json::booleanValue: + lua_pushboolean(L, value.asInt()); + break; + case Json::arrayValue: + lua_createtable(L, value.size(), 0); + for (Json::Value::const_iterator it = value.begin(); + it != value.end(); ++it) { + push_json_value_helper(L, *it, nullindex); + lua_rawseti(L, -2, it.index() + 1); + } + break; + case Json::objectValue: + lua_createtable(L, 0, value.size()); + for (Json::Value::const_iterator it = value.begin(); + it != value.end(); ++it) { #if !defined(JSONCPP_STRING) && (JSONCPP_VERSION_MAJOR < 1 || JSONCPP_VERSION_MINOR < 9) - const char *str = it.memberName(); - lua_pushstring(L, str ? str : ""); + const char *str = it.memberName(); + lua_pushstring(L, str ? str : ""); #else - std::string str = it.name(); - lua_pushstring(L, str.c_str()); + std::string str = it.name(); + lua_pushstring(L, str.c_str()); #endif - push_json_value_helper(L, *it, nullindex); - lua_rawset(L, -3); - } - break; + push_json_value_helper(L, *it, nullindex); + lua_rawset(L, -3); + } + break; } return true; } @@ -1744,7 +1759,7 @@ static bool push_json_value_helper(lua_State *L, const Json::Value &value, int n // nullindex: Lua stack index of value to use in place of JSON null bool push_json_value(lua_State *L, const Json::Value &value, int nullindex) { - if (nullindex < 0) + if(nullindex < 0) nullindex = lua_gettop(L) + 1 + nullindex; int depth = push_json_value_getdepth(value); @@ -1765,7 +1780,7 @@ void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion) } int type = lua_type(L, index); if (type == LUA_TBOOLEAN) { - root = (bool)lua_toboolean(L, index); + root = (bool) lua_toboolean(L, index); } else if (type == LUA_TNUMBER) { root = lua_tonumber(L, index); } else if (type == LUA_TSTRING) { @@ -1783,43 +1798,33 @@ void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion) int keytype = lua_type(L, -1); if (keytype == LUA_TNUMBER) { lua_Number key = lua_tonumber(L, -1); - if (roottype != Json::nullValue && - roottype != Json::arrayValue) { - throw SerializationError("Can't mix array and " - "object values in JSON"); + if (roottype != Json::nullValue && roottype != Json::arrayValue) { + throw SerializationError("Can't mix array and object values in JSON"); } else if (key < 1) { - throw SerializationError( - "Can't use zero-based or " - "negative indexes in JSON"); + throw SerializationError("Can't use zero-based or negative indexes in JSON"); } else if (floor(key) != key) { - throw SerializationError( - "Can't use indexes with a " - "fractional part in JSON"); + throw SerializationError("Can't use indexes with a fractional part in JSON"); } - root[(Json::ArrayIndex)key - 1] = value; + root[(Json::ArrayIndex) key - 1] = value; } else if (keytype == LUA_TSTRING) { - if (roottype != Json::nullValue && - roottype != Json::objectValue) { - throw SerializationError("Can't mix array and " - "object values in JSON"); + if (roottype != Json::nullValue && roottype != Json::objectValue) { + throw SerializationError("Can't mix array and object values in JSON"); } root[lua_tostring(L, -1)] = value; } else { - throw SerializationError("Lua key to convert to JSON is " - "not a string or number"); + throw SerializationError("Lua key to convert to JSON is not a string or number"); } } } else if (type == LUA_TNIL) { root = Json::nullValue; } else { - throw SerializationError("Can only store booleans, numbers, strings, " - "objects, arrays, and null in JSON"); + throw SerializationError("Can only store booleans, numbers, strings, objects, arrays, and null in JSON"); } lua_pop(L, 1); // Pop value } -void push_pointed_thing( - lua_State *L, const PointedThing &pointed, bool csm, bool hitpoint) +void push_pointed_thing(lua_State *L, const PointedThing &pointed, bool csm, + bool hitpoint) { lua_newtable(L); if (pointed.type == POINTEDTHING_NODE) { @@ -1838,7 +1843,7 @@ void push_pointed_thing( } else { push_objectRef(L, pointed.object_id); } - + lua_setfield(L, -2, "ref"); } else { lua_pushstring(L, "nothing"); @@ -1868,8 +1873,8 @@ void push_objectRef(lua_State *L, const u16 id) void read_hud_element(lua_State *L, HudElement *elem) { - elem->type = (HudElementType)getenumfield( - L, 2, "hud_elem_type", es_HudElementType, HUD_ELEM_TEXT); + elem->type = (HudElementType)getenumfield(L, 2, "hud_elem_type", + es_HudElementType, HUD_ELEM_TEXT); lua_getfield(L, 2, "position"); elem->pos = lua_istable(L, -1) ? read_v2f(L, -1) : v2f(); @@ -1883,18 +1888,18 @@ void read_hud_element(lua_State *L, HudElement *elem) elem->size = lua_istable(L, -1) ? read_v2s32(L, -1) : v2s32(); lua_pop(L, 1); - elem->name = getstringfield_default(L, 2, "name", ""); - elem->text = getstringfield_default(L, 2, "text", ""); - elem->number = getintfield_default(L, 2, "number", 0); + elem->name = getstringfield_default(L, 2, "name", ""); + elem->text = getstringfield_default(L, 2, "text", ""); + elem->number = getintfield_default(L, 2, "number", 0); if (elem->type == HUD_ELEM_WAYPOINT) // waypoints reuse the item field to store precision, item = precision + 1 elem->item = getintfield_default(L, 2, "precision", -1) + 1; else elem->item = getintfield_default(L, 2, "item", 0); - elem->dir = getintfield_default(L, 2, "direction", 0); - elem->z_index = MYMAX( - S16_MIN, MYMIN(S16_MAX, getintfield_default(L, 2, "z_index", 0))); - elem->text2 = getstringfield_default(L, 2, "text2", ""); + elem->dir = getintfield_default(L, 2, "direction", 0); + elem->z_index = MYMAX(S16_MIN, MYMIN(S16_MAX, + getintfield_default(L, 2, "z_index", 0))); + elem->text2 = getstringfield_default(L, 2, "text2", ""); // Deprecated, only for compatibility's sake if (elem->dir == 0) @@ -1913,8 +1918,8 @@ void read_hud_element(lua_State *L, HudElement *elem) lua_pop(L, 1); /* check for known deprecated element usage */ - if ((elem->type == HUD_ELEM_STATBAR) && (elem->size == v2s32())) - log_deprecated(L, "Deprecated usage of statbar without size!"); + if ((elem->type == HUD_ELEM_STATBAR) && (elem->size == v2s32())) + log_deprecated(L,"Deprecated usage of statbar without size!"); } void push_hud_element(lua_State *L, HudElement *elem) @@ -1974,64 +1979,63 @@ HudElementStat read_hud_change(lua_State *L, HudElement *elem, void **value) if (lua_isstring(L, 3)) { int statint; std::string statstr = lua_tostring(L, 3); - stat = string_to_enum(es_HudElementStat, statint, statstr) - ? (HudElementStat)statint - : stat; + stat = string_to_enum(es_HudElementStat, statint, statstr) ? + (HudElementStat)statint : stat; } switch (stat) { - case HUD_STAT_POS: - elem->pos = read_v2f(L, 4); - *value = &elem->pos; - break; - case HUD_STAT_NAME: - elem->name = luaL_checkstring(L, 4); - *value = &elem->name; - break; - case HUD_STAT_SCALE: - elem->scale = read_v2f(L, 4); - *value = &elem->scale; - break; - case HUD_STAT_TEXT: - elem->text = luaL_checkstring(L, 4); - *value = &elem->text; - break; - case HUD_STAT_NUMBER: - elem->number = luaL_checknumber(L, 4); - *value = &elem->number; - break; - case HUD_STAT_ITEM: - elem->item = luaL_checknumber(L, 4); - *value = &elem->item; - break; - case HUD_STAT_DIR: - elem->dir = luaL_checknumber(L, 4); - *value = &elem->dir; - break; - case HUD_STAT_ALIGN: - elem->align = read_v2f(L, 4); - *value = &elem->align; - break; - case HUD_STAT_OFFSET: - elem->offset = read_v2f(L, 4); - *value = &elem->offset; - break; - case HUD_STAT_WORLD_POS: - elem->world_pos = read_v3f(L, 4); - *value = &elem->world_pos; - break; - case HUD_STAT_SIZE: - elem->size = read_v2s32(L, 4); - *value = &elem->size; - break; - case HUD_STAT_Z_INDEX: - elem->z_index = MYMAX(S16_MIN, MYMIN(S16_MAX, luaL_checknumber(L, 4))); - *value = &elem->z_index; - break; - case HUD_STAT_TEXT2: - elem->text2 = luaL_checkstring(L, 4); - *value = &elem->text2; - break; + case HUD_STAT_POS: + elem->pos = read_v2f(L, 4); + *value = &elem->pos; + break; + case HUD_STAT_NAME: + elem->name = luaL_checkstring(L, 4); + *value = &elem->name; + break; + case HUD_STAT_SCALE: + elem->scale = read_v2f(L, 4); + *value = &elem->scale; + break; + case HUD_STAT_TEXT: + elem->text = luaL_checkstring(L, 4); + *value = &elem->text; + break; + case HUD_STAT_NUMBER: + elem->number = luaL_checknumber(L, 4); + *value = &elem->number; + break; + case HUD_STAT_ITEM: + elem->item = luaL_checknumber(L, 4); + *value = &elem->item; + break; + case HUD_STAT_DIR: + elem->dir = luaL_checknumber(L, 4); + *value = &elem->dir; + break; + case HUD_STAT_ALIGN: + elem->align = read_v2f(L, 4); + *value = &elem->align; + break; + case HUD_STAT_OFFSET: + elem->offset = read_v2f(L, 4); + *value = &elem->offset; + break; + case HUD_STAT_WORLD_POS: + elem->world_pos = read_v3f(L, 4); + *value = &elem->world_pos; + break; + case HUD_STAT_SIZE: + elem->size = read_v2s32(L, 4); + *value = &elem->size; + break; + case HUD_STAT_Z_INDEX: + elem->z_index = MYMAX(S16_MIN, MYMIN(S16_MAX, luaL_checknumber(L, 4))); + *value = &elem->z_index; + break; + case HUD_STAT_TEXT2: + elem->text2 = luaL_checkstring(L, 4); + *value = &elem->text2; + break; } return stat; } @@ -2040,15 +2044,15 @@ HudElementStat read_hud_change(lua_State *L, HudElement *elem, void **value) // Indices must match values in `enum CollisionType` exactly!! static const char *collision_type_str[] = { - "node", - "object", + "node", + "object", }; // Indices must match values in `enum CollisionAxis` exactly!! static const char *collision_axis_str[] = { - "x", - "y", - "z", + "x", + "y", + "z", }; void push_collision_move_result(lua_State *L, const collisionMoveResult &res) diff --git a/src/script/common/c_content.h b/src/script/common/c_content.h index 49ab96fd5..5a8bf6700 100644 --- a/src/script/common/c_content.h +++ b/src/script/common/c_content.h @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + /******************************************************************************/ /******************************************************************************/ /* WARNING!!!! do NOT add this header in any include file or any code file */ @@ -40,10 +41,7 @@ extern "C" { #include "c_types.h" #include "hud.h" -namespace Json -{ -class Value; -} +namespace Json { class Value; } struct MapNode; class NodeDefManager; @@ -69,96 +67,138 @@ struct collisionMoveResult; extern struct EnumString es_TileAnimationType[]; -ContentFeatures read_content_features(lua_State *L, int index); -void push_content_features(lua_State *L, const ContentFeatures &c); +ContentFeatures read_content_features (lua_State *L, int index); +void push_content_features (lua_State *L, + const ContentFeatures &c); -void push_nodebox(lua_State *L, const NodeBox &box); -void push_box(lua_State *L, const std::vector<aabb3f> &box); +void push_nodebox (lua_State *L, + const NodeBox &box); +void push_box (lua_State *L, + const std::vector<aabb3f> &box); -void push_palette(lua_State *L, const std::vector<video::SColor> *palette); +void push_palette (lua_State *L, + const std::vector<video::SColor> *palette); -TileDef read_tiledef(lua_State *L, int index, u8 drawtype); +TileDef read_tiledef (lua_State *L, int index, + u8 drawtype); -void read_soundspec(lua_State *L, int index, SimpleSoundSpec &spec); -NodeBox read_nodebox(lua_State *L, int index); +void read_soundspec (lua_State *L, int index, + SimpleSoundSpec &spec); +NodeBox read_nodebox (lua_State *L, int index); -void read_server_sound_params(lua_State *L, int index, ServerSoundParams ¶ms); +void read_server_sound_params (lua_State *L, int index, + ServerSoundParams ¶ms); -void push_dig_params(lua_State *L, const DigParams ¶ms); -void push_hit_params(lua_State *L, const HitParams ¶ms); +void push_dig_params (lua_State *L, + const DigParams ¶ms); +void push_hit_params (lua_State *L, + const HitParams ¶ms); -ItemStack read_item(lua_State *L, int index, IItemDefManager *idef); +ItemStack read_item (lua_State *L, int index, IItemDefManager *idef); struct TileAnimationParams read_animation_definition(lua_State *L, int index); -ToolCapabilities read_tool_capabilities(lua_State *L, int table); -void push_tool_capabilities(lua_State *L, const ToolCapabilities &prop); +ToolCapabilities read_tool_capabilities (lua_State *L, int table); +void push_tool_capabilities (lua_State *L, + const ToolCapabilities &prop); -void read_item_definition(lua_State *L, int index, const ItemDefinition &default_def, +void read_item_definition (lua_State *L, int index, const ItemDefinition &default_def, ItemDefinition &def); -void push_item_definition(lua_State *L, const ItemDefinition &i); -void push_item_definition_full(lua_State *L, const ItemDefinition &i); - -void read_object_properties(lua_State *L, int index, ServerActiveObject *sao, - ObjectProperties *prop, IItemDefManager *idef); -void push_object_properties(lua_State *L, ObjectProperties *prop); - -void push_inventory(lua_State *L, Inventory *inventory); - -void push_inventory_list(lua_State *L, Inventory *inv, const char *name); -void read_inventory_list(lua_State *L, int tableindex, Inventory *inv, const char *name, - Server *srv, int forcesize = -1); - -MapNode readnode(lua_State *L, int index, const NodeDefManager *ndef); -void pushnode(lua_State *L, const MapNode &n, const NodeDefManager *ndef); - -void read_groups(lua_State *L, int index, ItemGroupList &result); - -void push_groups(lua_State *L, const ItemGroupList &groups); - -// TODO rename to "read_enum_field" -int getenumfield(lua_State *L, int table, const char *fieldname, const EnumString *spec, - int default_); - -bool getflagsfield(lua_State *L, int table, const char *fieldname, FlagDesc *flagdesc, - u32 *flags, u32 *flagmask); - -bool read_flags(lua_State *L, int index, FlagDesc *flagdesc, u32 *flags, u32 *flagmask); - -void push_flags_string(lua_State *L, FlagDesc *flagdesc, u32 flags, u32 flagmask); - -u32 read_flags_table(lua_State *L, int table, FlagDesc *flagdesc, u32 *flagmask); - -void push_items(lua_State *L, const std::vector<ItemStack> &items); - -std::vector<ItemStack> read_items(lua_State *L, int index, Server *srv); - -void push_soundspec(lua_State *L, const SimpleSoundSpec &spec); - -bool string_to_enum(const EnumString *spec, int &result, const std::string &str); - -bool read_noiseparams(lua_State *L, int index, NoiseParams *np); -void push_noiseparams(lua_State *L, NoiseParams *np); - -void luaentity_get(lua_State *L, u16 id); - -bool push_json_value(lua_State *L, const Json::Value &value, int nullindex); -void read_json_value(lua_State *L, Json::Value &root, int index, u8 recursion = 0); +void push_item_definition (lua_State *L, + const ItemDefinition &i); +void push_item_definition_full (lua_State *L, + const ItemDefinition &i); + +void read_object_properties (lua_State *L, int index, + ServerActiveObject *sao, + ObjectProperties *prop, + IItemDefManager *idef); +void push_object_properties (lua_State *L, + ObjectProperties *prop); + +void push_inventory (lua_State *L, + Inventory *inventory); + +void push_inventory_list (lua_State *L, + Inventory *inv, + const char *name); +void read_inventory_list (lua_State *L, int tableindex, + Inventory *inv, const char *name, + Server *srv, int forcesize=-1); + +MapNode readnode (lua_State *L, int index, + const NodeDefManager *ndef); +void pushnode (lua_State *L, const MapNode &n, + const NodeDefManager *ndef); + + +void read_groups (lua_State *L, int index, + ItemGroupList &result); + +void push_groups (lua_State *L, + const ItemGroupList &groups); + +//TODO rename to "read_enum_field" +int getenumfield (lua_State *L, int table, + const char *fieldname, + const EnumString *spec, + int default_); + +bool getflagsfield (lua_State *L, int table, + const char *fieldname, + FlagDesc *flagdesc, + u32 *flags, u32 *flagmask); + +bool read_flags (lua_State *L, int index, + FlagDesc *flagdesc, + u32 *flags, u32 *flagmask); + +void push_flags_string (lua_State *L, FlagDesc *flagdesc, + u32 flags, u32 flagmask); + +u32 read_flags_table (lua_State *L, int table, + FlagDesc *flagdesc, u32 *flagmask); + +void push_items (lua_State *L, + const std::vector<ItemStack> &items); + +std::vector<ItemStack> read_items (lua_State *L, + int index, + Server* srv); + +void push_soundspec (lua_State *L, + const SimpleSoundSpec &spec); + +bool string_to_enum (const EnumString *spec, + int &result, + const std::string &str); + +bool read_noiseparams (lua_State *L, int index, + NoiseParams *np); +void push_noiseparams (lua_State *L, NoiseParams *np); + +void luaentity_get (lua_State *L,u16 id); + +bool push_json_value (lua_State *L, + const Json::Value &value, + int nullindex); +void read_json_value (lua_State *L, Json::Value &root, + int index, u8 recursion = 0); /*! * Pushes a Lua `pointed_thing` to the given Lua stack. * \param csm If true, a client side pointed thing is pushed * \param hitpoint If true, the exact pointing location is also pushed */ -void push_pointed_thing(lua_State *L, const PointedThing &pointed, bool csm = false, - bool hitpoint = false); +void push_pointed_thing(lua_State *L, const PointedThing &pointed, bool csm = + false, bool hitpoint = false); -void push_objectRef(lua_State *L, const u16 id); +void push_objectRef (lua_State *L, const u16 id); -void read_hud_element(lua_State *L, HudElement *elem); +void read_hud_element (lua_State *L, HudElement *elem); -void push_hud_element(lua_State *L, HudElement *elem); +void push_hud_element (lua_State *L, HudElement *elem); -HudElementStat read_hud_change(lua_State *L, HudElement *elem, void **value); +HudElementStat read_hud_change (lua_State *L, HudElement *elem, void **value); -void push_collision_move_result(lua_State *L, const collisionMoveResult &res); +void push_collision_move_result(lua_State *L, const collisionMoveResult &res); diff --git a/src/script/common/c_converter.cpp b/src/script/common/c_converter.cpp index 349f148d3..eb6ab5331 100644 --- a/src/script/common/c_converter.cpp +++ b/src/script/common/c_converter.cpp @@ -30,27 +30,27 @@ extern "C" { #include "constants.h" #include <set> -#define CHECK_TYPE(index, name, type) \ - { \ - int t = lua_type(L, (index)); \ - if (t != (type)) { \ - throw LuaError(std::string("Invalid ") + (name) + \ - " (expected " + lua_typename(L, (type)) + \ - " got " + lua_typename(L, t) + ")."); \ - } \ - } -#define CHECK_POS_COORD(name) \ - CHECK_TYPE(-1, "position coordinate '" name "'", LUA_TNUMBER) -#define CHECK_FLOAT_RANGE(value, name) \ - if (value < F1000_MIN || value > F1000_MAX) { \ - std::ostringstream error_text; \ - error_text << "Invalid float vector dimension range '" name "' " \ - << "(expected " << F1000_MIN << " < " name " < " << F1000_MAX \ - << " got " << value << ")." << std::endl; \ - throw LuaError(error_text.str()); \ + +#define CHECK_TYPE(index, name, type) { \ + int t = lua_type(L, (index)); \ + if (t != (type)) { \ + throw LuaError(std::string("Invalid ") + (name) + \ + " (expected " + lua_typename(L, (type)) + \ + " got " + lua_typename(L, t) + ")."); \ + } \ } +#define CHECK_POS_COORD(name) CHECK_TYPE(-1, "position coordinate '" name "'", LUA_TNUMBER) +#define CHECK_FLOAT_RANGE(value, name) \ +if (value < F1000_MIN || value > F1000_MAX) { \ + std::ostringstream error_text; \ + error_text << "Invalid float vector dimension range '" name "' " << \ + "(expected " << F1000_MIN << " < " name " < " << F1000_MAX << \ + " got " << value << ")." << std::endl; \ + throw LuaError(error_text.str()); \ +} #define CHECK_POS_TAB(index) CHECK_TYPE(index, "position", LUA_TTABLE) + void push_float_string(lua_State *L, float value) { std::stringstream ss; @@ -360,7 +360,7 @@ bool is_color_table(lua_State *L, int index) aabb3f read_aabb3f(lua_State *L, int index, f32 scale) { aabb3f box; - if (lua_istable(L, index)) { + if(lua_istable(L, index)){ lua_rawgeti(L, index, 1); box.MinEdge.X = lua_tonumber(L, -1) * scale; lua_pop(L, 1); @@ -404,22 +404,22 @@ void push_aabb3f(lua_State *L, aabb3f box) std::vector<aabb3f> read_aabb3f_vector(lua_State *L, int index, f32 scale) { std::vector<aabb3f> boxes; - if (lua_istable(L, index)) { + if(lua_istable(L, index)){ int n = lua_objlen(L, index); // Check if it's a single box or a list of boxes bool possibly_single_box = (n == 6); - for (int i = 1; i <= n && possibly_single_box; i++) { + for(int i = 1; i <= n && possibly_single_box; i++){ lua_rawgeti(L, index, i); - if (!lua_isnumber(L, -1)) + if(!lua_isnumber(L, -1)) possibly_single_box = false; lua_pop(L, 1); } - if (possibly_single_box) { + if(possibly_single_box){ // Read a single box boxes.push_back(read_aabb3f(L, index, scale)); } else { // Read a list of boxes - for (int i = 1; i <= n; i++) { + for(int i = 1; i <= n; i++){ lua_rawgeti(L, index, i); boxes.push_back(read_aabb3f(L, -1, scale)); lua_pop(L, 1); @@ -487,8 +487,8 @@ bool check_field_or_nil(lua_State *L, int index, int type, const char *fieldname // Types mismatch. Log unique line. std::string backtrace = std::string("Invalid field ") + fieldname + - " (expected " + lua_typename(L, type) + " got " + - lua_typename(L, t) + ").\n" + script_get_backtrace(L); + " (expected " + lua_typename(L, type) + + " got " + lua_typename(L, t) + ").\n" + script_get_backtrace(L); u64 hash = murmur_hash_64_ua(backtrace.data(), backtrace.length(), 0xBADBABE); if (warned_msgs.find(hash) == warned_msgs.end()) { @@ -499,7 +499,8 @@ bool check_field_or_nil(lua_State *L, int index, int type, const char *fieldname return false; } -bool getstringfield(lua_State *L, int table, const char *fieldname, std::string &result) +bool getstringfield(lua_State *L, int table, + const char *fieldname, std::string &result) { lua_getfield(L, table, fieldname); bool got = false; @@ -516,7 +517,8 @@ bool getstringfield(lua_State *L, int table, const char *fieldname, std::string return got; } -bool getfloatfield(lua_State *L, int table, const char *fieldname, float &result) +bool getfloatfield(lua_State *L, int table, + const char *fieldname, float &result) { lua_getfield(L, table, fieldname); bool got = false; @@ -529,12 +531,13 @@ bool getfloatfield(lua_State *L, int table, const char *fieldname, float &result return got; } -bool getboolfield(lua_State *L, int table, const char *fieldname, bool &result) +bool getboolfield(lua_State *L, int table, + const char *fieldname, bool &result) { lua_getfield(L, table, fieldname); bool got = false; - if (check_field_or_nil(L, -1, LUA_TBOOLEAN, fieldname)) { + if (check_field_or_nil(L, -1, LUA_TBOOLEAN, fieldname)){ result = lua_toboolean(L, -1); got = true; } @@ -553,82 +556,93 @@ size_t getstringlistfield(lua_State *L, int table, const char *fieldname, return num_strings_read; } -std::string getstringfield_default(lua_State *L, int table, const char *fieldname, - const std::string &default_) +std::string getstringfield_default(lua_State *L, int table, + const char *fieldname, const std::string &default_) { std::string result = default_; getstringfield(L, table, fieldname, result); return result; } -int getintfield_default(lua_State *L, int table, const char *fieldname, int default_) +int getintfield_default(lua_State *L, int table, + const char *fieldname, int default_) { int result = default_; getintfield(L, table, fieldname, result); return result; } -float getfloatfield_default( - lua_State *L, int table, const char *fieldname, float default_) +float getfloatfield_default(lua_State *L, int table, + const char *fieldname, float default_) { float result = default_; getfloatfield(L, table, fieldname, result); return result; } -bool getboolfield_default(lua_State *L, int table, const char *fieldname, bool default_) +bool getboolfield_default(lua_State *L, int table, + const char *fieldname, bool default_) { bool result = default_; getboolfield(L, table, fieldname, result); return result; } -v3s16 getv3s16field_default( - lua_State *L, int table, const char *fieldname, v3s16 default_) +v3s16 getv3s16field_default(lua_State *L, int table, + const char *fieldname, v3s16 default_) { getv3intfield(L, table, fieldname, default_); return default_; } -void setstringfield( - lua_State *L, int table, const char *fieldname, const std::string &value) +void setstringfield(lua_State *L, int table, + const char *fieldname, const std::string &value) { lua_pushlstring(L, value.c_str(), value.length()); - if (table < 0) + if(table < 0) table -= 1; lua_setfield(L, table, fieldname); } -void setintfield(lua_State *L, int table, const char *fieldname, int value) +void setintfield(lua_State *L, int table, + const char *fieldname, int value) { lua_pushinteger(L, value); - if (table < 0) + if(table < 0) table -= 1; lua_setfield(L, table, fieldname); } -void setfloatfield(lua_State *L, int table, const char *fieldname, float value) +void setfloatfield(lua_State *L, int table, + const char *fieldname, float value) { lua_pushnumber(L, value); - if (table < 0) + if(table < 0) table -= 1; lua_setfield(L, table, fieldname); } -void setboolfield(lua_State *L, int table, const char *fieldname, bool value) +void setboolfield(lua_State *L, int table, + const char *fieldname, bool value) { lua_pushboolean(L, value); - if (table < 0) + if(table < 0) table -= 1; lua_setfield(L, table, fieldname); } + //// //// Array table slices //// -size_t write_array_slice_float(lua_State *L, int table_index, float *data, - v3u16 data_size, v3u16 slice_offset, v3u16 slice_size) +size_t write_array_slice_float( + lua_State *L, + int table_index, + float *data, + v3u16 data_size, + v3u16 slice_offset, + v3u16 slice_size) { v3u16 pmin, pmax(data_size); @@ -655,19 +669,25 @@ size_t write_array_slice_float(lua_State *L, int table_index, float *data, u32 elem_index = 1; for (u32 z = pmin.Z; z != pmax.Z; z++) - for (u32 y = pmin.Y; y != pmax.Y; y++) - for (u32 x = pmin.X; x != pmax.X; x++) { - u32 i = z * zstride + y * ystride + x; - lua_pushnumber(L, data[i]); - lua_rawseti(L, table_index, elem_index); - elem_index++; - } + for (u32 y = pmin.Y; y != pmax.Y; y++) + for (u32 x = pmin.X; x != pmax.X; x++) { + u32 i = z * zstride + y * ystride + x; + lua_pushnumber(L, data[i]); + lua_rawseti(L, table_index, elem_index); + elem_index++; + } return elem_index - 1; } -size_t write_array_slice_u16(lua_State *L, int table_index, u16 *data, v3u16 data_size, - v3u16 slice_offset, v3u16 slice_size) + +size_t write_array_slice_u16( + lua_State *L, + int table_index, + u16 *data, + v3u16 data_size, + v3u16 slice_offset, + v3u16 slice_size) { v3u16 pmin, pmax(data_size); @@ -694,13 +714,13 @@ size_t write_array_slice_u16(lua_State *L, int table_index, u16 *data, v3u16 dat u32 elem_index = 1; for (u32 z = pmin.Z; z != pmax.Z; z++) - for (u32 y = pmin.Y; y != pmax.Y; y++) - for (u32 x = pmin.X; x != pmax.X; x++) { - u32 i = z * zstride + y * ystride + x; - lua_pushinteger(L, data[i]); - lua_rawseti(L, table_index, elem_index); - elem_index++; - } + for (u32 y = pmin.Y; y != pmax.Y; y++) + for (u32 x = pmin.X; x != pmax.X; x++) { + u32 i = z * zstride + y * ystride + x; + lua_pushinteger(L, data[i]); + lua_rawseti(L, table_index, elem_index); + elem_index++; + } return elem_index - 1; } diff --git a/src/script/common/c_converter.h b/src/script/common/c_converter.h index 16d21db3b..a4a7079fd 100644 --- a/src/script/common/c_converter.h +++ b/src/script/common/c_converter.h @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + /******************************************************************************/ /******************************************************************************/ /* WARNING!!!! do NOT add this header in any include file or any code file */ @@ -35,21 +36,24 @@ extern "C" { #include <lua.h> } -std::string getstringfield_default(lua_State *L, int table, const char *fieldname, - const std::string &default_); -bool getboolfield_default(lua_State *L, int table, const char *fieldname, bool default_); -float getfloatfield_default( - lua_State *L, int table, const char *fieldname, float default_); -int getintfield_default(lua_State *L, int table, const char *fieldname, int default_); +std::string getstringfield_default(lua_State *L, int table, + const char *fieldname, const std::string &default_); +bool getboolfield_default(lua_State *L, int table, + const char *fieldname, bool default_); +float getfloatfield_default(lua_State *L, int table, + const char *fieldname, float default_); +int getintfield_default(lua_State *L, int table, + const char *fieldname, int default_); bool check_field_or_nil(lua_State *L, int index, int type, const char *fieldname); -template <typename T> -bool getintfield(lua_State *L, int table, const char *fieldname, T &result) +template<typename T> +bool getintfield(lua_State *L, int table, + const char *fieldname, T &result) { lua_getfield(L, table, fieldname); bool got = false; - if (check_field_or_nil(L, -1, LUA_TNUMBER, fieldname)) { + if (check_field_or_nil(L, -1, LUA_TNUMBER, fieldname)){ result = lua_tointeger(L, -1); got = true; } @@ -57,8 +61,9 @@ bool getintfield(lua_State *L, int table, const char *fieldname, T &result) return got; } -template <class T> -bool getv3intfield(lua_State *L, int index, const char *fieldname, T &result) +template<class T> +bool getv3intfield(lua_State *L, int index, + const char *fieldname, T &result) { lua_getfield(L, index, fieldname); bool got = false; @@ -71,54 +76,65 @@ bool getv3intfield(lua_State *L, int index, const char *fieldname, T &result) return got; } -v3s16 getv3s16field_default( - lua_State *L, int table, const char *fieldname, v3s16 default_); -bool getstringfield(lua_State *L, int table, const char *fieldname, std::string &result); -size_t getstringlistfield(lua_State *L, int table, const char *fieldname, - std::vector<std::string> *result); -void read_groups(lua_State *L, int index, std::unordered_map<std::string, int> &result); -bool getboolfield(lua_State *L, int table, const char *fieldname, bool &result); -bool getfloatfield(lua_State *L, int table, const char *fieldname, float &result); - -void setstringfield( - lua_State *L, int table, const char *fieldname, const std::string &value); -void setintfield(lua_State *L, int table, const char *fieldname, int value); -void setfloatfield(lua_State *L, int table, const char *fieldname, float value); -void setboolfield(lua_State *L, int table, const char *fieldname, bool value); - -v3f checkFloatPos(lua_State *L, int index); -v3f check_v3f(lua_State *L, int index); -v3s16 check_v3s16(lua_State *L, int index); - -v3f read_v3f(lua_State *L, int index); -v2f read_v2f(lua_State *L, int index); -v2s16 read_v2s16(lua_State *L, int index); -v2s32 read_v2s32(lua_State *L, int index); -video::SColor read_ARGB8(lua_State *L, int index); -bool read_color(lua_State *L, int index, video::SColor *color); -bool is_color_table(lua_State *L, int index); - -aabb3f read_aabb3f(lua_State *L, int index, f32 scale); -v3s16 read_v3s16(lua_State *L, int index); -std::vector<aabb3f> read_aabb3f_vector(lua_State *L, int index, f32 scale); -size_t read_stringlist(lua_State *L, int index, std::vector<std::string> *result); - -void push_float_string(lua_State *L, float value); -void push_v3_float_string(lua_State *L, v3f p); -void push_v2_float_string(lua_State *L, v2f p); -void push_v2s16(lua_State *L, v2s16 p); -void push_v2s32(lua_State *L, v2s32 p); -void push_v3s16(lua_State *L, v3s16 p); -void push_aabb3f(lua_State *L, aabb3f box); -void push_ARGB8(lua_State *L, video::SColor color); -void pushFloatPos(lua_State *L, v3f p); -void push_v3f(lua_State *L, v3f p); -void push_v2f(lua_State *L, v2f p); - -void warn_if_field_exists(lua_State *L, int table, const char *fieldname, - const std::string &message); +v3s16 getv3s16field_default(lua_State *L, int table, + const char *fieldname, v3s16 default_); +bool getstringfield(lua_State *L, int table, + const char *fieldname, std::string &result); +size_t getstringlistfield(lua_State *L, int table, + const char *fieldname, + std::vector<std::string> *result); +void read_groups(lua_State *L, int index, + std::unordered_map<std::string, int> &result); +bool getboolfield(lua_State *L, int table, + const char *fieldname, bool &result); +bool getfloatfield(lua_State *L, int table, + const char *fieldname, float &result); + +void setstringfield(lua_State *L, int table, + const char *fieldname, const std::string &value); +void setintfield(lua_State *L, int table, + const char *fieldname, int value); +void setfloatfield(lua_State *L, int table, + const char *fieldname, float value); +void setboolfield(lua_State *L, int table, + const char *fieldname, bool value); + +v3f checkFloatPos (lua_State *L, int index); +v3f check_v3f (lua_State *L, int index); +v3s16 check_v3s16 (lua_State *L, int index); + +v3f read_v3f (lua_State *L, int index); +v2f read_v2f (lua_State *L, int index); +v2s16 read_v2s16 (lua_State *L, int index); +v2s32 read_v2s32 (lua_State *L, int index); +video::SColor read_ARGB8 (lua_State *L, int index); +bool read_color (lua_State *L, int index, + video::SColor *color); +bool is_color_table (lua_State *L, int index); + +aabb3f read_aabb3f (lua_State *L, int index, f32 scale); +v3s16 read_v3s16 (lua_State *L, int index); +std::vector<aabb3f> read_aabb3f_vector (lua_State *L, int index, f32 scale); +size_t read_stringlist (lua_State *L, int index, + std::vector<std::string> *result); + +void push_float_string (lua_State *L, float value); +void push_v3_float_string(lua_State *L, v3f p); +void push_v2_float_string(lua_State *L, v2f p); +void push_v2s16 (lua_State *L, v2s16 p); +void push_v2s32 (lua_State *L, v2s32 p); +void push_v3s16 (lua_State *L, v3s16 p); +void push_aabb3f (lua_State *L, aabb3f box); +void push_ARGB8 (lua_State *L, video::SColor color); +void pushFloatPos (lua_State *L, v3f p); +void push_v3f (lua_State *L, v3f p); +void push_v2f (lua_State *L, v2f p); + +void warn_if_field_exists(lua_State *L, int table, + const char *fieldname, + const std::string &message); size_t write_array_slice_float(lua_State *L, int table_index, float *data, - v3u16 data_size, v3u16 slice_offset, v3u16 slice_size); -size_t write_array_slice_u16(lua_State *L, int table_index, u16 *data, v3u16 data_size, - v3u16 slice_offset, v3u16 slice_size); + v3u16 data_size, v3u16 slice_offset, v3u16 slice_size); +size_t write_array_slice_u16(lua_State *L, int table_index, u16 *data, + v3u16 data_size, v3u16 slice_offset, v3u16 slice_size); diff --git a/src/script/common/c_internal.cpp b/src/script/common/c_internal.cpp index 19a874f63..6df1f8b7b 100644 --- a/src/script/common/c_internal.cpp +++ b/src/script/common/c_internal.cpp @@ -35,13 +35,13 @@ std::string script_get_backtrace(lua_State *L) int script_exception_wrapper(lua_State *L, lua_CFunction f) { try { - return f(L); // Call wrapped function and return result. - } catch (const char *s) { // Catch and convert exceptions. + return f(L); // Call wrapped function and return result. + } catch (const char *s) { // Catch and convert exceptions. lua_pushstring(L, s); } catch (std::exception &e) { lua_pushstring(L, e.what()); } - return lua_error(L); // Rethrow as a Lua error. + return lua_error(L); // Rethrow as a Lua error. } /* @@ -85,15 +85,15 @@ void script_error(lua_State *L, int pcall_result, const char *mod, const char *f err_descr = "<no description>"; char buf[256]; - porting::mt_snprintf(buf, sizeof(buf), - "%s error from mod '%s' in callback %s(): ", err_type, mod, fxn); + porting::mt_snprintf(buf, sizeof(buf), "%s error from mod '%s' in callback %s(): ", + err_type, mod, fxn); std::string err_msg(buf); err_msg += err_descr; if (pcall_result == LUA_ERRMEM) { - err_msg += "\nCurrent Lua memory usage: " + - itos(lua_gc(L, LUA_GCCOUNT, 0) >> 10) + " MB"; + err_msg += "\nCurrent Lua memory usage: " + + itos(lua_gc(L, LUA_GCCOUNT, 0) >> 10) + " MB"; } throw LuaError(err_msg); @@ -105,8 +105,8 @@ void script_error(lua_State *L, int pcall_result, const char *mod, const char *f // - runs the callbacks // - replaces the table and arguments with the return value, // computed depending on mode -void script_run_callbacks_f( - lua_State *L, int nargs, RunCallbacksMode mode, const char *fxn) +void script_run_callbacks_f(lua_State *L, int nargs, + RunCallbacksMode mode, const char *fxn) { FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments"); @@ -122,7 +122,7 @@ void script_run_callbacks_f( lua_insert(L, error_handler + 1); // Insert mode after table - lua_pushnumber(L, (int)mode); + lua_pushnumber(L, (int) mode); lua_insert(L, error_handler + 3); // Stack now looks like this: @@ -135,8 +135,8 @@ void script_run_callbacks_f( lua_remove(L, error_handler); } -static void script_log(lua_State *L, const std::string &message, std::ostream &log_to, - bool do_error, int stack_depth) +static void script_log(lua_State *L, const std::string &message, + std::ostream &log_to, bool do_error, int stack_depth) { lua_Debug ar; diff --git a/src/script/common/c_internal.h b/src/script/common/c_internal.h index 677194453..442546332 100644 --- a/src/script/common/c_internal.h +++ b/src/script/common/c_internal.h @@ -34,6 +34,7 @@ extern "C" { #include "config.h" #include "common/c_types.h" + /* Define our custom indices into the Lua registry table. @@ -44,15 +45,15 @@ extern "C" { so we can use numeric indices freely. */ #ifdef LUA_RIDX_LAST -#define CUSTOM_RIDX_BASE ((LUA_RIDX_LAST) + 1) +#define CUSTOM_RIDX_BASE ((LUA_RIDX_LAST)+1) #else #define CUSTOM_RIDX_BASE 1 #endif -#define CUSTOM_RIDX_SCRIPTAPI (CUSTOM_RIDX_BASE) -#define CUSTOM_RIDX_GLOBALS_BACKUP (CUSTOM_RIDX_BASE + 1) -#define CUSTOM_RIDX_CURRENT_MOD_NAME (CUSTOM_RIDX_BASE + 2) -#define CUSTOM_RIDX_BACKTRACE (CUSTOM_RIDX_BASE + 3) +#define CUSTOM_RIDX_SCRIPTAPI (CUSTOM_RIDX_BASE) +#define CUSTOM_RIDX_GLOBALS_BACKUP (CUSTOM_RIDX_BASE + 1) +#define CUSTOM_RIDX_CURRENT_MOD_NAME (CUSTOM_RIDX_BASE + 2) +#define CUSTOM_RIDX_BACKTRACE (CUSTOM_RIDX_BASE + 3) // Determine if CUSTOM_RIDX_SCRIPTAPI will hold a light or full userdata #if defined(__aarch64__) && USE_LUAJIT @@ -64,18 +65,17 @@ extern "C" { #endif // Pushes the error handler onto the stack and returns its index -#define PUSH_ERROR_HANDLER(L) \ +#define PUSH_ERROR_HANDLER(L) \ (lua_rawgeti((L), LUA_REGISTRYINDEX, CUSTOM_RIDX_BACKTRACE), lua_gettop((L))) -#define PCALL_RESL(L, RES) \ - { \ - int result_ = (RES); \ - if (result_ != 0) { \ - script_error((L), result_, NULL, __FUNCTION__); \ - } \ - } +#define PCALL_RESL(L, RES) { \ + int result_ = (RES); \ + if (result_ != 0) { \ + script_error((L), result_, NULL, __FUNCTION__); \ + } \ +} -#define script_run_callbacks(L, nargs, mode) \ +#define script_run_callbacks(L, nargs, mode) \ script_run_callbacks_f((L), (nargs), (mode), __FUNCTION__) // What script_run_callbacks does with the return values of callbacks. @@ -111,7 +111,8 @@ enum RunCallbacksMode std::string script_get_backtrace(lua_State *L); int script_exception_wrapper(lua_State *L, lua_CFunction f); void script_error(lua_State *L, int pcall_result, const char *mod, const char *fxn); -void script_run_callbacks_f( - lua_State *L, int nargs, RunCallbacksMode mode, const char *fxn); +void script_run_callbacks_f(lua_State *L, int nargs, + RunCallbacksMode mode, const char *fxn); -void log_deprecated(lua_State *L, const std::string &message, int stack_depth = 1); +void log_deprecated(lua_State *L, const std::string &message, + int stack_depth=1); diff --git a/src/script/common/c_types.cpp b/src/script/common/c_types.cpp index 93bb5bd70..e832ff2ab 100644 --- a/src/script/common/c_types.cpp +++ b/src/script/common/c_types.cpp @@ -23,10 +23,12 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "common/c_internal.h" #include "itemdef.h" -struct EnumString es_ItemType[] = { + +struct EnumString es_ItemType[] = + { {ITEM_NONE, "none"}, {ITEM_NODE, "node"}, {ITEM_CRAFT, "craft"}, {ITEM_TOOL, "tool"}, {0, NULL}, -}; + }; diff --git a/src/script/common/c_types.h b/src/script/common/c_types.h index 860bfaaa8..86bfb0b6b 100644 --- a/src/script/common/c_types.h +++ b/src/script/common/c_types.h @@ -38,9 +38,10 @@ class StackUnroller private: lua_State *m_lua; int m_original_top; - public: - StackUnroller(lua_State *L) : m_lua(L), m_original_top(-1) + StackUnroller(lua_State *L): + m_lua(L), + m_original_top(-1) { m_original_top = lua_gettop(m_lua); // store stack height } @@ -56,4 +57,5 @@ public: LuaError(const std::string &s) : ModError(s) {} }; + extern EnumString es_ItemType[]; diff --git a/src/script/cpp_api/s_async.cpp b/src/script/cpp_api/s_async.cpp index d0e520ae9..5f1f9297e 100644 --- a/src/script/cpp_api/s_async.cpp +++ b/src/script/cpp_api/s_async.cpp @@ -42,6 +42,7 @@ AsyncEngine::~AsyncEngine() workerThread->stop(); } + // Wake up all threads for (std::vector<AsyncWorkerThread *>::iterator it = workerThreads.begin(); it != workerThreads.end(); ++it) { @@ -76,16 +77,16 @@ void AsyncEngine::initialize(unsigned int numEngines) initDone = true; for (unsigned int i = 0; i < numEngines; i++) { - AsyncWorkerThread *toAdd = new AsyncWorkerThread( - this, std::string("AsyncWorker-") + itos(i)); + AsyncWorkerThread *toAdd = new AsyncWorkerThread(this, + std::string("AsyncWorker-") + itos(i)); workerThreads.push_back(toAdd); toAdd->start(); } } /******************************************************************************/ -unsigned int AsyncEngine::queueAsyncJob( - const std::string &func, const std::string ¶ms) +unsigned int AsyncEngine::queueAsyncJob(const std::string &func, + const std::string ¶ms) { jobQueueMutex.lock(); LuaJobInfo toAdd; @@ -157,8 +158,7 @@ void AsyncEngine::step(lua_State *L) } /******************************************************************************/ -void AsyncEngine::pushFinishedJobs(lua_State *L) -{ +void AsyncEngine::pushFinishedJobs(lua_State* L) { // Result Table MutexAutoLock l(resultQueueMutex); @@ -170,7 +170,7 @@ void AsyncEngine::pushFinishedJobs(lua_State *L) LuaJobInfo jobDone = resultQueue.front(); resultQueue.pop_front(); - lua_createtable(L, 0, 2); // Pre-allocate space for two map fields + lua_createtable(L, 0, 2); // Pre-allocate space for two map fields int top_lvl2 = lua_gettop(L); lua_pushstring(L, "jobid"); @@ -179,7 +179,7 @@ void AsyncEngine::pushFinishedJobs(lua_State *L) lua_pushstring(L, "retval"); lua_pushlstring(L, jobDone.serializedResult.data(), - jobDone.serializedResult.size()); + jobDone.serializedResult.size()); lua_settable(L, top_lvl2); lua_rawseti(L, top, index++); @@ -187,7 +187,7 @@ void AsyncEngine::pushFinishedJobs(lua_State *L) } /******************************************************************************/ -void AsyncEngine::prepareEnvironment(lua_State *L, int top) +void AsyncEngine::prepareEnvironment(lua_State* L, int top) { for (StateInitializer &stateInitializer : stateInitializers) { stateInitializer(L, top); @@ -195,10 +195,11 @@ void AsyncEngine::prepareEnvironment(lua_State *L, int top) } /******************************************************************************/ -AsyncWorkerThread::AsyncWorkerThread( - AsyncEngine *jobDispatcher, const std::string &name) : - Thread(name), - ScriptApiBase(ScriptingType::Async), jobDispatcher(jobDispatcher) +AsyncWorkerThread::AsyncWorkerThread(AsyncEngine* jobDispatcher, + const std::string &name) : + Thread(name), + ScriptApiBase(ScriptingType::Async), + jobDispatcher(jobDispatcher) { lua_State *L = getStack(); @@ -220,7 +221,7 @@ AsyncWorkerThread::~AsyncWorkerThread() } /******************************************************************************/ -void *AsyncWorkerThread::run() +void* AsyncWorkerThread::run() { lua_State *L = getStack(); @@ -228,8 +229,8 @@ void *AsyncWorkerThread::run() try { loadScript(script); } catch (const ModError &e) { - errorstream << "Execution of async base environment failed: " << e.what() - << std::endl; + errorstream << "Execution of async base environment failed: " + << e.what() << std::endl; FATAL_ERROR("Execution of async base environment failed"); } @@ -257,9 +258,11 @@ void *AsyncWorkerThread::run() luaL_checktype(L, -1, LUA_TFUNCTION); // Call it - lua_pushlstring(L, toProcess.serializedFunction.data(), + lua_pushlstring(L, + toProcess.serializedFunction.data(), toProcess.serializedFunction.size()); - lua_pushlstring(L, toProcess.serializedParams.data(), + lua_pushlstring(L, + toProcess.serializedParams.data(), toProcess.serializedParams.size()); int result = lua_pcall(L, 2, 1, error_handler); @@ -273,13 +276,14 @@ void *AsyncWorkerThread::run() toProcess.serializedResult = std::string(retval, length); } - lua_pop(L, 1); // Pop retval + lua_pop(L, 1); // Pop retval // Put job result jobDispatcher->putJobResult(toProcess); } - lua_pop(L, 2); // Pop core and error handler + lua_pop(L, 2); // Pop core and error handler return 0; } + diff --git a/src/script/cpp_api/s_async.h b/src/script/cpp_api/s_async.h index 1dc4145ba..b1f4bf45f 100644 --- a/src/script/cpp_api/s_async.h +++ b/src/script/cpp_api/s_async.h @@ -31,6 +31,7 @@ with this program; if not, write to the Free Software Foundation, Inc., // Forward declarations class AsyncEngine; + // Declarations // Data required to queue a job @@ -51,10 +52,9 @@ struct LuaJobInfo }; // Asynchronous working environment -class AsyncWorkerThread : public Thread, public ScriptApiBase -{ +class AsyncWorkerThread : public Thread, public ScriptApiBase { public: - AsyncWorkerThread(AsyncEngine *jobDispatcher, const std::string &name); + AsyncWorkerThread(AsyncEngine* jobDispatcher, const std::string &name); virtual ~AsyncWorkerThread(); void *run(); @@ -64,11 +64,9 @@ private: }; // Asynchornous thread and job management -class AsyncEngine -{ +class AsyncEngine { friend class AsyncWorkerThread; typedef void (*StateInitializer)(lua_State *L, int top); - public: AsyncEngine() = default; ~AsyncEngine(); @@ -127,7 +125,7 @@ protected: * @param L Lua stack to initialize * @param top Stack position */ - void prepareEnvironment(lua_State *L, int top); + void prepareEnvironment(lua_State* L, int top); private: // Variable locking the engine against further modification @@ -151,7 +149,7 @@ private: std::deque<LuaJobInfo> resultQueue; // List of current worker threads - std::vector<AsyncWorkerThread *> workerThreads; + std::vector<AsyncWorkerThread*> workerThreads; // Counter semaphore for job dispatching Semaphore jobQueueCounter; diff --git a/src/script/cpp_api/s_base.cpp b/src/script/cpp_api/s_base.cpp index 72774f6ca..1d62d8b65 100644 --- a/src/script/cpp_api/s_base.cpp +++ b/src/script/cpp_api/s_base.cpp @@ -32,10 +32,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/client.h" #endif + extern "C" { #include "lualib.h" #if USE_LUAJIT -#include "luajit.h" + #include "luajit.h" #endif } @@ -44,13 +45,14 @@ extern "C" { #include "script/common/c_content.h" #include <sstream> + class ModNameStorer { private: lua_State *L; - public: - ModNameStorer(lua_State *L_, const std::string &mod_name) : L(L_) + ModNameStorer(lua_State *L_, const std::string &mod_name): + L(L_) { // Store current mod name in registry lua_pushstring(L, mod_name.c_str()); @@ -64,11 +66,13 @@ public: } }; + /* ScriptApiBase */ -ScriptApiBase::ScriptApiBase(ScriptingType type) : m_type(type) +ScriptApiBase::ScriptApiBase(ScriptingType type): + m_type(type) { #ifdef SCRIPTAPI_LOCK_DEBUG m_lock_recursion_count = 0; @@ -82,7 +86,7 @@ ScriptApiBase::ScriptApiBase(ScriptingType type) : m_type(type) /*if (m_type == ScriptingType::Client) clientOpenLibs(m_luastack); else*/ - luaL_openlibs(m_luastack); + luaL_openlibs(m_luastack); // Make the ScriptApiBase* accessible to ModApiBase #if INDIRECT_SCRIPTAPI_RIDX @@ -101,7 +105,7 @@ ScriptApiBase::ScriptApiBase(ScriptingType type) : m_type(type) // If we are using LuaJIT add a C++ wrapper function to catch // exceptions thrown in Lua -> C++ calls #if USE_LUAJIT - lua_pushlightuserdata(m_luastack, (void *)script_exception_wrapper); + lua_pushlightuserdata(m_luastack, (void*) script_exception_wrapper); luaJIT_setmode(m_luastack, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON); lua_pop(m_luastack, 1); #endif @@ -132,7 +136,7 @@ int ScriptApiBase::luaPanic(lua_State *L) { std::ostringstream oss; oss << "LUA PANIC: unprotected error in call to Lua API (" - << readParam<std::string>(L, -1) << ")"; + << readParam<std::string>(L, -1) << ")"; FATAL_ERROR(oss.str().c_str()); // NOTREACHED return 0; @@ -141,25 +145,26 @@ int ScriptApiBase::luaPanic(lua_State *L) void ScriptApiBase::clientOpenLibs(lua_State *L) { static const std::vector<std::pair<std::string, lua_CFunction>> m_libs = { - {"", luaopen_base}, - {LUA_TABLIBNAME, luaopen_table}, - {LUA_OSLIBNAME, luaopen_os}, - {LUA_STRLIBNAME, luaopen_string}, - {LUA_MATHLIBNAME, luaopen_math}, - {LUA_DBLIBNAME, luaopen_debug}, + { "", luaopen_base }, + { LUA_TABLIBNAME, luaopen_table }, + { LUA_OSLIBNAME, luaopen_os }, + { LUA_STRLIBNAME, luaopen_string }, + { LUA_MATHLIBNAME, luaopen_math }, + { LUA_DBLIBNAME, luaopen_debug }, #if USE_LUAJIT - {LUA_JITLIBNAME, luaopen_jit}, + { LUA_JITLIBNAME, luaopen_jit }, #endif }; for (const std::pair<std::string, lua_CFunction> &lib : m_libs) { - lua_pushcfunction(L, lib.second); - lua_pushstring(L, lib.first.c_str()); - lua_call(L, 1, 0); + lua_pushcfunction(L, lib.second); + lua_pushstring(L, lib.first.c_str()); + lua_call(L, 1, 0); } } -void ScriptApiBase::loadMod(const std::string &script_path, const std::string &mod_name) +void ScriptApiBase::loadMod(const std::string &script_path, + const std::string &mod_name) { ModNameStorer mod_name_storer(getStack(), mod_name); @@ -186,8 +191,8 @@ void ScriptApiBase::loadScript(const std::string &script_path) if (!error_msg) error_msg = "(error object is not a string)"; lua_pop(L, 2); // Pop error message and error handler - throw ModError("Failed to load and run script from " + script_path + - ":\n" + error_msg); + throw ModError("Failed to load and run script from " + + script_path + ":\n" + error_msg); } lua_pop(L, 1); // Pop error handler } @@ -220,8 +225,8 @@ void ScriptApiBase::loadModFromMemory(const std::string &mod_name) if (!error_msg) error_msg = "(error object is not a string)"; lua_pop(L, 2); // Pop error message and error handler - throw ModError("Failed to load and run mod \"" + mod_name + "\":\n" + - error_msg); + throw ModError("Failed to load and run mod \"" + + mod_name + "\":\n" + error_msg); } lua_pop(L, 1); // Pop error handler } @@ -235,13 +240,14 @@ void ScriptApiBase::loadModFromMemory(const std::string &mod_name) // computed depending on mode // This function must only be called with scriptlock held (i.e. inside of a // code block with SCRIPTAPI_PRECHECKHEADER declared) -void ScriptApiBase::runCallbacksRaw(int nargs, RunCallbacksMode mode, const char *fxn) +void ScriptApiBase::runCallbacksRaw(int nargs, + RunCallbacksMode mode, const char *fxn) { #ifndef SERVER // Hard fail for bad guarded callbacks // Only run callbacks when the scripting enviroment is loaded - FATAL_ERROR_IF(m_type == ScriptingType::Client && !getClient()->modsLoaded(), - fxn); + FATAL_ERROR_IF(m_type == ScriptingType::Client && + !getClient()->modsLoaded(), fxn); #endif #ifdef SCRIPTAPI_LOCK_DEBUG @@ -294,25 +300,24 @@ void ScriptApiBase::scriptError(int result, const char *fxn) void ScriptApiBase::stackDump(std::ostream &o) { int top = lua_gettop(m_luastack); - for (int i = 1; i <= top; i++) { /* repeat for each level */ + for (int i = 1; i <= top; i++) { /* repeat for each level */ int t = lua_type(m_luastack, i); switch (t) { - case LUA_TSTRING: /* strings */ - o << "\"" << readParam<std::string>(m_luastack, i) << "\""; - break; - case LUA_TBOOLEAN: /* booleans */ - o << (readParam<bool>(m_luastack, i) ? "true" : "false"); - break; - case LUA_TNUMBER: /* numbers */ { - char buf[10]; - porting::mt_snprintf(buf, sizeof(buf), "%lf", - lua_tonumber(m_luastack, i)); - o << buf; - break; - } - default: /* other values */ - o << lua_typename(m_luastack, t); - break; + case LUA_TSTRING: /* strings */ + o << "\"" << readParam<std::string>(m_luastack, i) << "\""; + break; + case LUA_TBOOLEAN: /* booleans */ + o << (readParam<bool>(m_luastack, i) ? "true" : "false"); + break; + case LUA_TNUMBER: /* numbers */ { + char buf[10]; + porting::mt_snprintf(buf, sizeof(buf), "%lf", lua_tonumber(m_luastack, i)); + o << buf; + break; + } + default: /* other values */ + o << lua_typename(m_luastack, t); + break; } o << " "; } @@ -329,10 +334,9 @@ void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn) #ifdef SCRIPTAPI_DEBUG lua_State *L = getStack(); - m_last_run_mod = lua_istable(L, index) ? getstringfield_default(L, index, - "mod_origin", "") - : ""; - // printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str()); + m_last_run_mod = lua_istable(L, index) ? + getstringfield_default(L, index, "mod_origin", "") : ""; + //printf(">>>> running %s for mod: %s\n", fxn, m_last_run_mod.c_str()); #endif } @@ -353,7 +357,7 @@ void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn) void ScriptApiBase::addObjectReference(ServerActiveObject *cobj) { SCRIPTAPI_PRECHECKHEADER - // infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl; + //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl; // Create object on stack ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack @@ -367,14 +371,14 @@ void ScriptApiBase::addObjectReference(ServerActiveObject *cobj) // object_refs[id] = object lua_pushnumber(L, cobj->getId()); // Push id - lua_pushvalue(L, object); // Copy object to top of stack + lua_pushvalue(L, object); // Copy object to top of stack lua_settable(L, objectstable); } void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj) { SCRIPTAPI_PRECHECKHEADER - // infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl; + //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl; // Get core.object_refs table lua_getglobal(L, "core"); @@ -396,7 +400,8 @@ void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj) } // Creates a new anonymous reference if cobj=NULL or id=0 -void ScriptApiBase::objectrefGetOrCreate(lua_State *L, ServerActiveObject *cobj) +void ScriptApiBase::objectrefGetOrCreate(lua_State *L, + ServerActiveObject *cobj) { if (cobj == NULL || cobj->getId() == 0) { ObjectRef::create(L, cobj); @@ -404,13 +409,12 @@ void ScriptApiBase::objectrefGetOrCreate(lua_State *L, ServerActiveObject *cobj) push_objectRef(L, cobj->getId()); if (cobj->isGone()) warningstream << "ScriptApiBase::objectrefGetOrCreate(): " - << "Pushing ObjectRef to removed/deactivated object" - << ", this is probably a bug." << std::endl; + << "Pushing ObjectRef to removed/deactivated object" + << ", this is probably a bug." << std::endl; } } -void ScriptApiBase::pushPlayerHPChangeReason( - lua_State *L, const PlayerHPChangeReason &reason) +void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason) { if (reason.hasLuaReference()) lua_rawgeti(L, LUA_REGISTRYINDEX, reason.lua_reference); @@ -438,12 +442,12 @@ void ScriptApiBase::pushPlayerHPChangeReason( } } -Server *ScriptApiBase::getServer() +Server* ScriptApiBase::getServer() { return dynamic_cast<Server *>(m_gamedef); } #ifndef SERVER -Client *ScriptApiBase::getClient() +Client* ScriptApiBase::getClient() { return dynamic_cast<Client *>(m_gamedef); } diff --git a/src/script/cpp_api/s_base.h b/src/script/cpp_api/s_base.h index d2081ad5c..36331ad37 100644 --- a/src/script/cpp_api/s_base.h +++ b/src/script/cpp_api/s_base.h @@ -45,20 +45,20 @@ extern "C" { // use that name to bypass security! #define BUILTIN_MOD_NAME "*builtin*" -#define PCALL_RES(RES) \ - { \ - int result_ = (RES); \ - if (result_ != 0) { \ - scriptError(result_, __FUNCTION__); \ - } \ - } +#define PCALL_RES(RES) { \ + int result_ = (RES); \ + if (result_ != 0) { \ + scriptError(result_, __FUNCTION__); \ + } \ +} -#define runCallbacks(nargs, mode) runCallbacksRaw((nargs), (mode), __FUNCTION__) +#define runCallbacks(nargs, mode) \ + runCallbacksRaw((nargs), (mode), __FUNCTION__) -#define setOriginFromTable(index) setOriginFromTableRaw(index, __FUNCTION__) +#define setOriginFromTable(index) \ + setOriginFromTableRaw(index, __FUNCTION__) -enum class ScriptingType : u8 -{ +enum class ScriptingType: u8 { Async, Client, MainMenu, @@ -76,13 +76,14 @@ class GUIEngine; class ServerActiveObject; struct PlayerHPChangeReason; -class ScriptApiBase : protected LuaHelper -{ +class ScriptApiBase : protected LuaHelper { public: ScriptApiBase(ScriptingType type); - // fake constructor to allow script API classes (e.g ScriptApiEnv) to virtually - // inherit from this one. - ScriptApiBase() { FATAL_ERROR("ScriptApiBase created without ScriptingType!"); } + // fake constructor to allow script API classes (e.g ScriptApiEnv) to virtually inherit from this one. + ScriptApiBase() + { + FATAL_ERROR("ScriptApiBase created without ScriptingType!"); + } virtual ~ScriptApiBase(); DISABLE_CLASS_COPY(ScriptApiBase); @@ -94,17 +95,18 @@ public: void loadModFromMemory(const std::string &mod_name); #endif - void runCallbacksRaw(int nargs, RunCallbacksMode mode, const char *fxn); + void runCallbacksRaw(int nargs, + RunCallbacksMode mode, const char *fxn); /* object */ void addObjectReference(ServerActiveObject *cobj); void removeObjectReference(ServerActiveObject *cobj); IGameDef *getGameDef() { return m_gamedef; } - Server *getServer(); + Server* getServer(); ScriptingType getType() { return m_type; } #ifndef SERVER - Client *getClient(); + Client* getClient(); Game *getGame() { return m_game; } #endif @@ -124,49 +126,50 @@ protected: friend class ModApiEnvMod; friend class LuaVoxelManip; - lua_State *getStack() { return m_luastack; } + lua_State* getStack() + { return m_luastack; } void realityCheck(); void scriptError(int result, const char *fxn); void stackDump(std::ostream &o); - void setGameDef(IGameDef *gamedef) { m_gamedef = gamedef; } + void setGameDef(IGameDef* gamedef) { m_gamedef = gamedef; } #ifndef SERVER void setGame(Game *game) { m_game = game; } #endif - Environment *getEnv() { return m_environment; } - void setEnv(Environment *env) { m_environment = env; } + Environment* getEnv() { return m_environment; } + void setEnv(Environment* env) { m_environment = env; } #ifndef SERVER - GUIEngine *getGuiEngine() { return m_guiengine; } - void setGuiEngine(GUIEngine *guiengine) { m_guiengine = guiengine; } + GUIEngine* getGuiEngine() { return m_guiengine; } + void setGuiEngine(GUIEngine* guiengine) { m_guiengine = guiengine; } #endif void objectrefGetOrCreate(lua_State *L, ServerActiveObject *cobj); - void pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason); + void pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason& reason); std::recursive_mutex m_luastackmutex; - std::string m_last_run_mod; - bool m_secure = false; + std::string m_last_run_mod; + bool m_secure = false; #ifdef SCRIPTAPI_LOCK_DEBUG - int m_lock_recursion_count{}; + int m_lock_recursion_count{}; std::thread::id m_owning_thread; #endif private: static int luaPanic(lua_State *L); - lua_State *m_luastack = nullptr; + lua_State *m_luastack = nullptr; - IGameDef *m_gamedef = nullptr; + IGameDef *m_gamedef = nullptr; #ifndef SERVER - Game *m_game = nullptr; + Game *m_game = nullptr; #endif - Environment *m_environment = nullptr; + Environment *m_environment = nullptr; #ifndef SERVER - GUIEngine *m_guiengine = nullptr; + GUIEngine *m_guiengine = nullptr; #endif - ScriptingType m_type; + ScriptingType m_type; }; diff --git a/src/script/cpp_api/s_client.cpp b/src/script/cpp_api/s_client.cpp index e6c9eea1a..dd9019d4d 100644 --- a/src/script/cpp_api/s_client.cpp +++ b/src/script/cpp_api/s_client.cpp @@ -120,13 +120,13 @@ void ScriptApiClient::environment_step(float dtime) try { runCallbacks(1, RUN_CALLBACKS_MODE_FIRST); } catch (LuaError &e) { - getClient()->setFatalError(std::string("Client environment_step: ") + - e.what() + "\n" + script_get_backtrace(L)); + getClient()->setFatalError(std::string("Client environment_step: ") + e.what() + "\n" + + script_get_backtrace(L)); } } -void ScriptApiClient::on_formspec_input( - const std::string &formname, const StringMap &fields) +void ScriptApiClient::on_formspec_input(const std::string &formname, + const StringMap &fields) { SCRIPTAPI_PRECHECKHEADER @@ -187,8 +187,7 @@ bool ScriptApiClient::on_punchnode(v3s16 p, MapNode node) return readParam<bool>(L, -1); } -bool ScriptApiClient::on_placenode( - const PointedThing &pointed, const ItemDefinition &item) +bool ScriptApiClient::on_placenode(const PointedThing &pointed, const ItemDefinition &item) { SCRIPTAPI_PRECHECKHEADER @@ -238,11 +237,11 @@ bool ScriptApiClient::on_inventory_open(Inventory *inventory) void ScriptApiClient::open_enderchest() { SCRIPTAPI_PRECHECKHEADER - + PUSH_ERROR_HANDLER(L); int error_handler = lua_gettop(L) - 1; lua_insert(L, error_handler); - + lua_getglobal(L, "core"); lua_getfield(L, -1, "open_enderchest"); if (lua_isfunction(L, -1)) diff --git a/src/script/cpp_api/s_entity.cpp b/src/script/cpp_api/s_entity.cpp index baf455e1b..ea9320051 100644 --- a/src/script/cpp_api/s_entity.cpp +++ b/src/script/cpp_api/s_entity.cpp @@ -29,8 +29,8 @@ bool ScriptApiEntity::luaentity_Add(u16 id, const char *name) { SCRIPTAPI_PRECHECKHEADER - verbosestream << "scriptapi_luaentity_add: id=" << id << " name=\"" << name - << "\"" << std::endl; + verbosestream<<"scriptapi_luaentity_add: id="<<id<<" name=\"" + <<name<<"\""<<std::endl; // Get core.registered_entities[name] lua_getglobal(L, "core"); @@ -39,14 +39,13 @@ bool ScriptApiEntity::luaentity_Add(u16 id, const char *name) lua_pushstring(L, name); lua_gettable(L, -2); // Should be a table, which we will use as a prototype - // luaL_checktype(L, -1, LUA_TTABLE); - if (lua_type(L, -1) != LUA_TTABLE) { - errorstream << "LuaEntity name \"" << name << "\" not defined" - << std::endl; + //luaL_checktype(L, -1, LUA_TTABLE); + if (lua_type(L, -1) != LUA_TTABLE){ + errorstream<<"LuaEntity name \""<<name<<"\" not defined"<<std::endl; return false; } int prototype_table = lua_gettop(L); - // dump2(L, "prototype_table"); + //dump2(L, "prototype_table"); // Create entity object lua_newtable(L); @@ -68,15 +67,15 @@ bool ScriptApiEntity::luaentity_Add(u16 id, const char *name) lua_getglobal(L, "core"); lua_getfield(L, -1, "luaentities"); luaL_checktype(L, -1, LUA_TTABLE); - lua_pushnumber(L, id); // Push id + lua_pushnumber(L, id); // Push id lua_pushvalue(L, object); // Copy object to top of stack lua_settable(L, -3); return true; } -void ScriptApiEntity::luaentity_Activate( - u16 id, const std::string &staticdata, u32 dtime_s) +void ScriptApiEntity::luaentity_Activate(u16 id, + const std::string &staticdata, u32 dtime_s) { SCRIPTAPI_PRECHECKHEADER @@ -128,7 +127,7 @@ std::string ScriptApiEntity::luaentity_GetStaticdata(u16 id) { SCRIPTAPI_PRECHECKHEADER - // infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl; + //infostream<<"scriptapi_luaentity_get_staticdata: id="<<id<<std::endl; int error_handler = PUSH_ERROR_HANDLER(L); @@ -157,12 +156,12 @@ std::string ScriptApiEntity::luaentity_GetStaticdata(u16 id) return std::string(s, len); } -void ScriptApiEntity::luaentity_GetProperties( - u16 id, ServerActiveObject *self, ObjectProperties *prop) +void ScriptApiEntity::luaentity_GetProperties(u16 id, + ServerActiveObject *self, ObjectProperties *prop) { SCRIPTAPI_PRECHECKHEADER - // infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl; + //infostream<<"scriptapi_luaentity_get_properties: id="<<id<<std::endl; // Get core.luaentities[id] luaentity_get(L, id); @@ -179,8 +178,8 @@ void ScriptApiEntity::luaentity_GetProperties( lua_pop(L, 1); } -void ScriptApiEntity::luaentity_Step( - u16 id, float dtime, const collisionMoveResult *moveresult) +void ScriptApiEntity::luaentity_Step(u16 id, float dtime, + const collisionMoveResult *moveresult) { SCRIPTAPI_PRECHECKHEADER @@ -213,18 +212,18 @@ void ScriptApiEntity::luaentity_Step( // Calls entity:on_punch(ObjectRef puncher, time_from_last_punch, // tool_capabilities, direction, damage) -bool ScriptApiEntity::luaentity_Punch(u16 id, ServerActiveObject *puncher, - float time_from_last_punch, const ToolCapabilities *toolcap, v3f dir, - s16 damage) +bool ScriptApiEntity::luaentity_Punch(u16 id, + ServerActiveObject *puncher, float time_from_last_punch, + const ToolCapabilities *toolcap, v3f dir, s16 damage) { SCRIPTAPI_PRECHECKHEADER - // infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl; + //infostream<<"scriptapi_luaentity_step: id="<<id<<std::endl; int error_handler = PUSH_ERROR_HANDLER(L); // Get core.luaentities[id] - luaentity_get(L, id); + luaentity_get(L,id); int object = lua_gettop(L); // State: object is at top of stack // Get function @@ -234,8 +233,8 @@ bool ScriptApiEntity::luaentity_Punch(u16 id, ServerActiveObject *puncher, return false; } luaL_checktype(L, -1, LUA_TFUNCTION); - lua_pushvalue(L, object); // self - objectrefGetOrCreate(L, puncher); // Clicker reference + lua_pushvalue(L, object); // self + objectrefGetOrCreate(L, puncher); // Clicker reference lua_pushnumber(L, time_from_last_punch); push_tool_capabilities(L, *toolcap); push_v3f(L, dir); @@ -250,8 +249,8 @@ bool ScriptApiEntity::luaentity_Punch(u16 id, ServerActiveObject *puncher, } // Calls entity[field](ObjectRef self, ObjectRef sao) -bool ScriptApiEntity::luaentity_run_simple_callback( - u16 id, ServerActiveObject *sao, const char *field) +bool ScriptApiEntity::luaentity_run_simple_callback(u16 id, + ServerActiveObject *sao, const char *field) { SCRIPTAPI_PRECHECKHEADER @@ -268,8 +267,8 @@ bool ScriptApiEntity::luaentity_run_simple_callback( return false; } luaL_checktype(L, -1, LUA_TFUNCTION); - lua_pushvalue(L, object); // self - objectrefGetOrCreate(L, sao); // killer reference + lua_pushvalue(L, object); // self + objectrefGetOrCreate(L, sao); // killer reference setOriginFromTable(object); PCALL_RES(lua_pcall(L, 2, 1, error_handler)); diff --git a/src/script/cpp_api/s_entity.h b/src/script/cpp_api/s_entity.h index 93960ed03..b5f7a6586 100644 --- a/src/script/cpp_api/s_entity.h +++ b/src/script/cpp_api/s_entity.h @@ -26,26 +26,28 @@ struct ObjectProperties; struct ToolCapabilities; struct collisionMoveResult; -class ScriptApiEntity : virtual public ScriptApiBase +class ScriptApiEntity + : virtual public ScriptApiBase { public: bool luaentity_Add(u16 id, const char *name); - void luaentity_Activate(u16 id, const std::string &staticdata, u32 dtime_s); + void luaentity_Activate(u16 id, + const std::string &staticdata, u32 dtime_s); void luaentity_Remove(u16 id); std::string luaentity_GetStaticdata(u16 id); - void luaentity_GetProperties( - u16 id, ServerActiveObject *self, ObjectProperties *prop); - void luaentity_Step(u16 id, float dtime, const collisionMoveResult *moveresult); - bool luaentity_Punch(u16 id, ServerActiveObject *puncher, - float time_from_last_punch, const ToolCapabilities *toolcap, - v3f dir, s16 damage); + void luaentity_GetProperties(u16 id, + ServerActiveObject *self, ObjectProperties *prop); + void luaentity_Step(u16 id, float dtime, + const collisionMoveResult *moveresult); + bool luaentity_Punch(u16 id, + ServerActiveObject *puncher, float time_from_last_punch, + const ToolCapabilities *toolcap, v3f dir, s16 damage); bool luaentity_on_death(u16 id, ServerActiveObject *killer); void luaentity_Rightclick(u16 id, ServerActiveObject *clicker); void luaentity_on_attach_child(u16 id, ServerActiveObject *child); void luaentity_on_detach_child(u16 id, ServerActiveObject *child); void luaentity_on_detach(u16 id, ServerActiveObject *parent); - private: - bool luaentity_run_simple_callback( - u16 id, ServerActiveObject *sao, const char *field); + bool luaentity_run_simple_callback(u16 id, ServerActiveObject *sao, + const char *field); }; diff --git a/src/script/cpp_api/s_env.cpp b/src/script/cpp_api/s_env.cpp index 7511c0226..8da5debaa 100644 --- a/src/script/cpp_api/s_env.cpp +++ b/src/script/cpp_api/s_env.cpp @@ -26,7 +26,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_env.h" #include "server.h" -void ScriptApiEnv::environment_OnGenerated(v3s16 minp, v3s16 maxp, u32 blockseed) +void ScriptApiEnv::environment_OnGenerated(v3s16 minp, v3s16 maxp, + u32 blockseed) { SCRIPTAPI_PRECHECKHEADER @@ -43,7 +44,7 @@ void ScriptApiEnv::environment_OnGenerated(v3s16 minp, v3s16 maxp, u32 blockseed void ScriptApiEnv::environment_Step(float dtime) { SCRIPTAPI_PRECHECKHEADER - // infostream << "scriptapi_environment_step" << std::endl; + //infostream << "scriptapi_environment_step" << std::endl; // Get core.registered_globalsteps lua_getglobal(L, "core"); @@ -53,9 +54,9 @@ void ScriptApiEnv::environment_Step(float dtime) try { runCallbacks(1, RUN_CALLBACKS_MODE_FIRST); } catch (LuaError &e) { - getServer()->setAsyncFatalError(std::string("environment_Step: ") + - e.what() + "\n" + - script_get_backtrace(L)); + getServer()->setAsyncFatalError( + std::string("environment_Step: ") + e.what() + "\n" + + script_get_backtrace(L)); } } @@ -71,13 +72,14 @@ void ScriptApiEnv::player_event(ServerActiveObject *player, const std::string &t lua_getfield(L, -1, "registered_playerevents"); // Call callbacks - objectrefGetOrCreate(L, player); // player - lua_pushstring(L, type.c_str()); // event type + objectrefGetOrCreate(L, player); // player + lua_pushstring(L,type.c_str()); // event type try { runCallbacks(2, RUN_CALLBACKS_MODE_FIRST); } catch (LuaError &e) { - getServer()->setAsyncFatalError(std::string("player_event: ") + e.what() + - "\n" + script_get_backtrace(L)); + getServer()->setAsyncFatalError( + std::string("player_event: ") + e.what() + "\n" + + script_get_backtrace(L) ); } } @@ -114,8 +116,7 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) while (lua_next(L, table)) { // key at index -2 and value at index -1 luaL_checktype(L, -1, LUA_TSTRING); - trigger_contents.emplace_back( - readParam<std::string>(L, -1)); + trigger_contents.emplace_back(readParam<std::string>(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); } @@ -132,8 +133,7 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) while (lua_next(L, table)) { // key at index -2 and value at index -1 luaL_checktype(L, -1, LUA_TSTRING); - required_neighbors.emplace_back( - readParam<std::string>(L, -1)); + required_neighbors.emplace_back(readParam<std::string>(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); } @@ -156,7 +156,7 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) lua_pop(L, 1); LuaABM *abm = new LuaABM(L, id, trigger_contents, required_neighbors, - trigger_interval, trigger_chance, simple_catch_up); + trigger_interval, trigger_chance, simple_catch_up); env->addActiveBlockModifier(abm); @@ -201,15 +201,15 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) std::string name; getstringfield(L, current_lbm, "name", name); - bool run_at_every_load = getboolfield_default( - L, current_lbm, "run_at_every_load", false); + bool run_at_every_load = getboolfield_default(L, current_lbm, + "run_at_every_load", false); lua_getfield(L, current_lbm, "action"); luaL_checktype(L, current_lbm + 1, LUA_TFUNCTION); lua_pop(L, 1); - LuaLBM *lbm = new LuaLBM( - L, id, trigger_contents, name, run_at_every_load); + LuaLBM *lbm = new LuaLBM(L, id, trigger_contents, name, + run_at_every_load); env->addLoadingBlockModifierDef(lbm); @@ -220,7 +220,7 @@ void ScriptApiEnv::initializeEnvironment(ServerEnvironment *env) } void ScriptApiEnv::on_emerge_area_completion( - v3s16 blockpos, int action, ScriptCallbackState *state) + v3s16 blockpos, int action, ScriptCallbackState *state) { Server *server = getServer(); @@ -249,8 +249,9 @@ void ScriptApiEnv::on_emerge_area_completion( try { PCALL_RES(lua_pcall(L, 4, 0, error_handler)); } catch (LuaError &e) { - server->setAsyncFatalError(std::string("on_emerge_area_completion: ") + - e.what() + "\n" + script_get_backtrace(L)); + server->setAsyncFatalError( + std::string("on_emerge_area_completion: ") + e.what() + "\n" + + script_get_backtrace(L)); } lua_pop(L, 1); // Pop error handler diff --git a/src/script/cpp_api/s_env.h b/src/script/cpp_api/s_env.h index 1848c7a94..232a08aaf 100644 --- a/src/script/cpp_api/s_env.h +++ b/src/script/cpp_api/s_env.h @@ -38,8 +38,8 @@ public: void player_event(ServerActiveObject *player, const std::string &type); // Called after emerge of a block queued from core.emerge_area() - void on_emerge_area_completion( - v3s16 blockpos, int action, ScriptCallbackState *state); + void on_emerge_area_completion(v3s16 blockpos, int action, + ScriptCallbackState *state); void initializeEnvironment(ServerEnvironment *env); }; diff --git a/src/script/cpp_api/s_internal.h b/src/script/cpp_api/s_internal.h index 858b827de..83b3b9d27 100644 --- a/src/script/cpp_api/s_internal.h +++ b/src/script/cpp_api/s_internal.h @@ -34,14 +34,13 @@ with this program; if not, write to the Free Software Foundation, Inc., #ifdef SCRIPTAPI_LOCK_DEBUG #include <cassert> -class LockChecker -{ +class LockChecker { public: LockChecker(int *recursion_counter, std::thread::id *owning_thread) { m_lock_recursion_counter = recursion_counter; - m_owning_thread = owning_thread; - m_original_level = *recursion_counter; + m_owning_thread = owning_thread; + m_original_level = *recursion_counter; if (*m_lock_recursion_counter > 0) { assert(*m_owning_thread == std::this_thread::get_id()); @@ -68,18 +67,19 @@ private: std::thread::id *m_owning_thread; }; -#define SCRIPTAPI_LOCK_CHECK \ - LockChecker scriptlock_checker( \ - &this->m_lock_recursion_count, &this->m_owning_thread) +#define SCRIPTAPI_LOCK_CHECK \ + LockChecker scriptlock_checker( \ + &this->m_lock_recursion_count, \ + &this->m_owning_thread) #else -#define SCRIPTAPI_LOCK_CHECK while (0) + #define SCRIPTAPI_LOCK_CHECK while(0) #endif -#define SCRIPTAPI_PRECHECKHEADER \ - RecursiveMutexAutoLock scriptlock(this->m_luastackmutex); \ - SCRIPTAPI_LOCK_CHECK; \ - realityCheck(); \ - lua_State *L = getStack(); \ - assert(lua_checkstack(L, 20)); \ - StackUnroller stack_unroller(L); +#define SCRIPTAPI_PRECHECKHEADER \ + RecursiveMutexAutoLock scriptlock(this->m_luastackmutex); \ + SCRIPTAPI_LOCK_CHECK; \ + realityCheck(); \ + lua_State *L = getStack(); \ + assert(lua_checkstack(L, 20)); \ + StackUnroller stack_unroller(L); diff --git a/src/script/cpp_api/s_inventory.cpp b/src/script/cpp_api/s_inventory.cpp index e4d3f990d..e9c09f72e 100644 --- a/src/script/cpp_api/s_inventory.cpp +++ b/src/script/cpp_api/s_inventory.cpp @@ -26,7 +26,8 @@ with this program; if not, write to the Free Software Foundation, Inc., // Return number of accepted items to be moved int ScriptApiDetached::detached_inventory_AllowMove( - const MoveAction &ma, int count, ServerActiveObject *player) + const MoveAction &ma, int count, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -40,15 +41,14 @@ int ScriptApiDetached::detached_inventory_AllowMove( // inv InvRef::create(L, ma.from_inv); lua_pushstring(L, ma.from_list.c_str()); // from_list - lua_pushinteger(L, ma.from_i + 1); // from_index - lua_pushstring(L, ma.to_list.c_str()); // to_list - lua_pushinteger(L, ma.to_i + 1); // to_index - lua_pushinteger(L, count); // count - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // from_index + lua_pushstring(L, ma.to_list.c_str()); // to_list + lua_pushinteger(L, ma.to_i + 1); // to_index + lua_pushinteger(L, count); // count + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 7, 1, error_handler)); - if (!lua_isnumber(L, -1)) - throw LuaError("allow_move should return a number. name=" + - ma.from_inv.name); + if(!lua_isnumber(L, -1)) + throw LuaError("allow_move should return a number. name=" + ma.from_inv.name); int ret = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return ret; @@ -56,7 +56,8 @@ int ScriptApiDetached::detached_inventory_AllowMove( // Return number of accepted items to be put int ScriptApiDetached::detached_inventory_AllowPut( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -67,15 +68,14 @@ int ScriptApiDetached::detached_inventory_AllowPut( return stack.count; // All will be accepted // Call function(inv, listname, index, stack, player) - InvRef::create(L, ma.to_inv); // inv + InvRef::create(L, ma.to_inv); // inv lua_pushstring(L, ma.to_list.c_str()); // listname lua_pushinteger(L, ma.to_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 1, error_handler)); if (!lua_isnumber(L, -1)) - throw LuaError("allow_put should return a number. name=" + - ma.to_inv.name); + throw LuaError("allow_put should return a number. name=" + ma.to_inv.name); int ret = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return ret; @@ -83,7 +83,8 @@ int ScriptApiDetached::detached_inventory_AllowPut( // Return number of accepted items to be taken int ScriptApiDetached::detached_inventory_AllowTake( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -94,15 +95,14 @@ int ScriptApiDetached::detached_inventory_AllowTake( return stack.count; // All will be accepted // Call function(inv, listname, index, stack, player) - InvRef::create(L, ma.from_inv); // inv + InvRef::create(L, ma.from_inv); // inv lua_pushstring(L, ma.from_list.c_str()); // listname - lua_pushinteger(L, ma.from_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // index + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 1, error_handler)); if (!lua_isnumber(L, -1)) - throw LuaError("allow_take should return a number. name=" + - ma.from_inv.name); + throw LuaError("allow_take should return a number. name=" + ma.from_inv.name); int ret = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return ret; @@ -110,7 +110,8 @@ int ScriptApiDetached::detached_inventory_AllowTake( // Report moved items void ScriptApiDetached::detached_inventory_OnMove( - const MoveAction &ma, int count, ServerActiveObject *player) + const MoveAction &ma, int count, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -124,18 +125,19 @@ void ScriptApiDetached::detached_inventory_OnMove( // inv InvRef::create(L, ma.from_inv); lua_pushstring(L, ma.from_list.c_str()); // from_list - lua_pushinteger(L, ma.from_i + 1); // from_index - lua_pushstring(L, ma.to_list.c_str()); // to_list - lua_pushinteger(L, ma.to_i + 1); // to_index - lua_pushinteger(L, count); // count - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // from_index + lua_pushstring(L, ma.to_list.c_str()); // to_list + lua_pushinteger(L, ma.to_i + 1); // to_index + lua_pushinteger(L, count); // count + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 7, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Report put items void ScriptApiDetached::detached_inventory_OnPut( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -150,15 +152,16 @@ void ScriptApiDetached::detached_inventory_OnPut( InvRef::create(L, ma.to_inv); lua_pushstring(L, ma.to_list.c_str()); // listname lua_pushinteger(L, ma.to_i + 1); // index - LuaItemStack::create(L, stack); // stack + LuaItemStack::create(L, stack); // stack objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Report taken items void ScriptApiDetached::detached_inventory_OnTake( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -172,11 +175,11 @@ void ScriptApiDetached::detached_inventory_OnTake( // inv InvRef::create(L, ma.from_inv); lua_pushstring(L, ma.from_list.c_str()); // listname - lua_pushinteger(L, ma.from_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // index + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Retrieves core.detached_inventories[name][callbackname] @@ -196,8 +199,7 @@ bool ScriptApiDetached::getDetachedInventoryCallback( lua_remove(L, -2); // Should be a table if (lua_type(L, -1) != LUA_TTABLE) { - errorstream << "Detached inventory \"" << name << "\" not defined" - << std::endl; + errorstream<<"Detached inventory \""<<name<<"\" not defined"<<std::endl; lua_pop(L, 1); return false; } @@ -216,8 +218,8 @@ bool ScriptApiDetached::getDetachedInventoryCallback( return false; } - errorstream << "Detached inventory \"" << name << "\" callback \"" << callbackname - << "\" is not a function" << std::endl; + errorstream << "Detached inventory \"" << name << "\" callback \"" + << callbackname << "\" is not a function" << std::endl; lua_pop(L, 1); return false; } diff --git a/src/script/cpp_api/s_inventory.h b/src/script/cpp_api/s_inventory.h index c6476190e..e79b3d18b 100644 --- a/src/script/cpp_api/s_inventory.h +++ b/src/script/cpp_api/s_inventory.h @@ -24,29 +24,35 @@ with this program; if not, write to the Free Software Foundation, Inc., struct MoveAction; struct ItemStack; -class ScriptApiDetached : virtual public ScriptApiBase +class ScriptApiDetached + : virtual public ScriptApiBase { public: /* Detached inventory callbacks */ // Return number of accepted items to be moved int detached_inventory_AllowMove( - const MoveAction &ma, int count, ServerActiveObject *player); + const MoveAction &ma, int count, + ServerActiveObject *player); // Return number of accepted items to be put - int detached_inventory_AllowPut(const MoveAction &ma, const ItemStack &stack, + int detached_inventory_AllowPut( + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Return number of accepted items to be taken - int detached_inventory_AllowTake(const MoveAction &ma, const ItemStack &stack, + int detached_inventory_AllowTake( + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Report moved items void detached_inventory_OnMove( - const MoveAction &ma, int count, ServerActiveObject *player); + const MoveAction &ma, int count, + ServerActiveObject *player); // Report put items - void detached_inventory_OnPut(const MoveAction &ma, const ItemStack &stack, + void detached_inventory_OnPut( + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Report taken items - void detached_inventory_OnTake(const MoveAction &ma, const ItemStack &stack, + void detached_inventory_OnTake( + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); - private: bool getDetachedInventoryCallback( const std::string &name, const char *callbackname); diff --git a/src/script/cpp_api/s_item.cpp b/src/script/cpp_api/s_item.cpp index 4e77ad412..24955cefc 100644 --- a/src/script/cpp_api/s_item.cpp +++ b/src/script/cpp_api/s_item.cpp @@ -29,7 +29,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "inventory.h" #include "inventorymanager.h" -bool ScriptApiItem::item_OnDrop(ItemStack &item, ServerActiveObject *dropper, v3f pos) +bool ScriptApiItem::item_OnDrop(ItemStack &item, + ServerActiveObject *dropper, v3f pos) { SCRIPTAPI_PRECHECKHEADER @@ -51,12 +52,12 @@ bool ScriptApiItem::item_OnDrop(ItemStack &item, ServerActiveObject *dropper, v3 throw LuaError(std::string(e.what()) + ". item=" + item.name); } } - lua_pop(L, 2); // Pop item and error handler + lua_pop(L, 2); // Pop item and error handler return true; } -bool ScriptApiItem::item_OnPlace( - ItemStack &item, ServerActiveObject *placer, const PointedThing &pointed) +bool ScriptApiItem::item_OnPlace(ItemStack &item, + ServerActiveObject *placer, const PointedThing &pointed) { SCRIPTAPI_PRECHECKHEADER @@ -83,12 +84,12 @@ bool ScriptApiItem::item_OnPlace( throw LuaError(std::string(e.what()) + ". item=" + item.name); } } - lua_pop(L, 2); // Pop item and error handler + lua_pop(L, 2); // Pop item and error handler return true; } -bool ScriptApiItem::item_OnUse( - ItemStack &item, ServerActiveObject *user, const PointedThing &pointed) +bool ScriptApiItem::item_OnUse(ItemStack &item, + ServerActiveObject *user, const PointedThing &pointed) { SCRIPTAPI_PRECHECKHEADER @@ -103,19 +104,19 @@ bool ScriptApiItem::item_OnUse( objectrefGetOrCreate(L, user); pushPointedThing(pointed); PCALL_RES(lua_pcall(L, 3, 1, error_handler)); - if (!lua_isnil(L, -1)) { + if(!lua_isnil(L, -1)) { try { item = read_item(L, -1, getServer()->idef()); } catch (LuaError &e) { throw LuaError(std::string(e.what()) + ". item=" + item.name); } } - lua_pop(L, 2); // Pop item and error handler + lua_pop(L, 2); // Pop item and error handler return true; } -bool ScriptApiItem::item_OnSecondaryUse( - ItemStack &item, ServerActiveObject *user, const PointedThing &pointed) +bool ScriptApiItem::item_OnSecondaryUse(ItemStack &item, + ServerActiveObject *user, const PointedThing &pointed) { SCRIPTAPI_PRECHECKHEADER @@ -135,7 +136,7 @@ bool ScriptApiItem::item_OnSecondaryUse( throw LuaError(std::string(e.what()) + ". item=" + item.name); } } - lua_pop(L, 2); // Pop item and error handler + lua_pop(L, 2); // Pop item and error handler return true; } @@ -167,7 +168,7 @@ bool ScriptApiItem::item_OnCraft(ItemStack &item, ServerActiveObject *user, throw LuaError(std::string(e.what()) + ". item=" + item.name); } } - lua_pop(L, 2); // Pop item and error handler + lua_pop(L, 2); // Pop item and error handler return true; } @@ -183,7 +184,7 @@ bool ScriptApiItem::item_CraftPredict(ItemStack &item, ServerActiveObject *user, LuaItemStack::create(L, item); objectrefGetOrCreate(L, user); - // Push inventory list + //Push inventory list std::vector<ItemStack> items; for (u32 i = 0; i < old_craft_grid->getSize(); i++) { items.push_back(old_craft_grid->getItem(i)); @@ -199,7 +200,7 @@ bool ScriptApiItem::item_CraftPredict(ItemStack &item, ServerActiveObject *user, throw LuaError(std::string(e.what()) + ". item=" + item.name); } } - lua_pop(L, 2); // Pop item and error handler + lua_pop(L, 2); // Pop item and error handler return true; } @@ -209,10 +210,10 @@ bool ScriptApiItem::item_CraftPredict(ItemStack &item, ServerActiveObject *user, // function onto the stack // If core.registered_items[name] doesn't exist, core.nodedef_default // is tried instead so unknown items can still be manipulated to some degree -bool ScriptApiItem::getItemCallback( - const char *name, const char *callbackname, const v3s16 *p) +bool ScriptApiItem::getItemCallback(const char *name, const char *callbackname, + const v3s16 *p) { - lua_State *L = getStack(); + lua_State* L = getStack(); lua_getglobal(L, "core"); lua_getfield(L, -1, "registered_items"); @@ -246,8 +247,8 @@ bool ScriptApiItem::getItemCallback( } if (!lua_isnil(L, -1)) { - errorstream << "Item \"" << name << "\" callback \"" << callbackname - << "\" is not a function" << std::endl; + errorstream << "Item \"" << name << "\" callback \"" + << callbackname << "\" is not a function" << std::endl; } lua_pop(L, 1); return false; @@ -255,7 +256,8 @@ bool ScriptApiItem::getItemCallback( void ScriptApiItem::pushPointedThing(const PointedThing &pointed, bool hitpoint) { - lua_State *L = getStack(); + lua_State* L = getStack(); push_pointed_thing(L, pointed, false, hitpoint); } + diff --git a/src/script/cpp_api/s_item.h b/src/script/cpp_api/s_item.h index 530f14bbc..25a3501f9 100644 --- a/src/script/cpp_api/s_item.h +++ b/src/script/cpp_api/s_item.h @@ -31,32 +31,32 @@ class ModApiItemMod; class InventoryList; struct InventoryLocation; -class ScriptApiItem : virtual public ScriptApiBase +class ScriptApiItem +: virtual public ScriptApiBase { public: - bool item_OnDrop(ItemStack &item, ServerActiveObject *dropper, v3f pos); - bool item_OnPlace(ItemStack &item, ServerActiveObject *placer, - const PointedThing &pointed); - bool item_OnUse(ItemStack &item, ServerActiveObject *user, - const PointedThing &pointed); - bool item_OnSecondaryUse(ItemStack &item, ServerActiveObject *user, - const PointedThing &pointed); + bool item_OnDrop(ItemStack &item, + ServerActiveObject *dropper, v3f pos); + bool item_OnPlace(ItemStack &item, + ServerActiveObject *placer, const PointedThing &pointed); + bool item_OnUse(ItemStack &item, + ServerActiveObject *user, const PointedThing &pointed); + bool item_OnSecondaryUse(ItemStack &item, + ServerActiveObject *user, const PointedThing &pointed); bool item_OnCraft(ItemStack &item, ServerActiveObject *user, - const InventoryList *old_craft_grid, - const InventoryLocation &craft_inv); + const InventoryList *old_craft_grid, const InventoryLocation &craft_inv); bool item_CraftPredict(ItemStack &item, ServerActiveObject *user, - const InventoryList *old_craft_grid, - const InventoryLocation &craft_inv); + const InventoryList *old_craft_grid, const InventoryLocation &craft_inv); protected: friend class LuaItemStack; friend class ModApiItemMod; - bool getItemCallback(const char *name, const char *callbackname, - const v3s16 *p = nullptr); + bool getItemCallback(const char *name, const char *callbackname, const v3s16 *p = nullptr); /*! * Pushes a `pointed_thing` tabe to the stack. * \param hitpoint If true, the exact pointing location is also pushed */ void pushPointedThing(const PointedThing &pointed, bool hitpoint = false); + }; diff --git a/src/script/cpp_api/s_mainmenu.h b/src/script/cpp_api/s_mainmenu.h index 0f6ff9f78..aef36ce39 100644 --- a/src/script/cpp_api/s_mainmenu.h +++ b/src/script/cpp_api/s_mainmenu.h @@ -23,8 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/string.h" #include "gui/guiMainMenu.h" -class ScriptApiMainMenu : virtual public ScriptApiBase -{ +class ScriptApiMainMenu : virtual public ScriptApiBase { public: /** * Hand over MainMenuDataForScript to lua to inform lua of the content diff --git a/src/script/cpp_api/s_node.cpp b/src/script/cpp_api/s_node.cpp index 928fda6e2..e0f9bcd78 100644 --- a/src/script/cpp_api/s_node.cpp +++ b/src/script/cpp_api/s_node.cpp @@ -26,8 +26,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "environment.h" #include "util/pointedthing.h" + // Should be ordered exactly like enum NodeDrawType in nodedef.h -struct EnumString ScriptApiNode::es_DrawType[] = { +struct EnumString ScriptApiNode::es_DrawType[] = + { {NDT_NORMAL, "normal"}, {NDT_AIRLIKE, "airlike"}, {NDT_LIQUID, "liquid"}, @@ -47,9 +49,10 @@ struct EnumString ScriptApiNode::es_DrawType[] = { {NDT_MESH, "mesh"}, {NDT_PLANTLIKE_ROOTED, "plantlike_rooted"}, {0, NULL}, -}; + }; -struct EnumString ScriptApiNode::es_ContentParamType2[] = { +struct EnumString ScriptApiNode::es_ContentParamType2[] = + { {CPT2_NONE, "none"}, {CPT2_FULL, "full"}, {CPT2_FLOWINGLIQUID, "flowingliquid"}, @@ -63,32 +66,35 @@ struct EnumString ScriptApiNode::es_ContentParamType2[] = { {CPT2_COLORED_WALLMOUNTED, "colorwallmounted"}, {CPT2_GLASSLIKE_LIQUID_LEVEL, "glasslikeliquidlevel"}, {0, NULL}, -}; + }; -struct EnumString ScriptApiNode::es_LiquidType[] = { +struct EnumString ScriptApiNode::es_LiquidType[] = + { {LIQUID_NONE, "none"}, {LIQUID_FLOWING, "flowing"}, {LIQUID_SOURCE, "source"}, {0, NULL}, -}; + }; -struct EnumString ScriptApiNode::es_ContentParamType[] = { +struct EnumString ScriptApiNode::es_ContentParamType[] = + { {CPT_NONE, "none"}, {CPT_LIGHT, "light"}, {0, NULL}, -}; + }; -struct EnumString ScriptApiNode::es_NodeBoxType[] = { +struct EnumString ScriptApiNode::es_NodeBoxType[] = + { {NODEBOX_REGULAR, "regular"}, {NODEBOX_FIXED, "fixed"}, {NODEBOX_WALLMOUNTED, "wallmounted"}, {NODEBOX_LEVELED, "leveled"}, {NODEBOX_CONNECTED, "connected"}, {0, NULL}, -}; + }; -bool ScriptApiNode::node_on_punch(v3s16 p, MapNode node, ServerActiveObject *puncher, - const PointedThing &pointed) +bool ScriptApiNode::node_on_punch(v3s16 p, MapNode node, + ServerActiveObject *puncher, const PointedThing &pointed) { SCRIPTAPI_PRECHECKHEADER @@ -106,11 +112,12 @@ bool ScriptApiNode::node_on_punch(v3s16 p, MapNode node, ServerActiveObject *pun objectrefGetOrCreate(L, puncher); pushPointedThing(pointed); PCALL_RES(lua_pcall(L, 4, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler return true; } -bool ScriptApiNode::node_on_dig(v3s16 p, MapNode node, ServerActiveObject *digger) +bool ScriptApiNode::node_on_dig(v3s16 p, MapNode node, + ServerActiveObject *digger) { SCRIPTAPI_PRECHECKHEADER @@ -127,7 +134,7 @@ bool ScriptApiNode::node_on_dig(v3s16 p, MapNode node, ServerActiveObject *digge pushnode(L, node, ndef); objectrefGetOrCreate(L, digger); PCALL_RES(lua_pcall(L, 3, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler return true; } @@ -146,7 +153,7 @@ void ScriptApiNode::node_on_construct(v3s16 p, MapNode node) // Call function push_v3s16(L, p); PCALL_RES(lua_pcall(L, 1, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } void ScriptApiNode::node_on_destruct(v3s16 p, MapNode node) @@ -164,7 +171,7 @@ void ScriptApiNode::node_on_destruct(v3s16 p, MapNode node) // Call function push_v3s16(L, p); PCALL_RES(lua_pcall(L, 1, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } bool ScriptApiNode::node_on_flood(v3s16 p, MapNode node, MapNode newnode) @@ -204,7 +211,7 @@ void ScriptApiNode::node_after_destruct(v3s16 p, MapNode node) push_v3s16(L, p); pushnode(L, node, ndef); PCALL_RES(lua_pcall(L, 2, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } bool ScriptApiNode::node_on_timer(v3s16 p, MapNode node, f32 dtime) @@ -221,14 +228,16 @@ bool ScriptApiNode::node_on_timer(v3s16 p, MapNode node, f32 dtime) // Call function push_v3s16(L, p); - lua_pushnumber(L, dtime); + lua_pushnumber(L,dtime); PCALL_RES(lua_pcall(L, 2, 1, error_handler)); lua_remove(L, error_handler); return readParam<bool>(L, -1, false); } -void ScriptApiNode::node_on_receive_fields(v3s16 p, const std::string &formname, - const StringMap &fields, ServerActiveObject *sender) +void ScriptApiNode::node_on_receive_fields(v3s16 p, + const std::string &formname, + const StringMap &fields, + ServerActiveObject *sender) { SCRIPTAPI_PRECHECKHEADER @@ -246,9 +255,9 @@ void ScriptApiNode::node_on_receive_fields(v3s16 p, const std::string &formname, return; // Call function - push_v3s16(L, p); // pos + push_v3s16(L, p); // pos lua_pushstring(L, formname.c_str()); // formname - lua_newtable(L); // fields + lua_newtable(L); // fields StringMap::const_iterator it; for (it = fields.begin(); it != fields.end(); ++it) { const std::string &name = it->first; @@ -257,7 +266,7 @@ void ScriptApiNode::node_on_receive_fields(v3s16 p, const std::string &formname, lua_pushlstring(L, value.c_str(), value.size()); lua_settable(L, -3); } - objectrefGetOrCreate(L, sender); // player + objectrefGetOrCreate(L, sender); // player PCALL_RES(lua_pcall(L, 4, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } diff --git a/src/script/cpp_api/s_node.h b/src/script/cpp_api/s_node.h index 8f4e41479..81b44f0f0 100644 --- a/src/script/cpp_api/s_node.h +++ b/src/script/cpp_api/s_node.h @@ -27,23 +27,27 @@ with this program; if not, write to the Free Software Foundation, Inc., struct MapNode; class ServerActiveObject; -class ScriptApiNode : virtual public ScriptApiBase, public ScriptApiNodemeta +class ScriptApiNode + : virtual public ScriptApiBase, + public ScriptApiNodemeta { public: ScriptApiNode() = default; virtual ~ScriptApiNode() = default; - bool node_on_punch(v3s16 p, MapNode node, ServerActiveObject *puncher, - const PointedThing &pointed); - bool node_on_dig(v3s16 p, MapNode node, ServerActiveObject *digger); + bool node_on_punch(v3s16 p, MapNode node, + ServerActiveObject *puncher, const PointedThing &pointed); + bool node_on_dig(v3s16 p, MapNode node, + ServerActiveObject *digger); void node_on_construct(v3s16 p, MapNode node); void node_on_destruct(v3s16 p, MapNode node); bool node_on_flood(v3s16 p, MapNode node, MapNode newnode); void node_after_destruct(v3s16 p, MapNode node); bool node_on_timer(v3s16 p, MapNode node, f32 dtime); - void node_on_receive_fields(v3s16 p, const std::string &formname, - const StringMap &fields, ServerActiveObject *sender); - + void node_on_receive_fields(v3s16 p, + const std::string &formname, + const StringMap &fields, + ServerActiveObject *sender); public: static struct EnumString es_DrawType[]; static struct EnumString es_ContentParamType[]; diff --git a/src/script/cpp_api/s_nodemeta.cpp b/src/script/cpp_api/s_nodemeta.cpp index b7bd5f7c8..c081e9fc4 100644 --- a/src/script/cpp_api/s_nodemeta.cpp +++ b/src/script/cpp_api/s_nodemeta.cpp @@ -28,7 +28,8 @@ with this program; if not, write to the Free Software Foundation, Inc., // Return number of accepted items to be moved int ScriptApiNodemeta::nodemeta_inventory_AllowMove( - const MoveAction &ma, int count, ServerActiveObject *player) + const MoveAction &ma, int count, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -43,23 +44,21 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowMove( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_move", - &ma.to_inv.p)) + if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_move", &ma.to_inv.p)) return count; // function(pos, from_list, from_index, to_list, to_index, count, player) - push_v3s16(L, ma.to_inv.p); // pos + push_v3s16(L, ma.to_inv.p); // pos lua_pushstring(L, ma.from_list.c_str()); // from_list - lua_pushinteger(L, ma.from_i + 1); // from_index - lua_pushstring(L, ma.to_list.c_str()); // to_list - lua_pushinteger(L, ma.to_i + 1); // to_index - lua_pushinteger(L, count); // count - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // from_index + lua_pushstring(L, ma.to_list.c_str()); // to_list + lua_pushinteger(L, ma.to_i + 1); // to_index + lua_pushinteger(L, count); // count + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 7, 1, error_handler)); if (!lua_isnumber(L, -1)) throw LuaError("allow_metadata_inventory_move should" - " return a number, guilty node: " + - nodename); + " return a number, guilty node: " + nodename); int num = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return num; @@ -67,7 +66,8 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowMove( // Return number of accepted items to be put int ScriptApiNodemeta::nodemeta_inventory_AllowPut( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -82,21 +82,19 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowPut( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_put", - &ma.to_inv.p)) + if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_put", &ma.to_inv.p)) return stack.count; // Call function(pos, listname, index, stack, player) - push_v3s16(L, ma.to_inv.p); // pos + push_v3s16(L, ma.to_inv.p); // pos lua_pushstring(L, ma.to_list.c_str()); // listname lua_pushinteger(L, ma.to_i + 1); // index - LuaItemStack::create(L, stack); // stack + LuaItemStack::create(L, stack); // stack objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 1, error_handler)); - if (!lua_isnumber(L, -1)) + if(!lua_isnumber(L, -1)) throw LuaError("allow_metadata_inventory_put should" - " return a number, guilty node: " + - nodename); + " return a number, guilty node: " + nodename); int num = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return num; @@ -104,7 +102,8 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowPut( // Return number of accepted items to be taken int ScriptApiNodemeta::nodemeta_inventory_AllowTake( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -119,21 +118,19 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowTake( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_take", - &ma.from_inv.p)) + if (!getItemCallback(nodename.c_str(), "allow_metadata_inventory_take", &ma.from_inv.p)) return stack.count; // Call function(pos, listname, index, count, player) - push_v3s16(L, ma.from_inv.p); // pos + push_v3s16(L, ma.from_inv.p); // pos lua_pushstring(L, ma.from_list.c_str()); // listname - lua_pushinteger(L, ma.from_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // index + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 1, error_handler)); if (!lua_isnumber(L, -1)) throw LuaError("allow_metadata_inventory_take should" - " return a number, guilty node: " + - nodename); + " return a number, guilty node: " + nodename); int num = luaL_checkinteger(L, -1); lua_pop(L, 2); // Pop integer and error handler return num; @@ -141,7 +138,8 @@ int ScriptApiNodemeta::nodemeta_inventory_AllowTake( // Report moved items void ScriptApiNodemeta::nodemeta_inventory_OnMove( - const MoveAction &ma, int count, ServerActiveObject *player) + const MoveAction &ma, int count, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -156,25 +154,25 @@ void ScriptApiNodemeta::nodemeta_inventory_OnMove( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_move", - &ma.from_inv.p)) + if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_move", &ma.from_inv.p)) return; // function(pos, from_list, from_index, to_list, to_index, count, player) - push_v3s16(L, ma.from_inv.p); // pos + push_v3s16(L, ma.from_inv.p); // pos lua_pushstring(L, ma.from_list.c_str()); // from_list - lua_pushinteger(L, ma.from_i + 1); // from_index - lua_pushstring(L, ma.to_list.c_str()); // to_list - lua_pushinteger(L, ma.to_i + 1); // to_index - lua_pushinteger(L, count); // count - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // from_index + lua_pushstring(L, ma.to_list.c_str()); // to_list + lua_pushinteger(L, ma.to_i + 1); // to_index + lua_pushinteger(L, count); // count + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 7, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Report put items void ScriptApiNodemeta::nodemeta_inventory_OnPut( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -193,18 +191,19 @@ void ScriptApiNodemeta::nodemeta_inventory_OnPut( return; // Call function(pos, listname, index, stack, player) - push_v3s16(L, ma.to_inv.p); // pos + push_v3s16(L, ma.to_inv.p); // pos lua_pushstring(L, ma.to_list.c_str()); // listname lua_pushinteger(L, ma.to_i + 1); // index - LuaItemStack::create(L, stack); // stack + LuaItemStack::create(L, stack); // stack objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } // Report taken items void ScriptApiNodemeta::nodemeta_inventory_OnTake( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -219,16 +218,15 @@ void ScriptApiNodemeta::nodemeta_inventory_OnTake( // Push callback function on stack std::string nodename = ndef->get(node).name; - if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_take", - &ma.from_inv.p)) + if (!getItemCallback(nodename.c_str(), "on_metadata_inventory_take", &ma.from_inv.p)) return; // Call function(pos, listname, index, stack, player) - push_v3s16(L, ma.from_inv.p); // pos + push_v3s16(L, ma.from_inv.p); // pos lua_pushstring(L, ma.from_list.c_str()); // listname - lua_pushinteger(L, ma.from_i + 1); // index - LuaItemStack::create(L, stack); // stack - objectrefGetOrCreate(L, player); // player + lua_pushinteger(L, ma.from_i + 1); // index + LuaItemStack::create(L, stack); // stack + objectrefGetOrCreate(L, player); // player PCALL_RES(lua_pcall(L, 5, 0, error_handler)); - lua_pop(L, 1); // Pop error handler + lua_pop(L, 1); // Pop error handler } diff --git a/src/script/cpp_api/s_nodemeta.h b/src/script/cpp_api/s_nodemeta.h index 609898a30..8c7cdd93e 100644 --- a/src/script/cpp_api/s_nodemeta.h +++ b/src/script/cpp_api/s_nodemeta.h @@ -26,7 +26,9 @@ with this program; if not, write to the Free Software Foundation, Inc., struct MoveAction; struct ItemStack; -class ScriptApiNodemeta : virtual public ScriptApiBase, public ScriptApiItem +class ScriptApiNodemeta + : virtual public ScriptApiBase, + public ScriptApiItem { public: ScriptApiNodemeta() = default; @@ -34,22 +36,28 @@ public: // Return number of accepted items to be moved int nodemeta_inventory_AllowMove( - const MoveAction &ma, int count, ServerActiveObject *player); + const MoveAction &ma, int count, + ServerActiveObject *player); // Return number of accepted items to be put - int nodemeta_inventory_AllowPut(const MoveAction &ma, const ItemStack &stack, + int nodemeta_inventory_AllowPut( + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Return number of accepted items to be taken - int nodemeta_inventory_AllowTake(const MoveAction &ma, const ItemStack &stack, + int nodemeta_inventory_AllowTake( + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Report moved items void nodemeta_inventory_OnMove( - const MoveAction &ma, int count, ServerActiveObject *player); + const MoveAction &ma, int count, + ServerActiveObject *player); // Report put items - void nodemeta_inventory_OnPut(const MoveAction &ma, const ItemStack &stack, + void nodemeta_inventory_OnPut( + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); // Report taken items - void nodemeta_inventory_OnTake(const MoveAction &ma, const ItemStack &stack, + void nodemeta_inventory_OnTake( + const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player); - private: + }; diff --git a/src/script/cpp_api/s_player.cpp b/src/script/cpp_api/s_player.cpp index c9ab81db9..712120c61 100644 --- a/src/script/cpp_api/s_player.cpp +++ b/src/script/cpp_api/s_player.cpp @@ -39,8 +39,7 @@ void ScriptApiPlayer::on_newplayer(ServerActiveObject *player) runCallbacks(1, RUN_CALLBACKS_MODE_FIRST); } -void ScriptApiPlayer::on_dieplayer( - ServerActiveObject *player, const PlayerHPChangeReason &reason) +void ScriptApiPlayer::on_dieplayer(ServerActiveObject *player, const PlayerHPChangeReason &reason) { SCRIPTAPI_PRECHECKHEADER @@ -57,8 +56,11 @@ void ScriptApiPlayer::on_dieplayer( } bool ScriptApiPlayer::on_punchplayer(ServerActiveObject *player, - ServerActiveObject *hitter, float time_from_last_punch, - const ToolCapabilities *toolcap, v3f dir, s16 damage) + ServerActiveObject *hitter, + float time_from_last_punch, + const ToolCapabilities *toolcap, + v3f dir, + s16 damage) { SCRIPTAPI_PRECHECKHEADER // Get core.registered_on_punchplayers @@ -75,8 +77,8 @@ bool ScriptApiPlayer::on_punchplayer(ServerActiveObject *player, return readParam<bool>(L, -1); } -s32 ScriptApiPlayer::on_player_hpchange(ServerActiveObject *player, s32 hp_change, - const PlayerHPChangeReason &reason) +s32 ScriptApiPlayer::on_player_hpchange(ServerActiveObject *player, + s32 hp_change, const PlayerHPChangeReason &reason) { SCRIPTAPI_PRECHECKHEADER @@ -113,7 +115,9 @@ bool ScriptApiPlayer::on_respawnplayer(ServerActiveObject *player) } bool ScriptApiPlayer::on_prejoinplayer( - const std::string &name, const std::string &ip, std::string *reason) + const std::string &name, + const std::string &ip, + std::string *reason) { SCRIPTAPI_PRECHECKHEADER @@ -159,7 +163,8 @@ void ScriptApiPlayer::on_joinplayer(ServerActiveObject *player, s64 last_login) runCallbacks(2, RUN_CALLBACKS_MODE_FIRST); } -void ScriptApiPlayer::on_leaveplayer(ServerActiveObject *player, bool timeout) +void ScriptApiPlayer::on_leaveplayer(ServerActiveObject *player, + bool timeout) { SCRIPTAPI_PRECHECKHEADER @@ -172,7 +177,8 @@ void ScriptApiPlayer::on_leaveplayer(ServerActiveObject *player, bool timeout) runCallbacks(2, RUN_CALLBACKS_MODE_FIRST); } -void ScriptApiPlayer::on_cheat(ServerActiveObject *player, const std::string &cheat_type) +void ScriptApiPlayer::on_cheat(ServerActiveObject *player, + const std::string &cheat_type) { SCRIPTAPI_PRECHECKHEADER @@ -188,7 +194,8 @@ void ScriptApiPlayer::on_cheat(ServerActiveObject *player, const std::string &ch } void ScriptApiPlayer::on_playerReceiveFields(ServerActiveObject *player, - const std::string &formname, const StringMap &fields) + const std::string &formname, + const StringMap &fields) { SCRIPTAPI_PRECHECKHEADER @@ -213,8 +220,7 @@ void ScriptApiPlayer::on_playerReceiveFields(ServerActiveObject *player, runCallbacks(3, RUN_CALLBACKS_MODE_OR_SC); } -void ScriptApiPlayer::on_authplayer( - const std::string &name, const std::string &ip, bool is_success) +void ScriptApiPlayer::on_authplayer(const std::string &name, const std::string &ip, bool is_success) { SCRIPTAPI_PRECHECKHEADER @@ -230,12 +236,13 @@ void ScriptApiPlayer::on_authplayer( } void ScriptApiPlayer::pushMoveArguments( - const MoveAction &ma, int count, ServerActiveObject *player) + const MoveAction &ma, int count, + ServerActiveObject *player) { lua_State *L = getStack(); objectrefGetOrCreate(L, player); // player - lua_pushstring(L, "move"); // action - InvRef::create(L, ma.from_inv); // inventory + lua_pushstring(L, "move"); // action + InvRef::create(L, ma.from_inv); // inventory lua_newtable(L); { // Table containing the action information @@ -254,14 +261,15 @@ void ScriptApiPlayer::pushMoveArguments( } } -void ScriptApiPlayer::pushPutTakeArguments(const char *method, - const InventoryLocation &loc, const std::string &listname, int index, - const ItemStack &stack, ServerActiveObject *player) +void ScriptApiPlayer::pushPutTakeArguments( + const char *method, const InventoryLocation &loc, + const std::string &listname, int index, const ItemStack &stack, + ServerActiveObject *player) { lua_State *L = getStack(); objectrefGetOrCreate(L, player); // player - lua_pushstring(L, method); // action - InvRef::create(L, loc); // inventory + lua_pushstring(L, method); // action + InvRef::create(L, loc); // inventory lua_newtable(L); { // Table containing the action information @@ -278,7 +286,8 @@ void ScriptApiPlayer::pushPutTakeArguments(const char *method, // Return number of accepted items to be moved int ScriptApiPlayer::player_inventory_AllowMove( - const MoveAction &ma, int count, ServerActiveObject *player) + const MoveAction &ma, int count, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -292,7 +301,8 @@ int ScriptApiPlayer::player_inventory_AllowMove( // Return number of accepted items to be put int ScriptApiPlayer::player_inventory_AllowPut( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -306,7 +316,8 @@ int ScriptApiPlayer::player_inventory_AllowPut( // Return number of accepted items to be taken int ScriptApiPlayer::player_inventory_AllowTake( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -320,7 +331,8 @@ int ScriptApiPlayer::player_inventory_AllowTake( // Report moved items void ScriptApiPlayer::player_inventory_OnMove( - const MoveAction &ma, int count, ServerActiveObject *player) + const MoveAction &ma, int count, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -332,7 +344,8 @@ void ScriptApiPlayer::player_inventory_OnMove( // Report put items void ScriptApiPlayer::player_inventory_OnPut( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER @@ -344,7 +357,8 @@ void ScriptApiPlayer::player_inventory_OnPut( // Report taken items void ScriptApiPlayer::player_inventory_OnTake( - const MoveAction &ma, const ItemStack &stack, ServerActiveObject *player) + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player) { SCRIPTAPI_PRECHECKHEADER diff --git a/src/script/cpp_api/s_player.h b/src/script/cpp_api/s_player.h index 5a1cf15b8..a337f975b 100644 --- a/src/script/cpp_api/s_player.h +++ b/src/script/cpp_api/s_player.h @@ -51,33 +51,38 @@ public: const PlayerHPChangeReason &reason); void on_playerReceiveFields(ServerActiveObject *player, const std::string &formname, const StringMap &fields); - void on_authplayer( - const std::string &name, const std::string &ip, bool is_success); + void on_authplayer(const std::string &name, const std::string &ip, bool is_success); // Player inventory callbacks // Return number of accepted items to be moved int player_inventory_AllowMove( - const MoveAction &ma, int count, ServerActiveObject *player); + const MoveAction &ma, int count, + ServerActiveObject *player); // Return number of accepted items to be put - int player_inventory_AllowPut(const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player); + int player_inventory_AllowPut( + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player); // Return number of accepted items to be taken - int player_inventory_AllowTake(const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player); + int player_inventory_AllowTake( + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player); // Report moved items void player_inventory_OnMove( - const MoveAction &ma, int count, ServerActiveObject *player); + const MoveAction &ma, int count, + ServerActiveObject *player); // Report put items - void player_inventory_OnPut(const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player); + void player_inventory_OnPut( + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player); // Report taken items - void player_inventory_OnTake(const MoveAction &ma, const ItemStack &stack, - ServerActiveObject *player); - + void player_inventory_OnTake( + const MoveAction &ma, const ItemStack &stack, + ServerActiveObject *player); private: - void pushPutTakeArguments(const char *method, const InventoryLocation &loc, - const std::string &listname, int index, const ItemStack &stack, - ServerActiveObject *player); - void pushMoveArguments( - const MoveAction &ma, int count, ServerActiveObject *player); + void pushPutTakeArguments( + const char *method, const InventoryLocation &loc, + const std::string &listname, int index, const ItemStack &stack, + ServerActiveObject *player); + void pushMoveArguments(const MoveAction &ma, + int count, ServerActiveObject *player); }; diff --git a/src/script/cpp_api/s_security.cpp b/src/script/cpp_api/s_security.cpp index 21bc7eb0a..9d65819c0 100644 --- a/src/script/cpp_api/s_security.cpp +++ b/src/script/cpp_api/s_security.cpp @@ -29,20 +29,19 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <string> #include <iostream> -#define SECURE_API(lib, name) \ - lua_pushcfunction(L, sl_##lib##_##name); \ + +#define SECURE_API(lib, name) \ + lua_pushcfunction(L, sl_##lib##_##name); \ lua_setfield(L, -2, #name); -static inline void copy_safe(lua_State *L, const char *list[], unsigned len, - int from = -2, int to = -1) + +static inline void copy_safe(lua_State *L, const char *list[], unsigned len, int from=-2, int to=-1) { - if (from < 0) - from = lua_gettop(L) + from + 1; - if (to < 0) - to = lua_gettop(L) + to + 1; + if (from < 0) from = lua_gettop(L) + from + 1; + if (to < 0) to = lua_gettop(L) + to + 1; for (unsigned i = 0; i < (len / sizeof(list[0])); i++) { lua_getfield(L, from, list[i]); - lua_setfield(L, to, list[i]); + lua_setfield(L, to, list[i]); } } @@ -51,90 +50,91 @@ static inline void push_original(lua_State *L, const char *lib, const char *func { lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP); lua_getfield(L, -1, lib); - lua_remove(L, -2); // Remove globals_backup + lua_remove(L, -2); // Remove globals_backup lua_getfield(L, -1, func); - lua_remove(L, -2); // Remove lib + lua_remove(L, -2); // Remove lib } + void ScriptApiSecurity::initializeSecurity() { static const char *whitelist[] = { - "assert", - "core", - "collectgarbage", - "DIR_DELIM", - "error", - "getfenv", - "getmetatable", - "ipairs", - "next", - "pairs", - "pcall", - "print", - "rawequal", - "rawget", - "rawset", - "select", - "setfenv", - "setmetatable", - "tonumber", - "tostring", - "type", - "unpack", - "_VERSION", - "xpcall", - // Completely safe libraries - "coroutine", - "string", - "table", - "math", + "assert", + "core", + "collectgarbage", + "DIR_DELIM", + "error", + "getfenv", + "getmetatable", + "ipairs", + "next", + "pairs", + "pcall", + "print", + "rawequal", + "rawget", + "rawset", + "select", + "setfenv", + "setmetatable", + "tonumber", + "tostring", + "type", + "unpack", + "_VERSION", + "xpcall", + // Completely safe libraries + "coroutine", + "string", + "table", + "math", }; static const char *io_whitelist[] = { - "open", - "close", - "flush", - "read", - "type", - "write", + "open", + "close", + "flush", + "read", + "type", + "write", }; static const char *os_whitelist[] = { - "clock", - "date", - "difftime", - "getenv", - "setlocale", - "time", - "tmpname", + "clock", + "date", + "difftime", + "getenv", + "setlocale", + "time", + "tmpname", }; static const char *debug_whitelist[] = { - "gethook", - "traceback", - "getinfo", - "getmetatable", - "setupvalue", - "setmetatable", - "upvalueid", - "sethook", - "debug", - "setlocal", + "gethook", + "traceback", + "getinfo", + "getmetatable", + "setupvalue", + "setmetatable", + "upvalueid", + "sethook", + "debug", + "setlocal", }; static const char *package_whitelist[] = { - "config", - "cpath", - "path", - "searchpath", + "config", + "cpath", + "path", + "searchpath", }; #if USE_LUAJIT static const char *jit_whitelist[] = { - "arch", - "flush", - "off", - "on", - "opt", - "os", - "status", - "version", - "version_num", + "arch", + "flush", + "off", + "on", + "opt", + "os", + "status", + "version", + "version_num", }; #endif m_secure = true; @@ -154,6 +154,7 @@ void ScriptApiSecurity::initializeSecurity() lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP); int old_globals = lua_gettop(L); + // Copy safe base functions lua_getglobal(L, "_G"); copy_safe(L, whitelist, sizeof(whitelist)); @@ -166,19 +167,21 @@ void ScriptApiSecurity::initializeSecurity() SECURE_API(g, require); lua_pop(L, 1); + // Copy safe IO functions lua_getfield(L, old_globals, "io"); lua_newtable(L); copy_safe(L, io_whitelist, sizeof(io_whitelist)); // And replace unsafe ones - // SECURE_API(io, open); + //SECURE_API(io, open); SECURE_API(io, input); SECURE_API(io, output); SECURE_API(io, lines); lua_setglobal(L, "io"); - lua_pop(L, 1); // Pop old IO + lua_pop(L, 1); // Pop old IO + // Copy safe OS functions lua_getfield(L, old_globals, "os"); @@ -190,21 +193,23 @@ void ScriptApiSecurity::initializeSecurity() SECURE_API(os, rename); lua_setglobal(L, "os"); - lua_pop(L, 1); // Pop old OS + lua_pop(L, 1); // Pop old OS + // Copy safe debug functions lua_getfield(L, old_globals, "debug"); lua_newtable(L); copy_safe(L, debug_whitelist, sizeof(debug_whitelist)); lua_setglobal(L, "debug"); - lua_pop(L, 1); // Pop old debug + lua_pop(L, 1); // Pop old debug + // Copy safe package fields lua_getfield(L, old_globals, "package"); lua_newtable(L); copy_safe(L, package_whitelist, sizeof(package_whitelist)); lua_setglobal(L, "package"); - lua_pop(L, 1); // Pop old package + lua_pop(L, 1); // Pop old package #if USE_LUAJIT // Copy safe jit functions, if they exist @@ -214,7 +219,7 @@ void ScriptApiSecurity::initializeSecurity() copy_safe(L, jit_whitelist, sizeof(jit_whitelist)); lua_setglobal(L, "jit"); } - lua_pop(L, 1); // Pop old jit + lua_pop(L, 1); // Pop old jit #endif lua_pop(L, 1); // Pop globals_backup @@ -223,49 +228,57 @@ void ScriptApiSecurity::initializeSecurity() void ScriptApiSecurity::initializeSecurityClient() { static const char *whitelist[] = { - "assert", - "core", - "collectgarbage", - "DIR_DELIM", - "error", - "getfenv", - "ipairs", - "next", - "pairs", - "pcall", - "print", - "rawequal", - "rawget", - "rawset", - "select", - "setfenv", - // getmetatable can be used to escape the sandbox - "setmetatable", - "tonumber", - "tostring", - "type", - "unpack", - "_VERSION", - "xpcall", - // Completely safe libraries - "coroutine", - "string", - "table", - "math", + "assert", + "core", + "collectgarbage", + "DIR_DELIM", + "error", + "getfenv", + "ipairs", + "next", + "pairs", + "pcall", + "print", + "rawequal", + "rawget", + "rawset", + "select", + "setfenv", + // getmetatable can be used to escape the sandbox + "setmetatable", + "tonumber", + "tostring", + "type", + "unpack", + "_VERSION", + "xpcall", + // Completely safe libraries + "coroutine", + "string", + "table", + "math", + }; + static const char *os_whitelist[] = { + "clock", + "date", + "difftime", + "time" + }; + static const char *debug_whitelist[] = { + "getinfo", + "traceback" }; - static const char *os_whitelist[] = {"clock", "date", "difftime", "time"}; - static const char *debug_whitelist[] = {"getinfo", "traceback"}; #if USE_LUAJIT static const char *jit_whitelist[] = { - "arch", - "flush", - "off", - "on", - "opt", - "os", - "status", - "version", - "version_num", + "arch", + "flush", + "off", + "on", + "opt", + "os", + "status", + "version", + "version_num", }; #endif @@ -299,14 +312,16 @@ void ScriptApiSecurity::initializeSecurityClient() lua_newtable(L); copy_safe(L, os_whitelist, sizeof(os_whitelist)); lua_setfield(L, -3, "os"); - lua_pop(L, 1); // Pop old OS + lua_pop(L, 1); // Pop old OS + // Copy safe debug functions lua_getglobal(L, "debug"); lua_newtable(L); copy_safe(L, debug_whitelist, sizeof(debug_whitelist)); lua_setfield(L, -3, "debug"); - lua_pop(L, 1); // Pop old debug + lua_pop(L, 1); // Pop old debug + #if USE_LUAJIT // Copy safe jit functions, if they exist @@ -314,7 +329,7 @@ void ScriptApiSecurity::initializeSecurityClient() lua_newtable(L); copy_safe(L, jit_whitelist, sizeof(jit_whitelist)); lua_setfield(L, -3, "jit"); - lua_pop(L, 1); // Pop old jit + lua_pop(L, 1); // Pop old jit #endif // Set the environment to the one we created earlier @@ -324,9 +339,9 @@ void ScriptApiSecurity::initializeSecurityClient() int ScriptApiSecurity::getThread(lua_State *L) { #if LUA_VERSION_NUM <= 501 - int is_main = lua_pushthread(L); // Push the main thread + int is_main = lua_pushthread(L); // Push the main thread FATAL_ERROR_IF(!is_main, "Security: ScriptApi's Lua state " - "isn't the main Lua thread!"); + "isn't the main Lua thread!"); return lua_gettop(L); #endif return 0; @@ -334,21 +349,21 @@ int ScriptApiSecurity::getThread(lua_State *L) void ScriptApiSecurity::createEmptyEnv(lua_State *L) { - lua_newtable(L); // Create new environment + lua_newtable(L); // Create new environment lua_pushvalue(L, -1); - lua_setfield(L, -2, "_G"); // Create the _G loop + lua_setfield(L, -2, "_G"); // Create the _G loop } void ScriptApiSecurity::setLuaEnv(lua_State *L, int thread) { -#if LUA_VERSION_NUM >= 502 // Lua >= 5.2 +#if LUA_VERSION_NUM >= 502 // Lua >= 5.2 // Set the global environment lua_rawseti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS); -#else // Lua <= 5.1 - // Set the environment of the main thread +#else // Lua <= 5.1 + // Set the environment of the main thread FATAL_ERROR_IF(!lua_setfenv(L, thread), "Security: Unable to set " - "environment of the main Lua thread!"); - lua_pop(L, 1); // Pop thread + "environment of the main Lua thread!"); + lua_pop(L, 1); // Pop thread #endif } @@ -360,8 +375,7 @@ bool ScriptApiSecurity::isSecure(lua_State *L) return secure; } -bool ScriptApiSecurity::safeLoadString( - lua_State *L, const std::string &code, const char *chunk_name) +bool ScriptApiSecurity::safeLoadString(lua_State *L, const std::string &code, const char *chunk_name) { if (code.size() > 0 && code[0] == LUA_SIGNATURE[0]) { lua_pushliteral(L, "Bytecode prohibited when mod security is enabled."); @@ -372,8 +386,7 @@ bool ScriptApiSecurity::safeLoadString( return true; } -bool ScriptApiSecurity::safeLoadFile( - lua_State *L, const char *path, const char *display_name) +bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char *display_name) { FILE *fp; char *chunk_name; @@ -398,8 +411,7 @@ bool ScriptApiSecurity::safeLoadFile( int c = std::getc(fp); if (c == '#') { // Skip the first line - while ((c = std::getc(fp)) != EOF && c != '\n') { - } + while ((c = std::getc(fp)) != EOF && c != '\n') {} if (c == '\n') std::getc(fp); start = std::ftell(fp); @@ -411,7 +423,7 @@ bool ScriptApiSecurity::safeLoadFile( lua_pushfstring(L, "%s: %s", path, strerror(errno)); if (path) { std::fclose(fp); - delete[] chunk_name; + delete [] chunk_name; } return false; } @@ -423,7 +435,7 @@ bool ScriptApiSecurity::safeLoadFile( lua_pushfstring(L, "%s: %s", path, strerror(errno)); if (path) { std::fclose(fp); - delete[] chunk_name; + delete [] chunk_name; } return false; } @@ -434,31 +446,31 @@ bool ScriptApiSecurity::safeLoadFile( if (num_read != size) { lua_pushliteral(L, "Error reading file to load."); if (path) - delete[] chunk_name; + delete [] chunk_name; return false; } bool result = safeLoadString(L, code, chunk_name); if (path) - delete[] chunk_name; + delete [] chunk_name; return result; } -bool ScriptApiSecurity::checkPath( - lua_State *L, const char *path, bool write_required, bool *write_allowed) + +bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, + bool write_required, bool *write_allowed) { if (write_allowed) *write_allowed = false; - std::string str; // Transient + std::string str; // Transient std::string abs_path = fs::AbsolutePath(path); if (!abs_path.empty()) { // Don't allow accessing the settings file str = fs::AbsolutePath(g_settings_path); - if (str == abs_path) - return false; + if (str == abs_path) return false; } // If we couldn't find the absolute path (path doesn't exist) then @@ -470,18 +482,15 @@ bool ScriptApiSecurity::checkPath( std::string component; cur_path = fs::RemoveLastPathComponent(cur_path, &component); if (component == "..") { - // Parent components can't be allowed or we could allow something - // like + // Parent components can't be allowed or we could allow something like // /home/user/minetest/worlds/foo/noexist/../../../../../../etc/passwd. - // If we have previous non-relative elements in the path we might - // be able to remove them so that things like - // worlds/foo/noexist/../auth.txt could be allowed, but those - // paths will be interpreted as nonexistent by the operating - // system anyways. + // If we have previous non-relative elements in the path we might be + // able to remove them so that things like worlds/foo/noexist/../auth.txt + // could be allowed, but those paths will be interpreted as nonexistent + // by the operating system anyways. return false; } - removed.append(component).append( - removed.empty() ? "" : DIR_DELIM + removed); + removed.append(component).append(removed.empty() ? "" : DIR_DELIM + removed); abs_path = fs::AbsolutePath(cur_path); } if (abs_path.empty()) @@ -495,9 +504,9 @@ bool ScriptApiSecurity::checkPath( lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI); ScriptApiBase *script; #if INDIRECT_SCRIPTAPI_RIDX - script = (ScriptApiBase *)*(void **)(lua_touserdata(L, -1)); + script = (ScriptApiBase *) *(void**)(lua_touserdata(L, -1)); #else - script = (ScriptApiBase *)lua_touserdata(L, -1); + script = (ScriptApiBase *) lua_touserdata(L, -1); #endif lua_pop(L, 1); const IGameDef *gamedef = script->getGameDef(); @@ -511,27 +520,24 @@ bool ScriptApiSecurity::checkPath( // Builtin can access anything if (mod_name == BUILTIN_MOD_NAME) { - if (write_allowed) - *write_allowed = true; + if (write_allowed) *write_allowed = true; return true; } // Allow paths in mod path - // Don't bother if write access isn't important, since it will be handled - // later + // Don't bother if write access isn't important, since it will be handled later if (write_required || write_allowed != NULL) { const ModSpec *mod = gamedef->getModSpec(mod_name); if (mod) { str = fs::AbsolutePath(mod->path); if (!str.empty() && fs::PathStartsWith(abs_path, str)) { - if (write_allowed) - *write_allowed = true; + if (write_allowed) *write_allowed = true; return true; } } } } - lua_pop(L, 1); // Pop mod name + lua_pop(L, 1); // Pop mod name // Allow read-only access to all mod directories if (!write_required) { @@ -558,8 +564,7 @@ bool ScriptApiSecurity::checkPath( } // Allow all other paths in world path if (fs::PathStartsWith(abs_path, str)) { - if (write_allowed) - *write_allowed = true; + if (write_allowed) *write_allowed = true; return true; } } @@ -568,6 +573,7 @@ bool ScriptApiSecurity::checkPath( return false; } + int ScriptApiSecurity::sl_g_dofile(lua_State *L) { int nret = sl_g_loadfile(L); @@ -582,6 +588,7 @@ int ScriptApiSecurity::sl_g_dofile(lua_State *L) return lua_gettop(L) - (top_precall - 1); } + int ScriptApiSecurity::sl_g_load(lua_State *L) { size_t len; @@ -620,11 +627,12 @@ int ScriptApiSecurity::sl_g_load(lua_State *L) return 1; } + int ScriptApiSecurity::sl_g_loadfile(lua_State *L) { #ifndef SERVER lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI); - ScriptApiBase *script = (ScriptApiBase *)lua_touserdata(L, -1); + ScriptApiBase *script = (ScriptApiBase *) lua_touserdata(L, -1); lua_pop(L, 1); // Client implementation @@ -664,6 +672,7 @@ int ScriptApiSecurity::sl_g_loadfile(lua_State *L) return 1; } + int ScriptApiSecurity::sl_g_loadstring(lua_State *L) { const char *chunk_name = "=(load)"; @@ -686,12 +695,14 @@ int ScriptApiSecurity::sl_g_loadstring(lua_State *L) return 1; } + int ScriptApiSecurity::sl_g_require(lua_State *L) { lua_pushliteral(L, "require() is disabled when mod security is on."); return lua_error(L); } + int ScriptApiSecurity::sl_io_open(lua_State *L) { bool with_mode = lua_gettop(L) > 1; @@ -704,7 +715,8 @@ int ScriptApiSecurity::sl_io_open(lua_State *L) luaL_checktype(L, 2, LUA_TSTRING); const char *mode = lua_tostring(L, 2); write_requested = strchr(mode, 'w') != NULL || - strchr(mode, '+') != NULL || strchr(mode, 'a') != NULL; + strchr(mode, '+') != NULL || + strchr(mode, 'a') != NULL; } CHECK_SECURE_PATH_INTERNAL(L, path, write_requested, NULL); @@ -718,6 +730,7 @@ int ScriptApiSecurity::sl_io_open(lua_State *L) return 2; } + int ScriptApiSecurity::sl_io_input(lua_State *L) { if (lua_isstring(L, 1)) { @@ -731,6 +744,7 @@ int ScriptApiSecurity::sl_io_input(lua_State *L) return 1; } + int ScriptApiSecurity::sl_io_output(lua_State *L) { if (lua_isstring(L, 1)) { @@ -744,6 +758,7 @@ int ScriptApiSecurity::sl_io_output(lua_State *L) return 1; } + int ScriptApiSecurity::sl_io_lines(lua_State *L) { if (lua_isstring(L, 1)) { @@ -760,6 +775,7 @@ int ScriptApiSecurity::sl_io_lines(lua_State *L) return lua_gettop(L) - top_precall; } + int ScriptApiSecurity::sl_os_rename(lua_State *L) { luaL_checktype(L, 1, LUA_TSTRING); @@ -777,6 +793,7 @@ int ScriptApiSecurity::sl_os_rename(lua_State *L) return 2; } + int ScriptApiSecurity::sl_os_remove(lua_State *L) { luaL_checktype(L, 1, LUA_TSTRING); @@ -788,3 +805,4 @@ int ScriptApiSecurity::sl_os_remove(lua_State *L) lua_call(L, 1, 2); return 2; } + diff --git a/src/script/cpp_api/s_security.h b/src/script/cpp_api/s_security.h index 075950845..73e763548 100644 --- a/src/script/cpp_api/s_security.h +++ b/src/script/cpp_api/s_security.h @@ -21,20 +21,22 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "cpp_api/s_base.h" -#define CHECK_SECURE_PATH_INTERNAL(L, path, write_required, ptr) \ - if (!ScriptApiSecurity::checkPath(L, path, write_required, ptr)) { \ - throw LuaError(std::string("Mod security: Blocked attempted ") + \ - (write_required ? "write to " : "read from ") + path); \ + +#define CHECK_SECURE_PATH_INTERNAL(L, path, write_required, ptr) \ + if (!ScriptApiSecurity::checkPath(L, path, write_required, ptr)) { \ + throw LuaError(std::string("Mod security: Blocked attempted ") + \ + (write_required ? "write to " : "read from ") + path); \ } -#define CHECK_SECURE_PATH(L, path, write_required) \ - if (ScriptApiSecurity::isSecure(L)) { \ - CHECK_SECURE_PATH_INTERNAL(L, path, write_required, NULL); \ +#define CHECK_SECURE_PATH(L, path, write_required) \ + if (ScriptApiSecurity::isSecure(L)) { \ + CHECK_SECURE_PATH_INTERNAL(L, path, write_required, NULL); \ } -#define CHECK_SECURE_PATH_POSSIBLE_WRITE(L, path, ptr) \ - if (ScriptApiSecurity::isSecure(L)) { \ - CHECK_SECURE_PATH_INTERNAL(L, path, false, ptr); \ +#define CHECK_SECURE_PATH_POSSIBLE_WRITE(L, path, ptr) \ + if (ScriptApiSecurity::isSecure(L)) { \ + CHECK_SECURE_PATH_INTERNAL(L, path, false, ptr); \ } + class ScriptApiSecurity : virtual public ScriptApiBase { public: @@ -49,14 +51,12 @@ public: // Checks if the Lua state has been secured static bool isSecure(lua_State *L); // Loads a string as Lua code safely (doesn't allow bytecode). - static bool safeLoadString( - lua_State *L, const std::string &code, const char *chunk_name); + static bool safeLoadString(lua_State *L, const std::string &code, const char *chunk_name); // Loads a file as Lua code safely (doesn't allow bytecode). - static bool safeLoadFile( - lua_State *L, const char *path, const char *display_name = NULL); + static bool safeLoadFile(lua_State *L, const char *path, const char *display_name = NULL); // Checks if mods are allowed to read (and optionally write) to the path static bool checkPath(lua_State *L, const char *path, bool write_required, - bool *write_allowed = NULL); + bool *write_allowed=NULL); private: // Syntax: "sl_" <Library name or 'g' (global)> '_' <Function name> diff --git a/src/script/cpp_api/s_server.cpp b/src/script/cpp_api/s_server.cpp index 1cb3f99f1..96cb28b28 100644 --- a/src/script/cpp_api/s_server.cpp +++ b/src/script/cpp_api/s_server.cpp @@ -21,8 +21,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "cpp_api/s_internal.h" #include "common/c_converter.h" -bool ScriptApiServer::getAuth(const std::string &playername, std::string *dst_password, - std::set<std::string> *dst_privs, s64 *dst_last_login) +bool ScriptApiServer::getAuth(const std::string &playername, + std::string *dst_password, + std::set<std::string> *dst_privs, + s64 *dst_last_login) { SCRIPTAPI_PRECHECKHEADER @@ -52,10 +54,10 @@ bool ScriptApiServer::getAuth(const std::string &playername, std::string *dst_pa throw LuaError("Authentication handler didn't return privilege table"); if (dst_privs) readPrivileges(-1, *dst_privs); - lua_pop(L, 1); // Remove key from privs table + lua_pop(L, 1); // Remove key from privs table s64 last_login; - if (!getintfield(L, -1, "last_login", last_login)) + if(!getintfield(L, -1, "last_login", last_login)) throw LuaError("Authentication handler didn't return last_login"); if (dst_last_login) *dst_last_login = (s64)last_login; @@ -69,7 +71,7 @@ void ScriptApiServer::getAuthHandler() lua_getglobal(L, "core"); lua_getfield(L, -1, "registered_auth_handler"); - if (lua_isnil(L, -1)) { + if (lua_isnil(L, -1)){ lua_pop(L, 1); lua_getfield(L, -1, "builtin_auth_handler"); } @@ -100,8 +102,8 @@ void ScriptApiServer::readPrivileges(int index, std::set<std::string> &result) } } -void ScriptApiServer::createAuth( - const std::string &playername, const std::string &password) +void ScriptApiServer::createAuth(const std::string &playername, + const std::string &password) { SCRIPTAPI_PRECHECKHEADER @@ -117,8 +119,8 @@ void ScriptApiServer::createAuth( lua_pop(L, 1); // Pop error handler } -bool ScriptApiServer::setPassword( - const std::string &playername, const std::string &password) +bool ScriptApiServer::setPassword(const std::string &playername, + const std::string &password) { SCRIPTAPI_PRECHECKHEADER @@ -135,7 +137,8 @@ bool ScriptApiServer::setPassword( return lua_toboolean(L, -1); } -bool ScriptApiServer::on_chat_message(const std::string &name, const std::string &message) +bool ScriptApiServer::on_chat_message(const std::string &name, + const std::string &message) { SCRIPTAPI_PRECHECKHEADER @@ -171,8 +174,8 @@ void ScriptApiServer::on_shutdown() runCallbacks(0, RUN_CALLBACKS_MODE_FIRST); } -std::string ScriptApiServer::formatChatMessage( - const std::string &name, const std::string &message) +std::string ScriptApiServer::formatChatMessage(const std::string &name, + const std::string &message) { SCRIPTAPI_PRECHECKHEADER diff --git a/src/script/cpp_api/s_server.h b/src/script/cpp_api/s_server.h index db574bd56..d8639cba7 100644 --- a/src/script/cpp_api/s_server.h +++ b/src/script/cpp_api/s_server.h @@ -22,7 +22,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "cpp_api/s_base.h" #include <set> -class ScriptApiServer : virtual public ScriptApiBase +class ScriptApiServer + : virtual public ScriptApiBase { public: // Calls on_chat_message handlers @@ -36,15 +37,18 @@ public: void on_shutdown(); // Calls core.format_chat_message - std::string formatChatMessage( - const std::string &name, const std::string &message); + std::string formatChatMessage(const std::string &name, + const std::string &message); /* auth */ - bool getAuth(const std::string &playername, std::string *dst_password, - std::set<std::string> *dst_privs, s64 *dst_last_login = nullptr); - void createAuth(const std::string &playername, const std::string &password); - bool setPassword(const std::string &playername, const std::string &password); - + bool getAuth(const std::string &playername, + std::string *dst_password, + std::set<std::string> *dst_privs, + s64 *dst_last_login = nullptr); + void createAuth(const std::string &playername, + const std::string &password); + bool setPassword(const std::string &playername, + const std::string &password); private: void getAuthHandler(); void readPrivileges(int index, std::set<std::string> &result); diff --git a/src/script/lua_api/l_areastore.cpp b/src/script/lua_api/l_areastore.cpp index d043bfc90..908c766b0 100644 --- a/src/script/lua_api/l_areastore.cpp +++ b/src/script/lua_api/l_areastore.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "lua_api/l_areastore.h" #include "lua_api/l_internal.h" #include "common/c_converter.h" @@ -26,8 +27,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "filesys.h" #include <fstream> -static inline void get_data_and_border_flags( - lua_State *L, u8 start_i, bool *borders, bool *data) +static inline void get_data_and_border_flags(lua_State *L, u8 start_i, + bool *borders, bool *data) { if (!lua_isboolean(L, start_i)) return; @@ -37,8 +38,8 @@ static inline void get_data_and_border_flags( *data = lua_toboolean(L, start_i + 1); } -static void push_area( - lua_State *L, const Area *a, bool include_borders, bool include_data) +static void push_area(lua_State *L, const Area *a, + bool include_borders, bool include_data) { if (!include_borders && !include_data) { lua_pushboolean(L, true); @@ -57,8 +58,8 @@ static void push_area( } } -static inline void push_areas( - lua_State *L, const std::vector<Area *> &areas, bool borders, bool data) +static inline void push_areas(lua_State *L, const std::vector<Area *> &areas, + bool borders, bool data) { lua_newtable(L); size_t cnt = areas.size(); @@ -70,7 +71,8 @@ static inline void push_areas( } // Deserializes value and handles errors -static int deserialization_helper(lua_State *L, AreaStore *as, std::istream &is) +static int deserialization_helper(lua_State *L, AreaStore *as, + std::istream &is) { try { as->deserialize(is); @@ -326,9 +328,9 @@ int LuaAreaStore::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; - LuaAreaStore *o = (lua_isstring(L, 1)) - ? new LuaAreaStore(readParam<std::string>(L, 1)) - : new LuaAreaStore(); + LuaAreaStore *o = (lua_isstring(L, 1)) ? + new LuaAreaStore(readParam<std::string>(L, 1)) : + new LuaAreaStore(); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); @@ -346,7 +348,7 @@ LuaAreaStore *LuaAreaStore::checkobject(lua_State *L, int narg) if (!ud) luaL_typerror(L, narg, className); - return *(LuaAreaStore **)ud; // unbox pointer + return *(LuaAreaStore **)ud; // unbox pointer } void LuaAreaStore::Register(lua_State *L) @@ -358,7 +360,7 @@ void LuaAreaStore::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -368,22 +370,27 @@ void LuaAreaStore::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Can be created from Lua (AreaStore()) lua_register(L, className, create_object); } const char LuaAreaStore::className[] = "AreaStore"; -const luaL_Reg LuaAreaStore::methods[] = {luamethod(LuaAreaStore, get_area), - luamethod(LuaAreaStore, get_areas_for_pos), - luamethod(LuaAreaStore, get_areas_in_area), - luamethod(LuaAreaStore, insert_area), luamethod(LuaAreaStore, reserve), - luamethod(LuaAreaStore, remove_area), - luamethod(LuaAreaStore, set_cache_params), - luamethod(LuaAreaStore, to_string), luamethod(LuaAreaStore, to_file), - luamethod(LuaAreaStore, from_string), luamethod(LuaAreaStore, from_file), - {0, 0}}; +const luaL_Reg LuaAreaStore::methods[] = { + luamethod(LuaAreaStore, get_area), + luamethod(LuaAreaStore, get_areas_for_pos), + luamethod(LuaAreaStore, get_areas_in_area), + luamethod(LuaAreaStore, insert_area), + luamethod(LuaAreaStore, reserve), + luamethod(LuaAreaStore, remove_area), + luamethod(LuaAreaStore, set_cache_params), + luamethod(LuaAreaStore, to_string), + luamethod(LuaAreaStore, to_file), + luamethod(LuaAreaStore, from_string), + luamethod(LuaAreaStore, from_file), + {0,0} +}; diff --git a/src/script/lua_api/l_base.cpp b/src/script/lua_api/l_base.cpp index 8ae03d6c8..011434845 100644 --- a/src/script/lua_api/l_base.cpp +++ b/src/script/lua_api/l_base.cpp @@ -32,9 +32,9 @@ ScriptApiBase *ModApiBase::getScriptApiBase(lua_State *L) lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI); ScriptApiBase *sapi_ptr; #if INDIRECT_SCRIPTAPI_RIDX - sapi_ptr = (ScriptApiBase *)*(void **)(lua_touserdata(L, -1)); + sapi_ptr = (ScriptApiBase*) *(void**)(lua_touserdata(L, -1)); #else - sapi_ptr = (ScriptApiBase *)lua_touserdata(L, -1); + sapi_ptr = (ScriptApiBase*) lua_touserdata(L, -1); #endif lua_pop(L, 1); return sapi_ptr; @@ -93,8 +93,9 @@ std::string ModApiBase::getCurrentModPath(lua_State *L) return mod->path; } -bool ModApiBase::registerFunction( - lua_State *L, const char *name, lua_CFunction func, int top) + +bool ModApiBase::registerFunction(lua_State *L, const char *name, + lua_CFunction func, int top) { // TODO: Check presence first! @@ -125,7 +126,7 @@ int ModApiBase::l_deprecated_function(lua_State *L) // Get parent class to get the wrappers map luaL_checktype(L, 1, LUA_TUSERDATA); void *ud = lua_touserdata(L, 1); - ModApiBase *o = *(ModApiBase **)ud; + ModApiBase *o = *(ModApiBase**)ud; // New function and new function name auto it = o->m_deprecated_wrappers.find(ar.name); @@ -135,13 +136,12 @@ int ModApiBase::l_deprecated_function(lua_State *L) backtrace.append(":").append(std::to_string(ar.currentline)); u64 hash = murmur_hash_64_ua(backtrace.data(), backtrace.length(), 0xBADBABE); - if (std::find(deprecated_logged.begin(), deprecated_logged.end(), hash) == - deprecated_logged.end()) { + if (std::find(deprecated_logged.begin(), deprecated_logged.end(), hash) + == deprecated_logged.end()) { deprecated_logged.emplace_back(hash); - warningstream << "Call to deprecated function '" << ar.name - << "', please use '" << it->second.name << "' at " - << backtrace << std::endl; + warningstream << "Call to deprecated function '" << ar.name << "', please use '" + << it->second.name << "' at " << backtrace << std::endl; if (m_error_deprecated_calls) script_error(L, LUA_ERRRUN, NULL, NULL); @@ -172,8 +172,8 @@ void ModApiBase::markAliasDeprecated(luaL_Reg *reg) // Do not inline struct. Breaks MSVC or is error-prone original_reg.name = last_name; original_reg.func = reg->func; - m_deprecated_wrappers.emplace(std::pair<std::string, luaL_Reg>( - reg->name, original_reg)); + m_deprecated_wrappers.emplace( + std::pair<std::string, luaL_Reg>(reg->name, original_reg)); reg->func = l_deprecated_function; } diff --git a/src/script/lua_api/l_base.h b/src/script/lua_api/l_base.h index bb806d631..0cbee7756 100644 --- a/src/script/lua_api/l_base.h +++ b/src/script/lua_api/l_base.h @@ -41,44 +41,43 @@ class Server; class Environment; class ServerInventoryManager; -class ModApiBase : protected LuaHelper -{ +class ModApiBase : protected LuaHelper { public: - static ScriptApiBase *getScriptApiBase(lua_State *L); - static Server *getServer(lua_State *L); + static ScriptApiBase* getScriptApiBase(lua_State *L); + static Server* getServer(lua_State *L); static ServerInventoryManager *getServerInventoryMgr(lua_State *L); -#ifndef SERVER - static Client *getClient(lua_State *L); - static Game *getGame(lua_State *L); - static GUIEngine *getGuiEngine(lua_State *L); -#endif // !SERVER + #ifndef SERVER + static Client* getClient(lua_State *L); + static Game* getGame(lua_State *L); + static GUIEngine* getGuiEngine(lua_State *L); + #endif // !SERVER - static IGameDef *getGameDef(lua_State *L); - static Environment *getEnv(lua_State *L); + static IGameDef* getGameDef(lua_State *L); + static Environment* getEnv(lua_State *L); // When we are not loading the mod, this function returns "." - static std::string getCurrentModPath(lua_State *L); + static std::string getCurrentModPath(lua_State *L); // Get an arbitrary subclass of ScriptApiBase // by using dynamic_cast<> on getScriptApiBase() - template <typename T> static T *getScriptApi(lua_State *L) - { + template<typename T> + static T* getScriptApi(lua_State *L) { ScriptApiBase *scriptIface = getScriptApiBase(L); - T *scriptIfaceDowncast = dynamic_cast<T *>(scriptIface); + T *scriptIfaceDowncast = dynamic_cast<T*>(scriptIface); if (!scriptIfaceDowncast) { - throw LuaError("Requested unavailable ScriptApi - core engine " - "bug!"); + throw LuaError("Requested unavailable ScriptApi - core engine bug!"); } return scriptIfaceDowncast; } - static bool registerFunction( - lua_State *L, const char *name, lua_CFunction func, int top); + static bool registerFunction(lua_State *L, + const char* name, + lua_CFunction func, + int top); static int l_deprecated_function(lua_State *L); static void markAliasDeprecated(luaL_Reg *reg); - private: // <old_name> = { <new_name>, <new_function> } static std::unordered_map<std::string, luaL_Reg> m_deprecated_wrappers; diff --git a/src/script/lua_api/l_client.cpp b/src/script/lua_api/l_client.cpp index 44311be68..05bfcca52 100644 --- a/src/script/lua_api/l_client.cpp +++ b/src/script/lua_api/l_client.cpp @@ -38,12 +38,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "nodedef.h" #include "client/keycode.h" -#define checkCSMRestrictionFlag(flag) \ - (getClient(L)->checkCSMRestrictionFlag(CSMRestrictionFlags::flag)) +#define checkCSMRestrictionFlag(flag) \ + ( getClient(L)->checkCSMRestrictionFlag(CSMRestrictionFlags::flag) ) // Not the same as FlagDesc, which contains an `u32 flag` -struct CSMFlagDesc -{ +struct CSMFlagDesc { const char *name; u64 flag; }; @@ -54,12 +53,14 @@ struct CSMFlagDesc in network/networkprotocol.h */ const static CSMFlagDesc flagdesc_csm_restriction[] = { - {"load_client_mods", CSM_RF_LOAD_CLIENT_MODS}, - {"chat_messages", CSM_RF_CHAT_MESSAGES}, - {"read_itemdefs", CSM_RF_READ_ITEMDEFS}, - {"read_nodedefs", CSM_RF_READ_NODEDEFS}, - {"lookup_nodes", CSM_RF_LOOKUP_NODES}, - {"read_playerinfo", CSM_RF_READ_PLAYERINFO}, {NULL, 0}}; + {"load_client_mods", CSM_RF_LOAD_CLIENT_MODS}, + {"chat_messages", CSM_RF_CHAT_MESSAGES}, + {"read_itemdefs", CSM_RF_READ_ITEMDEFS}, + {"read_nodedefs", CSM_RF_READ_NODEDEFS}, + {"lookup_nodes", CSM_RF_LOOKUP_NODES}, + {"read_playerinfo", CSM_RF_READ_PLAYERINFO}, + {NULL, 0} +}; // get_current_modname() int ModApiClient::l_get_current_modname(lua_State *L) @@ -421,7 +422,7 @@ int ModApiClient::l_send_damage(lua_State *L) { u16 damage = luaL_checknumber(L, 1); getClient(L)->sendDamage(damage); - return 0; + return 0; } // place_node(pos) @@ -432,8 +433,7 @@ int ModApiClient::l_place_node(lua_State *L) LocalPlayer *player = client->getEnv().getLocalPlayer(); ItemStack selected_item, hand_item; player->getWieldedItem(&selected_item, &hand_item); - const ItemDefinition &selected_def = - selected_item.getDefinition(getGameDef(L)->idef()); + const ItemDefinition &selected_def = selected_item.getDefinition(getGameDef(L)->idef()); v3s16 pos = read_v3s16(L, 1); PointedThing pointed; pointed.type = POINTEDTHING_NODE; @@ -465,7 +465,7 @@ int ModApiClient::l_get_inventory(lua_State *L) InventoryLocation inventory_location; Inventory *inventory; std::string location; - + location = readParam<std::string>(L, 1); try { @@ -475,7 +475,7 @@ int ModApiClient::l_get_inventory(lua_State *L) } catch (SerializationError &) { lua_pushnil(L); } - + return 1; } @@ -508,17 +508,17 @@ int ModApiClient::l_drop_selected_item(lua_State *L) int ModApiClient::l_get_objects_inside_radius(lua_State *L) { ClientEnvironment &env = getClient(L)->getEnv(); - + v3f pos = checkFloatPos(L, 1); float radius = readParam<float>(L, 2) * BS; - + std::vector<DistanceSortedActiveObject> objs; env.getActiveObjects(pos, radius, objs); - + int i = 0; lua_createtable(L, objs.size(), 0); for (const auto obj : objs) { - ClientObjectRef::create(L, obj.obj); // TODO: getObjectRefOrCreate + ClientObjectRef::create(L, obj.obj); // TODO: getObjectRefOrCreate lua_rawseti(L, -2, ++i); } return 1; diff --git a/src/script/lua_api/l_clientobject.cpp b/src/script/lua_api/l_clientobject.cpp index 05b3e2850..d88b538a1 100644 --- a/src/script/lua_api/l_clientobject.cpp +++ b/src/script/lua_api/l_clientobject.cpp @@ -146,7 +146,7 @@ int ClientObjectRef::l_punch(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); - PointedThing pointed(gcao->getId(), v3f(0, 0, 0), v3s16(0, 0, 0), 0); + PointedThing pointed(gcao->getId(), v3f(0,0,0), v3s16(0,0,0), 0); getClient(L)->interact(INTERACT_START_DIGGING, pointed); return 0; } @@ -155,7 +155,7 @@ int ClientObjectRef::l_rightclick(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); - PointedThing pointed(gcao->getId(), v3f(0, 0, 0), v3s16(0, 0, 0), 0); + PointedThing pointed(gcao->getId(), v3f(0,0,0), v3s16(0,0,0), 0); getClient(L)->interact(INTERACT_PLACE, pointed); return 0; } @@ -223,5 +223,6 @@ luaL_Reg ClientObjectRef::methods[] = {luamethod(ClientObjectRef, get_pos), luamethod(ClientObjectRef, get_attach), luamethod(ClientObjectRef, get_nametag), luamethod(ClientObjectRef, get_item_textures), - luamethod(ClientObjectRef, get_max_hp), luamethod(ClientObjectRef, punch), + luamethod(ClientObjectRef, get_max_hp), + luamethod(ClientObjectRef, punch), luamethod(ClientObjectRef, rightclick), {0, 0}}; diff --git a/src/script/lua_api/l_clientobject.h b/src/script/lua_api/l_clientobject.h index a4516e047..521591444 100644 --- a/src/script/lua_api/l_clientobject.h +++ b/src/script/lua_api/l_clientobject.h @@ -60,7 +60,7 @@ private: // is_player(self) static int l_is_player(lua_State *L); - + // is_local_player(self) static int l_is_local_player(lua_State *L); diff --git a/src/script/lua_api/l_craft.cpp b/src/script/lua_api/l_craft.cpp index 07b45eaff..18622ee00 100644 --- a/src/script/lua_api/l_craft.cpp +++ b/src/script/lua_api/l_craft.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "lua_api/l_craft.h" #include "lua_api/l_internal.h" #include "lua_api/l_item.h" @@ -25,45 +26,46 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "server.h" #include "craftdef.h" -struct EnumString ModApiCraft::es_CraftMethod[] = { - {CRAFT_METHOD_NORMAL, "normal"}, - {CRAFT_METHOD_COOKING, "cooking"}, - {CRAFT_METHOD_FUEL, "fuel"}, - {0, NULL}, +struct EnumString ModApiCraft::es_CraftMethod[] = +{ + {CRAFT_METHOD_NORMAL, "normal"}, + {CRAFT_METHOD_COOKING, "cooking"}, + {CRAFT_METHOD_FUEL, "fuel"}, + {0, NULL}, }; // helper for register_craft -bool ModApiCraft::readCraftRecipeShaped( - lua_State *L, int index, int &width, std::vector<std::string> &recipe) +bool ModApiCraft::readCraftRecipeShaped(lua_State *L, int index, + int &width, std::vector<std::string> &recipe) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; - if (!lua_istable(L, index)) + if(!lua_istable(L, index)) return false; lua_pushnil(L); int rowcount = 0; - while (lua_next(L, index) != 0) { + while(lua_next(L, index) != 0){ int colcount = 0; // key at index -2 and value at index -1 - if (!lua_istable(L, -1)) + if(!lua_istable(L, -1)) return false; int table2 = lua_gettop(L); lua_pushnil(L); - while (lua_next(L, table2) != 0) { + while(lua_next(L, table2) != 0){ // key at index -2 and value at index -1 - if (!lua_isstring(L, -1)) + if(!lua_isstring(L, -1)) return false; recipe.emplace_back(readParam<std::string>(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); colcount++; } - if (rowcount == 0) { + if(rowcount == 0){ width = colcount; } else { - if (colcount != width) + if(colcount != width) return false; } // removes value, keeps key for next iteration @@ -74,19 +76,19 @@ bool ModApiCraft::readCraftRecipeShaped( } // helper for register_craft -bool ModApiCraft::readCraftRecipeShapeless( - lua_State *L, int index, std::vector<std::string> &recipe) +bool ModApiCraft::readCraftRecipeShapeless(lua_State *L, int index, + std::vector<std::string> &recipe) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; - if (!lua_istable(L, index)) + if(!lua_istable(L, index)) return false; lua_pushnil(L); - while (lua_next(L, index) != 0) { + while(lua_next(L, index) != 0){ // key at index -2 and value at index -1 - if (!lua_isstring(L, -1)) + if(!lua_isstring(L, -1)) return false; recipe.emplace_back(readParam<std::string>(L, -1)); // removes value, keeps key for next iteration @@ -96,27 +98,27 @@ bool ModApiCraft::readCraftRecipeShapeless( } // helper for register_craft -bool ModApiCraft::readCraftReplacements( - lua_State *L, int index, CraftReplacements &replacements) +bool ModApiCraft::readCraftReplacements(lua_State *L, int index, + CraftReplacements &replacements) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; - if (!lua_istable(L, index)) + if(!lua_istable(L, index)) return false; lua_pushnil(L); - while (lua_next(L, index) != 0) { + while(lua_next(L, index) != 0){ // key at index -2 and value at index -1 - if (!lua_istable(L, -1)) + if(!lua_istable(L, -1)) return false; lua_rawgeti(L, -1, 1); - if (!lua_isstring(L, -1)) + if(!lua_isstring(L, -1)) return false; std::string replace_from = readParam<std::string>(L, -1); lua_pop(L, 1); lua_rawgeti(L, -1, 2); - if (!lua_isstring(L, -1)) + if(!lua_isstring(L, -1)) return false; std::string replace_to = readParam<std::string>(L, -1); lua_pop(L, 1); @@ -130,19 +132,20 @@ bool ModApiCraft::readCraftReplacements( int ModApiCraft::l_register_craft(lua_State *L) { NO_MAP_LOCK_REQUIRED; - // infostream<<"register_craft"<<std::endl; + //infostream<<"register_craft"<<std::endl; luaL_checktype(L, 1, LUA_TTABLE); int table = 1; // Get the writable craft definition manager from the server - IWritableCraftDefManager *craftdef = getServer(L)->getWritableCraftDefManager(); + IWritableCraftDefManager *craftdef = + getServer(L)->getWritableCraftDefManager(); std::string type = getstringfield_default(L, table, "type", "shaped"); /* CraftDefinitionShaped */ - if (type == "shaped") { + if(type == "shaped"){ std::string output = getstringfield_default(L, table, "output", ""); if (output.empty()) throw LuaError("Crafting definition is missing an output"); @@ -150,22 +153,20 @@ int ModApiCraft::l_register_craft(lua_State *L) int width = 0; std::vector<std::string> recipe; lua_getfield(L, table, "recipe"); - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) throw LuaError("Crafting definition is missing a recipe" - " (output=\"" + - output + "\")"); - if (!readCraftRecipeShaped(L, -1, width, recipe)) + " (output=\"" + output + "\")"); + if(!readCraftRecipeShaped(L, -1, width, recipe)) throw LuaError("Invalid crafting recipe" - " (output=\"" + - output + "\")"); + " (output=\"" + output + "\")"); CraftReplacements replacements; lua_getfield(L, table, "replacements"); - if (!lua_isnil(L, -1)) { - if (!readCraftReplacements(L, -1, replacements)) + if(!lua_isnil(L, -1)) + { + if(!readCraftReplacements(L, -1, replacements)) throw LuaError("Invalid replacements" - " (output=\"" + - output + "\")"); + " (output=\"" + output + "\")"); } CraftDefinition *def = new CraftDefinitionShaped( @@ -175,31 +176,29 @@ int ModApiCraft::l_register_craft(lua_State *L) /* CraftDefinitionShapeless */ - else if (type == "shapeless") { + else if(type == "shapeless"){ std::string output = getstringfield_default(L, table, "output", ""); if (output.empty()) throw LuaError("Crafting definition (shapeless)" - " is missing an output"); + " is missing an output"); std::vector<std::string> recipe; lua_getfield(L, table, "recipe"); - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) throw LuaError("Crafting definition (shapeless)" - " is missing a recipe" - " (output=\"" + - output + "\")"); - if (!readCraftRecipeShapeless(L, -1, recipe)) + " is missing a recipe" + " (output=\"" + output + "\")"); + if(!readCraftRecipeShapeless(L, -1, recipe)) throw LuaError("Invalid crafting recipe" - " (output=\"" + - output + "\")"); + " (output=\"" + output + "\")"); CraftReplacements replacements; lua_getfield(L, table, "replacements"); - if (!lua_isnil(L, -1)) { - if (!readCraftReplacements(L, -1, replacements)) + if(!lua_isnil(L, -1)) + { + if(!readCraftReplacements(L, -1, replacements)) throw LuaError("Invalid replacements" - " (output=\"" + - output + "\")"); + " (output=\"" + output + "\")"); } CraftDefinition *def = new CraftDefinitionShapeless( @@ -209,38 +208,38 @@ int ModApiCraft::l_register_craft(lua_State *L) /* CraftDefinitionToolRepair */ - else if (type == "toolrepair") { - float additional_wear = - getfloatfield_default(L, table, "additional_wear", 0.0); + else if(type == "toolrepair"){ + float additional_wear = getfloatfield_default(L, table, + "additional_wear", 0.0); - CraftDefinition *def = new CraftDefinitionToolRepair(additional_wear); + CraftDefinition *def = new CraftDefinitionToolRepair( + additional_wear); craftdef->registerCraft(def, getServer(L)); } /* CraftDefinitionCooking */ - else if (type == "cooking") { + else if(type == "cooking"){ std::string output = getstringfield_default(L, table, "output", ""); if (output.empty()) throw LuaError("Crafting definition (cooking)" - " is missing an output"); + " is missing an output"); std::string recipe = getstringfield_default(L, table, "recipe", ""); if (recipe.empty()) throw LuaError("Crafting definition (cooking)" - " is missing a recipe" - " (output=\"" + - output + "\")"); + " is missing a recipe" + " (output=\"" + output + "\")"); float cooktime = getfloatfield_default(L, table, "cooktime", 3.0); CraftReplacements replacements; lua_getfield(L, table, "replacements"); - if (!lua_isnil(L, -1)) { - if (!readCraftReplacements(L, -1, replacements)) + if(!lua_isnil(L, -1)) + { + if(!readCraftReplacements(L, -1, replacements)) throw LuaError("Invalid replacements" - " (cooking output=\"" + - output + "\")"); + " (cooking output=\"" + output + "\")"); } CraftDefinition *def = new CraftDefinitionCooking( @@ -250,27 +249,29 @@ int ModApiCraft::l_register_craft(lua_State *L) /* CraftDefinitionFuel */ - else if (type == "fuel") { + else if(type == "fuel"){ std::string recipe = getstringfield_default(L, table, "recipe", ""); if (recipe.empty()) throw LuaError("Crafting definition (fuel)" - " is missing a recipe"); + " is missing a recipe"); float burntime = getfloatfield_default(L, table, "burntime", 1.0); CraftReplacements replacements; lua_getfield(L, table, "replacements"); - if (!lua_isnil(L, -1)) { - if (!readCraftReplacements(L, -1, replacements)) + if(!lua_isnil(L, -1)) + { + if(!readCraftReplacements(L, -1, replacements)) throw LuaError("Invalid replacements" - " (fuel recipe=\"" + - recipe + "\")"); + " (fuel recipe=\"" + recipe + "\")"); } - CraftDefinition *def = - new CraftDefinitionFuel(recipe, burntime, replacements); + CraftDefinition *def = new CraftDefinitionFuel( + recipe, burntime, replacements); craftdef->registerCraft(def, getServer(L)); - } else { + } + else + { throw LuaError("Unknown crafting definition type: \"" + type + "\""); } @@ -286,7 +287,8 @@ int ModApiCraft::l_clear_craft(lua_State *L) int table = 1; // Get the writable craft definition manager from the server - IWritableCraftDefManager *craftdef = getServer(L)->getWritableCraftDefManager(); + IWritableCraftDefManager *craftdef = + getServer(L)->getWritableCraftDefManager(); std::string output = getstringfield_default(L, table, "output", ""); std::string type = getstringfield_default(L, table, "type", "shaped"); @@ -332,7 +334,7 @@ int ModApiCraft::l_clear_craft(lua_State *L) std::string rec = getstringfield_default(L, table, "recipe", ""); if (rec.empty()) throw LuaError("Crafting definition (cooking)" - " is missing a recipe"); + " is missing a recipe"); recipe.push_back(rec); } /* @@ -343,7 +345,7 @@ int ModApiCraft::l_clear_craft(lua_State *L) std::string rec = getstringfield_default(L, table, "recipe", ""); if (rec.empty()) throw LuaError("Crafting definition (fuel)" - " is missing a recipe"); + " is missing a recipe"); recipe.push_back(rec); } else { throw LuaError("Unknown crafting definition type: \"" + type + "\""); @@ -372,15 +374,15 @@ int ModApiCraft::l_get_craft_result(lua_State *L) int input_i = 1; std::string method_s = getstringfield_default(L, input_i, "method", "normal"); - enum CraftMethod method = (CraftMethod)getenumfield( - L, input_i, "method", es_CraftMethod, CRAFT_METHOD_NORMAL); + enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method", + es_CraftMethod, CRAFT_METHOD_NORMAL); int width = 1; lua_getfield(L, input_i, "width"); - if (lua_isnumber(L, -1)) + if(lua_isnumber(L, -1)) width = luaL_checkinteger(L, -1); lua_pop(L, 1); lua_getfield(L, input_i, "items"); - std::vector<ItemStack> items = read_items(L, -1, getServer(L)); + std::vector<ItemStack> items = read_items(L, -1,getServer(L)); lua_pop(L, 1); // items IGameDef *gdef = getServer(L); @@ -415,7 +417,9 @@ int ModApiCraft::l_get_craft_result(lua_State *L) return 2; } -static void push_craft_recipe(lua_State *L, IGameDef *gdef, const CraftDefinition *recipe, + +static void push_craft_recipe(lua_State *L, IGameDef *gdef, + const CraftDefinition *recipe, const CraftOutput &tmpout) { CraftInput input = recipe->getInput(tmpout, gdef); @@ -458,7 +462,8 @@ static void push_craft_recipe(lua_State *L, IGameDef *gdef, const CraftDefinitio } static void push_craft_recipes(lua_State *L, IGameDef *gdef, - const std::vector<CraftDefinition *> &recipes, const CraftOutput &output) + const std::vector<CraftDefinition*> &recipes, + const CraftOutput &output) { lua_createtable(L, recipes.size(), 0); @@ -467,7 +472,7 @@ static void push_craft_recipes(lua_State *L, IGameDef *gdef, return; } - std::vector<CraftDefinition *>::const_iterator it = recipes.begin(); + std::vector<CraftDefinition*>::const_iterator it = recipes.begin(); for (unsigned i = 0; it != recipes.end(); ++it) { lua_newtable(L); push_craft_recipe(L, gdef, *it, output); @@ -475,6 +480,7 @@ static void push_craft_recipes(lua_State *L, IGameDef *gdef, } } + // get_craft_recipe(result item) int ModApiCraft::l_get_craft_recipe(lua_State *L) { @@ -483,8 +489,8 @@ int ModApiCraft::l_get_craft_recipe(lua_State *L) std::string item = luaL_checkstring(L, 1); Server *server = getServer(L); CraftOutput output(item, 0); - std::vector<CraftDefinition *> recipes = - server->cdef()->getCraftRecipes(output, server, 1); + std::vector<CraftDefinition*> recipes = server->cdef() + ->getCraftRecipes(output, server, 1); lua_createtable(L, 1, 0); @@ -506,8 +512,8 @@ int ModApiCraft::l_get_all_craft_recipes(lua_State *L) std::string item = luaL_checkstring(L, 1); Server *server = getServer(L); CraftOutput output(item, 0); - std::vector<CraftDefinition *> recipes = - server->cdef()->getCraftRecipes(output, server); + std::vector<CraftDefinition*> recipes = server->cdef() + ->getCraftRecipes(output, server); push_craft_recipes(L, server, recipes, output); return 1; diff --git a/src/script/lua_api/l_craft.h b/src/script/lua_api/l_craft.h index 5ba3d18fe..9002b23ef 100644 --- a/src/script/lua_api/l_craft.h +++ b/src/script/lua_api/l_craft.h @@ -26,8 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., struct CraftReplacements; -class ModApiCraft : public ModApiBase -{ +class ModApiCraft : public ModApiBase { private: static int l_register_craft(lua_State *L); static int l_get_craft_recipe(lua_State *L); @@ -35,12 +34,12 @@ private: static int l_get_craft_result(lua_State *L); static int l_clear_craft(lua_State *L); - static bool readCraftReplacements( - lua_State *L, int index, CraftReplacements &replacements); - static bool readCraftRecipeShapeless( - lua_State *L, int index, std::vector<std::string> &recipe); - static bool readCraftRecipeShaped(lua_State *L, int index, int &width, + static bool readCraftReplacements(lua_State *L, int index, + CraftReplacements &replacements); + static bool readCraftRecipeShapeless(lua_State *L, int index, std::vector<std::string> &recipe); + static bool readCraftRecipeShaped(lua_State *L, int index, + int &width, std::vector<std::string> &recipe); static struct EnumString es_CraftMethod[]; diff --git a/src/script/lua_api/l_env.cpp b/src/script/lua_api/l_env.cpp index 2c612eb9a..ee384ad10 100644 --- a/src/script/lua_api/l_env.cpp +++ b/src/script/lua_api/l_env.cpp @@ -46,16 +46,18 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/client.h" #endif -struct EnumString ModApiEnvMod::es_ClearObjectsMode[] = { - {CLEAR_OBJECTS_MODE_FULL, "full"}, - {CLEAR_OBJECTS_MODE_QUICK, "quick"}, - {0, NULL}, +struct EnumString ModApiEnvMod::es_ClearObjectsMode[] = +{ + {CLEAR_OBJECTS_MODE_FULL, "full"}, + {CLEAR_OBJECTS_MODE_QUICK, "quick"}, + {0, NULL}, }; /////////////////////////////////////////////////////////////////////////////// -void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n, u32 active_object_count, - u32 active_object_count_wider) + +void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n, + u32 active_object_count, u32 active_object_count_wider) { ServerScripting *scriptIface = env->getScriptIface(); scriptIface->realityCheck(); @@ -75,7 +77,7 @@ void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n, u32 active_obje // Get registered_abms[m_id] lua_pushinteger(L, m_id); lua_gettable(L, -2); - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) FATAL_ERROR(""); lua_remove(L, -2); // Remove registered_abms @@ -118,8 +120,7 @@ void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n) // Get registered_lbms[m_id] lua_pushinteger(L, m_id); lua_gettable(L, -2); - FATAL_ERROR_IF(lua_isnil(L, -1), - "Entry with given id not found in registered_lbms table"); + FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table"); lua_remove(L, -2); // Remove registered_lbms scriptIface->setOriginFromTable(-1); @@ -175,9 +176,10 @@ int LuaRaycast::create_object(lua_State *L) liquids = readParam<bool>(L, 4); } - LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2), objects, liquids); + LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2), + objects, liquids); - *(void **)(lua_newuserdata(L, sizeof(void *))) = o; + *(void **) (lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; @@ -191,12 +193,12 @@ LuaRaycast *LuaRaycast::checkobject(lua_State *L, int narg) void *ud = luaL_checkudata(L, narg, className); if (!ud) luaL_typerror(L, narg, className); - return *(LuaRaycast **)ud; + return *(LuaRaycast **) ud; } int LuaRaycast::gc_object(lua_State *L) { - LuaRaycast *o = *(LuaRaycast **)(lua_touserdata(L, 1)); + LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1)); delete o; return 0; } @@ -233,7 +235,11 @@ void LuaRaycast::Register(lua_State *L) } const char LuaRaycast::className[] = "Raycast"; -const luaL_Reg LuaRaycast::methods[] = {luamethod(LuaRaycast, next), {0, 0}}; +const luaL_Reg LuaRaycast::methods[] = +{ + luamethod(LuaRaycast, next), + { 0, 0 } +}; void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param) { @@ -385,7 +391,7 @@ int ModApiEnvMod::l_get_node_light(lua_State *L) // Do it v3s16 pos = read_v3s16(L, 1); u32 time_of_day = env->getTimeOfDay(); - if (lua_isnumber(L, 2)) + if(lua_isnumber(L, 2)) time_of_day = 24000.0 * lua_tonumber(L, 2); time_of_day %= 24000; u32 dnr = time_to_daynight_ratio(time_of_day, true); @@ -417,7 +423,7 @@ int ModApiEnvMod::l_place_node(lua_State *L) // Don't attempt to load non-loaded area as of now MapNode n_old = env->getMap().getNode(pos); - if (n_old.getContent() == CONTENT_IGNORE) { + if(n_old.getContent() == CONTENT_IGNORE){ lua_pushboolean(L, false); return 1; } @@ -427,7 +433,7 @@ int ModApiEnvMod::l_place_node(lua_State *L) PointedThing pointed; pointed.type = POINTEDTHING_NODE; pointed.node_abovesurface = pos; - pointed.node_undersurface = pos + v3s16(0, -1, 0); + pointed.node_undersurface = pos + v3s16(0,-1,0); // Place it with a NULL placer (appears in Lua as nil) bool success = scriptIfaceItem->item_OnPlace(item, nullptr, pointed); lua_pushboolean(L, success); @@ -446,7 +452,7 @@ int ModApiEnvMod::l_dig_node(lua_State *L) // Don't attempt to load non-loaded area as of now MapNode n = env->getMap().getNode(pos); - if (n.getContent() == CONTENT_IGNORE) { + if(n.getContent() == CONTENT_IGNORE){ lua_pushboolean(L, false); return 1; } @@ -469,7 +475,7 @@ int ModApiEnvMod::l_punch_node(lua_State *L) // Don't attempt to load non-loaded area as of now MapNode n = env->getMap().getNode(pos); - if (n.getContent() == CONTENT_IGNORE) { + if(n.getContent() == CONTENT_IGNORE){ lua_pushboolean(L, false); return 1; } @@ -513,7 +519,7 @@ int ModApiEnvMod::l_set_node_level(lua_State *L) v3s16 pos = read_v3s16(L, 1); u8 level = 1; - if (lua_isnumber(L, 2)) + if(lua_isnumber(L, 2)) level = lua_tonumber(L, 2); MapNode n = env->getMap().getNode(pos); lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level)); @@ -530,7 +536,7 @@ int ModApiEnvMod::l_add_node_level(lua_State *L) v3s16 pos = read_v3s16(L, 1); s16 level = 1; - if (lua_isnumber(L, 2)) + if(lua_isnumber(L, 2)) level = lua_tonumber(L, 2); MapNode n = env->getMap().getNode(pos); lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level)); @@ -544,7 +550,7 @@ int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L) GET_PLAIN_ENV_PTR; std::vector<v3s16> positions = env->getMap().findNodesWithMetadata( - check_v3s16(L, 1), check_v3s16(L, 2)); + check_v3s16(L, 1), check_v3s16(L, 2)); lua_createtable(L, positions.size(), 0); for (size_t i = 0; i != positions.size(); i++) { @@ -590,7 +596,7 @@ int ModApiEnvMod::l_add_entity(lua_State *L) ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata); int objectid = env->addActiveObject(obj); // If failed to add, return nothing (reads as nil) - if (objectid == 0) + if(objectid == 0) return 0; // If already deleted (can happen in on_activate), return nil @@ -607,10 +613,10 @@ int ModApiEnvMod::l_add_item(lua_State *L) GET_ENV_PTR; // pos - // v3f pos = checkFloatPos(L, 1); + //v3f pos = checkFloatPos(L, 1); // item - ItemStack item = read_item(L, 2, getServer(L)->idef()); - if (item.empty() || !item.isKnown(getServer(L)->idef())) + ItemStack item = read_item(L, 2,getServer(L)->idef()); + if(item.empty() || !item.isKnown(getServer(L)->idef())) return 0; int error_handler = PUSH_ERROR_HANDLER(L); @@ -619,7 +625,7 @@ int ModApiEnvMod::l_add_item(lua_State *L) lua_getglobal(L, "core"); lua_getfield(L, -1, "spawn_item"); lua_remove(L, -2); // Remove core - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) return 0; lua_pushvalue(L, 1); lua_pushstring(L, item.getItemString().c_str()); @@ -633,10 +639,10 @@ int ModApiEnvMod::l_add_item(lua_State *L) // get_connected_players() int ModApiEnvMod::l_get_connected_players(lua_State *L) { - ServerEnvironment *env = (ServerEnvironment *)getEnv(L); + ServerEnvironment *env = (ServerEnvironment *) getEnv(L); if (!env) { log_deprecated(L, "Calling get_connected_players() at mod load time" - " is deprecated"); + " is deprecated"); lua_createtable(L, 0, 0); return 1; } @@ -684,7 +690,7 @@ int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L) float radius = readParam<float>(L, 2) * BS; std::vector<ServerActiveObject *> objs; - auto include_obj_cb = [](ServerActiveObject *obj) { return !obj->isGone(); }; + auto include_obj_cb = [](ServerActiveObject *obj){ return !obj->isGone(); }; env->getObjectsInsideRadius(objs, pos, radius, include_obj_cb); int i = 0; @@ -710,7 +716,7 @@ int ModApiEnvMod::l_set_timeofday(lua_State *L) // This should be set directly in the environment but currently // such changes aren't immediately sent to the clients, so call // the server instead. - // env->setTimeOfDay(timeofday_mh); + //env->setTimeOfDay(timeofday_mh); getServer(L)->setTimeOfDay(timeofday_mh); return 0; } @@ -747,7 +753,7 @@ int ModApiEnvMod::l_get_gametime(lua_State *L) } void ModApiEnvMod::collectNodeIds(lua_State *L, int idx, const NodeDefManager *ndef, - std::vector<content_t> &filter) + std::vector<content_t> &filter) { if (lua_istable(L, idx)) { lua_pushnil(L); @@ -819,13 +825,13 @@ int ModApiEnvMod::l_find_nodes_near(lua_State *L) if (Client *client = getClient(L)) radius = client->CSMClampRadius(pos, radius); #endif - + std::vector<u32> individual_count; individual_count.resize(filter.size()); - + lua_newtable(L); u32 i = 0; - + for (int d = start_radius; d <= radius; d++) { const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d); for (const v3s16 &posi : list) { @@ -869,13 +875,13 @@ int ModApiEnvMod::l_find_nodes_near_under_air(lua_State *L) if (Client *client = getClient(L)) radius = client->CSMClampRadius(pos, radius); #endif - + std::vector<u32> individual_count; individual_count.resize(filter.size()); - + lua_newtable(L); u32 i = 0; - + for (int d = start_radius; d <= radius; d++) { const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d); for (const v3s16 &posi : list) { @@ -923,13 +929,13 @@ int ModApiEnvMod::l_find_nodes_near_under_air_except(lua_State *L) if (Client *client = getClient(L)) radius = client->CSMClampRadius(pos, radius); #endif - + std::vector<u32> individual_count; individual_count.resize(filter.size()); - + lua_newtable(L); u32 i = 0; - + for (int d = start_radius; d <= radius; d++) { const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d); for (const v3s16 &posi : list) { @@ -980,7 +986,7 @@ int ModApiEnvMod::l_find_nodes_in_area(lua_State *L) // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) { luaL_error(L, "find_nodes_in_area(): area volume" - " exceeds allowed value of 4096000"); + " exceeds allowed value of 4096000"); return 0; } @@ -1002,21 +1008,18 @@ int ModApiEnvMod::l_find_nodes_in_area(lua_State *L) v3s16 p; for (p.X = minp.X; p.X <= maxp.X; p.X++) - for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++) - for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { - content_t c = map.getNode(p).getContent(); - - auto it = std::find( - filter.begin(), filter.end(), c); - if (it != filter.end()) { - // Calculate index of the table and append - // the position - u32 filt_index = it - filter.begin(); - push_v3s16(L, p); - lua_rawseti(L, base + 1 + filt_index, - ++idx[filt_index]); - } - } + for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++) + for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { + content_t c = map.getNode(p).getContent(); + + auto it = std::find(filter.begin(), filter.end(), c); + if (it != filter.end()) { + // Calculate index of the table and append the position + u32 filt_index = it - filter.begin(); + push_v3s16(L, p); + lua_rawseti(L, base + 1 + filt_index, ++idx[filt_index]); + } + } // last filter table is at top of stack u32 i = filter.size() - 1; @@ -1040,21 +1043,19 @@ int ModApiEnvMod::l_find_nodes_in_area(lua_State *L) u32 i = 0; v3s16 p; for (p.X = minp.X; p.X <= maxp.X; p.X++) - for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++) - for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { - content_t c = env->getMap().getNode(p) - .getContent(); - - auto it = std::find( - filter.begin(), filter.end(), c); - if (it != filter.end()) { - push_v3s16(L, p); - lua_rawseti(L, -2, ++i); - - u32 filt_index = it - filter.begin(); - individual_count[filt_index]++; - } - } + for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++) + for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { + content_t c = env->getMap().getNode(p).getContent(); + + auto it = std::find(filter.begin(), filter.end(), c); + if (it != filter.end()) { + push_v3s16(L, p); + lua_rawseti(L, -2, ++i); + + u32 filt_index = it - filter.begin(); + individual_count[filt_index]++; + } + } lua_createtable(L, 0, filter.size()); for (u32 i = 0; i < filter.size(); i++) { @@ -1096,7 +1097,7 @@ int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L) // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) { luaL_error(L, "find_nodes_in_area_under_air(): area volume" - " exceeds allowed value of 4096000"); + " exceeds allowed value of 4096000"); return 0; } @@ -1107,20 +1108,20 @@ int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L) u32 i = 0; v3s16 p; for (p.X = minp.X; p.X <= maxp.X; p.X++) - for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { - p.Y = minp.Y; - content_t c = map.getNode(p).getContent(); - for (; p.Y <= maxp.Y; p.Y++) { - v3s16 psurf(p.X, p.Y + 1, p.Z); - content_t csurf = map.getNode(psurf).getContent(); - if (c != CONTENT_AIR && csurf == CONTENT_AIR && - CONTAINS(filter, c)) { - push_v3s16(L, p); - lua_rawseti(L, -2, ++i); - } - c = csurf; + for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { + p.Y = minp.Y; + content_t c = map.getNode(p).getContent(); + for (; p.Y <= maxp.Y; p.Y++) { + v3s16 psurf(p.X, p.Y + 1, p.Z); + content_t csurf = map.getNode(psurf).getContent(); + if (c != CONTENT_AIR && csurf == CONTENT_AIR && + CONTAINS(filter, c)) { + push_v3s16(L, p); + lua_rawseti(L, -2, ++i); } + c = csurf; } + } return 1; } @@ -1135,10 +1136,10 @@ int ModApiEnvMod::l_get_perlin(lua_State *L) if (lua_istable(L, 1)) { read_noiseparams(L, 1, ¶ms); } else { - params.seed = luaL_checkint(L, 1); + params.seed = luaL_checkint(L, 1); params.octaves = luaL_checkint(L, 2); params.persist = readParam<float>(L, 3); - params.spread = v3f(1, 1, 1) * readParam<float>(L, 4); + params.spread = v3f(1, 1, 1) * readParam<float>(L, 4); } params.seed += (int)env->getServerMap().getSeed(); @@ -1176,10 +1177,9 @@ int ModApiEnvMod::l_get_voxel_manip(lua_State *L) GET_ENV_PTR; Map *map = &(env->getMap()); - LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) - ? new LuaVoxelManip(map, read_v3s16(L, 1), - read_v3s16(L, 2)) - : new LuaVoxelManip(map); + LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ? + new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) : + new LuaVoxelManip(map); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, "VoxelManip"); @@ -1196,8 +1196,8 @@ int ModApiEnvMod::l_clear_objects(lua_State *L) ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK; if (lua_istable(L, 1)) { - mode = (ClearObjectsMode)getenumfield( - L, 1, "mode", ModApiEnvMod::es_ClearObjectsMode, mode); + mode = (ClearObjectsMode)getenumfield(L, 1, "mode", + ModApiEnvMod::es_ClearObjectsMode, mode); } env->clearObjects(mode); @@ -1237,12 +1237,10 @@ int ModApiEnvMod::l_fix_light(lua_State *L) bool success = true; v3s16 blockpos; for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++) - for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++) - for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; - blockpos.Z++) { - success = success & map.repairBlockLight(blockpos, - &modified_blocks); - } + for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++) + for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) { + success = success & map.repairBlockLight(blockpos, &modified_blocks); + } if (!modified_blocks.empty()) { MapEditEvent event; event.type = MEET_OTHER; @@ -1276,10 +1274,10 @@ int ModApiEnvMod::l_load_area(lua_State *L) v3s16 bp2 = getNodeBlockPos(check_v3s16(L, 2)); sortBoxVerticies(bp1, bp2); for (s16 z = bp1.Z; z <= bp2.Z; z++) - for (s16 y = bp1.Y; y <= bp2.Y; y++) - for (s16 x = bp1.X; x <= bp2.X; x++) { - map->emergeBlock(v3s16(x, y, z)); - } + for (s16 y = bp1.Y; y <= bp2.Y; y++) + for (s16 x = bp1.X; x <= bp2.X; x++) { + map->emergeBlock(v3s16(x, y, z)); + } } return 0; @@ -1313,22 +1311,19 @@ int ModApiEnvMod::l_emerge_area(lua_State *L) int args_ref = luaL_ref(L, LUA_REGISTRYINDEX); state = new ScriptCallbackState; - state->script = getServer(L)->getScriptIface(); + state->script = getServer(L)->getScriptIface(); state->callback_ref = callback_ref; - state->args_ref = args_ref; - state->refcount = num_blocks; - state->origin = getScriptApiBase(L)->getOrigin(); + state->args_ref = args_ref; + state->refcount = num_blocks; + state->origin = getScriptApiBase(L)->getOrigin(); } for (s16 z = bpmin.Z; z <= bpmax.Z; z++) - for (s16 y = bpmin.Y; y <= bpmax.Y; y++) - for (s16 x = bpmin.X; x <= bpmax.X; x++) { - emerge->enqueueBlockEmergeEx(v3s16(x, y, z), - PEER_ID_INEXISTENT, - BLOCK_EMERGE_ALLOW_GEN | - BLOCK_EMERGE_FORCE_QUEUE, - callback, state); - } + for (s16 y = bpmin.Y; y <= bpmax.Y; y++) + for (s16 x = bpmin.X; x <= bpmax.X; x++) { + emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT, + BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state); + } return 0; } @@ -1350,16 +1345,16 @@ int ModApiEnvMod::l_delete_area(lua_State *L) bool success = true; for (s16 z = bpmin.Z; z <= bpmax.Z; z++) - for (s16 y = bpmin.Y; y <= bpmax.Y; y++) - for (s16 x = bpmin.X; x <= bpmax.X; x++) { - v3s16 bp(x, y, z); - if (map.deleteBlock(bp)) { - env->setStaticForActiveObjectsInBlock(bp, false); - event.modified_blocks.insert(bp); - } else { - success = false; - } - } + for (s16 y = bpmin.Y; y <= bpmax.Y; y++) + for (s16 x = bpmin.X; x <= bpmax.X; x++) { + v3s16 bp(x, y, z); + if (map.deleteBlock(bp)) { + env->setStaticForActiveObjectsInBlock(bp, false); + event.modified_blocks.insert(bp); + } else { + success = false; + } + } map.dispatchEvent(event); lua_pushboolean(L, success); @@ -1372,14 +1367,14 @@ int ModApiEnvMod::l_find_path(lua_State *L) { Environment *env = getEnv(L); - v3s16 pos1 = read_v3s16(L, 1); - v3s16 pos2 = read_v3s16(L, 2); + v3s16 pos1 = read_v3s16(L, 1); + v3s16 pos2 = read_v3s16(L, 2); unsigned int searchdistance = luaL_checkint(L, 3); - unsigned int max_jump = luaL_checkint(L, 4); - unsigned int max_drop = luaL_checkint(L, 5); - PathAlgorithm algo = PA_PLAIN_NP; + unsigned int max_jump = luaL_checkint(L, 4); + unsigned int max_drop = luaL_checkint(L, 5); + PathAlgorithm algo = PA_PLAIN_NP; if (!lua_isnoneornil(L, 6)) { - std::string algorithm = luaL_checkstring(L, 6); + std::string algorithm = luaL_checkstring(L,6); if (algorithm == "A*") algo = PA_PLAIN; @@ -1387,16 +1382,16 @@ int ModApiEnvMod::l_find_path(lua_State *L) if (algorithm == "Dijkstra") algo = PA_DIJKSTRA; } - - std::vector<v3s16> path = get_path(&env->getMap(), env->getGameDef()->ndef(), - pos1, pos2, searchdistance, max_jump, max_drop, algo); + + std::vector<v3s16> path = get_path(&env->getMap(), env->getGameDef()->ndef(), pos1, pos2, + searchdistance, max_jump, max_drop, algo); if (!path.empty()) { lua_createtable(L, path.size(), 0); int top = lua_gettop(L); unsigned int index = 1; for (const v3s16 &i : path) { - lua_pushnumber(L, index); + lua_pushnumber(L,index); push_v3s16(L, i); lua_settable(L, top); index++; @@ -1415,23 +1410,24 @@ int ModApiEnvMod::l_spawn_tree(lua_State *L) v3s16 p0 = read_v3s16(L, 1); treegen::TreeDef tree_def; - std::string trunk, leaves, fruit; + std::string trunk,leaves,fruit; const NodeDefManager *ndef = env->getGameDef()->ndef(); - if (lua_istable(L, 2)) { + if(lua_istable(L, 2)) + { getstringfield(L, 2, "axiom", tree_def.initial_axiom); getstringfield(L, 2, "rules_a", tree_def.rules_a); getstringfield(L, 2, "rules_b", tree_def.rules_b); getstringfield(L, 2, "rules_c", tree_def.rules_c); getstringfield(L, 2, "rules_d", tree_def.rules_d); getstringfield(L, 2, "trunk", trunk); - tree_def.trunknode = ndef->getId(trunk); + tree_def.trunknode=ndef->getId(trunk); getstringfield(L, 2, "leaves", leaves); - tree_def.leavesnode = ndef->getId(leaves); - tree_def.leaves2_chance = 0; + tree_def.leavesnode=ndef->getId(leaves); + tree_def.leaves2_chance=0; getstringfield(L, 2, "leaves2", leaves); if (!leaves.empty()) { - tree_def.leaves2node = ndef->getId(leaves); + tree_def.leaves2node=ndef->getId(leaves); getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance); } getintfield(L, 2, "angle", tree_def.angle); @@ -1440,22 +1436,22 @@ int ModApiEnvMod::l_spawn_tree(lua_State *L) tree_def.iterations_random_level = 0; getstringfield(L, 2, "trunk_type", tree_def.trunk_type); getboolfield(L, 2, "thin_branches", tree_def.thin_branches); - tree_def.fruit_chance = 0; + tree_def.fruit_chance=0; getstringfield(L, 2, "fruit", fruit); if (!fruit.empty()) { - tree_def.fruitnode = ndef->getId(fruit); - getintfield(L, 2, "fruit_chance", tree_def.fruit_chance); + tree_def.fruitnode=ndef->getId(fruit); + getintfield(L, 2, "fruit_chance",tree_def.fruit_chance); } tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed); - } else + } + else return 0; ServerMap *map = &env->getServerMap(); treegen::error e; - if ((e = treegen::spawn_ltree(map, p0, ndef, tree_def)) != treegen::SUCCESS) { + if ((e = treegen::spawn_ltree (map, p0, ndef, tree_def)) != treegen::SUCCESS) { if (e == treegen::UNBALANCED_BRACKETS) { - luaL_error(L, "spawn_tree(): closing ']' has no matching opening " - "bracket"); + luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket"); } else { luaL_error(L, "spawn_tree(): unknown error"); } @@ -1497,14 +1493,14 @@ int ModApiEnvMod::l_forceload_free_block(lua_State *L) } // get_translated_string(lang_code, string) -int ModApiEnvMod::l_get_translated_string(lua_State *L) +int ModApiEnvMod::l_get_translated_string(lua_State * L) { GET_ENV_PTR; std::string lang_code = luaL_checkstring(L, 1); std::string string = luaL_checkstring(L, 2); getServer(L)->loadTranslationLanguage(lang_code); - string = wide_to_utf8(translate_string( - utf8_to_wide(string), &(*g_server_translations)[lang_code])); + string = wide_to_utf8(translate_string(utf8_to_wide(string), + &(*g_server_translations)[lang_code])); lua_pushstring(L, string.c_str()); return 1; } diff --git a/src/script/lua_api/l_env.h b/src/script/lua_api/l_env.h index 43388475e..e1b89494b 100644 --- a/src/script/lua_api/l_env.h +++ b/src/script/lua_api/l_env.h @@ -23,8 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "serverenvironment.h" #include "raycast.h" -class ModApiEnvMod : public ModApiBase -{ +class ModApiEnvMod : public ModApiBase { private: // set_node(pos, node) // pos = {x=num, y=num, z=num} @@ -127,17 +126,17 @@ private: // find_node_near(pos, radius, nodenames, search_center) -> pos or nil // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" static int l_find_node_near(lua_State *L); - + // find_nodes_near(pos, radius, nodenames, search_center) -> list of positions // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" static int l_find_nodes_near(lua_State *L); - - // find_nodes_near_under_air(pos, radius, nodenames, search_center) -> list of - // positions nodenames: eg. {"ignore", "group:tree"} or "default:dirt" + + // find_nodes_near_under_air(pos, radius, nodenames, search_center) -> list of positions + // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" static int l_find_nodes_near_under_air(lua_State *L); - - // find_nodes_near_under_air(pos, radius, nodenames, search_center) -> list of - // positions nodenames: eg. {"ignore", "group:tree"} or "default:dirt" + + // find_nodes_near_under_air(pos, radius, nodenames, search_center) -> list of positions + // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" static int l_find_nodes_near_under_air_except(lua_State *L); // find_nodes_in_area(minp, maxp, nodenames) -> list of positions @@ -201,12 +200,12 @@ private: static int l_forceload_free_block(lua_State *L); // Get a string translated server side - static int l_get_translated_string(lua_State *L); + static int l_get_translated_string(lua_State * L); /* Helpers */ - static void collectNodeIds(lua_State *L, int idx, const NodeDefManager *ndef, - std::vector<content_t> &filter); + static void collectNodeIds(lua_State *L, int idx, + const NodeDefManager *ndef, std::vector<content_t> &filter); public: static void Initialize(lua_State *L, int top); @@ -215,8 +214,7 @@ public: static struct EnumString es_ClearObjectsMode[]; }; -class LuaABM : public ActiveBlockModifier -{ +class LuaABM : public ActiveBlockModifier { private: int m_id; @@ -225,18 +223,17 @@ private: float m_trigger_interval; u32 m_trigger_chance; bool m_simple_catch_up; - public: - LuaABM(lua_State *L, int id, const std::vector<std::string> &trigger_contents, + LuaABM(lua_State *L, int id, + const std::vector<std::string> &trigger_contents, const std::vector<std::string> &required_neighbors, - float trigger_interval, u32 trigger_chance, - bool simple_catch_up) : - m_id(id), - m_trigger_contents(trigger_contents), - m_required_neighbors(required_neighbors), - m_trigger_interval(trigger_interval), - m_trigger_chance(trigger_chance), - m_simple_catch_up(simple_catch_up) + float trigger_interval, u32 trigger_chance, bool simple_catch_up): + m_id(id), + m_trigger_contents(trigger_contents), + m_required_neighbors(required_neighbors), + m_trigger_interval(trigger_interval), + m_trigger_chance(trigger_chance), + m_simple_catch_up(simple_catch_up) { } virtual const std::vector<std::string> &getTriggerContents() const @@ -247,9 +244,18 @@ public: { return m_required_neighbors; } - virtual float getTriggerInterval() { return m_trigger_interval; } - virtual u32 getTriggerChance() { return m_trigger_chance; } - virtual bool getSimpleCatchUp() { return m_simple_catch_up; } + virtual float getTriggerInterval() + { + return m_trigger_interval; + } + virtual u32 getTriggerChance() + { + return m_trigger_chance; + } + virtual bool getSimpleCatchUp() + { + return m_simple_catch_up; + } virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n, u32 active_object_count, u32 active_object_count_wider); }; @@ -258,11 +264,12 @@ class LuaLBM : public LoadingBlockModifierDef { private: int m_id; - public: - LuaLBM(lua_State *L, int id, const std::set<std::string> &trigger_contents, - const std::string &name, bool run_at_every_load) : - m_id(id) + LuaLBM(lua_State *L, int id, + const std::set<std::string> &trigger_contents, + const std::string &name, + bool run_at_every_load): + m_id(id) { this->run_at_every_load = run_at_every_load; this->trigger_contents = trigger_contents; @@ -290,14 +297,14 @@ private: * Returns the next pointed thing on the ray. */ static int l_next(lua_State *L); - public: //! Constructor with the same arguments as RaycastState. - LuaRaycast(const core::line3d<f32> &shootline, bool objects_pointable, - bool liquids_pointable) : - state(shootline, objects_pointable, liquids_pointable) - { - } + LuaRaycast( + const core::line3d<f32> &shootline, + bool objects_pointable, + bool liquids_pointable) : + state(shootline, objects_pointable, liquids_pointable) + {} //! Creates a LuaRaycast and leaves it on top of the stack. static int create_object(lua_State *L); @@ -312,8 +319,7 @@ public: static void Register(lua_State *L); }; -struct ScriptCallbackState -{ +struct ScriptCallbackState { ServerScripting *script; int callback_ref; int args_ref; diff --git a/src/script/lua_api/l_http.cpp b/src/script/lua_api/l_http.cpp index 21d000d25..84837e71b 100644 --- a/src/script/lua_api/l_http.cpp +++ b/src/script/lua_api/l_http.cpp @@ -30,9 +30,9 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <iomanip> #include <cctype> -#define HTTP_API(name) \ - lua_pushstring(L, #name); \ - lua_pushcfunction(L, l_http_##name); \ +#define HTTP_API(name) \ + lua_pushstring(L, #name); \ + lua_pushcfunction(L, l_http_##name); \ lua_settable(L, -3); #if USE_CURL @@ -54,8 +54,7 @@ void ModApiHttp::read_http_fetch_request(lua_State *L, HTTPFetchRequest &req) if (lua_istable(L, 2)) { lua_pushnil(L); while (lua_next(L, 2) != 0) { - req.post_fields[readParam<std::string>(L, -2)] = - readParam<std::string>(L, -1); + req.post_fields[readParam<std::string>(L, -2)] = readParam<std::string>(L, -1); lua_pop(L, 1); } } else if (lua_isstring(L, 2)) { @@ -74,8 +73,7 @@ void ModApiHttp::read_http_fetch_request(lua_State *L, HTTPFetchRequest &req) lua_pop(L, 1); } -void ModApiHttp::push_http_fetch_result( - lua_State *L, HTTPFetchResult &res, bool completed) +void ModApiHttp::push_http_fetch_result(lua_State *L, HTTPFetchResult &res, bool completed) { lua_newtable(L); setboolfield(L, -1, "succeeded", res.succeeded); @@ -173,19 +171,15 @@ int ModApiHttp::l_request_http_api(lua_State *L) std::string mod_name = readParam<std::string>(L, -1); std::string http_mods = g_settings->get("secure.http_mods"); - http_mods.erase(std::remove(http_mods.begin(), http_mods.end(), ' '), - http_mods.end()); + http_mods.erase(std::remove(http_mods.begin(), http_mods.end(), ' '), http_mods.end()); std::vector<std::string> mod_list_http = str_split(http_mods, ','); std::string trusted_mods = g_settings->get("secure.trusted_mods"); - trusted_mods.erase(std::remove(trusted_mods.begin(), trusted_mods.end(), ' '), - trusted_mods.end()); + trusted_mods.erase(std::remove(trusted_mods.begin(), trusted_mods.end(), ' '), trusted_mods.end()); std::vector<std::string> mod_list_trusted = str_split(trusted_mods, ','); - mod_list_http.insert(mod_list_http.end(), mod_list_trusted.begin(), - mod_list_trusted.end()); - if (std::find(mod_list_http.begin(), mod_list_http.end(), mod_name) == - mod_list_http.end()) { + mod_list_http.insert(mod_list_http.end(), mod_list_trusted.begin(), mod_list_trusted.end()); + if (std::find(mod_list_http.begin(), mod_list_http.end(), mod_name) == mod_list_http.end()) { lua_pushnil(L); return 1; } diff --git a/src/script/lua_api/l_http.h b/src/script/lua_api/l_http.h index f2c72eafb..de6e51b37 100644 --- a/src/script/lua_api/l_http.h +++ b/src/script/lua_api/l_http.h @@ -25,14 +25,12 @@ with this program; if not, write to the Free Software Foundation, Inc., struct HTTPFetchRequest; struct HTTPFetchResult; -class ModApiHttp : public ModApiBase -{ +class ModApiHttp : public ModApiBase { private: #if USE_CURL // Helpers for HTTP fetch functions static void read_http_fetch_request(lua_State *L, HTTPFetchRequest &req); - static void push_http_fetch_result( - lua_State *L, HTTPFetchResult &res, bool completed = true); + static void push_http_fetch_result(lua_State *L, HTTPFetchResult &res, bool completed = true); // http_fetch_sync({url=, timeout=, post_data=}) static int l_http_fetch_sync(lua_State *L); diff --git a/src/script/lua_api/l_internal.h b/src/script/lua_api/l_internal.h index 378d19cd0..a86eeaf79 100644 --- a/src/script/lua_api/l_internal.h +++ b/src/script/lua_api/l_internal.h @@ -28,12 +28,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "common/c_internal.h" -#define luamethod(class, name) \ - { \ -#name, class ::l_##name \ - } -#define luamethod_aliased(class, name, alias) \ - {#name, class ::l_##name}, { #alias, class ::l_##name } +#define luamethod(class, name) {#name, class::l_##name} +#define luamethod_aliased(class, name, alias) {#name, class::l_##name}, {#alias, class::l_##name} #define API_FCT(name) registerFunction(L, #name, l_##name, top) // For future use @@ -43,33 +39,32 @@ with this program; if not, write to the Free Software Foundation, Inc., /* In debug mode ensure no code tries to retrieve the server env when it isn't * actually available (in CSM) */ #if !defined(SERVER) && !defined(NDEBUG) -#define DEBUG_ASSERT_NO_CLIENTAPI \ - FATAL_ERROR_IF(getClient(L) != nullptr, \ - "Tried " \ - "to retrieve ServerEnvironment on client") +#define DEBUG_ASSERT_NO_CLIENTAPI \ + FATAL_ERROR_IF(getClient(L) != nullptr, "Tried " \ + "to retrieve ServerEnvironment on client") #else #define DEBUG_ASSERT_NO_CLIENTAPI ((void)0) #endif // Retrieve ServerEnvironment pointer as `env` (no map lock) -#define GET_ENV_PTR_NO_MAP_LOCK \ - DEBUG_ASSERT_NO_CLIENTAPI; \ - ServerEnvironment *env = (ServerEnvironment *)getEnv(L); \ - if (env == NULL) \ - return 0 +#define GET_ENV_PTR_NO_MAP_LOCK \ + DEBUG_ASSERT_NO_CLIENTAPI; \ + ServerEnvironment *env = (ServerEnvironment *)getEnv(L); \ + if (env == NULL) \ + return 0 // Retrieve ServerEnvironment pointer as `env` -#define GET_ENV_PTR \ - MAP_LOCK_REQUIRED; \ +#define GET_ENV_PTR \ + MAP_LOCK_REQUIRED; \ GET_ENV_PTR_NO_MAP_LOCK // Retrieve Environment pointer as `env` (no map lock) -#define GET_PLAIN_ENV_PTR_NO_MAP_LOCK \ - Environment *env = (Environment *)getEnv(L); \ - if (env == NULL) \ - return 0 +#define GET_PLAIN_ENV_PTR_NO_MAP_LOCK \ + Environment *env = (Environment *)getEnv(L); \ + if (env == NULL) \ + return 0 // Retrieve Environment pointer as `env` -#define GET_PLAIN_ENV_PTR \ - MAP_LOCK_REQUIRED; \ +#define GET_PLAIN_ENV_PTR \ + MAP_LOCK_REQUIRED; \ GET_PLAIN_ENV_PTR_NO_MAP_LOCK diff --git a/src/script/lua_api/l_inventory.cpp b/src/script/lua_api/l_inventory.cpp index d75d96ef3..e41b5cb41 100644 --- a/src/script/lua_api/l_inventory.cpp +++ b/src/script/lua_api/l_inventory.cpp @@ -29,25 +29,25 @@ with this program; if not, write to the Free Software Foundation, Inc., /* InvRef */ -InvRef *InvRef::checkobject(lua_State *L, int narg) +InvRef* InvRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); - if (!ud) - luaL_typerror(L, narg, className); - return *(InvRef **)ud; // unbox pointer + if(!ud) luaL_typerror(L, narg, className); + return *(InvRef**)ud; // unbox pointer } -Inventory *InvRef::getinv(lua_State *L, InvRef *ref) +Inventory* InvRef::getinv(lua_State *L, InvRef *ref) { return getServerInventoryMgr(L)->getInventory(ref->m_loc); } -InventoryList *InvRef::getlist(lua_State *L, InvRef *ref, const char *listname) +InventoryList* InvRef::getlist(lua_State *L, InvRef *ref, + const char *listname) { NO_MAP_LOCK_REQUIRED; Inventory *inv = getinv(L, ref); - if (!inv) + if(!inv) return NULL; return inv->getList(listname); } @@ -61,8 +61,7 @@ void InvRef::reportInventoryChange(lua_State *L, InvRef *ref) // Exported functions // garbage collector -int InvRef::gc_object(lua_State *L) -{ +int InvRef::gc_object(lua_State *L) { InvRef *o = *(InvRef **)(lua_touserdata(L, 1)); delete o; return 0; @@ -75,7 +74,7 @@ int InvRef::l_is_empty(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); InventoryList *list = getlist(L, ref, listname); - if (list && list->getUsedSlots() > 0) { + if(list && list->getUsedSlots() > 0){ lua_pushboolean(L, false); } else { lua_pushboolean(L, true); @@ -90,7 +89,7 @@ int InvRef::l_get_size(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ lua_pushinteger(L, list->getSize()); } else { lua_pushinteger(L, 0); @@ -105,7 +104,7 @@ int InvRef::l_get_width(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ lua_pushinteger(L, list->getWidth()); } else { lua_pushinteger(L, 0); @@ -127,22 +126,23 @@ int InvRef::l_set_size(lua_State *L) } Inventory *inv = getinv(L, ref); - if (inv == NULL) { + if(inv == NULL){ lua_pushboolean(L, false); return 1; } - if (newsize == 0) { + if(newsize == 0){ inv->deleteList(listname); reportInventoryChange(L, ref); lua_pushboolean(L, true); return 1; } InventoryList *list = inv->getList(listname); - if (list) { + if(list){ list->setSize(newsize); } else { list = inv->addList(listname, newsize); - if (!list) { + if (!list) + { lua_pushboolean(L, false); return 1; } @@ -160,11 +160,11 @@ int InvRef::l_set_width(lua_State *L) const char *listname = luaL_checkstring(L, 2); int newwidth = luaL_checknumber(L, 3); Inventory *inv = getinv(L, ref); - if (inv == NULL) { + if(inv == NULL){ return 0; } InventoryList *list = inv->getList(listname); - if (list) { + if(list){ list->setWidth(newwidth); } else { return 0; @@ -182,7 +182,7 @@ int InvRef::l_get_stack(lua_State *L) int i = luaL_checknumber(L, 3) - 1; InventoryList *list = getlist(L, ref, listname); ItemStack item; - if (list != NULL && i >= 0 && i < (int)list->getSize()) + if(list != NULL && i >= 0 && i < (int) list->getSize()) item = list->getItem(i); LuaItemStack::create(L, item); return 1; @@ -197,7 +197,7 @@ int InvRef::l_set_stack(lua_State *L) int i = luaL_checknumber(L, 3) - 1; ItemStack newitem = read_item(L, 4, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); - if (list != NULL && i >= 0 && i < (int)list->getSize()) { + if(list != NULL && i >= 0 && i < (int) list->getSize()){ list->changeItem(i, newitem); reportInventoryChange(L, ref); lua_pushboolean(L, true); @@ -214,7 +214,7 @@ int InvRef::l_get_list(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); Inventory *inv = getinv(L, ref); - if (inv) { + if(inv){ push_inventory_list(L, inv, listname); } else { lua_pushnil(L); @@ -229,12 +229,13 @@ int InvRef::l_set_list(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); Inventory *inv = getinv(L, ref); - if (inv == NULL) { + if(inv == NULL){ return 0; } InventoryList *list = inv->getList(listname); - if (list) - read_inventory_list(L, 3, inv, listname, getServer(L), list->getSize()); + if(list) + read_inventory_list(L, 3, inv, listname, + getServer(L), list->getSize()); else read_inventory_list(L, 3, inv, listname, getServer(L)); reportInventoryChange(L, ref); @@ -250,11 +251,11 @@ int InvRef::l_get_lists(lua_State *L) if (!inv) { return 0; } - std::vector<const InventoryList *> lists = inv->getLists(); - std::vector<const InventoryList *>::iterator iter = lists.begin(); + std::vector<const InventoryList*> lists = inv->getLists(); + std::vector<const InventoryList*>::iterator iter = lists.begin(); lua_createtable(L, 0, lists.size()); for (; iter != lists.end(); iter++) { - const char *name = (*iter)->getName().c_str(); + const char* name = (*iter)->getName().c_str(); lua_pushstring(L, name); push_inventory_list(L, inv, name); lua_rawset(L, -3); @@ -297,9 +298,9 @@ int InvRef::l_add_item(lua_State *L) const char *listname = luaL_checkstring(L, 2); ItemStack item = read_item(L, 3, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ ItemStack leftover = list->addItem(item); - if (leftover.count != item.count) + if(leftover.count != item.count) reportInventoryChange(L, ref); LuaItemStack::create(L, leftover); } else { @@ -317,7 +318,7 @@ int InvRef::l_room_for_item(lua_State *L) const char *listname = luaL_checkstring(L, 2); ItemStack item = read_item(L, 3, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ lua_pushboolean(L, list->roomForItem(item)); } else { lua_pushboolean(L, false); @@ -325,8 +326,8 @@ int InvRef::l_room_for_item(lua_State *L) return 1; } -// contains_item(self, listname, itemstack or itemstring or table or nil, [match_meta]) -> -// true/false Returns true if the list contains the given count of the given item +// contains_item(self, listname, itemstack or itemstring or table or nil, [match_meta]) -> true/false +// Returns true if the list contains the given count of the given item int InvRef::l_contains_item(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -354,9 +355,9 @@ int InvRef::l_remove_item(lua_State *L) const char *listname = luaL_checkstring(L, 2); ItemStack item = read_item(L, 3, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ ItemStack removed = list->removeItem(item); - if (!removed.empty()) + if(!removed.empty()) reportInventoryChange(L, ref); LuaItemStack::create(L, removed); } else { @@ -371,7 +372,7 @@ int InvRef::l_get_location(lua_State *L) NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const InventoryLocation &loc = ref->m_loc; - switch (loc.type) { + switch(loc.type){ case InventoryLocation::PLAYER: lua_newtable(L); lua_pushstring(L, "player"); @@ -403,7 +404,9 @@ int InvRef::l_get_location(lua_State *L) return 1; } -InvRef::InvRef(const InventoryLocation &loc) : m_loc(loc) + +InvRef::InvRef(const InventoryLocation &loc): + m_loc(loc) { } @@ -440,7 +443,7 @@ void InvRef::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -450,25 +453,35 @@ void InvRef::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Cannot be created from Lua - // lua_register(L, className, create_object); + //lua_register(L, className, create_object); } const char InvRef::className[] = "InvRef"; -const luaL_Reg InvRef::methods[] = {luamethod(InvRef, is_empty), - luamethod(InvRef, get_size), luamethod(InvRef, set_size), - luamethod(InvRef, get_width), luamethod(InvRef, set_width), - luamethod(InvRef, get_stack), luamethod(InvRef, set_stack), - luamethod(InvRef, get_list), luamethod(InvRef, set_list), - luamethod(InvRef, get_lists), luamethod(InvRef, set_lists), - luamethod(InvRef, add_item), luamethod(InvRef, room_for_item), - luamethod(InvRef, contains_item), luamethod(InvRef, remove_item), - luamethod(InvRef, get_location), {0, 0}}; +const luaL_Reg InvRef::methods[] = { + luamethod(InvRef, is_empty), + luamethod(InvRef, get_size), + luamethod(InvRef, set_size), + luamethod(InvRef, get_width), + luamethod(InvRef, set_width), + luamethod(InvRef, get_stack), + luamethod(InvRef, set_stack), + luamethod(InvRef, get_list), + luamethod(InvRef, set_list), + luamethod(InvRef, get_lists), + luamethod(InvRef, set_lists), + luamethod(InvRef, add_item), + luamethod(InvRef, room_for_item), + luamethod(InvRef, contains_item), + luamethod(InvRef, remove_item), + luamethod(InvRef, get_location), + {0,0} +}; // get_inventory(location) int ModApiInventory::l_get_inventory(lua_State *L) @@ -479,7 +492,7 @@ int ModApiInventory::l_get_inventory(lua_State *L) std::string type = luaL_checkstring(L, -1); lua_pop(L, 1); - if (type == "node") { + if(type == "node"){ MAP_LOCK_REQUIRED; lua_getfield(L, 1, "pos"); v3s16 pos = check_v3s16(L, -1); @@ -509,6 +522,7 @@ int ModApiInventory::l_get_inventory(lua_State *L) lua_pushnil(L); return 1; // END NO_MAP_LOCK_REQUIRED; + } // create_detached_inventory_raw(name, [player_name]) @@ -517,8 +531,7 @@ int ModApiInventory::l_create_detached_inventory_raw(lua_State *L) NO_MAP_LOCK_REQUIRED; const char *name = luaL_checkstring(L, 1); std::string player = readParam<std::string>(L, 2, ""); - if (getServerInventoryMgr(L)->createDetachedInventory( - name, getServer(L)->idef(), player) != NULL) { + if (getServerInventoryMgr(L)->createDetachedInventory(name, getServer(L)->idef(), player) != NULL) { InventoryLocation loc; loc.setDetached(name); InvRef::create(L, loc); diff --git a/src/script/lua_api/l_inventory.h b/src/script/lua_api/l_inventory.h index fa8a77ae2..94f670c9d 100644 --- a/src/script/lua_api/l_inventory.h +++ b/src/script/lua_api/l_inventory.h @@ -30,8 +30,7 @@ class RemotePlayer; InvRef */ -class InvRef : public ModApiBase -{ +class InvRef : public ModApiBase { private: InventoryLocation m_loc; @@ -40,9 +39,10 @@ private: static InvRef *checkobject(lua_State *L, int narg); - static Inventory *getinv(lua_State *L, InvRef *ref); + static Inventory* getinv(lua_State *L, InvRef *ref); - static InventoryList *getlist(lua_State *L, InvRef *ref, const char *listname); + static InventoryList* getlist(lua_State *L, InvRef *ref, + const char *listname); static void reportInventoryChange(lua_State *L, InvRef *ref); @@ -88,17 +88,16 @@ private: // Returns the leftover stack static int l_add_item(lua_State *L); - // room_for_item(self, listname, itemstack or itemstring or table or nil) -> - // true/false Returns true if the item completely fits into the list + // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false + // Returns true if the item completely fits into the list static int l_room_for_item(lua_State *L); - // contains_item(self, listname, itemstack or itemstring or table or nil, - // [match_meta]) -> true/false Returns true if the list contains the given count - // of the given item name + // contains_item(self, listname, itemstack or itemstring or table or nil, [match_meta]) -> true/false + // Returns true if the list contains the given count of the given item name static int l_contains_item(lua_State *L); - // remove_item(self, listname, itemstack or itemstring or table or nil) -> - // itemstack Returns the items that were actually removed + // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack + // Returns the items that were actually removed static int l_remove_item(lua_State *L); // get_location() -> location (like get_inventory(location)) @@ -117,8 +116,7 @@ public: static void Register(lua_State *L); }; -class ModApiInventory : public ModApiBase -{ +class ModApiInventory : public ModApiBase { private: static int l_create_detached_inventory_raw(lua_State *L); diff --git a/src/script/lua_api/l_inventoryaction.cpp b/src/script/lua_api/l_inventoryaction.cpp index f65137465..f3037ba83 100644 --- a/src/script/lua_api/l_inventoryaction.cpp +++ b/src/script/lua_api/l_inventoryaction.cpp @@ -43,9 +43,9 @@ int LuaInventoryAction::l_apply(lua_State *L) std::ostringstream os(std::ios::binary); o->m_action->serialize(os); - + std::istringstream is(os.str(), std::ios_base::binary); - + InventoryAction *a = InventoryAction::deSerialize(is); getClient(L)->inventoryAction(a); @@ -69,30 +69,29 @@ int LuaInventoryAction::l_to(lua_State *L) int LuaInventoryAction::l_craft(lua_State *L) { LuaInventoryAction *o = checkobject(L, 1); - + if (o->m_action->getType() != IAction::Craft) return 0; - + std::string locStr; InventoryLocation loc; - + locStr = readParam<std::string>(L, 2); - + try { loc.deSerialize(locStr); dynamic_cast<ICraftAction *>(o->m_action)->craft_inv = loc; - } catch (SerializationError &) { - } - + } catch (SerializationError &) {} + return 0; } int LuaInventoryAction::l_set_count(lua_State *L) { LuaInventoryAction *o = checkobject(L, 1); - + s16 count = luaL_checkinteger(L, 2); - + switch (o->m_action->getType()) { case IAction::Move: ((IMoveAction *)o->m_action)->count = count; @@ -104,7 +103,7 @@ int LuaInventoryAction::l_set_count(lua_State *L) ((ICraftAction *)o->m_action)->count = count; break; } - + return 0; } @@ -128,25 +127,23 @@ LuaInventoryAction::~LuaInventoryAction() delete m_action; } -void LuaInventoryAction::readFullInventoryLocationInto( - lua_State *L, InventoryLocation *loc, std::string *list, s16 *index) +void LuaInventoryAction::readFullInventoryLocationInto(lua_State *L, InventoryLocation *loc, std::string *list, s16 *index) { try { loc->deSerialize(readParam<std::string>(L, 2)); std::string l = readParam<std::string>(L, 3); *list = l; *index = luaL_checkinteger(L, 4) - 1; - } catch (SerializationError &) { - } + } catch (SerializationError &) {} } int LuaInventoryAction::create_object(lua_State *L) { IAction type; std::string typeStr; - + typeStr = readParam<std::string>(L, 1); - + if (typeStr == "move") type = IAction::Move; else if (typeStr == "drop") @@ -209,7 +206,11 @@ void LuaInventoryAction::Register(lua_State *L) } const char LuaInventoryAction::className[] = "InventoryAction"; -const luaL_Reg LuaInventoryAction::methods[] = {luamethod(LuaInventoryAction, apply), - luamethod(LuaInventoryAction, from), luamethod(LuaInventoryAction, to), - luamethod(LuaInventoryAction, craft), - luamethod(LuaInventoryAction, set_count), {0, 0}}; +const luaL_Reg LuaInventoryAction::methods[] = { + luamethod(LuaInventoryAction, apply), + luamethod(LuaInventoryAction, from), + luamethod(LuaInventoryAction, to), + luamethod(LuaInventoryAction, craft), + luamethod(LuaInventoryAction, set_count), + {0,0} +}; diff --git a/src/script/lua_api/l_inventoryaction.h b/src/script/lua_api/l_inventoryaction.h index a4cc6cbe5..c1a96d010 100644 --- a/src/script/lua_api/l_inventoryaction.h +++ b/src/script/lua_api/l_inventoryaction.h @@ -20,46 +20,44 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "inventorymanager.h" #include "lua_api/l_base.h" -#define GET_MOVE_ACTION \ - LuaInventoryAction *o = checkobject(L, 1); \ - if (o->m_action->getType() == IAction::Craft) \ - return 0; \ +#define GET_MOVE_ACTION \ + LuaInventoryAction *o = checkobject(L, 1); \ + if (o->m_action->getType() == IAction::Craft) \ + return 0; \ MoveAction *act = dynamic_cast<MoveAction *>(o->m_action); -class LuaInventoryAction : public ModApiBase -{ +class LuaInventoryAction : public ModApiBase { private: InventoryAction *m_action; - - static void readFullInventoryLocationInto(lua_State *L, InventoryLocation *loc, - std::string *list, s16 *index); - + + static void readFullInventoryLocationInto(lua_State *L, InventoryLocation *loc, std::string *list, s16 *index); + static const char className[]; static const luaL_Reg methods[]; - + // Exported functions - + // garbage collector static int gc_object(lua_State *L); // __tostring metamethod static int mt_tostring(lua_State *L); - + // apply(self) static int l_apply(lua_State *L); - + // from(self, location, list, index) static int l_from(lua_State *L); - + // to(self, location, list, index) static int l_to(lua_State *L); - + // craft(self, location) static int l_craft(lua_State *L); // set_count(self, count) static int l_set_count(lua_State *L); - + public: LuaInventoryAction(const IAction &type); ~LuaInventoryAction(); @@ -69,6 +67,6 @@ public: static int create_object(lua_State *L); // Not callable from Lua static int create(lua_State *L, const IAction &type); - static LuaInventoryAction *checkobject(lua_State *L, int narg); + static LuaInventoryAction* checkobject(lua_State *L, int narg); static void Register(lua_State *L); }; diff --git a/src/script/lua_api/l_item.cpp b/src/script/lua_api/l_item.cpp index 9bbf9826b..bea7d122f 100644 --- a/src/script/lua_api/l_item.cpp +++ b/src/script/lua_api/l_item.cpp @@ -234,9 +234,12 @@ int LuaItemStack::l_to_table(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); const ItemStack &item = o->m_stack; - if (item.empty()) { + if(item.empty()) + { lua_pushnil(L); - } else { + } + else + { lua_newtable(L); lua_pushstring(L, item.name.c_str()); lua_setfield(L, -2, "name"); @@ -311,7 +314,8 @@ int LuaItemStack::l_get_definition(lua_State *L) lua_getfield(L, -1, "registered_items"); luaL_checktype(L, -1, LUA_TTABLE); lua_getfield(L, -1, item.name.c_str()); - if (lua_isnil(L, -1)) { + if(lua_isnil(L, -1)) + { lua_pop(L, 1); lua_getfield(L, -1, "unknown"); } @@ -326,7 +330,8 @@ int LuaItemStack::l_get_tool_capabilities(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; - const ToolCapabilities &prop = item.getToolCapabilities(getGameDef(L)->idef()); + const ToolCapabilities &prop = + item.getToolCapabilities(getGameDef(L)->idef()); push_tool_capabilities(L, prop); return 1; } @@ -370,8 +375,8 @@ int LuaItemStack::l_item_fits(lua_State *L) ItemStack newitem = read_item(L, 2, getGameDef(L)->idef()); ItemStack restitem; bool fits = item.itemFits(newitem, &restitem, getGameDef(L)->idef()); - lua_pushboolean(L, fits); // first return value - create(L, restitem); // second return value + lua_pushboolean(L, fits); // first return value + create(L, restitem); // second return value return 2; } @@ -382,7 +387,7 @@ int LuaItemStack::l_take_item(lua_State *L) LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; u32 takecount = 1; - if (!lua_isnone(L, 2)) + if(!lua_isnone(L, 2)) takecount = luaL_checkinteger(L, 2); ItemStack taken = item.takeItem(takecount); create(L, taken); @@ -396,22 +401,23 @@ int LuaItemStack::l_peek_item(lua_State *L) LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; u32 peekcount = 1; - if (!lua_isnone(L, 2)) + if(!lua_isnone(L, 2)) peekcount = lua_tointeger(L, 2); ItemStack peekaboo = item.peekItem(peekcount); create(L, peekaboo); return 1; } -LuaItemStack::LuaItemStack(const ItemStack &item) : m_stack(item) +LuaItemStack::LuaItemStack(const ItemStack &item): + m_stack(item) { } -const ItemStack &LuaItemStack::getItem() const +const ItemStack& LuaItemStack::getItem() const { return m_stack; } -ItemStack &LuaItemStack::getItem() +ItemStack& LuaItemStack::getItem() { return m_stack; } @@ -470,32 +476,44 @@ void LuaItemStack::Register(lua_State *L) lua_pushcfunction(L, mt_tostring); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Can be created from Lua (ItemStack(itemstack or itemstring or table or nil)) lua_register(L, className, create_object); } const char LuaItemStack::className[] = "ItemStack"; -const luaL_Reg LuaItemStack::methods[] = {luamethod(LuaItemStack, is_empty), - luamethod(LuaItemStack, get_name), luamethod(LuaItemStack, set_name), - luamethod(LuaItemStack, get_count), luamethod(LuaItemStack, set_count), - luamethod(LuaItemStack, get_wear), luamethod(LuaItemStack, set_wear), - luamethod(LuaItemStack, get_meta), luamethod(LuaItemStack, get_metadata), - luamethod(LuaItemStack, set_metadata), - luamethod(LuaItemStack, get_description), luamethod(LuaItemStack, clear), - luamethod(LuaItemStack, replace), luamethod(LuaItemStack, to_string), - luamethod(LuaItemStack, to_table), luamethod(LuaItemStack, get_stack_max), - luamethod(LuaItemStack, get_free_space), - luamethod(LuaItemStack, is_known), - luamethod(LuaItemStack, get_definition), - luamethod(LuaItemStack, get_tool_capabilities), - luamethod(LuaItemStack, add_wear), luamethod(LuaItemStack, add_item), - luamethod(LuaItemStack, item_fits), luamethod(LuaItemStack, take_item), - luamethod(LuaItemStack, peek_item), {0, 0}}; +const luaL_Reg LuaItemStack::methods[] = { + luamethod(LuaItemStack, is_empty), + luamethod(LuaItemStack, get_name), + luamethod(LuaItemStack, set_name), + luamethod(LuaItemStack, get_count), + luamethod(LuaItemStack, set_count), + luamethod(LuaItemStack, get_wear), + luamethod(LuaItemStack, set_wear), + luamethod(LuaItemStack, get_meta), + luamethod(LuaItemStack, get_metadata), + luamethod(LuaItemStack, set_metadata), + luamethod(LuaItemStack, get_description), + luamethod(LuaItemStack, clear), + luamethod(LuaItemStack, replace), + luamethod(LuaItemStack, to_string), + luamethod(LuaItemStack, to_table), + luamethod(LuaItemStack, get_stack_max), + luamethod(LuaItemStack, get_free_space), + luamethod(LuaItemStack, is_known), + luamethod(LuaItemStack, get_definition), + luamethod(LuaItemStack, get_tool_capabilities), + luamethod(LuaItemStack, add_wear), + luamethod(LuaItemStack, add_item), + luamethod(LuaItemStack, item_fits), + luamethod(LuaItemStack, take_item), + luamethod(LuaItemStack, peek_item), + {0,0} +}; /* ItemDefinition @@ -509,13 +527,15 @@ int ModApiItemMod::l_register_item_raw(lua_State *L) int table = 1; // Get the writable item and node definition managers from the server - IWritableItemDefManager *idef = getGameDef(L)->getWritableItemDefManager(); - NodeDefManager *ndef = getGameDef(L)->getWritableNodeDefManager(); + IWritableItemDefManager *idef = + getGameDef(L)->getWritableItemDefManager(); + NodeDefManager *ndef = + getGameDef(L)->getWritableNodeDefManager(); // Check if name is defined std::string name; lua_getfield(L, table, "name"); - if (lua_isstring(L, -1)) { + if(lua_isstring(L, -1)){ name = readParam<std::string>(L, -1); } else { throw LuaError("register_item_raw: name is not defined or not a string"); @@ -532,8 +552,8 @@ int ModApiItemMod::l_register_item_raw(lua_State *L) // Default to having client-side placement prediction for nodes // ("" in item definition sets it off) - if (def.node_placement_prediction == "__default") { - if (def.type == ITEM_NODE) + if(def.node_placement_prediction == "__default"){ + if(def.type == ITEM_NODE) def.node_placement_prediction = name; else def.node_placement_prediction = ""; @@ -553,12 +573,13 @@ int ModApiItemMod::l_register_item_raw(lua_State *L) content_t id = ndef->set(f.name, f); if (id > MAX_REGISTERED_CONTENT) { - throw LuaError("Number of registerable nodes (" + - itos(MAX_REGISTERED_CONTENT + 1) + - ") exceeded (" + name + ")"); + throw LuaError("Number of registerable nodes (" + + itos(MAX_REGISTERED_CONTENT+1) + + ") exceeded (" + name + ")"); } + } - + return 0; /* number of results */ } @@ -568,11 +589,13 @@ int ModApiItemMod::l_unregister_item_raw(lua_State *L) NO_MAP_LOCK_REQUIRED; std::string name = luaL_checkstring(L, 1); - IWritableItemDefManager *idef = getGameDef(L)->getWritableItemDefManager(); + IWritableItemDefManager *idef = + getGameDef(L)->getWritableItemDefManager(); // Unregister the node if (idef->get(name).type == ITEM_NODE) { - NodeDefManager *ndef = getGameDef(L)->getWritableNodeDefManager(); + NodeDefManager *ndef = + getGameDef(L)->getWritableNodeDefManager(); ndef->removeNode(name); } @@ -589,7 +612,8 @@ int ModApiItemMod::l_register_alias_raw(lua_State *L) std::string convert_to = luaL_checkstring(L, 2); // Get the writable item definition manager from the server - IWritableItemDefManager *idef = getGameDef(L)->getWritableItemDefManager(); + IWritableItemDefManager *idef = + getGameDef(L)->getWritableItemDefManager(); idef->registerAlias(name, convert_to); @@ -612,8 +636,8 @@ int ModApiItemMod::l_get_content_id(lua_State *L) content_t content_id; if (alias_name != name) { if (!ndef->getId(alias_name, content_id)) - throw LuaError("Unknown node: " + alias_name + " (from alias " + - name + ")"); + throw LuaError("Unknown node: " + alias_name + + " (from alias " + name + ")"); } else if (!ndef->getId(name, content_id)) { throw LuaError("Unknown node: " + name); } diff --git a/src/script/lua_api/l_item.h b/src/script/lua_api/l_item.h index 21110b83a..98744c071 100644 --- a/src/script/lua_api/l_item.h +++ b/src/script/lua_api/l_item.h @@ -20,10 +20,9 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once #include "lua_api/l_base.h" -#include "inventory.h" // ItemStack +#include "inventory.h" // ItemStack -class LuaItemStack : public ModApiBase -{ +class LuaItemStack : public ModApiBase { private: ItemStack m_stack; @@ -115,8 +114,8 @@ private: // Returns leftover item stack static int l_add_item(lua_State *L); - // item_fits(self, itemstack or itemstring or table or nil) -> true/false, - // itemstack First return value is true iff the new item fits fully into the stack + // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack + // First return value is true iff the new item fits fully into the stack // Second return value is the would-be-left-over item stack static int l_item_fits(lua_State *L); @@ -130,27 +129,26 @@ public: LuaItemStack(const ItemStack &item); ~LuaItemStack() = default; - const ItemStack &getItem() const; - ItemStack &getItem(); + const ItemStack& getItem() const; + ItemStack& getItem(); // LuaItemStack(itemstack or itemstring or table or nil) // Creates an LuaItemStack and leaves it on top of stack static int create_object(lua_State *L); // Not callable from Lua static int create(lua_State *L, const ItemStack &item); - static LuaItemStack *checkobject(lua_State *L, int narg); + static LuaItemStack* checkobject(lua_State *L, int narg); static void Register(lua_State *L); + }; -class ModApiItemMod : public ModApiBase -{ +class ModApiItemMod : public ModApiBase { private: static int l_register_item_raw(lua_State *L); static int l_unregister_item_raw(lua_State *L); static int l_register_alias_raw(lua_State *L); static int l_get_content_id(lua_State *L); static int l_get_name_from_content_id(lua_State *L); - public: static void Initialize(lua_State *L, int top); }; diff --git a/src/script/lua_api/l_itemstackmeta.cpp b/src/script/lua_api/l_itemstackmeta.cpp index 5a5c9934a..d1ba1bda4 100644 --- a/src/script/lua_api/l_itemstackmeta.cpp +++ b/src/script/lua_api/l_itemstackmeta.cpp @@ -26,17 +26,17 @@ with this program; if not, write to the Free Software Foundation, Inc., /* NodeMetaRef */ -ItemStackMetaRef *ItemStackMetaRef::checkobject(lua_State *L, int narg) +ItemStackMetaRef* ItemStackMetaRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); if (!ud) luaL_typerror(L, narg, className); - return *(ItemStackMetaRef **)ud; // unbox pointer + return *(ItemStackMetaRef**)ud; // unbox pointer } -Metadata *ItemStackMetaRef::getmeta(bool auto_create) +Metadata* ItemStackMetaRef::getmeta(bool auto_create) { return &istack->metadata; } @@ -68,8 +68,7 @@ int ItemStackMetaRef::l_set_tool_capabilities(lua_State *L) } // garbage collector -int ItemStackMetaRef::gc_object(lua_State *L) -{ +int ItemStackMetaRef::gc_object(lua_State *L) { ItemStackMetaRef *o = *(ItemStackMetaRef **)(lua_touserdata(L, 1)); delete o; return 0; @@ -80,7 +79,7 @@ int ItemStackMetaRef::gc_object(lua_State *L) void ItemStackMetaRef::create(lua_State *L, ItemStack *istack) { ItemStackMetaRef *o = new ItemStackMetaRef(istack); - // infostream<<"NodeMetaRef::create: o="<<o<<std::endl; + //infostream<<"NodeMetaRef::create: o="<<o<<std::endl; *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); @@ -95,7 +94,7 @@ void ItemStackMetaRef::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "metadata_class"); lua_pushlstring(L, className, strlen(className)); @@ -113,20 +112,28 @@ void ItemStackMetaRef::Register(lua_State *L) lua_pushcfunction(L, l_equals); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Cannot be created from Lua - // lua_register(L, className, create_object); + //lua_register(L, className, create_object); } const char ItemStackMetaRef::className[] = "ItemStackMetaRef"; -const luaL_Reg ItemStackMetaRef::methods[] = {luamethod(MetaDataRef, contains), - luamethod(MetaDataRef, get), luamethod(MetaDataRef, get_string), - luamethod(MetaDataRef, set_string), luamethod(MetaDataRef, get_int), - luamethod(MetaDataRef, set_int), luamethod(MetaDataRef, get_float), - luamethod(MetaDataRef, set_float), luamethod(MetaDataRef, to_table), - luamethod(MetaDataRef, from_table), luamethod(MetaDataRef, equals), - luamethod(ItemStackMetaRef, set_tool_capabilities), {0, 0}}; +const luaL_Reg ItemStackMetaRef::methods[] = { + luamethod(MetaDataRef, contains), + luamethod(MetaDataRef, get), + luamethod(MetaDataRef, get_string), + luamethod(MetaDataRef, set_string), + luamethod(MetaDataRef, get_int), + luamethod(MetaDataRef, set_int), + luamethod(MetaDataRef, get_float), + luamethod(MetaDataRef, set_float), + luamethod(MetaDataRef, to_table), + luamethod(MetaDataRef, from_table), + luamethod(MetaDataRef, equals), + luamethod(ItemStackMetaRef, set_tool_capabilities), + {0,0} +}; diff --git a/src/script/lua_api/l_itemstackmeta.h b/src/script/lua_api/l_itemstackmeta.h index 1351da9da..c3198be4f 100644 --- a/src/script/lua_api/l_itemstackmeta.h +++ b/src/script/lua_api/l_itemstackmeta.h @@ -36,7 +36,7 @@ private: static ItemStackMetaRef *checkobject(lua_State *L, int narg); - virtual Metadata *getmeta(bool auto_create); + virtual Metadata* getmeta(bool auto_create); virtual void clearMeta(); @@ -47,16 +47,18 @@ private: istack->metadata.setToolCapabilities(caps); } - void clearToolCapabilities() { istack->metadata.clearToolCapabilities(); } + void clearToolCapabilities() + { + istack->metadata.clearToolCapabilities(); + } // Exported functions static int l_set_tool_capabilities(lua_State *L); // garbage collector static int gc_object(lua_State *L); - public: - ItemStackMetaRef(ItemStack *istack) : istack(istack) {} + ItemStackMetaRef(ItemStack *istack): istack(istack) {} ~ItemStackMetaRef() = default; // Creates an ItemStackMetaRef and leaves it on top of stack diff --git a/src/script/lua_api/l_localplayer.cpp b/src/script/lua_api/l_localplayer.cpp index d94668ed4..8cd5d01e4 100644 --- a/src/script/lua_api/l_localplayer.cpp +++ b/src/script/lua_api/l_localplayer.cpp @@ -66,10 +66,10 @@ int LuaLocalPlayer::l_get_velocity(lua_State *L) int LuaLocalPlayer::l_set_velocity(lua_State *L) { LocalPlayer *player = getobject(L, 1); - + v3f pos = checkFloatPos(L, 2); player->setSpeed(pos); - + return 0; } @@ -91,7 +91,7 @@ int LuaLocalPlayer::l_set_yaw(lua_State *L) g_game->cam_view.camera_yaw = yaw; g_game->cam_view_target.camera_yaw = yaw; } - + return 0; } @@ -149,7 +149,7 @@ int LuaLocalPlayer::l_set_wield_index(lua_State *L) { LocalPlayer *player = getobject(L, 1); u32 index = luaL_checkinteger(L, 2) - 1; - + player->setWieldIndex(index); g_game->processItemSelection(&g_game->runData.new_playeritem); ItemStack selected_item, hand_item; @@ -290,7 +290,7 @@ int LuaLocalPlayer::l_get_control(lua_State *L) LocalPlayer *player = getobject(L, 1); const PlayerControl &c = player->getPlayerControl(); - auto set = [L](const char *name, bool value) { + auto set = [L] (const char *name, bool value) { lua_pushboolean(L, value); lua_setfield(L, -2, name); }; @@ -332,7 +332,7 @@ int LuaLocalPlayer::l_get_pos(lua_State *L) int LuaLocalPlayer::l_set_pos(lua_State *L) { LocalPlayer *player = getobject(L, 1); - + v3f pos = checkFloatPos(L, 2); player->setPosition(pos); getClient(L)->sendPlayerPos(); @@ -546,7 +546,8 @@ void LuaLocalPlayer::Register(lua_State *L) } const char LuaLocalPlayer::className[] = "LocalPlayer"; -const luaL_Reg LuaLocalPlayer::methods[] = {luamethod(LuaLocalPlayer, get_velocity), +const luaL_Reg LuaLocalPlayer::methods[] = { + luamethod(LuaLocalPlayer, get_velocity), luamethod(LuaLocalPlayer, set_velocity), luamethod(LuaLocalPlayer, get_yaw), luamethod(LuaLocalPlayer, set_yaw), @@ -572,14 +573,18 @@ const luaL_Reg LuaLocalPlayer::methods[] = {luamethod(LuaLocalPlayer, get_veloci luamethod(LuaLocalPlayer, get_last_look_vertical), // luamethod(LuaLocalPlayer, get_control), - luamethod(LuaLocalPlayer, get_breath), luamethod(LuaLocalPlayer, get_pos), + luamethod(LuaLocalPlayer, get_breath), + luamethod(LuaLocalPlayer, get_pos), luamethod(LuaLocalPlayer, set_pos), luamethod(LuaLocalPlayer, get_movement_acceleration), luamethod(LuaLocalPlayer, get_movement_speed), luamethod(LuaLocalPlayer, get_movement), luamethod(LuaLocalPlayer, get_armor_groups), - luamethod(LuaLocalPlayer, hud_add), luamethod(LuaLocalPlayer, hud_remove), - luamethod(LuaLocalPlayer, hud_change), luamethod(LuaLocalPlayer, hud_get), + luamethod(LuaLocalPlayer, hud_add), + luamethod(LuaLocalPlayer, hud_remove), + luamethod(LuaLocalPlayer, hud_change), + luamethod(LuaLocalPlayer, hud_get), luamethod(LuaLocalPlayer, get_object), - {0, 0}}; + {0, 0} +}; diff --git a/src/script/lua_api/l_mainmenu.cpp b/src/script/lua_api/l_mainmenu.cpp index 78a33b755..f32c477c2 100644 --- a/src/script/lua_api/l_mainmenu.cpp +++ b/src/script/lua_api/l_mainmenu.cpp @@ -41,6 +41,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/renderingengine.h" #include "network/networkprotocol.h" + /******************************************************************************/ std::string ModApiMainMenu::getTextData(lua_State *L, std::string name) { @@ -48,39 +49,39 @@ std::string ModApiMainMenu::getTextData(lua_State *L, std::string name) lua_getfield(L, -1, name.c_str()); - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) return ""; return luaL_checkstring(L, -1); } /******************************************************************************/ -int ModApiMainMenu::getIntegerData(lua_State *L, std::string name, bool &valid) +int ModApiMainMenu::getIntegerData(lua_State *L, std::string name,bool& valid) { lua_getglobal(L, "gamedata"); lua_getfield(L, -1, name.c_str()); - if (lua_isnil(L, -1)) { + if(lua_isnil(L, -1)) { valid = false; return -1; - } + } valid = true; return luaL_checkinteger(L, -1); } /******************************************************************************/ -int ModApiMainMenu::getBoolData(lua_State *L, std::string name, bool &valid) +int ModApiMainMenu::getBoolData(lua_State *L, std::string name,bool& valid) { lua_getglobal(L, "gamedata"); lua_getfield(L, -1, name.c_str()); - if (lua_isnil(L, -1)) { + if(lua_isnil(L, -1)) { valid = false; return false; - } + } valid = true; return readParam<bool>(L, -1); @@ -89,13 +90,13 @@ int ModApiMainMenu::getBoolData(lua_State *L, std::string name, bool &valid) /******************************************************************************/ int ModApiMainMenu::l_update_formspec(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); if (engine->m_startgame) return 0; - // read formspec + //read formspec std::string formspec(luaL_checkstring(L, 1)); if (engine->m_formspecgui != 0) { @@ -123,28 +124,28 @@ int ModApiMainMenu::l_set_formspec_prepend(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_start(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); - // update c++ gamedata from lua table + //update c++ gamedata from lua table bool valid = false; MainMenuData *data = engine->m_data; - data->selected_world = getIntegerData(L, "selected_world", valid) - 1; - data->simple_singleplayer_mode = getBoolData(L, "singleplayer", valid); + data->selected_world = getIntegerData(L, "selected_world",valid) -1; + data->simple_singleplayer_mode = getBoolData(L,"singleplayer",valid); data->do_reconnect = getBoolData(L, "do_reconnect", valid); if (!data->do_reconnect) { - data->name = getTextData(L, "playername"); - data->password = getTextData(L, "password"); - data->address = getTextData(L, "address"); - data->port = getTextData(L, "port"); + data->name = getTextData(L,"playername"); + data->password = getTextData(L,"password"); + data->address = getTextData(L,"address"); + data->port = getTextData(L,"port"); } - data->serverdescription = getTextData(L, "serverdescription"); - data->servername = getTextData(L, "servername"); + data->serverdescription = getTextData(L,"serverdescription"); + data->servername = getTextData(L,"servername"); - // close menu next time + //close menu next time engine->m_startgame = true; return 0; } @@ -152,7 +153,7 @@ int ModApiMainMenu::l_start(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_close(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); engine->m_kill = true; @@ -162,14 +163,14 @@ int ModApiMainMenu::l_close(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_set_background(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); std::string backgroundlevel(luaL_checkstring(L, 1)); std::string texturename(luaL_checkstring(L, 2)); bool tile_image = false; - bool retval = false; + bool retval = false; unsigned int minsize = 16; if (!lua_isnone(L, 3)) { @@ -181,36 +182,36 @@ int ModApiMainMenu::l_set_background(lua_State *L) } if (backgroundlevel == "background") { - retval |= engine->setTexture( - TEX_LAYER_BACKGROUND, texturename, tile_image, minsize); + retval |= engine->setTexture(TEX_LAYER_BACKGROUND, texturename, + tile_image, minsize); } if (backgroundlevel == "overlay") { - retval |= engine->setTexture( - TEX_LAYER_OVERLAY, texturename, tile_image, minsize); + retval |= engine->setTexture(TEX_LAYER_OVERLAY, texturename, + tile_image, minsize); } if (backgroundlevel == "header") { - retval |= engine->setTexture( - TEX_LAYER_HEADER, texturename, tile_image, minsize); + retval |= engine->setTexture(TEX_LAYER_HEADER, texturename, + tile_image, minsize); } if (backgroundlevel == "footer") { - retval |= engine->setTexture( - TEX_LAYER_FOOTER, texturename, tile_image, minsize); + retval |= engine->setTexture(TEX_LAYER_FOOTER, texturename, + tile_image, minsize); } - lua_pushboolean(L, retval); + lua_pushboolean(L,retval); return 1; } /******************************************************************************/ int ModApiMainMenu::l_set_clouds(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); - bool value = readParam<bool>(L, 1); + bool value = readParam<bool>(L,1); engine->m_clouds_enabled = value; @@ -227,7 +228,7 @@ int ModApiMainMenu::l_get_textlist_index(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_get_table_index(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); std::string tablename(luaL_checkstring(L, 1)); @@ -251,20 +252,20 @@ int ModApiMainMenu::l_get_worlds(lua_State *L) unsigned int index = 1; for (const WorldSpec &world : worlds) { - lua_pushnumber(L, index); + lua_pushnumber(L,index); lua_newtable(L); int top_lvl2 = lua_gettop(L); - lua_pushstring(L, "path"); + lua_pushstring(L,"path"); lua_pushstring(L, world.path.c_str()); lua_settable(L, top_lvl2); - lua_pushstring(L, "name"); + lua_pushstring(L,"name"); lua_pushstring(L, world.name.c_str()); lua_settable(L, top_lvl2); - lua_pushstring(L, "gameid"); + lua_pushstring(L,"gameid"); lua_pushstring(L, world.gameid.c_str()); lua_settable(L, top_lvl2); @@ -285,7 +286,7 @@ int ModApiMainMenu::l_get_favorites(lua_State *L) std::vector<ServerListSpec> servers; - if (listtype == "online") { + if(listtype == "online") { servers = ServerList::getOnline(); } else { servers = ServerList::getLocal(); @@ -304,8 +305,8 @@ int ModApiMainMenu::l_get_favorites(lua_State *L) if (!server["clients"].asString().empty()) { std::string clients_raw = server["clients"].asString(); - char *endptr = 0; - int numbervalue = strtol(clients_raw.c_str(), &endptr, 10); + char* endptr = 0; + int numbervalue = strtol(clients_raw.c_str(), &endptr,10); if ((!clients_raw.empty()) && (*endptr == 0)) { lua_pushstring(L, "clients"); @@ -317,8 +318,8 @@ int ModApiMainMenu::l_get_favorites(lua_State *L) if (!server["clients_max"].asString().empty()) { std::string clients_max_raw = server["clients_max"].asString(); - char *endptr = 0; - int numbervalue = strtol(clients_max_raw.c_str(), &endptr, 10); + char* endptr = 0; + int numbervalue = strtol(clients_max_raw.c_str(), &endptr,10); if ((!clients_max_raw.empty()) && (*endptr == 0)) { lua_pushstring(L, "clients_max"); @@ -449,22 +450,25 @@ int ModApiMainMenu::l_delete_favorite(lua_State *L) std::string listtype = "local"; - if (!lua_isnone(L, 2)) { - listtype = luaL_checkstring(L, 2); + if (!lua_isnone(L,2)) { + listtype = luaL_checkstring(L,2); } - if ((listtype != "local") && (listtype != "online")) + if ((listtype != "local") && + (listtype != "online")) return 0; - if (listtype == "online") { + + if(listtype == "online") { servers = ServerList::getOnline(); } else { servers = ServerList::getLocal(); } - int fav_idx = luaL_checkinteger(L, 1) - 1; + int fav_idx = luaL_checkinteger(L,1) -1; - if ((fav_idx >= 0) && (fav_idx < (int)servers.size())) { + if ((fav_idx >= 0) && + (fav_idx < (int) servers.size())) { ServerList::deleteEntry(servers[fav_idx]); } @@ -486,37 +490,37 @@ int ModApiMainMenu::l_get_games(lua_State *L) lua_newtable(L); int top_lvl2 = lua_gettop(L); - lua_pushstring(L, "id"); - lua_pushstring(L, game.id.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "id"); + lua_pushstring(L, game.id.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "path"); - lua_pushstring(L, game.path.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "path"); + lua_pushstring(L, game.path.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "type"); - lua_pushstring(L, "game"); - lua_settable(L, top_lvl2); + lua_pushstring(L, "type"); + lua_pushstring(L, "game"); + lua_settable(L, top_lvl2); - lua_pushstring(L, "gamemods_path"); - lua_pushstring(L, game.gamemods_path.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "gamemods_path"); + lua_pushstring(L, game.gamemods_path.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "name"); - lua_pushstring(L, game.name.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "name"); + lua_pushstring(L, game.name.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "author"); - lua_pushstring(L, game.author.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "author"); + lua_pushstring(L, game.author.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "release"); + lua_pushstring(L, "release"); lua_pushinteger(L, game.release); - lua_settable(L, top_lvl2); + lua_settable(L, top_lvl2); - lua_pushstring(L, "menuicon_path"); - lua_pushstring(L, game.menuicon_path.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "menuicon_path"); + lua_pushstring(L, game.menuicon_path.c_str()); + lua_settable(L, top_lvl2); lua_pushstring(L, "addon_mods_paths"); lua_newtable(L); @@ -525,7 +529,7 @@ int ModApiMainMenu::l_get_games(lua_State *L) for (const std::string &addon_mods_path : game.addon_mods_paths) { lua_pushnumber(L, internal_index); lua_pushstring(L, addon_mods_path.c_str()); - lua_settable(L, table2); + lua_settable(L, table2); internal_index++; } lua_settable(L, top_lvl2); @@ -594,11 +598,13 @@ int ModApiMainMenu::l_get_content_info(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_show_keys_menu(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); GUIKeyChangeMenu *kmenu = new GUIKeyChangeMenu(RenderingEngine::get_gui_env(), - engine->m_parent, -1, engine->m_menumanager, + engine->m_parent, + -1, + engine->m_menumanager, engine->m_texture_source); kmenu->drop(); return 0; @@ -607,14 +613,17 @@ int ModApiMainMenu::l_show_keys_menu(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_create_world(lua_State *L) { - const char *name = luaL_checkstring(L, 1); - int gameidx = luaL_checkinteger(L, 2) - 1; + const char *name = luaL_checkstring(L, 1); + int gameidx = luaL_checkinteger(L,2) -1; - std::string path = porting::path_user + DIR_DELIM "worlds" + DIR_DELIM + name; + std::string path = porting::path_user + DIR_DELIM + "worlds" + DIR_DELIM + + name; std::vector<SubgameSpec> games = getAvailableGames(); - if ((gameidx >= 0) && (gameidx < (int)games.size())) { + if ((gameidx >= 0) && + (gameidx < (int) games.size())) { // Create world if it doesn't exist if (!loadGameConfAndInitWorld(path, games[gameidx])) { @@ -633,7 +642,7 @@ int ModApiMainMenu::l_delete_world(lua_State *L) { int world_id = luaL_checkinteger(L, 1) - 1; std::vector<WorldSpec> worlds = getAvailableWorlds(); - if (world_id < 0 || world_id >= (int)worlds.size()) { + if (world_id < 0 || world_id >= (int) worlds.size()) { lua_pushstring(L, "Invalid world index"); return 1; } @@ -648,12 +657,12 @@ int ModApiMainMenu::l_delete_world(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_set_topleft_text(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); std::string text; - if (!lua_isnone(L, 1) && !lua_isnil(L, 1)) + if (!lua_isnone(L,1) && !lua_isnil(L,1)) text = luaL_checkstring(L, 1); engine->setTopleftText(text); @@ -676,11 +685,12 @@ int ModApiMainMenu::l_get_mapgen_names(lua_State *L) return 1; } + /******************************************************************************/ int ModApiMainMenu::l_get_modpath(lua_State *L) { std::string modpath = fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM + "mods" + DIR_DELIM); + porting::path_user + DIR_DELIM + "mods" + DIR_DELIM); lua_pushstring(L, modpath.c_str()); return 1; } @@ -689,7 +699,7 @@ int ModApiMainMenu::l_get_modpath(lua_State *L) int ModApiMainMenu::l_get_clientmodpath(lua_State *L) { std::string modpath = fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM + "clientmods" + DIR_DELIM); + porting::path_user + DIR_DELIM + "clientmods" + DIR_DELIM); lua_pushstring(L, modpath.c_str()); return 1; } @@ -698,7 +708,7 @@ int ModApiMainMenu::l_get_clientmodpath(lua_State *L) int ModApiMainMenu::l_get_gamepath(lua_State *L) { std::string gamepath = fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM + "games" + DIR_DELIM); + porting::path_user + DIR_DELIM + "games" + DIR_DELIM); lua_pushstring(L, gamepath.c_str()); return 1; } @@ -707,7 +717,7 @@ int ModApiMainMenu::l_get_gamepath(lua_State *L) int ModApiMainMenu::l_get_texturepath(lua_State *L) { std::string gamepath = fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM + "textures"); + porting::path_user + DIR_DELIM + "textures"); lua_pushstring(L, gamepath.c_str()); return 1; } @@ -715,7 +725,7 @@ int ModApiMainMenu::l_get_texturepath(lua_State *L) int ModApiMainMenu::l_get_texturepath_share(lua_State *L) { std::string gamepath = fs::RemoveRelativePathComponents( - porting::path_share + DIR_DELIM + "textures"); + porting::path_share + DIR_DELIM + "textures"); lua_pushstring(L, gamepath.c_str()); return 1; } @@ -727,8 +737,7 @@ int ModApiMainMenu::l_get_cache_path(lua_State *L) } /******************************************************************************/ -int ModApiMainMenu::l_create_dir(lua_State *L) -{ +int ModApiMainMenu::l_create_dir(lua_State *L) { const char *path = luaL_checkstring(L, 1); if (ModApiMainMenu::mayModifyPath(path)) { @@ -759,37 +768,38 @@ int ModApiMainMenu::l_delete_dir(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_copy_dir(lua_State *L) { - const char *source = luaL_checkstring(L, 1); - const char *destination = luaL_checkstring(L, 2); + const char *source = luaL_checkstring(L, 1); + const char *destination = luaL_checkstring(L, 2); bool keep_source = true; - if ((!lua_isnone(L, 3)) && (!lua_isnil(L, 3))) { - keep_source = readParam<bool>(L, 3); + if ((!lua_isnone(L,3)) && + (!lua_isnil(L,3))) { + keep_source = readParam<bool>(L,3); } std::string absolute_destination = fs::RemoveRelativePathComponents(destination); std::string absolute_source = fs::RemoveRelativePathComponents(source); if ((ModApiMainMenu::mayModifyPath(absolute_destination))) { - bool retval = fs::CopyDir(absolute_source, absolute_destination); + bool retval = fs::CopyDir(absolute_source,absolute_destination); if (retval && (!keep_source)) { retval &= fs::RecursiveDelete(absolute_source); } - lua_pushboolean(L, retval); + lua_pushboolean(L,retval); return 1; } - lua_pushboolean(L, false); + lua_pushboolean(L,false); return 1; } /******************************************************************************/ int ModApiMainMenu::l_extract_zip(lua_State *L) { - const char *zipfile = luaL_checkstring(L, 1); - const char *destination = luaL_checkstring(L, 2); + const char *zipfile = luaL_checkstring(L, 1); + const char *destination = luaL_checkstring(L, 2); std::string absolute_destination = fs::RemoveRelativePathComponents(destination); @@ -799,7 +809,7 @@ int ModApiMainMenu::l_extract_zip(lua_State *L) io::IFileSystem *fs = RenderingEngine::get_filesystem(); if (!fs->addFileArchive(zipfile, false, false, io::EFAT_ZIP)) { - lua_pushboolean(L, false); + lua_pushboolean(L,false); return 1; } @@ -808,36 +818,33 @@ int ModApiMainMenu::l_extract_zip(lua_State *L) /**********************************************************************/ /* WARNING this is not threadsafe!! */ /**********************************************************************/ - io::IFileArchive *opened_zip = - fs->getFileArchive(fs->getFileArchiveCount() - 1); + io::IFileArchive* opened_zip = + fs->getFileArchive(fs->getFileArchiveCount()-1); - const io::IFileList *files_in_zip = opened_zip->getFileList(); + const io::IFileList* files_in_zip = opened_zip->getFileList(); unsigned int number_of_files = files_in_zip->getFileCount(); - for (unsigned int i = 0; i < number_of_files; i++) { + for (unsigned int i=0; i < number_of_files; i++) { std::string fullpath = destination; fullpath += DIR_DELIM; fullpath += files_in_zip->getFullFileName(i).c_str(); std::string fullpath_dir = fs::RemoveLastPathComponent(fullpath); if (!files_in_zip->isDirectory(i)) { - if (!fs::PathExists(fullpath_dir) && - !fs::CreateAllDirs(fullpath_dir)) { - fs->removeFileArchive( - fs->getFileArchiveCount() - 1); - lua_pushboolean(L, false); + if (!fs::PathExists(fullpath_dir) && !fs::CreateAllDirs(fullpath_dir)) { + fs->removeFileArchive(fs->getFileArchiveCount()-1); + lua_pushboolean(L,false); return 1; } - io::IReadFile *toread = opened_zip->createAndOpenFile(i); + io::IReadFile* toread = opened_zip->createAndOpenFile(i); - FILE *targetfile = fopen(fullpath.c_str(), "wb"); + FILE *targetfile = fopen(fullpath.c_str(),"wb"); if (targetfile == NULL) { - fs->removeFileArchive( - fs->getFileArchiveCount() - 1); - lua_pushboolean(L, false); + fs->removeFileArchive(fs->getFileArchiveCount()-1); + lua_pushboolean(L,false); return 1; } @@ -846,18 +853,14 @@ int ModApiMainMenu::l_extract_zip(lua_State *L) while (total_read < toread->getSize()) { - unsigned int bytes_read = toread->read( - read_buffer, sizeof(read_buffer)); - if ((bytes_read == 0) || - (fwrite(read_buffer, 1, - bytes_read, - targetfile) != - bytes_read)) { + unsigned int bytes_read = + toread->read(read_buffer,sizeof(read_buffer)); + if ((bytes_read == 0 ) || + (fwrite(read_buffer, 1, bytes_read, targetfile) != bytes_read)) + { fclose(targetfile); - fs->removeFileArchive( - fs->getFileArchiveCount() - - 1); - lua_pushboolean(L, false); + fs->removeFileArchive(fs->getFileArchiveCount()-1); + lua_pushboolean(L,false); return 1; } total_read += bytes_read; @@ -865,24 +868,25 @@ int ModApiMainMenu::l_extract_zip(lua_State *L) fclose(targetfile); } + } - fs->removeFileArchive(fs->getFileArchiveCount() - 1); - lua_pushboolean(L, true); + fs->removeFileArchive(fs->getFileArchiveCount()-1); + lua_pushboolean(L,true); return 1; } - lua_pushboolean(L, false); + lua_pushboolean(L,false); return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_mainmenu_path(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); - lua_pushstring(L, engine->getScriptDir().c_str()); + lua_pushstring(L,engine->getScriptDir().c_str()); return 1; } @@ -892,31 +896,25 @@ bool ModApiMainMenu::mayModifyPath(const std::string &path) if (fs::PathStartsWith(path, fs::TempPath())) return true; - if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + - DIR_DELIM "games"))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "games"))) return true; - if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + - DIR_DELIM "mods"))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "mods"))) return true; - if (fs::PathStartsWith(path, - fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM "textures"))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "textures"))) return true; - if (fs::PathStartsWith(path, - fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM "worlds"))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "worlds"))) return true; - if (fs::PathStartsWith( - path, fs::RemoveRelativePathComponents(porting::path_cache))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_cache))) return true; return false; } + /******************************************************************************/ int ModApiMainMenu::l_may_modify_path(lua_State *L) { @@ -929,16 +927,21 @@ int ModApiMainMenu::l_may_modify_path(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_show_path_select_dialog(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); - const char *formname = luaL_checkstring(L, 1); - const char *title = luaL_checkstring(L, 2); + const char *formname= luaL_checkstring(L, 1); + const char *title = luaL_checkstring(L, 2); bool is_file_select = readParam<bool>(L, 3); - GUIFileSelectMenu *fileOpenMenu = new GUIFileSelectMenu( - RenderingEngine::get_gui_env(), engine->m_parent, -1, - engine->m_menumanager, title, formname, is_file_select); + GUIFileSelectMenu* fileOpenMenu = + new GUIFileSelectMenu(RenderingEngine::get_gui_env(), + engine->m_parent, + -1, + engine->m_menumanager, + title, + formname, + is_file_select); fileOpenMenu->setTextDest(engine->m_buttonhandler); fileOpenMenu->drop(); return 0; @@ -947,36 +950,34 @@ int ModApiMainMenu::l_show_path_select_dialog(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_download_file(lua_State *L) { - const char *url = luaL_checkstring(L, 1); + const char *url = luaL_checkstring(L, 1); const char *target = luaL_checkstring(L, 2); - // check path + //check path std::string absolute_destination = fs::RemoveRelativePathComponents(target); if (ModApiMainMenu::mayModifyPath(absolute_destination)) { - if (GUIEngine::downloadFile(url, absolute_destination)) { - lua_pushboolean(L, true); + if (GUIEngine::downloadFile(url,absolute_destination)) { + lua_pushboolean(L,true); return 1; } } else { errorstream << "DOWNLOAD denied: " << absolute_destination - << " isn't a allowed path" << std::endl; + << " isn't a allowed path" << std::endl; } - lua_pushboolean(L, false); + lua_pushboolean(L,false); return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_video_drivers(lua_State *L) { - std::vector<irr::video::E_DRIVER_TYPE> drivers = - RenderingEngine::getSupportedVideoDrivers(); + std::vector<irr::video::E_DRIVER_TYPE> drivers = RenderingEngine::getSupportedVideoDrivers(); lua_newtable(L); for (u32 i = 0; i != drivers.size(); i++) { - const char *name = RenderingEngine::getVideoDriverName(drivers[i]); - const char *fname = - RenderingEngine::getVideoDriverFriendlyName(drivers[i]); + const char *name = RenderingEngine::getVideoDriverName(drivers[i]); + const char *fname = RenderingEngine::getVideoDriverFriendlyName(drivers[i]); lua_newtable(L); lua_pushstring(L, name); @@ -993,8 +994,8 @@ int ModApiMainMenu::l_get_video_drivers(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_get_video_modes(lua_State *L) { - std::vector<core::vector3d<u32>> videomodes = - RenderingEngine::getSupportedVideoModes(); + std::vector<core::vector3d<u32> > videomodes + = RenderingEngine::getSupportedVideoModes(); lua_newtable(L); for (u32 i = 0; i != videomodes.size(); i++) { @@ -1026,24 +1027,24 @@ int ModApiMainMenu::l_get_screen_info(lua_State *L) { lua_newtable(L); int top = lua_gettop(L); - lua_pushstring(L, "density"); - lua_pushnumber(L, RenderingEngine::getDisplayDensity()); + lua_pushstring(L,"density"); + lua_pushnumber(L,RenderingEngine::getDisplayDensity()); lua_settable(L, top); - lua_pushstring(L, "display_width"); - lua_pushnumber(L, RenderingEngine::getDisplaySize().X); + lua_pushstring(L,"display_width"); + lua_pushnumber(L,RenderingEngine::getDisplaySize().X); lua_settable(L, top); - lua_pushstring(L, "display_height"); - lua_pushnumber(L, RenderingEngine::getDisplaySize().Y); + lua_pushstring(L,"display_height"); + lua_pushnumber(L,RenderingEngine::getDisplaySize().Y); lua_settable(L, top); const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); - lua_pushstring(L, "window_width"); + lua_pushstring(L,"window_width"); lua_pushnumber(L, window_size.X); lua_settable(L, top); - lua_pushstring(L, "window_height"); + lua_pushstring(L,"window_height"); lua_pushnumber(L, window_size.Y); lua_settable(L, top); return 1; @@ -1073,12 +1074,12 @@ int ModApiMainMenu::l_open_url(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_do_async_callback(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); size_t func_length, param_length; - const char *serialized_func_raw = luaL_checklstring(L, 1, &func_length); + const char* serialized_func_raw = luaL_checklstring(L, 1, &func_length); - const char *serialized_param_raw = luaL_checklstring(L, 2, ¶m_length); + const char* serialized_param_raw = luaL_checklstring(L, 2, ¶m_length); sanity_check(serialized_func_raw != NULL); sanity_check(serialized_param_raw != NULL); @@ -1152,8 +1153,8 @@ void ModApiMainMenu::InitializeAsync(lua_State *L, int top) API_FCT(create_dir); API_FCT(delete_dir); API_FCT(copy_dir); - // API_FCT(extract_zip); //TODO remove dependency to GuiEngine + //API_FCT(extract_zip); //TODO remove dependency to GuiEngine API_FCT(may_modify_path); API_FCT(download_file); - // API_FCT(gettext); (gettext lib isn't threadsafe) + //API_FCT(gettext); (gettext lib isn't threadsafe) } diff --git a/src/script/lua_api/l_mainmenu.h b/src/script/lua_api/l_mainmenu.h index c5875e797..5a16b3bfe 100644 --- a/src/script/lua_api/l_mainmenu.h +++ b/src/script/lua_api/l_mainmenu.h @@ -24,7 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., class AsyncEngine; /** Implementation of lua api support for mainmenu */ -class ModApiMainMenu : public ModApiBase +class ModApiMainMenu: public ModApiBase { private: @@ -42,7 +42,7 @@ private: * @param name name of variable to read * @return integer value of requested variable */ - static int getIntegerData(lua_State *L, std::string name, bool &valid); + static int getIntegerData(lua_State *L, std::string name,bool& valid); /** * read a bool variable from gamedata table within lua stack @@ -50,7 +50,7 @@ private: * @param name name of variable to read * @return bool value of requested variable */ - static int getBoolData(lua_State *L, std::string name, bool &valid); + static int getBoolData(lua_State *L, std::string name,bool& valid); /** * Checks if a path may be modified. Paths in the temp directory or the user @@ -60,7 +60,7 @@ private: */ static bool mayModifyPath(const std::string &path); - // api calls + //api calls static int l_start(lua_State *L); @@ -80,13 +80,13 @@ private: static int l_gettext(lua_State *L); - // packages + //packages static int l_get_games(lua_State *L); static int l_get_content_info(lua_State *L); - // gui + //gui static int l_show_keys_menu(lua_State *L); @@ -108,7 +108,7 @@ private: static int l_get_screen_info(lua_State *L); - // filesystem + //filesystem static int l_get_mainmenu_path(lua_State *L); @@ -140,7 +140,7 @@ private: static int l_get_video_modes(lua_State *L); - // version compatibility + //version compatibility static int l_get_min_supp_proto(lua_State *L); static int l_get_max_supp_proto(lua_State *L); @@ -148,10 +148,12 @@ private: // other static int l_open_url(lua_State *L); + // async static int l_do_async_callback(lua_State *L); public: + /** * initialize this API module * @param L lua stack to initialize @@ -160,4 +162,5 @@ public: static void Initialize(lua_State *L, int top); static void InitializeAsync(lua_State *L, int top); + }; diff --git a/src/script/lua_api/l_mapgen.cpp b/src/script/lua_api/l_mapgen.cpp index d52191a29..834938e56 100644 --- a/src/script/lua_api/l_mapgen.cpp +++ b/src/script/lua_api/l_mapgen.cpp @@ -37,73 +37,81 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "settings.h" #include "log.h" -struct EnumString ModApiMapgen::es_BiomeTerrainType[] = { - {BIOMETYPE_NORMAL, "normal"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_BiomeTerrainType[] = +{ + {BIOMETYPE_NORMAL, "normal"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_DecorationType[] = { - {DECO_SIMPLE, "simple"}, - {DECO_SCHEMATIC, "schematic"}, - {DECO_LSYSTEM, "lsystem"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_DecorationType[] = +{ + {DECO_SIMPLE, "simple"}, + {DECO_SCHEMATIC, "schematic"}, + {DECO_LSYSTEM, "lsystem"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_MapgenObject[] = { - {MGOBJ_VMANIP, "voxelmanip"}, - {MGOBJ_HEIGHTMAP, "heightmap"}, - {MGOBJ_BIOMEMAP, "biomemap"}, - {MGOBJ_HEATMAP, "heatmap"}, - {MGOBJ_HUMIDMAP, "humiditymap"}, - {MGOBJ_GENNOTIFY, "gennotify"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_MapgenObject[] = +{ + {MGOBJ_VMANIP, "voxelmanip"}, + {MGOBJ_HEIGHTMAP, "heightmap"}, + {MGOBJ_BIOMEMAP, "biomemap"}, + {MGOBJ_HEATMAP, "heatmap"}, + {MGOBJ_HUMIDMAP, "humiditymap"}, + {MGOBJ_GENNOTIFY, "gennotify"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_OreType[] = { - {ORE_SCATTER, "scatter"}, - {ORE_SHEET, "sheet"}, - {ORE_PUFF, "puff"}, - {ORE_BLOB, "blob"}, - {ORE_VEIN, "vein"}, - {ORE_STRATUM, "stratum"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_OreType[] = +{ + {ORE_SCATTER, "scatter"}, + {ORE_SHEET, "sheet"}, + {ORE_PUFF, "puff"}, + {ORE_BLOB, "blob"}, + {ORE_VEIN, "vein"}, + {ORE_STRATUM, "stratum"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_Rotation[] = { - {ROTATE_0, "0"}, - {ROTATE_90, "90"}, - {ROTATE_180, "180"}, - {ROTATE_270, "270"}, - {ROTATE_RAND, "random"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_Rotation[] = +{ + {ROTATE_0, "0"}, + {ROTATE_90, "90"}, + {ROTATE_180, "180"}, + {ROTATE_270, "270"}, + {ROTATE_RAND, "random"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_SchematicFormatType[] = { - {SCHEM_FMT_HANDLE, "handle"}, - {SCHEM_FMT_MTS, "mts"}, - {SCHEM_FMT_LUA, "lua"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_SchematicFormatType[] = +{ + {SCHEM_FMT_HANDLE, "handle"}, + {SCHEM_FMT_MTS, "mts"}, + {SCHEM_FMT_LUA, "lua"}, + {0, NULL}, }; ObjDef *get_objdef(lua_State *L, int index, const ObjDefManager *objmgr); -Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr); +Biome *get_or_load_biome(lua_State *L, int index, + BiomeManager *biomemgr); Biome *read_biome_def(lua_State *L, int index, const NodeDefManager *ndef); -size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, - std::unordered_set<biome_t> *biome_id_list); +size_t get_biome_list(lua_State *L, int index, + BiomeManager *biomemgr, std::unordered_set<biome_t> *biome_id_list); -Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *schemmgr, - StringMap *replace_names); +Schematic *get_or_load_schematic(lua_State *L, int index, + SchematicManager *schemmgr, StringMap *replace_names); Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, - StringMap *replace_names); -Schematic *load_schematic_from_def(lua_State *L, int index, const NodeDefManager *ndef, - StringMap *replace_names); -bool read_schematic_def(lua_State *L, int index, Schematic *schem, - std::vector<std::string> *names); + StringMap *replace_names); +Schematic *load_schematic_from_def(lua_State *L, int index, + const NodeDefManager *ndef, StringMap *replace_names); +bool read_schematic_def(lua_State *L, int index, + Schematic *schem, std::vector<std::string> *names); bool read_deco_simple(lua_State *L, DecoSimple *deco); bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco); + /////////////////////////////////////////////////////////////////////////////// ObjDef *get_objdef(lua_State *L, int index, const ObjDefManager *objmgr) @@ -124,8 +132,8 @@ ObjDef *get_objdef(lua_State *L, int index, const ObjDefManager *objmgr) /////////////////////////////////////////////////////////////////////////////// -Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *schemmgr, - StringMap *replace_names) +Schematic *get_or_load_schematic(lua_State *L, int index, + SchematicManager *schemmgr, StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; @@ -134,7 +142,8 @@ Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *sche if (schem) return schem; - schem = load_schematic(L, index, schemmgr->getNodeDef(), replace_names); + schem = load_schematic(L, index, schemmgr->getNodeDef(), + replace_names); if (!schem) return NULL; @@ -146,8 +155,9 @@ Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *sche return schem; } + Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, - StringMap *replace_names) + StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; @@ -155,7 +165,8 @@ Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, Schematic *schem = NULL; if (lua_istable(L, index)) { - schem = load_schematic_from_def(L, index, ndef, replace_names); + schem = load_schematic_from_def(L, index, ndef, + replace_names); if (!schem) { delete schem; return NULL; @@ -167,10 +178,10 @@ Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, std::string filepath = lua_tostring(L, index); if (!fs::IsPathAbsolute(filepath)) - filepath = ModApiBase::getCurrentModPath(L) + DIR_DELIM + - filepath; + filepath = ModApiBase::getCurrentModPath(L) + DIR_DELIM + filepath; - if (!schem->loadSchematicFromFile(filepath, ndef, replace_names)) { + if (!schem->loadSchematicFromFile(filepath, ndef, + replace_names)) { delete schem; return NULL; } @@ -179,8 +190,9 @@ Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, return schem; } -Schematic *load_schematic_from_def(lua_State *L, int index, const NodeDefManager *ndef, - StringMap *replace_names) + +Schematic *load_schematic_from_def(lua_State *L, int index, + const NodeDefManager *ndef, StringMap *replace_names) { Schematic *schem = SchematicManager::create(SCHEMATIC_NORMAL); @@ -195,8 +207,7 @@ Schematic *load_schematic_from_def(lua_State *L, int index, const NodeDefManager if (replace_names) { for (size_t i = 0; i != num_nodes; i++) { - StringMap::iterator it = - replace_names->find(schem->m_nodenames[i]); + StringMap::iterator it = replace_names->find(schem->m_nodenames[i]); if (it != replace_names->end()) schem->m_nodenames[i] = it->second; } @@ -208,8 +219,9 @@ Schematic *load_schematic_from_def(lua_State *L, int index, const NodeDefManager return schem; } -bool read_schematic_def(lua_State *L, int index, Schematic *schem, - std::vector<std::string> *names) + +bool read_schematic_def(lua_State *L, int index, + Schematic *schem, std::vector<std::string> *names) { if (!lua_istable(L, index)) return false; @@ -239,21 +251,19 @@ bool read_schematic_def(lua_State *L, int index, Schematic *schem, //// Read name std::string name; if (!getstringfield(L, -1, "name", name)) - throw LuaError("Schematic data definition with missing name " - "field"); + throw LuaError("Schematic data definition with missing name field"); //// Read param1/prob u8 param1; if (!getintfield(L, -1, "param1", param1) && - !getintfield(L, -1, "prob", param1)) + !getintfield(L, -1, "prob", param1)) param1 = MTSCHEM_PROB_ALWAYS_OLD; //// Read param2 u8 param2 = getintfield_default(L, -1, "param2", 0); //// Find or add new nodename-to-ID mapping - std::unordered_map<std::string, content_t>::iterator it = - name_id_map.find(name); + std::unordered_map<std::string, content_t>::iterator it = name_id_map.find(name); content_t name_index; if (it != name_id_map.end()) { name_index = it->second; @@ -274,14 +284,14 @@ bool read_schematic_def(lua_State *L, int index, Schematic *schem, if (i != numnodes) { errorstream << "read_schematic_def: incorrect number of " - "nodes provided in raw schematic data (got " - << i << ", expected " << numnodes << ")." << std::endl; + "nodes provided in raw schematic data (got " << i << + ", expected " << numnodes << ")." << std::endl; return false; } //// Get Y-slice probability values (if present) schem->slice_probs = new u8[size.Y]; - for (i = 0; i != (u32)size.Y; i++) + for (i = 0; i != (u32) size.Y; i++) schem->slice_probs[i] = MTSCHEM_PROB_ALWAYS; lua_getfield(L, index, "yslice_prob"); @@ -289,8 +299,7 @@ bool read_schematic_def(lua_State *L, int index, Schematic *schem, for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { u16 ypos; if (!getintfield(L, -1, "ypos", ypos) || (ypos >= size.Y) || - !getintfield(L, -1, "prob", - schem->slice_probs[ypos])) + !getintfield(L, -1, "prob", schem->slice_probs[ypos])) continue; schem->slice_probs[ypos] >>= 1; @@ -300,6 +309,7 @@ bool read_schematic_def(lua_State *L, int index, Schematic *schem, return true; } + void read_schematic_replacements(lua_State *L, int index, StringMap *replace_names) { if (index < 0) @@ -313,25 +323,21 @@ void read_schematic_replacements(lua_State *L, int index, StringMap *replace_nam if (lua_istable(L, -1)) { // Old {{"x", "y"}, ...} format lua_rawgeti(L, -1, 1); if (!lua_isstring(L, -1)) - throw LuaError("schematics: replace_from field is not a " - "string"); + throw LuaError("schematics: replace_from field is not a string"); replace_from = lua_tostring(L, -1); lua_pop(L, 1); lua_rawgeti(L, -1, 2); if (!lua_isstring(L, -1)) - throw LuaError("schematics: replace_to field is not a " - "string"); + throw LuaError("schematics: replace_to field is not a string"); replace_to = lua_tostring(L, -1); lua_pop(L, 1); } else { // New {x = "y", ...} format if (!lua_isstring(L, -2)) - throw LuaError("schematics: replace_from field is not a " - "string"); + throw LuaError("schematics: replace_from field is not a string"); replace_from = lua_tostring(L, -2); if (!lua_isstring(L, -1)) - throw LuaError("schematics: replace_to field is not a " - "string"); + throw LuaError("schematics: replace_to field is not a string"); replace_to = lua_tostring(L, -1); } @@ -363,41 +369,42 @@ Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr) return biome; } + Biome *read_biome_def(lua_State *L, int index, const NodeDefManager *ndef) { if (!lua_istable(L, index)) return NULL; BiomeType biometype = (BiomeType)getenumfield(L, index, "type", - ModApiMapgen::es_BiomeTerrainType, BIOMETYPE_NORMAL); + ModApiMapgen::es_BiomeTerrainType, BIOMETYPE_NORMAL); Biome *b = BiomeManager::create(biometype); - b->name = getstringfield_default(L, index, "name", ""); - b->depth_top = getintfield_default(L, index, "depth_top", 0); - b->depth_filler = getintfield_default(L, index, "depth_filler", -31000); - b->depth_water_top = getintfield_default(L, index, "depth_water_top", 0); - b->depth_riverbed = getintfield_default(L, index, "depth_riverbed", 0); - b->heat_point = getfloatfield_default(L, index, "heat_point", 0.f); - b->humidity_point = getfloatfield_default(L, index, "humidity_point", 0.f); - b->vertical_blend = getintfield_default(L, index, "vertical_blend", 0); - b->flags = 0; // reserved + b->name = getstringfield_default(L, index, "name", ""); + b->depth_top = getintfield_default(L, index, "depth_top", 0); + b->depth_filler = getintfield_default(L, index, "depth_filler", -31000); + b->depth_water_top = getintfield_default(L, index, "depth_water_top", 0); + b->depth_riverbed = getintfield_default(L, index, "depth_riverbed", 0); + b->heat_point = getfloatfield_default(L, index, "heat_point", 0.f); + b->humidity_point = getfloatfield_default(L, index, "humidity_point", 0.f); + b->vertical_blend = getintfield_default(L, index, "vertical_blend", 0); + b->flags = 0; // reserved b->min_pos = getv3s16field_default( - L, index, "min_pos", v3s16(-31000, -31000, -31000)); + L, index, "min_pos", v3s16(-31000, -31000, -31000)); getintfield(L, index, "y_min", b->min_pos.Y); b->max_pos = getv3s16field_default( - L, index, "max_pos", v3s16(31000, 31000, 31000)); + L, index, "max_pos", v3s16(31000, 31000, 31000)); getintfield(L, index, "y_max", b->max_pos.Y); std::vector<std::string> &nn = b->m_nodenames; - nn.push_back(getstringfield_default(L, index, "node_top", "")); - nn.push_back(getstringfield_default(L, index, "node_filler", "")); - nn.push_back(getstringfield_default(L, index, "node_stone", "")); - nn.push_back(getstringfield_default(L, index, "node_water_top", "")); - nn.push_back(getstringfield_default(L, index, "node_water", "")); - nn.push_back(getstringfield_default(L, index, "node_river_water", "")); - nn.push_back(getstringfield_default(L, index, "node_riverbed", "")); - nn.push_back(getstringfield_default(L, index, "node_dust", "")); + nn.push_back(getstringfield_default(L, index, "node_top", "")); + nn.push_back(getstringfield_default(L, index, "node_filler", "")); + nn.push_back(getstringfield_default(L, index, "node_stone", "")); + nn.push_back(getstringfield_default(L, index, "node_water_top", "")); + nn.push_back(getstringfield_default(L, index, "node_water", "")); + nn.push_back(getstringfield_default(L, index, "node_river_water", "")); + nn.push_back(getstringfield_default(L, index, "node_riverbed", "")); + nn.push_back(getstringfield_default(L, index, "node_dust", "")); size_t nnames = getstringlistfield(L, index, "node_cave_liquid", &nn); // If no cave liquids defined, set list to "ignore" to trigger old hardcoded @@ -408,16 +415,17 @@ Biome *read_biome_def(lua_State *L, int index, const NodeDefManager *ndef) } b->m_nnlistsizes.push_back(nnames); - nn.push_back(getstringfield_default(L, index, "node_dungeon", "")); - nn.push_back(getstringfield_default(L, index, "node_dungeon_alt", "")); + nn.push_back(getstringfield_default(L, index, "node_dungeon", "")); + nn.push_back(getstringfield_default(L, index, "node_dungeon_alt", "")); nn.push_back(getstringfield_default(L, index, "node_dungeon_stair", "")); ndef->pendNodeResolve(b); return b; } -size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, - std::unordered_set<biome_t> *biome_id_list) + +size_t get_biome_list(lua_State *L, int index, + BiomeManager *biomemgr, std::unordered_set<biome_t> *biome_id_list) { if (index < 0) index = lua_gettop(L) + 1 + index; @@ -436,9 +444,8 @@ size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, Biome *biome = get_or_load_biome(L, index, biomemgr); if (!biome) { infostream << "get_biome_list: failed to get biome '" - << (lua_isstring(L, index) ? lua_tostring(L, index) - : "") - << "'." << std::endl; + << (lua_isstring(L, index) ? lua_tostring(L, index) : "") + << "'." << std::endl; return 1; } @@ -456,8 +463,8 @@ size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, if (!biome) { fail_count++; infostream << "get_biome_list: failed to get biome '" - << (lua_isstring(L, -1) ? lua_tostring(L, -1) : "") - << "'" << std::endl; + << (lua_isstring(L, -1) ? lua_tostring(L, -1) : "") + << "'" << std::endl; continue; } @@ -492,6 +499,7 @@ int ModApiMapgen::l_get_biome_id(lua_State *L) return 1; } + // get_biome_name(biome_id) // returns the biome name string int ModApiMapgen::l_get_biome_name(lua_State *L) @@ -510,6 +518,7 @@ int ModApiMapgen::l_get_biome_name(lua_State *L) return 1; } + // get_heat(pos) // returns the heat at the position int ModApiMapgen::l_get_heat(lua_State *L) @@ -522,11 +531,12 @@ int ModApiMapgen::l_get_heat(lua_State *L) NoiseParams np_heat_blend; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; - if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat", &np_heat) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_heat_blend", &np_heat_blend)) + if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat", + &np_heat) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat_blend", + &np_heat_blend)) return 0; std::string value; @@ -547,6 +557,7 @@ int ModApiMapgen::l_get_heat(lua_State *L) return 1; } + // get_humidity(pos) // returns the humidity at the position int ModApiMapgen::l_get_humidity(lua_State *L) @@ -559,12 +570,12 @@ int ModApiMapgen::l_get_humidity(lua_State *L) NoiseParams np_humidity_blend; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; - if (!settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_humidity", &np_humidity) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_humidity_blend", &np_humidity_blend)) + if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity", + &np_humidity) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity_blend", + &np_humidity_blend)) return 0; std::string value; @@ -578,14 +589,15 @@ int ModApiMapgen::l_get_humidity(lua_State *L) if (!bmgr) return 0; - float humidity = bmgr->getHumidityAtPosOriginal( - pos, np_humidity, np_humidity_blend, seed); + float humidity = bmgr->getHumidityAtPosOriginal(pos, np_humidity, + np_humidity_blend, seed); lua_pushnumber(L, humidity); return 1; } + // get_biome_data(pos) // returns a table containing the biome id, heat and humidity at the position int ModApiMapgen::l_get_biome_data(lua_State *L) @@ -600,15 +612,16 @@ int ModApiMapgen::l_get_biome_data(lua_State *L) NoiseParams np_humidity_blend; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; - - if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat", &np_heat) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_heat_blend", &np_heat_blend) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_humidity", &np_humidity) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_humidity_blend", &np_humidity_blend)) + getServer(L)->getEmergeManager()->map_settings_mgr; + + if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat", + &np_heat) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat_blend", + &np_heat_blend) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity", + &np_humidity) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity_blend", + &np_humidity_blend)) return 0; std::string value; @@ -626,8 +639,8 @@ int ModApiMapgen::l_get_biome_data(lua_State *L) if (!heat) return 0; - float humidity = bmgr->getHumidityAtPosOriginal( - pos, np_humidity, np_humidity_blend, seed); + float humidity = bmgr->getHumidityAtPosOriginal(pos, np_humidity, + np_humidity_blend, seed); if (!humidity) return 0; @@ -649,6 +662,7 @@ int ModApiMapgen::l_get_biome_data(lua_State *L) return 1; } + // get_mapgen_object(objectname) // returns the requested object used during map generation int ModApiMapgen::l_get_mapgen_object(lua_State *L) @@ -742,7 +756,7 @@ int ModApiMapgen::l_get_mapgen_object(lua_State *L) return 1; } case MGOBJ_GENNOTIFY: { - std::map<std::string, std::vector<v3s16>> event_map; + std::map<std::string, std::vector<v3s16> >event_map; mg->gennotify.getEvents(event_map); @@ -765,6 +779,7 @@ int ModApiMapgen::l_get_mapgen_object(lua_State *L) return 0; } + // get_spawn_level(x = num, z = num) int ModApiMapgen::l_get_spawn_level(lua_State *L) { @@ -785,17 +800,18 @@ int ModApiMapgen::l_get_spawn_level(lua_State *L) return 1; } + int ModApiMapgen::l_get_mapgen_params(lua_State *L) { NO_MAP_LOCK_REQUIRED; log_deprecated(L, "get_mapgen_params is deprecated; " - "use get_mapgen_setting instead"); + "use get_mapgen_setting instead"); std::string value; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; lua_newtable(L); @@ -825,6 +841,7 @@ int ModApiMapgen::l_get_mapgen_params(lua_State *L) return 1; } + // set_mapgen_params(params) // set mapgen parameters int ModApiMapgen::l_set_mapgen_params(lua_State *L) @@ -832,18 +849,17 @@ int ModApiMapgen::l_set_mapgen_params(lua_State *L) NO_MAP_LOCK_REQUIRED; log_deprecated(L, "set_mapgen_params is deprecated; " - "use set_mapgen_setting instead"); + "use set_mapgen_setting instead"); if (!lua_istable(L, 1)) return 0; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; lua_getfield(L, 1, "mgname"); if (lua_isstring(L, -1)) - settingsmgr->setMapSetting( - "mg_name", readParam<std::string>(L, -1), true); + settingsmgr->setMapSetting("mg_name", readParam<std::string>(L, -1), true); lua_getfield(L, 1, "seed"); if (lua_isnumber(L, -1)) @@ -851,21 +867,18 @@ int ModApiMapgen::l_set_mapgen_params(lua_State *L) lua_getfield(L, 1, "water_level"); if (lua_isnumber(L, -1)) - settingsmgr->setMapSetting( - "water_level", readParam<std::string>(L, -1), true); + settingsmgr->setMapSetting("water_level", readParam<std::string>(L, -1), true); lua_getfield(L, 1, "chunksize"); if (lua_isnumber(L, -1)) - settingsmgr->setMapSetting( - "chunksize", readParam<std::string>(L, -1), true); + settingsmgr->setMapSetting("chunksize", readParam<std::string>(L, -1), true); warn_if_field_exists(L, 1, "flagmask", - "Obsolete: flags field now includes unset flags."); + "Obsolete: flags field now includes unset flags."); lua_getfield(L, 1, "flags"); if (lua_isstring(L, -1)) - settingsmgr->setMapSetting( - "mg_flags", readParam<std::string>(L, -1), true); + settingsmgr->setMapSetting("mg_flags", readParam<std::string>(L, -1), true); return 0; } @@ -877,7 +890,7 @@ int ModApiMapgen::l_get_mapgen_setting(lua_State *L) std::string value; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); if (!settingsmgr->getMapSetting(name, &value)) @@ -894,7 +907,7 @@ int ModApiMapgen::l_get_mapgen_setting_noiseparams(lua_State *L) NoiseParams np; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); if (!settingsmgr->getMapSettingNoiseParams(name, &np)) @@ -911,20 +924,21 @@ int ModApiMapgen::l_set_mapgen_setting(lua_State *L) NO_MAP_LOCK_REQUIRED; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; - const char *name = luaL_checkstring(L, 1); - const char *value = luaL_checkstring(L, 2); + const char *name = luaL_checkstring(L, 1); + const char *value = luaL_checkstring(L, 2); bool override_meta = readParam<bool>(L, 3, false); if (!settingsmgr->setMapSetting(name, value, override_meta)) { - errorstream << "set_mapgen_setting: cannot set '" << name - << "' after initialization" << std::endl; + errorstream << "set_mapgen_setting: cannot set '" + << name << "' after initialization" << std::endl; } return 0; } + // set_mapgen_setting_noiseparams(name, noiseparams, set_default) // set mapgen config values for noise parameters int ModApiMapgen::l_set_mapgen_setting_noiseparams(lua_State *L) @@ -932,27 +946,28 @@ int ModApiMapgen::l_set_mapgen_setting_noiseparams(lua_State *L) NO_MAP_LOCK_REQUIRED; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); NoiseParams np; if (!read_noiseparams(L, 2, &np)) { errorstream << "set_mapgen_setting_noiseparams: cannot set '" << name - << "'; invalid noiseparams table" << std::endl; + << "'; invalid noiseparams table" << std::endl; return 0; } bool override_meta = readParam<bool>(L, 3, false); if (!settingsmgr->setMapSettingNoiseParams(name, &np, override_meta)) { - errorstream << "set_mapgen_setting_noiseparams: cannot set '" << name - << "' after initialization" << std::endl; + errorstream << "set_mapgen_setting_noiseparams: cannot set '" + << name << "' after initialization" << std::endl; } return 0; } + // set_noiseparams(name, noiseparams, set_default) // set global config values for noise parameters int ModApiMapgen::l_set_noiseparams(lua_State *L) @@ -964,7 +979,7 @@ int ModApiMapgen::l_set_noiseparams(lua_State *L) NoiseParams np; if (!read_noiseparams(L, 2, &np)) { errorstream << "set_noiseparams: cannot set '" << name - << "'; invalid noiseparams table" << std::endl; + << "'; invalid noiseparams table" << std::endl; return 0; } @@ -975,6 +990,7 @@ int ModApiMapgen::l_set_noiseparams(lua_State *L) return 0; } + // get_noiseparams(name) int ModApiMapgen::l_get_noiseparams(lua_State *L) { @@ -990,6 +1006,7 @@ int ModApiMapgen::l_get_noiseparams(lua_State *L) return 1; } + // set_gen_notify(flags, {deco_id_table}) int ModApiMapgen::l_set_gen_notify(lua_State *L) { @@ -1007,8 +1024,7 @@ int ModApiMapgen::l_set_gen_notify(lua_State *L) lua_pushnil(L); while (lua_next(L, 2)) { if (lua_isnumber(L, -1)) - emerge->gen_notify_on_deco_ids.insert( - (u32)lua_tonumber(L, -1)); + emerge->gen_notify_on_deco_ids.insert((u32)lua_tonumber(L, -1)); lua_pop(L, 1); } } @@ -1016,6 +1032,7 @@ int ModApiMapgen::l_set_gen_notify(lua_State *L) return 0; } + // get_gen_notify() int ModApiMapgen::l_get_gen_notify(lua_State *L) { @@ -1023,7 +1040,7 @@ int ModApiMapgen::l_get_gen_notify(lua_State *L) EmergeManager *emerge = getServer(L)->getEmergeManager(); push_flags_string(L, flagdesc_gennotify, emerge->gen_notify_on, - emerge->gen_notify_on); + emerge->gen_notify_on); lua_newtable(L); int i = 1; @@ -1034,6 +1051,7 @@ int ModApiMapgen::l_get_gen_notify(lua_State *L) return 2; } + // get_decoration_id(decoration_name) // returns the decoration ID as used in gennotify int ModApiMapgen::l_get_decoration_id(lua_State *L) @@ -1045,7 +1063,7 @@ int ModApiMapgen::l_get_decoration_id(lua_State *L) return 0; const DecorationManager *dmgr = - getServer(L)->getEmergeManager()->getDecorationManager(); + getServer(L)->getEmergeManager()->getDecorationManager(); if (!dmgr) return 0; @@ -1060,6 +1078,7 @@ int ModApiMapgen::l_get_decoration_id(lua_State *L) return 1; } + // register_biome({lots of stuff}) int ModApiMapgen::l_register_biome(lua_State *L) { @@ -1085,6 +1104,7 @@ int ModApiMapgen::l_register_biome(lua_State *L) return 1; } + // register_decoration({lots of stuff}) int ModApiMapgen::l_register_decoration(lua_State *L) { @@ -1093,33 +1113,32 @@ int ModApiMapgen::l_register_decoration(lua_State *L) int index = 1; luaL_checktype(L, index, LUA_TTABLE); - const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); + const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); EmergeManager *emerge = getServer(L)->getEmergeManager(); DecorationManager *decomgr = emerge->getWritableDecorationManager(); - BiomeManager *biomemgr = emerge->getWritableBiomeManager(); + BiomeManager *biomemgr = emerge->getWritableBiomeManager(); SchematicManager *schemmgr = emerge->getWritableSchematicManager(); - enum DecorationType decotype = (DecorationType)getenumfield( - L, index, "deco_type", es_DecorationType, -1); + enum DecorationType decotype = (DecorationType)getenumfield(L, index, + "deco_type", es_DecorationType, -1); Decoration *deco = decomgr->create(decotype); if (!deco) { errorstream << "register_decoration: decoration placement type " - << decotype << " not implemented" << std::endl; + << decotype << " not implemented" << std::endl; return 0; } - deco->name = getstringfield_default(L, index, "name", ""); - deco->fill_ratio = getfloatfield_default(L, index, "fill_ratio", 0.02); - deco->y_min = getintfield_default(L, index, "y_min", -31000); - deco->y_max = getintfield_default(L, index, "y_max", 31000); - deco->nspawnby = getintfield_default(L, index, "num_spawn_by", -1); + deco->name = getstringfield_default(L, index, "name", ""); + deco->fill_ratio = getfloatfield_default(L, index, "fill_ratio", 0.02); + deco->y_min = getintfield_default(L, index, "y_min", -31000); + deco->y_max = getintfield_default(L, index, "y_max", 31000); + deco->nspawnby = getintfield_default(L, index, "num_spawn_by", -1); deco->place_offset_y = getintfield_default(L, index, "place_offset_y", 0); - deco->sidelen = getintfield_default(L, index, "sidelen", 8); + deco->sidelen = getintfield_default(L, index, "sidelen", 8); if (deco->sidelen <= 0) { errorstream << "register_decoration: sidelen must be " - "greater than 0" - << std::endl; + "greater than 0" << std::endl; delete deco; return 0; } @@ -1140,8 +1159,7 @@ int ModApiMapgen::l_register_decoration(lua_State *L) //// Get biomes associated with this decoration (if any) lua_getfield(L, index, "biomes"); if (get_biome_list(L, -1, biomemgr, &deco->biomes)) - infostream << "register_decoration: couldn't get all biomes " - << std::endl; + infostream << "register_decoration: couldn't get all biomes " << std::endl; lua_pop(L, 1); //// Get node name(s) to 'spawn by' @@ -1149,8 +1167,7 @@ int ModApiMapgen::l_register_decoration(lua_State *L) deco->m_nnlistsizes.push_back(nnames); if (nnames == 0 && deco->nspawnby != -1) { errorstream << "register_decoration: no spawn_by nodes defined," - " but num_spawn_by specified" - << std::endl; + " but num_spawn_by specified" << std::endl; } //// Handle decoration type-specific parameters @@ -1183,19 +1200,19 @@ int ModApiMapgen::l_register_decoration(lua_State *L) return 1; } + bool read_deco_simple(lua_State *L, DecoSimple *deco) { int index = 1; int param2; int param2_max; - deco->deco_height = getintfield_default(L, index, "height", 1); + deco->deco_height = getintfield_default(L, index, "height", 1); deco->deco_height_max = getintfield_default(L, index, "height_max", 0); if (deco->deco_height <= 0) { errorstream << "register_decoration: simple decoration height" - " must be greater than 0" - << std::endl; + " must be greater than 0" << std::endl; return false; } @@ -1204,8 +1221,7 @@ bool read_deco_simple(lua_State *L, DecoSimple *deco) if (nnames == 0) { errorstream << "register_decoration: no decoration nodes " - "defined" - << std::endl; + "defined" << std::endl; return false; } @@ -1213,9 +1229,8 @@ bool read_deco_simple(lua_State *L, DecoSimple *deco) param2_max = getintfield_default(L, index, "param2_max", 0); if (param2 < 0 || param2 > 255 || param2_max < 0 || param2_max > 255) { - errorstream << "register_decoration: param2 or param2_max out of bounds " - "(0-255)" - << std::endl; + errorstream << "register_decoration: param2 or param2_max out of bounds (0-255)" + << std::endl; return false; } @@ -1225,12 +1240,13 @@ bool read_deco_simple(lua_State *L, DecoSimple *deco) return true; } + bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco) { int index = 1; - deco->rotation = (Rotation)getenumfield( - L, index, "rotation", ModApiMapgen::es_Rotation, ROTATE_0); + deco->rotation = (Rotation)getenumfield(L, index, "rotation", + ModApiMapgen::es_Rotation, ROTATE_0); StringMap replace_names; lua_getfield(L, index, "replacements"); @@ -1246,6 +1262,7 @@ bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic return schem != NULL; } + // register_ore({lots of stuff}) int ModApiMapgen::l_register_ore(lua_State *L) { @@ -1256,29 +1273,28 @@ int ModApiMapgen::l_register_ore(lua_State *L) const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); EmergeManager *emerge = getServer(L)->getEmergeManager(); - BiomeManager *bmgr = emerge->getWritableBiomeManager(); - OreManager *oremgr = emerge->getWritableOreManager(); + BiomeManager *bmgr = emerge->getWritableBiomeManager(); + OreManager *oremgr = emerge->getWritableOreManager(); - enum OreType oretype = (OreType)getenumfield( - L, index, "ore_type", es_OreType, ORE_SCATTER); + enum OreType oretype = (OreType)getenumfield(L, index, + "ore_type", es_OreType, ORE_SCATTER); Ore *ore = oremgr->create(oretype); if (!ore) { - errorstream << "register_ore: ore_type " << oretype - << " not implemented\n"; + errorstream << "register_ore: ore_type " << oretype << " not implemented\n"; return 0; } - ore->name = getstringfield_default(L, index, "name", ""); - ore->ore_param2 = (u8)getintfield_default(L, index, "ore_param2", 0); + ore->name = getstringfield_default(L, index, "name", ""); + ore->ore_param2 = (u8)getintfield_default(L, index, "ore_param2", 0); ore->clust_scarcity = getintfield_default(L, index, "clust_scarcity", 1); ore->clust_num_ores = getintfield_default(L, index, "clust_num_ores", 1); - ore->clust_size = getintfield_default(L, index, "clust_size", 0); - ore->noise = NULL; - ore->flags = 0; + ore->clust_size = getintfield_default(L, index, "clust_size", 0); + ore->noise = NULL; + ore->flags = 0; //// Get noise_threshold warn_if_field_exists(L, index, "noise_threshhold", - "Deprecated: new name is \"noise_threshold\"."); + "Deprecated: new name is \"noise_threshold\"."); float nthresh; if (!getfloatfield(L, index, "noise_threshold", nthresh) && @@ -1287,25 +1303,24 @@ int ModApiMapgen::l_register_ore(lua_State *L) ore->nthresh = nthresh; //// Get y_min/y_max - warn_if_field_exists( - L, index, "height_min", "Deprecated: new name is \"y_min\"."); - warn_if_field_exists( - L, index, "height_max", "Deprecated: new name is \"y_max\"."); + warn_if_field_exists(L, index, "height_min", + "Deprecated: new name is \"y_min\"."); + warn_if_field_exists(L, index, "height_max", + "Deprecated: new name is \"y_max\"."); int ymin, ymax; if (!getintfield(L, index, "y_min", ymin) && - !getintfield(L, index, "height_min", ymin)) + !getintfield(L, index, "height_min", ymin)) ymin = -31000; if (!getintfield(L, index, "y_max", ymax) && - !getintfield(L, index, "height_max", ymax)) + !getintfield(L, index, "height_max", ymax)) ymax = 31000; ore->y_min = ymin; ore->y_max = ymax; if (ore->clust_scarcity <= 0 || ore->clust_num_ores <= 0) { errorstream << "register_ore: clust_scarcity and clust_num_ores" - "must be greater than 0" - << std::endl; + "must be greater than 0" << std::endl; delete ore; return 0; } @@ -1325,8 +1340,7 @@ int ModApiMapgen::l_register_ore(lua_State *L) ore->flags |= OREFLAG_USE_NOISE; } else if (ore->NEEDS_NOISE) { errorstream << "register_ore: specified ore type requires valid " - "'noise_params' parameter" - << std::endl; + "'noise_params' parameter" << std::endl; delete ore; return 0; } @@ -1334,54 +1348,54 @@ int ModApiMapgen::l_register_ore(lua_State *L) //// Get type-specific parameters switch (oretype) { - case ORE_SHEET: { - OreSheet *oresheet = (OreSheet *)ore; + case ORE_SHEET: { + OreSheet *oresheet = (OreSheet *)ore; - oresheet->column_height_min = - getintfield_default(L, index, "column_height_min", 1); - oresheet->column_height_max = getintfield_default( - L, index, "column_height_max", ore->clust_size); - oresheet->column_midpoint_factor = getfloatfield_default( - L, index, "column_midpoint_factor", 0.5f); + oresheet->column_height_min = getintfield_default(L, index, + "column_height_min", 1); + oresheet->column_height_max = getintfield_default(L, index, + "column_height_max", ore->clust_size); + oresheet->column_midpoint_factor = getfloatfield_default(L, index, + "column_midpoint_factor", 0.5f); - break; - } - case ORE_PUFF: { - OrePuff *orepuff = (OrePuff *)ore; + break; + } + case ORE_PUFF: { + OrePuff *orepuff = (OrePuff *)ore; - lua_getfield(L, index, "np_puff_top"); - read_noiseparams(L, -1, &orepuff->np_puff_top); - lua_pop(L, 1); + lua_getfield(L, index, "np_puff_top"); + read_noiseparams(L, -1, &orepuff->np_puff_top); + lua_pop(L, 1); - lua_getfield(L, index, "np_puff_bottom"); - read_noiseparams(L, -1, &orepuff->np_puff_bottom); - lua_pop(L, 1); + lua_getfield(L, index, "np_puff_bottom"); + read_noiseparams(L, -1, &orepuff->np_puff_bottom); + lua_pop(L, 1); - break; - } - case ORE_VEIN: { - OreVein *orevein = (OreVein *)ore; + break; + } + case ORE_VEIN: { + OreVein *orevein = (OreVein *)ore; - orevein->random_factor = - getfloatfield_default(L, index, "random_factor", 1.f); + orevein->random_factor = getfloatfield_default(L, index, + "random_factor", 1.f); - break; - } - case ORE_STRATUM: { - OreStratum *orestratum = (OreStratum *)ore; + break; + } + case ORE_STRATUM: { + OreStratum *orestratum = (OreStratum *)ore; - lua_getfield(L, index, "np_stratum_thickness"); - if (read_noiseparams(L, -1, &orestratum->np_stratum_thickness)) - ore->flags |= OREFLAG_USE_NOISE2; - lua_pop(L, 1); + lua_getfield(L, index, "np_stratum_thickness"); + if (read_noiseparams(L, -1, &orestratum->np_stratum_thickness)) + ore->flags |= OREFLAG_USE_NOISE2; + lua_pop(L, 1); - orestratum->stratum_thickness = - getintfield_default(L, index, "stratum_thickness", 8); + orestratum->stratum_thickness = getintfield_default(L, index, + "stratum_thickness", 8); - break; - } - default: - break; + break; + } + default: + break; } ObjDefHandle handle = oremgr->add(ore); @@ -1401,19 +1415,21 @@ int ModApiMapgen::l_register_ore(lua_State *L) return 1; } + // register_schematic({schematic}, replacements={}) int ModApiMapgen::l_register_schematic(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *schemmgr = - getServer(L)->getEmergeManager()->getWritableSchematicManager(); + getServer(L)->getEmergeManager()->getWritableSchematicManager(); StringMap replace_names; if (lua_istable(L, 2)) read_schematic_replacements(L, 2, &replace_names); - Schematic *schem = load_schematic(L, 1, schemmgr->getNodeDef(), &replace_names); + Schematic *schem = load_schematic(L, 1, schemmgr->getNodeDef(), + &replace_names); if (!schem) return 0; @@ -1427,48 +1443,55 @@ int ModApiMapgen::l_register_schematic(lua_State *L) return 1; } + // clear_registered_biomes() int ModApiMapgen::l_clear_registered_biomes(lua_State *L) { NO_MAP_LOCK_REQUIRED; - BiomeManager *bmgr = getServer(L)->getEmergeManager()->getWritableBiomeManager(); + BiomeManager *bmgr = + getServer(L)->getEmergeManager()->getWritableBiomeManager(); bmgr->clear(); return 0; } + // clear_registered_decorations() int ModApiMapgen::l_clear_registered_decorations(lua_State *L) { NO_MAP_LOCK_REQUIRED; DecorationManager *dmgr = - getServer(L)->getEmergeManager()->getWritableDecorationManager(); + getServer(L)->getEmergeManager()->getWritableDecorationManager(); dmgr->clear(); return 0; } + // clear_registered_ores() int ModApiMapgen::l_clear_registered_ores(lua_State *L) { NO_MAP_LOCK_REQUIRED; - OreManager *omgr = getServer(L)->getEmergeManager()->getWritableOreManager(); + OreManager *omgr = + getServer(L)->getEmergeManager()->getWritableOreManager(); omgr->clear(); return 0; } + // clear_registered_schematics() int ModApiMapgen::l_clear_registered_schematics(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *smgr = - getServer(L)->getEmergeManager()->getWritableSchematicManager(); + getServer(L)->getEmergeManager()->getWritableSchematicManager(); smgr->clear(); return 0; } + // generate_ores(vm, p1, p2, [ore_id]) int ModApiMapgen::l_generate_ores(lua_State *L) { @@ -1478,15 +1501,13 @@ int ModApiMapgen::l_generate_ores(lua_State *L) Mapgen mg; mg.seed = emerge->mgparams->seed; - mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; + mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; mg.ndef = getServer(L)->getNodeDefManager(); - v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) - : mg.vm->m_area.MinEdge + - v3s16(1, 1, 1) * MAP_BLOCKSIZE; - v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) - : mg.vm->m_area.MaxEdge - - v3s16(1, 1, 1) * MAP_BLOCKSIZE; + v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : + mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE; + v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : + mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE; sortBoxVerticies(pmin, pmax); u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed); @@ -1496,6 +1517,7 @@ int ModApiMapgen::l_generate_ores(lua_State *L) return 0; } + // generate_decorations(vm, p1, p2, [deco_id]) int ModApiMapgen::l_generate_decorations(lua_State *L) { @@ -1505,15 +1527,13 @@ int ModApiMapgen::l_generate_decorations(lua_State *L) Mapgen mg; mg.seed = emerge->mgparams->seed; - mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; + mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; mg.ndef = getServer(L)->getNodeDefManager(); - v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) - : mg.vm->m_area.MinEdge + - v3s16(1, 1, 1) * MAP_BLOCKSIZE; - v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) - : mg.vm->m_area.MaxEdge - - v3s16(1, 1, 1) * MAP_BLOCKSIZE; + v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : + mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE; + v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : + mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE; sortBoxVerticies(pmin, pmax); u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed); @@ -1523,6 +1543,7 @@ int ModApiMapgen::l_generate_decorations(lua_State *L) return 0; } + // create_schematic(p1, p2, probability_list, filename, y_slice_prob_list) int ModApiMapgen::l_create_schematic(lua_State *L) { @@ -1540,7 +1561,7 @@ int ModApiMapgen::l_create_schematic(lua_State *L) v3s16 p2 = check_v3s16(L, 2); sortBoxVerticies(p1, p2); - std::vector<std::pair<v3s16, u8>> prob_list; + std::vector<std::pair<v3s16, u8> > prob_list; if (lua_istable(L, 3)) { lua_pushnil(L); while (lua_next(L, 3)) { @@ -1549,8 +1570,7 @@ int ModApiMapgen::l_create_schematic(lua_State *L) v3s16 pos = check_v3s16(L, -1); lua_pop(L, 1); - u8 prob = getintfield_default( - L, -1, "prob", MTSCHEM_PROB_ALWAYS); + u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); prob_list.emplace_back(pos, prob); } @@ -1558,14 +1578,13 @@ int ModApiMapgen::l_create_schematic(lua_State *L) } } - std::vector<std::pair<s16, u8>> slice_prob_list; + std::vector<std::pair<s16, u8> > slice_prob_list; if (lua_istable(L, 5)) { lua_pushnil(L); while (lua_next(L, 5)) { if (lua_istable(L, -1)) { s16 ypos = getintfield_default(L, -1, "ypos", 0); - u8 prob = getintfield_default( - L, -1, "prob", MTSCHEM_PROB_ALWAYS); + u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); slice_prob_list.emplace_back(ypos, prob); } @@ -1575,21 +1594,21 @@ int ModApiMapgen::l_create_schematic(lua_State *L) if (!schem.getSchematicFromMap(map, p1, p2)) { errorstream << "create_schematic: failed to get schematic " - "from map" - << std::endl; + "from map" << std::endl; return 0; } schem.applyProbabilities(p1, &prob_list, &slice_prob_list); schem.saveSchematicToFile(filename, ndef); - actionstream << "create_schematic: saved schematic file '" << filename << "'." - << std::endl; + actionstream << "create_schematic: saved schematic file '" + << filename << "'." << std::endl; lua_pushboolean(L, true); return 1; } + // place_schematic(p, schematic, rotation, // replacements, force_placement, flagstring) int ModApiMapgen::l_place_schematic(lua_State *L) @@ -1637,6 +1656,7 @@ int ModApiMapgen::l_place_schematic(lua_State *L) return 1; } + // place_schematic_on_vmanip(vm, p, schematic, rotation, // replacements, force_placement, flagstring) int ModApiMapgen::l_place_schematic_on_vmanip(lua_State *L) @@ -1679,19 +1699,19 @@ int ModApiMapgen::l_place_schematic_on_vmanip(lua_State *L) read_flags(L, 7, flagdesc_deco, &flags, NULL); bool schematic_did_fit = schem->placeOnVManip( - vm, p, flags, (Rotation)rot, force_placement); + vm, p, flags, (Rotation)rot, force_placement); lua_pushboolean(L, schematic_did_fit); return 1; } + // serialize_schematic(schematic, format, options={...}) int ModApiMapgen::l_serialize_schematic(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const SchematicManager *schemmgr = - getServer(L)->getEmergeManager()->getSchematicManager(); + const SchematicManager *schemmgr = getServer(L)->getEmergeManager()->getSchematicManager(); //// Read options bool use_comments = getboolfield_default(L, 3, "lua_use_comments", false); @@ -1705,8 +1725,7 @@ int ModApiMapgen::l_serialize_schematic(lua_State *L) was_loaded = true; } if (!schem) { - errorstream << "serialize_schematic: failed to get schematic" - << std::endl; + errorstream << "serialize_schematic: failed to get schematic" << std::endl; return 0; } @@ -1723,8 +1742,8 @@ int ModApiMapgen::l_serialize_schematic(lua_State *L) schem->serializeToMts(&os, schem->m_nodenames); break; case SCHEM_FMT_LUA: - schem->serializeToLua( - &os, schem->m_nodenames, use_comments, indent_spaces); + schem->serializeToLua(&os, schem->m_nodenames, + use_comments, indent_spaces); break; default: return 0; @@ -1744,11 +1763,10 @@ int ModApiMapgen::l_read_schematic(lua_State *L) NO_MAP_LOCK_REQUIRED; const SchematicManager *schemmgr = - getServer(L)->getEmergeManager()->getSchematicManager(); + getServer(L)->getEmergeManager()->getSchematicManager(); //// Read options - std::string write_yslice = - getstringfield_default(L, 2, "write_yslice_prob", "all"); + std::string write_yslice = getstringfield_default(L, 2, "write_yslice_prob", "all"); //// Get schematic bool was_loaded = false; @@ -1794,7 +1812,7 @@ int ModApiMapgen::l_read_schematic(lua_State *L) lua_createtable(L, numnodes, 0); // data table for (u32 i = 0; i < numnodes; ++i) { MapNode node = schem->schemdata[i]; - u8 probability = node.param1 & MTSCHEM_PROB_MASK; + u8 probability = node.param1 & MTSCHEM_PROB_MASK; bool force_place = node.param1 & MTSCHEM_FORCE_PLACE; lua_createtable(L, 0, force_place ? 4 : 3); lua_pushstring(L, names[schem->schemdata[i].getContent()].c_str()); @@ -1817,6 +1835,7 @@ int ModApiMapgen::l_read_schematic(lua_State *L) return 1; } + void ModApiMapgen::Initialize(lua_State *L, int top) { API_FCT(get_biome_id); diff --git a/src/script/lua_api/l_mapgen.h b/src/script/lua_api/l_mapgen.h index ebc49a5ec..0bdc56fc5 100644 --- a/src/script/lua_api/l_mapgen.h +++ b/src/script/lua_api/l_mapgen.h @@ -21,7 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_base.h" -typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include +typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include class ModApiMapgen : public ModApiBase { diff --git a/src/script/lua_api/l_metadata.cpp b/src/script/lua_api/l_metadata.cpp index 3c9670c22..21002e6a7 100644 --- a/src/script/lua_api/l_metadata.cpp +++ b/src/script/lua_api/l_metadata.cpp @@ -26,14 +26,12 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "server.h" // LUALIB_API -void *luaL_checkudata_is_metadataref(lua_State *L, int ud) -{ +void *luaL_checkudata_is_metadataref(lua_State *L, int ud) { void *p = lua_touserdata(L, ud); - if (p != NULL && // value is a userdata? - lua_getmetatable(L, ud)) { // does it have a metatable? + if (p != NULL && // value is a userdata? + lua_getmetatable(L, ud)) { // does it have a metatable? lua_getfield(L, -1, "metadata_class"); - if (lua_type(L, -1) == - LUA_TSTRING) { // does it have a metadata_class field? + if (lua_type(L, -1) == LUA_TSTRING) { // does it have a metadata_class field? return p; } } @@ -41,14 +39,14 @@ void *luaL_checkudata_is_metadataref(lua_State *L, int ud) return NULL; } -MetaDataRef *MetaDataRef::checkobject(lua_State *L, int narg) +MetaDataRef* MetaDataRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata_is_metadataref(L, narg); if (!ud) luaL_typerror(L, narg, "MetaDataRef"); - return *(MetaDataRef **)ud; // unbox pointer + return *(MetaDataRef**)ud; // unbox pointer } // Exported functions diff --git a/src/script/lua_api/l_minimap.cpp b/src/script/lua_api/l_minimap.cpp index 1c429bdcb..5fba76eb8 100644 --- a/src/script/lua_api/l_minimap.cpp +++ b/src/script/lua_api/l_minimap.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "lua_api/l_minimap.h" #include "lua_api/l_internal.h" #include "common/c_converter.h" @@ -98,11 +99,12 @@ int LuaMinimap::l_set_mode(lua_State *L) Minimap *m = getobject(ref); s32 mode = lua_tointeger(L, 2); - if (mode < MINIMAP_MODE_OFF || mode >= MINIMAP_MODE_COUNT) { + if (mode < MINIMAP_MODE_OFF || + mode >= MINIMAP_MODE_COUNT) { return 0; } - m->setMinimapMode((MinimapMode)mode); + m->setMinimapMode((MinimapMode) mode); return 1; } @@ -170,16 +172,15 @@ LuaMinimap *LuaMinimap::checkobject(lua_State *L, int narg) if (!ud) luaL_typerror(L, narg, className); - return *(LuaMinimap **)ud; // unbox pointer + return *(LuaMinimap **)ud; // unbox pointer } -Minimap *LuaMinimap::getobject(LuaMinimap *ref) +Minimap* LuaMinimap::getobject(LuaMinimap *ref) { return ref->m_minimap; } -int LuaMinimap::gc_object(lua_State *L) -{ +int LuaMinimap::gc_object(lua_State *L) { LuaMinimap *o = *(LuaMinimap **)(lua_touserdata(L, 1)); delete o; return 0; @@ -194,7 +195,7 @@ void LuaMinimap::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -204,16 +205,23 @@ void LuaMinimap::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable } const char LuaMinimap::className[] = "Minimap"; -const luaL_Reg LuaMinimap::methods[] = {luamethod(LuaMinimap, show), - luamethod(LuaMinimap, hide), luamethod(LuaMinimap, get_pos), - luamethod(LuaMinimap, set_pos), luamethod(LuaMinimap, get_angle), - luamethod(LuaMinimap, set_angle), luamethod(LuaMinimap, get_mode), - luamethod(LuaMinimap, set_mode), luamethod(LuaMinimap, set_shape), - luamethod(LuaMinimap, get_shape), {0, 0}}; +const luaL_Reg LuaMinimap::methods[] = { + luamethod(LuaMinimap, show), + luamethod(LuaMinimap, hide), + luamethod(LuaMinimap, get_pos), + luamethod(LuaMinimap, set_pos), + luamethod(LuaMinimap, get_angle), + luamethod(LuaMinimap, set_angle), + luamethod(LuaMinimap, get_mode), + luamethod(LuaMinimap, set_mode), + luamethod(LuaMinimap, set_shape), + luamethod(LuaMinimap, get_shape), + {0,0} +}; diff --git a/src/script/lua_api/l_nodemeta.cpp b/src/script/lua_api/l_nodemeta.cpp index 934c08796..57052cb42 100644 --- a/src/script/lua_api/l_nodemeta.cpp +++ b/src/script/lua_api/l_nodemeta.cpp @@ -29,16 +29,15 @@ with this program; if not, write to the Free Software Foundation, Inc., /* NodeMetaRef */ -NodeMetaRef *NodeMetaRef::checkobject(lua_State *L, int narg) +NodeMetaRef* NodeMetaRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); - if (!ud) - luaL_typerror(L, narg, className); - return *(NodeMetaRef **)ud; // unbox pointer + if(!ud) luaL_typerror(L, narg, className); + return *(NodeMetaRef**)ud; // unbox pointer } -Metadata *NodeMetaRef::getmeta(bool auto_create) +Metadata* NodeMetaRef::getmeta(bool auto_create) { if (m_is_local) return m_meta; @@ -65,7 +64,7 @@ void NodeMetaRef::reportMetadataChange(const std::string *name) SANITY_CHECK(!m_is_local); // NOTE: This same code is in rollback_interface.cpp // Inform other things that the metadata has changed - NodeMetadata *meta = dynamic_cast<NodeMetadata *>(m_meta); + NodeMetadata *meta = dynamic_cast<NodeMetadata*>(m_meta); MapEditEvent event; event.type = MEET_BLOCK_NODE_METADATA_CHANGED; @@ -77,8 +76,7 @@ void NodeMetaRef::reportMetadataChange(const std::string *name) // Exported functions // garbage collector -int NodeMetaRef::gc_object(lua_State *L) -{ +int NodeMetaRef::gc_object(lua_State *L) { NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1)); delete o; return 0; @@ -90,7 +88,7 @@ int NodeMetaRef::l_get_inventory(lua_State *L) MAP_LOCK_REQUIRED; NodeMetaRef *ref = checkobject(L, 1); - ref->getmeta(true); // try to ensure the metadata exists + ref->getmeta(true); // try to ensure the metadata exists InvRef::createNodeMeta(L, ref->m_p); return 1; } @@ -101,7 +99,7 @@ int NodeMetaRef::l_mark_as_private(lua_State *L) MAP_LOCK_REQUIRED; NodeMetaRef *ref = checkobject(L, 1); - NodeMetadata *meta = dynamic_cast<NodeMetadata *>(ref->getmeta(true)); + NodeMetadata *meta = dynamic_cast<NodeMetadata*>(ref->getmeta(true)); assert(meta); if (lua_istable(L, 2)) { @@ -126,15 +124,15 @@ void NodeMetaRef::handleToTable(lua_State *L, Metadata *_meta) // fields MetaDataRef::handleToTable(L, _meta); - NodeMetadata *meta = (NodeMetadata *)_meta; + NodeMetadata *meta = (NodeMetadata*) _meta; // inventory lua_newtable(L); Inventory *inv = meta->getInventory(); if (inv) { std::vector<const InventoryList *> lists = inv->getLists(); - for (std::vector<const InventoryList *>::const_iterator i = lists.begin(); - i != lists.end(); ++i) { + for(std::vector<const InventoryList *>::const_iterator + i = lists.begin(); i != lists.end(); ++i) { push_inventory_list(L, inv, (*i)->getName().c_str()); lua_setfield(L, -2, (*i)->getName().c_str()); } @@ -149,7 +147,7 @@ bool NodeMetaRef::handleFromTable(lua_State *L, int table, Metadata *_meta) if (!MetaDataRef::handleFromTable(L, table, _meta)) return false; - NodeMetadata *meta = (NodeMetadata *)_meta; + NodeMetadata *meta = (NodeMetadata*) _meta; // inventory Inventory *inv = meta->getInventory(); @@ -169,11 +167,16 @@ bool NodeMetaRef::handleFromTable(lua_State *L, int table, Metadata *_meta) return true; } -NodeMetaRef::NodeMetaRef(v3s16 p, ServerEnvironment *env) : m_p(p), m_env(env) + +NodeMetaRef::NodeMetaRef(v3s16 p, ServerEnvironment *env): + m_p(p), + m_env(env) { } -NodeMetaRef::NodeMetaRef(Metadata *meta) : m_meta(meta), m_is_local(true) +NodeMetaRef::NodeMetaRef(Metadata *meta): + m_meta(meta), + m_is_local(true) { } @@ -182,7 +185,7 @@ NodeMetaRef::NodeMetaRef(Metadata *meta) : m_meta(meta), m_is_local(true) void NodeMetaRef::create(lua_State *L, v3s16 p, ServerEnvironment *env) { NodeMetaRef *o = new NodeMetaRef(p, env); - // infostream<<"NodeMetaRef::create: o="<<o<<std::endl; + //infostream<<"NodeMetaRef::create: o="<<o<<std::endl; *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); @@ -207,7 +210,7 @@ void NodeMetaRef::RegisterCommon(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "metadata_class"); lua_pushlstring(L, className, strlen(className)); @@ -225,33 +228,49 @@ void NodeMetaRef::RegisterCommon(lua_State *L) lua_pushcfunction(L, l_equals); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable } void NodeMetaRef::Register(lua_State *L) { RegisterCommon(L); - luaL_openlib(L, 0, methodsServer, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methodsServer, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable } -const luaL_Reg NodeMetaRef::methodsServer[] = {luamethod(MetaDataRef, contains), - luamethod(MetaDataRef, get), luamethod(MetaDataRef, get_string), - luamethod(MetaDataRef, set_string), luamethod(MetaDataRef, get_int), - luamethod(MetaDataRef, set_int), luamethod(MetaDataRef, get_float), - luamethod(MetaDataRef, set_float), luamethod(MetaDataRef, to_table), - luamethod(MetaDataRef, from_table), luamethod(NodeMetaRef, get_inventory), - luamethod(NodeMetaRef, mark_as_private), luamethod(MetaDataRef, equals), - {0, 0}}; + +const luaL_Reg NodeMetaRef::methodsServer[] = { + luamethod(MetaDataRef, contains), + luamethod(MetaDataRef, get), + luamethod(MetaDataRef, get_string), + luamethod(MetaDataRef, set_string), + luamethod(MetaDataRef, get_int), + luamethod(MetaDataRef, set_int), + luamethod(MetaDataRef, get_float), + luamethod(MetaDataRef, set_float), + luamethod(MetaDataRef, to_table), + luamethod(MetaDataRef, from_table), + luamethod(NodeMetaRef, get_inventory), + luamethod(NodeMetaRef, mark_as_private), + luamethod(MetaDataRef, equals), + {0,0} +}; + void NodeMetaRef::RegisterClient(lua_State *L) { RegisterCommon(L); - luaL_openlib(L, 0, methodsClient, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methodsClient, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable } -const luaL_Reg NodeMetaRef::methodsClient[] = {luamethod(MetaDataRef, contains), - luamethod(MetaDataRef, get), luamethod(MetaDataRef, get_string), - luamethod(MetaDataRef, get_int), luamethod(MetaDataRef, get_float), - luamethod(MetaDataRef, to_table), {0, 0}}; + +const luaL_Reg NodeMetaRef::methodsClient[] = { + luamethod(MetaDataRef, contains), + luamethod(MetaDataRef, get), + luamethod(MetaDataRef, get_string), + luamethod(MetaDataRef, get_int), + luamethod(MetaDataRef, get_float), + luamethod(MetaDataRef, to_table), + {0,0} +}; diff --git a/src/script/lua_api/l_nodemeta.h b/src/script/lua_api/l_nodemeta.h index 227d79f09..fdc1766ed 100644 --- a/src/script/lua_api/l_nodemeta.h +++ b/src/script/lua_api/l_nodemeta.h @@ -31,8 +31,7 @@ class NodeMetadata; NodeMetaRef */ -class NodeMetaRef : public MetaDataRef -{ +class NodeMetaRef : public MetaDataRef { private: v3s16 m_p; ServerEnvironment *m_env = nullptr; @@ -55,11 +54,10 @@ private: * and @c NULL may be returned in case of an error regardless of @p auto_create. * * @param ref specifies the node for which the associated metadata is retrieved. - * @param auto_create when true, try to create metadata information for the node - * if it has none. + * @param auto_create when true, try to create metadata information for the node if it has none. * @return pointer to a @c NodeMetadata object or @c NULL in case of error. */ - virtual Metadata *getmeta(bool auto_create); + virtual Metadata* getmeta(bool auto_create); virtual void clearMeta(); virtual void reportMetadataChange(const std::string *name = nullptr); diff --git a/src/script/lua_api/l_nodetimer.cpp b/src/script/lua_api/l_nodetimer.cpp index 621af5fd3..c2df52c05 100644 --- a/src/script/lua_api/l_nodetimer.cpp +++ b/src/script/lua_api/l_nodetimer.cpp @@ -22,28 +22,27 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "serverenvironment.h" #include "map.h" -int NodeTimerRef::gc_object(lua_State *L) -{ + +int NodeTimerRef::gc_object(lua_State *L) { NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1)); delete o; return 0; } -NodeTimerRef *NodeTimerRef::checkobject(lua_State *L, int narg) +NodeTimerRef* NodeTimerRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); - if (!ud) - luaL_typerror(L, narg, className); - return *(NodeTimerRef **)ud; // unbox pointer + if(!ud) luaL_typerror(L, narg, className); + return *(NodeTimerRef**)ud; // unbox pointer } int NodeTimerRef::l_set(lua_State *L) { MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); - f32 t = readParam<float>(L, 2); - f32 e = readParam<float>(L, 3); + f32 t = readParam<float>(L,2); + f32 e = readParam<float>(L,3); o->m_map->setNodeTimer(NodeTimer(t, e, o->m_p)); return 0; } @@ -52,7 +51,7 @@ int NodeTimerRef::l_start(lua_State *L) { MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); - f32 t = readParam<float>(L, 2); + f32 t = readParam<float>(L,2); o->m_map->setNodeTimer(NodeTimer(t, 0, o->m_p)); return 0; } @@ -70,7 +69,7 @@ int NodeTimerRef::l_is_started(lua_State *L) MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); NodeTimer t = o->m_map->getNodeTimer(o->m_p); - lua_pushboolean(L, (t.timeout != 0)); + lua_pushboolean(L,(t.timeout != 0)); return 1; } @@ -79,7 +78,7 @@ int NodeTimerRef::l_get_timeout(lua_State *L) MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); NodeTimer t = o->m_map->getNodeTimer(o->m_p); - lua_pushnumber(L, t.timeout); + lua_pushnumber(L,t.timeout); return 1; } @@ -88,7 +87,7 @@ int NodeTimerRef::l_get_elapsed(lua_State *L) MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); NodeTimer t = o->m_map->getNodeTimer(o->m_p); - lua_pushnumber(L, t.elapsed); + lua_pushnumber(L,t.elapsed); return 1; } @@ -111,7 +110,7 @@ void NodeTimerRef::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -121,17 +120,22 @@ void NodeTimerRef::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Cannot be created from Lua - // lua_register(L, className, create_object); + //lua_register(L, className, create_object); } const char NodeTimerRef::className[] = "NodeTimerRef"; -const luaL_Reg NodeTimerRef::methods[] = {luamethod(NodeTimerRef, start), - luamethod(NodeTimerRef, set), luamethod(NodeTimerRef, stop), - luamethod(NodeTimerRef, is_started), luamethod(NodeTimerRef, get_timeout), - luamethod(NodeTimerRef, get_elapsed), {0, 0}}; +const luaL_Reg NodeTimerRef::methods[] = { + luamethod(NodeTimerRef, start), + luamethod(NodeTimerRef, set), + luamethod(NodeTimerRef, stop), + luamethod(NodeTimerRef, is_started), + luamethod(NodeTimerRef, get_timeout), + luamethod(NodeTimerRef, get_elapsed), + {0,0} +}; diff --git a/src/script/lua_api/l_noise.cpp b/src/script/lua_api/l_noise.cpp index 0e9ece82b..9aeb15709 100644 --- a/src/script/lua_api/l_noise.cpp +++ b/src/script/lua_api/l_noise.cpp @@ -30,10 +30,12 @@ with this program; if not, write to the Free Software Foundation, Inc., LuaPerlinNoise */ -LuaPerlinNoise::LuaPerlinNoise(NoiseParams *params) : np(*params) +LuaPerlinNoise::LuaPerlinNoise(NoiseParams *params) : + np(*params) { } + int LuaPerlinNoise::l_get_2d(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -44,6 +46,7 @@ int LuaPerlinNoise::l_get_2d(lua_State *L) return 1; } + int LuaPerlinNoise::l_get_3d(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -54,6 +57,7 @@ int LuaPerlinNoise::l_get_3d(lua_State *L) return 1; } + int LuaPerlinNoise::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -63,10 +67,10 @@ int LuaPerlinNoise::create_object(lua_State *L) if (lua_istable(L, 1)) { read_noiseparams(L, 1, ¶ms); } else { - params.seed = luaL_checkint(L, 1); + params.seed = luaL_checkint(L, 1); params.octaves = luaL_checkint(L, 2); params.persist = readParam<float>(L, 3); - params.spread = v3f(1, 1, 1) * readParam<float>(L, 4); + params.spread = v3f(1, 1, 1) * readParam<float>(L, 4); } LuaPerlinNoise *o = new LuaPerlinNoise(¶ms); @@ -77,6 +81,7 @@ int LuaPerlinNoise::create_object(lua_State *L) return 1; } + int LuaPerlinNoise::gc_object(lua_State *L) { LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1)); @@ -84,6 +89,7 @@ int LuaPerlinNoise::gc_object(lua_State *L) return 0; } + LuaPerlinNoise *LuaPerlinNoise::checkobject(lua_State *L, int narg) { NO_MAP_LOCK_REQUIRED; @@ -94,6 +100,7 @@ LuaPerlinNoise *LuaPerlinNoise::checkobject(lua_State *L, int narg) return *(LuaPerlinNoise **)ud; } + void LuaPerlinNoise::Register(lua_State *L) { lua_newtable(L); @@ -122,9 +129,13 @@ void LuaPerlinNoise::Register(lua_State *L) lua_register(L, className, create_object); } + const char LuaPerlinNoise::className[] = "PerlinNoise"; -luaL_Reg LuaPerlinNoise::methods[] = {luamethod_aliased(LuaPerlinNoise, get_2d, get2d), - luamethod_aliased(LuaPerlinNoise, get_3d, get3d), {0, 0}}; +luaL_Reg LuaPerlinNoise::methods[] = { + luamethod_aliased(LuaPerlinNoise, get_2d, get2d), + luamethod_aliased(LuaPerlinNoise, get_3d, get3d), + {0,0} +}; /////////////////////////////////////// /* @@ -142,11 +153,13 @@ LuaPerlinNoiseMap::LuaPerlinNoiseMap(NoiseParams *params, s32 seed, v3s16 size) } } + LuaPerlinNoiseMap::~LuaPerlinNoiseMap() { delete noise; } + int LuaPerlinNoiseMap::l_get_2d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -170,6 +183,7 @@ int LuaPerlinNoiseMap::l_get_2d_map(lua_State *L) return 1; } + int LuaPerlinNoiseMap::l_get_2d_map_flat(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -195,6 +209,7 @@ int LuaPerlinNoiseMap::l_get_2d_map_flat(lua_State *L) return 1; } + int LuaPerlinNoiseMap::l_get_3d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -225,13 +240,14 @@ int LuaPerlinNoiseMap::l_get_3d_map(lua_State *L) return 1; } + int LuaPerlinNoiseMap::l_get_3d_map_flat(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); - v3f p = check_v3f(L, 2); - bool use_buffer = lua_istable(L, 3); + v3f p = check_v3f(L, 2); + bool use_buffer = lua_istable(L, 3); if (!o->m_is3d) return 0; @@ -253,6 +269,7 @@ int LuaPerlinNoiseMap::l_get_3d_map_flat(lua_State *L) return 1; } + int LuaPerlinNoiseMap::l_calc_2d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -271,7 +288,7 @@ int LuaPerlinNoiseMap::l_calc_3d_map(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); - v3f p = check_v3f(L, 2); + v3f p = check_v3f(L, 2); if (!o->m_is3d) return 0; @@ -282,14 +299,15 @@ int LuaPerlinNoiseMap::l_calc_3d_map(lua_State *L) return 0; } + int LuaPerlinNoiseMap::l_get_map_slice(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); - v3s16 slice_offset = read_v3s16(L, 2); - v3s16 slice_size = read_v3s16(L, 3); - bool use_buffer = lua_istable(L, 4); + v3s16 slice_offset = read_v3s16(L, 2); + v3s16 slice_size = read_v3s16(L, 3); + bool use_buffer = lua_istable(L, 4); Noise *n = o->noise; @@ -298,13 +316,15 @@ int LuaPerlinNoiseMap::l_get_map_slice(lua_State *L) else lua_newtable(L); - write_array_slice_float(L, lua_gettop(L), n->result, v3u16(n->sx, n->sy, n->sz), - v3u16(slice_offset.X, slice_offset.Y, slice_offset.Z), - v3u16(slice_size.X, slice_size.Y, slice_size.Z)); + write_array_slice_float(L, lua_gettop(L), n->result, + v3u16(n->sx, n->sy, n->sz), + v3u16(slice_offset.X, slice_offset.Y, slice_offset.Z), + v3u16(slice_size.X, slice_size.Y, slice_size.Z)); return 1; } + int LuaPerlinNoiseMap::create_object(lua_State *L) { NoiseParams np; @@ -319,6 +339,7 @@ int LuaPerlinNoiseMap::create_object(lua_State *L) return 1; } + int LuaPerlinNoiseMap::gc_object(lua_State *L) { LuaPerlinNoiseMap *o = *(LuaPerlinNoiseMap **)(lua_touserdata(L, 1)); @@ -326,6 +347,7 @@ int LuaPerlinNoiseMap::gc_object(lua_State *L) return 0; } + LuaPerlinNoiseMap *LuaPerlinNoiseMap::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -337,6 +359,7 @@ LuaPerlinNoiseMap *LuaPerlinNoiseMap::checkobject(lua_State *L, int narg) return *(LuaPerlinNoiseMap **)ud; } + void LuaPerlinNoiseMap::Register(lua_State *L) { lua_newtable(L); @@ -365,15 +388,18 @@ void LuaPerlinNoiseMap::Register(lua_State *L) lua_register(L, className, create_object); } + const char LuaPerlinNoiseMap::className[] = "PerlinNoiseMap"; luaL_Reg LuaPerlinNoiseMap::methods[] = { - luamethod_aliased(LuaPerlinNoiseMap, get_2d_map, get2dMap), - luamethod_aliased(LuaPerlinNoiseMap, get_2d_map_flat, get2dMap_flat), - luamethod_aliased(LuaPerlinNoiseMap, calc_2d_map, calc2dMap), - luamethod_aliased(LuaPerlinNoiseMap, get_3d_map, get3dMap), - luamethod_aliased(LuaPerlinNoiseMap, get_3d_map_flat, get3dMap_flat), - luamethod_aliased(LuaPerlinNoiseMap, calc_3d_map, calc3dMap), - luamethod_aliased(LuaPerlinNoiseMap, get_map_slice, getMapSlice), {0, 0}}; + luamethod_aliased(LuaPerlinNoiseMap, get_2d_map, get2dMap), + luamethod_aliased(LuaPerlinNoiseMap, get_2d_map_flat, get2dMap_flat), + luamethod_aliased(LuaPerlinNoiseMap, calc_2d_map, calc2dMap), + luamethod_aliased(LuaPerlinNoiseMap, get_3d_map, get3dMap), + luamethod_aliased(LuaPerlinNoiseMap, get_3d_map_flat, get3dMap_flat), + luamethod_aliased(LuaPerlinNoiseMap, calc_3d_map, calc3dMap), + luamethod_aliased(LuaPerlinNoiseMap, get_map_slice, getMapSlice), + {0,0} +}; /////////////////////////////////////// /* @@ -393,22 +419,22 @@ int LuaPseudoRandom::l_next(lua_State *L) if (lua_isnumber(L, 3)) max = luaL_checkinteger(L, 3); if (max < min) { - errorstream << "PseudoRandom.next(): max=" << max << " min=" << min - << std::endl; + errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl; throw LuaError("PseudoRandom.next(): max < min"); } - if (max - min != 32767 && max - min > 32767 / 5) + if(max - min != 32767 && max - min > 32767/5) throw LuaError("PseudoRandom.next() max-min is not 32767" - " and is > 32768/5. This is disallowed due to" - " the bad random distribution the" - " implementation would otherwise make."); + " and is > 32768/5. This is disallowed due to" + " the bad random distribution the" + " implementation would otherwise make."); PseudoRandom &pseudo = o->m_pseudo; int val = pseudo.next(); - val = (val % (max - min + 1)) + min; + val = (val % (max-min+1)) + min; lua_pushinteger(L, val); return 1; } + int LuaPseudoRandom::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -421,6 +447,7 @@ int LuaPseudoRandom::create_object(lua_State *L) return 1; } + int LuaPseudoRandom::gc_object(lua_State *L) { LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1)); @@ -428,6 +455,7 @@ int LuaPseudoRandom::gc_object(lua_State *L) return 0; } + LuaPseudoRandom *LuaPseudoRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -437,6 +465,7 @@ LuaPseudoRandom *LuaPseudoRandom::checkobject(lua_State *L, int narg) return *(LuaPseudoRandom **)ud; } + void LuaPseudoRandom::Register(lua_State *L) { lua_newtable(L); @@ -464,8 +493,12 @@ void LuaPseudoRandom::Register(lua_State *L) lua_register(L, className, create_object); } + const char LuaPseudoRandom::className[] = "PseudoRandom"; -const luaL_Reg LuaPseudoRandom::methods[] = {luamethod(LuaPseudoRandom, next), {0, 0}}; +const luaL_Reg LuaPseudoRandom::methods[] = { + luamethod(LuaPseudoRandom, next), + {0,0} +}; /////////////////////////////////////// /* @@ -484,6 +517,7 @@ int LuaPcgRandom::l_next(lua_State *L) return 1; } + int LuaPcgRandom::l_rand_normal_dist(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -497,19 +531,22 @@ int LuaPcgRandom::l_rand_normal_dist(lua_State *L) return 1; } + int LuaPcgRandom::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; u64 seed = luaL_checknumber(L, 1); - LuaPcgRandom *o = lua_isnumber(L, 2) ? new LuaPcgRandom(seed, lua_tointeger(L, 2)) - : new LuaPcgRandom(seed); + LuaPcgRandom *o = lua_isnumber(L, 2) ? + new LuaPcgRandom(seed, lua_tointeger(L, 2)) : + new LuaPcgRandom(seed); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } + int LuaPcgRandom::gc_object(lua_State *L) { LuaPcgRandom *o = *(LuaPcgRandom **)(lua_touserdata(L, 1)); @@ -517,6 +554,7 @@ int LuaPcgRandom::gc_object(lua_State *L) return 0; } + LuaPcgRandom *LuaPcgRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -526,6 +564,7 @@ LuaPcgRandom *LuaPcgRandom::checkobject(lua_State *L, int narg) return *(LuaPcgRandom **)ud; } + void LuaPcgRandom::Register(lua_State *L) { lua_newtable(L); @@ -553,9 +592,13 @@ void LuaPcgRandom::Register(lua_State *L) lua_register(L, className, create_object); } + const char LuaPcgRandom::className[] = "PcgRandom"; -const luaL_Reg LuaPcgRandom::methods[] = {luamethod(LuaPcgRandom, next), - luamethod(LuaPcgRandom, rand_normal_dist), {0, 0}}; +const luaL_Reg LuaPcgRandom::methods[] = { + luamethod(LuaPcgRandom, next), + luamethod(LuaPcgRandom, rand_normal_dist), + {0,0} +}; /////////////////////////////////////// /* @@ -590,8 +633,7 @@ int LuaSecureRandom::l_next_bytes(lua_State *L) // Refill buffer and copy over the remainder of what was requested o->fillRandBuf(); - memcpy(output_buf + count_remaining, o->m_rand_buf, - count - count_remaining); + memcpy(output_buf + count_remaining, o->m_rand_buf, count - count_remaining); // Update index o->m_rand_idx = count - count_remaining; @@ -602,6 +644,7 @@ int LuaSecureRandom::l_next_bytes(lua_State *L) return 1; } + int LuaSecureRandom::create_object(lua_State *L) { LuaSecureRandom *o = new LuaSecureRandom(); @@ -618,6 +661,7 @@ int LuaSecureRandom::create_object(lua_State *L) return 1; } + int LuaSecureRandom::gc_object(lua_State *L) { LuaSecureRandom *o = *(LuaSecureRandom **)(lua_touserdata(L, 1)); @@ -625,6 +669,7 @@ int LuaSecureRandom::gc_object(lua_State *L) return 0; } + LuaSecureRandom *LuaSecureRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -634,6 +679,7 @@ LuaSecureRandom *LuaSecureRandom::checkobject(lua_State *L, int narg) return *(LuaSecureRandom **)ud; } + void LuaSecureRandom::Register(lua_State *L) { lua_newtable(L); @@ -663,4 +709,6 @@ void LuaSecureRandom::Register(lua_State *L) const char LuaSecureRandom::className[] = "SecureRandom"; const luaL_Reg LuaSecureRandom::methods[] = { - luamethod(LuaSecureRandom, next_bytes), {0, 0}}; + luamethod(LuaSecureRandom, next_bytes), + {0,0} +}; diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index 5d48ee93d..e7394133a 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -39,16 +39,16 @@ with this program; if not, write to the Free Software Foundation, Inc., ObjectRef */ -ObjectRef *ObjectRef::checkobject(lua_State *L, int narg) + +ObjectRef* ObjectRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); - if (!ud) - luaL_typerror(L, narg, className); - return *(ObjectRef **)ud; // unbox pointer + if (!ud) luaL_typerror(L, narg, className); + return *(ObjectRef**)ud; // unbox pointer } -ServerActiveObject *ObjectRef::getobject(ObjectRef *ref) +ServerActiveObject* ObjectRef::getobject(ObjectRef *ref) { ServerActiveObject *co = ref->m_object; if (co && co->isGone()) @@ -56,24 +56,24 @@ ServerActiveObject *ObjectRef::getobject(ObjectRef *ref) return co; } -LuaEntitySAO *ObjectRef::getluaobject(ObjectRef *ref) +LuaEntitySAO* ObjectRef::getluaobject(ObjectRef *ref) { ServerActiveObject *obj = getobject(ref); if (obj == NULL) return NULL; if (obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY) return NULL; - return (LuaEntitySAO *)obj; + return (LuaEntitySAO*)obj; } -PlayerSAO *ObjectRef::getplayersao(ObjectRef *ref) +PlayerSAO* ObjectRef::getplayersao(ObjectRef *ref) { ServerActiveObject *obj = getobject(ref); if (obj == NULL) return NULL; if (obj->getType() != ACTIVEOBJECT_TYPE_PLAYER) return NULL; - return (PlayerSAO *)obj; + return (PlayerSAO*)obj; } RemotePlayer *ObjectRef::getplayer(ObjectRef *ref) @@ -87,10 +87,9 @@ RemotePlayer *ObjectRef::getplayer(ObjectRef *ref) // Exported functions // garbage collector -int ObjectRef::gc_object(lua_State *L) -{ +int ObjectRef::gc_object(lua_State *L) { ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1)); - // infostream<<"ObjectRef::gc_object: o="<<o<<std::endl; + //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl; delete o; return 0; } @@ -122,8 +121,7 @@ int ObjectRef::l_get_pos(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; push_v3f(L, co->getBasePosition() / BS); return 1; } @@ -134,8 +132,7 @@ int ObjectRef::l_set_pos(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // pos v3f pos = checkFloatPos(L, 2); // Do it @@ -149,8 +146,7 @@ int ObjectRef::l_move_to(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // pos v3f pos = checkFloatPos(L, 2); // continuous @@ -189,18 +185,17 @@ int ObjectRef::l_punch(lua_State *L) lua_pushnumber(L, wear); // If the punched is a player, and its HP changed - if (src_original_hp != co->getHP() && co->getType() == ACTIVEOBJECT_TYPE_PLAYER) { + if (src_original_hp != co->getHP() && + co->getType() == ACTIVEOBJECT_TYPE_PLAYER) { getServer(L)->SendPlayerHPOrDie((PlayerSAO *)co, - PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, - puncher)); + PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, puncher)); } // If the puncher is a player, and its HP changed if (dst_origin_hp != puncher->getHP() && puncher->getType() == ACTIVEOBJECT_TYPE_PLAYER) { getServer(L)->SendPlayerHPOrDie((PlayerSAO *)puncher, - PlayerHPChangeReason( - PlayerHPChangeReason::PLAYER_PUNCH, co)); + PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, co)); } return 1; } @@ -213,10 +208,8 @@ int ObjectRef::l_right_click(lua_State *L) ObjectRef *ref2 = checkobject(L, 2); ServerActiveObject *co = getobject(ref); ServerActiveObject *co2 = getobject(ref2); - if (co == NULL) - return 0; - if (co2 == NULL) - return 0; + if (co == NULL) return 0; + if (co2 == NULL) return 0; // Do it co->rightClick(co2); return 0; @@ -247,8 +240,7 @@ int ObjectRef::l_set_hp(lua_State *L) lua_getfield(L, -1, "type"); if (lua_isstring(L, -1) && - !reason.setTypeFromString( - readParam<std::string>(L, -1))) { + !reason.setTypeFromString(readParam<std::string>(L, -1))) { errorstream << "Bad type given!" << std::endl; } lua_pop(L, 1); @@ -295,8 +287,7 @@ int ObjectRef::l_get_inventory(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it InventoryLocation loc = co->getInventoryLocation(); if (getServerInventoryMgr(L)->getInventory(loc) != NULL) @@ -356,8 +347,7 @@ int ObjectRef::l_set_wielded_item(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it ItemStack item = read_item(L, 2, getServer(L)->idef()); bool success = co->setWieldedItem(item); @@ -374,8 +364,7 @@ int ObjectRef::l_set_armor_groups(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it ItemGroupList groups; read_groups(L, 2, groups); @@ -402,9 +391,8 @@ int ObjectRef::l_set_physics_override(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = (PlayerSAO *)getobject(ref); - if (co == NULL) - return 0; + PlayerSAO *co = (PlayerSAO *) getobject(ref); + if (co == NULL) return 0; // Do it if (lua_istable(L, 2)) { co->m_physics_override_speed = getfloatfield_default( @@ -415,8 +403,8 @@ int ObjectRef::l_set_physics_override(lua_State *L) L, 2, "gravity", co->m_physics_override_gravity); co->m_physics_override_sneak = getboolfield_default( L, 2, "sneak", co->m_physics_override_sneak); - co->m_physics_override_sneak_glitch = getboolfield_default(L, 2, - "sneak_glitch", co->m_physics_override_sneak_glitch); + co->m_physics_override_sneak_glitch = getboolfield_default( + L, 2, "sneak_glitch", co->m_physics_override_sneak_glitch); co->m_physics_override_new_move = getboolfield_default( L, 2, "new_move", co->m_physics_override_new_move); co->m_physics_override_sent = false; @@ -469,8 +457,7 @@ int ObjectRef::l_set_animation(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it v2f frames = v2f(1, 1); if (!lua_isnil(L, 2)) @@ -497,7 +484,7 @@ int ObjectRef::l_get_animation(lua_State *L) if (co == NULL) return 0; // Do it - v2f frames = v2f(1, 1); + v2f frames = v2f(1,1); float frame_speed = 15; float frame_blend = 0; bool frame_loop = true; @@ -520,9 +507,9 @@ int ObjectRef::l_set_local_animation(lua_State *L) return 0; // Do it v2s32 frames[4]; - for (int i = 0; i < 4; i++) { - if (!lua_isnil(L, 2 + 1)) - frames[i] = read_v2s32(L, 2 + i); + for (int i=0;i<4;i++) { + if (!lua_isnil(L, 2+1)) + frames[i] = read_v2s32(L, 2+i); } float frame_speed = 30; if (!lua_isnil(L, 6)) @@ -572,10 +559,10 @@ int ObjectRef::l_set_eye_offset(lua_State *L) offset_third = read_v3f(L, 3); // Prevent abuse of offset values (keep player always visible) - offset_third.X = rangelim(offset_third.X, -10, 10); - offset_third.Z = rangelim(offset_third.Z, -5, 5); + offset_third.X = rangelim(offset_third.X,-10,10); + offset_third.Z = rangelim(offset_third.Z,-5,5); /* TODO: if possible: improve the camera colision detetion to allow Y <= -1.5) */ - offset_third.Y = rangelim(offset_third.Y, -10, 15); // 1.5*BS + offset_third.Y = rangelim(offset_third.Y,-10,15); //1.5*BS getServer(L)->setPlayerEyeOffset(player, offset_first, offset_third); lua_pushboolean(L, true); @@ -640,8 +627,7 @@ int ObjectRef::l_set_bone_position(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it std::string bone; if (!lua_isnil(L, 2)) @@ -694,8 +680,7 @@ int ObjectRef::l_set_attach(lua_State *L) return 0; if (co == parent) - throw LuaError("ObjectRef::set_attach: attaching object to itself is not " - "allowed."); + throw LuaError("ObjectRef::set_attach: attaching object to itself is not allowed."); // Do it int parent_id = 0; @@ -866,8 +851,7 @@ int ObjectRef::l_set_velocity(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; v3f pos = checkFloatPos(L, 2); // Do it co->setVelocity(pos); @@ -894,8 +878,7 @@ int ObjectRef::l_get_velocity(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it v3f v = co->getVelocity(); pushFloatPos(L, v); @@ -908,8 +891,7 @@ int ObjectRef::l_set_acceleration(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // pos v3f pos = checkFloatPos(L, 2); // Do it @@ -923,8 +905,7 @@ int ObjectRef::l_get_acceleration(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it v3f v = co->getAcceleration(); pushFloatPos(L, v); @@ -970,8 +951,7 @@ int ObjectRef::l_set_yaw(lua_State *L) ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; if (isNaN(L, 2)) throw LuaError("ObjectRef::set_yaw: NaN value is not allowed."); @@ -1000,8 +980,7 @@ int ObjectRef::l_set_texture_mod(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it std::string mod = luaL_checkstring(L, 2); co->setTextureMod(mod); @@ -1014,8 +993,7 @@ int ObjectRef::l_get_texture_mod(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it std::string mod = co->getTextureMod(); lua_pushstring(L, mod.c_str()); @@ -1029,10 +1007,9 @@ int ObjectRef::l_set_sprite(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it - v2s16 p(0, 0); + v2s16 p(0,0); if (!lua_isnil(L, 2)) p = readParam<v2s16>(L, 2); int num_frames = 1; @@ -1055,9 +1032,8 @@ int ObjectRef::l_get_entity_name(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - log_deprecated(L, "Deprecated call to \"get_entity_name"); - if (co == NULL) - return 0; + log_deprecated(L,"Deprecated call to \"get_entity_name"); + if (co == NULL) return 0; // Do it std::string name = co->getName(); lua_pushstring(L, name.c_str()); @@ -1070,8 +1046,7 @@ int ObjectRef::l_get_luaentity(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it luaentity_get(L, co->getId()); return 1; @@ -1085,7 +1060,7 @@ int ObjectRef::l_is_player_connected(lua_State *L) NO_MAP_LOCK_REQUIRED; // This method was once added for a bugfix, but never documented log_deprecated(L, "is_player_connected is undocumented and " - "will be removed in a future release"); + "will be removed in a future release"); ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); lua_pushboolean(L, (player != NULL && player->getPeerId() != PEER_ID_INEXISTENT)); @@ -1144,14 +1119,13 @@ int ObjectRef::l_get_look_dir(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it float pitch = co->getRadLookPitchDep(); float yaw = co->getRadYawDep(); - v3f v(std::cos(pitch) * std::cos(yaw), std::sin(pitch), - std::cos(pitch) * std::sin(yaw)); + v3f v(std::cos(pitch) * std::cos(yaw), std::sin(pitch), std::cos(pitch) * + std::sin(yaw)); push_v3f(L, v); return 1; } @@ -1162,13 +1136,12 @@ int ObjectRef::l_get_look_pitch(lua_State *L) { NO_MAP_LOCK_REQUIRED; - log_deprecated(L, "Deprecated call to get_look_pitch, use get_look_vertical " - "instead"); + log_deprecated(L, + "Deprecated call to get_look_pitch, use get_look_vertical instead"); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it lua_pushnumber(L, co->getRadLookPitchDep()); return 1; @@ -1180,13 +1153,12 @@ int ObjectRef::l_get_look_yaw(lua_State *L) { NO_MAP_LOCK_REQUIRED; - log_deprecated(L, "Deprecated call to get_look_yaw, use get_look_horizontal " - "instead"); + log_deprecated(L, + "Deprecated call to get_look_yaw, use get_look_horizontal instead"); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it lua_pushnumber(L, co->getRadYawDep()); return 1; @@ -1197,9 +1169,8 @@ int ObjectRef::l_get_look_vertical(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it lua_pushnumber(L, co->getRadLookPitch()); return 1; @@ -1210,9 +1181,8 @@ int ObjectRef::l_get_look_horizontal(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it lua_pushnumber(L, co->getRadRotation().Y); return 1; @@ -1223,9 +1193,8 @@ int ObjectRef::l_set_look_vertical(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; float pitch = readParam<float>(L, 2) * core::RADTODEG; // Do it co->setLookPitchAndSend(pitch); @@ -1237,9 +1206,8 @@ int ObjectRef::l_set_look_horizontal(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; float yaw = readParam<float>(L, 2) * core::RADTODEG; // Do it co->setPlayerYawAndSend(yaw); @@ -1252,13 +1220,12 @@ int ObjectRef::l_set_look_pitch(lua_State *L) { NO_MAP_LOCK_REQUIRED; - log_deprecated(L, "Deprecated call to set_look_pitch, use set_look_vertical " - "instead."); + log_deprecated(L, + "Deprecated call to set_look_pitch, use set_look_vertical instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; float pitch = readParam<float>(L, 2) * core::RADTODEG; // Do it co->setLookPitchAndSend(pitch); @@ -1271,13 +1238,12 @@ int ObjectRef::l_set_look_yaw(lua_State *L) { NO_MAP_LOCK_REQUIRED; - log_deprecated(L, "Deprecated call to set_look_yaw, use set_look_horizontal " - "instead."); + log_deprecated(L, + "Deprecated call to set_look_yaw, use set_look_horizontal instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; float yaw = readParam<float>(L, 2) * core::RADTODEG; // Do it co->setPlayerYawAndSend(yaw); @@ -1293,10 +1259,11 @@ int ObjectRef::l_set_fov(lua_State *L) if (!player) return 0; - player->setFov({static_cast<f32>(luaL_checknumber(L, 2)), - readParam<bool>(L, 3, false), - lua_isnumber(L, 4) ? static_cast<f32>(luaL_checknumber(L, 4)) - : 0.0f}); + player->setFov({ + static_cast<f32>(luaL_checknumber(L, 2)), + readParam<bool>(L, 3, false), + lua_isnumber(L, 4) ? static_cast<f32>(luaL_checknumber(L, 4)) : 0.0f + }); getServer(L)->SendPlayerFov(player->getPeerId()); return 0; @@ -1324,9 +1291,8 @@ int ObjectRef::l_set_breath(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; u16 breath = luaL_checknumber(L, 2); co->setBreath(breath); @@ -1338,23 +1304,22 @@ int ObjectRef::l_get_breath(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it u16 breath = co->getBreath(); - lua_pushinteger(L, breath); + lua_pushinteger (L, breath); return 1; } // set_attribute(self, attribute, value) int ObjectRef::l_set_attribute(lua_State *L) { - log_deprecated(L, "Deprecated call to set_attribute, use MetaDataRef methods " - "instead."); + log_deprecated(L, + "Deprecated call to set_attribute, use MetaDataRef methods instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); + PlayerSAO* co = getplayersao(ref); if (co == NULL) return 0; @@ -1371,11 +1336,11 @@ int ObjectRef::l_set_attribute(lua_State *L) // get_attribute(self, attribute) int ObjectRef::l_get_attribute(lua_State *L) { - log_deprecated(L, "Deprecated call to get_attribute, use MetaDataRef methods " - "instead."); + log_deprecated(L, + "Deprecated call to get_attribute, use MetaDataRef methods instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); + PlayerSAO* co = getplayersao(ref); if (co == NULL) return 0; @@ -1390,6 +1355,7 @@ int ObjectRef::l_get_attribute(lua_State *L) return 0; } + // get_meta(self, attribute) int ObjectRef::l_get_meta(lua_State *L) { @@ -1402,14 +1368,14 @@ int ObjectRef::l_get_meta(lua_State *L) return 1; } + // set_inventory_formspec(self, formspec) int ObjectRef::l_set_inventory_formspec(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) - return 0; + if (player == NULL) return 0; std::string formspec = luaL_checkstring(L, 2); player->inventory_formspec = formspec; @@ -1424,8 +1390,7 @@ int ObjectRef::l_get_inventory_formspec(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) - return 0; + if (player == NULL) return 0; std::string formspec = player->inventory_formspec; lua_pushlstring(L, formspec.c_str(), formspec.size()); @@ -1456,7 +1421,7 @@ int ObjectRef::l_get_formspec_prepend(lua_State *L) ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) - return 0; + return 0; std::string formspec = player->formspec_prepend; lua_pushlstring(L, formspec.c_str(), formspec.size()); @@ -1608,14 +1573,14 @@ int ObjectRef::l_hud_set_flags(lua_State *L) return 0; u32 flags = 0; - u32 mask = 0; + u32 mask = 0; bool flag; const EnumString *esp = es_HudBuiltinElement; for (int i = 0; esp[i].str; i++) { if (getboolfield(L, 2, esp[i].str, flag)) { flags |= esp[i].num * flag; - mask |= esp[i].num; + mask |= esp[i].num; } } if (!getServer(L)->hudSetFlags(player, flags, mask)) @@ -1770,8 +1735,7 @@ int ObjectRef::l_set_sky(lua_State *L) lua_pushnil(L); while (lua_next(L, -2) != 0) { // Key is at index -2 and value at index -1 - skybox_params.textures.emplace_back( - readParam<std::string>(L, -1)); + skybox_params.textures.emplace_back(readParam<std::string>(L, -1)); // Removes the value, but keeps the key for iteration lua_pop(L, 1); } @@ -1784,12 +1748,11 @@ int ObjectRef::l_set_sky(lua_State *L) using "regular" or "plain" skybox modes as textures aren't needed. */ - if (skybox_params.textures.size() != 6 && - skybox_params.textures.size() > 0) + if (skybox_params.textures.size() != 6 && skybox_params.textures.size() > 0) throw LuaError("Skybox expects 6 textures!"); - skybox_params.clouds = getboolfield_default( - L, 2, "clouds", skybox_params.clouds); + skybox_params.clouds = getboolfield_default(L, 2, + "clouds", skybox_params.clouds); lua_getfield(L, 2, "sky_color"); if (lua_istable(L, -1)) { @@ -1873,10 +1836,9 @@ int ObjectRef::l_set_sky(lua_State *L) if (lua_istable(L, 4)) { lua_pushnil(L); while (lua_next(L, 4) != 0) { - // Key at index -2, and value at index -1 + // Key at index -2, and value at index -1 if (lua_isstring(L, -1)) - skybox_params.textures.emplace_back( - readParam<std::string>(L, -1)); + skybox_params.textures.emplace_back(readParam<std::string>(L, -1)); else skybox_params.textures.emplace_back(""); // Remove the value, keep the key for the next iteration @@ -1916,7 +1878,7 @@ int ObjectRef::l_get_sky(lua_State *L) lua_newtable(L); s16 i = 1; - for (const std::string &texture : skybox_params.textures) { + for (const std::string& texture : skybox_params.textures) { lua_pushlstring(L, texture.c_str(), texture.size()); lua_rawseti(L, -2, i++); } @@ -1934,7 +1896,7 @@ int ObjectRef::l_get_sky_color(lua_State *L) if (!player) return 0; - const SkyboxParams &skybox_params = player->getSkyParams(); + const SkyboxParams& skybox_params = player->getSkyParams(); lua_newtable(L); if (skybox_params.type == "regular") { @@ -1976,20 +1938,25 @@ int ObjectRef::l_set_sun(lua_State *L) SunParams sun_params = player->getSunParams(); - sun_params.visible = getboolfield_default(L, 2, "visible", sun_params.visible); - sun_params.texture = getstringfield_default(L, 2, "texture", sun_params.texture); - sun_params.tonemap = getstringfield_default(L, 2, "tonemap", sun_params.tonemap); - sun_params.sunrise = getstringfield_default(L, 2, "sunrise", sun_params.sunrise); - sun_params.sunrise_visible = getboolfield_default( - L, 2, "sunrise_visible", sun_params.sunrise_visible); - sun_params.scale = getfloatfield_default(L, 2, "scale", sun_params.scale); + sun_params.visible = getboolfield_default(L, 2, + "visible", sun_params.visible); + sun_params.texture = getstringfield_default(L, 2, + "texture", sun_params.texture); + sun_params.tonemap = getstringfield_default(L, 2, + "tonemap", sun_params.tonemap); + sun_params.sunrise = getstringfield_default(L, 2, + "sunrise", sun_params.sunrise); + sun_params.sunrise_visible = getboolfield_default(L, 2, + "sunrise_visible", sun_params.sunrise_visible); + sun_params.scale = getfloatfield_default(L, 2, + "scale", sun_params.scale); getServer(L)->setSun(player, sun_params); lua_pushboolean(L, true); return 1; } -// get_sun(self) +//get_sun(self) int ObjectRef::l_get_sun(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -2029,12 +1996,14 @@ int ObjectRef::l_set_moon(lua_State *L) MoonParams moon_params = player->getMoonParams(); - moon_params.visible = getboolfield_default(L, 2, "visible", moon_params.visible); - moon_params.texture = - getstringfield_default(L, 2, "texture", moon_params.texture); - moon_params.tonemap = - getstringfield_default(L, 2, "tonemap", moon_params.tonemap); - moon_params.scale = getfloatfield_default(L, 2, "scale", moon_params.scale); + moon_params.visible = getboolfield_default(L, 2, + "visible", moon_params.visible); + moon_params.texture = getstringfield_default(L, 2, + "texture", moon_params.texture); + moon_params.tonemap = getstringfield_default(L, 2, + "tonemap", moon_params.tonemap); + moon_params.scale = getfloatfield_default(L, 2, + "scale", moon_params.scale); getServer(L)->setMoon(player, moon_params); lua_pushboolean(L, true); @@ -2077,15 +2046,18 @@ int ObjectRef::l_set_stars(lua_State *L) StarParams star_params = player->getStarParams(); - star_params.visible = getboolfield_default(L, 2, "visible", star_params.visible); - star_params.count = getintfield_default(L, 2, "count", star_params.count); + star_params.visible = getboolfield_default(L, 2, + "visible", star_params.visible); + star_params.count = getintfield_default(L, 2, + "count", star_params.count); lua_getfield(L, 2, "star_color"); if (!lua_isnil(L, -1)) read_color(L, -1, &star_params.starcolor); lua_pop(L, 1); - star_params.scale = getfloatfield_default(L, 2, "scale", star_params.scale); + star_params.scale = getfloatfield_default(L, 2, + "scale", star_params.scale); getServer(L)->setStars(player, star_params); lua_pushboolean(L, true); @@ -2128,8 +2100,7 @@ int ObjectRef::l_set_clouds(lua_State *L) CloudParams cloud_params = player->getCloudParams(); - cloud_params.density = - getfloatfield_default(L, 2, "density", cloud_params.density); + cloud_params.density = getfloatfield_default(L, 2, "density", cloud_params.density); lua_getfield(L, 2, "color"); if (!lua_isnil(L, -1)) @@ -2140,9 +2111,8 @@ int ObjectRef::l_set_clouds(lua_State *L) read_color(L, -1, &cloud_params.color_ambient); lua_pop(L, 1); - cloud_params.height = getfloatfield_default(L, 2, "height", cloud_params.height); - cloud_params.thickness = - getfloatfield_default(L, 2, "thickness", cloud_params.thickness); + cloud_params.height = getfloatfield_default(L, 2, "height", cloud_params.height ); + cloud_params.thickness = getfloatfield_default(L, 2, "thickness", cloud_params.thickness); lua_getfield(L, 2, "speed"); if (lua_istable(L, -1)) { @@ -2188,6 +2158,7 @@ int ObjectRef::l_get_clouds(lua_State *L) return 1; } + // override_day_night_ratio(self, brightness=0...1) int ObjectRef::l_override_day_night_ratio(lua_State *L) { @@ -2230,9 +2201,10 @@ int ObjectRef::l_get_day_night_ratio(lua_State *L) return 1; } -ObjectRef::ObjectRef(ServerActiveObject *object) : m_object(object) +ObjectRef::ObjectRef(ServerActiveObject *object): + m_object(object) { - // infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl; + //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl; } // Creates an ObjectRef and leaves it on top of stack @@ -2240,7 +2212,7 @@ ObjectRef::ObjectRef(ServerActiveObject *object) : m_object(object) void ObjectRef::create(lua_State *L, ServerActiveObject *object) { ObjectRef *o = new ObjectRef(object); - // infostream<<"ObjectRef::create: o="<<o<<std::endl; + //infostream<<"ObjectRef::create: o="<<o<<std::endl; *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); @@ -2261,7 +2233,7 @@ void ObjectRef::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -2271,97 +2243,119 @@ void ObjectRef::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable markAliasDeprecated(methods); - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Cannot be created from Lua - // lua_register(L, className, create_object); + //lua_register(L, className, create_object); } const char ObjectRef::className[] = "ObjectRef"; luaL_Reg ObjectRef::methods[] = { - // ServerActiveObject - luamethod(ObjectRef, remove), - luamethod_aliased(ObjectRef, get_pos, getpos), - luamethod_aliased(ObjectRef, set_pos, setpos), - luamethod_aliased(ObjectRef, move_to, moveto), - luamethod(ObjectRef, punch), luamethod(ObjectRef, right_click), - luamethod(ObjectRef, set_hp), luamethod(ObjectRef, get_hp), - luamethod(ObjectRef, get_inventory), luamethod(ObjectRef, get_wield_list), - luamethod(ObjectRef, get_wield_index), - luamethod(ObjectRef, get_wielded_item), - luamethod(ObjectRef, set_wielded_item), - luamethod(ObjectRef, set_armor_groups), - luamethod(ObjectRef, get_armor_groups), - luamethod(ObjectRef, set_animation), luamethod(ObjectRef, get_animation), - luamethod(ObjectRef, set_animation_frame_speed), - luamethod(ObjectRef, set_bone_position), - luamethod(ObjectRef, get_bone_position), luamethod(ObjectRef, set_attach), - luamethod(ObjectRef, get_attach), luamethod(ObjectRef, set_detach), - luamethod(ObjectRef, set_properties), - luamethod(ObjectRef, get_properties), - luamethod(ObjectRef, set_nametag_attributes), - luamethod(ObjectRef, get_nametag_attributes), - // LuaEntitySAO-only - luamethod_aliased(ObjectRef, set_velocity, setvelocity), - luamethod(ObjectRef, add_velocity), - luamethod_aliased(ObjectRef, get_velocity, getvelocity), - luamethod_aliased(ObjectRef, set_acceleration, setacceleration), - luamethod_aliased(ObjectRef, get_acceleration, getacceleration), - luamethod_aliased(ObjectRef, set_yaw, setyaw), - luamethod_aliased(ObjectRef, get_yaw, getyaw), - luamethod(ObjectRef, set_rotation), luamethod(ObjectRef, get_rotation), - luamethod_aliased(ObjectRef, set_texture_mod, settexturemod), - luamethod_aliased(ObjectRef, set_sprite, setsprite), - luamethod(ObjectRef, get_entity_name), - luamethod(ObjectRef, get_luaentity), - // Player-only - luamethod(ObjectRef, is_player), - luamethod(ObjectRef, is_player_connected), - luamethod(ObjectRef, get_player_name), - luamethod(ObjectRef, get_player_velocity), - luamethod(ObjectRef, add_player_velocity), - luamethod(ObjectRef, get_look_dir), luamethod(ObjectRef, get_look_pitch), - luamethod(ObjectRef, get_look_yaw), - luamethod(ObjectRef, get_look_vertical), - luamethod(ObjectRef, get_look_horizontal), - luamethod(ObjectRef, set_look_horizontal), - luamethod(ObjectRef, set_look_vertical), - luamethod(ObjectRef, set_look_yaw), luamethod(ObjectRef, set_look_pitch), - luamethod(ObjectRef, get_fov), luamethod(ObjectRef, set_fov), - luamethod(ObjectRef, get_breath), luamethod(ObjectRef, set_breath), - luamethod(ObjectRef, get_attribute), luamethod(ObjectRef, set_attribute), - luamethod(ObjectRef, get_meta), - luamethod(ObjectRef, set_inventory_formspec), - luamethod(ObjectRef, get_inventory_formspec), - luamethod(ObjectRef, set_formspec_prepend), - luamethod(ObjectRef, get_formspec_prepend), - luamethod(ObjectRef, get_player_control), - luamethod(ObjectRef, get_player_control_bits), - luamethod(ObjectRef, set_physics_override), - luamethod(ObjectRef, get_physics_override), luamethod(ObjectRef, hud_add), - luamethod(ObjectRef, hud_remove), luamethod(ObjectRef, hud_change), - luamethod(ObjectRef, hud_get), luamethod(ObjectRef, hud_set_flags), - luamethod(ObjectRef, hud_get_flags), - luamethod(ObjectRef, hud_set_hotbar_itemcount), - luamethod(ObjectRef, hud_get_hotbar_itemcount), - luamethod(ObjectRef, hud_set_hotbar_image), - luamethod(ObjectRef, hud_get_hotbar_image), - luamethod(ObjectRef, hud_set_hotbar_selected_image), - luamethod(ObjectRef, hud_get_hotbar_selected_image), - luamethod(ObjectRef, set_sky), luamethod(ObjectRef, get_sky), - luamethod(ObjectRef, get_sky_color), luamethod(ObjectRef, set_sun), - luamethod(ObjectRef, get_sun), luamethod(ObjectRef, set_moon), - luamethod(ObjectRef, get_moon), luamethod(ObjectRef, set_stars), - luamethod(ObjectRef, get_stars), luamethod(ObjectRef, set_clouds), - luamethod(ObjectRef, get_clouds), - luamethod(ObjectRef, override_day_night_ratio), - luamethod(ObjectRef, get_day_night_ratio), - luamethod(ObjectRef, set_local_animation), - luamethod(ObjectRef, get_local_animation), - luamethod(ObjectRef, set_eye_offset), - luamethod(ObjectRef, get_eye_offset), luamethod(ObjectRef, send_mapblock), - {0, 0}}; + // ServerActiveObject + luamethod(ObjectRef, remove), + luamethod_aliased(ObjectRef, get_pos, getpos), + luamethod_aliased(ObjectRef, set_pos, setpos), + luamethod_aliased(ObjectRef, move_to, moveto), + luamethod(ObjectRef, punch), + luamethod(ObjectRef, right_click), + luamethod(ObjectRef, set_hp), + luamethod(ObjectRef, get_hp), + luamethod(ObjectRef, get_inventory), + luamethod(ObjectRef, get_wield_list), + luamethod(ObjectRef, get_wield_index), + luamethod(ObjectRef, get_wielded_item), + luamethod(ObjectRef, set_wielded_item), + luamethod(ObjectRef, set_armor_groups), + luamethod(ObjectRef, get_armor_groups), + luamethod(ObjectRef, set_animation), + luamethod(ObjectRef, get_animation), + luamethod(ObjectRef, set_animation_frame_speed), + luamethod(ObjectRef, set_bone_position), + luamethod(ObjectRef, get_bone_position), + luamethod(ObjectRef, set_attach), + luamethod(ObjectRef, get_attach), + luamethod(ObjectRef, set_detach), + luamethod(ObjectRef, set_properties), + luamethod(ObjectRef, get_properties), + luamethod(ObjectRef, set_nametag_attributes), + luamethod(ObjectRef, get_nametag_attributes), + // LuaEntitySAO-only + luamethod_aliased(ObjectRef, set_velocity, setvelocity), + luamethod(ObjectRef, add_velocity), + luamethod_aliased(ObjectRef, get_velocity, getvelocity), + luamethod_aliased(ObjectRef, set_acceleration, setacceleration), + luamethod_aliased(ObjectRef, get_acceleration, getacceleration), + luamethod_aliased(ObjectRef, set_yaw, setyaw), + luamethod_aliased(ObjectRef, get_yaw, getyaw), + luamethod(ObjectRef, set_rotation), + luamethod(ObjectRef, get_rotation), + luamethod_aliased(ObjectRef, set_texture_mod, settexturemod), + luamethod_aliased(ObjectRef, set_sprite, setsprite), + luamethod(ObjectRef, get_entity_name), + luamethod(ObjectRef, get_luaentity), + // Player-only + luamethod(ObjectRef, is_player), + luamethod(ObjectRef, is_player_connected), + luamethod(ObjectRef, get_player_name), + luamethod(ObjectRef, get_player_velocity), + luamethod(ObjectRef, add_player_velocity), + luamethod(ObjectRef, get_look_dir), + luamethod(ObjectRef, get_look_pitch), + luamethod(ObjectRef, get_look_yaw), + luamethod(ObjectRef, get_look_vertical), + luamethod(ObjectRef, get_look_horizontal), + luamethod(ObjectRef, set_look_horizontal), + luamethod(ObjectRef, set_look_vertical), + luamethod(ObjectRef, set_look_yaw), + luamethod(ObjectRef, set_look_pitch), + luamethod(ObjectRef, get_fov), + luamethod(ObjectRef, set_fov), + luamethod(ObjectRef, get_breath), + luamethod(ObjectRef, set_breath), + luamethod(ObjectRef, get_attribute), + luamethod(ObjectRef, set_attribute), + luamethod(ObjectRef, get_meta), + luamethod(ObjectRef, set_inventory_formspec), + luamethod(ObjectRef, get_inventory_formspec), + luamethod(ObjectRef, set_formspec_prepend), + luamethod(ObjectRef, get_formspec_prepend), + luamethod(ObjectRef, get_player_control), + luamethod(ObjectRef, get_player_control_bits), + luamethod(ObjectRef, set_physics_override), + luamethod(ObjectRef, get_physics_override), + luamethod(ObjectRef, hud_add), + luamethod(ObjectRef, hud_remove), + luamethod(ObjectRef, hud_change), + luamethod(ObjectRef, hud_get), + luamethod(ObjectRef, hud_set_flags), + luamethod(ObjectRef, hud_get_flags), + luamethod(ObjectRef, hud_set_hotbar_itemcount), + luamethod(ObjectRef, hud_get_hotbar_itemcount), + luamethod(ObjectRef, hud_set_hotbar_image), + luamethod(ObjectRef, hud_get_hotbar_image), + luamethod(ObjectRef, hud_set_hotbar_selected_image), + luamethod(ObjectRef, hud_get_hotbar_selected_image), + luamethod(ObjectRef, set_sky), + luamethod(ObjectRef, get_sky), + luamethod(ObjectRef, get_sky_color), + luamethod(ObjectRef, set_sun), + luamethod(ObjectRef, get_sun), + luamethod(ObjectRef, set_moon), + luamethod(ObjectRef, get_moon), + luamethod(ObjectRef, set_stars), + luamethod(ObjectRef, get_stars), + luamethod(ObjectRef, set_clouds), + luamethod(ObjectRef, get_clouds), + luamethod(ObjectRef, override_day_night_ratio), + luamethod(ObjectRef, get_day_night_ratio), + luamethod(ObjectRef, set_local_animation), + luamethod(ObjectRef, get_local_animation), + luamethod(ObjectRef, set_eye_offset), + luamethod(ObjectRef, get_eye_offset), + luamethod(ObjectRef, send_mapblock), + {0,0} +}; diff --git a/src/script/lua_api/l_object.h b/src/script/lua_api/l_object.h index a7b52bdb3..a75c59fd9 100644 --- a/src/script/lua_api/l_object.h +++ b/src/script/lua_api/l_object.h @@ -31,8 +31,7 @@ class RemotePlayer; ObjectRef */ -class ObjectRef : public ModApiBase -{ +class ObjectRef : public ModApiBase { public: ObjectRef(ServerActiveObject *object); @@ -48,16 +47,16 @@ public: static ObjectRef *checkobject(lua_State *L, int narg); - static ServerActiveObject *getobject(ObjectRef *ref); - + static ServerActiveObject* getobject(ObjectRef *ref); private: ServerActiveObject *m_object = nullptr; static const char className[]; static luaL_Reg methods[]; - static LuaEntitySAO *getluaobject(ObjectRef *ref); - static PlayerSAO *getplayersao(ObjectRef *ref); + static LuaEntitySAO* getluaobject(ObjectRef *ref); + + static PlayerSAO* getplayersao(ObjectRef *ref); static RemotePlayer *getplayer(ObjectRef *ref); @@ -332,7 +331,7 @@ private: static int l_get_sky(lua_State *L); // get_sky_color(self) - static int l_get_sky_color(lua_State *L); + static int l_get_sky_color(lua_State* L); // set_sun(self, {visible, texture=, tonemap=, sunrise=, rotation=, scale=}) static int l_set_sun(lua_State *L); diff --git a/src/script/lua_api/l_particles.cpp b/src/script/lua_api/l_particles.cpp index ea0a7c796..a51c4fe20 100644 --- a/src/script/lua_api/l_particles.cpp +++ b/src/script/lua_api/l_particles.cpp @@ -49,7 +49,7 @@ int ModApiParticles::l_add_particle(lua_State *L) if (lua_gettop(L) > 1) // deprecated { log_deprecated(L, "Deprecated add_particle call with " - "individual parameters instead of definition"); + "individual parameters instead of definition"); p.pos = check_v3f(L, 1); p.vel = check_v3f(L, 2); p.acc = check_v3f(L, 3); @@ -59,7 +59,9 @@ int ModApiParticles::l_add_particle(lua_State *L) p.texture = luaL_checkstring(L, 7); if (lua_gettop(L) == 8) // only spawn for a single player playername = luaL_checkstring(L, 8); - } else if (lua_istable(L, 1)) { + } + else if (lua_istable(L, 1)) + { lua_getfield(L, 1, "pos"); if (lua_istable(L, -1)) p.pos = check_v3f(L, -1); @@ -69,7 +71,7 @@ int ModApiParticles::l_add_particle(lua_State *L) if (lua_istable(L, -1)) { p.vel = check_v3f(L, -1); log_deprecated(L, "The use of vel is deprecated. " - "Use velocity instead"); + "Use velocity instead"); } lua_pop(L, 1); @@ -82,7 +84,7 @@ int ModApiParticles::l_add_particle(lua_State *L) if (lua_istable(L, -1)) { p.acc = check_v3f(L, -1); log_deprecated(L, "The use of acc is deprecated. " - "Use acceleration instead"); + "Use acceleration instead"); } lua_pop(L, 1); @@ -91,15 +93,15 @@ int ModApiParticles::l_add_particle(lua_State *L) p.acc = check_v3f(L, -1); lua_pop(L, 1); - p.expirationtime = getfloatfield_default( - L, 1, "expirationtime", p.expirationtime); + p.expirationtime = getfloatfield_default(L, 1, "expirationtime", + p.expirationtime); p.size = getfloatfield_default(L, 1, "size", p.size); - p.collisiondetection = getboolfield_default( - L, 1, "collisiondetection", p.collisiondetection); - p.collision_removal = getboolfield_default( - L, 1, "collision_removal", p.collision_removal); - p.object_collision = getboolfield_default( - L, 1, "object_collision", p.object_collision); + p.collisiondetection = getboolfield_default(L, 1, + "collisiondetection", p.collisiondetection); + p.collision_removal = getboolfield_default(L, 1, + "collision_removal", p.collision_removal); + p.object_collision = getboolfield_default(L, 1, + "object_collision", p.object_collision); p.vertical = getboolfield_default(L, 1, "vertical", p.vertical); lua_getfield(L, 1, "animation"); @@ -154,10 +156,10 @@ int ModApiParticles::l_add_particlespawner(lua_State *L) ServerActiveObject *attached = NULL; std::string playername; - if (lua_gettop(L) > 1) // deprecated + if (lua_gettop(L) > 1) //deprecated { log_deprecated(L, "Deprecated add_particlespawner call with " - "individual parameters instead of definition"); + "individual parameters instead of definition"); p.amount = luaL_checknumber(L, 1); p.time = luaL_checknumber(L, 2); p.minpos = check_v3f(L, 3); @@ -174,7 +176,9 @@ int ModApiParticles::l_add_particlespawner(lua_State *L) p.texture = luaL_checkstring(L, 14); if (lua_gettop(L) == 15) // only spawn for a single player playername = luaL_checkstring(L, 15); - } else if (lua_istable(L, 1)) { + } + else if (lua_istable(L, 1)) + { p.amount = getintfield_default(L, 1, "amount", p.amount); p.time = getfloatfield_default(L, 1, "time", p.time); @@ -212,12 +216,12 @@ int ModApiParticles::l_add_particlespawner(lua_State *L) p.maxexptime = getfloatfield_default(L, 1, "maxexptime", p.maxexptime); p.minsize = getfloatfield_default(L, 1, "minsize", p.minsize); p.maxsize = getfloatfield_default(L, 1, "maxsize", p.maxsize); - p.collisiondetection = getboolfield_default( - L, 1, "collisiondetection", p.collisiondetection); - p.collision_removal = getboolfield_default( - L, 1, "collision_removal", p.collision_removal); - p.object_collision = getboolfield_default( - L, 1, "object_collision", p.object_collision); + p.collisiondetection = getboolfield_default(L, 1, + "collisiondetection", p.collisiondetection); + p.collision_removal = getboolfield_default(L, 1, + "collision_removal", p.collision_removal); + p.object_collision = getboolfield_default(L, 1, + "object_collision", p.object_collision); lua_getfield(L, 1, "animation"); p.animation = read_animation_definition(L, -1); @@ -272,3 +276,4 @@ void ModApiParticles::Initialize(lua_State *L, int top) API_FCT(add_particlespawner); API_FCT(delete_particlespawner); } + diff --git a/src/script/lua_api/l_particles.h b/src/script/lua_api/l_particles.h index 8734e5516..122810b6d 100644 --- a/src/script/lua_api/l_particles.h +++ b/src/script/lua_api/l_particles.h @@ -21,8 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_base.h" -class ModApiParticles : public ModApiBase -{ +class ModApiParticles : public ModApiBase { private: static int l_add_particle(lua_State *L); static int l_add_particlespawner(lua_State *L); diff --git a/src/script/lua_api/l_particles_local.cpp b/src/script/lua_api/l_particles_local.cpp index 498376d40..cc68b13a5 100644 --- a/src/script/lua_api/l_particles_local.cpp +++ b/src/script/lua_api/l_particles_local.cpp @@ -49,15 +49,15 @@ int ModApiParticlesLocal::l_add_particle(lua_State *L) p.acc = check_v3f(L, -1); lua_pop(L, 1); - p.expirationtime = - getfloatfield_default(L, 1, "expirationtime", p.expirationtime); + p.expirationtime = getfloatfield_default(L, 1, "expirationtime", + p.expirationtime); p.size = getfloatfield_default(L, 1, "size", p.size); - p.collisiondetection = getboolfield_default( - L, 1, "collisiondetection", p.collisiondetection); - p.collision_removal = getboolfield_default( - L, 1, "collision_removal", p.collision_removal); - p.object_collision = getboolfield_default( - L, 1, "object_collision", p.object_collision); + p.collisiondetection = getboolfield_default(L, 1, + "collisiondetection", p.collisiondetection); + p.collision_removal = getboolfield_default(L, 1, + "collision_removal", p.collision_removal); + p.object_collision = getboolfield_default(L, 1, + "object_collision", p.object_collision); p.vertical = getboolfield_default(L, 1, "vertical", p.vertical); lua_getfield(L, 1, "animation"); @@ -75,7 +75,7 @@ int ModApiParticlesLocal::l_add_particle(lua_State *L) p.node_tile = getintfield_default(L, 1, "node_tile", p.node_tile); ClientEvent *event = new ClientEvent(); - event->type = CE_SPAWN_PARTICLE; + event->type = CE_SPAWN_PARTICLE; event->spawn_particle = new ParticleParameters(p); getClient(L)->pushToEventQueue(event); @@ -126,12 +126,12 @@ int ModApiParticlesLocal::l_add_particlespawner(lua_State *L) p.maxexptime = getfloatfield_default(L, 1, "maxexptime", p.maxexptime); p.minsize = getfloatfield_default(L, 1, "minsize", p.minsize); p.maxsize = getfloatfield_default(L, 1, "maxsize", p.maxsize); - p.collisiondetection = getboolfield_default( - L, 1, "collisiondetection", p.collisiondetection); - p.collision_removal = getboolfield_default( - L, 1, "collision_removal", p.collision_removal); - p.object_collision = getboolfield_default( - L, 1, "object_collision", p.object_collision); + p.collisiondetection = getboolfield_default(L, 1, + "collisiondetection", p.collisiondetection); + p.collision_removal = getboolfield_default(L, 1, + "collision_removal", p.collision_removal); + p.object_collision = getboolfield_default(L, 1, + "object_collision", p.object_collision); lua_getfield(L, 1, "animation"); p.animation = read_animation_definition(L, -1); @@ -151,10 +151,10 @@ int ModApiParticlesLocal::l_add_particlespawner(lua_State *L) u64 id = getClient(L)->getParticleManager()->generateSpawnerId(); auto event = new ClientEvent(); - event->type = CE_ADD_PARTICLESPAWNER; - event->add_particlespawner.p = new ParticleSpawnerParameters(p); + event->type = CE_ADD_PARTICLESPAWNER; + event->add_particlespawner.p = new ParticleSpawnerParameters(p); event->add_particlespawner.attached_id = 0; - event->add_particlespawner.id = id; + event->add_particlespawner.id = id; getClient(L)->pushToEventQueue(event); lua_pushnumber(L, id); @@ -168,7 +168,7 @@ int ModApiParticlesLocal::l_delete_particlespawner(lua_State *L) u32 id = luaL_checknumber(L, 1); ClientEvent *event = new ClientEvent(); - event->type = CE_DELETE_PARTICLESPAWNER; + event->type = CE_DELETE_PARTICLESPAWNER; event->delete_particlespawner.id = id; getClient(L)->pushToEventQueue(event); diff --git a/src/script/lua_api/l_rollback.cpp b/src/script/lua_api/l_rollback.cpp index 09da123c3..482b0cbf5 100644 --- a/src/script/lua_api/l_rollback.cpp +++ b/src/script/lua_api/l_rollback.cpp @@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "server.h" #include "rollback_interface.h" + void push_RollbackNode(lua_State *L, RollbackNode &node) { lua_createtable(L, 0, 3); @@ -34,15 +35,14 @@ void push_RollbackNode(lua_State *L, RollbackNode &node) lua_setfield(L, -2, "param2"); } -// rollback_get_node_actions(pos, range, seconds, limit) -> {{actor, pos, time, oldnode, -// newnode}, ...} +// rollback_get_node_actions(pos, range, seconds, limit) -> {{actor, pos, time, oldnode, newnode}, ...} int ModApiRollback::l_rollback_get_node_actions(lua_State *L) { NO_MAP_LOCK_REQUIRED; v3s16 pos = read_v3s16(L, 1); int range = luaL_checknumber(L, 2); - time_t seconds = (time_t)luaL_checknumber(L, 3); + time_t seconds = (time_t) luaL_checknumber(L, 3); int limit = luaL_checknumber(L, 4); Server *server = getServer(L); IRollbackManager *rollback = server->getRollbackManager(); @@ -50,8 +50,7 @@ int ModApiRollback::l_rollback_get_node_actions(lua_State *L) return 0; } - std::list<RollbackAction> actions = - rollback->getNodeActors(pos, range, seconds, limit); + std::list<RollbackAction> actions = rollback->getNodeActors(pos, range, seconds, limit); std::list<RollbackAction>::iterator iter = actions.begin(); lua_createtable(L, actions.size(), 0); @@ -102,8 +101,8 @@ int ModApiRollback::l_rollback_revert_actions_by(lua_State *L) lua_pushboolean(L, success); lua_createtable(L, log.size(), 0); unsigned long i = 0; - for (std::list<std::string>::const_iterator iter = log.begin(); iter != log.end(); - ++i, ++iter) { + for(std::list<std::string>::const_iterator iter = log.begin(); + iter != log.end(); ++i, ++iter) { lua_pushnumber(L, i); lua_pushstring(L, iter->c_str()); lua_settable(L, -3); diff --git a/src/script/lua_api/l_rollback.h b/src/script/lua_api/l_rollback.h index 74d8ce10e..c26ff634e 100644 --- a/src/script/lua_api/l_rollback.h +++ b/src/script/lua_api/l_rollback.h @@ -24,8 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., class ModApiRollback : public ModApiBase { private: - // rollback_get_node_actions(pos, range, seconds) -> {{actor, pos, time, oldnode, - // newnode}, ...} + // rollback_get_node_actions(pos, range, seconds) -> {{actor, pos, time, oldnode, newnode}, ...} static int l_rollback_get_node_actions(lua_State *L); // rollback_revert_actions_by(actor, seconds) -> bool, log messages diff --git a/src/script/lua_api/l_server.cpp b/src/script/lua_api/l_server.cpp index f4362dd7f..64ae924d2 100644 --- a/src/script/lua_api/l_server.cpp +++ b/src/script/lua_api/l_server.cpp @@ -56,6 +56,7 @@ int ModApiServer::l_get_server_uptime(lua_State *L) return 1; } + // print(text) int ModApiServer::l_print(lua_State *L) { @@ -115,14 +116,15 @@ int ModApiServer::l_get_player_privs(lua_State *L) int ModApiServer::l_get_player_ip(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char *name = luaL_checkstring(L, 1); - RemotePlayer *player = - dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name); - if (player == NULL) { + const char * name = luaL_checkstring(L, 1); + RemotePlayer *player = dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name); + if(player == NULL) + { lua_pushnil(L); // no such player return 1; } - try { + try + { Address addr = getServer(L)->getPeerAddress(player->getPeerId()); std::string ip_str = addr.serializeString(); lua_pushstring(L, ip_str.c_str()); @@ -164,19 +166,21 @@ int ModApiServer::l_get_player_information(lua_State *L) u8 ser_vers, major, minor, patch; std::string vers_string, lang_code; - auto getConInfo = [&](con::rtt_stat_type type, float *value) -> bool { + auto getConInfo = [&] (con::rtt_stat_type type, float *value) -> bool { return server->getClientConInfo(player->getPeerId(), type, value); }; - bool have_con_info = getConInfo(con::MIN_RTT, &min_rtt) && - getConInfo(con::MAX_RTT, &max_rtt) && - getConInfo(con::AVG_RTT, &avg_rtt) && - getConInfo(con::MIN_JITTER, &min_jitter) && - getConInfo(con::MAX_JITTER, &max_jitter) && - getConInfo(con::AVG_JITTER, &avg_jitter); - - bool r = server->getClientInfo(player->getPeerId(), &state, &uptime, &ser_vers, - &prot_vers, &major, &minor, &patch, &vers_string, &lang_code); + bool have_con_info = + getConInfo(con::MIN_RTT, &min_rtt) && + getConInfo(con::MAX_RTT, &max_rtt) && + getConInfo(con::AVG_RTT, &avg_rtt) && + getConInfo(con::MIN_JITTER, &min_jitter) && + getConInfo(con::MAX_JITTER, &max_jitter) && + getConInfo(con::AVG_JITTER, &avg_jitter); + + bool r = server->getClientInfo(player->getPeerId(), &state, &uptime, + &ser_vers, &prot_vers, &major, &minor, &patch, &vers_string, + &lang_code); if (!r) { dstream << FUNCTION_NAME << ": peer was not found" << std::endl; lua_pushnil(L); // error @@ -186,11 +190,11 @@ int ModApiServer::l_get_player_information(lua_State *L) lua_newtable(L); int table = lua_gettop(L); - lua_pushstring(L, "address"); + lua_pushstring(L,"address"); lua_pushstring(L, addr.serializeString().c_str()); lua_settable(L, table); - lua_pushstring(L, "ip_version"); + lua_pushstring(L,"ip_version"); if (addr.getFamily() == AF_INET) { lua_pushnumber(L, 4); } else if (addr.getFamily() == AF_INET6) { @@ -226,11 +230,11 @@ int ModApiServer::l_get_player_information(lua_State *L) lua_settable(L, table); } - lua_pushstring(L, "connection_uptime"); + lua_pushstring(L,"connection_uptime"); lua_pushnumber(L, uptime); lua_settable(L, table); - lua_pushstring(L, "protocol_version"); + lua_pushstring(L,"protocol_version"); lua_pushnumber(L, prot_vers); lua_settable(L, table); @@ -243,28 +247,28 @@ int ModApiServer::l_get_player_information(lua_State *L) lua_settable(L, table); #ifndef NDEBUG - lua_pushstring(L, "serialization_version"); + lua_pushstring(L,"serialization_version"); lua_pushnumber(L, ser_vers); lua_settable(L, table); - lua_pushstring(L, "major"); + lua_pushstring(L,"major"); lua_pushnumber(L, major); lua_settable(L, table); - lua_pushstring(L, "minor"); + lua_pushstring(L,"minor"); lua_pushnumber(L, minor); lua_settable(L, table); - lua_pushstring(L, "patch"); + lua_pushstring(L,"patch"); lua_pushnumber(L, patch); lua_settable(L, table); - lua_pushstring(L, "version_string"); + lua_pushstring(L,"version_string"); lua_pushstring(L, vers_string.c_str()); lua_settable(L, table); - lua_pushstring(L, "state"); - lua_pushstring(L, ClientInterface::state2Name(state).c_str()); + lua_pushstring(L,"state"); + lua_pushstring(L,ClientInterface::state2Name(state).c_str()); lua_settable(L, table); #endif @@ -283,9 +287,8 @@ int ModApiServer::l_get_ban_list(lua_State *L) int ModApiServer::l_get_ban_description(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char *ip_or_name = luaL_checkstring(L, 1); - lua_pushstring(L, - getServer(L)->getBanDescription(std::string(ip_or_name)).c_str()); + const char * ip_or_name = luaL_checkstring(L, 1); + lua_pushstring(L, getServer(L)->getBanDescription(std::string(ip_or_name)).c_str()); return 1; } @@ -293,21 +296,19 @@ int ModApiServer::l_get_ban_description(lua_State *L) int ModApiServer::l_ban_player(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char *name = luaL_checkstring(L, 1); - RemotePlayer *player = - dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name); + const char * name = luaL_checkstring(L, 1); + RemotePlayer *player = dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name); if (player == NULL) { lua_pushboolean(L, false); // no such player return 1; } - try { + try + { Address addr = getServer(L)->getPeerAddress( - dynamic_cast<ServerEnvironment *>(getEnv(L)) - ->getPlayer(name) - ->getPeerId()); + dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name)->getPeerId()); std::string ip_str = addr.serializeString(); getServer(L)->setIpBanned(ip_str, name); - } catch (const con::PeerNotFoundException &) { + } catch(const con::PeerNotFoundException &) { dstream << FUNCTION_NAME << ": peer was not found" << std::endl; lua_pushboolean(L, false); // error return 1; @@ -327,8 +328,7 @@ int ModApiServer::l_kick_player(lua_State *L) else message.append("."); - RemotePlayer *player = - dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name); + RemotePlayer *player = dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name); if (player == NULL) { lua_pushboolean(L, false); // No such player return 1; @@ -359,7 +359,7 @@ int ModApiServer::l_remove_player(lua_State *L) int ModApiServer::l_unban_player_or_ip(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char *ip_or_name = luaL_checkstring(L, 1); + const char * ip_or_name = luaL_checkstring(L, 1); getServer(L)->unsetIpBanned(ip_or_name); lua_pushboolean(L, true); return 1; @@ -373,9 +373,10 @@ int ModApiServer::l_show_formspec(lua_State *L) const char *formname = luaL_checkstring(L, 2); const char *formspec = luaL_checkstring(L, 3); - if (getServer(L)->showFormspec(playername, formspec, formname)) { + if(getServer(L)->showFormspec(playername,formspec,formname)) + { lua_pushboolean(L, true); - } else { + }else{ lua_pushboolean(L, false); } return 1; @@ -479,8 +480,7 @@ int ModApiServer::l_dynamic_add_media(lua_State *L) // Reject adding media before the server has started up if (!getEnv(L)) - throw LuaError("Dynamic media cannot be added before server has started " - "up"); + throw LuaError("Dynamic media cannot be added before server has started up"); std::string filepath = readParam<std::string>(L, 1); CHECK_SECURE_PATH(L, filepath.c_str(), false); @@ -503,7 +503,7 @@ int ModApiServer::l_notify_authentication_modified(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string name; - if (lua_isstring(L, 1)) + if(lua_isstring(L, 1)) name = readParam<std::string>(L, 1); getServer(L)->reportPrivsModified(name); return 0; @@ -529,7 +529,7 @@ int ModApiServer::l_set_last_run_mod(lua_State *L) #ifdef SCRIPTAPI_DEBUG const char *mod = lua_tostring(L, 1); getScriptApiBase(L)->setOriginDirect(mod); - // printf(">>>> last mod set from Lua: %s\n", mod); + //printf(">>>> last mod set from Lua: %s\n", mod); #endif return 0; } diff --git a/src/script/lua_api/l_settings.cpp b/src/script/lua_api/l_settings.cpp index cc4b23ee4..33eb02392 100644 --- a/src/script/lua_api/l_settings.cpp +++ b/src/script/lua_api/l_settings.cpp @@ -25,20 +25,23 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "noise.h" #include "log.h" -#define SET_SECURITY_CHECK(L, name) \ - if (o->m_settings == g_settings && ScriptApiSecurity::isSecure(L) && \ - name.compare(0, 7, "secure.") == 0) { \ - throw LuaError("Attempt to set secure setting."); \ + +#define SET_SECURITY_CHECK(L, name) \ + if (o->m_settings == g_settings && ScriptApiSecurity::isSecure(L) && \ + name.compare(0, 7, "secure.") == 0) { \ + throw LuaError("Attempt to set secure setting."); \ } LuaSettings::LuaSettings(Settings *settings, const std::string &filename) : - m_settings(settings), m_filename(filename) + m_settings(settings), + m_filename(filename) { } LuaSettings::LuaSettings(const std::string &filename, bool write_allowed) : - m_filename(filename), m_is_own_settings(true), - m_write_allowed(write_allowed) + m_filename(filename), + m_is_own_settings(true), + m_write_allowed(write_allowed) { m_settings = new Settings(); m_settings->readConfigFile(filename.c_str()); @@ -50,7 +53,9 @@ LuaSettings::~LuaSettings() delete m_settings; } -void LuaSettings::create(lua_State *L, Settings *settings, const std::string &filename) + +void LuaSettings::create(lua_State *L, Settings *settings, + const std::string &filename) { LuaSettings *o = new LuaSettings(settings, filename); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; @@ -58,19 +63,21 @@ void LuaSettings::create(lua_State *L, Settings *settings, const std::string &fi lua_setmetatable(L, -2); } + // garbage collector -int LuaSettings::gc_object(lua_State *L) +int LuaSettings::gc_object(lua_State* L) { - LuaSettings *o = *(LuaSettings **)(lua_touserdata(L, 1)); + LuaSettings* o = *(LuaSettings **)(lua_touserdata(L, 1)); delete o; return 0; } + // get(self, key) -> value -int LuaSettings::l_get(lua_State *L) +int LuaSettings::l_get(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); if (o->m_settings->exists(key)) { @@ -84,10 +91,10 @@ int LuaSettings::l_get(lua_State *L) } // get_bool(self, key) -> boolean -int LuaSettings::l_get_bool(lua_State *L) +int LuaSettings::l_get_bool(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); if (o->m_settings->exists(key)) { @@ -146,13 +153,13 @@ int LuaSettings::l_get_flags(lua_State *L) } // set(self, key, value) -int LuaSettings::l_set(lua_State *L) +int LuaSettings::l_set(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); - const char *value = luaL_checkstring(L, 3); + const char* value = luaL_checkstring(L, 3); SET_SECURITY_CHECK(L, key); @@ -163,10 +170,10 @@ int LuaSettings::l_set(lua_State *L) } // set_bool(self, key, value) -int LuaSettings::l_set_bool(lua_State *L) +int LuaSettings::l_set_bool(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); bool value = readParam<bool>(L, 3); @@ -196,10 +203,10 @@ int LuaSettings::l_set_np_group(lua_State *L) } // remove(self, key) -> success -int LuaSettings::l_remove(lua_State *L) +int LuaSettings::l_remove(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); @@ -212,15 +219,16 @@ int LuaSettings::l_remove(lua_State *L) } // get_names(self) -> {key1, ...} -int LuaSettings::l_get_names(lua_State *L) +int LuaSettings::l_get_names(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::vector<std::string> keys = o->m_settings->getNames(); lua_newtable(L); - for (unsigned int i = 0; i < keys.size(); i++) { + for (unsigned int i=0; i < keys.size(); i++) + { lua_pushstring(L, keys[i].c_str()); lua_rawseti(L, -2, i + 1); } @@ -229,10 +237,10 @@ int LuaSettings::l_get_names(lua_State *L) } // write(self) -> success -int LuaSettings::l_write(lua_State *L) +int LuaSettings::l_write(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); if (!o->m_write_allowed) { throw LuaError("Settings: writing " + o->m_filename + @@ -246,10 +254,10 @@ int LuaSettings::l_write(lua_State *L) } // to_table(self) -> {[key1]=value1,...} -int LuaSettings::l_to_table(lua_State *L) +int LuaSettings::l_to_table(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::vector<std::string> keys = o->m_settings->getNames(); @@ -262,7 +270,8 @@ int LuaSettings::l_to_table(lua_State *L) return 1; } -void LuaSettings::Register(lua_State *L) + +void LuaSettings::Register(lua_State* L) { lua_newtable(L); int methodtable = lua_gettop(L); @@ -271,7 +280,7 @@ void LuaSettings::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -281,10 +290,10 @@ void LuaSettings::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Can be created from Lua (Settings(filename)) lua_register(L, className, create_object); @@ -292,33 +301,41 @@ void LuaSettings::Register(lua_State *L) // LuaSettings(filename) // Creates a LuaSettings and leaves it on top of the stack -int LuaSettings::create_object(lua_State *L) +int LuaSettings::create_object(lua_State* L) { NO_MAP_LOCK_REQUIRED; bool write_allowed = true; - const char *filename = luaL_checkstring(L, 1); + const char* filename = luaL_checkstring(L, 1); CHECK_SECURE_PATH_POSSIBLE_WRITE(L, filename, &write_allowed); - LuaSettings *o = new LuaSettings(filename, write_allowed); + LuaSettings* o = new LuaSettings(filename, write_allowed); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } -LuaSettings *LuaSettings::checkobject(lua_State *L, int narg) +LuaSettings* LuaSettings::checkobject(lua_State* L, int narg) { NO_MAP_LOCK_REQUIRED; luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); if (!ud) luaL_typerror(L, narg, className); - return *(LuaSettings **)ud; // unbox pointer + return *(LuaSettings**) ud; // unbox pointer } const char LuaSettings::className[] = "Settings"; -const luaL_Reg LuaSettings::methods[] = {luamethod(LuaSettings, get), - luamethod(LuaSettings, get_bool), luamethod(LuaSettings, get_np_group), - luamethod(LuaSettings, get_flags), luamethod(LuaSettings, set), - luamethod(LuaSettings, set_bool), luamethod(LuaSettings, set_np_group), - luamethod(LuaSettings, remove), luamethod(LuaSettings, get_names), - luamethod(LuaSettings, write), luamethod(LuaSettings, to_table), {0, 0}}; +const luaL_Reg LuaSettings::methods[] = { + luamethod(LuaSettings, get), + luamethod(LuaSettings, get_bool), + luamethod(LuaSettings, get_np_group), + luamethod(LuaSettings, get_flags), + luamethod(LuaSettings, set), + luamethod(LuaSettings, set_bool), + luamethod(LuaSettings, set_np_group), + luamethod(LuaSettings, remove), + luamethod(LuaSettings, get_names), + luamethod(LuaSettings, write), + luamethod(LuaSettings, to_table), + {0,0} +}; diff --git a/src/script/lua_api/l_sound.cpp b/src/script/lua_api/l_sound.cpp index bd9ec2543..b86eda53e 100644 --- a/src/script/lua_api/l_sound.cpp +++ b/src/script/lua_api/l_sound.cpp @@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "common/c_content.h" #include "gui/guiEngine.h" + int ModApiSound::l_sound_play(lua_State *L) { SimpleSoundSpec spec; diff --git a/src/script/lua_api/l_storage.cpp b/src/script/lua_api/l_storage.cpp index fe3b4d74c..cba34fb63 100644 --- a/src/script/lua_api/l_storage.cpp +++ b/src/script/lua_api/l_storage.cpp @@ -53,7 +53,8 @@ void ModApiStorage::Initialize(lua_State *L, int top) API_FCT(get_mod_storage); } -StorageRef::StorageRef(ModMetadata *object) : m_object(object) +StorageRef::StorageRef(ModMetadata *object): + m_object(object) { } @@ -89,7 +90,7 @@ void StorageRef::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "metadata_class"); lua_pushlstring(L, className, strlen(className)); @@ -107,28 +108,27 @@ void StorageRef::Register(lua_State *L) lua_pushcfunction(L, l_equals); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable } -StorageRef *StorageRef::checkobject(lua_State *L, int narg) +StorageRef* StorageRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); - if (!ud) - luaL_typerror(L, narg, className); - return *(StorageRef **)ud; // unbox pointer + if (!ud) luaL_typerror(L, narg, className); + return *(StorageRef**)ud; // unbox pointer } -ModMetadata *StorageRef::getobject(StorageRef *ref) +ModMetadata* StorageRef::getobject(StorageRef *ref) { ModMetadata *co = ref->m_object; return co; } -Metadata *StorageRef::getmeta(bool auto_create) +Metadata* StorageRef::getmeta(bool auto_create) { return m_object; } @@ -139,10 +139,17 @@ void StorageRef::clearMeta() } const char StorageRef::className[] = "StorageRef"; -const luaL_Reg StorageRef::methods[] = {luamethod(MetaDataRef, contains), - luamethod(MetaDataRef, get), luamethod(MetaDataRef, get_string), - luamethod(MetaDataRef, set_string), luamethod(MetaDataRef, get_int), - luamethod(MetaDataRef, set_int), luamethod(MetaDataRef, get_float), - luamethod(MetaDataRef, set_float), luamethod(MetaDataRef, to_table), - luamethod(MetaDataRef, from_table), luamethod(MetaDataRef, equals), - {0, 0}}; +const luaL_Reg StorageRef::methods[] = { + luamethod(MetaDataRef, contains), + luamethod(MetaDataRef, get), + luamethod(MetaDataRef, get_string), + luamethod(MetaDataRef, set_string), + luamethod(MetaDataRef, get_int), + luamethod(MetaDataRef, set_int), + luamethod(MetaDataRef, get_float), + luamethod(MetaDataRef, set_float), + luamethod(MetaDataRef, to_table), + luamethod(MetaDataRef, from_table), + luamethod(MetaDataRef, equals), + {0,0} +}; diff --git a/src/script/lua_api/l_util.cpp b/src/script/lua_api/l_util.cpp index b77e26886..4595dc1c1 100644 --- a/src/script/lua_api/l_util.cpp +++ b/src/script/lua_api/l_util.cpp @@ -41,6 +41,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/sha1.h" #include <algorithm> + // log([level,] text) // Writes a line to the logger. // The one-argument version logs to LL_NONE. @@ -64,7 +65,7 @@ int ModApiUtil::l_log(lua_State *L) level = Logger::stringToLevel(name); if (level == LL_MAX) { warningstream << "Tried to log at unknown level '" << name - << "'. Defaulting to \"none\"." << std::endl; + << "'. Defaulting to \"none\"." << std::endl; level = LL_NONE; } } @@ -108,10 +109,8 @@ int ModApiUtil::l_parse_json(lua_State *L) size_t jlen = strlen(jsonstr); if (jlen > 100) { errorstream << "Data (" << jlen - << " bytes) printed to warningstream." - << std::endl; - warningstream << "data: \"" << jsonstr << "\"" - << std::endl; + << " bytes) printed to warningstream." << std::endl; + warningstream << "data: \"" << jsonstr << "\"" << std::endl; } else { errorstream << "data: \"" << jsonstr << "\"" << std::endl; } @@ -122,7 +121,7 @@ int ModApiUtil::l_parse_json(lua_State *L) if (!push_json_value(L, root, nullindex)) { errorstream << "Failed to parse json data, " - << "depth exceeds lua stack limit" << std::endl; + << "depth exceeds lua stack limit" << std::endl; errorstream << "data: \"" << jsonstr << "\"" << std::endl; lua_pushnil(L); } @@ -177,7 +176,7 @@ int ModApiUtil::l_get_hit_params(lua_State *L) std::unordered_map<std::string, int> groups; read_groups(L, 1, groups); ToolCapabilities tp = read_tool_capabilities(L, 2); - if (lua_isnoneornil(L, 3)) + if(lua_isnoneornil(L, 3)) push_hit_params(L, getHitParams(groups, &tp)); else push_hit_params(L, getHitParams(groups, &tp, readParam<float>(L, 3))); @@ -229,9 +228,9 @@ int ModApiUtil::l_is_yes(lua_State *L) { NO_MAP_LOCK_REQUIRED; - lua_getglobal(L, "tostring"); // function to be called - lua_pushvalue(L, 1); // 1st argument - lua_call(L, 1, 1); // execute function + lua_getglobal(L, "tostring"); // function to be called + lua_pushvalue(L, 1); // 1st argument + lua_call(L, 1, 1); // execute function std::string str = readParam<std::string>(L, -1); // get result lua_pop(L, 1); @@ -346,7 +345,7 @@ int ModApiUtil::l_get_dir_list(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *path = luaL_checkstring(L, 1); - bool list_all = !lua_isboolean(L, 2); // if its not a boolean list all + bool list_all = !lua_isboolean(L, 2); // if its not a boolean list all bool list_dirs = readParam<bool>(L, 2); // true: list dirs, false: list files CHECK_SECURE_PATH(L, path, false); @@ -417,11 +416,12 @@ int ModApiUtil::l_request_insecure_environment(lua_State *L) // Check secure.trusted_mods std::string mod_name = readParam<std::string>(L, -1); std::string trusted_mods = g_settings->get("secure.trusted_mods"); - trusted_mods.erase(std::remove_if(trusted_mods.begin(), trusted_mods.end(), - static_cast<int (*)(int)>(&std::isspace)), + trusted_mods.erase(std::remove_if(trusted_mods.begin(), + trusted_mods.end(), static_cast<int(*)(int)>(&std::isspace)), trusted_mods.end()); std::vector<std::string> mod_list = str_split(trusted_mods, ','); - if (std::find(mod_list.begin(), mod_list.end(), mod_name) == mod_list.end()) { + if (std::find(mod_list.begin(), mod_list.end(), mod_name) == + mod_list.end()) { return 0; } @@ -463,7 +463,7 @@ int ModApiUtil::l_sha1(lua_State *L) SHA1 ctx; ctx.addBytes(data, size); unsigned char *data_tmpdigest = ctx.getDigest(); - data_sha1.assign((char *)data_tmpdigest, 20); + data_sha1.assign((char*) data_tmpdigest, 20); free(data_tmpdigest); } @@ -527,7 +527,7 @@ void ModApiUtil::InitializeClient(lua_State *L, int top) API_FCT(is_yes); API_FCT(is_nan); - + API_FCT(compress); API_FCT(decompress); @@ -538,7 +538,7 @@ void ModApiUtil::InitializeClient(lua_State *L, int top) API_FCT(get_version); API_FCT(sha1); - + LuaSettings::create(L, g_settings, g_settings_path); lua_setfield(L, top, "settings"); } @@ -571,3 +571,4 @@ void ModApiUtil::InitializeAsync(lua_State *L, int top) LuaSettings::create(L, g_settings, g_settings_path); lua_setfield(L, top, "settings"); } + diff --git a/src/script/lua_api/l_vmanip.cpp b/src/script/lua_api/l_vmanip.cpp index 17fb830f9..b99b1d98c 100644 --- a/src/script/lua_api/l_vmanip.cpp +++ b/src/script/lua_api/l_vmanip.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "lua_api/l_vmanip.h" #include "lua_api/l_internal.h" #include "common/c_content.h" @@ -62,7 +63,7 @@ int LuaVoxelManip::l_get_data(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); - bool use_buffer = lua_istable(L, 2); + bool use_buffer = lua_istable(L, 2); MMVManip *vm = o->vm; @@ -116,7 +117,8 @@ int LuaVoxelManip::l_write_to_map(lua_State *L) if (o->is_mapgen_vm || !update_light) { o->vm->blitBackAll(&(o->modified_blocks)); } else { - voxalgo::blit_back_with_light(map, o->vm, &(o->modified_blocks)); + voxalgo::blit_back_with_light(map, o->vm, + &(o->modified_blocks)); } MapEditEvent event; @@ -137,7 +139,7 @@ int LuaVoxelManip::l_get_node_at(lua_State *L) const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); LuaVoxelManip *o = checkobject(L, 1); - v3s16 pos = check_v3s16(L, 2); + v3s16 pos = check_v3s16(L, 2); pushnode(L, o->vm->getNodeNoExNoEmerge(pos), ndef); return 1; @@ -150,8 +152,8 @@ int LuaVoxelManip::l_set_node_at(lua_State *L) const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); LuaVoxelManip *o = checkobject(L, 1); - v3s16 pos = check_v3s16(L, 2); - MapNode n = readnode(L, 3, ndef); + v3s16 pos = check_v3s16(L, 2); + MapNode n = readnode(L, 3, ndef); o->vm->setNodeNoEmerge(pos, n); @@ -169,11 +171,11 @@ int LuaVoxelManip::l_update_liquids(lua_State *L) MMVManip *vm = o->vm; Mapgen mg; - mg.vm = vm; + mg.vm = vm; mg.ndef = ndef; - mg.updateLiquid(&map->m_transforming_liquid, vm->m_area.MinEdge, - vm->m_area.MaxEdge); + mg.updateLiquid(&map->m_transforming_liquid, + vm->m_area.MinEdge, vm->m_area.MaxEdge); return 0; } @@ -185,8 +187,7 @@ int LuaVoxelManip::l_calc_lighting(lua_State *L) LuaVoxelManip *o = checkobject(L, 1); if (!o->is_mapgen_vm) { warningstream << "VoxelManip:calc_lighting called for a non-mapgen " - "VoxelManip object" - << std::endl; + "VoxelManip object" << std::endl; return 0; } @@ -195,10 +196,10 @@ int LuaVoxelManip::l_calc_lighting(lua_State *L) MMVManip *vm = o->vm; v3s16 yblock = v3s16(0, 1, 0) * MAP_BLOCKSIZE; - v3s16 fpmin = vm->m_area.MinEdge; - v3s16 fpmax = vm->m_area.MaxEdge; - v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : fpmin + yblock; - v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : fpmax - yblock; + v3s16 fpmin = vm->m_area.MinEdge; + v3s16 fpmax = vm->m_area.MaxEdge; + v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : fpmin + yblock; + v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : fpmax - yblock; bool propagate_shadow = !lua_isboolean(L, 4) || readParam<bool>(L, 4); sortBoxVerticies(pmin, pmax); @@ -206,8 +207,8 @@ int LuaVoxelManip::l_calc_lighting(lua_State *L) throw LuaError("Specified voxel area out of VoxelManipulator bounds"); Mapgen mg; - mg.vm = vm; - mg.ndef = ndef; + mg.vm = vm; + mg.ndef = ndef; mg.water_level = emerge->mgparams->water_level; mg.calcLighting(pmin, pmax, fpmin, fpmax, propagate_shadow); @@ -222,8 +223,7 @@ int LuaVoxelManip::l_set_lighting(lua_State *L) LuaVoxelManip *o = checkobject(L, 1); if (!o->is_mapgen_vm) { warningstream << "VoxelManip:set_lighting called for a non-mapgen " - "VoxelManip object" - << std::endl; + "VoxelManip object" << std::endl; return 0; } @@ -231,7 +231,7 @@ int LuaVoxelManip::l_set_lighting(lua_State *L) throw LuaError("VoxelManip:set_lighting called with missing parameter"); u8 light; - light = (getintfield_default(L, 2, "day", 0) & 0x0F); + light = (getintfield_default(L, 2, "day", 0) & 0x0F); light |= (getintfield_default(L, 2, "night", 0) & 0x0F) << 4; MMVManip *vm = o->vm; @@ -280,7 +280,7 @@ int LuaVoxelManip::l_set_light_data(lua_State *L) if (!lua_istable(L, 2)) throw LuaError("VoxelManip:set_light_data called with missing " - "parameter"); + "parameter"); u32 volume = vm->m_area.getVolume(); for (u32 i = 0; i != volume; i++) { @@ -300,7 +300,7 @@ int LuaVoxelManip::l_get_param2_data(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); - bool use_buffer = lua_istable(L, 2); + bool use_buffer = lua_istable(L, 2); MMVManip *vm = o->vm; @@ -329,7 +329,7 @@ int LuaVoxelManip::l_set_param2_data(lua_State *L) if (!lua_istable(L, 2)) throw LuaError("VoxelManip:set_param2_data called with missing " - "parameter"); + "parameter"); u32 volume = vm->m_area.getVolume(); for (u32 i = 0; i != volume; i++) { @@ -374,7 +374,8 @@ int LuaVoxelManip::l_get_emerged_area(lua_State *L) } LuaVoxelManip::LuaVoxelManip(MMVManip *mmvm, bool is_mg_vm) : - is_mapgen_vm(is_mg_vm), vm(mmvm) + is_mapgen_vm(is_mg_vm), + vm(mmvm) { } @@ -405,10 +406,9 @@ int LuaVoxelManip::create_object(lua_State *L) GET_ENV_PTR; Map *map = &(env->getMap()); - LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) - ? new LuaVoxelManip(map, check_v3s16(L, 1), - check_v3s16(L, 2)) - : new LuaVoxelManip(map); + LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ? + new LuaVoxelManip(map, check_v3s16(L, 1), check_v3s16(L, 2)) : + new LuaVoxelManip(map); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); @@ -426,7 +426,7 @@ LuaVoxelManip *LuaVoxelManip::checkobject(lua_State *L, int narg) if (!ud) luaL_typerror(L, narg, className); - return *(LuaVoxelManip **)ud; // unbox pointer + return *(LuaVoxelManip **)ud; // unbox pointer } void LuaVoxelManip::Register(lua_State *L) @@ -438,7 +438,7 @@ void LuaVoxelManip::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -448,28 +448,32 @@ void LuaVoxelManip::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Can be created from Lua (VoxelManip()) lua_register(L, className, create_object); } const char LuaVoxelManip::className[] = "VoxelManip"; -const luaL_Reg LuaVoxelManip::methods[] = {luamethod(LuaVoxelManip, read_from_map), - luamethod(LuaVoxelManip, get_data), luamethod(LuaVoxelManip, set_data), - luamethod(LuaVoxelManip, get_node_at), - luamethod(LuaVoxelManip, set_node_at), - luamethod(LuaVoxelManip, write_to_map), - luamethod(LuaVoxelManip, update_map), - luamethod(LuaVoxelManip, update_liquids), - luamethod(LuaVoxelManip, calc_lighting), - luamethod(LuaVoxelManip, set_lighting), - luamethod(LuaVoxelManip, get_light_data), - luamethod(LuaVoxelManip, set_light_data), - luamethod(LuaVoxelManip, get_param2_data), - luamethod(LuaVoxelManip, set_param2_data), - luamethod(LuaVoxelManip, was_modified), - luamethod(LuaVoxelManip, get_emerged_area), {0, 0}}; +const luaL_Reg LuaVoxelManip::methods[] = { + luamethod(LuaVoxelManip, read_from_map), + luamethod(LuaVoxelManip, get_data), + luamethod(LuaVoxelManip, set_data), + luamethod(LuaVoxelManip, get_node_at), + luamethod(LuaVoxelManip, set_node_at), + luamethod(LuaVoxelManip, write_to_map), + luamethod(LuaVoxelManip, update_map), + luamethod(LuaVoxelManip, update_liquids), + luamethod(LuaVoxelManip, calc_lighting), + luamethod(LuaVoxelManip, set_lighting), + luamethod(LuaVoxelManip, get_light_data), + luamethod(LuaVoxelManip, set_light_data), + luamethod(LuaVoxelManip, get_param2_data), + luamethod(LuaVoxelManip, set_param2_data), + luamethod(LuaVoxelManip, was_modified), + luamethod(LuaVoxelManip, get_emerged_area), + {0,0} +}; diff --git a/src/script/scripting_client.cpp b/src/script/scripting_client.cpp index 011c93b43..729645678 100644 --- a/src/script/scripting_client.cpp +++ b/src/script/scripting_client.cpp @@ -41,7 +41,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_settings.h" #include "lua_api/l_http.h" -ClientScripting::ClientScripting(Client *client) : ScriptApiBase(ScriptingType::Client) +ClientScripting::ClientScripting(Client *client): + ScriptApiBase(ScriptingType::Client) { setGameDef(client); setGame(g_game); diff --git a/src/script/scripting_client.h b/src/script/scripting_client.h index b8dd257a9..e162f8bcf 100644 --- a/src/script/scripting_client.h +++ b/src/script/scripting_client.h @@ -31,11 +31,12 @@ class LocalPlayer; class Camera; class Minimap; -class ClientScripting : virtual public ScriptApiBase, - public ScriptApiSecurity, - public ScriptApiClient, - public ScriptApiModChannels, - public ScriptApiCheats +class ClientScripting: + virtual public ScriptApiBase, + public ScriptApiSecurity, + public ScriptApiClient, + public ScriptApiModChannels, + public ScriptApiCheats { public: ClientScripting(Client *client); diff --git a/src/script/scripting_mainmenu.cpp b/src/script/scripting_mainmenu.cpp index 835368776..0f672f917 100644 --- a/src/script/scripting_mainmenu.cpp +++ b/src/script/scripting_mainmenu.cpp @@ -34,7 +34,8 @@ extern "C" { #define MAINMENU_NUM_ASYNC_THREADS 4 -MainMenuScripting::MainMenuScripting(GUIEngine *guiengine) : + +MainMenuScripting::MainMenuScripting(GUIEngine* guiengine): ScriptApiBase(ScriptingType::MainMenu) { setGuiEngine(guiengine); @@ -75,7 +76,7 @@ void MainMenuScripting::initializeModApi(lua_State *L, int top) asyncEngine.registerStateInitializer(ModApiHttp::InitializeAsync); // Initialize async environment - // TODO possibly make number of async threads configurable + //TODO possibly make number of async threads configurable asyncEngine.initialize(MAINMENU_NUM_ASYNC_THREADS); } @@ -92,8 +93,9 @@ void MainMenuScripting::step() } /******************************************************************************/ -unsigned int MainMenuScripting::queueAsync( - const std::string &serialized_func, const std::string &serialized_param) +unsigned int MainMenuScripting::queueAsync(const std::string &serialized_func, + const std::string &serialized_param) { return asyncEngine.queueAsyncJob(serialized_func, serialized_param); } + diff --git a/src/script/scripting_mainmenu.h b/src/script/scripting_mainmenu.h index 16d0a0cc0..9e23bdc1b 100644 --- a/src/script/scripting_mainmenu.h +++ b/src/script/scripting_mainmenu.h @@ -27,10 +27,12 @@ with this program; if not, write to the Free Software Foundation, Inc., /* Scripting <-> Main Menu Interface */ /*****************************************************************************/ -class MainMenuScripting : virtual public ScriptApiBase, public ScriptApiMainMenu +class MainMenuScripting + : virtual public ScriptApiBase, + public ScriptApiMainMenu { public: - MainMenuScripting(GUIEngine *guiengine); + MainMenuScripting(GUIEngine* guiengine); // Global step handler to pass back async events void step(); @@ -38,7 +40,6 @@ public: // Pass async events from engine to async threads unsigned int queueAsync(const std::string &serialized_func, const std::string &serialized_params); - private: void initializeModApi(lua_State *L, int top); static void registerLuaClasses(lua_State *L, int top); diff --git a/src/script/scripting_server.cpp b/src/script/scripting_server.cpp index 604607e78..85411ded4 100644 --- a/src/script/scripting_server.cpp +++ b/src/script/scripting_server.cpp @@ -50,7 +50,8 @@ extern "C" { #include "lualib.h" } -ServerScripting::ServerScripting(Server *server) : ScriptApiBase(ScriptingType::Server) +ServerScripting::ServerScripting(Server* server): + ScriptApiBase(ScriptingType::Server) { setGameDef(server); @@ -62,12 +63,9 @@ ServerScripting::ServerScripting(Server *server) : ScriptApiBase(ScriptingType:: if (g_settings->getBool("secure.enable_security")) { initializeSecurity(); } else { - warningstream << "\\!/ Mod security should never be disabled, as it " - "allows any mod to " - << "access the host machine." - << "Mods should use " - "minetest.request_insecure_environment() instead \\!/" - << std::endl; + warningstream << "\\!/ Mod security should never be disabled, as it allows any mod to " + << "access the host machine." + << "Mods should use minetest.request_insecure_environment() instead \\!/" << std::endl; } lua_getglobal(L, "core"); diff --git a/src/script/scripting_server.h b/src/script/scripting_server.h index b0619f449..bf06ab197 100644 --- a/src/script/scripting_server.h +++ b/src/script/scripting_server.h @@ -32,18 +32,19 @@ with this program; if not, write to the Free Software Foundation, Inc., /* Scripting <-> Server Game Interface */ /*****************************************************************************/ -class ServerScripting : virtual public ScriptApiBase, - public ScriptApiDetached, - public ScriptApiEntity, - public ScriptApiEnv, - public ScriptApiModChannels, - public ScriptApiNode, - public ScriptApiPlayer, - public ScriptApiServer, - public ScriptApiSecurity +class ServerScripting: + virtual public ScriptApiBase, + public ScriptApiDetached, + public ScriptApiEntity, + public ScriptApiEnv, + public ScriptApiModChannels, + public ScriptApiNode, + public ScriptApiPlayer, + public ScriptApiServer, + public ScriptApiSecurity { public: - ServerScripting(Server *server); + ServerScripting(Server* server); // use ScriptApiBase::loadMod() to load mods |