/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola 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. */ // This would get rid of the console window //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup") #include "irrlicht.h" // createDevice #include "mainmenumanager.h" #include "irrlichttypes_extrabloated.h" #include "debug.h" #include "unittest/test.h" #include "server.h" #include "filesys.h" #include "version.h" #include "guiMainMenu.h" #include "game.h" #include "defaultsettings.h" #include "gettext.h" #include "log.h" #include "quicktune.h" #include "httpfetch.h" #include "guiEngine.h" #include "map.h" #include "player.h" #include "mapsector.h" #include "fontengine.h" #include "gameparams.h" #include "database.h" #include "config.h" #if USE_CURSES #include "terminal_chat_console.h" #endif #ifndef SERVER #include "client/clientlauncher.h" #endif #ifdef HAVE_TOUCHSCREENGUI #include "touchscreengui.h" #endif #if !defined(SERVER) && \ (IRRLICHT_VERSION_MAJOR == 1) && \ (IRRLICHT_VERSION_MINOR == 8) && \ (IRRLICHT_VERSION_REVISION == 2) #error "Irrlicht 1.8.2 is known to be broken - please update Irrlicht to version >= 1.8.3" #endif #define DEBUGFILE "debug.txt" #define DEFAULT_SERVER_PORT 30000 typedef std::map OptionList; /********************************************************************** * Private functions **********************************************************************/ static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args); static void set_allowed_options(OptionList *allowed_options); static void print_help(const OptionList &allowed_options); static void print_allowed_options(const OptionList &allowed_options); static void print_version(); static void print_worldspecs(const std::vector &worldspecs, std::ostream &os); static void print_modified_quicktune_values(); static void list_game_ids(); static void list_worlds(); static void setup_log_params(const Settings &cmd_args); static bool create_userdata_path(); static bool init_common(const Settings &cmd_args, int argc, char *argv[]); static void startup_message(); static bool read_config_file(const Settings &cmd_args); static void init_log_streams(const Settings &cmd_args); static bool game_configure(GameParams *game_params, const Settings &cmd_args); static void game_configure_port(GameParams *game_params, const Settings &cmd_args); static bool game_configure_world(GameParams *game_params, const Settings &cmd_args); static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args); static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args); static bool auto_select_world(GameParams *game_params); static std::string get_clean_world_path(const std::string &path); static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args); static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args); static bool determine_subgame(GameParams *game_params); static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args); static bool migrate_database(const GameParams &game_params, const Settings &cmd_args); /**********************************************************************/ /* gettime.h implementation */ #ifdef SERVER u32 getTimeMs() { /* Use imprecise system calls directly (from porting.h) */ return porting::getTime(PRECISION_MILLI); } u32 getTime(TimePrecision prec) { return porting::getTime(prec); } #endif FileLogOutput file_log_output; static OptionList allowed_options; int main(int argc, char *argv[]) { int retval; debug_set_exception_handler(); g_logger.registerThread("Main"); g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION); Settings cmd_args; bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args); if (!cmd_args_ok || cmd_args.getFlag("help") || cmd_args.exists("nonopt1")) { print_help(allowed_options); return cmd_args_ok ? 0 : 1; } if (cmd_args.getFlag("version")) { print_version(); return 0; } setup_log_params(cmd_args); porting::signal_handler_init(); #ifdef __ANDROID__ porting::initAndroid(); porting::initializePathsAndroid(); #else porting::initializePaths(); #endif if (!create_userdata_path()) { errorstream << "Cannot create user data directory" << std::endl; return 1; } // Initialize debug stacks DSTACK(FUNCTION_NAME); // Debug handler BEGIN_DEBUG_EXCEPTION_HANDLER // List gameids if requested if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") { list_game_ids(); return 0; } // List worlds if requested if (cmd_args.exists("world") && cmd_args.get("world") == "list") { list_worlds(); return 0; } if (!init_common(cmd_args, argc, argv)) return 1; #ifndef __ANDROID__ // Run unit tests if (cmd_args.getFlag("run-unittests")) { return run_tests(); } #endif GameParams game_params; #ifdef SERVER game_params.is_dedicated_server = true; #else game_params.is_dedicated_server = cmd_args.getFlag("server"); #endif if (!game_configure(&game_params, cmd_args)) return 1; sanity_check(!game_params.world_path.empty()); infostream << "Using commanded world path [" << game_params.world_path << "]" << std::endl; if (game_params.is_dedicated_server) return run_dedicated_server(game_params, cmd_args) ? 0 : 1; #ifndef SERVER ClientLauncher launcher; retval = launcher.run(game_params, cmd_args) ? 0 : 1; #else retval = 0; #endif // Update configuration file if (g_settings_path != "") g_settings->updateConfigFile(g_settings_path.c_str()); print_modified_quicktune_values(); // Stop httpfetch thread (if started) httpfetch_cleanup(); END_DEBUG_EXCEPTION_HANDLER return retval; } /***************************************************************************** * Startup / Init *****************************************************************************/ static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args) { set_allowed_options(&allowed_options); return cmd_args->parseCommandLine(argc, argv, allowed_options); } static void set_allowed_options(OptionList *allowed_options) { allowed_options->clear(); allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG, _("Show allowed options")))); allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG, _("Show version information")))); allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING, _("Load configuration from specified file")))); allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING, _("Set network port (UDP)")))); allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG, _("Run the unit tests and exit")))); allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING, _("Same as --world (deprecated)")))); allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING, _("Set world path (implies local game) ('list' lists all)")))); allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING, _("Set world by name (implies local game)")))); allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG, _("Print to console errors only")))); allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG, _("Print/* 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 "environment.h" #include <ISceneManager.h> #include "clientobject.h" #include "util/numeric.h" #include "activeobjectmgr.h" class ClientSimpleObject; class ClientMap; class ClientScripting; class ClientActiveObject; class GenericCAO; class LocalPlayer; /* The client-side environment. This is not thread-safe. Must be called from main (irrlicht) thread (uses the SceneManager) Client uses an environment mutex. */ enum ClientEnvEventType { CEE_NONE, CEE_PLAYER_DAMAGE }; struct ClientEnvEvent { ClientEnvEventType type; union { //struct{ //} none; struct{ u16 amount; bool send_to_server; } player_damage; }; }; typedef std::unordered_map<u16, ClientActiveObject*> ClientActiveObjectMap; class ClientEnvironment : public Environment { public: ClientEnvironment(ClientMap *map, ITextureSource *texturesource, Client *client); ~ClientEnvironment(); Map & getMap(); ClientMap & getClientMap(); Client *getGameDef() { return m_client; } void setScript(ClientScripting *script) { m_script = script; } void step(f32 dtime); virtual void setLocalPlayer(LocalPlayer *player); LocalPlayer *getLocalPlayer() const { return m_local_player; } /* ClientSimpleObjects */ void addSimpleObject(ClientSimpleObject *simple); /* ActiveObjects */ GenericCAO* getGenericCAO(u16 id); ClientActiveObject* getActiveObject(u16 id) { return m_ao_manager.getActiveObject(id); } /* Adds 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(ClientActiveObject *object); void addActiveObject(u16 id, u8 type, const std::string &init_data); void removeActiveObject(u16 id); void processActiveObjectMessage(u16 id, const std::string &data); /* Callbacks for activeobjects */ void damageLocalPlayer(u16 damage, bool handle_hp=true); /* Client likes to call these */ // Get all nearby objects void getActiveObjects(const v3f &origin, f32 max_d, std::vector<DistanceSortedActiveObject> &dest) { return m_ao_manager.getActiveObjects(origin, max_d, dest); } bool hasClientEnvEvents() const { return !m_client_event_queue.empty(); } // Get event from queue. If queue is empty, it triggers an assertion failure. ClientEnvEvent getClientEnvEvent(); virtual void getSelectedActiveObjects( const core::line3d<f32> &shootline_on_map, std::vector<PointedThing> &objects ); const std::list<std::string> &getPlayerNames() { return m_player_names; } void addPlayerName(const std::string &name) { m_player_names.push_back(name); } void removePlayerName(const std::string &name) { m_player_names.remove(name); } void updateCameraOffset(const v3s16 &camera_offset) { m_camera_offset = camera_offset; } v3s16 getCameraOffset() const { return m_camera_offset; } private: ClientMap *m_map; LocalPlayer *m_local_player = nullptr; ITextureSource *m_texturesource; Client *m_client; ClientScripting *m_script = nullptr; client::ActiveObjectMgr m_ao_manager; std::vector<ClientSimpleObject*> m_simple_objects; std::queue<ClientEnvEvent> m_client_event_queue; IntervalLimiter m_active_object_light_update_interval; std::list<std::string> m_player_names; v3s16 m_camera_offset; }; e_params->world_path)) { // Try to take gamespec from command line if (game_params->game_spec.isValid()) { gamespec = game_params->game_spec; infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl; } else { // Otherwise we will be using "minetest" gamespec = findSubgame(g_settings->get("default_game")); infostream << "Using default gameid [" << gamespec.id << "]" << std::endl; if (!gamespec.isValid()) { errorstream << "Subgame specified in default_game [" << g_settings->get("default_game") << "] is invalid." << std::endl; return false; } } } else { // World exists std::string world_gameid = getWorldGameId(game_params->world_path, false); // If commanded to use a gameid, do so if (game_params->game_spec.isValid()) { gamespec = game_params->game_spec; if (game_params->game_spec.id != world_gameid) { warningstream << "Using commanded gameid [" << gamespec.id << "]" << " instead of world gameid [" << world_gameid << "]" << std::endl; } } else { // If world contains an embedded game, use it; // Otherwise find world from local system. gamespec = findWorldSubgame(game_params->world_path); infostream << "Using world gameid [" << gamespec.id << "]" << std::endl; } } if (!gamespec.isValid()) { errorstream << "Subgame [" << gamespec.id << "] could not be found." << std::endl; return false; } game_params->game_spec = gamespec; return true; } /***************************************************************************** * Dedicated server *****************************************************************************/ static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args) { DSTACK("Dedicated server branch"); verbosestream << _("Using world path") << " [" << game_params.world_path << "]" << std::endl; verbosestream << _("Using gameid") << " [" << game_params.game_spec.id << "]" << std::endl; // Bind address std::string bind_str = g_settings->get("bind_address"); Address bind_addr(0, 0, 0, 0, game_params.socket_port); if (g_settings->getBool("ipv6_server")) { bind_addr.setAddress((IPv6AddressBytes*) NULL); } try { bind_addr.Resolve(bind_str.c_str()); } catch (ResolveError &e) { infostream << "Resolving bind address \"" << bind_str << "\" failed: " << e.what() << " -- Listening on all addresses." << std::endl; } if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) { errorstream << "Unable to listen on " << bind_addr.serializeString() << L" because IPv6 is disabled" << std::endl; return false; } // Database migration if (cmd_args.exists("migrate")) return migrate_database(game_params, cmd_args); if (cmd_args.exists("terminal")) { #if USE_CURSES bool name_ok = true; std::string admin_nick = g_settings->get("name"); name_ok = name_ok && !admin_nick.empty(); name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS); if (!name_ok) { if (admin_nick.empty()) { errorstream << "No name given for admin. " << "Please check your minetest.conf that it " << "contains a 'name = ' to your main admin account." << std::endl; } else { errorstream << "Name for admin '" << admin_nick << "' is not valid. " << "Please check that it only contains allowed characters. " << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL << std::endl; } return false; } ChatInterface iface; bool &kill = *porting::signal_handler_killstatus(); try { // Create server Server server(game_params.world_path, game_params.game_spec, false, bind_addr.isIPv6(), true, &iface); g_term_console.setup(&iface, &kill, admin_nick); g_term_console.start(); server.start(bind_addr); // Run server dedicated_server_loop(server, kill); } catch (const ModError &e) { g_term_console.stopAndWaitforThread(); errorstream << "ModError: " << e.what() << std::endl; return false; } catch (const ServerError &e) { g_term_console.stopAndWaitforThread(); errorstream << "ServerError: " << e.what() << std::endl; return false; } // Tell the console to stop, and wait for it to finish, // only then leave context and free iface g_term_console.stop(); g_term_console.wait(); g_term_console.clearKillStatus(); } else { #else errorstream << "Cmd arg --terminal passed, but " << "compiled without ncurses. Ignoring." << std::endl; } { #endif try { // Create server Server server(game_params.world_path, game_params.game_spec, false, bind_addr.isIPv6(), true); server.start(bind_addr); // Run server bool &kill = *porting::signal_handler_killstatus(); dedicated_server_loop(server, kill); } catch (const ModError &e) { errorstream << "ModError: " << e.what() << std::endl; return false; } catch (const ServerError &e) { errorstream << "ServerError: " << e.what() << std::endl; return false; } } return true; } static bool migrate_database(const GameParams &game_params, const Settings &cmd_args) { std::string migrate_to = cmd_args.get("migrate"); 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("backend")) { errorstream << "Please specify your current backend in world.mt:" << std::endl << " backend = {sqlite3|leveldb|redis|dummy}" << std::endl; return false; } std::string backend = world_mt.get("backend"); if (backend == migrate_to) { errorstream << "Cannot migrate: new backend is same" << " as the old one" << std::endl; return false; } Database *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt), *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt); u32 count = 0; time_t last_update_time = 0; bool &kill = *porting::signal_handler_killstatus(); std::vector blocks; old_db->listAllLoadableBlocks(blocks); new_db->beginSave(); for (std::vector::const_iterator it = blocks.begin(); it != blocks.end(); ++it) { if (kill) return false; std::string data; old_db->loadBlock(*it, &data); if (!data.empty()) { new_db->saveBlock(*it, data); } else { errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl; } if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) { std::cerr << " Migrated " << count << " blocks, " << (100.0 * count / blocks.size()) << "% completed.\r"; new_db->endSave(); new_db->beginSave(); last_update_time = time(NULL); } } std::cerr << std::endl; new_db->endSave(); delete old_db; delete new_db; actionstream << "Successfully migrated " << count << " blocks" << std::endl; world_mt.set("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; return true; }