diff options
author | Elias Fleckenstein <eliasfleckenstein@web.de> | 2020-11-04 16:19:54 +0100 |
---|---|---|
committer | Elias Fleckenstein <eliasfleckenstein@web.de> | 2020-11-04 16:19:54 +0100 |
commit | ad148587dcf5244c2d2011dba339786c765c54c4 (patch) | |
tree | bdd914121cd326da2ed26679838878e3edffc841 /src/script | |
parent | 1145b05ea0bda87dc0827821385810eced08f774 (diff) | |
download | dragonfireclient-ad148587dcf5244c2d2011dba339786c765c54c4.tar.xz |
Make Lint Happy
Diffstat (limited to 'src/script')
84 files changed, 2987 insertions, 3330 deletions
diff --git a/src/script/common/c_content.cpp b/src/script/common/c_content.cpp index 7d4c1e748..9e99d5673 100644 --- a/src/script/common/c_content.cpp +++ b/src/script/common/c_content.cpp @@ -38,23 +38,21 @@ 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); @@ -69,7 +67,7 @@ void read_item_definition(lua_State* L, int index, 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); @@ -87,15 +85,15 @@ void read_item_definition(lua_State* L, int index, "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(); } @@ -182,10 +180,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; @@ -200,7 +198,8 @@ void read_object_properties(lua_State *L, int index, 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); } } @@ -248,13 +247,13 @@ void read_object_properties(lua_State *L, int index, 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(""); @@ -277,12 +276,12 @@ void read_object_properties(lua_State *L, int index, 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); @@ -316,7 +315,8 @@ void read_object_properties(lua_State *L, int index, 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,14 +417,15 @@ 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; @@ -432,41 +433,39 @@ 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") @@ -493,20 +492,23 @@ 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"); @@ -523,8 +525,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 */ @@ -533,31 +535,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++; } @@ -596,23 +598,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; } @@ -622,8 +624,7 @@ 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; @@ -647,22 +648,21 @@ 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,31 +695,27 @@ 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); @@ -757,24 +753,23 @@ 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); @@ -783,7 +778,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); @@ -797,8 +792,7 @@ 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; } @@ -806,7 +800,8 @@ 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); @@ -834,7 +829,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); @@ -934,48 +929,47 @@ 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; } } @@ -1004,37 +998,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); } @@ -1043,7 +1037,7 @@ void read_server_sound_params(lua_State *L, int index, /******************************************************************************/ 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; @@ -1080,20 +1074,21 @@ 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"); @@ -1159,34 +1154,31 @@ 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; @@ -1197,9 +1189,9 @@ bool string_to_enum(const EnumString *spec, int &result, } /******************************************************************************/ -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)) { @@ -1215,21 +1207,16 @@ 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); @@ -1253,7 +1240,8 @@ 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 } } @@ -1264,57 +1252,56 @@ 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 + // Create groupcaps table + lua_newtable(L); + // For each groupcap + for (const auto &gc_it : toolcap.groupcaps) { + // Create groupcap table lua_newtable(L); - // 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 + const std::string &name = gc_it.first; + const ToolGroupCap &groupcap = gc_it.second; + // Create subtable "times" 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()); + for (auto time : groupcap.times) { + lua_pushinteger(L, time.first); + lua_pushnumber(L, time.second); + lua_settable(L, -3); } - lua_setfield(L, -2, "damage_groups"); + // 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"); } /******************************************************************************/ 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); @@ -1325,40 +1312,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++; } @@ -1367,7 +1354,7 @@ void read_inventory_list(lua_State *L, int tableindex, /******************************************************************************/ 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; @@ -1375,74 +1362,75 @@ 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); } } @@ -1457,10 +1445,10 @@ ToolCapabilities read_tool_capabilities( 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); @@ -1474,7 +1462,7 @@ ToolCapabilities read_tool_capabilities( } /******************************************************************************/ -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); @@ -1483,7 +1471,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); @@ -1492,8 +1480,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); @@ -1504,8 +1492,7 @@ bool getflagsfield(lua_State *L, int table, const char *fieldname, 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); @@ -1601,7 +1588,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; @@ -1612,7 +1599,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()); @@ -1643,21 +1630,23 @@ 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; @@ -1679,8 +1668,7 @@ 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); @@ -1703,55 +1691,52 @@ 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; } @@ -1759,7 +1744,7 @@ static bool push_json_value_helper(lua_State *L, const Json::Value &value, // 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); @@ -1780,7 +1765,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) { @@ -1798,33 +1783,43 @@ 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) { @@ -1843,7 +1838,7 @@ void push_pointed_thing(lua_State *L, const PointedThing &pointed, bool csm, } else { push_objectRef(L, pointed.object_id); } - + lua_setfield(L, -2, "ref"); } else { lua_pushstring(L, "nothing"); @@ -1873,8 +1868,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(); @@ -1888,18 +1883,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) @@ -1918,8 +1913,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) @@ -1979,63 +1974,64 @@ 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; } @@ -2044,15 +2040,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 5a8bf6700..49ab96fd5 100644 --- a/src/script/common/c_content.h +++ b/src/script/common/c_content.h @@ -17,7 +17,6 @@ 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 */ @@ -41,7 +40,10 @@ extern "C" { #include "c_types.h" #include "hud.h" -namespace Json { class Value; } +namespace Json +{ +class Value; +} struct MapNode; class NodeDefManager; @@ -67,138 +69,96 @@ 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 eb6ab5331..349f148d3 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_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_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,8 +499,7 @@ 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; @@ -517,8 +516,7 @@ bool getstringfield(lua_State *L, int table, 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; @@ -531,13 +529,12 @@ bool getfloatfield(lua_State *L, int table, 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; } @@ -556,93 +553,82 @@ 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); @@ -669,25 +655,19 @@ size_t write_array_slice_float( 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); @@ -714,13 +694,13 @@ size_t write_array_slice_u16( 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 a4a7079fd..16d21db3b 100644 --- a/src/script/common/c_converter.h +++ b/src/script/common/c_converter.h @@ -17,7 +17,6 @@ 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 */ @@ -36,24 +35,21 @@ 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; } @@ -61,9 +57,8 @@ bool getintfield(lua_State *L, int table, 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; @@ -76,65 +71,54 @@ bool getv3intfield(lua_State *L, int index, 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 6df1f8b7b..19a874f63 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_State *L, int nargs, 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_State *L, int nargs, 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 442546332..677194453 100644 --- a/src/script/common/c_internal.h +++ b/src/script/common/c_internal.h @@ -34,7 +34,6 @@ extern "C" { #include "config.h" #include "common/c_types.h" - /* Define our custom indices into the Lua registry table. @@ -45,15 +44,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 @@ -65,17 +64,18 @@ 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,8 +111,7 @@ 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 e832ff2ab..93bb5bd70 100644 --- a/src/script/common/c_types.cpp +++ b/src/script/common/c_types.cpp @@ -23,12 +23,10 @@ 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 86bfb0b6b..860bfaaa8 100644 --- a/src/script/common/c_types.h +++ b/src/script/common/c_types.h @@ -38,10 +38,9 @@ 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 } @@ -57,5 +56,4 @@ 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 5f1f9297e..d0e520ae9 100644 --- a/src/script/cpp_api/s_async.cpp +++ b/src/script/cpp_api/s_async.cpp @@ -42,7 +42,6 @@ AsyncEngine::~AsyncEngine() workerThread->stop(); } - // Wake up all threads for (std::vector<AsyncWorkerThread *>::iterator it = workerThreads.begin(); it != workerThreads.end(); ++it) { @@ -77,16 +76,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; @@ -158,7 +157,8 @@ 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,11 +195,10 @@ 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(); @@ -221,7 +220,7 @@ AsyncWorkerThread::~AsyncWorkerThread() } /******************************************************************************/ -void* AsyncWorkerThread::run() +void *AsyncWorkerThread::run() { lua_State *L = getStack(); @@ -229,8 +228,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"); } @@ -258,11 +257,9 @@ 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); @@ -276,14 +273,13 @@ 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 b1f4bf45f..1dc4145ba 100644 --- a/src/script/cpp_api/s_async.h +++ b/src/script/cpp_api/s_async.h @@ -31,7 +31,6 @@ with this program; if not, write to the Free Software Foundation, Inc., // Forward declarations class AsyncEngine; - // Declarations // Data required to queue a job @@ -52,9 +51,10 @@ 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,9 +64,11 @@ 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(); @@ -125,7 +127,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 @@ -149,7 +151,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 1d62d8b65..72774f6ca 100644 --- a/src/script/cpp_api/s_base.cpp +++ b/src/script/cpp_api/s_base.cpp @@ -32,11 +32,10 @@ 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 } @@ -45,14 +44,13 @@ 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()); @@ -66,13 +64,11 @@ 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; @@ -86,7 +82,7 @@ ScriptApiBase::ScriptApiBase(ScriptingType 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 @@ -105,7 +101,7 @@ ScriptApiBase::ScriptApiBase(ScriptingType 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 @@ -136,7 +132,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; @@ -145,26 +141,25 @@ 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); @@ -191,8 +186,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 } @@ -225,8 +220,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 } @@ -240,14 +235,13 @@ 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 @@ -300,24 +294,25 @@ 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 << " "; } @@ -334,9 +329,10 @@ 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 } @@ -357,7 +353,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 @@ -371,14 +367,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"); @@ -400,8 +396,7 @@ 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); @@ -409,12 +404,13 @@ void ScriptApiBase::objectrefGetOrCreate(lua_State *L, 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); @@ -442,12 +438,12 @@ void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeR } } -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 36331ad37..d2081ad5c 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,14 +76,13 @@ 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); @@ -95,18 +94,17 @@ 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 @@ -126,50 +124,49 @@ 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 dd9019d4d..e6c9eea1a 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,7 +187,8 @@ 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 @@ -237,11 +238,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 ea9320051..baf455e1b 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,13 +39,14 @@ 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); @@ -67,15 +68,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 @@ -127,7 +128,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); @@ -156,12 +157,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); @@ -178,8 +179,8 @@ void ScriptApiEntity::luaentity_GetProperties(u16 id, 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 @@ -212,18 +213,18 @@ void ScriptApiEntity::luaentity_Step(u16 id, float dtime, // 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 @@ -233,8 +234,8 @@ bool ScriptApiEntity::luaentity_Punch(u16 id, 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); @@ -249,8 +250,8 @@ bool ScriptApiEntity::luaentity_Punch(u16 id, } // 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 @@ -267,8 +268,8 @@ bool ScriptApiEntity::luaentity_run_simple_callback(u16 id, 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 b5f7a6586..93960ed03 100644 --- a/src/script/cpp_api/s_entity.h +++ b/src/script/cpp_api/s_entity.h @@ -26,28 +26,26 @@ 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 8da5debaa..7511c0226 100644 --- a/src/script/cpp_api/s_env.cpp +++ b/src/script/cpp_api/s_env.cpp @@ -26,8 +26,7 @@ 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 @@ -44,7 +43,7 @@ void ScriptApiEnv::environment_OnGenerated(v3s16 minp, v3s16 maxp, 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"); @@ -54,9 +53,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)); } } @@ -72,14 +71,13 @@ 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)); } } @@ -116,7 +114,8 @@ 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); } @@ -133,7 +132,8 @@ 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,9 +249,8 @@ 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 232a08aaf..1848c7a94 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 83b3b9d27..858b827de 100644 --- a/src/script/cpp_api/s_internal.h +++ b/src/script/cpp_api/s_internal.h @@ -34,13 +34,14 @@ 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()); @@ -67,19 +68,18 @@ 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 e9c09f72e..e4d3f990d 100644 --- a/src/script/cpp_api/s_inventory.cpp +++ b/src/script/cpp_api/s_inventory.cpp @@ -26,8 +26,7 @@ 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 @@ -41,14 +40,15 @@ 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,8 +56,7 @@ 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 @@ -68,14 +67,15 @@ 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,8 +83,7 @@ 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 @@ -95,14 +94,15 @@ 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,8 +110,7 @@ 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 @@ -125,19 +124,18 @@ 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 @@ -152,16 +150,15 @@ 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 @@ -175,11 +172,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] @@ -199,7 +196,8 @@ 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; } @@ -218,8 +216,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 e79b3d18b..c6476190e 100644 --- a/src/script/cpp_api/s_inventory.h +++ b/src/script/cpp_api/s_inventory.h @@ -24,35 +24,29 @@ 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 24955cefc..4e77ad412 100644 --- a/src/script/cpp_api/s_item.cpp +++ b/src/script/cpp_api/s_item.cpp @@ -29,8 +29,7 @@ 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 @@ -52,12 +51,12 @@ bool ScriptApiItem::item_OnDrop(ItemStack &item, 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 @@ -84,12 +83,12 @@ bool ScriptApiItem::item_OnPlace(ItemStack &item, 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 @@ -104,19 +103,19 @@ bool ScriptApiItem::item_OnUse(ItemStack &item, 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 @@ -136,7 +135,7 @@ bool ScriptApiItem::item_OnSecondaryUse(ItemStack &item, 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; } @@ -168,7 +167,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; } @@ -184,7 +183,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)); @@ -200,7 +199,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; } @@ -210,10 +209,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"); @@ -247,8 +246,8 @@ bool ScriptApiItem::getItemCallback(const char *name, const char *callbackname, } 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; @@ -256,8 +255,7 @@ bool ScriptApiItem::getItemCallback(const char *name, const char *callbackname, 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 25a3501f9..530f14bbc 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 aef36ce39..0f6ff9f78 100644 --- a/src/script/cpp_api/s_mainmenu.h +++ b/src/script/cpp_api/s_mainmenu.h @@ -23,7 +23,8 @@ 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 e0f9bcd78..928fda6e2 100644 --- a/src/script/cpp_api/s_node.cpp +++ b/src/script/cpp_api/s_node.cpp @@ -26,10 +26,8 @@ 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"}, @@ -49,10 +47,9 @@ 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"}, @@ -66,35 +63,32 @@ 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 @@ -112,12 +106,11 @@ bool ScriptApiNode::node_on_punch(v3s16 p, MapNode node, 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 @@ -134,7 +127,7 @@ bool ScriptApiNode::node_on_dig(v3s16 p, MapNode node, 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; } @@ -153,7 +146,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) @@ -171,7 +164,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) @@ -211,7 +204,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) @@ -228,16 +221,14 @@ 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 @@ -255,9 +246,9 @@ void ScriptApiNode::node_on_receive_fields(v3s16 p, 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; @@ -266,7 +257,7 @@ void ScriptApiNode::node_on_receive_fields(v3s16 p, 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 81b44f0f0..8f4e41479 100644 --- a/src/script/cpp_api/s_node.h +++ b/src/script/cpp_api/s_node.h @@ -27,27 +27,23 @@ 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 c081e9fc4..b7bd5f7c8 100644 --- a/src/script/cpp_api/s_nodemeta.cpp +++ b/src/script/cpp_api/s_nodemeta.cpp @@ -28,8 +28,7 @@ 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 @@ -44,21 +43,23 @@ 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; @@ -66,8 +67,7 @@ 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,19 +82,21 @@ 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; @@ -102,8 +104,7 @@ 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 @@ -118,19 +119,21 @@ 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; @@ -138,8 +141,7 @@ 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 @@ -154,25 +156,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 @@ -191,19 +193,18 @@ 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 @@ -218,15 +219,16 @@ 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 8c7cdd93e..609898a30 100644 --- a/src/script/cpp_api/s_nodemeta.h +++ b/src/script/cpp_api/s_nodemeta.h @@ -26,9 +26,7 @@ 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; @@ -36,28 +34,22 @@ 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: +private: }; diff --git a/src/script/cpp_api/s_player.cpp b/src/script/cpp_api/s_player.cpp index 712120c61..c9ab81db9 100644 --- a/src/script/cpp_api/s_player.cpp +++ b/src/script/cpp_api/s_player.cpp @@ -39,7 +39,8 @@ 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 @@ -56,11 +57,8 @@ void ScriptApiPlayer::on_dieplayer(ServerActiveObject *player, const PlayerHPCha } 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 @@ -77,8 +75,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 @@ -115,9 +113,7 @@ 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 @@ -163,8 +159,7 @@ 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 @@ -177,8 +172,7 @@ void ScriptApiPlayer::on_leaveplayer(ServerActiveObject *player, 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 @@ -194,8 +188,7 @@ void ScriptApiPlayer::on_cheat(ServerActiveObject *player, } void ScriptApiPlayer::on_playerReceiveFields(ServerActiveObject *player, - const std::string &formname, - const StringMap &fields) + const std::string &formname, const StringMap &fields) { SCRIPTAPI_PRECHECKHEADER @@ -220,7 +213,8 @@ 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 @@ -236,13 +230,12 @@ void ScriptApiPlayer::on_authplayer(const std::string &name, const std::string & } 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 @@ -261,15 +254,14 @@ 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 @@ -286,8 +278,7 @@ void ScriptApiPlayer::pushPutTakeArguments( // 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 @@ -301,8 +292,7 @@ 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 @@ -316,8 +306,7 @@ 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 @@ -331,8 +320,7 @@ 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 @@ -344,8 +332,7 @@ 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 @@ -357,8 +344,7 @@ 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 a337f975b..5a1cf15b8 100644 --- a/src/script/cpp_api/s_player.h +++ b/src/script/cpp_api/s_player.h @@ -51,38 +51,33 @@ 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 9d65819c0..21bc7eb0a 100644 --- a/src/script/cpp_api/s_security.cpp +++ b/src/script/cpp_api/s_security.cpp @@ -29,19 +29,20 @@ 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]); } } @@ -50,91 +51,90 @@ 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,7 +154,6 @@ 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)); @@ -167,21 +166,19 @@ 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"); @@ -193,23 +190,21 @@ 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 @@ -219,7 +214,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 @@ -228,57 +223,49 @@ 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", - }; - static const char *os_whitelist[] = { - "clock", - "date", - "difftime", - "time" - }; - static const char *debug_whitelist[] = { - "getinfo", - "traceback" + "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"}; #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 @@ -312,16 +299,14 @@ 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 @@ -329,7 +314,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 @@ -339,9 +324,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; @@ -349,21 +334,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 } @@ -375,7 +360,8 @@ 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."); @@ -386,7 +372,8 @@ bool ScriptApiSecurity::safeLoadString(lua_State *L, const std::string &code, co 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; @@ -411,7 +398,8 @@ bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char 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); @@ -423,7 +411,7 @@ bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char lua_pushfstring(L, "%s: %s", path, strerror(errno)); if (path) { std::fclose(fp); - delete [] chunk_name; + delete[] chunk_name; } return false; } @@ -435,7 +423,7 @@ bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char lua_pushfstring(L, "%s: %s", path, strerror(errno)); if (path) { std::fclose(fp); - delete [] chunk_name; + delete[] chunk_name; } return false; } @@ -446,31 +434,31 @@ bool ScriptApiSecurity::safeLoadFile(lua_State *L, const char *path, const char 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 @@ -482,15 +470,18 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, 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()) @@ -504,9 +495,9 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, 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(); @@ -520,24 +511,27 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, // 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) { @@ -564,7 +558,8 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, } // 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; } } @@ -573,7 +568,6 @@ bool ScriptApiSecurity::checkPath(lua_State *L, const char *path, return false; } - int ScriptApiSecurity::sl_g_dofile(lua_State *L) { int nret = sl_g_loadfile(L); @@ -588,7 +582,6 @@ 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; @@ -627,12 +620,11 @@ 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 @@ -672,7 +664,6 @@ int ScriptApiSecurity::sl_g_loadfile(lua_State *L) return 1; } - int ScriptApiSecurity::sl_g_loadstring(lua_State *L) { const char *chunk_name = "=(load)"; @@ -695,14 +686,12 @@ 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; @@ -715,8 +704,7 @@ 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); @@ -730,7 +718,6 @@ int ScriptApiSecurity::sl_io_open(lua_State *L) return 2; } - int ScriptApiSecurity::sl_io_input(lua_State *L) { if (lua_isstring(L, 1)) { @@ -744,7 +731,6 @@ int ScriptApiSecurity::sl_io_input(lua_State *L) return 1; } - int ScriptApiSecurity::sl_io_output(lua_State *L) { if (lua_isstring(L, 1)) { @@ -758,7 +744,6 @@ int ScriptApiSecurity::sl_io_output(lua_State *L) return 1; } - int ScriptApiSecurity::sl_io_lines(lua_State *L) { if (lua_isstring(L, 1)) { @@ -775,7 +760,6 @@ 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); @@ -793,7 +777,6 @@ int ScriptApiSecurity::sl_os_rename(lua_State *L) return 2; } - int ScriptApiSecurity::sl_os_remove(lua_State *L) { luaL_checktype(L, 1, LUA_TSTRING); @@ -805,4 +788,3 @@ 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 73e763548..075950845 100644 --- a/src/script/cpp_api/s_security.h +++ b/src/script/cpp_api/s_security.h @@ -21,22 +21,20 @@ 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: @@ -51,12 +49,14 @@ 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 96cb28b28..1cb3f99f1 100644 --- a/src/script/cpp_api/s_server.cpp +++ b/src/script/cpp_api/s_server.cpp @@ -21,10 +21,8 @@ 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 @@ -54,10 +52,10 @@ bool ScriptApiServer::getAuth(const std::string &playername, 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; @@ -71,7 +69,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"); } @@ -102,8 +100,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 @@ -119,8 +117,8 @@ void ScriptApiServer::createAuth(const std::string &playername, 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 @@ -137,8 +135,7 @@ bool ScriptApiServer::setPassword(const std::string &playername, 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 @@ -174,8 +171,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 d8639cba7..db574bd56 100644 --- a/src/script/cpp_api/s_server.h +++ b/src/script/cpp_api/s_server.h @@ -22,8 +22,7 @@ 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 @@ -37,18 +36,15 @@ 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 908c766b0..d043bfc90 100644 --- a/src/script/lua_api/l_areastore.cpp +++ b/src/script/lua_api/l_areastore.cpp @@ -17,7 +17,6 @@ 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" @@ -27,8 +26,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; @@ -38,8 +37,8 @@ static inline void get_data_and_border_flags(lua_State *L, u8 start_i, *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); @@ -58,8 +57,8 @@ static void push_area(lua_State *L, const Area *a, } } -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(); @@ -71,8 +70,7 @@ static inline void push_areas(lua_State *L, const std::vector<Area *> &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); @@ -328,9 +326,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); @@ -348,7 +346,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) @@ -360,7 +358,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); @@ -370,27 +368,22 @@ 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 011434845..8ae03d6c8 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,9 +93,8 @@ 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! @@ -126,7 +125,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); @@ -136,12 +135,13 @@ 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 0cbee7756..bb806d631 100644 --- a/src/script/lua_api/l_base.h +++ b/src/script/lua_api/l_base.h @@ -41,43 +41,44 @@ 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 9961471ff..1bc4829d4 100644 --- a/src/script/lua_api/l_client.cpp +++ b/src/script/lua_api/l_client.cpp @@ -38,11 +38,12 @@ 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; }; @@ -53,14 +54,12 @@ 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) @@ -422,7 +421,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) @@ -433,7 +432,8 @@ 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 d88b538a1..05b3e2850 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,6 +223,5 @@ 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 521591444..a4516e047 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 18622ee00..07b45eaff 100644 --- a/src/script/lua_api/l_craft.cpp +++ b/src/script/lua_api/l_craft.cpp @@ -17,7 +17,6 @@ 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" @@ -26,46 +25,45 @@ 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 @@ -76,19 +74,19 @@ bool ModApiCraft::readCraftRecipeShaped(lua_State *L, int index, } // 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 @@ -98,27 +96,27 @@ bool ModApiCraft::readCraftRecipeShapeless(lua_State *L, int index, } // 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); @@ -132,20 +130,19 @@ bool ModApiCraft::readCraftReplacements(lua_State *L, int index, 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"); @@ -153,20 +150,22 @@ 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( @@ -176,29 +175,31 @@ 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( @@ -208,38 +209,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( @@ -249,29 +250,27 @@ 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 + "\""); } @@ -287,8 +286,7 @@ 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"); @@ -334,7 +332,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); } /* @@ -345,7 +343,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 + "\""); @@ -374,15 +372,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); @@ -417,9 +415,7 @@ 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); @@ -462,8 +458,7 @@ static void push_craft_recipe(lua_State *L, IGameDef *gdef, } 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); @@ -472,7 +467,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); @@ -480,7 +475,6 @@ static void push_craft_recipes(lua_State *L, IGameDef *gdef, } } - // get_craft_recipe(result item) int ModApiCraft::l_get_craft_recipe(lua_State *L) { @@ -489,8 +483,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); @@ -512,8 +506,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 9002b23ef..5ba3d18fe 100644 --- a/src/script/lua_api/l_craft.h +++ b/src/script/lua_api/l_craft.h @@ -26,7 +26,8 @@ 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); @@ -34,12 +35,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, + 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 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 ee384ad10..2c612eb9a 100644 --- a/src/script/lua_api/l_env.cpp +++ b/src/script/lua_api/l_env.cpp @@ -46,18 +46,16 @@ 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(); @@ -77,7 +75,7 @@ void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n, // 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 @@ -120,7 +118,8 @@ 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); @@ -176,10 +175,9 @@ 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; @@ -193,12 +191,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; } @@ -235,11 +233,7 @@ 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) { @@ -391,7 +385,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); @@ -423,7 +417,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; } @@ -433,7 +427,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); @@ -452,7 +446,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; } @@ -475,7 +469,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; } @@ -519,7 +513,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)); @@ -536,7 +530,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)); @@ -550,7 +544,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++) { @@ -596,7 +590,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 @@ -613,10 +607,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); @@ -625,7 +619,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()); @@ -639,10 +633,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; } @@ -690,7 +684,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; @@ -716,7 +710,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; } @@ -753,7 +747,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); @@ -825,13 +819,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) { @@ -875,13 +869,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) { @@ -929,13 +923,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) { @@ -986,7 +980,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; } @@ -1008,18 +1002,21 @@ 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; @@ -1043,19 +1040,21 @@ 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++) { @@ -1097,7 +1096,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; } @@ -1108,20 +1107,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); + 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; } - c = csurf; } - } return 1; } @@ -1136,10 +1135,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(); @@ -1177,9 +1176,10 @@ 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,10 +1237,12 @@ 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; @@ -1274,10 +1276,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; @@ -1311,19 +1313,22 @@ 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; } @@ -1345,16 +1350,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); @@ -1367,14 +1372,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; @@ -1382,16 +1387,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++; @@ -1410,24 +1415,23 @@ 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); @@ -1436,22 +1440,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"); } @@ -1493,14 +1497,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 e1b89494b..43388475e 100644 --- a/src/script/lua_api/l_env.h +++ b/src/script/lua_api/l_env.h @@ -23,7 +23,8 @@ 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} @@ -126,17 +127,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 @@ -200,12 +201,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); @@ -214,7 +215,8 @@ public: static struct EnumString es_ClearObjectsMode[]; }; -class LuaABM : public ActiveBlockModifier { +class LuaABM : public ActiveBlockModifier +{ private: int m_id; @@ -223,17 +225,18 @@ 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 @@ -244,18 +247,9 @@ 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); }; @@ -264,12 +258,11 @@ 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; @@ -297,14 +290,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); @@ -319,7 +312,8 @@ 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 84837e71b..21d000d25 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,7 +54,8 @@ 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)) { @@ -73,7 +74,8 @@ 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); @@ -171,15 +173,19 @@ 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 de6e51b37..f2c72eafb 100644 --- a/src/script/lua_api/l_http.h +++ b/src/script/lua_api/l_http.h @@ -25,12 +25,14 @@ 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 a86eeaf79..378d19cd0 100644 --- a/src/script/lua_api/l_internal.h +++ b/src/script/lua_api/l_internal.h @@ -28,8 +28,12 @@ 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 @@ -39,32 +43,33 @@ 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 e41b5cb41..d75d96ef3 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,7 +61,8 @@ 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; @@ -74,7 +75,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); @@ -89,7 +90,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); @@ -104,7 +105,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); @@ -126,23 +127,22 @@ 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,13 +229,12 @@ 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); @@ -251,11 +250,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); @@ -298,9 +297,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 { @@ -318,7 +317,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); @@ -326,8 +325,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; @@ -355,9 +354,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 { @@ -372,7 +371,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"); @@ -404,9 +403,7 @@ 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) { } @@ -443,7 +440,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); @@ -453,35 +450,25 @@ 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) @@ -492,7 +479,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); @@ -522,7 +509,6 @@ 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]) @@ -531,7 +517,8 @@ 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 94f670c9d..fa8a77ae2 100644 --- a/src/script/lua_api/l_inventory.h +++ b/src/script/lua_api/l_inventory.h @@ -30,7 +30,8 @@ class RemotePlayer; InvRef */ -class InvRef : public ModApiBase { +class InvRef : public ModApiBase +{ private: InventoryLocation m_loc; @@ -39,10 +40,9 @@ 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,16 +88,17 @@ 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)) @@ -116,7 +117,8 @@ 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 f3037ba83..f65137465 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,29 +69,30 @@ 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; @@ -103,7 +104,7 @@ int LuaInventoryAction::l_set_count(lua_State *L) ((ICraftAction *)o->m_action)->count = count; break; } - + return 0; } @@ -127,23 +128,25 @@ 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") @@ -206,11 +209,7 @@ 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 c1a96d010..a4cc6cbe5 100644 --- a/src/script/lua_api/l_inventoryaction.h +++ b/src/script/lua_api/l_inventoryaction.h @@ -20,44 +20,46 @@ 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(); @@ -67,6 +69,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 bea7d122f..9bbf9826b 100644 --- a/src/script/lua_api/l_item.cpp +++ b/src/script/lua_api/l_item.cpp @@ -234,12 +234,9 @@ 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"); @@ -314,8 +311,7 @@ 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"); } @@ -330,8 +326,7 @@ 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; } @@ -375,8 +370,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; } @@ -387,7 +382,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); @@ -401,23 +396,22 @@ 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; } @@ -476,44 +470,32 @@ 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 @@ -527,15 +509,13 @@ 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"); @@ -552,8 +532,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 = ""; @@ -573,13 +553,12 @@ 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 */ } @@ -589,13 +568,11 @@ 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); } @@ -612,8 +589,7 @@ 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); @@ -636,8 +612,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 98744c071..21110b83a 100644 --- a/src/script/lua_api/l_item.h +++ b/src/script/lua_api/l_item.h @@ -20,9 +20,10 @@ 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; @@ -114,8 +115,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); @@ -129,26 +130,27 @@ 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 d1ba1bda4..5a5c9934a 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,7 +68,8 @@ 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; @@ -79,7 +80,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); @@ -94,7 +95,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)); @@ -112,28 +113,20 @@ 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 c3198be4f..1351da9da 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,18 +47,16 @@ 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 e40dd7b37..789b3a3f0 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; } @@ -125,7 +125,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; @@ -266,7 +266,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); }; @@ -308,7 +308,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(); @@ -522,13 +522,10 @@ 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), - luamethod(LuaLocalPlayer, get_hp), - luamethod(LuaLocalPlayer, get_name), + luamethod(LuaLocalPlayer, get_yaw), luamethod(LuaLocalPlayer, set_yaw), + luamethod(LuaLocalPlayer, get_hp), luamethod(LuaLocalPlayer, get_name), luamethod(LuaLocalPlayer, get_wield_index), luamethod(LuaLocalPlayer, set_wield_index), luamethod(LuaLocalPlayer, get_wielded_item), @@ -547,18 +544,14 @@ const luaL_Reg LuaLocalPlayer::methods[] = { 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 f32c477c2..78a33b755 100644 --- a/src/script/lua_api/l_mainmenu.cpp +++ b/src/script/lua_api/l_mainmenu.cpp @@ -41,7 +41,6 @@ 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) { @@ -49,39 +48,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); @@ -90,13 +89,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) { @@ -124,28 +123,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; } @@ -153,7 +152,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; @@ -163,14 +162,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)) { @@ -182,36 +181,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; @@ -228,7 +227,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)); @@ -252,20 +251,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); @@ -286,7 +285,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(); @@ -305,8 +304,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"); @@ -318,8 +317,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"); @@ -450,25 +449,22 @@ 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]); } @@ -490,37 +486,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); @@ -529,7 +525,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); @@ -598,13 +594,11 @@ 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; @@ -613,17 +607,14 @@ 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])) { @@ -642,7 +633,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; } @@ -657,12 +648,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); @@ -685,12 +676,11 @@ 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; } @@ -699,7 +689,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; } @@ -708,7 +698,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; } @@ -717,7 +707,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; } @@ -725,7 +715,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; } @@ -737,7 +727,8 @@ 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)) { @@ -768,38 +759,37 @@ 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); @@ -809,7 +799,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; } @@ -818,33 +808,36 @@ 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; } @@ -853,14 +846,18 @@ 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; @@ -868,25 +865,24 @@ 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; } @@ -896,25 +892,31 @@ 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) { @@ -927,21 +929,16 @@ 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; @@ -950,34 +947,36 @@ 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); @@ -994,8 +993,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++) { @@ -1027,24 +1026,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; @@ -1074,12 +1073,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); @@ -1153,8 +1152,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 5a16b3bfe..c5875e797 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,12 +148,10 @@ 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 @@ -162,5 +160,4 @@ 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 834938e56..d52191a29 100644 --- a/src/script/lua_api/l_mapgen.cpp +++ b/src/script/lua_api/l_mapgen.cpp @@ -37,81 +37,73 @@ 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) @@ -132,8 +124,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; @@ -142,8 +134,7 @@ Schematic *get_or_load_schematic(lua_State *L, int index, 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; @@ -155,9 +146,8 @@ Schematic *get_or_load_schematic(lua_State *L, int index, 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; @@ -165,8 +155,7 @@ 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; @@ -178,10 +167,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; } @@ -190,9 +179,8 @@ 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); @@ -207,7 +195,8 @@ Schematic *load_schematic_from_def(lua_State *L, int index, 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; } @@ -219,9 +208,8 @@ Schematic *load_schematic_from_def(lua_State *L, int index, 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; @@ -251,19 +239,21 @@ bool read_schematic_def(lua_State *L, int index, //// 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; @@ -284,14 +274,14 @@ bool read_schematic_def(lua_State *L, int index, 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"); @@ -299,7 +289,8 @@ bool read_schematic_def(lua_State *L, int index, 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; @@ -309,7 +300,6 @@ bool read_schematic_def(lua_State *L, int index, return true; } - void read_schematic_replacements(lua_State *L, int index, StringMap *replace_names) { if (index < 0) @@ -323,21 +313,25 @@ 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); } @@ -369,42 +363,41 @@ 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 @@ -415,17 +408,16 @@ 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; @@ -444,8 +436,9 @@ size_t get_biome_list(lua_State *L, int index, 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; } @@ -463,8 +456,8 @@ size_t get_biome_list(lua_State *L, int index, 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; } @@ -499,7 +492,6 @@ 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) @@ -518,7 +510,6 @@ 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) @@ -531,12 +522,11 @@ 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; @@ -557,7 +547,6 @@ 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) @@ -570,12 +559,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; @@ -589,15 +578,14 @@ 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) @@ -612,16 +600,15 @@ 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; @@ -639,8 +626,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; @@ -662,7 +649,6 @@ 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) @@ -756,7 +742,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); @@ -779,7 +765,6 @@ 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) { @@ -800,18 +785,17 @@ 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); @@ -841,7 +825,6 @@ 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) @@ -849,17 +832,18 @@ 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)) @@ -867,18 +851,21 @@ 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; } @@ -890,7 +877,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)) @@ -907,7 +894,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)) @@ -924,21 +911,20 @@ 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) @@ -946,28 +932,27 @@ 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) @@ -979,7 +964,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; } @@ -990,7 +975,6 @@ int ModApiMapgen::l_set_noiseparams(lua_State *L) return 0; } - // get_noiseparams(name) int ModApiMapgen::l_get_noiseparams(lua_State *L) { @@ -1006,7 +990,6 @@ 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) { @@ -1024,7 +1007,8 @@ 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); } } @@ -1032,7 +1016,6 @@ int ModApiMapgen::l_set_gen_notify(lua_State *L) return 0; } - // get_gen_notify() int ModApiMapgen::l_get_gen_notify(lua_State *L) { @@ -1040,7 +1023,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; @@ -1051,7 +1034,6 @@ 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) @@ -1063,7 +1045,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; @@ -1078,7 +1060,6 @@ int ModApiMapgen::l_get_decoration_id(lua_State *L) return 1; } - // register_biome({lots of stuff}) int ModApiMapgen::l_register_biome(lua_State *L) { @@ -1104,7 +1085,6 @@ int ModApiMapgen::l_register_biome(lua_State *L) return 1; } - // register_decoration({lots of stuff}) int ModApiMapgen::l_register_decoration(lua_State *L) { @@ -1113,32 +1093,33 @@ 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; } @@ -1159,7 +1140,8 @@ 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' @@ -1167,7 +1149,8 @@ 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 @@ -1200,19 +1183,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; } @@ -1221,7 +1204,8 @@ 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; } @@ -1229,8 +1213,9 @@ 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; } @@ -1240,13 +1225,12 @@ 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"); @@ -1262,7 +1246,6 @@ 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) { @@ -1273,28 +1256,29 @@ 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) && @@ -1303,24 +1287,25 @@ 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; } @@ -1340,7 +1325,8 @@ 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; } @@ -1348,54 +1334,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); @@ -1415,21 +1401,19 @@ 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; @@ -1443,55 +1427,48 @@ 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) { @@ -1501,13 +1478,15 @@ 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); @@ -1517,7 +1496,6 @@ 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) { @@ -1527,13 +1505,15 @@ 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); @@ -1543,7 +1523,6 @@ 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) { @@ -1561,7 +1540,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)) { @@ -1570,7 +1549,8 @@ 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); } @@ -1578,13 +1558,14 @@ 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); } @@ -1594,21 +1575,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) @@ -1656,7 +1637,6 @@ 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) @@ -1699,19 +1679,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); @@ -1725,7 +1705,8 @@ 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; } @@ -1742,8 +1723,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; @@ -1763,10 +1744,11 @@ 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; @@ -1812,7 +1794,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()); @@ -1835,7 +1817,6 @@ 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 0bdc56fc5..ebc49a5ec 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 21002e6a7..3c9670c22 100644 --- a/src/script/lua_api/l_metadata.cpp +++ b/src/script/lua_api/l_metadata.cpp @@ -26,12 +26,14 @@ 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; } } @@ -39,14 +41,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 5fba76eb8..1c429bdcb 100644 --- a/src/script/lua_api/l_minimap.cpp +++ b/src/script/lua_api/l_minimap.cpp @@ -17,7 +17,6 @@ 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" @@ -99,12 +98,11 @@ 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; } @@ -172,15 +170,16 @@ 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; @@ -195,7 +194,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); @@ -205,23 +204,16 @@ 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 57052cb42..934c08796 100644 --- a/src/script/lua_api/l_nodemeta.cpp +++ b/src/script/lua_api/l_nodemeta.cpp @@ -29,15 +29,16 @@ 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; @@ -64,7 +65,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; @@ -76,7 +77,8 @@ 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; @@ -88,7 +90,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; } @@ -99,7 +101,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)) { @@ -124,15 +126,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()); } @@ -147,7 +149,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(); @@ -167,16 +169,11 @@ 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) { } @@ -185,7 +182,7 @@ NodeMetaRef::NodeMetaRef(Metadata *meta): 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); @@ -210,7 +207,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)); @@ -228,49 +225,33 @@ 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 fdc1766ed..227d79f09 100644 --- a/src/script/lua_api/l_nodemeta.h +++ b/src/script/lua_api/l_nodemeta.h @@ -31,7 +31,8 @@ class NodeMetadata; NodeMetaRef */ -class NodeMetaRef : public MetaDataRef { +class NodeMetaRef : public MetaDataRef +{ private: v3s16 m_p; ServerEnvironment *m_env = nullptr; @@ -54,10 +55,11 @@ 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 c2df52c05..621af5fd3 100644 --- a/src/script/lua_api/l_nodetimer.cpp +++ b/src/script/lua_api/l_nodetimer.cpp @@ -22,27 +22,28 @@ 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; } @@ -51,7 +52,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; } @@ -69,7 +70,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; } @@ -78,7 +79,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; } @@ -87,7 +88,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; } @@ -110,7 +111,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); @@ -120,22 +121,17 @@ 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 9aeb15709..0e9ece82b 100644 --- a/src/script/lua_api/l_noise.cpp +++ b/src/script/lua_api/l_noise.cpp @@ -30,12 +30,10 @@ 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; @@ -46,7 +44,6 @@ int LuaPerlinNoise::l_get_2d(lua_State *L) return 1; } - int LuaPerlinNoise::l_get_3d(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -57,7 +54,6 @@ int LuaPerlinNoise::l_get_3d(lua_State *L) return 1; } - int LuaPerlinNoise::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -67,10 +63,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); @@ -81,7 +77,6 @@ int LuaPerlinNoise::create_object(lua_State *L) return 1; } - int LuaPerlinNoise::gc_object(lua_State *L) { LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1)); @@ -89,7 +84,6 @@ int LuaPerlinNoise::gc_object(lua_State *L) return 0; } - LuaPerlinNoise *LuaPerlinNoise::checkobject(lua_State *L, int narg) { NO_MAP_LOCK_REQUIRED; @@ -100,7 +94,6 @@ LuaPerlinNoise *LuaPerlinNoise::checkobject(lua_State *L, int narg) return *(LuaPerlinNoise **)ud; } - void LuaPerlinNoise::Register(lua_State *L) { lua_newtable(L); @@ -129,13 +122,9 @@ 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}}; /////////////////////////////////////// /* @@ -153,13 +142,11 @@ 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; @@ -183,7 +170,6 @@ 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; @@ -209,7 +195,6 @@ 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; @@ -240,14 +225,13 @@ 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; @@ -269,7 +253,6 @@ 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; @@ -288,7 +271,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; @@ -299,15 +282,14 @@ 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; @@ -316,15 +298,13 @@ 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; @@ -339,7 +319,6 @@ int LuaPerlinNoiseMap::create_object(lua_State *L) return 1; } - int LuaPerlinNoiseMap::gc_object(lua_State *L) { LuaPerlinNoiseMap *o = *(LuaPerlinNoiseMap **)(lua_touserdata(L, 1)); @@ -347,7 +326,6 @@ int LuaPerlinNoiseMap::gc_object(lua_State *L) return 0; } - LuaPerlinNoiseMap *LuaPerlinNoiseMap::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -359,7 +337,6 @@ LuaPerlinNoiseMap *LuaPerlinNoiseMap::checkobject(lua_State *L, int narg) return *(LuaPerlinNoiseMap **)ud; } - void LuaPerlinNoiseMap::Register(lua_State *L) { lua_newtable(L); @@ -388,18 +365,15 @@ 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}}; /////////////////////////////////////// /* @@ -419,22 +393,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; @@ -447,7 +421,6 @@ int LuaPseudoRandom::create_object(lua_State *L) return 1; } - int LuaPseudoRandom::gc_object(lua_State *L) { LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1)); @@ -455,7 +428,6 @@ int LuaPseudoRandom::gc_object(lua_State *L) return 0; } - LuaPseudoRandom *LuaPseudoRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -465,7 +437,6 @@ LuaPseudoRandom *LuaPseudoRandom::checkobject(lua_State *L, int narg) return *(LuaPseudoRandom **)ud; } - void LuaPseudoRandom::Register(lua_State *L) { lua_newtable(L); @@ -493,12 +464,8 @@ 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}}; /////////////////////////////////////// /* @@ -517,7 +484,6 @@ int LuaPcgRandom::l_next(lua_State *L) return 1; } - int LuaPcgRandom::l_rand_normal_dist(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -531,22 +497,19 @@ 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)); @@ -554,7 +517,6 @@ int LuaPcgRandom::gc_object(lua_State *L) return 0; } - LuaPcgRandom *LuaPcgRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -564,7 +526,6 @@ LuaPcgRandom *LuaPcgRandom::checkobject(lua_State *L, int narg) return *(LuaPcgRandom **)ud; } - void LuaPcgRandom::Register(lua_State *L) { lua_newtable(L); @@ -592,13 +553,9 @@ 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}}; /////////////////////////////////////// /* @@ -633,7 +590,8 @@ 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; @@ -644,7 +602,6 @@ int LuaSecureRandom::l_next_bytes(lua_State *L) return 1; } - int LuaSecureRandom::create_object(lua_State *L) { LuaSecureRandom *o = new LuaSecureRandom(); @@ -661,7 +618,6 @@ int LuaSecureRandom::create_object(lua_State *L) return 1; } - int LuaSecureRandom::gc_object(lua_State *L) { LuaSecureRandom *o = *(LuaSecureRandom **)(lua_touserdata(L, 1)); @@ -669,7 +625,6 @@ int LuaSecureRandom::gc_object(lua_State *L) return 0; } - LuaSecureRandom *LuaSecureRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -679,7 +634,6 @@ LuaSecureRandom *LuaSecureRandom::checkobject(lua_State *L, int narg) return *(LuaSecureRandom **)ud; } - void LuaSecureRandom::Register(lua_State *L) { lua_newtable(L); @@ -709,6 +663,4 @@ 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 e7394133a..5d48ee93d 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,9 +87,10 @@ 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; } @@ -121,7 +122,8 @@ 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; } @@ -132,7 +134,8 @@ 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 @@ -146,7 +149,8 @@ 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 @@ -185,17 +189,18 @@ 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; } @@ -208,8 +213,10 @@ 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; @@ -240,7 +247,8 @@ 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); @@ -287,7 +295,8 @@ 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) @@ -347,7 +356,8 @@ 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); @@ -364,7 +374,8 @@ 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); @@ -391,8 +402,9 @@ 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( @@ -403,8 +415,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; @@ -457,7 +469,8 @@ 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)) @@ -484,7 +497,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; @@ -507,9 +520,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)) @@ -559,10 +572,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); @@ -627,7 +640,8 @@ 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)) @@ -680,7 +694,8 @@ 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; @@ -851,7 +866,8 @@ 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); @@ -878,7 +894,8 @@ 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); @@ -891,7 +908,8 @@ 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 @@ -905,7 +923,8 @@ 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); @@ -951,7 +970,8 @@ 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."); @@ -980,7 +1000,8 @@ 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); @@ -993,7 +1014,8 @@ 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()); @@ -1007,9 +1029,10 @@ 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; @@ -1032,8 +1055,9 @@ 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()); @@ -1046,7 +1070,8 @@ 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; @@ -1060,7 +1085,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)); @@ -1119,13 +1144,14 @@ 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; } @@ -1136,12 +1162,13 @@ 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; @@ -1153,12 +1180,13 @@ 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; @@ -1169,8 +1197,9 @@ 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; @@ -1181,8 +1210,9 @@ 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; @@ -1193,8 +1223,9 @@ 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); @@ -1206,8 +1237,9 @@ 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); @@ -1220,12 +1252,13 @@ 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); @@ -1238,12 +1271,13 @@ 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); @@ -1259,11 +1293,10 @@ 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; @@ -1291,8 +1324,9 @@ 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); @@ -1304,22 +1338,23 @@ 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; @@ -1336,11 +1371,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; @@ -1355,7 +1390,6 @@ int ObjectRef::l_get_attribute(lua_State *L) return 0; } - // get_meta(self, attribute) int ObjectRef::l_get_meta(lua_State *L) { @@ -1368,14 +1402,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; @@ -1390,7 +1424,8 @@ 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()); @@ -1421,7 +1456,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()); @@ -1573,14 +1608,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)) @@ -1735,7 +1770,8 @@ 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); } @@ -1748,11 +1784,12 @@ 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)) { @@ -1836,9 +1873,10 @@ 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 @@ -1878,7 +1916,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++); } @@ -1896,7 +1934,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") { @@ -1938,25 +1976,20 @@ 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; @@ -1996,14 +2029,12 @@ 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); @@ -2046,18 +2077,15 @@ 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); @@ -2100,7 +2128,8 @@ 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)) @@ -2111,8 +2140,9 @@ 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)) { @@ -2158,7 +2188,6 @@ 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) { @@ -2201,10 +2230,9 @@ 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 @@ -2212,7 +2240,7 @@ ObjectRef::ObjectRef(ServerActiveObject *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); @@ -2233,7 +2261,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); @@ -2243,119 +2271,97 @@ 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 a75c59fd9..a7b52bdb3 100644 --- a/src/script/lua_api/l_object.h +++ b/src/script/lua_api/l_object.h @@ -31,7 +31,8 @@ class RemotePlayer; ObjectRef */ -class ObjectRef : public ModApiBase { +class ObjectRef : public ModApiBase +{ public: ObjectRef(ServerActiveObject *object); @@ -47,16 +48,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 LuaEntitySAO* getluaobject(ObjectRef *ref); - - static PlayerSAO* getplayersao(ObjectRef *ref); + static PlayerSAO *getplayersao(ObjectRef *ref); static RemotePlayer *getplayer(ObjectRef *ref); @@ -331,7 +332,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 a51c4fe20..ea0a7c796 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,9 +59,7 @@ 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); @@ -71,7 +69,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); @@ -84,7 +82,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); @@ -93,15 +91,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"); @@ -156,10 +154,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); @@ -176,9 +174,7 @@ 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); @@ -216,12 +212,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); @@ -276,4 +272,3 @@ 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 122810b6d..8734e5516 100644 --- a/src/script/lua_api/l_particles.h +++ b/src/script/lua_api/l_particles.h @@ -21,7 +21,8 @@ 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 cc68b13a5..498376d40 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 482b0cbf5..09da123c3 100644 --- a/src/script/lua_api/l_rollback.cpp +++ b/src/script/lua_api/l_rollback.cpp @@ -23,7 +23,6 @@ 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); @@ -35,14 +34,15 @@ 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,7 +50,8 @@ 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); @@ -101,8 +102,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 c26ff634e..74d8ce10e 100644 --- a/src/script/lua_api/l_rollback.h +++ b/src/script/lua_api/l_rollback.h @@ -24,7 +24,8 @@ 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 64ae924d2..f4362dd7f 100644 --- a/src/script/lua_api/l_server.cpp +++ b/src/script/lua_api/l_server.cpp @@ -56,7 +56,6 @@ int ModApiServer::l_get_server_uptime(lua_State *L) return 1; } - // print(text) int ModApiServer::l_print(lua_State *L) { @@ -116,15 +115,14 @@ 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()); @@ -166,21 +164,19 @@ 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 @@ -190,11 +186,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) { @@ -230,11 +226,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); @@ -247,28 +243,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 @@ -287,8 +283,9 @@ 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; } @@ -296,19 +293,21 @@ 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; @@ -328,7 +327,8 @@ 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,10 +373,9 @@ 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; @@ -480,7 +479,8 @@ 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 33eb02392..cc4b23ee4 100644 --- a/src/script/lua_api/l_settings.cpp +++ b/src/script/lua_api/l_settings.cpp @@ -25,23 +25,20 @@ 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()); @@ -53,9 +50,7 @@ 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; @@ -63,21 +58,19 @@ void LuaSettings::create(lua_State *L, Settings *settings, 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)) { @@ -91,10 +84,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)) { @@ -153,13 +146,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); @@ -170,10 +163,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); @@ -203,10 +196,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)); @@ -219,16 +212,15 @@ 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); } @@ -237,10 +229,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 + @@ -254,10 +246,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(); @@ -270,8 +262,7 @@ 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); @@ -280,7 +271,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); @@ -290,10 +281,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); @@ -301,41 +292,33 @@ 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 b86eda53e..bd9ec2543 100644 --- a/src/script/lua_api/l_sound.cpp +++ b/src/script/lua_api/l_sound.cpp @@ -23,7 +23,6 @@ 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 cba34fb63..fe3b4d74c 100644 --- a/src/script/lua_api/l_storage.cpp +++ b/src/script/lua_api/l_storage.cpp @@ -53,8 +53,7 @@ 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) { } @@ -90,7 +89,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)); @@ -108,27 +107,28 @@ 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,17 +139,10 @@ 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 4595dc1c1..b77e26886 100644 --- a/src/script/lua_api/l_util.cpp +++ b/src/script/lua_api/l_util.cpp @@ -41,7 +41,6 @@ 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. @@ -65,7 +64,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; } } @@ -109,8 +108,10 @@ 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; } @@ -121,7 +122,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); } @@ -176,7 +177,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))); @@ -228,9 +229,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); @@ -345,7 +346,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); @@ -416,12 +417,11 @@ 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,4 +571,3 @@ 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 b99b1d98c..17fb830f9 100644 --- a/src/script/lua_api/l_vmanip.cpp +++ b/src/script/lua_api/l_vmanip.cpp @@ -17,7 +17,6 @@ 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" @@ -63,7 +62,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; @@ -117,8 +116,7 @@ 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; @@ -139,7 +137,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; @@ -152,8 +150,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); @@ -171,11 +169,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; } @@ -187,7 +185,8 @@ 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; } @@ -196,10 +195,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); @@ -207,8 +206,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); @@ -223,7 +222,8 @@ 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,8 +374,7 @@ 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) { } @@ -406,9 +405,10 @@ 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,32 +448,28 @@ 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 729645678..011c93b43 100644 --- a/src/script/scripting_client.cpp +++ b/src/script/scripting_client.cpp @@ -41,8 +41,7 @@ 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 e162f8bcf..b8dd257a9 100644 --- a/src/script/scripting_client.h +++ b/src/script/scripting_client.h @@ -31,12 +31,11 @@ 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 0f672f917..835368776 100644 --- a/src/script/scripting_mainmenu.cpp +++ b/src/script/scripting_mainmenu.cpp @@ -34,8 +34,7 @@ extern "C" { #define MAINMENU_NUM_ASYNC_THREADS 4 - -MainMenuScripting::MainMenuScripting(GUIEngine* guiengine): +MainMenuScripting::MainMenuScripting(GUIEngine *guiengine) : ScriptApiBase(ScriptingType::MainMenu) { setGuiEngine(guiengine); @@ -76,7 +75,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); } @@ -93,9 +92,8 @@ 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 9e23bdc1b..16d0a0cc0 100644 --- a/src/script/scripting_mainmenu.h +++ b/src/script/scripting_mainmenu.h @@ -27,12 +27,10 @@ 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(); @@ -40,6 +38,7 @@ 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 85411ded4..604607e78 100644 --- a/src/script/scripting_server.cpp +++ b/src/script/scripting_server.cpp @@ -50,8 +50,7 @@ extern "C" { #include "lualib.h" } -ServerScripting::ServerScripting(Server* server): - ScriptApiBase(ScriptingType::Server) +ServerScripting::ServerScripting(Server *server) : ScriptApiBase(ScriptingType::Server) { setGameDef(server); @@ -63,9 +62,12 @@ ServerScripting::ServerScripting(Server* server): 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 bf06ab197..b0619f449 100644 --- a/src/script/scripting_server.h +++ b/src/script/scripting_server.h @@ -32,19 +32,18 @@ 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 |