code
string
repo_name
string
path
string
language
string
license
string
size
int64
set(common_SCRIPT_LUA_API_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/l_areastore.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_auth.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_base.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_craft.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_env.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_http.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_inventory.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_item.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_itemstackmeta.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_mapgen.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_metadata.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_modchannels.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_nodemeta.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_nodetimer.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_noise.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_object.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_particles.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_playermeta.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_rollback.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_server.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_settings.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_storage.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_util.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_vmanip.cpp PARENT_SCOPE) set(client_SCRIPT_LUA_API_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/l_camera.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_client.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_localplayer.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_mainmenu.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_minimap.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_particles_local.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_sound.cpp ${CMAKE_CURRENT_SOURCE_DIR}/l_storage.cpp PARENT_SCOPE)
pgimeno/minetest
src/script/lua_api/CMakeLists.txt
Text
mit
1,476
/* Minetest Copyright (C) 2015 est31 <mtest31@outlook.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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" #include "cpp_api/s_security.h" #include "irr_v3d.h" #include "util/areastore.h" #include "filesys.h" #include <fstream> 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; *borders = lua_toboolean(L, start_i); if (!lua_isboolean(L, start_i + 1)) return; *data = lua_toboolean(L, start_i + 1); } 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); return; } lua_newtable(L); if (include_borders) { push_v3s16(L, a->minedge); lua_setfield(L, -2, "min"); push_v3s16(L, a->maxedge); lua_setfield(L, -2, "max"); } if (include_data) { lua_pushlstring(L, a->data.c_str(), a->data.size()); lua_setfield(L, -2, "data"); } } static inline void push_areas(lua_State *L, const std::vector<Area *> &areas, bool borders, bool data) { lua_newtable(L); size_t cnt = areas.size(); for (size_t i = 0; i < cnt; i++) { lua_pushnumber(L, areas[i]->id); push_area(L, areas[i], borders, data); lua_settable(L, -3); } } // Deserializes value and handles errors static int deserialization_helper(lua_State *L, AreaStore *as, std::istream &is) { try { as->deserialize(is); } catch (const SerializationError &e) { lua_pushboolean(L, false); lua_pushstring(L, e.what()); return 2; } lua_pushboolean(L, true); return 1; } // garbage collector int LuaAreaStore::gc_object(lua_State *L) { LuaAreaStore *o = *(LuaAreaStore **)(lua_touserdata(L, 1)); delete o; return 0; } // get_area(id, include_borders, include_data) int LuaAreaStore::l_get_area(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaAreaStore *o = checkobject(L, 1); AreaStore *ast = o->as; u32 id = luaL_checknumber(L, 2); bool include_borders = true; bool include_data = false; get_data_and_border_flags(L, 3, &include_borders, &include_data); const Area *res; res = ast->getArea(id); if (!res) return 0; push_area(L, res, include_borders, include_data); return 1; } // get_areas_for_pos(pos, include_borders, include_data) int LuaAreaStore::l_get_areas_for_pos(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaAreaStore *o = checkobject(L, 1); AreaStore *ast = o->as; v3s16 pos = check_v3s16(L, 2); bool include_borders = true; bool include_data = false; get_data_and_border_flags(L, 3, &include_borders, &include_data); std::vector<Area *> res; ast->getAreasForPos(&res, pos); push_areas(L, res, include_borders, include_data); return 1; } // get_areas_in_area(edge1, edge2, accept_overlap, include_borders, include_data) int LuaAreaStore::l_get_areas_in_area(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaAreaStore *o = checkobject(L, 1); AreaStore *ast = o->as; v3s16 minedge = check_v3s16(L, 2); v3s16 maxedge = check_v3s16(L, 3); bool include_borders = true; bool include_data = false; bool accept_overlap = false; if (lua_isboolean(L, 4)) { accept_overlap = readParam<bool>(L, 4); get_data_and_border_flags(L, 5, &include_borders, &include_data); } std::vector<Area *> res; ast->getAreasInArea(&res, minedge, maxedge, accept_overlap); push_areas(L, res, include_borders, include_data); return 1; } // insert_area(edge1, edge2, data, id) int LuaAreaStore::l_insert_area(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaAreaStore *o = checkobject(L, 1); AreaStore *ast = o->as; Area a(check_v3s16(L, 2), check_v3s16(L, 3)); size_t d_len; const char *data = luaL_checklstring(L, 4, &d_len); a.data = std::string(data, d_len); if (lua_isnumber(L, 5)) a.id = lua_tonumber(L, 5); if (!ast->insertArea(&a)) return 0; lua_pushnumber(L, a.id); return 1; } // reserve(count) int LuaAreaStore::l_reserve(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaAreaStore *o = checkobject(L, 1); AreaStore *ast = o->as; size_t count = luaL_checknumber(L, 2); ast->reserve(count); return 0; } // remove_area(id) int LuaAreaStore::l_remove_area(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaAreaStore *o = checkobject(L, 1); AreaStore *ast = o->as; u32 id = luaL_checknumber(L, 2); bool success = ast->removeArea(id); lua_pushboolean(L, success); return 1; } // set_cache_params(params) int LuaAreaStore::l_set_cache_params(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaAreaStore *o = checkobject(L, 1); AreaStore *ast = o->as; luaL_checktype(L, 2, LUA_TTABLE); bool enabled = getboolfield_default(L, 2, "enabled", true); u8 block_radius = getintfield_default(L, 2, "block_radius", 64); size_t limit = getintfield_default(L, 2, "block_radius", 1000); ast->setCacheParams(enabled, block_radius, limit); return 0; } // to_string() int LuaAreaStore::l_to_string(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaAreaStore *o = checkobject(L, 1); std::ostringstream os(std::ios_base::binary); o->as->serialize(os); std::string str = os.str(); lua_pushlstring(L, str.c_str(), str.length()); return 1; } // to_file(filename) int LuaAreaStore::l_to_file(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaAreaStore *o = checkobject(L, 1); AreaStore *ast = o->as; const char *filename = luaL_checkstring(L, 2); CHECK_SECURE_PATH(L, filename, true); std::ostringstream os(std::ios_base::binary); ast->serialize(os); lua_pushboolean(L, fs::safeWriteToFile(filename, os.str())); return 1; } // from_string(str) int LuaAreaStore::l_from_string(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaAreaStore *o = checkobject(L, 1); size_t len; const char *str = luaL_checklstring(L, 2, &len); std::istringstream is(std::string(str, len), std::ios::binary); return deserialization_helper(L, o->as, is); } // from_file(filename) int LuaAreaStore::l_from_file(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaAreaStore *o = checkobject(L, 1); const char *filename = luaL_checkstring(L, 2); CHECK_SECURE_PATH(L, filename, false); std::ifstream is(filename, std::ios::binary); return deserialization_helper(L, o->as, is); } LuaAreaStore::LuaAreaStore() : as(AreaStore::getOptimalImplementation()) { } LuaAreaStore::LuaAreaStore(const std::string &type) { #if USE_SPATIAL if (type == "LibSpatial") { as = new SpatialAreaStore(); } else #endif { as = new VectorAreaStore(); } } LuaAreaStore::~LuaAreaStore() { delete as; } // LuaAreaStore() // Creates an LuaAreaStore and leaves it on top of stack int LuaAreaStore::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaAreaStore *o = (lua_isstring(L, 1)) ? new LuaAreaStore(readParam<std::string>(L, 1)) : new LuaAreaStore(); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } LuaAreaStore *LuaAreaStore::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 *(LuaAreaStore **)ud; // unbox pointer } void LuaAreaStore::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); // drop metatable 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} };
pgimeno/minetest
src/script/lua_api/l_areastore.cpp
C++
mit
9,064
/* Minetest Copyright (C) 2015 est31 <mtest31@outlook.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" class AreaStore; class LuaAreaStore : public ModApiBase { private: static const char className[]; static const luaL_Reg methods[]; static int gc_object(lua_State *L); static int l_get_area(lua_State *L); static int l_get_areas_for_pos(lua_State *L); static int l_get_areas_in_area(lua_State *L); static int l_insert_area(lua_State *L); static int l_reserve(lua_State *L); static int l_remove_area(lua_State *L); static int l_set_cache_params(lua_State *L); static int l_to_string(lua_State *L); static int l_to_file(lua_State *L); static int l_from_string(lua_State *L); static int l_from_file(lua_State *L); public: AreaStore *as = nullptr; LuaAreaStore(); LuaAreaStore(const std::string &type); ~LuaAreaStore(); // AreaStore() // Creates a AreaStore and leaves it on top of stack static int create_object(lua_State *L); static LuaAreaStore *checkobject(lua_State *L, int narg); static void Register(lua_State *L); };
pgimeno/minetest
src/script/lua_api/l_areastore.h
C++
mit
1,764
/* Minetest Copyright (C) 2018 bendeutsch, Ben Deutsch <ben@bendeutsch.de> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_auth.h" #include "lua_api/l_internal.h" #include "common/c_converter.h" #include "common/c_content.h" #include "cpp_api/s_base.h" #include "server.h" #include "environment.h" #include "database/database.h" #include <algorithm> // common start: ensure auth db AuthDatabase *ModApiAuth::getAuthDb(lua_State *L) { ServerEnvironment *server_environment = dynamic_cast<ServerEnvironment *>(getEnv(L)); if (!server_environment) return nullptr; return server_environment->getAuthDatabase(); } void ModApiAuth::pushAuthEntry(lua_State *L, const AuthEntry &authEntry) { lua_newtable(L); int table = lua_gettop(L); // id lua_pushnumber(L, authEntry.id); lua_setfield(L, table, "id"); // name lua_pushstring(L, authEntry.name.c_str()); lua_setfield(L, table, "name"); // password lua_pushstring(L, authEntry.password.c_str()); lua_setfield(L, table, "password"); // privileges lua_newtable(L); int privtable = lua_gettop(L); for (const std::string &privs : authEntry.privileges) { lua_pushboolean(L, true); lua_setfield(L, privtable, privs.c_str()); } lua_setfield(L, table, "privileges"); // last_login lua_pushnumber(L, authEntry.last_login); lua_setfield(L, table, "last_login"); lua_pushvalue(L, table); } // auth_read(name) int ModApiAuth::l_auth_read(lua_State *L) { NO_MAP_LOCK_REQUIRED; AuthDatabase *auth_db = getAuthDb(L); if (!auth_db) return 0; AuthEntry authEntry; const char *name = luaL_checkstring(L, 1); bool success = auth_db->getAuth(std::string(name), authEntry); if (!success) return 0; pushAuthEntry(L, authEntry); return 1; } // auth_save(table) int ModApiAuth::l_auth_save(lua_State *L) { NO_MAP_LOCK_REQUIRED; AuthDatabase *auth_db = getAuthDb(L); if (!auth_db) return 0; luaL_checktype(L, 1, LUA_TTABLE); int table = 1; AuthEntry authEntry; bool success; success = getintfield(L, table, "id", authEntry.id); success = success && getstringfield(L, table, "name", authEntry.name); success = success && getstringfield(L, table, "password", authEntry.password); lua_getfield(L, table, "privileges"); if (lua_istable(L, -1)) { lua_pushnil(L); while (lua_next(L, -2)) { authEntry.privileges.emplace_back( lua_tostring(L, -2)); // the key, not the value lua_pop(L, 1); } } else { success = false; } lua_pop(L, 1); // the table success = success && getintfield(L, table, "last_login", authEntry.last_login); if (!success) { lua_pushboolean(L, false); return 1; } lua_pushboolean(L, auth_db->saveAuth(authEntry)); return 1; } // auth_create(table) int ModApiAuth::l_auth_create(lua_State *L) { NO_MAP_LOCK_REQUIRED; AuthDatabase *auth_db = getAuthDb(L); if (!auth_db) return 0; luaL_checktype(L, 1, LUA_TTABLE); int table = 1; AuthEntry authEntry; bool success; // no meaningful id field, we assume success = getstringfield(L, table, "name", authEntry.name); success = success && getstringfield(L, table, "password", authEntry.password); lua_getfield(L, table, "privileges"); if (lua_istable(L, -1)) { lua_pushnil(L); while (lua_next(L, -2)) { authEntry.privileges.emplace_back( lua_tostring(L, -2)); // the key, not the value lua_pop(L, 1); } } else { success = false; } lua_pop(L, 1); // the table success = success && getintfield(L, table, "last_login", authEntry.last_login); if (!success) return 0; if (auth_db->createAuth(authEntry)) { pushAuthEntry(L, authEntry); return 1; } return 0; } // auth_delete(name) int ModApiAuth::l_auth_delete(lua_State *L) { NO_MAP_LOCK_REQUIRED; AuthDatabase *auth_db = getAuthDb(L); if (!auth_db) return 0; std::string name(luaL_checkstring(L, 1)); lua_pushboolean(L, auth_db->deleteAuth(name)); return 1; } // auth_list_names() int ModApiAuth::l_auth_list_names(lua_State *L) { NO_MAP_LOCK_REQUIRED; AuthDatabase *auth_db = getAuthDb(L); if (!auth_db) return 0; std::vector<std::string> names; auth_db->listNames(names); lua_createtable(L, names.size(), 0); int table = lua_gettop(L); int i = 1; for (const std::string &name : names) { lua_pushstring(L, name.c_str()); lua_rawseti(L, table, i++); } return 1; } // auth_reload() int ModApiAuth::l_auth_reload(lua_State *L) { NO_MAP_LOCK_REQUIRED; AuthDatabase *auth_db = getAuthDb(L); if (auth_db) auth_db->reload(); return 0; } void ModApiAuth::Initialize(lua_State *L, int top) { lua_newtable(L); int auth_top = lua_gettop(L); registerFunction(L, "read", l_auth_read, auth_top); registerFunction(L, "save", l_auth_save, auth_top); registerFunction(L, "create", l_auth_create, auth_top); registerFunction(L, "delete", l_auth_delete, auth_top); registerFunction(L, "list_names", l_auth_list_names, auth_top); registerFunction(L, "reload", l_auth_reload, auth_top); lua_setfield(L, top, "auth"); }
pgimeno/minetest
src/script/lua_api/l_auth.cpp
C++
mit
5,592
/* Minetest Copyright (C) 2018 bendeutsch, Ben Deutsch <ben@bendeutsch.de> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" class AuthDatabase; struct AuthEntry; class ModApiAuth : public ModApiBase { private: // auth_read(name) static int l_auth_read(lua_State *L); // auth_save(table) static int l_auth_save(lua_State *L); // auth_create(table) static int l_auth_create(lua_State *L); // auth_delete(name) static int l_auth_delete(lua_State *L); // auth_list_names() static int l_auth_list_names(lua_State *L); // auth_reload() static int l_auth_reload(lua_State *L); // helper for auth* methods static AuthDatabase *getAuthDb(lua_State *L); static void pushAuthEntry(lua_State *L, const AuthEntry &authEntry); public: static void Initialize(lua_State *L, int top); };
pgimeno/minetest
src/script/lua_api/l_auth.h
C++
mit
1,497
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_base.h" #include "lua_api/l_internal.h" #include "cpp_api/s_base.h" #include "content/mods.h" #include "profiler.h" #include "server.h" #include <algorithm> #include <cmath> ScriptApiBase *ModApiBase::getScriptApiBase(lua_State *L) { // Get server from registry lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_SCRIPTAPI); ScriptApiBase *sapi_ptr = (ScriptApiBase*) lua_touserdata(L, -1); lua_pop(L, 1); return sapi_ptr; } Server *ModApiBase::getServer(lua_State *L) { return getScriptApiBase(L)->getServer(); } #ifndef SERVER Client *ModApiBase::getClient(lua_State *L) { return getScriptApiBase(L)->getClient(); } #endif IGameDef *ModApiBase::getGameDef(lua_State *L) { return getScriptApiBase(L)->getGameDef(); } Environment *ModApiBase::getEnv(lua_State *L) { return getScriptApiBase(L)->getEnv(); } GUIEngine *ModApiBase::getGuiEngine(lua_State *L) { return getScriptApiBase(L)->getGuiEngine(); } std::string ModApiBase::getCurrentModPath(lua_State *L) { lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME); std::string current_mod_name = readParam<std::string>(L, -1, ""); if (current_mod_name.empty()) return "."; const ModSpec *mod = getServer(L)->getModSpec(current_mod_name); if (!mod) return "."; return mod->path; } bool ModApiBase::registerFunction(lua_State *L, const char *name, lua_CFunction func, int top) { // TODO: Check presence first! lua_pushcfunction(L, func); lua_setfield(L, top, name); return true; } std::unordered_map<std::string, luaL_Reg> ModApiBase::m_deprecated_wrappers; bool ModApiBase::m_error_deprecated_calls = false; int ModApiBase::l_deprecated_function(lua_State *L) { thread_local std::vector<u64> deprecated_logged; u64 start_time = porting::getTimeUs(); lua_Debug ar; // Get function name for lookup FATAL_ERROR_IF(!lua_getstack(L, 0, &ar), "lua_getstack() failed"); FATAL_ERROR_IF(!lua_getinfo(L, "n", &ar), "lua_getinfo() failed"); // Combine name with line and script backtrace FATAL_ERROR_IF(!lua_getstack(L, 1, &ar), "lua_getstack() failed"); FATAL_ERROR_IF(!lua_getinfo(L, "Sl", &ar), "lua_getinfo() failed"); // Get parent class to get the wrappers map luaL_checktype(L, 1, LUA_TUSERDATA); void *ud = lua_touserdata(L, 1); ModApiBase *o = *(ModApiBase**)ud; // New function and new function name auto it = o->m_deprecated_wrappers.find(ar.name); // Get backtrace and hash it to reduce the warning flood std::string backtrace = ar.short_src; 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()) { deprecated_logged.emplace_back(hash); 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); } u64 end_time = porting::getTimeUs(); g_profiler->avg("l_deprecated_function", end_time - start_time); return it->second.func(L); } void ModApiBase::markAliasDeprecated(luaL_Reg *reg) { std::string value = g_settings->get("deprecated_lua_api_handling"); m_error_deprecated_calls = value == "error"; if (!m_error_deprecated_calls && value != "log") return; const char *last_name = nullptr; lua_CFunction last_func = nullptr; // ! Null termination ! while (reg->func) { if (last_func == reg->func) { // Duplicate found luaL_Reg original_reg; // Do not inline struct. Breaks MSVC or is error-prone original_reg.name = last_name; original_reg.func = reg->func; m_deprecated_wrappers.emplace( std::pair<std::string, luaL_Reg>(reg->name, original_reg)); reg->func = l_deprecated_function; } last_func = reg->func; last_name = reg->name; ++reg; } }
pgimeno/minetest
src/script/lua_api/l_base.cpp
C++
mit
4,680
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "common/c_types.h" #include "common/c_internal.h" #include "common/helper.h" #include "gamedef.h" #include <unordered_map> extern "C" { #include <lua.h> #include <lauxlib.h> } #ifndef SERVER class Client; #endif class ScriptApiBase; class Server; class Environment; class GUIEngine; class ModApiBase : protected LuaHelper { public: static ScriptApiBase* getScriptApiBase(lua_State *L); static Server* getServer(lua_State *L); #ifndef SERVER static Client* getClient(lua_State *L); #endif // !SERVER static IGameDef* getGameDef(lua_State *L); static Environment* getEnv(lua_State *L); static GUIEngine* getGuiEngine(lua_State *L); // When we are not loading the mod, this function returns "." static std::string getCurrentModPath(lua_State *L); // Get an arbitrary subclass of ScriptApiBase // by using dynamic_cast<> on getScriptApiBase() template<typename T> static T* getScriptApi(lua_State *L) { ScriptApiBase *scriptIface = getScriptApiBase(L); T *scriptIfaceDowncast = dynamic_cast<T*>(scriptIface); if (!scriptIfaceDowncast) { 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 int l_deprecated_function(lua_State *L); static void markAliasDeprecated(luaL_Reg *reg); private: // <old_name> = { <new_name>, <new_function> } static std::unordered_map<std::string, luaL_Reg> m_deprecated_wrappers; static bool m_error_deprecated_calls; };
pgimeno/minetest
src/script/lua_api/l_base.h
C++
mit
2,394
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "l_camera.h" #include <cmath> #include "script/common/c_converter.h" #include "l_internal.h" #include "client/content_cao.h" #include "client/camera.h" #include "client/client.h" LuaCamera::LuaCamera(Camera *m) : m_camera(m) { } void LuaCamera::create(lua_State *L, Camera *m) { LuaCamera *o = new LuaCamera(m); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); int camera_object = lua_gettop(L); lua_getglobal(L, "core"); luaL_checktype(L, -1, LUA_TTABLE); int coretable = lua_gettop(L); lua_pushvalue(L, camera_object); lua_setfield(L, coretable, "camera"); } int LuaCamera::l_set_camera_mode(lua_State *L) { Camera *camera = getobject(L, 1); GenericCAO *playercao = getClient(L)->getEnv().getLocalPlayer()->getCAO(); if (!camera) return 0; sanity_check(playercao); if (!lua_isnumber(L, 2)) return 0; camera->setCameraMode((CameraMode)((int)lua_tonumber(L, 2))); playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST); playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST); return 0; } int LuaCamera::l_get_camera_mode(lua_State *L) { Camera *camera = getobject(L, 1); if (!camera) return 0; lua_pushnumber(L, (int)camera->getCameraMode()); return 1; } int LuaCamera::l_get_fov(lua_State *L) { Camera *camera = getobject(L, 1); if (!camera) return 0; lua_newtable(L); lua_pushnumber(L, camera->getFovX() * core::DEGTORAD); lua_setfield(L, -2, "x"); lua_pushnumber(L, camera->getFovY() * core::DEGTORAD); lua_setfield(L, -2, "y"); lua_pushnumber(L, camera->getCameraNode()->getFOV() * core::RADTODEG); lua_setfield(L, -2, "actual"); lua_pushnumber(L, camera->getFovMax() * core::RADTODEG); lua_setfield(L, -2, "max"); return 1; } int LuaCamera::l_get_pos(lua_State *L) { Camera *camera = getobject(L, 1); if (!camera) return 0; push_v3f(L, camera->getPosition()); return 1; } int LuaCamera::l_get_offset(lua_State *L) { Camera *camera = getobject(L, 1); if (!camera) return 0; push_v3s16(L, camera->getOffset()); return 1; } int LuaCamera::l_get_look_dir(lua_State *L) { LocalPlayer *player = getClient(L)->getEnv().getLocalPlayer(); sanity_check(player); float pitch = -1.0 * player->getPitch() * core::DEGTORAD; float yaw = (player->getYaw() + 90.) * core::DEGTORAD; v3f v(std::cos(pitch) * std::cos(yaw), std::sin(pitch), std::cos(pitch) * std::sin(yaw)); push_v3f(L, v); return 1; } int LuaCamera::l_get_look_horizontal(lua_State *L) { LocalPlayer *player = getClient(L)->getEnv().getLocalPlayer(); sanity_check(player); lua_pushnumber(L, (player->getYaw() + 90.) * core::DEGTORAD); return 1; } int LuaCamera::l_get_look_vertical(lua_State *L) { LocalPlayer *player = getClient(L)->getEnv().getLocalPlayer(); sanity_check(player); lua_pushnumber(L, -1.0 * player->getPitch() * core::DEGTORAD); return 1; } int LuaCamera::l_get_aspect_ratio(lua_State *L) { Camera *camera = getobject(L, 1); if (!camera) return 0; lua_pushnumber(L, camera->getCameraNode()->getAspectRatio()); return 1; } LuaCamera *LuaCamera::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 *(LuaCamera **)ud; } Camera *LuaCamera::getobject(LuaCamera *ref) { return ref->m_camera; } Camera *LuaCamera::getobject(lua_State *L, int narg) { LuaCamera *ref = checkobject(L, narg); assert(ref); Camera *camera = getobject(ref); if (!camera) return NULL; return camera; } int LuaCamera::gc_object(lua_State *L) { LuaCamera *o = *(LuaCamera **)(lua_touserdata(L, 1)); delete o; return 0; } void LuaCamera::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); } const char LuaCamera::className[] = "Camera"; const luaL_Reg LuaCamera::methods[] = {luamethod(LuaCamera, set_camera_mode), luamethod(LuaCamera, get_camera_mode), luamethod(LuaCamera, get_fov), luamethod(LuaCamera, get_pos), luamethod(LuaCamera, get_offset), luamethod(LuaCamera, get_look_dir), luamethod(LuaCamera, get_look_vertical), luamethod(LuaCamera, get_look_horizontal), luamethod(LuaCamera, get_aspect_ratio), {0, 0}};
pgimeno/minetest
src/script/lua_api/l_camera.cpp
C++
mit
5,460
/* Minetest Copyright (C) 2013-2017 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "l_base.h" class Camera; class LuaCamera : public ModApiBase { private: static const char className[]; static const luaL_Reg methods[]; // garbage collector static int gc_object(lua_State *L); static int l_set_camera_mode(lua_State *L); static int l_get_camera_mode(lua_State *L); static int l_get_fov(lua_State *L); static int l_get_pos(lua_State *L); static int l_get_offset(lua_State *L); static int l_get_look_dir(lua_State *L); static int l_get_look_vertical(lua_State *L); static int l_get_look_horizontal(lua_State *L); static int l_get_aspect_ratio(lua_State *L); Camera *m_camera = nullptr; public: LuaCamera(Camera *m); ~LuaCamera() = default; static void create(lua_State *L, Camera *m); static LuaCamera *checkobject(lua_State *L, int narg); static Camera *getobject(LuaCamera *ref); static Camera *getobject(lua_State *L, int narg); static void Register(lua_State *L); };
pgimeno/minetest
src/script/lua_api/l_camera.h
C++
mit
1,730
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "l_client.h" #include "chatmessage.h" #include "client/client.h" #include "client/clientevent.h" #include "client/sound.h" #include "client/clientenvironment.h" #include "common/c_content.h" #include "common/c_converter.h" #include "cpp_api/s_base.h" #include "gettext.h" #include "l_internal.h" #include "lua_api/l_item.h" #include "lua_api/l_nodemeta.h" #include "gui/mainmenumanager.h" #include "map.h" #include "util/string.h" #include "nodedef.h" int ModApiClient::l_get_current_modname(lua_State *L) { lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME); return 1; } // get_last_run_mod() int ModApiClient::l_get_last_run_mod(lua_State *L) { lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME); std::string current_mod = readParam<std::string>(L, -1, ""); if (current_mod.empty()) { lua_pop(L, 1); lua_pushstring(L, getScriptApiBase(L)->getOrigin().c_str()); } return 1; } // set_last_run_mod(modname) int ModApiClient::l_set_last_run_mod(lua_State *L) { if (!lua_isstring(L, 1)) return 0; const char *mod = lua_tostring(L, 1); getScriptApiBase(L)->setOriginDirect(mod); lua_pushboolean(L, true); return 1; } // print(text) int ModApiClient::l_print(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string text = luaL_checkstring(L, 1); rawstream << text << std::endl; return 0; } // display_chat_message(message) int ModApiClient::l_display_chat_message(lua_State *L) { if (!lua_isstring(L, 1)) return 0; std::string message = luaL_checkstring(L, 1); getClient(L)->pushToChatQueue(new ChatMessage(utf8_to_wide(message))); lua_pushboolean(L, true); return 1; } // send_chat_message(message) int ModApiClient::l_send_chat_message(lua_State *L) { if (!lua_isstring(L, 1)) return 0; // If server disabled this API, discard // clang-format off if (getClient(L)->checkCSMRestrictionFlag( CSMRestrictionFlags::CSM_RF_CHAT_MESSAGES)) return 0; // clang-format on std::string message = luaL_checkstring(L, 1); getClient(L)->sendChatMessage(utf8_to_wide(message)); return 0; } // clear_out_chat_queue() int ModApiClient::l_clear_out_chat_queue(lua_State *L) { getClient(L)->clearOutChatQueue(); return 0; } // get_player_names() int ModApiClient::l_get_player_names(lua_State *L) { // clang-format off if (getClient(L)->checkCSMRestrictionFlag( CSMRestrictionFlags::CSM_RF_READ_PLAYERINFO)) { return 0; } // clang-format on const std::list<std::string> &plist = getClient(L)->getConnectedPlayerNames(); lua_createtable(L, plist.size(), 0); int newTable = lua_gettop(L); int index = 1; std::list<std::string>::const_iterator iter; for (iter = plist.begin(); iter != plist.end(); ++iter) { lua_pushstring(L, (*iter).c_str()); lua_rawseti(L, newTable, index); index++; } return 1; } // show_formspec(formspec) int ModApiClient::l_show_formspec(lua_State *L) { if (!lua_isstring(L, 1) || !lua_isstring(L, 2)) return 0; ClientEvent *event = new ClientEvent(); event->type = CE_SHOW_LOCAL_FORMSPEC; event->show_formspec.formname = new std::string(luaL_checkstring(L, 1)); event->show_formspec.formspec = new std::string(luaL_checkstring(L, 2)); getClient(L)->pushToEventQueue(event); lua_pushboolean(L, true); return 1; } // send_respawn() int ModApiClient::l_send_respawn(lua_State *L) { getClient(L)->sendRespawn(); return 0; } // disconnect() int ModApiClient::l_disconnect(lua_State *L) { // Stops badly written Lua code form causing boot loops if (getClient(L)->isShutdown()) { lua_pushboolean(L, false); return 1; } g_gamecallback->disconnect(); lua_pushboolean(L, true); return 1; } // gettext(text) int ModApiClient::l_gettext(lua_State *L) { std::string text = strgettext(std::string(luaL_checkstring(L, 1))); lua_pushstring(L, text.c_str()); return 1; } // get_node(pos) // pos = {x=num, y=num, z=num} int ModApiClient::l_get_node_or_nil(lua_State *L) { // pos v3s16 pos = read_v3s16(L, 1); // Do it bool pos_ok; MapNode n = getClient(L)->getNode(pos, &pos_ok); if (pos_ok) { // Return node pushnode(L, n, getClient(L)->ndef()); } else { lua_pushnil(L); } return 1; } int ModApiClient::l_get_language(lua_State *L) { char *locale = setlocale(LC_ALL, ""); lua_pushstring(L, locale); return 1; } int ModApiClient::l_get_wielded_item(lua_State *L) { Client *client = getClient(L); Inventory local_inventory(client->idef()); client->getLocalInventory(local_inventory); InventoryList *mlist = local_inventory.getList("main"); if (mlist && client->getPlayerItem() < mlist->getSize()) { LuaItemStack::create(L, mlist->getItem(client->getPlayerItem())); } else { LuaItemStack::create(L, ItemStack()); } return 1; } // get_meta(pos) int ModApiClient::l_get_meta(lua_State *L) { v3s16 p = read_v3s16(L, 1); NodeMetadata *meta = getClient(L)->getEnv().getMap().getNodeMetadata(p); NodeMetaRef::createClient(L, meta); return 1; } int ModApiClient::l_sound_play(lua_State *L) { ISoundManager *sound = getClient(L)->getSoundManager(); SimpleSoundSpec spec; read_soundspec(L, 1, spec); float gain = 1.0f; float pitch = 1.0f; bool looped = false; s32 handle; if (lua_istable(L, 2)) { getfloatfield(L, 2, "gain", gain); getfloatfield(L, 2, "pitch", pitch); getboolfield(L, 2, "loop", looped); lua_getfield(L, 2, "pos"); if (!lua_isnil(L, -1)) { v3f pos = read_v3f(L, -1) * BS; lua_pop(L, 1); handle = sound->playSoundAt( spec.name, looped, gain * spec.gain, pos, pitch); lua_pushinteger(L, handle); return 1; } } handle = sound->playSound(spec.name, looped, gain * spec.gain, 0.0f, pitch); lua_pushinteger(L, handle); return 1; } int ModApiClient::l_sound_stop(lua_State *L) { u32 handle = luaL_checkinteger(L, 1); getClient(L)->getSoundManager()->stopSound(handle); return 0; } // get_server_info() int ModApiClient::l_get_server_info(lua_State *L) { Client *client = getClient(L); Address serverAddress = client->getServerAddress(); lua_newtable(L); lua_pushstring(L, client->getAddressName().c_str()); lua_setfield(L, -2, "address"); lua_pushstring(L, serverAddress.serializeString().c_str()); lua_setfield(L, -2, "ip"); lua_pushinteger(L, serverAddress.getPort()); lua_setfield(L, -2, "port"); lua_pushinteger(L, client->getProtoVersion()); lua_setfield(L, -2, "protocol_version"); return 1; } // get_item_def(itemstring) int ModApiClient::l_get_item_def(lua_State *L) { IGameDef *gdef = getGameDef(L); assert(gdef); IItemDefManager *idef = gdef->idef(); assert(idef); // clang-format off if (getClient(L)->checkCSMRestrictionFlag( CSMRestrictionFlags::CSM_RF_READ_ITEMDEFS)) return 0; // clang-format on if (!lua_isstring(L, 1)) return 0; std::string name = readParam<std::string>(L, 1); if (!idef->isKnown(name)) return 0; const ItemDefinition &def = idef->get(name); push_item_definition_full(L, def); return 1; } // get_node_def(nodename) int ModApiClient::l_get_node_def(lua_State *L) { IGameDef *gdef = getGameDef(L); assert(gdef); const NodeDefManager *ndef = gdef->ndef(); assert(ndef); if (!lua_isstring(L, 1)) return 0; // clang-format off if (getClient(L)->checkCSMRestrictionFlag( CSMRestrictionFlags::CSM_RF_READ_NODEDEFS)) return 0; // clang-format on std::string name = readParam<std::string>(L, 1); const ContentFeatures &cf = ndef->get(ndef->getId(name)); if (cf.name != name) // Unknown node. | name = <whatever>, cf.name = ignore return 0; push_content_features(L, cf); return 1; } int ModApiClient::l_get_privilege_list(lua_State *L) { const Client *client = getClient(L); lua_newtable(L); for (const std::string &priv : client->getPrivilegeList()) { lua_pushboolean(L, true); lua_setfield(L, -2, priv.c_str()); } return 1; } // get_builtin_path() int ModApiClient::l_get_builtin_path(lua_State *L) { lua_pushstring(L, BUILTIN_MOD_NAME ":"); return 1; } void ModApiClient::Initialize(lua_State *L, int top) { API_FCT(get_current_modname); API_FCT(print); API_FCT(display_chat_message); API_FCT(send_chat_message); API_FCT(clear_out_chat_queue); API_FCT(get_player_names); API_FCT(set_last_run_mod); API_FCT(get_last_run_mod); API_FCT(show_formspec); API_FCT(send_respawn); API_FCT(gettext); API_FCT(get_node_or_nil); API_FCT(get_wielded_item); API_FCT(disconnect); API_FCT(get_meta); API_FCT(sound_play); API_FCT(sound_stop); API_FCT(get_server_info); API_FCT(get_item_def); API_FCT(get_node_def); API_FCT(get_privilege_list); API_FCT(get_builtin_path); API_FCT(get_language); }
pgimeno/minetest
src/script/lua_api/l_client.cpp
C++
mit
9,389
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" #include "itemdef.h" #include "tool.h" class ModApiClient : public ModApiBase { private: // get_current_modname() static int l_get_current_modname(lua_State *L); // print(text) static int l_print(lua_State *L); // display_chat_message(message) static int l_display_chat_message(lua_State *L); // send_chat_message(message) static int l_send_chat_message(lua_State *L); // clear_out_chat_queue() static int l_clear_out_chat_queue(lua_State *L); // get_player_names() static int l_get_player_names(lua_State *L); // show_formspec(name, formspec) static int l_show_formspec(lua_State *L); // send_respawn() static int l_send_respawn(lua_State *L); // disconnect() static int l_disconnect(lua_State *L); // gettext(text) static int l_gettext(lua_State *L); // get_last_run_mod(n) static int l_get_last_run_mod(lua_State *L); // set_last_run_mod(modname) static int l_set_last_run_mod(lua_State *L); // get_node(pos) static int l_get_node_or_nil(lua_State *L); static int l_get_language(lua_State *L); // get_wielded_item() static int l_get_wielded_item(lua_State *L); // get_meta(pos) static int l_get_meta(lua_State *L); static int l_sound_play(lua_State *L); static int l_sound_stop(lua_State *L); // get_server_info() static int l_get_server_info(lua_State *L); // get_item_def(itemstring) static int l_get_item_def(lua_State *L); // get_node_def(nodename) static int l_get_node_def(lua_State *L); // get_privilege_list() static int l_get_privilege_list(lua_State *L); // get_builtin_path() static int l_get_builtin_path(lua_State *L); public: static void Initialize(lua_State *L, int top); };
pgimeno/minetest
src/script/lua_api/l_client.h
C++
mit
2,557
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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" #include "common/c_converter.h" #include "common/c_content.h" #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}, }; // helper for register_craft bool ModApiCraft::readCraftRecipeShaped(lua_State *L, int index, int &width, std::vector<std::string> &recipe) { if(index < 0) index = lua_gettop(L) + 1 + index; if(!lua_istable(L, index)) return false; lua_pushnil(L); int rowcount = 0; while(lua_next(L, index) != 0){ int colcount = 0; // key at index -2 and value at index -1 if(!lua_istable(L, -1)) return false; int table2 = lua_gettop(L); lua_pushnil(L); while(lua_next(L, table2) != 0){ // key at index -2 and value at index -1 if(!lua_isstring(L, -1)) return false; recipe.emplace_back(readParam<std::string>(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); colcount++; } if(rowcount == 0){ width = colcount; } else { if(colcount != width) return false; } // removes value, keeps key for next iteration lua_pop(L, 1); rowcount++; } return width != 0; } // helper for register_craft bool ModApiCraft::readCraftRecipeShapeless(lua_State *L, int index, std::vector<std::string> &recipe) { if(index < 0) index = lua_gettop(L) + 1 + index; if(!lua_istable(L, index)) return false; lua_pushnil(L); while(lua_next(L, index) != 0){ // key at index -2 and value at index -1 if(!lua_isstring(L, -1)) return false; recipe.emplace_back(readParam<std::string>(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); } return true; } // helper for register_craft bool ModApiCraft::readCraftReplacements(lua_State *L, int index, CraftReplacements &replacements) { if(index < 0) index = lua_gettop(L) + 1 + index; if(!lua_istable(L, index)) return false; lua_pushnil(L); while(lua_next(L, index) != 0){ // key at index -2 and value at index -1 if(!lua_istable(L, -1)) return false; lua_rawgeti(L, -1, 1); if(!lua_isstring(L, -1)) return false; std::string replace_from = readParam<std::string>(L, -1); lua_pop(L, 1); lua_rawgeti(L, -1, 2); if(!lua_isstring(L, -1)) return false; std::string replace_to = readParam<std::string>(L, -1); lua_pop(L, 1); replacements.pairs.emplace_back(replace_from, replace_to); // removes value, keeps key for next iteration lua_pop(L, 1); } return true; } // register_craft({output=item, recipe={{item00,item10},{item01,item11}}) int ModApiCraft::l_register_craft(lua_State *L) { NO_MAP_LOCK_REQUIRED; //infostream<<"register_craft"<<std::endl; luaL_checktype(L, 1, LUA_TTABLE); int table = 1; // Get the writable craft definition manager from the server IWritableCraftDefManager *craftdef = getServer(L)->getWritableCraftDefManager(); std::string type = getstringfield_default(L, table, "type", "shaped"); /* CraftDefinitionShaped */ if(type == "shaped"){ std::string output = getstringfield_default(L, table, "output", ""); if (output.empty()) throw LuaError("Crafting definition is missing an output"); int width = 0; std::vector<std::string> recipe; lua_getfield(L, table, "recipe"); if(lua_isnil(L, -1)) throw LuaError("Crafting definition is missing a recipe" " (output=\"" + output + "\")"); if(!readCraftRecipeShaped(L, -1, width, recipe)) throw LuaError("Invalid crafting recipe" " (output=\"" + output + "\")"); CraftReplacements replacements; lua_getfield(L, table, "replacements"); if(!lua_isnil(L, -1)) { if(!readCraftReplacements(L, -1, replacements)) throw LuaError("Invalid replacements" " (output=\"" + output + "\")"); } CraftDefinition *def = new CraftDefinitionShaped( output, width, recipe, replacements); craftdef->registerCraft(def, getServer(L)); } /* CraftDefinitionShapeless */ else if(type == "shapeless"){ std::string output = getstringfield_default(L, table, "output", ""); if (output.empty()) throw LuaError("Crafting definition (shapeless)" " is missing an output"); std::vector<std::string> recipe; lua_getfield(L, table, "recipe"); if(lua_isnil(L, -1)) throw LuaError("Crafting definition (shapeless)" " is missing a recipe" " (output=\"" + output + "\")"); if(!readCraftRecipeShapeless(L, -1, recipe)) throw LuaError("Invalid crafting recipe" " (output=\"" + output + "\")"); CraftReplacements replacements; lua_getfield(L, table, "replacements"); if(!lua_isnil(L, -1)) { if(!readCraftReplacements(L, -1, replacements)) throw LuaError("Invalid replacements" " (output=\"" + output + "\")"); } CraftDefinition *def = new CraftDefinitionShapeless( output, recipe, replacements); craftdef->registerCraft(def, getServer(L)); } /* CraftDefinitionToolRepair */ else if(type == "toolrepair"){ float additional_wear = getfloatfield_default(L, table, "additional_wear", 0.0); CraftDefinition *def = new CraftDefinitionToolRepair( additional_wear); craftdef->registerCraft(def, getServer(L)); } /* CraftDefinitionCooking */ else if(type == "cooking"){ std::string output = getstringfield_default(L, table, "output", ""); if (output.empty()) throw LuaError("Crafting definition (cooking)" " 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 + "\")"); 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)) throw LuaError("Invalid replacements" " (cooking output=\"" + output + "\")"); } CraftDefinition *def = new CraftDefinitionCooking( output, recipe, cooktime, replacements); craftdef->registerCraft(def, getServer(L)); } /* CraftDefinitionFuel */ else if(type == "fuel"){ std::string recipe = getstringfield_default(L, table, "recipe", ""); if (recipe.empty()) throw LuaError("Crafting definition (fuel)" " 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)) throw LuaError("Invalid replacements" " (fuel recipe=\"" + recipe + "\")"); } CraftDefinition *def = new CraftDefinitionFuel( recipe, burntime, replacements); craftdef->registerCraft(def, getServer(L)); } else { throw LuaError("Unknown crafting definition type: \"" + type + "\""); } lua_pop(L, 1); return 0; /* number of results */ } // clear_craft({[output=item], [recipe={{item00,item10},{item01,item11}}]) int ModApiCraft::l_clear_craft(lua_State *L) { NO_MAP_LOCK_REQUIRED; luaL_checktype(L, 1, LUA_TTABLE); int table = 1; // Get the writable craft definition manager from the server IWritableCraftDefManager *craftdef = getServer(L)->getWritableCraftDefManager(); std::string output = getstringfield_default(L, table, "output", ""); std::string type = getstringfield_default(L, table, "type", "shaped"); CraftOutput c_output(output, 0); if (!output.empty()) { if (craftdef->clearCraftRecipesByOutput(c_output, getServer(L))) { lua_pushboolean(L, true); return 1; } warningstream << "No craft recipe known for output" << std::endl; lua_pushboolean(L, false); return 1; } std::vector<std::string> recipe; int width = 0; CraftMethod method = CRAFT_METHOD_NORMAL; /* CraftDefinitionShaped */ if (type == "shaped") { lua_getfield(L, table, "recipe"); if (lua_isnil(L, -1)) throw LuaError("Either output or recipe has to be defined"); if (!readCraftRecipeShaped(L, -1, width, recipe)) throw LuaError("Invalid crafting recipe"); } /* CraftDefinitionShapeless */ else if (type == "shapeless") { lua_getfield(L, table, "recipe"); if (lua_isnil(L, -1)) throw LuaError("Either output or recipe has to be defined"); if (!readCraftRecipeShapeless(L, -1, recipe)) throw LuaError("Invalid crafting recipe"); } /* CraftDefinitionCooking */ else if (type == "cooking") { method = CRAFT_METHOD_COOKING; std::string rec = getstringfield_default(L, table, "recipe", ""); if (rec.empty()) throw LuaError("Crafting definition (cooking)" " is missing a recipe"); recipe.push_back(rec); } /* CraftDefinitionFuel */ else if (type == "fuel") { method = CRAFT_METHOD_FUEL; std::string rec = getstringfield_default(L, table, "recipe", ""); if (rec.empty()) throw LuaError("Crafting definition (fuel)" " is missing a recipe"); recipe.push_back(rec); } else { throw LuaError("Unknown crafting definition type: \"" + type + "\""); } if (!craftdef->clearCraftRecipesByInput(method, width, recipe, getServer(L))) { warningstream << "No craft recipe matches input" << std::endl; lua_pushboolean(L, false); return 1; } lua_pushboolean(L, true); return 1; } // get_craft_result(input) int ModApiCraft::l_get_craft_result(lua_State *L) { NO_MAP_LOCK_REQUIRED; 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); int width = 1; lua_getfield(L, input_i, "width"); if(lua_isnumber(L, -1)) width = luaL_checkinteger(L, -1); lua_pop(L, 1); lua_getfield(L, input_i, "items"); std::vector<ItemStack> items = read_items(L, -1,getServer(L)); lua_pop(L, 1); // items IGameDef *gdef = getServer(L); ICraftDefManager *cdef = gdef->cdef(); CraftInput input(method, width, items); CraftOutput output; std::vector<ItemStack> output_replacements; bool got = cdef->getCraftResult(input, output, output_replacements, true, gdef); lua_newtable(L); // output table if (got) { ItemStack item; item.deSerialize(output.item, gdef->idef()); LuaItemStack::create(L, item); lua_setfield(L, -2, "item"); setintfield(L, -1, "time", output.time); push_items(L, output_replacements); lua_setfield(L, -2, "replacements"); } else { LuaItemStack::create(L, ItemStack()); lua_setfield(L, -2, "item"); setintfield(L, -1, "time", 0); lua_newtable(L); lua_setfield(L, -2, "replacements"); } lua_newtable(L); // decremented input table lua_pushstring(L, method_s.c_str()); lua_setfield(L, -2, "method"); lua_pushinteger(L, width); lua_setfield(L, -2, "width"); push_items(L, input.items); lua_setfield(L, -2, "items"); return 2; } static void push_craft_recipe(lua_State *L, IGameDef *gdef, const CraftDefinition *recipe, const CraftOutput &tmpout) { CraftInput input = recipe->getInput(tmpout, gdef); CraftOutput output = recipe->getOutput(input, gdef); lua_newtable(L); // items std::vector<ItemStack>::const_iterator iter = input.items.begin(); for (u16 j = 1; iter != input.items.end(); ++iter, j++) { if (iter->empty()) continue; lua_pushstring(L, iter->name.c_str()); lua_rawseti(L, -2, j); } lua_setfield(L, -2, "items"); setintfield(L, -1, "width", input.width); std::string method_s; switch (input.method) { case CRAFT_METHOD_NORMAL: method_s = "normal"; break; case CRAFT_METHOD_COOKING: method_s = "cooking"; break; case CRAFT_METHOD_FUEL: method_s = "fuel"; break; default: method_s = "unknown"; } lua_pushstring(L, method_s.c_str()); lua_setfield(L, -2, "method"); // Deprecated, only for compatibility's sake lua_pushstring(L, method_s.c_str()); lua_setfield(L, -2, "type"); lua_pushstring(L, output.item.c_str()); lua_setfield(L, -2, "output"); } static void push_craft_recipes(lua_State *L, IGameDef *gdef, const std::vector<CraftDefinition*> &recipes, const CraftOutput &output) { lua_createtable(L, recipes.size(), 0); if (recipes.empty()) { lua_pushnil(L); return; } std::vector<CraftDefinition*>::const_iterator it = recipes.begin(); for (unsigned i = 0; it != recipes.end(); ++it) { lua_newtable(L); push_craft_recipe(L, gdef, *it, output); lua_rawseti(L, -2, ++i); } } // get_craft_recipe(result item) int ModApiCraft::l_get_craft_recipe(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string item = luaL_checkstring(L, 1); Server *server = getServer(L); CraftOutput output(item, 0); std::vector<CraftDefinition*> recipes = server->cdef() ->getCraftRecipes(output, server, 1); lua_createtable(L, 1, 0); if (recipes.empty()) { lua_pushnil(L); lua_setfield(L, -2, "items"); setintfield(L, -1, "width", 0); return 1; } push_craft_recipe(L, server, recipes[0], output); return 1; } // get_all_craft_recipes(result item) int ModApiCraft::l_get_all_craft_recipes(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string item = luaL_checkstring(L, 1); Server *server = getServer(L); CraftOutput output(item, 0); std::vector<CraftDefinition*> recipes = server->cdef() ->getCraftRecipes(output, server); push_craft_recipes(L, server, recipes, output); return 1; } void ModApiCraft::Initialize(lua_State *L, int top) { API_FCT(get_all_craft_recipes); API_FCT(get_craft_recipe); API_FCT(get_craft_result); API_FCT(register_craft); API_FCT(clear_craft); }
pgimeno/minetest
src/script/lua_api/l_craft.cpp
C++
mit
14,300
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <string> #include <vector> #include "lua_api/l_base.h" struct CraftReplacements; class ModApiCraft : public ModApiBase { private: static int l_register_craft(lua_State *L); static int l_get_craft_recipe(lua_State *L); static int l_get_all_craft_recipes(lua_State *L); static int l_get_craft_result(lua_State *L); static int l_clear_craft(lua_State *L); static bool readCraftReplacements(lua_State *L, int index, CraftReplacements &replacements); static bool readCraftRecipeShapeless(lua_State *L, int index, std::vector<std::string> &recipe); static bool readCraftRecipeShaped(lua_State *L, int index, int &width, std::vector<std::string> &recipe); static struct EnumString es_CraftMethod[]; public: static void Initialize(lua_State *L, int top); };
pgimeno/minetest
src/script/lua_api/l_craft.h
C++
mit
1,583
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_env.h" #include "lua_api/l_internal.h" #include "lua_api/l_nodemeta.h" #include "lua_api/l_nodetimer.h" #include "lua_api/l_noise.h" #include "lua_api/l_vmanip.h" #include "common/c_converter.h" #include "common/c_content.h" #include <algorithm> #include "scripting_server.h" #include "environment.h" #include "mapblock.h" #include "server.h" #include "nodedef.h" #include "daynightratio.h" #include "util/pointedthing.h" #include "content_sao.h" #include "mapgen/treegen.h" #include "emerge.h" #include "pathfinder.h" #include "face_position_cache.h" #include "remoteplayer.h" #ifndef SERVER #include "client/client.h" #endif 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) { ServerScripting *scriptIface = env->getScriptIface(); scriptIface->realityCheck(); lua_State *L = scriptIface->getStack(); sanity_check(lua_checkstack(L, 20)); StackUnroller stack_unroller(L); int error_handler = PUSH_ERROR_HANDLER(L); // Get registered_abms lua_getglobal(L, "core"); lua_getfield(L, -1, "registered_abms"); luaL_checktype(L, -1, LUA_TTABLE); lua_remove(L, -2); // Remove core // Get registered_abms[m_id] lua_pushnumber(L, m_id); lua_gettable(L, -2); if(lua_isnil(L, -1)) FATAL_ERROR(""); lua_remove(L, -2); // Remove registered_abms scriptIface->setOriginFromTable(-1); // Call action luaL_checktype(L, -1, LUA_TTABLE); lua_getfield(L, -1, "action"); luaL_checktype(L, -1, LUA_TFUNCTION); lua_remove(L, -2); // Remove registered_abms[m_id] push_v3s16(L, p); pushnode(L, n, env->getGameDef()->ndef()); lua_pushnumber(L, active_object_count); lua_pushnumber(L, active_object_count_wider); int result = lua_pcall(L, 4, 0, error_handler); if (result) scriptIface->scriptError(result, "LuaABM::trigger"); lua_pop(L, 1); // Pop error handler } void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n) { ServerScripting *scriptIface = env->getScriptIface(); scriptIface->realityCheck(); lua_State *L = scriptIface->getStack(); sanity_check(lua_checkstack(L, 20)); StackUnroller stack_unroller(L); int error_handler = PUSH_ERROR_HANDLER(L); // Get registered_lbms lua_getglobal(L, "core"); lua_getfield(L, -1, "registered_lbms"); luaL_checktype(L, -1, LUA_TTABLE); lua_remove(L, -2); // Remove core // Get registered_lbms[m_id] lua_pushnumber(L, m_id); lua_gettable(L, -2); 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); // Call action luaL_checktype(L, -1, LUA_TTABLE); lua_getfield(L, -1, "action"); luaL_checktype(L, -1, LUA_TFUNCTION); lua_remove(L, -2); // Remove registered_lbms[m_id] push_v3s16(L, p); pushnode(L, n, env->getGameDef()->ndef()); int result = lua_pcall(L, 2, 0, error_handler); if (result) scriptIface->scriptError(result, "LuaLBM::trigger"); lua_pop(L, 1); // Pop error handler } int LuaRaycast::l_next(lua_State *L) { MAP_LOCK_REQUIRED; ScriptApiItem *script = getScriptApi<ScriptApiItem>(L); GET_ENV_PTR; LuaRaycast *o = checkobject(L, 1); PointedThing pointed; env->continueRaycast(&o->state, &pointed); if (pointed.type == POINTEDTHING_NOTHING) lua_pushnil(L); else script->pushPointedThing(pointed, true); return 1; } int LuaRaycast::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; bool objects = true; bool liquids = false; v3f pos1 = checkFloatPos(L, 1); v3f pos2 = checkFloatPos(L, 2); if (lua_isboolean(L, 3)) { objects = readParam<bool>(L, 3); } if (lua_isboolean(L, 4)) { liquids = readParam<bool>(L, 4); } LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2), objects, liquids); *(void **) (lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } LuaRaycast *LuaRaycast::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 *(LuaRaycast **) ud; } int LuaRaycast::gc_object(lua_State *L) { LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1)); delete o; return 0; } void LuaRaycast::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pushliteral(L, "__call"); lua_pushcfunction(L, l_next); lua_settable(L, metatable); lua_pop(L, 1); luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); lua_register(L, className, create_object); } const char LuaRaycast::className[] = "Raycast"; const luaL_Reg LuaRaycast::methods[] = { luamethod(LuaRaycast, next), { 0, 0 } }; void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param) { ScriptCallbackState *state = (ScriptCallbackState *)param; assert(state != NULL); assert(state->script != NULL); assert(state->refcount > 0); // state must be protected by envlock Server *server = state->script->getServer(); MutexAutoLock envlock(server->m_env_mutex); state->refcount--; state->script->on_emerge_area_completion(blockpos, action, state); if (state->refcount == 0) delete state; } // Exported functions // set_node(pos, node) // pos = {x=num, y=num, z=num} int ModApiEnvMod::l_set_node(lua_State *L) { GET_ENV_PTR; const NodeDefManager *ndef = env->getGameDef()->ndef(); // parameters v3s16 pos = read_v3s16(L, 1); MapNode n = readnode(L, 2, ndef); // Do it bool succeeded = env->setNode(pos, n); lua_pushboolean(L, succeeded); return 1; } // bulk_set_node([pos1, pos2, ...], node) // pos = {x=num, y=num, z=num} int ModApiEnvMod::l_bulk_set_node(lua_State *L) { GET_ENV_PTR; const NodeDefManager *ndef = env->getGameDef()->ndef(); // parameters if (!lua_istable(L, 1)) { return 0; } s32 len = lua_objlen(L, 1); if (len == 0) { lua_pushboolean(L, true); return 1; } MapNode n = readnode(L, 2, ndef); // Do it bool succeeded = true; for (s32 i = 1; i <= len; i++) { lua_rawgeti(L, 1, i); if (!env->setNode(read_v3s16(L, -1), n)) succeeded = false; lua_pop(L, 1); } lua_pushboolean(L, succeeded); return 1; } int ModApiEnvMod::l_add_node(lua_State *L) { return l_set_node(L); } // remove_node(pos) // pos = {x=num, y=num, z=num} int ModApiEnvMod::l_remove_node(lua_State *L) { GET_ENV_PTR; // parameters v3s16 pos = read_v3s16(L, 1); // Do it bool succeeded = env->removeNode(pos); lua_pushboolean(L, succeeded); return 1; } // swap_node(pos, node) // pos = {x=num, y=num, z=num} int ModApiEnvMod::l_swap_node(lua_State *L) { GET_ENV_PTR; const NodeDefManager *ndef = env->getGameDef()->ndef(); // parameters v3s16 pos = read_v3s16(L, 1); MapNode n = readnode(L, 2, ndef); // Do it bool succeeded = env->swapNode(pos, n); lua_pushboolean(L, succeeded); return 1; } // get_node(pos) // pos = {x=num, y=num, z=num} int ModApiEnvMod::l_get_node(lua_State *L) { GET_ENV_PTR; // pos v3s16 pos = read_v3s16(L, 1); // Do it MapNode n = env->getMap().getNodeNoEx(pos); // Return node pushnode(L, n, env->getGameDef()->ndef()); return 1; } // get_node_or_nil(pos) // pos = {x=num, y=num, z=num} int ModApiEnvMod::l_get_node_or_nil(lua_State *L) { GET_ENV_PTR; // pos v3s16 pos = read_v3s16(L, 1); // Do it bool pos_ok; MapNode n = env->getMap().getNodeNoEx(pos, &pos_ok); if (pos_ok) { // Return node pushnode(L, n, env->getGameDef()->ndef()); } else { lua_pushnil(L); } return 1; } // get_node_light(pos, timeofday) // pos = {x=num, y=num, z=num} // timeofday: nil = current time, 0 = night, 0.5 = day int ModApiEnvMod::l_get_node_light(lua_State *L) { GET_ENV_PTR; // Do it v3s16 pos = read_v3s16(L, 1); u32 time_of_day = env->getTimeOfDay(); 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); bool is_position_ok; MapNode n = env->getMap().getNodeNoEx(pos, &is_position_ok); if (is_position_ok) { const NodeDefManager *ndef = env->getGameDef()->ndef(); lua_pushinteger(L, n.getLightBlend(dnr, ndef)); } else { lua_pushnil(L); } return 1; } // place_node(pos, node) // pos = {x=num, y=num, z=num} int ModApiEnvMod::l_place_node(lua_State *L) { GET_ENV_PTR; ScriptApiItem *scriptIfaceItem = getScriptApi<ScriptApiItem>(L); Server *server = getServer(L); const NodeDefManager *ndef = server->ndef(); IItemDefManager *idef = server->idef(); v3s16 pos = read_v3s16(L, 1); MapNode n = readnode(L, 2, ndef); // Don't attempt to load non-loaded area as of now MapNode n_old = env->getMap().getNodeNoEx(pos); if(n_old.getContent() == CONTENT_IGNORE){ lua_pushboolean(L, false); return 1; } // Create item to place ItemStack item(ndef->get(n).name, 1, 0, idef); // Make pointed position PointedThing pointed; pointed.type = POINTEDTHING_NODE; pointed.node_abovesurface = pos; 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); return 1; } // dig_node(pos) // pos = {x=num, y=num, z=num} int ModApiEnvMod::l_dig_node(lua_State *L) { GET_ENV_PTR; ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L); v3s16 pos = read_v3s16(L, 1); // Don't attempt to load non-loaded area as of now MapNode n = env->getMap().getNodeNoEx(pos); if(n.getContent() == CONTENT_IGNORE){ lua_pushboolean(L, false); return 1; } // Dig it out with a NULL digger (appears in Lua as a // non-functional ObjectRef) bool success = scriptIfaceNode->node_on_dig(pos, n, NULL); lua_pushboolean(L, success); return 1; } // punch_node(pos) // pos = {x=num, y=num, z=num} int ModApiEnvMod::l_punch_node(lua_State *L) { GET_ENV_PTR; ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L); v3s16 pos = read_v3s16(L, 1); // Don't attempt to load non-loaded area as of now MapNode n = env->getMap().getNodeNoEx(pos); if(n.getContent() == CONTENT_IGNORE){ lua_pushboolean(L, false); return 1; } // Punch it with a NULL puncher (appears in Lua as a non-functional // ObjectRef) bool success = scriptIfaceNode->node_on_punch(pos, n, NULL, PointedThing()); lua_pushboolean(L, success); return 1; } // get_node_max_level(pos) // pos = {x=num, y=num, z=num} int ModApiEnvMod::l_get_node_max_level(lua_State *L) { Environment *env = getEnv(L); if (!env) { return 0; } v3s16 pos = read_v3s16(L, 1); MapNode n = env->getMap().getNodeNoEx(pos); lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef())); return 1; } // get_node_level(pos) // pos = {x=num, y=num, z=num} int ModApiEnvMod::l_get_node_level(lua_State *L) { Environment *env = getEnv(L); if (!env) { return 0; } v3s16 pos = read_v3s16(L, 1); MapNode n = env->getMap().getNodeNoEx(pos); lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef())); return 1; } // set_node_level(pos, level) // pos = {x=num, y=num, z=num} // level: 0..63 int ModApiEnvMod::l_set_node_level(lua_State *L) { GET_ENV_PTR; v3s16 pos = read_v3s16(L, 1); u8 level = 1; if(lua_isnumber(L, 2)) level = lua_tonumber(L, 2); MapNode n = env->getMap().getNodeNoEx(pos); lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level)); env->setNode(pos, n); return 1; } // add_node_level(pos, level) // pos = {x=num, y=num, z=num} // level: 0..63 int ModApiEnvMod::l_add_node_level(lua_State *L) { GET_ENV_PTR; v3s16 pos = read_v3s16(L, 1); u8 level = 1; if(lua_isnumber(L, 2)) level = lua_tonumber(L, 2); MapNode n = env->getMap().getNodeNoEx(pos); lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level)); env->setNode(pos, n); return 1; } // find_nodes_with_meta(pos1, pos2) int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L) { GET_ENV_PTR; std::vector<v3s16> positions = env->getMap().findNodesWithMetadata( check_v3s16(L, 1), check_v3s16(L, 2)); lua_newtable(L); for (size_t i = 0; i != positions.size(); i++) { push_v3s16(L, positions[i]); lua_rawseti(L, -2, i + 1); } return 1; } // get_meta(pos) int ModApiEnvMod::l_get_meta(lua_State *L) { GET_ENV_PTR; // Do it v3s16 p = read_v3s16(L, 1); NodeMetaRef::create(L, p, env); return 1; } // get_node_timer(pos) int ModApiEnvMod::l_get_node_timer(lua_State *L) { GET_ENV_PTR; // Do it v3s16 p = read_v3s16(L, 1); NodeTimerRef::create(L, p, env); return 1; } // add_entity(pos, entityname, [staticdata]) -> ObjectRef or nil // pos = {x=num, y=num, z=num} int ModApiEnvMod::l_add_entity(lua_State *L) { GET_ENV_PTR; // pos v3f pos = checkFloatPos(L, 1); // content const char *name = luaL_checkstring(L, 2); // staticdata const char *staticdata = luaL_optstring(L, 3, ""); // Do it 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) return 0; // Return ObjectRef getScriptApiBase(L)->objectrefGetOrCreate(L, obj); return 1; } // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil // pos = {x=num, y=num, z=num} int ModApiEnvMod::l_add_item(lua_State *L) { GET_ENV_PTR; // pos //v3f pos = checkFloatPos(L, 1); // item 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); // Use spawn_item to spawn a __builtin:item lua_getglobal(L, "core"); lua_getfield(L, -1, "spawn_item"); lua_remove(L, -2); // Remove core if(lua_isnil(L, -1)) return 0; lua_pushvalue(L, 1); lua_pushstring(L, item.getItemString().c_str()); PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler)); lua_remove(L, error_handler); return 1; } // get_player_by_name(name) int ModApiEnvMod::l_get_player_by_name(lua_State *L) { GET_ENV_PTR; // Do it const char *name = luaL_checkstring(L, 1); RemotePlayer *player = dynamic_cast<RemotePlayer *>(env->getPlayer(name)); if (player == NULL){ lua_pushnil(L); return 1; } PlayerSAO *sao = player->getPlayerSAO(); if(sao == NULL){ lua_pushnil(L); return 1; } // Put player on stack getScriptApiBase(L)->objectrefGetOrCreate(L, sao); return 1; } // get_objects_inside_radius(pos, radius) int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L) { GET_ENV_PTR; // Do it v3f pos = checkFloatPos(L, 1); float radius = readParam<float>(L, 2) * BS; std::vector<u16> ids; env->getObjectsInsideRadius(ids, pos, radius); ScriptApiBase *script = getScriptApiBase(L); lua_createtable(L, ids.size(), 0); std::vector<u16>::const_iterator iter = ids.begin(); for(u32 i = 0; iter != ids.end(); ++iter) { ServerActiveObject *obj = env->getActiveObject(*iter); if (!obj->isGone()) { // Insert object reference into table script->objectrefGetOrCreate(L, obj); lua_rawseti(L, -2, ++i); } } return 1; } // set_timeofday(val) // val = 0...1 int ModApiEnvMod::l_set_timeofday(lua_State *L) { GET_ENV_PTR; // Do it float timeofday_f = readParam<float>(L, 1); sanity_check(timeofday_f >= 0.0 && timeofday_f <= 1.0); int timeofday_mh = (int)(timeofday_f * 24000.0); // 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); getServer(L)->setTimeOfDay(timeofday_mh); return 0; } // get_timeofday() -> 0...1 int ModApiEnvMod::l_get_timeofday(lua_State *L) { Environment *env = getEnv(L); if (!env) { return 0; } // Do it int timeofday_mh = env->getTimeOfDay(); float timeofday_f = (float)timeofday_mh / 24000.0f; lua_pushnumber(L, timeofday_f); return 1; } // get_day_count() -> int int ModApiEnvMod::l_get_day_count(lua_State *L) { Environment *env = getEnv(L); if (!env) { return 0; } lua_pushnumber(L, env->getDayCount()); return 1; } // get_gametime() int ModApiEnvMod::l_get_gametime(lua_State *L) { GET_ENV_PTR; int game_time = env->getGameTime(); lua_pushnumber(L, game_time); return 1; } // find_node_near(pos, radius, nodenames, search_center) -> pos or nil // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" int ModApiEnvMod::l_find_node_near(lua_State *L) { Environment *env = getEnv(L); if (!env) { return 0; } const NodeDefManager *ndef = getGameDef(L)->ndef(); v3s16 pos = read_v3s16(L, 1); int radius = luaL_checkinteger(L, 2); std::vector<content_t> filter; if (lua_istable(L, 3)) { lua_pushnil(L); while (lua_next(L, 3) != 0) { // key at index -2 and value at index -1 luaL_checktype(L, -1, LUA_TSTRING); ndef->getIds(readParam<std::string>(L, -1), filter); // removes value, keeps key for next iteration lua_pop(L, 1); } } else if (lua_isstring(L, 3)) { ndef->getIds(readParam<std::string>(L, 3), filter); } int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1; #ifndef SERVER // Client API limitations if (getClient(L) && getClient(L)->checkCSMRestrictionFlag( CSMRestrictionFlags::CSM_RF_LOOKUP_NODES)) { radius = std::max<int>(radius, getClient(L)->getCSMNodeRangeLimit()); } #endif for (int d = start_radius; d <= radius; d++) { std::vector<v3s16> list = FacePositionCache::getFacePositions(d); for (const v3s16 &i : list) { v3s16 p = pos + i; content_t c = env->getMap().getNodeNoEx(p).getContent(); if (CONTAINS(filter, c)) { push_v3s16(L, p); return 1; } } } return 0; } // find_nodes_in_area(minp, maxp, nodenames) -> list of positions // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" int ModApiEnvMod::l_find_nodes_in_area(lua_State *L) { GET_ENV_PTR; const NodeDefManager *ndef = getServer(L)->ndef(); v3s16 minp = read_v3s16(L, 1); v3s16 maxp = read_v3s16(L, 2); sortBoxVerticies(minp, maxp); v3s16 cube = maxp - minp + 1; // 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"); return 0; } std::vector<content_t> filter; if (lua_istable(L, 3)) { lua_pushnil(L); while (lua_next(L, 3) != 0) { // key at index -2 and value at index -1 luaL_checktype(L, -1, LUA_TSTRING); ndef->getIds(readParam<std::string>(L, -1), filter); // removes value, keeps key for next iteration lua_pop(L, 1); } } else if (lua_isstring(L, 3)) { ndef->getIds(readParam<std::string>(L, 3), filter); } std::vector<u32> individual_count; individual_count.resize(filter.size()); lua_newtable(L); u64 i = 0; for (s16 x = minp.X; x <= maxp.X; x++) for (s16 y = minp.Y; y <= maxp.Y; y++) for (s16 z = minp.Z; z <= maxp.Z; z++) { v3s16 p(x, y, z); content_t c = env->getMap().getNodeNoEx(p).getContent(); std::vector<content_t>::iterator 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_newtable(L); for (u32 i = 0; i < filter.size(); i++) { lua_pushnumber(L, individual_count[i]); lua_setfield(L, -2, ndef->get(filter[i]).name.c_str()); } return 2; } // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt" int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L) { /* Note: A similar but generalized (and therefore slower) version of this * function could be created -- e.g. find_nodes_in_area_under -- which * would accept a node name (or ID?) or list of names that the "above node" * should be. * TODO */ GET_ENV_PTR; const NodeDefManager *ndef = getServer(L)->ndef(); v3s16 minp = read_v3s16(L, 1); v3s16 maxp = read_v3s16(L, 2); sortBoxVerticies(minp, maxp); v3s16 cube = maxp - minp + 1; // 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"); return 0; } std::vector<content_t> filter; if (lua_istable(L, 3)) { lua_pushnil(L); while (lua_next(L, 3) != 0) { // key at index -2 and value at index -1 luaL_checktype(L, -1, LUA_TSTRING); ndef->getIds(readParam<std::string>(L, -1), filter); // removes value, keeps key for next iteration lua_pop(L, 1); } } else if (lua_isstring(L, 3)) { ndef->getIds(readParam<std::string>(L, 3), filter); } lua_newtable(L); u64 i = 0; for (s16 x = minp.X; x <= maxp.X; x++) for (s16 z = minp.Z; z <= maxp.Z; z++) { s16 y = minp.Y; v3s16 p(x, y, z); content_t c = env->getMap().getNodeNoEx(p).getContent(); for (; y <= maxp.Y; y++) { v3s16 psurf(x, y + 1, z); content_t csurf = env->getMap().getNodeNoEx(psurf).getContent(); if (c != CONTENT_AIR && csurf == CONTENT_AIR && CONTAINS(filter, c)) { push_v3s16(L, v3s16(x, y, z)); lua_rawseti(L, -2, ++i); } c = csurf; } } return 1; } // get_perlin(seeddiff, octaves, persistence, scale) // returns world-specific PerlinNoise int ModApiEnvMod::l_get_perlin(lua_State *L) { GET_ENV_PTR_NO_MAP_LOCK; NoiseParams params; if (lua_istable(L, 1)) { read_noiseparams(L, 1, &params); } else { params.seed = luaL_checkint(L, 1); params.octaves = luaL_checkint(L, 2); params.persist = readParam<float>(L, 3); params.spread = v3f(1, 1, 1) * readParam<float>(L, 4); } params.seed += (int)env->getServerMap().getSeed(); LuaPerlinNoise *n = new LuaPerlinNoise(&params); *(void **)(lua_newuserdata(L, sizeof(void *))) = n; luaL_getmetatable(L, "PerlinNoise"); lua_setmetatable(L, -2); return 1; } // get_perlin_map(noiseparams, size) // returns world-specific PerlinNoiseMap int ModApiEnvMod::l_get_perlin_map(lua_State *L) { GET_ENV_PTR_NO_MAP_LOCK; NoiseParams np; if (!read_noiseparams(L, 1, &np)) return 0; v3s16 size = read_v3s16(L, 2); s32 seed = (s32)(env->getServerMap().getSeed()); LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size); *(void **)(lua_newuserdata(L, sizeof(void *))) = n; luaL_getmetatable(L, "PerlinNoiseMap"); lua_setmetatable(L, -2); return 1; } // get_voxel_manip() // returns voxel manipulator 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); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, "VoxelManip"); lua_setmetatable(L, -2); return 1; } // clear_objects([options]) // clear all objects in the environment // where options = {mode = "full" or "quick"} int ModApiEnvMod::l_clear_objects(lua_State *L) { GET_ENV_PTR; ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK; if (lua_istable(L, 1)) { mode = (ClearObjectsMode)getenumfield(L, 1, "mode", ModApiEnvMod::es_ClearObjectsMode, mode); } env->clearObjects(mode); return 0; } // line_of_sight(pos1, pos2) -> true/false, pos int ModApiEnvMod::l_line_of_sight(lua_State *L) { GET_ENV_PTR; // read position 1 from lua v3f pos1 = checkFloatPos(L, 1); // read position 2 from lua v3f pos2 = checkFloatPos(L, 2); v3s16 p; bool success = env->line_of_sight(pos1, pos2, &p); lua_pushboolean(L, success); if (!success) { push_v3s16(L, p); return 2; } return 1; } // fix_light(p1, p2) int ModApiEnvMod::l_fix_light(lua_State *L) { GET_ENV_PTR; v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE); v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE); ServerMap &map = env->getServerMap(); std::map<v3s16, MapBlock *> modified_blocks; 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); } if (!modified_blocks.empty()) { MapEditEvent event; event.type = MEET_OTHER; for (auto &modified_block : modified_blocks) event.modified_blocks.insert(modified_block.first); map.dispatchEvent(&event); } lua_pushboolean(L, success); return 1; } int ModApiEnvMod::l_raycast(lua_State *L) { return LuaRaycast::create_object(L); } // load_area(p1, [p2]) // load mapblocks in area p1..p2, but do not generate map int ModApiEnvMod::l_load_area(lua_State *L) { GET_ENV_PTR; MAP_LOCK_REQUIRED; Map *map = &(env->getMap()); v3s16 bp1 = getNodeBlockPos(check_v3s16(L, 1)); if (!lua_istable(L, 2)) { map->emergeBlock(bp1); } else { 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)); } } return 0; } // emerge_area(p1, p2, [callback, context]) // emerge mapblocks in area p1..p2, calls callback with context upon completion int ModApiEnvMod::l_emerge_area(lua_State *L) { GET_ENV_PTR; EmergeCompletionCallback callback = NULL; ScriptCallbackState *state = NULL; EmergeManager *emerge = getServer(L)->getEmergeManager(); v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1)); v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2)); sortBoxVerticies(bpmin, bpmax); size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume(); assert(num_blocks != 0); if (lua_isfunction(L, 3)) { callback = LuaEmergeAreaCallback; lua_pushvalue(L, 3); int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX); lua_pushvalue(L, 4); int args_ref = luaL_ref(L, LUA_REGISTRYINDEX); state = new ScriptCallbackState; state->script = getServer(L)->getScriptIface(); state->callback_ref = callback_ref; 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); } return 0; } // delete_area(p1, p2) // delete mapblocks in area p1..p2 int ModApiEnvMod::l_delete_area(lua_State *L) { GET_ENV_PTR; v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1)); v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2)); sortBoxVerticies(bpmin, bpmax); ServerMap &map = env->getServerMap(); MapEditEvent event; event.type = MEET_OTHER; 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; } } map.dispatchEvent(&event); lua_pushboolean(L, success); return 1; } // find_path(pos1, pos2, searchdistance, // max_jump, max_drop, algorithm) -> table containing path int ModApiEnvMod::l_find_path(lua_State *L) { GET_ENV_PTR; 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; if (!lua_isnil(L, 6)) { std::string algorithm = luaL_checkstring(L,6); if (algorithm == "A*") algo = PA_PLAIN; if (algorithm == "Dijkstra") algo = PA_DIJKSTRA; } std::vector<v3s16> path = get_path(env, pos1, pos2, searchdistance, max_jump, max_drop, algo); if (!path.empty()) { lua_newtable(L); int top = lua_gettop(L); unsigned int index = 1; for (const v3s16 &i : path) { lua_pushnumber(L,index); push_v3s16(L, i); lua_settable(L, top); index++; } return 1; } return 0; } // spawn_tree(pos, treedef) int ModApiEnvMod::l_spawn_tree(lua_State *L) { GET_ENV_PTR; v3s16 p0 = read_v3s16(L, 1); treegen::TreeDef tree_def; std::string trunk,leaves,fruit; const NodeDefManager *ndef = env->getGameDef()->ndef(); 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); getstringfield(L, 2, "leaves", leaves); 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); getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance); } getintfield(L, 2, "angle", tree_def.angle); getintfield(L, 2, "iterations", tree_def.iterations); if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level)) 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; 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.explicit_seed = getintfield(L, 2, "seed", tree_def.seed); } else return 0; treegen::error e; if ((e = treegen::spawn_ltree (env, p0, ndef, tree_def)) != treegen::SUCCESS) { if (e == treegen::UNBALANCED_BRACKETS) { luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket"); } else { luaL_error(L, "spawn_tree(): unknown error"); } } return 1; } // transforming_liquid_add(pos) int ModApiEnvMod::l_transforming_liquid_add(lua_State *L) { GET_ENV_PTR; v3s16 p0 = read_v3s16(L, 1); env->getMap().transforming_liquid_add(p0); return 1; } // forceload_block(blockpos) // blockpos = {x=num, y=num, z=num} int ModApiEnvMod::l_forceload_block(lua_State *L) { GET_ENV_PTR; v3s16 blockpos = read_v3s16(L, 1); env->getForceloadedBlocks()->insert(blockpos); return 0; } // forceload_free_block(blockpos) // blockpos = {x=num, y=num, z=num} int ModApiEnvMod::l_forceload_free_block(lua_State *L) { GET_ENV_PTR; v3s16 blockpos = read_v3s16(L, 1); env->getForceloadedBlocks()->erase(blockpos); return 0; } void ModApiEnvMod::Initialize(lua_State *L, int top) { API_FCT(set_node); API_FCT(bulk_set_node); API_FCT(add_node); API_FCT(swap_node); API_FCT(add_item); API_FCT(remove_node); API_FCT(get_node); API_FCT(get_node_or_nil); API_FCT(get_node_light); API_FCT(place_node); API_FCT(dig_node); API_FCT(punch_node); API_FCT(get_node_max_level); API_FCT(get_node_level); API_FCT(set_node_level); API_FCT(add_node_level); API_FCT(add_entity); API_FCT(find_nodes_with_meta); API_FCT(get_meta); API_FCT(get_node_timer); API_FCT(get_player_by_name); API_FCT(get_objects_inside_radius); API_FCT(set_timeofday); API_FCT(get_timeofday); API_FCT(get_gametime); API_FCT(get_day_count); API_FCT(find_node_near); API_FCT(find_nodes_in_area); API_FCT(find_nodes_in_area_under_air); API_FCT(fix_light); API_FCT(load_area); API_FCT(emerge_area); API_FCT(delete_area); API_FCT(get_perlin); API_FCT(get_perlin_map); API_FCT(get_voxel_manip); API_FCT(clear_objects); API_FCT(spawn_tree); API_FCT(find_path); API_FCT(line_of_sight); API_FCT(raycast); API_FCT(transforming_liquid_add); API_FCT(forceload_block); API_FCT(forceload_free_block); } void ModApiEnvMod::InitializeClient(lua_State *L, int top) { API_FCT(get_timeofday); API_FCT(get_day_count); API_FCT(get_node_max_level); API_FCT(get_node_level); API_FCT(find_node_near); }
pgimeno/minetest
src/script/lua_api/l_env.cpp
C++
mit
33,297
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" #include "serverenvironment.h" #include "raycast.h" class ModApiEnvMod : public ModApiBase { private: // set_node(pos, node) // pos = {x=num, y=num, z=num} static int l_set_node(lua_State *L); // bulk_set_node([pos1, pos2, ...], node) // pos = {x=num, y=num, z=num} static int l_bulk_set_node(lua_State *L); static int l_add_node(lua_State *L); // remove_node(pos) // pos = {x=num, y=num, z=num} static int l_remove_node(lua_State *L); // swap_node(pos, node) // pos = {x=num, y=num, z=num} static int l_swap_node(lua_State *L); // get_node(pos) // pos = {x=num, y=num, z=num} static int l_get_node(lua_State *L); // get_node_or_nil(pos) // pos = {x=num, y=num, z=num} static int l_get_node_or_nil(lua_State *L); // get_node_light(pos, timeofday) // pos = {x=num, y=num, z=num} // timeofday: nil = current time, 0 = night, 0.5 = day static int l_get_node_light(lua_State *L); // place_node(pos, node) // pos = {x=num, y=num, z=num} static int l_place_node(lua_State *L); // dig_node(pos) // pos = {x=num, y=num, z=num} static int l_dig_node(lua_State *L); // punch_node(pos) // pos = {x=num, y=num, z=num} static int l_punch_node(lua_State *L); // get_node_max_level(pos) // pos = {x=num, y=num, z=num} static int l_get_node_max_level(lua_State *L); // get_node_level(pos) // pos = {x=num, y=num, z=num} static int l_get_node_level(lua_State *L); // set_node_level(pos) // pos = {x=num, y=num, z=num} static int l_set_node_level(lua_State *L); // add_node_level(pos) // pos = {x=num, y=num, z=num} static int l_add_node_level(lua_State *L); // find_nodes_with_meta(pos1, pos2) static int l_find_nodes_with_meta(lua_State *L); // get_meta(pos) static int l_get_meta(lua_State *L); // get_node_timer(pos) static int l_get_node_timer(lua_State *L); // add_entity(pos, entityname) -> ObjectRef or nil // pos = {x=num, y=num, z=num} static int l_add_entity(lua_State *L); // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil // pos = {x=num, y=num, z=num} static int l_add_item(lua_State *L); // get_player_by_name(name) static int l_get_player_by_name(lua_State *L); // get_objects_inside_radius(pos, radius) static int l_get_objects_inside_radius(lua_State *L); // set_timeofday(val) // val = 0...1 static int l_set_timeofday(lua_State *L); // get_timeofday() -> 0...1 static int l_get_timeofday(lua_State *L); // get_gametime() static int l_get_gametime(lua_State *L); // get_day_count() -> int static int l_get_day_count(lua_State *L); // 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_in_area(minp, maxp, nodenames) -> list of positions // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" static int l_find_nodes_in_area(lua_State *L); // find_surface_nodes_in_area(minp, maxp, nodenames) -> list of positions // nodenames: eg. {"ignore", "group:tree"} or "default:dirt" static int l_find_nodes_in_area_under_air(lua_State *L); // fix_light(p1, p2) -> true/false static int l_fix_light(lua_State *L); // load_area(p1) static int l_load_area(lua_State *L); // emerge_area(p1, p2) static int l_emerge_area(lua_State *L); // delete_area(p1, p2) -> true/false static int l_delete_area(lua_State *L); // get_perlin(seeddiff, octaves, persistence, scale) // returns world-specific PerlinNoise static int l_get_perlin(lua_State *L); // get_perlin_map(noiseparams, size) // returns world-specific PerlinNoiseMap static int l_get_perlin_map(lua_State *L); // get_voxel_manip() // returns world-specific voxel manipulator static int l_get_voxel_manip(lua_State *L); // clear_objects() // clear all objects in the environment static int l_clear_objects(lua_State *L); // spawn_tree(pos, treedef) static int l_spawn_tree(lua_State *L); // line_of_sight(pos1, pos2) -> true/false static int l_line_of_sight(lua_State *L); // raycast(pos1, pos2, objects, liquids) -> Raycast static int l_raycast(lua_State *L); // find_path(pos1, pos2, searchdistance, // max_jump, max_drop, algorithm) -> table containing path static int l_find_path(lua_State *L); // transforming_liquid_add(pos) static int l_transforming_liquid_add(lua_State *L); // forceload_block(blockpos) // forceloads a block static int l_forceload_block(lua_State *L); // forceload_free_block(blockpos) // stops forceloading a position static int l_forceload_free_block(lua_State *L); public: static void Initialize(lua_State *L, int top); static void InitializeClient(lua_State *L, int top); static struct EnumString es_ClearObjectsMode[]; }; class LuaABM : public ActiveBlockModifier { private: int m_id; std::vector<std::string> m_trigger_contents; std::vector<std::string> m_required_neighbors; float m_trigger_interval; u32 m_trigger_chance; bool m_simple_catch_up; public: LuaABM(lua_State *L, int id, const std::vector<std::string> &trigger_contents, const std::vector<std::string> &required_neighbors, float trigger_interval, u32 trigger_chance, bool simple_catch_up): m_id(id), m_trigger_contents(trigger_contents), m_required_neighbors(required_neighbors), m_trigger_interval(trigger_interval), m_trigger_chance(trigger_chance), m_simple_catch_up(simple_catch_up) { } virtual const std::vector<std::string> &getTriggerContents() const { return m_trigger_contents; } virtual const std::vector<std::string> &getRequiredNeighbors() const { 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 void trigger(ServerEnvironment *env, v3s16 p, MapNode n, u32 active_object_count, u32 active_object_count_wider); }; class LuaLBM : public LoadingBlockModifierDef { private: int m_id; public: LuaLBM(lua_State *L, int id, const std::set<std::string> &trigger_contents, const std::string &name, bool run_at_every_load): m_id(id) { this->run_at_every_load = run_at_every_load; this->trigger_contents = trigger_contents; this->name = name; } virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n); }; //! Lua wrapper for RaycastState objects class LuaRaycast : public ModApiBase { private: static const char className[]; static const luaL_Reg methods[]; //! Inner state RaycastState state; // Exported functions // garbage collector static int gc_object(lua_State *L); /*! * Raycast:next() -> pointed_thing * Returns the next pointed thing on the ray. */ static int l_next(lua_State *L); public: //! Constructor with the same arguments as RaycastState. LuaRaycast( const core::line3d<f32> &shootline, bool objects_pointable, bool liquids_pointable) : state(shootline, objects_pointable, liquids_pointable) {} //! Creates a LuaRaycast and leaves it on top of the stack. static int create_object(lua_State *L); /*! * Returns the Raycast from the stack or throws an error. * @param narg location of the RaycastState in the stack */ static LuaRaycast *checkobject(lua_State *L, int narg); //! Registers Raycast as a Lua userdata type. static void Register(lua_State *L); }; struct ScriptCallbackState { ServerScripting *script; int callback_ref; int args_ref; unsigned int refcount; std::string origin; };
pgimeno/minetest
src/script/lua_api/l_env.h
C++
mit
8,323
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_internal.h" #include "common/c_converter.h" #include "common/c_content.h" #include "lua_api/l_http.h" #include "httpfetch.h" #include "settings.h" #include "debug.h" #include "log.h" #include <algorithm> #include <iomanip> #include <cctype> #define HTTP_API(name) \ lua_pushstring(L, #name); \ lua_pushcfunction(L, l_http_##name); \ lua_settable(L, -3); #if USE_CURL void ModApiHttp::read_http_fetch_request(lua_State *L, HTTPFetchRequest &req) { luaL_checktype(L, 1, LUA_TTABLE); req.caller = httpfetch_caller_alloc_secure(); getstringfield(L, 1, "url", req.url); lua_getfield(L, 1, "user_agent"); if (lua_isstring(L, -1)) req.useragent = getstringfield_default(L, 1, "user_agent", ""); lua_pop(L, 1); req.multipart = getboolfield_default(L, 1, "multipart", false); req.timeout = getintfield_default(L, 1, "timeout", 3) * 1000; // post_data: if table, post form data, otherwise raw data lua_getfield(L, 1, "post_data"); if (lua_istable(L, 2)) { lua_pushnil(L); while (lua_next(L, 2) != 0) { req.post_fields[luaL_checkstring(L, -2)] = luaL_checkstring(L, -1); lua_pop(L, 1); } } else if (lua_isstring(L, 2)) { req.post_data = readParam<std::string>(L, 2); } lua_pop(L, 1); lua_getfield(L, 1, "extra_headers"); if (lua_istable(L, 2)) { lua_pushnil(L); while (lua_next(L, 2) != 0) { const char *header = luaL_checkstring(L, -1); req.extra_headers.emplace_back(header); lua_pop(L, 1); } } lua_pop(L, 1); } void ModApiHttp::push_http_fetch_result(lua_State *L, HTTPFetchResult &res, bool completed) { lua_newtable(L); setboolfield(L, -1, "succeeded", res.succeeded); setboolfield(L, -1, "timeout", res.timeout); setboolfield(L, -1, "completed", completed); setintfield(L, -1, "code", res.response_code); setstringfield(L, -1, "data", res.data.c_str()); } // http_api.fetch_async(HTTPRequest definition) int ModApiHttp::l_http_fetch_async(lua_State *L) { NO_MAP_LOCK_REQUIRED; HTTPFetchRequest req; read_http_fetch_request(L, req); actionstream << "Mod performs HTTP request with URL " << req.url << std::endl; httpfetch_async(req); // Convert handle to hex string since lua can't handle 64-bit integers std::stringstream handle_conversion_stream; handle_conversion_stream << std::hex << req.caller; std::string caller_handle(handle_conversion_stream.str()); lua_pushstring(L, caller_handle.c_str()); return 1; } // http_api.fetch_async_get(handle) int ModApiHttp::l_http_fetch_async_get(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string handle_str = luaL_checkstring(L, 1); // Convert hex string back to 64-bit handle u64 handle; std::stringstream handle_conversion_stream; handle_conversion_stream << std::hex << handle_str; handle_conversion_stream >> handle; HTTPFetchResult res; bool completed = httpfetch_async_get(handle, res); push_http_fetch_result(L, res, completed); return 1; } int ModApiHttp::l_request_http_api(lua_State *L) { NO_MAP_LOCK_REQUIRED; // We have to make sure that this function is being called directly by // a mod, otherwise a malicious mod could override this function and // steal its return value. lua_Debug info; // Make sure there's only one item below this function on the stack... if (lua_getstack(L, 2, &info)) { return 0; } FATAL_ERROR_IF(!lua_getstack(L, 1, &info), "lua_getstack() failed"); FATAL_ERROR_IF(!lua_getinfo(L, "S", &info), "lua_getinfo() failed"); // ...and that that item is the main file scope. if (strcmp(info.what, "main") != 0) { return 0; } // Mod must be listed in secure.http_mods or secure.trusted_mods lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME); if (!lua_isstring(L, -1)) { return 0; } std::string mod_name = readParam<std::string>(L, -1); std::string http_mods = g_settings->get("secure.http_mods"); http_mods.erase(std::remove(http_mods.begin(), http_mods.end(), ' '), http_mods.end()); std::vector<std::string> mod_list_http = str_split(http_mods, ','); std::string trusted_mods = g_settings->get("secure.trusted_mods"); trusted_mods.erase(std::remove(trusted_mods.begin(), trusted_mods.end(), ' '), trusted_mods.end()); std::vector<std::string> mod_list_trusted = str_split(trusted_mods, ','); mod_list_http.insert(mod_list_http.end(), mod_list_trusted.begin(), mod_list_trusted.end()); if (std::find(mod_list_http.begin(), mod_list_http.end(), mod_name) == mod_list_http.end()) { lua_pushnil(L); return 1; } lua_getglobal(L, "core"); lua_getfield(L, -1, "http_add_fetch"); lua_newtable(L); HTTP_API(fetch_async); HTTP_API(fetch_async_get); // Stack now looks like this: // <core.http_add_fetch> <table with fetch_async, fetch_async_get> // Now call core.http_add_fetch to append .fetch(request, callback) to table lua_call(L, 1, 1); return 1; } #endif void ModApiHttp::Initialize(lua_State *L, int top) { #if USE_CURL API_FCT(request_http_api); #endif }
pgimeno/minetest
src/script/lua_api/l_http.cpp
C++
mit
5,705
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" #include "config.h" struct HTTPFetchRequest; struct HTTPFetchResult; 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); // http_fetch_async({url=, timeout=, post_data=}) static int l_http_fetch_async(lua_State *L); // http_fetch_async_get(handle) static int l_http_fetch_async_get(lua_State *L); // request_http_api() static int l_request_http_api(lua_State *L); #endif public: static void Initialize(lua_State *L, int top); };
pgimeno/minetest
src/script/lua_api/l_http.h
C++
mit
1,486
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /******************************************************************************/ /******************************************************************************/ /* WARNING!!!! do NOT add this header in any include file or any code file */ /* not being a modapi file!!!!!!!! */ /******************************************************************************/ /******************************************************************************/ #pragma once #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 API_FCT(name) registerFunction(L, #name, l_##name, top) #define MAP_LOCK_REQUIRED #define NO_MAP_LOCK_REQUIRED #define GET_ENV_PTR_NO_MAP_LOCK \ ServerEnvironment *env = (ServerEnvironment *)getEnv(L); \ if (env == NULL) \ return 0 #define GET_ENV_PTR \ MAP_LOCK_REQUIRED; \ GET_ENV_PTR_NO_MAP_LOCK
pgimeno/minetest
src/script/lua_api/l_internal.h
C++
mit
1,870
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_inventory.h" #include "lua_api/l_internal.h" #include "lua_api/l_item.h" #include "common/c_converter.h" #include "common/c_content.h" #include "server.h" #include "remoteplayer.h" /* InvRef */ 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 } Inventory* InvRef::getinv(lua_State *L, InvRef *ref) { return getServer(L)->getInventory(ref->m_loc); } InventoryList* InvRef::getlist(lua_State *L, InvRef *ref, const char *listname) { NO_MAP_LOCK_REQUIRED; Inventory *inv = getinv(L, ref); if(!inv) return NULL; return inv->getList(listname); } void InvRef::reportInventoryChange(lua_State *L, InvRef *ref) { // Inform other things that the inventory has changed getServer(L)->setInventoryModified(ref->m_loc); } // Exported functions // garbage collector int InvRef::gc_object(lua_State *L) { InvRef *o = *(InvRef **)(lua_touserdata(L, 1)); delete o; return 0; } // is_empty(self, listname) -> true/false int InvRef::l_is_empty(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); InventoryList *list = getlist(L, ref, listname); if(list && list->getUsedSlots() > 0){ lua_pushboolean(L, false); } else { lua_pushboolean(L, true); } return 1; } // get_size(self, listname) int InvRef::l_get_size(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); InventoryList *list = getlist(L, ref, listname); if(list){ lua_pushinteger(L, list->getSize()); } else { lua_pushinteger(L, 0); } return 1; } // get_width(self, listname) int InvRef::l_get_width(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); InventoryList *list = getlist(L, ref, listname); if(list){ lua_pushinteger(L, list->getWidth()); } else { lua_pushinteger(L, 0); } return 1; } // set_size(self, listname, size) int InvRef::l_set_size(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); int newsize = luaL_checknumber(L, 3); if (newsize < 0) { lua_pushboolean(L, false); return 1; } Inventory *inv = getinv(L, ref); if(inv == NULL){ lua_pushboolean(L, false); return 1; } if(newsize == 0){ inv->deleteList(listname); reportInventoryChange(L, ref); lua_pushboolean(L, true); return 1; } InventoryList *list = inv->getList(listname); if(list){ list->setSize(newsize); } else { list = inv->addList(listname, newsize); if (!list) { lua_pushboolean(L, false); return 1; } } reportInventoryChange(L, ref); lua_pushboolean(L, true); return 1; } // set_width(self, listname, size) int InvRef::l_set_width(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); int newwidth = luaL_checknumber(L, 3); Inventory *inv = getinv(L, ref); if(inv == NULL){ return 0; } InventoryList *list = inv->getList(listname); if(list){ list->setWidth(newwidth); } else { return 0; } reportInventoryChange(L, ref); return 0; } // get_stack(self, listname, i) -> itemstack int InvRef::l_get_stack(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); int i = luaL_checknumber(L, 3) - 1; InventoryList *list = getlist(L, ref, listname); ItemStack item; if(list != NULL && i >= 0 && i < (int) list->getSize()) item = list->getItem(i); LuaItemStack::create(L, item); return 1; } // set_stack(self, listname, i, stack) -> true/false int InvRef::l_set_stack(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); 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()){ list->changeItem(i, newitem); reportInventoryChange(L, ref); lua_pushboolean(L, true); } else { lua_pushboolean(L, false); } return 1; } // get_list(self, listname) -> list or nil int InvRef::l_get_list(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); Inventory *inv = getinv(L, ref); if(inv){ push_inventory_list(L, inv, listname); } else { lua_pushnil(L); } return 1; } // set_list(self, listname, list) int InvRef::l_set_list(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); Inventory *inv = getinv(L, ref); if(inv == NULL){ return 0; } InventoryList *list = inv->getList(listname); 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); return 0; } // get_lists(self) -> list of InventoryLists int InvRef::l_get_lists(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); Inventory *inv = getinv(L, ref); if (!inv) { return 0; } std::vector<const InventoryList*> lists = inv->getLists(); std::vector<const InventoryList*>::iterator iter = lists.begin(); lua_createtable(L, 0, lists.size()); for (; iter != lists.end(); iter++) { const char* name = (*iter)->getName().c_str(); lua_pushstring(L, name); push_inventory_list(L, inv, name); lua_rawset(L, -3); } return 1; } // set_lists(self, lists) int InvRef::l_set_lists(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); Inventory *inv = getinv(L, ref); if (!inv) { return 0; } // Make a temporary inventory in case reading fails Inventory *tempInv(inv); tempInv->clear(); Server *server = getServer(L); lua_pushnil(L); while (lua_next(L, 2)) { const char *listname = lua_tostring(L, -2); read_inventory_list(L, -1, tempInv, listname, server); lua_pop(L, 1); } inv = tempInv; return 0; } // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack // Returns the leftover stack int InvRef::l_add_item(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); ItemStack item = read_item(L, 3, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); if(list){ ItemStack leftover = list->addItem(item); if(leftover.count != item.count) reportInventoryChange(L, ref); LuaItemStack::create(L, leftover); } else { LuaItemStack::create(L, item); } return 1; } // room_for_item(self, listname, itemstack or itemstring or table or nil) -> true/false // Returns true if the item completely fits into the list int InvRef::l_room_for_item(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); ItemStack item = read_item(L, 3, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); if(list){ lua_pushboolean(L, list->roomForItem(item)); } else { lua_pushboolean(L, false); } 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 int InvRef::l_contains_item(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); ItemStack item = read_item(L, 3, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); bool match_meta = false; if (lua_isboolean(L, 4)) match_meta = readParam<bool>(L, 4); if (list) { lua_pushboolean(L, list->containsItem(item, match_meta)); } else { lua_pushboolean(L, false); } return 1; } // remove_item(self, listname, itemstack or itemstring or table or nil) -> itemstack // Returns the items that were actually removed int InvRef::l_remove_item(lua_State *L) { NO_MAP_LOCK_REQUIRED; InvRef *ref = checkobject(L, 1); const char *listname = luaL_checkstring(L, 2); ItemStack item = read_item(L, 3, getServer(L)->idef()); InventoryList *list = getlist(L, ref, listname); if(list){ ItemStack removed = list->removeItem(item); if(!removed.empty()) reportInventoryChange(L, ref); LuaItemStack::create(L, removed); } else { LuaItemStack::create(L, ItemStack()); } return 1; } // get_location() -> location (like get_inventory(location)) 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){ case InventoryLocation::PLAYER: lua_newtable(L); lua_pushstring(L, "player"); lua_setfield(L, -2, "type"); lua_pushstring(L, loc.name.c_str()); lua_setfield(L, -2, "name"); return 1; case InventoryLocation::NODEMETA: lua_newtable(L); lua_pushstring(L, "node"); lua_setfield(L, -2, "type"); push_v3s16(L, loc.p); lua_setfield(L, -2, "pos"); return 1; case InventoryLocation::DETACHED: lua_newtable(L); lua_pushstring(L, "detached"); lua_setfield(L, -2, "type"); lua_pushstring(L, loc.name.c_str()); lua_setfield(L, -2, "name"); return 1; case InventoryLocation::UNDEFINED: case InventoryLocation::CURRENT_PLAYER: break; } lua_newtable(L); lua_pushstring(L, "undefined"); lua_setfield(L, -2, "type"); return 1; } InvRef::InvRef(const InventoryLocation &loc): m_loc(loc) { } // Creates an InvRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. void InvRef::create(lua_State *L, const InventoryLocation &loc) { NO_MAP_LOCK_REQUIRED; InvRef *o = new InvRef(loc); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); } void InvRef::createPlayer(lua_State *L, RemotePlayer *player) { NO_MAP_LOCK_REQUIRED; InventoryLocation loc; loc.setPlayer(player->getName()); create(L, loc); } void InvRef::createNodeMeta(lua_State *L, v3s16 p) { InventoryLocation loc; loc.setNodeMeta(p); create(L, loc); } void InvRef::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); // drop metatable 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); } 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} }; // get_inventory(location) int ModApiInventory::l_get_inventory(lua_State *L) { InventoryLocation loc; std::string type = checkstringfield(L, 1, "type"); if(type == "node"){ MAP_LOCK_REQUIRED; lua_getfield(L, 1, "pos"); v3s16 pos = check_v3s16(L, -1); loc.setNodeMeta(pos); if (getServer(L)->getInventory(loc) != NULL) InvRef::create(L, loc); else lua_pushnil(L); return 1; } NO_MAP_LOCK_REQUIRED; if (type == "player") { std::string name = checkstringfield(L, 1, "name"); loc.setPlayer(name); } else if (type == "detached") { std::string name = checkstringfield(L, 1, "name"); loc.setDetached(name); } if (getServer(L)->getInventory(loc) != NULL) InvRef::create(L, loc); else lua_pushnil(L); return 1; // END NO_MAP_LOCK_REQUIRED; } // create_detached_inventory_raw(name, [player_name]) int ModApiInventory::l_create_detached_inventory_raw(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *name = luaL_checkstring(L, 1); std::string player = readParam<std::string>(L, 2, ""); if (getServer(L)->createDetachedInventory(name, player) != NULL) { InventoryLocation loc; loc.setDetached(name); InvRef::create(L, loc); } else { lua_pushnil(L); } return 1; } // remove_detached_inventory_raw(name) int ModApiInventory::l_remove_detached_inventory_raw(lua_State *L) { NO_MAP_LOCK_REQUIRED; const std::string &name = luaL_checkstring(L, 1); lua_pushboolean(L, getServer(L)->removeDetachedInventory(name)); return 1; } void ModApiInventory::Initialize(lua_State *L, int top) { API_FCT(create_detached_inventory_raw); API_FCT(remove_detached_inventory_raw); API_FCT(get_inventory); }
pgimeno/minetest
src/script/lua_api/l_inventory.cpp
C++
mit
13,929
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" #include "inventory.h" #include "inventorymanager.h" class RemotePlayer; /* InvRef */ class InvRef : public ModApiBase { private: InventoryLocation m_loc; static const char className[]; static const luaL_Reg methods[]; static InvRef *checkobject(lua_State *L, int narg); static Inventory* getinv(lua_State *L, InvRef *ref); static InventoryList* getlist(lua_State *L, InvRef *ref, const char *listname); static void reportInventoryChange(lua_State *L, InvRef *ref); // Exported functions // garbage collector static int gc_object(lua_State *L); // is_empty(self, listname) -> true/false static int l_is_empty(lua_State *L); // get_size(self, listname) static int l_get_size(lua_State *L); // get_width(self, listname) static int l_get_width(lua_State *L); // set_size(self, listname, size) static int l_set_size(lua_State *L); // set_width(self, listname, size) static int l_set_width(lua_State *L); // get_stack(self, listname, i) -> itemstack static int l_get_stack(lua_State *L); // set_stack(self, listname, i, stack) -> true/false static int l_set_stack(lua_State *L); // get_list(self, listname) -> list or nil static int l_get_list(lua_State *L); // set_list(self, listname, list) static int l_set_list(lua_State *L); // get_lists(self) -> list of InventoryLists static int l_get_lists(lua_State *L); // set_lists(self, lists) static int l_set_lists(lua_State *L); // add_item(self, listname, itemstack or itemstring or table or nil) -> itemstack // 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 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 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 static int l_remove_item(lua_State *L); // get_location() -> location (like get_inventory(location)) static int l_get_location(lua_State *L); public: InvRef(const InventoryLocation &loc); ~InvRef() = default; // Creates an InvRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. static void create(lua_State *L, const InventoryLocation &loc); static void createPlayer(lua_State *L, RemotePlayer *player); static void createNodeMeta(lua_State *L, v3s16 p); static void Register(lua_State *L); }; class ModApiInventory : public ModApiBase { private: static int l_create_detached_inventory_raw(lua_State *L); static int l_remove_detached_inventory_raw(lua_State *L); static int l_get_inventory(lua_State *L); public: static void Initialize(lua_State *L, int top); };
pgimeno/minetest
src/script/lua_api/l_inventory.h
C++
mit
3,798
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_item.h" #include "lua_api/l_itemstackmeta.h" #include "lua_api/l_internal.h" #include "common/c_converter.h" #include "common/c_content.h" #include "itemdef.h" #include "nodedef.h" #include "server.h" #include "content_sao.h" #include "inventory.h" #include "log.h" // garbage collector int LuaItemStack::gc_object(lua_State *L) { LuaItemStack *o = *(LuaItemStack **)(lua_touserdata(L, 1)); delete o; return 0; } // is_empty(self) -> true/false int LuaItemStack::l_is_empty(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; lua_pushboolean(L, item.empty()); return 1; } // get_name(self) -> string int LuaItemStack::l_get_name(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; lua_pushstring(L, item.name.c_str()); return 1; } // set_name(self, name) int LuaItemStack::l_set_name(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; bool status = true; item.name = luaL_checkstring(L, 2); if (item.name.empty() || item.empty()) { item.clear(); status = false; } lua_pushboolean(L, status); return 1; } // get_count(self) -> number int LuaItemStack::l_get_count(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; lua_pushinteger(L, item.count); return 1; } // set_count(self, number) int LuaItemStack::l_set_count(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; bool status; lua_Integer count = luaL_checkinteger(L, 2); if (count > 0 && count <= 65535) { item.count = count; status = true; } else { item.clear(); status = false; } lua_pushboolean(L, status); return 1; } // get_wear(self) -> number int LuaItemStack::l_get_wear(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; lua_pushinteger(L, item.wear); return 1; } // set_wear(self, number) int LuaItemStack::l_set_wear(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; bool status; lua_Integer wear = luaL_checkinteger(L, 2); if (wear <= 65535) { item.wear = wear; status = true; } else { item.clear(); status = false; } lua_pushboolean(L, status); return 1; } // get_meta(self) -> string int LuaItemStack::l_get_meta(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStackMetaRef::create(L, &o->m_stack); return 1; } // DEPRECATED // get_metadata(self) -> string int LuaItemStack::l_get_metadata(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; const std::string &value = item.metadata.getString(""); lua_pushlstring(L, value.c_str(), value.size()); return 1; } // DEPRECATED // set_metadata(self, string) int LuaItemStack::l_set_metadata(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; size_t len = 0; const char *ptr = luaL_checklstring(L, 2, &len); item.metadata.setString("", std::string(ptr, len)); lua_pushboolean(L, true); return 1; } // clear(self) -> true int LuaItemStack::l_clear(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); o->m_stack.clear(); lua_pushboolean(L, true); return 1; } // replace(self, itemstack or itemstring or table or nil) -> true int LuaItemStack::l_replace(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); o->m_stack = read_item(L, 2, getGameDef(L)->idef()); lua_pushboolean(L, true); return 1; } // to_string(self) -> string int LuaItemStack::l_to_string(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); std::string itemstring = o->m_stack.getItemString(); lua_pushstring(L, itemstring.c_str()); return 1; } // to_table(self) -> table or nil 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()) { lua_pushnil(L); } else { lua_newtable(L); lua_pushstring(L, item.name.c_str()); lua_setfield(L, -2, "name"); lua_pushinteger(L, item.count); lua_setfield(L, -2, "count"); lua_pushinteger(L, item.wear); lua_setfield(L, -2, "wear"); const std::string &metadata_str = item.metadata.getString(""); lua_pushlstring(L, metadata_str.c_str(), metadata_str.size()); lua_setfield(L, -2, "metadata"); lua_newtable(L); const StringMap &fields = item.metadata.getStrings(); for (const auto &field : fields) { const std::string &name = field.first; if (name.empty()) continue; const std::string &value = field.second; lua_pushlstring(L, name.c_str(), name.size()); lua_pushlstring(L, value.c_str(), value.size()); lua_settable(L, -3); } lua_setfield(L, -2, "meta"); } return 1; } // get_stack_max(self) -> number int LuaItemStack::l_get_stack_max(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; lua_pushinteger(L, item.getStackMax(getGameDef(L)->idef())); return 1; } // get_free_space(self) -> number int LuaItemStack::l_get_free_space(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; lua_pushinteger(L, item.freeSpace(getGameDef(L)->idef())); return 1; } // is_known(self) -> true/false // Checks if the item is defined. int LuaItemStack::l_is_known(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; bool is_known = item.isKnown(getGameDef(L)->idef()); lua_pushboolean(L, is_known); return 1; } // get_definition(self) -> table // Returns the item definition table from registered_items, // or a fallback one (name="unknown") int LuaItemStack::l_get_definition(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; // Get registered_items[name] lua_getglobal(L, "core"); 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)) { lua_pop(L, 1); lua_getfield(L, -1, "unknown"); } return 1; } // get_tool_capabilities(self) -> table // Returns the effective tool digging properties. // Returns those of the hand ("") if this item has none associated. 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()); push_tool_capabilities(L, prop); return 1; } // add_wear(self, amount) -> true/false // The range for "amount" is [0,65535]. Wear is only added if the item // is a tool. Adding wear might destroy the item. // Returns true if the item is (or was) a tool. int LuaItemStack::l_add_wear(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; int amount = lua_tointeger(L, 2); bool result = item.addWear(amount, getGameDef(L)->idef()); lua_pushboolean(L, result); return 1; } // add_item(self, itemstack or itemstring or table or nil) -> itemstack // Returns leftover item stack int LuaItemStack::l_add_item(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; ItemStack newitem = read_item(L, -1, getGameDef(L)->idef()); ItemStack leftover = item.addItem(newitem, getGameDef(L)->idef()); create(L, leftover); return 1; } // 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 int LuaItemStack::l_item_fits(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; 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 return 2; } // take_item(self, takecount=1) -> itemstack int LuaItemStack::l_take_item(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; u32 takecount = 1; if(!lua_isnone(L, 2)) takecount = luaL_checkinteger(L, 2); ItemStack taken = item.takeItem(takecount); create(L, taken); return 1; } // peek_item(self, peekcount=1) -> itemstack int LuaItemStack::l_peek_item(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = checkobject(L, 1); ItemStack &item = o->m_stack; u32 peekcount = 1; 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) { } const ItemStack& LuaItemStack::getItem() const { return m_stack; } ItemStack& LuaItemStack::getItem() { return m_stack; } // LuaItemStack(itemstack or itemstring or table or nil) // Creates an LuaItemStack and leaves it on top of stack int LuaItemStack::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; ItemStack item = read_item(L, 1, getGameDef(L)->idef()); LuaItemStack *o = new LuaItemStack(item); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } // Not callable from Lua int LuaItemStack::create(lua_State *L, const ItemStack &item) { NO_MAP_LOCK_REQUIRED; LuaItemStack *o = new LuaItemStack(item); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } LuaItemStack* LuaItemStack::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 *(LuaItemStack**)ud; // unbox pointer } void LuaItemStack::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); // drop metatable luaL_openlib(L, 0, methods, 0); // fill methodtable lua_pop(L, 1); // drop methodtable // Can be created from Lua (LuaItemStack(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, 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 */ // register_item_raw({lots of stuff}) int ModApiItemMod::l_register_item_raw(lua_State *L) { NO_MAP_LOCK_REQUIRED; luaL_checktype(L, 1, LUA_TTABLE); int table = 1; // Get the writable item and node definition managers from the server IWritableItemDefManager *idef = getServer(L)->getWritableItemDefManager(); NodeDefManager *ndef = getServer(L)->getWritableNodeDefManager(); // Check if name is defined std::string name; lua_getfield(L, table, "name"); if(lua_isstring(L, -1)){ name = readParam<std::string>(L, -1); verbosestream<<"register_item_raw: "<<name<<std::endl; } else { throw LuaError("register_item_raw: name is not defined or not a string"); } // Check if on_use is defined ItemDefinition def; // Set a distinctive default value to check if this is set def.node_placement_prediction = "__default"; // Read the item definition read_item_definition(L, table, def, def); // 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) def.node_placement_prediction = name; else def.node_placement_prediction = ""; } // Register item definition idef->registerItem(def); // Read the node definition (content features) and register it if (def.type == ITEM_NODE) { ContentFeatures f = read_content_features(L, table); // when a mod reregisters ignore, only texture changes and such should // be done if (f.name == "ignore") return 0; 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 + ")"); } } return 0; /* number of results */ } // unregister_item(name) int ModApiItemMod::l_unregister_item_raw(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string name = luaL_checkstring(L, 1); IWritableItemDefManager *idef = getServer(L)->getWritableItemDefManager(); // Unregister the node if (idef->get(name).type == ITEM_NODE) { NodeDefManager *ndef = getServer(L)->getWritableNodeDefManager(); ndef->removeNode(name); } idef->unregisterItem(name); return 0; /* number of results */ } // register_alias_raw(name, convert_to_name) int ModApiItemMod::l_register_alias_raw(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string name = luaL_checkstring(L, 1); std::string convert_to = luaL_checkstring(L, 2); // Get the writable item definition manager from the server IWritableItemDefManager *idef = getServer(L)->getWritableItemDefManager(); idef->registerAlias(name, convert_to); return 0; /* number of results */ } // get_content_id(name) int ModApiItemMod::l_get_content_id(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string name = luaL_checkstring(L, 1); const NodeDefManager *ndef = getGameDef(L)->getNodeDefManager(); content_t c = ndef->getId(name); lua_pushinteger(L, c); return 1; /* number of results */ } // get_name_from_content_id(name) int ModApiItemMod::l_get_name_from_content_id(lua_State *L) { NO_MAP_LOCK_REQUIRED; content_t c = luaL_checkint(L, 1); const NodeDefManager *ndef = getGameDef(L)->getNodeDefManager(); const char *name = ndef->get(c).name.c_str(); lua_pushstring(L, name); return 1; /* number of results */ } void ModApiItemMod::Initialize(lua_State *L, int top) { API_FCT(register_item_raw); API_FCT(unregister_item_raw); API_FCT(register_alias_raw); API_FCT(get_content_id); API_FCT(get_name_from_content_id); }
pgimeno/minetest
src/script/lua_api/l_item.cpp
C++
mit
16,203
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" #include "inventory.h" // ItemStack class LuaItemStack : public ModApiBase { private: ItemStack m_stack; static const char className[]; static const luaL_Reg methods[]; // Exported functions // garbage collector static int gc_object(lua_State *L); // is_empty(self) -> true/false static int l_is_empty(lua_State *L); // get_name(self) -> string static int l_get_name(lua_State *L); // set_name(self, name) static int l_set_name(lua_State *L); // get_count(self) -> number static int l_get_count(lua_State *L); // set_count(self, number) static int l_set_count(lua_State *L); // get_wear(self) -> number static int l_get_wear(lua_State *L); // set_wear(self, number) static int l_set_wear(lua_State *L); // get_meta(self) -> string static int l_get_meta(lua_State *L); // DEPRECATED // get_metadata(self) -> string static int l_get_metadata(lua_State *L); // DEPRECATED // set_metadata(self, string) static int l_set_metadata(lua_State *L); // clear(self) -> true static int l_clear(lua_State *L); // replace(self, itemstack or itemstring or table or nil) -> true static int l_replace(lua_State *L); // to_string(self) -> string static int l_to_string(lua_State *L); // to_table(self) -> table or nil static int l_to_table(lua_State *L); // get_stack_max(self) -> number static int l_get_stack_max(lua_State *L); // get_free_space(self) -> number static int l_get_free_space(lua_State *L); // is_known(self) -> true/false // Checks if the item is defined. static int l_is_known(lua_State *L); // get_definition(self) -> table // Returns the item definition table from core.registered_items, // or a fallback one (name="unknown") static int l_get_definition(lua_State *L); // get_tool_capabilities(self) -> table // Returns the effective tool digging properties. // Returns those of the hand ("") if this item has none associated. static int l_get_tool_capabilities(lua_State *L); // add_wear(self, amount) -> true/false // The range for "amount" is [0,65535]. Wear is only added if the item // is a tool. Adding wear might destroy the item. // Returns true if the item is (or was) a tool. static int l_add_wear(lua_State *L); // add_item(self, itemstack or itemstring or table or nil) -> itemstack // 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 // Second return value is the would-be-left-over item stack static int l_item_fits(lua_State *L); // take_item(self, takecount=1) -> itemstack static int l_take_item(lua_State *L); // peek_item(self, peekcount=1) -> itemstack static int l_peek_item(lua_State *L); public: LuaItemStack(const ItemStack &item); ~LuaItemStack() = default; 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 void Register(lua_State *L); }; 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); };
pgimeno/minetest
src/script/lua_api/l_item.h
C++
mit
4,438
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017-8 rubenwardy <rw@rubenwardy.com> Copyright (C) 2017 raymoo This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_itemstackmeta.h" #include "lua_api/l_internal.h" #include "common/c_content.h" /* NodeMetaRef */ 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 } Metadata* ItemStackMetaRef::getmeta(bool auto_create) { return &istack->metadata; } void ItemStackMetaRef::clearMeta() { istack->metadata.clear(); } void ItemStackMetaRef::reportMetadataChange(const std::string *name) { // TODO } // Exported functions int ItemStackMetaRef::l_set_tool_capabilities(lua_State *L) { ItemStackMetaRef *metaref = checkobject(L, 1); if (lua_isnoneornil(L, 2)) { metaref->clearToolCapabilities(); } else if (lua_istable(L, 2)) { ToolCapabilities caps = read_tool_capabilities(L, 2); metaref->setToolCapabilities(caps); } else { luaL_typerror(L, 2, "table or nil"); } return 0; } // garbage collector int ItemStackMetaRef::gc_object(lua_State *L) { ItemStackMetaRef *o = *(ItemStackMetaRef **)(lua_touserdata(L, 1)); delete o; return 0; } // Creates an NodeMetaRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. void ItemStackMetaRef::create(lua_State *L, ItemStack *istack) { ItemStackMetaRef *o = new ItemStackMetaRef(istack); //infostream<<"NodeMetaRef::create: o="<<o<<std::endl; *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); } void ItemStackMetaRef::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "metadata_class"); lua_pushlstring(L, className, strlen(className)); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pushliteral(L, "__eq"); lua_pushcfunction(L, l_equals); lua_settable(L, metatable); lua_pop(L, 1); // drop metatable 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); } const char ItemStackMetaRef::className[] = "ItemStackMetaRef"; const luaL_Reg ItemStackMetaRef::methods[] = { luamethod(MetaDataRef, contains), luamethod(MetaDataRef, get), luamethod(MetaDataRef, get_string), luamethod(MetaDataRef, set_string), luamethod(MetaDataRef, get_int), luamethod(MetaDataRef, set_int), luamethod(MetaDataRef, get_float), luamethod(MetaDataRef, set_float), luamethod(MetaDataRef, to_table), luamethod(MetaDataRef, from_table), luamethod(MetaDataRef, equals), luamethod(ItemStackMetaRef, set_tool_capabilities), {0,0} };
pgimeno/minetest
src/script/lua_api/l_itemstackmeta.cpp
C++
mit
3,925
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017-8 rubenwardy <rw@rubenwardy.com> Copyright (C) 2017 raymoo This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" #include "lua_api/l_metadata.h" #include "irrlichttypes_bloated.h" #include "inventory.h" class ItemStackMetaRef : public MetaDataRef { private: ItemStack *istack = nullptr; static const char className[]; static const luaL_Reg methods[]; static ItemStackMetaRef *checkobject(lua_State *L, int narg); virtual Metadata* getmeta(bool auto_create); virtual void clearMeta(); virtual void reportMetadataChange(const std::string *name = nullptr); void setToolCapabilities(const ToolCapabilities &caps) { istack->metadata.setToolCapabilities(caps); } 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() = default; // Creates an ItemStackMetaRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. static void create(lua_State *L, ItemStack *istack); static void Register(lua_State *L); };
pgimeno/minetest
src/script/lua_api/l_itemstackmeta.h
C++
mit
2,007
/* Minetest Copyright (C) 2017 Dumbeldor, Vincent Glize <vincent.glize@live.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "l_localplayer.h" #include "l_internal.h" #include "script/common/c_converter.h" #include "client/localplayer.h" #include "hud.h" #include "common/c_content.h" LuaLocalPlayer::LuaLocalPlayer(LocalPlayer *m) : m_localplayer(m) { } void LuaLocalPlayer::create(lua_State *L, LocalPlayer *m) { LuaLocalPlayer *o = new LuaLocalPlayer(m); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); // Keep localplayer object stack id int localplayer_object = lua_gettop(L); lua_getglobal(L, "core"); luaL_checktype(L, -1, LUA_TTABLE); int coretable = lua_gettop(L); lua_pushvalue(L, localplayer_object); lua_setfield(L, coretable, "localplayer"); } int LuaLocalPlayer::l_get_velocity(lua_State *L) { LocalPlayer *player = getobject(L, 1); push_v3f(L, player->getSpeed() / BS); return 1; } int LuaLocalPlayer::l_get_hp(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_pushinteger(L, player->hp); return 1; } int LuaLocalPlayer::l_get_name(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_pushstring(L, player->getName()); return 1; } int LuaLocalPlayer::l_is_attached(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_pushboolean(L, player->isAttached); return 1; } int LuaLocalPlayer::l_is_touching_ground(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_pushboolean(L, player->touching_ground); return 1; } int LuaLocalPlayer::l_is_in_liquid(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_pushboolean(L, player->in_liquid); return 1; } int LuaLocalPlayer::l_is_in_liquid_stable(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_pushboolean(L, player->in_liquid_stable); return 1; } int LuaLocalPlayer::l_get_liquid_viscosity(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_pushinteger(L, player->liquid_viscosity); return 1; } int LuaLocalPlayer::l_is_climbing(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_pushboolean(L, player->is_climbing); return 1; } int LuaLocalPlayer::l_swimming_vertical(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_pushboolean(L, player->swimming_vertical); return 1; } int LuaLocalPlayer::l_get_physics_override(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_newtable(L); lua_pushnumber(L, player->physics_override_speed); lua_setfield(L, -2, "speed"); lua_pushnumber(L, player->physics_override_jump); lua_setfield(L, -2, "jump"); lua_pushnumber(L, player->physics_override_gravity); lua_setfield(L, -2, "gravity"); lua_pushboolean(L, player->physics_override_sneak); lua_setfield(L, -2, "sneak"); lua_pushboolean(L, player->physics_override_sneak_glitch); lua_setfield(L, -2, "sneak_glitch"); return 1; } int LuaLocalPlayer::l_get_override_pos(lua_State *L) { LocalPlayer *player = getobject(L, 1); push_v3f(L, player->overridePosition); return 1; } int LuaLocalPlayer::l_get_last_pos(lua_State *L) { LocalPlayer *player = getobject(L, 1); push_v3f(L, player->last_position / BS); return 1; } int LuaLocalPlayer::l_get_last_velocity(lua_State *L) { LocalPlayer *player = getobject(L, 1); push_v3f(L, player->last_speed); return 1; } int LuaLocalPlayer::l_get_last_look_vertical(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_pushnumber(L, -1.0 * player->last_pitch * core::DEGTORAD); return 1; } int LuaLocalPlayer::l_get_last_look_horizontal(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_pushnumber(L, (player->last_yaw + 90.) * core::DEGTORAD); return 1; } int LuaLocalPlayer::l_get_key_pressed(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_pushinteger(L, player->last_keyPressed); return 1; } int LuaLocalPlayer::l_get_breath(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_pushinteger(L, player->getBreath()); return 1; } int LuaLocalPlayer::l_get_pos(lua_State *L) { LocalPlayer *player = getobject(L, 1); push_v3f(L, player->getPosition() / BS); return 1; } int LuaLocalPlayer::l_get_movement_acceleration(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_newtable(L); lua_pushnumber(L, player->movement_acceleration_default); lua_setfield(L, -2, "default"); lua_pushnumber(L, player->movement_acceleration_air); lua_setfield(L, -2, "air"); lua_pushnumber(L, player->movement_acceleration_fast); lua_setfield(L, -2, "fast"); return 1; } int LuaLocalPlayer::l_get_movement_speed(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_newtable(L); lua_pushnumber(L, player->movement_speed_walk); lua_setfield(L, -2, "walk"); lua_pushnumber(L, player->movement_speed_crouch); lua_setfield(L, -2, "crouch"); lua_pushnumber(L, player->movement_speed_fast); lua_setfield(L, -2, "fast"); lua_pushnumber(L, player->movement_speed_climb); lua_setfield(L, -2, "climb"); lua_pushnumber(L, player->movement_speed_jump); lua_setfield(L, -2, "jump"); return 1; } int LuaLocalPlayer::l_get_movement(lua_State *L) { LocalPlayer *player = getobject(L, 1); lua_newtable(L); lua_pushnumber(L, player->movement_liquid_fluidity); lua_setfield(L, -2, "liquid_fluidity"); lua_pushnumber(L, player->movement_liquid_fluidity_smooth); lua_setfield(L, -2, "liquid_fluidity_smooth"); lua_pushnumber(L, player->movement_liquid_sink); lua_setfield(L, -2, "liquid_sink"); lua_pushnumber(L, player->movement_gravity); lua_setfield(L, -2, "gravity"); return 1; } // hud_add(self, form) int LuaLocalPlayer::l_hud_add(lua_State *L) { LocalPlayer *player = getobject(L, 1); HudElement *elem = new HudElement; read_hud_element(L, elem); u32 id = player->addHud(elem); if (id == U32_MAX) { delete elem; return 0; } lua_pushnumber(L, id); return 1; } // hud_remove(self, id) int LuaLocalPlayer::l_hud_remove(lua_State *L) { LocalPlayer *player = getobject(L, 1); u32 id = luaL_checkinteger(L, 2); HudElement *element = player->removeHud(id); if (!element) lua_pushboolean(L, false); else lua_pushboolean(L, true); delete element; return 1; } // hud_change(self, id, stat, data) int LuaLocalPlayer::l_hud_change(lua_State *L) { LocalPlayer *player = getobject(L, 1); u32 id = luaL_checkinteger(L, 2); HudElement *element = player->getHud(id); if (!element) return 0; void *unused; read_hud_change(L, element, &unused); lua_pushboolean(L, true); return 1; } // hud_get(self, id) int LuaLocalPlayer::l_hud_get(lua_State *L) { LocalPlayer *player = getobject(L, 1); u32 id = luaL_checkinteger(L, -1); HudElement *e = player->getHud(id); if (!e) { lua_pushnil(L); return 1; } push_hud_element(L, e); return 1; } LuaLocalPlayer *LuaLocalPlayer::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 *(LuaLocalPlayer **)ud; } LocalPlayer *LuaLocalPlayer::getobject(LuaLocalPlayer *ref) { return ref->m_localplayer; } LocalPlayer *LuaLocalPlayer::getobject(lua_State *L, int narg) { LuaLocalPlayer *ref = checkobject(L, narg); assert(ref); LocalPlayer *player = getobject(ref); assert(player); return player; } int LuaLocalPlayer::gc_object(lua_State *L) { LuaLocalPlayer *o = *(LuaLocalPlayer **)(lua_touserdata(L, 1)); delete o; return 0; } void LuaLocalPlayer::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); // Drop metatable luaL_openlib(L, 0, methods, 0); // fill methodtable lua_pop(L, 1); // Drop methodtable } const char LuaLocalPlayer::className[] = "LocalPlayer"; const luaL_Reg LuaLocalPlayer::methods[] = { luamethod(LuaLocalPlayer, get_velocity), luamethod(LuaLocalPlayer, get_hp), luamethod(LuaLocalPlayer, get_name), luamethod(LuaLocalPlayer, is_attached), luamethod(LuaLocalPlayer, is_touching_ground), luamethod(LuaLocalPlayer, is_in_liquid), luamethod(LuaLocalPlayer, is_in_liquid_stable), luamethod(LuaLocalPlayer, get_liquid_viscosity), luamethod(LuaLocalPlayer, is_climbing), luamethod(LuaLocalPlayer, swimming_vertical), luamethod(LuaLocalPlayer, get_physics_override), luamethod(LuaLocalPlayer, get_override_pos), luamethod(LuaLocalPlayer, get_last_pos), luamethod(LuaLocalPlayer, get_last_velocity), luamethod(LuaLocalPlayer, get_last_look_horizontal), luamethod(LuaLocalPlayer, get_last_look_vertical), luamethod(LuaLocalPlayer, get_key_pressed), luamethod(LuaLocalPlayer, get_breath), luamethod(LuaLocalPlayer, get_pos), luamethod(LuaLocalPlayer, get_movement_acceleration), luamethod(LuaLocalPlayer, get_movement_speed), luamethod(LuaLocalPlayer, get_movement), luamethod(LuaLocalPlayer, hud_add), luamethod(LuaLocalPlayer, hud_remove), luamethod(LuaLocalPlayer, hud_change), luamethod(LuaLocalPlayer, hud_get), {0, 0} };
pgimeno/minetest
src/script/lua_api/l_localplayer.cpp
C++
mit
10,034
/* Minetest Copyright (C) 2017 Dumbeldor, Vincent Glize <vincent.glize@live.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "l_base.h" class LocalPlayer; class LuaLocalPlayer : public ModApiBase { private: static const char className[]; static const luaL_Reg methods[]; // garbage collector static int gc_object(lua_State *L); static int l_get_velocity(lua_State *L); static int l_get_hp(lua_State *L); static int l_get_name(lua_State *L); static int l_is_attached(lua_State *L); static int l_is_touching_ground(lua_State *L); static int l_is_in_liquid(lua_State *L); static int l_is_in_liquid_stable(lua_State *L); static int l_get_liquid_viscosity(lua_State *L); static int l_is_climbing(lua_State *L); static int l_swimming_vertical(lua_State *L); static int l_get_physics_override(lua_State *L); static int l_get_override_pos(lua_State *L); static int l_get_last_pos(lua_State *L); static int l_get_last_velocity(lua_State *L); static int l_get_last_look_vertical(lua_State *L); static int l_get_last_look_horizontal(lua_State *L); static int l_get_key_pressed(lua_State *L); static int l_get_breath(lua_State *L); static int l_get_pos(lua_State *L); static int l_get_movement_acceleration(lua_State *L); static int l_get_movement_speed(lua_State *L); static int l_get_movement(lua_State *L); // hud_add(self, id, form) static int l_hud_add(lua_State *L); // hud_rm(self, id) static int l_hud_remove(lua_State *L); // hud_change(self, id, stat, data) static int l_hud_change(lua_State *L); // hud_get(self, id) static int l_hud_get(lua_State *L); LocalPlayer *m_localplayer = nullptr; public: LuaLocalPlayer(LocalPlayer *m); ~LuaLocalPlayer() = default; static void create(lua_State *L, LocalPlayer *m); static LuaLocalPlayer *checkobject(lua_State *L, int narg); static LocalPlayer *getobject(LuaLocalPlayer *ref); static LocalPlayer *getobject(lua_State *L, int narg); static void Register(lua_State *L); };
pgimeno/minetest
src/script/lua_api/l_localplayer.h
C++
mit
2,666
/* Minetest Copyright (C) 2013 sapier This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_mainmenu.h" #include "lua_api/l_internal.h" #include "common/c_content.h" #include "cpp_api/s_async.h" #include "gui/guiEngine.h" #include "gui/guiMainMenu.h" #include "gui/guiKeyChangeMenu.h" #include "gui/guiPathSelectMenu.h" #include "version.h" #include "porting.h" #include "filesys.h" #include "convert_json.h" #include "content/packages.h" #include "content/content.h" #include "content/subgames.h" #include "serverlist.h" #include "mapgen/mapgen.h" #include "settings.h" #include <IFileArchive.h> #include <IFileSystem.h> #include "client/renderingengine.h" #include "network/networkprotocol.h" /******************************************************************************/ std::string ModApiMainMenu::getTextData(lua_State *L, std::string name) { lua_getglobal(L, "gamedata"); lua_getfield(L, -1, name.c_str()); if(lua_isnil(L, -1)) return ""; return luaL_checkstring(L, -1); } /******************************************************************************/ 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)) { valid = false; return -1; } valid = true; return luaL_checkinteger(L, -1); } /******************************************************************************/ 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)) { valid = false; return false; } valid = true; return readParam<bool>(L, -1); } /******************************************************************************/ int ModApiMainMenu::l_update_formspec(lua_State *L) { GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); if (engine->m_startgame) return 0; //read formspec std::string formspec(luaL_checkstring(L, 1)); if (engine->m_formspecgui != 0) { engine->m_formspecgui->setForm(formspec); } return 0; } /******************************************************************************/ int ModApiMainMenu::l_start(lua_State *L) { GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); //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->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->serverdescription = getTextData(L,"serverdescription"); data->servername = getTextData(L,"servername"); //close menu next time engine->m_startgame = true; return 0; } /******************************************************************************/ int ModApiMainMenu::l_close(lua_State *L) { GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); engine->m_kill = true; return 0; } /******************************************************************************/ int ModApiMainMenu::l_set_background(lua_State *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; unsigned int minsize = 16; if (!lua_isnone(L, 3)) { tile_image = readParam<bool>(L, 3); } if (!lua_isnone(L, 4)) { minsize = lua_tonumber(L, 4); } if (backgroundlevel == "background") { retval |= engine->setTexture(TEX_LAYER_BACKGROUND, texturename, tile_image, minsize); } if (backgroundlevel == "overlay") { retval |= engine->setTexture(TEX_LAYER_OVERLAY, texturename, tile_image, minsize); } if (backgroundlevel == "header") { retval |= engine->setTexture(TEX_LAYER_HEADER, texturename, tile_image, minsize); } if (backgroundlevel == "footer") { retval |= engine->setTexture(TEX_LAYER_FOOTER, texturename, tile_image, minsize); } lua_pushboolean(L,retval); return 1; } /******************************************************************************/ int ModApiMainMenu::l_set_clouds(lua_State *L) { GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); bool value = readParam<bool>(L,1); engine->m_clouds_enabled = value; return 0; } /******************************************************************************/ int ModApiMainMenu::l_get_textlist_index(lua_State *L) { // get_table_index accepts both tables and textlists return l_get_table_index(L); } /******************************************************************************/ int ModApiMainMenu::l_get_table_index(lua_State *L) { GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); std::string tablename(luaL_checkstring(L, 1)); GUITable *table = engine->m_menu->getTable(tablename); s32 selection = table ? table->getSelected() : 0; if (selection >= 1) lua_pushinteger(L, selection); else lua_pushnil(L); return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_worlds(lua_State *L) { std::vector<WorldSpec> worlds = getAvailableWorlds(); lua_newtable(L); int top = lua_gettop(L); unsigned int index = 1; for (const WorldSpec &world : worlds) { lua_pushnumber(L,index); lua_newtable(L); int top_lvl2 = lua_gettop(L); lua_pushstring(L,"path"); lua_pushstring(L, world.path.c_str()); lua_settable(L, top_lvl2); lua_pushstring(L,"name"); lua_pushstring(L, world.name.c_str()); lua_settable(L, top_lvl2); lua_pushstring(L,"gameid"); lua_pushstring(L, world.gameid.c_str()); lua_settable(L, top_lvl2); lua_settable(L, top); index++; } return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_favorites(lua_State *L) { std::string listtype = "local"; if (!lua_isnone(L,1)) { listtype = luaL_checkstring(L,1); } std::vector<ServerListSpec> servers; if(listtype == "online") { servers = ServerList::getOnline(); } else { servers = ServerList::getLocal(); } lua_newtable(L); int top = lua_gettop(L); unsigned int index = 1; for (const Json::Value &server : servers) { lua_pushnumber(L,index); lua_newtable(L); int top_lvl2 = lua_gettop(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); if ((!clients_raw.empty()) && (*endptr == 0)) { lua_pushstring(L,"clients"); lua_pushnumber(L,numbervalue); lua_settable(L, top_lvl2); } } 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); if ((!clients_max_raw.empty()) && (*endptr == 0)) { lua_pushstring(L,"clients_max"); lua_pushnumber(L,numbervalue); lua_settable(L, top_lvl2); } } if (!server["version"].asString().empty()) { lua_pushstring(L,"version"); std::string topush = server["version"].asString(); lua_pushstring(L,topush.c_str()); lua_settable(L, top_lvl2); } if (!server["proto_min"].asString().empty()) { lua_pushstring(L,"proto_min"); lua_pushinteger(L, server["proto_min"].asInt()); lua_settable(L, top_lvl2); } if (!server["proto_max"].asString().empty()) { lua_pushstring(L,"proto_max"); lua_pushinteger(L, server["proto_max"].asInt()); lua_settable(L, top_lvl2); } if (!server["password"].asString().empty()) { lua_pushstring(L,"password"); lua_pushboolean(L, server["password"].asBool()); lua_settable(L, top_lvl2); } if (!server["creative"].asString().empty()) { lua_pushstring(L,"creative"); lua_pushboolean(L, server["creative"].asBool()); lua_settable(L, top_lvl2); } if (!server["damage"].asString().empty()) { lua_pushstring(L,"damage"); lua_pushboolean(L, server["damage"].asBool()); lua_settable(L, top_lvl2); } if (!server["pvp"].asString().empty()) { lua_pushstring(L,"pvp"); lua_pushboolean(L, server["pvp"].asBool()); lua_settable(L, top_lvl2); } if (!server["description"].asString().empty()) { lua_pushstring(L,"description"); std::string topush = server["description"].asString(); lua_pushstring(L,topush.c_str()); lua_settable(L, top_lvl2); } if (!server["name"].asString().empty()) { lua_pushstring(L,"name"); std::string topush = server["name"].asString(); lua_pushstring(L,topush.c_str()); lua_settable(L, top_lvl2); } if (!server["address"].asString().empty()) { lua_pushstring(L,"address"); std::string topush = server["address"].asString(); lua_pushstring(L,topush.c_str()); lua_settable(L, top_lvl2); } if (!server["port"].asString().empty()) { lua_pushstring(L,"port"); std::string topush = server["port"].asString(); lua_pushstring(L,topush.c_str()); lua_settable(L, top_lvl2); } if (server.isMember("ping")) { float ping = server["ping"].asFloat(); lua_pushstring(L, "ping"); lua_pushnumber(L, ping); lua_settable(L, top_lvl2); } lua_settable(L, top); index++; } return 1; } /******************************************************************************/ int ModApiMainMenu::l_delete_favorite(lua_State *L) { std::vector<ServerListSpec> servers; std::string listtype = "local"; if (!lua_isnone(L,2)) { listtype = luaL_checkstring(L,2); } if ((listtype != "local") && (listtype != "online")) return 0; if(listtype == "online") { servers = ServerList::getOnline(); } else { servers = ServerList::getLocal(); } int fav_idx = luaL_checkinteger(L,1) -1; if ((fav_idx >= 0) && (fav_idx < (int) servers.size())) { ServerList::deleteEntry(servers[fav_idx]); } return 0; } /******************************************************************************/ int ModApiMainMenu::l_get_games(lua_State *L) { std::vector<SubgameSpec> games = getAvailableGames(); lua_newtable(L); int top = lua_gettop(L); unsigned int index = 1; for (const SubgameSpec &game : games) { lua_pushnumber(L, index); 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, "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, "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, "author"); lua_pushstring(L, game.author.c_str()); lua_settable(L, top_lvl2); lua_pushstring(L, "release"); lua_pushinteger(L, game.release); 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); int table2 = lua_gettop(L); int internal_index = 1; 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); internal_index++; } lua_settable(L, top_lvl2); lua_settable(L, top); index++; } return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_content_info(lua_State *L) { std::string path = luaL_checkstring(L, 1); ContentSpec spec; spec.path = path; parseContentInfo(spec); lua_newtable(L); lua_pushstring(L, spec.name.c_str()); lua_setfield(L, -2, "name"); lua_pushstring(L, spec.type.c_str()); lua_setfield(L, -2, "type"); lua_pushstring(L, spec.author.c_str()); lua_setfield(L, -2, "author"); lua_pushinteger(L, spec.release); lua_setfield(L, -2, "release"); lua_pushstring(L, spec.desc.c_str()); lua_setfield(L, -2, "description"); lua_pushstring(L, spec.path.c_str()); lua_setfield(L, -2, "path"); if (spec.type == "mod") { ModSpec spec; spec.path = path; parseModContents(spec); // Dependencies lua_newtable(L); int i = 1; for (const auto &dep : spec.depends) { lua_pushstring(L, dep.c_str()); lua_rawseti(L, -2, i++); } lua_setfield(L, -2, "depends"); // Optional Dependencies lua_newtable(L); i = 1; for (const auto &dep : spec.optdepends) { lua_pushstring(L, dep.c_str()); lua_rawseti(L, -2, i++); } lua_setfield(L, -2, "optional_depends"); } return 1; } /******************************************************************************/ int ModApiMainMenu::l_show_keys_menu(lua_State *L) { GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); GUIKeyChangeMenu *kmenu = new GUIKeyChangeMenu(RenderingEngine::get_gui_env(), engine->m_parent, -1, engine->m_menumanager); kmenu->drop(); return 0; } /******************************************************************************/ int ModApiMainMenu::l_create_world(lua_State *L) { 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::vector<SubgameSpec> games = getAvailableGames(); if ((gameidx >= 0) && (gameidx < (int) games.size())) { // Create world if it doesn't exist if (!loadGameConfAndInitWorld(path, games[gameidx])) { lua_pushstring(L, "Failed to initialize world"); } else { lua_pushnil(L); } } else { lua_pushstring(L, "Invalid game index"); } return 1; } /******************************************************************************/ int ModApiMainMenu::l_delete_world(lua_State *L) { int world_id = luaL_checkinteger(L, 1) - 1; std::vector<WorldSpec> worlds = getAvailableWorlds(); if (world_id < 0 || world_id >= (int) worlds.size()) { lua_pushstring(L, "Invalid world index"); return 1; } const WorldSpec &spec = worlds[world_id]; if (!fs::RecursiveDelete(spec.path)) { lua_pushstring(L, "Failed to delete world"); return 1; } return 0; } /******************************************************************************/ int ModApiMainMenu::l_set_topleft_text(lua_State *L) { GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); std::string text; if (!lua_isnone(L,1) && !lua_isnil(L,1)) text = luaL_checkstring(L, 1); engine->setTopleftText(text); return 0; } /******************************************************************************/ int ModApiMainMenu::l_get_mapgen_names(lua_State *L) { std::vector<const char *> names; bool include_hidden = lua_isboolean(L, 1) && readParam<bool>(L, 1); Mapgen::getMapgenNames(&names, include_hidden); lua_newtable(L); for (size_t i = 0; i != names.size(); i++) { lua_pushstring(L, names[i]); lua_rawseti(L, -2, i + 1); } return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_modpath(lua_State *L) { std::string modpath = fs::RemoveRelativePathComponents( porting::path_user + DIR_DELIM + "mods" + DIR_DELIM); lua_pushstring(L, modpath.c_str()); return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_clientmodpath(lua_State *L) { std::string modpath = fs::RemoveRelativePathComponents( porting::path_user + DIR_DELIM + "clientmods" + DIR_DELIM); lua_pushstring(L, modpath.c_str()); return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_gamepath(lua_State *L) { std::string gamepath = fs::RemoveRelativePathComponents( porting::path_user + DIR_DELIM + "games" + DIR_DELIM); lua_pushstring(L, gamepath.c_str()); return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_texturepath(lua_State *L) { std::string gamepath = fs::RemoveRelativePathComponents( porting::path_user + DIR_DELIM + "textures"); lua_pushstring(L, gamepath.c_str()); return 1; } int ModApiMainMenu::l_get_texturepath_share(lua_State *L) { std::string gamepath = fs::RemoveRelativePathComponents( porting::path_share + DIR_DELIM + "textures"); lua_pushstring(L, gamepath.c_str()); return 1; } int ModApiMainMenu::l_get_cache_path(lua_State *L) { lua_pushstring(L, fs::RemoveRelativePathComponents(porting::path_cache).c_str()); return 1; } /******************************************************************************/ int ModApiMainMenu::l_create_dir(lua_State *L) { const char *path = luaL_checkstring(L, 1); if (ModApiMainMenu::mayModifyPath(path)) { lua_pushboolean(L, fs::CreateAllDirs(path)); return 1; } lua_pushboolean(L, false); return 1; } /******************************************************************************/ int ModApiMainMenu::l_delete_dir(lua_State *L) { const char *path = luaL_checkstring(L, 1); std::string absolute_path = fs::RemoveRelativePathComponents(path); if (ModApiMainMenu::mayModifyPath(absolute_path)) { lua_pushboolean(L, fs::RecursiveDelete(absolute_path)); return 1; } lua_pushboolean(L, false); return 1; } /******************************************************************************/ int ModApiMainMenu::l_copy_dir(lua_State *L) { const char *source = luaL_checkstring(L, 1); const char *destination = luaL_checkstring(L, 2); bool keep_source = true; if ((!lua_isnone(L,3)) && (!lua_isnil(L,3))) { keep_source = readParam<bool>(L,3); } 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); if (retval && (!keep_source)) { retval &= fs::RecursiveDelete(absolute_source); } lua_pushboolean(L,retval); return 1; } 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); std::string absolute_destination = fs::RemoveRelativePathComponents(destination); if (ModApiMainMenu::mayModifyPath(absolute_destination)) { fs::CreateAllDirs(absolute_destination); io::IFileSystem *fs = RenderingEngine::get_filesystem(); if (!fs->addFileArchive(zipfile, false, false, io::EFAT_ZIP)) { lua_pushboolean(L,false); return 1; } sanity_check(fs->getFileArchiveCount() > 0); /**********************************************************************/ /* WARNING this is not threadsafe!! */ /**********************************************************************/ io::IFileArchive* opened_zip = fs->getFileArchive(fs->getFileArchiveCount()-1); 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++) { 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); return 1; } io::IReadFile* toread = opened_zip->createAndOpenFile(i); FILE *targetfile = fopen(fullpath.c_str(),"wb"); if (targetfile == NULL) { fs->removeFileArchive(fs->getFileArchiveCount()-1); lua_pushboolean(L,false); return 1; } char read_buffer[1024]; long total_read = 0; 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)) { fclose(targetfile); fs->removeFileArchive(fs->getFileArchiveCount()-1); lua_pushboolean(L,false); return 1; } total_read += bytes_read; } fclose(targetfile); } } fs->removeFileArchive(fs->getFileArchiveCount()-1); lua_pushboolean(L,true); return 1; } lua_pushboolean(L,false); return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_mainmenu_path(lua_State *L) { GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); lua_pushstring(L,engine->getScriptDir().c_str()); return 1; } /******************************************************************************/ 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"))) return true; 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"))) return true; if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "worlds"))) return true; if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_cache))) return true; return false; } /******************************************************************************/ int ModApiMainMenu::l_may_modify_path(lua_State *L) { const char *target = luaL_checkstring(L, 1); std::string absolute_destination = fs::RemoveRelativePathComponents(target); lua_pushboolean(L, ModApiMainMenu::mayModifyPath(absolute_destination)); return 1; } /******************************************************************************/ int ModApiMainMenu::l_show_path_select_dialog(lua_State *L) { GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); const char *formname= luaL_checkstring(L, 1); const char *title = luaL_checkstring(L, 2); bool is_file_select = readParam<bool>(L, 3); GUIFileSelectMenu* fileOpenMenu = new GUIFileSelectMenu(RenderingEngine::get_gui_env(), engine->m_parent, -1, engine->m_menumanager, title, formname, is_file_select); fileOpenMenu->setTextDest(engine->m_buttonhandler); fileOpenMenu->drop(); return 0; } /******************************************************************************/ int ModApiMainMenu::l_download_file(lua_State *L) { const char *url = luaL_checkstring(L, 1); const char *target = luaL_checkstring(L, 2); //check path std::string absolute_destination = fs::RemoveRelativePathComponents(target); if (ModApiMainMenu::mayModifyPath(absolute_destination)) { 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; } lua_pushboolean(L,false); return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_video_drivers(lua_State *L) { std::vector<irr::video::E_DRIVER_TYPE> drivers = RenderingEngine::getSupportedVideoDrivers(); 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]); lua_newtable(L); lua_pushstring(L, name); lua_setfield(L, -2, "name"); lua_pushstring(L, fname); lua_setfield(L, -2, "friendly_name"); lua_rawseti(L, -2, i + 1); } return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_video_modes(lua_State *L) { std::vector<core::vector3d<u32> > videomodes = RenderingEngine::getSupportedVideoModes(); lua_newtable(L); for (u32 i = 0; i != videomodes.size(); i++) { lua_newtable(L); lua_pushnumber(L, videomodes[i].X); lua_setfield(L, -2, "w"); lua_pushnumber(L, videomodes[i].Y); lua_setfield(L, -2, "h"); lua_pushnumber(L, videomodes[i].Z); lua_setfield(L, -2, "depth"); lua_rawseti(L, -2, i + 1); } return 1; } /******************************************************************************/ int ModApiMainMenu::l_gettext(lua_State *L) { std::string text = strgettext(std::string(luaL_checkstring(L, 1))); lua_pushstring(L, text.c_str()); return 1; } /******************************************************************************/ 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_settable(L, top); 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_settable(L, top); const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); lua_pushstring(L,"window_width"); lua_pushnumber(L, window_size.X); lua_settable(L, top); lua_pushstring(L,"window_height"); lua_pushnumber(L, window_size.Y); lua_settable(L, top); return 1; } /******************************************************************************/ int ModApiMainMenu::l_get_min_supp_proto(lua_State *L) { lua_pushinteger(L, CLIENT_PROTOCOL_VERSION_MIN); return 1; } int ModApiMainMenu::l_get_max_supp_proto(lua_State *L) { lua_pushinteger(L, CLIENT_PROTOCOL_VERSION_MAX); return 1; } /******************************************************************************/ int ModApiMainMenu::l_do_async_callback(lua_State *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_param_raw = luaL_checklstring(L, 2, &param_length); sanity_check(serialized_func_raw != NULL); sanity_check(serialized_param_raw != NULL); std::string serialized_func = std::string(serialized_func_raw, func_length); std::string serialized_param = std::string(serialized_param_raw, param_length); lua_pushinteger(L, engine->queueAsync(serialized_func, serialized_param)); return 1; } /******************************************************************************/ void ModApiMainMenu::Initialize(lua_State *L, int top) { API_FCT(update_formspec); API_FCT(set_clouds); API_FCT(get_textlist_index); API_FCT(get_table_index); API_FCT(get_worlds); API_FCT(get_games); API_FCT(get_content_info); API_FCT(start); API_FCT(close); API_FCT(get_favorites); API_FCT(show_keys_menu); API_FCT(create_world); API_FCT(delete_world); API_FCT(delete_favorite); API_FCT(set_background); API_FCT(set_topleft_text); API_FCT(get_mapgen_names); API_FCT(get_modpath); API_FCT(get_clientmodpath); API_FCT(get_gamepath); API_FCT(get_texturepath); API_FCT(get_texturepath_share); API_FCT(get_cache_path); API_FCT(create_dir); API_FCT(delete_dir); API_FCT(copy_dir); API_FCT(extract_zip); API_FCT(may_modify_path); API_FCT(get_mainmenu_path); API_FCT(show_path_select_dialog); API_FCT(download_file); API_FCT(gettext); API_FCT(get_video_drivers); API_FCT(get_video_modes); API_FCT(get_screen_info); API_FCT(get_min_supp_proto); API_FCT(get_max_supp_proto); API_FCT(do_async_callback); } /******************************************************************************/ void ModApiMainMenu::InitializeAsync(lua_State *L, int top) { API_FCT(get_worlds); API_FCT(get_games); API_FCT(get_favorites); API_FCT(get_mapgen_names); API_FCT(get_modpath); API_FCT(get_clientmodpath); API_FCT(get_gamepath); API_FCT(get_texturepath); API_FCT(get_texturepath_share); API_FCT(get_cache_path); API_FCT(create_dir); API_FCT(delete_dir); API_FCT(copy_dir); //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) }
pgimeno/minetest
src/script/lua_api/l_mainmenu.cpp
C++
mit
29,339
/* Minetest Copyright (C) 2013 sapier This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" class AsyncEngine; /** Implementation of lua api support for mainmenu */ class ModApiMainMenu: public ModApiBase { private: /** * read a text variable from gamedata table within lua stack * @param L stack to read variable from * @param name name of variable to read * @return string value of requested variable */ static std::string getTextData(lua_State *L, std::string name); /** * read a integer variable from gamedata table within lua stack * @param L stack to read variable from * @param name name of variable to read * @return integer value of requested variable */ static int getIntegerData(lua_State *L, std::string name,bool& valid); /** * read a bool variable from gamedata table within lua stack * @param L stack to read variable from * @param name name of variable to read * @return bool value of requested variable */ 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 * games, mods, textures, or worlds directories may be modified. * @param path path to check * @return true if the path may be modified */ static bool mayModifyPath(const std::string &path); //api calls static int l_start(lua_State *L); static int l_close(lua_State *L); static int l_create_world(lua_State *L); static int l_delete_world(lua_State *L); static int l_get_worlds(lua_State *L); static int l_get_mapgen_names(lua_State *L); static int l_get_favorites(lua_State *L); static int l_delete_favorite(lua_State *L); static int l_gettext(lua_State *L); //packages static int l_get_games(lua_State *L); static int l_get_content_info(lua_State *L); //gui static int l_show_keys_menu(lua_State *L); static int l_show_path_select_dialog(lua_State *L); static int l_set_topleft_text(lua_State *L); static int l_set_clouds(lua_State *L); static int l_get_textlist_index(lua_State *L); static int l_get_table_index(lua_State *L); static int l_set_background(lua_State *L); static int l_update_formspec(lua_State *L); static int l_get_screen_info(lua_State *L); //filesystem static int l_get_mainmenu_path(lua_State *L); static int l_get_modpath(lua_State *L); static int l_get_clientmodpath(lua_State *L); static int l_get_gamepath(lua_State *L); static int l_get_texturepath(lua_State *L); static int l_get_texturepath_share(lua_State *L); static int l_get_cache_path(lua_State *L); static int l_create_dir(lua_State *L); static int l_delete_dir(lua_State *L); static int l_copy_dir(lua_State *L); static int l_extract_zip(lua_State *L); static int l_may_modify_path(lua_State *L); static int l_download_file(lua_State *L); static int l_get_video_drivers(lua_State *L); static int l_get_video_modes(lua_State *L); //version compatibility static int l_get_min_supp_proto(lua_State *L); static int l_get_max_supp_proto(lua_State *L); // async static int l_do_async_callback(lua_State *L); public: /** * initialize this API module * @param L lua stack to initialize * @param top index (in lua stack) of global API table */ static void Initialize(lua_State *L, int top); static void InitializeAsync(lua_State *L, int top); };
pgimeno/minetest
src/script/lua_api/l_mainmenu.h
C++
mit
4,044
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_mapgen.h" #include "lua_api/l_internal.h" #include "lua_api/l_vmanip.h" #include "common/c_converter.h" #include "common/c_content.h" #include "cpp_api/s_security.h" #include "util/serialize.h" #include "server.h" #include "environment.h" #include "emerge.h" #include "mapgen/mg_biome.h" #include "mapgen/mg_ore.h" #include "mapgen/mg_decoration.h" #include "mapgen/mg_schematic.h" #include "mapgen/mapgen_v5.h" #include "mapgen/mapgen_v7.h" #include "filesys.h" #include "settings.h" #include "log.h" 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_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_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}, }; ObjDef *get_objdef(lua_State *L, int index, ObjDefManager *objmgr); 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<u8> *biome_id_list); Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *schemmgr, StringMap *replace_names); Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, StringMap *replace_names); Schematic *load_schematic_from_def(lua_State *L, int index, const NodeDefManager *ndef, StringMap *replace_names); bool read_schematic_def(lua_State *L, int index, Schematic *schem, std::vector<std::string> *names); 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, ObjDefManager *objmgr) { if (index < 0) index = lua_gettop(L) + 1 + index; // If a number, assume this is a handle to an object def if (lua_isnumber(L, index)) return objmgr->get(lua_tointeger(L, index)); // If a string, assume a name is given instead if (lua_isstring(L, index)) return objmgr->getByName(lua_tostring(L, index)); return NULL; } /////////////////////////////////////////////////////////////////////////////// Schematic *get_or_load_schematic(lua_State *L, int index, SchematicManager *schemmgr, StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; Schematic *schem = (Schematic *)get_objdef(L, index, schemmgr); if (schem) return schem; schem = load_schematic(L, index, schemmgr->getNodeDef(), replace_names); if (!schem) return NULL; if (schemmgr->add(schem) == OBJDEF_INVALID_HANDLE) { delete schem; return NULL; } return schem; } Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef, StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; Schematic *schem = NULL; if (lua_istable(L, index)) { schem = load_schematic_from_def(L, index, ndef, replace_names); if (!schem) { delete schem; return NULL; } } else if (lua_isnumber(L, index)) { return NULL; } else if (lua_isstring(L, index)) { schem = SchematicManager::create(SCHEMATIC_NORMAL); std::string filepath = lua_tostring(L, index); if (!fs::IsPathAbsolute(filepath)) filepath = ModApiBase::getCurrentModPath(L) + DIR_DELIM + filepath; if (!schem->loadSchematicFromFile(filepath, ndef, replace_names)) { delete schem; return NULL; } } return schem; } Schematic *load_schematic_from_def(lua_State *L, int index, const NodeDefManager *ndef, StringMap *replace_names) { Schematic *schem = SchematicManager::create(SCHEMATIC_NORMAL); if (!read_schematic_def(L, index, schem, &schem->m_nodenames)) { delete schem; return NULL; } size_t num_nodes = schem->m_nodenames.size(); schem->m_nnlistsizes.push_back(num_nodes); if (replace_names) { for (size_t i = 0; i != num_nodes; i++) { StringMap::iterator it = replace_names->find(schem->m_nodenames[i]); if (it != replace_names->end()) schem->m_nodenames[i] = it->second; } } if (ndef) ndef->pendNodeResolve(schem); return schem; } bool read_schematic_def(lua_State *L, int index, Schematic *schem, std::vector<std::string> *names) { if (!lua_istable(L, index)) return false; //// Get schematic size lua_getfield(L, index, "size"); v3s16 size = check_v3s16(L, -1); lua_pop(L, 1); schem->size = size; //// Get schematic data lua_getfield(L, index, "data"); luaL_checktype(L, -1, LUA_TTABLE); u32 numnodes = size.X * size.Y * size.Z; schem->schemdata = new MapNode[numnodes]; size_t names_base = names->size(); std::unordered_map<std::string, content_t> name_id_map; u32 i = 0; for (lua_pushnil(L); lua_next(L, -2); i++, lua_pop(L, 1)) { if (i >= numnodes) continue; //// Read name std::string name; if (!getstringfield(L, -1, "name", name)) 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)) param1 = MTSCHEM_PROB_ALWAYS_OLD; //// Read param2 u8 param2 = getintfield_default(L, -1, "param2", 0); //// Find or add new nodename-to-ID mapping std::unordered_map<std::string, content_t>::iterator it = name_id_map.find(name); content_t name_index; if (it != name_id_map.end()) { name_index = it->second; } else { name_index = names->size() - names_base; name_id_map[name] = name_index; names->push_back(name); } //// Perform probability/force_place fixup on param1 param1 >>= 1; if (getboolfield_default(L, -1, "force_place", false)) param1 |= MTSCHEM_FORCE_PLACE; //// Actually set the node in the schematic schem->schemdata[i] = MapNode(name_index, param1, param2); } if (i != numnodes) { errorstream << "read_schematic_def: incorrect number of " "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++) schem->slice_probs[i] = MTSCHEM_PROB_ALWAYS; lua_getfield(L, index, "yslice_prob"); if (lua_istable(L, -1)) { 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])) continue; schem->slice_probs[ypos] >>= 1; } } return true; } void read_schematic_replacements(lua_State *L, int index, StringMap *replace_names) { if (index < 0) index = lua_gettop(L) + 1 + index; lua_pushnil(L); while (lua_next(L, index)) { std::string replace_from; std::string replace_to; 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"); 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"); 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"); replace_from = lua_tostring(L, -2); if (!lua_isstring(L, -1)) throw LuaError("schematics: replace_to field is not a string"); replace_to = lua_tostring(L, -1); } replace_names->insert(std::make_pair(replace_from, replace_to)); lua_pop(L, 1); } } /////////////////////////////////////////////////////////////////////////////// Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr) { if (index < 0) index = lua_gettop(L) + 1 + index; Biome *biome = (Biome *)get_objdef(L, index, biomemgr); if (biome) return biome; biome = read_biome_def(L, index, biomemgr->getNodeDef()); if (!biome) return NULL; if (biomemgr->add(biome) == OBJDEF_INVALID_HANDLE) { delete biome; return NULL; } 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); 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->min_pos = getv3s16field_default( 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)); getintfield(L, index, "y_max", b->max_pos.Y); std::vector<std::string> &nn = b->m_nodenames; nn.push_back(getstringfield_default(L, index, "node_top", "")); nn.push_back(getstringfield_default(L, index, "node_filler", "")); nn.push_back(getstringfield_default(L, index, "node_stone", "")); nn.push_back(getstringfield_default(L, index, "node_water_top", "")); nn.push_back(getstringfield_default(L, index, "node_water", "")); nn.push_back(getstringfield_default(L, index, "node_river_water", "")); nn.push_back(getstringfield_default(L, index, "node_riverbed", "")); nn.push_back(getstringfield_default(L, index, "node_dust", "")); nn.push_back(getstringfield_default(L, index, "node_cave_liquid", "")); 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<u8> *biome_id_list) { if (index < 0) index = lua_gettop(L) + 1 + index; if (lua_isnil(L, index)) return 0; bool is_single = true; if (lua_istable(L, index)) { lua_getfield(L, index, "name"); is_single = !lua_isnil(L, -1); lua_pop(L, 1); } if (is_single) { 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; return 1; } biome_id_list->insert(biome->index); return 0; } // returns number of failed resolutions size_t fail_count = 0; size_t count = 0; for (lua_pushnil(L); lua_next(L, index); lua_pop(L, 1)) { count++; Biome *biome = get_or_load_biome(L, -1, biomemgr); if (!biome) { fail_count++; infostream << "get_biome_list: failed to get biome '" << (lua_isstring(L, -1) ? lua_tostring(L, -1) : "") << "'" << std::endl; continue; } biome_id_list->insert(biome->index); } return fail_count; } /////////////////////////////////////////////////////////////////////////////// // get_biome_id(biomename) // returns the biome id as used in biomemap and returned by 'get_biome_data()' int ModApiMapgen::l_get_biome_id(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *biome_str = lua_tostring(L, 1); if (!biome_str) return 0; BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; if (!bmgr) return 0; Biome *biome = (Biome *)bmgr->getByName(biome_str); if (!biome || biome->index == OBJDEF_INVALID_INDEX) return 0; lua_pushinteger(L, biome->index); return 1; } // get_biome_name(biome_id) // returns the biome name string int ModApiMapgen::l_get_biome_name(lua_State *L) { NO_MAP_LOCK_REQUIRED; int biome_id = luaL_checkinteger(L, 1); BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; if (!bmgr) return 0; Biome *b = (Biome *)bmgr->getRaw(biome_id); lua_pushstring(L, b->name.c_str()); return 1; } // get_heat(pos) // returns the heat at the position int ModApiMapgen::l_get_heat(lua_State *L) { NO_MAP_LOCK_REQUIRED; v3s16 pos = read_v3s16(L, 1); NoiseParams np_heat; NoiseParams np_heat_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)) return 0; std::string value; if (!settingsmgr->getMapSetting("seed", &value)) return 0; std::istringstream ss(value); u64 seed; ss >> seed; BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; if (!bmgr) return 0; float heat = bmgr->getHeatAtPosOriginal(pos, np_heat, np_heat_blend, seed); if (!heat) return 0; lua_pushnumber(L, heat); return 1; } // get_humidity(pos) // returns the humidity at the position int ModApiMapgen::l_get_humidity(lua_State *L) { NO_MAP_LOCK_REQUIRED; v3s16 pos = read_v3s16(L, 1); NoiseParams np_humidity; NoiseParams np_humidity_blend; MapSettingsManager *settingsmgr = 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)) return 0; std::string value; if (!settingsmgr->getMapSetting("seed", &value)) return 0; std::istringstream ss(value); u64 seed; ss >> seed; BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; if (!bmgr) return 0; float humidity = bmgr->getHumidityAtPosOriginal(pos, np_humidity, np_humidity_blend, seed); if (!humidity) return 0; 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) { NO_MAP_LOCK_REQUIRED; v3s16 pos = read_v3s16(L, 1); NoiseParams np_heat; NoiseParams np_heat_blend; NoiseParams np_humidity; 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)) return 0; std::string value; if (!settingsmgr->getMapSetting("seed", &value)) return 0; std::istringstream ss(value); u64 seed; ss >> seed; BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; if (!bmgr) return 0; float heat = bmgr->getHeatAtPosOriginal(pos, np_heat, np_heat_blend, seed); if (!heat) return 0; float humidity = bmgr->getHumidityAtPosOriginal(pos, np_humidity, np_humidity_blend, seed); if (!humidity) return 0; Biome *biome = (Biome *)bmgr->getBiomeFromNoiseOriginal(heat, humidity, pos); if (!biome || biome->index == OBJDEF_INVALID_INDEX) return 0; lua_newtable(L); lua_pushinteger(L, biome->index); lua_setfield(L, -2, "biome"); lua_pushnumber(L, heat); lua_setfield(L, -2, "heat"); lua_pushnumber(L, humidity); lua_setfield(L, -2, "humidity"); return 1; } // get_mapgen_object(objectname) // returns the requested object used during map generation int ModApiMapgen::l_get_mapgen_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *mgobjstr = lua_tostring(L, 1); int mgobjint; if (!string_to_enum(es_MapgenObject, mgobjint, mgobjstr ? mgobjstr : "")) return 0; enum MapgenObject mgobj = (MapgenObject)mgobjint; EmergeManager *emerge = getServer(L)->getEmergeManager(); Mapgen *mg = emerge->getCurrentMapgen(); if (!mg) throw LuaError("Must only be called in a mapgen thread!"); size_t maplen = mg->csize.X * mg->csize.Z; switch (mgobj) { case MGOBJ_VMANIP: { MMVManip *vm = mg->vm; // VoxelManip object LuaVoxelManip *o = new LuaVoxelManip(vm, true); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, "VoxelManip"); lua_setmetatable(L, -2); // emerged min pos push_v3s16(L, vm->m_area.MinEdge); // emerged max pos push_v3s16(L, vm->m_area.MaxEdge); return 3; } case MGOBJ_HEIGHTMAP: { if (!mg->heightmap) return 0; lua_newtable(L); for (size_t i = 0; i != maplen; i++) { lua_pushinteger(L, mg->heightmap[i]); lua_rawseti(L, -2, i + 1); } return 1; } case MGOBJ_BIOMEMAP: { if (!mg->biomegen) return 0; lua_newtable(L); for (size_t i = 0; i != maplen; i++) { lua_pushinteger(L, mg->biomegen->biomemap[i]); lua_rawseti(L, -2, i + 1); } return 1; } case MGOBJ_HEATMAP: { if (!mg->biomegen || mg->biomegen->getType() != BIOMEGEN_ORIGINAL) return 0; BiomeGenOriginal *bg = (BiomeGenOriginal *)mg->biomegen; lua_newtable(L); for (size_t i = 0; i != maplen; i++) { lua_pushnumber(L, bg->heatmap[i]); lua_rawseti(L, -2, i + 1); } return 1; } case MGOBJ_HUMIDMAP: { if (!mg->biomegen || mg->biomegen->getType() != BIOMEGEN_ORIGINAL) return 0; BiomeGenOriginal *bg = (BiomeGenOriginal *)mg->biomegen; lua_newtable(L); for (size_t i = 0; i != maplen; i++) { lua_pushnumber(L, bg->humidmap[i]); lua_rawseti(L, -2, i + 1); } return 1; } case MGOBJ_GENNOTIFY: { std::map<std::string, std::vector<v3s16> >event_map; std::map<std::string, std::vector<v3s16> >::iterator it; mg->gennotify.getEvents(event_map); lua_newtable(L); for (it = event_map.begin(); it != event_map.end(); ++it) { lua_newtable(L); for (size_t j = 0; j != it->second.size(); j++) { push_v3s16(L, it->second[j]); lua_rawseti(L, -2, j + 1); } lua_setfield(L, -2, it->first.c_str()); } return 1; } } return 0; } // get_spawn_level(x = num, z = num) int ModApiMapgen::l_get_spawn_level(lua_State *L) { NO_MAP_LOCK_REQUIRED; s16 x = luaL_checkinteger(L, 1); s16 z = luaL_checkinteger(L, 2); EmergeManager *emerge = getServer(L)->getEmergeManager(); int spawn_level = emerge->getSpawnLevelAtPoint(v2s16(x, z)); // Unsuitable spawn point if (spawn_level == MAX_MAP_GENERATION_LIMIT) return 0; // 'findSpawnPos()' in server.cpp adds at least 1 lua_pushinteger(L, spawn_level + 1); 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"); std::string value; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; lua_newtable(L); settingsmgr->getMapSetting("mg_name", &value); lua_pushstring(L, value.c_str()); lua_setfield(L, -2, "mgname"); settingsmgr->getMapSetting("seed", &value); std::istringstream ss(value); u64 seed; ss >> seed; lua_pushinteger(L, seed); lua_setfield(L, -2, "seed"); settingsmgr->getMapSetting("water_level", &value); lua_pushinteger(L, stoi(value, -32768, 32767)); lua_setfield(L, -2, "water_level"); settingsmgr->getMapSetting("chunksize", &value); lua_pushinteger(L, stoi(value, -32768, 32767)); lua_setfield(L, -2, "chunksize"); settingsmgr->getMapSetting("mg_flags", &value); lua_pushstring(L, value.c_str()); lua_setfield(L, -2, "flags"); return 1; } // set_mapgen_params(params) // set mapgen parameters 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"); if (!lua_istable(L, 1)) return 0; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; lua_getfield(L, 1, "mgname"); if (lua_isstring(L, -1)) settingsmgr->setMapSetting("mg_name", readParam<std::string>(L, -1), true); lua_getfield(L, 1, "seed"); if (lua_isnumber(L, -1)) settingsmgr->setMapSetting("seed", readParam<std::string>(L, -1), true); lua_getfield(L, 1, "water_level"); if (lua_isnumber(L, -1)) settingsmgr->setMapSetting("water_level", readParam<std::string>(L, -1), true); lua_getfield(L, 1, "chunksize"); if (lua_isnumber(L, -1)) settingsmgr->setMapSetting("chunksize", readParam<std::string>(L, -1), true); warn_if_field_exists(L, 1, "flagmask", "Deprecated: flags field now includes unset flags."); lua_getfield(L, 1, "flags"); if (lua_isstring(L, -1)) settingsmgr->setMapSetting("mg_flags", readParam<std::string>(L, -1), true); return 0; } // get_mapgen_setting(name) int ModApiMapgen::l_get_mapgen_setting(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string value; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); if (!settingsmgr->getMapSetting(name, &value)) return 0; lua_pushstring(L, value.c_str()); return 1; } // get_mapgen_setting_noiseparams(name) int ModApiMapgen::l_get_mapgen_setting_noiseparams(lua_State *L) { NO_MAP_LOCK_REQUIRED; NoiseParams np; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); if (!settingsmgr->getMapSettingNoiseParams(name, &np)) return 0; push_noiseparams(L, &np); return 1; } // set_mapgen_setting(name, value, override_meta) // set mapgen config values int ModApiMapgen::l_set_mapgen_setting(lua_State *L) { NO_MAP_LOCK_REQUIRED; MapSettingsManager *settingsmgr = getServer(L)->getEmergeManager()->map_settings_mgr; const char *name = luaL_checkstring(L, 1); const char *value = luaL_checkstring(L, 2); bool override_meta = readParam<bool>(L, 3, false); if (!settingsmgr->setMapSetting(name, value, override_meta)) { errorstream << "set_mapgen_setting: cannot set '" << name << "' after initialization" << std::endl; } 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) { NO_MAP_LOCK_REQUIRED; MapSettingsManager *settingsmgr = 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; return 0; } bool override_meta = readParam<bool>(L, 3, false); if (!settingsmgr->setMapSettingNoiseParams(name, &np, override_meta)) { errorstream << "set_mapgen_setting_noiseparams: cannot set '" << name << "' after initialization" << std::endl; } return 0; } // set_noiseparams(name, noiseparams, set_default) // set global config values for noise parameters int ModApiMapgen::l_set_noiseparams(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *name = luaL_checkstring(L, 1); NoiseParams np; if (!read_noiseparams(L, 2, &np)) { errorstream << "set_noiseparams: cannot set '" << name << "'; invalid noiseparams table" << std::endl; return 0; } bool set_default = !lua_isboolean(L, 3) || readParam<bool>(L, 3); g_settings->setNoiseParams(name, np, set_default); return 0; } // get_noiseparams(name) int ModApiMapgen::l_get_noiseparams(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string name = luaL_checkstring(L, 1); NoiseParams np; if (!g_settings->getNoiseParams(name, np)) return 0; push_noiseparams(L, &np); return 1; } // set_gen_notify(flags, {deco_id_table}) int ModApiMapgen::l_set_gen_notify(lua_State *L) { NO_MAP_LOCK_REQUIRED; u32 flags = 0, flagmask = 0; EmergeManager *emerge = getServer(L)->getEmergeManager(); if (read_flags(L, 1, flagdesc_gennotify, &flags, &flagmask)) { emerge->gen_notify_on &= ~flagmask; emerge->gen_notify_on |= flags; } if (lua_istable(L, 2)) { 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)); lua_pop(L, 1); } } return 0; } // get_gen_notify() int ModApiMapgen::l_get_gen_notify(lua_State *L) { NO_MAP_LOCK_REQUIRED; EmergeManager *emerge = getServer(L)->getEmergeManager(); push_flags_string(L, flagdesc_gennotify, emerge->gen_notify_on, emerge->gen_notify_on); lua_newtable(L); int i = 1; for (u32 gen_notify_on_deco_id : emerge->gen_notify_on_deco_ids) { lua_pushnumber(L, gen_notify_on_deco_id); lua_rawseti(L, -2, i++); } return 2; } // get_decoration_id(decoration_name) // returns the decoration ID as used in gennotify int ModApiMapgen::l_get_decoration_id(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *deco_str = luaL_checkstring(L, 1); if (!deco_str) return 0; DecorationManager *dmgr = getServer(L)->getEmergeManager()->decomgr; if (!dmgr) return 0; Decoration *deco = (Decoration *)dmgr->getByName(deco_str); if (!deco) return 0; lua_pushinteger(L, deco->index); return 1; } // register_biome({lots of stuff}) int ModApiMapgen::l_register_biome(lua_State *L) { NO_MAP_LOCK_REQUIRED; int index = 1; luaL_checktype(L, index, LUA_TTABLE); const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; Biome *biome = read_biome_def(L, index, ndef); if (!biome) return 0; ObjDefHandle handle = bmgr->add(biome); if (handle == OBJDEF_INVALID_HANDLE) { delete biome; return 0; } lua_pushinteger(L, handle); return 1; } // register_decoration({lots of stuff}) int ModApiMapgen::l_register_decoration(lua_State *L) { NO_MAP_LOCK_REQUIRED; int index = 1; luaL_checktype(L, index, LUA_TTABLE); const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); DecorationManager *decomgr = getServer(L)->getEmergeManager()->decomgr; BiomeManager *biomemgr = getServer(L)->getEmergeManager()->biomemgr; SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; 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; 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->place_offset_y = getintfield_default(L, index, "place_offset_y", 0); deco->sidelen = getintfield_default(L, index, "sidelen", 8); if (deco->sidelen <= 0) { errorstream << "register_decoration: sidelen must be " "greater than 0" << std::endl; delete deco; return 0; } //// Get node name(s) to place decoration on size_t nread = getstringlistfield(L, index, "place_on", &deco->m_nodenames); deco->m_nnlistsizes.push_back(nread); //// Get decoration flags getflagsfield(L, index, "flags", flagdesc_deco, &deco->flags, NULL); //// Get NoiseParams to define how decoration is placed lua_getfield(L, index, "noise_params"); if (read_noiseparams(L, -1, &deco->np)) deco->flags |= DECO_USE_NOISE; lua_pop(L, 1); //// 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; lua_pop(L, 1); //// Get node name(s) to 'spawn by' size_t nnames = getstringlistfield(L, index, "spawn_by", &deco->m_nodenames); 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; } //// Handle decoration type-specific parameters bool success = false; switch (decotype) { case DECO_SIMPLE: success = read_deco_simple(L, (DecoSimple *)deco); break; case DECO_SCHEMATIC: success = read_deco_schematic(L, schemmgr, (DecoSchematic *)deco); break; case DECO_LSYSTEM: break; } if (!success) { delete deco; return 0; } ndef->pendNodeResolve(deco); ObjDefHandle handle = decomgr->add(deco); if (handle == OBJDEF_INVALID_HANDLE) { delete deco; return 0; } lua_pushinteger(L, handle); 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_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; return false; } size_t nnames = getstringlistfield(L, index, "decoration", &deco->m_nodenames); deco->m_nnlistsizes.push_back(nnames); if (nnames == 0) { errorstream << "register_decoration: no decoration nodes " "defined" << std::endl; return false; } param2 = getintfield_default(L, index, "param2", 0); 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; return false; } deco->deco_param2 = (u8)param2; deco->deco_param2_max = (u8)param2_max; 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); StringMap replace_names; lua_getfield(L, index, "replacements"); if (lua_istable(L, -1)) read_schematic_replacements(L, -1, &replace_names); lua_pop(L, 1); lua_getfield(L, index, "schematic"); Schematic *schem = get_or_load_schematic(L, -1, schemmgr, &replace_names); lua_pop(L, 1); deco->schematic = schem; return schem != NULL; } // register_ore({lots of stuff}) int ModApiMapgen::l_register_ore(lua_State *L) { NO_MAP_LOCK_REQUIRED; int index = 1; luaL_checktype(L, index, LUA_TTABLE); const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; OreManager *oremgr = getServer(L)->getEmergeManager()->oremgr; 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"; return 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; //// Get noise_threshold warn_if_field_exists(L, index, "noise_threshhold", "Deprecated: new name is \"noise_threshold\"."); float nthresh; if (!getfloatfield(L, index, "noise_threshold", nthresh) && !getfloatfield(L, index, "noise_threshhold", nthresh)) nthresh = 0; 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\"."); int ymin, ymax; if (!getintfield(L, index, "y_min", ymin) && !getintfield(L, index, "height_min", ymin)) ymin = -31000; if (!getintfield(L, index, "y_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; delete ore; return 0; } //// Get flags getflagsfield(L, index, "flags", flagdesc_ore, &ore->flags, NULL); //// Get biomes associated with this decoration (if any) lua_getfield(L, index, "biomes"); if (get_biome_list(L, -1, bmgr, &ore->biomes)) infostream << "register_ore: couldn't get all biomes " << std::endl; lua_pop(L, 1); //// Get noise parameters if needed lua_getfield(L, index, "noise_params"); if (read_noiseparams(L, -1, &ore->np)) { ore->flags |= OREFLAG_USE_NOISE; } else if (ore->NEEDS_NOISE) { errorstream << "register_ore: specified ore type requires valid " "'noise_params' parameter" << std::endl; delete ore; return 0; } lua_pop(L, 1); //// Get type-specific parameters switch (oretype) { 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); 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_bottom"); read_noiseparams(L, -1, &orepuff->np_puff_bottom); lua_pop(L, 1); break; } case ORE_VEIN: { OreVein *orevein = (OreVein *)ore; orevein->random_factor = getfloatfield_default(L, index, "random_factor", 1.f); 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); orestratum->stratum_thickness = getintfield_default(L, index, "stratum_thickness", 8); break; } default: break; } ObjDefHandle handle = oremgr->add(ore); if (handle == OBJDEF_INVALID_HANDLE) { delete ore; return 0; } ore->m_nodenames.push_back(getstringfield_default(L, index, "ore", "")); size_t nnames = getstringlistfield(L, index, "wherein", &ore->m_nodenames); ore->m_nnlistsizes.push_back(nnames); ndef->pendNodeResolve(ore); lua_pushinteger(L, handle); return 1; } // register_schematic({schematic}, replacements={}) int ModApiMapgen::l_register_schematic(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; 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); if (!schem) return 0; ObjDefHandle handle = schemmgr->add(schem); if (handle == OBJDEF_INVALID_HANDLE) { delete schem; return 0; } lua_pushinteger(L, handle); return 1; } // clear_registered_biomes() int ModApiMapgen::l_clear_registered_biomes(lua_State *L) { NO_MAP_LOCK_REQUIRED; BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr; 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()->decomgr; 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()->oremgr; 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()->schemmgr; smgr->clear(); return 0; } // generate_ores(vm, p1, p2, [ore_id]) int ModApiMapgen::l_generate_ores(lua_State *L) { NO_MAP_LOCK_REQUIRED; EmergeManager *emerge = getServer(L)->getEmergeManager(); Mapgen mg; mg.seed = emerge->mgparams->seed; 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; sortBoxVerticies(pmin, pmax); u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed); emerge->oremgr->placeAllOres(&mg, blockseed, pmin, pmax); return 0; } // generate_decorations(vm, p1, p2, [deco_id]) int ModApiMapgen::l_generate_decorations(lua_State *L) { NO_MAP_LOCK_REQUIRED; EmergeManager *emerge = getServer(L)->getEmergeManager(); Mapgen mg; mg.seed = emerge->mgparams->seed; 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; sortBoxVerticies(pmin, pmax); u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed); emerge->decomgr->placeAllDecos(&mg, blockseed, pmin, pmax); return 0; } // create_schematic(p1, p2, probability_list, filename, y_slice_prob_list) int ModApiMapgen::l_create_schematic(lua_State *L) { MAP_LOCK_REQUIRED; const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); const char *filename = luaL_checkstring(L, 4); CHECK_SECURE_PATH(L, filename, true); Map *map = &(getEnv(L)->getMap()); Schematic schem; v3s16 p1 = check_v3s16(L, 1); v3s16 p2 = check_v3s16(L, 2); sortBoxVerticies(p1, p2); std::vector<std::pair<v3s16, u8> > prob_list; if (lua_istable(L, 3)) { lua_pushnil(L); while (lua_next(L, 3)) { if (lua_istable(L, -1)) { lua_getfield(L, -1, "pos"); v3s16 pos = check_v3s16(L, -1); lua_pop(L, 1); u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); prob_list.emplace_back(pos, prob); } lua_pop(L, 1); } } std::vector<std::pair<s16, u8> > slice_prob_list; if (lua_istable(L, 5)) { lua_pushnil(L); while (lua_next(L, 5)) { if (lua_istable(L, -1)) { s16 ypos = getintfield_default(L, -1, "ypos", 0); u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS); slice_prob_list.emplace_back(ypos, prob); } lua_pop(L, 1); } } if (!schem.getSchematicFromMap(map, p1, p2)) { errorstream << "create_schematic: failed to get schematic " "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; lua_pushboolean(L, true); return 1; } // place_schematic(p, schematic, rotation, // replacements, force_placement, flagstring) int ModApiMapgen::l_place_schematic(lua_State *L) { MAP_LOCK_REQUIRED; GET_ENV_PTR; ServerMap *map = &(env->getServerMap()); SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; //// Read position v3s16 p = check_v3s16(L, 1); //// Read rotation int rot = ROTATE_0; std::string enumstr = readParam<std::string>(L, 3, ""); if (!enumstr.empty()) string_to_enum(es_Rotation, rot, enumstr); //// Read force placement bool force_placement = true; if (lua_isboolean(L, 5)) force_placement = readParam<bool>(L, 5); //// Read node replacements StringMap replace_names; if (lua_istable(L, 4)) read_schematic_replacements(L, 4, &replace_names); //// Read schematic Schematic *schem = get_or_load_schematic(L, 2, schemmgr, &replace_names); if (!schem) { errorstream << "place_schematic: failed to get schematic" << std::endl; return 0; } //// Read flags u32 flags = 0; read_flags(L, 6, flagdesc_deco, &flags, NULL); schem->placeOnMap(map, p, flags, (Rotation)rot, force_placement); lua_pushboolean(L, true); return 1; } // place_schematic_on_vmanip(vm, p, schematic, rotation, // replacements, force_placement, flagstring) int ModApiMapgen::l_place_schematic_on_vmanip(lua_State *L) { NO_MAP_LOCK_REQUIRED; SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; //// Read VoxelManip object MMVManip *vm = LuaVoxelManip::checkobject(L, 1)->vm; //// Read position v3s16 p = check_v3s16(L, 2); //// Read rotation int rot = ROTATE_0; std::string enumstr = readParam<std::string>(L, 4, ""); if (!enumstr.empty()) string_to_enum(es_Rotation, rot, std::string(enumstr)); //// Read force placement bool force_placement = true; if (lua_isboolean(L, 6)) force_placement = readParam<bool>(L, 6); //// Read node replacements StringMap replace_names; if (lua_istable(L, 5)) read_schematic_replacements(L, 5, &replace_names); //// Read schematic Schematic *schem = get_or_load_schematic(L, 3, schemmgr, &replace_names); if (!schem) { errorstream << "place_schematic: failed to get schematic" << std::endl; return 0; } //// Read flags u32 flags = 0; read_flags(L, 7, flagdesc_deco, &flags, NULL); bool schematic_did_fit = schem->placeOnVManip( 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; SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr; //// Read options bool use_comments = getboolfield_default(L, 3, "lua_use_comments", false); u32 indent_spaces = getintfield_default(L, 3, "lua_num_indent_spaces", 0); //// Get schematic bool was_loaded = false; Schematic *schem = (Schematic *)get_objdef(L, 1, schemmgr); if (!schem) { schem = load_schematic(L, 1, NULL, NULL); was_loaded = true; } if (!schem) { errorstream << "serialize_schematic: failed to get schematic" << std::endl; return 0; } //// Read format of definition to save as int schem_format = SCHEM_FMT_MTS; std::string enumstr = readParam<std::string>(L, 2, ""); if (!enumstr.empty()) string_to_enum(es_SchematicFormatType, schem_format, enumstr); //// Serialize to binary string std::ostringstream os(std::ios_base::binary); switch (schem_format) { case SCHEM_FMT_MTS: schem->serializeToMts(&os, schem->m_nodenames); break; case SCHEM_FMT_LUA: schem->serializeToLua(&os, schem->m_nodenames, use_comments, indent_spaces); break; default: return 0; } if (was_loaded) delete schem; std::string ser = os.str(); lua_pushlstring(L, ser.c_str(), ser.length()); return 1; } void ModApiMapgen::Initialize(lua_State *L, int top) { API_FCT(get_biome_id); API_FCT(get_biome_name); API_FCT(get_heat); API_FCT(get_humidity); API_FCT(get_biome_data); API_FCT(get_mapgen_object); API_FCT(get_spawn_level); API_FCT(get_mapgen_params); API_FCT(set_mapgen_params); API_FCT(get_mapgen_setting); API_FCT(set_mapgen_setting); API_FCT(get_mapgen_setting_noiseparams); API_FCT(set_mapgen_setting_noiseparams); API_FCT(set_noiseparams); API_FCT(get_noiseparams); API_FCT(set_gen_notify); API_FCT(get_gen_notify); API_FCT(get_decoration_id); API_FCT(register_biome); API_FCT(register_decoration); API_FCT(register_ore); API_FCT(register_schematic); API_FCT(clear_registered_biomes); API_FCT(clear_registered_decorations); API_FCT(clear_registered_ores); API_FCT(clear_registered_schematics); API_FCT(generate_ores); API_FCT(generate_decorations); API_FCT(create_schematic); API_FCT(place_schematic); API_FCT(place_schematic_on_vmanip); API_FCT(serialize_schematic); }
pgimeno/minetest
src/script/lua_api/l_mapgen.cpp
C++
mit
45,669
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" class ModApiMapgen : public ModApiBase { private: // get_biome_id(biomename) // returns the biome id as used in biomemap and returned by 'get_biome_data()' static int l_get_biome_id(lua_State *L); // get_biome_name(biome_id) // returns the biome name string static int l_get_biome_name(lua_State *L); // get_heat(pos) // returns the heat at the position static int l_get_heat(lua_State *L); // get_humidity(pos) // returns the humidity at the position static int l_get_humidity(lua_State *L); // get_biome_data(pos) // returns a table containing the biome id, heat and humidity at the position static int l_get_biome_data(lua_State *L); // get_mapgen_object(objectname) // returns the requested object used during map generation static int l_get_mapgen_object(lua_State *L); // get_spawn_level(x = num, z = num) static int l_get_spawn_level(lua_State *L); // get_mapgen_params() // returns the currently active map generation parameter set static int l_get_mapgen_params(lua_State *L); // set_mapgen_params(params) // set mapgen parameters static int l_set_mapgen_params(lua_State *L); // get_mapgen_setting(name) static int l_get_mapgen_setting(lua_State *L); // set_mapgen_setting(name, value, override_meta) static int l_set_mapgen_setting(lua_State *L); // get_mapgen_setting_noiseparams(name) static int l_get_mapgen_setting_noiseparams(lua_State *L); // set_mapgen_setting_noiseparams(name, value, override_meta) static int l_set_mapgen_setting_noiseparams(lua_State *L); // set_noiseparam_defaults(name, noiseparams, set_default) static int l_set_noiseparams(lua_State *L); // get_noiseparam_defaults(name) static int l_get_noiseparams(lua_State *L); // set_gen_notify(flags, {deco_id_table}) static int l_set_gen_notify(lua_State *L); // get_gen_notify() static int l_get_gen_notify(lua_State *L); // get_decoration_id(decoration_name) // returns the decoration ID as used in gennotify static int l_get_decoration_id(lua_State *L); // register_biome({lots of stuff}) static int l_register_biome(lua_State *L); // register_decoration({lots of stuff}) static int l_register_decoration(lua_State *L); // register_ore({lots of stuff}) static int l_register_ore(lua_State *L); // register_schematic({schematic}, replacements={}) static int l_register_schematic(lua_State *L); // clear_registered_biomes() static int l_clear_registered_biomes(lua_State *L); // clear_registered_decorations() static int l_clear_registered_decorations(lua_State *L); // clear_registered_schematics() static int l_clear_registered_schematics(lua_State *L); // generate_ores(vm, p1, p2) static int l_generate_ores(lua_State *L); // generate_decorations(vm, p1, p2) static int l_generate_decorations(lua_State *L); // clear_registered_ores static int l_clear_registered_ores(lua_State *L); // create_schematic(p1, p2, probability_list, filename) static int l_create_schematic(lua_State *L); // place_schematic(p, schematic, rotation, // replacements, force_placement, flagstring) static int l_place_schematic(lua_State *L); // place_schematic_on_vmanip(vm, p, schematic, rotation, // replacements, force_placement, flagstring) static int l_place_schematic_on_vmanip(lua_State *L); // serialize_schematic(schematic, format, options={...}) static int l_serialize_schematic(lua_State *L); public: static void Initialize(lua_State *L, int top); static struct EnumString es_BiomeTerrainType[]; static struct EnumString es_DecorationType[]; static struct EnumString es_MapgenObject[]; static struct EnumString es_OreType[]; static struct EnumString es_Rotation[]; static struct EnumString es_SchematicFormatType[]; static struct EnumString es_NodeResolveMethod[]; };
pgimeno/minetest
src/script/lua_api/l_mapgen.h
C++
mit
4,594
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017-8 rubenwardy <rw@rubenwardy.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_metadata.h" #include "lua_api/l_internal.h" #include "common/c_content.h" #include "serverenvironment.h" #include "map.h" #include "server.h" // LUALIB_API 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? lua_getfield(L, -1, "metadata_class"); if (lua_type(L, -1) == LUA_TSTRING) { // does it have a metadata_class field? return p; } } luaL_typerror(L, ud, "MetaDataRef"); return NULL; } 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 } // Exported functions // contains(self, name) int MetaDataRef::l_contains(lua_State *L) { MAP_LOCK_REQUIRED; MetaDataRef *ref = checkobject(L, 1); std::string name = luaL_checkstring(L, 2); Metadata *meta = ref->getmeta(false); if (meta == NULL) return 0; lua_pushboolean(L, meta->contains(name)); return 1; } // get(self, name) int MetaDataRef::l_get(lua_State *L) { MAP_LOCK_REQUIRED; MetaDataRef *ref = checkobject(L, 1); std::string name = luaL_checkstring(L, 2); Metadata *meta = ref->getmeta(false); if (meta == NULL) return 0; std::string str; if (meta->getStringToRef(name, str)) { lua_pushlstring(L, str.c_str(), str.size()); return 1; } return 0; } // get_string(self, name) int MetaDataRef::l_get_string(lua_State *L) { MAP_LOCK_REQUIRED; MetaDataRef *ref = checkobject(L, 1); std::string name = luaL_checkstring(L, 2); Metadata *meta = ref->getmeta(false); if (meta == NULL) { lua_pushlstring(L, "", 0); return 1; } const std::string &str = meta->getString(name); lua_pushlstring(L, str.c_str(), str.size()); return 1; } // set_string(self, name, var) int MetaDataRef::l_set_string(lua_State *L) { MAP_LOCK_REQUIRED; MetaDataRef *ref = checkobject(L, 1); std::string name = luaL_checkstring(L, 2); size_t len = 0; const char *s = lua_tolstring(L, 3, &len); std::string str(s, len); Metadata *meta = ref->getmeta(!str.empty()); if (meta == NULL || str == meta->getString(name)) return 0; meta->setString(name, str); ref->reportMetadataChange(&name); return 0; } // get_int(self, name) int MetaDataRef::l_get_int(lua_State *L) { MAP_LOCK_REQUIRED; MetaDataRef *ref = checkobject(L, 1); std::string name = luaL_checkstring(L, 2); Metadata *meta = ref->getmeta(false); if (meta == NULL) { lua_pushnumber(L, 0); return 1; } const std::string &str = meta->getString(name); lua_pushnumber(L, stoi(str)); return 1; } // set_int(self, name, var) int MetaDataRef::l_set_int(lua_State *L) { MAP_LOCK_REQUIRED; MetaDataRef *ref = checkobject(L, 1); std::string name = luaL_checkstring(L, 2); int a = luaL_checkint(L, 3); std::string str = itos(a); Metadata *meta = ref->getmeta(true); if (meta == NULL || str == meta->getString(name)) return 0; meta->setString(name, str); ref->reportMetadataChange(&name); return 0; } // get_float(self, name) int MetaDataRef::l_get_float(lua_State *L) { MAP_LOCK_REQUIRED; MetaDataRef *ref = checkobject(L, 1); std::string name = luaL_checkstring(L, 2); Metadata *meta = ref->getmeta(false); if (meta == NULL) { lua_pushnumber(L, 0); return 1; } const std::string &str = meta->getString(name); lua_pushnumber(L, stof(str)); return 1; } // set_float(self, name, var) int MetaDataRef::l_set_float(lua_State *L) { MAP_LOCK_REQUIRED; MetaDataRef *ref = checkobject(L, 1); std::string name = luaL_checkstring(L, 2); float a = readParam<float>(L, 3); std::string str = ftos(a); Metadata *meta = ref->getmeta(true); if (meta == NULL || str == meta->getString(name)) return 0; meta->setString(name, str); ref->reportMetadataChange(&name); return 0; } // to_table(self) int MetaDataRef::l_to_table(lua_State *L) { MAP_LOCK_REQUIRED; MetaDataRef *ref = checkobject(L, 1); Metadata *meta = ref->getmeta(true); if (meta == NULL) { lua_pushnil(L); return 1; } lua_newtable(L); ref->handleToTable(L, meta); return 1; } // from_table(self, table) int MetaDataRef::l_from_table(lua_State *L) { MAP_LOCK_REQUIRED; MetaDataRef *ref = checkobject(L, 1); int base = 2; ref->clearMeta(); if (!lua_istable(L, base)) { // No metadata lua_pushboolean(L, true); return 1; } // Create new metadata Metadata *meta = ref->getmeta(true); if (meta == NULL) { lua_pushboolean(L, false); return 1; } bool was_successful = ref->handleFromTable(L, base, meta); ref->reportMetadataChange(); lua_pushboolean(L, was_successful); return 1; } void MetaDataRef::handleToTable(lua_State *L, Metadata *meta) { lua_newtable(L); { const StringMap &fields = meta->getStrings(); for (const auto &field : fields) { const std::string &name = field.first; const std::string &value = field.second; lua_pushlstring(L, name.c_str(), name.size()); lua_pushlstring(L, value.c_str(), value.size()); lua_settable(L, -3); } } lua_setfield(L, -2, "fields"); } bool MetaDataRef::handleFromTable(lua_State *L, int table, Metadata *meta) { // Set fields lua_getfield(L, table, "fields"); if (lua_istable(L, -1)) { int fieldstable = lua_gettop(L); lua_pushnil(L); while (lua_next(L, fieldstable) != 0) { // key at index -2 and value at index -1 std::string name = readParam<std::string>(L, -2); size_t cl; const char *cs = lua_tolstring(L, -1, &cl); meta->setString(name, std::string(cs, cl)); lua_pop(L, 1); // Remove value, keep key for next iteration } lua_pop(L, 1); } return true; } // equals(self, other) int MetaDataRef::l_equals(lua_State *L) { MetaDataRef *ref1 = checkobject(L, 1); Metadata *data1 = ref1->getmeta(false); MetaDataRef *ref2 = checkobject(L, 2); Metadata *data2 = ref2->getmeta(false); if (data1 == NULL || data2 == NULL) lua_pushboolean(L, data1 == data2); else lua_pushboolean(L, *data1 == *data2); return 1; }
pgimeno/minetest
src/script/lua_api/l_metadata.cpp
C++
mit
6,930
/* Minetest Copyright (C) 2013-8 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017-8 rubenwardy <rw@rubenwardy.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes_bloated.h" #include "lua_api/l_base.h" class Metadata; /* NodeMetaRef */ class MetaDataRef : public ModApiBase { public: virtual ~MetaDataRef() = default; protected: static MetaDataRef *checkobject(lua_State *L, int narg); virtual void reportMetadataChange(const std::string *name = nullptr) {} virtual Metadata *getmeta(bool auto_create) = 0; virtual void clearMeta() = 0; virtual void handleToTable(lua_State *L, Metadata *meta); virtual bool handleFromTable(lua_State *L, int table, Metadata *meta); // Exported functions // contains(self, name) static int l_contains(lua_State *L); // get(self, name) static int l_get(lua_State *L); // get_string(self, name) static int l_get_string(lua_State *L); // set_string(self, name, var) static int l_set_string(lua_State *L); // get_int(self, name) static int l_get_int(lua_State *L); // set_int(self, name, var) static int l_set_int(lua_State *L); // get_float(self, name) static int l_get_float(lua_State *L); // set_float(self, name, var) static int l_set_float(lua_State *L); // to_table(self) static int l_to_table(lua_State *L); // from_table(self, table) static int l_from_table(lua_State *L); // equals(self, other) static int l_equals(lua_State *L); };
pgimeno/minetest
src/script/lua_api/l_metadata.h
C++
mit
2,134
/* Minetest Copyright (C) 2017 Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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" #include "client/client.h" #include "client/minimap.h" #include "settings.h" LuaMinimap::LuaMinimap(Minimap *m) : m_minimap(m) { } void LuaMinimap::create(lua_State *L, Minimap *m) { LuaMinimap *o = new LuaMinimap(m); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); // Keep minimap object stack id int minimap_object = lua_gettop(L); lua_getglobal(L, "core"); lua_getfield(L, -1, "ui"); luaL_checktype(L, -1, LUA_TTABLE); int uitable = lua_gettop(L); lua_pushvalue(L, minimap_object); // Copy object to top of stack lua_setfield(L, uitable, "minimap"); } int LuaMinimap::l_get_pos(lua_State *L) { LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); push_v3s16(L, m->getPos()); return 1; } int LuaMinimap::l_set_pos(lua_State *L) { LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); m->setPos(read_v3s16(L, 2)); return 1; } int LuaMinimap::l_get_angle(lua_State *L) { LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); lua_pushinteger(L, m->getAngle()); return 1; } int LuaMinimap::l_set_angle(lua_State *L) { LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); m->setAngle(lua_tointeger(L, 2)); return 1; } int LuaMinimap::l_get_mode(lua_State *L) { LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); lua_pushinteger(L, m->getMinimapMode()); return 1; } int LuaMinimap::l_set_mode(lua_State *L) { LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); s32 mode = lua_tointeger(L, 2); if (mode < MINIMAP_MODE_OFF || mode >= MINIMAP_MODE_COUNT) { return 0; } m->setMinimapMode((MinimapMode) mode); return 1; } int LuaMinimap::l_set_shape(lua_State *L) { LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); if (!lua_isnumber(L, 2)) return 0; m->setMinimapShape((MinimapShape)((int)lua_tonumber(L, 2))); return 0; } int LuaMinimap::l_get_shape(lua_State *L) { LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); lua_pushnumber(L, (int)m->getMinimapShape()); return 1; } int LuaMinimap::l_show(lua_State *L) { // If minimap is disabled by config, don't show it. if (!g_settings->getBool("enable_minimap")) return 1; Client *client = getClient(L); assert(client); LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); if (m->getMinimapMode() == MINIMAP_MODE_OFF) m->setMinimapMode(MINIMAP_MODE_SURFACEx1); client->showMinimap(true); return 1; } int LuaMinimap::l_hide(lua_State *L) { Client *client = getClient(L); assert(client); LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); if (m->getMinimapMode() != MINIMAP_MODE_OFF) m->setMinimapMode(MINIMAP_MODE_OFF); client->showMinimap(false); return 1; } LuaMinimap *LuaMinimap::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 *(LuaMinimap **)ud; // unbox pointer } Minimap* LuaMinimap::getobject(LuaMinimap *ref) { return ref->m_minimap; } int LuaMinimap::gc_object(lua_State *L) { LuaMinimap *o = *(LuaMinimap **)(lua_touserdata(L, 1)); delete o; return 0; } void LuaMinimap::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); // drop metatable 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} };
pgimeno/minetest
src/script/lua_api/l_minimap.cpp
C++
mit
5,210
/* Minetest Copyright (C) 2017 Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "l_base.h" class Minimap; class LuaMinimap : public ModApiBase { private: static const char className[]; static const luaL_Reg methods[]; // garbage collector static int gc_object(lua_State *L); static int l_get_pos(lua_State *L); static int l_set_pos(lua_State *L); static int l_get_angle(lua_State *L); static int l_set_angle(lua_State *L); static int l_get_mode(lua_State *L); static int l_set_mode(lua_State *L); static int l_show(lua_State *L); static int l_hide(lua_State *L); static int l_set_shape(lua_State *L); static int l_get_shape(lua_State *L); Minimap *m_minimap = nullptr; public: LuaMinimap(Minimap *m); ~LuaMinimap() = default; static void create(lua_State *L, Minimap *object); static LuaMinimap *checkobject(lua_State *L, int narg); static Minimap *getobject(LuaMinimap *ref); static void Register(lua_State *L); };
pgimeno/minetest
src/script/lua_api/l_minimap.h
C++
mit
1,673
/* Minetest Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <cassert> #include <log.h> #include "lua_api/l_modchannels.h" #include "l_internal.h" #include "modchannels.h" int ModApiChannels::l_mod_channel_join(lua_State *L) { if (!lua_isstring(L, 1)) return 0; std::string channel = luaL_checkstring(L, 1); if (channel.empty()) return 0; getGameDef(L)->joinModChannel(channel); assert(getGameDef(L)->getModChannel(channel) != nullptr); ModChannelRef::create(L, channel); int object = lua_gettop(L); lua_pushvalue(L, object); return 1; } void ModApiChannels::Initialize(lua_State *L, int top) { API_FCT(mod_channel_join); } /* * ModChannelRef */ ModChannelRef::ModChannelRef(const std::string &modchannel) : m_modchannel_name(modchannel) { } int ModChannelRef::l_leave(lua_State *L) { ModChannelRef *ref = checkobject(L, 1); getGameDef(L)->leaveModChannel(ref->m_modchannel_name); return 0; } int ModChannelRef::l_send_all(lua_State *L) { ModChannelRef *ref = checkobject(L, 1); ModChannel *channel = getobject(L, ref); if (!channel || !channel->canWrite()) return 0; // @TODO serialize message std::string message = luaL_checkstring(L, 2); getGameDef(L)->sendModChannelMessage(channel->getName(), message); return 0; } int ModChannelRef::l_is_writeable(lua_State *L) { ModChannelRef *ref = checkobject(L, 1); ModChannel *channel = getobject(L, ref); if (!channel) return 0; lua_pushboolean(L, channel->canWrite()); return 1; } void ModChannelRef::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); // Drop metatable luaL_openlib(L, 0, methods, 0); // fill methodtable lua_pop(L, 1); // Drop methodtable } void ModChannelRef::create(lua_State *L, const std::string &channel) { ModChannelRef *o = new ModChannelRef(channel); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); } int ModChannelRef::gc_object(lua_State *L) { ModChannelRef *o = *(ModChannelRef **)(lua_touserdata(L, 1)); delete o; return 0; } ModChannelRef *ModChannelRef::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 *(ModChannelRef **)ud; // unbox pointer } ModChannel *ModChannelRef::getobject(lua_State *L, ModChannelRef *ref) { return getGameDef(L)->getModChannel(ref->m_modchannel_name); } // clang-format off const char ModChannelRef::className[] = "ModChannelRef"; const luaL_Reg ModChannelRef::methods[] = { luamethod(ModChannelRef, leave), luamethod(ModChannelRef, is_writeable), luamethod(ModChannelRef, send_all), {0, 0}, }; // clang-format on
pgimeno/minetest
src/script/lua_api/l_modchannels.cpp
C++
mit
3,863
/* Minetest Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" #include "config.h" class ModChannel; class ModApiChannels : public ModApiBase { private: // mod_channel_join(name) static int l_mod_channel_join(lua_State *L); public: static void Initialize(lua_State *L, int top); }; class ModChannelRef : public ModApiBase { public: ModChannelRef(const std::string &modchannel); ~ModChannelRef() = default; static void Register(lua_State *L); static void create(lua_State *L, const std::string &channel); // leave() static int l_leave(lua_State *L); // send(message) static int l_send_all(lua_State *L); // is_writeable() static int l_is_writeable(lua_State *L); private: // garbage collector static int gc_object(lua_State *L); static ModChannelRef *checkobject(lua_State *L, int narg); static ModChannel *getobject(lua_State *L, ModChannelRef *ref); std::string m_modchannel_name; static const char className[]; static const luaL_Reg methods[]; };
pgimeno/minetest
src/script/lua_api/l_modchannels.h
C++
mit
1,749
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_nodemeta.h" #include "lua_api/l_internal.h" #include "lua_api/l_inventory.h" #include "common/c_content.h" #include "serverenvironment.h" #include "map.h" #include "mapblock.h" #include "server.h" /* NodeMetaRef */ 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 } Metadata* NodeMetaRef::getmeta(bool auto_create) { if (m_is_local) return m_meta; NodeMetadata *meta = m_env->getMap().getNodeMetadata(m_p); if (meta == NULL && auto_create) { meta = new NodeMetadata(m_env->getGameDef()->idef()); if (!m_env->getMap().setNodeMetadata(m_p, meta)) { delete meta; return NULL; } } return meta; } void NodeMetaRef::clearMeta() { m_env->getMap().removeNodeMetadata(m_p); } void NodeMetaRef::reportMetadataChange(const std::string *name) { // NOTE: This same code is in rollback_interface.cpp // Inform other things that the metadata has changed NodeMetadata *meta = dynamic_cast<NodeMetadata*>(m_meta); MapEditEvent event; event.type = MEET_BLOCK_NODE_METADATA_CHANGED; event.p = m_p; event.is_private_change = name && meta && meta->isPrivate(*name); m_env->getMap().dispatchEvent(&event); } // Exported functions // garbage collector int NodeMetaRef::gc_object(lua_State *L) { NodeMetaRef *o = *(NodeMetaRef **)(lua_touserdata(L, 1)); delete o; return 0; } // get_inventory(self) 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 InvRef::createNodeMeta(L, ref->m_p); return 1; } // mark_as_private(self, <string> or {<string>, <string>, ...}) int NodeMetaRef::l_mark_as_private(lua_State *L) { MAP_LOCK_REQUIRED; NodeMetaRef *ref = checkobject(L, 1); NodeMetadata *meta = dynamic_cast<NodeMetadata*>(ref->getmeta(true)); assert(meta); if (lua_istable(L, 2)) { lua_pushnil(L); while (lua_next(L, 2) != 0) { // key at index -2 and value at index -1 luaL_checktype(L, -1, LUA_TSTRING); meta->markPrivate(readParam<std::string>(L, -1), true); // removes value, keeps key for next iteration lua_pop(L, 1); } } else if (lua_isstring(L, 2)) { meta->markPrivate(readParam<std::string>(L, 2), true); } ref->reportMetadataChange(); return 0; } void NodeMetaRef::handleToTable(lua_State *L, Metadata *_meta) { // fields MetaDataRef::handleToTable(L, _meta); NodeMetadata *meta = (NodeMetadata*) _meta; // inventory lua_newtable(L); Inventory *inv = meta->getInventory(); if (inv) { std::vector<const InventoryList *> lists = inv->getLists(); for(std::vector<const InventoryList *>::const_iterator i = lists.begin(); i != lists.end(); ++i) { push_inventory_list(L, inv, (*i)->getName().c_str()); lua_setfield(L, -2, (*i)->getName().c_str()); } } lua_setfield(L, -2, "inventory"); } // from_table(self, table) bool NodeMetaRef::handleFromTable(lua_State *L, int table, Metadata *_meta) { // fields if (!MetaDataRef::handleFromTable(L, table, _meta)) return false; NodeMetadata *meta = (NodeMetadata*) _meta; // inventory Inventory *inv = meta->getInventory(); lua_getfield(L, table, "inventory"); if (lua_istable(L, -1)) { int inventorytable = lua_gettop(L); lua_pushnil(L); while (lua_next(L, inventorytable) != 0) { // key at index -2 and value at index -1 std::string name = luaL_checkstring(L, -2); read_inventory_list(L, -1, inv, name.c_str(), getServer(L)); lua_pop(L, 1); // Remove value, keep key for next iteration } lua_pop(L, 1); } return true; } NodeMetaRef::NodeMetaRef(v3s16 p, ServerEnvironment *env): m_p(p), m_env(env) { } NodeMetaRef::NodeMetaRef(Metadata *meta): m_meta(meta), m_is_local(true) { } // Creates an NodeMetaRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. void NodeMetaRef::create(lua_State *L, v3s16 p, ServerEnvironment *env) { NodeMetaRef *o = new NodeMetaRef(p, env); //infostream<<"NodeMetaRef::create: o="<<o<<std::endl; *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); } // Client-sided version of the above void NodeMetaRef::createClient(lua_State *L, Metadata *meta) { NodeMetaRef *o = new NodeMetaRef(meta); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); } const char NodeMetaRef::className[] = "NodeMetaRef"; void NodeMetaRef::RegisterCommon(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "metadata_class"); lua_pushlstring(L, className, strlen(className)); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pushliteral(L, "__eq"); lua_pushcfunction(L, l_equals); lua_settable(L, metatable); lua_pop(L, 1); // drop metatable } void NodeMetaRef::Register(lua_State *L) { RegisterCommon(L); luaL_openlib(L, 0, methodsServer, 0); // fill methodtable lua_pop(L, 1); // drop methodtable } const luaL_Reg NodeMetaRef::methodsServer[] = { luamethod(MetaDataRef, contains), luamethod(MetaDataRef, get), luamethod(MetaDataRef, get_string), luamethod(MetaDataRef, set_string), luamethod(MetaDataRef, get_int), luamethod(MetaDataRef, set_int), luamethod(MetaDataRef, get_float), luamethod(MetaDataRef, set_float), luamethod(MetaDataRef, to_table), luamethod(MetaDataRef, from_table), luamethod(NodeMetaRef, get_inventory), luamethod(NodeMetaRef, mark_as_private), luamethod(MetaDataRef, equals), {0,0} }; void NodeMetaRef::RegisterClient(lua_State *L) { RegisterCommon(L); luaL_openlib(L, 0, methodsClient, 0); // fill methodtable lua_pop(L, 1); // drop methodtable } const luaL_Reg NodeMetaRef::methodsClient[] = { luamethod(MetaDataRef, contains), luamethod(MetaDataRef, get), luamethod(MetaDataRef, get_string), luamethod(MetaDataRef, get_int), luamethod(MetaDataRef, get_float), luamethod(MetaDataRef, to_table), {0,0} };
pgimeno/minetest
src/script/lua_api/l_nodemeta.cpp
C++
mit
7,263
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" #include "lua_api/l_metadata.h" #include "irrlichttypes_bloated.h" #include "nodemetadata.h" class ServerEnvironment; class NodeMetadata; /* NodeMetaRef */ class NodeMetaRef : public MetaDataRef { private: v3s16 m_p; ServerEnvironment *m_env = nullptr; Metadata *m_meta = nullptr; bool m_is_local = false; static const char className[]; static const luaL_Reg methodsServer[]; static const luaL_Reg methodsClient[]; static NodeMetaRef *checkobject(lua_State *L, int narg); /** * Retrieve metadata for a node. * If @p auto_create is set and the specified node has no metadata information * associated with it yet, the method attempts to attach a new metadata object * to the node and returns a pointer to the metadata when successful. * * However, it is NOT guaranteed that the method will return a pointer, * and @c NULL may be returned in case of an error regardless of @p auto_create. * * @param ref specifies the node for which the associated metadata is retrieved. * @param auto_create when true, try to create metadata information for the node if it has none. * @return pointer to a @c NodeMetadata object or @c NULL in case of error. */ virtual Metadata* getmeta(bool auto_create); virtual void clearMeta(); virtual void reportMetadataChange(const std::string *name = nullptr); virtual void handleToTable(lua_State *L, Metadata *_meta); virtual bool handleFromTable(lua_State *L, int table, Metadata *_meta); // Exported functions // garbage collector static int gc_object(lua_State *L); // get_inventory(self) static int l_get_inventory(lua_State *L); // mark_as_private(self, <string> or {<string>, <string>, ...}) static int l_mark_as_private(lua_State *L); public: NodeMetaRef(v3s16 p, ServerEnvironment *env); NodeMetaRef(Metadata *meta); ~NodeMetaRef() = default; // Creates an NodeMetaRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. static void create(lua_State *L, v3s16 p, ServerEnvironment *env); // Client-sided version of the above static void createClient(lua_State *L, Metadata *meta); static void RegisterCommon(lua_State *L); static void Register(lua_State *L); static void RegisterClient(lua_State *L); };
pgimeno/minetest
src/script/lua_api/l_nodemeta.h
C++
mit
3,083
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_nodetimer.h" #include "lua_api/l_internal.h" #include "serverenvironment.h" #include "map.h" int NodeTimerRef::gc_object(lua_State *L) { NodeTimerRef *o = *(NodeTimerRef **)(lua_touserdata(L, 1)); delete o; return 0; } NodeTimerRef* NodeTimerRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); if(!ud) luaL_typerror(L, narg, className); return *(NodeTimerRef**)ud; // unbox pointer } int NodeTimerRef::l_set(lua_State *L) { MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); ServerEnvironment *env = o->m_env; if(env == NULL) return 0; f32 t = readParam<float>(L,2); f32 e = readParam<float>(L,3); env->getMap().setNodeTimer(NodeTimer(t, e, o->m_p)); return 0; } int NodeTimerRef::l_start(lua_State *L) { MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); ServerEnvironment *env = o->m_env; if(env == NULL) return 0; f32 t = readParam<float>(L,2); env->getMap().setNodeTimer(NodeTimer(t, 0, o->m_p)); return 0; } int NodeTimerRef::l_stop(lua_State *L) { MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); ServerEnvironment *env = o->m_env; if(env == NULL) return 0; env->getMap().removeNodeTimer(o->m_p); return 0; } int NodeTimerRef::l_is_started(lua_State *L) { MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); ServerEnvironment *env = o->m_env; if(env == NULL) return 0; NodeTimer t = env->getMap().getNodeTimer(o->m_p); lua_pushboolean(L,(t.timeout != 0)); return 1; } int NodeTimerRef::l_get_timeout(lua_State *L) { MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); ServerEnvironment *env = o->m_env; if(env == NULL) return 0; NodeTimer t = env->getMap().getNodeTimer(o->m_p); lua_pushnumber(L,t.timeout); return 1; } int NodeTimerRef::l_get_elapsed(lua_State *L) { MAP_LOCK_REQUIRED; NodeTimerRef *o = checkobject(L, 1); ServerEnvironment *env = o->m_env; if(env == NULL) return 0; NodeTimer t = env->getMap().getNodeTimer(o->m_p); lua_pushnumber(L,t.elapsed); return 1; } NodeTimerRef::NodeTimerRef(v3s16 p, ServerEnvironment *env): m_p(p), m_env(env) { } // Creates an NodeTimerRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. void NodeTimerRef::create(lua_State *L, v3s16 p, ServerEnvironment *env) { NodeTimerRef *o = new NodeTimerRef(p, env); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); } void NodeTimerRef::set_null(lua_State *L) { NodeTimerRef *o = checkobject(L, -1); o->m_env = NULL; } void NodeTimerRef::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); // drop metatable 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); } 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} };
pgimeno/minetest
src/script/lua_api/l_nodetimer.cpp
C++
mit
4,426
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irr_v3d.h" #include "lua_api/l_base.h" class ServerEnvironment; class NodeTimerRef : public ModApiBase { private: v3s16 m_p; ServerEnvironment *m_env = nullptr; static const char className[]; static const luaL_Reg methods[]; static int gc_object(lua_State *L); static NodeTimerRef *checkobject(lua_State *L, int narg); static int l_set(lua_State *L); static int l_start(lua_State *L); static int l_stop(lua_State *L); static int l_is_started(lua_State *L); static int l_get_timeout(lua_State *L); static int l_get_elapsed(lua_State *L); public: NodeTimerRef(v3s16 p, ServerEnvironment *env); ~NodeTimerRef() = default; // Creates an NodeTimerRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. static void create(lua_State *L, v3s16 p, ServerEnvironment *env); static void set_null(lua_State *L); static void Register(lua_State *L); };
pgimeno/minetest
src/script/lua_api/l_nodetimer.h
C++
mit
1,729
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_noise.h" #include "lua_api/l_internal.h" #include "common/c_converter.h" #include "common/c_content.h" #include "log.h" #include "porting.h" #include "util/numeric.h" /////////////////////////////////////// /* LuaPerlinNoise */ LuaPerlinNoise::LuaPerlinNoise(NoiseParams *params) : np(*params) { } int LuaPerlinNoise::l_get_2d(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoise *o = checkobject(L, 1); v2f p = readParam<v2f>(L, 2); lua_Number val = NoisePerlin2D(&o->np, p.X, p.Y, 0); lua_pushnumber(L, val); return 1; } int LuaPerlinNoise::l_get_3d(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoise *o = checkobject(L, 1); v3f p = check_v3f(L, 2); lua_Number val = NoisePerlin3D(&o->np, p.X, p.Y, p.Z, 0); lua_pushnumber(L, val); return 1; } int LuaPerlinNoise::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; NoiseParams params; if (lua_istable(L, 1)) { read_noiseparams(L, 1, &params); } else { params.seed = luaL_checkint(L, 1); params.octaves = luaL_checkint(L, 2); params.persist = readParam<float>(L, 3); params.spread = v3f(1, 1, 1) * readParam<float>(L, 4); } LuaPerlinNoise *o = new LuaPerlinNoise(&params); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } int LuaPerlinNoise::gc_object(lua_State *L) { LuaPerlinNoise *o = *(LuaPerlinNoise **)(lua_touserdata(L, 1)); delete o; return 0; } LuaPerlinNoise *LuaPerlinNoise::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 *(LuaPerlinNoise **)ud; } void LuaPerlinNoise::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); markAliasDeprecated(methods); luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); 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} }; /////////////////////////////////////// /* LuaPerlinNoiseMap */ LuaPerlinNoiseMap::LuaPerlinNoiseMap(NoiseParams *params, s32 seed, v3s16 size) { m_is3d = size.Z > 1; np = *params; try { noise = new Noise(&np, seed, size.X, size.Y, size.Z); } catch (InvalidNoiseParamsException &e) { throw LuaError(e.what()); } } LuaPerlinNoiseMap::~LuaPerlinNoiseMap() { delete noise; } int LuaPerlinNoiseMap::l_get_2d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; size_t i = 0; LuaPerlinNoiseMap *o = checkobject(L, 1); v2f p = readParam<v2f>(L, 2); Noise *n = o->noise; n->perlinMap2D(p.X, p.Y); lua_newtable(L); for (u32 y = 0; y != n->sy; y++) { lua_newtable(L); for (u32 x = 0; x != n->sx; x++) { lua_pushnumber(L, n->result[i++]); lua_rawseti(L, -2, x + 1); } lua_rawseti(L, -2, y + 1); } return 1; } int LuaPerlinNoiseMap::l_get_2d_map_flat(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); v2f p = readParam<v2f>(L, 2); bool use_buffer = lua_istable(L, 3); Noise *n = o->noise; n->perlinMap2D(p.X, p.Y); size_t maplen = n->sx * n->sy; if (use_buffer) lua_pushvalue(L, 3); else lua_newtable(L); for (size_t i = 0; i != maplen; i++) { lua_pushnumber(L, n->result[i]); lua_rawseti(L, -2, i + 1); } return 1; } int LuaPerlinNoiseMap::l_get_3d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; size_t i = 0; LuaPerlinNoiseMap *o = checkobject(L, 1); v3f p = check_v3f(L, 2); if (!o->m_is3d) return 0; Noise *n = o->noise; n->perlinMap3D(p.X, p.Y, p.Z); lua_newtable(L); for (u32 z = 0; z != n->sz; z++) { lua_newtable(L); for (u32 y = 0; y != n->sy; y++) { lua_newtable(L); for (u32 x = 0; x != n->sx; x++) { lua_pushnumber(L, n->result[i++]); lua_rawseti(L, -2, x + 1); } lua_rawseti(L, -2, y + 1); } lua_rawseti(L, -2, z + 1); } 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); if (!o->m_is3d) return 0; Noise *n = o->noise; n->perlinMap3D(p.X, p.Y, p.Z); size_t maplen = n->sx * n->sy * n->sz; if (use_buffer) lua_pushvalue(L, 3); else lua_newtable(L); for (size_t i = 0; i != maplen; i++) { lua_pushnumber(L, n->result[i]); lua_rawseti(L, -2, i + 1); } return 1; } int LuaPerlinNoiseMap::l_calc_2d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); v2f p = readParam<v2f>(L, 2); Noise *n = o->noise; n->perlinMap2D(p.X, p.Y); return 0; } int LuaPerlinNoiseMap::l_calc_3d_map(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPerlinNoiseMap *o = checkobject(L, 1); v3f p = check_v3f(L, 2); if (!o->m_is3d) return 0; Noise *n = o->noise; n->perlinMap3D(p.X, p.Y, p.Z); 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); Noise *n = o->noise; if (use_buffer) lua_pushvalue(L, 4); 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)); return 1; } int LuaPerlinNoiseMap::create_object(lua_State *L) { NoiseParams np; if (!read_noiseparams(L, 1, &np)) return 0; v3s16 size = read_v3s16(L, 2); LuaPerlinNoiseMap *o = new LuaPerlinNoiseMap(&np, 0, size); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } int LuaPerlinNoiseMap::gc_object(lua_State *L) { LuaPerlinNoiseMap *o = *(LuaPerlinNoiseMap **)(lua_touserdata(L, 1)); delete o; return 0; } LuaPerlinNoiseMap *LuaPerlinNoiseMap::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 *(LuaPerlinNoiseMap **)ud; } void LuaPerlinNoiseMap::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); markAliasDeprecated(methods); luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); 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} }; /////////////////////////////////////// /* LuaPseudoRandom */ int LuaPseudoRandom::l_next(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPseudoRandom *o = checkobject(L, 1); int min = 0; int max = 32767; lua_settop(L, 3); if (lua_isnumber(L, 2)) min = luaL_checkinteger(L, 2); if (lua_isnumber(L, 3)) max = luaL_checkinteger(L, 3); if (max < min) { errorstream<<"PseudoRandom.next(): max="<<max<<" min="<<min<<std::endl; throw LuaError("PseudoRandom.next(): max < min"); } 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."); PseudoRandom &pseudo = o->m_pseudo; int val = pseudo.next(); val = (val % (max-min+1)) + min; lua_pushinteger(L, val); return 1; } int LuaPseudoRandom::create_object(lua_State *L) { NO_MAP_LOCK_REQUIRED; u64 seed = luaL_checknumber(L, 1); LuaPseudoRandom *o = new LuaPseudoRandom(seed); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } int LuaPseudoRandom::gc_object(lua_State *L) { LuaPseudoRandom *o = *(LuaPseudoRandom **)(lua_touserdata(L, 1)); delete o; return 0; } LuaPseudoRandom *LuaPseudoRandom::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 *(LuaPseudoRandom **)ud; } void LuaPseudoRandom::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); lua_register(L, className, create_object); } const char LuaPseudoRandom::className[] = "PseudoRandom"; const luaL_Reg LuaPseudoRandom::methods[] = { luamethod(LuaPseudoRandom, next), {0,0} }; /////////////////////////////////////// /* LuaPcgRandom */ int LuaPcgRandom::l_next(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPcgRandom *o = checkobject(L, 1); u32 min = lua_isnumber(L, 2) ? lua_tointeger(L, 2) : o->m_rnd.RANDOM_MIN; u32 max = lua_isnumber(L, 3) ? lua_tointeger(L, 3) : o->m_rnd.RANDOM_MAX; lua_pushinteger(L, o->m_rnd.range(min, max)); return 1; } int LuaPcgRandom::l_rand_normal_dist(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaPcgRandom *o = checkobject(L, 1); u32 min = lua_isnumber(L, 2) ? lua_tointeger(L, 2) : o->m_rnd.RANDOM_MIN; u32 max = lua_isnumber(L, 3) ? lua_tointeger(L, 3) : o->m_rnd.RANDOM_MAX; int num_trials = lua_isnumber(L, 4) ? lua_tointeger(L, 4) : 6; lua_pushinteger(L, o->m_rnd.randNormalDist(min, max, num_trials)); 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); *(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)); delete o; return 0; } LuaPcgRandom *LuaPcgRandom::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 *(LuaPcgRandom **)ud; } void LuaPcgRandom::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); 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} }; /////////////////////////////////////// /* LuaSecureRandom */ bool LuaSecureRandom::fillRandBuf() { return porting::secure_rand_fill_buf(m_rand_buf, RAND_BUF_SIZE); } int LuaSecureRandom::l_next_bytes(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaSecureRandom *o = checkobject(L, 1); u32 count = lua_isnumber(L, 2) ? lua_tointeger(L, 2) : 1; // Limit count count = MYMIN(RAND_BUF_SIZE, count); // Find out whether we can pass directly from our array, or have to do some gluing size_t count_remaining = RAND_BUF_SIZE - o->m_rand_idx; if (count_remaining >= count) { lua_pushlstring(L, o->m_rand_buf + o->m_rand_idx, count); o->m_rand_idx += count; } else { char output_buf[RAND_BUF_SIZE]; // Copy over with what we have left from our current buffer memcpy(output_buf, o->m_rand_buf + o->m_rand_idx, count_remaining); // 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); // Update index o->m_rand_idx = count - count_remaining; lua_pushlstring(L, output_buf, count); } return 1; } int LuaSecureRandom::create_object(lua_State *L) { LuaSecureRandom *o = new LuaSecureRandom(); // Fail and return nil if we can't securely fill the buffer if (!o->fillRandBuf()) { delete o; return 0; } *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } int LuaSecureRandom::gc_object(lua_State *L) { LuaSecureRandom *o = *(LuaSecureRandom **)(lua_touserdata(L, 1)); delete o; return 0; } LuaSecureRandom *LuaSecureRandom::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 *(LuaSecureRandom **)ud; } void LuaSecureRandom::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); lua_register(L, className, create_object); } const char LuaSecureRandom::className[] = "SecureRandom"; const luaL_Reg LuaSecureRandom::methods[] = { luamethod(LuaSecureRandom, next_bytes), {0,0} };
pgimeno/minetest
src/script/lua_api/l_noise.cpp
C++
mit
15,750
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irr_v3d.h" #include "lua_api/l_base.h" #include "noise.h" /* LuaPerlinNoise */ class LuaPerlinNoise : public ModApiBase { private: NoiseParams np; static const char className[]; static luaL_Reg methods[]; // Exported functions // garbage collector static int gc_object(lua_State *L); static int l_get_2d(lua_State *L); static int l_get_3d(lua_State *L); public: LuaPerlinNoise(NoiseParams *params); ~LuaPerlinNoise() = default; // LuaPerlinNoise(seed, octaves, persistence, scale) // Creates an LuaPerlinNoise and leaves it on top of stack static int create_object(lua_State *L); static LuaPerlinNoise *checkobject(lua_State *L, int narg); static void Register(lua_State *L); }; /* LuaPerlinNoiseMap */ class LuaPerlinNoiseMap : public ModApiBase { NoiseParams np; Noise *noise; bool m_is3d; static const char className[]; static luaL_Reg methods[]; // Exported functions // garbage collector static int gc_object(lua_State *L); static int l_get_2d_map(lua_State *L); static int l_get_2d_map_flat(lua_State *L); static int l_get_3d_map(lua_State *L); static int l_get_3d_map_flat(lua_State *L); static int l_calc_2d_map(lua_State *L); static int l_calc_3d_map(lua_State *L); static int l_get_map_slice(lua_State *L); public: LuaPerlinNoiseMap(NoiseParams *np, s32 seed, v3s16 size); ~LuaPerlinNoiseMap(); // LuaPerlinNoiseMap(np, size) // Creates an LuaPerlinNoiseMap and leaves it on top of stack static int create_object(lua_State *L); static LuaPerlinNoiseMap *checkobject(lua_State *L, int narg); static void Register(lua_State *L); }; /* LuaPseudoRandom */ class LuaPseudoRandom : public ModApiBase { private: PseudoRandom m_pseudo; static const char className[]; static const luaL_Reg methods[]; // Exported functions // garbage collector static int gc_object(lua_State *L); // next(self, min=0, max=32767) -> get next value static int l_next(lua_State *L); public: LuaPseudoRandom(s32 seed) : m_pseudo(seed) {} // LuaPseudoRandom(seed) // Creates an LuaPseudoRandom and leaves it on top of stack static int create_object(lua_State *L); static LuaPseudoRandom *checkobject(lua_State *L, int narg); static void Register(lua_State *L); }; /* LuaPcgRandom */ class LuaPcgRandom : public ModApiBase { private: PcgRandom m_rnd; static const char className[]; static const luaL_Reg methods[]; // Exported functions // garbage collector static int gc_object(lua_State *L); // next(self, min=-2147483648, max=2147483647) -> get next value static int l_next(lua_State *L); // rand_normal_dist(self, min=-2147483648, max=2147483647, num_trials=6) -> // get next normally distributed random value static int l_rand_normal_dist(lua_State *L); public: LuaPcgRandom(u64 seed) : m_rnd(seed) {} LuaPcgRandom(u64 seed, u64 seq) : m_rnd(seed, seq) {} // LuaPcgRandom(seed) // Creates an LuaPcgRandom and leaves it on top of stack static int create_object(lua_State *L); static LuaPcgRandom *checkobject(lua_State *L, int narg); static void Register(lua_State *L); }; /* LuaSecureRandom */ class LuaSecureRandom : public ModApiBase { private: static const size_t RAND_BUF_SIZE = 2048; static const char className[]; static const luaL_Reg methods[]; u32 m_rand_idx; char m_rand_buf[RAND_BUF_SIZE]; // Exported functions // garbage collector static int gc_object(lua_State *L); // next_bytes(self, count) -> get count many bytes static int l_next_bytes(lua_State *L); public: bool fillRandBuf(); // LuaSecureRandom() // Creates an LuaSecureRandom and leaves it on top of stack static int create_object(lua_State *L); static LuaSecureRandom *checkobject(lua_State *L, int narg); static void Register(lua_State *L); };
pgimeno/minetest
src/script/lua_api/l_noise.h
C++
mit
4,547
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_object.h" #include <cmath> #include "lua_api/l_internal.h" #include "lua_api/l_inventory.h" #include "lua_api/l_item.h" #include "lua_api/l_playermeta.h" #include "common/c_converter.h" #include "common/c_content.h" #include "log.h" #include "tool.h" #include "serverobject.h" #include "content_sao.h" #include "remoteplayer.h" #include "server.h" #include "hud.h" #include "scripting_server.h" /* ObjectRef */ 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 } ServerActiveObject* ObjectRef::getobject(ObjectRef *ref) { ServerActiveObject *co = ref->m_object; return co; } 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; } 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; } RemotePlayer *ObjectRef::getplayer(ObjectRef *ref) { PlayerSAO *playersao = getplayersao(ref); if (playersao == NULL) return NULL; return playersao->getPlayer(); } // Exported functions // garbage collector int ObjectRef::gc_object(lua_State *L) { ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1)); //infostream<<"ObjectRef::gc_object: o="<<o<<std::endl; delete o; return 0; } // remove(self) int ObjectRef::l_remove(lua_State *L) { GET_ENV_PTR; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; if (co->getType() == ACTIVEOBJECT_TYPE_PLAYER) return 0; co->clearChildAttachments(); co->clearParentAttachment(); verbosestream << "ObjectRef::l_remove(): id=" << co->getId() << std::endl; co->m_pending_removal = true; return 0; } // get_pos(self) // returns: {x=num, y=num, z=num} int ObjectRef::l_get_pos(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; v3f pos = co->getBasePosition() / BS; lua_newtable(L); lua_pushnumber(L, pos.X); lua_setfield(L, -2, "x"); lua_pushnumber(L, pos.Y); lua_setfield(L, -2, "y"); lua_pushnumber(L, pos.Z); lua_setfield(L, -2, "z"); return 1; } // set_pos(self, pos) int ObjectRef::l_set_pos(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); //LuaEntitySAO *co = getluaobject(ref); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; // pos v3f pos = checkFloatPos(L, 2); // Do it co->setPos(pos); return 0; } // move_to(self, pos, continuous=false) int ObjectRef::l_move_to(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); //LuaEntitySAO *co = getluaobject(ref); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; // pos v3f pos = checkFloatPos(L, 2); // continuous bool continuous = readParam<bool>(L, 3); // Do it co->moveTo(pos, continuous); return 0; } // punch(self, puncher, time_from_last_punch, tool_capabilities, dir) int ObjectRef::l_punch(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ObjectRef *puncher_ref = checkobject(L, 2); ServerActiveObject *co = getobject(ref); ServerActiveObject *puncher = getobject(puncher_ref); if (co == NULL) return 0; if (puncher == NULL) return 0; v3f dir; if (lua_type(L, 5) != LUA_TTABLE) dir = co->getBasePosition() - puncher->getBasePosition(); else dir = read_v3f(L, 5); float time_from_last_punch = 1000000; if (lua_isnumber(L, 3)) time_from_last_punch = lua_tonumber(L, 3); ToolCapabilities toolcap = read_tool_capabilities(L, 4); dir.normalize(); u16 src_original_hp = co->getHP(); u16 dst_origin_hp = puncher->getHP(); // Do it co->punch(dir, &toolcap, puncher, time_from_last_punch); // If the punched is a player, and its HP changed if (src_original_hp != co->getHP() && co->getType() == ACTIVEOBJECT_TYPE_PLAYER) { getServer(L)->SendPlayerHPOrDie((PlayerSAO *)co, PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, puncher)); } // If the puncher is a player, and its HP changed if (dst_origin_hp != puncher->getHP() && puncher->getType() == ACTIVEOBJECT_TYPE_PLAYER) { getServer(L)->SendPlayerHPOrDie((PlayerSAO *)puncher, PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, co)); } return 0; } // right_click(self, clicker); clicker = an another ObjectRef int ObjectRef::l_right_click(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ObjectRef *ref2 = checkobject(L, 2); ServerActiveObject *co = getobject(ref); ServerActiveObject *co2 = getobject(ref2); if (co == NULL) return 0; if (co2 == NULL) return 0; // Do it co->rightClick(co2); return 0; } // set_hp(self, hp) // hp = number of hitpoints (2 * number of hearts) // returns: nil int ObjectRef::l_set_hp(lua_State *L) { NO_MAP_LOCK_REQUIRED; // Get Object ObjectRef *ref = checkobject(L, 1); luaL_checknumber(L, 2); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; // Get HP int hp = lua_tonumber(L, 2); // Get Reason PlayerHPChangeReason reason(PlayerHPChangeReason::SET_HP); reason.from_mod = true; if (lua_istable(L, 3)) { lua_pushvalue(L, 3); lua_getfield(L, -1, "type"); if (lua_isstring(L, -1) && !reason.setTypeFromString(readParam<std::string>(L, -1))) { errorstream << "Bad type given!" << std::endl; } lua_pop(L, 1); reason.lua_reference = luaL_ref(L, LUA_REGISTRYINDEX); } // Do it co->setHP(hp, reason); if (co->getType() == ACTIVEOBJECT_TYPE_PLAYER) getServer(L)->SendPlayerHPOrDie((PlayerSAO *)co, reason); if (reason.hasLuaReference()) luaL_unref(L, LUA_REGISTRYINDEX, reason.lua_reference); // Return return 0; } // get_hp(self) // returns: number of hitpoints (2 * number of hearts) // 0 if not applicable to this type of object int ObjectRef::l_get_hp(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) { // Default hp is 1 lua_pushnumber(L, 1); return 1; } int hp = co->getHP(); /*infostream<<"ObjectRef::l_get_hp(): id="<<co->getId() <<" hp="<<hp<<std::endl;*/ // Return lua_pushnumber(L, hp); return 1; } // get_inventory(self) 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; // Do it InventoryLocation loc = co->getInventoryLocation(); if (getServer(L)->getInventory(loc) != NULL) InvRef::create(L, loc); else lua_pushnil(L); // An object may have no inventory (nil) return 1; } // get_wield_list(self) int ObjectRef::l_get_wield_list(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; // Do it lua_pushstring(L, co->getWieldList().c_str()); return 1; } // get_wield_index(self) int ObjectRef::l_get_wield_index(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; // Do it lua_pushinteger(L, co->getWieldIndex() + 1); return 1; } // get_wielded_item(self) int ObjectRef::l_get_wielded_item(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) { // Empty ItemStack LuaItemStack::create(L, ItemStack()); return 1; } // Do it LuaItemStack::create(L, co->getWieldedItem()); return 1; } // set_wielded_item(self, itemstack or itemstring or table or nil) 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; // Do it ItemStack item = read_item(L, 2, getServer(L)->idef()); bool success = co->setWieldedItem(item); if (success && co->getType() == ACTIVEOBJECT_TYPE_PLAYER) { getServer(L)->SendInventory(((PlayerSAO*)co)); } lua_pushboolean(L, success); return 1; } // set_armor_groups(self, groups) 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; // Do it ItemGroupList groups; read_groups(L, 2, groups); co->setArmorGroups(groups); return 0; } // get_armor_groups(self) int ObjectRef::l_get_armor_groups(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; // Do it push_groups(L, co->getArmorGroups()); return 1; } // set_physics_override(self, physics_override_speed, physics_override_jump, // physics_override_gravity, sneak, sneak_glitch, new_move) 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; // Do it if (lua_istable(L, 2)) { co->m_physics_override_speed = getfloatfield_default( L, 2, "speed", co->m_physics_override_speed); co->m_physics_override_jump = getfloatfield_default( L, 2, "jump", co->m_physics_override_jump); co->m_physics_override_gravity = getfloatfield_default( 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_new_move = getboolfield_default( L, 2, "new_move", co->m_physics_override_new_move); co->m_physics_override_sent = false; } else { // old, non-table format if (!lua_isnil(L, 2)) { co->m_physics_override_speed = lua_tonumber(L, 2); co->m_physics_override_sent = false; } if (!lua_isnil(L, 3)) { co->m_physics_override_jump = lua_tonumber(L, 3); co->m_physics_override_sent = false; } if (!lua_isnil(L, 4)) { co->m_physics_override_gravity = lua_tonumber(L, 4); co->m_physics_override_sent = false; } } return 0; } // get_physics_override(self) int ObjectRef::l_get_physics_override(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); PlayerSAO *co = (PlayerSAO *)getobject(ref); if (co == NULL) return 0; // Do it lua_newtable(L); lua_pushnumber(L, co->m_physics_override_speed); lua_setfield(L, -2, "speed"); lua_pushnumber(L, co->m_physics_override_jump); lua_setfield(L, -2, "jump"); lua_pushnumber(L, co->m_physics_override_gravity); lua_setfield(L, -2, "gravity"); lua_pushboolean(L, co->m_physics_override_sneak); lua_setfield(L, -2, "sneak"); lua_pushboolean(L, co->m_physics_override_sneak_glitch); lua_setfield(L, -2, "sneak_glitch"); lua_pushboolean(L, co->m_physics_override_new_move); lua_setfield(L, -2, "new_move"); return 1; } // set_animation(self, frame_range, frame_speed, frame_blend, frame_loop) 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; // Do it v2f frames = v2f(1, 1); if (!lua_isnil(L, 2)) frames = readParam<v2f>(L, 2); float frame_speed = 15; if (!lua_isnil(L, 3)) frame_speed = lua_tonumber(L, 3); float frame_blend = 0; if (!lua_isnil(L, 4)) frame_blend = lua_tonumber(L, 4); bool frame_loop = true; if (lua_isboolean(L, 5)) frame_loop = readParam<bool>(L, 5); co->setAnimation(frames, frame_speed, frame_blend, frame_loop); return 0; } // get_animation(self) int ObjectRef::l_get_animation(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; // Do it v2f frames = v2f(1,1); float frame_speed = 15; float frame_blend = 0; bool frame_loop = true; co->getAnimation(&frames, &frame_speed, &frame_blend, &frame_loop); push_v2f(L, frames); lua_pushnumber(L, frame_speed); lua_pushnumber(L, frame_blend); lua_pushboolean(L, frame_loop); return 4; } // set_local_animation(self, {stand/idle}, {walk}, {dig}, {walk+dig}, frame_speed) int ObjectRef::l_set_local_animation(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) 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); } float frame_speed = 30; if (!lua_isnil(L, 6)) frame_speed = lua_tonumber(L, 6); getServer(L)->setLocalPlayerAnimations(player, frames, frame_speed); lua_pushboolean(L, true); return 1; } // get_local_animation(self) int ObjectRef::l_get_local_animation(lua_State *L) { NO_MAP_LOCK_REQUIRED ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; v2s32 frames[4]; float frame_speed; player->getLocalAnimations(frames, &frame_speed); for (const v2s32 &frame : frames) { push_v2s32(L, frame); } lua_pushnumber(L, frame_speed); return 5; } // set_eye_offset(self, v3f first pv, v3f third pv) int ObjectRef::l_set_eye_offset(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; // Do it v3f offset_first = v3f(0, 0, 0); v3f offset_third = v3f(0, 0, 0); if (!lua_isnil(L, 2)) offset_first = read_v3f(L, 2); if (!lua_isnil(L, 3)) 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); /* 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 getServer(L)->setPlayerEyeOffset(player, offset_first, offset_third); lua_pushboolean(L, true); return 1; } // get_eye_offset(self) int ObjectRef::l_get_eye_offset(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; // Do it push_v3f(L, player->eye_offset_first); push_v3f(L, player->eye_offset_third); return 2; } // set_animation_frame_speed(self, frame_speed) int ObjectRef::l_set_animation_frame_speed(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; // Do it if (!lua_isnil(L, 2)) { float frame_speed = lua_tonumber(L, 2); co->setAnimationSpeed(frame_speed); lua_pushboolean(L, true); } else { lua_pushboolean(L, false); } return 1; } // set_bone_position(self, std::string bone, v3f position, v3f rotation) 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; // Do it std::string bone; if (!lua_isnil(L, 2)) bone = readParam<std::string>(L, 2); v3f position = v3f(0, 0, 0); if (!lua_isnil(L, 3)) position = check_v3f(L, 3); v3f rotation = v3f(0, 0, 0); if (!lua_isnil(L, 4)) rotation = check_v3f(L, 4); co->setBonePosition(bone, position, rotation); return 0; } // get_bone_position(self, bone) int ObjectRef::l_get_bone_position(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; // Do it std::string bone; if (!lua_isnil(L, 2)) bone = readParam<std::string>(L, 2); v3f position = v3f(0, 0, 0); v3f rotation = v3f(0, 0, 0); co->getBonePosition(bone, &position, &rotation); push_v3f(L, position); push_v3f(L, rotation); return 2; } // set_attach(self, parent, bone, position, rotation) int ObjectRef::l_set_attach(lua_State *L) { GET_ENV_PTR; ObjectRef *ref = checkobject(L, 1); ObjectRef *parent_ref = checkobject(L, 2); ServerActiveObject *co = getobject(ref); ServerActiveObject *parent = getobject(parent_ref); if (co == NULL) return 0; if (parent == NULL) return 0; // Do it int parent_id = 0; std::string bone; v3f position = v3f(0, 0, 0); v3f rotation = v3f(0, 0, 0); co->getAttachment(&parent_id, &bone, &position, &rotation); if (parent_id) { ServerActiveObject *old_parent = env->getActiveObject(parent_id); old_parent->removeAttachmentChild(co->getId()); } bone = ""; if (!lua_isnil(L, 3)) bone = readParam<std::string>(L, 3); position = v3f(0, 0, 0); if (!lua_isnil(L, 4)) position = read_v3f(L, 4); rotation = v3f(0, 0, 0); if (!lua_isnil(L, 5)) rotation = read_v3f(L, 5); co->setAttachment(parent->getId(), bone, position, rotation); parent->addAttachmentChild(co->getId()); return 0; } // get_attach(self) int ObjectRef::l_get_attach(lua_State *L) { GET_ENV_PTR; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; // Do it int parent_id = 0; std::string bone; v3f position = v3f(0, 0, 0); v3f rotation = v3f(0, 0, 0); co->getAttachment(&parent_id, &bone, &position, &rotation); if (!parent_id) return 0; ServerActiveObject *parent = env->getActiveObject(parent_id); getScriptApiBase(L)->objectrefGetOrCreate(L, parent); lua_pushlstring(L, bone.c_str(), bone.size()); push_v3f(L, position); push_v3f(L, rotation); return 4; } // set_detach(self) int ObjectRef::l_set_detach(lua_State *L) { GET_ENV_PTR; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; co->clearParentAttachment(); return 0; } // set_properties(self, properties) int ObjectRef::l_set_properties(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; ObjectProperties *prop = co->accessObjectProperties(); if (!prop) return 0; read_object_properties(L, 2, prop, getServer(L)->idef()); if (prop->hp_max < co->getHP()) { PlayerHPChangeReason reason(PlayerHPChangeReason::SET_HP); co->setHP(prop->hp_max, reason); if (co->getType() == ACTIVEOBJECT_TYPE_PLAYER) getServer(L)->SendPlayerHPOrDie((PlayerSAO *)co, reason); } co->notifyObjectPropertiesModified(); return 0; } // get_properties(self) int ObjectRef::l_get_properties(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; ObjectProperties *prop = co->accessObjectProperties(); if (!prop) return 0; push_object_properties(L, prop); return 1; } // is_player(self) int ObjectRef::l_is_player(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); lua_pushboolean(L, (player != NULL)); return 1; } // set_nametag_attributes(self, attributes) int ObjectRef::l_set_nametag_attributes(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; ObjectProperties *prop = co->accessObjectProperties(); if (!prop) return 0; lua_getfield(L, 2, "color"); if (!lua_isnil(L, -1)) { video::SColor color = prop->nametag_color; read_color(L, -1, &color); prop->nametag_color = color; } lua_pop(L, 1); std::string nametag = getstringfield_default(L, 2, "text", ""); prop->nametag = nametag; co->notifyObjectPropertiesModified(); lua_pushboolean(L, true); return 1; } // get_nametag_attributes(self) int ObjectRef::l_get_nametag_attributes(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; ObjectProperties *prop = co->accessObjectProperties(); if (!prop) return 0; video::SColor color = prop->nametag_color; lua_newtable(L); push_ARGB8(L, color); lua_setfield(L, -2, "color"); lua_pushstring(L, prop->nametag.c_str()); lua_setfield(L, -2, "text"); return 1; } /* LuaEntitySAO-only */ // set_velocity(self, {x=num, y=num, z=num}) 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; v3f pos = checkFloatPos(L, 2); // Do it co->setVelocity(pos); return 0; } // add_velocity(self, {x=num, y=num, z=num}) int ObjectRef::l_add_velocity(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if (!co) return 0; v3f pos = checkFloatPos(L, 2); // Do it co->addVelocity(pos); return 0; } // get_velocity(self) 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; // Do it v3f v = co->getVelocity(); pushFloatPos(L, v); return 1; } // set_acceleration(self, {x=num, y=num, z=num}) 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; // pos v3f pos = checkFloatPos(L, 2); // Do it co->setAcceleration(pos); return 0; } // get_acceleration(self) 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; // Do it v3f v = co->getAcceleration(); pushFloatPos(L, v); return 1; } // set_rotation(self, {x=num, y=num, z=num}) // Each 'num' is in radians int ObjectRef::l_set_rotation(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if (!co) return 0; v3f rotation = check_v3f(L, 2) * core::RADTODEG; co->setRotation(rotation); return 0; } // get_rotation(self) // returns: {x=num, y=num, z=num} // Each 'num' is in radians int ObjectRef::l_get_rotation(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if (!co) return 0; lua_newtable(L); v3f rotation = co->getRotation() * core::DEGTORAD; push_v3f(L, rotation); return 1; } // set_yaw(self, radians) int ObjectRef::l_set_yaw(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if (co == NULL) return 0; if (isNaN(L, 2)) throw LuaError("ObjectRef::set_yaw: NaN value is not allowed."); float yaw = readParam<float>(L, 2) * core::RADTODEG; co->setRotation(v3f(0, yaw, 0)); return 0; } // get_yaw(self) int ObjectRef::l_get_yaw(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if (!co) return 0; float yaw = co->getRotation().Y * core::DEGTORAD; lua_pushnumber(L, yaw); return 1; } // set_texture_mod(self, mod) 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; // Do it std::string mod = luaL_checkstring(L, 2); co->setTextureMod(mod); return 0; } // get_texture_mod(self) 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; // Do it std::string mod = co->getTextureMod(); lua_pushstring(L, mod.c_str()); return 1; } // set_sprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2, // select_horiz_by_yawpitch=false) 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; // Do it v2s16 p(0,0); if (!lua_isnil(L, 2)) p = readParam<v2s16>(L, 2); int num_frames = 1; if (!lua_isnil(L, 3)) num_frames = lua_tonumber(L, 3); float framelength = 0.2; if (!lua_isnil(L, 4)) framelength = lua_tonumber(L, 4); bool select_horiz_by_yawpitch = false; if (!lua_isnil(L, 5)) select_horiz_by_yawpitch = readParam<bool>(L, 5); co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch); return 0; } // DEPRECATED // get_entity_name(self) 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; // Do it std::string name = co->getName(); lua_pushstring(L, name.c_str()); return 1; } // get_luaentity(self) 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; // Do it luaentity_get(L, co->getId()); return 1; } /* Player-only */ // is_player_connected(self) int ObjectRef::l_is_player_connected(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); lua_pushboolean(L, (player != NULL && player->getPeerId() != PEER_ID_INEXISTENT)); return 1; } // get_player_name(self) int ObjectRef::l_get_player_name(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) { lua_pushlstring(L, "", 0); return 1; } // Do it lua_pushstring(L, player->getName()); return 1; } // get_player_velocity(self) int ObjectRef::l_get_player_velocity(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) { lua_pushnil(L); return 1; } // Do it push_v3f(L, player->getSpeed() / BS); return 1; } // get_look_dir(self) 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; // 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)); push_v3f(L, v); return 1; } // DEPRECATED // get_look_pitch(self) 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"); ObjectRef *ref = checkobject(L, 1); PlayerSAO* co = getplayersao(ref); if (co == NULL) return 0; // Do it lua_pushnumber(L, co->getRadLookPitchDep()); return 1; } // DEPRECATED // get_look_yaw(self) 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"); ObjectRef *ref = checkobject(L, 1); PlayerSAO* co = getplayersao(ref); if (co == NULL) return 0; // Do it lua_pushnumber(L, co->getRadYawDep()); return 1; } // get_look_pitch2(self) 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; // Do it lua_pushnumber(L, co->getRadLookPitch()); return 1; } // get_look_yaw2(self) 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; // Do it lua_pushnumber(L, co->getRadRotation().Y); return 1; } // set_look_vertical(self, radians) 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; float pitch = readParam<float>(L, 2) * core::RADTODEG; // Do it co->setLookPitchAndSend(pitch); return 1; } // set_look_horizontal(self, radians) 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; float yaw = readParam<float>(L, 2) * core::RADTODEG; // Do it co->setPlayerYawAndSend(yaw); return 1; } // DEPRECATED // set_look_pitch(self, radians) 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."); ObjectRef *ref = checkobject(L, 1); PlayerSAO* co = getplayersao(ref); if (co == NULL) return 0; float pitch = readParam<float>(L, 2) * core::RADTODEG; // Do it co->setLookPitchAndSend(pitch); return 1; } // DEPRECATED // set_look_yaw(self, radians) 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."); ObjectRef *ref = checkobject(L, 1); PlayerSAO* co = getplayersao(ref); if (co == NULL) return 0; float yaw = readParam<float>(L, 2) * core::RADTODEG; // Do it co->setPlayerYawAndSend(yaw); return 1; } // set_breath(self, breath) 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; u16 breath = luaL_checknumber(L, 2); co->setBreath(breath); return 0; } // get_breath(self) 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; // Do it u16 breath = co->getBreath(); 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."); ObjectRef *ref = checkobject(L, 1); PlayerSAO* co = getplayersao(ref); if (co == NULL) return 0; std::string attr = luaL_checkstring(L, 2); if (lua_isnil(L, 3)) { co->getMeta().removeString(attr); } else { std::string value = luaL_checkstring(L, 3); co->getMeta().setString(attr, value); } return 1; } // get_attribute(self, attribute) int ObjectRef::l_get_attribute(lua_State *L) { log_deprecated(L, "Deprecated call to get_attribute, use MetaDataRef methods instead."); ObjectRef *ref = checkobject(L, 1); PlayerSAO* co = getplayersao(ref); if (co == NULL) return 0; std::string attr = luaL_checkstring(L, 2); std::string value; if (co->getMeta().getStringToRef(attr, value)) { lua_pushstring(L, value.c_str()); return 1; } return 0; } // get_meta(self, attribute) int ObjectRef::l_get_meta(lua_State *L) { ObjectRef *ref = checkobject(L, 1); PlayerSAO *co = getplayersao(ref); if (co == NULL) return 0; PlayerMetaRef::create(L, &co->getMeta()); 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; std::string formspec = luaL_checkstring(L, 2); player->inventory_formspec = formspec; getServer(L)->reportInventoryFormspecModified(player->getName()); lua_pushboolean(L, true); return 1; } // get_inventory_formspec(self) -> formspec 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; std::string formspec = player->inventory_formspec; lua_pushlstring(L, formspec.c_str(), formspec.size()); return 1; } // set_formspec_prepend(self, formspec) int ObjectRef::l_set_formspec_prepend(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; std::string formspec = luaL_checkstring(L, 2); player->formspec_prepend = formspec; getServer(L)->reportFormspecPrependModified(player->getName()); lua_pushboolean(L, true); return 1; } // get_formspec_prepend(self) -> formspec int ObjectRef::l_get_formspec_prepend(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; std::string formspec = player->formspec_prepend; lua_pushlstring(L, formspec.c_str(), formspec.size()); return 1; } // get_player_control(self) int ObjectRef::l_get_player_control(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) { lua_pushlstring(L, "", 0); return 1; } const PlayerControl &control = player->getPlayerControl(); lua_newtable(L); lua_pushboolean(L, control.up); lua_setfield(L, -2, "up"); lua_pushboolean(L, control.down); lua_setfield(L, -2, "down"); lua_pushboolean(L, control.left); lua_setfield(L, -2, "left"); lua_pushboolean(L, control.right); lua_setfield(L, -2, "right"); lua_pushboolean(L, control.jump); lua_setfield(L, -2, "jump"); lua_pushboolean(L, control.aux1); lua_setfield(L, -2, "aux1"); lua_pushboolean(L, control.sneak); lua_setfield(L, -2, "sneak"); lua_pushboolean(L, control.LMB); lua_setfield(L, -2, "LMB"); lua_pushboolean(L, control.RMB); lua_setfield(L, -2, "RMB"); return 1; } // get_player_control_bits(self) int ObjectRef::l_get_player_control_bits(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) { lua_pushlstring(L, "", 0); return 1; } // Do it lua_pushnumber(L, player->keyPressed); return 1; } // hud_add(self, form) int ObjectRef::l_hud_add(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; HudElement *elem = new HudElement; read_hud_element(L, elem); u32 id = getServer(L)->hudAdd(player, elem); if (id == U32_MAX) { delete elem; return 0; } lua_pushnumber(L, id); return 1; } // hud_remove(self, id) int ObjectRef::l_hud_remove(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; u32 id = -1; if (!lua_isnil(L, 2)) id = lua_tonumber(L, 2); if (!getServer(L)->hudRemove(player, id)) return 0; lua_pushboolean(L, true); return 1; } // hud_change(self, id, stat, data) int ObjectRef::l_hud_change(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; u32 id = lua_isnumber(L, 2) ? lua_tonumber(L, 2) : -1; HudElement *e = player->getHud(id); if (!e) return 0; void *value = NULL; HudElementStat stat = read_hud_change(L, e, &value); getServer(L)->hudChange(player, id, stat, value); lua_pushboolean(L, true); return 1; } // hud_get(self, id) int ObjectRef::l_hud_get(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; u32 id = lua_tonumber(L, -1); HudElement *e = player->getHud(id); if (!e) return 0; push_hud_element(L, e); return 1; } // hud_set_flags(self, flags) int ObjectRef::l_hud_set_flags(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; u32 flags = 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; } } if (!getServer(L)->hudSetFlags(player, flags, mask)) return 0; lua_pushboolean(L, true); return 1; } int ObjectRef::l_hud_get_flags(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; lua_newtable(L); lua_pushboolean(L, player->hud_flags & HUD_FLAG_HOTBAR_VISIBLE); lua_setfield(L, -2, "hotbar"); lua_pushboolean(L, player->hud_flags & HUD_FLAG_HEALTHBAR_VISIBLE); lua_setfield(L, -2, "healthbar"); lua_pushboolean(L, player->hud_flags & HUD_FLAG_CROSSHAIR_VISIBLE); lua_setfield(L, -2, "crosshair"); lua_pushboolean(L, player->hud_flags & HUD_FLAG_WIELDITEM_VISIBLE); lua_setfield(L, -2, "wielditem"); lua_pushboolean(L, player->hud_flags & HUD_FLAG_BREATHBAR_VISIBLE); lua_setfield(L, -2, "breathbar"); lua_pushboolean(L, player->hud_flags & HUD_FLAG_MINIMAP_VISIBLE); lua_setfield(L, -2, "minimap"); lua_pushboolean(L, player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE); lua_setfield(L, -2, "minimap_radar"); return 1; } // hud_set_hotbar_itemcount(self, hotbar_itemcount) int ObjectRef::l_hud_set_hotbar_itemcount(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; s32 hotbar_itemcount = lua_tonumber(L, 2); if (!getServer(L)->hudSetHotbarItemcount(player, hotbar_itemcount)) return 0; lua_pushboolean(L, true); return 1; } // hud_get_hotbar_itemcount(self) int ObjectRef::l_hud_get_hotbar_itemcount(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; lua_pushnumber(L, player->getHotbarItemcount()); return 1; } // hud_set_hotbar_image(self, name) int ObjectRef::l_hud_set_hotbar_image(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; std::string name = readParam<std::string>(L, 2); getServer(L)->hudSetHotbarImage(player, name); return 1; } // hud_get_hotbar_image(self) int ObjectRef::l_hud_get_hotbar_image(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; const std::string &name = player->getHotbarImage(); lua_pushlstring(L, name.c_str(), name.size()); return 1; } // hud_set_hotbar_selected_image(self, name) int ObjectRef::l_hud_set_hotbar_selected_image(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; std::string name = readParam<std::string>(L, 2); getServer(L)->hudSetHotbarSelectedImage(player, name); return 1; } // hud_get_hotbar_selected_image(self) int ObjectRef::l_hud_get_hotbar_selected_image(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; const std::string &name = player->getHotbarSelectedImage(); lua_pushlstring(L, name.c_str(), name.size()); return 1; } // set_sky(self, bgcolor, type, list, clouds = true) int ObjectRef::l_set_sky(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; video::SColor bgcolor(255,255,255,255); read_color(L, 2, &bgcolor); std::string type = luaL_checkstring(L, 3); std::vector<std::string> params; if (lua_istable(L, 4)) { lua_pushnil(L); while (lua_next(L, 4) != 0) { // key at index -2 and value at index -1 if (lua_isstring(L, -1)) params.emplace_back(readParam<std::string>(L, -1)); else params.emplace_back(""); // removes value, keeps key for next iteration lua_pop(L, 1); } } if (type == "skybox" && params.size() != 6) throw LuaError("skybox expects 6 textures"); bool clouds = true; if (lua_isboolean(L, 5)) clouds = readParam<bool>(L, 5); getServer(L)->setSky(player, bgcolor, type, params, clouds); lua_pushboolean(L, true); return 1; } // get_sky(self) int ObjectRef::l_get_sky(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; video::SColor bgcolor(255, 255, 255, 255); std::string type; std::vector<std::string> params; bool clouds; player->getSky(&bgcolor, &type, &params, &clouds); type = type.empty() ? "regular" : type; push_ARGB8(L, bgcolor); lua_pushlstring(L, type.c_str(), type.size()); lua_newtable(L); s16 i = 1; for (const std::string &param : params) { lua_pushlstring(L, param.c_str(), param.size()); lua_rawseti(L, -2, i++); } lua_pushboolean(L, clouds); return 4; } // set_clouds(self, {density=, color=, ambient=, height=, thickness=, speed=}) int ObjectRef::l_set_clouds(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (!player) return 0; if (!lua_istable(L, 2)) return 0; CloudParams cloud_params = player->getCloudParams(); cloud_params.density = getfloatfield_default(L, 2, "density", cloud_params.density); lua_getfield(L, 2, "color"); if (!lua_isnil(L, -1)) read_color(L, -1, &cloud_params.color_bright); lua_pop(L, 1); lua_getfield(L, 2, "ambient"); if (!lua_isnil(L, -1)) 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); lua_getfield(L, 2, "speed"); if (lua_istable(L, -1)) { v2f new_speed; new_speed.X = getfloatfield_default(L, -1, "x", 0); new_speed.Y = getfloatfield_default(L, -1, "z", 0); cloud_params.speed = new_speed; } lua_pop(L, 1); getServer(L)->setClouds(player, cloud_params); lua_pushboolean(L, true); return 1; } int ObjectRef::l_get_clouds(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (!player) return 0; const CloudParams &cloud_params = player->getCloudParams(); lua_newtable(L); lua_pushnumber(L, cloud_params.density); lua_setfield(L, -2, "density"); push_ARGB8(L, cloud_params.color_bright); lua_setfield(L, -2, "color"); push_ARGB8(L, cloud_params.color_ambient); lua_setfield(L, -2, "ambient"); lua_pushnumber(L, cloud_params.height); lua_setfield(L, -2, "height"); lua_pushnumber(L, cloud_params.thickness); lua_setfield(L, -2, "thickness"); lua_newtable(L); lua_pushnumber(L, cloud_params.speed.X); lua_setfield(L, -2, "x"); lua_pushnumber(L, cloud_params.speed.Y); lua_setfield(L, -2, "y"); lua_setfield(L, -2, "speed"); return 1; } // override_day_night_ratio(self, brightness=0...1) int ObjectRef::l_override_day_night_ratio(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; bool do_override = false; float ratio = 0.0f; if (!lua_isnil(L, 2)) { do_override = true; ratio = readParam<float>(L, 2); } if (!getServer(L)->overrideDayNightRatio(player, do_override, ratio)) return 0; lua_pushboolean(L, true); return 1; } // get_day_night_ratio(self) int ObjectRef::l_get_day_night_ratio(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); if (player == NULL) return 0; bool do_override; float ratio; player->getDayNightRatio(&do_override, &ratio); if (do_override) lua_pushnumber(L, ratio); else lua_pushnil(L); return 1; } ObjectRef::ObjectRef(ServerActiveObject *object): m_object(object) { //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl; } // Creates an ObjectRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. void ObjectRef::create(lua_State *L, ServerActiveObject *object) { ObjectRef *o = new ObjectRef(object); //infostream<<"ObjectRef::create: o="<<o<<std::endl; *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); } void ObjectRef::set_null(lua_State *L) { ObjectRef *o = checkobject(L, -1); o->m_object = NULL; } void ObjectRef::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); // drop metatable markAliasDeprecated(methods); 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); } const char ObjectRef::className[] = "ObjectRef"; luaL_Reg ObjectRef::methods[] = { // ServerActiveObject luamethod(ObjectRef, remove), luamethod_aliased(ObjectRef, get_pos, getpos), luamethod_aliased(ObjectRef, set_pos, setpos), luamethod_aliased(ObjectRef, move_to, moveto), luamethod(ObjectRef, punch), luamethod(ObjectRef, right_click), luamethod(ObjectRef, set_hp), luamethod(ObjectRef, get_hp), luamethod(ObjectRef, get_inventory), luamethod(ObjectRef, get_wield_list), luamethod(ObjectRef, get_wield_index), luamethod(ObjectRef, get_wielded_item), luamethod(ObjectRef, set_wielded_item), luamethod(ObjectRef, set_armor_groups), luamethod(ObjectRef, get_armor_groups), luamethod(ObjectRef, set_animation), luamethod(ObjectRef, get_animation), luamethod(ObjectRef, set_animation_frame_speed), luamethod(ObjectRef, set_bone_position), luamethod(ObjectRef, get_bone_position), luamethod(ObjectRef, set_attach), luamethod(ObjectRef, get_attach), luamethod(ObjectRef, set_detach), luamethod(ObjectRef, set_properties), luamethod(ObjectRef, get_properties), luamethod(ObjectRef, set_nametag_attributes), luamethod(ObjectRef, get_nametag_attributes), // LuaEntitySAO-only luamethod_aliased(ObjectRef, set_velocity, setvelocity), luamethod(ObjectRef, add_velocity), luamethod_aliased(ObjectRef, get_velocity, getvelocity), luamethod_aliased(ObjectRef, set_acceleration, setacceleration), luamethod_aliased(ObjectRef, get_acceleration, getacceleration), luamethod_aliased(ObjectRef, set_yaw, setyaw), luamethod_aliased(ObjectRef, get_yaw, getyaw), luamethod(ObjectRef, set_rotation), luamethod(ObjectRef, get_rotation), luamethod_aliased(ObjectRef, set_texture_mod, settexturemod), luamethod_aliased(ObjectRef, set_sprite, setsprite), luamethod(ObjectRef, get_entity_name), luamethod(ObjectRef, get_luaentity), // Player-only luamethod(ObjectRef, is_player), luamethod(ObjectRef, is_player_connected), luamethod(ObjectRef, get_player_name), luamethod(ObjectRef, get_player_velocity), luamethod(ObjectRef, get_look_dir), luamethod(ObjectRef, get_look_pitch), luamethod(ObjectRef, get_look_yaw), luamethod(ObjectRef, get_look_vertical), luamethod(ObjectRef, get_look_horizontal), luamethod(ObjectRef, set_look_horizontal), luamethod(ObjectRef, set_look_vertical), luamethod(ObjectRef, set_look_yaw), luamethod(ObjectRef, set_look_pitch), luamethod(ObjectRef, get_breath), luamethod(ObjectRef, set_breath), luamethod(ObjectRef, get_attribute), luamethod(ObjectRef, set_attribute), luamethod(ObjectRef, get_meta), luamethod(ObjectRef, set_inventory_formspec), luamethod(ObjectRef, get_inventory_formspec), luamethod(ObjectRef, set_formspec_prepend), luamethod(ObjectRef, get_formspec_prepend), luamethod(ObjectRef, get_player_control), luamethod(ObjectRef, get_player_control_bits), luamethod(ObjectRef, set_physics_override), luamethod(ObjectRef, get_physics_override), luamethod(ObjectRef, hud_add), luamethod(ObjectRef, hud_remove), luamethod(ObjectRef, hud_change), luamethod(ObjectRef, hud_get), luamethod(ObjectRef, hud_set_flags), luamethod(ObjectRef, hud_get_flags), luamethod(ObjectRef, hud_set_hotbar_itemcount), luamethod(ObjectRef, hud_get_hotbar_itemcount), luamethod(ObjectRef, hud_set_hotbar_image), luamethod(ObjectRef, hud_get_hotbar_image), luamethod(ObjectRef, hud_set_hotbar_selected_image), luamethod(ObjectRef, hud_get_hotbar_selected_image), luamethod(ObjectRef, set_sky), luamethod(ObjectRef, get_sky), luamethod(ObjectRef, set_clouds), luamethod(ObjectRef, get_clouds), luamethod(ObjectRef, override_day_night_ratio), luamethod(ObjectRef, get_day_night_ratio), luamethod(ObjectRef, set_local_animation), luamethod(ObjectRef, get_local_animation), luamethod(ObjectRef, set_eye_offset), luamethod(ObjectRef, get_eye_offset), {0,0} };
pgimeno/minetest
src/script/lua_api/l_object.cpp
C++
mit
49,302
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" #include "irrlichttypes.h" class ServerActiveObject; class LuaEntitySAO; class PlayerSAO; class RemotePlayer; /* ObjectRef */ class ObjectRef : public ModApiBase { public: ObjectRef(ServerActiveObject *object); ~ObjectRef() = default; // Creates an ObjectRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. static void create(lua_State *L, ServerActiveObject *object); static void set_null(lua_State *L); static void Register(lua_State *L); static ObjectRef *checkobject(lua_State *L, int narg); static ServerActiveObject* getobject(ObjectRef *ref); private: ServerActiveObject *m_object = nullptr; static const char className[]; static luaL_Reg methods[]; static LuaEntitySAO* getluaobject(ObjectRef *ref); static PlayerSAO* getplayersao(ObjectRef *ref); static RemotePlayer *getplayer(ObjectRef *ref); // Exported functions // garbage collector static int gc_object(lua_State *L); // remove(self) static int l_remove(lua_State *L); // get_pos(self) // returns: {x=num, y=num, z=num} static int l_get_pos(lua_State *L); // set_pos(self, pos) static int l_set_pos(lua_State *L); // move_to(self, pos, continuous=false) static int l_move_to(lua_State *L); // punch(self, puncher, time_from_last_punch, tool_capabilities, dir) static int l_punch(lua_State *L); // right_click(self, clicker); clicker = an another ObjectRef static int l_right_click(lua_State *L); // set_hp(self, hp) // hp = number of hitpoints (2 * number of hearts) // returns: nil static int l_set_hp(lua_State *L); // get_hp(self) // returns: number of hitpoints (2 * number of hearts) // 0 if not applicable to this type of object static int l_get_hp(lua_State *L); // get_inventory(self) static int l_get_inventory(lua_State *L); // get_wield_list(self) static int l_get_wield_list(lua_State *L); // get_wield_index(self) static int l_get_wield_index(lua_State *L); // get_wielded_item(self) static int l_get_wielded_item(lua_State *L); // set_wielded_item(self, itemstack or itemstring or table or nil) static int l_set_wielded_item(lua_State *L); // set_armor_groups(self, groups) static int l_set_armor_groups(lua_State *L); // get_armor_groups(self) static int l_get_armor_groups(lua_State *L); // set_physics_override(self, physics_override_speed, physics_override_jump, // physics_override_gravity, sneak, sneak_glitch, new_move) static int l_set_physics_override(lua_State *L); // get_physics_override(self) static int l_get_physics_override(lua_State *L); // set_animation(self, frame_range, frame_speed, frame_blend, frame_loop) static int l_set_animation(lua_State *L); // set_animation_frame_speed(self, frame_speed) static int l_set_animation_frame_speed(lua_State *L); // get_animation(self) static int l_get_animation(lua_State *L); // set_bone_position(self, std::string bone, v3f position, v3f rotation) static int l_set_bone_position(lua_State *L); // get_bone_position(self, bone) static int l_get_bone_position(lua_State *L); // set_attach(self, parent, bone, position, rotation) static int l_set_attach(lua_State *L); // get_attach(self) static int l_get_attach(lua_State *L); // set_detach(self) static int l_set_detach(lua_State *L); // set_properties(self, properties) static int l_set_properties(lua_State *L); // get_properties(self) static int l_get_properties(lua_State *L); // is_player(self) static int l_is_player(lua_State *L); /* LuaEntitySAO-only */ // set_velocity(self, {x=num, y=num, z=num}) static int l_set_velocity(lua_State *L); // add_velocity(self, {x=num, y=num, z=num}) static int l_add_velocity(lua_State *L); // get_velocity(self) static int l_get_velocity(lua_State *L); // set_acceleration(self, {x=num, y=num, z=num}) static int l_set_acceleration(lua_State *L); // get_acceleration(self) static int l_get_acceleration(lua_State *L); // set_rotation(self, {x=num, y=num, z=num}) static int l_set_rotation(lua_State *L); // get_rotation(self) static int l_get_rotation(lua_State *L); // set_yaw(self, radians) static int l_set_yaw(lua_State *L); // get_yaw(self) static int l_get_yaw(lua_State *L); // set_texture_mod(self, mod) static int l_set_texture_mod(lua_State *L); // l_get_texture_mod(self) static int l_get_texture_mod(lua_State *L); // set_sprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2, // select_horiz_by_yawpitch=false) static int l_set_sprite(lua_State *L); // DEPRECATED // get_entity_name(self) static int l_get_entity_name(lua_State *L); // get_luaentity(self) static int l_get_luaentity(lua_State *L); /* Player-only */ // is_player_connected(self) static int l_is_player_connected(lua_State *L); // get_player_name(self) static int l_get_player_name(lua_State *L); // get_player_velocity(self) static int l_get_player_velocity(lua_State *L); // get_look_dir(self) static int l_get_look_dir(lua_State *L); // DEPRECATED // get_look_pitch(self) static int l_get_look_pitch(lua_State *L); // DEPRECATED // get_look_yaw(self) static int l_get_look_yaw(lua_State *L); // get_look_pitch2(self) static int l_get_look_vertical(lua_State *L); // get_look_yaw2(self) static int l_get_look_horizontal(lua_State *L); // set_look_vertical(self, radians) static int l_set_look_vertical(lua_State *L); // set_look_horizontal(self, radians) static int l_set_look_horizontal(lua_State *L); // DEPRECATED // set_look_pitch(self, radians) static int l_set_look_pitch(lua_State *L); // DEPRECATED // set_look_yaw(self, radians) static int l_set_look_yaw(lua_State *L); // set_breath(self, breath) static int l_set_breath(lua_State *L); // get_breath(self, breath) static int l_get_breath(lua_State *L); // set_attribute(self, attribute, value) static int l_set_attribute(lua_State *L); // get_attribute(self, attribute) static int l_get_attribute(lua_State *L); // get_meta(self) static int l_get_meta(lua_State *L); // set_inventory_formspec(self, formspec) static int l_set_inventory_formspec(lua_State *L); // get_inventory_formspec(self) -> formspec static int l_get_inventory_formspec(lua_State *L); // set_formspec_prepend(self, formspec) static int l_set_formspec_prepend(lua_State *L); // get_formspec_prepend(self) -> formspec static int l_get_formspec_prepend(lua_State *L); // get_player_control(self) static int l_get_player_control(lua_State *L); // get_player_control_bits(self) static int l_get_player_control_bits(lua_State *L); // hud_add(self, id, form) static int l_hud_add(lua_State *L); // hud_rm(self, id) static int l_hud_remove(lua_State *L); // hud_change(self, id, stat, data) static int l_hud_change(lua_State *L); // hud_get_next_id(self) static u32 hud_get_next_id(lua_State *L); // hud_get(self, id) static int l_hud_get(lua_State *L); // hud_set_flags(self, flags) static int l_hud_set_flags(lua_State *L); // hud_get_flags() static int l_hud_get_flags(lua_State *L); // hud_set_hotbar_itemcount(self, hotbar_itemcount) static int l_hud_set_hotbar_itemcount(lua_State *L); // hud_get_hotbar_itemcount(self) static int l_hud_get_hotbar_itemcount(lua_State *L); // hud_set_hotbar_image(self, name) static int l_hud_set_hotbar_image(lua_State *L); // hud_get_hotbar_image(self) static int l_hud_get_hotbar_image(lua_State *L); // hud_set_hotbar_selected_image(self, name) static int l_hud_set_hotbar_selected_image(lua_State *L); // hud_get_hotbar_selected_image(self) static int l_hud_get_hotbar_selected_image(lua_State *L); // set_sky(self, bgcolor, type, list, clouds = true) static int l_set_sky(lua_State *L); // get_sky(self) static int l_get_sky(lua_State *L); // set_clouds(self, {density=, color=, ambient=, height=, thickness=, speed=}) static int l_set_clouds(lua_State *L); // get_clouds(self) static int l_get_clouds(lua_State *L); // override_day_night_ratio(self, type) static int l_override_day_night_ratio(lua_State *L); // get_day_night_ratio(self) static int l_get_day_night_ratio(lua_State *L); // set_local_animation(self, {stand/idle}, {walk}, {dig}, {walk+dig}, frame_speed) static int l_set_local_animation(lua_State *L); // get_local_animation(self) static int l_get_local_animation(lua_State *L); // set_eye_offset(self, v3f first pv, v3f third pv) static int l_set_eye_offset(lua_State *L); // get_eye_offset(self) static int l_get_eye_offset(lua_State *L); // set_nametag_attributes(self, attributes) static int l_set_nametag_attributes(lua_State *L); // get_nametag_attributes(self) static int l_get_nametag_attributes(lua_State *L); };
pgimeno/minetest
src/script/lua_api/l_object.h
C++
mit
9,551
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_particles.h" #include "lua_api/l_object.h" #include "lua_api/l_internal.h" #include "common/c_converter.h" #include "common/c_content.h" #include "server.h" #include "client/particles.h" // add_particle({pos=, velocity=, acceleration=, expirationtime=, // size=, collisiondetection=, collision_removal=, object_collision=, // vertical=, texture=, player=}) // pos/velocity/acceleration = {x=num, y=num, z=num} // expirationtime = num (seconds) // size = num // collisiondetection = bool // collision_removal = bool // object_collision = bool // vertical = bool // texture = e.g."default_wood.png" // animation = TileAnimation definition // glow = num int ModApiParticles::l_add_particle(lua_State *L) { MAP_LOCK_REQUIRED; // Get parameters v3f pos, vel, acc; float expirationtime, size; expirationtime = size = 1; bool collisiondetection, vertical, collision_removal, object_collision; collisiondetection = vertical = collision_removal = object_collision = false; struct TileAnimationParams animation; animation.type = TAT_NONE; std::string texture; std::string playername; u8 glow = 0; if (lua_gettop(L) > 1) // deprecated { log_deprecated(L, "Deprecated add_particle call with individual parameters instead of definition"); pos = check_v3f(L, 1); vel = check_v3f(L, 2); acc = check_v3f(L, 3); expirationtime = luaL_checknumber(L, 4); size = luaL_checknumber(L, 5); collisiondetection = readParam<bool>(L, 6); 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)) { lua_getfield(L, 1, "pos"); pos = lua_istable(L, -1) ? check_v3f(L, -1) : v3f(); lua_pop(L, 1); lua_getfield(L, 1, "vel"); if (lua_istable(L, -1)) { vel = check_v3f(L, -1); log_deprecated(L, "The use of vel is deprecated. " "Use velocity instead"); } lua_pop(L, 1); lua_getfield(L, 1, "velocity"); vel = lua_istable(L, -1) ? check_v3f(L, -1) : vel; lua_pop(L, 1); lua_getfield(L, 1, "acc"); if (lua_istable(L, -1)) { acc = check_v3f(L, -1); log_deprecated(L, "The use of acc is deprecated. " "Use acceleration instead"); } lua_pop(L, 1); lua_getfield(L, 1, "acceleration"); acc = lua_istable(L, -1) ? check_v3f(L, -1) : acc; lua_pop(L, 1); expirationtime = getfloatfield_default(L, 1, "expirationtime", 1); size = getfloatfield_default(L, 1, "size", 1); collisiondetection = getboolfield_default(L, 1, "collisiondetection", collisiondetection); collision_removal = getboolfield_default(L, 1, "collision_removal", collision_removal); object_collision = getboolfield_default(L, 1, "object_collision", object_collision); vertical = getboolfield_default(L, 1, "vertical", vertical); lua_getfield(L, 1, "animation"); animation = read_animation_definition(L, -1); lua_pop(L, 1); texture = getstringfield_default(L, 1, "texture", ""); playername = getstringfield_default(L, 1, "playername", ""); glow = getintfield_default(L, 1, "glow", 0); } getServer(L)->spawnParticle(playername, pos, vel, acc, expirationtime, size, collisiondetection, collision_removal, object_collision, vertical, texture, animation, glow); return 1; } // add_particlespawner({amount=, time=, // minpos=, maxpos=, // minvel=, maxvel=, // minacc=, maxacc=, // minexptime=, maxexptime=, // minsize=, maxsize=, // collisiondetection=, // collision_removal=, // object_collision=, // vertical=, // texture=, // player=}) // minpos/maxpos/minvel/maxvel/minacc/maxacc = {x=num, y=num, z=num} // minexptime/maxexptime = num (seconds) // minsize/maxsize = num // collisiondetection = bool // collision_removal = bool // object_collision = bool // vertical = bool // texture = e.g."default_wood.png" // animation = TileAnimation definition // glow = num int ModApiParticles::l_add_particlespawner(lua_State *L) { MAP_LOCK_REQUIRED; // Get parameters u16 amount = 1; v3f minpos, maxpos, minvel, maxvel, minacc, maxacc; float time, minexptime, maxexptime, minsize, maxsize; time = minexptime = maxexptime = minsize = maxsize = 1; bool collisiondetection, vertical, collision_removal, object_collision; collisiondetection = vertical = collision_removal = object_collision = false; struct TileAnimationParams animation; animation.type = TAT_NONE; ServerActiveObject *attached = NULL; std::string texture; std::string playername; u8 glow = 0; if (lua_gettop(L) > 1) //deprecated { log_deprecated(L,"Deprecated add_particlespawner call with individual parameters instead of definition"); amount = luaL_checknumber(L, 1); time = luaL_checknumber(L, 2); minpos = check_v3f(L, 3); maxpos = check_v3f(L, 4); minvel = check_v3f(L, 5); maxvel = check_v3f(L, 6); minacc = check_v3f(L, 7); maxacc = check_v3f(L, 8); minexptime = luaL_checknumber(L, 9); maxexptime = luaL_checknumber(L, 10); minsize = luaL_checknumber(L, 11); maxsize = luaL_checknumber(L, 12); collisiondetection = readParam<bool>(L, 13); 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)) { amount = getintfield_default(L, 1, "amount", amount); time = getfloatfield_default(L, 1, "time", time); lua_getfield(L, 1, "minpos"); minpos = lua_istable(L, -1) ? check_v3f(L, -1) : minpos; lua_pop(L, 1); lua_getfield(L, 1, "maxpos"); maxpos = lua_istable(L, -1) ? check_v3f(L, -1) : maxpos; lua_pop(L, 1); lua_getfield(L, 1, "minvel"); minvel = lua_istable(L, -1) ? check_v3f(L, -1) : minvel; lua_pop(L, 1); lua_getfield(L, 1, "maxvel"); maxvel = lua_istable(L, -1) ? check_v3f(L, -1) : maxvel; lua_pop(L, 1); lua_getfield(L, 1, "minacc"); minacc = lua_istable(L, -1) ? check_v3f(L, -1) : minacc; lua_pop(L, 1); lua_getfield(L, 1, "maxacc"); maxacc = lua_istable(L, -1) ? check_v3f(L, -1) : maxacc; lua_pop(L, 1); minexptime = getfloatfield_default(L, 1, "minexptime", minexptime); maxexptime = getfloatfield_default(L, 1, "maxexptime", maxexptime); minsize = getfloatfield_default(L, 1, "minsize", minsize); maxsize = getfloatfield_default(L, 1, "maxsize", maxsize); collisiondetection = getboolfield_default(L, 1, "collisiondetection", collisiondetection); collision_removal = getboolfield_default(L, 1, "collision_removal", collision_removal); object_collision = getboolfield_default(L, 1, "object_collision", object_collision); lua_getfield(L, 1, "animation"); animation = read_animation_definition(L, -1); lua_pop(L, 1); lua_getfield(L, 1, "attached"); if (!lua_isnil(L, -1)) { ObjectRef *ref = ObjectRef::checkobject(L, -1); lua_pop(L, 1); attached = ObjectRef::getobject(ref); } vertical = getboolfield_default(L, 1, "vertical", vertical); texture = getstringfield_default(L, 1, "texture", ""); playername = getstringfield_default(L, 1, "playername", ""); glow = getintfield_default(L, 1, "glow", 0); } u32 id = getServer(L)->addParticleSpawner(amount, time, minpos, maxpos, minvel, maxvel, minacc, maxacc, minexptime, maxexptime, minsize, maxsize, collisiondetection, collision_removal, object_collision, attached, vertical, texture, playername, animation, glow); lua_pushnumber(L, id); return 1; } // delete_particlespawner(id, player) // player (string) is optional int ModApiParticles::l_delete_particlespawner(lua_State *L) { MAP_LOCK_REQUIRED; // Get parameters u32 id = luaL_checknumber(L, 1); std::string playername; if (lua_gettop(L) == 2) { playername = luaL_checkstring(L, 2); } getServer(L)->deleteParticleSpawner(playername, id); return 1; } void ModApiParticles::Initialize(lua_State *L, int top) { API_FCT(add_particle); API_FCT(add_particlespawner); API_FCT(delete_particlespawner); }
pgimeno/minetest
src/script/lua_api/l_particles.cpp
C++
mit
8,704
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" class ModApiParticles : public ModApiBase { private: static int l_add_particle(lua_State *L); static int l_add_particlespawner(lua_State *L); static int l_delete_particlespawner(lua_State *L); public: static void Initialize(lua_State *L, int top); };
pgimeno/minetest
src/script/lua_api/l_particles.h
C++
mit
1,084
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 red-001 <red-001@outlook.ie> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_particles_local.h" #include "common/c_content.h" #include "common/c_converter.h" #include "lua_api/l_internal.h" #include "lua_api/l_object.h" #include "client/particles.h" #include "client/client.h" #include "client/clientevent.h" int ModApiParticlesLocal::l_add_particle(lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); // Get parameters v3f pos, vel, acc; float expirationtime, size; bool collisiondetection, vertical, collision_removal; struct TileAnimationParams animation; animation.type = TAT_NONE; std::string texture; u8 glow; lua_getfield(L, 1, "pos"); pos = lua_istable(L, -1) ? check_v3f(L, -1) : v3f(0, 0, 0); lua_pop(L, 1); lua_getfield(L, 1, "velocity"); vel = lua_istable(L, -1) ? check_v3f(L, -1) : v3f(0, 0, 0); lua_pop(L, 1); lua_getfield(L, 1, "acceleration"); acc = lua_istable(L, -1) ? check_v3f(L, -1) : v3f(0, 0, 0); lua_pop(L, 1); expirationtime = getfloatfield_default(L, 1, "expirationtime", 1); size = getfloatfield_default(L, 1, "size", 1); collisiondetection = getboolfield_default(L, 1, "collisiondetection", false); collision_removal = getboolfield_default(L, 1, "collision_removal", false); vertical = getboolfield_default(L, 1, "vertical", false); lua_getfield(L, 1, "animation"); animation = read_animation_definition(L, -1); lua_pop(L, 1); texture = getstringfield_default(L, 1, "texture", ""); glow = getintfield_default(L, 1, "glow", 0); ClientEvent *event = new ClientEvent(); event->type = CE_SPAWN_PARTICLE; event->spawn_particle.pos = new v3f (pos); event->spawn_particle.vel = new v3f (vel); event->spawn_particle.acc = new v3f (acc); event->spawn_particle.expirationtime = expirationtime; event->spawn_particle.size = size; event->spawn_particle.collisiondetection = collisiondetection; event->spawn_particle.collision_removal = collision_removal; event->spawn_particle.vertical = vertical; event->spawn_particle.texture = new std::string(texture); event->spawn_particle.animation = animation; event->spawn_particle.glow = glow; getClient(L)->pushToEventQueue(event); return 0; } int ModApiParticlesLocal::l_add_particlespawner(lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); // Get parameters u16 amount; v3f minpos, maxpos, minvel, maxvel, minacc, maxacc; float time, minexptime, maxexptime, minsize, maxsize; bool collisiondetection, vertical, collision_removal; struct TileAnimationParams animation; animation.type = TAT_NONE; // TODO: Implement this when there is a way to get an objectref. // ServerActiveObject *attached = NULL; std::string texture; u8 glow; amount = getintfield_default(L, 1, "amount", 1); time = getfloatfield_default(L, 1, "time", 1); lua_getfield(L, 1, "minpos"); minpos = lua_istable(L, -1) ? check_v3f(L, -1) : v3f(0, 0, 0); lua_pop(L, 1); lua_getfield(L, 1, "maxpos"); maxpos = lua_istable(L, -1) ? check_v3f(L, -1) : v3f(0, 0, 0); lua_pop(L, 1); lua_getfield(L, 1, "minvel"); minvel = lua_istable(L, -1) ? check_v3f(L, -1) : v3f(0, 0, 0); lua_pop(L, 1); lua_getfield(L, 1, "maxvel"); maxvel = lua_istable(L, -1) ? check_v3f(L, -1) : v3f(0, 0, 0); lua_pop(L, 1); lua_getfield(L, 1, "minacc"); minacc = lua_istable(L, -1) ? check_v3f(L, -1) : v3f(0, 0, 0); lua_pop(L, 1); lua_getfield(L, 1, "maxacc"); maxacc = lua_istable(L, -1) ? check_v3f(L, -1) : v3f(0, 0, 0); lua_pop(L, 1); minexptime = getfloatfield_default(L, 1, "minexptime", 1); maxexptime = getfloatfield_default(L, 1, "maxexptime", 1); minsize = getfloatfield_default(L, 1, "minsize", 1); maxsize = getfloatfield_default(L, 1, "maxsize", 1); collisiondetection = getboolfield_default(L, 1, "collisiondetection", false); collision_removal = getboolfield_default(L, 1, "collision_removal", false); vertical = getboolfield_default(L, 1, "vertical", false); lua_getfield(L, 1, "animation"); animation = read_animation_definition(L, -1); lua_pop(L, 1); // TODO: Implement this when a way to get an objectref on the client is added // lua_getfield(L, 1, "attached"); // if (!lua_isnil(L, -1)) { // ObjectRef *ref = ObjectRef::checkobject(L, -1); // lua_pop(L, 1); // attached = ObjectRef::getobject(ref); // } texture = getstringfield_default(L, 1, "texture", ""); glow = getintfield_default(L, 1, "glow", 0); u64 id = getClient(L)->getParticleManager()->generateSpawnerId(); auto event = new ClientEvent(); event->type = CE_ADD_PARTICLESPAWNER; event->add_particlespawner.amount = amount; event->add_particlespawner.spawntime = time; event->add_particlespawner.minpos = new v3f (minpos); event->add_particlespawner.maxpos = new v3f (maxpos); event->add_particlespawner.minvel = new v3f (minvel); event->add_particlespawner.maxvel = new v3f (maxvel); event->add_particlespawner.minacc = new v3f (minacc); event->add_particlespawner.maxacc = new v3f (maxacc); event->add_particlespawner.minexptime = minexptime; event->add_particlespawner.maxexptime = maxexptime; event->add_particlespawner.minsize = minsize; event->add_particlespawner.maxsize = maxsize; event->add_particlespawner.collisiondetection = collisiondetection; event->add_particlespawner.collision_removal = collision_removal; event->add_particlespawner.attached_id = 0; event->add_particlespawner.vertical = vertical; event->add_particlespawner.texture = new std::string(texture); event->add_particlespawner.id = id; event->add_particlespawner.animation = animation; event->add_particlespawner.glow = glow; getClient(L)->pushToEventQueue(event); lua_pushnumber(L, id); return 1; } int ModApiParticlesLocal::l_delete_particlespawner(lua_State *L) { // Get parameters u32 id = luaL_checknumber(L, 1); ClientEvent *event = new ClientEvent(); event->type = CE_DELETE_PARTICLESPAWNER; event->delete_particlespawner.id = id; getClient(L)->pushToEventQueue(event); return 0; } void ModApiParticlesLocal::Initialize(lua_State *L, int top) { API_FCT(add_particle); API_FCT(add_particlespawner); API_FCT(delete_particlespawner); }
pgimeno/minetest
src/script/lua_api/l_particles_local.cpp
C++
mit
7,224
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 red-001 <red-001@outlook.ie> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_base.h" class ModApiParticlesLocal : public ModApiBase { private: static int l_add_particle(lua_State *L); static int l_add_particlespawner(lua_State *L); static int l_delete_particlespawner(lua_State *L); public: static void Initialize(lua_State *L, int top); };
pgimeno/minetest
src/script/lua_api/l_particles_local.h
C++
mit
1,123
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017-8 rubenwardy <rw@rubenwardy.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_playermeta.h" #include "lua_api/l_internal.h" #include "common/c_content.h" /* PlayerMetaRef */ PlayerMetaRef *PlayerMetaRef::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 *(PlayerMetaRef **)ud; // unbox pointer } Metadata *PlayerMetaRef::getmeta(bool auto_create) { return metadata; } void PlayerMetaRef::clearMeta() { metadata->clear(); } void PlayerMetaRef::reportMetadataChange(const std::string *name) { // TODO } // garbage collector int PlayerMetaRef::gc_object(lua_State *L) { PlayerMetaRef *o = *(PlayerMetaRef **)(lua_touserdata(L, 1)); delete o; return 0; } // Creates an PlayerMetaRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. void PlayerMetaRef::create(lua_State *L, Metadata *metadata) { PlayerMetaRef *o = new PlayerMetaRef(metadata); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); } void PlayerMetaRef::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "metadata_class"); lua_pushlstring(L, className, strlen(className)); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pushliteral(L, "__eq"); lua_pushcfunction(L, l_equals); lua_settable(L, metatable); lua_pop(L, 1); // drop metatable luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); // Cannot be created from Lua // lua_register(L, className, create_object); } // clang-format off const char PlayerMetaRef::className[] = "PlayerMetaRef"; const luaL_Reg PlayerMetaRef::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} }; // clang-format on
pgimeno/minetest
src/script/lua_api/l_playermeta.cpp
C++
mit
3,334
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017-8 rubenwardy <rw@rubenwardy.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" #include "lua_api/l_metadata.h" #include "irrlichttypes_bloated.h" #include "inventory.h" #include "metadata.h" class PlayerMetaRef : public MetaDataRef { private: Metadata *metadata = nullptr; static const char className[]; static const luaL_Reg methods[]; static PlayerMetaRef *checkobject(lua_State *L, int narg); virtual Metadata *getmeta(bool auto_create); virtual void clearMeta(); virtual void reportMetadataChange(const std::string *name = nullptr); // garbage collector static int gc_object(lua_State *L); public: PlayerMetaRef(Metadata *metadata) : metadata(metadata) {} ~PlayerMetaRef() = default; // Creates an ItemStackMetaRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. static void create(lua_State *L, Metadata *metadata); static void Register(lua_State *L); };
pgimeno/minetest
src/script/lua_api/l_playermeta.h
C++
mit
1,735
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_rollback.h" #include "lua_api/l_internal.h" #include "common/c_converter.h" #include "server.h" #include "rollback_interface.h" void push_RollbackNode(lua_State *L, RollbackNode &node) { lua_createtable(L, 0, 3); lua_pushstring(L, node.name.c_str()); lua_setfield(L, -2, "name"); lua_pushnumber(L, node.param1); lua_setfield(L, -2, "param1"); lua_pushnumber(L, node.param2); lua_setfield(L, -2, "param2"); } // 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); int limit = luaL_checknumber(L, 4); Server *server = getServer(L); IRollbackManager *rollback = server->getRollbackManager(); if (rollback == NULL) { return 0; } std::list<RollbackAction> actions = rollback->getNodeActors(pos, range, seconds, limit); std::list<RollbackAction>::iterator iter = actions.begin(); lua_createtable(L, actions.size(), 0); for (unsigned int i = 1; iter != actions.end(); ++iter, ++i) { lua_createtable(L, 0, 5); // Make a table with enough space pre-allocated lua_pushstring(L, iter->actor.c_str()); lua_setfield(L, -2, "actor"); push_v3s16(L, iter->p); lua_setfield(L, -2, "pos"); lua_pushnumber(L, iter->unix_time); lua_setfield(L, -2, "time"); push_RollbackNode(L, iter->n_old); lua_setfield(L, -2, "oldnode"); push_RollbackNode(L, iter->n_new); lua_setfield(L, -2, "newnode"); lua_rawseti(L, -2, i); // Add action table to main table } return 1; } // rollback_revert_actions_by(actor, seconds) -> bool, log messages int ModApiRollback::l_rollback_revert_actions_by(lua_State *L) { MAP_LOCK_REQUIRED; std::string actor = luaL_checkstring(L, 1); int seconds = luaL_checknumber(L, 2); Server *server = getServer(L); IRollbackManager *rollback = server->getRollbackManager(); // If rollback is disabled, tell it's not a success. if (rollback == NULL) { lua_pushboolean(L, false); lua_newtable(L); return 2; } std::list<RollbackAction> actions = rollback->getRevertActions(actor, seconds); std::list<std::string> log; bool success = server->rollbackRevertActions(actions, &log); // Push boolean result lua_pushboolean(L, success); lua_createtable(L, log.size(), 0); unsigned long i = 0; for(std::list<std::string>::const_iterator iter = log.begin(); iter != log.end(); ++i, ++iter) { lua_pushnumber(L, i); lua_pushstring(L, iter->c_str()); lua_settable(L, -3); } return 2; } void ModApiRollback::Initialize(lua_State *L, int top) { API_FCT(rollback_get_node_actions); API_FCT(rollback_revert_actions_by); }
pgimeno/minetest
src/script/lua_api/l_rollback.cpp
C++
mit
3,552
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" class ModApiRollback : public ModApiBase { private: // 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 static int l_rollback_revert_actions_by(lua_State *L); public: static void Initialize(lua_State *L, int top); };
pgimeno/minetest
src/script/lua_api/l_rollback.h
C++
mit
1,219
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_server.h" #include "lua_api/l_internal.h" #include "common/c_converter.h" #include "common/c_content.h" #include "cpp_api/s_base.h" #include "server.h" #include "environment.h" #include "remoteplayer.h" #include "log.h" #include <algorithm> // request_shutdown() int ModApiServer::l_request_shutdown(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *msg = lua_tolstring(L, 1, NULL); bool reconnect = readParam<bool>(L, 2); float seconds_before_shutdown = lua_tonumber(L, 3); getServer(L)->requestShutdown(msg ? msg : "", reconnect, seconds_before_shutdown); return 0; } // get_server_status() int ModApiServer::l_get_server_status(lua_State *L) { NO_MAP_LOCK_REQUIRED; lua_pushstring(L, wide_to_narrow(getServer(L)->getStatusString()).c_str()); return 1; } // get_server_uptime() int ModApiServer::l_get_server_uptime(lua_State *L) { NO_MAP_LOCK_REQUIRED; lua_pushnumber(L, getServer(L)->getUptime()); return 1; } // print(text) int ModApiServer::l_print(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string text; text = luaL_checkstring(L, 1); getServer(L)->printToConsoleOnly(text); return 0; } // chat_send_all(text) int ModApiServer::l_chat_send_all(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *text = luaL_checkstring(L, 1); // Get server from registry Server *server = getServer(L); // Send server->notifyPlayers(utf8_to_wide(text)); return 0; } // chat_send_player(name, text) int ModApiServer::l_chat_send_player(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *name = luaL_checkstring(L, 1); const char *text = luaL_checkstring(L, 2); // Get server from registry Server *server = getServer(L); // Send server->notifyPlayer(name, utf8_to_wide(text)); return 0; } // get_player_privs(name, text) int ModApiServer::l_get_player_privs(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *name = luaL_checkstring(L, 1); // Get server from registry Server *server = getServer(L); // Do it lua_newtable(L); int table = lua_gettop(L); std::set<std::string> privs_s = server->getPlayerEffectivePrivs(name); for (const std::string &privs_ : privs_s) { lua_pushboolean(L, true); lua_setfield(L, table, privs_.c_str()); } lua_pushvalue(L, table); return 1; } // get_player_ip() int ModApiServer::l_get_player_ip(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char * name = luaL_checkstring(L, 1); RemotePlayer *player = dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name); if(player == NULL) { lua_pushnil(L); // no such player return 1; } try { Address addr = getServer(L)->getPeerAddress(player->getPeerId()); std::string ip_str = addr.serializeString(); lua_pushstring(L, ip_str.c_str()); return 1; } catch (const con::PeerNotFoundException &) { dstream << FUNCTION_NAME << ": peer was not found" << std::endl; lua_pushnil(L); // error return 1; } } // get_player_information(name) int ModApiServer::l_get_player_information(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char * name = luaL_checkstring(L, 1); RemotePlayer *player = dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name); if (player == NULL) { lua_pushnil(L); // no such player return 1; } Address addr; try { addr = getServer(L)->getPeerAddress(player->getPeerId()); } catch(const con::PeerNotFoundException &) { dstream << FUNCTION_NAME << ": peer was not found" << std::endl; lua_pushnil(L); // error return 1; } float min_rtt,max_rtt,avg_rtt,min_jitter,max_jitter,avg_jitter; ClientState state; u32 uptime; u16 prot_vers; u8 ser_vers,major,minor,patch; std::string vers_string; #define ERET(code) \ if (!(code)) { \ dstream << FUNCTION_NAME << ": peer was not found" << std::endl; \ lua_pushnil(L); /* error */ \ return 1; \ } ERET(getServer(L)->getClientConInfo(player->getPeerId(), con::MIN_RTT, &min_rtt)) ERET(getServer(L)->getClientConInfo(player->getPeerId(), con::MAX_RTT, &max_rtt)) ERET(getServer(L)->getClientConInfo(player->getPeerId(), con::AVG_RTT, &avg_rtt)) ERET(getServer(L)->getClientConInfo(player->getPeerId(), con::MIN_JITTER, &min_jitter)) ERET(getServer(L)->getClientConInfo(player->getPeerId(), con::MAX_JITTER, &max_jitter)) ERET(getServer(L)->getClientConInfo(player->getPeerId(), con::AVG_JITTER, &avg_jitter)) ERET(getServer(L)->getClientInfo(player->getPeerId(), &state, &uptime, &ser_vers, &prot_vers, &major, &minor, &patch, &vers_string)) lua_newtable(L); int table = lua_gettop(L); lua_pushstring(L,"address"); lua_pushstring(L, addr.serializeString().c_str()); lua_settable(L, table); lua_pushstring(L,"ip_version"); if (addr.getFamily() == AF_INET) { lua_pushnumber(L, 4); } else if (addr.getFamily() == AF_INET6) { lua_pushnumber(L, 6); } else { lua_pushnumber(L, 0); } lua_settable(L, table); lua_pushstring(L,"min_rtt"); lua_pushnumber(L, min_rtt); lua_settable(L, table); lua_pushstring(L,"max_rtt"); lua_pushnumber(L, max_rtt); lua_settable(L, table); lua_pushstring(L,"avg_rtt"); lua_pushnumber(L, avg_rtt); lua_settable(L, table); lua_pushstring(L,"min_jitter"); lua_pushnumber(L, min_jitter); lua_settable(L, table); lua_pushstring(L,"max_jitter"); lua_pushnumber(L, max_jitter); lua_settable(L, table); lua_pushstring(L,"avg_jitter"); lua_pushnumber(L, avg_jitter); lua_settable(L, table); lua_pushstring(L,"connection_uptime"); lua_pushnumber(L, uptime); lua_settable(L, table); lua_pushstring(L,"protocol_version"); lua_pushnumber(L, prot_vers); lua_settable(L, table); #ifndef NDEBUG lua_pushstring(L,"serialization_version"); lua_pushnumber(L, ser_vers); lua_settable(L, table); lua_pushstring(L,"major"); lua_pushnumber(L, major); lua_settable(L, table); lua_pushstring(L,"minor"); lua_pushnumber(L, minor); lua_settable(L, table); lua_pushstring(L,"patch"); lua_pushnumber(L, patch); lua_settable(L, table); 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_settable(L, table); #endif #undef ERET return 1; } // get_ban_list() int ModApiServer::l_get_ban_list(lua_State *L) { NO_MAP_LOCK_REQUIRED; lua_pushstring(L, getServer(L)->getBanDescription("").c_str()); return 1; } // get_ban_description() 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()); return 1; } // ban_player() int ModApiServer::l_ban_player(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char * name = luaL_checkstring(L, 1); RemotePlayer *player = dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name); if (player == NULL) { lua_pushboolean(L, false); // no such player return 1; } try { Address addr = getServer(L)->getPeerAddress( dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name)->getPeerId()); std::string ip_str = addr.serializeString(); getServer(L)->setIpBanned(ip_str, name); } catch(const con::PeerNotFoundException &) { dstream << FUNCTION_NAME << ": peer was not found" << std::endl; lua_pushboolean(L, false); // error return 1; } lua_pushboolean(L, true); return 1; } // kick_player(name, [reason]) -> success int ModApiServer::l_kick_player(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *name = luaL_checkstring(L, 1); std::string message("Kicked"); if (lua_isstring(L, 2)) message.append(": ").append(readParam<std::string>(L, 2)); else message.append("."); RemotePlayer *player = dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name); if (player == NULL) { lua_pushboolean(L, false); // No such player return 1; } getServer(L)->DenyAccess_Legacy(player->getPeerId(), utf8_to_wide(message)); lua_pushboolean(L, true); return 1; } int ModApiServer::l_remove_player(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string name = luaL_checkstring(L, 1); ServerEnvironment *s_env = dynamic_cast<ServerEnvironment *>(getEnv(L)); assert(s_env); RemotePlayer *player = s_env->getPlayer(name.c_str()); if (!player) lua_pushinteger(L, s_env->removePlayerFromDatabase(name) ? 0 : 1); else lua_pushinteger(L, 2); return 1; } // unban_player_or_ip() int ModApiServer::l_unban_player_or_ip(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char * ip_or_name = luaL_checkstring(L, 1); getServer(L)->unsetIpBanned(ip_or_name); lua_pushboolean(L, true); return 1; } // show_formspec(playername,formname,formspec) int ModApiServer::l_show_formspec(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *playername = luaL_checkstring(L, 1); const char *formname = luaL_checkstring(L, 2); const char *formspec = luaL_checkstring(L, 3); if(getServer(L)->showFormspec(playername,formspec,formname)) { lua_pushboolean(L, true); }else{ lua_pushboolean(L, false); } return 1; } // get_current_modname() int ModApiServer::l_get_current_modname(lua_State *L) { NO_MAP_LOCK_REQUIRED; lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME); return 1; } // get_modpath(modname) int ModApiServer::l_get_modpath(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string modname = luaL_checkstring(L, 1); const ModSpec *mod = getServer(L)->getModSpec(modname); if (!mod) { lua_pushnil(L); return 1; } lua_pushstring(L, mod->path.c_str()); return 1; } // get_modnames() // the returned list is sorted alphabetically for you int ModApiServer::l_get_modnames(lua_State *L) { NO_MAP_LOCK_REQUIRED; // Get a list of mods std::vector<std::string> modlist; getServer(L)->getModNames(modlist); // Take unsorted items from mods_unsorted and sort them into // mods_sorted; not great performance but the number of mods on a // server will likely be small. std::sort(modlist.begin(), modlist.end()); // Package them up for Lua lua_createtable(L, modlist.size(), 0); std::vector<std::string>::iterator iter = modlist.begin(); for (u16 i = 0; iter != modlist.end(); ++iter) { lua_pushstring(L, iter->c_str()); lua_rawseti(L, -2, ++i); } return 1; } // get_worldpath() int ModApiServer::l_get_worldpath(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string worldpath = getServer(L)->getWorldPath(); lua_pushstring(L, worldpath.c_str()); return 1; } // sound_play(spec, parameters) int ModApiServer::l_sound_play(lua_State *L) { NO_MAP_LOCK_REQUIRED; SimpleSoundSpec spec; read_soundspec(L, 1, spec); ServerSoundParams params; read_server_sound_params(L, 2, params); s32 handle = getServer(L)->playSound(spec, params); lua_pushinteger(L, handle); return 1; } // sound_stop(handle) int ModApiServer::l_sound_stop(lua_State *L) { NO_MAP_LOCK_REQUIRED; int handle = luaL_checkinteger(L, 1); getServer(L)->stopSound(handle); return 0; } int ModApiServer::l_sound_fade(lua_State *L) { NO_MAP_LOCK_REQUIRED; s32 handle = luaL_checkinteger(L, 1); float step = readParam<float>(L, 2); float gain = readParam<float>(L, 3); getServer(L)->fadeSound(handle, step, gain); return 0; } // is_singleplayer() int ModApiServer::l_is_singleplayer(lua_State *L) { NO_MAP_LOCK_REQUIRED; lua_pushboolean(L, getServer(L)->isSingleplayer()); return 1; } // notify_authentication_modified(name) int ModApiServer::l_notify_authentication_modified(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string name; if(lua_isstring(L, 1)) name = readParam<std::string>(L, 1); getServer(L)->reportPrivsModified(name); return 0; } // get_last_run_mod() int ModApiServer::l_get_last_run_mod(lua_State *L) { NO_MAP_LOCK_REQUIRED; lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME); std::string current_mod = readParam<std::string>(L, -1, ""); if (current_mod.empty()) { lua_pop(L, 1); lua_pushstring(L, getScriptApiBase(L)->getOrigin().c_str()); } return 1; } // set_last_run_mod(modname) int ModApiServer::l_set_last_run_mod(lua_State *L) { NO_MAP_LOCK_REQUIRED; #ifdef SCRIPTAPI_DEBUG const char *mod = lua_tostring(L, 1); getScriptApiBase(L)->setOriginDirect(mod); //printf(">>>> last mod set from Lua: %s\n", mod); #endif return 0; } void ModApiServer::Initialize(lua_State *L, int top) { API_FCT(request_shutdown); API_FCT(get_server_status); API_FCT(get_server_uptime); API_FCT(get_worldpath); API_FCT(is_singleplayer); API_FCT(get_current_modname); API_FCT(get_modpath); API_FCT(get_modnames); API_FCT(print); API_FCT(chat_send_all); API_FCT(chat_send_player); API_FCT(show_formspec); API_FCT(sound_play); API_FCT(sound_stop); API_FCT(sound_fade); API_FCT(get_player_information); API_FCT(get_player_privs); API_FCT(get_player_ip); API_FCT(get_ban_list); API_FCT(get_ban_description); API_FCT(ban_player); API_FCT(kick_player); API_FCT(remove_player); API_FCT(unban_player_or_ip); API_FCT(notify_authentication_modified); API_FCT(get_last_run_mod); API_FCT(set_last_run_mod); }
pgimeno/minetest
src/script/lua_api/l_server.cpp
C++
mit
13,913
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" class ModApiServer : public ModApiBase { private: // request_shutdown([message], [reconnect]) static int l_request_shutdown(lua_State *L); // get_server_status() static int l_get_server_status(lua_State *L); // get_server_uptime() static int l_get_server_uptime(lua_State *L); // get_worldpath() static int l_get_worldpath(lua_State *L); // is_singleplayer() static int l_is_singleplayer(lua_State *L); // get_current_modname() static int l_get_current_modname(lua_State *L); // get_modpath(modname) static int l_get_modpath(lua_State *L); // get_modnames() // the returned list is sorted alphabetically for you static int l_get_modnames(lua_State *L); // print(text) static int l_print(lua_State *L); // chat_send_all(text) static int l_chat_send_all(lua_State *L); // chat_send_player(name, text) static int l_chat_send_player(lua_State *L); // show_formspec(playername,formname,formspec) static int l_show_formspec(lua_State *L); // sound_play(spec, parameters) static int l_sound_play(lua_State *L); // sound_stop(handle) static int l_sound_stop(lua_State *L); // sound_fade(handle, step, gain) static int l_sound_fade(lua_State *L); // get_player_privs(name, text) static int l_get_player_privs(lua_State *L); // get_player_ip() static int l_get_player_ip(lua_State *L); // get_player_information(name) static int l_get_player_information(lua_State *L); // get_ban_list() static int l_get_ban_list(lua_State *L); // get_ban_description() static int l_get_ban_description(lua_State *L); // ban_player() static int l_ban_player(lua_State *L); // unban_player_or_ip() static int l_unban_player_or_ip(lua_State *L); // kick_player(name, [message]) -> success static int l_kick_player(lua_State *L); // remove_player(name) static int l_remove_player(lua_State *L); // notify_authentication_modified(name) static int l_notify_authentication_modified(lua_State *L); // get_last_run_mod() static int l_get_last_run_mod(lua_State *L); // set_last_run_mod(modname) static int l_set_last_run_mod(lua_State *L); public: static void Initialize(lua_State *L, int top); };
pgimeno/minetest
src/script/lua_api/l_server.h
C++
mit
2,974
/* Minetest Copyright (C) 2013 PilzAdam <pilzadam@minetest.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_settings.h" #include "lua_api/l_internal.h" #include "cpp_api/s_security.h" #include "settings.h" #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."); \ } LuaSettings::LuaSettings(Settings *settings, const std::string &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_settings = new Settings(); m_settings->readConfigFile(filename.c_str()); } LuaSettings::~LuaSettings() { if (m_is_own_settings) delete m_settings; } 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; luaL_getmetatable(L, className); lua_setmetatable(L, -2); } // garbage collector int LuaSettings::gc_object(lua_State* L) { LuaSettings* o = *(LuaSettings **)(lua_touserdata(L, 1)); delete o; return 0; } // get(self, key) -> value int LuaSettings::l_get(lua_State* L) { NO_MAP_LOCK_REQUIRED; LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); if (o->m_settings->exists(key)) { std::string value = o->m_settings->get(key); lua_pushstring(L, value.c_str()); } else { lua_pushnil(L); } return 1; } // get_bool(self, key) -> boolean int LuaSettings::l_get_bool(lua_State* L) { NO_MAP_LOCK_REQUIRED; LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); if (o->m_settings->exists(key)) { bool value = o->m_settings->getBool(key); lua_pushboolean(L, value); } else { // Push default value if (lua_isboolean(L, 3)) lua_pushboolean(L, readParam<bool>(L, 3)); else lua_pushnil(L); } return 1; } // get_np_group(self, key) -> value int LuaSettings::l_get_np_group(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaSettings *o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); if (o->m_settings->exists(key)) { NoiseParams np; o->m_settings->getNoiseParams(key, np); push_noiseparams(L, &np); } else { lua_pushnil(L); } return 1; } // set(self, key, value) int LuaSettings::l_set(lua_State* L) { NO_MAP_LOCK_REQUIRED; LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); const char* value = luaL_checkstring(L, 3); SET_SECURITY_CHECK(L, key); if (!o->m_settings->set(key, value)) throw LuaError("Invalid sequence found in setting parameters"); return 0; } // set_bool(self, key, value) int LuaSettings::l_set_bool(lua_State* L) { NO_MAP_LOCK_REQUIRED; LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); bool value = readParam<bool>(L, 3); SET_SECURITY_CHECK(L, key); o->m_settings->setBool(key, value); return 1; } // set(self, key, value) int LuaSettings::l_set_np_group(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaSettings *o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); NoiseParams value; read_noiseparams(L, 3, &value); SET_SECURITY_CHECK(L, key); o->m_settings->setNoiseParams(key, value, false); return 0; } // remove(self, key) -> success int LuaSettings::l_remove(lua_State* L) { NO_MAP_LOCK_REQUIRED; LuaSettings* o = checkobject(L, 1); std::string key = std::string(luaL_checkstring(L, 2)); SET_SECURITY_CHECK(L, key); bool success = o->m_settings->remove(key); lua_pushboolean(L, success); return 1; } // get_names(self) -> {key1, ...} int LuaSettings::l_get_names(lua_State* L) { NO_MAP_LOCK_REQUIRED; LuaSettings* o = checkobject(L, 1); std::vector<std::string> keys = o->m_settings->getNames(); lua_newtable(L); for (unsigned int i=0; i < keys.size(); i++) { lua_pushstring(L, keys[i].c_str()); lua_rawseti(L, -2, i + 1); } return 1; } // write(self) -> success int LuaSettings::l_write(lua_State* L) { NO_MAP_LOCK_REQUIRED; LuaSettings* o = checkobject(L, 1); if (!o->m_write_allowed) { throw LuaError("Settings: writing " + o->m_filename + " not allowed with mod security on."); } bool success = o->m_settings->updateConfigFile(o->m_filename.c_str()); lua_pushboolean(L, success); return 1; } // to_table(self) -> {[key1]=value1,...} int LuaSettings::l_to_table(lua_State* L) { NO_MAP_LOCK_REQUIRED; LuaSettings* o = checkobject(L, 1); std::vector<std::string> keys = o->m_settings->getNames(); lua_newtable(L); for (const std::string &key : keys) { lua_pushstring(L, o->m_settings->get(key).c_str()); lua_setfield(L, -2, key.c_str()); } return 1; } void LuaSettings::Register(lua_State* L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); // drop metatable 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); } // LuaSettings(filename) // Creates a LuaSettings and leaves it on top of the stack int LuaSettings::create_object(lua_State* L) { NO_MAP_LOCK_REQUIRED; bool write_allowed = true; const char* filename = luaL_checkstring(L, 1); CHECK_SECURE_PATH_POSSIBLE_WRITE(L, 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) { 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 } const char LuaSettings::className[] = "Settings"; const luaL_Reg LuaSettings::methods[] = { luamethod(LuaSettings, get), luamethod(LuaSettings, get_bool), luamethod(LuaSettings, get_np_group), 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} };
pgimeno/minetest
src/script/lua_api/l_settings.cpp
C++
mit
7,522
/* Minetest Copyright (C) 2013 PilzAdam <pilzadam@minetest.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "common/c_content.h" #include "lua_api/l_base.h" class Settings; class LuaSettings : public ModApiBase { private: static const char className[]; static const luaL_Reg methods[]; // garbage collector static int gc_object(lua_State *L); // get(self, key) -> value static int l_get(lua_State *L); // get_bool(self, key) -> boolean static int l_get_bool(lua_State *L); // get_np_group(self, key) -> noiseparam static int l_get_np_group(lua_State *L); // set(self, key, value) static int l_set(lua_State *L); // set_bool(self, key, value) static int l_set_bool(lua_State *L); // set_np_group(self, key, value) static int l_set_np_group(lua_State *L); // remove(self, key) -> success static int l_remove(lua_State *L); // get_names(self) -> {key1, ...} static int l_get_names(lua_State *L); // write(self) -> success static int l_write(lua_State *L); // to_table(self) -> {[key1]=value1,...} static int l_to_table(lua_State *L); Settings *m_settings = nullptr; std::string m_filename; bool m_is_own_settings = false; bool m_write_allowed = true; public: LuaSettings(Settings *settings, const std::string &filename); LuaSettings(const std::string &filename, bool write_allowed); ~LuaSettings(); static void create(lua_State *L, Settings *settings, const std::string &filename); // LuaSettings(filename) // Creates a LuaSettings and leaves it on top of the stack static int create_object(lua_State *L); static LuaSettings *checkobject(lua_State *L, int narg); static void Register(lua_State *L); };
pgimeno/minetest
src/script/lua_api/l_settings.h
C++
mit
2,342
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "l_sound.h" #include "l_internal.h" #include "common/c_content.h" #include "gui/guiEngine.h" int ModApiSound::l_sound_play(lua_State *L) { SimpleSoundSpec spec; read_soundspec(L, 1, spec); bool looped = readParam<bool>(L, 2); s32 handle = getGuiEngine(L)->playSound(spec, looped); lua_pushinteger(L, handle); return 1; } int ModApiSound::l_sound_stop(lua_State *L) { u32 handle = luaL_checkinteger(L, 1); getGuiEngine(L)->stopSound(handle); return 1; } void ModApiSound::Initialize(lua_State *L, int top) { API_FCT(sound_play); API_FCT(sound_stop); }
pgimeno/minetest
src/script/lua_api/l_sound.cpp
C++
mit
1,434
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" class ModApiSound : public ModApiBase { private: static int l_sound_play(lua_State *L); static int l_sound_stop(lua_State *L); public: static void Initialize(lua_State *L, int top); };
pgimeno/minetest
src/script/lua_api/l_sound.h
C++
mit
1,086
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_storage.h" #include "l_internal.h" #include "content/mods.h" #include "server.h" int ModApiStorage::l_get_mod_storage(lua_State *L) { lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME); if (!lua_isstring(L, -1)) { return 0; } std::string mod_name = readParam<std::string>(L, -1); ModMetadata *store = new ModMetadata(mod_name); if (IGameDef *gamedef = getGameDef(L)) { store->load(gamedef->getModStoragePath()); gamedef->registerModStorage(store); } else { delete store; assert(false); // this should not happen } StorageRef::create(L, store); int object = lua_gettop(L); lua_pushvalue(L, object); return 1; } void ModApiStorage::Initialize(lua_State *L, int top) { API_FCT(get_mod_storage); } StorageRef::StorageRef(ModMetadata *object): m_object(object) { } StorageRef::~StorageRef() { delete m_object; } void StorageRef::create(lua_State *L, ModMetadata *object) { StorageRef *o = new StorageRef(object); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); } int StorageRef::gc_object(lua_State *L) { StorageRef *o = *(StorageRef **)(lua_touserdata(L, 1)); // Server side if (IGameDef *gamedef = getGameDef(L)) gamedef->unregisterModStorage(getobject(o)->getModName()); delete o; return 0; } void StorageRef::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "metadata_class"); lua_pushlstring(L, className, strlen(className)); lua_settable(L, metatable); lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pushliteral(L, "__eq"); lua_pushcfunction(L, l_equals); lua_settable(L, metatable); lua_pop(L, 1); // drop metatable luaL_openlib(L, 0, methods, 0); // fill methodtable lua_pop(L, 1); // drop methodtable } 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 } ModMetadata* StorageRef::getobject(StorageRef *ref) { ModMetadata *co = ref->m_object; return co; } Metadata* StorageRef::getmeta(bool auto_create) { return m_object; } void StorageRef::clearMeta() { m_object->clear(); } 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} };
pgimeno/minetest
src/script/lua_api/l_storage.cpp
C++
mit
3,977
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "l_metadata.h" #include "lua_api/l_base.h" class ModMetadata; class ModApiStorage : public ModApiBase { protected: static int l_get_mod_storage(lua_State *L); public: static void Initialize(lua_State *L, int top); }; class StorageRef : public MetaDataRef { private: ModMetadata *m_object = nullptr; static const char className[]; static const luaL_Reg methods[]; virtual Metadata *getmeta(bool auto_create); virtual void clearMeta(); // garbage collector static int gc_object(lua_State *L); public: StorageRef(ModMetadata *object); ~StorageRef(); static void Register(lua_State *L); static void create(lua_State *L, ModMetadata *object); static StorageRef *checkobject(lua_State *L, int narg); static ModMetadata *getobject(StorageRef *ref); };
pgimeno/minetest
src/script/lua_api/l_storage.h
C++
mit
1,647
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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_util.h" #include "lua_api/l_internal.h" #include "lua_api/l_settings.h" #include "common/c_converter.h" #include "common/c_content.h" #include "cpp_api/s_async.h" #include "serialization.h" #include <json/json.h> #include "cpp_api/s_security.h" #include "porting.h" #include "convert_json.h" #include "debug.h" #include "log.h" #include "tool.h" #include "filesys.h" #include "settings.h" #include "util/auth.h" #include "util/base64.h" #include "config.h" #include "version.h" #include "util/hex.h" #include "util/sha1.h" #include <algorithm> // log([level,] text) // Writes a line to the logger. // The one-argument version logs to infostream. // The two-argument version accepts a log level. // Either the special case "deprecated" for deprecation notices, or any specified in // Logger::stringToLevel(name). int ModApiUtil::l_log(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string text; LogLevel level = LL_NONE; if (lua_isnone(L, 2)) { text = luaL_checkstring(L, 1); } else { std::string name = luaL_checkstring(L, 1); text = luaL_checkstring(L, 2); if (name == "deprecated") { log_deprecated(L, text); return 0; } level = Logger::stringToLevel(name); if (level == LL_MAX) { warningstream << "Tried to log at unknown level '" << name << "'. Defaulting to \"none\"." << std::endl; level = LL_NONE; } } g_logger.log(level, text); return 0; } // get_us_time() int ModApiUtil::l_get_us_time(lua_State *L) { NO_MAP_LOCK_REQUIRED; lua_pushnumber(L, porting::getTimeUs()); return 1; } // parse_json(str[, nullvalue]) int ModApiUtil::l_parse_json(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *jsonstr = luaL_checkstring(L, 1); // Use passed nullvalue or default to nil int nullindex = 2; if (lua_isnone(L, nullindex)) { lua_pushnil(L); nullindex = lua_gettop(L); } Json::Value root; { std::istringstream stream(jsonstr); Json::CharReaderBuilder builder; builder.settings_["collectComments"] = false; std::string errs; if (!Json::parseFromStream(builder, stream, &root, &errs)) { errorstream << "Failed to parse json data " << errs << std::endl; size_t jlen = strlen(jsonstr); if (jlen > 100) { errorstream << "Data (" << jlen << " bytes) printed to warningstream." << std::endl; warningstream << "data: \"" << jsonstr << "\"" << std::endl; } else { errorstream << "data: \"" << jsonstr << "\"" << std::endl; } lua_pushnil(L); return 1; } } if (!push_json_value(L, root, nullindex)) { errorstream << "Failed to parse json data, " << "depth exceeds lua stack limit" << std::endl; errorstream << "data: \"" << jsonstr << "\"" << std::endl; lua_pushnil(L); } return 1; } // write_json(data[, styled]) -> string or nil and error message int ModApiUtil::l_write_json(lua_State *L) { NO_MAP_LOCK_REQUIRED; bool styled = false; if (!lua_isnone(L, 2)) { styled = readParam<bool>(L, 2); lua_pop(L, 1); } Json::Value root; try { read_json_value(L, root, 1); } catch (SerializationError &e) { lua_pushnil(L); lua_pushstring(L, e.what()); return 2; } std::string out; if (styled) { out = root.toStyledString(); } else { out = fastWriteJson(root); } lua_pushlstring(L, out.c_str(), out.size()); return 1; } // get_dig_params(groups, tool_capabilities) int ModApiUtil::l_get_dig_params(lua_State *L) { NO_MAP_LOCK_REQUIRED; ItemGroupList groups; read_groups(L, 1, groups); ToolCapabilities tp = read_tool_capabilities(L, 2); push_dig_params(L, getDigParams(groups, &tp)); return 1; } // get_hit_params(groups, tool_capabilities[, time_from_last_punch]) int ModApiUtil::l_get_hit_params(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::unordered_map<std::string, int> groups; read_groups(L, 1, groups); ToolCapabilities tp = read_tool_capabilities(L, 2); if(lua_isnoneornil(L, 3)) push_hit_params(L, getHitParams(groups, &tp)); else push_hit_params(L, getHitParams(groups, &tp, readParam<float>(L, 3))); return 1; } // check_password_entry(name, entry, password) int ModApiUtil::l_check_password_entry(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string name = luaL_checkstring(L, 1); std::string entry = luaL_checkstring(L, 2); std::string password = luaL_checkstring(L, 3); if (base64_is_valid(entry)) { std::string hash = translate_password(name, password); lua_pushboolean(L, hash == entry); return 1; } std::string salt; std::string verifier; if (!decode_srp_verifier_and_salt(entry, &verifier, &salt)) { // invalid format warningstream << "Invalid password format for " << name << std::endl; lua_pushboolean(L, false); return 1; } std::string gen_verifier = generate_srp_verifier(name, password, salt); lua_pushboolean(L, gen_verifier == verifier); return 1; } // get_password_hash(name, raw_password) int ModApiUtil::l_get_password_hash(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string name = luaL_checkstring(L, 1); std::string raw_password = luaL_checkstring(L, 2); std::string hash = translate_password(name, raw_password); lua_pushstring(L, hash.c_str()); return 1; } // is_yes(arg) 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 std::string str = readParam<std::string>(L, -1); // get result lua_pop(L, 1); bool yes = is_yes(str); lua_pushboolean(L, yes); return 1; } // is_nan(arg) int ModApiUtil::l_is_nan(lua_State *L) { NO_MAP_LOCK_REQUIRED; lua_pushboolean(L, isNaN(L, 1)); return 1; } // get_builtin_path() int ModApiUtil::l_get_builtin_path(lua_State *L) { NO_MAP_LOCK_REQUIRED; std::string path = porting::path_share + DIR_DELIM + "builtin" + DIR_DELIM; lua_pushstring(L, path.c_str()); return 1; } // compress(data, method, level) int ModApiUtil::l_compress(lua_State *L) { NO_MAP_LOCK_REQUIRED; size_t size; const char *data = luaL_checklstring(L, 1, &size); int level = -1; if (!lua_isnone(L, 3) && !lua_isnil(L, 3)) level = readParam<float>(L, 3); std::ostringstream os; compressZlib(std::string(data, size), os, level); std::string out = os.str(); lua_pushlstring(L, out.data(), out.size()); return 1; } // decompress(data, method) int ModApiUtil::l_decompress(lua_State *L) { NO_MAP_LOCK_REQUIRED; size_t size; const char *data = luaL_checklstring(L, 1, &size); std::istringstream is(std::string(data, size)); std::ostringstream os; decompressZlib(is, os); std::string out = os.str(); lua_pushlstring(L, out.data(), out.size()); return 1; } // encode_base64(string) int ModApiUtil::l_encode_base64(lua_State *L) { NO_MAP_LOCK_REQUIRED; size_t size; const char *data = luaL_checklstring(L, 1, &size); std::string out = base64_encode((const unsigned char *)(data), size); lua_pushlstring(L, out.data(), out.size()); return 1; } // decode_base64(string) int ModApiUtil::l_decode_base64(lua_State *L) { NO_MAP_LOCK_REQUIRED; size_t size; const char *data = luaL_checklstring(L, 1, &size); std::string out = base64_decode(std::string(data, size)); lua_pushlstring(L, out.data(), out.size()); return 1; } // mkdir(path) int ModApiUtil::l_mkdir(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *path = luaL_checkstring(L, 1); CHECK_SECURE_PATH(L, path, true); lua_pushboolean(L, fs::CreateAllDirs(path)); return 1; } // get_dir_list(path, is_dir) 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_dirs = readParam<bool>(L, 2); // true: list dirs, false: list files CHECK_SECURE_PATH(L, path, false); std::vector<fs::DirListNode> list = fs::GetDirListing(path); int index = 0; lua_newtable(L); for (const fs::DirListNode &dln : list) { if (list_all || list_dirs == dln.dir) { lua_pushstring(L, dln.name.c_str()); lua_rawseti(L, -2, ++index); } } return 1; } // safe_file_write(path, content) int ModApiUtil::l_safe_file_write(lua_State *L) { NO_MAP_LOCK_REQUIRED; const char *path = luaL_checkstring(L, 1); size_t size; const char *content = luaL_checklstring(L, 2, &size); CHECK_SECURE_PATH(L, path, true); bool ret = fs::safeWriteToFile(path, std::string(content, size)); lua_pushboolean(L, ret); return 1; } // request_insecure_environment() int ModApiUtil::l_request_insecure_environment(lua_State *L) { NO_MAP_LOCK_REQUIRED; // Just return _G if security is disabled if (!ScriptApiSecurity::isSecure(L)) { lua_getglobal(L, "_G"); return 1; } // We have to make sure that this function is being called directly by // a mod, otherwise a malicious mod could override this function and // steal its return value. lua_Debug info; // Make sure there's only one item below this function on the stack... if (lua_getstack(L, 2, &info)) { return 0; } FATAL_ERROR_IF(!lua_getstack(L, 1, &info), "lua_getstack() failed"); FATAL_ERROR_IF(!lua_getinfo(L, "S", &info), "lua_getinfo() failed"); // ...and that that item is the main file scope. if (strcmp(info.what, "main") != 0) { return 0; } // Get mod name lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_CURRENT_MOD_NAME); if (!lua_isstring(L, -1)) { return 0; } // Check secure.trusted_mods std::string mod_name = readParam<std::string>(L, -1); std::string trusted_mods = g_settings->get("secure.trusted_mods"); trusted_mods.erase(std::remove_if(trusted_mods.begin(), trusted_mods.end(), static_cast<int(*)(int)>(&std::isspace)), trusted_mods.end()); std::vector<std::string> mod_list = str_split(trusted_mods, ','); if (std::find(mod_list.begin(), mod_list.end(), mod_name) == mod_list.end()) { return 0; } // Push insecure environment lua_rawgeti(L, LUA_REGISTRYINDEX, CUSTOM_RIDX_GLOBALS_BACKUP); return 1; } // get_version() int ModApiUtil::l_get_version(lua_State *L) { lua_createtable(L, 0, 3); int table = lua_gettop(L); lua_pushstring(L, PROJECT_NAME_C); lua_setfield(L, table, "project"); lua_pushstring(L, g_version_string); lua_setfield(L, table, "string"); if (strcmp(g_version_string, g_version_hash) != 0) { lua_pushstring(L, g_version_hash); lua_setfield(L, table, "hash"); } return 1; } int ModApiUtil::l_sha1(lua_State *L) { NO_MAP_LOCK_REQUIRED; size_t size; const char *data = luaL_checklstring(L, 1, &size); bool hex = !lua_isboolean(L, 2) || !readParam<bool>(L, 2); // Compute actual checksum of data std::string data_sha1; { SHA1 ctx; ctx.addBytes(data, size); unsigned char *data_tmpdigest = ctx.getDigest(); data_sha1.assign((char*) data_tmpdigest, 20); free(data_tmpdigest); } if (hex) { std::string sha1_hex = hex_encode(data_sha1); lua_pushstring(L, sha1_hex.c_str()); } else { lua_pushlstring(L, data_sha1.data(), data_sha1.size()); } return 1; } void ModApiUtil::Initialize(lua_State *L, int top) { API_FCT(log); API_FCT(get_us_time); API_FCT(parse_json); API_FCT(write_json); API_FCT(get_dig_params); API_FCT(get_hit_params); API_FCT(check_password_entry); API_FCT(get_password_hash); API_FCT(is_yes); API_FCT(is_nan); API_FCT(get_builtin_path); API_FCT(compress); API_FCT(decompress); API_FCT(mkdir); API_FCT(get_dir_list); API_FCT(safe_file_write); API_FCT(request_insecure_environment); API_FCT(encode_base64); API_FCT(decode_base64); API_FCT(get_version); API_FCT(sha1); LuaSettings::create(L, g_settings, g_settings_path); lua_setfield(L, top, "settings"); } void ModApiUtil::InitializeClient(lua_State *L, int top) { API_FCT(log); API_FCT(get_us_time); API_FCT(parse_json); API_FCT(write_json); API_FCT(is_yes); API_FCT(is_nan); API_FCT(compress); API_FCT(decompress); API_FCT(encode_base64); API_FCT(decode_base64); API_FCT(get_version); API_FCT(sha1); } void ModApiUtil::InitializeAsync(lua_State *L, int top) { API_FCT(log); API_FCT(get_us_time); API_FCT(parse_json); API_FCT(write_json); API_FCT(is_yes); API_FCT(get_builtin_path); API_FCT(compress); API_FCT(decompress); API_FCT(mkdir); API_FCT(get_dir_list); API_FCT(encode_base64); API_FCT(decode_base64); API_FCT(get_version); API_FCT(sha1); LuaSettings::create(L, g_settings, g_settings_path); lua_setfield(L, top, "settings"); }
pgimeno/minetest
src/script/lua_api/l_util.cpp
C++
mit
13,089
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "lua_api/l_base.h" class AsyncEngine; class ModApiUtil : public ModApiBase { private: /* NOTE: The functions in this module are available in the in-game API as well as in the mainmenu API. All functions that don't require either a Server or GUIEngine instance should be in here. */ // log([level,] text) // Writes a line to the logger. // The one-argument version logs to infostream. // The two-argument version accepts a log level. static int l_log(lua_State *L); // get us precision time static int l_get_us_time(lua_State *L); // parse_json(str[, nullvalue]) static int l_parse_json(lua_State *L); // write_json(data[, styled]) static int l_write_json(lua_State *L); // get_dig_params(groups, tool_capabilities[, time_from_last_punch]) static int l_get_dig_params(lua_State *L); // get_hit_params(groups, tool_capabilities[, time_from_last_punch]) static int l_get_hit_params(lua_State *L); // check_password_entry(name, entry, password) static int l_check_password_entry(lua_State *L); // get_password_hash(name, raw_password) static int l_get_password_hash(lua_State *L); // is_yes(arg) static int l_is_yes(lua_State *L); // is_nan(arg) static int l_is_nan(lua_State *L); // get_builtin_path() static int l_get_builtin_path(lua_State *L); // compress(data, method, ...) static int l_compress(lua_State *L); // decompress(data, method, ...) static int l_decompress(lua_State *L); // mkdir(path) static int l_mkdir(lua_State *L); // get_dir_list(path, is_dir) static int l_get_dir_list(lua_State *L); // safe_file_write(path, content) static int l_safe_file_write(lua_State *L); // request_insecure_environment() static int l_request_insecure_environment(lua_State *L); // encode_base64(string) static int l_encode_base64(lua_State *L); // decode_base64(string) static int l_decode_base64(lua_State *L); // get_version() static int l_get_version(lua_State *L); // sha1(string, raw) static int l_sha1(lua_State *L); public: static void Initialize(lua_State *L, int top); static void InitializeAsync(lua_State *L, int top); static void InitializeClient(lua_State *L, int top); static void InitializeAsync(AsyncEngine &engine); };
pgimeno/minetest
src/script/lua_api/l_util.h
C++
mit
3,026
/* Minetest Copyright (C) 2013 kwolekr, Ryan Kwolek <kwolekr@minetest.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along 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" #include "common/c_converter.h" #include "emerge.h" #include "environment.h" #include "map.h" #include "mapblock.h" #include "server.h" #include "mapgen/mapgen.h" #include "voxelalgorithms.h" // garbage collector int LuaVoxelManip::gc_object(lua_State *L) { LuaVoxelManip *o = *(LuaVoxelManip **)(lua_touserdata(L, 1)); delete o; return 0; } int LuaVoxelManip::l_read_from_map(lua_State *L) { MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); MMVManip *vm = o->vm; v3s16 bp1 = getNodeBlockPos(check_v3s16(L, 2)); v3s16 bp2 = getNodeBlockPos(check_v3s16(L, 3)); sortBoxVerticies(bp1, bp2); vm->initialEmerge(bp1, bp2); push_v3s16(L, vm->m_area.MinEdge); push_v3s16(L, vm->m_area.MaxEdge); return 2; } int LuaVoxelManip::l_get_data(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); bool use_buffer = lua_istable(L, 2); MMVManip *vm = o->vm; u32 volume = vm->m_area.getVolume(); if (use_buffer) lua_pushvalue(L, 2); else lua_newtable(L); for (u32 i = 0; i != volume; i++) { lua_Integer cid = vm->m_data[i].getContent(); lua_pushinteger(L, cid); lua_rawseti(L, -2, i + 1); } return 1; } int LuaVoxelManip::l_set_data(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); MMVManip *vm = o->vm; if (!lua_istable(L, 2)) throw LuaError("VoxelManip:set_data called with missing parameter"); u32 volume = vm->m_area.getVolume(); for (u32 i = 0; i != volume; i++) { lua_rawgeti(L, 2, i + 1); content_t c = lua_tointeger(L, -1); vm->m_data[i].setContent(c); lua_pop(L, 1); } return 0; } int LuaVoxelManip::l_write_to_map(lua_State *L) { MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); bool update_light = !lua_isboolean(L, 2) || readParam<bool>(L, 2); GET_ENV_PTR; ServerMap *map = &(env->getServerMap()); 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)); } MapEditEvent event; event.type = MEET_OTHER; for (const auto &modified_block : o->modified_blocks) event.modified_blocks.insert(modified_block.first); map->dispatchEvent(&event); o->modified_blocks.clear(); return 0; } int LuaVoxelManip::l_get_node_at(lua_State *L) { NO_MAP_LOCK_REQUIRED; const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); LuaVoxelManip *o = checkobject(L, 1); v3s16 pos = check_v3s16(L, 2); pushnode(L, o->vm->getNodeNoExNoEmerge(pos), ndef); return 1; } int LuaVoxelManip::l_set_node_at(lua_State *L) { NO_MAP_LOCK_REQUIRED; const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); LuaVoxelManip *o = checkobject(L, 1); v3s16 pos = check_v3s16(L, 2); MapNode n = readnode(L, 3, ndef); o->vm->setNodeNoEmerge(pos, n); return 0; } int LuaVoxelManip::l_update_liquids(lua_State *L) { GET_ENV_PTR; LuaVoxelManip *o = checkobject(L, 1); Map *map = &(env->getMap()); const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); MMVManip *vm = o->vm; Mapgen mg; mg.vm = vm; mg.ndef = ndef; mg.updateLiquid(&map->m_transforming_liquid, vm->m_area.MinEdge, vm->m_area.MaxEdge); return 0; } int LuaVoxelManip::l_calc_lighting(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); if (!o->is_mapgen_vm) { warningstream << "VoxelManip:calc_lighting called for a non-mapgen " "VoxelManip object" << std::endl; return 0; } const NodeDefManager *ndef = getServer(L)->getNodeDefManager(); EmergeManager *emerge = getServer(L)->getEmergeManager(); 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; bool propagate_shadow = !lua_isboolean(L, 4) || readParam<bool>(L, 4); sortBoxVerticies(pmin, pmax); if (!vm->m_area.contains(VoxelArea(pmin, pmax))) throw LuaError("Specified voxel area out of VoxelManipulator bounds"); Mapgen mg; mg.vm = vm; mg.ndef = ndef; mg.water_level = emerge->mgparams->water_level; mg.calcLighting(pmin, pmax, fpmin, fpmax, propagate_shadow); return 0; } int LuaVoxelManip::l_set_lighting(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); if (!o->is_mapgen_vm) { warningstream << "VoxelManip:set_lighting called for a non-mapgen " "VoxelManip object" << std::endl; return 0; } if (!lua_istable(L, 2)) throw LuaError("VoxelManip:set_lighting called with missing parameter"); u8 light; light = (getintfield_default(L, 2, "day", 0) & 0x0F); light |= (getintfield_default(L, 2, "night", 0) & 0x0F) << 4; MMVManip *vm = o->vm; v3s16 yblock = v3s16(0, 1, 0) * MAP_BLOCKSIZE; v3s16 pmin = lua_istable(L, 3) ? check_v3s16(L, 3) : vm->m_area.MinEdge + yblock; v3s16 pmax = lua_istable(L, 4) ? check_v3s16(L, 4) : vm->m_area.MaxEdge - yblock; sortBoxVerticies(pmin, pmax); if (!vm->m_area.contains(VoxelArea(pmin, pmax))) throw LuaError("Specified voxel area out of VoxelManipulator bounds"); Mapgen mg; mg.vm = vm; mg.setLighting(light, pmin, pmax); return 0; } int LuaVoxelManip::l_get_light_data(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); MMVManip *vm = o->vm; u32 volume = vm->m_area.getVolume(); lua_newtable(L); for (u32 i = 0; i != volume; i++) { lua_Integer light = vm->m_data[i].param1; lua_pushinteger(L, light); lua_rawseti(L, -2, i + 1); } return 1; } int LuaVoxelManip::l_set_light_data(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); MMVManip *vm = o->vm; if (!lua_istable(L, 2)) throw LuaError("VoxelManip:set_light_data called with missing " "parameter"); u32 volume = vm->m_area.getVolume(); for (u32 i = 0; i != volume; i++) { lua_rawgeti(L, 2, i + 1); u8 light = lua_tointeger(L, -1); vm->m_data[i].param1 = light; lua_pop(L, 1); } return 0; } 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); MMVManip *vm = o->vm; u32 volume = vm->m_area.getVolume(); if (use_buffer) lua_pushvalue(L, 2); else lua_newtable(L); for (u32 i = 0; i != volume; i++) { lua_Integer param2 = vm->m_data[i].param2; lua_pushinteger(L, param2); lua_rawseti(L, -2, i + 1); } return 1; } int LuaVoxelManip::l_set_param2_data(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); MMVManip *vm = o->vm; if (!lua_istable(L, 2)) throw LuaError("VoxelManip:set_param2_data called with missing " "parameter"); u32 volume = vm->m_area.getVolume(); for (u32 i = 0; i != volume; i++) { lua_rawgeti(L, 2, i + 1); u8 param2 = lua_tointeger(L, -1); vm->m_data[i].param2 = param2; lua_pop(L, 1); } return 0; } int LuaVoxelManip::l_update_map(lua_State *L) { return 0; } int LuaVoxelManip::l_was_modified(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); MMVManip *vm = o->vm; lua_pushboolean(L, vm->m_is_dirty); return 1; } int LuaVoxelManip::l_get_emerged_area(lua_State *L) { NO_MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); push_v3s16(L, o->vm->m_area.MinEdge); push_v3s16(L, o->vm->m_area.MaxEdge); return 2; } LuaVoxelManip::LuaVoxelManip(MMVManip *mmvm, bool is_mg_vm) : is_mapgen_vm(is_mg_vm), vm(mmvm) { } LuaVoxelManip::LuaVoxelManip(Map *map) : vm(new MMVManip(map)) { } LuaVoxelManip::LuaVoxelManip(Map *map, v3s16 p1, v3s16 p2) { vm = new MMVManip(map); v3s16 bp1 = getNodeBlockPos(p1); v3s16 bp2 = getNodeBlockPos(p2); sortBoxVerticies(bp1, bp2); vm->initialEmerge(bp1, bp2); } LuaVoxelManip::~LuaVoxelManip() { if (!is_mapgen_vm) delete vm; } // LuaVoxelManip() // Creates an LuaVoxelManip and leaves it on top of stack 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); *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); return 1; } LuaVoxelManip *LuaVoxelManip::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 *(LuaVoxelManip **)ud; // unbox pointer } void LuaVoxelManip::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); // drop metatable 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} };
pgimeno/minetest
src/script/lua_api/l_vmanip.cpp
C++
mit
10,987
/* Minetest Copyright (C) 2013 kwolekr, Ryan Kwolek <kwolekr@minetest.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <map> #include "irr_v3d.h" #include "lua_api/l_base.h" class Map; class MapBlock; class MMVManip; /* VoxelManip */ class LuaVoxelManip : public ModApiBase { private: std::map<v3s16, MapBlock *> modified_blocks; bool is_mapgen_vm = false; static const char className[]; static const luaL_Reg methods[]; static int gc_object(lua_State *L); static int l_read_from_map(lua_State *L); static int l_get_data(lua_State *L); static int l_set_data(lua_State *L); static int l_write_to_map(lua_State *L); static int l_get_node_at(lua_State *L); static int l_set_node_at(lua_State *L); static int l_update_map(lua_State *L); static int l_update_liquids(lua_State *L); static int l_calc_lighting(lua_State *L); static int l_set_lighting(lua_State *L); static int l_get_light_data(lua_State *L); static int l_set_light_data(lua_State *L); static int l_get_param2_data(lua_State *L); static int l_set_param2_data(lua_State *L); static int l_was_modified(lua_State *L); static int l_get_emerged_area(lua_State *L); public: MMVManip *vm = nullptr; LuaVoxelManip(MMVManip *mmvm, bool is_mapgen_vm); LuaVoxelManip(Map *map, v3s16 p1, v3s16 p2); LuaVoxelManip(Map *map); ~LuaVoxelManip(); // LuaVoxelManip() // Creates a LuaVoxelManip and leaves it on top of stack static int create_object(lua_State *L); static LuaVoxelManip *checkobject(lua_State *L, int narg); static void Register(lua_State *L); };
pgimeno/minetest
src/script/lua_api/l_vmanip.h
C++
mit
2,239
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "scripting_client.h" #include "client/client.h" #include "cpp_api/s_internal.h" #include "lua_api/l_client.h" #include "lua_api/l_env.h" #include "lua_api/l_item.h" #include "lua_api/l_minimap.h" #include "lua_api/l_modchannels.h" #include "lua_api/l_particles_local.h" #include "lua_api/l_storage.h" #include "lua_api/l_sound.h" #include "lua_api/l_util.h" #include "lua_api/l_item.h" #include "lua_api/l_nodemeta.h" #include "lua_api/l_localplayer.h" #include "lua_api/l_camera.h" ClientScripting::ClientScripting(Client *client): ScriptApiBase(ScriptingType::Client) { setGameDef(client); SCRIPTAPI_PRECHECKHEADER // Security is mandatory client side initializeSecurityClient(); lua_getglobal(L, "core"); int top = lua_gettop(L); lua_newtable(L); lua_setfield(L, -2, "ui"); InitializeModApi(L, top); lua_pop(L, 1); if (client->getMinimap()) LuaMinimap::create(L, client->getMinimap()); // Push builtin initialization type lua_pushstring(L, "client"); lua_setglobal(L, "INIT"); infostream << "SCRIPTAPI: Initialized client game modules" << std::endl; } void ClientScripting::InitializeModApi(lua_State *L, int top) { LuaItemStack::Register(L); StorageRef::Register(L); LuaMinimap::Register(L); NodeMetaRef::RegisterClient(L); LuaLocalPlayer::Register(L); LuaCamera::Register(L); ModChannelRef::Register(L); ModApiUtil::InitializeClient(L, top); ModApiClient::Initialize(L, top); ModApiStorage::Initialize(L, top); ModApiEnvMod::InitializeClient(L, top); ModApiChannels::Initialize(L, top); ModApiParticlesLocal::Initialize(L, top); } void ClientScripting::on_client_ready(LocalPlayer *localplayer) { lua_State *L = getStack(); LuaLocalPlayer::create(L, localplayer); } void ClientScripting::on_camera_ready(Camera *camera) { LuaCamera::create(getStack(), camera); }
pgimeno/minetest
src/script/scripting_client.cpp
C++
mit
2,678
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "cpp_api/s_base.h" #include "cpp_api/s_client.h" #include "cpp_api/s_modchannels.h" #include "cpp_api/s_security.h" class Client; class LocalPlayer; class Camera; class ClientScripting: virtual public ScriptApiBase, public ScriptApiSecurity, public ScriptApiClient, public ScriptApiModChannels { public: ClientScripting(Client *client); void on_client_ready(LocalPlayer *localplayer); void on_camera_ready(Camera *camera); private: virtual void InitializeModApi(lua_State *L, int top); };
pgimeno/minetest
src/script/scripting_client.h
C++
mit
1,376
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "scripting_mainmenu.h" #include "content/mods.h" #include "cpp_api/s_internal.h" #include "lua_api/l_base.h" #include "lua_api/l_mainmenu.h" #include "lua_api/l_sound.h" #include "lua_api/l_util.h" #include "lua_api/l_settings.h" #include "log.h" extern "C" { #include "lualib.h" } #define MAINMENU_NUM_ASYNC_THREADS 4 MainMenuScripting::MainMenuScripting(GUIEngine* guiengine): ScriptApiBase(ScriptingType::MainMenu) { setGuiEngine(guiengine); SCRIPTAPI_PRECHECKHEADER lua_getglobal(L, "core"); int top = lua_gettop(L); lua_newtable(L); lua_setglobal(L, "gamedata"); // Initialize our lua_api modules initializeModApi(L, top); lua_pop(L, 1); // Push builtin initialization type lua_pushstring(L, "mainmenu"); lua_setglobal(L, "INIT"); infostream << "SCRIPTAPI: Initialized main menu modules" << std::endl; } /******************************************************************************/ void MainMenuScripting::initializeModApi(lua_State *L, int top) { registerLuaClasses(L, top); // Initialize mod API modules ModApiMainMenu::Initialize(L, top); ModApiUtil::Initialize(L, top); ModApiSound::Initialize(L, top); asyncEngine.registerStateInitializer(registerLuaClasses); asyncEngine.registerStateInitializer(ModApiMainMenu::InitializeAsync); asyncEngine.registerStateInitializer(ModApiUtil::InitializeAsync); // Initialize async environment //TODO possibly make number of async threads configurable asyncEngine.initialize(MAINMENU_NUM_ASYNC_THREADS); } /******************************************************************************/ void MainMenuScripting::registerLuaClasses(lua_State *L, int top) { LuaSettings::Register(L); } /******************************************************************************/ void MainMenuScripting::step() { asyncEngine.step(getStack()); } /******************************************************************************/ unsigned int MainMenuScripting::queueAsync(const std::string &serialized_func, const std::string &serialized_param) { return asyncEngine.queueAsyncJob(serialized_func, serialized_param); }
pgimeno/minetest
src/script/scripting_mainmenu.cpp
C++
mit
2,891
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "cpp_api/s_base.h" #include "cpp_api/s_mainmenu.h" #include "cpp_api/s_async.h" /*****************************************************************************/ /* Scripting <-> Main Menu Interface */ /*****************************************************************************/ class MainMenuScripting : virtual public ScriptApiBase, public ScriptApiMainMenu { public: MainMenuScripting(GUIEngine* guiengine); // Global step handler to pass back async events void step(); // Pass async events from engine to async threads unsigned int queueAsync(const std::string &serialized_func, const std::string &serialized_params); private: void initializeModApi(lua_State *L, int top); static void registerLuaClasses(lua_State *L, int top); AsyncEngine asyncEngine; };
pgimeno/minetest
src/script/scripting_mainmenu.h
C++
mit
1,631
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "scripting_server.h" #include "server.h" #include "log.h" #include "settings.h" #include "cpp_api/s_internal.h" #include "lua_api/l_areastore.h" #include "lua_api/l_auth.h" #include "lua_api/l_base.h" #include "lua_api/l_craft.h" #include "lua_api/l_env.h" #include "lua_api/l_inventory.h" #include "lua_api/l_item.h" #include "lua_api/l_itemstackmeta.h" #include "lua_api/l_mapgen.h" #include "lua_api/l_modchannels.h" #include "lua_api/l_nodemeta.h" #include "lua_api/l_nodetimer.h" #include "lua_api/l_noise.h" #include "lua_api/l_object.h" #include "lua_api/l_playermeta.h" #include "lua_api/l_particles.h" #include "lua_api/l_rollback.h" #include "lua_api/l_server.h" #include "lua_api/l_util.h" #include "lua_api/l_vmanip.h" #include "lua_api/l_settings.h" #include "lua_api/l_http.h" #include "lua_api/l_storage.h" extern "C" { #include "lualib.h" } ServerScripting::ServerScripting(Server* server): ScriptApiBase(ScriptingType::Server) { setGameDef(server); // setEnv(env) is called by ScriptApiEnv::initializeEnvironment() // once the environment has been created SCRIPTAPI_PRECHECKHEADER if (g_settings->getBool("secure.enable_security")) { initializeSecurity(); } lua_getglobal(L, "core"); int top = lua_gettop(L); lua_newtable(L); lua_setfield(L, -2, "object_refs"); lua_newtable(L); lua_setfield(L, -2, "luaentities"); // Initialize our lua_api modules InitializeModApi(L, top); lua_pop(L, 1); // Push builtin initialization type lua_pushstring(L, "game"); lua_setglobal(L, "INIT"); infostream << "SCRIPTAPI: Initialized game modules" << std::endl; } void ServerScripting::InitializeModApi(lua_State *L, int top) { // Register reference classes (userdata) InvRef::Register(L); ItemStackMetaRef::Register(L); LuaAreaStore::Register(L); LuaItemStack::Register(L); LuaPerlinNoise::Register(L); LuaPerlinNoiseMap::Register(L); LuaPseudoRandom::Register(L); LuaPcgRandom::Register(L); LuaRaycast::Register(L); LuaSecureRandom::Register(L); LuaVoxelManip::Register(L); NodeMetaRef::Register(L); NodeTimerRef::Register(L); ObjectRef::Register(L); PlayerMetaRef::Register(L); LuaSettings::Register(L); StorageRef::Register(L); ModChannelRef::Register(L); // Initialize mod api modules ModApiAuth::Initialize(L, top); ModApiCraft::Initialize(L, top); ModApiEnvMod::Initialize(L, top); ModApiInventory::Initialize(L, top); ModApiItemMod::Initialize(L, top); ModApiMapgen::Initialize(L, top); ModApiParticles::Initialize(L, top); ModApiRollback::Initialize(L, top); ModApiServer::Initialize(L, top); ModApiUtil::Initialize(L, top); ModApiHttp::Initialize(L, top); ModApiStorage::Initialize(L, top); ModApiChannels::Initialize(L, top); } void log_deprecated(const std::string &message) { log_deprecated(NULL, message); }
pgimeno/minetest
src/script/scripting_server.cpp
C++
mit
3,587
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "cpp_api/s_base.h" #include "cpp_api/s_entity.h" #include "cpp_api/s_env.h" #include "cpp_api/s_inventory.h" #include "cpp_api/s_modchannels.h" #include "cpp_api/s_node.h" #include "cpp_api/s_player.h" #include "cpp_api/s_server.h" #include "cpp_api/s_security.h" /*****************************************************************************/ /* Scripting <-> Server Game Interface */ /*****************************************************************************/ class ServerScripting: virtual public ScriptApiBase, public ScriptApiDetached, public ScriptApiEntity, public ScriptApiEnv, public ScriptApiModChannels, public ScriptApiNode, public ScriptApiPlayer, public ScriptApiServer, public ScriptApiSecurity { public: ServerScripting(Server* server); // use ScriptApiBase::loadMod() to load mods private: void InitializeModApi(lua_State *L, int top); }; void log_deprecated(const std::string &message);
pgimeno/minetest
src/script/scripting_server.h
C++
mit
1,780
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "serialization.h" #include "util/serialize.h" #if defined(_WIN32) && !defined(WIN32_NO_ZLIB_WINAPI) #define ZLIB_WINAPI #endif #include "zlib.h" /* report a zlib or i/o error */ void zerr(int ret) { dstream<<"zerr: "; switch (ret) { case Z_ERRNO: if (ferror(stdin)) dstream<<"error reading stdin"<<std::endl; if (ferror(stdout)) dstream<<"error writing stdout"<<std::endl; break; case Z_STREAM_ERROR: dstream<<"invalid compression level"<<std::endl; break; case Z_DATA_ERROR: dstream<<"invalid or incomplete deflate data"<<std::endl; break; case Z_MEM_ERROR: dstream<<"out of memory"<<std::endl; break; case Z_VERSION_ERROR: dstream<<"zlib version mismatch!"<<std::endl; break; default: dstream<<"return value = "<<ret<<std::endl; } } void compressZlib(const u8 *data, size_t data_size, std::ostream &os, int level) { z_stream z; const s32 bufsize = 16384; char output_buffer[bufsize]; int status = 0; int ret; z.zalloc = Z_NULL; z.zfree = Z_NULL; z.opaque = Z_NULL; ret = deflateInit(&z, level); if(ret != Z_OK) throw SerializationError("compressZlib: deflateInit failed"); // Point zlib to our input buffer z.next_in = (Bytef*)&data[0]; z.avail_in = data_size; // And get all output for(;;) { z.next_out = (Bytef*)output_buffer; z.avail_out = bufsize; status = deflate(&z, Z_FINISH); if(status == Z_NEED_DICT || status == Z_DATA_ERROR || status == Z_MEM_ERROR) { zerr(status); throw SerializationError("compressZlib: deflate failed"); } int count = bufsize - z.avail_out; if(count) os.write(output_buffer, count); // This determines zlib has given all output if(status == Z_STREAM_END) break; } deflateEnd(&z); } void compressZlib(const std::string &data, std::ostream &os, int level) { compressZlib((u8*)data.c_str(), data.size(), os, level); } void decompressZlib(std::istream &is, std::ostream &os) { z_stream z; const s32 bufsize = 16384; char input_buffer[bufsize]; char output_buffer[bufsize]; int status = 0; int ret; int bytes_read = 0; int input_buffer_len = 0; z.zalloc = Z_NULL; z.zfree = Z_NULL; z.opaque = Z_NULL; ret = inflateInit(&z); if(ret != Z_OK) throw SerializationError("dcompressZlib: inflateInit failed"); z.avail_in = 0; //dstream<<"initial fail="<<is.fail()<<" bad="<<is.bad()<<std::endl; for(;;) { z.next_out = (Bytef*)output_buffer; z.avail_out = bufsize; if(z.avail_in == 0) { z.next_in = (Bytef*)input_buffer; is.read(input_buffer, bufsize); input_buffer_len = is.gcount(); z.avail_in = input_buffer_len; //dstream<<"read fail="<<is.fail()<<" bad="<<is.bad()<<std::endl; } if(z.avail_in == 0) { //dstream<<"z.avail_in == 0"<<std::endl; break; } //dstream<<"1 z.avail_in="<<z.avail_in<<std::endl; status = inflate(&z, Z_NO_FLUSH); //dstream<<"2 z.avail_in="<<z.avail_in<<std::endl; bytes_read += is.gcount() - z.avail_in; //dstream<<"bytes_read="<<bytes_read<<std::endl; if(status == Z_NEED_DICT || status == Z_DATA_ERROR || status == Z_MEM_ERROR) { zerr(status); throw SerializationError("decompressZlib: inflate failed"); } int count = bufsize - z.avail_out; //dstream<<"count="<<count<<std::endl; if(count) os.write(output_buffer, count); if(status == Z_STREAM_END) { //dstream<<"Z_STREAM_END"<<std::endl; //dstream<<"z.avail_in="<<z.avail_in<<std::endl; //dstream<<"fail="<<is.fail()<<" bad="<<is.bad()<<std::endl; // Unget all the data that inflate didn't take is.clear(); // Just in case EOF is set for(u32 i=0; i < z.avail_in; i++) { is.unget(); if(is.fail() || is.bad()) { dstream<<"unget #"<<i<<" failed"<<std::endl; dstream<<"fail="<<is.fail()<<" bad="<<is.bad()<<std::endl; throw SerializationError("decompressZlib: unget failed"); } } break; } } inflateEnd(&z); } void compress(const SharedBuffer<u8> &data, std::ostream &os, u8 version) { if(version >= 11) { compressZlib(*data ,data.getSize(), os); return; } if(data.getSize() == 0) return; // Write length (u32) u8 tmp[4]; writeU32(tmp, data.getSize()); os.write((char*)tmp, 4); // We will be writing 8-bit pairs of more_count and byte u8 more_count = 0; u8 current_byte = data[0]; for(u32 i=1; i<data.getSize(); i++) { if( data[i] != current_byte || more_count == 255 ) { // write count and byte os.write((char*)&more_count, 1); os.write((char*)&current_byte, 1); more_count = 0; current_byte = data[i]; } else { more_count++; } } // write count and byte os.write((char*)&more_count, 1); os.write((char*)&current_byte, 1); } void decompress(std::istream &is, std::ostream &os, u8 version) { if(version >= 11) { decompressZlib(is, os); return; } // Read length (u32) u8 tmp[4]; is.read((char*)tmp, 4); u32 len = readU32(tmp); // We will be reading 8-bit pairs of more_count and byte u32 count = 0; for(;;) { u8 more_count=0; u8 byte=0; is.read((char*)&more_count, 1); is.read((char*)&byte, 1); if(is.eof()) throw SerializationError("decompress: stream ended halfway"); for(s32 i=0; i<(u16)more_count+1; i++) os.write((char*)&byte, 1); count += (u16)more_count+1; if(count == len) break; } }
pgimeno/minetest
src/serialization.cpp
C++
mit
6,176
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" #include "exceptions.h" #include <iostream> #include "util/pointer.h" /* Map format serialization version -------------------------------- For map data (blocks, nodes, sectors). NOTE: The goal is to increment this so that saved maps will be loadable by any version. Other compatibility is not maintained. 0: original networked test with 1-byte nodes 1: update with 2-byte nodes 2: lighting is transmitted in param 3: optional fetching of far blocks 4: block compression 5: sector objects NOTE: block compression was left accidentally out 6: failed attempt at switching block compression on again 7: block compression switched on again 8: server-initiated block transfers and all kinds of stuff 9: block objects 10: water pressure 11: zlib'd blocks, block flags 12: UnlimitedHeightmap now uses interpolated areas 13: Mapgen v2 14: NodeMetadata 15: StaticObjects 16: larger maximum size of node metadata, and compression 17: MapBlocks contain timestamp 18: new generator (not really necessary, but it's there) 19: new content type handling 20: many existing content types translated to extended ones 21: dynamic content type allocation 22: minerals removed, facedir & wallmounted changed 23: new node metadata format 24: 16-bit node ids and node timers (never released as stable) 25: Improved node timer format 26: Never written; read the same as 25 27: Added light spreading flags to blocks 28: Added "private" flag to NodeMetadata */ // This represents an uninitialized or invalid format #define SER_FMT_VER_INVALID 255 // Highest supported serialization version #define SER_FMT_VER_HIGHEST_READ 28 // Saved on disk version #define SER_FMT_VER_HIGHEST_WRITE 28 // Lowest supported serialization version #define SER_FMT_VER_LOWEST_READ 0 // Lowest serialization version for writing // Can't do < 24 anymore; we have 16-bit dynamically allocated node IDs // in memory; conversion just won't work in this direction. #define SER_FMT_VER_LOWEST_WRITE 24 inline bool ser_ver_supported(s32 v) { return v >= SER_FMT_VER_LOWEST_READ && v <= SER_FMT_VER_HIGHEST_READ; } /* Misc. serialization functions */ void compressZlib(const u8 *data, size_t data_size, std::ostream &os, int level = -1); void compressZlib(const std::string &data, std::ostream &os, int level = -1); void decompressZlib(std::istream &is, std::ostream &os); // These choose between zlib and a self-made one according to version void compress(const SharedBuffer<u8> &data, std::ostream &os, u8 version); //void compress(const std::string &data, std::ostream &os, u8 version); void decompress(std::istream &is, std::ostream &os, u8 version);
pgimeno/minetest
src/serialization.h
C++
mit
3,480
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "server.h" #include <iostream> #include <queue> #include <algorithm> #include "network/connection.h" #include "network/networkprotocol.h" #include "network/serveropcodes.h" #include "ban.h" #include "environment.h" #include "map.h" #include "threading/mutex_auto_lock.h" #include "constants.h" #include "voxel.h" #include "config.h" #include "version.h" #include "filesys.h" #include "mapblock.h" #include "serverobject.h" #include "genericobject.h" #include "settings.h" #include "profiler.h" #include "log.h" #include "scripting_server.h" #include "nodedef.h" #include "itemdef.h" #include "craftdef.h" #include "emerge.h" #include "mapgen/mapgen.h" #include "mapgen/mg_biome.h" #include "content_mapnode.h" #include "content_nodemeta.h" #include "content_sao.h" #include "content/mods.h" #include "modchannels.h" #include "serverlist.h" #include "util/string.h" #include "rollback.h" #include "util/serialize.h" #include "util/thread.h" #include "defaultsettings.h" #include "server/mods.h" #include "util/base64.h" #include "util/sha1.h" #include "util/hex.h" #include "database/database.h" #include "chatmessage.h" #include "chat_interface.h" #include "remoteplayer.h" class ClientNotFoundException : public BaseException { public: ClientNotFoundException(const char *s): BaseException(s) {} }; class ServerThread : public Thread { public: ServerThread(Server *server): Thread("Server"), m_server(server) {} void *run(); private: Server *m_server; }; void *ServerThread::run() { BEGIN_DEBUG_EXCEPTION_HANDLER m_server->AsyncRunStep(true); while (!stopRequested()) { try { m_server->AsyncRunStep(); m_server->Receive(); } catch (con::NoIncomingDataException &e) { } catch (con::PeerNotFoundException &e) { infostream<<"Server: PeerNotFoundException"<<std::endl; } catch (ClientNotFoundException &e) { } catch (con::ConnectionBindFailed &e) { m_server->setAsyncFatalError(e.what()); } catch (LuaError &e) { m_server->setAsyncFatalError( "ServerThread::run Lua: " + std::string(e.what())); } } END_DEBUG_EXCEPTION_HANDLER return nullptr; } v3f ServerSoundParams::getPos(ServerEnvironment *env, bool *pos_exists) const { if(pos_exists) *pos_exists = false; switch(type){ case SSP_LOCAL: return v3f(0,0,0); case SSP_POSITIONAL: if(pos_exists) *pos_exists = true; return pos; case SSP_OBJECT: { if(object == 0) return v3f(0,0,0); ServerActiveObject *sao = env->getActiveObject(object); if(!sao) return v3f(0,0,0); if(pos_exists) *pos_exists = true; return sao->getBasePosition(); } } return v3f(0,0,0); } void Server::ShutdownState::reset() { m_timer = 0.0f; message.clear(); should_reconnect = false; is_requested = false; } void Server::ShutdownState::trigger(float delay, const std::string &msg, bool reconnect) { m_timer = delay; message = msg; should_reconnect = reconnect; } void Server::ShutdownState::tick(float dtime, Server *server) { if (m_timer <= 0.0f) return; // Timed shutdown static const float shutdown_msg_times[] = { 1, 2, 3, 4, 5, 10, 20, 40, 60, 120, 180, 300, 600, 1200, 1800, 3600 }; // Automated messages if (m_timer < shutdown_msg_times[ARRLEN(shutdown_msg_times) - 1]) { for (float t : shutdown_msg_times) { // If shutdown timer matches an automessage, shot it if (m_timer > t && m_timer - dtime < t) { std::wstring periodicMsg = getShutdownTimerMessage(); infostream << wide_to_utf8(periodicMsg).c_str() << std::endl; server->SendChatMessage(PEER_ID_INEXISTENT, periodicMsg); break; } } } m_timer -= dtime; if (m_timer < 0.0f) { m_timer = 0.0f; is_requested = true; } } std::wstring Server::ShutdownState::getShutdownTimerMessage() const { std::wstringstream ws; ws << L"*** Server shutting down in " << duration_to_string(myround(m_timer)).c_str() << "."; return ws.str(); } /* Server */ Server::Server( const std::string &path_world, const SubgameSpec &gamespec, bool simple_singleplayer_mode, Address bind_addr, bool dedicated, ChatInterface *iface ): m_bind_addr(bind_addr), m_path_world(path_world), m_gamespec(gamespec), m_simple_singleplayer_mode(simple_singleplayer_mode), m_dedicated(dedicated), m_async_fatal_error(""), m_con(std::make_shared<con::Connection>(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, m_bind_addr.isIPv6(), this)), m_itemdef(createItemDefManager()), m_nodedef(createNodeDefManager()), m_craftdef(createCraftDefManager()), m_thread(new ServerThread(this)), m_uptime(0), m_clients(m_con), m_admin_chat(iface), m_modchannel_mgr(new ModChannelMgr()) { m_lag = g_settings->getFloat("dedicated_server_step"); if (m_path_world.empty()) throw ServerError("Supplied empty world path"); if (!gamespec.isValid()) throw ServerError("Supplied invalid gamespec"); } Server::~Server() { // Send shutdown message SendChatMessage(PEER_ID_INEXISTENT, ChatMessage(CHATMESSAGE_TYPE_ANNOUNCE, L"*** Server shutting down")); if (m_env) { MutexAutoLock envlock(m_env_mutex); infostream << "Server: Saving players" << std::endl; m_env->saveLoadedPlayers(); infostream << "Server: Kicking players" << std::endl; std::string kick_msg; bool reconnect = false; if (isShutdownRequested()) { reconnect = m_shutdown_state.should_reconnect; kick_msg = m_shutdown_state.message; } if (kick_msg.empty()) { kick_msg = g_settings->get("kick_msg_shutdown"); } m_env->saveLoadedPlayers(true); m_env->kickAllPlayers(SERVER_ACCESSDENIED_SHUTDOWN, kick_msg, reconnect); } actionstream << "Server: Shutting down" << std::endl; // Do this before stopping the server in case mapgen callbacks need to access // server-controlled resources (like ModStorages). Also do them before // shutdown callbacks since they may modify state that is finalized in a // callback. if (m_emerge) m_emerge->stopThreads(); if (m_env) { MutexAutoLock envlock(m_env_mutex); // Execute script shutdown hooks infostream << "Executing shutdown hooks" << std::endl; m_script->on_shutdown(); infostream << "Server: Saving environment metadata" << std::endl; m_env->saveMeta(); } // Stop threads if (m_thread) { stop(); delete m_thread; } // Delete things in the reverse order of creation delete m_emerge; delete m_env; delete m_rollback; delete m_banmanager; delete m_itemdef; delete m_nodedef; delete m_craftdef; // Deinitialize scripting infostream << "Server: Deinitializing scripting" << std::endl; delete m_script; // Delete detached inventories for (auto &detached_inventory : m_detached_inventories) { delete detached_inventory.second; } } void Server::init() { infostream << "Server created for gameid \"" << m_gamespec.id << "\""; if (m_simple_singleplayer_mode) infostream << " in simple singleplayer mode" << std::endl; else infostream << std::endl; infostream << "- world: " << m_path_world << std::endl; infostream << "- game: " << m_gamespec.path << std::endl; // Create world if it doesn't exist if (!loadGameConfAndInitWorld(m_path_world, m_gamespec)) throw ServerError("Failed to initialize world"); // Create emerge manager m_emerge = new EmergeManager(this); // Create ban manager std::string ban_path = m_path_world + DIR_DELIM "ipban.txt"; m_banmanager = new BanManager(ban_path); m_modmgr = std::unique_ptr<ServerModManager>(new ServerModManager(m_path_world)); std::vector<ModSpec> unsatisfied_mods = m_modmgr->getUnsatisfiedMods(); // complain about mods with unsatisfied dependencies if (!m_modmgr->isConsistent()) { m_modmgr->printUnsatisfiedModsError(); } //lock environment MutexAutoLock envlock(m_env_mutex); // Create the Map (loads map_meta.txt, overriding configured mapgen params) ServerMap *servermap = new ServerMap(m_path_world, this, m_emerge); // Initialize scripting infostream << "Server: Initializing Lua" << std::endl; m_script = new ServerScripting(this); m_script->loadMod(getBuiltinLuaPath() + DIR_DELIM "init.lua", BUILTIN_MOD_NAME); m_modmgr->loadMods(m_script); // Read Textures and calculate sha1 sums fillMediaCache(); // Apply item aliases in the node definition manager m_nodedef->updateAliases(m_itemdef); // Apply texture overrides from texturepack/override.txt std::vector<std::string> paths; fs::GetRecursiveDirs(paths, g_settings->get("texture_path")); fs::GetRecursiveDirs(paths, m_gamespec.path + DIR_DELIM + "textures"); for (const std::string &path : paths) m_nodedef->applyTextureOverrides(path + DIR_DELIM + "override.txt"); m_nodedef->setNodeRegistrationStatus(true); // Perform pending node name resolutions m_nodedef->runNodeResolveCallbacks(); // unmap node names for connected nodeboxes m_nodedef->mapNodeboxConnections(); // init the recipe hashes to speed up crafting m_craftdef->initHashes(this); // Initialize Environment m_env = new ServerEnvironment(servermap, m_script, this, m_path_world); m_clients.setEnv(m_env); if (!servermap->settings_mgr.makeMapgenParams()) FATAL_ERROR("Couldn't create any mapgen type"); // Initialize mapgens m_emerge->initMapgens(servermap->getMapgenParams()); if (g_settings->getBool("enable_rollback_recording")) { // Create rollback manager m_rollback = new RollbackManager(m_path_world, this); } // Give environment reference to scripting api m_script->initializeEnvironment(m_env); // Register us to receive map edit events servermap->addEventReceiver(this); m_env->loadMeta(); m_liquid_transform_every = g_settings->getFloat("liquid_update"); m_max_chatmessage_length = g_settings->getU16("chat_message_max_size"); m_csm_restriction_flags = g_settings->getU64("csm_restriction_flags"); m_csm_restriction_noderange = g_settings->getU32("csm_restriction_noderange"); } void Server::start() { infostream << "Starting server on " << m_bind_addr.serializeString() << "..." << std::endl; // Stop thread if already running m_thread->stop(); // Initialize connection m_con->SetTimeoutMs(30); m_con->Serve(m_bind_addr); // Start thread m_thread->start(); // ASCII art for the win! std::cerr << " .__ __ __ " << std::endl << " _____ |__| ____ _____/ |_ ____ _______/ |_ " << std::endl << " / \\| |/ \\_/ __ \\ __\\/ __ \\ / ___/\\ __\\" << std::endl << "| Y Y \\ | | \\ ___/| | \\ ___/ \\___ \\ | | " << std::endl << "|__|_| /__|___| /\\___ >__| \\___ >____ > |__| " << std::endl << " \\/ \\/ \\/ \\/ \\/ " << std::endl; actionstream << "World at [" << m_path_world << "]" << std::endl; actionstream << "Server for gameid=\"" << m_gamespec.id << "\" listening on " << m_bind_addr.serializeString() << ":" << m_bind_addr.getPort() << "." << std::endl; } void Server::stop() { infostream<<"Server: Stopping and waiting threads"<<std::endl; // Stop threads (set run=false first so both start stopping) m_thread->stop(); //m_emergethread.setRun(false); m_thread->wait(); //m_emergethread.stop(); infostream<<"Server: Threads stopped"<<std::endl; } void Server::step(float dtime) { // Limit a bit if (dtime > 2.0) dtime = 2.0; { MutexAutoLock lock(m_step_dtime_mutex); m_step_dtime += dtime; } // Throw if fatal error occurred in thread std::string async_err = m_async_fatal_error.get(); if (!async_err.empty()) { if (!m_simple_singleplayer_mode) { m_env->kickAllPlayers(SERVER_ACCESSDENIED_CRASH, g_settings->get("kick_msg_crash"), g_settings->getBool("ask_reconnect_on_crash")); } throw ServerError("AsyncErr: " + async_err); } } void Server::AsyncRunStep(bool initial_step) { g_profiler->add("Server::AsyncRunStep (num)", 1); float dtime; { MutexAutoLock lock1(m_step_dtime_mutex); dtime = m_step_dtime; } { // Send blocks to clients SendBlocks(dtime); } if((dtime < 0.001) && !initial_step) return; g_profiler->add("Server::AsyncRunStep with dtime (num)", 1); //infostream<<"Server steps "<<dtime<<std::endl; //infostream<<"Server::AsyncRunStep(): dtime="<<dtime<<std::endl; { MutexAutoLock lock1(m_step_dtime_mutex); m_step_dtime -= dtime; } /* Update uptime */ { m_uptime.set(m_uptime.get() + dtime); } handlePeerChanges(); /* Update time of day and overall game time */ m_env->setTimeOfDaySpeed(g_settings->getFloat("time_speed")); /* Send to clients at constant intervals */ m_time_of_day_send_timer -= dtime; if(m_time_of_day_send_timer < 0.0) { m_time_of_day_send_timer = g_settings->getFloat("time_send_interval"); u16 time = m_env->getTimeOfDay(); float time_speed = g_settings->getFloat("time_speed"); SendTimeOfDay(PEER_ID_INEXISTENT, time, time_speed); } { MutexAutoLock lock(m_env_mutex); // Figure out and report maximum lag to environment float max_lag = m_env->getMaxLagEstimate(); max_lag *= 0.9998; // Decrease slowly (about half per 5 minutes) if(dtime > max_lag){ if(dtime > 0.1 && dtime > max_lag * 2.0) infostream<<"Server: Maximum lag peaked to "<<dtime <<" s"<<std::endl; max_lag = dtime; } m_env->reportMaxLagEstimate(max_lag); // Step environment ScopeProfiler sp(g_profiler, "SEnv step"); ScopeProfiler sp2(g_profiler, "SEnv step avg", SPT_AVG); m_env->step(dtime); } static const float map_timer_and_unload_dtime = 2.92; if(m_map_timer_and_unload_interval.step(dtime, map_timer_and_unload_dtime)) { MutexAutoLock lock(m_env_mutex); // Run Map's timers and unload unused data ScopeProfiler sp(g_profiler, "Server: map timer and unload"); m_env->getMap().timerUpdate(map_timer_and_unload_dtime, g_settings->getFloat("server_unload_unused_data_timeout"), U32_MAX); } /* Listen to the admin chat, if available */ if (m_admin_chat) { if (!m_admin_chat->command_queue.empty()) { MutexAutoLock lock(m_env_mutex); while (!m_admin_chat->command_queue.empty()) { ChatEvent *evt = m_admin_chat->command_queue.pop_frontNoEx(); handleChatInterfaceEvent(evt); delete evt; } } m_admin_chat->outgoing_queue.push_back( new ChatEventTimeInfo(m_env->getGameTime(), m_env->getTimeOfDay())); } /* Do background stuff */ /* Transform liquids */ m_liquid_transform_timer += dtime; if(m_liquid_transform_timer >= m_liquid_transform_every) { m_liquid_transform_timer -= m_liquid_transform_every; MutexAutoLock lock(m_env_mutex); ScopeProfiler sp(g_profiler, "Server: liquid transform"); std::map<v3s16, MapBlock*> modified_blocks; m_env->getMap().transformLiquids(modified_blocks, m_env); /* Set the modified blocks unsent for all the clients */ if (!modified_blocks.empty()) { SetBlocksNotSent(modified_blocks); } } m_clients.step(dtime); m_lag += (m_lag > dtime ? -1 : 1) * dtime/100; #if USE_CURL // send masterserver announce { float &counter = m_masterserver_timer; if (!isSingleplayer() && (!counter || counter >= 300.0) && g_settings->getBool("server_announce")) { ServerList::sendAnnounce(counter ? ServerList::AA_UPDATE : ServerList::AA_START, m_bind_addr.getPort(), m_clients.getPlayerNames(), m_uptime.get(), m_env->getGameTime(), m_lag, m_gamespec.id, Mapgen::getMapgenName(m_emerge->mgparams->mgtype), m_modmgr->getMods(), m_dedicated); counter = 0.01; } counter += dtime; } #endif /* Check added and deleted active objects */ { //infostream<<"Server: Checking added and deleted active objects"<<std::endl; MutexAutoLock envlock(m_env_mutex); m_clients.lock(); const RemoteClientMap &clients = m_clients.getClientList(); ScopeProfiler sp(g_profiler, "Server: checking added and deleted objs"); // Radius inside which objects are active static thread_local const s16 radius = g_settings->getS16("active_object_send_range_blocks") * MAP_BLOCKSIZE; // Radius inside which players are active static thread_local const bool is_transfer_limited = g_settings->exists("unlimited_player_transfer_distance") && !g_settings->getBool("unlimited_player_transfer_distance"); static thread_local const s16 player_transfer_dist = g_settings->getS16("player_transfer_distance") * MAP_BLOCKSIZE; s16 player_radius = player_transfer_dist; if (player_radius == 0 && is_transfer_limited) player_radius = radius; for (const auto &client_it : clients) { RemoteClient *client = client_it.second; // If definitions and textures have not been sent, don't // send objects either if (client->getState() < CS_DefinitionsSent) continue; RemotePlayer *player = m_env->getPlayer(client->peer_id); if (!player) { // This can happen if the client timeouts somehow continue; } PlayerSAO *playersao = player->getPlayerSAO(); if (!playersao) continue; s16 my_radius = MYMIN(radius, playersao->getWantedRange() * MAP_BLOCKSIZE); if (my_radius <= 0) my_radius = radius; //infostream << "Server: Active Radius " << my_radius << std::endl; std::queue<u16> removed_objects; std::queue<u16> added_objects; m_env->getRemovedActiveObjects(playersao, my_radius, player_radius, client->m_known_objects, removed_objects); m_env->getAddedActiveObjects(playersao, my_radius, player_radius, client->m_known_objects, added_objects); // Ignore if nothing happened if (removed_objects.empty() && added_objects.empty()) { continue; } std::string data_buffer; char buf[4]; // Handle removed objects writeU16((u8*)buf, removed_objects.size()); data_buffer.append(buf, 2); while (!removed_objects.empty()) { // Get object u16 id = removed_objects.front(); ServerActiveObject* obj = m_env->getActiveObject(id); // Add to data buffer for sending writeU16((u8*)buf, id); data_buffer.append(buf, 2); // Remove from known objects client->m_known_objects.erase(id); if(obj && obj->m_known_by_count > 0) obj->m_known_by_count--; removed_objects.pop(); } // Handle added objects writeU16((u8*)buf, added_objects.size()); data_buffer.append(buf, 2); while (!added_objects.empty()) { // Get object u16 id = added_objects.front(); ServerActiveObject* obj = m_env->getActiveObject(id); // Get object type u8 type = ACTIVEOBJECT_TYPE_INVALID; if (!obj) warningstream << FUNCTION_NAME << ": NULL object" << std::endl; else type = obj->getSendType(); // Add to data buffer for sending writeU16((u8*)buf, id); data_buffer.append(buf, 2); writeU8((u8*)buf, type); data_buffer.append(buf, 1); if(obj) data_buffer.append(serializeLongString( obj->getClientInitializationData(client->net_proto_version))); else data_buffer.append(serializeLongString("")); // Add to known objects client->m_known_objects.insert(id); if(obj) obj->m_known_by_count++; added_objects.pop(); } u32 pktSize = SendActiveObjectRemoveAdd(client->peer_id, data_buffer); verbosestream << "Server: Sent object remove/add: " << removed_objects.size() << " removed, " << added_objects.size() << " added, " << "packet size is " << pktSize << std::endl; } m_clients.unlock(); m_mod_storage_save_timer -= dtime; if (m_mod_storage_save_timer <= 0.0f) { infostream << "Saving registered mod storages." << std::endl; m_mod_storage_save_timer = g_settings->getFloat("server_map_save_interval"); for (std::unordered_map<std::string, ModMetadata *>::const_iterator it = m_mod_storages.begin(); it != m_mod_storages.end(); ++it) { if (it->second->isModified()) { it->second->save(getModStoragePath()); } } } } /* Send object messages */ { MutexAutoLock envlock(m_env_mutex); ScopeProfiler sp(g_profiler, "Server: sending object messages"); // Key = object id // Value = data sent by object std::unordered_map<u16, std::vector<ActiveObjectMessage>*> buffered_messages; // Get active object messages from environment for(;;) { ActiveObjectMessage aom = m_env->getActiveObjectMessage(); if (aom.id == 0) break; std::vector<ActiveObjectMessage>* message_list = nullptr; std::unordered_map<u16, std::vector<ActiveObjectMessage>* >::iterator n; n = buffered_messages.find(aom.id); if (n == buffered_messages.end()) { message_list = new std::vector<ActiveObjectMessage>; buffered_messages[aom.id] = message_list; } else { message_list = n->second; } message_list->push_back(aom); } m_clients.lock(); const RemoteClientMap &clients = m_clients.getClientList(); // Route data to every client for (const auto &client_it : clients) { RemoteClient *client = client_it.second; std::string reliable_data; std::string unreliable_data; // Go through all objects in message buffer for (const auto &buffered_message : buffered_messages) { // If object is not known by client, skip it u16 id = buffered_message.first; if (client->m_known_objects.find(id) == client->m_known_objects.end()) continue; // Get message list of object std::vector<ActiveObjectMessage>* list = buffered_message.second; // Go through every message for (const ActiveObjectMessage &aom : *list) { // Compose the full new data with header std::string new_data; // Add object id char buf[2]; writeU16((u8*)&buf[0], aom.id); new_data.append(buf, 2); // Add data new_data += serializeString(aom.datastring); // Add data to buffer if (aom.reliable) reliable_data += new_data; else unreliable_data += new_data; } } /* reliable_data and unreliable_data are now ready. Send them. */ if (!reliable_data.empty()) { SendActiveObjectMessages(client->peer_id, reliable_data); } if (!unreliable_data.empty()) { SendActiveObjectMessages(client->peer_id, unreliable_data, false); } } m_clients.unlock(); // Clear buffered_messages for (auto &buffered_message : buffered_messages) { delete buffered_message.second; } } /* Send queued-for-sending map edit events. */ { // We will be accessing the environment MutexAutoLock lock(m_env_mutex); // Don't send too many at a time //u32 count = 0; // Single change sending is disabled if queue size is not small bool disable_single_change_sending = false; if(m_unsent_map_edit_queue.size() >= 4) disable_single_change_sending = true; int event_count = m_unsent_map_edit_queue.size(); // We'll log the amount of each Profiler prof; std::list<v3s16> node_meta_updates; while (!m_unsent_map_edit_queue.empty()) { MapEditEvent* event = m_unsent_map_edit_queue.front(); m_unsent_map_edit_queue.pop(); // Players far away from the change are stored here. // Instead of sending the changes, MapBlocks are set not sent // for them. std::unordered_set<u16> far_players; switch (event->type) { case MEET_ADDNODE: case MEET_SWAPNODE: prof.add("MEET_ADDNODE", 1); sendAddNode(event->p, event->n, &far_players, disable_single_change_sending ? 5 : 30, event->type == MEET_ADDNODE); break; case MEET_REMOVENODE: prof.add("MEET_REMOVENODE", 1); sendRemoveNode(event->p, &far_players, disable_single_change_sending ? 5 : 30); break; case MEET_BLOCK_NODE_METADATA_CHANGED: { verbosestream << "Server: MEET_BLOCK_NODE_METADATA_CHANGED" << std::endl; prof.add("MEET_BLOCK_NODE_METADATA_CHANGED", 1); if (!event->is_private_change) { // Don't send the change yet. Collect them to eliminate dupes. node_meta_updates.remove(event->p); node_meta_updates.push_back(event->p); } if (MapBlock *block = m_env->getMap().getBlockNoCreateNoEx( getNodeBlockPos(event->p))) { block->raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_REPORT_META_CHANGE); } break; } case MEET_OTHER: infostream << "Server: MEET_OTHER" << std::endl; prof.add("MEET_OTHER", 1); for (const v3s16 &modified_block : event->modified_blocks) { m_clients.markBlockposAsNotSent(modified_block); } break; default: prof.add("unknown", 1); warningstream << "Server: Unknown MapEditEvent " << ((u32)event->type) << std::endl; break; } /* Set blocks not sent to far players */ if (!far_players.empty()) { // Convert list format to that wanted by SetBlocksNotSent std::map<v3s16, MapBlock*> modified_blocks2; for (const v3s16 &modified_block : event->modified_blocks) { modified_blocks2[modified_block] = m_env->getMap().getBlockNoCreateNoEx(modified_block); } // Set blocks not sent for (const u16 far_player : far_players) { if (RemoteClient *client = getClient(far_player)) client->SetBlocksNotSent(modified_blocks2); } } delete event; } if (event_count >= 5) { infostream << "Server: MapEditEvents:" << std::endl; prof.print(infostream); } else if (event_count != 0) { verbosestream << "Server: MapEditEvents:" << std::endl; prof.print(verbosestream); } // Send all metadata updates if (node_meta_updates.size()) sendMetadataChanged(node_meta_updates); } /* Trigger emergethread (it somehow gets to a non-triggered but bysy state sometimes) */ { float &counter = m_emergethread_trigger_timer; counter += dtime; if (counter >= 2.0) { counter = 0.0; m_emerge->startThreads(); } } // Save map, players and auth stuff { float &counter = m_savemap_timer; counter += dtime; static thread_local const float save_interval = g_settings->getFloat("server_map_save_interval"); if (counter >= save_interval) { counter = 0.0; MutexAutoLock lock(m_env_mutex); ScopeProfiler sp(g_profiler, "Server: saving stuff"); // Save ban file if (m_banmanager->isModified()) { m_banmanager->save(); } // Save changed parts of map m_env->getMap().save(MOD_STATE_WRITE_NEEDED); // Save players m_env->saveLoadedPlayers(); // Save environment metadata m_env->saveMeta(); } } m_shutdown_state.tick(dtime, this); } void Server::Receive() { session_t peer_id = 0; try { NetworkPacket pkt; m_con->Receive(&pkt); peer_id = pkt.getPeerId(); ProcessData(&pkt); } catch (const con::InvalidIncomingDataException &e) { infostream << "Server::Receive(): InvalidIncomingDataException: what()=" << e.what() << std::endl; } catch (const SerializationError &e) { infostream << "Server::Receive(): SerializationError: what()=" << e.what() << std::endl; } catch (const ClientStateError &e) { errorstream << "ProcessData: peer=" << peer_id << e.what() << std::endl; DenyAccess_Legacy(peer_id, L"Your client sent something server didn't expect." L"Try reconnecting or updating your client"); } catch (const con::PeerNotFoundException &e) { // Do nothing } } PlayerSAO* Server::StageTwoClientInit(session_t peer_id) { std::string playername; PlayerSAO *playersao = NULL; m_clients.lock(); try { RemoteClient* client = m_clients.lockedGetClientNoEx(peer_id, CS_InitDone); if (client) { playername = client->getName(); playersao = emergePlayer(playername.c_str(), peer_id, client->net_proto_version); } } catch (std::exception &e) { m_clients.unlock(); throw; } m_clients.unlock(); RemotePlayer *player = m_env->getPlayer(playername.c_str()); // If failed, cancel if (!playersao || !player) { if (player && player->getPeerId() != PEER_ID_INEXISTENT) { actionstream << "Server: Failed to emerge player \"" << playername << "\" (player allocated to an another client)" << std::endl; DenyAccess_Legacy(peer_id, L"Another client is connected with this " L"name. If your client closed unexpectedly, try again in " L"a minute."); } else { errorstream << "Server: " << playername << ": Failed to emerge player" << std::endl; DenyAccess_Legacy(peer_id, L"Could not allocate player."); } return NULL; } /* Send complete position information */ SendMovePlayer(peer_id); // Send privileges SendPlayerPrivileges(peer_id); // Send inventory formspec SendPlayerInventoryFormspec(peer_id); // Send inventory SendInventory(playersao); // Send HP or death screen if (playersao->isDead()) SendDeathscreen(peer_id, false, v3f(0,0,0)); else SendPlayerHPOrDie(playersao, PlayerHPChangeReason(PlayerHPChangeReason::SET_HP)); // Send Breath SendPlayerBreath(playersao); Address addr = getPeerAddress(player->getPeerId()); std::string ip_str = addr.serializeString(); actionstream<<player->getName() <<" [" << ip_str << "] joins game. " << std::endl; /* Print out action */ { const std::vector<std::string> &names = m_clients.getPlayerNames(); actionstream << player->getName() << " joins game. List of players: "; for (const std::string &name : names) { actionstream << name << " "; } actionstream << player->getName() <<std::endl; } return playersao; } inline void Server::handleCommand(NetworkPacket* pkt) { const ToServerCommandHandler& opHandle = toServerCommandTable[pkt->getCommand()]; (this->*opHandle.handler)(pkt); } void Server::ProcessData(NetworkPacket *pkt) { // Environment is locked first. MutexAutoLock envlock(m_env_mutex); ScopeProfiler sp(g_profiler, "Server::ProcessData"); u32 peer_id = pkt->getPeerId(); try { Address address = getPeerAddress(peer_id); std::string addr_s = address.serializeString(); if(m_banmanager->isIpBanned(addr_s)) { std::string ban_name = m_banmanager->getBanName(addr_s); infostream << "Server: A banned client tried to connect from " << addr_s << "; banned name was " << ban_name << std::endl; // This actually doesn't seem to transfer to the client DenyAccess_Legacy(peer_id, L"Your ip is banned. Banned name was " + utf8_to_wide(ban_name)); return; } } catch(con::PeerNotFoundException &e) { /* * no peer for this packet found * most common reason is peer timeout, e.g. peer didn't * respond for some time, your server was overloaded or * things like that. */ infostream << "Server::ProcessData(): Canceling: peer " << peer_id << " not found" << std::endl; return; } try { ToServerCommand command = (ToServerCommand) pkt->getCommand(); // Command must be handled into ToServerCommandHandler if (command >= TOSERVER_NUM_MSG_TYPES) { infostream << "Server: Ignoring unknown command " << command << std::endl; return; } if (toServerCommandTable[command].state == TOSERVER_STATE_NOT_CONNECTED) { handleCommand(pkt); return; } u8 peer_ser_ver = getClient(peer_id, CS_InitDone)->serialization_version; if(peer_ser_ver == SER_FMT_VER_INVALID) { errorstream << "Server::ProcessData(): Cancelling: Peer" " serialization format invalid or not initialized." " Skipping incoming command=" << command << std::endl; return; } /* Handle commands related to client startup */ if (toServerCommandTable[command].state == TOSERVER_STATE_STARTUP) { handleCommand(pkt); return; } if (m_clients.getClientState(peer_id) < CS_Active) { if (command == TOSERVER_PLAYERPOS) return; errorstream << "Got packet command: " << command << " for peer id " << peer_id << " but client isn't active yet. Dropping packet " << std::endl; return; } handleCommand(pkt); } catch (SendFailedException &e) { errorstream << "Server::ProcessData(): SendFailedException: " << "what=" << e.what() << std::endl; } catch (PacketError &e) { actionstream << "Server::ProcessData(): PacketError: " << "what=" << e.what() << std::endl; } } void Server::setTimeOfDay(u32 time) { m_env->setTimeOfDay(time); m_time_of_day_send_timer = 0; } void Server::onMapEditEvent(MapEditEvent *event) { if (m_ignore_map_edit_events_area.contains(event->getArea())) return; MapEditEvent *e = event->clone(); m_unsent_map_edit_queue.push(e); } Inventory* Server::getInventory(const InventoryLocation &loc) { switch (loc.type) { case InventoryLocation::UNDEFINED: case InventoryLocation::CURRENT_PLAYER: break; case InventoryLocation::PLAYER: { RemotePlayer *player = m_env->getPlayer(loc.name.c_str()); if(!player) return NULL; PlayerSAO *playersao = player->getPlayerSAO(); if(!playersao) return NULL; return playersao->getInventory(); } break; case InventoryLocation::NODEMETA: { NodeMetadata *meta = m_env->getMap().getNodeMetadata(loc.p); if(!meta) return NULL; return meta->getInventory(); } break; case InventoryLocation::DETACHED: { if(m_detached_inventories.count(loc.name) == 0) return NULL; return m_detached_inventories[loc.name]; } break; default: sanity_check(false); // abort break; } return NULL; } void Server::setInventoryModified(const InventoryLocation &loc, bool playerSend) { switch(loc.type){ case InventoryLocation::UNDEFINED: break; case InventoryLocation::PLAYER: { if (!playerSend) return; RemotePlayer *player = m_env->getPlayer(loc.name.c_str()); if (!player) return; PlayerSAO *playersao = player->getPlayerSAO(); if(!playersao) return; SendInventory(playersao); } break; case InventoryLocation::NODEMETA: { MapEditEvent event; event.type = MEET_BLOCK_NODE_METADATA_CHANGED; event.p = loc.p; m_env->getMap().dispatchEvent(&event); } break; case InventoryLocation::DETACHED: { sendDetachedInventory(loc.name,PEER_ID_INEXISTENT); } break; default: sanity_check(false); // abort break; } } void Server::SetBlocksNotSent(std::map<v3s16, MapBlock *>& block) { std::vector<session_t> clients = m_clients.getClientIDs(); m_clients.lock(); // Set the modified blocks unsent for all the clients for (const session_t client_id : clients) { if (RemoteClient *client = m_clients.lockedGetClientNoEx(client_id)) client->SetBlocksNotSent(block); } m_clients.unlock(); } void Server::peerAdded(con::Peer *peer) { verbosestream<<"Server::peerAdded(): peer->id=" <<peer->id<<std::endl; m_peer_change_queue.push(con::PeerChange(con::PEER_ADDED, peer->id, false)); } void Server::deletingPeer(con::Peer *peer, bool timeout) { verbosestream<<"Server::deletingPeer(): peer->id=" <<peer->id<<", timeout="<<timeout<<std::endl; m_clients.event(peer->id, CSE_Disconnect); m_peer_change_queue.push(con::PeerChange(con::PEER_REMOVED, peer->id, timeout)); } bool Server::getClientConInfo(session_t peer_id, con::rtt_stat_type type, float* retval) { *retval = m_con->getPeerStat(peer_id,type); return *retval != -1; } bool Server::getClientInfo( session_t peer_id, ClientState* state, u32* uptime, u8* ser_vers, u16* prot_vers, u8* major, u8* minor, u8* patch, std::string* vers_string ) { *state = m_clients.getClientState(peer_id); m_clients.lock(); RemoteClient* client = m_clients.lockedGetClientNoEx(peer_id, CS_Invalid); if (!client) { m_clients.unlock(); return false; } *uptime = client->uptime(); *ser_vers = client->serialization_version; *prot_vers = client->net_proto_version; *major = client->getMajor(); *minor = client->getMinor(); *patch = client->getPatch(); *vers_string = client->getPatch(); m_clients.unlock(); return true; } void Server::handlePeerChanges() { while(!m_peer_change_queue.empty()) { con::PeerChange c = m_peer_change_queue.front(); m_peer_change_queue.pop(); verbosestream<<"Server: Handling peer change: " <<"id="<<c.peer_id<<", timeout="<<c.timeout <<std::endl; switch(c.type) { case con::PEER_ADDED: m_clients.CreateClient(c.peer_id); break; case con::PEER_REMOVED: DeleteClient(c.peer_id, c.timeout?CDR_TIMEOUT:CDR_LEAVE); break; default: FATAL_ERROR("Invalid peer change event received!"); break; } } } void Server::printToConsoleOnly(const std::string &text) { if (m_admin_chat) { m_admin_chat->outgoing_queue.push_back( new ChatEventChat("", utf8_to_wide(text))); } else { std::cout << text << std::endl; } } void Server::Send(NetworkPacket *pkt) { Send(pkt->getPeerId(), pkt); } void Server::Send(session_t peer_id, NetworkPacket *pkt) { m_clients.send(peer_id, clientCommandFactoryTable[pkt->getCommand()].channel, pkt, clientCommandFactoryTable[pkt->getCommand()].reliable); } void Server::SendMovement(session_t peer_id) { std::ostringstream os(std::ios_base::binary); NetworkPacket pkt(TOCLIENT_MOVEMENT, 12 * sizeof(float), peer_id); pkt << g_settings->getFloat("movement_acceleration_default"); pkt << g_settings->getFloat("movement_acceleration_air"); pkt << g_settings->getFloat("movement_acceleration_fast"); pkt << g_settings->getFloat("movement_speed_walk"); pkt << g_settings->getFloat("movement_speed_crouch"); pkt << g_settings->getFloat("movement_speed_fast"); pkt << g_settings->getFloat("movement_speed_climb"); pkt << g_settings->getFloat("movement_speed_jump"); pkt << g_settings->getFloat("movement_liquid_fluidity"); pkt << g_settings->getFloat("movement_liquid_fluidity_smooth"); pkt << g_settings->getFloat("movement_liquid_sink"); pkt << g_settings->getFloat("movement_gravity"); Send(&pkt); } void Server::SendPlayerHPOrDie(PlayerSAO *playersao, const PlayerHPChangeReason &reason) { if (!g_settings->getBool("enable_damage")) return; session_t peer_id = playersao->getPeerID(); bool is_alive = playersao->getHP() > 0; if (is_alive) SendPlayerHP(peer_id); else DiePlayer(peer_id, reason); } void Server::SendHP(session_t peer_id, u16 hp) { NetworkPacket pkt(TOCLIENT_HP, 1, peer_id); pkt << hp; Send(&pkt); } void Server::SendBreath(session_t peer_id, u16 breath) { NetworkPacket pkt(TOCLIENT_BREATH, 2, peer_id); pkt << (u16) breath; Send(&pkt); } void Server::SendAccessDenied(session_t peer_id, AccessDeniedCode reason, const std::string &custom_reason, bool reconnect) { assert(reason < SERVER_ACCESSDENIED_MAX); NetworkPacket pkt(TOCLIENT_ACCESS_DENIED, 1, peer_id); pkt << (u8)reason; if (reason == SERVER_ACCESSDENIED_CUSTOM_STRING) pkt << custom_reason; else if (reason == SERVER_ACCESSDENIED_SHUTDOWN || reason == SERVER_ACCESSDENIED_CRASH) pkt << custom_reason << (u8)reconnect; Send(&pkt); } void Server::SendAccessDenied_Legacy(session_t peer_id,const std::wstring &reason) { NetworkPacket pkt(TOCLIENT_ACCESS_DENIED_LEGACY, 0, peer_id); pkt << reason; Send(&pkt); } void Server::SendDeathscreen(session_t peer_id, bool set_camera_point_target, v3f camera_point_target) { NetworkPacket pkt(TOCLIENT_DEATHSCREEN, 1 + sizeof(v3f), peer_id); pkt << set_camera_point_target << camera_point_target; Send(&pkt); } void Server::SendItemDef(session_t peer_id, IItemDefManager *itemdef, u16 protocol_version) { NetworkPacket pkt(TOCLIENT_ITEMDEF, 0, peer_id); /* u16 command u32 length of the next item zlib-compressed serialized ItemDefManager */ std::ostringstream tmp_os(std::ios::binary); itemdef->serialize(tmp_os, protocol_version); std::ostringstream tmp_os2(std::ios::binary); compressZlib(tmp_os.str(), tmp_os2); pkt.putLongString(tmp_os2.str()); // Make data buffer verbosestream << "Server: Sending item definitions to id(" << peer_id << "): size=" << pkt.getSize() << std::endl; Send(&pkt); } void Server::SendNodeDef(session_t peer_id, const NodeDefManager *nodedef, u16 protocol_version) { NetworkPacket pkt(TOCLIENT_NODEDEF, 0, peer_id); /* u16 command u32 length of the next item zlib-compressed serialized NodeDefManager */ std::ostringstream tmp_os(std::ios::binary); nodedef->serialize(tmp_os, protocol_version); std::ostringstream tmp_os2(std::ios::binary); compressZlib(tmp_os.str(), tmp_os2); pkt.putLongString(tmp_os2.str()); // Make data buffer verbosestream << "Server: Sending node definitions to id(" << peer_id << "): size=" << pkt.getSize() << std::endl; Send(&pkt); } /* Non-static send methods */ void Server::SendInventory(PlayerSAO* playerSAO) { UpdateCrafting(playerSAO->getPlayer()); /* Serialize it */ NetworkPacket pkt(TOCLIENT_INVENTORY, 0, playerSAO->getPeerID()); std::ostringstream os; playerSAO->getInventory()->serialize(os); std::string s = os.str(); pkt.putRawString(s.c_str(), s.size()); Send(&pkt); } void Server::SendChatMessage(session_t peer_id, const ChatMessage &message) { NetworkPacket pkt(TOCLIENT_CHAT_MESSAGE, 0, peer_id); u8 version = 1; u8 type = message.type; pkt << version << type << std::wstring(L"") << message.message << (u64)message.timestamp; if (peer_id != PEER_ID_INEXISTENT) { RemotePlayer *player = m_env->getPlayer(peer_id); if (!player) return; Send(&pkt); } else { m_clients.sendToAll(&pkt); } } void Server::SendShowFormspecMessage(session_t peer_id, const std::string &formspec, const std::string &formname) { NetworkPacket pkt(TOCLIENT_SHOW_FORMSPEC, 0 , peer_id); if (formspec.empty()){ //the client should close the formspec //but make sure there wasn't another one open in meantime const auto it = m_formspec_state_data.find(peer_id); if (it != m_formspec_state_data.end() && it->second == formname) { m_formspec_state_data.erase(peer_id); } pkt.putLongString(""); } else { m_formspec_state_data[peer_id] = formname; pkt.putLongString(FORMSPEC_VERSION_STRING + formspec); } pkt << formname; Send(&pkt); } // Spawns a particle on peer with peer_id void Server::SendSpawnParticle(session_t peer_id, u16 protocol_version, v3f pos, v3f velocity, v3f acceleration, float expirationtime, float size, bool collisiondetection, bool collision_removal, bool object_collision, bool vertical, const std::string &texture, const struct TileAnimationParams &animation, u8 glow) { static thread_local const float radius = g_settings->getS16("max_block_send_distance") * MAP_BLOCKSIZE * BS; if (peer_id == PEER_ID_INEXISTENT) { std::vector<session_t> clients = m_clients.getClientIDs(); for (const session_t client_id : clients) { RemotePlayer *player = m_env->getPlayer(client_id); if (!player) continue; PlayerSAO *sao = player->getPlayerSAO(); if (!sao) continue; // Do not send to distant clients if (sao->getBasePosition().getDistanceFrom(pos * BS) > radius) continue; SendSpawnParticle(client_id, player->protocol_version, pos, velocity, acceleration, expirationtime, size, collisiondetection, collision_removal, object_collision, vertical, texture, animation, glow); } return; } NetworkPacket pkt(TOCLIENT_SPAWN_PARTICLE, 0, peer_id); pkt << pos << velocity << acceleration << expirationtime << size << collisiondetection; pkt.putLongString(texture); pkt << vertical; pkt << collision_removal; // This is horrible but required (why are there two ways to serialize pkts?) std::ostringstream os(std::ios_base::binary); animation.serialize(os, protocol_version); pkt.putRawString(os.str()); pkt << glow; pkt << object_collision; Send(&pkt); } // Adds a ParticleSpawner on peer with peer_id void Server::SendAddParticleSpawner(session_t peer_id, u16 protocol_version, u16 amount, float spawntime, v3f minpos, v3f maxpos, v3f minvel, v3f maxvel, v3f minacc, v3f maxacc, float minexptime, float maxexptime, float minsize, float maxsize, bool collisiondetection, bool collision_removal, bool object_collision, u16 attached_id, bool vertical, const std::string &texture, u32 id, const struct TileAnimationParams &animation, u8 glow) { if (peer_id == PEER_ID_INEXISTENT) { // This sucks and should be replaced: std::vector<session_t> clients = m_clients.getClientIDs(); for (const session_t client_id : clients) { RemotePlayer *player = m_env->getPlayer(client_id); if (!player) continue; SendAddParticleSpawner(client_id, player->protocol_version, amount, spawntime, minpos, maxpos, minvel, maxvel, minacc, maxacc, minexptime, maxexptime, minsize, maxsize, collisiondetection, collision_removal, object_collision, attached_id, vertical, texture, id, animation, glow); } return; } NetworkPacket pkt(TOCLIENT_ADD_PARTICLESPAWNER, 0, peer_id); pkt << amount << spawntime << minpos << maxpos << minvel << maxvel << minacc << maxacc << minexptime << maxexptime << minsize << maxsize << collisiondetection; pkt.putLongString(texture); pkt << id << vertical; pkt << collision_removal; pkt << attached_id; // This is horrible but required std::ostringstream os(std::ios_base::binary); animation.serialize(os, protocol_version); pkt.putRawString(os.str()); pkt << glow; pkt << object_collision; Send(&pkt); } void Server::SendDeleteParticleSpawner(session_t peer_id, u32 id) { NetworkPacket pkt(TOCLIENT_DELETE_PARTICLESPAWNER, 4, peer_id); // Ugly error in this packet pkt << id; if (peer_id != PEER_ID_INEXISTENT) Send(&pkt); else m_clients.sendToAll(&pkt); } void Server::SendHUDAdd(session_t peer_id, u32 id, HudElement *form) { NetworkPacket pkt(TOCLIENT_HUDADD, 0 , peer_id); pkt << id << (u8) form->type << form->pos << form->name << form->scale << form->text << form->number << form->item << form->dir << form->align << form->offset << form->world_pos << form->size; Send(&pkt); } void Server::SendHUDRemove(session_t peer_id, u32 id) { NetworkPacket pkt(TOCLIENT_HUDRM, 4, peer_id); pkt << id; Send(&pkt); } void Server::SendHUDChange(session_t peer_id, u32 id, HudElementStat stat, void *value) { NetworkPacket pkt(TOCLIENT_HUDCHANGE, 0, peer_id); pkt << id << (u8) stat; switch (stat) { case HUD_STAT_POS: case HUD_STAT_SCALE: case HUD_STAT_ALIGN: case HUD_STAT_OFFSET: pkt << *(v2f *) value; break; case HUD_STAT_NAME: case HUD_STAT_TEXT: pkt << *(std::string *) value; break; case HUD_STAT_WORLD_POS: pkt << *(v3f *) value; break; case HUD_STAT_SIZE: pkt << *(v2s32 *) value; break; case HUD_STAT_NUMBER: case HUD_STAT_ITEM: case HUD_STAT_DIR: default: pkt << *(u32 *) value; break; } Send(&pkt); } void Server::SendHUDSetFlags(session_t peer_id, u32 flags, u32 mask) { NetworkPacket pkt(TOCLIENT_HUD_SET_FLAGS, 4 + 4, peer_id); flags &= ~(HUD_FLAG_HEALTHBAR_VISIBLE | HUD_FLAG_BREATHBAR_VISIBLE); pkt << flags << mask; Send(&pkt); } void Server::SendHUDSetParam(session_t peer_id, u16 param, const std::string &value) { NetworkPacket pkt(TOCLIENT_HUD_SET_PARAM, 0, peer_id); pkt << param << value; Send(&pkt); } void Server::SendSetSky(session_t peer_id, const video::SColor &bgcolor, const std::string &type, const std::vector<std::string> &params, bool &clouds) { NetworkPacket pkt(TOCLIENT_SET_SKY, 0, peer_id); pkt << bgcolor << type << (u16) params.size(); for (const std::string &param : params) pkt << param; pkt << clouds; Send(&pkt); } void Server::SendCloudParams(session_t peer_id, const CloudParams &params) { NetworkPacket pkt(TOCLIENT_CLOUD_PARAMS, 0, peer_id); pkt << params.density << params.color_bright << params.color_ambient << params.height << params.thickness << params.speed; Send(&pkt); } void Server::SendOverrideDayNightRatio(session_t peer_id, bool do_override, float ratio) { NetworkPacket pkt(TOCLIENT_OVERRIDE_DAY_NIGHT_RATIO, 1 + 2, peer_id); pkt << do_override << (u16) (ratio * 65535); Send(&pkt); } void Server::SendTimeOfDay(session_t peer_id, u16 time, f32 time_speed) { NetworkPacket pkt(TOCLIENT_TIME_OF_DAY, 0, peer_id); pkt << time << time_speed; if (peer_id == PEER_ID_INEXISTENT) { m_clients.sendToAll(&pkt); } else { Send(&pkt); } } void Server::SendPlayerHP(session_t peer_id) { PlayerSAO *playersao = getPlayerSAO(peer_id); // In some rare case if the player is disconnected // while Lua call l_punch, for example, this can be NULL if (!playersao) return; SendHP(peer_id, playersao->getHP()); m_script->player_event(playersao,"health_changed"); // Send to other clients std::string str = gob_cmd_punched(playersao->getHP()); ActiveObjectMessage aom(playersao->getId(), true, str); playersao->m_messages_out.push(aom); } void Server::SendPlayerBreath(PlayerSAO *sao) { assert(sao); m_script->player_event(sao, "breath_changed"); SendBreath(sao->getPeerID(), sao->getBreath()); } void Server::SendMovePlayer(session_t peer_id) { RemotePlayer *player = m_env->getPlayer(peer_id); assert(player); PlayerSAO *sao = player->getPlayerSAO(); assert(sao); NetworkPacket pkt(TOCLIENT_MOVE_PLAYER, sizeof(v3f) + sizeof(f32) * 2, peer_id); pkt << sao->getBasePosition() << sao->getLookPitch() << sao->getRotation().Y; { v3f pos = sao->getBasePosition(); verbosestream << "Server: Sending TOCLIENT_MOVE_PLAYER" << " pos=(" << pos.X << "," << pos.Y << "," << pos.Z << ")" << " pitch=" << sao->getLookPitch() << " yaw=" << sao->getRotation().Y << std::endl; } Send(&pkt); } void Server::SendLocalPlayerAnimations(session_t peer_id, v2s32 animation_frames[4], f32 animation_speed) { NetworkPacket pkt(TOCLIENT_LOCAL_PLAYER_ANIMATIONS, 0, peer_id); pkt << animation_frames[0] << animation_frames[1] << animation_frames[2] << animation_frames[3] << animation_speed; Send(&pkt); } void Server::SendEyeOffset(session_t peer_id, v3f first, v3f third) { NetworkPacket pkt(TOCLIENT_EYE_OFFSET, 0, peer_id); pkt << first << third; Send(&pkt); } void Server::SendPlayerPrivileges(session_t peer_id) { RemotePlayer *player = m_env->getPlayer(peer_id); assert(player); if(player->getPeerId() == PEER_ID_INEXISTENT) return; std::set<std::string> privs; m_script->getAuth(player->getName(), NULL, &privs); NetworkPacket pkt(TOCLIENT_PRIVILEGES, 0, peer_id); pkt << (u16) privs.size(); for (const std::string &priv : privs) { pkt << priv; } Send(&pkt); } void Server::SendPlayerInventoryFormspec(session_t peer_id) { RemotePlayer *player = m_env->getPlayer(peer_id); assert(player); if (player->getPeerId() == PEER_ID_INEXISTENT) return; NetworkPacket pkt(TOCLIENT_INVENTORY_FORMSPEC, 0, peer_id); pkt.putLongString(FORMSPEC_VERSION_STRING + player->inventory_formspec); Send(&pkt); } void Server::SendPlayerFormspecPrepend(session_t peer_id) { RemotePlayer *player = m_env->getPlayer(peer_id); assert(player); if (player->getPeerId() == PEER_ID_INEXISTENT) return; NetworkPacket pkt(TOCLIENT_FORMSPEC_PREPEND, 0, peer_id); pkt << FORMSPEC_VERSION_STRING + player->formspec_prepend; Send(&pkt); } u32 Server::SendActiveObjectRemoveAdd(session_t peer_id, const std::string &datas) { NetworkPacket pkt(TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD, datas.size(), peer_id); pkt.putRawString(datas.c_str(), datas.size()); Send(&pkt); return pkt.getSize(); } void Server::SendActiveObjectMessages(session_t peer_id, const std::string &datas, bool reliable) { NetworkPacket pkt(TOCLIENT_ACTIVE_OBJECT_MESSAGES, datas.size(), peer_id); pkt.putRawString(datas.c_str(), datas.size()); m_clients.send(pkt.getPeerId(), reliable ? clientCommandFactoryTable[pkt.getCommand()].channel : 1, &pkt, reliable); } void Server::SendCSMRestrictionFlags(session_t peer_id) { NetworkPacket pkt(TOCLIENT_CSM_RESTRICTION_FLAGS, sizeof(m_csm_restriction_flags) + sizeof(m_csm_restriction_noderange), peer_id); pkt << m_csm_restriction_flags << m_csm_restriction_noderange; Send(&pkt); } s32 Server::playSound(const SimpleSoundSpec &spec, const ServerSoundParams &params) { // Find out initial position of sound bool pos_exists = false; v3f pos = params.getPos(m_env, &pos_exists); // If position is not found while it should be, cancel sound if(pos_exists != (params.type != ServerSoundParams::SSP_LOCAL)) return -1; // Filter destination clients std::vector<session_t> dst_clients; if(!params.to_player.empty()) { RemotePlayer *player = m_env->getPlayer(params.to_player.c_str()); if(!player){ infostream<<"Server::playSound: Player \""<<params.to_player <<"\" not found"<<std::endl; return -1; } if (player->getPeerId() == PEER_ID_INEXISTENT) { infostream<<"Server::playSound: Player \""<<params.to_player <<"\" not connected"<<std::endl; return -1; } dst_clients.push_back(player->getPeerId()); } else { std::vector<session_t> clients = m_clients.getClientIDs(); for (const session_t client_id : clients) { RemotePlayer *player = m_env->getPlayer(client_id); if (!player) continue; PlayerSAO *sao = player->getPlayerSAO(); if (!sao) continue; if (pos_exists) { if(sao->getBasePosition().getDistanceFrom(pos) > params.max_hear_distance) continue; } dst_clients.push_back(client_id); } } if(dst_clients.empty()) return -1; // Create the sound s32 id = m_next_sound_id++; // The sound will exist as a reference in m_playing_sounds m_playing_sounds[id] = ServerPlayingSound(); ServerPlayingSound &psound = m_playing_sounds[id]; psound.params = params; psound.spec = spec; float gain = params.gain * spec.gain; NetworkPacket pkt(TOCLIENT_PLAY_SOUND, 0); pkt << id << spec.name << gain << (u8) params.type << pos << params.object << params.loop << params.fade << params.pitch; // Backwards compability bool play_sound = gain > 0; for (const u16 dst_client : dst_clients) { if (play_sound || m_clients.getProtocolVersion(dst_client) >= 32) { psound.clients.insert(dst_client); m_clients.send(dst_client, 0, &pkt, true); } } return id; } void Server::stopSound(s32 handle) { // Get sound reference std::unordered_map<s32, ServerPlayingSound>::iterator i = m_playing_sounds.find(handle); if (i == m_playing_sounds.end()) return; ServerPlayingSound &psound = i->second; NetworkPacket pkt(TOCLIENT_STOP_SOUND, 4); pkt << handle; for (std::unordered_set<session_t>::const_iterator si = psound.clients.begin(); si != psound.clients.end(); ++si) { // Send as reliable m_clients.send(*si, 0, &pkt, true); } // Remove sound reference m_playing_sounds.erase(i); } void Server::fadeSound(s32 handle, float step, float gain) { // Get sound reference std::unordered_map<s32, ServerPlayingSound>::iterator i = m_playing_sounds.find(handle); if (i == m_playing_sounds.end()) return; ServerPlayingSound &psound = i->second; psound.params.gain = gain; NetworkPacket pkt(TOCLIENT_FADE_SOUND, 4); pkt << handle << step << gain; // Backwards compability bool play_sound = gain > 0; ServerPlayingSound compat_psound = psound; compat_psound.clients.clear(); NetworkPacket compat_pkt(TOCLIENT_STOP_SOUND, 4); compat_pkt << handle; for (std::unordered_set<u16>::iterator it = psound.clients.begin(); it != psound.clients.end();) { if (m_clients.getProtocolVersion(*it) >= 32) { // Send as reliable m_clients.send(*it, 0, &pkt, true); ++it; } else { compat_psound.clients.insert(*it); // Stop old sound m_clients.send(*it, 0, &compat_pkt, true); psound.clients.erase(it++); } } // Remove sound reference if (!play_sound || psound.clients.empty()) m_playing_sounds.erase(i); if (play_sound && !compat_psound.clients.empty()) { // Play new sound volume on older clients playSound(compat_psound.spec, compat_psound.params); } } void Server::sendRemoveNode(v3s16 p, std::unordered_set<u16> *far_players, float far_d_nodes) { float maxd = far_d_nodes * BS; v3f p_f = intToFloat(p, BS); v3s16 block_pos = getNodeBlockPos(p); NetworkPacket pkt(TOCLIENT_REMOVENODE, 6); pkt << p; std::vector<session_t> clients = m_clients.getClientIDs(); m_clients.lock(); for (session_t client_id : clients) { RemoteClient *client = m_clients.lockedGetClientNoEx(client_id); if (!client) continue; RemotePlayer *player = m_env->getPlayer(client_id); PlayerSAO *sao = player ? player->getPlayerSAO() : nullptr; // If player is far away, only set modified blocks not sent if (!client->isBlockSent(block_pos) || (sao && sao->getBasePosition().getDistanceFrom(p_f) > maxd)) { if (far_players) far_players->emplace(client_id); else client->SetBlockNotSent(block_pos); continue; } // Send as reliable m_clients.send(client_id, 0, &pkt, true); } m_clients.unlock(); } void Server::sendAddNode(v3s16 p, MapNode n, std::unordered_set<u16> *far_players, float far_d_nodes, bool remove_metadata) { float maxd = far_d_nodes * BS; v3f p_f = intToFloat(p, BS); v3s16 block_pos = getNodeBlockPos(p); NetworkPacket pkt(TOCLIENT_ADDNODE, 6 + 2 + 1 + 1 + 1); pkt << p << n.param0 << n.param1 << n.param2 << (u8) (remove_metadata ? 0 : 1); std::vector<session_t> clients = m_clients.getClientIDs(); m_clients.lock(); for (session_t client_id : clients) { RemoteClient *client = m_clients.lockedGetClientNoEx(client_id); if (!client) continue; RemotePlayer *player = m_env->getPlayer(client_id); PlayerSAO *sao = player ? player->getPlayerSAO() : nullptr; // If player is far away, only set modified blocks not sent if (!client->isBlockSent(block_pos) || (sao && sao->getBasePosition().getDistanceFrom(p_f) > maxd)) { if (far_players) far_players->emplace(client_id); else client->SetBlockNotSent(block_pos); continue; } // Send as reliable m_clients.send(client_id, 0, &pkt, true); } m_clients.unlock(); } void Server::sendMetadataChanged(const std::list<v3s16> &meta_updates, float far_d_nodes) { float maxd = far_d_nodes * BS; NodeMetadataList meta_updates_list(false); std::vector<session_t> clients = m_clients.getClientIDs(); m_clients.lock(); for (session_t i : clients) { RemoteClient *client = m_clients.lockedGetClientNoEx(i); if (!client) continue; ServerActiveObject *player = m_env->getActiveObject(i); v3f player_pos = player ? player->getBasePosition() : v3f(); for (const v3s16 &pos : meta_updates) { NodeMetadata *meta = m_env->getMap().getNodeMetadata(pos); if (!meta) continue; v3s16 block_pos = getNodeBlockPos(pos); if (!client->isBlockSent(block_pos) || (player && player_pos.getDistanceFrom(intToFloat(pos, BS)) > maxd)) { client->SetBlockNotSent(block_pos); continue; } // Add the change to send list meta_updates_list.set(pos, meta); } if (meta_updates_list.size() == 0) continue; // Send the meta changes std::ostringstream os(std::ios::binary); meta_updates_list.serialize(os, client->net_proto_version, false, true); std::ostringstream oss(std::ios::binary); compressZlib(os.str(), oss); NetworkPacket pkt(TOCLIENT_NODEMETA_CHANGED, 0); pkt.putLongString(oss.str()); m_clients.send(i, 0, &pkt, true); meta_updates_list.clear(); } m_clients.unlock(); } void Server::SendBlockNoLock(session_t peer_id, MapBlock *block, u8 ver, u16 net_proto_version) { /* Create a packet with the block in the right format */ std::ostringstream os(std::ios_base::binary); block->serialize(os, ver, false); block->serializeNetworkSpecific(os); std::string s = os.str(); NetworkPacket pkt(TOCLIENT_BLOCKDATA, 2 + 2 + 2 + 2 + s.size(), peer_id); pkt << block->getPos(); pkt.putRawString(s.c_str(), s.size()); Send(&pkt); } void Server::SendBlocks(float dtime) { MutexAutoLock envlock(m_env_mutex); //TODO check if one big lock could be faster then multiple small ones ScopeProfiler sp(g_profiler, "Server: sel and send blocks to clients"); std::vector<PrioritySortedBlockTransfer> queue; u32 total_sending = 0; { ScopeProfiler sp2(g_profiler, "Server: selecting blocks for sending"); std::vector<session_t> clients = m_clients.getClientIDs(); m_clients.lock(); for (const session_t client_id : clients) { RemoteClient *client = m_clients.lockedGetClientNoEx(client_id, CS_Active); if (!client) continue; total_sending += client->getSendingCount(); client->GetNextBlocks(m_env,m_emerge, dtime, queue); } m_clients.unlock(); } // Sort. // Lowest priority number comes first. // Lowest is most important. std::sort(queue.begin(), queue.end()); m_clients.lock(); // Maximal total count calculation // The per-client block sends is halved with the maximal online users u32 max_blocks_to_send = (m_env->getPlayerCount() + g_settings->getU32("max_users")) * g_settings->getU32("max_simultaneous_block_sends_per_client") / 4 + 1; for (const PrioritySortedBlockTransfer &block_to_send : queue) { if (total_sending >= max_blocks_to_send) break; MapBlock *block = nullptr; try { block = m_env->getMap().getBlockNoCreate(block_to_send.pos); } catch (const InvalidPositionException &e) { continue; } RemoteClient *client = m_clients.lockedGetClientNoEx(block_to_send.peer_id, CS_Active); if (!client) continue; SendBlockNoLock(block_to_send.peer_id, block, client->serialization_version, client->net_proto_version); client->SentBlock(block_to_send.pos); total_sending++; } m_clients.unlock(); } void Server::fillMediaCache() { infostream<<"Server: Calculating media file checksums"<<std::endl; // Collect all media file paths std::vector<std::string> paths; m_modmgr->getModsMediaPaths(paths); fs::GetRecursiveDirs(paths, m_gamespec.path + DIR_DELIM + "textures"); fs::GetRecursiveDirs(paths, porting::path_user + DIR_DELIM + "textures" + DIR_DELIM + "server"); // Collect media file information from paths into cache for (const std::string &mediapath : paths) { std::vector<fs::DirListNode> dirlist = fs::GetDirListing(mediapath); for (const fs::DirListNode &dln : dirlist) { if (dln.dir) // Ignode dirs continue; std::string filename = dln.name; // If name contains illegal characters, ignore the file if (!string_allowed(filename, TEXTURENAME_ALLOWED_CHARS)) { infostream<<"Server: ignoring illegal file name: \"" << filename << "\"" << std::endl; continue; } // If name is not in a supported format, ignore it const char *supported_ext[] = { ".png", ".jpg", ".bmp", ".tga", ".pcx", ".ppm", ".psd", ".wal", ".rgb", ".ogg", ".x", ".b3d", ".md2", ".obj", // Custom translation file format ".tr", NULL }; if (removeStringEnd(filename, supported_ext).empty()){ infostream << "Server: ignoring unsupported file extension: \"" << filename << "\"" << std::endl; continue; } // Ok, attempt to load the file and add to cache std::string filepath; filepath.append(mediapath).append(DIR_DELIM).append(filename); // Read data std::ifstream fis(filepath.c_str(), std::ios_base::binary); if (!fis.good()) { errorstream << "Server::fillMediaCache(): Could not open \"" << filename << "\" for reading" << std::endl; continue; } std::ostringstream tmp_os(std::ios_base::binary); bool bad = false; for(;;) { char buf[1024]; fis.read(buf, 1024); std::streamsize len = fis.gcount(); tmp_os.write(buf, len); if (fis.eof()) break; if (!fis.good()) { bad = true; break; } } if(bad) { errorstream<<"Server::fillMediaCache(): Failed to read \"" << filename << "\"" << std::endl; continue; } if(tmp_os.str().length() == 0) { errorstream << "Server::fillMediaCache(): Empty file \"" << filepath << "\"" << std::endl; continue; } SHA1 sha1; sha1.addBytes(tmp_os.str().c_str(), tmp_os.str().length()); unsigned char *digest = sha1.getDigest(); std::string sha1_base64 = base64_encode(digest, 20); std::string sha1_hex = hex_encode((char*)digest, 20); free(digest); // Put in list m_media[filename] = MediaInfo(filepath, sha1_base64); verbosestream << "Server: " << sha1_hex << " is " << filename << std::endl; } } } void Server::sendMediaAnnouncement(session_t peer_id, const std::string &lang_code) { verbosestream << "Server: Announcing files to id(" << peer_id << ")" << std::endl; // Make packet NetworkPacket pkt(TOCLIENT_ANNOUNCE_MEDIA, 0, peer_id); u16 media_sent = 0; std::string lang_suffix; lang_suffix.append(".").append(lang_code).append(".tr"); for (const auto &i : m_media) { if (str_ends_with(i.first, ".tr") && !str_ends_with(i.first, lang_suffix)) continue; media_sent++; } pkt << media_sent; for (const auto &i : m_media) { if (str_ends_with(i.first, ".tr") && !str_ends_with(i.first, lang_suffix)) continue; pkt << i.first << i.second.sha1_digest; } pkt << g_settings->get("remote_media"); Send(&pkt); } struct SendableMedia { std::string name; std::string path; std::string data; SendableMedia(const std::string &name_="", const std::string &path_="", const std::string &data_=""): name(name_), path(path_), data(data_) {} }; void Server::sendRequestedMedia(session_t peer_id, const std::vector<std::string> &tosend) { verbosestream<<"Server::sendRequestedMedia(): " <<"Sending files to client"<<std::endl; /* Read files */ // Put 5kB in one bunch (this is not accurate) u32 bytes_per_bunch = 5000; std::vector< std::vector<SendableMedia> > file_bunches; file_bunches.emplace_back(); u32 file_size_bunch_total = 0; for (const std::string &name : tosend) { if (m_media.find(name) == m_media.end()) { errorstream<<"Server::sendRequestedMedia(): Client asked for " <<"unknown file \""<<(name)<<"\""<<std::endl; continue; } //TODO get path + name std::string tpath = m_media[name].path; // Read data std::ifstream fis(tpath.c_str(), std::ios_base::binary); if(!fis.good()){ errorstream<<"Server::sendRequestedMedia(): Could not open \"" <<tpath<<"\" for reading"<<std::endl; continue; } std::ostringstream tmp_os(std::ios_base::binary); bool bad = false; for(;;) { char buf[1024]; fis.read(buf, 1024); std::streamsize len = fis.gcount(); tmp_os.write(buf, len); file_size_bunch_total += len; if(fis.eof()) break; if(!fis.good()) { bad = true; break; } } if (bad) { errorstream<<"Server::sendRequestedMedia(): Failed to read \"" <<name<<"\""<<std::endl; continue; } /*infostream<<"Server::sendRequestedMedia(): Loaded \"" <<tname<<"\""<<std::endl;*/ // Put in list file_bunches[file_bunches.size()-1].emplace_back(name, tpath, tmp_os.str()); // Start next bunch if got enough data if(file_size_bunch_total >= bytes_per_bunch) { file_bunches.emplace_back(); file_size_bunch_total = 0; } } /* Create and send packets */ u16 num_bunches = file_bunches.size(); for (u16 i = 0; i < num_bunches; i++) { /* u16 command u16 total number of texture bunches u16 index of this bunch u32 number of files in this bunch for each file { u16 length of name string name u32 length of data data } */ NetworkPacket pkt(TOCLIENT_MEDIA, 4 + 0, peer_id); pkt << num_bunches << i << (u32) file_bunches[i].size(); for (const SendableMedia &j : file_bunches[i]) { pkt << j.name; pkt.putLongString(j.data); } verbosestream << "Server::sendRequestedMedia(): bunch " << i << "/" << num_bunches << " files=" << file_bunches[i].size() << " size=" << pkt.getSize() << std::endl; Send(&pkt); } } void Server::sendDetachedInventory(const std::string &name, session_t peer_id) { const auto &inv_it = m_detached_inventories.find(name); const auto &player_it = m_detached_inventories_player.find(name); if (player_it == m_detached_inventories_player.end() || player_it->second.empty()) { // OK. Send to everyone } else { RemotePlayer *p = m_env->getPlayer(player_it->second.c_str()); if (!p) return; // Player is offline if (peer_id != PEER_ID_INEXISTENT && peer_id != p->getPeerId()) return; // Caller requested send to a different player, so don't send. peer_id = p->getPeerId(); } NetworkPacket pkt(TOCLIENT_DETACHED_INVENTORY, 0, peer_id); pkt << name; if (inv_it == m_detached_inventories.end()) { pkt << false; // Remove inventory } else { pkt << true; // Update inventory // Serialization & NetworkPacket isn't a love story std::ostringstream os(std::ios_base::binary); inv_it->second->serialize(os); std::string os_str = os.str(); pkt << static_cast<u16>(os_str.size()); // HACK: to keep compatibility with 5.0.0 clients pkt.putRawString(os_str); } if (peer_id == PEER_ID_INEXISTENT) m_clients.sendToAll(&pkt); else Send(&pkt); } void Server::sendDetachedInventories(session_t peer_id) { for (const auto &detached_inventory : m_detached_inventories) { const std::string &name = detached_inventory.first; //Inventory *inv = i->second; sendDetachedInventory(name, peer_id); } } /* Something random */ void Server::DiePlayer(session_t peer_id, const PlayerHPChangeReason &reason) { PlayerSAO *playersao = getPlayerSAO(peer_id); // In some rare cases this can be NULL -- if the player is disconnected // when a Lua function modifies l_punch, for example if (!playersao) return; infostream << "Server::DiePlayer(): Player " << playersao->getPlayer()->getName() << " dies" << std::endl; playersao->setHP(0, reason); playersao->clearParentAttachment(); // Trigger scripted stuff m_script->on_dieplayer(playersao, reason); SendPlayerHP(peer_id); SendDeathscreen(peer_id, false, v3f(0,0,0)); } void Server::RespawnPlayer(session_t peer_id) { PlayerSAO *playersao = getPlayerSAO(peer_id); assert(playersao); infostream << "Server::RespawnPlayer(): Player " << playersao->getPlayer()->getName() << " respawns" << std::endl; playersao->setHP(playersao->accessObjectProperties()->hp_max, PlayerHPChangeReason(PlayerHPChangeReason::RESPAWN)); playersao->setBreath(playersao->accessObjectProperties()->breath_max); bool repositioned = m_script->on_respawnplayer(playersao); if (!repositioned) { // setPos will send the new position to client playersao->setPos(findSpawnPos()); } SendPlayerHP(peer_id); } void Server::DenySudoAccess(session_t peer_id) { NetworkPacket pkt(TOCLIENT_DENY_SUDO_MODE, 0, peer_id); Send(&pkt); } void Server::DenyAccessVerCompliant(session_t peer_id, u16 proto_ver, AccessDeniedCode reason, const std::string &str_reason, bool reconnect) { SendAccessDenied(peer_id, reason, str_reason, reconnect); m_clients.event(peer_id, CSE_SetDenied); DisconnectPeer(peer_id); } void Server::DenyAccess(session_t peer_id, AccessDeniedCode reason, const std::string &custom_reason) { SendAccessDenied(peer_id, reason, custom_reason); m_clients.event(peer_id, CSE_SetDenied); DisconnectPeer(peer_id); } // 13/03/15: remove this function when protocol version 25 will become // the minimum version for MT users, maybe in 1 year void Server::DenyAccess_Legacy(session_t peer_id, const std::wstring &reason) { SendAccessDenied_Legacy(peer_id, reason); m_clients.event(peer_id, CSE_SetDenied); DisconnectPeer(peer_id); } void Server::DisconnectPeer(session_t peer_id) { m_modchannel_mgr->leaveAllChannels(peer_id); m_con->DisconnectPeer(peer_id); } void Server::acceptAuth(session_t peer_id, bool forSudoMode) { if (!forSudoMode) { RemoteClient* client = getClient(peer_id, CS_Invalid); NetworkPacket resp_pkt(TOCLIENT_AUTH_ACCEPT, 1 + 6 + 8 + 4, peer_id); // Right now, the auth mechs don't change between login and sudo mode. u32 sudo_auth_mechs = client->allowed_auth_mechs; client->allowed_sudo_mechs = sudo_auth_mechs; resp_pkt << v3f(0,0,0) << (u64) m_env->getServerMap().getSeed() << g_settings->getFloat("dedicated_server_step") << sudo_auth_mechs; Send(&resp_pkt); m_clients.event(peer_id, CSE_AuthAccept); } else { NetworkPacket resp_pkt(TOCLIENT_ACCEPT_SUDO_MODE, 1 + 6 + 8 + 4, peer_id); // We only support SRP right now u32 sudo_auth_mechs = AUTH_MECHANISM_FIRST_SRP; resp_pkt << sudo_auth_mechs; Send(&resp_pkt); m_clients.event(peer_id, CSE_SudoSuccess); } } void Server::DeleteClient(session_t peer_id, ClientDeletionReason reason) { std::wstring message; { /* Clear references to playing sounds */ for (std::unordered_map<s32, ServerPlayingSound>::iterator i = m_playing_sounds.begin(); i != m_playing_sounds.end();) { ServerPlayingSound &psound = i->second; psound.clients.erase(peer_id); if (psound.clients.empty()) m_playing_sounds.erase(i++); else ++i; } // clear formspec info so the next client can't abuse the current state m_formspec_state_data.erase(peer_id); RemotePlayer *player = m_env->getPlayer(peer_id); /* Run scripts and remove from environment */ if (player) { PlayerSAO *playersao = player->getPlayerSAO(); assert(playersao); playersao->clearChildAttachments(); playersao->clearParentAttachment(); // inform connected clients const std::string &player_name = player->getName(); NetworkPacket notice(TOCLIENT_UPDATE_PLAYER_LIST, 0, PEER_ID_INEXISTENT); // (u16) 1 + std::string represents a vector serialization representation notice << (u8) PLAYER_LIST_REMOVE << (u16) 1 << player_name; m_clients.sendToAll(&notice); // run scripts m_script->on_leaveplayer(playersao, reason == CDR_TIMEOUT); playersao->disconnected(); } /* Print out action */ { if (player && reason != CDR_DENY) { std::ostringstream os(std::ios_base::binary); std::vector<session_t> clients = m_clients.getClientIDs(); for (const session_t client_id : clients) { // Get player RemotePlayer *player = m_env->getPlayer(client_id); if (!player) continue; // Get name of player os << player->getName() << " "; } std::string name = player->getName(); actionstream << name << " " << (reason == CDR_TIMEOUT ? "times out." : "leaves game.") << " List of players: " << os.str() << std::endl; if (m_admin_chat) m_admin_chat->outgoing_queue.push_back( new ChatEventNick(CET_NICK_REMOVE, name)); } } { MutexAutoLock env_lock(m_env_mutex); m_clients.DeleteClient(peer_id); } } // Send leave chat message to all remaining clients if (!message.empty()) { SendChatMessage(PEER_ID_INEXISTENT, ChatMessage(CHATMESSAGE_TYPE_ANNOUNCE, message)); } } void Server::UpdateCrafting(RemotePlayer *player) { InventoryList *clist = player->inventory.getList("craft"); if (!clist || clist->getSize() == 0) return; // Get a preview for crafting ItemStack preview; InventoryLocation loc; loc.setPlayer(player->getName()); std::vector<ItemStack> output_replacements; getCraftingResult(&player->inventory, preview, output_replacements, false, this); m_env->getScriptIface()->item_CraftPredict(preview, player->getPlayerSAO(), clist, loc); InventoryList *plist = player->inventory.getList("craftpreview"); if (plist && plist->getSize() >= 1) { // Put the new preview in plist->changeItem(0, preview); } } void Server::handleChatInterfaceEvent(ChatEvent *evt) { if (evt->type == CET_NICK_ADD) { // The terminal informed us of its nick choice m_admin_nick = ((ChatEventNick *)evt)->nick; if (!m_script->getAuth(m_admin_nick, NULL, NULL)) { errorstream << "You haven't set up an account." << std::endl << "Please log in using the client as '" << m_admin_nick << "' with a secure password." << std::endl << "Until then, you can't execute admin tasks via the console," << std::endl << "and everybody can claim the user account instead of you," << std::endl << "giving them full control over this server." << std::endl; } } else { assert(evt->type == CET_CHAT); handleAdminChat((ChatEventChat *)evt); } } std::wstring Server::handleChat(const std::string &name, const std::wstring &wname, std::wstring wmessage, bool check_shout_priv, RemotePlayer *player) { // If something goes wrong, this player is to blame RollbackScopeActor rollback_scope(m_rollback, std::string("player:") + name); if (g_settings->getBool("strip_color_codes")) wmessage = unescape_enriched(wmessage); if (player) { switch (player->canSendChatMessage()) { case RPLAYER_CHATRESULT_FLOODING: { std::wstringstream ws; ws << L"You cannot send more messages. You are limited to " << g_settings->getFloat("chat_message_limit_per_10sec") << L" messages per 10 seconds."; return ws.str(); } case RPLAYER_CHATRESULT_KICK: DenyAccess_Legacy(player->getPeerId(), L"You have been kicked due to message flooding."); return L""; case RPLAYER_CHATRESULT_OK: break; default: FATAL_ERROR("Unhandled chat filtering result found."); } } if (m_max_chatmessage_length > 0 && wmessage.length() > m_max_chatmessage_length) { return L"Your message exceed the maximum chat message limit set on the server. " L"It was refused. Send a shorter message"; } auto message = trim(wide_to_utf8(wmessage)); if (message.find_first_of("\n\r") != std::wstring::npos) { return L"New lines are not permitted in chat messages"; } // Run script hook, exit if script ate the chat message if (m_script->on_chat_message(name, message)) return L""; // Line to send std::wstring line; // Whether to send line to the player that sent the message, or to all players bool broadcast_line = true; if (check_shout_priv && !checkPriv(name, "shout")) { line += L"-!- You don't have permission to shout."; broadcast_line = false; } else { line += L"<"; line += wname; line += L"> "; line += wmessage; } /* Tell calling method to send the message to sender */ if (!broadcast_line) return line; /* Send the message to others */ actionstream << "CHAT: " << wide_to_narrow(unescape_enriched(line)) << std::endl; std::vector<session_t> clients = m_clients.getClientIDs(); /* Send the message back to the inital sender if they are using protocol version >= 29 */ session_t peer_id_to_avoid_sending = (player ? player->getPeerId() : PEER_ID_INEXISTENT); if (player && player->protocol_version >= 29) peer_id_to_avoid_sending = PEER_ID_INEXISTENT; for (u16 cid : clients) { if (cid != peer_id_to_avoid_sending) SendChatMessage(cid, ChatMessage(line)); } return L""; } void Server::handleAdminChat(const ChatEventChat *evt) { std::string name = evt->nick; std::wstring wname = utf8_to_wide(name); std::wstring wmessage = evt->evt_msg; std::wstring answer = handleChat(name, wname, wmessage); // If asked to send answer to sender if (!answer.empty()) { m_admin_chat->outgoing_queue.push_back(new ChatEventChat("", answer)); } } RemoteClient *Server::getClient(session_t peer_id, ClientState state_min) { RemoteClient *client = getClientNoEx(peer_id,state_min); if(!client) throw ClientNotFoundException("Client not found"); return client; } RemoteClient *Server::getClientNoEx(session_t peer_id, ClientState state_min) { return m_clients.getClientNoEx(peer_id, state_min); } std::string Server::getPlayerName(session_t peer_id) { RemotePlayer *player = m_env->getPlayer(peer_id); if (!player) return "[id="+itos(peer_id)+"]"; return player->getName(); } PlayerSAO *Server::getPlayerSAO(session_t peer_id) { RemotePlayer *player = m_env->getPlayer(peer_id); if (!player) return NULL; return player->getPlayerSAO(); } std::wstring Server::getStatusString() { std::wostringstream os(std::ios_base::binary); os << L"# Server: "; // Version os << L"version=" << narrow_to_wide(g_version_string); // Uptime os << L", uptime=" << m_uptime.get(); // Max lag estimate os << L", max_lag=" << (m_env ? m_env->getMaxLagEstimate() : 0); // Information about clients bool first = true; os << L", clients={"; if (m_env) { std::vector<session_t> clients = m_clients.getClientIDs(); for (session_t client_id : clients) { RemotePlayer *player = m_env->getPlayer(client_id); // Get name of player std::wstring name = L"unknown"; if (player) name = narrow_to_wide(player->getName()); // Add name to information string if (!first) os << L", "; else first = false; os << name; } } os << L"}"; if (m_env && !((ServerMap*)(&m_env->getMap()))->isSavingEnabled()) os << std::endl << L"# Server: " << " WARNING: Map saving is disabled."; if (!g_settings->get("motd").empty()) os << std::endl << L"# Server: " << narrow_to_wide(g_settings->get("motd")); return os.str(); } std::set<std::string> Server::getPlayerEffectivePrivs(const std::string &name) { std::set<std::string> privs; m_script->getAuth(name, NULL, &privs); return privs; } bool Server::checkPriv(const std::string &name, const std::string &priv) { std::set<std::string> privs = getPlayerEffectivePrivs(name); return (privs.count(priv) != 0); } void Server::reportPrivsModified(const std::string &name) { if (name.empty()) { std::vector<session_t> clients = m_clients.getClientIDs(); for (const session_t client_id : clients) { RemotePlayer *player = m_env->getPlayer(client_id); reportPrivsModified(player->getName()); } } else { RemotePlayer *player = m_env->getPlayer(name.c_str()); if (!player) return; SendPlayerPrivileges(player->getPeerId()); PlayerSAO *sao = player->getPlayerSAO(); if(!sao) return; sao->updatePrivileges( getPlayerEffectivePrivs(name), isSingleplayer()); } } void Server::reportInventoryFormspecModified(const std::string &name) { RemotePlayer *player = m_env->getPlayer(name.c_str()); if (!player) return; SendPlayerInventoryFormspec(player->getPeerId()); } void Server::reportFormspecPrependModified(const std::string &name) { RemotePlayer *player = m_env->getPlayer(name.c_str()); if (!player) return; SendPlayerFormspecPrepend(player->getPeerId()); } void Server::setIpBanned(const std::string &ip, const std::string &name) { m_banmanager->add(ip, name); } void Server::unsetIpBanned(const std::string &ip_or_name) { m_banmanager->remove(ip_or_name); } std::string Server::getBanDescription(const std::string &ip_or_name) { return m_banmanager->getBanDescription(ip_or_name); } void Server::notifyPlayer(const char *name, const std::wstring &msg) { // m_env will be NULL if the server is initializing if (!m_env) return; if (m_admin_nick == name && !m_admin_nick.empty()) { m_admin_chat->outgoing_queue.push_back(new ChatEventChat("", msg)); } RemotePlayer *player = m_env->getPlayer(name); if (!player) { return; } if (player->getPeerId() == PEER_ID_INEXISTENT) return; SendChatMessage(player->getPeerId(), ChatMessage(msg)); } bool Server::showFormspec(const char *playername, const std::string &formspec, const std::string &formname) { // m_env will be NULL if the server is initializing if (!m_env) return false; RemotePlayer *player = m_env->getPlayer(playername); if (!player) return false; SendShowFormspecMessage(player->getPeerId(), formspec, formname); return true; } u32 Server::hudAdd(RemotePlayer *player, HudElement *form) { if (!player) return -1; u32 id = player->addHud(form); SendHUDAdd(player->getPeerId(), id, form); return id; } bool Server::hudRemove(RemotePlayer *player, u32 id) { if (!player) return false; HudElement* todel = player->removeHud(id); if (!todel) return false; delete todel; SendHUDRemove(player->getPeerId(), id); return true; } bool Server::hudChange(RemotePlayer *player, u32 id, HudElementStat stat, void *data) { if (!player) return false; SendHUDChange(player->getPeerId(), id, stat, data); return true; } bool Server::hudSetFlags(RemotePlayer *player, u32 flags, u32 mask) { if (!player) return false; SendHUDSetFlags(player->getPeerId(), flags, mask); player->hud_flags &= ~mask; player->hud_flags |= flags; PlayerSAO* playersao = player->getPlayerSAO(); if (!playersao) return false; m_script->player_event(playersao, "hud_changed"); return true; } bool Server::hudSetHotbarItemcount(RemotePlayer *player, s32 hotbar_itemcount) { if (!player) return false; if (hotbar_itemcount <= 0 || hotbar_itemcount > HUD_HOTBAR_ITEMCOUNT_MAX) return false; player->setHotbarItemcount(hotbar_itemcount); std::ostringstream os(std::ios::binary); writeS32(os, hotbar_itemcount); SendHUDSetParam(player->getPeerId(), HUD_PARAM_HOTBAR_ITEMCOUNT, os.str()); return true; } void Server::hudSetHotbarImage(RemotePlayer *player, std::string name) { if (!player) return; player->setHotbarImage(name); SendHUDSetParam(player->getPeerId(), HUD_PARAM_HOTBAR_IMAGE, name); } void Server::hudSetHotbarSelectedImage(RemotePlayer *player, std::string name) { if (!player) return; player->setHotbarSelectedImage(name); SendHUDSetParam(player->getPeerId(), HUD_PARAM_HOTBAR_SELECTED_IMAGE, name); } Address Server::getPeerAddress(session_t peer_id) { return m_con->GetPeerAddress(peer_id); } void Server::setLocalPlayerAnimations(RemotePlayer *player, v2s32 animation_frames[4], f32 frame_speed) { sanity_check(player); player->setLocalAnimations(animation_frames, frame_speed); SendLocalPlayerAnimations(player->getPeerId(), animation_frames, frame_speed); } void Server::setPlayerEyeOffset(RemotePlayer *player, const v3f &first, const v3f &third) { sanity_check(player); player->eye_offset_first = first; player->eye_offset_third = third; SendEyeOffset(player->getPeerId(), first, third); } void Server::setSky(RemotePlayer *player, const video::SColor &bgcolor, const std::string &type, const std::vector<std::string> &params, bool &clouds) { sanity_check(player); player->setSky(bgcolor, type, params, clouds); SendSetSky(player->getPeerId(), bgcolor, type, params, clouds); } void Server::setClouds(RemotePlayer *player, const CloudParams &params) { sanity_check(player); player->setCloudParams(params); SendCloudParams(player->getPeerId(), params); } bool Server::overrideDayNightRatio(RemotePlayer *player, bool do_override, float ratio) { if (!player) return false; player->overrideDayNightRatio(do_override, ratio); SendOverrideDayNightRatio(player->getPeerId(), do_override, ratio); return true; } void Server::notifyPlayers(const std::wstring &msg) { SendChatMessage(PEER_ID_INEXISTENT, ChatMessage(msg)); } void Server::spawnParticle(const std::string &playername, v3f pos, v3f velocity, v3f acceleration, float expirationtime, float size, bool collisiondetection, bool collision_removal, bool object_collision, bool vertical, const std::string &texture, const struct TileAnimationParams &animation, u8 glow) { // m_env will be NULL if the server is initializing if (!m_env) return; session_t peer_id = PEER_ID_INEXISTENT; u16 proto_ver = 0; if (!playername.empty()) { RemotePlayer *player = m_env->getPlayer(playername.c_str()); if (!player) return; peer_id = player->getPeerId(); proto_ver = player->protocol_version; } SendSpawnParticle(peer_id, proto_ver, pos, velocity, acceleration, expirationtime, size, collisiondetection, collision_removal, object_collision, vertical, texture, animation, glow); } u32 Server::addParticleSpawner(u16 amount, float spawntime, v3f minpos, v3f maxpos, v3f minvel, v3f maxvel, v3f minacc, v3f maxacc, float minexptime, float maxexptime, float minsize, float maxsize, bool collisiondetection, bool collision_removal, bool object_collision, ServerActiveObject *attached, bool vertical, const std::string &texture, const std::string &playername, const struct TileAnimationParams &animation, u8 glow) { // m_env will be NULL if the server is initializing if (!m_env) return -1; session_t peer_id = PEER_ID_INEXISTENT; u16 proto_ver = 0; if (!playername.empty()) { RemotePlayer *player = m_env->getPlayer(playername.c_str()); if (!player) return -1; peer_id = player->getPeerId(); proto_ver = player->protocol_version; } u16 attached_id = attached ? attached->getId() : 0; u32 id; if (attached_id == 0) id = m_env->addParticleSpawner(spawntime); else id = m_env->addParticleSpawner(spawntime, attached_id); SendAddParticleSpawner(peer_id, proto_ver, amount, spawntime, minpos, maxpos, minvel, maxvel, minacc, maxacc, minexptime, maxexptime, minsize, maxsize, collisiondetection, collision_removal, object_collision, attached_id, vertical, texture, id, animation, glow); return id; } void Server::deleteParticleSpawner(const std::string &playername, u32 id) { // m_env will be NULL if the server is initializing if (!m_env) throw ServerError("Can't delete particle spawners during initialisation!"); session_t peer_id = PEER_ID_INEXISTENT; if (!playername.empty()) { RemotePlayer *player = m_env->getPlayer(playername.c_str()); if (!player) return; peer_id = player->getPeerId(); } m_env->deleteParticleSpawner(id); SendDeleteParticleSpawner(peer_id, id); } Inventory* Server::createDetachedInventory(const std::string &name, const std::string &player) { if(m_detached_inventories.count(name) > 0){ infostream<<"Server clearing detached inventory \""<<name<<"\""<<std::endl; delete m_detached_inventories[name]; } else { infostream<<"Server creating detached inventory \""<<name<<"\""<<std::endl; } Inventory *inv = new Inventory(m_itemdef); sanity_check(inv); m_detached_inventories[name] = inv; m_detached_inventories_player[name] = player; //TODO find a better way to do this sendDetachedInventory(name,PEER_ID_INEXISTENT); return inv; } bool Server::removeDetachedInventory(const std::string &name) { const auto &inv_it = m_detached_inventories.find(name); if (inv_it == m_detached_inventories.end()) return false; delete inv_it->second; m_detached_inventories.erase(inv_it); const auto &player_it = m_detached_inventories_player.find(name); if (player_it != m_detached_inventories_player.end()) { RemotePlayer *player = m_env->getPlayer(player_it->second.c_str()); if (player && player->getPeerId() != PEER_ID_INEXISTENT) sendDetachedInventory(name, player->getPeerId()); m_detached_inventories_player.erase(player_it); } else { // Notify all players about the change sendDetachedInventory(name, PEER_ID_INEXISTENT); } return true; } // actions: time-reversed list // Return value: success/failure bool Server::rollbackRevertActions(const std::list<RollbackAction> &actions, std::list<std::string> *log) { infostream<<"Server::rollbackRevertActions(len="<<actions.size()<<")"<<std::endl; ServerMap *map = (ServerMap*)(&m_env->getMap()); // Fail if no actions to handle if (actions.empty()) { assert(log); log->push_back("Nothing to do."); return false; } int num_tried = 0; int num_failed = 0; for (const RollbackAction &action : actions) { num_tried++; bool success = action.applyRevert(map, this, this); if(!success){ num_failed++; std::ostringstream os; os<<"Revert of step ("<<num_tried<<") "<<action.toString()<<" failed"; infostream<<"Map::rollbackRevertActions(): "<<os.str()<<std::endl; if (log) log->push_back(os.str()); }else{ std::ostringstream os; os<<"Successfully reverted step ("<<num_tried<<") "<<action.toString(); infostream<<"Map::rollbackRevertActions(): "<<os.str()<<std::endl; if (log) log->push_back(os.str()); } } infostream<<"Map::rollbackRevertActions(): "<<num_failed<<"/"<<num_tried <<" failed"<<std::endl; // Call it done if less than half failed return num_failed <= num_tried/2; } // IGameDef interface // Under envlock IItemDefManager *Server::getItemDefManager() { return m_itemdef; } const NodeDefManager *Server::getNodeDefManager() { return m_nodedef; } ICraftDefManager *Server::getCraftDefManager() { return m_craftdef; } u16 Server::allocateUnknownNodeId(const std::string &name) { return m_nodedef->allocateDummy(name); } IWritableItemDefManager *Server::getWritableItemDefManager() { return m_itemdef; } NodeDefManager *Server::getWritableNodeDefManager() { return m_nodedef; } IWritableCraftDefManager *Server::getWritableCraftDefManager() { return m_craftdef; } const std::vector<ModSpec> & Server::getMods() const { return m_modmgr->getMods(); } const ModSpec *Server::getModSpec(const std::string &modname) const { return m_modmgr->getModSpec(modname); } void Server::getModNames(std::vector<std::string> &modlist) { m_modmgr->getModNames(modlist); } std::string Server::getBuiltinLuaPath() { return porting::path_share + DIR_DELIM + "builtin"; } std::string Server::getModStoragePath() const { return m_path_world + DIR_DELIM + "mod_storage"; } v3f Server::findSpawnPos() { ServerMap &map = m_env->getServerMap(); v3f nodeposf; if (g_settings->getV3FNoEx("static_spawnpoint", nodeposf)) { return nodeposf * BS; } bool is_good = false; // Limit spawn range to mapgen edges (determined by 'mapgen_limit') s32 range_max = map.getMapgenParams()->getSpawnRangeMax(); // Try to find a good place a few times for(s32 i = 0; i < 4000 && !is_good; i++) { s32 range = MYMIN(1 + i, range_max); // We're going to try to throw the player to this position v2s16 nodepos2d = v2s16( -range + (myrand() % (range * 2)), -range + (myrand() % (range * 2))); // Get spawn level at point s16 spawn_level = m_emerge->getSpawnLevelAtPoint(nodepos2d); // Continue if MAX_MAP_GENERATION_LIMIT was returned by // the mapgen to signify an unsuitable spawn position if (spawn_level == MAX_MAP_GENERATION_LIMIT) continue; v3s16 nodepos(nodepos2d.X, spawn_level, nodepos2d.Y); s32 air_count = 0; for (s32 i = 0; i < 10; i++) { v3s16 blockpos = getNodeBlockPos(nodepos); map.emergeBlock(blockpos, true); content_t c = map.getNodeNoEx(nodepos).getContent(); if (c == CONTENT_AIR || c == CONTENT_IGNORE) { air_count++; if (air_count >= 2) { nodeposf = intToFloat(nodepos, BS); // Don't spawn the player outside map boundaries if (objectpos_over_limit(nodeposf)) continue; is_good = true; break; } } nodepos.Y++; } } return nodeposf; } void Server::requestShutdown(const std::string &msg, bool reconnect, float delay) { if (delay == 0.0f) { // No delay, shutdown immediately m_shutdown_state.is_requested = true; // only print to the infostream, a chat message saying // "Server Shutting Down" is sent when the server destructs. infostream << "*** Immediate Server shutdown requested." << std::endl; } else if (delay < 0.0f && m_shutdown_state.isTimerRunning()) { // Negative delay, cancel shutdown if requested m_shutdown_state.reset(); std::wstringstream ws; ws << L"*** Server shutdown canceled."; infostream << wide_to_utf8(ws.str()).c_str() << std::endl; SendChatMessage(PEER_ID_INEXISTENT, ws.str()); // m_shutdown_* are already handled, skip. return; } else if (delay > 0.0f) { // Positive delay, tell the clients when the server will shut down std::wstringstream ws; ws << L"*** Server shutting down in " << duration_to_string(myround(delay)).c_str() << "."; infostream << wide_to_utf8(ws.str()).c_str() << std::endl; SendChatMessage(PEER_ID_INEXISTENT, ws.str()); } m_shutdown_state.trigger(delay, msg, reconnect); } PlayerSAO* Server::emergePlayer(const char *name, session_t peer_id, u16 proto_version) { /* Try to get an existing player */ RemotePlayer *player = m_env->getPlayer(name); // If player is already connected, cancel if (player && player->getPeerId() != PEER_ID_INEXISTENT) { infostream<<"emergePlayer(): Player already connected"<<std::endl; return NULL; } /* If player with the wanted peer_id already exists, cancel. */ if (m_env->getPlayer(peer_id)) { infostream<<"emergePlayer(): Player with wrong name but same" " peer_id already exists"<<std::endl; return NULL; } if (!player) { player = new RemotePlayer(name, idef()); } bool newplayer = false; // Load player PlayerSAO *playersao = m_env->loadPlayer(player, &newplayer, peer_id, isSingleplayer()); // Complete init with server parts playersao->finalize(player, getPlayerEffectivePrivs(player->getName())); player->protocol_version = proto_version; /* Run scripts */ if (newplayer) { m_script->on_newplayer(playersao); } return playersao; } bool Server::registerModStorage(ModMetadata *storage) { if (m_mod_storages.find(storage->getModName()) != m_mod_storages.end()) { errorstream << "Unable to register same mod storage twice. Storage name: " << storage->getModName() << std::endl; return false; } m_mod_storages[storage->getModName()] = storage; return true; } void Server::unregisterModStorage(const std::string &name) { std::unordered_map<std::string, ModMetadata *>::const_iterator it = m_mod_storages.find(name); if (it != m_mod_storages.end()) { // Save unconditionaly on unregistration it->second->save(getModStoragePath()); m_mod_storages.erase(name); } } void dedicated_server_loop(Server &server, bool &kill) { verbosestream<<"dedicated_server_loop()"<<std::endl; IntervalLimiter m_profiler_interval; static thread_local const float steplen = g_settings->getFloat("dedicated_server_step"); static thread_local const float profiler_print_interval = g_settings->getFloat("profiler_print_interval"); for(;;) { // This is kind of a hack but can be done like this // because server.step() is very light { ScopeProfiler sp(g_profiler, "dedicated server sleep"); sleep_ms((int)(steplen*1000.0)); } server.step(steplen); if (server.isShutdownRequested() || kill) break; /* Profiler */ if (profiler_print_interval != 0) { if(m_profiler_interval.step(steplen, profiler_print_interval)) { infostream<<"Profiler:"<<std::endl; g_profiler->print(infostream); g_profiler->clear(); } } } infostream << "Dedicated server quitting" << std::endl; #if USE_CURL if (g_settings->getBool("server_announce")) ServerList::sendAnnounce(ServerList::AA_DELETE, server.m_bind_addr.getPort()); #endif } /* * Mod channels */ bool Server::joinModChannel(const std::string &channel) { return m_modchannel_mgr->joinChannel(channel, PEER_ID_SERVER) && m_modchannel_mgr->setChannelState(channel, MODCHANNEL_STATE_READ_WRITE); } bool Server::leaveModChannel(const std::string &channel) { return m_modchannel_mgr->leaveChannel(channel, PEER_ID_SERVER); } bool Server::sendModChannelMessage(const std::string &channel, const std::string &message) { if (!m_modchannel_mgr->canWriteOnChannel(channel)) return false; broadcastModChannelMessage(channel, message, PEER_ID_SERVER); return true; } ModChannel* Server::getModChannel(const std::string &channel) { return m_modchannel_mgr->getModChannel(channel); } void Server::broadcastModChannelMessage(const std::string &channel, const std::string &message, session_t from_peer) { const std::vector<u16> &peers = m_modchannel_mgr->getChannelPeers(channel); if (peers.empty()) return; if (message.size() > STRING_MAX_LEN) { warningstream << "ModChannel message too long, dropping before sending " << " (" << message.size() << " > " << STRING_MAX_LEN << ", channel: " << channel << ")" << std::endl; return; } std::string sender; if (from_peer != PEER_ID_SERVER) { sender = getPlayerName(from_peer); } NetworkPacket resp_pkt(TOCLIENT_MODCHANNEL_MSG, 2 + channel.size() + 2 + sender.size() + 2 + message.size()); resp_pkt << channel << sender << message; for (session_t peer_id : peers) { // Ignore sender if (peer_id == from_peer) continue; Send(peer_id, &resp_pkt); } if (from_peer != PEER_ID_SERVER) { m_script->on_modchannel_message(channel, sender, message); } }
pgimeno/minetest
src/server.cpp
C++
mit
100,072
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irr_v3d.h" #include "map.h" #include "hud.h" #include "gamedef.h" #include "serialization.h" // For SER_FMT_VER_INVALID #include "content/mods.h" #include "inventorymanager.h" #include "content/subgames.h" #include "tileanimation.h" // struct TileAnimationParams #include "network/peerhandler.h" #include "network/address.h" #include "util/numeric.h" #include "util/thread.h" #include "util/basic_macros.h" #include "serverenvironment.h" #include "clientiface.h" #include "chatmessage.h" #include <string> #include <list> #include <map> #include <vector> class ChatEvent; struct ChatEventChat; struct ChatInterface; class IWritableItemDefManager; class NodeDefManager; class IWritableCraftDefManager; class BanManager; class EventManager; class Inventory; class ModChannelMgr; class RemotePlayer; class PlayerSAO; struct PlayerHPChangeReason; class IRollbackManager; struct RollbackAction; class EmergeManager; class ServerScripting; class ServerEnvironment; struct SimpleSoundSpec; struct CloudParams; class ServerThread; class ServerModManager; enum ClientDeletionReason { CDR_LEAVE, CDR_TIMEOUT, CDR_DENY }; struct MediaInfo { std::string path; std::string sha1_digest; MediaInfo(const std::string &path_="", const std::string &sha1_digest_=""): path(path_), sha1_digest(sha1_digest_) { } }; struct ServerSoundParams { enum Type { SSP_LOCAL, SSP_POSITIONAL, SSP_OBJECT } type = SSP_LOCAL; float gain = 1.0f; float fade = 0.0f; float pitch = 1.0f; bool loop = false; float max_hear_distance = 32 * BS; v3f pos; u16 object = 0; std::string to_player = ""; v3f getPos(ServerEnvironment *env, bool *pos_exists) const; }; struct ServerPlayingSound { ServerSoundParams params; SimpleSoundSpec spec; std::unordered_set<session_t> clients; // peer ids }; class Server : public con::PeerHandler, public MapEventReceiver, public InventoryManager, public IGameDef { public: /* NOTE: Every public method should be thread-safe */ Server( const std::string &path_world, const SubgameSpec &gamespec, bool simple_singleplayer_mode, Address bind_addr, bool dedicated, ChatInterface *iface = nullptr ); ~Server(); DISABLE_CLASS_COPY(Server); void init(); void start(); void stop(); // This is mainly a way to pass the time to the server. // Actual processing is done in an another thread. void step(float dtime); // This is run by ServerThread and does the actual processing void AsyncRunStep(bool initial_step=false); void Receive(); PlayerSAO* StageTwoClientInit(session_t peer_id); /* * Command Handlers */ void handleCommand(NetworkPacket* pkt); void handleCommand_Null(NetworkPacket* pkt) {}; void handleCommand_Deprecated(NetworkPacket* pkt); void handleCommand_Init(NetworkPacket* pkt); void handleCommand_Init2(NetworkPacket* pkt); void handleCommand_ModChannelJoin(NetworkPacket *pkt); void handleCommand_ModChannelLeave(NetworkPacket *pkt); void handleCommand_ModChannelMsg(NetworkPacket *pkt); void handleCommand_RequestMedia(NetworkPacket* pkt); void handleCommand_ClientReady(NetworkPacket* pkt); void handleCommand_GotBlocks(NetworkPacket* pkt); void handleCommand_PlayerPos(NetworkPacket* pkt); void handleCommand_DeletedBlocks(NetworkPacket* pkt); void handleCommand_InventoryAction(NetworkPacket* pkt); void handleCommand_ChatMessage(NetworkPacket* pkt); void handleCommand_Damage(NetworkPacket* pkt); void handleCommand_Password(NetworkPacket* pkt); void handleCommand_PlayerItem(NetworkPacket* pkt); void handleCommand_Respawn(NetworkPacket* pkt); void handleCommand_Interact(NetworkPacket* pkt); void handleCommand_RemovedSounds(NetworkPacket* pkt); void handleCommand_NodeMetaFields(NetworkPacket* pkt); void handleCommand_InventoryFields(NetworkPacket* pkt); void handleCommand_FirstSrp(NetworkPacket* pkt); void handleCommand_SrpBytesA(NetworkPacket* pkt); void handleCommand_SrpBytesM(NetworkPacket* pkt); void ProcessData(NetworkPacket *pkt); void Send(NetworkPacket *pkt); void Send(session_t peer_id, NetworkPacket *pkt); // Helper for handleCommand_PlayerPos and handleCommand_Interact void process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao, NetworkPacket *pkt); // Both setter and getter need no envlock, // can be called freely from threads void setTimeOfDay(u32 time); /* Shall be called with the environment locked. This is accessed by the map, which is inside the environment, so it shouldn't be a problem. */ void onMapEditEvent(MapEditEvent *event); /* Shall be called with the environment and the connection locked. */ Inventory* getInventory(const InventoryLocation &loc); void setInventoryModified(const InventoryLocation &loc, bool playerSend = true); // Connection must be locked when called std::wstring getStatusString(); inline double getUptime() const { return m_uptime.m_value; } // read shutdown state inline bool isShutdownRequested() const { return m_shutdown_state.is_requested; } // request server to shutdown void requestShutdown(const std::string &msg, bool reconnect, float delay = 0.0f); // Returns -1 if failed, sound handle on success // Envlock s32 playSound(const SimpleSoundSpec &spec, const ServerSoundParams &params); void stopSound(s32 handle); void fadeSound(s32 handle, float step, float gain); // Envlock std::set<std::string> getPlayerEffectivePrivs(const std::string &name); bool checkPriv(const std::string &name, const std::string &priv); void reportPrivsModified(const std::string &name=""); // ""=all void reportInventoryFormspecModified(const std::string &name); void reportFormspecPrependModified(const std::string &name); void setIpBanned(const std::string &ip, const std::string &name); void unsetIpBanned(const std::string &ip_or_name); std::string getBanDescription(const std::string &ip_or_name); void notifyPlayer(const char *name, const std::wstring &msg); void notifyPlayers(const std::wstring &msg); void spawnParticle(const std::string &playername, v3f pos, v3f velocity, v3f acceleration, float expirationtime, float size, bool collisiondetection, bool collision_removal, bool object_collision, bool vertical, const std::string &texture, const struct TileAnimationParams &animation, u8 glow); u32 addParticleSpawner(u16 amount, float spawntime, v3f minpos, v3f maxpos, v3f minvel, v3f maxvel, v3f minacc, v3f maxacc, float minexptime, float maxexptime, float minsize, float maxsize, bool collisiondetection, bool collision_removal, bool object_collision, ServerActiveObject *attached, bool vertical, const std::string &texture, const std::string &playername, const struct TileAnimationParams &animation, u8 glow); void deleteParticleSpawner(const std::string &playername, u32 id); // Creates or resets inventory Inventory *createDetachedInventory(const std::string &name, const std::string &player = ""); bool removeDetachedInventory(const std::string &name); // Envlock and conlock should be locked when using scriptapi ServerScripting *getScriptIface(){ return m_script; } // actions: time-reversed list // Return value: success/failure bool rollbackRevertActions(const std::list<RollbackAction> &actions, std::list<std::string> *log); // IGameDef interface // Under envlock virtual IItemDefManager* getItemDefManager(); virtual const NodeDefManager* getNodeDefManager(); virtual ICraftDefManager* getCraftDefManager(); virtual u16 allocateUnknownNodeId(const std::string &name); IRollbackManager *getRollbackManager() { return m_rollback; } virtual EmergeManager *getEmergeManager() { return m_emerge; } IWritableItemDefManager* getWritableItemDefManager(); NodeDefManager* getWritableNodeDefManager(); IWritableCraftDefManager* getWritableCraftDefManager(); virtual const std::vector<ModSpec> &getMods() const; virtual const ModSpec* getModSpec(const std::string &modname) const; void getModNames(std::vector<std::string> &modlist); std::string getBuiltinLuaPath(); virtual std::string getWorldPath() const { return m_path_world; } virtual std::string getModStoragePath() const; inline bool isSingleplayer() { return m_simple_singleplayer_mode; } inline void setAsyncFatalError(const std::string &error) { m_async_fatal_error.set(error); } bool showFormspec(const char *name, const std::string &formspec, const std::string &formname); Map & getMap() { return m_env->getMap(); } ServerEnvironment & getEnv() { return *m_env; } v3f findSpawnPos(); u32 hudAdd(RemotePlayer *player, HudElement *element); bool hudRemove(RemotePlayer *player, u32 id); bool hudChange(RemotePlayer *player, u32 id, HudElementStat stat, void *value); bool hudSetFlags(RemotePlayer *player, u32 flags, u32 mask); bool hudSetHotbarItemcount(RemotePlayer *player, s32 hotbar_itemcount); void hudSetHotbarImage(RemotePlayer *player, std::string name); void hudSetHotbarSelectedImage(RemotePlayer *player, std::string name); Address getPeerAddress(session_t peer_id); void setLocalPlayerAnimations(RemotePlayer *player, v2s32 animation_frames[4], f32 frame_speed); void setPlayerEyeOffset(RemotePlayer *player, const v3f &first, const v3f &third); void setSky(RemotePlayer *player, const video::SColor &bgcolor, const std::string &type, const std::vector<std::string> &params, bool &clouds); void setClouds(RemotePlayer *player, const CloudParams &params); bool overrideDayNightRatio(RemotePlayer *player, bool do_override, float brightness); /* con::PeerHandler implementation. */ void peerAdded(con::Peer *peer); void deletingPeer(con::Peer *peer, bool timeout); void DenySudoAccess(session_t peer_id); void DenyAccessVerCompliant(session_t peer_id, u16 proto_ver, AccessDeniedCode reason, const std::string &str_reason = "", bool reconnect = false); void DenyAccess(session_t peer_id, AccessDeniedCode reason, const std::string &custom_reason = ""); void acceptAuth(session_t peer_id, bool forSudoMode); void DenyAccess_Legacy(session_t peer_id, const std::wstring &reason); void DisconnectPeer(session_t peer_id); bool getClientConInfo(session_t peer_id, con::rtt_stat_type type, float *retval); bool getClientInfo(session_t peer_id, ClientState *state, u32 *uptime, u8* ser_vers, u16* prot_vers, u8* major, u8* minor, u8* patch, std::string* vers_string); void printToConsoleOnly(const std::string &text); void SendPlayerHPOrDie(PlayerSAO *player, const PlayerHPChangeReason &reason); void SendPlayerBreath(PlayerSAO *sao); void SendInventory(PlayerSAO* playerSAO); void SendMovePlayer(session_t peer_id); virtual bool registerModStorage(ModMetadata *storage); virtual void unregisterModStorage(const std::string &name); bool joinModChannel(const std::string &channel); bool leaveModChannel(const std::string &channel); bool sendModChannelMessage(const std::string &channel, const std::string &message); ModChannel *getModChannel(const std::string &channel); // Bind address Address m_bind_addr; // Environment mutex (envlock) std::mutex m_env_mutex; private: friend class EmergeThread; friend class RemoteClient; friend class TestServerShutdownState; struct ShutdownState { friend class TestServerShutdownState; public: bool is_requested = false; bool should_reconnect = false; std::string message; void reset(); void trigger(float delay, const std::string &msg, bool reconnect); void tick(float dtime, Server *server); std::wstring getShutdownTimerMessage() const; bool isTimerRunning() const { return m_timer > 0.0f; } private: float m_timer = 0.0f; }; void SendMovement(session_t peer_id); void SendHP(session_t peer_id, u16 hp); void SendBreath(session_t peer_id, u16 breath); void SendAccessDenied(session_t peer_id, AccessDeniedCode reason, const std::string &custom_reason, bool reconnect = false); void SendAccessDenied_Legacy(session_t peer_id, const std::wstring &reason); void SendDeathscreen(session_t peer_id, bool set_camera_point_target, v3f camera_point_target); void SendItemDef(session_t peer_id, IItemDefManager *itemdef, u16 protocol_version); void SendNodeDef(session_t peer_id, const NodeDefManager *nodedef, u16 protocol_version); /* mark blocks not sent for all clients */ void SetBlocksNotSent(std::map<v3s16, MapBlock *>& block); virtual void SendChatMessage(session_t peer_id, const ChatMessage &message); void SendTimeOfDay(session_t peer_id, u16 time, f32 time_speed); void SendPlayerHP(session_t peer_id); void SendLocalPlayerAnimations(session_t peer_id, v2s32 animation_frames[4], f32 animation_speed); void SendEyeOffset(session_t peer_id, v3f first, v3f third); void SendPlayerPrivileges(session_t peer_id); void SendPlayerInventoryFormspec(session_t peer_id); void SendPlayerFormspecPrepend(session_t peer_id); void SendShowFormspecMessage(session_t peer_id, const std::string &formspec, const std::string &formname); void SendHUDAdd(session_t peer_id, u32 id, HudElement *form); void SendHUDRemove(session_t peer_id, u32 id); void SendHUDChange(session_t peer_id, u32 id, HudElementStat stat, void *value); void SendHUDSetFlags(session_t peer_id, u32 flags, u32 mask); void SendHUDSetParam(session_t peer_id, u16 param, const std::string &value); void SendSetSky(session_t peer_id, const video::SColor &bgcolor, const std::string &type, const std::vector<std::string> &params, bool &clouds); void SendCloudParams(session_t peer_id, const CloudParams &params); void SendOverrideDayNightRatio(session_t peer_id, bool do_override, float ratio); void broadcastModChannelMessage(const std::string &channel, const std::string &message, session_t from_peer); /* Send a node removal/addition event to all clients except ignore_id. Additionally, if far_players!=NULL, players further away than far_d_nodes are ignored and their peer_ids are added to far_players */ // Envlock and conlock should be locked when calling these void sendRemoveNode(v3s16 p, std::unordered_set<u16> *far_players = nullptr, float far_d_nodes = 100); void sendAddNode(v3s16 p, MapNode n, std::unordered_set<u16> *far_players = nullptr, float far_d_nodes = 100, bool remove_metadata = true); void sendMetadataChanged(const std::list<v3s16> &meta_updates, float far_d_nodes = 100); // Environment and Connection must be locked when called void SendBlockNoLock(session_t peer_id, MapBlock *block, u8 ver, u16 net_proto_version); // Sends blocks to clients (locks env and con on its own) void SendBlocks(float dtime); void fillMediaCache(); void sendMediaAnnouncement(session_t peer_id, const std::string &lang_code); void sendRequestedMedia(session_t peer_id, const std::vector<std::string> &tosend); void sendDetachedInventory(const std::string &name, session_t peer_id); void sendDetachedInventories(session_t peer_id); // Adds a ParticleSpawner on peer with peer_id (PEER_ID_INEXISTENT == all) void SendAddParticleSpawner(session_t peer_id, u16 protocol_version, u16 amount, float spawntime, v3f minpos, v3f maxpos, v3f minvel, v3f maxvel, v3f minacc, v3f maxacc, float minexptime, float maxexptime, float minsize, float maxsize, bool collisiondetection, bool collision_removal, bool object_collision, u16 attached_id, bool vertical, const std::string &texture, u32 id, const struct TileAnimationParams &animation, u8 glow); void SendDeleteParticleSpawner(session_t peer_id, u32 id); // Spawns particle on peer with peer_id (PEER_ID_INEXISTENT == all) void SendSpawnParticle(session_t peer_id, u16 protocol_version, v3f pos, v3f velocity, v3f acceleration, float expirationtime, float size, bool collisiondetection, bool collision_removal, bool object_collision, bool vertical, const std::string &texture, const struct TileAnimationParams &animation, u8 glow); u32 SendActiveObjectRemoveAdd(session_t peer_id, const std::string &datas); void SendActiveObjectMessages(session_t peer_id, const std::string &datas, bool reliable = true); void SendCSMRestrictionFlags(session_t peer_id); /* Something random */ void DiePlayer(session_t peer_id, const PlayerHPChangeReason &reason); void RespawnPlayer(session_t peer_id); void DeleteClient(session_t peer_id, ClientDeletionReason reason); void UpdateCrafting(RemotePlayer *player); bool checkInteractDistance(RemotePlayer *player, const f32 d, const std::string &what); void handleChatInterfaceEvent(ChatEvent *evt); // This returns the answer to the sender of wmessage, or "" if there is none std::wstring handleChat(const std::string &name, const std::wstring &wname, std::wstring wmessage_input, bool check_shout_priv = false, RemotePlayer *player = NULL); void handleAdminChat(const ChatEventChat *evt); // When called, connection mutex should be locked RemoteClient* getClient(session_t peer_id, ClientState state_min = CS_Active); RemoteClient* getClientNoEx(session_t peer_id, ClientState state_min = CS_Active); // When called, environment mutex should be locked std::string getPlayerName(session_t peer_id); PlayerSAO *getPlayerSAO(session_t peer_id); /* Get a player from memory or creates one. If player is already connected, return NULL Does not verify/modify auth info and password. Call with env and con locked. */ PlayerSAO *emergePlayer(const char *name, session_t peer_id, u16 proto_version); void handlePeerChanges(); /* Variables */ // World directory std::string m_path_world; // Subgame specification SubgameSpec m_gamespec; // If true, do not allow multiple players and hide some multiplayer // functionality bool m_simple_singleplayer_mode; u16 m_max_chatmessage_length; // For "dedicated" server list flag bool m_dedicated; // Thread can set; step() will throw as ServerError MutexedVariable<std::string> m_async_fatal_error; // Some timers float m_liquid_transform_timer = 0.0f; float m_liquid_transform_every = 1.0f; float m_masterserver_timer = 0.0f; float m_emergethread_trigger_timer = 0.0f; float m_savemap_timer = 0.0f; IntervalLimiter m_map_timer_and_unload_interval; // Environment ServerEnvironment *m_env = nullptr; // server connection std::shared_ptr<con::Connection> m_con; // Ban checking BanManager *m_banmanager = nullptr; // Rollback manager (behind m_env_mutex) IRollbackManager *m_rollback = nullptr; // Emerge manager EmergeManager *m_emerge = nullptr; // Scripting // Envlock and conlock should be locked when using Lua ServerScripting *m_script = nullptr; // Item definition manager IWritableItemDefManager *m_itemdef; // Node definition manager NodeDefManager *m_nodedef; // Craft definition manager IWritableCraftDefManager *m_craftdef; // Event manager EventManager *m_event; // Mods std::unique_ptr<ServerModManager> m_modmgr; /* Threads */ // A buffer for time steps // step() increments and AsyncRunStep() run by m_thread reads it. float m_step_dtime = 0.0f; std::mutex m_step_dtime_mutex; // current server step lag counter float m_lag; // The server mainly operates in this thread ServerThread *m_thread = nullptr; /* Time related stuff */ // Timer for sending time of day over network float m_time_of_day_send_timer = 0.0f; // Uptime of server in seconds MutexedVariable<double> m_uptime; /* Client interface */ ClientInterface m_clients; /* Peer change queue. Queues stuff from peerAdded() and deletingPeer() to handlePeerChanges() */ std::queue<con::PeerChange> m_peer_change_queue; std::unordered_map<session_t, std::string> m_formspec_state_data; /* Random stuff */ ShutdownState m_shutdown_state; ChatInterface *m_admin_chat; std::string m_admin_nick; /* Map edit event queue. Automatically receives all map edits. The constructor of this class registers us to receive them through onMapEditEvent NOTE: Should these be moved to actually be members of ServerEnvironment? */ /* Queue of map edits from the environment for sending to the clients This is behind m_env_mutex */ std::queue<MapEditEvent*> m_unsent_map_edit_queue; /* If a non-empty area, map edit events contained within are left unsent. Done at map generation time to speed up editing of the generated area, as it will be sent anyway. This is behind m_env_mutex */ VoxelArea m_ignore_map_edit_events_area; // media files known to server std::unordered_map<std::string, MediaInfo> m_media; /* Sounds */ std::unordered_map<s32, ServerPlayingSound> m_playing_sounds; s32 m_next_sound_id = 0; /* Detached inventories (behind m_env_mutex) */ // key = name std::map<std::string, Inventory*> m_detached_inventories; // value = "" (visible to all players) or player name std::map<std::string, std::string> m_detached_inventories_player; std::unordered_map<std::string, ModMetadata *> m_mod_storages; float m_mod_storage_save_timer = 10.0f; // CSM restrictions byteflag u64 m_csm_restriction_flags = CSMRestrictionFlags::CSM_RF_NONE; u32 m_csm_restriction_noderange = 8; // ModChannel manager std::unique_ptr<ModChannelMgr> m_modchannel_mgr; }; /* Runs a simple dedicated server loop. Shuts down when kill is set to true. */ void dedicated_server_loop(Server &server, bool &kill);
pgimeno/minetest
src/server.h
C++
mit
22,061
set(server_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/activeobjectmgr.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mods.cpp PARENT_SCOPE)
pgimeno/minetest
src/server/CMakeLists.txt
Text
mit
118
/* Minetest Copyright (C) 2010-2018 nerzhul, Loic BLOT <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <log.h> #include "mapblock.h" #include "profiler.h" #include "activeobjectmgr.h" namespace server { void ActiveObjectMgr::clear(const std::function<bool(ServerActiveObject *, u16)> &cb) { std::vector<u16> objects_to_remove; for (auto &it : m_active_objects) { if (cb(it.second, it.first)) { // Id to be removed from m_active_objects objects_to_remove.push_back(it.first); } } // Remove references from m_active_objects for (u16 i : objects_to_remove) { m_active_objects.erase(i); } } void ActiveObjectMgr::step( float dtime, const std::function<void(ServerActiveObject *)> &f) { g_profiler->avg("Server::ActiveObjectMgr: num of objects", m_active_objects.size()); for (auto &ao_it : m_active_objects) { f(ao_it.second); } } // clang-format off bool ActiveObjectMgr::registerObject(ServerActiveObject *obj) { assert(obj); // Pre-condition if (obj->getId() == 0) { u16 new_id = getFreeId(); if (new_id == 0) { errorstream << "Server::ActiveObjectMgr::addActiveObjectRaw(): " << "no free id available" << std::endl; if (obj->environmentDeletes()) delete obj; return false; } obj->setId(new_id); } else { verbosestream << "Server::ActiveObjectMgr::addActiveObjectRaw(): " << "supplied with id " << obj->getId() << std::endl; } if (!isFreeId(obj->getId())) { errorstream << "Server::ActiveObjectMgr::addActiveObjectRaw(): " << "id is not free (" << obj->getId() << ")" << std::endl; if (obj->environmentDeletes()) delete obj; return false; } if (objectpos_over_limit(obj->getBasePosition())) { v3f p = obj->getBasePosition(); warningstream << "Server::ActiveObjectMgr::addActiveObjectRaw(): " << "object position (" << p.X << "," << p.Y << "," << p.Z << ") outside maximum range" << std::endl; if (obj->environmentDeletes()) delete obj; return false; } m_active_objects[obj->getId()] = obj; verbosestream << "Server::ActiveObjectMgr::addActiveObjectRaw(): " << "Added id=" << obj->getId() << "; there are now " << m_active_objects.size() << " active objects." << std::endl; return true; } void ActiveObjectMgr::removeObject(u16 id) { verbosestream << "Server::ActiveObjectMgr::removeObject(): " << "id=" << id << std::endl; ServerActiveObject *obj = getActiveObject(id); if (!obj) { infostream << "Server::ActiveObjectMgr::removeObject(): " << "id=" << id << " not found" << std::endl; return; } m_active_objects.erase(id); delete obj; } // clang-format on void ActiveObjectMgr::getObjectsInsideRadius( const v3f &pos, float radius, std::vector<u16> &result) { for (auto &activeObject : m_active_objects) { ServerActiveObject *obj = activeObject.second; u16 id = activeObject.first; const v3f &objectpos = obj->getBasePosition(); if (objectpos.getDistanceFrom(pos) > radius) continue; result.push_back(id); } } void ActiveObjectMgr::getAddedActiveObjectsAroundPos(const v3f &player_pos, f32 radius, f32 player_radius, std::set<u16> &current_objects, std::queue<u16> &added_objects) { /* Go through the object list, - discard removed/deactivated objects, - discard objects that are too far away, - discard objects that are found in current_objects. - add remaining objects to added_objects */ for (auto &ao_it : m_active_objects) { u16 id = ao_it.first; // Get object ServerActiveObject *object = ao_it.second; if (!object) continue; if (object->isGone()) continue; f32 distance_f = object->getBasePosition().getDistanceFrom(player_pos); if (object->getType() == ACTIVEOBJECT_TYPE_PLAYER) { // Discard if too far if (distance_f > player_radius && player_radius != 0) continue; } else if (distance_f > radius) continue; // Discard if already on current_objects auto n = current_objects.find(id); if (n != current_objects.end()) continue; // Add to added_objects added_objects.push(id); } } } // namespace server
pgimeno/minetest
src/server/activeobjectmgr.cpp
C++
mit
4,735
/* Minetest Copyright (C) 2010-2018 nerzhul, Loic BLOT <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <functional> #include <vector> #include "../activeobjectmgr.h" #include "serverobject.h" namespace server { class ActiveObjectMgr : public ::ActiveObjectMgr<ServerActiveObject> { public: void clear(const std::function<bool(ServerActiveObject *, u16)> &cb); void step(float dtime, const std::function<void(ServerActiveObject *)> &f) override; bool registerObject(ServerActiveObject *obj) override; void removeObject(u16 id) override; void getObjectsInsideRadius( const v3f &pos, float radius, std::vector<u16> &result); void getAddedActiveObjectsAroundPos(const v3f &player_pos, f32 radius, f32 player_radius, std::set<u16> &current_objects, std::queue<u16> &added_objects); }; } // namespace server
pgimeno/minetest
src/server/activeobjectmgr.h
C++
mit
1,537
/* Minetest Copyright (C) 2018 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "mods.h" #include "filesys.h" #include "log.h" #include "scripting_server.h" #include "content/subgames.h" /** * Manage server mods * * All new calls to this class must be tested in test_servermodmanager.cpp */ /** * Creates a ServerModManager which targets worldpath * @param worldpath */ ServerModManager::ServerModManager(const std::string &worldpath) : ModConfiguration(worldpath) { SubgameSpec gamespec = findWorldSubgame(worldpath); // Add all game mods and all world mods addModsInPath(gamespec.gamemods_path); addModsInPath(worldpath + DIR_DELIM + "worldmods"); // Load normal mods std::string worldmt = worldpath + DIR_DELIM + "world.mt"; addModsFromConfig(worldmt, gamespec.addon_mods_paths); } // clang-format off // This function cannot be currenctly easily tested but it should be ASAP void ServerModManager::loadMods(ServerScripting *script) { // Print mods infostream << "Server: Loading mods: "; for (const ModSpec &mod : m_sorted_mods) { infostream << mod.name << " "; } infostream << std::endl; // Load and run "mod" scripts for (const ModSpec &mod : m_sorted_mods) { if (!string_allowed(mod.name, MODNAME_ALLOWED_CHARS)) { throw ModError("Error loading mod \"" + mod.name + "\": Mod name does not follow naming " "conventions: " "Only characters [a-z0-9_] are allowed."); } std::string script_path = mod.path + DIR_DELIM + "init.lua"; infostream << " [" << padStringRight(mod.name, 12) << "] [\"" << script_path << "\"]" << std::endl; auto t = std::chrono::steady_clock::now(); script->loadMod(script_path, mod.name); infostream << "Mod \"" << mod.name << "\" loaded after " << std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - t).count() * 0.001f << " seconds" << std::endl; } // Run a callback when mods are loaded script->on_mods_loaded(); } // clang-format on const ModSpec *ServerModManager::getModSpec(const std::string &modname) const { std::vector<ModSpec>::const_iterator it; for (it = m_sorted_mods.begin(); it != m_sorted_mods.end(); ++it) { const ModSpec &mod = *it; if (mod.name == modname) return &mod; } return NULL; } void ServerModManager::getModNames(std::vector<std::string> &modlist) const { for (const ModSpec &spec : m_sorted_mods) modlist.push_back(spec.name); } void ServerModManager::getModsMediaPaths(std::vector<std::string> &paths) const { for (const ModSpec &spec : m_sorted_mods) { paths.push_back(spec.path + DIR_DELIM + "textures"); paths.push_back(spec.path + DIR_DELIM + "sounds"); paths.push_back(spec.path + DIR_DELIM + "media"); paths.push_back(spec.path + DIR_DELIM + "models"); paths.push_back(spec.path + DIR_DELIM + "locale"); } }
pgimeno/minetest
src/server/mods.cpp
C++
mit
3,538
/* Minetest Copyright (C) 2018 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "content/mods.h" class ServerScripting; /** * Manage server mods * * All new calls to this class must be tested in test_servermodmanager.cpp */ class ServerModManager : public ModConfiguration { public: /** * Creates a ServerModManager which targets worldpath * @param worldpath */ ServerModManager(const std::string &worldpath); void loadMods(ServerScripting *script); const ModSpec *getModSpec(const std::string &modname) const; void getModNames(std::vector<std::string> &modlist) const; void getModsMediaPaths(std::vector<std::string> &paths) const; };
pgimeno/minetest
src/server/mods.h
C++
mit
1,386
/* Minetest Copyright (C) 2010-2017 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "serverenvironment.h" #include "content_sao.h" #include "settings.h" #include "log.h" #include "mapblock.h" #include "nodedef.h" #include "nodemetadata.h" #include "gamedef.h" #include "map.h" #include "porting.h" #include "profiler.h" #include "raycast.h" #include "remoteplayer.h" #include "scripting_server.h" #include "server.h" #include "util/serialize.h" #include "util/basic_macros.h" #include "util/pointedthing.h" #include "threading/mutex_auto_lock.h" #include "filesys.h" #include "gameparams.h" #include "database/database-dummy.h" #include "database/database-files.h" #include "database/database-sqlite3.h" #if USE_POSTGRESQL #include "database/database-postgresql.h" #endif #include <algorithm> #define LBM_NAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyz0123456789_:" // A number that is much smaller than the timeout for particle spawners should/could ever be #define PARTICLE_SPAWNER_NO_EXPIRY -1024.f /* ABMWithState */ ABMWithState::ABMWithState(ActiveBlockModifier *abm_): abm(abm_) { // Initialize timer to random value to spread processing float itv = abm->getTriggerInterval(); itv = MYMAX(0.001, itv); // No less than 1ms int minval = MYMAX(-0.51*itv, -60); // Clamp to int maxval = MYMIN(0.51*itv, 60); // +-60 seconds timer = myrand_range(minval, maxval); } /* LBMManager */ void LBMContentMapping::deleteContents() { for (auto &it : lbm_list) { delete it; } } void LBMContentMapping::addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef) { // Add the lbm_def to the LBMContentMapping. // Unknown names get added to the global NameIdMapping. const NodeDefManager *nodedef = gamedef->ndef(); lbm_list.push_back(lbm_def); for (const std::string &nodeTrigger: lbm_def->trigger_contents) { std::vector<content_t> c_ids; bool found = nodedef->getIds(nodeTrigger, c_ids); if (!found) { content_t c_id = gamedef->allocateUnknownNodeId(nodeTrigger); if (c_id == CONTENT_IGNORE) { // Seems it can't be allocated. warningstream << "Could not internalize node name \"" << nodeTrigger << "\" while loading LBM \"" << lbm_def->name << "\"." << std::endl; continue; } c_ids.push_back(c_id); } for (content_t c_id : c_ids) { map[c_id].push_back(lbm_def); } } } const std::vector<LoadingBlockModifierDef *> * LBMContentMapping::lookup(content_t c) const { lbm_map::const_iterator it = map.find(c); if (it == map.end()) return NULL; // This first dereferences the iterator, returning // a std::vector<LoadingBlockModifierDef *> // reference, then we convert it to a pointer. return &(it->second); } LBMManager::~LBMManager() { for (auto &m_lbm_def : m_lbm_defs) { delete m_lbm_def.second; } for (auto &it : m_lbm_lookup) { (it.second).deleteContents(); } } void LBMManager::addLBMDef(LoadingBlockModifierDef *lbm_def) { // Precondition, in query mode the map isn't used anymore FATAL_ERROR_IF(m_query_mode, "attempted to modify LBMManager in query mode"); if (!string_allowed(lbm_def->name, LBM_NAME_ALLOWED_CHARS)) { throw ModError("Error adding LBM \"" + lbm_def->name + "\": Does not follow naming conventions: " "Only characters [a-z0-9_:] are allowed."); } m_lbm_defs[lbm_def->name] = lbm_def; } void LBMManager::loadIntroductionTimes(const std::string &times, IGameDef *gamedef, u32 now) { m_query_mode = true; // name -> time map. // Storing it in a map first instead of // handling the stuff directly in the loop // removes all duplicate entries. // TODO make this std::unordered_map std::map<std::string, u32> introduction_times; /* The introduction times string consists of name~time entries, with each entry terminated by a semicolon. The time is decimal. */ size_t idx = 0; size_t idx_new; while ((idx_new = times.find(';', idx)) != std::string::npos) { std::string entry = times.substr(idx, idx_new - idx); std::vector<std::string> components = str_split(entry, '~'); if (components.size() != 2) throw SerializationError("Introduction times entry \"" + entry + "\" requires exactly one '~'!"); const std::string &name = components[0]; u32 time = from_string<u32>(components[1]); introduction_times[name] = time; idx = idx_new + 1; } // Put stuff from introduction_times into m_lbm_lookup for (std::map<std::string, u32>::const_iterator it = introduction_times.begin(); it != introduction_times.end(); ++it) { const std::string &name = it->first; u32 time = it->second; std::map<std::string, LoadingBlockModifierDef *>::iterator def_it = m_lbm_defs.find(name); if (def_it == m_lbm_defs.end()) { // This seems to be an LBM entry for // an LBM we haven't loaded. Discard it. continue; } LoadingBlockModifierDef *lbm_def = def_it->second; if (lbm_def->run_at_every_load) { // This seems to be an LBM entry for // an LBM that runs at every load. // Don't add it just yet. continue; } m_lbm_lookup[time].addLBM(lbm_def, gamedef); // Erase the entry so that we know later // what elements didn't get put into m_lbm_lookup m_lbm_defs.erase(name); } // Now also add the elements from m_lbm_defs to m_lbm_lookup // that weren't added in the previous step. // They are introduced first time to this world, // or are run at every load (introducement time hardcoded to U32_MAX). LBMContentMapping &lbms_we_introduce_now = m_lbm_lookup[now]; LBMContentMapping &lbms_running_always = m_lbm_lookup[U32_MAX]; for (auto &m_lbm_def : m_lbm_defs) { if (m_lbm_def.second->run_at_every_load) { lbms_running_always.addLBM(m_lbm_def.second, gamedef); } else { lbms_we_introduce_now.addLBM(m_lbm_def.second, gamedef); } } // Clear the list, so that we don't delete remaining elements // twice in the destructor m_lbm_defs.clear(); } std::string LBMManager::createIntroductionTimesString() { // Precondition, we must be in query mode FATAL_ERROR_IF(!m_query_mode, "attempted to query on non fully set up LBMManager"); std::ostringstream oss; for (const auto &it : m_lbm_lookup) { u32 time = it.first; const std::vector<LoadingBlockModifierDef *> &lbm_list = it.second.lbm_list; for (const auto &lbm_def : lbm_list) { // Don't add if the LBM runs at every load, // then introducement time is hardcoded // and doesn't need to be stored if (lbm_def->run_at_every_load) continue; oss << lbm_def->name << "~" << time << ";"; } } return oss.str(); } void LBMManager::applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp) { // Precondition, we need m_lbm_lookup to be initialized FATAL_ERROR_IF(!m_query_mode, "attempted to query on non fully set up LBMManager"); v3s16 pos_of_block = block->getPosRelative(); v3s16 pos; MapNode n; content_t c; lbm_lookup_map::const_iterator it = getLBMsIntroducedAfter(stamp); for (; it != m_lbm_lookup.end(); ++it) { // Cache previous version to speedup lookup which has a very high performance // penalty on each call content_t previous_c{}; std::vector<LoadingBlockModifierDef *> *lbm_list = nullptr; for (pos.X = 0; pos.X < MAP_BLOCKSIZE; pos.X++) for (pos.Y = 0; pos.Y < MAP_BLOCKSIZE; pos.Y++) for (pos.Z = 0; pos.Z < MAP_BLOCKSIZE; pos.Z++) { n = block->getNodeNoEx(pos); c = n.getContent(); // If content_t are not matching perform an LBM lookup if (previous_c != c) { lbm_list = (std::vector<LoadingBlockModifierDef *> *) it->second.lookup(c); previous_c = c; } if (!lbm_list) continue; for (auto lbmdef : *lbm_list) { lbmdef->trigger(env, pos + pos_of_block, n); } } } } /* ActiveBlockList */ void fillRadiusBlock(v3s16 p0, s16 r, std::set<v3s16> &list) { v3s16 p; for(p.X=p0.X-r; p.X<=p0.X+r; p.X++) for(p.Y=p0.Y-r; p.Y<=p0.Y+r; p.Y++) for(p.Z=p0.Z-r; p.Z<=p0.Z+r; p.Z++) { // limit to a sphere if (p.getDistanceFrom(p0) <= r) { // Set in list list.insert(p); } } } void fillViewConeBlock(v3s16 p0, const s16 r, const v3f camera_pos, const v3f camera_dir, const float camera_fov, std::set<v3s16> &list) { v3s16 p; const s16 r_nodes = r * BS * MAP_BLOCKSIZE; for (p.X = p0.X - r; p.X <= p0.X+r; p.X++) for (p.Y = p0.Y - r; p.Y <= p0.Y+r; p.Y++) for (p.Z = p0.Z - r; p.Z <= p0.Z+r; p.Z++) { if (isBlockInSight(p, camera_pos, camera_dir, camera_fov, r_nodes)) { list.insert(p); } } } void ActiveBlockList::update(std::vector<PlayerSAO*> &active_players, s16 active_block_range, s16 active_object_range, std::set<v3s16> &blocks_removed, std::set<v3s16> &blocks_added) { /* Create the new list */ std::set<v3s16> newlist = m_forceloaded_list; m_abm_list = m_forceloaded_list; for (const PlayerSAO *playersao : active_players) { v3s16 pos = getNodeBlockPos(floatToInt(playersao->getBasePosition(), BS)); fillRadiusBlock(pos, active_block_range, m_abm_list); fillRadiusBlock(pos, active_block_range, newlist); s16 player_ao_range = std::min(active_object_range, playersao->getWantedRange()); // only do this if this would add blocks if (player_ao_range > active_block_range) { v3f camera_dir = v3f(0,0,1); camera_dir.rotateYZBy(playersao->getLookPitch()); camera_dir.rotateXZBy(playersao->getRotation().Y); fillViewConeBlock(pos, player_ao_range, playersao->getEyePosition(), camera_dir, playersao->getFov(), newlist); } } /* Find out which blocks on the old list are not on the new list */ // Go through old list for (v3s16 p : m_list) { // If not on new list, it's been removed if (newlist.find(p) == newlist.end()) blocks_removed.insert(p); } /* Find out which blocks on the new list are not on the old list */ // Go through new list for (v3s16 p : newlist) { // If not on old list, it's been added if(m_list.find(p) == m_list.end()) blocks_added.insert(p); } /* Update m_list */ m_list.clear(); for (v3s16 p : newlist) { m_list.insert(p); } } /* ServerEnvironment */ ServerEnvironment::ServerEnvironment(ServerMap *map, ServerScripting *scriptIface, Server *server, const std::string &path_world): Environment(server), m_map(map), m_script(scriptIface), m_server(server), m_path_world(path_world) { // Determine which database backend to use std::string conf_path = path_world + DIR_DELIM + "world.mt"; Settings conf; std::string player_backend_name = "sqlite3"; std::string auth_backend_name = "sqlite3"; bool succeeded = conf.readConfigFile(conf_path.c_str()); // If we open world.mt read the backend configurations. if (succeeded) { // Read those values before setting defaults bool player_backend_exists = conf.exists("player_backend"); bool auth_backend_exists = conf.exists("auth_backend"); // player backend is not set, assume it's legacy file backend. if (!player_backend_exists) { // fall back to files conf.set("player_backend", "files"); player_backend_name = "files"; if (!conf.updateConfigFile(conf_path.c_str())) { errorstream << "ServerEnvironment::ServerEnvironment(): " << "Failed to update world.mt!" << std::endl; } } else { conf.getNoEx("player_backend", player_backend_name); } // auth backend is not set, assume it's legacy file backend. if (!auth_backend_exists) { conf.set("auth_backend", "files"); auth_backend_name = "files"; if (!conf.updateConfigFile(conf_path.c_str())) { errorstream << "ServerEnvironment::ServerEnvironment(): " << "Failed to update world.mt!" << std::endl; } } else { conf.getNoEx("auth_backend", auth_backend_name); } } if (player_backend_name == "files") { warningstream << "/!\\ You are using old player file backend. " << "This backend is deprecated and will be removed in a future release /!\\" << std::endl << "Switching to SQLite3 or PostgreSQL is advised, " << "please read http://wiki.minetest.net/Database_backends." << std::endl; } if (auth_backend_name == "files") { warningstream << "/!\\ You are using old auth file backend. " << "This backend is deprecated and will be removed in a future release /!\\" << std::endl << "Switching to SQLite3 is advised, " << "please read http://wiki.minetest.net/Database_backends." << std::endl; } m_player_database = openPlayerDatabase(player_backend_name, path_world, conf); m_auth_database = openAuthDatabase(auth_backend_name, path_world, conf); } ServerEnvironment::~ServerEnvironment() { // Clear active block list. // This makes the next one delete all active objects. m_active_blocks.clear(); // Convert all objects to static and delete the active objects deactivateFarObjects(true); // Drop/delete map m_map->drop(); // Delete ActiveBlockModifiers for (ABMWithState &m_abm : m_abms) { delete m_abm.abm; } // Deallocate players for (RemotePlayer *m_player : m_players) { delete m_player; } delete m_player_database; delete m_auth_database; } Map & ServerEnvironment::getMap() { return *m_map; } ServerMap & ServerEnvironment::getServerMap() { return *m_map; } RemotePlayer *ServerEnvironment::getPlayer(const session_t peer_id) { for (RemotePlayer *player : m_players) { if (player->getPeerId() == peer_id) return player; } return NULL; } RemotePlayer *ServerEnvironment::getPlayer(const char* name) { for (RemotePlayer *player : m_players) { if (strcmp(player->getName(), name) == 0) return player; } return NULL; } void ServerEnvironment::addPlayer(RemotePlayer *player) { /* Check that peer_ids are unique. Also check that names are unique. Exception: there can be multiple players with peer_id=0 */ // If peer id is non-zero, it has to be unique. if (player->getPeerId() != PEER_ID_INEXISTENT) FATAL_ERROR_IF(getPlayer(player->getPeerId()) != NULL, "Peer id not unique"); // Name has to be unique. FATAL_ERROR_IF(getPlayer(player->getName()) != NULL, "Player name not unique"); // Add. m_players.push_back(player); } void ServerEnvironment::removePlayer(RemotePlayer *player) { for (std::vector<RemotePlayer *>::iterator it = m_players.begin(); it != m_players.end(); ++it) { if ((*it) == player) { delete *it; m_players.erase(it); return; } } } bool ServerEnvironment::removePlayerFromDatabase(const std::string &name) { return m_player_database->removePlayer(name); } bool ServerEnvironment::line_of_sight(v3f pos1, v3f pos2, v3s16 *p) { // Iterate trough nodes on the line voxalgo::VoxelLineIterator iterator(pos1 / BS, (pos2 - pos1) / BS); do { MapNode n = getMap().getNodeNoEx(iterator.m_current_node_pos); // Return non-air if (n.param0 != CONTENT_AIR) { if (p) *p = iterator.m_current_node_pos; return false; } iterator.next(); } while (iterator.m_current_index <= iterator.m_last_index); return true; } void ServerEnvironment::kickAllPlayers(AccessDeniedCode reason, const std::string &str_reason, bool reconnect) { for (RemotePlayer *player : m_players) { m_server->DenyAccessVerCompliant(player->getPeerId(), player->protocol_version, reason, str_reason, reconnect); } } void ServerEnvironment::saveLoadedPlayers(bool force) { for (RemotePlayer *player : m_players) { if (force || player->checkModified() || (player->getPlayerSAO() && player->getPlayerSAO()->getMeta().isModified())) { try { m_player_database->savePlayer(player); } catch (DatabaseException &e) { errorstream << "Failed to save player " << player->getName() << " exception: " << e.what() << std::endl; throw; } } } } void ServerEnvironment::savePlayer(RemotePlayer *player) { try { m_player_database->savePlayer(player); } catch (DatabaseException &e) { errorstream << "Failed to save player " << player->getName() << " exception: " << e.what() << std::endl; throw; } } PlayerSAO *ServerEnvironment::loadPlayer(RemotePlayer *player, bool *new_player, session_t peer_id, bool is_singleplayer) { PlayerSAO *playersao = new PlayerSAO(this, player, peer_id, is_singleplayer); // Create player if it doesn't exist if (!m_player_database->loadPlayer(player, playersao)) { *new_player = true; // Set player position infostream << "Server: Finding spawn place for player \"" << player->getName() << "\"" << std::endl; playersao->setBasePosition(m_server->findSpawnPos()); // Make sure the player is saved player->setModified(true); } else { // If the player exists, ensure that they respawn inside legal bounds // This fixes an assert crash when the player can't be added // to the environment if (objectpos_over_limit(playersao->getBasePosition())) { actionstream << "Respawn position for player \"" << player->getName() << "\" outside limits, resetting" << std::endl; playersao->setBasePosition(m_server->findSpawnPos()); } } // Add player to environment addPlayer(player); /* Clean up old HUD elements from previous sessions */ player->clearHud(); /* Add object to environment */ addActiveObject(playersao); return playersao; } void ServerEnvironment::saveMeta() { std::string path = m_path_world + DIR_DELIM "env_meta.txt"; // Open file and serialize std::ostringstream ss(std::ios_base::binary); Settings args; args.setU64("game_time", m_game_time); args.setU64("time_of_day", getTimeOfDay()); args.setU64("last_clear_objects_time", m_last_clear_objects_time); args.setU64("lbm_introduction_times_version", 1); args.set("lbm_introduction_times", m_lbm_mgr.createIntroductionTimesString()); args.setU64("day_count", m_day_count); args.writeLines(ss); ss<<"EnvArgsEnd\n"; if(!fs::safeWriteToFile(path, ss.str())) { infostream<<"ServerEnvironment::saveMeta(): Failed to write " <<path<<std::endl; throw SerializationError("Couldn't save env meta"); } } void ServerEnvironment::loadMeta() { // If file doesn't exist, load default environment metadata if (!fs::PathExists(m_path_world + DIR_DELIM "env_meta.txt")) { infostream << "ServerEnvironment: Loading default environment metadata" << std::endl; loadDefaultMeta(); return; } infostream << "ServerEnvironment: Loading environment metadata" << std::endl; std::string path = m_path_world + DIR_DELIM "env_meta.txt"; // Open file and deserialize std::ifstream is(path.c_str(), std::ios_base::binary); if (!is.good()) { infostream << "ServerEnvironment::loadMeta(): Failed to open " << path << std::endl; throw SerializationError("Couldn't load env meta"); } Settings args; if (!args.parseConfigLines(is, "EnvArgsEnd")) { throw SerializationError("ServerEnvironment::loadMeta(): " "EnvArgsEnd not found!"); } try { m_game_time = args.getU64("game_time"); } catch (SettingNotFoundException &e) { // Getting this is crucial, otherwise timestamps are useless throw SerializationError("Couldn't load env meta game_time"); } setTimeOfDay(args.exists("time_of_day") ? // set day to early morning by default args.getU64("time_of_day") : 5250); m_last_clear_objects_time = args.exists("last_clear_objects_time") ? // If missing, do as if clearObjects was never called args.getU64("last_clear_objects_time") : 0; std::string lbm_introduction_times; try { u64 ver = args.getU64("lbm_introduction_times_version"); if (ver == 1) { lbm_introduction_times = args.get("lbm_introduction_times"); } else { infostream << "ServerEnvironment::loadMeta(): Non-supported" << " introduction time version " << ver << std::endl; } } catch (SettingNotFoundException &e) { // No problem, this is expected. Just continue with an empty string } m_lbm_mgr.loadIntroductionTimes(lbm_introduction_times, m_server, m_game_time); m_day_count = args.exists("day_count") ? args.getU64("day_count") : 0; } /** * called if env_meta.txt doesn't exist (e.g. new world) */ void ServerEnvironment::loadDefaultMeta() { m_lbm_mgr.loadIntroductionTimes("", m_server, m_game_time); } struct ActiveABM { ActiveBlockModifier *abm; int chance; std::vector<content_t> required_neighbors; bool check_required_neighbors; // false if required_neighbors is known to be empty }; class ABMHandler { private: ServerEnvironment *m_env; std::vector<std::vector<ActiveABM> *> m_aabms; public: ABMHandler(std::vector<ABMWithState> &abms, float dtime_s, ServerEnvironment *env, bool use_timers): m_env(env) { if(dtime_s < 0.001) return; const NodeDefManager *ndef = env->getGameDef()->ndef(); for (ABMWithState &abmws : abms) { ActiveBlockModifier *abm = abmws.abm; float trigger_interval = abm->getTriggerInterval(); if(trigger_interval < 0.001) trigger_interval = 0.001; float actual_interval = dtime_s; if(use_timers){ abmws.timer += dtime_s; if(abmws.timer < trigger_interval) continue; abmws.timer -= trigger_interval; actual_interval = trigger_interval; } float chance = abm->getTriggerChance(); if(chance == 0) chance = 1; ActiveABM aabm; aabm.abm = abm; if (abm->getSimpleCatchUp()) { float intervals = actual_interval / trigger_interval; if(intervals == 0) continue; aabm.chance = chance / intervals; if(aabm.chance == 0) aabm.chance = 1; } else { aabm.chance = chance; } // Trigger neighbors const std::vector<std::string> &required_neighbors_s = abm->getRequiredNeighbors(); for (const std::string &required_neighbor_s : required_neighbors_s) { ndef->getIds(required_neighbor_s, aabm.required_neighbors); } aabm.check_required_neighbors = !required_neighbors_s.empty(); // Trigger contents const std::vector<std::string> &contents_s = abm->getTriggerContents(); for (const std::string &content_s : contents_s) { std::vector<content_t> ids; ndef->getIds(content_s, ids); for (content_t c : ids) { if (c >= m_aabms.size()) m_aabms.resize(c + 256, NULL); if (!m_aabms[c]) m_aabms[c] = new std::vector<ActiveABM>; m_aabms[c]->push_back(aabm); } } } } ~ABMHandler() { for (auto &aabms : m_aabms) delete aabms; } // Find out how many objects the given block and its neighbours contain. // Returns the number of objects in the block, and also in 'wider' the // number of objects in the block and all its neighbours. The latter // may an estimate if any neighbours are unloaded. u32 countObjects(MapBlock *block, ServerMap * map, u32 &wider) { wider = 0; u32 wider_unknown_count = 0; for(s16 x=-1; x<=1; x++) for(s16 y=-1; y<=1; y++) for(s16 z=-1; z<=1; z++) { MapBlock *block2 = map->getBlockNoCreateNoEx( block->getPos() + v3s16(x,y,z)); if(block2==NULL){ wider_unknown_count++; continue; } wider += block2->m_static_objects.m_active.size() + block2->m_static_objects.m_stored.size(); } // Extrapolate u32 active_object_count = block->m_static_objects.m_active.size(); u32 wider_known_count = 3*3*3 - wider_unknown_count; wider += wider_unknown_count * wider / wider_known_count; return active_object_count; } void apply(MapBlock *block, int &blocks_scanned, int &abms_run, int &blocks_cached) { if(m_aabms.empty() || block->isDummy()) return; // Check the content type cache first // to see whether there are any ABMs // to be run at all for this block. if (block->contents_cached) { blocks_cached++; bool run_abms = false; for (content_t c : block->contents) { if (c < m_aabms.size() && m_aabms[c]) { run_abms = true; break; } } if (!run_abms) return; } else { // Clear any caching block->contents.clear(); } blocks_scanned++; ServerMap *map = &m_env->getServerMap(); u32 active_object_count_wider; u32 active_object_count = this->countObjects(block, map, active_object_count_wider); m_env->m_added_objects = 0; v3s16 p0; for(p0.X=0; p0.X<MAP_BLOCKSIZE; p0.X++) for(p0.Y=0; p0.Y<MAP_BLOCKSIZE; p0.Y++) for(p0.Z=0; p0.Z<MAP_BLOCKSIZE; p0.Z++) { const MapNode &n = block->getNodeUnsafe(p0); content_t c = n.getContent(); // Cache content types as we go if (!block->contents_cached && !block->do_not_cache_contents) { block->contents.insert(c); if (block->contents.size() > 64) { // Too many different nodes... don't try to cache block->do_not_cache_contents = true; block->contents.clear(); } } if (c >= m_aabms.size() || !m_aabms[c]) continue; v3s16 p = p0 + block->getPosRelative(); for (ActiveABM &aabm : *m_aabms[c]) { if (myrand() % aabm.chance != 0) continue; // Check neighbors if (aabm.check_required_neighbors) { v3s16 p1; for(p1.X = p0.X-1; p1.X <= p0.X+1; p1.X++) for(p1.Y = p0.Y-1; p1.Y <= p0.Y+1; p1.Y++) for(p1.Z = p0.Z-1; p1.Z <= p0.Z+1; p1.Z++) { if(p1 == p0) continue; content_t c; if (block->isValidPosition(p1)) { // if the neighbor is found on the same map block // get it straight from there const MapNode &n = block->getNodeUnsafe(p1); c = n.getContent(); } else { // otherwise consult the map MapNode n = map->getNodeNoEx(p1 + block->getPosRelative()); c = n.getContent(); } if (CONTAINS(aabm.required_neighbors, c)) goto neighbor_found; } // No required neighbor found continue; } neighbor_found: abms_run++; // Call all the trigger variations aabm.abm->trigger(m_env, p, n); aabm.abm->trigger(m_env, p, n, active_object_count, active_object_count_wider); // Count surrounding objects again if the abms added any if(m_env->m_added_objects > 0) { active_object_count = countObjects(block, map, active_object_count_wider); m_env->m_added_objects = 0; } } } block->contents_cached = !block->do_not_cache_contents; } }; void ServerEnvironment::activateBlock(MapBlock *block, u32 additional_dtime) { // Reset usage timer immediately, otherwise a block that becomes active // again at around the same time as it would normally be unloaded will // get unloaded incorrectly. (I think this still leaves a small possibility // of a race condition between this and server::AsyncRunStep, which only // some kind of synchronisation will fix, but it at least reduces the window // of opportunity for it to break from seconds to nanoseconds) block->resetUsageTimer(); // Get time difference u32 dtime_s = 0; u32 stamp = block->getTimestamp(); if (m_game_time > stamp && stamp != BLOCK_TIMESTAMP_UNDEFINED) dtime_s = m_game_time - stamp; dtime_s += additional_dtime; /*infostream<<"ServerEnvironment::activateBlock(): block timestamp: " <<stamp<<", game time: "<<m_game_time<<std::endl;*/ // Remove stored static objects if clearObjects was called since block's timestamp if (stamp == BLOCK_TIMESTAMP_UNDEFINED || stamp < m_last_clear_objects_time) { block->m_static_objects.m_stored.clear(); // do not set changed flag to avoid unnecessary mapblock writes } // Set current time as timestamp block->setTimestampNoChangedFlag(m_game_time); /*infostream<<"ServerEnvironment::activateBlock(): block is " <<dtime_s<<" seconds old."<<std::endl;*/ // Activate stored objects activateObjects(block, dtime_s); /* Handle LoadingBlockModifiers */ m_lbm_mgr.applyLBMs(this, block, stamp); // Run node timers std::vector<NodeTimer> elapsed_timers = block->m_node_timers.step((float)dtime_s); if (!elapsed_timers.empty()) { MapNode n; for (const NodeTimer &elapsed_timer : elapsed_timers) { n = block->getNodeNoEx(elapsed_timer.position); v3s16 p = elapsed_timer.position + block->getPosRelative(); if (m_script->node_on_timer(p, n, elapsed_timer.elapsed)) block->setNodeTimer(NodeTimer(elapsed_timer.timeout, 0, elapsed_timer.position)); } } } void ServerEnvironment::addActiveBlockModifier(ActiveBlockModifier *abm) { m_abms.emplace_back(abm); } void ServerEnvironment::addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm) { m_lbm_mgr.addLBMDef(lbm); } bool ServerEnvironment::setNode(v3s16 p, const MapNode &n) { const NodeDefManager *ndef = m_server->ndef(); MapNode n_old = m_map->getNodeNoEx(p); const ContentFeatures &cf_old = ndef->get(n_old); // Call destructor if (cf_old.has_on_destruct) m_script->node_on_destruct(p, n_old); // Replace node if (!m_map->addNodeWithEvent(p, n)) return false; // Update active VoxelManipulator if a mapgen thread m_map->updateVManip(p); // Call post-destructor if (cf_old.has_after_destruct) m_script->node_after_destruct(p, n_old); // Retrieve node content features // if new node is same as old, reuse old definition to prevent a lookup const ContentFeatures &cf_new = n_old == n ? cf_old : ndef->get(n); // Call constructor if (cf_new.has_on_construct) m_script->node_on_construct(p, n); return true; } bool ServerEnvironment::removeNode(v3s16 p) { const NodeDefManager *ndef = m_server->ndef(); MapNode n_old = m_map->getNodeNoEx(p); // Call destructor if (ndef->get(n_old).has_on_destruct) m_script->node_on_destruct(p, n_old); // Replace with air // This is slightly optimized compared to addNodeWithEvent(air) if (!m_map->removeNodeWithEvent(p)) return false; // Update active VoxelManipulator if a mapgen thread m_map->updateVManip(p); // Call post-destructor if (ndef->get(n_old).has_after_destruct) m_script->node_after_destruct(p, n_old); // Air doesn't require constructor return true; } bool ServerEnvironment::swapNode(v3s16 p, const MapNode &n) { if (!m_map->addNodeWithEvent(p, n, false)) return false; // Update active VoxelManipulator if a mapgen thread m_map->updateVManip(p); return true; } void ServerEnvironment::clearObjects(ClearObjectsMode mode) { infostream << "ServerEnvironment::clearObjects(): " << "Removing all active objects" << std::endl; auto cb_removal = [this] (ServerActiveObject *obj, u16 id) { if (obj->getType() == ACTIVEOBJECT_TYPE_PLAYER) return false; // Delete static object if block is loaded deleteStaticFromBlock(obj, id, MOD_REASON_CLEAR_ALL_OBJECTS, true); // If known by some client, don't delete immediately if (obj->m_known_by_count > 0) { obj->m_pending_removal = true; return false; } // Tell the object about removal obj->removingFromEnvironment(); // Deregister in scripting api m_script->removeObjectReference(obj); // Delete active object if (obj->environmentDeletes()) delete obj; return true; }; m_ao_manager.clear(cb_removal); // Get list of loaded blocks std::vector<v3s16> loaded_blocks; infostream << "ServerEnvironment::clearObjects(): " << "Listing all loaded blocks" << std::endl; m_map->listAllLoadedBlocks(loaded_blocks); infostream << "ServerEnvironment::clearObjects(): " << "Done listing all loaded blocks: " << loaded_blocks.size()<<std::endl; // Get list of loadable blocks std::vector<v3s16> loadable_blocks; if (mode == CLEAR_OBJECTS_MODE_FULL) { infostream << "ServerEnvironment::clearObjects(): " << "Listing all loadable blocks" << std::endl; m_map->listAllLoadableBlocks(loadable_blocks); infostream << "ServerEnvironment::clearObjects(): " << "Done listing all loadable blocks: " << loadable_blocks.size() << std::endl; } else { loadable_blocks = loaded_blocks; } actionstream << "ServerEnvironment::clearObjects(): " << "Now clearing objects in " << loadable_blocks.size() << " blocks" << std::endl; // Grab a reference on each loaded block to avoid unloading it for (v3s16 p : loaded_blocks) { MapBlock *block = m_map->getBlockNoCreateNoEx(p); assert(block != NULL); block->refGrab(); } // Remove objects in all loadable blocks u32 unload_interval = U32_MAX; if (mode == CLEAR_OBJECTS_MODE_FULL) { unload_interval = g_settings->getS32("max_clearobjects_extra_loaded_blocks"); unload_interval = MYMAX(unload_interval, 1); } u32 report_interval = loadable_blocks.size() / 10; u32 num_blocks_checked = 0; u32 num_blocks_cleared = 0; u32 num_objs_cleared = 0; for (auto i = loadable_blocks.begin(); i != loadable_blocks.end(); ++i) { v3s16 p = *i; MapBlock *block = m_map->emergeBlock(p, false); if (!block) { errorstream << "ServerEnvironment::clearObjects(): " << "Failed to emerge block " << PP(p) << std::endl; continue; } u32 num_stored = block->m_static_objects.m_stored.size(); u32 num_active = block->m_static_objects.m_active.size(); if (num_stored != 0 || num_active != 0) { block->m_static_objects.m_stored.clear(); block->m_static_objects.m_active.clear(); block->raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_CLEAR_ALL_OBJECTS); num_objs_cleared += num_stored + num_active; num_blocks_cleared++; } num_blocks_checked++; if (report_interval != 0 && num_blocks_checked % report_interval == 0) { float percent = 100.0 * (float)num_blocks_checked / loadable_blocks.size(); actionstream << "ServerEnvironment::clearObjects(): " << "Cleared " << num_objs_cleared << " objects" << " in " << num_blocks_cleared << " blocks (" << percent << "%)" << std::endl; } if (num_blocks_checked % unload_interval == 0) { m_map->unloadUnreferencedBlocks(); } } m_map->unloadUnreferencedBlocks(); // Drop references that were added above for (v3s16 p : loaded_blocks) { MapBlock *block = m_map->getBlockNoCreateNoEx(p); assert(block); block->refDrop(); } m_last_clear_objects_time = m_game_time; actionstream << "ServerEnvironment::clearObjects(): " << "Finished: Cleared " << num_objs_cleared << " objects" << " in " << num_blocks_cleared << " blocks" << std::endl; } void ServerEnvironment::step(float dtime) { /* Step time of day */ stepTimeOfDay(dtime); // Update this one // NOTE: This is kind of funny on a singleplayer game, but doesn't // really matter that much. static thread_local const float server_step = g_settings->getFloat("dedicated_server_step"); m_recommended_send_interval = server_step; /* Increment game time */ { m_game_time_fraction_counter += dtime; u32 inc_i = (u32)m_game_time_fraction_counter; m_game_time += inc_i; m_game_time_fraction_counter -= (float)inc_i; } /* Handle players */ { ScopeProfiler sp(g_profiler, "SEnv: handle players avg", SPT_AVG); for (RemotePlayer *player : m_players) { // Ignore disconnected players if (player->getPeerId() == PEER_ID_INEXISTENT) continue; // Move player->move(dtime, this, 100 * BS); } } /* Manage active block list */ if (m_active_blocks_management_interval.step(dtime, m_cache_active_block_mgmt_interval)) { ScopeProfiler sp(g_profiler, "SEnv: manage act. block list avg per interval", SPT_AVG); /* Get player block positions */ std::vector<PlayerSAO*> players; for (RemotePlayer *player: m_players) { // Ignore disconnected players if (player->getPeerId() == PEER_ID_INEXISTENT) continue; PlayerSAO *playersao = player->getPlayerSAO(); assert(playersao); players.push_back(playersao); } /* Update list of active blocks, collecting changes */ // use active_object_send_range_blocks since that is max distance // for active objects sent the client anyway static thread_local const s16 active_object_range = g_settings->getS16("active_object_send_range_blocks"); static thread_local const s16 active_block_range = g_settings->getS16("active_block_range"); std::set<v3s16> blocks_removed; std::set<v3s16> blocks_added; m_active_blocks.update(players, active_block_range, active_object_range, blocks_removed, blocks_added); /* Handle removed blocks */ // Convert active objects that are no more in active blocks to static deactivateFarObjects(false); for (const v3s16 &p: blocks_removed) { MapBlock *block = m_map->getBlockNoCreateNoEx(p); if (!block) continue; // Set current time as timestamp (and let it set ChangedFlag) block->setTimestamp(m_game_time); } /* Handle added blocks */ for (const v3s16 &p: blocks_added) { MapBlock *block = m_map->getBlockOrEmerge(p); if (!block) { m_active_blocks.m_list.erase(p); m_active_blocks.m_abm_list.erase(p); continue; } activateBlock(block); } } /* Mess around in active blocks */ if (m_active_blocks_nodemetadata_interval.step(dtime, m_cache_nodetimer_interval)) { ScopeProfiler sp(g_profiler, "SEnv: mess in act. blocks avg per interval", SPT_AVG); float dtime = m_cache_nodetimer_interval; for (const v3s16 &p: m_active_blocks.m_list) { MapBlock *block = m_map->getBlockNoCreateNoEx(p); if (!block) continue; // Reset block usage timer block->resetUsageTimer(); // Set current time as timestamp block->setTimestampNoChangedFlag(m_game_time); // If time has changed much from the one on disk, // set block to be saved when it is unloaded if(block->getTimestamp() > block->getDiskTimestamp() + 60) block->raiseModified(MOD_STATE_WRITE_AT_UNLOAD, MOD_REASON_BLOCK_EXPIRED); // Run node timers std::vector<NodeTimer> elapsed_timers = block->m_node_timers.step(dtime); if (!elapsed_timers.empty()) { MapNode n; v3s16 p2; for (const NodeTimer &elapsed_timer: elapsed_timers) { n = block->getNodeNoEx(elapsed_timer.position); p2 = elapsed_timer.position + block->getPosRelative(); if (m_script->node_on_timer(p2, n, elapsed_timer.elapsed)) { block->setNodeTimer(NodeTimer( elapsed_timer.timeout, 0, elapsed_timer.position)); } } } } } if (m_active_block_modifier_interval.step(dtime, m_cache_abm_interval)) do { // breakable if (m_active_block_interval_overload_skip > 0) { ScopeProfiler sp(g_profiler, "SEnv: ABM overload skips"); m_active_block_interval_overload_skip--; break; } ScopeProfiler sp(g_profiler, "SEnv: modify in blocks avg per interval", SPT_AVG); TimeTaker timer("modify in active blocks per interval"); // Initialize handling of ActiveBlockModifiers ABMHandler abmhandler(m_abms, m_cache_abm_interval, this, true); int blocks_scanned = 0; int abms_run = 0; int blocks_cached = 0; for (const v3s16 &p : m_active_blocks.m_abm_list) { MapBlock *block = m_map->getBlockNoCreateNoEx(p); if (!block) continue; // Set current time as timestamp block->setTimestampNoChangedFlag(m_game_time); /* Handle ActiveBlockModifiers */ abmhandler.apply(block, blocks_scanned, abms_run, blocks_cached); } g_profiler->avg("SEnv: active blocks", m_active_blocks.m_abm_list.size()); g_profiler->avg("SEnv: active blocks cached", blocks_cached); g_profiler->avg("SEnv: active blocks scanned for ABMs", blocks_scanned); g_profiler->avg("SEnv: ABMs run", abms_run); u32 time_ms = timer.stop(true); u32 max_time_ms = 200; if (time_ms > max_time_ms) { warningstream<<"active block modifiers took " <<time_ms<<"ms (longer than " <<max_time_ms<<"ms)"<<std::endl; m_active_block_interval_overload_skip = (time_ms / max_time_ms) + 1; } }while(0); /* Step script environment (run global on_step()) */ m_script->environment_Step(dtime); /* Step active objects */ { ScopeProfiler sp(g_profiler, "SEnv: step act. objs avg", SPT_AVG); // This helps the objects to send data at the same time bool send_recommended = false; m_send_recommended_timer += dtime; if (m_send_recommended_timer > getSendRecommendedInterval()) { m_send_recommended_timer -= getSendRecommendedInterval(); send_recommended = true; } auto cb_state = [this, dtime, send_recommended] (ServerActiveObject *obj) { if (obj->isGone()) return; // Step object obj->step(dtime, send_recommended); // Read messages from object while (!obj->m_messages_out.empty()) { this->m_active_object_messages.push(obj->m_messages_out.front()); obj->m_messages_out.pop(); } }; m_ao_manager.step(dtime, cb_state); } /* Manage active objects */ if (m_object_management_interval.step(dtime, 0.5)) { ScopeProfiler sp(g_profiler, "SEnv: remove removed objs avg /.5s", SPT_AVG); removeRemovedObjects(); } /* Manage particle spawner expiration */ if (m_particle_management_interval.step(dtime, 1.0)) { for (std::unordered_map<u32, float>::iterator i = m_particle_spawners.begin(); i != m_particle_spawners.end(); ) { //non expiring spawners if (i->second == PARTICLE_SPAWNER_NO_EXPIRY) { ++i; continue; } i->second -= 1.0f; if (i->second <= 0.f) m_particle_spawners.erase(i++); else ++i; } } } u32 ServerEnvironment::addParticleSpawner(float exptime) { // Timers with lifetime 0 do not expire float time = exptime > 0.f ? exptime : PARTICLE_SPAWNER_NO_EXPIRY; u32 id = 0; for (;;) { // look for unused particlespawner id id++; std::unordered_map<u32, float>::iterator f = m_particle_spawners.find(id); if (f == m_particle_spawners.end()) { m_particle_spawners[id] = time; break; } } return id; } u32 ServerEnvironment::addParticleSpawner(float exptime, u16 attached_id) { u32 id = addParticleSpawner(exptime); m_particle_spawner_attachments[id] = attached_id; if (ServerActiveObject *obj = getActiveObject(attached_id)) { obj->attachParticleSpawner(id); } return id; } void ServerEnvironment::deleteParticleSpawner(u32 id, bool remove_from_object) { m_particle_spawners.erase(id); const auto &it = m_particle_spawner_attachments.find(id); if (it != m_particle_spawner_attachments.end()) { u16 obj_id = it->second; ServerActiveObject *sao = getActiveObject(obj_id); if (sao != NULL && remove_from_object) { sao->detachParticleSpawner(id); } m_particle_spawner_attachments.erase(id); } } u16 ServerEnvironment::addActiveObject(ServerActiveObject *object) { assert(object); // Pre-condition m_added_objects++; u16 id = addActiveObjectRaw(object, true, 0); return id; } /* Finds out what new objects have been added to inside a radius around a position */ void ServerEnvironment::getAddedActiveObjects(PlayerSAO *playersao, s16 radius, s16 player_radius, std::set<u16> &current_objects, std::queue<u16> &added_objects) { f32 radius_f = radius * BS; f32 player_radius_f = player_radius * BS; if (player_radius_f < 0.0f) player_radius_f = 0.0f; m_ao_manager.getAddedActiveObjectsAroundPos(playersao->getBasePosition(), radius_f, player_radius_f, current_objects, added_objects); } /* Finds out what objects have been removed from inside a radius around a position */ void ServerEnvironment::getRemovedActiveObjects(PlayerSAO *playersao, s16 radius, s16 player_radius, std::set<u16> &current_objects, std::queue<u16> &removed_objects) { f32 radius_f = radius * BS; f32 player_radius_f = player_radius * BS; if (player_radius_f < 0) player_radius_f = 0; /* Go through current_objects; object is removed if: - object is not found in m_active_objects (this is actually an error condition; objects should be removed only after all clients have been informed about removal), or - object is to be removed or deactivated, or - object is too far away */ for (u16 id : current_objects) { ServerActiveObject *object = getActiveObject(id); if (object == NULL) { infostream << "ServerEnvironment::getRemovedActiveObjects():" << " object in current_objects is NULL" << std::endl; removed_objects.push(id); continue; } if (object->isGone()) { removed_objects.push(id); continue; } f32 distance_f = object->getBasePosition().getDistanceFrom(playersao->getBasePosition()); if (object->getType() == ACTIVEOBJECT_TYPE_PLAYER) { if (distance_f <= player_radius_f || player_radius_f == 0) continue; } else if (distance_f <= radius_f) continue; // Object is no longer visible removed_objects.push(id); } } void ServerEnvironment::setStaticForActiveObjectsInBlock( v3s16 blockpos, bool static_exists, v3s16 static_block) { MapBlock *block = m_map->getBlockNoCreateNoEx(blockpos); if (!block) return; for (auto &so_it : block->m_static_objects.m_active) { // Get the ServerActiveObject counterpart to this StaticObject ServerActiveObject *sao = m_ao_manager.getActiveObject(so_it.first); if (!sao) { // If this ever happens, there must be some kind of nasty bug. errorstream << "ServerEnvironment::setStaticForObjectsInBlock(): " "Object from MapBlock::m_static_objects::m_active not found " "in m_active_objects"; continue; } sao->m_static_exists = static_exists; sao->m_static_block = static_block; } } ActiveObjectMessage ServerEnvironment::getActiveObjectMessage() { if(m_active_object_messages.empty()) return ActiveObjectMessage(0); ActiveObjectMessage message = m_active_object_messages.front(); m_active_object_messages.pop(); return message; } void ServerEnvironment::getSelectedActiveObjects( const core::line3d<f32> &shootline_on_map, std::vector<PointedThing> &objects) { std::vector<u16> objectIds; getObjectsInsideRadius(objectIds, shootline_on_map.start, shootline_on_map.getLength() + 10.0f); const v3f line_vector = shootline_on_map.getVector(); for (u16 objectId : objectIds) { ServerActiveObject* obj = getActiveObject(objectId); aabb3f selection_box; if (!obj->getSelectionBox(&selection_box)) continue; v3f pos = obj->getBasePosition(); aabb3f offsetted_box(selection_box.MinEdge + pos, selection_box.MaxEdge + pos); v3f current_intersection; v3s16 current_normal; if (boxLineCollision(offsetted_box, shootline_on_map.start, line_vector, &current_intersection, &current_normal)) { objects.emplace_back( (s16) objectId, current_intersection, current_normal, (current_intersection - shootline_on_map.start).getLengthSQ()); } } } /* ************ Private methods ************* */ u16 ServerEnvironment::addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s) { if (!m_ao_manager.registerObject(object)) { return 0; } // Register reference in scripting api (must be done before post-init) m_script->addObjectReference(object); // Post-initialize object object->addedToEnvironment(dtime_s); // Add static data to block if (object->isStaticAllowed()) { // Add static object to active static list of the block v3f objectpos = object->getBasePosition(); StaticObject s_obj(object, objectpos); // Add to the block where the object is located in v3s16 blockpos = getNodeBlockPos(floatToInt(objectpos, BS)); MapBlock *block = m_map->emergeBlock(blockpos); if(block){ block->m_static_objects.m_active[object->getId()] = s_obj; object->m_static_exists = true; object->m_static_block = blockpos; if(set_changed) block->raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_ADD_ACTIVE_OBJECT_RAW); } else { v3s16 p = floatToInt(objectpos, BS); errorstream<<"ServerEnvironment::addActiveObjectRaw(): " <<"could not emerge block for storing id="<<object->getId() <<" statically (pos="<<PP(p)<<")"<<std::endl; } } return object->getId(); } /* Remove objects that satisfy (isGone() && m_known_by_count==0) */ void ServerEnvironment::removeRemovedObjects() { auto clear_cb = [this] (ServerActiveObject *obj, u16 id) { // This shouldn't happen but check it if (!obj) { errorstream << "ServerEnvironment::removeRemovedObjects(): " << "NULL object found. id=" << id << std::endl; return true; } /* We will handle objects marked for removal or deactivation */ if (!obj->isGone()) return false; /* Delete static data from block if removed */ if (obj->m_pending_removal) deleteStaticFromBlock(obj, id, MOD_REASON_REMOVE_OBJECTS_REMOVE, false); // If still known by clients, don't actually remove. On some future // invocation this will be 0, which is when removal will continue. if(obj->m_known_by_count > 0) return false; /* Move static data from active to stored if deactivated */ if (!obj->m_pending_removal && obj->m_static_exists) { MapBlock *block = m_map->emergeBlock(obj->m_static_block, false); if (block) { const auto i = block->m_static_objects.m_active.find(id); if (i != block->m_static_objects.m_active.end()) { block->m_static_objects.m_stored.push_back(i->second); block->m_static_objects.m_active.erase(id); block->raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_REMOVE_OBJECTS_DEACTIVATE); } else { warningstream << "ServerEnvironment::removeRemovedObjects(): " << "id=" << id << " m_static_exists=true but " << "static data doesn't actually exist in " << PP(obj->m_static_block) << std::endl; } } else { infostream << "Failed to emerge block from which an object to " << "be deactivated was loaded from. id=" << id << std::endl; } } // Tell the object about removal obj->removingFromEnvironment(); // Deregister in scripting api m_script->removeObjectReference(obj); // Delete if (obj->environmentDeletes()) delete obj; return true; }; m_ao_manager.clear(clear_cb); } static void print_hexdump(std::ostream &o, const std::string &data) { const int linelength = 16; for(int l=0; ; l++){ int i0 = linelength * l; bool at_end = false; int thislinelength = linelength; if(i0 + thislinelength > (int)data.size()){ thislinelength = data.size() - i0; at_end = true; } for(int di=0; di<linelength; di++){ int i = i0 + di; char buf[4]; if(di<thislinelength) porting::mt_snprintf(buf, sizeof(buf), "%.2x ", data[i]); else porting::mt_snprintf(buf, sizeof(buf), " "); o<<buf; } o<<" "; for(int di=0; di<thislinelength; di++){ int i = i0 + di; if(data[i] >= 32) o<<data[i]; else o<<"."; } o<<std::endl; if(at_end) break; } } /* Convert stored objects from blocks near the players to active. */ void ServerEnvironment::activateObjects(MapBlock *block, u32 dtime_s) { if(block == NULL) return; // Ignore if no stored objects (to not set changed flag) if(block->m_static_objects.m_stored.empty()) return; verbosestream<<"ServerEnvironment::activateObjects(): " <<"activating objects of block "<<PP(block->getPos()) <<" ("<<block->m_static_objects.m_stored.size() <<" objects)"<<std::endl; bool large_amount = (block->m_static_objects.m_stored.size() > g_settings->getU16("max_objects_per_block")); if (large_amount) { errorstream<<"suspiciously large amount of objects detected: " <<block->m_static_objects.m_stored.size()<<" in " <<PP(block->getPos()) <<"; removing all of them."<<std::endl; // Clear stored list block->m_static_objects.m_stored.clear(); block->raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_TOO_MANY_OBJECTS); return; } // Activate stored objects std::vector<StaticObject> new_stored; for (const StaticObject &s_obj : block->m_static_objects.m_stored) { // Create an active object from the data ServerActiveObject *obj = ServerActiveObject::create ((ActiveObjectType) s_obj.type, this, 0, s_obj.pos, s_obj.data); // If couldn't create object, store static data back. if(obj == NULL) { errorstream<<"ServerEnvironment::activateObjects(): " <<"failed to create active object from static object " <<"in block "<<PP(s_obj.pos/BS) <<" type="<<(int)s_obj.type<<" data:"<<std::endl; print_hexdump(verbosestream, s_obj.data); new_stored.push_back(s_obj); continue; } verbosestream<<"ServerEnvironment::activateObjects(): " <<"activated static object pos="<<PP(s_obj.pos/BS) <<" type="<<(int)s_obj.type<<std::endl; // This will also add the object to the active static list addActiveObjectRaw(obj, false, dtime_s); } // Clear stored list block->m_static_objects.m_stored.clear(); // Add leftover failed stuff to stored list for (const StaticObject &s_obj : new_stored) { block->m_static_objects.m_stored.push_back(s_obj); } /* Note: Block hasn't really been modified here. The objects have just been activated and moved from the stored static list to the active static list. As such, the block is essentially the same. Thus, do not call block->raiseModified(MOD_STATE_WRITE_NEEDED). Otherwise there would be a huge amount of unnecessary I/O. */ } /* Convert objects that are not standing inside active blocks to static. If m_known_by_count != 0, active object is not deleted, but static data is still updated. If force_delete is set, active object is deleted nevertheless. It shall only be set so in the destructor of the environment. If block wasn't generated (not in memory or on disk), */ void ServerEnvironment::deactivateFarObjects(bool _force_delete) { auto cb_deactivate = [this, _force_delete] (ServerActiveObject *obj, u16 id) { // force_delete might be overriden per object bool force_delete = _force_delete; // Do not deactivate if static data creation not allowed if (!force_delete && !obj->isStaticAllowed()) return false; // removeRemovedObjects() is responsible for these if (!force_delete && obj->isGone()) return false; const v3f &objectpos = obj->getBasePosition(); // The block in which the object resides in v3s16 blockpos_o = getNodeBlockPos(floatToInt(objectpos, BS)); // If object's static data is stored in a deactivated block and object // is actually located in an active block, re-save to the block in // which the object is actually located in. if (!force_delete && obj->m_static_exists && !m_active_blocks.contains(obj->m_static_block) && m_active_blocks.contains(blockpos_o)) { // Delete from block where object was located deleteStaticFromBlock(obj, id, MOD_REASON_STATIC_DATA_REMOVED, false); StaticObject s_obj(obj, objectpos); // Save to block where object is located saveStaticToBlock(blockpos_o, id, obj, s_obj, MOD_REASON_STATIC_DATA_ADDED); return false; } // If block is still active, don't remove if (!force_delete && m_active_blocks.contains(blockpos_o)) return false; verbosestream << "ServerEnvironment::deactivateFarObjects(): " << "deactivating object id=" << id << " on inactive block " << PP(blockpos_o) << std::endl; // If known by some client, don't immediately delete. bool pending_delete = (obj->m_known_by_count > 0 && !force_delete); /* Update the static data */ if (obj->isStaticAllowed()) { // Create new static object StaticObject s_obj(obj, objectpos); bool stays_in_same_block = false; bool data_changed = true; // Check if static data has changed considerably if (obj->m_static_exists) { if (obj->m_static_block == blockpos_o) stays_in_same_block = true; MapBlock *block = m_map->emergeBlock(obj->m_static_block, false); if (block) { const auto n = block->m_static_objects.m_active.find(id); if (n != block->m_static_objects.m_active.end()) { StaticObject static_old = n->second; float save_movem = obj->getMinimumSavedMovement(); if (static_old.data == s_obj.data && (static_old.pos - objectpos).getLength() < save_movem) data_changed = false; } else { warningstream << "ServerEnvironment::deactivateFarObjects(): " << "id=" << id << " m_static_exists=true but " << "static data doesn't actually exist in " << PP(obj->m_static_block) << std::endl; } } } /* While changes are always saved, blocks are only marked as modified if the object has moved or different staticdata. (see above) */ bool shall_be_written = (!stays_in_same_block || data_changed); u32 reason = shall_be_written ? MOD_REASON_STATIC_DATA_CHANGED : MOD_REASON_UNKNOWN; // Delete old static object deleteStaticFromBlock(obj, id, reason, false); // Add to the block where the object is located in v3s16 blockpos = getNodeBlockPos(floatToInt(objectpos, BS)); u16 store_id = pending_delete ? id : 0; if (!saveStaticToBlock(blockpos, store_id, obj, s_obj, reason)) force_delete = true; } /* If known by some client, set pending deactivation. Otherwise delete it immediately. */ if (pending_delete && !force_delete) { verbosestream << "ServerEnvironment::deactivateFarObjects(): " << "object id=" << id << " is known by clients" << "; not deleting yet" << std::endl; obj->m_pending_deactivation = true; return false; } verbosestream << "ServerEnvironment::deactivateFarObjects(): " << "object id=" << id << " is not known by clients" << "; deleting" << std::endl; // Tell the object about removal obj->removingFromEnvironment(); // Deregister in scripting api m_script->removeObjectReference(obj); // Delete active object if (obj->environmentDeletes()) delete obj; return true; }; m_ao_manager.clear(cb_deactivate); } void ServerEnvironment::deleteStaticFromBlock( ServerActiveObject *obj, u16 id, u32 mod_reason, bool no_emerge) { if (!obj->m_static_exists) return; MapBlock *block; if (no_emerge) block = m_map->getBlockNoCreateNoEx(obj->m_static_block); else block = m_map->emergeBlock(obj->m_static_block, false); if (!block) { if (!no_emerge) errorstream << "ServerEnv: Failed to emerge block " << PP(obj->m_static_block) << " when deleting static data of object from it. id=" << id << std::endl; return; } block->m_static_objects.remove(id); if (mod_reason != MOD_REASON_UNKNOWN) // Do not mark as modified if requested block->raiseModified(MOD_STATE_WRITE_NEEDED, mod_reason); obj->m_static_exists = false; } bool ServerEnvironment::saveStaticToBlock( v3s16 blockpos, u16 store_id, ServerActiveObject *obj, const StaticObject &s_obj, u32 mod_reason) { MapBlock *block = nullptr; try { block = m_map->emergeBlock(blockpos); } catch (InvalidPositionException &e) { // Handled via NULL pointer // NOTE: emergeBlock's failure is usually determined by it // actually returning NULL } if (!block) { errorstream << "ServerEnv: Failed to emerge block " << PP(obj->m_static_block) << " when saving static data of object to it. id=" << store_id << std::endl; return false; } if (block->m_static_objects.m_stored.size() >= g_settings->getU16("max_objects_per_block")) { warningstream << "ServerEnv: Trying to store id = " << store_id << " statically but block " << PP(blockpos) << " already contains " << block->m_static_objects.m_stored.size() << " objects." << std::endl; return false; } block->m_static_objects.insert(store_id, s_obj); if (mod_reason != MOD_REASON_UNKNOWN) // Do not mark as modified if requested block->raiseModified(MOD_STATE_WRITE_NEEDED, mod_reason); obj->m_static_exists = true; obj->m_static_block = blockpos; return true; } PlayerDatabase *ServerEnvironment::openPlayerDatabase(const std::string &name, const std::string &savedir, const Settings &conf) { if (name == "sqlite3") return new PlayerDatabaseSQLite3(savedir); if (name == "dummy") return new Database_Dummy(); #if USE_POSTGRESQL if (name == "postgresql") { std::string connect_string; conf.getNoEx("pgsql_player_connection", connect_string); return new PlayerDatabasePostgreSQL(connect_string); } #endif if (name == "files") return new PlayerDatabaseFiles(savedir + DIR_DELIM + "players"); throw BaseException(std::string("Database backend ") + name + " not supported."); } bool ServerEnvironment::migratePlayersDatabase(const GameParams &game_params, const Settings &cmd_args) { std::string migrate_to = cmd_args.get("migrate-players"); Settings world_mt; std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt"; if (!world_mt.readConfigFile(world_mt_path.c_str())) { errorstream << "Cannot read world.mt!" << std::endl; return false; } if (!world_mt.exists("player_backend")) { errorstream << "Please specify your current backend in world.mt:" << std::endl << " player_backend = {files|sqlite3|postgresql}" << std::endl; return false; } std::string backend = world_mt.get("player_backend"); if (backend == migrate_to) { errorstream << "Cannot migrate: new backend is same" << " as the old one" << std::endl; return false; } const std::string players_backup_path = game_params.world_path + DIR_DELIM + "players.bak"; if (backend == "files") { // Create backup directory fs::CreateDir(players_backup_path); } try { PlayerDatabase *srcdb = ServerEnvironment::openPlayerDatabase(backend, game_params.world_path, world_mt); PlayerDatabase *dstdb = ServerEnvironment::openPlayerDatabase(migrate_to, game_params.world_path, world_mt); std::vector<std::string> player_list; srcdb->listPlayers(player_list); for (std::vector<std::string>::const_iterator it = player_list.begin(); it != player_list.end(); ++it) { actionstream << "Migrating player " << it->c_str() << std::endl; RemotePlayer player(it->c_str(), NULL); PlayerSAO playerSAO(NULL, &player, 15000, false); srcdb->loadPlayer(&player, &playerSAO); playerSAO.finalize(&player, std::set<std::string>()); player.setPlayerSAO(&playerSAO); dstdb->savePlayer(&player); // For files source, move player files to backup dir if (backend == "files") { fs::Rename( game_params.world_path + DIR_DELIM + "players" + DIR_DELIM + (*it), players_backup_path + DIR_DELIM + (*it)); } } actionstream << "Successfully migrated " << player_list.size() << " players" << std::endl; world_mt.set("player_backend", migrate_to); if (!world_mt.updateConfigFile(world_mt_path.c_str())) errorstream << "Failed to update world.mt!" << std::endl; else actionstream << "world.mt updated" << std::endl; // When migration is finished from file backend, remove players directory if empty if (backend == "files") { fs::DeleteSingleFileOrEmptyDirectory(game_params.world_path + DIR_DELIM + "players"); } delete srcdb; delete dstdb; } catch (BaseException &e) { errorstream << "An error occurred during migration: " << e.what() << std::endl; return false; } return true; } AuthDatabase *ServerEnvironment::openAuthDatabase( const std::string &name, const std::string &savedir, const Settings &conf) { if (name == "sqlite3") return new AuthDatabaseSQLite3(savedir); if (name == "files") return new AuthDatabaseFiles(savedir); throw BaseException(std::string("Database backend ") + name + " not supported."); } bool ServerEnvironment::migrateAuthDatabase( const GameParams &game_params, const Settings &cmd_args) { std::string migrate_to = cmd_args.get("migrate-auth"); Settings world_mt; std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt"; if (!world_mt.readConfigFile(world_mt_path.c_str())) { errorstream << "Cannot read world.mt!" << std::endl; return false; } std::string backend = "files"; if (world_mt.exists("auth_backend")) backend = world_mt.get("auth_backend"); else warningstream << "No auth_backend found in world.mt, " "assuming \"files\"." << std::endl; if (backend == migrate_to) { errorstream << "Cannot migrate: new backend is same" << " as the old one" << std::endl; return false; } try { const std::unique_ptr<AuthDatabase> srcdb(ServerEnvironment::openAuthDatabase( backend, game_params.world_path, world_mt)); const std::unique_ptr<AuthDatabase> dstdb(ServerEnvironment::openAuthDatabase( migrate_to, game_params.world_path, world_mt)); std::vector<std::string> names_list; srcdb->listNames(names_list); for (const std::string &name : names_list) { actionstream << "Migrating auth entry for " << name << std::endl; bool success; AuthEntry authEntry; success = srcdb->getAuth(name, authEntry); success = success && dstdb->createAuth(authEntry); if (!success) errorstream << "Failed to migrate " << name << std::endl; } actionstream << "Successfully migrated " << names_list.size() << " auth entries" << std::endl; world_mt.set("auth_backend", migrate_to); if (!world_mt.updateConfigFile(world_mt_path.c_str())) errorstream << "Failed to update world.mt!" << std::endl; else actionstream << "world.mt updated" << std::endl; if (backend == "files") { // special-case files migration: // move auth.txt to auth.txt.bak if possible std::string auth_txt_path = game_params.world_path + DIR_DELIM + "auth.txt"; std::string auth_bak_path = auth_txt_path + ".bak"; if (!fs::PathExists(auth_bak_path)) if (fs::Rename(auth_txt_path, auth_bak_path)) actionstream << "Renamed auth.txt to auth.txt.bak" << std::endl; else errorstream << "Could not rename auth.txt to " "auth.txt.bak" << std::endl; else warningstream << "auth.txt.bak already exists, auth.txt " "not renamed" << std::endl; } } catch (BaseException &e) { errorstream << "An error occurred during migration: " << e.what() << std::endl; return false; } return true; }
pgimeno/minetest
src/serverenvironment.cpp
C++
mit
65,675
/* Minetest Copyright (C) 2010-2017 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "activeobject.h" #include "environment.h" #include "mapnode.h" #include "settings.h" #include "server/activeobjectmgr.h" #include "util/numeric.h" #include <set> class IGameDef; class ServerMap; struct GameParams; class MapBlock; class RemotePlayer; class PlayerDatabase; class AuthDatabase; class PlayerSAO; class ServerEnvironment; class ActiveBlockModifier; struct StaticObject; class ServerActiveObject; class Server; class ServerScripting; /* {Active, Loading} block modifier interface. These are fed into ServerEnvironment at initialization time; ServerEnvironment handles deleting them. */ class ActiveBlockModifier { public: ActiveBlockModifier() = default; virtual ~ActiveBlockModifier() = default; // Set of contents to trigger on virtual const std::vector<std::string> &getTriggerContents() const = 0; // Set of required neighbors (trigger doesn't happen if none are found) // Empty = do not check neighbors virtual const std::vector<std::string> &getRequiredNeighbors() const = 0; // Trigger interval in seconds virtual float getTriggerInterval() = 0; // Random chance of (1 / return value), 0 is disallowed virtual u32 getTriggerChance() = 0; // Whether to modify chance to simulate time lost by an unnattended block virtual bool getSimpleCatchUp() = 0; // This is called usually at interval for 1/chance of the nodes virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){}; virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n, u32 active_object_count, u32 active_object_count_wider){}; }; struct ABMWithState { ActiveBlockModifier *abm; float timer = 0.0f; ABMWithState(ActiveBlockModifier *abm_); }; struct LoadingBlockModifierDef { // Set of contents to trigger on std::set<std::string> trigger_contents; std::string name; bool run_at_every_load = false; virtual ~LoadingBlockModifierDef() = default; virtual void trigger(ServerEnvironment *env, v3s16 p, MapNode n){}; }; struct LBMContentMapping { typedef std::unordered_map<content_t, std::vector<LoadingBlockModifierDef *>> lbm_map; lbm_map map; std::vector<LoadingBlockModifierDef *> lbm_list; // Needs to be separate method (not inside destructor), // because the LBMContentMapping may be copied and destructed // many times during operation in the lbm_lookup_map. void deleteContents(); void addLBM(LoadingBlockModifierDef *lbm_def, IGameDef *gamedef); const std::vector<LoadingBlockModifierDef *> *lookup(content_t c) const; }; class LBMManager { public: LBMManager() = default; ~LBMManager(); // Don't call this after loadIntroductionTimes() ran. void addLBMDef(LoadingBlockModifierDef *lbm_def); void loadIntroductionTimes(const std::string &times, IGameDef *gamedef, u32 now); // Don't call this before loadIntroductionTimes() ran. std::string createIntroductionTimesString(); // Don't call this before loadIntroductionTimes() ran. void applyLBMs(ServerEnvironment *env, MapBlock *block, u32 stamp); // Warning: do not make this std::unordered_map, order is relevant here typedef std::map<u32, LBMContentMapping> lbm_lookup_map; private: // Once we set this to true, we can only query, // not modify bool m_query_mode = false; // For m_query_mode == false: // The key of the map is the LBM def's name. // TODO make this std::unordered_map std::map<std::string, LoadingBlockModifierDef *> m_lbm_defs; // For m_query_mode == true: // The key of the map is the LBM def's first introduction time. lbm_lookup_map m_lbm_lookup; // Returns an iterator to the LBMs that were introduced // after the given time. This is guaranteed to return // valid values for everything lbm_lookup_map::const_iterator getLBMsIntroducedAfter(u32 time) { return m_lbm_lookup.lower_bound(time); } }; /* List of active blocks, used by ServerEnvironment */ class ActiveBlockList { public: void update(std::vector<PlayerSAO*> &active_players, s16 active_block_range, s16 active_object_range, std::set<v3s16> &blocks_removed, std::set<v3s16> &blocks_added); bool contains(v3s16 p){ return (m_list.find(p) != m_list.end()); } void clear(){ m_list.clear(); } std::set<v3s16> m_list; std::set<v3s16> m_abm_list; std::set<v3s16> m_forceloaded_list; private: }; /* Operation mode for ServerEnvironment::clearObjects() */ enum ClearObjectsMode { // Load and go through every mapblock, clearing objects CLEAR_OBJECTS_MODE_FULL, // Clear objects immediately in loaded mapblocks; // clear objects in unloaded mapblocks only when the mapblocks are next activated. CLEAR_OBJECTS_MODE_QUICK, }; /* The server-side environment. This is not thread-safe. Server uses an environment mutex. */ typedef std::unordered_map<u16, ServerActiveObject *> ServerActiveObjectMap; class ServerEnvironment : public Environment { public: ServerEnvironment(ServerMap *map, ServerScripting *scriptIface, Server *server, const std::string &path_world); ~ServerEnvironment(); Map & getMap(); ServerMap & getServerMap(); //TODO find way to remove this fct! ServerScripting* getScriptIface() { return m_script; } Server *getGameDef() { return m_server; } float getSendRecommendedInterval() { return m_recommended_send_interval; } void kickAllPlayers(AccessDeniedCode reason, const std::string &str_reason, bool reconnect); // Save players void saveLoadedPlayers(bool force = false); void savePlayer(RemotePlayer *player); PlayerSAO *loadPlayer(RemotePlayer *player, bool *new_player, session_t peer_id, bool is_singleplayer); void addPlayer(RemotePlayer *player); void removePlayer(RemotePlayer *player); bool removePlayerFromDatabase(const std::string &name); /* Save and load time of day and game timer */ void saveMeta(); void loadMeta(); u32 addParticleSpawner(float exptime); u32 addParticleSpawner(float exptime, u16 attached_id); void deleteParticleSpawner(u32 id, bool remove_from_object = true); /* External ActiveObject interface ------------------------------------------- */ ServerActiveObject* getActiveObject(u16 id) { return m_ao_manager.getActiveObject(id); } /* Add an active object to the environment. Environment handles deletion of object. Object may be deleted by environment immediately. If id of object is 0, assigns a free id to it. Returns the id of the object. Returns 0 if not added and thus deleted. */ u16 addActiveObject(ServerActiveObject *object); /* Add an active object as a static object to the corresponding MapBlock. Caller allocates memory, ServerEnvironment frees memory. Return value: true if succeeded, false if failed. (note: not used, pending removal from engine) */ //bool addActiveObjectAsStatic(ServerActiveObject *object); /* Find out what new objects have been added to inside a radius around a position */ void getAddedActiveObjects(PlayerSAO *playersao, s16 radius, s16 player_radius, std::set<u16> &current_objects, std::queue<u16> &added_objects); /* Find out what new objects have been removed from inside a radius around a position */ void getRemovedActiveObjects(PlayerSAO *playersao, s16 radius, s16 player_radius, std::set<u16> &current_objects, std::queue<u16> &removed_objects); /* Get the next message emitted by some active object. Returns a message with id=0 if no messages are available. */ ActiveObjectMessage getActiveObjectMessage(); virtual void getSelectedActiveObjects( const core::line3d<f32> &shootline_on_map, std::vector<PointedThing> &objects ); /* Activate objects and dynamically modify for the dtime determined from timestamp and additional_dtime */ void activateBlock(MapBlock *block, u32 additional_dtime=0); /* {Active,Loading}BlockModifiers ------------------------------------------- */ void addActiveBlockModifier(ActiveBlockModifier *abm); void addLoadingBlockModifierDef(LoadingBlockModifierDef *lbm); /* Other stuff ------------------------------------------- */ // Script-aware node setters bool setNode(v3s16 p, const MapNode &n); bool removeNode(v3s16 p); bool swapNode(v3s16 p, const MapNode &n); // Find all active objects inside a radius around a point void getObjectsInsideRadius(std::vector<u16> &objects, const v3f &pos, float radius) { return m_ao_manager.getObjectsInsideRadius(pos, radius, objects); } // Clear objects, loading and going through every MapBlock void clearObjects(ClearObjectsMode mode); // This makes stuff happen void step(f32 dtime); /*! * Returns false if the given line intersects with a * non-air node, true otherwise. * \param pos1 start of the line * \param pos2 end of the line * \param p output, position of the first non-air node * the line intersects */ bool line_of_sight(v3f pos1, v3f pos2, v3s16 *p = NULL); u32 getGameTime() const { return m_game_time; } void reportMaxLagEstimate(float f) { m_max_lag_estimate = f; } float getMaxLagEstimate() { return m_max_lag_estimate; } std::set<v3s16>* getForceloadedBlocks() { return &m_active_blocks.m_forceloaded_list; }; // Sets the static object status all the active objects in the specified block // This is only really needed for deleting blocks from the map void setStaticForActiveObjectsInBlock(v3s16 blockpos, bool static_exists, v3s16 static_block=v3s16(0,0,0)); RemotePlayer *getPlayer(const session_t peer_id); RemotePlayer *getPlayer(const char* name); u32 getPlayerCount() const { return m_players.size(); } static bool migratePlayersDatabase(const GameParams &game_params, const Settings &cmd_args); AuthDatabase *getAuthDatabase() { return m_auth_database; } static bool migrateAuthDatabase(const GameParams &game_params, const Settings &cmd_args); private: /** * called if env_meta.txt doesn't exist (e.g. new world) */ void loadDefaultMeta(); static PlayerDatabase *openPlayerDatabase(const std::string &name, const std::string &savedir, const Settings &conf); static AuthDatabase *openAuthDatabase(const std::string &name, const std::string &savedir, const Settings &conf); /* Internal ActiveObject interface ------------------------------------------- */ /* Add an active object to the environment. Called by addActiveObject. Object may be deleted by environment immediately. If id of object is 0, assigns a free id to it. Returns the id of the object. Returns 0 if not added and thus deleted. */ u16 addActiveObjectRaw(ServerActiveObject *object, bool set_changed, u32 dtime_s); /* Remove all objects that satisfy (isGone() && m_known_by_count==0) */ void removeRemovedObjects(); /* Convert stored objects from block to active */ void activateObjects(MapBlock *block, u32 dtime_s); /* Convert objects that are not in active blocks to static. If m_known_by_count != 0, active object is not deleted, but static data is still updated. If force_delete is set, active object is deleted nevertheless. It shall only be set so in the destructor of the environment. */ void deactivateFarObjects(bool force_delete); /* A few helpers used by the three above methods */ void deleteStaticFromBlock( ServerActiveObject *obj, u16 id, u32 mod_reason, bool no_emerge); bool saveStaticToBlock(v3s16 blockpos, u16 store_id, ServerActiveObject *obj, const StaticObject &s_obj, u32 mod_reason); /* Member variables */ // The map ServerMap *m_map; // Lua state ServerScripting* m_script; // Server definition Server *m_server; // Active Object Manager server::ActiveObjectMgr m_ao_manager; // World path const std::string m_path_world; // Outgoing network message buffer for active objects std::queue<ActiveObjectMessage> m_active_object_messages; // Some timers float m_send_recommended_timer = 0.0f; IntervalLimiter m_object_management_interval; // List of active blocks ActiveBlockList m_active_blocks; IntervalLimiter m_active_blocks_management_interval; IntervalLimiter m_active_block_modifier_interval; IntervalLimiter m_active_blocks_nodemetadata_interval; int m_active_block_interval_overload_skip = 0; // Time from the beginning of the game in seconds. // Incremented in step(). u32 m_game_time = 0; // A helper variable for incrementing the latter float m_game_time_fraction_counter = 0.0f; // Time of last clearObjects call (game time). // When a mapblock older than this is loaded, its objects are cleared. u32 m_last_clear_objects_time = 0; // Active block modifiers std::vector<ABMWithState> m_abms; LBMManager m_lbm_mgr; // An interval for generally sending object positions and stuff float m_recommended_send_interval = 0.1f; // Estimate for general maximum lag as determined by server. // Can raise to high values like 15s with eg. map generation mods. float m_max_lag_estimate = 0.1f; // peer_ids in here should be unique, except that there may be many 0s std::vector<RemotePlayer*> m_players; PlayerDatabase *m_player_database = nullptr; AuthDatabase *m_auth_database = nullptr; // Particles IntervalLimiter m_particle_management_interval; std::unordered_map<u32, float> m_particle_spawners; std::unordered_map<u32, u16> m_particle_spawner_attachments; };
pgimeno/minetest
src/serverenvironment.h
C++
mit
13,975
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <fstream> #include <iostream> #include <sstream> #include <algorithm> #include "version.h" #include "settings.h" #include "serverlist.h" #include "filesys.h" #include "porting.h" #include "log.h" #include "network/networkprotocol.h" #include <json/json.h> #include "convert_json.h" #include "httpfetch.h" #include "util/string.h" namespace ServerList { std::string getFilePath() { std::string serverlist_file = g_settings->get("serverlist_file"); std::string dir_path = "client" DIR_DELIM "serverlist" DIR_DELIM; fs::CreateDir(porting::path_user + DIR_DELIM "client"); fs::CreateDir(porting::path_user + DIR_DELIM + dir_path); return porting::path_user + DIR_DELIM + dir_path + serverlist_file; } std::vector<ServerListSpec> getLocal() { std::string path = ServerList::getFilePath(); std::string liststring; if (fs::PathExists(path)) { std::ifstream istream(path.c_str()); if (istream.is_open()) { std::ostringstream ostream; ostream << istream.rdbuf(); liststring = ostream.str(); istream.close(); } } return deSerialize(liststring); } std::vector<ServerListSpec> getOnline() { std::ostringstream geturl; u16 proto_version_min = CLIENT_PROTOCOL_VERSION_MIN; geturl << g_settings->get("serverlist_url") << "/list?proto_version_min=" << proto_version_min << "&proto_version_max=" << CLIENT_PROTOCOL_VERSION_MAX; Json::Value root = fetchJsonValue(geturl.str(), NULL); std::vector<ServerListSpec> server_list; if (!root.isObject()) { return server_list; } root = root["list"]; if (!root.isArray()) { return server_list; } for (const Json::Value &i : root) { if (i.isObject()) { server_list.push_back(i); } } return server_list; } // Delete a server from the local favorites list bool deleteEntry(const ServerListSpec &server) { std::vector<ServerListSpec> serverlist = ServerList::getLocal(); for (std::vector<ServerListSpec>::iterator it = serverlist.begin(); it != serverlist.end();) { if ((*it)["address"] == server["address"] && (*it)["port"] == server["port"]) { it = serverlist.erase(it); } else { ++it; } } std::string path = ServerList::getFilePath(); std::ostringstream ss(std::ios_base::binary); ss << ServerList::serialize(serverlist); if (!fs::safeWriteToFile(path, ss.str())) return false; return true; } // Insert a server to the local favorites list bool insert(const ServerListSpec &server) { // Remove duplicates ServerList::deleteEntry(server); std::vector<ServerListSpec> serverlist = ServerList::getLocal(); // Insert new server at the top of the list serverlist.insert(serverlist.begin(), server); std::string path = ServerList::getFilePath(); std::ostringstream ss(std::ios_base::binary); ss << ServerList::serialize(serverlist); if (!fs::safeWriteToFile(path, ss.str())) return false; return true; } std::vector<ServerListSpec> deSerialize(const std::string &liststring) { std::vector<ServerListSpec> serverlist; std::istringstream stream(liststring); std::string line, tmp; while (std::getline(stream, line)) { std::transform(line.begin(), line.end(), line.begin(), ::toupper); if (line == "[SERVER]") { ServerListSpec server; std::getline(stream, tmp); server["name"] = tmp; std::getline(stream, tmp); server["address"] = tmp; std::getline(stream, tmp); server["port"] = tmp; std::getline(stream, tmp); server["description"] = tmp; serverlist.push_back(server); } } return serverlist; } const std::string serialize(const std::vector<ServerListSpec> &serverlist) { std::string liststring; for (const ServerListSpec &it : serverlist) { liststring += "[server]\n"; liststring += it["name"].asString() + '\n'; liststring += it["address"].asString() + '\n'; liststring += it["port"].asString() + '\n'; liststring += it["description"].asString() + '\n'; liststring += '\n'; } return liststring; } const std::string serializeJson(const std::vector<ServerListSpec> &serverlist) { Json::Value root; Json::Value list(Json::arrayValue); for (const ServerListSpec &it : serverlist) { list.append(it); } root["list"] = list; return fastWriteJson(root); } #if USE_CURL void sendAnnounce(AnnounceAction action, const u16 port, const std::vector<std::string> &clients_names, const double uptime, const u32 game_time, const float lag, const std::string &gameid, const std::string &mg_name, const std::vector<ModSpec> &mods, bool dedicated) { static const char *aa_names[] = {"start", "update", "delete"}; Json::Value server; server["action"] = aa_names[action]; server["port"] = port; if (g_settings->exists("server_address")) { server["address"] = g_settings->get("server_address"); } if (action != AA_DELETE) { bool strict_checking = g_settings->getBool("strict_protocol_version_checking"); server["name"] = g_settings->get("server_name"); server["description"] = g_settings->get("server_description"); server["version"] = g_version_string; server["proto_min"] = strict_checking ? LATEST_PROTOCOL_VERSION : SERVER_PROTOCOL_VERSION_MIN; server["proto_max"] = strict_checking ? LATEST_PROTOCOL_VERSION : SERVER_PROTOCOL_VERSION_MAX; server["url"] = g_settings->get("server_url"); server["creative"] = g_settings->getBool("creative_mode"); server["damage"] = g_settings->getBool("enable_damage"); server["password"] = g_settings->getBool("disallow_empty_password"); server["pvp"] = g_settings->getBool("enable_pvp"); server["uptime"] = (int) uptime; server["game_time"] = game_time; server["clients"] = (int) clients_names.size(); server["clients_max"] = g_settings->getU16("max_users"); server["clients_list"] = Json::Value(Json::arrayValue); for (const std::string &clients_name : clients_names) { server["clients_list"].append(clients_name); } if (!gameid.empty()) server["gameid"] = gameid; } if (action == AA_START) { server["dedicated"] = dedicated; server["rollback"] = g_settings->getBool("enable_rollback_recording"); server["mapgen"] = mg_name; server["privs"] = g_settings->get("default_privs"); server["can_see_far_names"] = g_settings->getS16("player_transfer_distance") <= 0; server["mods"] = Json::Value(Json::arrayValue); for (const ModSpec &mod : mods) { server["mods"].append(mod.name); } actionstream << "Announcing to " << g_settings->get("serverlist_url") << std::endl; } else if (action == AA_UPDATE) { if (lag) server["lag"] = lag; } HTTPFetchRequest fetch_request; fetch_request.url = g_settings->get("serverlist_url") + std::string("/announce"); fetch_request.post_fields["json"] = fastWriteJson(server); fetch_request.multipart = true; httpfetch_async(fetch_request); } #endif } // namespace ServerList
pgimeno/minetest
src/serverlist.cpp
C++
mit
7,651
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <iostream> #include "config.h" #include "content/mods.h" #include <json/json.h> #pragma once typedef Json::Value ServerListSpec; namespace ServerList { std::vector<ServerListSpec> getLocal(); std::vector<ServerListSpec> getOnline(); bool deleteEntry(const ServerListSpec &server); bool insert(const ServerListSpec &server); std::vector<ServerListSpec> deSerialize(const std::string &liststring); const std::string serialize(const std::vector<ServerListSpec> &serverlist); std::vector<ServerListSpec> deSerializeJson(const std::string &liststring); const std::string serializeJson(const std::vector<ServerListSpec> &serverlist); #if USE_CURL enum AnnounceAction {AA_START, AA_UPDATE, AA_DELETE}; void sendAnnounce(AnnounceAction, u16 port, const std::vector<std::string> &clients_names = std::vector<std::string>(), double uptime = 0, u32 game_time = 0, float lag = 0, const std::string &gameid = "", const std::string &mg_name = "", const std::vector<ModSpec> &mods = std::vector<ModSpec>(), bool dedicated = false); #endif } // namespace ServerList
pgimeno/minetest
src/serverlist.h
C++
mit
1,861
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "serverobject.h" #include <fstream> #include "inventory.h" #include "constants.h" // BS #include "log.h" ServerActiveObject::ServerActiveObject(ServerEnvironment *env, v3f pos): ActiveObject(0), m_env(env), m_base_position(pos) { } ServerActiveObject* ServerActiveObject::create(ActiveObjectType type, ServerEnvironment *env, u16 id, v3f pos, const std::string &data) { // Find factory function std::map<u16, Factory>::iterator n; n = m_types.find(type); if(n == m_types.end()) { // These are 0.3 entity types, return without error. if (ACTIVEOBJECT_TYPE_ITEM <= type && type <= ACTIVEOBJECT_TYPE_MOBV2) { return NULL; } // If factory is not found, just return. warningstream<<"ServerActiveObject: No factory for type=" <<type<<std::endl; return NULL; } Factory f = n->second; ServerActiveObject *object = (*f)(env, pos, data); return object; } void ServerActiveObject::registerType(u16 type, Factory f) { std::map<u16, Factory>::iterator n; n = m_types.find(type); if(n != m_types.end()) return; m_types[type] = f; } float ServerActiveObject::getMinimumSavedMovement() { return 2.0*BS; } ItemStack ServerActiveObject::getWieldedItem() const { const Inventory *inv = getInventory(); if(inv) { const InventoryList *list = inv->getList(getWieldList()); if(list && (getWieldIndex() < (s32)list->getSize())) return list->getItem(getWieldIndex()); } return ItemStack(); } bool ServerActiveObject::setWieldedItem(const ItemStack &item) { if(Inventory *inv = getInventory()) { if (InventoryList *list = inv->getList(getWieldList())) { list->changeItem(getWieldIndex(), item); return true; } } return false; }
pgimeno/minetest
src/serverobject.cpp
C++
mit
2,475
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <unordered_set> #include "irrlichttypes_bloated.h" #include "activeobject.h" #include "inventorymanager.h" #include "itemgroup.h" #include "util/container.h" /* Some planning ------------- * Server environment adds an active object, which gets the id 1 * The active object list is scanned for each client once in a while, and it finds out what objects have been added that are not known by the client yet. This scan is initiated by the Server class and the result ends up directly to the server. * A network packet is created with the info and sent to the client. * Environment converts objects to static data and static data to objects, based on how close players are to them. */ class ServerEnvironment; struct ItemStack; struct ToolCapabilities; struct ObjectProperties; struct PlayerHPChangeReason; class ServerActiveObject : public ActiveObject { public: /* NOTE: m_env can be NULL, but step() isn't called if it is. Prototypes are used that way. */ ServerActiveObject(ServerEnvironment *env, v3f pos); virtual ~ServerActiveObject() = default; virtual ActiveObjectType getSendType() const { return getType(); } // Called after id has been set and has been inserted in environment virtual void addedToEnvironment(u32 dtime_s){}; // Called before removing from environment virtual void removingFromEnvironment(){}; // Returns true if object's deletion is the job of the // environment virtual bool environmentDeletes() const { return true; } // Create a certain type of ServerActiveObject static ServerActiveObject* create(ActiveObjectType type, ServerEnvironment *env, u16 id, v3f pos, const std::string &data); /* Some simple getters/setters */ v3f getBasePosition() const { return m_base_position; } void setBasePosition(v3f pos){ m_base_position = pos; } ServerEnvironment* getEnv(){ return m_env; } /* Some more dynamic interface */ virtual void setPos(const v3f &pos) { setBasePosition(pos); } // continuous: if true, object does not stop immediately at pos virtual void moveTo(v3f pos, bool continuous) { setBasePosition(pos); } // If object has moved less than this and data has not changed, // saving to disk may be omitted virtual float getMinimumSavedMovement(); virtual std::string getDescription(){return "SAO";} /* Step object in time. Messages added to messages are sent to client over network. send_recommended: True at around 5-10 times a second, same for all objects. This is used to let objects send most of the data at the same time so that the data can be combined in a single packet. */ virtual void step(float dtime, bool send_recommended){} /* The return value of this is passed to the client-side object when it is created */ virtual std::string getClientInitializationData(u16 protocol_version){return "";} /* The return value of this is passed to the server-side object when it is created (converted from static to active - actually the data is the static form) */ virtual void getStaticData(std::string *result) const { assert(isStaticAllowed()); *result = ""; } /* Return false in here to never save and instead remove object on unload. getStaticData() will not be called in that case. */ virtual bool isStaticAllowed() const {return true;} // Returns tool wear virtual int punch(v3f dir, const ToolCapabilities *toolcap=NULL, ServerActiveObject *puncher=NULL, float time_from_last_punch=1000000) { return 0; } virtual void rightClick(ServerActiveObject *clicker) {} virtual void setHP(s32 hp, const PlayerHPChangeReason &reason) {} virtual u16 getHP() const { return 0; } virtual void setArmorGroups(const ItemGroupList &armor_groups) {} virtual const ItemGroupList &getArmorGroups() { static ItemGroupList rv; return rv; } virtual void setPhysicsOverride(float physics_override_speed, float physics_override_jump, float physics_override_gravity) {} virtual void setAnimation(v2f frames, float frame_speed, float frame_blend, bool frame_loop) {} virtual void getAnimation(v2f *frames, float *frame_speed, float *frame_blend, bool *frame_loop) {} virtual void setAnimationSpeed(float frame_speed) {} virtual void setBonePosition(const std::string &bone, v3f position, v3f rotation) {} virtual void getBonePosition(const std::string &bone, v3f *position, v3f *lotation) {} virtual void setAttachment(int parent_id, const std::string &bone, v3f position, v3f rotation) {} virtual void getAttachment(int *parent_id, std::string *bone, v3f *position, v3f *rotation) {} virtual void clearChildAttachments() {} virtual void clearParentAttachment() {} virtual void addAttachmentChild(int child_id) {} virtual void removeAttachmentChild(int child_id) {} virtual const std::unordered_set<int> &getAttachmentChildIds() { static std::unordered_set<int> rv; return rv; } virtual ServerActiveObject *getParent() const { return nullptr; } virtual ObjectProperties* accessObjectProperties() { return NULL; } virtual void notifyObjectPropertiesModified() {} // Inventory and wielded item virtual Inventory* getInventory() { return NULL; } virtual const Inventory* getInventory() const { return NULL; } virtual InventoryLocation getInventoryLocation() const { return InventoryLocation(); } virtual void setInventoryModified() {} virtual std::string getWieldList() const { return ""; } virtual int getWieldIndex() const { return 0; } virtual ItemStack getWieldedItem() const; virtual bool setWieldedItem(const ItemStack &item); inline void attachParticleSpawner(u32 id) { m_attached_particle_spawners.insert(id); } inline void detachParticleSpawner(u32 id) { m_attached_particle_spawners.erase(id); } /* Number of players which know about this object. Object won't be deleted until this is 0 to keep the id preserved for the right object. */ u16 m_known_by_count = 0; /* - Whether this object is to be removed when nobody knows about it anymore. - Removal is delayed to preserve the id for the time during which it could be confused to some other object by some client. - This is usually set to true by the step() method when the object wants to be deleted but can be set by anything else too. */ bool m_pending_removal = false; /* Same purpose as m_pending_removal but for deactivation. deactvation = save static data in block, remove active object If this is set alongside with m_pending_removal, removal takes priority. */ bool m_pending_deactivation = false; /* A getter that unifies the above to answer the question: "Can the environment still interact with this object?" */ inline bool isGone() const { return m_pending_removal || m_pending_deactivation; } /* Whether the object's static data has been stored to a block */ bool m_static_exists = false; /* The block from which the object was loaded from, and in which a copy of the static data resides. */ v3s16 m_static_block = v3s16(1337,1337,1337); /* Queue of messages to be sent to the client */ std::queue<ActiveObjectMessage> m_messages_out; protected: virtual void onAttach(int parent_id) {} virtual void onDetach(int parent_id) {} // Used for creating objects based on type typedef ServerActiveObject* (*Factory) (ServerEnvironment *env, v3f pos, const std::string &data); static void registerType(u16 type, Factory f); ServerEnvironment *m_env; v3f m_base_position; std::unordered_set<u32> m_attached_particle_spawners; private: // Used for creating objects based on type static std::map<u16, Factory> m_types; };
pgimeno/minetest
src/serverobject.h
C++
mit
8,404
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "settings.h" #include "irrlichttypes_bloated.h" #include "exceptions.h" #include "threading/mutex_auto_lock.h" #include "util/strfnd.h" #include <iostream> #include <fstream> #include <sstream> #include "debug.h" #include "log.h" #include "util/serialize.h" #include "filesys.h" #include "noise.h" #include <cctype> #include <algorithm> static Settings main_settings; Settings *g_settings = &main_settings; std::string g_settings_path; Settings::~Settings() { clear(); } Settings & Settings::operator += (const Settings &other) { update(other); return *this; } Settings & Settings::operator = (const Settings &other) { if (&other == this) return *this; MutexAutoLock lock(m_mutex); MutexAutoLock lock2(other.m_mutex); clearNoLock(); updateNoLock(other); return *this; } bool Settings::checkNameValid(const std::string &name) { bool valid = name.find_first_of("=\"{}#") == std::string::npos; if (valid) valid = trim(name) == name; if (!valid) { errorstream << "Invalid setting name \"" << name << "\"" << std::endl; return false; } return true; } bool Settings::checkValueValid(const std::string &value) { if (value.substr(0, 3) == "\"\"\"" || value.find("\n\"\"\"") != std::string::npos) { errorstream << "Invalid character sequence '\"\"\"' found in" " setting value!" << std::endl; return false; } return true; } std::string Settings::getMultiline(std::istream &is, size_t *num_lines) { size_t lines = 1; std::string value; std::string line; while (is.good()) { lines++; std::getline(is, line); if (line == "\"\"\"") break; value += line; value.push_back('\n'); } size_t len = value.size(); if (len) value.erase(len - 1); if (num_lines) *num_lines = lines; return value; } bool Settings::readConfigFile(const char *filename) { std::ifstream is(filename); if (!is.good()) return false; return parseConfigLines(is, ""); } bool Settings::parseConfigLines(std::istream &is, const std::string &end) { MutexAutoLock lock(m_mutex); std::string line, name, value; while (is.good()) { std::getline(is, line); SettingsParseEvent event = parseConfigObject(line, end, name, value); switch (event) { case SPE_NONE: case SPE_INVALID: case SPE_COMMENT: break; case SPE_KVPAIR: m_settings[name] = SettingsEntry(value); break; case SPE_END: return true; case SPE_GROUP: { Settings *group = new Settings; if (!group->parseConfigLines(is, "}")) { delete group; return false; } m_settings[name] = SettingsEntry(group); break; } case SPE_MULTILINE: m_settings[name] = SettingsEntry(getMultiline(is)); break; } } return end.empty(); } void Settings::writeLines(std::ostream &os, u32 tab_depth) const { MutexAutoLock lock(m_mutex); for (const auto &setting_it : m_settings) printEntry(os, setting_it.first, setting_it.second, tab_depth); } void Settings::printEntry(std::ostream &os, const std::string &name, const SettingsEntry &entry, u32 tab_depth) { for (u32 i = 0; i != tab_depth; i++) os << "\t"; if (entry.is_group) { os << name << " = {\n"; entry.group->writeLines(os, tab_depth + 1); for (u32 i = 0; i != tab_depth; i++) os << "\t"; os << "}\n"; } else { os << name << " = "; if (entry.value.find('\n') != std::string::npos) os << "\"\"\"\n" << entry.value << "\n\"\"\"\n"; else os << entry.value << "\n"; } } bool Settings::updateConfigObject(std::istream &is, std::ostream &os, const std::string &end, u32 tab_depth) { SettingEntries::const_iterator it; std::set<std::string> present_entries; std::string line, name, value; bool was_modified = false; bool end_found = false; // Add any settings that exist in the config file with the current value // in the object if existing while (is.good() && !end_found) { std::getline(is, line); SettingsParseEvent event = parseConfigObject(line, end, name, value); switch (event) { case SPE_END: os << line << (is.eof() ? "" : "\n"); end_found = true; break; case SPE_MULTILINE: value = getMultiline(is); /* FALLTHROUGH */ case SPE_KVPAIR: it = m_settings.find(name); if (it != m_settings.end() && (it->second.is_group || it->second.value != value)) { printEntry(os, name, it->second, tab_depth); was_modified = true; } else if (it == m_settings.end()) { // Remove by skipping was_modified = true; break; } else { os << line << "\n"; if (event == SPE_MULTILINE) os << value << "\n\"\"\"\n"; } present_entries.insert(name); break; case SPE_GROUP: it = m_settings.find(name); if (it != m_settings.end() && it->second.is_group) { os << line << "\n"; sanity_check(it->second.group != NULL); was_modified |= it->second.group->updateConfigObject(is, os, "}", tab_depth + 1); } else if (it == m_settings.end()) { // Remove by skipping was_modified = true; Settings removed_group; // Move 'is' to group end std::stringstream ss; removed_group.updateConfigObject(is, ss, "}", tab_depth + 1); break; } else { printEntry(os, name, it->second, tab_depth); was_modified = true; } present_entries.insert(name); break; default: os << line << (is.eof() ? "" : "\n"); break; } } // Add any settings in the object that don't exist in the config file yet for (it = m_settings.begin(); it != m_settings.end(); ++it) { if (present_entries.find(it->first) != present_entries.end()) continue; printEntry(os, it->first, it->second, tab_depth); was_modified = true; } return was_modified; } bool Settings::updateConfigFile(const char *filename) { MutexAutoLock lock(m_mutex); std::ifstream is(filename); std::ostringstream os(std::ios_base::binary); bool was_modified = updateConfigObject(is, os, ""); is.close(); if (!was_modified) return true; if (!fs::safeWriteToFile(filename, os.str())) { errorstream << "Error writing configuration file: \"" << filename << "\"" << std::endl; return false; } return true; } bool Settings::parseCommandLine(int argc, char *argv[], std::map<std::string, ValueSpec> &allowed_options) { int nonopt_index = 0; for (int i = 1; i < argc; i++) { std::string arg_name = argv[i]; if (arg_name.substr(0, 2) != "--") { // If option doesn't start with -, read it in as nonoptX if (arg_name[0] != '-'){ std::string name = "nonopt"; name += itos(nonopt_index); set(name, arg_name); nonopt_index++; continue; } errorstream << "Invalid command-line parameter \"" << arg_name << "\": --<option> expected." << std::endl; return false; } std::string name = arg_name.substr(2); std::map<std::string, ValueSpec>::iterator n; n = allowed_options.find(name); if (n == allowed_options.end()) { errorstream << "Unknown command-line parameter \"" << arg_name << "\"" << std::endl; return false; } ValueType type = n->second.type; std::string value; if (type == VALUETYPE_FLAG) { value = "true"; } else { if ((i + 1) >= argc) { errorstream << "Invalid command-line parameter \"" << name << "\": missing value" << std::endl; return false; } value = argv[++i]; } set(name, value); } return true; } /*********** * Getters * ***********/ const SettingsEntry &Settings::getEntry(const std::string &name) const { MutexAutoLock lock(m_mutex); SettingEntries::const_iterator n; if ((n = m_settings.find(name)) == m_settings.end()) { if ((n = m_defaults.find(name)) == m_defaults.end()) throw SettingNotFoundException("Setting [" + name + "] not found."); } return n->second; } const SettingsEntry &Settings::getEntryDefault(const std::string &name) const { MutexAutoLock lock(m_mutex); SettingEntries::const_iterator n; if ((n = m_defaults.find(name)) == m_defaults.end()) { throw SettingNotFoundException("Setting [" + name + "] not found."); } return n->second; } Settings *Settings::getGroup(const std::string &name) const { const SettingsEntry &entry = getEntry(name); if (!entry.is_group) throw SettingNotFoundException("Setting [" + name + "] is not a group."); return entry.group; } const std::string &Settings::get(const std::string &name) const { const SettingsEntry &entry = getEntry(name); if (entry.is_group) throw SettingNotFoundException("Setting [" + name + "] is a group."); return entry.value; } const std::string &Settings::getDefault(const std::string &name) const { const SettingsEntry &entry = getEntryDefault(name); if (entry.is_group) throw SettingNotFoundException("Setting [" + name + "] is a group."); return entry.value; } bool Settings::getBool(const std::string &name) const { return is_yes(get(name)); } u16 Settings::getU16(const std::string &name) const { return stoi(get(name), 0, 65535); } s16 Settings::getS16(const std::string &name) const { return stoi(get(name), -32768, 32767); } u32 Settings::getU32(const std::string &name) const { return (u32) stoi(get(name)); } s32 Settings::getS32(const std::string &name) const { return stoi(get(name)); } float Settings::getFloat(const std::string &name) const { return stof(get(name)); } u64 Settings::getU64(const std::string &name) const { u64 value = 0; std::string s = get(name); std::istringstream ss(s); ss >> value; return value; } v2f Settings::getV2F(const std::string &name) const { v2f value; Strfnd f(get(name)); f.next("("); value.X = stof(f.next(",")); value.Y = stof(f.next(")")); return value; } v3f Settings::getV3F(const std::string &name) const { v3f value; Strfnd f(get(name)); f.next("("); value.X = stof(f.next(",")); value.Y = stof(f.next(",")); value.Z = stof(f.next(")")); return value; } u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc, u32 *flagmask) const { std::string val = get(name); return std::isdigit(val[0]) ? stoi(val) : readFlagString(val, flagdesc, flagmask); } // N.B. if getStruct() is used to read a non-POD aggregate type, // the behavior is undefined. bool Settings::getStruct(const std::string &name, const std::string &format, void *out, size_t olen) const { std::string valstr; try { valstr = get(name); } catch (SettingNotFoundException &e) { return false; } if (!deSerializeStringToStruct(valstr, format, out, olen)) return false; return true; } bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const { return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np); } bool Settings::getNoiseParamsFromValue(const std::string &name, NoiseParams &np) const { std::string value; if (!getNoEx(name, value)) return false; Strfnd f(value); np.offset = stof(f.next(",")); np.scale = stof(f.next(",")); f.next("("); np.spread.X = stof(f.next(",")); np.spread.Y = stof(f.next(",")); np.spread.Z = stof(f.next(")")); f.next(","); np.seed = stoi(f.next(",")); np.octaves = stoi(f.next(",")); np.persist = stof(f.next(",")); std::string optional_params = f.next(""); if (!optional_params.empty()) np.lacunarity = stof(optional_params); return true; } bool Settings::getNoiseParamsFromGroup(const std::string &name, NoiseParams &np) const { Settings *group = NULL; if (!getGroupNoEx(name, group)) return false; group->getFloatNoEx("offset", np.offset); group->getFloatNoEx("scale", np.scale); group->getV3FNoEx("spread", np.spread); group->getS32NoEx("seed", np.seed); group->getU16NoEx("octaves", np.octaves); group->getFloatNoEx("persistence", np.persist); group->getFloatNoEx("lacunarity", np.lacunarity); np.flags = 0; if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams)) np.flags = NOISE_FLAG_DEFAULTS; return true; } bool Settings::exists(const std::string &name) const { MutexAutoLock lock(m_mutex); return (m_settings.find(name) != m_settings.end() || m_defaults.find(name) != m_defaults.end()); } std::vector<std::string> Settings::getNames() const { std::vector<std::string> names; for (const auto &settings_it : m_settings) { names.push_back(settings_it.first); } return names; } /*************************************** * Getters that don't throw exceptions * ***************************************/ bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const { try { val = getEntry(name); return true; } catch (SettingNotFoundException &e) { return false; } } bool Settings::getEntryDefaultNoEx(const std::string &name, SettingsEntry &val) const { try { val = getEntryDefault(name); return true; } catch (SettingNotFoundException &e) { return false; } } bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const { try { val = getGroup(name); return true; } catch (SettingNotFoundException &e) { return false; } } bool Settings::getNoEx(const std::string &name, std::string &val) const { try { val = get(name); return true; } catch (SettingNotFoundException &e) { return false; } } bool Settings::getDefaultNoEx(const std::string &name, std::string &val) const { try { val = getDefault(name); return true; } catch (SettingNotFoundException &e) { return false; } } bool Settings::getFlag(const std::string &name) const { try { return getBool(name); } catch(SettingNotFoundException &e) { return false; } } bool Settings::getFloatNoEx(const std::string &name, float &val) const { try { val = getFloat(name); return true; } catch (SettingNotFoundException &e) { return false; } } bool Settings::getU16NoEx(const std::string &name, u16 &val) const { try { val = getU16(name); return true; } catch (SettingNotFoundException &e) { return false; } } bool Settings::getS16NoEx(const std::string &name, s16 &val) const { try { val = getS16(name); return true; } catch (SettingNotFoundException &e) { return false; } } bool Settings::getS32NoEx(const std::string &name, s32 &val) const { try { val = getS32(name); return true; } catch (SettingNotFoundException &e) { return false; } } bool Settings::getU64NoEx(const std::string &name, u64 &val) const { try { val = getU64(name); return true; } catch (SettingNotFoundException &e) { return false; } } bool Settings::getV2FNoEx(const std::string &name, v2f &val) const { try { val = getV2F(name); return true; } catch (SettingNotFoundException &e) { return false; } } bool Settings::getV3FNoEx(const std::string &name, v3f &val) const { try { val = getV3F(name); return true; } catch (SettingNotFoundException &e) { return false; } } // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus, // val must be initialized before using getFlagStrNoEx(). The intention of // this is to simplify modifying a flags field from a default value. bool Settings::getFlagStrNoEx(const std::string &name, u32 &val, FlagDesc *flagdesc) const { try { u32 flags, flagmask; flags = getFlagStr(name, flagdesc, &flagmask); val &= ~flagmask; val |= flags; return true; } catch (SettingNotFoundException &e) { return false; } } /*********** * Setters * ***********/ bool Settings::setEntry(const std::string &name, const void *data, bool set_group, bool set_default) { Settings *old_group = NULL; if (!checkNameValid(name)) return false; if (!set_group && !checkValueValid(*(const std::string *)data)) return false; { MutexAutoLock lock(m_mutex); SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name]; old_group = entry.group; entry.value = set_group ? "" : *(const std::string *)data; entry.group = set_group ? *(Settings **)data : NULL; entry.is_group = set_group; } delete old_group; return true; } bool Settings::set(const std::string &name, const std::string &value) { if (!setEntry(name, &value, false, false)) return false; doCallbacks(name); return true; } bool Settings::setDefault(const std::string &name, const std::string &value) { return setEntry(name, &value, false, true); } bool Settings::setGroup(const std::string &name, Settings *group) { return setEntry(name, &group, true, false); } bool Settings::setGroupDefault(const std::string &name, Settings *group) { return setEntry(name, &group, true, true); } bool Settings::setBool(const std::string &name, bool value) { return set(name, value ? "true" : "false"); } bool Settings::setS16(const std::string &name, s16 value) { return set(name, itos(value)); } bool Settings::setU16(const std::string &name, u16 value) { return set(name, itos(value)); } bool Settings::setS32(const std::string &name, s32 value) { return set(name, itos(value)); } bool Settings::setU64(const std::string &name, u64 value) { std::ostringstream os; os << value; return set(name, os.str()); } bool Settings::setFloat(const std::string &name, float value) { return set(name, ftos(value)); } bool Settings::setV2F(const std::string &name, v2f value) { std::ostringstream os; os << "(" << value.X << "," << value.Y << ")"; return set(name, os.str()); } bool Settings::setV3F(const std::string &name, v3f value) { std::ostringstream os; os << "(" << value.X << "," << value.Y << "," << value.Z << ")"; return set(name, os.str()); } bool Settings::setFlagStr(const std::string &name, u32 flags, const FlagDesc *flagdesc, u32 flagmask) { return set(name, writeFlagString(flags, flagdesc, flagmask)); } bool Settings::setStruct(const std::string &name, const std::string &format, void *value) { std::string structstr; if (!serializeStructToString(&structstr, format, value)) return false; return set(name, structstr); } bool Settings::setNoiseParams(const std::string &name, const NoiseParams &np, bool set_default) { Settings *group = new Settings; group->setFloat("offset", np.offset); group->setFloat("scale", np.scale); group->setV3F("spread", np.spread); group->setS32("seed", np.seed); group->setU16("octaves", np.octaves); group->setFloat("persistence", np.persist); group->setFloat("lacunarity", np.lacunarity); group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags); return setEntry(name, &group, true, set_default); } bool Settings::remove(const std::string &name) { MutexAutoLock lock(m_mutex); SettingEntries::iterator it = m_settings.find(name); if (it != m_settings.end()) { delete it->second.group; m_settings.erase(it); doCallbacks(name); return true; } return false; } void Settings::clear() { MutexAutoLock lock(m_mutex); clearNoLock(); } void Settings::clearDefaults() { MutexAutoLock lock(m_mutex); clearDefaultsNoLock(); } void Settings::updateValue(const Settings &other, const std::string &name) { if (&other == this) return; MutexAutoLock lock(m_mutex); try { m_settings[name] = other.get(name); } catch (SettingNotFoundException &e) { } } void Settings::update(const Settings &other) { if (&other == this) return; MutexAutoLock lock(m_mutex); MutexAutoLock lock2(other.m_mutex); updateNoLock(other); } SettingsParseEvent Settings::parseConfigObject(const std::string &line, const std::string &end, std::string &name, std::string &value) { std::string trimmed_line = trim(line); if (trimmed_line.empty()) return SPE_NONE; if (trimmed_line[0] == '#') return SPE_COMMENT; if (trimmed_line == end) return SPE_END; size_t pos = trimmed_line.find('='); if (pos == std::string::npos) return SPE_INVALID; name = trim(trimmed_line.substr(0, pos)); value = trim(trimmed_line.substr(pos + 1)); if (value == "{") return SPE_GROUP; if (value == "\"\"\"") return SPE_MULTILINE; return SPE_KVPAIR; } void Settings::updateNoLock(const Settings &other) { m_settings.insert(other.m_settings.begin(), other.m_settings.end()); m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end()); } void Settings::clearNoLock() { for (SettingEntries::const_iterator it = m_settings.begin(); it != m_settings.end(); ++it) delete it->second.group; m_settings.clear(); clearDefaultsNoLock(); } void Settings::clearDefaultsNoLock() { for (SettingEntries::const_iterator it = m_defaults.begin(); it != m_defaults.end(); ++it) delete it->second.group; m_defaults.clear(); } void Settings::registerChangedCallback(const std::string &name, SettingsChangedCallback cbf, void *userdata) { MutexAutoLock lock(m_callback_mutex); m_callbacks[name].emplace_back(cbf, userdata); } void Settings::deregisterChangedCallback(const std::string &name, SettingsChangedCallback cbf, void *userdata) { MutexAutoLock lock(m_callback_mutex); SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name); if (it_cbks != m_callbacks.end()) { SettingsCallbackList &cbks = it_cbks->second; SettingsCallbackList::iterator position = std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata)); if (position != cbks.end()) cbks.erase(position); } } void Settings::doCallbacks(const std::string &name) const { MutexAutoLock lock(m_callback_mutex); SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name); if (it_cbks != m_callbacks.end()) { SettingsCallbackList::const_iterator it; for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it) (it->first)(name, it->second); } }
pgimeno/minetest
src/settings.cpp
C++
mit
22,183
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes_bloated.h" #include "util/string.h" #include <string> #include <list> #include <set> #include <mutex> class Settings; struct NoiseParams; // Global objects extern Settings *g_settings; extern std::string g_settings_path; // Type for a settings changed callback function typedef void (*SettingsChangedCallback)(const std::string &name, void *data); typedef std::vector< std::pair< SettingsChangedCallback, void * > > SettingsCallbackList; typedef std::unordered_map<std::string, SettingsCallbackList> SettingsCallbackMap; enum ValueType { VALUETYPE_STRING, VALUETYPE_FLAG // Doesn't take any arguments }; enum SettingsParseEvent { SPE_NONE, SPE_INVALID, SPE_COMMENT, SPE_KVPAIR, SPE_END, SPE_GROUP, SPE_MULTILINE, }; struct ValueSpec { ValueSpec(ValueType a_type, const char *a_help=NULL) { type = a_type; help = a_help; } ValueType type; const char *help; }; struct SettingsEntry { SettingsEntry() = default; SettingsEntry(const std::string &value_) : value(value_) {} SettingsEntry(Settings *group_) : group(group_), is_group(true) {} std::string value = ""; Settings *group = nullptr; bool is_group = false; }; typedef std::unordered_map<std::string, SettingsEntry> SettingEntries; class Settings { public: Settings() = default; ~Settings(); Settings & operator += (const Settings &other); Settings & operator = (const Settings &other); /*********************** * Reading and writing * ***********************/ // Read configuration file. Returns success. bool readConfigFile(const char *filename); //Updates configuration file. Returns success. bool updateConfigFile(const char *filename); // NOTE: Types of allowed_options are ignored. Returns success. bool parseCommandLine(int argc, char *argv[], std::map<std::string, ValueSpec> &allowed_options); bool parseConfigLines(std::istream &is, const std::string &end = ""); void writeLines(std::ostream &os, u32 tab_depth=0) const; SettingsParseEvent parseConfigObject(const std::string &line, const std::string &end, std::string &name, std::string &value); bool updateConfigObject(std::istream &is, std::ostream &os, const std::string &end, u32 tab_depth=0); static bool checkNameValid(const std::string &name); static bool checkValueValid(const std::string &value); static std::string getMultiline(std::istream &is, size_t *num_lines=NULL); static void printEntry(std::ostream &os, const std::string &name, const SettingsEntry &entry, u32 tab_depth=0); /*********** * Getters * ***********/ const SettingsEntry &getEntry(const std::string &name) const; const SettingsEntry &getEntryDefault(const std::string &name) const; Settings *getGroup(const std::string &name) const; const std::string &get(const std::string &name) const; const std::string &getDefault(const std::string &name) const; bool getBool(const std::string &name) const; u16 getU16(const std::string &name) const; s16 getS16(const std::string &name) const; u32 getU32(const std::string &name) const; s32 getS32(const std::string &name) const; u64 getU64(const std::string &name) const; float getFloat(const std::string &name) const; v2f getV2F(const std::string &name) const; v3f getV3F(const std::string &name) const; u32 getFlagStr(const std::string &name, const FlagDesc *flagdesc, u32 *flagmask) const; // N.B. if getStruct() is used to read a non-POD aggregate type, // the behavior is undefined. bool getStruct(const std::string &name, const std::string &format, void *out, size_t olen) const; bool getNoiseParams(const std::string &name, NoiseParams &np) const; bool getNoiseParamsFromValue(const std::string &name, NoiseParams &np) const; bool getNoiseParamsFromGroup(const std::string &name, NoiseParams &np) const; // return all keys used std::vector<std::string> getNames() const; bool exists(const std::string &name) const; /*************************************** * Getters that don't throw exceptions * ***************************************/ bool getEntryNoEx(const std::string &name, SettingsEntry &val) const; bool getEntryDefaultNoEx(const std::string &name, SettingsEntry &val) const; bool getGroupNoEx(const std::string &name, Settings *&val) const; bool getNoEx(const std::string &name, std::string &val) const; bool getDefaultNoEx(const std::string &name, std::string &val) const; bool getFlag(const std::string &name) const; bool getU16NoEx(const std::string &name, u16 &val) const; bool getS16NoEx(const std::string &name, s16 &val) const; bool getS32NoEx(const std::string &name, s32 &val) const; bool getU64NoEx(const std::string &name, u64 &val) const; bool getFloatNoEx(const std::string &name, float &val) const; bool getV2FNoEx(const std::string &name, v2f &val) const; bool getV3FNoEx(const std::string &name, v3f &val) const; // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus, // val must be initialized before using getFlagStrNoEx(). The intention of // this is to simplify modifying a flags field from a default value. bool getFlagStrNoEx(const std::string &name, u32 &val, FlagDesc *flagdesc) const; /*********** * Setters * ***********/ // N.B. Groups not allocated with new must be set to NULL in the settings // tree before object destruction. bool setEntry(const std::string &name, const void *entry, bool set_group, bool set_default); bool set(const std::string &name, const std::string &value); bool setDefault(const std::string &name, const std::string &value); bool setGroup(const std::string &name, Settings *group); bool setGroupDefault(const std::string &name, Settings *group); bool setBool(const std::string &name, bool value); bool setS16(const std::string &name, s16 value); bool setU16(const std::string &name, u16 value); bool setS32(const std::string &name, s32 value); bool setU64(const std::string &name, u64 value); bool setFloat(const std::string &name, float value); bool setV2F(const std::string &name, v2f value); bool setV3F(const std::string &name, v3f value); bool setFlagStr(const std::string &name, u32 flags, const FlagDesc *flagdesc, u32 flagmask); bool setNoiseParams(const std::string &name, const NoiseParams &np, bool set_default=false); // N.B. if setStruct() is used to write a non-POD aggregate type, // the behavior is undefined. bool setStruct(const std::string &name, const std::string &format, void *value); // remove a setting bool remove(const std::string &name); void clear(); void clearDefaults(); void updateValue(const Settings &other, const std::string &name); void update(const Settings &other); void registerChangedCallback(const std::string &name, SettingsChangedCallback cbf, void *userdata = NULL); void deregisterChangedCallback(const std::string &name, SettingsChangedCallback cbf, void *userdata = NULL); private: void updateNoLock(const Settings &other); void clearNoLock(); void clearDefaultsNoLock(); void doCallbacks(const std::string &name) const; SettingEntries m_settings; SettingEntries m_defaults; SettingsCallbackMap m_callbacks; mutable std::mutex m_callback_mutex; // All methods that access m_settings/m_defaults directly should lock this. mutable std::mutex m_mutex; };
pgimeno/minetest
src/settings.h
C++
mit
8,069
// This file is automatically generated // It conatins a bunch of fake gettext calls, to tell xgettext about the strings in config files // To update it, refer to the bottom of builtin/mainmenu/dlg_settings_advanced.lua fake_function() { gettext("Controls"); gettext("Build inside player"); gettext("If enabled, you can place blocks at the position (feet + eye level) where you stand.\nThis is helpful when working with nodeboxes in small areas."); gettext("Flying"); gettext("Player is able to fly without being affected by gravity.\nThis requires the \"fly\" privilege on the server."); gettext("Pitch move mode"); gettext("If enabled, makes move directions relative to the player's pitch when flying or swimming."); gettext("Fast movement"); gettext("Fast movement (via the \"special\" key).\nThis requires the \"fast\" privilege on the server."); gettext("Noclip"); gettext("If enabled together with fly mode, player is able to fly through solid nodes.\nThis requires the \"noclip\" privilege on the server."); gettext("Cinematic mode"); gettext("Smooths camera when looking around. Also called look or mouse smoothing.\nUseful for recording videos."); gettext("Camera smoothing"); gettext("Smooths rotation of camera. 0 to disable."); gettext("Camera smoothing in cinematic mode"); gettext("Smooths rotation of camera in cinematic mode. 0 to disable."); gettext("Invert mouse"); gettext("Invert vertical mouse movement."); gettext("Mouse sensitivity"); gettext("Mouse sensitivity multiplier."); gettext("Special key for climbing/descending"); gettext("If enabled, \"special\" key instead of \"sneak\" key is used for climbing down and\ndescending."); gettext("Double tap jump for fly"); gettext("Double-tapping the jump key toggles fly mode."); gettext("Always fly and fast"); gettext("If disabled, \"special\" key is used to fly fast if both fly and fast mode are\nenabled."); gettext("Rightclick repetition interval"); gettext("The time in seconds it takes between repeated right clicks when holding the right\nmouse button."); gettext("Automatic jumping"); gettext("Automatically jump up single-node obstacles."); gettext("Safe digging and placing"); gettext("Prevent digging and placing from repeating when holding the mouse buttons.\nEnable this when you dig or place too often by accident."); gettext("Random input"); gettext("Enable random user input (only used for testing)."); gettext("Continuous forward"); gettext("Continuous forward movement, toggled by autoforward key.\nPress the autoforward key again or the backwards movement to disable."); gettext("Touch screen threshold"); gettext("The length in pixels it takes for touch screen interaction to start."); gettext("Fixed virtual joystick"); gettext("(Android) Fixes the position of virtual joystick.\nIf disabled, virtual joystick will center to first-touch's position."); gettext("Virtual joystick triggers aux button"); gettext("(Android) Use virtual joystick to trigger \"aux\" button.\nIf enabled, virtual joystick will also tap \"aux\" button when out of main circle."); gettext("Enable joysticks"); gettext("Enable joysticks"); gettext("Joystick ID"); gettext("The identifier of the joystick to use"); gettext("Joystick type"); gettext("The type of joystick"); gettext("Joystick button repetition interval"); gettext("The time in seconds it takes between repeated events\nwhen holding down a joystick button combination."); gettext("Joystick frustum sensitivity"); gettext("The sensitivity of the joystick axes for moving the\ningame view frustum around."); gettext("Forward key"); gettext("Key for moving the player forward.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Backward key"); gettext("Key for moving the player backward.\nWill also disable autoforward, when active.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Left key"); gettext("Key for moving the player left.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Right key"); gettext("Key for moving the player right.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Jump key"); gettext("Key for jumping.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Sneak key"); gettext("Key for sneaking.\nAlso used for climbing down and descending in water if aux1_descends is disabled.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Inventory key"); gettext("Key for opening the inventory.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Special key"); gettext("Key for moving fast in fast mode.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Chat key"); gettext("Key for opening the chat window.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Command key"); gettext("Key for opening the chat window to type commands.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Command key"); gettext("Key for opening the chat window to type local commands.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Range select key"); gettext("Key for toggling unlimited view range.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Fly key"); gettext("Key for toggling flying.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Pitch move key"); gettext("Key for toggling pitch move mode.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Fast key"); gettext("Key for toggling fast mode.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Noclip key"); gettext("Key for toggling noclip mode.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar next key"); gettext("Key for selecting the next item in the hotbar.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar previous key"); gettext("Key for selecting the previous item in the hotbar.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Mute key"); gettext("Key for muting the game.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Inc. volume key"); gettext("Key for increasing the volume.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Dec. volume key"); gettext("Key for decreasing the volume.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Automatic forward key"); gettext("Key for toggling autoforward.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Cinematic mode key"); gettext("Key for toggling cinematic mode.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Minimap key"); gettext("Key for toggling display of minimap.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Screenshot"); gettext("Key for taking screenshots.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Drop item key"); gettext("Key for dropping the currently selected item.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("View zoom key"); gettext("Key to use view zoom when possible.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 1 key"); gettext("Key for selecting the first hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 2 key"); gettext("Key for selecting the second hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 3 key"); gettext("Key for selecting the third hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 4 key"); gettext("Key for selecting the fourth hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 5 key"); gettext("Key for selecting the fifth hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 6 key"); gettext("Key for selecting the sixth hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 7 key"); gettext("Key for selecting the seventh hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 8 key"); gettext("Key for selecting the eighth hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 9 key"); gettext("Key for selecting the ninth hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 10 key"); gettext("Key for selecting the tenth hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 11 key"); gettext("Key for selecting the 11th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 12 key"); gettext("Key for selecting the 12th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 13 key"); gettext("Key for selecting the 13th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 14 key"); gettext("Key for selecting the 14th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 15 key"); gettext("Key for selecting the 15th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 16 key"); gettext("Key for selecting the 16th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 17 key"); gettext("Key for selecting the 17th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 18 key"); gettext("Key for selecting the 18th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 19 key"); gettext("Key for selecting the 19th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 20 key"); gettext("Key for selecting the 20th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 21 key"); gettext("Key for selecting the 21st hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 22 key"); gettext("Key for selecting the 22nd hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 23 key"); gettext("Key for selecting the 23rd hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 24 key"); gettext("Key for selecting the 24th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 25 key"); gettext("Key for selecting the 25th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 26 key"); gettext("Key for selecting the 26th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 27 key"); gettext("Key for selecting the 27th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 28 key"); gettext("Key for selecting the 28th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 29 key"); gettext("Key for selecting the 29th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 30 key"); gettext("Key for selecting the 30th hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 31 key"); gettext("Key for selecting the 31st hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Hotbar slot 32 key"); gettext("Key for selecting the 32nd hotbar slot.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("HUD toggle key"); gettext("Key for toggling the display of the HUD.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Chat toggle key"); gettext("Key for toggling the display of chat.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Large chat console key"); gettext("Key for toggling the display of the large chat console.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Fog toggle key"); gettext("Key for toggling the display of fog.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Camera update toggle key"); gettext("Key for toggling the camera update. Only used for development\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Debug info toggle key"); gettext("Key for toggling the display of debug info.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Profiler toggle key"); gettext("Key for toggling the display of the profiler. Used for development.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Toggle camera mode key"); gettext("Key for switching between first- and third-person camera.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("View range increase key"); gettext("Key for increasing the viewing range.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("View range decrease key"); gettext("Key for decreasing the viewing range.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Graphics"); gettext("In-Game"); gettext("Basic"); gettext("VBO"); gettext("Enable VBO"); gettext("Fog"); gettext("Whether to fog out the end of the visible area."); gettext("Leaves style"); gettext("Leaves style:\n- Fancy: all faces visible\n- Simple: only outer faces, if defined special_tiles are used\n- Opaque: disable transparency"); gettext("Connect glass"); gettext("Connects glass if supported by node."); gettext("Smooth lighting"); gettext("Enable smooth lighting with simple ambient occlusion.\nDisable for speed or for different looks."); gettext("Clouds"); gettext("Clouds are a client side effect."); gettext("3D clouds"); gettext("Use 3D cloud look instead of flat."); gettext("Node highlighting"); gettext("Method used to highlight selected object."); gettext("Digging particles"); gettext("Adds particles when digging a node."); gettext("Filtering"); gettext("Mipmapping"); gettext("Use mip mapping to scale textures. May slightly increase performance,\nespecially when using a high resolution texture pack.\nGamma correct downscaling is not supported."); gettext("Anisotropic filtering"); gettext("Use anisotropic filtering when viewing at textures from an angle."); gettext("Bilinear filtering"); gettext("Use bilinear filtering when scaling textures."); gettext("Trilinear filtering"); gettext("Use trilinear filtering when scaling textures."); gettext("Clean transparent textures"); gettext("Filtered textures can blend RGB values with fully-transparent neighbors,\nwhich PNG optimizers usually discard, sometimes resulting in a dark or\nlight edge to transparent textures. Apply this filter to clean that up\nat texture load time."); gettext("Minimum texture size"); gettext("When using bilinear/trilinear/anisotropic filters, low-resolution textures\ncan be blurred, so automatically upscale them with nearest-neighbor\ninterpolation to preserve crisp pixels. This sets the minimum texture size\nfor the upscaled textures; higher values look sharper, but require more\nmemory. Powers of 2 are recommended. Setting this higher than 1 may not\nhave a visible effect unless bilinear/trilinear/anisotropic filtering is\nenabled.\nThis is also used as the base node texture size for world-aligned\ntexture autoscaling."); gettext("FSAA"); gettext("Experimental option, might cause visible spaces between blocks\nwhen set to higher number than 0."); gettext("Undersampling"); gettext("Undersampling is similar to using lower screen resolution, but it applies\nto the game world only, keeping the GUI intact.\nIt should give significant performance boost at the cost of less detailed image."); gettext("Shaders"); gettext("Shaders"); gettext("Shaders allow advanced visual effects and may increase performance on some video\ncards.\nThis only works with the OpenGL video backend."); gettext("Shader path"); gettext("Path to shader directory. If no path is defined, default location will be used."); gettext("Tone Mapping"); gettext("Filmic tone mapping"); gettext("Enables filmic tone mapping"); gettext("Bumpmapping"); gettext("Bumpmapping"); gettext("Enables bumpmapping for textures. Normalmaps need to be supplied by the texture pack\nor need to be auto-generated.\nRequires shaders to be enabled."); gettext("Generate normalmaps"); gettext("Enables on the fly normalmap generation (Emboss effect).\nRequires bumpmapping to be enabled."); gettext("Normalmaps strength"); gettext("Strength of generated normalmaps."); gettext("Normalmaps sampling"); gettext("Defines sampling step of texture.\nA higher value results in smoother normal maps."); gettext("Parallax Occlusion"); gettext("Parallax occlusion"); gettext("Enables parallax occlusion mapping.\nRequires shaders to be enabled."); gettext("Parallax occlusion mode"); gettext("0 = parallax occlusion with slope information (faster).\n1 = relief mapping (slower, more accurate)."); gettext("Parallax occlusion strength"); gettext("Strength of parallax."); gettext("Parallax occlusion iterations"); gettext("Number of parallax occlusion iterations."); gettext("Parallax occlusion scale"); gettext("Overall scale of parallax occlusion effect."); gettext("Parallax occlusion bias"); gettext("Overall bias of parallax occlusion effect, usually scale/2."); gettext("Waving Nodes"); gettext("Waving water"); gettext("Set to true enables waving water.\nRequires shaders to be enabled."); gettext("Waving water height"); gettext("Waving water length"); gettext("Waving water speed"); gettext("Waving leaves"); gettext("Set to true enables waving leaves.\nRequires shaders to be enabled."); gettext("Waving plants"); gettext("Set to true enables waving plants.\nRequires shaders to be enabled."); gettext("Advanced"); gettext("Arm inertia"); gettext("Arm inertia, gives a more realistic movement of\nthe arm when the camera moves."); gettext("Maximum FPS"); gettext("If FPS would go higher than this, limit it by sleeping\nto not waste CPU power for no benefit."); gettext("FPS in pause menu"); gettext("Maximum FPS when game is paused."); gettext("Pause on lost window focus"); gettext("Open the pause menu when the window's focus is lost. Does not pause if a formspec is\nopen."); gettext("Viewing range"); gettext("View distance in nodes."); gettext("Near plane"); gettext("Camera near plane distance in nodes, between 0 and 0.5\nMost users will not need to change this.\nIncreasing can reduce artifacting on weaker GPUs.\n0.1 = Default, 0.25 = Good value for weaker tablets."); gettext("Screen width"); gettext("Width component of the initial window size."); gettext("Screen height"); gettext("Height component of the initial window size."); gettext("Autosave screen size"); gettext("Save window size automatically when modified."); gettext("Full screen"); gettext("Fullscreen mode."); gettext("Full screen BPP"); gettext("Bits per pixel (aka color depth) in fullscreen mode."); gettext("VSync"); gettext("Vertical screen synchronization."); gettext("Field of view"); gettext("Field of view in degrees."); gettext("Gamma"); gettext("Adjust the gamma encoding for the light tables. Higher numbers are brighter.\nThis setting is for the client only and is ignored by the server."); gettext("Darkness sharpness"); gettext("Gradient of light curve at minimum light level."); gettext("Lightness sharpness"); gettext("Gradient of light curve at maximum light level."); gettext("Light curve mid boost"); gettext("Strength of light curve mid-boost."); gettext("Light curve mid boost center"); gettext("Center of light curve mid-boost."); gettext("Light curve mid boost spread"); gettext("Spread of light curve mid-boost.\nStandard deviation of the mid-boost gaussian."); gettext("Texture path"); gettext("Path to texture directory. All textures are first searched from here."); gettext("Video driver"); gettext("The rendering back-end for Irrlicht.\nA restart is required after changing this.\nNote: On Android, stick with OGLES1 if unsure! App may fail to start otherwise.\nOn other platforms, OpenGL is recommended, and it’s the only driver with\nshader support currently."); gettext("Cloud radius"); gettext("Radius of cloud area stated in number of 64 node cloud squares.\nValues larger than 26 will start to produce sharp cutoffs at cloud area corners."); gettext("View bobbing factor"); gettext("Enable view bobbing and amount of view bobbing.\nFor example: 0 for no view bobbing; 1.0 for normal; 2.0 for double."); gettext("Fall bobbing factor"); gettext("Multiplier for fall bobbing.\nFor example: 0 for no view bobbing; 1.0 for normal; 2.0 for double."); gettext("3D mode"); gettext("3D support.\nCurrently supported:\n- none: no 3d output.\n- anaglyph: cyan/magenta color 3d.\n- interlaced: odd/even line based polarisation screen support.\n- topbottom: split screen top/bottom.\n- sidebyside: split screen side by side.\n- crossview: Cross-eyed 3d\n- pageflip: quadbuffer based 3d.\nNote that the interlaced mode requires shaders to be enabled."); gettext("Console height"); gettext("In-game chat console height, between 0.1 (10%) and 1.0 (100%)."); gettext("Console color"); gettext("In-game chat console background color (R,G,B)."); gettext("Console alpha"); gettext("In-game chat console background alpha (opaqueness, between 0 and 255)."); gettext("Formspec Full-Screen Background Opacity"); gettext("Formspec full-screen background opacity (between 0 and 255)."); gettext("Formspec Full-Screen Background Color"); gettext("Formspec full-screen background color (R,G,B)."); gettext("Formspec Default Background Opacity"); gettext("Formspec default background opacity (between 0 and 255)."); gettext("Formspec Default Background Color"); gettext("Formspec default background color (R,G,B)."); gettext("Selection box color"); gettext("Selection box border color (R,G,B)."); gettext("Selection box width"); gettext("Width of the selection box lines around nodes."); gettext("Crosshair color"); gettext("Crosshair color (R,G,B)."); gettext("Crosshair alpha"); gettext("Crosshair alpha (opaqueness, between 0 and 255)."); gettext("Recent Chat Messages"); gettext("Maximum number of recent chat messages to show"); gettext("Desynchronize block animation"); gettext("Whether node texture animations should be desynchronized per mapblock."); gettext("Maximum hotbar width"); gettext("Maximum proportion of current window to be used for hotbar.\nUseful if there's something to be displayed right or left of hotbar."); gettext("HUD scale factor"); gettext("Modifies the size of the hudbar elements."); gettext("Mesh cache"); gettext("Enables caching of facedir rotated meshes."); gettext("Mapblock mesh generation delay"); gettext("Delay between mesh updates on the client in ms. Increasing this will slow\ndown the rate of mesh updates, thus reducing jitter on slower clients."); gettext("Mapblock mesh generator's MapBlock cache size in MB"); gettext("Size of the MapBlock cache of the mesh generator. Increasing this will\nincrease the cache hit %, reducing the data being copied from the main\nthread, thus reducing jitter."); gettext("Minimap"); gettext("Enables minimap."); gettext("Round minimap"); gettext("Shape of the minimap. Enabled = round, disabled = square."); gettext("Minimap scan height"); gettext("True = 256\nFalse = 128\nUseable to make minimap smoother on slower machines."); gettext("Colored fog"); gettext("Make fog and sky colors depend on daytime (dawn/sunset) and view direction."); gettext("Ambient occlusion gamma"); gettext("The strength (darkness) of node ambient-occlusion shading.\nLower is darker, Higher is lighter. The valid range of values for this\nsetting is 0.25 to 4.0 inclusive. If the value is out of range it will be\nset to the nearest valid value."); gettext("Inventory items animations"); gettext("Enables animation of inventory items."); gettext("Fog start"); gettext("Fraction of the visible distance at which fog starts to be rendered"); gettext("Opaque liquids"); gettext("Makes all liquids opaque"); gettext("World-aligned textures mode"); gettext("Textures on a node may be aligned either to the node or to the world.\nThe former mode suits better things like machines, furniture, etc., while\nthe latter makes stairs and microblocks fit surroundings better.\nHowever, as this possibility is new, thus may not be used by older servers,\nthis option allows enforcing it for certain node types. Note though that\nthat is considered EXPERIMENTAL and may not work properly."); gettext("Autoscaling mode"); gettext("World-aligned textures may be scaled to span several nodes. However,\nthe server may not send the scale you want, especially if you use\na specially-designed texture pack; with this option, the client tries\nto determine the scale automatically basing on the texture size.\nSee also texture_min_size.\nWarning: This option is EXPERIMENTAL!"); gettext("Show entity selection boxes"); gettext("Show entity selection boxes"); gettext("Menus"); gettext("Clouds in menu"); gettext("Use a cloud animation for the main menu background."); gettext("GUI scaling"); gettext("Scale GUI by a user specified value.\nUse a nearest-neighbor-anti-alias filter to scale the GUI.\nThis will smooth over some of the rough edges, and blend\npixels when scaling down, at the cost of blurring some\nedge pixels when images are scaled by non-integer sizes."); gettext("GUI scaling filter"); gettext("When gui_scaling_filter is true, all GUI images need to be\nfiltered in software, but some images are generated directly\nto hardware (e.g. render-to-texture for nodes in inventory)."); gettext("GUI scaling filter txr2img"); gettext("When gui_scaling_filter_txr2img is true, copy those images\nfrom hardware to software for scaling. When false, fall back\nto the old scaling method, for video drivers that don't\nproperly support downloading textures back from hardware."); gettext("Tooltip delay"); gettext("Delay showing tooltips, stated in milliseconds."); gettext("Append item name"); gettext("Append item name to tooltip."); gettext("FreeType fonts"); gettext("Whether FreeType fonts are used, requires FreeType support to be compiled in."); gettext("Font path"); gettext("Path to TrueTypeFont or bitmap."); gettext("Font size"); gettext("Font shadow"); gettext("Font shadow offset, if 0 then shadow will not be drawn."); gettext("Font shadow alpha"); gettext("Font shadow alpha (opaqueness, between 0 and 255)."); gettext("Monospace font path"); gettext("Monospace font size"); gettext("Fallback font"); gettext("This font will be used for certain languages."); gettext("Fallback font size"); gettext("Fallback font shadow"); gettext("Fallback font shadow alpha"); gettext("Screenshot folder"); gettext("Path to save screenshots at."); gettext("Screenshot format"); gettext("Format of screenshots."); gettext("Screenshot quality"); gettext("Screenshot quality. Only used for JPEG format.\n1 means worst quality; 100 means best quality.\nUse 0 for default quality."); gettext("Advanced"); gettext("DPI"); gettext("Adjust dpi configuration to your screen (non X11/Android only) e.g. for 4k screens."); gettext("Enable console window"); gettext("Windows systems only: Start Minetest with the command line window in the background.\nContains the same information as the file debug.txt (default name)."); gettext("Sound"); gettext("Sound"); gettext("Volume"); gettext("Mute sound"); gettext("Client"); gettext("Network"); gettext("Server address"); gettext("Address to connect to.\nLeave this blank to start a local server.\nNote that the address field in the main menu overrides this setting."); gettext("Remote port"); gettext("Port to connect to (UDP).\nNote that the port field in the main menu overrides this setting."); gettext("Saving map received from server"); gettext("Save the map received by the client on disk."); gettext("Connect to external media server"); gettext("Enable usage of remote media server (if provided by server).\nRemote servers offer a significantly faster way to download media (e.g. textures)\nwhen connecting to the server."); gettext("Client modding"); gettext("Enable Lua modding support on client.\nThis support is experimental and API can change."); gettext("Serverlist URL"); gettext("URL to the server list displayed in the Multiplayer Tab."); gettext("Serverlist file"); gettext("File in client/serverlist/ that contains your favorite servers displayed in the\nMultiplayer Tab."); gettext("Maximum size of the out chat queue"); gettext("Maximum size of the out chat queue.\n0 to disable queueing and -1 to make the queue size unlimited."); gettext("Enable register confirmation"); gettext("Enable register confirmation when connecting to server.\nIf disabled, new account will be registered automatically."); gettext("Advanced"); gettext("Mapblock unload timeout"); gettext("Timeout for client to remove unused map data from memory."); gettext("Mapblock limit"); gettext("Maximum number of mapblocks for client to be kept in memory.\nSet to -1 for unlimited amount."); gettext("Show debug info"); gettext("Whether to show the client debug info (has the same effect as hitting F5)."); gettext("Server / Singleplayer"); gettext("Server name"); gettext("Name of the server, to be displayed when players join and in the serverlist."); gettext("Server description"); gettext("Description of server, to be displayed when players join and in the serverlist."); gettext("Server address"); gettext("Domain name of server, to be displayed in the serverlist."); gettext("Server URL"); gettext("Homepage of server, to be displayed in the serverlist."); gettext("Announce server"); gettext("Automatically report to the serverlist."); gettext("Serverlist URL"); gettext("Announce to this serverlist."); gettext("Strip color codes"); gettext("Remove color codes from incoming chat messages\nUse this to stop players from being able to use color in their messages"); gettext("Network"); gettext("Server port"); gettext("Network port to listen (UDP).\nThis value will be overridden when starting from the main menu."); gettext("Bind address"); gettext("The network interface that the server listens on."); gettext("Strict protocol checking"); gettext("Enable to disallow old clients from connecting.\nOlder clients are compatible in the sense that they will not crash when connecting\nto new servers, but they may not support all new features that you are expecting."); gettext("Remote media"); gettext("Specifies URL from which client fetches media instead of using UDP.\n$filename should be accessible from $remote_media$filename via cURL\n(obviously, remote_media should end with a slash).\nFiles that are not present will be fetched the usual way."); gettext("IPv6 server"); gettext("Enable/disable running an IPv6 server.\nIgnored if bind_address is set."); gettext("Advanced"); gettext("Maximum simultaneous block sends per client"); gettext("Maximum number of blocks that are simultaneously sent per client.\nThe maximum total count is calculated dynamically:\nmax_total = ceil((#clients + max_users) * per_client / 4)"); gettext("Delay in sending blocks after building"); gettext("To reduce lag, block transfers are slowed down when a player is building something.\nThis determines how long they are slowed down after placing or removing a node."); gettext("Max. packets per iteration"); gettext("Maximum number of packets sent per send step, if you have a slow connection\ntry reducing it, but don't reduce it to a number below double of targeted\nclient number."); gettext("Game"); gettext("Default game"); gettext("Default game when creating a new world.\nThis will be overridden when creating a world from the main menu."); gettext("Message of the day"); gettext("Message of the day displayed to players connecting."); gettext("Maximum users"); gettext("Maximum number of players that can be connected simultaneously."); gettext("Map directory"); gettext("World directory (everything in the world is stored here).\nNot needed if starting from the main menu."); gettext("Item entity TTL"); gettext("Time in seconds for item entity (dropped items) to live.\nSetting it to -1 disables the feature."); gettext("Damage"); gettext("Enable players getting damage and dying."); gettext("Creative"); gettext("Enable creative mode for new created maps."); gettext("Fixed map seed"); gettext("A chosen map seed for a new map, leave empty for random.\nWill be overridden when creating a new world in the main menu."); gettext("Default password"); gettext("New users need to input this password."); gettext("Default privileges"); gettext("The privileges that new users automatically get.\nSee /privs in game for a full list on your server and mod configuration."); gettext("Basic privileges"); gettext("Privileges that players with basic_privs can grant"); gettext("Unlimited player transfer distance"); gettext("Whether players are shown to clients without any range limit.\nDeprecated, use the setting player_transfer_distance instead."); gettext("Player transfer distance"); gettext("Defines the maximal player transfer distance in blocks (0 = unlimited)."); gettext("Player versus player"); gettext("Whether to allow players to damage and kill each other."); gettext("Mod channels"); gettext("Enable mod channels support."); gettext("Static spawnpoint"); gettext("If this is set, players will always (re)spawn at the given position."); gettext("Disallow empty passwords"); gettext("If enabled, new players cannot join with an empty password."); gettext("Disable anticheat"); gettext("If enabled, disable cheat prevention in multiplayer."); gettext("Rollback recording"); gettext("If enabled, actions are recorded for rollback.\nThis option is only read when server starts."); gettext("Shutdown message"); gettext("A message to be displayed to all clients when the server shuts down."); gettext("Crash message"); gettext("A message to be displayed to all clients when the server crashes."); gettext("Ask to reconnect after crash"); gettext("Whether to ask clients to reconnect after a (Lua) crash.\nSet this to true if your server is set up to restart automatically."); gettext("Active object send range"); gettext("From how far clients know about objects, stated in mapblocks (16 nodes).\n\nSetting this larger than active_block_range will also cause the server\nto maintain active objects up to this distance in the direction the\nplayer is looking. (This can avoid mobs suddenly disappearing from view)"); gettext("Active block range"); gettext("The radius of the volume of blocks around every player that is subject to the\nactive block stuff, stated in mapblocks (16 nodes).\nIn active blocks objects are loaded and ABMs run.\nThis is also the minimum range in which active objects (mobs) are maintained.\nThis should be configured together with active_object_range."); gettext("Max block send distance"); gettext("From how far blocks are sent to clients, stated in mapblocks (16 nodes)."); gettext("Maximum forceloaded blocks"); gettext("Maximum number of forceloaded mapblocks."); gettext("Time send interval"); gettext("Interval of sending time of day to clients."); gettext("Time speed"); gettext("Controls length of day/night cycle.\nExamples:\n72 = 20min, 360 = 4min, 1 = 24hour, 0 = day/night/whatever stays unchanged."); gettext("World start time"); gettext("Time of day when a new world is started, in millihours (0-23999)."); gettext("Map save interval"); gettext("Interval of saving important changes in the world, stated in seconds."); gettext("Chat message max length"); gettext("Set the maximum character length of a chat message sent by clients."); gettext("Chat message count limit"); gettext("Amount of messages a player may send per 10 seconds."); gettext("Chat message kick threshold"); gettext("Kick players who sent more than X messages per 10 seconds."); gettext("Physics"); gettext("Default acceleration"); gettext("Acceleration in air"); gettext("Fast mode acceleration"); gettext("Walking speed"); gettext("Sneaking speed"); gettext("Fast mode speed"); gettext("Climbing speed"); gettext("Jumping speed"); gettext("Liquid fluidity"); gettext("Liquid fluidity smoothing"); gettext("Liquid sinking speed"); gettext("Gravity"); gettext("Advanced"); gettext("Deprecated Lua API handling"); gettext("Handling for deprecated lua api calls:\n- legacy: (try to) mimic old behaviour (default for release).\n- log: mimic and log backtrace of deprecated call (default for debug).\n- error: abort on usage of deprecated call (suggested for mod developers)."); gettext("Max. clearobjects extra blocks"); gettext("Number of extra blocks that can be loaded by /clearobjects at once.\nThis is a trade-off between sqlite transaction overhead and\nmemory consumption (4096=100MB, as a rule of thumb)."); gettext("Unload unused server data"); gettext("How much the server will wait before unloading unused mapblocks.\nHigher value is smoother, but will use more RAM."); gettext("Maximum objects per block"); gettext("Maximum number of statically stored objects in a block."); gettext("Synchronous SQLite"); gettext("See https://www.sqlite.org/pragma.html#pragma_synchronous"); gettext("Dedicated server step"); gettext("Length of a server tick and the interval at which objects are generally updated over\nnetwork."); gettext("Active block management interval"); gettext("Length of time between active block management cycles"); gettext("ABM interval"); gettext("Length of time between Active Block Modifier (ABM) execution cycles"); gettext("NodeTimer interval"); gettext("Length of time between NodeTimer execution cycles"); gettext("Ignore world errors"); gettext("If enabled, invalid world data won't cause the server to shut down.\nOnly enable this if you know what you are doing."); gettext("Liquid loop max"); gettext("Max liquids processed per step."); gettext("Liquid queue purge time"); gettext("The time (in seconds) that the liquids queue may grow beyond processing\ncapacity until an attempt is made to decrease its size by dumping old queue\nitems. A value of 0 disables the functionality."); gettext("Liquid update tick"); gettext("Liquid update interval in seconds."); gettext("Block send optimize distance"); gettext("At this distance the server will aggressively optimize which blocks are sent to\nclients.\nSmall values potentially improve performance a lot, at the expense of visible\nrendering glitches (some blocks will not be rendered under water and in caves,\nas well as sometimes on land).\nSetting this to a value greater than max_block_send_distance disables this\noptimization.\nStated in mapblocks (16 nodes)."); gettext("Server side occlusion culling"); gettext("If enabled the server will perform map block occlusion culling based on\non the eye position of the player. This can reduce the number of blocks\nsent to the client 50-80%. The client will not longer receive most invisible\nso that the utility of noclip mode is reduced."); gettext("Client side modding restrictions"); gettext("Restricts the access of certain client-side functions on servers.\nCombine the byteflags below to restrict client-side features, or set to 0\nfor no restrictions:\nLOAD_CLIENT_MODS: 1 (disable loading client-provided mods)\nCHAT_MESSAGES: 2 (disable send_chat_message call client-side)\nREAD_ITEMDEFS: 4 (disable get_item_def call client-side)\nREAD_NODEDEFS: 8 (disable get_node_def call client-side)\nLOOKUP_NODES_LIMIT: 16 (limits get_node call client-side to\ncsm_restriction_noderange)\nREAD_PLAYERINFO: 32 (disable get_player_names call client-side)"); gettext("Client side node lookup range restriction"); gettext("If the CSM restriction for node range is enabled, get_node calls are limited\nto this distance from the player to the node."); gettext("Security"); gettext("Enable mod security"); gettext("Prevent mods from doing insecure things like running shell commands."); gettext("Trusted mods"); gettext("Comma-separated list of trusted mods that are allowed to access insecure\nfunctions even when mod security is on (via request_insecure_environment())."); gettext("HTTP mods"); gettext("Comma-separated list of mods that are allowed to access HTTP APIs, which\nallow them to upload and download data to/from the internet."); gettext("Advanced"); gettext("Profiling"); gettext("Load the game profiler"); gettext("Load the game profiler to collect game profiling data.\nProvides a /profiler command to access the compiled profile.\nUseful for mod developers and server operators."); gettext("Default report format"); gettext("The default format in which profiles are being saved,\nwhen calling `/profiler save [format]` without format."); gettext("Report path"); gettext("The file path relative to your worldpath in which profiles will be saved to."); gettext("Instrumentation"); gettext("Entity methods"); gettext("Instrument the methods of entities on registration."); gettext("Active Block Modifiers"); gettext("Instrument the action function of Active Block Modifiers on registration."); gettext("Loading Block Modifiers"); gettext("Instrument the action function of Loading Block Modifiers on registration."); gettext("Chatcommands"); gettext("Instrument chatcommands on registration."); gettext("Global callbacks"); gettext("Instrument global callback functions on registration.\n(anything you pass to a minetest.register_*() function)"); gettext("Advanced"); gettext("Builtin"); gettext("Instrument builtin.\nThis is usually only needed by core/builtin contributors"); gettext("Profiler"); gettext("Have the profiler instrument itself:\n* Instrument an empty function.\nThis estimates the overhead, that instrumentation is adding (+1 function call).\n* Instrument the sampler being used to update the statistics."); gettext("Client and Server"); gettext("Player name"); gettext("Name of the player.\nWhen running a server, clients connecting with this name are admins.\nWhen starting from the main menu, this is overridden."); gettext("Language"); gettext("Set the language. Leave empty to use the system language.\nA restart is required after changing this."); gettext("Debug log level"); gettext("Level of logging to be written to debug.txt:\n- <nothing> (no logging)\n- none (messages with no level)\n- error\n- warning\n- action\n- info\n- verbose"); gettext("IPv6"); gettext("IPv6 support."); gettext("Advanced"); gettext("cURL timeout"); gettext("Default timeout for cURL, stated in milliseconds.\nOnly has an effect if compiled with cURL."); gettext("cURL parallel limit"); gettext("Limits number of parallel HTTP requests. Affects:\n- Media fetch if server uses remote_media setting.\n- Serverlist download and server announcement.\n- Downloads performed by main menu (e.g. mod manager).\nOnly has an effect if compiled with cURL."); gettext("cURL file download timeout"); gettext("Maximum time in ms a file download (e.g. a mod download) may take."); gettext("High-precision FPU"); gettext("Makes DirectX work with LuaJIT. Disable if it causes troubles."); gettext("Main menu style"); gettext("Changes the main menu UI:\n- Full: Multiple singleplayer worlds, game choice, texture pack chooser, etc.\n- Simple: One singleplayer world, no game or texture pack choosers. May be\nnecessary for smaller screens."); gettext("Main menu script"); gettext("Replaces the default main menu with a custom one."); gettext("Engine profiling data print interval"); gettext("Print the engine's profiling data in regular intervals (in seconds).\n0 = disable. Useful for developers."); gettext("Mapgen"); gettext("Mapgen name"); gettext("Name of map generator to be used when creating a new world.\nCreating a world in the main menu will override this.\nCurrent stable mapgens:\nv5, v6, v7 (except floatlands), singlenode.\n'stable' means the terrain shape in an existing world will not be changed\nin the future. Note that biomes are defined by games and may still change."); gettext("Water level"); gettext("Water surface level of the world."); gettext("Max block generate distance"); gettext("From how far blocks are generated for clients, stated in mapblocks (16 nodes)."); gettext("Map generation limit"); gettext("Limit of map generation, in nodes, in all 6 directions from (0, 0, 0).\nOnly mapchunks completely within the mapgen limit are generated.\nValue is stored per-world."); gettext("Mapgen flags"); gettext("Global map generation attributes.\nIn Mapgen v6 the 'decorations' flag controls all decorations except trees\nand junglegrass, in all other mapgens this flag controls all decorations."); gettext("Projecting dungeons"); gettext("Whether dungeons occasionally project from the terrain."); gettext("Biome API temperature and humidity noise parameters"); gettext("Heat noise"); gettext("Temperature variation for biomes."); gettext("Heat blend noise"); gettext("Small-scale temperature variation for blending biomes on borders."); gettext("Humidity noise"); gettext("Humidity variation for biomes."); gettext("Humidity blend noise"); gettext("Small-scale humidity variation for blending biomes on borders."); gettext("Mapgen V5"); gettext("Mapgen V5 specific flags"); gettext("Map generation attributes specific to Mapgen v5."); gettext("Cave width"); gettext("Controls width of tunnels, a smaller value creates wider tunnels."); gettext("Large cave depth"); gettext("Y of upper limit of large caves."); gettext("Lava depth"); gettext("Y of upper limit of lava in large caves."); gettext("Cavern limit"); gettext("Y-level of cavern upper limit."); gettext("Cavern taper"); gettext("Y-distance over which caverns expand to full size."); gettext("Cavern threshold"); gettext("Defines full size of caverns, smaller values create larger caverns."); gettext("Dungeon minimum Y"); gettext("Lower Y limit of dungeons."); gettext("Dungeon maximum Y"); gettext("Upper Y limit of dungeons."); gettext("Noises"); gettext("Filler depth noise"); gettext("Variation of biome filler depth."); gettext("Factor noise"); gettext("Variation of terrain vertical scale.\nWhen noise is < -0.55 terrain is near-flat."); gettext("Height noise"); gettext("Y-level of average terrain surface."); gettext("Cave1 noise"); gettext("First of two 3D noises that together define tunnels."); gettext("Cave2 noise"); gettext("Second of two 3D noises that together define tunnels."); gettext("Cavern noise"); gettext("3D noise defining giant caverns."); gettext("Ground noise"); gettext("3D noise defining terrain."); gettext("Mapgen V6"); gettext("Mapgen V6 specific flags"); gettext("Map generation attributes specific to Mapgen v6.\nThe 'snowbiomes' flag enables the new 5 biome system.\nWhen the new biome system is enabled jungles are automatically enabled and\nthe 'jungles' flag is ignored."); gettext("Desert noise threshold"); gettext("Deserts occur when np_biome exceeds this value.\nWhen the new biome system is enabled, this is ignored."); gettext("Beach noise threshold"); gettext("Sandy beaches occur when np_beach exceeds this value."); gettext("Dungeon minimum Y"); gettext("Lower Y limit of dungeons."); gettext("Dungeon maximum Y"); gettext("Upper Y limit of dungeons."); gettext("Noises"); gettext("Terrain base noise"); gettext("Y-level of lower terrain and seabed."); gettext("Terrain higher noise"); gettext("Y-level of higher terrain that creates cliffs."); gettext("Steepness noise"); gettext("Varies steepness of cliffs."); gettext("Height select noise"); gettext("Defines distribution of higher terrain."); gettext("Mud noise"); gettext("Varies depth of biome surface nodes."); gettext("Beach noise"); gettext("Defines areas with sandy beaches."); gettext("Biome noise"); gettext("Temperature variation for biomes."); gettext("Cave noise"); gettext("Variation of number of caves."); gettext("Humidity noise"); gettext("Humidity variation for biomes."); gettext("Trees noise"); gettext("Defines tree areas and tree density."); gettext("Apple trees noise"); gettext("Defines areas where trees have apples."); gettext("Mapgen V7"); gettext("Mapgen V7 specific flags"); gettext("Map generation attributes specific to Mapgen v7.\n'ridges' enables the rivers."); gettext("Mountain zero level"); gettext("Y of mountain density gradient zero level. Used to shift mountains vertically."); gettext("Cave width"); gettext("Controls width of tunnels, a smaller value creates wider tunnels."); gettext("Large cave depth"); gettext("Y of upper limit of large caves."); gettext("Lava depth"); gettext("Y of upper limit of lava in large caves."); gettext("Floatland mountain density"); gettext("Controls the density of mountain-type floatlands.\nIs a noise offset added to the 'mgv7_np_mountain' noise value."); gettext("Floatland mountain height"); gettext("Typical maximum height, above and below midpoint, of floatland mountains."); gettext("Floatland mountain exponent"); gettext("Alters how mountain-type floatlands taper above and below midpoint."); gettext("Floatland level"); gettext("Y-level of floatland midpoint and lake surface."); gettext("Shadow limit"); gettext("Y-level to which floatland shadows extend."); gettext("Cavern limit"); gettext("Y-level of cavern upper limit."); gettext("Cavern taper"); gettext("Y-distance over which caverns expand to full size."); gettext("Cavern threshold"); gettext("Defines full size of caverns, smaller values create larger caverns."); gettext("Dungeon minimum Y"); gettext("Lower Y limit of dungeons."); gettext("Dungeon maximum Y"); gettext("Upper Y limit of dungeons."); gettext("Noises"); gettext("Terrain base noise"); gettext("Y-level of higher terrain that creates cliffs."); gettext("Terrain alternative noise"); gettext("Y-level of lower terrain and seabed."); gettext("Terrain persistence noise"); gettext("Varies roughness of terrain.\nDefines the 'persistence' value for terrain_base and terrain_alt noises."); gettext("Height select noise"); gettext("Defines distribution of higher terrain and steepness of cliffs."); gettext("Filler depth noise"); gettext("Variation of biome filler depth."); gettext("Mountain height noise"); gettext("Variation of maximum mountain height (in nodes)."); gettext("Ridge underwater noise"); gettext("Defines large-scale river channel structure."); gettext("Floatland base noise"); gettext("Defines areas of floatland smooth terrain.\nSmooth floatlands occur when noise > 0."); gettext("Floatland base height noise"); gettext("Variation of hill height and lake depth on floatland smooth terrain."); gettext("Mountain noise"); gettext("3D noise defining mountain structure and height.\nAlso defines structure of floatland mountain terrain."); gettext("Ridge noise"); gettext("3D noise defining structure of river canyon walls."); gettext("Cavern noise"); gettext("3D noise defining giant caverns."); gettext("Cave1 noise"); gettext("First of two 3D noises that together define tunnels."); gettext("Cave2 noise"); gettext("Second of two 3D noises that together define tunnels."); gettext("Mapgen Carpathian"); gettext("Mapgen Carpathian specific flags"); gettext("Map generation attributes specific to Mapgen Carpathian."); gettext("Base ground level"); gettext("Defines the base ground level."); gettext("Cave width"); gettext("Controls width of tunnels, a smaller value creates wider tunnels."); gettext("Large cave depth"); gettext("Y of upper limit of large caves."); gettext("Lava depth"); gettext("Y of upper limit of lava in large caves."); gettext("Cavern limit"); gettext("Y-level of cavern upper limit."); gettext("Cavern taper"); gettext("Y-distance over which caverns expand to full size."); gettext("Cavern threshold"); gettext("Defines full size of caverns, smaller values create larger caverns."); gettext("Dungeon minimum Y"); gettext("Lower Y limit of dungeons."); gettext("Dungeon maximum Y"); gettext("Upper Y limit of dungeons."); gettext("Noises"); gettext("Filler depth noise"); gettext("Variation of biome filler depth."); gettext("Hilliness1 noise"); gettext("First of 4 2D noises that together define hill/mountain range height."); gettext("Hilliness2 noise"); gettext("Second of 4 2D noises that together define hill/mountain range height."); gettext("Hilliness3 noise"); gettext("Third of 4 2D noises that together define hill/mountain range height."); gettext("Hilliness4 noise"); gettext("Fourth of 4 2D noises that together define hill/mountain range height."); gettext("Rolling hills spread noise"); gettext("2D noise that controls the size/occurrence of rolling hills."); gettext("Ridge mountain spread noise"); gettext("2D noise that controls the size/occurrence of ridged mountain ranges."); gettext("Step mountain spread noise"); gettext("2D noise that controls the size/occurrence of step mountain ranges."); gettext("Rolling hill size noise"); gettext("2D noise that controls the shape/size of rolling hills."); gettext("Ridged mountain size noise"); gettext("2D noise that controls the shape/size of ridged mountains."); gettext("Step mountain size noise"); gettext("2D noise that controls the shape/size of step mountains."); gettext("Mountain variation noise"); gettext("3D noise for mountain overhangs, cliffs, etc. Usually small variations."); gettext("Cave1 noise"); gettext("First of two 3D noises that together define tunnels."); gettext("Cave2 noise"); gettext("Second of two 3D noises that together define tunnels."); gettext("Cavern noise"); gettext("3D noise defining giant caverns."); gettext("Mapgen Flat"); gettext("Mapgen Flat specific flags"); gettext("Map generation attributes specific to Mapgen flat.\nOccasional lakes and hills can be added to the flat world."); gettext("Ground level"); gettext("Y of flat ground."); gettext("Large cave depth"); gettext("Y of upper limit of large caves."); gettext("Lava depth"); gettext("Y of upper limit of lava in large caves."); gettext("Cave width"); gettext("Controls width of tunnels, a smaller value creates wider tunnels."); gettext("Lake threshold"); gettext("Terrain noise threshold for lakes.\nControls proportion of world area covered by lakes.\nAdjust towards 0.0 for a larger proportion."); gettext("Lake steepness"); gettext("Controls steepness/depth of lake depressions."); gettext("Hill threshold"); gettext("Terrain noise threshold for hills.\nControls proportion of world area covered by hills.\nAdjust towards 0.0 for a larger proportion."); gettext("Hill steepness"); gettext("Controls steepness/height of hills."); gettext("Dungeon minimum Y"); gettext("Lower Y limit of dungeons."); gettext("Dungeon maximum Y"); gettext("Upper Y limit of dungeons."); gettext("Noises"); gettext("Terrain noise"); gettext("Defines location and terrain of optional hills and lakes."); gettext("Filler depth noise"); gettext("Variation of biome filler depth."); gettext("Cave1 noise"); gettext("First of two 3D noises that together define tunnels."); gettext("Cave2 noise"); gettext("Second of two 3D noises that together define tunnels."); gettext("Mapgen Fractal"); gettext("Cave width"); gettext("Controls width of tunnels, a smaller value creates wider tunnels."); gettext("Large cave depth"); gettext("Y of upper limit of large caves."); gettext("Lava depth"); gettext("Y of upper limit of lava in large caves."); gettext("Dungeon minimum Y"); gettext("Lower Y limit of dungeons."); gettext("Dungeon maximum Y"); gettext("Upper Y limit of dungeons."); gettext("Fractal type"); gettext("Selects one of 18 fractal types.\n1 = 4D \"Roundy\" mandelbrot set.\n2 = 4D \"Roundy\" julia set.\n3 = 4D \"Squarry\" mandelbrot set.\n4 = 4D \"Squarry\" julia set.\n5 = 4D \"Mandy Cousin\" mandelbrot set.\n6 = 4D \"Mandy Cousin\" julia set.\n7 = 4D \"Variation\" mandelbrot set.\n8 = 4D \"Variation\" julia set.\n9 = 3D \"Mandelbrot/Mandelbar\" mandelbrot set.\n10 = 3D \"Mandelbrot/Mandelbar\" julia set.\n11 = 3D \"Christmas Tree\" mandelbrot set.\n12 = 3D \"Christmas Tree\" julia set.\n13 = 3D \"Mandelbulb\" mandelbrot set.\n14 = 3D \"Mandelbulb\" julia set.\n15 = 3D \"Cosine Mandelbulb\" mandelbrot set.\n16 = 3D \"Cosine Mandelbulb\" julia set.\n17 = 4D \"Mandelbulb\" mandelbrot set.\n18 = 4D \"Mandelbulb\" julia set."); gettext("Iterations"); gettext("Iterations of the recursive function.\nIncreasing this increases the amount of fine detail, but also\nincreases processing load.\nAt iterations = 20 this mapgen has a similar load to mapgen V7."); gettext("Scale"); gettext("(X,Y,Z) scale of fractal in nodes.\nActual fractal size will be 2 to 3 times larger.\nThese numbers can be made very large, the fractal does\nnot have to fit inside the world.\nIncrease these to 'zoom' into the detail of the fractal.\nDefault is for a vertically-squashed shape suitable for\nan island, set all 3 numbers equal for the raw shape."); gettext("Offset"); gettext("(X,Y,Z) offset of fractal from world center in units of 'scale'.\nCan be used to move a desired point to (0, 0) to create a\nsuitable spawn point, or to allow 'zooming in' on a desired\npoint by increasing 'scale'.\nThe default is tuned for a suitable spawn point for mandelbrot\nsets with default parameters, it may need altering in other\nsituations.\nRange roughly -2 to 2. Multiply by 'scale' for offset in nodes."); gettext("Slice w"); gettext("W coordinate of the generated 3D slice of a 4D fractal.\nDetermines which 3D slice of the 4D shape is generated.\nAlters the shape of the fractal.\nHas no effect on 3D fractals.\nRange roughly -2 to 2."); gettext("Julia x"); gettext("Julia set only.\nX component of hypercomplex constant.\nAlters the shape of the fractal.\nRange roughly -2 to 2."); gettext("Julia y"); gettext("Julia set only.\nY component of hypercomplex constant.\nAlters the shape of the fractal.\nRange roughly -2 to 2."); gettext("Julia z"); gettext("Julia set only.\nZ component of hypercomplex constant.\nAlters the shape of the fractal.\nRange roughly -2 to 2."); gettext("Julia w"); gettext("Julia set only.\nW component of hypercomplex constant.\nAlters the shape of the fractal.\nHas no effect on 3D fractals.\nRange roughly -2 to 2."); gettext("Noises"); gettext("Seabed noise"); gettext("Y-level of seabed."); gettext("Filler depth noise"); gettext("Variation of biome filler depth."); gettext("Cave1 noise"); gettext("First of two 3D noises that together define tunnels."); gettext("Cave2 noise"); gettext("Second of two 3D noises that together define tunnels."); gettext("Mapgen Valleys"); gettext("Mapgen Valleys specific flags"); gettext("Map generation attributes specific to Mapgen Valleys.\n'altitude_chill': Reduces heat with altitude.\n'humid_rivers': Increases humidity around rivers.\n'vary_river_depth': If enabled, low humidity and high heat causes rivers\nto become shallower and occasionally dry.\n'altitude_dry': Reduces humidity with altitude."); gettext("Altitude chill"); gettext("The vertical distance over which heat drops by 20 if 'altitude_chill' is\nenabled. Also the vertical distance over which humidity drops by 10 if\n'altitude_dry' is enabled."); gettext("Large cave depth"); gettext("Depth below which you'll find large caves."); gettext("Lava depth"); gettext("Y of upper limit of lava in large caves."); gettext("Cavern upper limit"); gettext("Depth below which you'll find giant caverns."); gettext("Cavern taper"); gettext("Y-distance over which caverns expand to full size."); gettext("Cavern threshold"); gettext("Defines full size of caverns, smaller values create larger caverns."); gettext("River depth"); gettext("How deep to make rivers."); gettext("River size"); gettext("How wide to make rivers."); gettext("Cave width"); gettext("Controls width of tunnels, a smaller value creates wider tunnels."); gettext("Dungeon minimum Y"); gettext("Lower Y limit of dungeons."); gettext("Dungeon maximum Y"); gettext("Upper Y limit of dungeons."); gettext("Noises"); gettext("Cave noise #1"); gettext("First of two 3D noises that together define tunnels."); gettext("Cave noise #2"); gettext("Second of two 3D noises that together define tunnels."); gettext("Filler depth"); gettext("The depth of dirt or other biome filler node."); gettext("Cavern noise"); gettext("3D noise defining giant caverns."); gettext("River noise"); gettext("Defines large-scale river channel structure."); gettext("Terrain height"); gettext("Base terrain height."); gettext("Valley depth"); gettext("Raises terrain to make valleys around the rivers."); gettext("Valley fill"); gettext("Slope and fill work together to modify the heights."); gettext("Valley profile"); gettext("Amplifies the valleys."); gettext("Valley slope"); gettext("Slope and fill work together to modify the heights."); gettext("Advanced"); gettext("Chunk size"); gettext("Size of mapchunks generated by mapgen, stated in mapblocks (16 nodes).\nWARNING!: There is no benefit, and there are several dangers, in\nincreasing this value above 5.\nReducing this value increases cave and dungeon density.\nAltering this value is for special usage, leaving it unchanged is\nrecommended."); gettext("Mapgen debug"); gettext("Dump the mapgen debug information."); gettext("Absolute limit of emerge queues"); gettext("Maximum number of blocks that can be queued for loading."); gettext("Limit of emerge queues on disk"); gettext("Maximum number of blocks to be queued that are to be loaded from file.\nSet to blank for an appropriate amount to be chosen automatically."); gettext("Limit of emerge queues to generate"); gettext("Maximum number of blocks to be queued that are to be generated.\nSet to blank for an appropriate amount to be chosen automatically."); gettext("Number of emerge threads"); gettext("Number of emerge threads to use.\nEmpty or 0 value:\n- Automatic selection. The number of emerge threads will be\n- 'number of processors - 2', with a lower limit of 1.\nAny other value:\n- Specifies the number of emerge threads, with a lower limit of 1.\nWarning: Increasing the number of emerge threads increases engine mapgen\nspeed, but this may harm game performance by interfering with other\nprocesses, especially in singleplayer and/or when running Lua code in\n'on_generated'.\nFor many users the optimum setting may be '1'."); gettext("Online Content Repository"); gettext("ContentDB URL"); gettext("The URL for the content repository"); gettext("ContentDB Flag Blacklist"); gettext("Comma-separated list of flags to hide in the content repository.\n\"nonfree\" can be used to hide packages which do not qualify as 'free software',\nas defined by the Free Software Foundation.\nYou can also specify content ratings.\nThese flags are independent from Minetest versions,\nso see a full list at https://content.minetest.net/help/content_flags/"); }
pgimeno/minetest
src/settings_translation_file.cpp
C++
mit
66,137
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <set> #include <string> #include "util/serialize.h" #include "irrlichttypes_bloated.h" struct SimpleSoundSpec { SimpleSoundSpec(const std::string &name = "", float gain = 1.0f, float fade = 0.0f, float pitch = 1.0f) : name(name), gain(gain), fade(fade), pitch(pitch) { } bool exists() const { return !name.empty(); } // Take cf_version from ContentFeatures::serialize to // keep in sync with item definitions void serialize(std::ostream &os, u8 cf_version) const { os << serializeString(name); writeF32(os, gain); writeF32(os, pitch); writeF32(os, fade); // if (cf_version < ?) // return; } void deSerialize(std::istream &is, u8 cf_version) { name = deSerializeString(is); gain = readF32(is); pitch = readF32(is); fade = readF32(is); } std::string name; float gain = 1.0f; float fade = 0.0f; float pitch = 1.0f; };
pgimeno/minetest
src/sound.h
C++
mit
1,677
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "staticobject.h" #include "util/serialize.h" #include "content_sao.h" StaticObject::StaticObject(const ServerActiveObject *s_obj, const v3f &pos_): type(s_obj->getType()), pos(pos_) { s_obj->getStaticData(&data); } void StaticObject::serialize(std::ostream &os) { // type writeU8(os, type); // pos writeV3F1000(os, pos); // data os<<serializeString(data); } void StaticObject::deSerialize(std::istream &is, u8 version) { // type type = readU8(is); // pos pos = readV3F1000(is); // data data = deSerializeString(is); } void StaticObjectList::serialize(std::ostream &os) { // version u8 version = 0; writeU8(os, version); // count size_t count = m_stored.size() + m_active.size(); // Make sure it fits into u16, else it would get truncated and cause e.g. // issue #2610 (Invalid block data in database: unsupported NameIdMapping version). if (count > U16_MAX) { errorstream << "StaticObjectList::serialize(): " << "too many objects (" << count << ") in list, " << "not writing them to disk." << std::endl; writeU16(os, 0); // count = 0 return; } writeU16(os, count); for (StaticObject &s_obj : m_stored) { s_obj.serialize(os); } for (auto &i : m_active) { StaticObject s_obj = i.second; s_obj.serialize(os); } } void StaticObjectList::deSerialize(std::istream &is) { // version u8 version = readU8(is); // count u16 count = readU16(is); for(u16 i = 0; i < count; i++) { StaticObject s_obj; s_obj.deSerialize(is, version); m_stored.push_back(s_obj); } }
pgimeno/minetest
src/staticobject.cpp
C++
mit
2,317
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes_bloated.h" #include <string> #include <sstream> #include <vector> #include <map> #include "debug.h" class ServerActiveObject; struct StaticObject { u8 type = 0; v3f pos; std::string data; StaticObject() = default; StaticObject(const ServerActiveObject *s_obj, const v3f &pos_); void serialize(std::ostream &os); void deSerialize(std::istream &is, u8 version); }; class StaticObjectList { public: /* Inserts an object to the container. Id must be unique (active) or 0 (stored). */ void insert(u16 id, const StaticObject &obj) { if(id == 0) { m_stored.push_back(obj); } else { if(m_active.find(id) != m_active.end()) { dstream<<"ERROR: StaticObjectList::insert(): " <<"id already exists"<<std::endl; FATAL_ERROR("StaticObjectList::insert()"); } m_active[id] = obj; } } void remove(u16 id) { assert(id != 0); // Pre-condition if(m_active.find(id) == m_active.end()) { warningstream<<"StaticObjectList::remove(): id="<<id <<" not found"<<std::endl; return; } m_active.erase(id); } void serialize(std::ostream &os); void deSerialize(std::istream &is); /* NOTE: When an object is transformed to active, it is removed from m_stored and inserted to m_active. The caller directly manipulates these containers. */ std::vector<StaticObject> m_stored; std::map<u16, StaticObject> m_active; private: };
pgimeno/minetest
src/staticobject.h
C++
mit
2,220
/* Minetest Copyright (C) 2015 est31 <MTest31@outlook.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #if USE_CURSES #include "version.h" #include "terminal_chat_console.h" #include "porting.h" #include "settings.h" #include "util/numeric.h" #include "util/string.h" #include "chat_interface.h" TerminalChatConsole g_term_console; // include this last to avoid any conflicts // (likes to set macros to common names, conflicting various stuff) #if CURSES_HAVE_NCURSESW_NCURSES_H #include <ncursesw/ncurses.h> #elif CURSES_HAVE_NCURSESW_CURSES_H #include <ncursesw/curses.h> #elif CURSES_HAVE_CURSES_H #include <curses.h> #elif CURSES_HAVE_NCURSES_H #include <ncurses.h> #elif CURSES_HAVE_NCURSES_NCURSES_H #include <ncurses/ncurses.h> #elif CURSES_HAVE_NCURSES_CURSES_H #include <ncurses/curses.h> #endif // Some functions to make drawing etc position independent static bool reformat_backend(ChatBackend *backend, int rows, int cols) { if (rows < 2) return false; backend->reformat(cols, rows - 2); return true; } static void move_for_backend(int row, int col) { move(row + 1, col); } void TerminalChatConsole::initOfCurses() { initscr(); cbreak(); //raw(); noecho(); keypad(stdscr, TRUE); nodelay(stdscr, TRUE); timeout(100); // To make esc not delay up to one second. According to the internet, // this is the value vim uses, too. set_escdelay(25); getmaxyx(stdscr, m_rows, m_cols); m_can_draw_text = reformat_backend(&m_chat_backend, m_rows, m_cols); } void TerminalChatConsole::deInitOfCurses() { endwin(); } void *TerminalChatConsole::run() { BEGIN_DEBUG_EXCEPTION_HANDLER std::cout << "========================" << std::endl; std::cout << "Begin log output over terminal" << " (no stdout/stderr backlog during that)" << std::endl; // Make the loggers to stdout/stderr shut up. // Go over our own loggers instead. LogLevelMask err_mask = g_logger.removeOutput(&stderr_output); LogLevelMask out_mask = g_logger.removeOutput(&stdout_output); g_logger.addOutput(&m_log_output); // Inform the server of our nick m_chat_interface->command_queue.push_back( new ChatEventNick(CET_NICK_ADD, m_nick)); { // Ensures that curses is deinitialized even on an exception being thrown CursesInitHelper helper(this); while (!stopRequested()) { int ch = getch(); if (stopRequested()) break; step(ch); } } if (m_kill_requested) *m_kill_requested = true; g_logger.removeOutput(&m_log_output); g_logger.addOutputMasked(&stderr_output, err_mask); g_logger.addOutputMasked(&stdout_output, out_mask); std::cout << "End log output over terminal" << " (no stdout/stderr backlog during that)" << std::endl; std::cout << "========================" << std::endl; END_DEBUG_EXCEPTION_HANDLER return NULL; } void TerminalChatConsole::typeChatMessage(const std::wstring &msg) { // Discard empty line if (msg.empty()) return; // Send to server m_chat_interface->command_queue.push_back( new ChatEventChat(m_nick, msg)); // Print if its a command (gets eaten by server otherwise) if (msg[0] == L'/') { m_chat_backend.addMessage(L"", (std::wstring)L"Issued command: " + msg); } } void TerminalChatConsole::handleInput(int ch, bool &complete_redraw_needed) { ChatPrompt &prompt = m_chat_backend.getPrompt(); // Helpful if you want to collect key codes that aren't documented /*if (ch != ERR) { m_chat_backend.addMessage(L"", (std::wstring)L"Pressed key " + utf8_to_wide( std::string(keyname(ch)) + " (code " + itos(ch) + ")")); complete_redraw_needed = true; }//*/ // All the key codes below are compatible to xterm // Only add new ones if you have tried them there, // to ensure compatibility with not just xterm but the wide // range of terminals that are compatible to xterm. switch (ch) { case ERR: // no input break; case 27: // ESC // Toggle ESC mode m_esc_mode = !m_esc_mode; break; case KEY_PPAGE: m_chat_backend.scrollPageUp(); complete_redraw_needed = true; break; case KEY_NPAGE: m_chat_backend.scrollPageDown(); complete_redraw_needed = true; break; case KEY_ENTER: case '\r': case '\n': { prompt.addToHistory(prompt.getLine()); typeChatMessage(prompt.replace(L"")); break; } case KEY_UP: prompt.historyPrev(); break; case KEY_DOWN: prompt.historyNext(); break; case KEY_LEFT: // Left pressed // move character to the left prompt.cursorOperation( ChatPrompt::CURSOROP_MOVE, ChatPrompt::CURSOROP_DIR_LEFT, ChatPrompt::CURSOROP_SCOPE_CHARACTER); break; case 545: // Ctrl-Left pressed // move word to the left prompt.cursorOperation( ChatPrompt::CURSOROP_MOVE, ChatPrompt::CURSOROP_DIR_LEFT, ChatPrompt::CURSOROP_SCOPE_WORD); break; case KEY_RIGHT: // Right pressed // move character to the right prompt.cursorOperation( ChatPrompt::CURSOROP_MOVE, ChatPrompt::CURSOROP_DIR_RIGHT, ChatPrompt::CURSOROP_SCOPE_CHARACTER); break; case 560: // Ctrl-Right pressed // move word to the right prompt.cursorOperation( ChatPrompt::CURSOROP_MOVE, ChatPrompt::CURSOROP_DIR_RIGHT, ChatPrompt::CURSOROP_SCOPE_WORD); break; case KEY_HOME: // Home pressed // move to beginning of line prompt.cursorOperation( ChatPrompt::CURSOROP_MOVE, ChatPrompt::CURSOROP_DIR_LEFT, ChatPrompt::CURSOROP_SCOPE_LINE); break; case KEY_END: // End pressed // move to end of line prompt.cursorOperation( ChatPrompt::CURSOROP_MOVE, ChatPrompt::CURSOROP_DIR_RIGHT, ChatPrompt::CURSOROP_SCOPE_LINE); break; case KEY_BACKSPACE: case '\b': case 127: // Backspace pressed // delete character to the left prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_LEFT, ChatPrompt::CURSOROP_SCOPE_CHARACTER); break; case KEY_DC: // Delete pressed // delete character to the right prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_RIGHT, ChatPrompt::CURSOROP_SCOPE_CHARACTER); break; case 519: // Ctrl-Delete pressed // delete word to the right prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_RIGHT, ChatPrompt::CURSOROP_SCOPE_WORD); break; case 21: // Ctrl-U pressed // kill line to left end prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_LEFT, ChatPrompt::CURSOROP_SCOPE_LINE); break; case 11: // Ctrl-K pressed // kill line to right end prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_RIGHT, ChatPrompt::CURSOROP_SCOPE_LINE); break; case KEY_TAB: // Tab pressed // Nick completion prompt.nickCompletion(m_nicks, false); break; default: // Add character to the prompt, // assuming UTF-8. if (IS_UTF8_MULTB_START(ch)) { m_pending_utf8_bytes.append(1, (char)ch); m_utf8_bytes_to_wait += UTF8_MULTB_START_LEN(ch) - 1; } else if (m_utf8_bytes_to_wait != 0) { m_pending_utf8_bytes.append(1, (char)ch); m_utf8_bytes_to_wait--; if (m_utf8_bytes_to_wait == 0) { std::wstring w = utf8_to_wide(m_pending_utf8_bytes); m_pending_utf8_bytes = ""; // hopefully only one char in the wstring... for (size_t i = 0; i < w.size(); i++) { prompt.input(w.c_str()[i]); } } } else if (IS_ASCII_PRINTABLE_CHAR(ch)) { prompt.input(ch); } else { // Silently ignore characters we don't handle //warningstream << "Pressed invalid character '" // << keyname(ch) << "' (code " << itos(ch) << ")" << std::endl; } break; } } void TerminalChatConsole::step(int ch) { bool complete_redraw_needed = false; // empty queues while (!m_chat_interface->outgoing_queue.empty()) { ChatEvent *evt = m_chat_interface->outgoing_queue.pop_frontNoEx(); switch (evt->type) { case CET_NICK_REMOVE: m_nicks.remove(((ChatEventNick *)evt)->nick); break; case CET_NICK_ADD: m_nicks.push_back(((ChatEventNick *)evt)->nick); break; case CET_CHAT: complete_redraw_needed = true; // This is only used for direct replies from commands // or for lua's print() functionality m_chat_backend.addMessage(L"", ((ChatEventChat *)evt)->evt_msg); break; case CET_TIME_INFO: ChatEventTimeInfo *tevt = (ChatEventTimeInfo *)evt; m_game_time = tevt->game_time; m_time_of_day = tevt->time; }; delete evt; } while (!m_log_output.queue.empty()) { complete_redraw_needed = true; std::pair<LogLevel, std::string> p = m_log_output.queue.pop_frontNoEx(); if (p.first > m_log_level) continue; std::wstring error_message = utf8_to_wide(Logger::getLevelLabel(p.first)); if (!g_settings->getBool("disable_escape_sequences")) { error_message = std::wstring(L"\x1b(c@red)").append(error_message) .append(L"\x1b(c@white)"); } m_chat_backend.addMessage(error_message, utf8_to_wide(p.second)); } // handle input if (!m_esc_mode) { handleInput(ch, complete_redraw_needed); } else { switch (ch) { case ERR: // no input break; case 27: // ESC // Toggle ESC mode m_esc_mode = !m_esc_mode; break; case 'L': m_log_level--; m_log_level = MYMAX(m_log_level, LL_NONE + 1); // LL_NONE isn't accessible break; case 'l': m_log_level++; m_log_level = MYMIN(m_log_level, LL_MAX - 1); break; } } // was there a resize? int xn, yn; getmaxyx(stdscr, yn, xn); if (xn != m_cols || yn != m_rows) { m_cols = xn; m_rows = yn; m_can_draw_text = reformat_backend(&m_chat_backend, m_rows, m_cols); complete_redraw_needed = true; } // draw title move(0, 0); clrtoeol(); addstr(PROJECT_NAME_C); addstr(" "); addstr(g_version_hash); u32 minutes = m_time_of_day % 1000; u32 hours = m_time_of_day / 1000; minutes = (float)minutes / 1000 * 60; if (m_game_time) printw(" | Game %d Time of day %02d:%02d ", m_game_time, hours, minutes); // draw text if (complete_redraw_needed && m_can_draw_text) draw_text(); // draw prompt if (!m_esc_mode) { // normal prompt ChatPrompt& prompt = m_chat_backend.getPrompt(); std::string prompt_text = wide_to_utf8(prompt.getVisiblePortion()); move(m_rows - 1, 0); clrtoeol(); addstr(prompt_text.c_str()); // Draw cursor s32 cursor_pos = prompt.getVisibleCursorPosition(); if (cursor_pos >= 0) { move(m_rows - 1, cursor_pos); } } else { // esc prompt move(m_rows - 1, 0); clrtoeol(); printw("[ESC] Toggle ESC mode |" " [CTRL+C] Shut down |" " (L) in-, (l) decrease loglevel %s", Logger::getLevelLabel((LogLevel) m_log_level).c_str()); } refresh(); } void TerminalChatConsole::draw_text() { ChatBuffer& buf = m_chat_backend.getConsoleBuffer(); for (u32 row = 0; row < buf.getRows(); row++) { move_for_backend(row, 0); clrtoeol(); const ChatFormattedLine& line = buf.getFormattedLine(row); if (line.fragments.empty()) continue; for (const ChatFormattedFragment &fragment : line.fragments) { addstr(wide_to_utf8(fragment.text.getString()).c_str()); } } } void TerminalChatConsole::stopAndWaitforThread() { clearKillStatus(); stop(); wait(); } #endif
pgimeno/minetest
src/terminal_chat_console.cpp
C++
mit
11,894
/* Minetest Copyright (C) 2015 est31 <MTest31@outlook.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "chat.h" #include "threading/thread.h" #include "util/container.h" #include "log.h" #include <sstream> struct ChatInterface; class TermLogOutput : public ILogOutput { public: void logRaw(LogLevel lev, const std::string &line) { queue.push_back(std::make_pair(lev, line)); } virtual void log(LogLevel lev, const std::string &combined, const std::string &time, const std::string &thread_name, const std::string &payload_text) { std::ostringstream os(std::ios_base::binary); os << time << ": [" << thread_name << "] " << payload_text; queue.push_back(std::make_pair(lev, os.str())); } MutexedQueue<std::pair<LogLevel, std::string> > queue; }; class TerminalChatConsole : public Thread { public: TerminalChatConsole() : Thread("TerminalThread") {} void setup( ChatInterface *iface, bool *kill_requested, const std::string &nick) { m_nick = nick; m_kill_requested = kill_requested; m_chat_interface = iface; } virtual void *run(); // Highly required! void clearKillStatus() { m_kill_requested = nullptr; } void stopAndWaitforThread(); private: // these have stupid names so that nobody missclassifies them // as curses functions. Oh, curses has stupid names too? // Well, at least it was worth a try... void initOfCurses(); void deInitOfCurses(); void draw_text(); void typeChatMessage(const std::wstring &m); void handleInput(int ch, bool &complete_redraw_needed); void step(int ch); // Used to ensure the deinitialisation is always called. struct CursesInitHelper { TerminalChatConsole *cons; CursesInitHelper(TerminalChatConsole * a_console) : cons(a_console) { cons->initOfCurses(); } ~CursesInitHelper() { cons->deInitOfCurses(); } }; int m_log_level = LL_ACTION; std::string m_nick; u8 m_utf8_bytes_to_wait = 0; std::string m_pending_utf8_bytes; std::list<std::string> m_nicks; int m_cols; int m_rows; bool m_can_draw_text; bool *m_kill_requested = nullptr; ChatBackend m_chat_backend; ChatInterface *m_chat_interface; TermLogOutput m_log_output; bool m_esc_mode = false; u64 m_game_time = 0; u32 m_time_of_day = 0; }; extern TerminalChatConsole g_term_console;
pgimeno/minetest
src/terminal_chat_console.h
C++
mit
2,961
set(JTHREAD_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/event.cpp ${CMAKE_CURRENT_SOURCE_DIR}/thread.cpp ${CMAKE_CURRENT_SOURCE_DIR}/semaphore.cpp PARENT_SCOPE)
pgimeno/minetest
src/threading/CMakeLists.txt
Text
mit
155
/* This file is a part of the JThread package, which contains some object- oriented thread wrappers for different thread implementations. Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "threading/event.h" #include "threading/mutex_auto_lock.h" void Event::wait() { MutexAutoLock lock(mutex); while (!notified) { cv.wait(lock); } notified = false; } void Event::signal() { MutexAutoLock lock(mutex); notified = true; cv.notify_one(); }
pgimeno/minetest
src/threading/event.cpp
C++
mit
1,510
/* This file is a part of the JThread package, which contains some object- oriented thread wrappers for different thread implementations. Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <condition_variable> /** A syncronization primitive that will wake up one waiting thread when signaled. * Calling @c signal() multiple times before a waiting thread has had a chance * to notice the signal will wake only one thread. Additionally, if no threads * are waiting on the event when it is signaled, the next call to @c wait() * will return (almost) immediately. */ class Event { public: void wait(); void signal(); private: std::condition_variable cv; std::mutex mutex; bool notified = false; };
pgimeno/minetest
src/threading/event.h
C++
mit
1,780
/* This file is a part of the JThread package, which contains some object- oriented thread wrappers for different thread implementations. Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <mutex> using MutexAutoLock = std::unique_lock<std::mutex>; using RecursiveMutexAutoLock = std::unique_lock<std::recursive_mutex>;
pgimeno/minetest
src/threading/mutex_auto_lock.h
C++
mit
1,393
/* Minetest Copyright (C) 2013 sapier <sapier AT gmx DOT net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "threading/semaphore.h" #include <iostream> #include <cstdlib> #include <cassert> #define UNUSED(expr) do { (void)(expr); } while (0) #ifdef _WIN32 #include <climits> #define MAX_SEMAPHORE_COUNT LONG_MAX - 1 #else #include <cerrno> #include <sys/time.h> #include <pthread.h> #if defined(__MACH__) && defined(__APPLE__) #include <mach/mach.h> #include <mach/task.h> #include <mach/semaphore.h> #include <sys/semaphore.h> #include <unistd.h> #undef sem_t #undef sem_init #undef sem_wait #undef sem_post #undef sem_destroy #define sem_t semaphore_t #define sem_init(s, p, c) semaphore_create(mach_task_self(), (s), 0, (c)) #define sem_wait(s) semaphore_wait(*(s)) #define sem_post(s) semaphore_signal(*(s)) #define sem_destroy(s) semaphore_destroy(mach_task_self(), *(s)) #endif #endif Semaphore::Semaphore(int val) { #ifdef _WIN32 semaphore = CreateSemaphore(NULL, val, MAX_SEMAPHORE_COUNT, NULL); #else int ret = sem_init(&semaphore, 0, val); assert(!ret); UNUSED(ret); #endif } Semaphore::~Semaphore() { #ifdef _WIN32 CloseHandle(semaphore); #else int ret = sem_destroy(&semaphore); #ifdef __ANDROID__ // Workaround for broken bionic semaphore implementation! assert(!ret || errno == EBUSY); #else assert(!ret); #endif UNUSED(ret); #endif } void Semaphore::post(unsigned int num) { assert(num > 0); #ifdef _WIN32 ReleaseSemaphore(semaphore, num, NULL); #else for (unsigned i = 0; i < num; i++) { int ret = sem_post(&semaphore); assert(!ret); UNUSED(ret); } #endif } void Semaphore::wait() { #ifdef _WIN32 WaitForSingleObject(semaphore, INFINITE); #else int ret = sem_wait(&semaphore); assert(!ret); UNUSED(ret); #endif } bool Semaphore::wait(unsigned int time_ms) { #ifdef _WIN32 unsigned int ret = WaitForSingleObject(semaphore, time_ms); if (ret == WAIT_OBJECT_0) { return true; } else { assert(ret == WAIT_TIMEOUT); return false; } #else # if defined(__MACH__) && defined(__APPLE__) mach_timespec_t wait_time; wait_time.tv_sec = time_ms / 1000; wait_time.tv_nsec = 1000000 * (time_ms % 1000); errno = 0; int ret = semaphore_timedwait(semaphore, wait_time); switch (ret) { case KERN_OPERATION_TIMED_OUT: errno = ETIMEDOUT; break; case KERN_ABORTED: errno = EINTR; break; default: if (ret) errno = EINVAL; } # else struct timespec wait_time; struct timeval now; if (gettimeofday(&now, NULL) == -1) { std::cerr << "Semaphore::wait(ms): Unable to get time with gettimeofday!" << std::endl; abort(); } wait_time.tv_nsec = ((time_ms % 1000) * 1000 * 1000) + (now.tv_usec * 1000); wait_time.tv_sec = (time_ms / 1000) + (wait_time.tv_nsec / (1000 * 1000 * 1000)) + now.tv_sec; wait_time.tv_nsec %= 1000 * 1000 * 1000; int ret = sem_timedwait(&semaphore, &wait_time); # endif assert(!ret || (errno == ETIMEDOUT || errno == EINTR)); return !ret; #endif }
pgimeno/minetest
src/threading/semaphore.cpp
C++
mit
3,684
/* Minetest Copyright (C) 2013 sapier <sapier AT gmx DOT net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #if defined(_WIN32) #include <windows.h> #elif defined(__MACH__) && defined(__APPLE__) #include <mach/semaphore.h> #else #include <semaphore.h> #endif #include "util/basic_macros.h" class Semaphore { public: Semaphore(int val = 0); ~Semaphore(); DISABLE_CLASS_COPY(Semaphore); void post(unsigned int num = 1); void wait(); bool wait(unsigned int time_ms); private: #if defined(WIN32) HANDLE semaphore; #elif defined(__MACH__) && defined(__APPLE__) semaphore_t semaphore; #else sem_t semaphore; #endif };
pgimeno/minetest
src/threading/semaphore.h
C++
mit
1,302
/* This file is a part of the JThread package, which contains some object- oriented thread wrappers for different thread implementations. Copyright (c) 2000-2006 Jori Liesenborgs (jori.liesenborgs@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "threading/thread.h" #include "threading/mutex_auto_lock.h" #include "log.h" #include "porting.h" // for setName #if defined(__linux__) #include <sys/prctl.h> #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) #include <pthread_np.h> #elif defined(_MSC_VER) struct THREADNAME_INFO { DWORD dwType; // Must be 0x1000 LPCSTR szName; // Pointer to name (in user addr space) DWORD dwThreadID; // Thread ID (-1=caller thread) DWORD dwFlags; // Reserved for future use, must be zero }; #endif // for bindToProcessor #if __FreeBSD_version >= 702106 typedef cpuset_t cpu_set_t; #elif defined(__sun) || defined(sun) #include <sys/types.h> #include <sys/processor.h> #include <sys/procset.h> #elif defined(_AIX) #include <sys/processor.h> #include <sys/thread.h> #elif defined(__APPLE__) #include <mach/mach_init.h> #include <mach/thread_act.h> #endif Thread::Thread(const std::string &name) : m_name(name), m_request_stop(false), m_running(false) { #ifdef _AIX m_kernel_thread_id = -1; #endif } Thread::~Thread() { kill(); // Make sure start finished mutex is unlocked before it's destroyed if (m_start_finished_mutex.try_lock()) m_start_finished_mutex.unlock(); } bool Thread::start() { MutexAutoLock lock(m_mutex); if (m_running) return false; m_request_stop = false; // The mutex may already be locked if the thread is being restarted m_start_finished_mutex.try_lock(); try { m_thread_obj = new std::thread(threadProc, this); } catch (const std::system_error &e) { return false; } // Allow spawned thread to continue m_start_finished_mutex.unlock(); while (!m_running) sleep_ms(1); m_joinable = true; return true; } bool Thread::stop() { m_request_stop = true; return true; } bool Thread::wait() { MutexAutoLock lock(m_mutex); if (!m_joinable) return false; m_thread_obj->join(); delete m_thread_obj; m_thread_obj = nullptr; assert(m_running == false); m_joinable = false; return true; } bool Thread::kill() { if (!m_running) { wait(); return false; } m_running = false; #if defined(_WIN32) // See https://msdn.microsoft.com/en-us/library/hh920601.aspx#thread__native_handle_method TerminateThread((HANDLE) m_thread_obj->native_handle(), 0); CloseHandle((HANDLE) m_thread_obj->native_handle()); #else // We need to pthread_kill instead on Android since NDKv5's pthread // implementation is incomplete. # ifdef __ANDROID__ pthread_kill(getThreadHandle(), SIGKILL); # else pthread_cancel(getThreadHandle()); # endif wait(); #endif m_retval = nullptr; m_joinable = false; m_request_stop = false; return true; } bool Thread::getReturnValue(void **ret) { if (m_running) return false; *ret = m_retval; return true; } void Thread::threadProc(Thread *thr) { #ifdef _AIX thr->m_kernel_thread_id = thread_self(); #endif thr->setName(thr->m_name); g_logger.registerThread(thr->m_name); thr->m_running = true; // Wait for the thread that started this one to finish initializing the // thread handle so that getThreadId/getThreadHandle will work. thr->m_start_finished_mutex.lock(); thr->m_retval = thr->run(); thr->m_running = false; // Unlock m_start_finished_mutex to prevent data race condition on Windows. // On Windows with VS2017 build TerminateThread is called and this mutex is not // released. We try to unlock it from caller thread and it's refused by system. thr->m_start_finished_mutex.unlock(); g_logger.deregisterThread(); } void Thread::setName(const std::string &name) { #if defined(__linux__) // It would be cleaner to do this with pthread_setname_np, // which was added to glibc in version 2.12, but some major // distributions are still runing 2.11 and previous versions. prctl(PR_SET_NAME, name.c_str()); #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) pthread_set_name_np(pthread_self(), name.c_str()); #elif defined(__NetBSD__) pthread_setname_np(pthread_self(), name.c_str()); #elif defined(__APPLE__) pthread_setname_np(name.c_str()); #elif defined(_MSC_VER) // Windows itself doesn't support thread names, // but the MSVC debugger does... THREADNAME_INFO info; info.dwType = 0x1000; info.szName = name.c_str(); info.dwThreadID = -1; info.dwFlags = 0; __try { RaiseException(0x406D1388, 0, sizeof(info) / sizeof(DWORD), (ULONG_PTR *)&info); } __except (EXCEPTION_CONTINUE_EXECUTION) { } #elif defined(_WIN32) || defined(__GNU__) // These platforms are known to not support thread names. // Silently ignore the request. #else #warning "Unrecognized platform, thread names will not be available." #endif } unsigned int Thread::getNumberOfProcessors() { return std::thread::hardware_concurrency(); } bool Thread::bindToProcessor(unsigned int proc_number) { #if defined(__ANDROID__) return false; #elif _MSC_VER return SetThreadAffinityMask(getThreadHandle(), 1 << proc_number); #elif __MINGW32__ return SetThreadAffinityMask(pthread_gethandle(getThreadHandle()), 1 << proc_number); #elif __FreeBSD_version >= 702106 || defined(__linux__) || defined(__DragonFly__) cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(proc_number, &cpuset); return pthread_setaffinity_np(getThreadHandle(), sizeof(cpuset), &cpuset) == 0; #elif defined(__sun) || defined(sun) return processor_bind(P_LWPID, P_MYID, proc_number, NULL) == 0 #elif defined(_AIX) return bindprocessor(BINDTHREAD, m_kernel_thread_id, proc_number) == 0; #elif defined(__hpux) || defined(hpux) pthread_spu_t answer; return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP, &answer, proc_number, getThreadHandle()) == 0; #elif defined(__APPLE__) struct thread_affinity_policy tapol; thread_port_t threadport = pthread_mach_thread_np(getThreadHandle()); tapol.affinity_tag = proc_number + 1; return thread_policy_set(threadport, THREAD_AFFINITY_POLICY, (thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS; #else return false; #endif } bool Thread::setPriority(int prio) { #ifdef _MSC_VER return SetThreadPriority(getThreadHandle(), prio); #elif __MINGW32__ return SetThreadPriority(pthread_gethandle(getThreadHandle()), prio); #else struct sched_param sparam; int policy; if (pthread_getschedparam(getThreadHandle(), &policy, &sparam) != 0) return false; int min = sched_get_priority_min(policy); int max = sched_get_priority_max(policy); sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST; return pthread_setschedparam(getThreadHandle(), policy, &sparam) == 0; #endif }
pgimeno/minetest
src/threading/thread.cpp
C++
mit
7,847