From 6ccb5835ff55d85156be91473c598eca9d6cb9a6 Mon Sep 17 00:00:00 2001 From: Elias Fleckenstein Date: Wed, 4 Nov 2020 16:57:41 +0100 Subject: Revert "Make Lint Happy" This reverts commit ad148587dcf5244c2d2011dba339786c765c54c4. --- src/script/lua_api/l_areastore.cpp | 55 +-- src/script/lua_api/l_base.cpp | 24 +- src/script/lua_api/l_base.h | 39 +- src/script/lua_api/l_client.cpp | 38 +- src/script/lua_api/l_clientobject.cpp | 7 +- src/script/lua_api/l_clientobject.h | 2 +- src/script/lua_api/l_craft.cpp | 188 +++++----- src/script/lua_api/l_craft.h | 13 +- src/script/lua_api/l_env.cpp | 298 ++++++++-------- src/script/lua_api/l_env.h | 84 +++-- src/script/lua_api/l_http.cpp | 24 +- src/script/lua_api/l_http.h | 6 +- src/script/lua_api/l_internal.h | 41 +-- src/script/lua_api/l_inventory.cpp | 119 ++++--- src/script/lua_api/l_inventory.h | 24 +- src/script/lua_api/l_inventoryaction.cpp | 45 +-- src/script/lua_api/l_inventoryaction.h | 34 +- src/script/lua_api/l_item.cpp | 112 +++--- src/script/lua_api/l_item.h | 20 +- src/script/lua_api/l_itemstackmeta.cpp | 43 ++- src/script/lua_api/l_itemstackmeta.h | 10 +- src/script/lua_api/l_localplayer.cpp | 33 +- src/script/lua_api/l_mainmenu.cpp | 349 +++++++++--------- src/script/lua_api/l_mainmenu.h | 19 +- src/script/lua_api/l_mapgen.cpp | 593 ++++++++++++++++--------------- src/script/lua_api/l_mapgen.h | 2 +- src/script/lua_api/l_metadata.cpp | 14 +- src/script/lua_api/l_minimap.cpp | 40 ++- src/script/lua_api/l_nodemeta.cpp | 89 +++-- src/script/lua_api/l_nodemeta.h | 8 +- src/script/lua_api/l_nodetimer.cpp | 46 +-- src/script/lua_api/l_noise.cpp | 120 +++++-- src/script/lua_api/l_object.cpp | 514 +++++++++++++-------------- src/script/lua_api/l_object.h | 13 +- src/script/lua_api/l_particles.cpp | 47 +-- src/script/lua_api/l_particles.h | 3 +- src/script/lua_api/l_particles_local.cpp | 38 +- src/script/lua_api/l_rollback.cpp | 13 +- src/script/lua_api/l_rollback.h | 3 +- src/script/lua_api/l_server.cpp | 92 ++--- src/script/lua_api/l_settings.cpp | 105 +++--- src/script/lua_api/l_sound.cpp | 1 + src/script/lua_api/l_storage.cpp | 43 ++- src/script/lua_api/l_util.cpp | 35 +- src/script/lua_api/l_vmanip.cpp | 98 ++--- 45 files changed, 1858 insertions(+), 1686 deletions(-) (limited to 'src/script/lua_api') diff --git a/src/script/lua_api/l_areastore.cpp b/src/script/lua_api/l_areastore.cpp index d043bfc90..908c766b0 100644 --- a/src/script/lua_api/l_areastore.cpp +++ b/src/script/lua_api/l_areastore.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "lua_api/l_areastore.h" #include "lua_api/l_internal.h" #include "common/c_converter.h" @@ -26,8 +27,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "filesys.h" #include -static inline void get_data_and_border_flags( - lua_State *L, u8 start_i, bool *borders, bool *data) +static inline void get_data_and_border_flags(lua_State *L, u8 start_i, + bool *borders, bool *data) { if (!lua_isboolean(L, start_i)) return; @@ -37,8 +38,8 @@ static inline void get_data_and_border_flags( *data = lua_toboolean(L, start_i + 1); } -static void push_area( - lua_State *L, const Area *a, bool include_borders, bool include_data) +static void push_area(lua_State *L, const Area *a, + bool include_borders, bool include_data) { if (!include_borders && !include_data) { lua_pushboolean(L, true); @@ -57,8 +58,8 @@ static void push_area( } } -static inline void push_areas( - lua_State *L, const std::vector &areas, bool borders, bool data) +static inline void push_areas(lua_State *L, const std::vector &areas, + bool borders, bool data) { lua_newtable(L); size_t cnt = areas.size(); @@ -70,7 +71,8 @@ static inline void push_areas( } // Deserializes value and handles errors -static int deserialization_helper(lua_State *L, AreaStore *as, std::istream &is) +static int deserialization_helper(lua_State *L, AreaStore *as, + std::istream &is) { try { as->deserialize(is); @@ -326,9 +328,9 @@ int LuaAreaStore::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; - LuaAreaStore *o = (lua_isstring(L, 1)) - ? new LuaAreaStore(readParam(L, 1)) - : new LuaAreaStore(); + LuaAreaStore *o = (lua_isstring(L, 1)) ? + new LuaAreaStore(readParam(L, 1)) : + new LuaAreaStore(); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); @@ -346,7 +348,7 @@ LuaAreaStore *LuaAreaStore::checkobject(lua_State *L, int narg) if (!ud) luaL_typerror(L, narg, className); - return *(LuaAreaStore **)ud; // unbox pointer + return *(LuaAreaStore **)ud; // unbox pointer } void LuaAreaStore::Register(lua_State *L) @@ -358,7 +360,7 @@ void LuaAreaStore::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -368,22 +370,27 @@ void LuaAreaStore::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Can be created from Lua (AreaStore()) lua_register(L, className, create_object); } const char LuaAreaStore::className[] = "AreaStore"; -const luaL_Reg LuaAreaStore::methods[] = {luamethod(LuaAreaStore, get_area), - luamethod(LuaAreaStore, get_areas_for_pos), - luamethod(LuaAreaStore, get_areas_in_area), - luamethod(LuaAreaStore, insert_area), luamethod(LuaAreaStore, reserve), - luamethod(LuaAreaStore, remove_area), - luamethod(LuaAreaStore, set_cache_params), - luamethod(LuaAreaStore, to_string), luamethod(LuaAreaStore, to_file), - luamethod(LuaAreaStore, from_string), luamethod(LuaAreaStore, from_file), - {0, 0}}; +const luaL_Reg LuaAreaStore::methods[] = { + luamethod(LuaAreaStore, get_area), + luamethod(LuaAreaStore, get_areas_for_pos), + luamethod(LuaAreaStore, get_areas_in_area), + luamethod(LuaAreaStore, insert_area), + luamethod(LuaAreaStore, reserve), + luamethod(LuaAreaStore, remove_area), + luamethod(LuaAreaStore, set_cache_params), + luamethod(LuaAreaStore, to_string), + luamethod(LuaAreaStore, to_file), + luamethod(LuaAreaStore, from_string), + luamethod(LuaAreaStore, from_file), + {0,0} +}; diff --git a/src/script/lua_api/l_base.cpp b/src/script/lua_api/l_base.cpp index 8ae03d6c8..011434845 100644 --- a/src/script/lua_api/l_base.cpp +++ b/src/script/lua_api/l_base.cpp @@ -32,9 +32,9 @@ ScriptApiBase *ModApiBase::getScriptApiBase(lua_State *L) lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI); ScriptApiBase *sapi_ptr; #if INDIRECT_SCRIPTAPI_RIDX - sapi_ptr = (ScriptApiBase *)*(void **)(lua_touserdata(L, -1)); + sapi_ptr = (ScriptApiBase*) *(void**)(lua_touserdata(L, -1)); #else - sapi_ptr = (ScriptApiBase *)lua_touserdata(L, -1); + sapi_ptr = (ScriptApiBase*) lua_touserdata(L, -1); #endif lua_pop(L, 1); return sapi_ptr; @@ -93,8 +93,9 @@ std::string ModApiBase::getCurrentModPath(lua_State *L) return mod->path; } -bool ModApiBase::registerFunction( - lua_State *L, const char *name, lua_CFunction func, int top) + +bool ModApiBase::registerFunction(lua_State *L, const char *name, + lua_CFunction func, int top) { // TODO: Check presence first! @@ -125,7 +126,7 @@ int ModApiBase::l_deprecated_function(lua_State *L) // Get parent class to get the wrappers map luaL_checktype(L, 1, LUA_TUSERDATA); void *ud = lua_touserdata(L, 1); - ModApiBase *o = *(ModApiBase **)ud; + ModApiBase *o = *(ModApiBase**)ud; // New function and new function name auto it = o->m_deprecated_wrappers.find(ar.name); @@ -135,13 +136,12 @@ int ModApiBase::l_deprecated_function(lua_State *L) backtrace.append(":").append(std::to_string(ar.currentline)); u64 hash = murmur_hash_64_ua(backtrace.data(), backtrace.length(), 0xBADBABE); - if (std::find(deprecated_logged.begin(), deprecated_logged.end(), hash) == - deprecated_logged.end()) { + if (std::find(deprecated_logged.begin(), deprecated_logged.end(), hash) + == deprecated_logged.end()) { deprecated_logged.emplace_back(hash); - warningstream << "Call to deprecated function '" << ar.name - << "', please use '" << it->second.name << "' at " - << backtrace << std::endl; + warningstream << "Call to deprecated function '" << ar.name << "', please use '" + << it->second.name << "' at " << backtrace << std::endl; if (m_error_deprecated_calls) script_error(L, LUA_ERRRUN, NULL, NULL); @@ -172,8 +172,8 @@ void ModApiBase::markAliasDeprecated(luaL_Reg *reg) // Do not inline struct. Breaks MSVC or is error-prone original_reg.name = last_name; original_reg.func = reg->func; - m_deprecated_wrappers.emplace(std::pair( - reg->name, original_reg)); + m_deprecated_wrappers.emplace( + std::pair(reg->name, original_reg)); reg->func = l_deprecated_function; } diff --git a/src/script/lua_api/l_base.h b/src/script/lua_api/l_base.h index bb806d631..0cbee7756 100644 --- a/src/script/lua_api/l_base.h +++ b/src/script/lua_api/l_base.h @@ -41,44 +41,43 @@ class Server; class Environment; class ServerInventoryManager; -class ModApiBase : protected LuaHelper -{ +class ModApiBase : protected LuaHelper { public: - static ScriptApiBase *getScriptApiBase(lua_State *L); - static Server *getServer(lua_State *L); + static ScriptApiBase* getScriptApiBase(lua_State *L); + static Server* getServer(lua_State *L); static ServerInventoryManager *getServerInventoryMgr(lua_State *L); -#ifndef SERVER - static Client *getClient(lua_State *L); - static Game *getGame(lua_State *L); - static GUIEngine *getGuiEngine(lua_State *L); -#endif // !SERVER + #ifndef SERVER + static Client* getClient(lua_State *L); + static Game* getGame(lua_State *L); + static GUIEngine* getGuiEngine(lua_State *L); + #endif // !SERVER - static IGameDef *getGameDef(lua_State *L); - static Environment *getEnv(lua_State *L); + static IGameDef* getGameDef(lua_State *L); + static Environment* getEnv(lua_State *L); // When we are not loading the mod, this function returns "." - static std::string getCurrentModPath(lua_State *L); + static std::string getCurrentModPath(lua_State *L); // Get an arbitrary subclass of ScriptApiBase // by using dynamic_cast<> on getScriptApiBase() - template static T *getScriptApi(lua_State *L) - { + template + static T* getScriptApi(lua_State *L) { ScriptApiBase *scriptIface = getScriptApiBase(L); - T *scriptIfaceDowncast = dynamic_cast(scriptIface); + T *scriptIfaceDowncast = dynamic_cast(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: // = { , } static std::unordered_map m_deprecated_wrappers; diff --git a/src/script/lua_api/l_client.cpp b/src/script/lua_api/l_client.cpp index 1bc4829d4..9961471ff 100644 --- a/src/script/lua_api/l_client.cpp +++ b/src/script/lua_api/l_client.cpp @@ -38,12 +38,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "nodedef.h" #include "client/keycode.h" -#define checkCSMRestrictionFlag(flag) \ - (getClient(L)->checkCSMRestrictionFlag(CSMRestrictionFlags::flag)) +#define checkCSMRestrictionFlag(flag) \ + ( getClient(L)->checkCSMRestrictionFlag(CSMRestrictionFlags::flag) ) // Not the same as FlagDesc, which contains an `u32 flag` -struct CSMFlagDesc -{ +struct CSMFlagDesc { const char *name; u64 flag; }; @@ -54,12 +53,14 @@ struct CSMFlagDesc in network/networkprotocol.h */ const static CSMFlagDesc flagdesc_csm_restriction[] = { - {"load_client_mods", CSM_RF_LOAD_CLIENT_MODS}, - {"chat_messages", CSM_RF_CHAT_MESSAGES}, - {"read_itemdefs", CSM_RF_READ_ITEMDEFS}, - {"read_nodedefs", CSM_RF_READ_NODEDEFS}, - {"lookup_nodes", CSM_RF_LOOKUP_NODES}, - {"read_playerinfo", CSM_RF_READ_PLAYERINFO}, {NULL, 0}}; + {"load_client_mods", CSM_RF_LOAD_CLIENT_MODS}, + {"chat_messages", CSM_RF_CHAT_MESSAGES}, + {"read_itemdefs", CSM_RF_READ_ITEMDEFS}, + {"read_nodedefs", CSM_RF_READ_NODEDEFS}, + {"lookup_nodes", CSM_RF_LOOKUP_NODES}, + {"read_playerinfo", CSM_RF_READ_PLAYERINFO}, + {NULL, 0} +}; // get_current_modname() int ModApiClient::l_get_current_modname(lua_State *L) @@ -421,7 +422,7 @@ int ModApiClient::l_send_damage(lua_State *L) { u16 damage = luaL_checknumber(L, 1); getClient(L)->sendDamage(damage); - return 0; + return 0; } // place_node(pos) @@ -432,8 +433,7 @@ int ModApiClient::l_place_node(lua_State *L) LocalPlayer *player = client->getEnv().getLocalPlayer(); ItemStack selected_item, hand_item; player->getWieldedItem(&selected_item, &hand_item); - const ItemDefinition &selected_def = - selected_item.getDefinition(getGameDef(L)->idef()); + const ItemDefinition &selected_def = selected_item.getDefinition(getGameDef(L)->idef()); v3s16 pos = read_v3s16(L, 1); PointedThing pointed; pointed.type = POINTEDTHING_NODE; @@ -465,7 +465,7 @@ int ModApiClient::l_get_inventory(lua_State *L) InventoryLocation inventory_location; Inventory *inventory; std::string location; - + location = readParam(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(L, 2) * BS; - + std::vector objs; env.getActiveObjects(pos, radius, objs); - + int i = 0; lua_createtable(L, objs.size(), 0); for (const auto obj : objs) { - ClientObjectRef::create(L, obj.obj); // TODO: getObjectRefOrCreate + ClientObjectRef::create(L, obj.obj); // TODO: getObjectRefOrCreate lua_rawseti(L, -2, ++i); } return 1; diff --git a/src/script/lua_api/l_clientobject.cpp b/src/script/lua_api/l_clientobject.cpp index 05b3e2850..d88b538a1 100644 --- a/src/script/lua_api/l_clientobject.cpp +++ b/src/script/lua_api/l_clientobject.cpp @@ -146,7 +146,7 @@ int ClientObjectRef::l_punch(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); - PointedThing pointed(gcao->getId(), v3f(0, 0, 0), v3s16(0, 0, 0), 0); + PointedThing pointed(gcao->getId(), v3f(0,0,0), v3s16(0,0,0), 0); getClient(L)->interact(INTERACT_START_DIGGING, pointed); return 0; } @@ -155,7 +155,7 @@ int ClientObjectRef::l_rightclick(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); - PointedThing pointed(gcao->getId(), v3f(0, 0, 0), v3s16(0, 0, 0), 0); + PointedThing pointed(gcao->getId(), v3f(0,0,0), v3s16(0,0,0), 0); getClient(L)->interact(INTERACT_PLACE, pointed); return 0; } @@ -223,5 +223,6 @@ luaL_Reg ClientObjectRef::methods[] = {luamethod(ClientObjectRef, get_pos), luamethod(ClientObjectRef, get_attach), luamethod(ClientObjectRef, get_nametag), luamethod(ClientObjectRef, get_item_textures), - luamethod(ClientObjectRef, get_max_hp), luamethod(ClientObjectRef, punch), + luamethod(ClientObjectRef, get_max_hp), + luamethod(ClientObjectRef, punch), luamethod(ClientObjectRef, rightclick), {0, 0}}; diff --git a/src/script/lua_api/l_clientobject.h b/src/script/lua_api/l_clientobject.h index a4516e047..521591444 100644 --- a/src/script/lua_api/l_clientobject.h +++ b/src/script/lua_api/l_clientobject.h @@ -60,7 +60,7 @@ private: // is_player(self) static int l_is_player(lua_State *L); - + // is_local_player(self) static int l_is_local_player(lua_State *L); diff --git a/src/script/lua_api/l_craft.cpp b/src/script/lua_api/l_craft.cpp index 07b45eaff..18622ee00 100644 --- a/src/script/lua_api/l_craft.cpp +++ b/src/script/lua_api/l_craft.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "lua_api/l_craft.h" #include "lua_api/l_internal.h" #include "lua_api/l_item.h" @@ -25,45 +26,46 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "server.h" #include "craftdef.h" -struct EnumString ModApiCraft::es_CraftMethod[] = { - {CRAFT_METHOD_NORMAL, "normal"}, - {CRAFT_METHOD_COOKING, "cooking"}, - {CRAFT_METHOD_FUEL, "fuel"}, - {0, NULL}, +struct EnumString ModApiCraft::es_CraftMethod[] = +{ + {CRAFT_METHOD_NORMAL, "normal"}, + {CRAFT_METHOD_COOKING, "cooking"}, + {CRAFT_METHOD_FUEL, "fuel"}, + {0, NULL}, }; // helper for register_craft -bool ModApiCraft::readCraftRecipeShaped( - lua_State *L, int index, int &width, std::vector &recipe) +bool ModApiCraft::readCraftRecipeShaped(lua_State *L, int index, + int &width, std::vector &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(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); colcount++; } - if (rowcount == 0) { + if(rowcount == 0){ width = colcount; } else { - if (colcount != width) + if(colcount != width) return false; } // removes value, keeps key for next iteration @@ -74,19 +76,19 @@ bool ModApiCraft::readCraftRecipeShaped( } // helper for register_craft -bool ModApiCraft::readCraftRecipeShapeless( - lua_State *L, int index, std::vector &recipe) +bool ModApiCraft::readCraftRecipeShapeless(lua_State *L, int index, + std::vector &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(L, -1)); // removes value, keeps key for next iteration @@ -96,27 +98,27 @@ bool ModApiCraft::readCraftRecipeShapeless( } // helper for register_craft -bool ModApiCraft::readCraftReplacements( - lua_State *L, int index, CraftReplacements &replacements) +bool ModApiCraft::readCraftReplacements(lua_State *L, int index, + CraftReplacements &replacements) { - if (index < 0) + if(index < 0) index = lua_gettop(L) + 1 + index; - if (!lua_istable(L, index)) + if(!lua_istable(L, index)) return false; lua_pushnil(L); - while (lua_next(L, index) != 0) { + while(lua_next(L, index) != 0){ // key at index -2 and value at index -1 - if (!lua_istable(L, -1)) + if(!lua_istable(L, -1)) return false; lua_rawgeti(L, -1, 1); - if (!lua_isstring(L, -1)) + if(!lua_isstring(L, -1)) return false; std::string replace_from = readParam(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(L, -1); lua_pop(L, 1); @@ -130,19 +132,20 @@ bool ModApiCraft::readCraftReplacements( int ModApiCraft::l_register_craft(lua_State *L) { NO_MAP_LOCK_REQUIRED; - // infostream<<"register_craft"<getWritableCraftDefManager(); + IWritableCraftDefManager *craftdef = + getServer(L)->getWritableCraftDefManager(); std::string type = getstringfield_default(L, table, "type", "shaped"); /* CraftDefinitionShaped */ - if (type == "shaped") { + if(type == "shaped"){ std::string output = getstringfield_default(L, table, "output", ""); if (output.empty()) throw LuaError("Crafting definition is missing an output"); @@ -150,22 +153,20 @@ int ModApiCraft::l_register_craft(lua_State *L) int width = 0; std::vector recipe; lua_getfield(L, table, "recipe"); - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) throw LuaError("Crafting definition is missing a recipe" - " (output=\"" + - output + "\")"); - if (!readCraftRecipeShaped(L, -1, width, recipe)) + " (output=\"" + output + "\")"); + if(!readCraftRecipeShaped(L, -1, width, recipe)) throw LuaError("Invalid crafting recipe" - " (output=\"" + - output + "\")"); + " (output=\"" + output + "\")"); CraftReplacements replacements; lua_getfield(L, table, "replacements"); - if (!lua_isnil(L, -1)) { - if (!readCraftReplacements(L, -1, replacements)) + if(!lua_isnil(L, -1)) + { + if(!readCraftReplacements(L, -1, replacements)) throw LuaError("Invalid replacements" - " (output=\"" + - output + "\")"); + " (output=\"" + output + "\")"); } CraftDefinition *def = new CraftDefinitionShaped( @@ -175,31 +176,29 @@ int ModApiCraft::l_register_craft(lua_State *L) /* CraftDefinitionShapeless */ - else if (type == "shapeless") { + else if(type == "shapeless"){ std::string output = getstringfield_default(L, table, "output", ""); if (output.empty()) throw LuaError("Crafting definition (shapeless)" - " is missing an output"); + " is missing an output"); std::vector recipe; lua_getfield(L, table, "recipe"); - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) throw LuaError("Crafting definition (shapeless)" - " is missing a recipe" - " (output=\"" + - output + "\")"); - if (!readCraftRecipeShapeless(L, -1, recipe)) + " is missing a recipe" + " (output=\"" + output + "\")"); + if(!readCraftRecipeShapeless(L, -1, recipe)) throw LuaError("Invalid crafting recipe" - " (output=\"" + - output + "\")"); + " (output=\"" + output + "\")"); CraftReplacements replacements; lua_getfield(L, table, "replacements"); - if (!lua_isnil(L, -1)) { - if (!readCraftReplacements(L, -1, replacements)) + if(!lua_isnil(L, -1)) + { + if(!readCraftReplacements(L, -1, replacements)) throw LuaError("Invalid replacements" - " (output=\"" + - output + "\")"); + " (output=\"" + output + "\")"); } CraftDefinition *def = new CraftDefinitionShapeless( @@ -209,38 +208,38 @@ int ModApiCraft::l_register_craft(lua_State *L) /* CraftDefinitionToolRepair */ - else if (type == "toolrepair") { - float additional_wear = - getfloatfield_default(L, table, "additional_wear", 0.0); + else if(type == "toolrepair"){ + float additional_wear = getfloatfield_default(L, table, + "additional_wear", 0.0); - CraftDefinition *def = new CraftDefinitionToolRepair(additional_wear); + CraftDefinition *def = new CraftDefinitionToolRepair( + additional_wear); craftdef->registerCraft(def, getServer(L)); } /* CraftDefinitionCooking */ - else if (type == "cooking") { + else if(type == "cooking"){ std::string output = getstringfield_default(L, table, "output", ""); if (output.empty()) throw LuaError("Crafting definition (cooking)" - " is missing an output"); + " is missing an output"); std::string recipe = getstringfield_default(L, table, "recipe", ""); if (recipe.empty()) throw LuaError("Crafting definition (cooking)" - " is missing a recipe" - " (output=\"" + - output + "\")"); + " is missing a recipe" + " (output=\"" + output + "\")"); float cooktime = getfloatfield_default(L, table, "cooktime", 3.0); CraftReplacements replacements; lua_getfield(L, table, "replacements"); - if (!lua_isnil(L, -1)) { - if (!readCraftReplacements(L, -1, replacements)) + if(!lua_isnil(L, -1)) + { + if(!readCraftReplacements(L, -1, replacements)) throw LuaError("Invalid replacements" - " (cooking output=\"" + - output + "\")"); + " (cooking output=\"" + output + "\")"); } CraftDefinition *def = new CraftDefinitionCooking( @@ -250,27 +249,29 @@ int ModApiCraft::l_register_craft(lua_State *L) /* CraftDefinitionFuel */ - else if (type == "fuel") { + else if(type == "fuel"){ std::string recipe = getstringfield_default(L, table, "recipe", ""); if (recipe.empty()) throw LuaError("Crafting definition (fuel)" - " is missing a recipe"); + " is missing a recipe"); float burntime = getfloatfield_default(L, table, "burntime", 1.0); CraftReplacements replacements; lua_getfield(L, table, "replacements"); - if (!lua_isnil(L, -1)) { - if (!readCraftReplacements(L, -1, replacements)) + if(!lua_isnil(L, -1)) + { + if(!readCraftReplacements(L, -1, replacements)) throw LuaError("Invalid replacements" - " (fuel recipe=\"" + - recipe + "\")"); + " (fuel recipe=\"" + recipe + "\")"); } - CraftDefinition *def = - new CraftDefinitionFuel(recipe, burntime, replacements); + CraftDefinition *def = new CraftDefinitionFuel( + recipe, burntime, replacements); craftdef->registerCraft(def, getServer(L)); - } else { + } + else + { throw LuaError("Unknown crafting definition type: \"" + type + "\""); } @@ -286,7 +287,8 @@ int ModApiCraft::l_clear_craft(lua_State *L) int table = 1; // Get the writable craft definition manager from the server - IWritableCraftDefManager *craftdef = getServer(L)->getWritableCraftDefManager(); + IWritableCraftDefManager *craftdef = + getServer(L)->getWritableCraftDefManager(); std::string output = getstringfield_default(L, table, "output", ""); std::string type = getstringfield_default(L, table, "type", "shaped"); @@ -332,7 +334,7 @@ int ModApiCraft::l_clear_craft(lua_State *L) std::string rec = getstringfield_default(L, table, "recipe", ""); if (rec.empty()) throw LuaError("Crafting definition (cooking)" - " is missing a recipe"); + " is missing a recipe"); recipe.push_back(rec); } /* @@ -343,7 +345,7 @@ int ModApiCraft::l_clear_craft(lua_State *L) std::string rec = getstringfield_default(L, table, "recipe", ""); if (rec.empty()) throw LuaError("Crafting definition (fuel)" - " is missing a recipe"); + " is missing a recipe"); recipe.push_back(rec); } else { throw LuaError("Unknown crafting definition type: \"" + type + "\""); @@ -372,15 +374,15 @@ int ModApiCraft::l_get_craft_result(lua_State *L) int input_i = 1; std::string method_s = getstringfield_default(L, input_i, "method", "normal"); - enum CraftMethod method = (CraftMethod)getenumfield( - L, input_i, "method", es_CraftMethod, CRAFT_METHOD_NORMAL); + enum CraftMethod method = (CraftMethod)getenumfield(L, input_i, "method", + es_CraftMethod, CRAFT_METHOD_NORMAL); int width = 1; lua_getfield(L, input_i, "width"); - if (lua_isnumber(L, -1)) + if(lua_isnumber(L, -1)) width = luaL_checkinteger(L, -1); lua_pop(L, 1); lua_getfield(L, input_i, "items"); - std::vector items = read_items(L, -1, getServer(L)); + std::vector items = read_items(L, -1,getServer(L)); lua_pop(L, 1); // items IGameDef *gdef = getServer(L); @@ -415,7 +417,9 @@ int ModApiCraft::l_get_craft_result(lua_State *L) return 2; } -static void push_craft_recipe(lua_State *L, IGameDef *gdef, const CraftDefinition *recipe, + +static void push_craft_recipe(lua_State *L, IGameDef *gdef, + const CraftDefinition *recipe, const CraftOutput &tmpout) { CraftInput input = recipe->getInput(tmpout, gdef); @@ -458,7 +462,8 @@ static void push_craft_recipe(lua_State *L, IGameDef *gdef, const CraftDefinitio } static void push_craft_recipes(lua_State *L, IGameDef *gdef, - const std::vector &recipes, const CraftOutput &output) + const std::vector &recipes, + const CraftOutput &output) { lua_createtable(L, recipes.size(), 0); @@ -467,7 +472,7 @@ static void push_craft_recipes(lua_State *L, IGameDef *gdef, return; } - std::vector::const_iterator it = recipes.begin(); + std::vector::const_iterator it = recipes.begin(); for (unsigned i = 0; it != recipes.end(); ++it) { lua_newtable(L); push_craft_recipe(L, gdef, *it, output); @@ -475,6 +480,7 @@ static void push_craft_recipes(lua_State *L, IGameDef *gdef, } } + // get_craft_recipe(result item) int ModApiCraft::l_get_craft_recipe(lua_State *L) { @@ -483,8 +489,8 @@ int ModApiCraft::l_get_craft_recipe(lua_State *L) std::string item = luaL_checkstring(L, 1); Server *server = getServer(L); CraftOutput output(item, 0); - std::vector recipes = - server->cdef()->getCraftRecipes(output, server, 1); + std::vector recipes = server->cdef() + ->getCraftRecipes(output, server, 1); lua_createtable(L, 1, 0); @@ -506,8 +512,8 @@ int ModApiCraft::l_get_all_craft_recipes(lua_State *L) std::string item = luaL_checkstring(L, 1); Server *server = getServer(L); CraftOutput output(item, 0); - std::vector recipes = - server->cdef()->getCraftRecipes(output, server); + std::vector recipes = server->cdef() + ->getCraftRecipes(output, server); push_craft_recipes(L, server, recipes, output); return 1; diff --git a/src/script/lua_api/l_craft.h b/src/script/lua_api/l_craft.h index 5ba3d18fe..9002b23ef 100644 --- a/src/script/lua_api/l_craft.h +++ b/src/script/lua_api/l_craft.h @@ -26,8 +26,7 @@ with this program; if not, write to the Free Software Foundation, Inc., struct CraftReplacements; -class ModApiCraft : public ModApiBase -{ +class ModApiCraft : public ModApiBase { private: static int l_register_craft(lua_State *L); static int l_get_craft_recipe(lua_State *L); @@ -35,12 +34,12 @@ private: static int l_get_craft_result(lua_State *L); static int l_clear_craft(lua_State *L); - static bool readCraftReplacements( - lua_State *L, int index, CraftReplacements &replacements); - static bool readCraftRecipeShapeless( - lua_State *L, int index, std::vector &recipe); - static bool readCraftRecipeShaped(lua_State *L, int index, int &width, + static bool readCraftReplacements(lua_State *L, int index, + CraftReplacements &replacements); + static bool readCraftRecipeShapeless(lua_State *L, int index, std::vector &recipe); + static bool readCraftRecipeShaped(lua_State *L, int index, + int &width, std::vector &recipe); static struct EnumString es_CraftMethod[]; diff --git a/src/script/lua_api/l_env.cpp b/src/script/lua_api/l_env.cpp index 2c612eb9a..ee384ad10 100644 --- a/src/script/lua_api/l_env.cpp +++ b/src/script/lua_api/l_env.cpp @@ -46,16 +46,18 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/client.h" #endif -struct EnumString ModApiEnvMod::es_ClearObjectsMode[] = { - {CLEAR_OBJECTS_MODE_FULL, "full"}, - {CLEAR_OBJECTS_MODE_QUICK, "quick"}, - {0, NULL}, +struct EnumString ModApiEnvMod::es_ClearObjectsMode[] = +{ + {CLEAR_OBJECTS_MODE_FULL, "full"}, + {CLEAR_OBJECTS_MODE_QUICK, "quick"}, + {0, NULL}, }; /////////////////////////////////////////////////////////////////////////////// -void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n, u32 active_object_count, - u32 active_object_count_wider) + +void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n, + u32 active_object_count, u32 active_object_count_wider) { ServerScripting *scriptIface = env->getScriptIface(); scriptIface->realityCheck(); @@ -75,7 +77,7 @@ void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n, u32 active_obje // Get registered_abms[m_id] lua_pushinteger(L, m_id); lua_gettable(L, -2); - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) FATAL_ERROR(""); lua_remove(L, -2); // Remove registered_abms @@ -118,8 +120,7 @@ void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n) // Get registered_lbms[m_id] lua_pushinteger(L, m_id); lua_gettable(L, -2); - FATAL_ERROR_IF(lua_isnil(L, -1), - "Entry with given id not found in registered_lbms table"); + FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table"); lua_remove(L, -2); // Remove registered_lbms scriptIface->setOriginFromTable(-1); @@ -175,9 +176,10 @@ int LuaRaycast::create_object(lua_State *L) liquids = readParam(L, 4); } - LuaRaycast *o = new LuaRaycast(core::line3d(pos1, pos2), objects, liquids); + LuaRaycast *o = new LuaRaycast(core::line3d(pos1, pos2), + objects, liquids); - *(void **)(lua_newuserdata(L, sizeof(void *))) = o; + *(void **) (lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; @@ -191,12 +193,12 @@ LuaRaycast *LuaRaycast::checkobject(lua_State *L, int narg) void *ud = luaL_checkudata(L, narg, className); if (!ud) luaL_typerror(L, narg, className); - return *(LuaRaycast **)ud; + return *(LuaRaycast **) ud; } int LuaRaycast::gc_object(lua_State *L) { - LuaRaycast *o = *(LuaRaycast **)(lua_touserdata(L, 1)); + LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1)); delete o; return 0; } @@ -233,7 +235,11 @@ void LuaRaycast::Register(lua_State *L) } const char LuaRaycast::className[] = "Raycast"; -const luaL_Reg LuaRaycast::methods[] = {luamethod(LuaRaycast, next), {0, 0}}; +const luaL_Reg LuaRaycast::methods[] = +{ + luamethod(LuaRaycast, next), + { 0, 0 } +}; void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param) { @@ -385,7 +391,7 @@ int ModApiEnvMod::l_get_node_light(lua_State *L) // Do it v3s16 pos = read_v3s16(L, 1); u32 time_of_day = env->getTimeOfDay(); - if (lua_isnumber(L, 2)) + if(lua_isnumber(L, 2)) time_of_day = 24000.0 * lua_tonumber(L, 2); time_of_day %= 24000; u32 dnr = time_to_daynight_ratio(time_of_day, true); @@ -417,7 +423,7 @@ int ModApiEnvMod::l_place_node(lua_State *L) // Don't attempt to load non-loaded area as of now MapNode n_old = env->getMap().getNode(pos); - if (n_old.getContent() == CONTENT_IGNORE) { + if(n_old.getContent() == CONTENT_IGNORE){ lua_pushboolean(L, false); return 1; } @@ -427,7 +433,7 @@ int ModApiEnvMod::l_place_node(lua_State *L) PointedThing pointed; pointed.type = POINTEDTHING_NODE; pointed.node_abovesurface = pos; - pointed.node_undersurface = pos + v3s16(0, -1, 0); + pointed.node_undersurface = pos + v3s16(0,-1,0); // Place it with a NULL placer (appears in Lua as nil) bool success = scriptIfaceItem->item_OnPlace(item, nullptr, pointed); lua_pushboolean(L, success); @@ -446,7 +452,7 @@ int ModApiEnvMod::l_dig_node(lua_State *L) // Don't attempt to load non-loaded area as of now MapNode n = env->getMap().getNode(pos); - if (n.getContent() == CONTENT_IGNORE) { + if(n.getContent() == CONTENT_IGNORE){ lua_pushboolean(L, false); return 1; } @@ -469,7 +475,7 @@ int ModApiEnvMod::l_punch_node(lua_State *L) // Don't attempt to load non-loaded area as of now MapNode n = env->getMap().getNode(pos); - if (n.getContent() == CONTENT_IGNORE) { + if(n.getContent() == CONTENT_IGNORE){ lua_pushboolean(L, false); return 1; } @@ -513,7 +519,7 @@ int ModApiEnvMod::l_set_node_level(lua_State *L) v3s16 pos = read_v3s16(L, 1); u8 level = 1; - if (lua_isnumber(L, 2)) + if(lua_isnumber(L, 2)) level = lua_tonumber(L, 2); MapNode n = env->getMap().getNode(pos); lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level)); @@ -530,7 +536,7 @@ int ModApiEnvMod::l_add_node_level(lua_State *L) v3s16 pos = read_v3s16(L, 1); s16 level = 1; - if (lua_isnumber(L, 2)) + if(lua_isnumber(L, 2)) level = lua_tonumber(L, 2); MapNode n = env->getMap().getNode(pos); lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level)); @@ -544,7 +550,7 @@ int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L) GET_PLAIN_ENV_PTR; std::vector positions = env->getMap().findNodesWithMetadata( - check_v3s16(L, 1), check_v3s16(L, 2)); + check_v3s16(L, 1), check_v3s16(L, 2)); lua_createtable(L, positions.size(), 0); for (size_t i = 0; i != positions.size(); i++) { @@ -590,7 +596,7 @@ int ModApiEnvMod::l_add_entity(lua_State *L) ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata); int objectid = env->addActiveObject(obj); // If failed to add, return nothing (reads as nil) - if (objectid == 0) + if(objectid == 0) return 0; // If already deleted (can happen in on_activate), return nil @@ -607,10 +613,10 @@ int ModApiEnvMod::l_add_item(lua_State *L) GET_ENV_PTR; // pos - // v3f pos = checkFloatPos(L, 1); + //v3f pos = checkFloatPos(L, 1); // item - ItemStack item = read_item(L, 2, getServer(L)->idef()); - if (item.empty() || !item.isKnown(getServer(L)->idef())) + ItemStack item = read_item(L, 2,getServer(L)->idef()); + if(item.empty() || !item.isKnown(getServer(L)->idef())) return 0; int error_handler = PUSH_ERROR_HANDLER(L); @@ -619,7 +625,7 @@ int ModApiEnvMod::l_add_item(lua_State *L) lua_getglobal(L, "core"); lua_getfield(L, -1, "spawn_item"); lua_remove(L, -2); // Remove core - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) return 0; lua_pushvalue(L, 1); lua_pushstring(L, item.getItemString().c_str()); @@ -633,10 +639,10 @@ int ModApiEnvMod::l_add_item(lua_State *L) // get_connected_players() int ModApiEnvMod::l_get_connected_players(lua_State *L) { - ServerEnvironment *env = (ServerEnvironment *)getEnv(L); + ServerEnvironment *env = (ServerEnvironment *) getEnv(L); if (!env) { log_deprecated(L, "Calling get_connected_players() at mod load time" - " is deprecated"); + " is deprecated"); lua_createtable(L, 0, 0); return 1; } @@ -684,7 +690,7 @@ int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L) float radius = readParam(L, 2) * BS; std::vector objs; - auto include_obj_cb = [](ServerActiveObject *obj) { return !obj->isGone(); }; + auto include_obj_cb = [](ServerActiveObject *obj){ return !obj->isGone(); }; env->getObjectsInsideRadius(objs, pos, radius, include_obj_cb); int i = 0; @@ -710,7 +716,7 @@ int ModApiEnvMod::l_set_timeofday(lua_State *L) // This should be set directly in the environment but currently // such changes aren't immediately sent to the clients, so call // the server instead. - // env->setTimeOfDay(timeofday_mh); + //env->setTimeOfDay(timeofday_mh); getServer(L)->setTimeOfDay(timeofday_mh); return 0; } @@ -747,7 +753,7 @@ int ModApiEnvMod::l_get_gametime(lua_State *L) } void ModApiEnvMod::collectNodeIds(lua_State *L, int idx, const NodeDefManager *ndef, - std::vector &filter) + std::vector &filter) { if (lua_istable(L, idx)) { lua_pushnil(L); @@ -819,13 +825,13 @@ int ModApiEnvMod::l_find_nodes_near(lua_State *L) if (Client *client = getClient(L)) radius = client->CSMClampRadius(pos, radius); #endif - + std::vector individual_count; individual_count.resize(filter.size()); - + lua_newtable(L); u32 i = 0; - + for (int d = start_radius; d <= radius; d++) { const std::vector &list = FacePositionCache::getFacePositions(d); for (const v3s16 &posi : list) { @@ -869,13 +875,13 @@ int ModApiEnvMod::l_find_nodes_near_under_air(lua_State *L) if (Client *client = getClient(L)) radius = client->CSMClampRadius(pos, radius); #endif - + std::vector individual_count; individual_count.resize(filter.size()); - + lua_newtable(L); u32 i = 0; - + for (int d = start_radius; d <= radius; d++) { const std::vector &list = FacePositionCache::getFacePositions(d); for (const v3s16 &posi : list) { @@ -923,13 +929,13 @@ int ModApiEnvMod::l_find_nodes_near_under_air_except(lua_State *L) if (Client *client = getClient(L)) radius = client->CSMClampRadius(pos, radius); #endif - + std::vector individual_count; individual_count.resize(filter.size()); - + lua_newtable(L); u32 i = 0; - + for (int d = start_radius; d <= radius; d++) { const std::vector &list = FacePositionCache::getFacePositions(d); for (const v3s16 &posi : list) { @@ -980,7 +986,7 @@ int ModApiEnvMod::l_find_nodes_in_area(lua_State *L) // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) { luaL_error(L, "find_nodes_in_area(): area volume" - " exceeds allowed value of 4096000"); + " exceeds allowed value of 4096000"); return 0; } @@ -1002,21 +1008,18 @@ int ModApiEnvMod::l_find_nodes_in_area(lua_State *L) v3s16 p; for (p.X = minp.X; p.X <= maxp.X; p.X++) - for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++) - for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { - content_t c = map.getNode(p).getContent(); - - auto it = std::find( - filter.begin(), filter.end(), c); - if (it != filter.end()) { - // Calculate index of the table and append - // the position - u32 filt_index = it - filter.begin(); - push_v3s16(L, p); - lua_rawseti(L, base + 1 + filt_index, - ++idx[filt_index]); - } - } + for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++) + for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { + content_t c = map.getNode(p).getContent(); + + auto it = std::find(filter.begin(), filter.end(), c); + if (it != filter.end()) { + // Calculate index of the table and append the position + u32 filt_index = it - filter.begin(); + push_v3s16(L, p); + lua_rawseti(L, base + 1 + filt_index, ++idx[filt_index]); + } + } // last filter table is at top of stack u32 i = filter.size() - 1; @@ -1040,21 +1043,19 @@ int ModApiEnvMod::l_find_nodes_in_area(lua_State *L) u32 i = 0; v3s16 p; for (p.X = minp.X; p.X <= maxp.X; p.X++) - for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++) - for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { - content_t c = env->getMap().getNode(p) - .getContent(); - - auto it = std::find( - filter.begin(), filter.end(), c); - if (it != filter.end()) { - push_v3s16(L, p); - lua_rawseti(L, -2, ++i); - - u32 filt_index = it - filter.begin(); - individual_count[filt_index]++; - } - } + for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++) + for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { + content_t c = env->getMap().getNode(p).getContent(); + + auto it = std::find(filter.begin(), filter.end(), c); + if (it != filter.end()) { + push_v3s16(L, p); + lua_rawseti(L, -2, ++i); + + u32 filt_index = it - filter.begin(); + individual_count[filt_index]++; + } + } lua_createtable(L, 0, filter.size()); for (u32 i = 0; i < filter.size(); i++) { @@ -1096,7 +1097,7 @@ int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L) // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) { luaL_error(L, "find_nodes_in_area_under_air(): area volume" - " exceeds allowed value of 4096000"); + " exceeds allowed value of 4096000"); return 0; } @@ -1107,20 +1108,20 @@ int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L) u32 i = 0; v3s16 p; for (p.X = minp.X; p.X <= maxp.X; p.X++) - for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { - p.Y = minp.Y; - content_t c = map.getNode(p).getContent(); - for (; p.Y <= maxp.Y; p.Y++) { - v3s16 psurf(p.X, p.Y + 1, p.Z); - content_t csurf = map.getNode(psurf).getContent(); - if (c != CONTENT_AIR && csurf == CONTENT_AIR && - CONTAINS(filter, c)) { - push_v3s16(L, p); - lua_rawseti(L, -2, ++i); - } - c = csurf; + for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) { + p.Y = minp.Y; + content_t c = map.getNode(p).getContent(); + for (; p.Y <= maxp.Y; p.Y++) { + v3s16 psurf(p.X, p.Y + 1, p.Z); + content_t csurf = map.getNode(psurf).getContent(); + if (c != CONTENT_AIR && csurf == CONTENT_AIR && + CONTAINS(filter, c)) { + push_v3s16(L, p); + lua_rawseti(L, -2, ++i); } + c = csurf; } + } return 1; } @@ -1135,10 +1136,10 @@ int ModApiEnvMod::l_get_perlin(lua_State *L) if (lua_istable(L, 1)) { read_noiseparams(L, 1, ¶ms); } else { - params.seed = luaL_checkint(L, 1); + params.seed = luaL_checkint(L, 1); params.octaves = luaL_checkint(L, 2); params.persist = readParam(L, 3); - params.spread = v3f(1, 1, 1) * readParam(L, 4); + params.spread = v3f(1, 1, 1) * readParam(L, 4); } params.seed += (int)env->getServerMap().getSeed(); @@ -1176,10 +1177,9 @@ int ModApiEnvMod::l_get_voxel_manip(lua_State *L) GET_ENV_PTR; Map *map = &(env->getMap()); - LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) - ? new LuaVoxelManip(map, read_v3s16(L, 1), - read_v3s16(L, 2)) - : new LuaVoxelManip(map); + LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ? + new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) : + new LuaVoxelManip(map); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, "VoxelManip"); @@ -1196,8 +1196,8 @@ int ModApiEnvMod::l_clear_objects(lua_State *L) ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK; if (lua_istable(L, 1)) { - mode = (ClearObjectsMode)getenumfield( - L, 1, "mode", ModApiEnvMod::es_ClearObjectsMode, mode); + mode = (ClearObjectsMode)getenumfield(L, 1, "mode", + ModApiEnvMod::es_ClearObjectsMode, mode); } env->clearObjects(mode); @@ -1237,12 +1237,10 @@ int ModApiEnvMod::l_fix_light(lua_State *L) bool success = true; v3s16 blockpos; for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++) - for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++) - for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; - blockpos.Z++) { - success = success & map.repairBlockLight(blockpos, - &modified_blocks); - } + for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++) + for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) { + success = success & map.repairBlockLight(blockpos, &modified_blocks); + } if (!modified_blocks.empty()) { MapEditEvent event; event.type = MEET_OTHER; @@ -1276,10 +1274,10 @@ int ModApiEnvMod::l_load_area(lua_State *L) v3s16 bp2 = getNodeBlockPos(check_v3s16(L, 2)); sortBoxVerticies(bp1, bp2); for (s16 z = bp1.Z; z <= bp2.Z; z++) - for (s16 y = bp1.Y; y <= bp2.Y; y++) - for (s16 x = bp1.X; x <= bp2.X; x++) { - map->emergeBlock(v3s16(x, y, z)); - } + for (s16 y = bp1.Y; y <= bp2.Y; y++) + for (s16 x = bp1.X; x <= bp2.X; x++) { + map->emergeBlock(v3s16(x, y, z)); + } } return 0; @@ -1313,22 +1311,19 @@ int ModApiEnvMod::l_emerge_area(lua_State *L) int args_ref = luaL_ref(L, LUA_REGISTRYINDEX); state = new ScriptCallbackState; - state->script = getServer(L)->getScriptIface(); + state->script = getServer(L)->getScriptIface(); state->callback_ref = callback_ref; - state->args_ref = args_ref; - state->refcount = num_blocks; - state->origin = getScriptApiBase(L)->getOrigin(); + state->args_ref = args_ref; + state->refcount = num_blocks; + state->origin = getScriptApiBase(L)->getOrigin(); } for (s16 z = bpmin.Z; z <= bpmax.Z; z++) - for (s16 y = bpmin.Y; y <= bpmax.Y; y++) - for (s16 x = bpmin.X; x <= bpmax.X; x++) { - emerge->enqueueBlockEmergeEx(v3s16(x, y, z), - PEER_ID_INEXISTENT, - BLOCK_EMERGE_ALLOW_GEN | - BLOCK_EMERGE_FORCE_QUEUE, - callback, state); - } + for (s16 y = bpmin.Y; y <= bpmax.Y; y++) + for (s16 x = bpmin.X; x <= bpmax.X; x++) { + emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT, + BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state); + } return 0; } @@ -1350,16 +1345,16 @@ int ModApiEnvMod::l_delete_area(lua_State *L) bool success = true; for (s16 z = bpmin.Z; z <= bpmax.Z; z++) - for (s16 y = bpmin.Y; y <= bpmax.Y; y++) - for (s16 x = bpmin.X; x <= bpmax.X; x++) { - v3s16 bp(x, y, z); - if (map.deleteBlock(bp)) { - env->setStaticForActiveObjectsInBlock(bp, false); - event.modified_blocks.insert(bp); - } else { - success = false; - } - } + for (s16 y = bpmin.Y; y <= bpmax.Y; y++) + for (s16 x = bpmin.X; x <= bpmax.X; x++) { + v3s16 bp(x, y, z); + if (map.deleteBlock(bp)) { + env->setStaticForActiveObjectsInBlock(bp, false); + event.modified_blocks.insert(bp); + } else { + success = false; + } + } map.dispatchEvent(event); lua_pushboolean(L, success); @@ -1372,14 +1367,14 @@ int ModApiEnvMod::l_find_path(lua_State *L) { Environment *env = getEnv(L); - v3s16 pos1 = read_v3s16(L, 1); - v3s16 pos2 = read_v3s16(L, 2); + v3s16 pos1 = read_v3s16(L, 1); + v3s16 pos2 = read_v3s16(L, 2); unsigned int searchdistance = luaL_checkint(L, 3); - unsigned int max_jump = luaL_checkint(L, 4); - unsigned int max_drop = luaL_checkint(L, 5); - PathAlgorithm algo = PA_PLAIN_NP; + unsigned int max_jump = luaL_checkint(L, 4); + unsigned int max_drop = luaL_checkint(L, 5); + PathAlgorithm algo = PA_PLAIN_NP; if (!lua_isnoneornil(L, 6)) { - std::string algorithm = luaL_checkstring(L, 6); + std::string algorithm = luaL_checkstring(L,6); if (algorithm == "A*") algo = PA_PLAIN; @@ -1387,16 +1382,16 @@ int ModApiEnvMod::l_find_path(lua_State *L) if (algorithm == "Dijkstra") algo = PA_DIJKSTRA; } - - std::vector path = get_path(&env->getMap(), env->getGameDef()->ndef(), - pos1, pos2, searchdistance, max_jump, max_drop, algo); + + std::vector path = get_path(&env->getMap(), env->getGameDef()->ndef(), pos1, pos2, + searchdistance, max_jump, max_drop, algo); if (!path.empty()) { lua_createtable(L, path.size(), 0); int top = lua_gettop(L); unsigned int index = 1; for (const v3s16 &i : path) { - lua_pushnumber(L, index); + lua_pushnumber(L,index); push_v3s16(L, i); lua_settable(L, top); index++; @@ -1415,23 +1410,24 @@ int ModApiEnvMod::l_spawn_tree(lua_State *L) v3s16 p0 = read_v3s16(L, 1); treegen::TreeDef tree_def; - std::string trunk, leaves, fruit; + std::string trunk,leaves,fruit; const NodeDefManager *ndef = env->getGameDef()->ndef(); - if (lua_istable(L, 2)) { + if(lua_istable(L, 2)) + { getstringfield(L, 2, "axiom", tree_def.initial_axiom); getstringfield(L, 2, "rules_a", tree_def.rules_a); getstringfield(L, 2, "rules_b", tree_def.rules_b); getstringfield(L, 2, "rules_c", tree_def.rules_c); getstringfield(L, 2, "rules_d", tree_def.rules_d); getstringfield(L, 2, "trunk", trunk); - tree_def.trunknode = ndef->getId(trunk); + tree_def.trunknode=ndef->getId(trunk); getstringfield(L, 2, "leaves", leaves); - tree_def.leavesnode = ndef->getId(leaves); - tree_def.leaves2_chance = 0; + tree_def.leavesnode=ndef->getId(leaves); + tree_def.leaves2_chance=0; getstringfield(L, 2, "leaves2", leaves); if (!leaves.empty()) { - tree_def.leaves2node = ndef->getId(leaves); + tree_def.leaves2node=ndef->getId(leaves); getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance); } getintfield(L, 2, "angle", tree_def.angle); @@ -1440,22 +1436,22 @@ int ModApiEnvMod::l_spawn_tree(lua_State *L) tree_def.iterations_random_level = 0; getstringfield(L, 2, "trunk_type", tree_def.trunk_type); getboolfield(L, 2, "thin_branches", tree_def.thin_branches); - tree_def.fruit_chance = 0; + tree_def.fruit_chance=0; getstringfield(L, 2, "fruit", fruit); if (!fruit.empty()) { - tree_def.fruitnode = ndef->getId(fruit); - getintfield(L, 2, "fruit_chance", tree_def.fruit_chance); + tree_def.fruitnode=ndef->getId(fruit); + getintfield(L, 2, "fruit_chance",tree_def.fruit_chance); } tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed); - } else + } + else return 0; ServerMap *map = &env->getServerMap(); treegen::error e; - if ((e = treegen::spawn_ltree(map, p0, ndef, tree_def)) != treegen::SUCCESS) { + if ((e = treegen::spawn_ltree (map, p0, ndef, tree_def)) != treegen::SUCCESS) { if (e == treegen::UNBALANCED_BRACKETS) { - luaL_error(L, "spawn_tree(): closing ']' has no matching opening " - "bracket"); + luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket"); } else { luaL_error(L, "spawn_tree(): unknown error"); } @@ -1497,14 +1493,14 @@ int ModApiEnvMod::l_forceload_free_block(lua_State *L) } // get_translated_string(lang_code, string) -int ModApiEnvMod::l_get_translated_string(lua_State *L) +int ModApiEnvMod::l_get_translated_string(lua_State * L) { GET_ENV_PTR; std::string lang_code = luaL_checkstring(L, 1); std::string string = luaL_checkstring(L, 2); getServer(L)->loadTranslationLanguage(lang_code); - string = wide_to_utf8(translate_string( - utf8_to_wide(string), &(*g_server_translations)[lang_code])); + string = wide_to_utf8(translate_string(utf8_to_wide(string), + &(*g_server_translations)[lang_code])); lua_pushstring(L, string.c_str()); return 1; } diff --git a/src/script/lua_api/l_env.h b/src/script/lua_api/l_env.h index 43388475e..e1b89494b 100644 --- a/src/script/lua_api/l_env.h +++ b/src/script/lua_api/l_env.h @@ -23,8 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "serverenvironment.h" #include "raycast.h" -class ModApiEnvMod : public ModApiBase -{ +class ModApiEnvMod : public ModApiBase { private: // set_node(pos, node) // pos = {x=num, y=num, z=num} @@ -127,17 +126,17 @@ private: // find_node_near(pos, radius, nodenames, search_center) -> pos or nil // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" static int l_find_node_near(lua_State *L); - + // find_nodes_near(pos, radius, nodenames, search_center) -> list of positions // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" static int l_find_nodes_near(lua_State *L); - - // find_nodes_near_under_air(pos, radius, nodenames, search_center) -> list of - // positions nodenames: eg. {"ignore", "group:tree"} or "default:dirt" + + // find_nodes_near_under_air(pos, radius, nodenames, search_center) -> list of positions + // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" static int l_find_nodes_near_under_air(lua_State *L); - - // find_nodes_near_under_air(pos, radius, nodenames, search_center) -> list of - // positions nodenames: eg. {"ignore", "group:tree"} or "default:dirt" + + // find_nodes_near_under_air(pos, radius, nodenames, search_center) -> list of positions + // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" static int l_find_nodes_near_under_air_except(lua_State *L); // find_nodes_in_area(minp, maxp, nodenames) -> list of positions @@ -201,12 +200,12 @@ private: static int l_forceload_free_block(lua_State *L); // Get a string translated server side - static int l_get_translated_string(lua_State *L); + static int l_get_translated_string(lua_State * L); /* Helpers */ - static void collectNodeIds(lua_State *L, int idx, const NodeDefManager *ndef, - std::vector &filter); + static void collectNodeIds(lua_State *L, int idx, + const NodeDefManager *ndef, std::vector &filter); public: static void Initialize(lua_State *L, int top); @@ -215,8 +214,7 @@ public: static struct EnumString es_ClearObjectsMode[]; }; -class LuaABM : public ActiveBlockModifier -{ +class LuaABM : public ActiveBlockModifier { private: int m_id; @@ -225,18 +223,17 @@ private: float m_trigger_interval; u32 m_trigger_chance; bool m_simple_catch_up; - public: - LuaABM(lua_State *L, int id, const std::vector &trigger_contents, + LuaABM(lua_State *L, int id, + const std::vector &trigger_contents, const std::vector &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 &getTriggerContents() const @@ -247,9 +244,18 @@ public: { return m_required_neighbors; } - virtual float getTriggerInterval() { return m_trigger_interval; } - virtual u32 getTriggerChance() { return m_trigger_chance; } - virtual bool getSimpleCatchUp() { return m_simple_catch_up; } + virtual float getTriggerInterval() + { + return m_trigger_interval; + } + virtual u32 getTriggerChance() + { + return m_trigger_chance; + } + virtual bool getSimpleCatchUp() + { + return m_simple_catch_up; + } virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n, u32 active_object_count, u32 active_object_count_wider); }; @@ -258,11 +264,12 @@ class LuaLBM : public LoadingBlockModifierDef { private: int m_id; - public: - LuaLBM(lua_State *L, int id, const std::set &trigger_contents, - const std::string &name, bool run_at_every_load) : - m_id(id) + LuaLBM(lua_State *L, int id, + const std::set &trigger_contents, + const std::string &name, + bool run_at_every_load): + m_id(id) { this->run_at_every_load = run_at_every_load; this->trigger_contents = trigger_contents; @@ -290,14 +297,14 @@ private: * Returns the next pointed thing on the ray. */ static int l_next(lua_State *L); - public: //! Constructor with the same arguments as RaycastState. - LuaRaycast(const core::line3d &shootline, bool objects_pointable, - bool liquids_pointable) : - state(shootline, objects_pointable, liquids_pointable) - { - } + LuaRaycast( + const core::line3d &shootline, + bool objects_pointable, + bool liquids_pointable) : + state(shootline, objects_pointable, liquids_pointable) + {} //! Creates a LuaRaycast and leaves it on top of the stack. static int create_object(lua_State *L); @@ -312,8 +319,7 @@ public: static void Register(lua_State *L); }; -struct ScriptCallbackState -{ +struct ScriptCallbackState { ServerScripting *script; int callback_ref; int args_ref; diff --git a/src/script/lua_api/l_http.cpp b/src/script/lua_api/l_http.cpp index 21d000d25..84837e71b 100644 --- a/src/script/lua_api/l_http.cpp +++ b/src/script/lua_api/l_http.cpp @@ -30,9 +30,9 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include -#define HTTP_API(name) \ - lua_pushstring(L, #name); \ - lua_pushcfunction(L, l_http_##name); \ +#define HTTP_API(name) \ + lua_pushstring(L, #name); \ + lua_pushcfunction(L, l_http_##name); \ lua_settable(L, -3); #if USE_CURL @@ -54,8 +54,7 @@ void ModApiHttp::read_http_fetch_request(lua_State *L, HTTPFetchRequest &req) if (lua_istable(L, 2)) { lua_pushnil(L); while (lua_next(L, 2) != 0) { - req.post_fields[readParam(L, -2)] = - readParam(L, -1); + req.post_fields[readParam(L, -2)] = readParam(L, -1); lua_pop(L, 1); } } else if (lua_isstring(L, 2)) { @@ -74,8 +73,7 @@ void ModApiHttp::read_http_fetch_request(lua_State *L, HTTPFetchRequest &req) lua_pop(L, 1); } -void ModApiHttp::push_http_fetch_result( - lua_State *L, HTTPFetchResult &res, bool completed) +void ModApiHttp::push_http_fetch_result(lua_State *L, HTTPFetchResult &res, bool completed) { lua_newtable(L); setboolfield(L, -1, "succeeded", res.succeeded); @@ -173,19 +171,15 @@ int ModApiHttp::l_request_http_api(lua_State *L) std::string mod_name = readParam(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 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 mod_list_trusted = str_split(trusted_mods, ','); - mod_list_http.insert(mod_list_http.end(), mod_list_trusted.begin(), - mod_list_trusted.end()); - if (std::find(mod_list_http.begin(), mod_list_http.end(), mod_name) == - mod_list_http.end()) { + mod_list_http.insert(mod_list_http.end(), mod_list_trusted.begin(), mod_list_trusted.end()); + if (std::find(mod_list_http.begin(), mod_list_http.end(), mod_name) == mod_list_http.end()) { lua_pushnil(L); return 1; } diff --git a/src/script/lua_api/l_http.h b/src/script/lua_api/l_http.h index f2c72eafb..de6e51b37 100644 --- a/src/script/lua_api/l_http.h +++ b/src/script/lua_api/l_http.h @@ -25,14 +25,12 @@ with this program; if not, write to the Free Software Foundation, Inc., struct HTTPFetchRequest; struct HTTPFetchResult; -class ModApiHttp : public ModApiBase -{ +class ModApiHttp : public ModApiBase { private: #if USE_CURL // Helpers for HTTP fetch functions static void read_http_fetch_request(lua_State *L, HTTPFetchRequest &req); - static void push_http_fetch_result( - lua_State *L, HTTPFetchResult &res, bool completed = true); + static void push_http_fetch_result(lua_State *L, HTTPFetchResult &res, bool completed = true); // http_fetch_sync({url=, timeout=, post_data=}) static int l_http_fetch_sync(lua_State *L); diff --git a/src/script/lua_api/l_internal.h b/src/script/lua_api/l_internal.h index 378d19cd0..a86eeaf79 100644 --- a/src/script/lua_api/l_internal.h +++ b/src/script/lua_api/l_internal.h @@ -28,12 +28,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "common/c_internal.h" -#define luamethod(class, name) \ - { \ -#name, class ::l_##name \ - } -#define luamethod_aliased(class, name, alias) \ - {#name, class ::l_##name}, { #alias, class ::l_##name } +#define luamethod(class, name) {#name, class::l_##name} +#define luamethod_aliased(class, name, alias) {#name, class::l_##name}, {#alias, class::l_##name} #define API_FCT(name) registerFunction(L, #name, l_##name, top) // For future use @@ -43,33 +39,32 @@ with this program; if not, write to the Free Software Foundation, Inc., /* In debug mode ensure no code tries to retrieve the server env when it isn't * actually available (in CSM) */ #if !defined(SERVER) && !defined(NDEBUG) -#define DEBUG_ASSERT_NO_CLIENTAPI \ - FATAL_ERROR_IF(getClient(L) != nullptr, \ - "Tried " \ - "to retrieve ServerEnvironment on client") +#define DEBUG_ASSERT_NO_CLIENTAPI \ + FATAL_ERROR_IF(getClient(L) != nullptr, "Tried " \ + "to retrieve ServerEnvironment on client") #else #define DEBUG_ASSERT_NO_CLIENTAPI ((void)0) #endif // Retrieve ServerEnvironment pointer as `env` (no map lock) -#define GET_ENV_PTR_NO_MAP_LOCK \ - DEBUG_ASSERT_NO_CLIENTAPI; \ - ServerEnvironment *env = (ServerEnvironment *)getEnv(L); \ - if (env == NULL) \ - return 0 +#define GET_ENV_PTR_NO_MAP_LOCK \ + DEBUG_ASSERT_NO_CLIENTAPI; \ + ServerEnvironment *env = (ServerEnvironment *)getEnv(L); \ + if (env == NULL) \ + return 0 // Retrieve ServerEnvironment pointer as `env` -#define GET_ENV_PTR \ - MAP_LOCK_REQUIRED; \ +#define GET_ENV_PTR \ + MAP_LOCK_REQUIRED; \ GET_ENV_PTR_NO_MAP_LOCK // Retrieve Environment pointer as `env` (no map lock) -#define GET_PLAIN_ENV_PTR_NO_MAP_LOCK \ - Environment *env = (Environment *)getEnv(L); \ - if (env == NULL) \ - return 0 +#define GET_PLAIN_ENV_PTR_NO_MAP_LOCK \ + Environment *env = (Environment *)getEnv(L); \ + if (env == NULL) \ + return 0 // Retrieve Environment pointer as `env` -#define GET_PLAIN_ENV_PTR \ - MAP_LOCK_REQUIRED; \ +#define GET_PLAIN_ENV_PTR \ + MAP_LOCK_REQUIRED; \ GET_PLAIN_ENV_PTR_NO_MAP_LOCK diff --git a/src/script/lua_api/l_inventory.cpp b/src/script/lua_api/l_inventory.cpp index d75d96ef3..e41b5cb41 100644 --- a/src/script/lua_api/l_inventory.cpp +++ b/src/script/lua_api/l_inventory.cpp @@ -29,25 +29,25 @@ with this program; if not, write to the Free Software Foundation, Inc., /* InvRef */ -InvRef *InvRef::checkobject(lua_State *L, int narg) +InvRef* InvRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); - if (!ud) - luaL_typerror(L, narg, className); - return *(InvRef **)ud; // unbox pointer + if(!ud) luaL_typerror(L, narg, className); + return *(InvRef**)ud; // unbox pointer } -Inventory *InvRef::getinv(lua_State *L, InvRef *ref) +Inventory* InvRef::getinv(lua_State *L, InvRef *ref) { return getServerInventoryMgr(L)->getInventory(ref->m_loc); } -InventoryList *InvRef::getlist(lua_State *L, InvRef *ref, const char *listname) +InventoryList* InvRef::getlist(lua_State *L, InvRef *ref, + const char *listname) { NO_MAP_LOCK_REQUIRED; Inventory *inv = getinv(L, ref); - if (!inv) + if(!inv) return NULL; return inv->getList(listname); } @@ -61,8 +61,7 @@ void InvRef::reportInventoryChange(lua_State *L, InvRef *ref) // Exported functions // garbage collector -int InvRef::gc_object(lua_State *L) -{ +int InvRef::gc_object(lua_State *L) { InvRef *o = *(InvRef **)(lua_touserdata(L, 1)); delete o; return 0; @@ -75,7 +74,7 @@ int InvRef::l_is_empty(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); InventoryList *list = getlist(L, ref, listname); - if (list && list->getUsedSlots() > 0) { + if(list && list->getUsedSlots() > 0){ lua_pushboolean(L, false); } else { lua_pushboolean(L, true); @@ -90,7 +89,7 @@ int InvRef::l_get_size(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ lua_pushinteger(L, list->getSize()); } else { lua_pushinteger(L, 0); @@ -105,7 +104,7 @@ int InvRef::l_get_width(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ lua_pushinteger(L, list->getWidth()); } else { lua_pushinteger(L, 0); @@ -127,22 +126,23 @@ int InvRef::l_set_size(lua_State *L) } Inventory *inv = getinv(L, ref); - if (inv == NULL) { + if(inv == NULL){ lua_pushboolean(L, false); return 1; } - if (newsize == 0) { + if(newsize == 0){ inv->deleteList(listname); reportInventoryChange(L, ref); lua_pushboolean(L, true); return 1; } InventoryList *list = inv->getList(listname); - if (list) { + if(list){ list->setSize(newsize); } else { list = inv->addList(listname, newsize); - if (!list) { + if (!list) + { lua_pushboolean(L, false); return 1; } @@ -160,11 +160,11 @@ int InvRef::l_set_width(lua_State *L) const char *listname = luaL_checkstring(L, 2); int newwidth = luaL_checknumber(L, 3); Inventory *inv = getinv(L, ref); - if (inv == NULL) { + if(inv == NULL){ return 0; } InventoryList *list = inv->getList(listname); - if (list) { + if(list){ list->setWidth(newwidth); } else { return 0; @@ -182,7 +182,7 @@ int InvRef::l_get_stack(lua_State *L) int i = luaL_checknumber(L, 3) - 1; InventoryList *list = getlist(L, ref, listname); ItemStack item; - if (list != NULL && i >= 0 && i < (int)list->getSize()) + if(list != NULL && i >= 0 && i < (int) list->getSize()) item = list->getItem(i); LuaItemStack::create(L, item); return 1; @@ -197,7 +197,7 @@ int InvRef::l_set_stack(lua_State *L) int i = luaL_checknumber(L, 3) - 1; ItemStack newitem = read_item(L, 4, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); - if (list != NULL && i >= 0 && i < (int)list->getSize()) { + if(list != NULL && i >= 0 && i < (int) list->getSize()){ list->changeItem(i, newitem); reportInventoryChange(L, ref); lua_pushboolean(L, true); @@ -214,7 +214,7 @@ int InvRef::l_get_list(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); Inventory *inv = getinv(L, ref); - if (inv) { + if(inv){ push_inventory_list(L, inv, listname); } else { lua_pushnil(L); @@ -229,12 +229,13 @@ int InvRef::l_set_list(lua_State *L) InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); Inventory *inv = getinv(L, ref); - if (inv == NULL) { + if(inv == NULL){ return 0; } InventoryList *list = inv->getList(listname); - if (list) - read_inventory_list(L, 3, inv, listname, getServer(L), list->getSize()); + if(list) + read_inventory_list(L, 3, inv, listname, + getServer(L), list->getSize()); else read_inventory_list(L, 3, inv, listname, getServer(L)); reportInventoryChange(L, ref); @@ -250,11 +251,11 @@ int InvRef::l_get_lists(lua_State *L) if (!inv) { return 0; } - std::vector lists = inv->getLists(); - std::vector::iterator iter = lists.begin(); + std::vector lists = inv->getLists(); + std::vector::iterator iter = lists.begin(); lua_createtable(L, 0, lists.size()); for (; iter != lists.end(); iter++) { - const char *name = (*iter)->getName().c_str(); + const char* name = (*iter)->getName().c_str(); lua_pushstring(L, name); push_inventory_list(L, inv, name); lua_rawset(L, -3); @@ -297,9 +298,9 @@ int InvRef::l_add_item(lua_State *L) const char *listname = luaL_checkstring(L, 2); ItemStack item = read_item(L, 3, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ ItemStack leftover = list->addItem(item); - if (leftover.count != item.count) + if(leftover.count != item.count) reportInventoryChange(L, ref); LuaItemStack::create(L, leftover); } else { @@ -317,7 +318,7 @@ int InvRef::l_room_for_item(lua_State *L) const char *listname = luaL_checkstring(L, 2); ItemStack item = read_item(L, 3, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ lua_pushboolean(L, list->roomForItem(item)); } else { lua_pushboolean(L, false); @@ -325,8 +326,8 @@ int InvRef::l_room_for_item(lua_State *L) return 1; } -// contains_item(self, listname, itemstack or itemstring or table or nil, [match_meta]) -> -// true/false Returns true if the list contains the given count of the given item +// contains_item(self, listname, itemstack or itemstring or table or nil, [match_meta]) -> true/false +// Returns true if the list contains the given count of the given item int InvRef::l_contains_item(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -354,9 +355,9 @@ int InvRef::l_remove_item(lua_State *L) const char *listname = luaL_checkstring(L, 2); ItemStack item = read_item(L, 3, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); - if (list) { + if(list){ ItemStack removed = list->removeItem(item); - if (!removed.empty()) + if(!removed.empty()) reportInventoryChange(L, ref); LuaItemStack::create(L, removed); } else { @@ -371,7 +372,7 @@ int InvRef::l_get_location(lua_State *L) NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const InventoryLocation &loc = ref->m_loc; - switch (loc.type) { + switch(loc.type){ case InventoryLocation::PLAYER: lua_newtable(L); lua_pushstring(L, "player"); @@ -403,7 +404,9 @@ int InvRef::l_get_location(lua_State *L) return 1; } -InvRef::InvRef(const InventoryLocation &loc) : m_loc(loc) + +InvRef::InvRef(const InventoryLocation &loc): + m_loc(loc) { } @@ -440,7 +443,7 @@ void InvRef::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -450,25 +453,35 @@ void InvRef::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Cannot be created from Lua - // lua_register(L, className, create_object); + //lua_register(L, className, create_object); } const char InvRef::className[] = "InvRef"; -const luaL_Reg InvRef::methods[] = {luamethod(InvRef, is_empty), - luamethod(InvRef, get_size), luamethod(InvRef, set_size), - luamethod(InvRef, get_width), luamethod(InvRef, set_width), - luamethod(InvRef, get_stack), luamethod(InvRef, set_stack), - luamethod(InvRef, get_list), luamethod(InvRef, set_list), - luamethod(InvRef, get_lists), luamethod(InvRef, set_lists), - luamethod(InvRef, add_item), luamethod(InvRef, room_for_item), - luamethod(InvRef, contains_item), luamethod(InvRef, remove_item), - luamethod(InvRef, get_location), {0, 0}}; +const luaL_Reg InvRef::methods[] = { + luamethod(InvRef, is_empty), + luamethod(InvRef, get_size), + luamethod(InvRef, set_size), + luamethod(InvRef, get_width), + luamethod(InvRef, set_width), + luamethod(InvRef, get_stack), + luamethod(InvRef, set_stack), + luamethod(InvRef, get_list), + luamethod(InvRef, set_list), + luamethod(InvRef, get_lists), + luamethod(InvRef, set_lists), + luamethod(InvRef, add_item), + luamethod(InvRef, room_for_item), + luamethod(InvRef, contains_item), + luamethod(InvRef, remove_item), + luamethod(InvRef, get_location), + {0,0} +}; // get_inventory(location) int ModApiInventory::l_get_inventory(lua_State *L) @@ -479,7 +492,7 @@ int ModApiInventory::l_get_inventory(lua_State *L) std::string type = luaL_checkstring(L, -1); lua_pop(L, 1); - if (type == "node") { + if(type == "node"){ MAP_LOCK_REQUIRED; lua_getfield(L, 1, "pos"); v3s16 pos = check_v3s16(L, -1); @@ -509,6 +522,7 @@ int ModApiInventory::l_get_inventory(lua_State *L) lua_pushnil(L); return 1; // END NO_MAP_LOCK_REQUIRED; + } // create_detached_inventory_raw(name, [player_name]) @@ -517,8 +531,7 @@ int ModApiInventory::l_create_detached_inventory_raw(lua_State *L) NO_MAP_LOCK_REQUIRED; const char *name = luaL_checkstring(L, 1); std::string player = readParam(L, 2, ""); - if (getServerInventoryMgr(L)->createDetachedInventory( - name, getServer(L)->idef(), player) != NULL) { + if (getServerInventoryMgr(L)->createDetachedInventory(name, getServer(L)->idef(), player) != NULL) { InventoryLocation loc; loc.setDetached(name); InvRef::create(L, loc); diff --git a/src/script/lua_api/l_inventory.h b/src/script/lua_api/l_inventory.h index fa8a77ae2..94f670c9d 100644 --- a/src/script/lua_api/l_inventory.h +++ b/src/script/lua_api/l_inventory.h @@ -30,8 +30,7 @@ class RemotePlayer; InvRef */ -class InvRef : public ModApiBase -{ +class InvRef : public ModApiBase { private: InventoryLocation m_loc; @@ -40,9 +39,10 @@ private: static InvRef *checkobject(lua_State *L, int narg); - static Inventory *getinv(lua_State *L, InvRef *ref); + static Inventory* getinv(lua_State *L, InvRef *ref); - static InventoryList *getlist(lua_State *L, InvRef *ref, const char *listname); + static InventoryList* getlist(lua_State *L, InvRef *ref, + const char *listname); static void reportInventoryChange(lua_State *L, InvRef *ref); @@ -88,17 +88,16 @@ private: // Returns the leftover stack static int l_add_item(lua_State *L); - // room_for_item(self, listname, itemstack or itemstring or table or nil) -> - // true/false Returns true if the item completely fits into the list + // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false + // Returns true if the item completely fits into the list static int l_room_for_item(lua_State *L); - // contains_item(self, listname, itemstack or itemstring or table or nil, - // [match_meta]) -> true/false Returns true if the list contains the given count - // of the given item name + // contains_item(self, listname, itemstack or itemstring or table or nil, [match_meta]) -> true/false + // Returns true if the list contains the given count of the given item name static int l_contains_item(lua_State *L); - // remove_item(self, listname, itemstack or itemstring or table or nil) -> - // itemstack Returns the items that were actually removed + // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack + // Returns the items that were actually removed static int l_remove_item(lua_State *L); // get_location() -> location (like get_inventory(location)) @@ -117,8 +116,7 @@ public: static void Register(lua_State *L); }; -class ModApiInventory : public ModApiBase -{ +class ModApiInventory : public ModApiBase { private: static int l_create_detached_inventory_raw(lua_State *L); diff --git a/src/script/lua_api/l_inventoryaction.cpp b/src/script/lua_api/l_inventoryaction.cpp index f65137465..f3037ba83 100644 --- a/src/script/lua_api/l_inventoryaction.cpp +++ b/src/script/lua_api/l_inventoryaction.cpp @@ -43,9 +43,9 @@ int LuaInventoryAction::l_apply(lua_State *L) std::ostringstream os(std::ios::binary); o->m_action->serialize(os); - + std::istringstream is(os.str(), std::ios_base::binary); - + InventoryAction *a = InventoryAction::deSerialize(is); getClient(L)->inventoryAction(a); @@ -69,30 +69,29 @@ int LuaInventoryAction::l_to(lua_State *L) int LuaInventoryAction::l_craft(lua_State *L) { LuaInventoryAction *o = checkobject(L, 1); - + if (o->m_action->getType() != IAction::Craft) return 0; - + std::string locStr; InventoryLocation loc; - + locStr = readParam(L, 2); - + try { loc.deSerialize(locStr); dynamic_cast(o->m_action)->craft_inv = loc; - } catch (SerializationError &) { - } - + } catch (SerializationError &) {} + return 0; } int LuaInventoryAction::l_set_count(lua_State *L) { LuaInventoryAction *o = checkobject(L, 1); - + s16 count = luaL_checkinteger(L, 2); - + switch (o->m_action->getType()) { case IAction::Move: ((IMoveAction *)o->m_action)->count = count; @@ -104,7 +103,7 @@ int LuaInventoryAction::l_set_count(lua_State *L) ((ICraftAction *)o->m_action)->count = count; break; } - + return 0; } @@ -128,25 +127,23 @@ LuaInventoryAction::~LuaInventoryAction() delete m_action; } -void LuaInventoryAction::readFullInventoryLocationInto( - lua_State *L, InventoryLocation *loc, std::string *list, s16 *index) +void LuaInventoryAction::readFullInventoryLocationInto(lua_State *L, InventoryLocation *loc, std::string *list, s16 *index) { try { loc->deSerialize(readParam(L, 2)); std::string l = readParam(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(L, 1); - + if (typeStr == "move") type = IAction::Move; else if (typeStr == "drop") @@ -209,7 +206,11 @@ void LuaInventoryAction::Register(lua_State *L) } const char LuaInventoryAction::className[] = "InventoryAction"; -const luaL_Reg LuaInventoryAction::methods[] = {luamethod(LuaInventoryAction, apply), - luamethod(LuaInventoryAction, from), luamethod(LuaInventoryAction, to), - luamethod(LuaInventoryAction, craft), - luamethod(LuaInventoryAction, set_count), {0, 0}}; +const luaL_Reg LuaInventoryAction::methods[] = { + luamethod(LuaInventoryAction, apply), + luamethod(LuaInventoryAction, from), + luamethod(LuaInventoryAction, to), + luamethod(LuaInventoryAction, craft), + luamethod(LuaInventoryAction, set_count), + {0,0} +}; diff --git a/src/script/lua_api/l_inventoryaction.h b/src/script/lua_api/l_inventoryaction.h index a4cc6cbe5..c1a96d010 100644 --- a/src/script/lua_api/l_inventoryaction.h +++ b/src/script/lua_api/l_inventoryaction.h @@ -20,46 +20,44 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "inventorymanager.h" #include "lua_api/l_base.h" -#define GET_MOVE_ACTION \ - LuaInventoryAction *o = checkobject(L, 1); \ - if (o->m_action->getType() == IAction::Craft) \ - return 0; \ +#define GET_MOVE_ACTION \ + LuaInventoryAction *o = checkobject(L, 1); \ + if (o->m_action->getType() == IAction::Craft) \ + return 0; \ MoveAction *act = dynamic_cast(o->m_action); -class LuaInventoryAction : public ModApiBase -{ +class LuaInventoryAction : public ModApiBase { private: InventoryAction *m_action; - - static void readFullInventoryLocationInto(lua_State *L, InventoryLocation *loc, - std::string *list, s16 *index); - + + static void readFullInventoryLocationInto(lua_State *L, InventoryLocation *loc, std::string *list, s16 *index); + static const char className[]; static const luaL_Reg methods[]; - + // Exported functions - + // garbage collector static int gc_object(lua_State *L); // __tostring metamethod static int mt_tostring(lua_State *L); - + // apply(self) static int l_apply(lua_State *L); - + // from(self, location, list, index) static int l_from(lua_State *L); - + // to(self, location, list, index) static int l_to(lua_State *L); - + // craft(self, location) static int l_craft(lua_State *L); // set_count(self, count) static int l_set_count(lua_State *L); - + public: LuaInventoryAction(const IAction &type); ~LuaInventoryAction(); @@ -69,6 +67,6 @@ public: static int create_object(lua_State *L); // Not callable from Lua static int create(lua_State *L, const IAction &type); - static LuaInventoryAction *checkobject(lua_State *L, int narg); + static LuaInventoryAction* checkobject(lua_State *L, int narg); static void Register(lua_State *L); }; diff --git a/src/script/lua_api/l_item.cpp b/src/script/lua_api/l_item.cpp index 9bbf9826b..bea7d122f 100644 --- a/src/script/lua_api/l_item.cpp +++ b/src/script/lua_api/l_item.cpp @@ -234,9 +234,12 @@ int LuaItemStack::l_to_table(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); const ItemStack &item = o->m_stack; - if (item.empty()) { + if(item.empty()) + { lua_pushnil(L); - } else { + } + else + { lua_newtable(L); lua_pushstring(L, item.name.c_str()); lua_setfield(L, -2, "name"); @@ -311,7 +314,8 @@ int LuaItemStack::l_get_definition(lua_State *L) lua_getfield(L, -1, "registered_items"); luaL_checktype(L, -1, LUA_TTABLE); lua_getfield(L, -1, item.name.c_str()); - if (lua_isnil(L, -1)) { + if(lua_isnil(L, -1)) + { lua_pop(L, 1); lua_getfield(L, -1, "unknown"); } @@ -326,7 +330,8 @@ int LuaItemStack::l_get_tool_capabilities(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; - const ToolCapabilities &prop = item.getToolCapabilities(getGameDef(L)->idef()); + const ToolCapabilities &prop = + item.getToolCapabilities(getGameDef(L)->idef()); push_tool_capabilities(L, prop); return 1; } @@ -370,8 +375,8 @@ int LuaItemStack::l_item_fits(lua_State *L) ItemStack newitem = read_item(L, 2, getGameDef(L)->idef()); ItemStack restitem; bool fits = item.itemFits(newitem, &restitem, getGameDef(L)->idef()); - lua_pushboolean(L, fits); // first return value - create(L, restitem); // second return value + lua_pushboolean(L, fits); // first return value + create(L, restitem); // second return value return 2; } @@ -382,7 +387,7 @@ int LuaItemStack::l_take_item(lua_State *L) LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; u32 takecount = 1; - if (!lua_isnone(L, 2)) + if(!lua_isnone(L, 2)) takecount = luaL_checkinteger(L, 2); ItemStack taken = item.takeItem(takecount); create(L, taken); @@ -396,22 +401,23 @@ int LuaItemStack::l_peek_item(lua_State *L) LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; u32 peekcount = 1; - if (!lua_isnone(L, 2)) + if(!lua_isnone(L, 2)) peekcount = lua_tointeger(L, 2); ItemStack peekaboo = item.peekItem(peekcount); create(L, peekaboo); return 1; } -LuaItemStack::LuaItemStack(const ItemStack &item) : m_stack(item) +LuaItemStack::LuaItemStack(const ItemStack &item): + m_stack(item) { } -const ItemStack &LuaItemStack::getItem() const +const ItemStack& LuaItemStack::getItem() const { return m_stack; } -ItemStack &LuaItemStack::getItem() +ItemStack& LuaItemStack::getItem() { return m_stack; } @@ -470,32 +476,44 @@ void LuaItemStack::Register(lua_State *L) lua_pushcfunction(L, mt_tostring); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Can be created from Lua (ItemStack(itemstack or itemstring or table or nil)) lua_register(L, className, create_object); } const char LuaItemStack::className[] = "ItemStack"; -const luaL_Reg LuaItemStack::methods[] = {luamethod(LuaItemStack, is_empty), - luamethod(LuaItemStack, get_name), luamethod(LuaItemStack, set_name), - luamethod(LuaItemStack, get_count), luamethod(LuaItemStack, set_count), - luamethod(LuaItemStack, get_wear), luamethod(LuaItemStack, set_wear), - luamethod(LuaItemStack, get_meta), luamethod(LuaItemStack, get_metadata), - luamethod(LuaItemStack, set_metadata), - luamethod(LuaItemStack, get_description), luamethod(LuaItemStack, clear), - luamethod(LuaItemStack, replace), luamethod(LuaItemStack, to_string), - luamethod(LuaItemStack, to_table), luamethod(LuaItemStack, get_stack_max), - luamethod(LuaItemStack, get_free_space), - luamethod(LuaItemStack, is_known), - luamethod(LuaItemStack, get_definition), - luamethod(LuaItemStack, get_tool_capabilities), - luamethod(LuaItemStack, add_wear), luamethod(LuaItemStack, add_item), - luamethod(LuaItemStack, item_fits), luamethod(LuaItemStack, take_item), - luamethod(LuaItemStack, peek_item), {0, 0}}; +const luaL_Reg LuaItemStack::methods[] = { + luamethod(LuaItemStack, is_empty), + luamethod(LuaItemStack, get_name), + luamethod(LuaItemStack, set_name), + luamethod(LuaItemStack, get_count), + luamethod(LuaItemStack, set_count), + luamethod(LuaItemStack, get_wear), + luamethod(LuaItemStack, set_wear), + luamethod(LuaItemStack, get_meta), + luamethod(LuaItemStack, get_metadata), + luamethod(LuaItemStack, set_metadata), + luamethod(LuaItemStack, get_description), + luamethod(LuaItemStack, clear), + luamethod(LuaItemStack, replace), + luamethod(LuaItemStack, to_string), + luamethod(LuaItemStack, to_table), + luamethod(LuaItemStack, get_stack_max), + luamethod(LuaItemStack, get_free_space), + luamethod(LuaItemStack, is_known), + luamethod(LuaItemStack, get_definition), + luamethod(LuaItemStack, get_tool_capabilities), + luamethod(LuaItemStack, add_wear), + luamethod(LuaItemStack, add_item), + luamethod(LuaItemStack, item_fits), + luamethod(LuaItemStack, take_item), + luamethod(LuaItemStack, peek_item), + {0,0} +}; /* ItemDefinition @@ -509,13 +527,15 @@ int ModApiItemMod::l_register_item_raw(lua_State *L) int table = 1; // Get the writable item and node definition managers from the server - IWritableItemDefManager *idef = getGameDef(L)->getWritableItemDefManager(); - NodeDefManager *ndef = getGameDef(L)->getWritableNodeDefManager(); + IWritableItemDefManager *idef = + getGameDef(L)->getWritableItemDefManager(); + NodeDefManager *ndef = + getGameDef(L)->getWritableNodeDefManager(); // Check if name is defined std::string name; lua_getfield(L, table, "name"); - if (lua_isstring(L, -1)) { + if(lua_isstring(L, -1)){ name = readParam(L, -1); } else { throw LuaError("register_item_raw: name is not defined or not a string"); @@ -532,8 +552,8 @@ int ModApiItemMod::l_register_item_raw(lua_State *L) // Default to having client-side placement prediction for nodes // ("" in item definition sets it off) - if (def.node_placement_prediction == "__default") { - if (def.type == ITEM_NODE) + if(def.node_placement_prediction == "__default"){ + if(def.type == ITEM_NODE) def.node_placement_prediction = name; else def.node_placement_prediction = ""; @@ -553,12 +573,13 @@ int ModApiItemMod::l_register_item_raw(lua_State *L) content_t id = ndef->set(f.name, f); if (id > MAX_REGISTERED_CONTENT) { - throw LuaError("Number of registerable nodes (" + - itos(MAX_REGISTERED_CONTENT + 1) + - ") exceeded (" + name + ")"); + throw LuaError("Number of registerable nodes (" + + itos(MAX_REGISTERED_CONTENT+1) + + ") exceeded (" + name + ")"); } + } - + return 0; /* number of results */ } @@ -568,11 +589,13 @@ int ModApiItemMod::l_unregister_item_raw(lua_State *L) NO_MAP_LOCK_REQUIRED; std::string name = luaL_checkstring(L, 1); - IWritableItemDefManager *idef = getGameDef(L)->getWritableItemDefManager(); + IWritableItemDefManager *idef = + getGameDef(L)->getWritableItemDefManager(); // Unregister the node if (idef->get(name).type == ITEM_NODE) { - NodeDefManager *ndef = getGameDef(L)->getWritableNodeDefManager(); + NodeDefManager *ndef = + getGameDef(L)->getWritableNodeDefManager(); ndef->removeNode(name); } @@ -589,7 +612,8 @@ int ModApiItemMod::l_register_alias_raw(lua_State *L) std::string convert_to = luaL_checkstring(L, 2); // Get the writable item definition manager from the server - IWritableItemDefManager *idef = getGameDef(L)->getWritableItemDefManager(); + IWritableItemDefManager *idef = + getGameDef(L)->getWritableItemDefManager(); idef->registerAlias(name, convert_to); @@ -612,8 +636,8 @@ int ModApiItemMod::l_get_content_id(lua_State *L) content_t content_id; if (alias_name != name) { if (!ndef->getId(alias_name, content_id)) - throw LuaError("Unknown node: " + alias_name + " (from alias " + - name + ")"); + throw LuaError("Unknown node: " + alias_name + + " (from alias " + name + ")"); } else if (!ndef->getId(name, content_id)) { throw LuaError("Unknown node: " + name); } diff --git a/src/script/lua_api/l_item.h b/src/script/lua_api/l_item.h index 21110b83a..98744c071 100644 --- a/src/script/lua_api/l_item.h +++ b/src/script/lua_api/l_item.h @@ -20,10 +20,9 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once #include "lua_api/l_base.h" -#include "inventory.h" // ItemStack +#include "inventory.h" // ItemStack -class LuaItemStack : public ModApiBase -{ +class LuaItemStack : public ModApiBase { private: ItemStack m_stack; @@ -115,8 +114,8 @@ private: // Returns leftover item stack static int l_add_item(lua_State *L); - // item_fits(self, itemstack or itemstring or table or nil) -> true/false, - // itemstack First return value is true iff the new item fits fully into the stack + // item_fits(self, itemstack or itemstring or table or nil) -> true/false, itemstack + // First return value is true iff the new item fits fully into the stack // Second return value is the would-be-left-over item stack static int l_item_fits(lua_State *L); @@ -130,27 +129,26 @@ public: LuaItemStack(const ItemStack &item); ~LuaItemStack() = default; - const ItemStack &getItem() const; - ItemStack &getItem(); + const ItemStack& getItem() const; + ItemStack& getItem(); // LuaItemStack(itemstack or itemstring or table or nil) // Creates an LuaItemStack and leaves it on top of stack static int create_object(lua_State *L); // Not callable from Lua static int create(lua_State *L, const ItemStack &item); - static LuaItemStack *checkobject(lua_State *L, int narg); + static LuaItemStack* checkobject(lua_State *L, int narg); static void Register(lua_State *L); + }; -class ModApiItemMod : public ModApiBase -{ +class ModApiItemMod : public ModApiBase { private: static int l_register_item_raw(lua_State *L); static int l_unregister_item_raw(lua_State *L); static int l_register_alias_raw(lua_State *L); static int l_get_content_id(lua_State *L); static int l_get_name_from_content_id(lua_State *L); - public: static void Initialize(lua_State *L, int top); }; diff --git a/src/script/lua_api/l_itemstackmeta.cpp b/src/script/lua_api/l_itemstackmeta.cpp index 5a5c9934a..d1ba1bda4 100644 --- a/src/script/lua_api/l_itemstackmeta.cpp +++ b/src/script/lua_api/l_itemstackmeta.cpp @@ -26,17 +26,17 @@ with this program; if not, write to the Free Software Foundation, Inc., /* NodeMetaRef */ -ItemStackMetaRef *ItemStackMetaRef::checkobject(lua_State *L, int narg) +ItemStackMetaRef* ItemStackMetaRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); if (!ud) luaL_typerror(L, narg, className); - return *(ItemStackMetaRef **)ud; // unbox pointer + return *(ItemStackMetaRef**)ud; // unbox pointer } -Metadata *ItemStackMetaRef::getmeta(bool auto_create) +Metadata* ItemStackMetaRef::getmeta(bool auto_create) { return &istack->metadata; } @@ -68,8 +68,7 @@ int ItemStackMetaRef::l_set_tool_capabilities(lua_State *L) } // garbage collector -int ItemStackMetaRef::gc_object(lua_State *L) -{ +int ItemStackMetaRef::gc_object(lua_State *L) { ItemStackMetaRef *o = *(ItemStackMetaRef **)(lua_touserdata(L, 1)); delete o; return 0; @@ -80,7 +79,7 @@ int ItemStackMetaRef::gc_object(lua_State *L) void ItemStackMetaRef::create(lua_State *L, ItemStack *istack) { ItemStackMetaRef *o = new ItemStackMetaRef(istack); - // infostream<<"NodeMetaRef::create: o="<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 789b3a3f0..e40dd7b37 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,10 +522,13 @@ 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), @@ -544,14 +547,18 @@ const luaL_Reg LuaLocalPlayer::methods[] = {luamethod(LuaLocalPlayer, get_veloci luamethod(LuaLocalPlayer, get_last_look_vertical), // luamethod(LuaLocalPlayer, get_control), - luamethod(LuaLocalPlayer, get_breath), luamethod(LuaLocalPlayer, get_pos), + luamethod(LuaLocalPlayer, get_breath), + luamethod(LuaLocalPlayer, get_pos), luamethod(LuaLocalPlayer, set_pos), luamethod(LuaLocalPlayer, get_movement_acceleration), luamethod(LuaLocalPlayer, get_movement_speed), luamethod(LuaLocalPlayer, get_movement), luamethod(LuaLocalPlayer, get_armor_groups), - luamethod(LuaLocalPlayer, hud_add), luamethod(LuaLocalPlayer, hud_remove), - luamethod(LuaLocalPlayer, hud_change), luamethod(LuaLocalPlayer, hud_get), + luamethod(LuaLocalPlayer, hud_add), + luamethod(LuaLocalPlayer, hud_remove), + luamethod(LuaLocalPlayer, hud_change), + luamethod(LuaLocalPlayer, hud_get), luamethod(LuaLocalPlayer, get_object), - {0, 0}}; + {0, 0} +}; diff --git a/src/script/lua_api/l_mainmenu.cpp b/src/script/lua_api/l_mainmenu.cpp index 78a33b755..f32c477c2 100644 --- a/src/script/lua_api/l_mainmenu.cpp +++ b/src/script/lua_api/l_mainmenu.cpp @@ -41,6 +41,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/renderingengine.h" #include "network/networkprotocol.h" + /******************************************************************************/ std::string ModApiMainMenu::getTextData(lua_State *L, std::string name) { @@ -48,39 +49,39 @@ std::string ModApiMainMenu::getTextData(lua_State *L, std::string name) lua_getfield(L, -1, name.c_str()); - if (lua_isnil(L, -1)) + if(lua_isnil(L, -1)) return ""; return luaL_checkstring(L, -1); } /******************************************************************************/ -int ModApiMainMenu::getIntegerData(lua_State *L, std::string name, bool &valid) +int ModApiMainMenu::getIntegerData(lua_State *L, std::string name,bool& valid) { lua_getglobal(L, "gamedata"); lua_getfield(L, -1, name.c_str()); - if (lua_isnil(L, -1)) { + if(lua_isnil(L, -1)) { valid = false; return -1; - } + } valid = true; return luaL_checkinteger(L, -1); } /******************************************************************************/ -int ModApiMainMenu::getBoolData(lua_State *L, std::string name, bool &valid) +int ModApiMainMenu::getBoolData(lua_State *L, std::string name,bool& valid) { lua_getglobal(L, "gamedata"); lua_getfield(L, -1, name.c_str()); - if (lua_isnil(L, -1)) { + if(lua_isnil(L, -1)) { valid = false; return false; - } + } valid = true; return readParam(L, -1); @@ -89,13 +90,13 @@ int ModApiMainMenu::getBoolData(lua_State *L, std::string name, bool &valid) /******************************************************************************/ int ModApiMainMenu::l_update_formspec(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); if (engine->m_startgame) return 0; - // read formspec + //read formspec std::string formspec(luaL_checkstring(L, 1)); if (engine->m_formspecgui != 0) { @@ -123,28 +124,28 @@ int ModApiMainMenu::l_set_formspec_prepend(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_start(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); - // update c++ gamedata from lua table + //update c++ gamedata from lua table bool valid = false; MainMenuData *data = engine->m_data; - data->selected_world = getIntegerData(L, "selected_world", valid) - 1; - data->simple_singleplayer_mode = getBoolData(L, "singleplayer", valid); + data->selected_world = getIntegerData(L, "selected_world",valid) -1; + data->simple_singleplayer_mode = getBoolData(L,"singleplayer",valid); data->do_reconnect = getBoolData(L, "do_reconnect", valid); if (!data->do_reconnect) { - data->name = getTextData(L, "playername"); - data->password = getTextData(L, "password"); - data->address = getTextData(L, "address"); - data->port = getTextData(L, "port"); + data->name = getTextData(L,"playername"); + data->password = getTextData(L,"password"); + data->address = getTextData(L,"address"); + data->port = getTextData(L,"port"); } - data->serverdescription = getTextData(L, "serverdescription"); - data->servername = getTextData(L, "servername"); + data->serverdescription = getTextData(L,"serverdescription"); + data->servername = getTextData(L,"servername"); - // close menu next time + //close menu next time engine->m_startgame = true; return 0; } @@ -152,7 +153,7 @@ int ModApiMainMenu::l_start(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_close(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); engine->m_kill = true; @@ -162,14 +163,14 @@ int ModApiMainMenu::l_close(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_set_background(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); std::string backgroundlevel(luaL_checkstring(L, 1)); std::string texturename(luaL_checkstring(L, 2)); bool tile_image = false; - bool retval = false; + bool retval = false; unsigned int minsize = 16; if (!lua_isnone(L, 3)) { @@ -181,36 +182,36 @@ int ModApiMainMenu::l_set_background(lua_State *L) } if (backgroundlevel == "background") { - retval |= engine->setTexture( - TEX_LAYER_BACKGROUND, texturename, tile_image, minsize); + retval |= engine->setTexture(TEX_LAYER_BACKGROUND, texturename, + tile_image, minsize); } if (backgroundlevel == "overlay") { - retval |= engine->setTexture( - TEX_LAYER_OVERLAY, texturename, tile_image, minsize); + retval |= engine->setTexture(TEX_LAYER_OVERLAY, texturename, + tile_image, minsize); } if (backgroundlevel == "header") { - retval |= engine->setTexture( - TEX_LAYER_HEADER, texturename, tile_image, minsize); + retval |= engine->setTexture(TEX_LAYER_HEADER, texturename, + tile_image, minsize); } if (backgroundlevel == "footer") { - retval |= engine->setTexture( - TEX_LAYER_FOOTER, texturename, tile_image, minsize); + retval |= engine->setTexture(TEX_LAYER_FOOTER, texturename, + tile_image, minsize); } - lua_pushboolean(L, retval); + lua_pushboolean(L,retval); return 1; } /******************************************************************************/ int ModApiMainMenu::l_set_clouds(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); - bool value = readParam(L, 1); + bool value = readParam(L,1); engine->m_clouds_enabled = value; @@ -227,7 +228,7 @@ int ModApiMainMenu::l_get_textlist_index(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_get_table_index(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); std::string tablename(luaL_checkstring(L, 1)); @@ -251,20 +252,20 @@ int ModApiMainMenu::l_get_worlds(lua_State *L) unsigned int index = 1; for (const WorldSpec &world : worlds) { - lua_pushnumber(L, index); + lua_pushnumber(L,index); lua_newtable(L); int top_lvl2 = lua_gettop(L); - lua_pushstring(L, "path"); + lua_pushstring(L,"path"); lua_pushstring(L, world.path.c_str()); lua_settable(L, top_lvl2); - lua_pushstring(L, "name"); + lua_pushstring(L,"name"); lua_pushstring(L, world.name.c_str()); lua_settable(L, top_lvl2); - lua_pushstring(L, "gameid"); + lua_pushstring(L,"gameid"); lua_pushstring(L, world.gameid.c_str()); lua_settable(L, top_lvl2); @@ -285,7 +286,7 @@ int ModApiMainMenu::l_get_favorites(lua_State *L) std::vector servers; - if (listtype == "online") { + if(listtype == "online") { servers = ServerList::getOnline(); } else { servers = ServerList::getLocal(); @@ -304,8 +305,8 @@ int ModApiMainMenu::l_get_favorites(lua_State *L) if (!server["clients"].asString().empty()) { std::string clients_raw = server["clients"].asString(); - char *endptr = 0; - int numbervalue = strtol(clients_raw.c_str(), &endptr, 10); + char* endptr = 0; + int numbervalue = strtol(clients_raw.c_str(), &endptr,10); if ((!clients_raw.empty()) && (*endptr == 0)) { lua_pushstring(L, "clients"); @@ -317,8 +318,8 @@ int ModApiMainMenu::l_get_favorites(lua_State *L) if (!server["clients_max"].asString().empty()) { std::string clients_max_raw = server["clients_max"].asString(); - char *endptr = 0; - int numbervalue = strtol(clients_max_raw.c_str(), &endptr, 10); + char* endptr = 0; + int numbervalue = strtol(clients_max_raw.c_str(), &endptr,10); if ((!clients_max_raw.empty()) && (*endptr == 0)) { lua_pushstring(L, "clients_max"); @@ -449,22 +450,25 @@ int ModApiMainMenu::l_delete_favorite(lua_State *L) std::string listtype = "local"; - if (!lua_isnone(L, 2)) { - listtype = luaL_checkstring(L, 2); + if (!lua_isnone(L,2)) { + listtype = luaL_checkstring(L,2); } - if ((listtype != "local") && (listtype != "online")) + if ((listtype != "local") && + (listtype != "online")) return 0; - if (listtype == "online") { + + if(listtype == "online") { servers = ServerList::getOnline(); } else { servers = ServerList::getLocal(); } - int fav_idx = luaL_checkinteger(L, 1) - 1; + int fav_idx = luaL_checkinteger(L,1) -1; - if ((fav_idx >= 0) && (fav_idx < (int)servers.size())) { + if ((fav_idx >= 0) && + (fav_idx < (int) servers.size())) { ServerList::deleteEntry(servers[fav_idx]); } @@ -486,37 +490,37 @@ int ModApiMainMenu::l_get_games(lua_State *L) lua_newtable(L); int top_lvl2 = lua_gettop(L); - lua_pushstring(L, "id"); - lua_pushstring(L, game.id.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "id"); + lua_pushstring(L, game.id.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "path"); - lua_pushstring(L, game.path.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "path"); + lua_pushstring(L, game.path.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "type"); - lua_pushstring(L, "game"); - lua_settable(L, top_lvl2); + lua_pushstring(L, "type"); + lua_pushstring(L, "game"); + lua_settable(L, top_lvl2); - lua_pushstring(L, "gamemods_path"); - lua_pushstring(L, game.gamemods_path.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "gamemods_path"); + lua_pushstring(L, game.gamemods_path.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "name"); - lua_pushstring(L, game.name.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "name"); + lua_pushstring(L, game.name.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "author"); - lua_pushstring(L, game.author.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "author"); + lua_pushstring(L, game.author.c_str()); + lua_settable(L, top_lvl2); - lua_pushstring(L, "release"); + lua_pushstring(L, "release"); lua_pushinteger(L, game.release); - lua_settable(L, top_lvl2); + lua_settable(L, top_lvl2); - lua_pushstring(L, "menuicon_path"); - lua_pushstring(L, game.menuicon_path.c_str()); - lua_settable(L, top_lvl2); + lua_pushstring(L, "menuicon_path"); + lua_pushstring(L, game.menuicon_path.c_str()); + lua_settable(L, top_lvl2); lua_pushstring(L, "addon_mods_paths"); lua_newtable(L); @@ -525,7 +529,7 @@ int ModApiMainMenu::l_get_games(lua_State *L) for (const std::string &addon_mods_path : game.addon_mods_paths) { lua_pushnumber(L, internal_index); lua_pushstring(L, addon_mods_path.c_str()); - lua_settable(L, table2); + lua_settable(L, table2); internal_index++; } lua_settable(L, top_lvl2); @@ -594,11 +598,13 @@ int ModApiMainMenu::l_get_content_info(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_show_keys_menu(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); GUIKeyChangeMenu *kmenu = new GUIKeyChangeMenu(RenderingEngine::get_gui_env(), - engine->m_parent, -1, engine->m_menumanager, + engine->m_parent, + -1, + engine->m_menumanager, engine->m_texture_source); kmenu->drop(); return 0; @@ -607,14 +613,17 @@ int ModApiMainMenu::l_show_keys_menu(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_create_world(lua_State *L) { - const char *name = luaL_checkstring(L, 1); - int gameidx = luaL_checkinteger(L, 2) - 1; + const char *name = luaL_checkstring(L, 1); + int gameidx = luaL_checkinteger(L,2) -1; - std::string path = porting::path_user + DIR_DELIM "worlds" + DIR_DELIM + name; + std::string path = porting::path_user + DIR_DELIM + "worlds" + DIR_DELIM + + name; std::vector games = getAvailableGames(); - if ((gameidx >= 0) && (gameidx < (int)games.size())) { + if ((gameidx >= 0) && + (gameidx < (int) games.size())) { // Create world if it doesn't exist if (!loadGameConfAndInitWorld(path, games[gameidx])) { @@ -633,7 +642,7 @@ int ModApiMainMenu::l_delete_world(lua_State *L) { int world_id = luaL_checkinteger(L, 1) - 1; std::vector worlds = getAvailableWorlds(); - if (world_id < 0 || world_id >= (int)worlds.size()) { + if (world_id < 0 || world_id >= (int) worlds.size()) { lua_pushstring(L, "Invalid world index"); return 1; } @@ -648,12 +657,12 @@ int ModApiMainMenu::l_delete_world(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_set_topleft_text(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); std::string text; - if (!lua_isnone(L, 1) && !lua_isnil(L, 1)) + if (!lua_isnone(L,1) && !lua_isnil(L,1)) text = luaL_checkstring(L, 1); engine->setTopleftText(text); @@ -676,11 +685,12 @@ int ModApiMainMenu::l_get_mapgen_names(lua_State *L) return 1; } + /******************************************************************************/ int ModApiMainMenu::l_get_modpath(lua_State *L) { std::string modpath = fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM + "mods" + DIR_DELIM); + porting::path_user + DIR_DELIM + "mods" + DIR_DELIM); lua_pushstring(L, modpath.c_str()); return 1; } @@ -689,7 +699,7 @@ int ModApiMainMenu::l_get_modpath(lua_State *L) int ModApiMainMenu::l_get_clientmodpath(lua_State *L) { std::string modpath = fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM + "clientmods" + DIR_DELIM); + porting::path_user + DIR_DELIM + "clientmods" + DIR_DELIM); lua_pushstring(L, modpath.c_str()); return 1; } @@ -698,7 +708,7 @@ int ModApiMainMenu::l_get_clientmodpath(lua_State *L) int ModApiMainMenu::l_get_gamepath(lua_State *L) { std::string gamepath = fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM + "games" + DIR_DELIM); + porting::path_user + DIR_DELIM + "games" + DIR_DELIM); lua_pushstring(L, gamepath.c_str()); return 1; } @@ -707,7 +717,7 @@ int ModApiMainMenu::l_get_gamepath(lua_State *L) int ModApiMainMenu::l_get_texturepath(lua_State *L) { std::string gamepath = fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM + "textures"); + porting::path_user + DIR_DELIM + "textures"); lua_pushstring(L, gamepath.c_str()); return 1; } @@ -715,7 +725,7 @@ int ModApiMainMenu::l_get_texturepath(lua_State *L) int ModApiMainMenu::l_get_texturepath_share(lua_State *L) { std::string gamepath = fs::RemoveRelativePathComponents( - porting::path_share + DIR_DELIM + "textures"); + porting::path_share + DIR_DELIM + "textures"); lua_pushstring(L, gamepath.c_str()); return 1; } @@ -727,8 +737,7 @@ int ModApiMainMenu::l_get_cache_path(lua_State *L) } /******************************************************************************/ -int ModApiMainMenu::l_create_dir(lua_State *L) -{ +int ModApiMainMenu::l_create_dir(lua_State *L) { const char *path = luaL_checkstring(L, 1); if (ModApiMainMenu::mayModifyPath(path)) { @@ -759,37 +768,38 @@ int ModApiMainMenu::l_delete_dir(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_copy_dir(lua_State *L) { - const char *source = luaL_checkstring(L, 1); - const char *destination = luaL_checkstring(L, 2); + const char *source = luaL_checkstring(L, 1); + const char *destination = luaL_checkstring(L, 2); bool keep_source = true; - if ((!lua_isnone(L, 3)) && (!lua_isnil(L, 3))) { - keep_source = readParam(L, 3); + if ((!lua_isnone(L,3)) && + (!lua_isnil(L,3))) { + keep_source = readParam(L,3); } std::string absolute_destination = fs::RemoveRelativePathComponents(destination); std::string absolute_source = fs::RemoveRelativePathComponents(source); if ((ModApiMainMenu::mayModifyPath(absolute_destination))) { - bool retval = fs::CopyDir(absolute_source, absolute_destination); + bool retval = fs::CopyDir(absolute_source,absolute_destination); if (retval && (!keep_source)) { retval &= fs::RecursiveDelete(absolute_source); } - lua_pushboolean(L, retval); + lua_pushboolean(L,retval); return 1; } - lua_pushboolean(L, false); + lua_pushboolean(L,false); return 1; } /******************************************************************************/ int ModApiMainMenu::l_extract_zip(lua_State *L) { - const char *zipfile = luaL_checkstring(L, 1); - const char *destination = luaL_checkstring(L, 2); + const char *zipfile = luaL_checkstring(L, 1); + const char *destination = luaL_checkstring(L, 2); std::string absolute_destination = fs::RemoveRelativePathComponents(destination); @@ -799,7 +809,7 @@ int ModApiMainMenu::l_extract_zip(lua_State *L) io::IFileSystem *fs = RenderingEngine::get_filesystem(); if (!fs->addFileArchive(zipfile, false, false, io::EFAT_ZIP)) { - lua_pushboolean(L, false); + lua_pushboolean(L,false); return 1; } @@ -808,36 +818,33 @@ int ModApiMainMenu::l_extract_zip(lua_State *L) /**********************************************************************/ /* WARNING this is not threadsafe!! */ /**********************************************************************/ - io::IFileArchive *opened_zip = - fs->getFileArchive(fs->getFileArchiveCount() - 1); + io::IFileArchive* opened_zip = + fs->getFileArchive(fs->getFileArchiveCount()-1); - const io::IFileList *files_in_zip = opened_zip->getFileList(); + const io::IFileList* files_in_zip = opened_zip->getFileList(); unsigned int number_of_files = files_in_zip->getFileCount(); - for (unsigned int i = 0; i < number_of_files; i++) { + for (unsigned int i=0; i < number_of_files; i++) { std::string fullpath = destination; fullpath += DIR_DELIM; fullpath += files_in_zip->getFullFileName(i).c_str(); std::string fullpath_dir = fs::RemoveLastPathComponent(fullpath); if (!files_in_zip->isDirectory(i)) { - if (!fs::PathExists(fullpath_dir) && - !fs::CreateAllDirs(fullpath_dir)) { - fs->removeFileArchive( - fs->getFileArchiveCount() - 1); - lua_pushboolean(L, false); + if (!fs::PathExists(fullpath_dir) && !fs::CreateAllDirs(fullpath_dir)) { + fs->removeFileArchive(fs->getFileArchiveCount()-1); + lua_pushboolean(L,false); return 1; } - io::IReadFile *toread = opened_zip->createAndOpenFile(i); + io::IReadFile* toread = opened_zip->createAndOpenFile(i); - FILE *targetfile = fopen(fullpath.c_str(), "wb"); + FILE *targetfile = fopen(fullpath.c_str(),"wb"); if (targetfile == NULL) { - fs->removeFileArchive( - fs->getFileArchiveCount() - 1); - lua_pushboolean(L, false); + fs->removeFileArchive(fs->getFileArchiveCount()-1); + lua_pushboolean(L,false); return 1; } @@ -846,18 +853,14 @@ int ModApiMainMenu::l_extract_zip(lua_State *L) while (total_read < toread->getSize()) { - unsigned int bytes_read = toread->read( - read_buffer, sizeof(read_buffer)); - if ((bytes_read == 0) || - (fwrite(read_buffer, 1, - bytes_read, - targetfile) != - bytes_read)) { + unsigned int bytes_read = + toread->read(read_buffer,sizeof(read_buffer)); + if ((bytes_read == 0 ) || + (fwrite(read_buffer, 1, bytes_read, targetfile) != bytes_read)) + { fclose(targetfile); - fs->removeFileArchive( - fs->getFileArchiveCount() - - 1); - lua_pushboolean(L, false); + fs->removeFileArchive(fs->getFileArchiveCount()-1); + lua_pushboolean(L,false); return 1; } total_read += bytes_read; @@ -865,24 +868,25 @@ int ModApiMainMenu::l_extract_zip(lua_State *L) fclose(targetfile); } + } - fs->removeFileArchive(fs->getFileArchiveCount() - 1); - lua_pushboolean(L, true); + fs->removeFileArchive(fs->getFileArchiveCount()-1); + lua_pushboolean(L,true); return 1; } - lua_pushboolean(L, false); + lua_pushboolean(L,false); return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_mainmenu_path(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); - lua_pushstring(L, engine->getScriptDir().c_str()); + lua_pushstring(L,engine->getScriptDir().c_str()); return 1; } @@ -892,31 +896,25 @@ bool ModApiMainMenu::mayModifyPath(const std::string &path) if (fs::PathStartsWith(path, fs::TempPath())) return true; - if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + - DIR_DELIM "games"))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "games"))) return true; - if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + - DIR_DELIM "mods"))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "mods"))) return true; - if (fs::PathStartsWith(path, - fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM "textures"))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "textures"))) return true; - if (fs::PathStartsWith(path, - fs::RemoveRelativePathComponents( - porting::path_user + DIR_DELIM "worlds"))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "worlds"))) return true; - if (fs::PathStartsWith( - path, fs::RemoveRelativePathComponents(porting::path_cache))) + if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_cache))) return true; return false; } + /******************************************************************************/ int ModApiMainMenu::l_may_modify_path(lua_State *L) { @@ -929,16 +927,21 @@ int ModApiMainMenu::l_may_modify_path(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_show_path_select_dialog(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); - const char *formname = luaL_checkstring(L, 1); - const char *title = luaL_checkstring(L, 2); + const char *formname= luaL_checkstring(L, 1); + const char *title = luaL_checkstring(L, 2); bool is_file_select = readParam(L, 3); - GUIFileSelectMenu *fileOpenMenu = new GUIFileSelectMenu( - RenderingEngine::get_gui_env(), engine->m_parent, -1, - engine->m_menumanager, title, formname, is_file_select); + GUIFileSelectMenu* fileOpenMenu = + new GUIFileSelectMenu(RenderingEngine::get_gui_env(), + engine->m_parent, + -1, + engine->m_menumanager, + title, + formname, + is_file_select); fileOpenMenu->setTextDest(engine->m_buttonhandler); fileOpenMenu->drop(); return 0; @@ -947,36 +950,34 @@ int ModApiMainMenu::l_show_path_select_dialog(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_download_file(lua_State *L) { - const char *url = luaL_checkstring(L, 1); + const char *url = luaL_checkstring(L, 1); const char *target = luaL_checkstring(L, 2); - // check path + //check path std::string absolute_destination = fs::RemoveRelativePathComponents(target); if (ModApiMainMenu::mayModifyPath(absolute_destination)) { - if (GUIEngine::downloadFile(url, absolute_destination)) { - lua_pushboolean(L, true); + if (GUIEngine::downloadFile(url,absolute_destination)) { + lua_pushboolean(L,true); return 1; } } else { errorstream << "DOWNLOAD denied: " << absolute_destination - << " isn't a allowed path" << std::endl; + << " isn't a allowed path" << std::endl; } - lua_pushboolean(L, false); + lua_pushboolean(L,false); return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_video_drivers(lua_State *L) { - std::vector drivers = - RenderingEngine::getSupportedVideoDrivers(); + std::vector drivers = RenderingEngine::getSupportedVideoDrivers(); lua_newtable(L); for (u32 i = 0; i != drivers.size(); i++) { - const char *name = RenderingEngine::getVideoDriverName(drivers[i]); - const char *fname = - RenderingEngine::getVideoDriverFriendlyName(drivers[i]); + const char *name = RenderingEngine::getVideoDriverName(drivers[i]); + const char *fname = RenderingEngine::getVideoDriverFriendlyName(drivers[i]); lua_newtable(L); lua_pushstring(L, name); @@ -993,8 +994,8 @@ int ModApiMainMenu::l_get_video_drivers(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_get_video_modes(lua_State *L) { - std::vector> videomodes = - RenderingEngine::getSupportedVideoModes(); + std::vector > videomodes + = RenderingEngine::getSupportedVideoModes(); lua_newtable(L); for (u32 i = 0; i != videomodes.size(); i++) { @@ -1026,24 +1027,24 @@ int ModApiMainMenu::l_get_screen_info(lua_State *L) { lua_newtable(L); int top = lua_gettop(L); - lua_pushstring(L, "density"); - lua_pushnumber(L, RenderingEngine::getDisplayDensity()); + lua_pushstring(L,"density"); + lua_pushnumber(L,RenderingEngine::getDisplayDensity()); lua_settable(L, top); - lua_pushstring(L, "display_width"); - lua_pushnumber(L, RenderingEngine::getDisplaySize().X); + lua_pushstring(L,"display_width"); + lua_pushnumber(L,RenderingEngine::getDisplaySize().X); lua_settable(L, top); - lua_pushstring(L, "display_height"); - lua_pushnumber(L, RenderingEngine::getDisplaySize().Y); + lua_pushstring(L,"display_height"); + lua_pushnumber(L,RenderingEngine::getDisplaySize().Y); lua_settable(L, top); const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); - lua_pushstring(L, "window_width"); + lua_pushstring(L,"window_width"); lua_pushnumber(L, window_size.X); lua_settable(L, top); - lua_pushstring(L, "window_height"); + lua_pushstring(L,"window_height"); lua_pushnumber(L, window_size.Y); lua_settable(L, top); return 1; @@ -1073,12 +1074,12 @@ int ModApiMainMenu::l_open_url(lua_State *L) /******************************************************************************/ int ModApiMainMenu::l_do_async_callback(lua_State *L) { - GUIEngine *engine = getGuiEngine(L); + GUIEngine* engine = getGuiEngine(L); size_t func_length, param_length; - const char *serialized_func_raw = luaL_checklstring(L, 1, &func_length); + const char* serialized_func_raw = luaL_checklstring(L, 1, &func_length); - const char *serialized_param_raw = luaL_checklstring(L, 2, ¶m_length); + const char* serialized_param_raw = luaL_checklstring(L, 2, ¶m_length); sanity_check(serialized_func_raw != NULL); sanity_check(serialized_param_raw != NULL); @@ -1152,8 +1153,8 @@ void ModApiMainMenu::InitializeAsync(lua_State *L, int top) API_FCT(create_dir); API_FCT(delete_dir); API_FCT(copy_dir); - // API_FCT(extract_zip); //TODO remove dependency to GuiEngine + //API_FCT(extract_zip); //TODO remove dependency to GuiEngine API_FCT(may_modify_path); API_FCT(download_file); - // API_FCT(gettext); (gettext lib isn't threadsafe) + //API_FCT(gettext); (gettext lib isn't threadsafe) } diff --git a/src/script/lua_api/l_mainmenu.h b/src/script/lua_api/l_mainmenu.h index c5875e797..5a16b3bfe 100644 --- a/src/script/lua_api/l_mainmenu.h +++ b/src/script/lua_api/l_mainmenu.h @@ -24,7 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., class AsyncEngine; /** Implementation of lua api support for mainmenu */ -class ModApiMainMenu : public ModApiBase +class ModApiMainMenu: public ModApiBase { private: @@ -42,7 +42,7 @@ private: * @param name name of variable to read * @return integer value of requested variable */ - static int getIntegerData(lua_State *L, std::string name, bool &valid); + static int getIntegerData(lua_State *L, std::string name,bool& valid); /** * read a bool variable from gamedata table within lua stack @@ -50,7 +50,7 @@ private: * @param name name of variable to read * @return bool value of requested variable */ - static int getBoolData(lua_State *L, std::string name, bool &valid); + static int getBoolData(lua_State *L, std::string name,bool& valid); /** * Checks if a path may be modified. Paths in the temp directory or the user @@ -60,7 +60,7 @@ private: */ static bool mayModifyPath(const std::string &path); - // api calls + //api calls static int l_start(lua_State *L); @@ -80,13 +80,13 @@ private: static int l_gettext(lua_State *L); - // packages + //packages static int l_get_games(lua_State *L); static int l_get_content_info(lua_State *L); - // gui + //gui static int l_show_keys_menu(lua_State *L); @@ -108,7 +108,7 @@ private: static int l_get_screen_info(lua_State *L); - // filesystem + //filesystem static int l_get_mainmenu_path(lua_State *L); @@ -140,7 +140,7 @@ private: static int l_get_video_modes(lua_State *L); - // version compatibility + //version compatibility static int l_get_min_supp_proto(lua_State *L); static int l_get_max_supp_proto(lua_State *L); @@ -148,10 +148,12 @@ private: // other static int l_open_url(lua_State *L); + // async static int l_do_async_callback(lua_State *L); public: + /** * initialize this API module * @param L lua stack to initialize @@ -160,4 +162,5 @@ public: static void Initialize(lua_State *L, int top); static void InitializeAsync(lua_State *L, int top); + }; diff --git a/src/script/lua_api/l_mapgen.cpp b/src/script/lua_api/l_mapgen.cpp index d52191a29..834938e56 100644 --- a/src/script/lua_api/l_mapgen.cpp +++ b/src/script/lua_api/l_mapgen.cpp @@ -37,73 +37,81 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "settings.h" #include "log.h" -struct EnumString ModApiMapgen::es_BiomeTerrainType[] = { - {BIOMETYPE_NORMAL, "normal"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_BiomeTerrainType[] = +{ + {BIOMETYPE_NORMAL, "normal"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_DecorationType[] = { - {DECO_SIMPLE, "simple"}, - {DECO_SCHEMATIC, "schematic"}, - {DECO_LSYSTEM, "lsystem"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_DecorationType[] = +{ + {DECO_SIMPLE, "simple"}, + {DECO_SCHEMATIC, "schematic"}, + {DECO_LSYSTEM, "lsystem"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_MapgenObject[] = { - {MGOBJ_VMANIP, "voxelmanip"}, - {MGOBJ_HEIGHTMAP, "heightmap"}, - {MGOBJ_BIOMEMAP, "biomemap"}, - {MGOBJ_HEATMAP, "heatmap"}, - {MGOBJ_HUMIDMAP, "humiditymap"}, - {MGOBJ_GENNOTIFY, "gennotify"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_MapgenObject[] = +{ + {MGOBJ_VMANIP, "voxelmanip"}, + {MGOBJ_HEIGHTMAP, "heightmap"}, + {MGOBJ_BIOMEMAP, "biomemap"}, + {MGOBJ_HEATMAP, "heatmap"}, + {MGOBJ_HUMIDMAP, "humiditymap"}, + {MGOBJ_GENNOTIFY, "gennotify"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_OreType[] = { - {ORE_SCATTER, "scatter"}, - {ORE_SHEET, "sheet"}, - {ORE_PUFF, "puff"}, - {ORE_BLOB, "blob"}, - {ORE_VEIN, "vein"}, - {ORE_STRATUM, "stratum"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_OreType[] = +{ + {ORE_SCATTER, "scatter"}, + {ORE_SHEET, "sheet"}, + {ORE_PUFF, "puff"}, + {ORE_BLOB, "blob"}, + {ORE_VEIN, "vein"}, + {ORE_STRATUM, "stratum"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_Rotation[] = { - {ROTATE_0, "0"}, - {ROTATE_90, "90"}, - {ROTATE_180, "180"}, - {ROTATE_270, "270"}, - {ROTATE_RAND, "random"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_Rotation[] = +{ + {ROTATE_0, "0"}, + {ROTATE_90, "90"}, + {ROTATE_180, "180"}, + {ROTATE_270, "270"}, + {ROTATE_RAND, "random"}, + {0, NULL}, }; -struct EnumString ModApiMapgen::es_SchematicFormatType[] = { - {SCHEM_FMT_HANDLE, "handle"}, - {SCHEM_FMT_MTS, "mts"}, - {SCHEM_FMT_LUA, "lua"}, - {0, NULL}, +struct EnumString ModApiMapgen::es_SchematicFormatType[] = +{ + {SCHEM_FMT_HANDLE, "handle"}, + {SCHEM_FMT_MTS, "mts"}, + {SCHEM_FMT_LUA, "lua"}, + {0, NULL}, }; ObjDef *get_objdef(lua_State *L, int index, const ObjDefManager *objmgr); -Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr); +Biome *get_or_load_biome(lua_State *L, int index, + BiomeManager *biomemgr); Biome *read_biome_def(lua_State *L, int index, const NodeDefManager *ndef); -size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, - std::unordered_set *biome_id_list); +size_t get_biome_list(lua_State *L, int index, + BiomeManager *biomemgr, std::unordered_set *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 *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 *names); bool read_deco_simple(lua_State *L, DecoSimple *deco); bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco); + /////////////////////////////////////////////////////////////////////////////// ObjDef *get_objdef(lua_State *L, int index, const ObjDefManager *objmgr) @@ -124,8 +132,8 @@ ObjDef *get_objdef(lua_State *L, int index, const ObjDefManager *objmgr) /////////////////////////////////////////////////////////////////////////////// -Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *schemmgr, - StringMap *replace_names) +Schematic *get_or_load_schematic(lua_State *L, int index, + SchematicManager *schemmgr, StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; @@ -134,7 +142,8 @@ Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *sche if (schem) return schem; - schem = load_schematic(L, index, schemmgr->getNodeDef(), replace_names); + schem = load_schematic(L, index, schemmgr->getNodeDef(), + replace_names); if (!schem) return NULL; @@ -146,8 +155,9 @@ Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *sche return schem; } + Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, - StringMap *replace_names) + StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; @@ -155,7 +165,8 @@ Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, Schematic *schem = NULL; if (lua_istable(L, index)) { - schem = load_schematic_from_def(L, index, ndef, replace_names); + schem = load_schematic_from_def(L, index, ndef, + replace_names); if (!schem) { delete schem; return NULL; @@ -167,10 +178,10 @@ Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, std::string filepath = lua_tostring(L, index); if (!fs::IsPathAbsolute(filepath)) - filepath = ModApiBase::getCurrentModPath(L) + DIR_DELIM + - filepath; + filepath = ModApiBase::getCurrentModPath(L) + DIR_DELIM + filepath; - if (!schem->loadSchematicFromFile(filepath, ndef, replace_names)) { + if (!schem->loadSchematicFromFile(filepath, ndef, + replace_names)) { delete schem; return NULL; } @@ -179,8 +190,9 @@ Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, return schem; } -Schematic *load_schematic_from_def(lua_State *L, int index, const NodeDefManager *ndef, - StringMap *replace_names) + +Schematic *load_schematic_from_def(lua_State *L, int index, + const NodeDefManager *ndef, StringMap *replace_names) { Schematic *schem = SchematicManager::create(SCHEMATIC_NORMAL); @@ -195,8 +207,7 @@ Schematic *load_schematic_from_def(lua_State *L, int index, const NodeDefManager if (replace_names) { for (size_t i = 0; i != num_nodes; i++) { - StringMap::iterator it = - replace_names->find(schem->m_nodenames[i]); + StringMap::iterator it = replace_names->find(schem->m_nodenames[i]); if (it != replace_names->end()) schem->m_nodenames[i] = it->second; } @@ -208,8 +219,9 @@ Schematic *load_schematic_from_def(lua_State *L, int index, const NodeDefManager return schem; } -bool read_schematic_def(lua_State *L, int index, Schematic *schem, - std::vector *names) + +bool read_schematic_def(lua_State *L, int index, + Schematic *schem, std::vector *names) { if (!lua_istable(L, index)) return false; @@ -239,21 +251,19 @@ bool read_schematic_def(lua_State *L, int index, Schematic *schem, //// Read name std::string name; if (!getstringfield(L, -1, "name", name)) - throw LuaError("Schematic data definition with missing name " - "field"); + throw LuaError("Schematic data definition with missing name field"); //// Read param1/prob u8 param1; if (!getintfield(L, -1, "param1", param1) && - !getintfield(L, -1, "prob", param1)) + !getintfield(L, -1, "prob", param1)) param1 = MTSCHEM_PROB_ALWAYS_OLD; //// Read param2 u8 param2 = getintfield_default(L, -1, "param2", 0); //// Find or add new nodename-to-ID mapping - std::unordered_map::iterator it = - name_id_map.find(name); + std::unordered_map::iterator it = name_id_map.find(name); content_t name_index; if (it != name_id_map.end()) { name_index = it->second; @@ -274,14 +284,14 @@ bool read_schematic_def(lua_State *L, int index, Schematic *schem, if (i != numnodes) { errorstream << "read_schematic_def: incorrect number of " - "nodes provided in raw schematic data (got " - << i << ", expected " << numnodes << ")." << std::endl; + "nodes provided in raw schematic data (got " << i << + ", expected " << numnodes << ")." << std::endl; return false; } //// Get Y-slice probability values (if present) schem->slice_probs = new u8[size.Y]; - for (i = 0; i != (u32)size.Y; i++) + for (i = 0; i != (u32) size.Y; i++) schem->slice_probs[i] = MTSCHEM_PROB_ALWAYS; lua_getfield(L, index, "yslice_prob"); @@ -289,8 +299,7 @@ bool read_schematic_def(lua_State *L, int index, Schematic *schem, for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) { u16 ypos; if (!getintfield(L, -1, "ypos", ypos) || (ypos >= size.Y) || - !getintfield(L, -1, "prob", - schem->slice_probs[ypos])) + !getintfield(L, -1, "prob", schem->slice_probs[ypos])) continue; schem->slice_probs[ypos] >>= 1; @@ -300,6 +309,7 @@ bool read_schematic_def(lua_State *L, int index, Schematic *schem, return true; } + void read_schematic_replacements(lua_State *L, int index, StringMap *replace_names) { if (index < 0) @@ -313,25 +323,21 @@ void read_schematic_replacements(lua_State *L, int index, StringMap *replace_nam if (lua_istable(L, -1)) { // Old {{"x", "y"}, ...} format lua_rawgeti(L, -1, 1); if (!lua_isstring(L, -1)) - throw LuaError("schematics: replace_from field is not a " - "string"); + throw LuaError("schematics: replace_from field is not a string"); replace_from = lua_tostring(L, -1); lua_pop(L, 1); lua_rawgeti(L, -1, 2); if (!lua_isstring(L, -1)) - throw LuaError("schematics: replace_to field is not a " - "string"); + throw LuaError("schematics: replace_to field is not a string"); replace_to = lua_tostring(L, -1); lua_pop(L, 1); } else { // New {x = "y", ...} format if (!lua_isstring(L, -2)) - throw LuaError("schematics: replace_from field is not a " - "string"); + throw LuaError("schematics: replace_from field is not a string"); replace_from = lua_tostring(L, -2); if (!lua_isstring(L, -1)) - throw LuaError("schematics: replace_to field is not a " - "string"); + throw LuaError("schematics: replace_to field is not a string"); replace_to = lua_tostring(L, -1); } @@ -363,41 +369,42 @@ Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr) return biome; } + Biome *read_biome_def(lua_State *L, int index, const NodeDefManager *ndef) { if (!lua_istable(L, index)) return NULL; BiomeType biometype = (BiomeType)getenumfield(L, index, "type", - ModApiMapgen::es_BiomeTerrainType, BIOMETYPE_NORMAL); + ModApiMapgen::es_BiomeTerrainType, BIOMETYPE_NORMAL); Biome *b = BiomeManager::create(biometype); - b->name = getstringfield_default(L, index, "name", ""); - b->depth_top = getintfield_default(L, index, "depth_top", 0); - b->depth_filler = getintfield_default(L, index, "depth_filler", -31000); - b->depth_water_top = getintfield_default(L, index, "depth_water_top", 0); - b->depth_riverbed = getintfield_default(L, index, "depth_riverbed", 0); - b->heat_point = getfloatfield_default(L, index, "heat_point", 0.f); - b->humidity_point = getfloatfield_default(L, index, "humidity_point", 0.f); - b->vertical_blend = getintfield_default(L, index, "vertical_blend", 0); - b->flags = 0; // reserved + b->name = getstringfield_default(L, index, "name", ""); + b->depth_top = getintfield_default(L, index, "depth_top", 0); + b->depth_filler = getintfield_default(L, index, "depth_filler", -31000); + b->depth_water_top = getintfield_default(L, index, "depth_water_top", 0); + b->depth_riverbed = getintfield_default(L, index, "depth_riverbed", 0); + b->heat_point = getfloatfield_default(L, index, "heat_point", 0.f); + b->humidity_point = getfloatfield_default(L, index, "humidity_point", 0.f); + b->vertical_blend = getintfield_default(L, index, "vertical_blend", 0); + b->flags = 0; // reserved b->min_pos = getv3s16field_default( - L, index, "min_pos", v3s16(-31000, -31000, -31000)); + L, index, "min_pos", v3s16(-31000, -31000, -31000)); getintfield(L, index, "y_min", b->min_pos.Y); b->max_pos = getv3s16field_default( - L, index, "max_pos", v3s16(31000, 31000, 31000)); + L, index, "max_pos", v3s16(31000, 31000, 31000)); getintfield(L, index, "y_max", b->max_pos.Y); std::vector &nn = b->m_nodenames; - nn.push_back(getstringfield_default(L, index, "node_top", "")); - nn.push_back(getstringfield_default(L, index, "node_filler", "")); - nn.push_back(getstringfield_default(L, index, "node_stone", "")); - nn.push_back(getstringfield_default(L, index, "node_water_top", "")); - nn.push_back(getstringfield_default(L, index, "node_water", "")); - nn.push_back(getstringfield_default(L, index, "node_river_water", "")); - nn.push_back(getstringfield_default(L, index, "node_riverbed", "")); - nn.push_back(getstringfield_default(L, index, "node_dust", "")); + nn.push_back(getstringfield_default(L, index, "node_top", "")); + nn.push_back(getstringfield_default(L, index, "node_filler", "")); + nn.push_back(getstringfield_default(L, index, "node_stone", "")); + nn.push_back(getstringfield_default(L, index, "node_water_top", "")); + nn.push_back(getstringfield_default(L, index, "node_water", "")); + nn.push_back(getstringfield_default(L, index, "node_river_water", "")); + nn.push_back(getstringfield_default(L, index, "node_riverbed", "")); + nn.push_back(getstringfield_default(L, index, "node_dust", "")); size_t nnames = getstringlistfield(L, index, "node_cave_liquid", &nn); // If no cave liquids defined, set list to "ignore" to trigger old hardcoded @@ -408,16 +415,17 @@ Biome *read_biome_def(lua_State *L, int index, const NodeDefManager *ndef) } b->m_nnlistsizes.push_back(nnames); - nn.push_back(getstringfield_default(L, index, "node_dungeon", "")); - nn.push_back(getstringfield_default(L, index, "node_dungeon_alt", "")); + nn.push_back(getstringfield_default(L, index, "node_dungeon", "")); + nn.push_back(getstringfield_default(L, index, "node_dungeon_alt", "")); nn.push_back(getstringfield_default(L, index, "node_dungeon_stair", "")); ndef->pendNodeResolve(b); return b; } -size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, - std::unordered_set *biome_id_list) + +size_t get_biome_list(lua_State *L, int index, + BiomeManager *biomemgr, std::unordered_set *biome_id_list) { if (index < 0) index = lua_gettop(L) + 1 + index; @@ -436,9 +444,8 @@ size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, Biome *biome = get_or_load_biome(L, index, biomemgr); if (!biome) { infostream << "get_biome_list: failed to get biome '" - << (lua_isstring(L, index) ? lua_tostring(L, index) - : "") - << "'." << std::endl; + << (lua_isstring(L, index) ? lua_tostring(L, index) : "") + << "'." << std::endl; return 1; } @@ -456,8 +463,8 @@ size_t get_biome_list(lua_State *L, int index, BiomeManager *biomemgr, if (!biome) { fail_count++; infostream << "get_biome_list: failed to get biome '" - << (lua_isstring(L, -1) ? lua_tostring(L, -1) : "") - << "'" << std::endl; + << (lua_isstring(L, -1) ? lua_tostring(L, -1) : "") + << "'" << std::endl; continue; } @@ -492,6 +499,7 @@ int ModApiMapgen::l_get_biome_id(lua_State *L) return 1; } + // get_biome_name(biome_id) // returns the biome name string int ModApiMapgen::l_get_biome_name(lua_State *L) @@ -510,6 +518,7 @@ int ModApiMapgen::l_get_biome_name(lua_State *L) return 1; } + // get_heat(pos) // returns the heat at the position int ModApiMapgen::l_get_heat(lua_State *L) @@ -522,11 +531,12 @@ int ModApiMapgen::l_get_heat(lua_State *L) NoiseParams np_heat_blend; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; - if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat", &np_heat) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_heat_blend", &np_heat_blend)) + if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat", + &np_heat) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat_blend", + &np_heat_blend)) return 0; std::string value; @@ -547,6 +557,7 @@ int ModApiMapgen::l_get_heat(lua_State *L) return 1; } + // get_humidity(pos) // returns the humidity at the position int ModApiMapgen::l_get_humidity(lua_State *L) @@ -559,12 +570,12 @@ int ModApiMapgen::l_get_humidity(lua_State *L) NoiseParams np_humidity_blend; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; - if (!settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_humidity", &np_humidity) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_humidity_blend", &np_humidity_blend)) + if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity", + &np_humidity) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity_blend", + &np_humidity_blend)) return 0; std::string value; @@ -578,14 +589,15 @@ int ModApiMapgen::l_get_humidity(lua_State *L) if (!bmgr) return 0; - float humidity = bmgr->getHumidityAtPosOriginal( - pos, np_humidity, np_humidity_blend, seed); + float humidity = bmgr->getHumidityAtPosOriginal(pos, np_humidity, + np_humidity_blend, seed); lua_pushnumber(L, humidity); return 1; } + // get_biome_data(pos) // returns a table containing the biome id, heat and humidity at the position int ModApiMapgen::l_get_biome_data(lua_State *L) @@ -600,15 +612,16 @@ int ModApiMapgen::l_get_biome_data(lua_State *L) NoiseParams np_humidity_blend; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; - - if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat", &np_heat) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_heat_blend", &np_heat_blend) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_humidity", &np_humidity) || - !settingsmgr->getMapSettingNoiseParams( - "mg_biome_np_humidity_blend", &np_humidity_blend)) + getServer(L)->getEmergeManager()->map_settings_mgr; + + if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat", + &np_heat) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat_blend", + &np_heat_blend) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity", + &np_humidity) || + !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity_blend", + &np_humidity_blend)) return 0; std::string value; @@ -626,8 +639,8 @@ int ModApiMapgen::l_get_biome_data(lua_State *L) if (!heat) return 0; - float humidity = bmgr->getHumidityAtPosOriginal( - pos, np_humidity, np_humidity_blend, seed); + float humidity = bmgr->getHumidityAtPosOriginal(pos, np_humidity, + np_humidity_blend, seed); if (!humidity) return 0; @@ -649,6 +662,7 @@ int ModApiMapgen::l_get_biome_data(lua_State *L) return 1; } + // get_mapgen_object(objectname) // returns the requested object used during map generation int ModApiMapgen::l_get_mapgen_object(lua_State *L) @@ -742,7 +756,7 @@ int ModApiMapgen::l_get_mapgen_object(lua_State *L) return 1; } case MGOBJ_GENNOTIFY: { - std::map> event_map; + std::map >event_map; mg->gennotify.getEvents(event_map); @@ -765,6 +779,7 @@ int ModApiMapgen::l_get_mapgen_object(lua_State *L) return 0; } + // get_spawn_level(x = num, z = num) int ModApiMapgen::l_get_spawn_level(lua_State *L) { @@ -785,17 +800,18 @@ int ModApiMapgen::l_get_spawn_level(lua_State *L) return 1; } + int ModApiMapgen::l_get_mapgen_params(lua_State *L) { NO_MAP_LOCK_REQUIRED; log_deprecated(L, "get_mapgen_params is deprecated; " - "use get_mapgen_setting instead"); + "use get_mapgen_setting instead"); std::string value; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; lua_newtable(L); @@ -825,6 +841,7 @@ int ModApiMapgen::l_get_mapgen_params(lua_State *L) return 1; } + // set_mapgen_params(params) // set mapgen parameters int ModApiMapgen::l_set_mapgen_params(lua_State *L) @@ -832,18 +849,17 @@ int ModApiMapgen::l_set_mapgen_params(lua_State *L) NO_MAP_LOCK_REQUIRED; log_deprecated(L, "set_mapgen_params is deprecated; " - "use set_mapgen_setting instead"); + "use set_mapgen_setting instead"); if (!lua_istable(L, 1)) return 0; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; lua_getfield(L, 1, "mgname"); if (lua_isstring(L, -1)) - settingsmgr->setMapSetting( - "mg_name", readParam(L, -1), true); + settingsmgr->setMapSetting("mg_name", readParam(L, -1), true); lua_getfield(L, 1, "seed"); if (lua_isnumber(L, -1)) @@ -851,21 +867,18 @@ int ModApiMapgen::l_set_mapgen_params(lua_State *L) lua_getfield(L, 1, "water_level"); if (lua_isnumber(L, -1)) - settingsmgr->setMapSetting( - "water_level", readParam(L, -1), true); + settingsmgr->setMapSetting("water_level", readParam(L, -1), true); lua_getfield(L, 1, "chunksize"); if (lua_isnumber(L, -1)) - settingsmgr->setMapSetting( - "chunksize", readParam(L, -1), true); + settingsmgr->setMapSetting("chunksize", readParam(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(L, -1), true); + settingsmgr->setMapSetting("mg_flags", readParam(L, -1), true); return 0; } @@ -877,7 +890,7 @@ int ModApiMapgen::l_get_mapgen_setting(lua_State *L) std::string value; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); if (!settingsmgr->getMapSetting(name, &value)) @@ -894,7 +907,7 @@ int ModApiMapgen::l_get_mapgen_setting_noiseparams(lua_State *L) NoiseParams np; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); if (!settingsmgr->getMapSettingNoiseParams(name, &np)) @@ -911,20 +924,21 @@ int ModApiMapgen::l_set_mapgen_setting(lua_State *L) NO_MAP_LOCK_REQUIRED; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; - const char *name = luaL_checkstring(L, 1); - const char *value = luaL_checkstring(L, 2); + const char *name = luaL_checkstring(L, 1); + const char *value = luaL_checkstring(L, 2); bool override_meta = readParam(L, 3, false); if (!settingsmgr->setMapSetting(name, value, override_meta)) { - errorstream << "set_mapgen_setting: cannot set '" << name - << "' after initialization" << std::endl; + errorstream << "set_mapgen_setting: cannot set '" + << name << "' after initialization" << std::endl; } return 0; } + // set_mapgen_setting_noiseparams(name, noiseparams, set_default) // set mapgen config values for noise parameters int ModApiMapgen::l_set_mapgen_setting_noiseparams(lua_State *L) @@ -932,27 +946,28 @@ int ModApiMapgen::l_set_mapgen_setting_noiseparams(lua_State *L) NO_MAP_LOCK_REQUIRED; MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; + getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); NoiseParams np; if (!read_noiseparams(L, 2, &np)) { errorstream << "set_mapgen_setting_noiseparams: cannot set '" << name - << "'; invalid noiseparams table" << std::endl; + << "'; invalid noiseparams table" << std::endl; return 0; } bool override_meta = readParam(L, 3, false); if (!settingsmgr->setMapSettingNoiseParams(name, &np, override_meta)) { - errorstream << "set_mapgen_setting_noiseparams: cannot set '" << name - << "' after initialization" << std::endl; + errorstream << "set_mapgen_setting_noiseparams: cannot set '" + << name << "' after initialization" << std::endl; } return 0; } + // set_noiseparams(name, noiseparams, set_default) // set global config values for noise parameters int ModApiMapgen::l_set_noiseparams(lua_State *L) @@ -964,7 +979,7 @@ int ModApiMapgen::l_set_noiseparams(lua_State *L) NoiseParams np; if (!read_noiseparams(L, 2, &np)) { errorstream << "set_noiseparams: cannot set '" << name - << "'; invalid noiseparams table" << std::endl; + << "'; invalid noiseparams table" << std::endl; return 0; } @@ -975,6 +990,7 @@ int ModApiMapgen::l_set_noiseparams(lua_State *L) return 0; } + // get_noiseparams(name) int ModApiMapgen::l_get_noiseparams(lua_State *L) { @@ -990,6 +1006,7 @@ int ModApiMapgen::l_get_noiseparams(lua_State *L) return 1; } + // set_gen_notify(flags, {deco_id_table}) int ModApiMapgen::l_set_gen_notify(lua_State *L) { @@ -1007,8 +1024,7 @@ int ModApiMapgen::l_set_gen_notify(lua_State *L) lua_pushnil(L); while (lua_next(L, 2)) { if (lua_isnumber(L, -1)) - emerge->gen_notify_on_deco_ids.insert( - (u32)lua_tonumber(L, -1)); + emerge->gen_notify_on_deco_ids.insert((u32)lua_tonumber(L, -1)); lua_pop(L, 1); } } @@ -1016,6 +1032,7 @@ int ModApiMapgen::l_set_gen_notify(lua_State *L) return 0; } + // get_gen_notify() int ModApiMapgen::l_get_gen_notify(lua_State *L) { @@ -1023,7 +1040,7 @@ int ModApiMapgen::l_get_gen_notify(lua_State *L) EmergeManager *emerge = getServer(L)->getEmergeManager(); push_flags_string(L, flagdesc_gennotify, emerge->gen_notify_on, - emerge->gen_notify_on); + emerge->gen_notify_on); lua_newtable(L); int i = 1; @@ -1034,6 +1051,7 @@ int ModApiMapgen::l_get_gen_notify(lua_State *L) return 2; } + // get_decoration_id(decoration_name) // returns the decoration ID as used in gennotify int ModApiMapgen::l_get_decoration_id(lua_State *L) @@ -1045,7 +1063,7 @@ int ModApiMapgen::l_get_decoration_id(lua_State *L) return 0; const DecorationManager *dmgr = - getServer(L)->getEmergeManager()->getDecorationManager(); + getServer(L)->getEmergeManager()->getDecorationManager(); if (!dmgr) return 0; @@ -1060,6 +1078,7 @@ int ModApiMapgen::l_get_decoration_id(lua_State *L) return 1; } + // register_biome({lots of stuff}) int ModApiMapgen::l_register_biome(lua_State *L) { @@ -1085,6 +1104,7 @@ int ModApiMapgen::l_register_biome(lua_State *L) return 1; } + // register_decoration({lots of stuff}) int ModApiMapgen::l_register_decoration(lua_State *L) { @@ -1093,33 +1113,32 @@ int ModApiMapgen::l_register_decoration(lua_State *L) int index = 1; luaL_checktype(L, index, LUA_TTABLE); - const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); + const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); EmergeManager *emerge = getServer(L)->getEmergeManager(); DecorationManager *decomgr = emerge->getWritableDecorationManager(); - BiomeManager *biomemgr = emerge->getWritableBiomeManager(); + BiomeManager *biomemgr = emerge->getWritableBiomeManager(); SchematicManager *schemmgr = emerge->getWritableSchematicManager(); - enum DecorationType decotype = (DecorationType)getenumfield( - L, index, "deco_type", es_DecorationType, -1); + enum DecorationType decotype = (DecorationType)getenumfield(L, index, + "deco_type", es_DecorationType, -1); Decoration *deco = decomgr->create(decotype); if (!deco) { errorstream << "register_decoration: decoration placement type " - << decotype << " not implemented" << std::endl; + << decotype << " not implemented" << std::endl; return 0; } - deco->name = getstringfield_default(L, index, "name", ""); - deco->fill_ratio = getfloatfield_default(L, index, "fill_ratio", 0.02); - deco->y_min = getintfield_default(L, index, "y_min", -31000); - deco->y_max = getintfield_default(L, index, "y_max", 31000); - deco->nspawnby = getintfield_default(L, index, "num_spawn_by", -1); + deco->name = getstringfield_default(L, index, "name", ""); + deco->fill_ratio = getfloatfield_default(L, index, "fill_ratio", 0.02); + deco->y_min = getintfield_default(L, index, "y_min", -31000); + deco->y_max = getintfield_default(L, index, "y_max", 31000); + deco->nspawnby = getintfield_default(L, index, "num_spawn_by", -1); deco->place_offset_y = getintfield_default(L, index, "place_offset_y", 0); - deco->sidelen = getintfield_default(L, index, "sidelen", 8); + deco->sidelen = getintfield_default(L, index, "sidelen", 8); if (deco->sidelen <= 0) { errorstream << "register_decoration: sidelen must be " - "greater than 0" - << std::endl; + "greater than 0" << std::endl; delete deco; return 0; } @@ -1140,8 +1159,7 @@ int ModApiMapgen::l_register_decoration(lua_State *L) //// Get biomes associated with this decoration (if any) lua_getfield(L, index, "biomes"); if (get_biome_list(L, -1, biomemgr, &deco->biomes)) - infostream << "register_decoration: couldn't get all biomes " - << std::endl; + infostream << "register_decoration: couldn't get all biomes " << std::endl; lua_pop(L, 1); //// Get node name(s) to 'spawn by' @@ -1149,8 +1167,7 @@ int ModApiMapgen::l_register_decoration(lua_State *L) deco->m_nnlistsizes.push_back(nnames); if (nnames == 0 && deco->nspawnby != -1) { errorstream << "register_decoration: no spawn_by nodes defined," - " but num_spawn_by specified" - << std::endl; + " but num_spawn_by specified" << std::endl; } //// Handle decoration type-specific parameters @@ -1183,19 +1200,19 @@ int ModApiMapgen::l_register_decoration(lua_State *L) return 1; } + bool read_deco_simple(lua_State *L, DecoSimple *deco) { int index = 1; int param2; int param2_max; - deco->deco_height = getintfield_default(L, index, "height", 1); + deco->deco_height = getintfield_default(L, index, "height", 1); deco->deco_height_max = getintfield_default(L, index, "height_max", 0); if (deco->deco_height <= 0) { errorstream << "register_decoration: simple decoration height" - " must be greater than 0" - << std::endl; + " must be greater than 0" << std::endl; return false; } @@ -1204,8 +1221,7 @@ bool read_deco_simple(lua_State *L, DecoSimple *deco) if (nnames == 0) { errorstream << "register_decoration: no decoration nodes " - "defined" - << std::endl; + "defined" << std::endl; return false; } @@ -1213,9 +1229,8 @@ bool read_deco_simple(lua_State *L, DecoSimple *deco) param2_max = getintfield_default(L, index, "param2_max", 0); if (param2 < 0 || param2 > 255 || param2_max < 0 || param2_max > 255) { - errorstream << "register_decoration: param2 or param2_max out of bounds " - "(0-255)" - << std::endl; + errorstream << "register_decoration: param2 or param2_max out of bounds (0-255)" + << std::endl; return false; } @@ -1225,12 +1240,13 @@ bool read_deco_simple(lua_State *L, DecoSimple *deco) return true; } + bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco) { int index = 1; - deco->rotation = (Rotation)getenumfield( - L, index, "rotation", ModApiMapgen::es_Rotation, ROTATE_0); + deco->rotation = (Rotation)getenumfield(L, index, "rotation", + ModApiMapgen::es_Rotation, ROTATE_0); StringMap replace_names; lua_getfield(L, index, "replacements"); @@ -1246,6 +1262,7 @@ bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic return schem != NULL; } + // register_ore({lots of stuff}) int ModApiMapgen::l_register_ore(lua_State *L) { @@ -1256,29 +1273,28 @@ int ModApiMapgen::l_register_ore(lua_State *L) const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); EmergeManager *emerge = getServer(L)->getEmergeManager(); - BiomeManager *bmgr = emerge->getWritableBiomeManager(); - OreManager *oremgr = emerge->getWritableOreManager(); + BiomeManager *bmgr = emerge->getWritableBiomeManager(); + OreManager *oremgr = emerge->getWritableOreManager(); - enum OreType oretype = (OreType)getenumfield( - L, index, "ore_type", es_OreType, ORE_SCATTER); + enum OreType oretype = (OreType)getenumfield(L, index, + "ore_type", es_OreType, ORE_SCATTER); Ore *ore = oremgr->create(oretype); if (!ore) { - errorstream << "register_ore: ore_type " << oretype - << " not implemented\n"; + errorstream << "register_ore: ore_type " << oretype << " not implemented\n"; return 0; } - ore->name = getstringfield_default(L, index, "name", ""); - ore->ore_param2 = (u8)getintfield_default(L, index, "ore_param2", 0); + ore->name = getstringfield_default(L, index, "name", ""); + ore->ore_param2 = (u8)getintfield_default(L, index, "ore_param2", 0); ore->clust_scarcity = getintfield_default(L, index, "clust_scarcity", 1); ore->clust_num_ores = getintfield_default(L, index, "clust_num_ores", 1); - ore->clust_size = getintfield_default(L, index, "clust_size", 0); - ore->noise = NULL; - ore->flags = 0; + ore->clust_size = getintfield_default(L, index, "clust_size", 0); + ore->noise = NULL; + ore->flags = 0; //// Get noise_threshold warn_if_field_exists(L, index, "noise_threshhold", - "Deprecated: new name is \"noise_threshold\"."); + "Deprecated: new name is \"noise_threshold\"."); float nthresh; if (!getfloatfield(L, index, "noise_threshold", nthresh) && @@ -1287,25 +1303,24 @@ int ModApiMapgen::l_register_ore(lua_State *L) ore->nthresh = nthresh; //// Get y_min/y_max - warn_if_field_exists( - L, index, "height_min", "Deprecated: new name is \"y_min\"."); - warn_if_field_exists( - L, index, "height_max", "Deprecated: new name is \"y_max\"."); + warn_if_field_exists(L, index, "height_min", + "Deprecated: new name is \"y_min\"."); + warn_if_field_exists(L, index, "height_max", + "Deprecated: new name is \"y_max\"."); int ymin, ymax; if (!getintfield(L, index, "y_min", ymin) && - !getintfield(L, index, "height_min", ymin)) + !getintfield(L, index, "height_min", ymin)) ymin = -31000; if (!getintfield(L, index, "y_max", ymax) && - !getintfield(L, index, "height_max", ymax)) + !getintfield(L, index, "height_max", ymax)) ymax = 31000; ore->y_min = ymin; ore->y_max = ymax; if (ore->clust_scarcity <= 0 || ore->clust_num_ores <= 0) { errorstream << "register_ore: clust_scarcity and clust_num_ores" - "must be greater than 0" - << std::endl; + "must be greater than 0" << std::endl; delete ore; return 0; } @@ -1325,8 +1340,7 @@ int ModApiMapgen::l_register_ore(lua_State *L) ore->flags |= OREFLAG_USE_NOISE; } else if (ore->NEEDS_NOISE) { errorstream << "register_ore: specified ore type requires valid " - "'noise_params' parameter" - << std::endl; + "'noise_params' parameter" << std::endl; delete ore; return 0; } @@ -1334,54 +1348,54 @@ int ModApiMapgen::l_register_ore(lua_State *L) //// Get type-specific parameters switch (oretype) { - case ORE_SHEET: { - OreSheet *oresheet = (OreSheet *)ore; + case ORE_SHEET: { + OreSheet *oresheet = (OreSheet *)ore; - oresheet->column_height_min = - getintfield_default(L, index, "column_height_min", 1); - oresheet->column_height_max = getintfield_default( - L, index, "column_height_max", ore->clust_size); - oresheet->column_midpoint_factor = getfloatfield_default( - L, index, "column_midpoint_factor", 0.5f); + oresheet->column_height_min = getintfield_default(L, index, + "column_height_min", 1); + oresheet->column_height_max = getintfield_default(L, index, + "column_height_max", ore->clust_size); + oresheet->column_midpoint_factor = getfloatfield_default(L, index, + "column_midpoint_factor", 0.5f); - break; - } - case ORE_PUFF: { - OrePuff *orepuff = (OrePuff *)ore; + break; + } + case ORE_PUFF: { + OrePuff *orepuff = (OrePuff *)ore; - lua_getfield(L, index, "np_puff_top"); - read_noiseparams(L, -1, &orepuff->np_puff_top); - lua_pop(L, 1); + lua_getfield(L, index, "np_puff_top"); + read_noiseparams(L, -1, &orepuff->np_puff_top); + lua_pop(L, 1); - lua_getfield(L, index, "np_puff_bottom"); - read_noiseparams(L, -1, &orepuff->np_puff_bottom); - lua_pop(L, 1); + lua_getfield(L, index, "np_puff_bottom"); + read_noiseparams(L, -1, &orepuff->np_puff_bottom); + lua_pop(L, 1); - break; - } - case ORE_VEIN: { - OreVein *orevein = (OreVein *)ore; + break; + } + case ORE_VEIN: { + OreVein *orevein = (OreVein *)ore; - orevein->random_factor = - getfloatfield_default(L, index, "random_factor", 1.f); + orevein->random_factor = getfloatfield_default(L, index, + "random_factor", 1.f); - break; - } - case ORE_STRATUM: { - OreStratum *orestratum = (OreStratum *)ore; + break; + } + case ORE_STRATUM: { + OreStratum *orestratum = (OreStratum *)ore; - lua_getfield(L, index, "np_stratum_thickness"); - if (read_noiseparams(L, -1, &orestratum->np_stratum_thickness)) - ore->flags |= OREFLAG_USE_NOISE2; - lua_pop(L, 1); + lua_getfield(L, index, "np_stratum_thickness"); + if (read_noiseparams(L, -1, &orestratum->np_stratum_thickness)) + ore->flags |= OREFLAG_USE_NOISE2; + lua_pop(L, 1); - orestratum->stratum_thickness = - getintfield_default(L, index, "stratum_thickness", 8); + orestratum->stratum_thickness = getintfield_default(L, index, + "stratum_thickness", 8); - break; - } - default: - break; + break; + } + default: + break; } ObjDefHandle handle = oremgr->add(ore); @@ -1401,19 +1415,21 @@ int ModApiMapgen::l_register_ore(lua_State *L) return 1; } + // register_schematic({schematic}, replacements={}) int ModApiMapgen::l_register_schematic(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *schemmgr = - getServer(L)->getEmergeManager()->getWritableSchematicManager(); + getServer(L)->getEmergeManager()->getWritableSchematicManager(); StringMap replace_names; if (lua_istable(L, 2)) read_schematic_replacements(L, 2, &replace_names); - Schematic *schem = load_schematic(L, 1, schemmgr->getNodeDef(), &replace_names); + Schematic *schem = load_schematic(L, 1, schemmgr->getNodeDef(), + &replace_names); if (!schem) return 0; @@ -1427,48 +1443,55 @@ int ModApiMapgen::l_register_schematic(lua_State *L) return 1; } + // clear_registered_biomes() int ModApiMapgen::l_clear_registered_biomes(lua_State *L) { NO_MAP_LOCK_REQUIRED; - BiomeManager *bmgr = getServer(L)->getEmergeManager()->getWritableBiomeManager(); + BiomeManager *bmgr = + getServer(L)->getEmergeManager()->getWritableBiomeManager(); bmgr->clear(); return 0; } + // clear_registered_decorations() int ModApiMapgen::l_clear_registered_decorations(lua_State *L) { NO_MAP_LOCK_REQUIRED; DecorationManager *dmgr = - getServer(L)->getEmergeManager()->getWritableDecorationManager(); + getServer(L)->getEmergeManager()->getWritableDecorationManager(); dmgr->clear(); return 0; } + // clear_registered_ores() int ModApiMapgen::l_clear_registered_ores(lua_State *L) { NO_MAP_LOCK_REQUIRED; - OreManager *omgr = getServer(L)->getEmergeManager()->getWritableOreManager(); + OreManager *omgr = + getServer(L)->getEmergeManager()->getWritableOreManager(); omgr->clear(); return 0; } + // clear_registered_schematics() int ModApiMapgen::l_clear_registered_schematics(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *smgr = - getServer(L)->getEmergeManager()->getWritableSchematicManager(); + getServer(L)->getEmergeManager()->getWritableSchematicManager(); smgr->clear(); return 0; } + // generate_ores(vm, p1, p2, [ore_id]) int ModApiMapgen::l_generate_ores(lua_State *L) { @@ -1478,15 +1501,13 @@ int ModApiMapgen::l_generate_ores(lua_State *L) Mapgen mg; mg.seed = emerge->mgparams->seed; - mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; + mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; mg.ndef = getServer(L)->getNodeDefManager(); - v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) - : mg.vm->m_area.MinEdge + - v3s16(1, 1, 1) * MAP_BLOCKSIZE; - v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) - : mg.vm->m_area.MaxEdge - - v3s16(1, 1, 1) * MAP_BLOCKSIZE; + v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : + mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE; + v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : + mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE; sortBoxVerticies(pmin, pmax); u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed); @@ -1496,6 +1517,7 @@ int ModApiMapgen::l_generate_ores(lua_State *L) return 0; } + // generate_decorations(vm, p1, p2, [deco_id]) int ModApiMapgen::l_generate_decorations(lua_State *L) { @@ -1505,15 +1527,13 @@ int ModApiMapgen::l_generate_decorations(lua_State *L) Mapgen mg; mg.seed = emerge->mgparams->seed; - mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; + mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; mg.ndef = getServer(L)->getNodeDefManager(); - v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) - : mg.vm->m_area.MinEdge + - v3s16(1, 1, 1) * MAP_BLOCKSIZE; - v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) - : mg.vm->m_area.MaxEdge - - v3s16(1, 1, 1) * MAP_BLOCKSIZE; + v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : + mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE; + v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : + mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE; sortBoxVerticies(pmin, pmax); u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed); @@ -1523,6 +1543,7 @@ int ModApiMapgen::l_generate_decorations(lua_State *L) return 0; } + // create_schematic(p1, p2, probability_list, filename, y_slice_prob_list) int ModApiMapgen::l_create_schematic(lua_State *L) { @@ -1540,7 +1561,7 @@ int ModApiMapgen::l_create_schematic(lua_State *L) v3s16 p2 = check_v3s16(L, 2); sortBoxVerticies(p1, p2); - std::vector> prob_list; + std::vector > prob_list; if (lua_istable(L, 3)) { lua_pushnil(L); while (lua_next(L, 3)) { @@ -1549,8 +1570,7 @@ int ModApiMapgen::l_create_schematic(lua_State *L) v3s16 pos = check_v3s16(L, -1); lua_pop(L, 1); - u8 prob = getintfield_default( - L, -1, "prob", MTSCHEM_PROB_ALWAYS); + u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); prob_list.emplace_back(pos, prob); } @@ -1558,14 +1578,13 @@ int ModApiMapgen::l_create_schematic(lua_State *L) } } - std::vector> slice_prob_list; + std::vector > slice_prob_list; if (lua_istable(L, 5)) { lua_pushnil(L); while (lua_next(L, 5)) { if (lua_istable(L, -1)) { s16 ypos = getintfield_default(L, -1, "ypos", 0); - u8 prob = getintfield_default( - L, -1, "prob", MTSCHEM_PROB_ALWAYS); + u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); slice_prob_list.emplace_back(ypos, prob); } @@ -1575,21 +1594,21 @@ int ModApiMapgen::l_create_schematic(lua_State *L) if (!schem.getSchematicFromMap(map, p1, p2)) { errorstream << "create_schematic: failed to get schematic " - "from map" - << std::endl; + "from map" << std::endl; return 0; } schem.applyProbabilities(p1, &prob_list, &slice_prob_list); schem.saveSchematicToFile(filename, ndef); - actionstream << "create_schematic: saved schematic file '" << filename << "'." - << std::endl; + actionstream << "create_schematic: saved schematic file '" + << filename << "'." << std::endl; lua_pushboolean(L, true); return 1; } + // place_schematic(p, schematic, rotation, // replacements, force_placement, flagstring) int ModApiMapgen::l_place_schematic(lua_State *L) @@ -1637,6 +1656,7 @@ int ModApiMapgen::l_place_schematic(lua_State *L) return 1; } + // place_schematic_on_vmanip(vm, p, schematic, rotation, // replacements, force_placement, flagstring) int ModApiMapgen::l_place_schematic_on_vmanip(lua_State *L) @@ -1679,19 +1699,19 @@ int ModApiMapgen::l_place_schematic_on_vmanip(lua_State *L) read_flags(L, 7, flagdesc_deco, &flags, NULL); bool schematic_did_fit = schem->placeOnVManip( - vm, p, flags, (Rotation)rot, force_placement); + vm, p, flags, (Rotation)rot, force_placement); lua_pushboolean(L, schematic_did_fit); return 1; } + // serialize_schematic(schematic, format, options={...}) int ModApiMapgen::l_serialize_schematic(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const SchematicManager *schemmgr = - getServer(L)->getEmergeManager()->getSchematicManager(); + const SchematicManager *schemmgr = getServer(L)->getEmergeManager()->getSchematicManager(); //// Read options bool use_comments = getboolfield_default(L, 3, "lua_use_comments", false); @@ -1705,8 +1725,7 @@ int ModApiMapgen::l_serialize_schematic(lua_State *L) was_loaded = true; } if (!schem) { - errorstream << "serialize_schematic: failed to get schematic" - << std::endl; + errorstream << "serialize_schematic: failed to get schematic" << std::endl; return 0; } @@ -1723,8 +1742,8 @@ int ModApiMapgen::l_serialize_schematic(lua_State *L) schem->serializeToMts(&os, schem->m_nodenames); break; case SCHEM_FMT_LUA: - schem->serializeToLua( - &os, schem->m_nodenames, use_comments, indent_spaces); + schem->serializeToLua(&os, schem->m_nodenames, + use_comments, indent_spaces); break; default: return 0; @@ -1744,11 +1763,10 @@ int ModApiMapgen::l_read_schematic(lua_State *L) NO_MAP_LOCK_REQUIRED; const SchematicManager *schemmgr = - getServer(L)->getEmergeManager()->getSchematicManager(); + getServer(L)->getEmergeManager()->getSchematicManager(); //// Read options - std::string write_yslice = - getstringfield_default(L, 2, "write_yslice_prob", "all"); + std::string write_yslice = getstringfield_default(L, 2, "write_yslice_prob", "all"); //// Get schematic bool was_loaded = false; @@ -1794,7 +1812,7 @@ int ModApiMapgen::l_read_schematic(lua_State *L) lua_createtable(L, numnodes, 0); // data table for (u32 i = 0; i < numnodes; ++i) { MapNode node = schem->schemdata[i]; - u8 probability = node.param1 & MTSCHEM_PROB_MASK; + u8 probability = node.param1 & MTSCHEM_PROB_MASK; bool force_place = node.param1 & MTSCHEM_FORCE_PLACE; lua_createtable(L, 0, force_place ? 4 : 3); lua_pushstring(L, names[schem->schemdata[i].getContent()].c_str()); @@ -1817,6 +1835,7 @@ int ModApiMapgen::l_read_schematic(lua_State *L) return 1; } + void ModApiMapgen::Initialize(lua_State *L, int top) { API_FCT(get_biome_id); diff --git a/src/script/lua_api/l_mapgen.h b/src/script/lua_api/l_mapgen.h index ebc49a5ec..0bdc56fc5 100644 --- a/src/script/lua_api/l_mapgen.h +++ b/src/script/lua_api/l_mapgen.h @@ -21,7 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_base.h" -typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include +typedef u16 biome_t; // copy from mg_biome.h to avoid an unnecessary include class ModApiMapgen : public ModApiBase { diff --git a/src/script/lua_api/l_metadata.cpp b/src/script/lua_api/l_metadata.cpp index 3c9670c22..21002e6a7 100644 --- a/src/script/lua_api/l_metadata.cpp +++ b/src/script/lua_api/l_metadata.cpp @@ -26,14 +26,12 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "server.h" // LUALIB_API -void *luaL_checkudata_is_metadataref(lua_State *L, int ud) -{ +void *luaL_checkudata_is_metadataref(lua_State *L, int ud) { void *p = lua_touserdata(L, ud); - if (p != NULL && // value is a userdata? - lua_getmetatable(L, ud)) { // does it have a metatable? + if (p != NULL && // value is a userdata? + lua_getmetatable(L, ud)) { // does it have a metatable? lua_getfield(L, -1, "metadata_class"); - if (lua_type(L, -1) == - LUA_TSTRING) { // does it have a metadata_class field? + if (lua_type(L, -1) == LUA_TSTRING) { // does it have a metadata_class field? return p; } } @@ -41,14 +39,14 @@ void *luaL_checkudata_is_metadataref(lua_State *L, int ud) return NULL; } -MetaDataRef *MetaDataRef::checkobject(lua_State *L, int narg) +MetaDataRef* MetaDataRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata_is_metadataref(L, narg); if (!ud) luaL_typerror(L, narg, "MetaDataRef"); - return *(MetaDataRef **)ud; // unbox pointer + return *(MetaDataRef**)ud; // unbox pointer } // Exported functions diff --git a/src/script/lua_api/l_minimap.cpp b/src/script/lua_api/l_minimap.cpp index 1c429bdcb..5fba76eb8 100644 --- a/src/script/lua_api/l_minimap.cpp +++ b/src/script/lua_api/l_minimap.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "lua_api/l_minimap.h" #include "lua_api/l_internal.h" #include "common/c_converter.h" @@ -98,11 +99,12 @@ int LuaMinimap::l_set_mode(lua_State *L) Minimap *m = getobject(ref); s32 mode = lua_tointeger(L, 2); - if (mode < MINIMAP_MODE_OFF || mode >= MINIMAP_MODE_COUNT) { + if (mode < MINIMAP_MODE_OFF || + mode >= MINIMAP_MODE_COUNT) { return 0; } - m->setMinimapMode((MinimapMode)mode); + m->setMinimapMode((MinimapMode) mode); return 1; } @@ -170,16 +172,15 @@ LuaMinimap *LuaMinimap::checkobject(lua_State *L, int narg) if (!ud) luaL_typerror(L, narg, className); - return *(LuaMinimap **)ud; // unbox pointer + return *(LuaMinimap **)ud; // unbox pointer } -Minimap *LuaMinimap::getobject(LuaMinimap *ref) +Minimap* LuaMinimap::getobject(LuaMinimap *ref) { return ref->m_minimap; } -int LuaMinimap::gc_object(lua_State *L) -{ +int LuaMinimap::gc_object(lua_State *L) { LuaMinimap *o = *(LuaMinimap **)(lua_touserdata(L, 1)); delete o; return 0; @@ -194,7 +195,7 @@ void LuaMinimap::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -204,16 +205,23 @@ void LuaMinimap::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable } const char LuaMinimap::className[] = "Minimap"; -const luaL_Reg LuaMinimap::methods[] = {luamethod(LuaMinimap, show), - luamethod(LuaMinimap, hide), luamethod(LuaMinimap, get_pos), - luamethod(LuaMinimap, set_pos), luamethod(LuaMinimap, get_angle), - luamethod(LuaMinimap, set_angle), luamethod(LuaMinimap, get_mode), - luamethod(LuaMinimap, set_mode), luamethod(LuaMinimap, set_shape), - luamethod(LuaMinimap, get_shape), {0, 0}}; +const luaL_Reg LuaMinimap::methods[] = { + luamethod(LuaMinimap, show), + luamethod(LuaMinimap, hide), + luamethod(LuaMinimap, get_pos), + luamethod(LuaMinimap, set_pos), + luamethod(LuaMinimap, get_angle), + luamethod(LuaMinimap, set_angle), + luamethod(LuaMinimap, get_mode), + luamethod(LuaMinimap, set_mode), + luamethod(LuaMinimap, set_shape), + luamethod(LuaMinimap, get_shape), + {0,0} +}; diff --git a/src/script/lua_api/l_nodemeta.cpp b/src/script/lua_api/l_nodemeta.cpp index 934c08796..57052cb42 100644 --- a/src/script/lua_api/l_nodemeta.cpp +++ b/src/script/lua_api/l_nodemeta.cpp @@ -29,16 +29,15 @@ with this program; if not, write to the Free Software Foundation, Inc., /* NodeMetaRef */ -NodeMetaRef *NodeMetaRef::checkobject(lua_State *L, int narg) +NodeMetaRef* NodeMetaRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); - if (!ud) - luaL_typerror(L, narg, className); - return *(NodeMetaRef **)ud; // unbox pointer + if(!ud) luaL_typerror(L, narg, className); + return *(NodeMetaRef**)ud; // unbox pointer } -Metadata *NodeMetaRef::getmeta(bool auto_create) +Metadata* NodeMetaRef::getmeta(bool auto_create) { if (m_is_local) return m_meta; @@ -65,7 +64,7 @@ void NodeMetaRef::reportMetadataChange(const std::string *name) SANITY_CHECK(!m_is_local); // NOTE: This same code is in rollback_interface.cpp // Inform other things that the metadata has changed - NodeMetadata *meta = dynamic_cast(m_meta); + NodeMetadata *meta = dynamic_cast(m_meta); MapEditEvent event; event.type = MEET_BLOCK_NODE_METADATA_CHANGED; @@ -77,8 +76,7 @@ void NodeMetaRef::reportMetadataChange(const std::string *name) // Exported functions // garbage collector -int NodeMetaRef::gc_object(lua_State *L) -{ +int NodeMetaRef::gc_object(lua_State *L) { NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1)); delete o; return 0; @@ -90,7 +88,7 @@ int NodeMetaRef::l_get_inventory(lua_State *L) MAP_LOCK_REQUIRED; NodeMetaRef *ref = checkobject(L, 1); - ref->getmeta(true); // try to ensure the metadata exists + ref->getmeta(true); // try to ensure the metadata exists InvRef::createNodeMeta(L, ref->m_p); return 1; } @@ -101,7 +99,7 @@ int NodeMetaRef::l_mark_as_private(lua_State *L) MAP_LOCK_REQUIRED; NodeMetaRef *ref = checkobject(L, 1); - NodeMetadata *meta = dynamic_cast(ref->getmeta(true)); + NodeMetadata *meta = dynamic_cast(ref->getmeta(true)); assert(meta); if (lua_istable(L, 2)) { @@ -126,15 +124,15 @@ void NodeMetaRef::handleToTable(lua_State *L, Metadata *_meta) // fields MetaDataRef::handleToTable(L, _meta); - NodeMetadata *meta = (NodeMetadata *)_meta; + NodeMetadata *meta = (NodeMetadata*) _meta; // inventory lua_newtable(L); Inventory *inv = meta->getInventory(); if (inv) { std::vector lists = inv->getLists(); - for (std::vector::const_iterator i = lists.begin(); - i != lists.end(); ++i) { + for(std::vector::const_iterator + i = lists.begin(); i != lists.end(); ++i) { push_inventory_list(L, inv, (*i)->getName().c_str()); lua_setfield(L, -2, (*i)->getName().c_str()); } @@ -149,7 +147,7 @@ bool NodeMetaRef::handleFromTable(lua_State *L, int table, Metadata *_meta) if (!MetaDataRef::handleFromTable(L, table, _meta)) return false; - NodeMetadata *meta = (NodeMetadata *)_meta; + NodeMetadata *meta = (NodeMetadata*) _meta; // inventory Inventory *inv = meta->getInventory(); @@ -169,11 +167,16 @@ bool NodeMetaRef::handleFromTable(lua_State *L, int table, Metadata *_meta) return true; } -NodeMetaRef::NodeMetaRef(v3s16 p, ServerEnvironment *env) : m_p(p), m_env(env) + +NodeMetaRef::NodeMetaRef(v3s16 p, ServerEnvironment *env): + m_p(p), + m_env(env) { } -NodeMetaRef::NodeMetaRef(Metadata *meta) : m_meta(meta), m_is_local(true) +NodeMetaRef::NodeMetaRef(Metadata *meta): + m_meta(meta), + m_is_local(true) { } @@ -182,7 +185,7 @@ NodeMetaRef::NodeMetaRef(Metadata *meta) : m_meta(meta), m_is_local(true) void NodeMetaRef::create(lua_State *L, v3s16 p, ServerEnvironment *env) { NodeMetaRef *o = new NodeMetaRef(p, env); - // infostream<<"NodeMetaRef::create: o="<(L, 2); - f32 e = readParam(L, 3); + f32 t = readParam(L,2); + f32 e = readParam(L,3); o->m_map->setNodeTimer(NodeTimer(t, e, o->m_p)); return 0; } @@ -52,7 +51,7 @@ int NodeTimerRef::l_start(lua_State *L) { MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); - f32 t = readParam(L, 2); + f32 t = readParam(L,2); o->m_map->setNodeTimer(NodeTimer(t, 0, o->m_p)); return 0; } @@ -70,7 +69,7 @@ int NodeTimerRef::l_is_started(lua_State *L) MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); NodeTimer t = o->m_map->getNodeTimer(o->m_p); - lua_pushboolean(L, (t.timeout != 0)); + lua_pushboolean(L,(t.timeout != 0)); return 1; } @@ -79,7 +78,7 @@ int NodeTimerRef::l_get_timeout(lua_State *L) MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); NodeTimer t = o->m_map->getNodeTimer(o->m_p); - lua_pushnumber(L, t.timeout); + lua_pushnumber(L,t.timeout); return 1; } @@ -88,7 +87,7 @@ int NodeTimerRef::l_get_elapsed(lua_State *L) MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); NodeTimer t = o->m_map->getNodeTimer(o->m_p); - lua_pushnumber(L, t.elapsed); + lua_pushnumber(L,t.elapsed); return 1; } @@ -111,7 +110,7 @@ void NodeTimerRef::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -121,17 +120,22 @@ void NodeTimerRef::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Cannot be created from Lua - // lua_register(L, className, create_object); + //lua_register(L, className, create_object); } const char NodeTimerRef::className[] = "NodeTimerRef"; -const luaL_Reg NodeTimerRef::methods[] = {luamethod(NodeTimerRef, start), - luamethod(NodeTimerRef, set), luamethod(NodeTimerRef, stop), - luamethod(NodeTimerRef, is_started), luamethod(NodeTimerRef, get_timeout), - luamethod(NodeTimerRef, get_elapsed), {0, 0}}; +const luaL_Reg NodeTimerRef::methods[] = { + luamethod(NodeTimerRef, start), + luamethod(NodeTimerRef, set), + luamethod(NodeTimerRef, stop), + luamethod(NodeTimerRef, is_started), + luamethod(NodeTimerRef, get_timeout), + luamethod(NodeTimerRef, get_elapsed), + {0,0} +}; diff --git a/src/script/lua_api/l_noise.cpp b/src/script/lua_api/l_noise.cpp index 0e9ece82b..9aeb15709 100644 --- a/src/script/lua_api/l_noise.cpp +++ b/src/script/lua_api/l_noise.cpp @@ -30,10 +30,12 @@ with this program; if not, write to the Free Software Foundation, Inc., LuaPerlinNoise */ -LuaPerlinNoise::LuaPerlinNoise(NoiseParams *params) : np(*params) +LuaPerlinNoise::LuaPerlinNoise(NoiseParams *params) : + np(*params) { } + int LuaPerlinNoise::l_get_2d(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -44,6 +46,7 @@ int LuaPerlinNoise::l_get_2d(lua_State *L) return 1; } + int LuaPerlinNoise::l_get_3d(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -54,6 +57,7 @@ int LuaPerlinNoise::l_get_3d(lua_State *L) return 1; } + int LuaPerlinNoise::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -63,10 +67,10 @@ int LuaPerlinNoise::create_object(lua_State *L) if (lua_istable(L, 1)) { read_noiseparams(L, 1, ¶ms); } else { - params.seed = luaL_checkint(L, 1); + params.seed = luaL_checkint(L, 1); params.octaves = luaL_checkint(L, 2); params.persist = readParam(L, 3); - params.spread = v3f(1, 1, 1) * readParam(L, 4); + params.spread = v3f(1, 1, 1) * readParam(L, 4); } LuaPerlinNoise *o = new LuaPerlinNoise(¶ms); @@ -77,6 +81,7 @@ int LuaPerlinNoise::create_object(lua_State *L) return 1; } + int LuaPerlinNoise::gc_object(lua_State *L) { LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1)); @@ -84,6 +89,7 @@ int LuaPerlinNoise::gc_object(lua_State *L) return 0; } + LuaPerlinNoise *LuaPerlinNoise::checkobject(lua_State *L, int narg) { NO_MAP_LOCK_REQUIRED; @@ -94,6 +100,7 @@ LuaPerlinNoise *LuaPerlinNoise::checkobject(lua_State *L, int narg) return *(LuaPerlinNoise **)ud; } + void LuaPerlinNoise::Register(lua_State *L) { lua_newtable(L); @@ -122,9 +129,13 @@ void LuaPerlinNoise::Register(lua_State *L) lua_register(L, className, create_object); } + const char LuaPerlinNoise::className[] = "PerlinNoise"; -luaL_Reg LuaPerlinNoise::methods[] = {luamethod_aliased(LuaPerlinNoise, get_2d, get2d), - luamethod_aliased(LuaPerlinNoise, get_3d, get3d), {0, 0}}; +luaL_Reg LuaPerlinNoise::methods[] = { + luamethod_aliased(LuaPerlinNoise, get_2d, get2d), + luamethod_aliased(LuaPerlinNoise, get_3d, get3d), + {0,0} +}; /////////////////////////////////////// /* @@ -142,11 +153,13 @@ LuaPerlinNoiseMap::LuaPerlinNoiseMap(NoiseParams *params, s32 seed, v3s16 size) } } + LuaPerlinNoiseMap::~LuaPerlinNoiseMap() { delete noise; } + int LuaPerlinNoiseMap::l_get_2d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -170,6 +183,7 @@ int LuaPerlinNoiseMap::l_get_2d_map(lua_State *L) return 1; } + int LuaPerlinNoiseMap::l_get_2d_map_flat(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -195,6 +209,7 @@ int LuaPerlinNoiseMap::l_get_2d_map_flat(lua_State *L) return 1; } + int LuaPerlinNoiseMap::l_get_3d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -225,13 +240,14 @@ int LuaPerlinNoiseMap::l_get_3d_map(lua_State *L) return 1; } + int LuaPerlinNoiseMap::l_get_3d_map_flat(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); - v3f p = check_v3f(L, 2); - bool use_buffer = lua_istable(L, 3); + v3f p = check_v3f(L, 2); + bool use_buffer = lua_istable(L, 3); if (!o->m_is3d) return 0; @@ -253,6 +269,7 @@ int LuaPerlinNoiseMap::l_get_3d_map_flat(lua_State *L) return 1; } + int LuaPerlinNoiseMap::l_calc_2d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -271,7 +288,7 @@ int LuaPerlinNoiseMap::l_calc_3d_map(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); - v3f p = check_v3f(L, 2); + v3f p = check_v3f(L, 2); if (!o->m_is3d) return 0; @@ -282,14 +299,15 @@ int LuaPerlinNoiseMap::l_calc_3d_map(lua_State *L) return 0; } + int LuaPerlinNoiseMap::l_get_map_slice(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); - v3s16 slice_offset = read_v3s16(L, 2); - v3s16 slice_size = read_v3s16(L, 3); - bool use_buffer = lua_istable(L, 4); + v3s16 slice_offset = read_v3s16(L, 2); + v3s16 slice_size = read_v3s16(L, 3); + bool use_buffer = lua_istable(L, 4); Noise *n = o->noise; @@ -298,13 +316,15 @@ int LuaPerlinNoiseMap::l_get_map_slice(lua_State *L) else lua_newtable(L); - write_array_slice_float(L, lua_gettop(L), n->result, v3u16(n->sx, n->sy, n->sz), - v3u16(slice_offset.X, slice_offset.Y, slice_offset.Z), - v3u16(slice_size.X, slice_size.Y, slice_size.Z)); + write_array_slice_float(L, lua_gettop(L), n->result, + v3u16(n->sx, n->sy, n->sz), + v3u16(slice_offset.X, slice_offset.Y, slice_offset.Z), + v3u16(slice_size.X, slice_size.Y, slice_size.Z)); return 1; } + int LuaPerlinNoiseMap::create_object(lua_State *L) { NoiseParams np; @@ -319,6 +339,7 @@ int LuaPerlinNoiseMap::create_object(lua_State *L) return 1; } + int LuaPerlinNoiseMap::gc_object(lua_State *L) { LuaPerlinNoiseMap *o = *(LuaPerlinNoiseMap **)(lua_touserdata(L, 1)); @@ -326,6 +347,7 @@ int LuaPerlinNoiseMap::gc_object(lua_State *L) return 0; } + LuaPerlinNoiseMap *LuaPerlinNoiseMap::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -337,6 +359,7 @@ LuaPerlinNoiseMap *LuaPerlinNoiseMap::checkobject(lua_State *L, int narg) return *(LuaPerlinNoiseMap **)ud; } + void LuaPerlinNoiseMap::Register(lua_State *L) { lua_newtable(L); @@ -365,15 +388,18 @@ void LuaPerlinNoiseMap::Register(lua_State *L) lua_register(L, className, create_object); } + const char LuaPerlinNoiseMap::className[] = "PerlinNoiseMap"; luaL_Reg LuaPerlinNoiseMap::methods[] = { - luamethod_aliased(LuaPerlinNoiseMap, get_2d_map, get2dMap), - luamethod_aliased(LuaPerlinNoiseMap, get_2d_map_flat, get2dMap_flat), - luamethod_aliased(LuaPerlinNoiseMap, calc_2d_map, calc2dMap), - luamethod_aliased(LuaPerlinNoiseMap, get_3d_map, get3dMap), - luamethod_aliased(LuaPerlinNoiseMap, get_3d_map_flat, get3dMap_flat), - luamethod_aliased(LuaPerlinNoiseMap, calc_3d_map, calc3dMap), - luamethod_aliased(LuaPerlinNoiseMap, get_map_slice, getMapSlice), {0, 0}}; + luamethod_aliased(LuaPerlinNoiseMap, get_2d_map, get2dMap), + luamethod_aliased(LuaPerlinNoiseMap, get_2d_map_flat, get2dMap_flat), + luamethod_aliased(LuaPerlinNoiseMap, calc_2d_map, calc2dMap), + luamethod_aliased(LuaPerlinNoiseMap, get_3d_map, get3dMap), + luamethod_aliased(LuaPerlinNoiseMap, get_3d_map_flat, get3dMap_flat), + luamethod_aliased(LuaPerlinNoiseMap, calc_3d_map, calc3dMap), + luamethod_aliased(LuaPerlinNoiseMap, get_map_slice, getMapSlice), + {0,0} +}; /////////////////////////////////////// /* @@ -393,22 +419,22 @@ int LuaPseudoRandom::l_next(lua_State *L) if (lua_isnumber(L, 3)) max = luaL_checkinteger(L, 3); if (max < min) { - errorstream << "PseudoRandom.next(): max=" << max << " min=" << min - << std::endl; + errorstream<<"PseudoRandom.next(): max="< 32767 / 5) + if(max - min != 32767 && max - min > 32767/5) throw LuaError("PseudoRandom.next() max-min is not 32767" - " and is > 32768/5. This is disallowed due to" - " the bad random distribution the" - " implementation would otherwise make."); + " and is > 32768/5. This is disallowed due to" + " the bad random distribution the" + " implementation would otherwise make."); PseudoRandom &pseudo = o->m_pseudo; int val = pseudo.next(); - val = (val % (max - min + 1)) + min; + val = (val % (max-min+1)) + min; lua_pushinteger(L, val); return 1; } + int LuaPseudoRandom::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -421,6 +447,7 @@ int LuaPseudoRandom::create_object(lua_State *L) return 1; } + int LuaPseudoRandom::gc_object(lua_State *L) { LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1)); @@ -428,6 +455,7 @@ int LuaPseudoRandom::gc_object(lua_State *L) return 0; } + LuaPseudoRandom *LuaPseudoRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -437,6 +465,7 @@ LuaPseudoRandom *LuaPseudoRandom::checkobject(lua_State *L, int narg) return *(LuaPseudoRandom **)ud; } + void LuaPseudoRandom::Register(lua_State *L) { lua_newtable(L); @@ -464,8 +493,12 @@ void LuaPseudoRandom::Register(lua_State *L) lua_register(L, className, create_object); } + const char LuaPseudoRandom::className[] = "PseudoRandom"; -const luaL_Reg LuaPseudoRandom::methods[] = {luamethod(LuaPseudoRandom, next), {0, 0}}; +const luaL_Reg LuaPseudoRandom::methods[] = { + luamethod(LuaPseudoRandom, next), + {0,0} +}; /////////////////////////////////////// /* @@ -484,6 +517,7 @@ int LuaPcgRandom::l_next(lua_State *L) return 1; } + int LuaPcgRandom::l_rand_normal_dist(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -497,19 +531,22 @@ int LuaPcgRandom::l_rand_normal_dist(lua_State *L) return 1; } + int LuaPcgRandom::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; u64 seed = luaL_checknumber(L, 1); - LuaPcgRandom *o = lua_isnumber(L, 2) ? new LuaPcgRandom(seed, lua_tointeger(L, 2)) - : new LuaPcgRandom(seed); + LuaPcgRandom *o = lua_isnumber(L, 2) ? + new LuaPcgRandom(seed, lua_tointeger(L, 2)) : + new LuaPcgRandom(seed); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } + int LuaPcgRandom::gc_object(lua_State *L) { LuaPcgRandom *o = *(LuaPcgRandom **)(lua_touserdata(L, 1)); @@ -517,6 +554,7 @@ int LuaPcgRandom::gc_object(lua_State *L) return 0; } + LuaPcgRandom *LuaPcgRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -526,6 +564,7 @@ LuaPcgRandom *LuaPcgRandom::checkobject(lua_State *L, int narg) return *(LuaPcgRandom **)ud; } + void LuaPcgRandom::Register(lua_State *L) { lua_newtable(L); @@ -553,9 +592,13 @@ void LuaPcgRandom::Register(lua_State *L) lua_register(L, className, create_object); } + const char LuaPcgRandom::className[] = "PcgRandom"; -const luaL_Reg LuaPcgRandom::methods[] = {luamethod(LuaPcgRandom, next), - luamethod(LuaPcgRandom, rand_normal_dist), {0, 0}}; +const luaL_Reg LuaPcgRandom::methods[] = { + luamethod(LuaPcgRandom, next), + luamethod(LuaPcgRandom, rand_normal_dist), + {0,0} +}; /////////////////////////////////////// /* @@ -590,8 +633,7 @@ int LuaSecureRandom::l_next_bytes(lua_State *L) // Refill buffer and copy over the remainder of what was requested o->fillRandBuf(); - memcpy(output_buf + count_remaining, o->m_rand_buf, - count - count_remaining); + memcpy(output_buf + count_remaining, o->m_rand_buf, count - count_remaining); // Update index o->m_rand_idx = count - count_remaining; @@ -602,6 +644,7 @@ int LuaSecureRandom::l_next_bytes(lua_State *L) return 1; } + int LuaSecureRandom::create_object(lua_State *L) { LuaSecureRandom *o = new LuaSecureRandom(); @@ -618,6 +661,7 @@ int LuaSecureRandom::create_object(lua_State *L) return 1; } + int LuaSecureRandom::gc_object(lua_State *L) { LuaSecureRandom *o = *(LuaSecureRandom **)(lua_touserdata(L, 1)); @@ -625,6 +669,7 @@ int LuaSecureRandom::gc_object(lua_State *L) return 0; } + LuaSecureRandom *LuaSecureRandom::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); @@ -634,6 +679,7 @@ LuaSecureRandom *LuaSecureRandom::checkobject(lua_State *L, int narg) return *(LuaSecureRandom **)ud; } + void LuaSecureRandom::Register(lua_State *L) { lua_newtable(L); @@ -663,4 +709,6 @@ void LuaSecureRandom::Register(lua_State *L) const char LuaSecureRandom::className[] = "SecureRandom"; const luaL_Reg LuaSecureRandom::methods[] = { - luamethod(LuaSecureRandom, next_bytes), {0, 0}}; + luamethod(LuaSecureRandom, next_bytes), + {0,0} +}; diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index 5d48ee93d..e7394133a 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -39,16 +39,16 @@ with this program; if not, write to the Free Software Foundation, Inc., ObjectRef */ -ObjectRef *ObjectRef::checkobject(lua_State *L, int narg) + +ObjectRef* ObjectRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); - if (!ud) - luaL_typerror(L, narg, className); - return *(ObjectRef **)ud; // unbox pointer + if (!ud) luaL_typerror(L, narg, className); + return *(ObjectRef**)ud; // unbox pointer } -ServerActiveObject *ObjectRef::getobject(ObjectRef *ref) +ServerActiveObject* ObjectRef::getobject(ObjectRef *ref) { ServerActiveObject *co = ref->m_object; if (co && co->isGone()) @@ -56,24 +56,24 @@ ServerActiveObject *ObjectRef::getobject(ObjectRef *ref) return co; } -LuaEntitySAO *ObjectRef::getluaobject(ObjectRef *ref) +LuaEntitySAO* ObjectRef::getluaobject(ObjectRef *ref) { ServerActiveObject *obj = getobject(ref); if (obj == NULL) return NULL; if (obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY) return NULL; - return (LuaEntitySAO *)obj; + return (LuaEntitySAO*)obj; } -PlayerSAO *ObjectRef::getplayersao(ObjectRef *ref) +PlayerSAO* ObjectRef::getplayersao(ObjectRef *ref) { ServerActiveObject *obj = getobject(ref); if (obj == NULL) return NULL; if (obj->getType() != ACTIVEOBJECT_TYPE_PLAYER) return NULL; - return (PlayerSAO *)obj; + return (PlayerSAO*)obj; } RemotePlayer *ObjectRef::getplayer(ObjectRef *ref) @@ -87,10 +87,9 @@ RemotePlayer *ObjectRef::getplayer(ObjectRef *ref) // Exported functions // garbage collector -int ObjectRef::gc_object(lua_State *L) -{ +int ObjectRef::gc_object(lua_State *L) { ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1)); - // infostream<<"ObjectRef::gc_object: o="<(L, -1))) { + !reason.setTypeFromString(readParam(L, -1))) { errorstream << "Bad type given!" << std::endl; } lua_pop(L, 1); @@ -295,8 +287,7 @@ int ObjectRef::l_get_inventory(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it InventoryLocation loc = co->getInventoryLocation(); if (getServerInventoryMgr(L)->getInventory(loc) != NULL) @@ -356,8 +347,7 @@ int ObjectRef::l_set_wielded_item(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it ItemStack item = read_item(L, 2, getServer(L)->idef()); bool success = co->setWieldedItem(item); @@ -374,8 +364,7 @@ int ObjectRef::l_set_armor_groups(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it ItemGroupList groups; read_groups(L, 2, groups); @@ -402,9 +391,8 @@ int ObjectRef::l_set_physics_override(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = (PlayerSAO *)getobject(ref); - if (co == NULL) - return 0; + PlayerSAO *co = (PlayerSAO *) getobject(ref); + if (co == NULL) return 0; // Do it if (lua_istable(L, 2)) { co->m_physics_override_speed = getfloatfield_default( @@ -415,8 +403,8 @@ int ObjectRef::l_set_physics_override(lua_State *L) L, 2, "gravity", co->m_physics_override_gravity); co->m_physics_override_sneak = getboolfield_default( L, 2, "sneak", co->m_physics_override_sneak); - co->m_physics_override_sneak_glitch = getboolfield_default(L, 2, - "sneak_glitch", co->m_physics_override_sneak_glitch); + co->m_physics_override_sneak_glitch = getboolfield_default( + L, 2, "sneak_glitch", co->m_physics_override_sneak_glitch); co->m_physics_override_new_move = getboolfield_default( L, 2, "new_move", co->m_physics_override_new_move); co->m_physics_override_sent = false; @@ -469,8 +457,7 @@ int ObjectRef::l_set_animation(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it v2f frames = v2f(1, 1); if (!lua_isnil(L, 2)) @@ -497,7 +484,7 @@ int ObjectRef::l_get_animation(lua_State *L) if (co == NULL) return 0; // Do it - v2f frames = v2f(1, 1); + v2f frames = v2f(1,1); float frame_speed = 15; float frame_blend = 0; bool frame_loop = true; @@ -520,9 +507,9 @@ int ObjectRef::l_set_local_animation(lua_State *L) return 0; // Do it v2s32 frames[4]; - for (int i = 0; i < 4; i++) { - if (!lua_isnil(L, 2 + 1)) - frames[i] = read_v2s32(L, 2 + i); + for (int i=0;i<4;i++) { + if (!lua_isnil(L, 2+1)) + frames[i] = read_v2s32(L, 2+i); } float frame_speed = 30; if (!lua_isnil(L, 6)) @@ -572,10 +559,10 @@ int ObjectRef::l_set_eye_offset(lua_State *L) offset_third = read_v3f(L, 3); // Prevent abuse of offset values (keep player always visible) - offset_third.X = rangelim(offset_third.X, -10, 10); - offset_third.Z = rangelim(offset_third.Z, -5, 5); + offset_third.X = rangelim(offset_third.X,-10,10); + offset_third.Z = rangelim(offset_third.Z,-5,5); /* TODO: if possible: improve the camera colision detetion to allow Y <= -1.5) */ - offset_third.Y = rangelim(offset_third.Y, -10, 15); // 1.5*BS + offset_third.Y = rangelim(offset_third.Y,-10,15); //1.5*BS getServer(L)->setPlayerEyeOffset(player, offset_first, offset_third); lua_pushboolean(L, true); @@ -640,8 +627,7 @@ int ObjectRef::l_set_bone_position(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it std::string bone; if (!lua_isnil(L, 2)) @@ -694,8 +680,7 @@ int ObjectRef::l_set_attach(lua_State *L) return 0; if (co == parent) - throw LuaError("ObjectRef::set_attach: attaching object to itself is not " - "allowed."); + throw LuaError("ObjectRef::set_attach: attaching object to itself is not allowed."); // Do it int parent_id = 0; @@ -866,8 +851,7 @@ int ObjectRef::l_set_velocity(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; v3f pos = checkFloatPos(L, 2); // Do it co->setVelocity(pos); @@ -894,8 +878,7 @@ int ObjectRef::l_get_velocity(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it v3f v = co->getVelocity(); pushFloatPos(L, v); @@ -908,8 +891,7 @@ int ObjectRef::l_set_acceleration(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // pos v3f pos = checkFloatPos(L, 2); // Do it @@ -923,8 +905,7 @@ int ObjectRef::l_get_acceleration(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it v3f v = co->getAcceleration(); pushFloatPos(L, v); @@ -970,8 +951,7 @@ int ObjectRef::l_set_yaw(lua_State *L) ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; if (isNaN(L, 2)) throw LuaError("ObjectRef::set_yaw: NaN value is not allowed."); @@ -1000,8 +980,7 @@ int ObjectRef::l_set_texture_mod(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it std::string mod = luaL_checkstring(L, 2); co->setTextureMod(mod); @@ -1014,8 +993,7 @@ int ObjectRef::l_get_texture_mod(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it std::string mod = co->getTextureMod(); lua_pushstring(L, mod.c_str()); @@ -1029,10 +1007,9 @@ int ObjectRef::l_set_sprite(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it - v2s16 p(0, 0); + v2s16 p(0,0); if (!lua_isnil(L, 2)) p = readParam(L, 2); int num_frames = 1; @@ -1055,9 +1032,8 @@ int ObjectRef::l_get_entity_name(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - log_deprecated(L, "Deprecated call to \"get_entity_name"); - if (co == NULL) - return 0; + log_deprecated(L,"Deprecated call to \"get_entity_name"); + if (co == NULL) return 0; // Do it std::string name = co->getName(); lua_pushstring(L, name.c_str()); @@ -1070,8 +1046,7 @@ int ObjectRef::l_get_luaentity(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) - return 0; + if (co == NULL) return 0; // Do it luaentity_get(L, co->getId()); return 1; @@ -1085,7 +1060,7 @@ int ObjectRef::l_is_player_connected(lua_State *L) NO_MAP_LOCK_REQUIRED; // This method was once added for a bugfix, but never documented log_deprecated(L, "is_player_connected is undocumented and " - "will be removed in a future release"); + "will be removed in a future release"); ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); lua_pushboolean(L, (player != NULL && player->getPeerId() != PEER_ID_INEXISTENT)); @@ -1144,14 +1119,13 @@ int ObjectRef::l_get_look_dir(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it float pitch = co->getRadLookPitchDep(); float yaw = co->getRadYawDep(); - v3f v(std::cos(pitch) * std::cos(yaw), std::sin(pitch), - std::cos(pitch) * std::sin(yaw)); + v3f v(std::cos(pitch) * std::cos(yaw), std::sin(pitch), std::cos(pitch) * + std::sin(yaw)); push_v3f(L, v); return 1; } @@ -1162,13 +1136,12 @@ int ObjectRef::l_get_look_pitch(lua_State *L) { NO_MAP_LOCK_REQUIRED; - log_deprecated(L, "Deprecated call to get_look_pitch, use get_look_vertical " - "instead"); + log_deprecated(L, + "Deprecated call to get_look_pitch, use get_look_vertical instead"); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it lua_pushnumber(L, co->getRadLookPitchDep()); return 1; @@ -1180,13 +1153,12 @@ int ObjectRef::l_get_look_yaw(lua_State *L) { NO_MAP_LOCK_REQUIRED; - log_deprecated(L, "Deprecated call to get_look_yaw, use get_look_horizontal " - "instead"); + log_deprecated(L, + "Deprecated call to get_look_yaw, use get_look_horizontal instead"); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it lua_pushnumber(L, co->getRadYawDep()); return 1; @@ -1197,9 +1169,8 @@ int ObjectRef::l_get_look_vertical(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it lua_pushnumber(L, co->getRadLookPitch()); return 1; @@ -1210,9 +1181,8 @@ int ObjectRef::l_get_look_horizontal(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it lua_pushnumber(L, co->getRadRotation().Y); return 1; @@ -1223,9 +1193,8 @@ int ObjectRef::l_set_look_vertical(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; float pitch = readParam(L, 2) * core::RADTODEG; // Do it co->setLookPitchAndSend(pitch); @@ -1237,9 +1206,8 @@ int ObjectRef::l_set_look_horizontal(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; float yaw = readParam(L, 2) * core::RADTODEG; // Do it co->setPlayerYawAndSend(yaw); @@ -1252,13 +1220,12 @@ int ObjectRef::l_set_look_pitch(lua_State *L) { NO_MAP_LOCK_REQUIRED; - log_deprecated(L, "Deprecated call to set_look_pitch, use set_look_vertical " - "instead."); + log_deprecated(L, + "Deprecated call to set_look_pitch, use set_look_vertical instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; float pitch = readParam(L, 2) * core::RADTODEG; // Do it co->setLookPitchAndSend(pitch); @@ -1271,13 +1238,12 @@ int ObjectRef::l_set_look_yaw(lua_State *L) { NO_MAP_LOCK_REQUIRED; - log_deprecated(L, "Deprecated call to set_look_yaw, use set_look_horizontal " - "instead."); + log_deprecated(L, + "Deprecated call to set_look_yaw, use set_look_horizontal instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; float yaw = readParam(L, 2) * core::RADTODEG; // Do it co->setPlayerYawAndSend(yaw); @@ -1293,10 +1259,11 @@ int ObjectRef::l_set_fov(lua_State *L) if (!player) return 0; - player->setFov({static_cast(luaL_checknumber(L, 2)), - readParam(L, 3, false), - lua_isnumber(L, 4) ? static_cast(luaL_checknumber(L, 4)) - : 0.0f}); + player->setFov({ + static_cast(luaL_checknumber(L, 2)), + readParam(L, 3, false), + lua_isnumber(L, 4) ? static_cast(luaL_checknumber(L, 4)) : 0.0f + }); getServer(L)->SendPlayerFov(player->getPeerId()); return 0; @@ -1324,9 +1291,8 @@ int ObjectRef::l_set_breath(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; u16 breath = luaL_checknumber(L, 2); co->setBreath(breath); @@ -1338,23 +1304,22 @@ int ObjectRef::l_get_breath(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) - return 0; + PlayerSAO* co = getplayersao(ref); + if (co == NULL) return 0; // Do it u16 breath = co->getBreath(); - lua_pushinteger(L, breath); + lua_pushinteger (L, breath); return 1; } // set_attribute(self, attribute, value) int ObjectRef::l_set_attribute(lua_State *L) { - log_deprecated(L, "Deprecated call to set_attribute, use MetaDataRef methods " - "instead."); + log_deprecated(L, + "Deprecated call to set_attribute, use MetaDataRef methods instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); + PlayerSAO* co = getplayersao(ref); if (co == NULL) return 0; @@ -1371,11 +1336,11 @@ int ObjectRef::l_set_attribute(lua_State *L) // get_attribute(self, attribute) int ObjectRef::l_get_attribute(lua_State *L) { - log_deprecated(L, "Deprecated call to get_attribute, use MetaDataRef methods " - "instead."); + log_deprecated(L, + "Deprecated call to get_attribute, use MetaDataRef methods instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); + PlayerSAO* co = getplayersao(ref); if (co == NULL) return 0; @@ -1390,6 +1355,7 @@ int ObjectRef::l_get_attribute(lua_State *L) return 0; } + // get_meta(self, attribute) int ObjectRef::l_get_meta(lua_State *L) { @@ -1402,14 +1368,14 @@ int ObjectRef::l_get_meta(lua_State *L) return 1; } + // set_inventory_formspec(self, formspec) int ObjectRef::l_set_inventory_formspec(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) - return 0; + if (player == NULL) return 0; std::string formspec = luaL_checkstring(L, 2); player->inventory_formspec = formspec; @@ -1424,8 +1390,7 @@ int ObjectRef::l_get_inventory_formspec(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) - return 0; + if (player == NULL) return 0; std::string formspec = player->inventory_formspec; lua_pushlstring(L, formspec.c_str(), formspec.size()); @@ -1456,7 +1421,7 @@ int ObjectRef::l_get_formspec_prepend(lua_State *L) ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) - return 0; + return 0; std::string formspec = player->formspec_prepend; lua_pushlstring(L, formspec.c_str(), formspec.size()); @@ -1608,14 +1573,14 @@ int ObjectRef::l_hud_set_flags(lua_State *L) return 0; u32 flags = 0; - u32 mask = 0; + u32 mask = 0; bool flag; const EnumString *esp = es_HudBuiltinElement; for (int i = 0; esp[i].str; i++) { if (getboolfield(L, 2, esp[i].str, flag)) { flags |= esp[i].num * flag; - mask |= esp[i].num; + mask |= esp[i].num; } } if (!getServer(L)->hudSetFlags(player, flags, mask)) @@ -1770,8 +1735,7 @@ int ObjectRef::l_set_sky(lua_State *L) lua_pushnil(L); while (lua_next(L, -2) != 0) { // Key is at index -2 and value at index -1 - skybox_params.textures.emplace_back( - readParam(L, -1)); + skybox_params.textures.emplace_back(readParam(L, -1)); // Removes the value, but keeps the key for iteration lua_pop(L, 1); } @@ -1784,12 +1748,11 @@ int ObjectRef::l_set_sky(lua_State *L) using "regular" or "plain" skybox modes as textures aren't needed. */ - if (skybox_params.textures.size() != 6 && - skybox_params.textures.size() > 0) + if (skybox_params.textures.size() != 6 && skybox_params.textures.size() > 0) throw LuaError("Skybox expects 6 textures!"); - skybox_params.clouds = getboolfield_default( - L, 2, "clouds", skybox_params.clouds); + skybox_params.clouds = getboolfield_default(L, 2, + "clouds", skybox_params.clouds); lua_getfield(L, 2, "sky_color"); if (lua_istable(L, -1)) { @@ -1873,10 +1836,9 @@ int ObjectRef::l_set_sky(lua_State *L) if (lua_istable(L, 4)) { lua_pushnil(L); while (lua_next(L, 4) != 0) { - // Key at index -2, and value at index -1 + // Key at index -2, and value at index -1 if (lua_isstring(L, -1)) - skybox_params.textures.emplace_back( - readParam(L, -1)); + skybox_params.textures.emplace_back(readParam(L, -1)); else skybox_params.textures.emplace_back(""); // Remove the value, keep the key for the next iteration @@ -1916,7 +1878,7 @@ int ObjectRef::l_get_sky(lua_State *L) lua_newtable(L); s16 i = 1; - for (const std::string &texture : skybox_params.textures) { + for (const std::string& texture : skybox_params.textures) { lua_pushlstring(L, texture.c_str(), texture.size()); lua_rawseti(L, -2, i++); } @@ -1934,7 +1896,7 @@ int ObjectRef::l_get_sky_color(lua_State *L) if (!player) return 0; - const SkyboxParams &skybox_params = player->getSkyParams(); + const SkyboxParams& skybox_params = player->getSkyParams(); lua_newtable(L); if (skybox_params.type == "regular") { @@ -1976,20 +1938,25 @@ int ObjectRef::l_set_sun(lua_State *L) SunParams sun_params = player->getSunParams(); - sun_params.visible = getboolfield_default(L, 2, "visible", sun_params.visible); - sun_params.texture = getstringfield_default(L, 2, "texture", sun_params.texture); - sun_params.tonemap = getstringfield_default(L, 2, "tonemap", sun_params.tonemap); - sun_params.sunrise = getstringfield_default(L, 2, "sunrise", sun_params.sunrise); - sun_params.sunrise_visible = getboolfield_default( - L, 2, "sunrise_visible", sun_params.sunrise_visible); - sun_params.scale = getfloatfield_default(L, 2, "scale", sun_params.scale); + sun_params.visible = getboolfield_default(L, 2, + "visible", sun_params.visible); + sun_params.texture = getstringfield_default(L, 2, + "texture", sun_params.texture); + sun_params.tonemap = getstringfield_default(L, 2, + "tonemap", sun_params.tonemap); + sun_params.sunrise = getstringfield_default(L, 2, + "sunrise", sun_params.sunrise); + sun_params.sunrise_visible = getboolfield_default(L, 2, + "sunrise_visible", sun_params.sunrise_visible); + sun_params.scale = getfloatfield_default(L, 2, + "scale", sun_params.scale); getServer(L)->setSun(player, sun_params); lua_pushboolean(L, true); return 1; } -// get_sun(self) +//get_sun(self) int ObjectRef::l_get_sun(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -2029,12 +1996,14 @@ int ObjectRef::l_set_moon(lua_State *L) MoonParams moon_params = player->getMoonParams(); - moon_params.visible = getboolfield_default(L, 2, "visible", moon_params.visible); - moon_params.texture = - getstringfield_default(L, 2, "texture", moon_params.texture); - moon_params.tonemap = - getstringfield_default(L, 2, "tonemap", moon_params.tonemap); - moon_params.scale = getfloatfield_default(L, 2, "scale", moon_params.scale); + moon_params.visible = getboolfield_default(L, 2, + "visible", moon_params.visible); + moon_params.texture = getstringfield_default(L, 2, + "texture", moon_params.texture); + moon_params.tonemap = getstringfield_default(L, 2, + "tonemap", moon_params.tonemap); + moon_params.scale = getfloatfield_default(L, 2, + "scale", moon_params.scale); getServer(L)->setMoon(player, moon_params); lua_pushboolean(L, true); @@ -2077,15 +2046,18 @@ int ObjectRef::l_set_stars(lua_State *L) StarParams star_params = player->getStarParams(); - star_params.visible = getboolfield_default(L, 2, "visible", star_params.visible); - star_params.count = getintfield_default(L, 2, "count", star_params.count); + star_params.visible = getboolfield_default(L, 2, + "visible", star_params.visible); + star_params.count = getintfield_default(L, 2, + "count", star_params.count); lua_getfield(L, 2, "star_color"); if (!lua_isnil(L, -1)) read_color(L, -1, &star_params.starcolor); lua_pop(L, 1); - star_params.scale = getfloatfield_default(L, 2, "scale", star_params.scale); + star_params.scale = getfloatfield_default(L, 2, + "scale", star_params.scale); getServer(L)->setStars(player, star_params); lua_pushboolean(L, true); @@ -2128,8 +2100,7 @@ int ObjectRef::l_set_clouds(lua_State *L) CloudParams cloud_params = player->getCloudParams(); - cloud_params.density = - getfloatfield_default(L, 2, "density", cloud_params.density); + cloud_params.density = getfloatfield_default(L, 2, "density", cloud_params.density); lua_getfield(L, 2, "color"); if (!lua_isnil(L, -1)) @@ -2140,9 +2111,8 @@ int ObjectRef::l_set_clouds(lua_State *L) read_color(L, -1, &cloud_params.color_ambient); lua_pop(L, 1); - cloud_params.height = getfloatfield_default(L, 2, "height", cloud_params.height); - cloud_params.thickness = - getfloatfield_default(L, 2, "thickness", cloud_params.thickness); + cloud_params.height = getfloatfield_default(L, 2, "height", cloud_params.height ); + cloud_params.thickness = getfloatfield_default(L, 2, "thickness", cloud_params.thickness); lua_getfield(L, 2, "speed"); if (lua_istable(L, -1)) { @@ -2188,6 +2158,7 @@ int ObjectRef::l_get_clouds(lua_State *L) return 1; } + // override_day_night_ratio(self, brightness=0...1) int ObjectRef::l_override_day_night_ratio(lua_State *L) { @@ -2230,9 +2201,10 @@ int ObjectRef::l_get_day_night_ratio(lua_State *L) return 1; } -ObjectRef::ObjectRef(ServerActiveObject *object) : m_object(object) +ObjectRef::ObjectRef(ServerActiveObject *object): + m_object(object) { - // infostream<<"ObjectRef created for id="<getId()< 1) // deprecated { log_deprecated(L, "Deprecated add_particle call with " - "individual parameters instead of definition"); + "individual parameters instead of definition"); p.pos = check_v3f(L, 1); p.vel = check_v3f(L, 2); p.acc = check_v3f(L, 3); @@ -59,7 +59,9 @@ int ModApiParticles::l_add_particle(lua_State *L) p.texture = luaL_checkstring(L, 7); if (lua_gettop(L) == 8) // only spawn for a single player playername = luaL_checkstring(L, 8); - } else if (lua_istable(L, 1)) { + } + else if (lua_istable(L, 1)) + { lua_getfield(L, 1, "pos"); if (lua_istable(L, -1)) p.pos = check_v3f(L, -1); @@ -69,7 +71,7 @@ int ModApiParticles::l_add_particle(lua_State *L) if (lua_istable(L, -1)) { p.vel = check_v3f(L, -1); log_deprecated(L, "The use of vel is deprecated. " - "Use velocity instead"); + "Use velocity instead"); } lua_pop(L, 1); @@ -82,7 +84,7 @@ int ModApiParticles::l_add_particle(lua_State *L) if (lua_istable(L, -1)) { p.acc = check_v3f(L, -1); log_deprecated(L, "The use of acc is deprecated. " - "Use acceleration instead"); + "Use acceleration instead"); } lua_pop(L, 1); @@ -91,15 +93,15 @@ int ModApiParticles::l_add_particle(lua_State *L) p.acc = check_v3f(L, -1); lua_pop(L, 1); - p.expirationtime = getfloatfield_default( - L, 1, "expirationtime", p.expirationtime); + p.expirationtime = getfloatfield_default(L, 1, "expirationtime", + p.expirationtime); p.size = getfloatfield_default(L, 1, "size", p.size); - p.collisiondetection = getboolfield_default( - L, 1, "collisiondetection", p.collisiondetection); - p.collision_removal = getboolfield_default( - L, 1, "collision_removal", p.collision_removal); - p.object_collision = getboolfield_default( - L, 1, "object_collision", p.object_collision); + p.collisiondetection = getboolfield_default(L, 1, + "collisiondetection", p.collisiondetection); + p.collision_removal = getboolfield_default(L, 1, + "collision_removal", p.collision_removal); + p.object_collision = getboolfield_default(L, 1, + "object_collision", p.object_collision); p.vertical = getboolfield_default(L, 1, "vertical", p.vertical); lua_getfield(L, 1, "animation"); @@ -154,10 +156,10 @@ int ModApiParticles::l_add_particlespawner(lua_State *L) ServerActiveObject *attached = NULL; std::string playername; - if (lua_gettop(L) > 1) // deprecated + if (lua_gettop(L) > 1) //deprecated { log_deprecated(L, "Deprecated add_particlespawner call with " - "individual parameters instead of definition"); + "individual parameters instead of definition"); p.amount = luaL_checknumber(L, 1); p.time = luaL_checknumber(L, 2); p.minpos = check_v3f(L, 3); @@ -174,7 +176,9 @@ int ModApiParticles::l_add_particlespawner(lua_State *L) p.texture = luaL_checkstring(L, 14); if (lua_gettop(L) == 15) // only spawn for a single player playername = luaL_checkstring(L, 15); - } else if (lua_istable(L, 1)) { + } + else if (lua_istable(L, 1)) + { p.amount = getintfield_default(L, 1, "amount", p.amount); p.time = getfloatfield_default(L, 1, "time", p.time); @@ -212,12 +216,12 @@ int ModApiParticles::l_add_particlespawner(lua_State *L) p.maxexptime = getfloatfield_default(L, 1, "maxexptime", p.maxexptime); p.minsize = getfloatfield_default(L, 1, "minsize", p.minsize); p.maxsize = getfloatfield_default(L, 1, "maxsize", p.maxsize); - p.collisiondetection = getboolfield_default( - L, 1, "collisiondetection", p.collisiondetection); - p.collision_removal = getboolfield_default( - L, 1, "collision_removal", p.collision_removal); - p.object_collision = getboolfield_default( - L, 1, "object_collision", p.object_collision); + p.collisiondetection = getboolfield_default(L, 1, + "collisiondetection", p.collisiondetection); + p.collision_removal = getboolfield_default(L, 1, + "collision_removal", p.collision_removal); + p.object_collision = getboolfield_default(L, 1, + "object_collision", p.object_collision); lua_getfield(L, 1, "animation"); p.animation = read_animation_definition(L, -1); @@ -272,3 +276,4 @@ void ModApiParticles::Initialize(lua_State *L, int top) API_FCT(add_particlespawner); API_FCT(delete_particlespawner); } + diff --git a/src/script/lua_api/l_particles.h b/src/script/lua_api/l_particles.h index 8734e5516..122810b6d 100644 --- a/src/script/lua_api/l_particles.h +++ b/src/script/lua_api/l_particles.h @@ -21,8 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_base.h" -class ModApiParticles : public ModApiBase -{ +class ModApiParticles : public ModApiBase { private: static int l_add_particle(lua_State *L); static int l_add_particlespawner(lua_State *L); diff --git a/src/script/lua_api/l_particles_local.cpp b/src/script/lua_api/l_particles_local.cpp index 498376d40..cc68b13a5 100644 --- a/src/script/lua_api/l_particles_local.cpp +++ b/src/script/lua_api/l_particles_local.cpp @@ -49,15 +49,15 @@ int ModApiParticlesLocal::l_add_particle(lua_State *L) p.acc = check_v3f(L, -1); lua_pop(L, 1); - p.expirationtime = - getfloatfield_default(L, 1, "expirationtime", p.expirationtime); + p.expirationtime = getfloatfield_default(L, 1, "expirationtime", + p.expirationtime); p.size = getfloatfield_default(L, 1, "size", p.size); - p.collisiondetection = getboolfield_default( - L, 1, "collisiondetection", p.collisiondetection); - p.collision_removal = getboolfield_default( - L, 1, "collision_removal", p.collision_removal); - p.object_collision = getboolfield_default( - L, 1, "object_collision", p.object_collision); + p.collisiondetection = getboolfield_default(L, 1, + "collisiondetection", p.collisiondetection); + p.collision_removal = getboolfield_default(L, 1, + "collision_removal", p.collision_removal); + p.object_collision = getboolfield_default(L, 1, + "object_collision", p.object_collision); p.vertical = getboolfield_default(L, 1, "vertical", p.vertical); lua_getfield(L, 1, "animation"); @@ -75,7 +75,7 @@ int ModApiParticlesLocal::l_add_particle(lua_State *L) p.node_tile = getintfield_default(L, 1, "node_tile", p.node_tile); ClientEvent *event = new ClientEvent(); - event->type = CE_SPAWN_PARTICLE; + event->type = CE_SPAWN_PARTICLE; event->spawn_particle = new ParticleParameters(p); getClient(L)->pushToEventQueue(event); @@ -126,12 +126,12 @@ int ModApiParticlesLocal::l_add_particlespawner(lua_State *L) p.maxexptime = getfloatfield_default(L, 1, "maxexptime", p.maxexptime); p.minsize = getfloatfield_default(L, 1, "minsize", p.minsize); p.maxsize = getfloatfield_default(L, 1, "maxsize", p.maxsize); - p.collisiondetection = getboolfield_default( - L, 1, "collisiondetection", p.collisiondetection); - p.collision_removal = getboolfield_default( - L, 1, "collision_removal", p.collision_removal); - p.object_collision = getboolfield_default( - L, 1, "object_collision", p.object_collision); + p.collisiondetection = getboolfield_default(L, 1, + "collisiondetection", p.collisiondetection); + p.collision_removal = getboolfield_default(L, 1, + "collision_removal", p.collision_removal); + p.object_collision = getboolfield_default(L, 1, + "object_collision", p.object_collision); lua_getfield(L, 1, "animation"); p.animation = read_animation_definition(L, -1); @@ -151,10 +151,10 @@ int ModApiParticlesLocal::l_add_particlespawner(lua_State *L) u64 id = getClient(L)->getParticleManager()->generateSpawnerId(); auto event = new ClientEvent(); - event->type = CE_ADD_PARTICLESPAWNER; - event->add_particlespawner.p = new ParticleSpawnerParameters(p); + event->type = CE_ADD_PARTICLESPAWNER; + event->add_particlespawner.p = new ParticleSpawnerParameters(p); event->add_particlespawner.attached_id = 0; - event->add_particlespawner.id = id; + event->add_particlespawner.id = id; getClient(L)->pushToEventQueue(event); lua_pushnumber(L, id); @@ -168,7 +168,7 @@ int ModApiParticlesLocal::l_delete_particlespawner(lua_State *L) u32 id = luaL_checknumber(L, 1); ClientEvent *event = new ClientEvent(); - event->type = CE_DELETE_PARTICLESPAWNER; + event->type = CE_DELETE_PARTICLESPAWNER; event->delete_particlespawner.id = id; getClient(L)->pushToEventQueue(event); diff --git a/src/script/lua_api/l_rollback.cpp b/src/script/lua_api/l_rollback.cpp index 09da123c3..482b0cbf5 100644 --- a/src/script/lua_api/l_rollback.cpp +++ b/src/script/lua_api/l_rollback.cpp @@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "server.h" #include "rollback_interface.h" + void push_RollbackNode(lua_State *L, RollbackNode &node) { lua_createtable(L, 0, 3); @@ -34,15 +35,14 @@ void push_RollbackNode(lua_State *L, RollbackNode &node) lua_setfield(L, -2, "param2"); } -// rollback_get_node_actions(pos, range, seconds, limit) -> {{actor, pos, time, oldnode, -// newnode}, ...} +// rollback_get_node_actions(pos, range, seconds, limit) -> {{actor, pos, time, oldnode, newnode}, ...} int ModApiRollback::l_rollback_get_node_actions(lua_State *L) { NO_MAP_LOCK_REQUIRED; v3s16 pos = read_v3s16(L, 1); int range = luaL_checknumber(L, 2); - time_t seconds = (time_t)luaL_checknumber(L, 3); + time_t seconds = (time_t) luaL_checknumber(L, 3); int limit = luaL_checknumber(L, 4); Server *server = getServer(L); IRollbackManager *rollback = server->getRollbackManager(); @@ -50,8 +50,7 @@ int ModApiRollback::l_rollback_get_node_actions(lua_State *L) return 0; } - std::list actions = - rollback->getNodeActors(pos, range, seconds, limit); + std::list actions = rollback->getNodeActors(pos, range, seconds, limit); std::list::iterator iter = actions.begin(); lua_createtable(L, actions.size(), 0); @@ -102,8 +101,8 @@ int ModApiRollback::l_rollback_revert_actions_by(lua_State *L) lua_pushboolean(L, success); lua_createtable(L, log.size(), 0); unsigned long i = 0; - for (std::list::const_iterator iter = log.begin(); iter != log.end(); - ++i, ++iter) { + for(std::list::const_iterator iter = log.begin(); + iter != log.end(); ++i, ++iter) { lua_pushnumber(L, i); lua_pushstring(L, iter->c_str()); lua_settable(L, -3); diff --git a/src/script/lua_api/l_rollback.h b/src/script/lua_api/l_rollback.h index 74d8ce10e..c26ff634e 100644 --- a/src/script/lua_api/l_rollback.h +++ b/src/script/lua_api/l_rollback.h @@ -24,8 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., class ModApiRollback : public ModApiBase { private: - // rollback_get_node_actions(pos, range, seconds) -> {{actor, pos, time, oldnode, - // newnode}, ...} + // rollback_get_node_actions(pos, range, seconds) -> {{actor, pos, time, oldnode, newnode}, ...} static int l_rollback_get_node_actions(lua_State *L); // rollback_revert_actions_by(actor, seconds) -> bool, log messages diff --git a/src/script/lua_api/l_server.cpp b/src/script/lua_api/l_server.cpp index f4362dd7f..64ae924d2 100644 --- a/src/script/lua_api/l_server.cpp +++ b/src/script/lua_api/l_server.cpp @@ -56,6 +56,7 @@ int ModApiServer::l_get_server_uptime(lua_State *L) return 1; } + // print(text) int ModApiServer::l_print(lua_State *L) { @@ -115,14 +116,15 @@ int ModApiServer::l_get_player_privs(lua_State *L) int ModApiServer::l_get_player_ip(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char *name = luaL_checkstring(L, 1); - RemotePlayer *player = - dynamic_cast(getEnv(L))->getPlayer(name); - if (player == NULL) { + const char * name = luaL_checkstring(L, 1); + RemotePlayer *player = dynamic_cast(getEnv(L))->getPlayer(name); + if(player == NULL) + { lua_pushnil(L); // no such player return 1; } - try { + try + { Address addr = getServer(L)->getPeerAddress(player->getPeerId()); std::string ip_str = addr.serializeString(); lua_pushstring(L, ip_str.c_str()); @@ -164,19 +166,21 @@ int ModApiServer::l_get_player_information(lua_State *L) u8 ser_vers, major, minor, patch; std::string vers_string, lang_code; - auto getConInfo = [&](con::rtt_stat_type type, float *value) -> bool { + auto getConInfo = [&] (con::rtt_stat_type type, float *value) -> bool { return server->getClientConInfo(player->getPeerId(), type, value); }; - bool have_con_info = getConInfo(con::MIN_RTT, &min_rtt) && - getConInfo(con::MAX_RTT, &max_rtt) && - getConInfo(con::AVG_RTT, &avg_rtt) && - getConInfo(con::MIN_JITTER, &min_jitter) && - getConInfo(con::MAX_JITTER, &max_jitter) && - getConInfo(con::AVG_JITTER, &avg_jitter); - - bool r = server->getClientInfo(player->getPeerId(), &state, &uptime, &ser_vers, - &prot_vers, &major, &minor, &patch, &vers_string, &lang_code); + bool have_con_info = + getConInfo(con::MIN_RTT, &min_rtt) && + getConInfo(con::MAX_RTT, &max_rtt) && + getConInfo(con::AVG_RTT, &avg_rtt) && + getConInfo(con::MIN_JITTER, &min_jitter) && + getConInfo(con::MAX_JITTER, &max_jitter) && + getConInfo(con::AVG_JITTER, &avg_jitter); + + bool r = server->getClientInfo(player->getPeerId(), &state, &uptime, + &ser_vers, &prot_vers, &major, &minor, &patch, &vers_string, + &lang_code); if (!r) { dstream << FUNCTION_NAME << ": peer was not found" << std::endl; lua_pushnil(L); // error @@ -186,11 +190,11 @@ int ModApiServer::l_get_player_information(lua_State *L) lua_newtable(L); int table = lua_gettop(L); - lua_pushstring(L, "address"); + lua_pushstring(L,"address"); lua_pushstring(L, addr.serializeString().c_str()); lua_settable(L, table); - lua_pushstring(L, "ip_version"); + lua_pushstring(L,"ip_version"); if (addr.getFamily() == AF_INET) { lua_pushnumber(L, 4); } else if (addr.getFamily() == AF_INET6) { @@ -226,11 +230,11 @@ int ModApiServer::l_get_player_information(lua_State *L) lua_settable(L, table); } - lua_pushstring(L, "connection_uptime"); + lua_pushstring(L,"connection_uptime"); lua_pushnumber(L, uptime); lua_settable(L, table); - lua_pushstring(L, "protocol_version"); + lua_pushstring(L,"protocol_version"); lua_pushnumber(L, prot_vers); lua_settable(L, table); @@ -243,28 +247,28 @@ int ModApiServer::l_get_player_information(lua_State *L) lua_settable(L, table); #ifndef NDEBUG - lua_pushstring(L, "serialization_version"); + lua_pushstring(L,"serialization_version"); lua_pushnumber(L, ser_vers); lua_settable(L, table); - lua_pushstring(L, "major"); + lua_pushstring(L,"major"); lua_pushnumber(L, major); lua_settable(L, table); - lua_pushstring(L, "minor"); + lua_pushstring(L,"minor"); lua_pushnumber(L, minor); lua_settable(L, table); - lua_pushstring(L, "patch"); + lua_pushstring(L,"patch"); lua_pushnumber(L, patch); lua_settable(L, table); - lua_pushstring(L, "version_string"); + lua_pushstring(L,"version_string"); lua_pushstring(L, vers_string.c_str()); lua_settable(L, table); - lua_pushstring(L, "state"); - lua_pushstring(L, ClientInterface::state2Name(state).c_str()); + lua_pushstring(L,"state"); + lua_pushstring(L,ClientInterface::state2Name(state).c_str()); lua_settable(L, table); #endif @@ -283,9 +287,8 @@ int ModApiServer::l_get_ban_list(lua_State *L) int ModApiServer::l_get_ban_description(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char *ip_or_name = luaL_checkstring(L, 1); - lua_pushstring(L, - getServer(L)->getBanDescription(std::string(ip_or_name)).c_str()); + const char * ip_or_name = luaL_checkstring(L, 1); + lua_pushstring(L, getServer(L)->getBanDescription(std::string(ip_or_name)).c_str()); return 1; } @@ -293,21 +296,19 @@ int ModApiServer::l_get_ban_description(lua_State *L) int ModApiServer::l_ban_player(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char *name = luaL_checkstring(L, 1); - RemotePlayer *player = - dynamic_cast(getEnv(L))->getPlayer(name); + const char * name = luaL_checkstring(L, 1); + RemotePlayer *player = dynamic_cast(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(getEnv(L)) - ->getPlayer(name) - ->getPeerId()); + dynamic_cast(getEnv(L))->getPlayer(name)->getPeerId()); std::string ip_str = addr.serializeString(); getServer(L)->setIpBanned(ip_str, name); - } catch (const con::PeerNotFoundException &) { + } catch(const con::PeerNotFoundException &) { dstream << FUNCTION_NAME << ": peer was not found" << std::endl; lua_pushboolean(L, false); // error return 1; @@ -327,8 +328,7 @@ int ModApiServer::l_kick_player(lua_State *L) else message.append("."); - RemotePlayer *player = - dynamic_cast(getEnv(L))->getPlayer(name); + RemotePlayer *player = dynamic_cast(getEnv(L))->getPlayer(name); if (player == NULL) { lua_pushboolean(L, false); // No such player return 1; @@ -359,7 +359,7 @@ int ModApiServer::l_remove_player(lua_State *L) int ModApiServer::l_unban_player_or_ip(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char *ip_or_name = luaL_checkstring(L, 1); + const char * ip_or_name = luaL_checkstring(L, 1); getServer(L)->unsetIpBanned(ip_or_name); lua_pushboolean(L, true); return 1; @@ -373,9 +373,10 @@ int ModApiServer::l_show_formspec(lua_State *L) const char *formname = luaL_checkstring(L, 2); const char *formspec = luaL_checkstring(L, 3); - if (getServer(L)->showFormspec(playername, formspec, formname)) { + if(getServer(L)->showFormspec(playername,formspec,formname)) + { lua_pushboolean(L, true); - } else { + }else{ lua_pushboolean(L, false); } return 1; @@ -479,8 +480,7 @@ int ModApiServer::l_dynamic_add_media(lua_State *L) // Reject adding media before the server has started up if (!getEnv(L)) - throw LuaError("Dynamic media cannot be added before server has started " - "up"); + throw LuaError("Dynamic media cannot be added before server has started up"); std::string filepath = readParam(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(L, 1); getServer(L)->reportPrivsModified(name); return 0; @@ -529,7 +529,7 @@ int ModApiServer::l_set_last_run_mod(lua_State *L) #ifdef SCRIPTAPI_DEBUG const char *mod = lua_tostring(L, 1); getScriptApiBase(L)->setOriginDirect(mod); - // printf(">>>> last mod set from Lua: %s\n", mod); + //printf(">>>> last mod set from Lua: %s\n", mod); #endif return 0; } diff --git a/src/script/lua_api/l_settings.cpp b/src/script/lua_api/l_settings.cpp index cc4b23ee4..33eb02392 100644 --- a/src/script/lua_api/l_settings.cpp +++ b/src/script/lua_api/l_settings.cpp @@ -25,20 +25,23 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "noise.h" #include "log.h" -#define SET_SECURITY_CHECK(L, name) \ - if (o->m_settings == g_settings && ScriptApiSecurity::isSecure(L) && \ - name.compare(0, 7, "secure.") == 0) { \ - throw LuaError("Attempt to set secure setting."); \ + +#define SET_SECURITY_CHECK(L, name) \ + if (o->m_settings == g_settings && ScriptApiSecurity::isSecure(L) && \ + name.compare(0, 7, "secure.") == 0) { \ + throw LuaError("Attempt to set secure setting."); \ } LuaSettings::LuaSettings(Settings *settings, const std::string &filename) : - m_settings(settings), m_filename(filename) + m_settings(settings), + m_filename(filename) { } LuaSettings::LuaSettings(const std::string &filename, bool write_allowed) : - m_filename(filename), m_is_own_settings(true), - m_write_allowed(write_allowed) + m_filename(filename), + m_is_own_settings(true), + m_write_allowed(write_allowed) { m_settings = new Settings(); m_settings->readConfigFile(filename.c_str()); @@ -50,7 +53,9 @@ LuaSettings::~LuaSettings() delete m_settings; } -void LuaSettings::create(lua_State *L, Settings *settings, const std::string &filename) + +void LuaSettings::create(lua_State *L, Settings *settings, + const std::string &filename) { LuaSettings *o = new LuaSettings(settings, filename); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; @@ -58,19 +63,21 @@ void LuaSettings::create(lua_State *L, Settings *settings, const std::string &fi lua_setmetatable(L, -2); } + // garbage collector -int LuaSettings::gc_object(lua_State *L) +int LuaSettings::gc_object(lua_State* L) { - LuaSettings *o = *(LuaSettings **)(lua_touserdata(L, 1)); + LuaSettings* o = *(LuaSettings **)(lua_touserdata(L, 1)); delete o; return 0; } + // get(self, key) -> value -int LuaSettings::l_get(lua_State *L) +int LuaSettings::l_get(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); if (o->m_settings->exists(key)) { @@ -84,10 +91,10 @@ int LuaSettings::l_get(lua_State *L) } // get_bool(self, key) -> boolean -int LuaSettings::l_get_bool(lua_State *L) +int LuaSettings::l_get_bool(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); if (o->m_settings->exists(key)) { @@ -146,13 +153,13 @@ int LuaSettings::l_get_flags(lua_State *L) } // set(self, key, value) -int LuaSettings::l_set(lua_State *L) +int LuaSettings::l_set(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); - const char *value = luaL_checkstring(L, 3); + const char* value = luaL_checkstring(L, 3); SET_SECURITY_CHECK(L, key); @@ -163,10 +170,10 @@ int LuaSettings::l_set(lua_State *L) } // set_bool(self, key, value) -int LuaSettings::l_set_bool(lua_State *L) +int LuaSettings::l_set_bool(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); bool value = readParam(L, 3); @@ -196,10 +203,10 @@ int LuaSettings::l_set_np_group(lua_State *L) } // remove(self, key) -> success -int LuaSettings::l_remove(lua_State *L) +int LuaSettings::l_remove(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); @@ -212,15 +219,16 @@ int LuaSettings::l_remove(lua_State *L) } // get_names(self) -> {key1, ...} -int LuaSettings::l_get_names(lua_State *L) +int LuaSettings::l_get_names(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::vector keys = o->m_settings->getNames(); lua_newtable(L); - for (unsigned int i = 0; i < keys.size(); i++) { + for (unsigned int i=0; i < keys.size(); i++) + { lua_pushstring(L, keys[i].c_str()); lua_rawseti(L, -2, i + 1); } @@ -229,10 +237,10 @@ int LuaSettings::l_get_names(lua_State *L) } // write(self) -> success -int LuaSettings::l_write(lua_State *L) +int LuaSettings::l_write(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); if (!o->m_write_allowed) { throw LuaError("Settings: writing " + o->m_filename + @@ -246,10 +254,10 @@ int LuaSettings::l_write(lua_State *L) } // to_table(self) -> {[key1]=value1,...} -int LuaSettings::l_to_table(lua_State *L) +int LuaSettings::l_to_table(lua_State* L) { NO_MAP_LOCK_REQUIRED; - LuaSettings *o = checkobject(L, 1); + LuaSettings* o = checkobject(L, 1); std::vector keys = o->m_settings->getNames(); @@ -262,7 +270,8 @@ int LuaSettings::l_to_table(lua_State *L) return 1; } -void LuaSettings::Register(lua_State *L) + +void LuaSettings::Register(lua_State* L) { lua_newtable(L); int methodtable = lua_gettop(L); @@ -271,7 +280,7 @@ void LuaSettings::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -281,10 +290,10 @@ void LuaSettings::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Can be created from Lua (Settings(filename)) lua_register(L, className, create_object); @@ -292,33 +301,41 @@ void LuaSettings::Register(lua_State *L) // LuaSettings(filename) // Creates a LuaSettings and leaves it on top of the stack -int LuaSettings::create_object(lua_State *L) +int LuaSettings::create_object(lua_State* L) { NO_MAP_LOCK_REQUIRED; bool write_allowed = true; - const char *filename = luaL_checkstring(L, 1); + const char* filename = luaL_checkstring(L, 1); CHECK_SECURE_PATH_POSSIBLE_WRITE(L, filename, &write_allowed); - LuaSettings *o = new LuaSettings(filename, write_allowed); + LuaSettings* o = new LuaSettings(filename, write_allowed); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } -LuaSettings *LuaSettings::checkobject(lua_State *L, int narg) +LuaSettings* LuaSettings::checkobject(lua_State* L, int narg) { NO_MAP_LOCK_REQUIRED; luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); if (!ud) luaL_typerror(L, narg, className); - return *(LuaSettings **)ud; // unbox pointer + return *(LuaSettings**) ud; // unbox pointer } const char LuaSettings::className[] = "Settings"; -const luaL_Reg LuaSettings::methods[] = {luamethod(LuaSettings, get), - luamethod(LuaSettings, get_bool), luamethod(LuaSettings, get_np_group), - luamethod(LuaSettings, get_flags), luamethod(LuaSettings, set), - luamethod(LuaSettings, set_bool), luamethod(LuaSettings, set_np_group), - luamethod(LuaSettings, remove), luamethod(LuaSettings, get_names), - luamethod(LuaSettings, write), luamethod(LuaSettings, to_table), {0, 0}}; +const luaL_Reg LuaSettings::methods[] = { + luamethod(LuaSettings, get), + luamethod(LuaSettings, get_bool), + luamethod(LuaSettings, get_np_group), + luamethod(LuaSettings, get_flags), + luamethod(LuaSettings, set), + luamethod(LuaSettings, set_bool), + luamethod(LuaSettings, set_np_group), + luamethod(LuaSettings, remove), + luamethod(LuaSettings, get_names), + luamethod(LuaSettings, write), + luamethod(LuaSettings, to_table), + {0,0} +}; diff --git a/src/script/lua_api/l_sound.cpp b/src/script/lua_api/l_sound.cpp index bd9ec2543..b86eda53e 100644 --- a/src/script/lua_api/l_sound.cpp +++ b/src/script/lua_api/l_sound.cpp @@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "common/c_content.h" #include "gui/guiEngine.h" + int ModApiSound::l_sound_play(lua_State *L) { SimpleSoundSpec spec; diff --git a/src/script/lua_api/l_storage.cpp b/src/script/lua_api/l_storage.cpp index fe3b4d74c..cba34fb63 100644 --- a/src/script/lua_api/l_storage.cpp +++ b/src/script/lua_api/l_storage.cpp @@ -53,7 +53,8 @@ void ModApiStorage::Initialize(lua_State *L, int top) API_FCT(get_mod_storage); } -StorageRef::StorageRef(ModMetadata *object) : m_object(object) +StorageRef::StorageRef(ModMetadata *object): + m_object(object) { } @@ -89,7 +90,7 @@ void StorageRef::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "metadata_class"); lua_pushlstring(L, className, strlen(className)); @@ -107,28 +108,27 @@ void StorageRef::Register(lua_State *L) lua_pushcfunction(L, l_equals); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable } -StorageRef *StorageRef::checkobject(lua_State *L, int narg) +StorageRef* StorageRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); - if (!ud) - luaL_typerror(L, narg, className); - return *(StorageRef **)ud; // unbox pointer + if (!ud) luaL_typerror(L, narg, className); + return *(StorageRef**)ud; // unbox pointer } -ModMetadata *StorageRef::getobject(StorageRef *ref) +ModMetadata* StorageRef::getobject(StorageRef *ref) { ModMetadata *co = ref->m_object; return co; } -Metadata *StorageRef::getmeta(bool auto_create) +Metadata* StorageRef::getmeta(bool auto_create) { return m_object; } @@ -139,10 +139,17 @@ void StorageRef::clearMeta() } const char StorageRef::className[] = "StorageRef"; -const luaL_Reg StorageRef::methods[] = {luamethod(MetaDataRef, contains), - luamethod(MetaDataRef, get), luamethod(MetaDataRef, get_string), - luamethod(MetaDataRef, set_string), luamethod(MetaDataRef, get_int), - luamethod(MetaDataRef, set_int), luamethod(MetaDataRef, get_float), - luamethod(MetaDataRef, set_float), luamethod(MetaDataRef, to_table), - luamethod(MetaDataRef, from_table), luamethod(MetaDataRef, equals), - {0, 0}}; +const luaL_Reg StorageRef::methods[] = { + luamethod(MetaDataRef, contains), + luamethod(MetaDataRef, get), + luamethod(MetaDataRef, get_string), + luamethod(MetaDataRef, set_string), + luamethod(MetaDataRef, get_int), + luamethod(MetaDataRef, set_int), + luamethod(MetaDataRef, get_float), + luamethod(MetaDataRef, set_float), + luamethod(MetaDataRef, to_table), + luamethod(MetaDataRef, from_table), + luamethod(MetaDataRef, equals), + {0,0} +}; diff --git a/src/script/lua_api/l_util.cpp b/src/script/lua_api/l_util.cpp index b77e26886..4595dc1c1 100644 --- a/src/script/lua_api/l_util.cpp +++ b/src/script/lua_api/l_util.cpp @@ -41,6 +41,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/sha1.h" #include + // log([level,] text) // Writes a line to the logger. // The one-argument version logs to LL_NONE. @@ -64,7 +65,7 @@ int ModApiUtil::l_log(lua_State *L) level = Logger::stringToLevel(name); if (level == LL_MAX) { warningstream << "Tried to log at unknown level '" << name - << "'. Defaulting to \"none\"." << std::endl; + << "'. Defaulting to \"none\"." << std::endl; level = LL_NONE; } } @@ -108,10 +109,8 @@ int ModApiUtil::l_parse_json(lua_State *L) size_t jlen = strlen(jsonstr); if (jlen > 100) { errorstream << "Data (" << jlen - << " bytes) printed to warningstream." - << std::endl; - warningstream << "data: \"" << jsonstr << "\"" - << std::endl; + << " bytes) printed to warningstream." << std::endl; + warningstream << "data: \"" << jsonstr << "\"" << std::endl; } else { errorstream << "data: \"" << jsonstr << "\"" << std::endl; } @@ -122,7 +121,7 @@ int ModApiUtil::l_parse_json(lua_State *L) if (!push_json_value(L, root, nullindex)) { errorstream << "Failed to parse json data, " - << "depth exceeds lua stack limit" << std::endl; + << "depth exceeds lua stack limit" << std::endl; errorstream << "data: \"" << jsonstr << "\"" << std::endl; lua_pushnil(L); } @@ -177,7 +176,7 @@ int ModApiUtil::l_get_hit_params(lua_State *L) std::unordered_map 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(L, 3))); @@ -229,9 +228,9 @@ int ModApiUtil::l_is_yes(lua_State *L) { NO_MAP_LOCK_REQUIRED; - lua_getglobal(L, "tostring"); // function to be called - lua_pushvalue(L, 1); // 1st argument - lua_call(L, 1, 1); // execute function + lua_getglobal(L, "tostring"); // function to be called + lua_pushvalue(L, 1); // 1st argument + lua_call(L, 1, 1); // execute function std::string str = readParam(L, -1); // get result lua_pop(L, 1); @@ -346,7 +345,7 @@ int ModApiUtil::l_get_dir_list(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *path = luaL_checkstring(L, 1); - bool list_all = !lua_isboolean(L, 2); // if its not a boolean list all + bool list_all = !lua_isboolean(L, 2); // if its not a boolean list all bool list_dirs = readParam(L, 2); // true: list dirs, false: list files CHECK_SECURE_PATH(L, path, false); @@ -417,11 +416,12 @@ int ModApiUtil::l_request_insecure_environment(lua_State *L) // Check secure.trusted_mods std::string mod_name = readParam(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(&std::isspace)), + trusted_mods.erase(std::remove_if(trusted_mods.begin(), + trusted_mods.end(), static_cast(&std::isspace)), trusted_mods.end()); std::vector mod_list = str_split(trusted_mods, ','); - if (std::find(mod_list.begin(), mod_list.end(), mod_name) == mod_list.end()) { + if (std::find(mod_list.begin(), mod_list.end(), mod_name) == + mod_list.end()) { return 0; } @@ -463,7 +463,7 @@ int ModApiUtil::l_sha1(lua_State *L) SHA1 ctx; ctx.addBytes(data, size); unsigned char *data_tmpdigest = ctx.getDigest(); - data_sha1.assign((char *)data_tmpdigest, 20); + data_sha1.assign((char*) data_tmpdigest, 20); free(data_tmpdigest); } @@ -527,7 +527,7 @@ void ModApiUtil::InitializeClient(lua_State *L, int top) API_FCT(is_yes); API_FCT(is_nan); - + API_FCT(compress); API_FCT(decompress); @@ -538,7 +538,7 @@ void ModApiUtil::InitializeClient(lua_State *L, int top) API_FCT(get_version); API_FCT(sha1); - + LuaSettings::create(L, g_settings, g_settings_path); lua_setfield(L, top, "settings"); } @@ -571,3 +571,4 @@ void ModApiUtil::InitializeAsync(lua_State *L, int top) LuaSettings::create(L, g_settings, g_settings_path); lua_setfield(L, top, "settings"); } + diff --git a/src/script/lua_api/l_vmanip.cpp b/src/script/lua_api/l_vmanip.cpp index 17fb830f9..b99b1d98c 100644 --- a/src/script/lua_api/l_vmanip.cpp +++ b/src/script/lua_api/l_vmanip.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ + #include "lua_api/l_vmanip.h" #include "lua_api/l_internal.h" #include "common/c_content.h" @@ -62,7 +63,7 @@ int LuaVoxelManip::l_get_data(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); - bool use_buffer = lua_istable(L, 2); + bool use_buffer = lua_istable(L, 2); MMVManip *vm = o->vm; @@ -116,7 +117,8 @@ int LuaVoxelManip::l_write_to_map(lua_State *L) if (o->is_mapgen_vm || !update_light) { o->vm->blitBackAll(&(o->modified_blocks)); } else { - voxalgo::blit_back_with_light(map, o->vm, &(o->modified_blocks)); + voxalgo::blit_back_with_light(map, o->vm, + &(o->modified_blocks)); } MapEditEvent event; @@ -137,7 +139,7 @@ int LuaVoxelManip::l_get_node_at(lua_State *L) const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); LuaVoxelManip *o = checkobject(L, 1); - v3s16 pos = check_v3s16(L, 2); + v3s16 pos = check_v3s16(L, 2); pushnode(L, o->vm->getNodeNoExNoEmerge(pos), ndef); return 1; @@ -150,8 +152,8 @@ int LuaVoxelManip::l_set_node_at(lua_State *L) const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); LuaVoxelManip *o = checkobject(L, 1); - v3s16 pos = check_v3s16(L, 2); - MapNode n = readnode(L, 3, ndef); + v3s16 pos = check_v3s16(L, 2); + MapNode n = readnode(L, 3, ndef); o->vm->setNodeNoEmerge(pos, n); @@ -169,11 +171,11 @@ int LuaVoxelManip::l_update_liquids(lua_State *L) MMVManip *vm = o->vm; Mapgen mg; - mg.vm = vm; + mg.vm = vm; mg.ndef = ndef; - mg.updateLiquid(&map->m_transforming_liquid, vm->m_area.MinEdge, - vm->m_area.MaxEdge); + mg.updateLiquid(&map->m_transforming_liquid, + vm->m_area.MinEdge, vm->m_area.MaxEdge); return 0; } @@ -185,8 +187,7 @@ int LuaVoxelManip::l_calc_lighting(lua_State *L) LuaVoxelManip *o = checkobject(L, 1); if (!o->is_mapgen_vm) { warningstream << "VoxelManip:calc_lighting called for a non-mapgen " - "VoxelManip object" - << std::endl; + "VoxelManip object" << std::endl; return 0; } @@ -195,10 +196,10 @@ int LuaVoxelManip::l_calc_lighting(lua_State *L) MMVManip *vm = o->vm; v3s16 yblock = v3s16(0, 1, 0) * MAP_BLOCKSIZE; - v3s16 fpmin = vm->m_area.MinEdge; - v3s16 fpmax = vm->m_area.MaxEdge; - v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : fpmin + yblock; - v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : fpmax - yblock; + v3s16 fpmin = vm->m_area.MinEdge; + v3s16 fpmax = vm->m_area.MaxEdge; + v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : fpmin + yblock; + v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : fpmax - yblock; bool propagate_shadow = !lua_isboolean(L, 4) || readParam(L, 4); sortBoxVerticies(pmin, pmax); @@ -206,8 +207,8 @@ int LuaVoxelManip::l_calc_lighting(lua_State *L) throw LuaError("Specified voxel area out of VoxelManipulator bounds"); Mapgen mg; - mg.vm = vm; - mg.ndef = ndef; + mg.vm = vm; + mg.ndef = ndef; mg.water_level = emerge->mgparams->water_level; mg.calcLighting(pmin, pmax, fpmin, fpmax, propagate_shadow); @@ -222,8 +223,7 @@ int LuaVoxelManip::l_set_lighting(lua_State *L) LuaVoxelManip *o = checkobject(L, 1); if (!o->is_mapgen_vm) { warningstream << "VoxelManip:set_lighting called for a non-mapgen " - "VoxelManip object" - << std::endl; + "VoxelManip object" << std::endl; return 0; } @@ -231,7 +231,7 @@ int LuaVoxelManip::l_set_lighting(lua_State *L) throw LuaError("VoxelManip:set_lighting called with missing parameter"); u8 light; - light = (getintfield_default(L, 2, "day", 0) & 0x0F); + light = (getintfield_default(L, 2, "day", 0) & 0x0F); light |= (getintfield_default(L, 2, "night", 0) & 0x0F) << 4; MMVManip *vm = o->vm; @@ -280,7 +280,7 @@ int LuaVoxelManip::l_set_light_data(lua_State *L) if (!lua_istable(L, 2)) throw LuaError("VoxelManip:set_light_data called with missing " - "parameter"); + "parameter"); u32 volume = vm->m_area.getVolume(); for (u32 i = 0; i != volume; i++) { @@ -300,7 +300,7 @@ int LuaVoxelManip::l_get_param2_data(lua_State *L) NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); - bool use_buffer = lua_istable(L, 2); + bool use_buffer = lua_istable(L, 2); MMVManip *vm = o->vm; @@ -329,7 +329,7 @@ int LuaVoxelManip::l_set_param2_data(lua_State *L) if (!lua_istable(L, 2)) throw LuaError("VoxelManip:set_param2_data called with missing " - "parameter"); + "parameter"); u32 volume = vm->m_area.getVolume(); for (u32 i = 0; i != volume; i++) { @@ -374,7 +374,8 @@ int LuaVoxelManip::l_get_emerged_area(lua_State *L) } LuaVoxelManip::LuaVoxelManip(MMVManip *mmvm, bool is_mg_vm) : - is_mapgen_vm(is_mg_vm), vm(mmvm) + is_mapgen_vm(is_mg_vm), + vm(mmvm) { } @@ -405,10 +406,9 @@ int LuaVoxelManip::create_object(lua_State *L) GET_ENV_PTR; Map *map = &(env->getMap()); - LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) - ? new LuaVoxelManip(map, check_v3s16(L, 1), - check_v3s16(L, 2)) - : new LuaVoxelManip(map); + LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ? + new LuaVoxelManip(map, check_v3s16(L, 1), check_v3s16(L, 2)) : + new LuaVoxelManip(map); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); @@ -426,7 +426,7 @@ LuaVoxelManip *LuaVoxelManip::checkobject(lua_State *L, int narg) if (!ud) luaL_typerror(L, narg, className); - return *(LuaVoxelManip **)ud; // unbox pointer + return *(LuaVoxelManip **)ud; // unbox pointer } void LuaVoxelManip::Register(lua_State *L) @@ -438,7 +438,7 @@ void LuaVoxelManip::Register(lua_State *L) lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); - lua_settable(L, metatable); // hide metatable from Lua getmetatable() + lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); @@ -448,28 +448,32 @@ void LuaVoxelManip::Register(lua_State *L) lua_pushcfunction(L, gc_object); lua_settable(L, metatable); - lua_pop(L, 1); // drop metatable + lua_pop(L, 1); // drop metatable - luaL_openlib(L, 0, methods, 0); // fill methodtable - lua_pop(L, 1); // drop methodtable + luaL_openlib(L, 0, methods, 0); // fill methodtable + lua_pop(L, 1); // drop methodtable // Can be created from Lua (VoxelManip()) lua_register(L, className, create_object); } const char LuaVoxelManip::className[] = "VoxelManip"; -const luaL_Reg LuaVoxelManip::methods[] = {luamethod(LuaVoxelManip, read_from_map), - luamethod(LuaVoxelManip, get_data), luamethod(LuaVoxelManip, set_data), - luamethod(LuaVoxelManip, get_node_at), - luamethod(LuaVoxelManip, set_node_at), - luamethod(LuaVoxelManip, write_to_map), - luamethod(LuaVoxelManip, update_map), - luamethod(LuaVoxelManip, update_liquids), - luamethod(LuaVoxelManip, calc_lighting), - luamethod(LuaVoxelManip, set_lighting), - luamethod(LuaVoxelManip, get_light_data), - luamethod(LuaVoxelManip, set_light_data), - luamethod(LuaVoxelManip, get_param2_data), - luamethod(LuaVoxelManip, set_param2_data), - luamethod(LuaVoxelManip, was_modified), - luamethod(LuaVoxelManip, get_emerged_area), {0, 0}}; +const luaL_Reg LuaVoxelManip::methods[] = { + luamethod(LuaVoxelManip, read_from_map), + luamethod(LuaVoxelManip, get_data), + luamethod(LuaVoxelManip, set_data), + luamethod(LuaVoxelManip, get_node_at), + luamethod(LuaVoxelManip, set_node_at), + luamethod(LuaVoxelManip, write_to_map), + luamethod(LuaVoxelManip, update_map), + luamethod(LuaVoxelManip, update_liquids), + luamethod(LuaVoxelManip, calc_lighting), + luamethod(LuaVoxelManip, set_lighting), + luamethod(LuaVoxelManip, get_light_data), + luamethod(LuaVoxelManip, set_light_data), + luamethod(LuaVoxelManip, get_param2_data), + luamethod(LuaVoxelManip, set_param2_data), + luamethod(LuaVoxelManip, was_modified), + luamethod(LuaVoxelManip, get_emerged_area), + {0,0} +}; -- cgit v1.2.3