3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "irrlicht.h" // createDevice
21 #include "irrlichttypes_extrabloated.h"
22 #include "chat_interface.h"
24 #include "unittest/test.h"
28 #include "client/game.h"
29 #include "defaultsettings.h"
32 #include "quicktune.h"
33 #include "httpfetch.h"
34 #include "gameparams.h"
35 #include "database/database.h"
39 #include "network/socket.h"
41 #include "terminal_chat_console.h"
44 #include "gui/guiMainMenu.h"
45 #include "client/clientlauncher.h"
46 #include "gui/guiEngine.h"
47 #include "gui/mainmenumanager.h"
50 #ifdef HAVE_TOUCHSCREENGUI
51 #include "gui/touchscreengui.h"
54 #if !defined(SERVER) && \
55 (IRRLICHT_VERSION_MAJOR == 1) && \
56 (IRRLICHT_VERSION_MINOR == 8) && \
57 (IRRLICHT_VERSION_REVISION == 2)
58 #error "Irrlicht 1.8.2 is known to be broken - please update Irrlicht to version >= 1.8.3"
61 #define DEBUGFILE "debug.txt"
62 #define DEFAULT_SERVER_PORT 30000
64 typedef std::map<std::string, ValueSpec> OptionList;
66 /**********************************************************************
68 **********************************************************************/
70 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
71 static void set_allowed_options(OptionList *allowed_options);
73 static void print_help(const OptionList &allowed_options);
74 static void print_allowed_options(const OptionList &allowed_options);
75 static void print_version();
76 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
77 std::ostream &os, bool print_name = true, bool print_path = true);
78 static void print_modified_quicktune_values();
80 static void list_game_ids();
81 static void list_worlds(bool print_name, bool print_path);
82 static void setup_log_params(const Settings &cmd_args);
83 static bool create_userdata_path();
84 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
85 static void startup_message();
86 static bool read_config_file(const Settings &cmd_args);
87 static void init_log_streams(const Settings &cmd_args);
89 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
90 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
92 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
93 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
94 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
95 static bool auto_select_world(GameParams *game_params);
96 static std::string get_clean_world_path(const std::string &path);
98 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
99 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
100 static bool determine_subgame(GameParams *game_params);
102 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
103 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
105 /**********************************************************************/
108 FileLogOutput file_log_output;
110 static OptionList allowed_options;
112 int main(int argc, char *argv[])
115 debug_set_exception_handler();
117 g_logger.registerThread("Main");
118 g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
121 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
123 || cmd_args.getFlag("help")
124 || cmd_args.exists("nonopt1")) {
125 porting::attachOrCreateConsole();
126 print_help(allowed_options);
127 return cmd_args_ok ? 0 : 1;
129 if (cmd_args.getFlag("console"))
130 porting::attachOrCreateConsole();
132 if (cmd_args.getFlag("version")) {
133 porting::attachOrCreateConsole();
138 setup_log_params(cmd_args);
140 porting::signal_handler_init();
143 porting::initAndroid();
144 porting::initializePathsAndroid();
146 porting::initializePaths();
149 if (!create_userdata_path()) {
150 errorstream << "Cannot create user data directory" << std::endl;
155 BEGIN_DEBUG_EXCEPTION_HANDLER
157 // List gameids if requested
158 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
163 // List worlds, world names, and world paths if requested
164 if (cmd_args.exists("worldlist")) {
165 if (cmd_args.get("worldlist") == "name") {
166 list_worlds(true, false);
167 } else if (cmd_args.get("worldlist") == "path") {
168 list_worlds(false, true);
170 list_worlds(true, true);
175 if (!init_common(cmd_args, argc, argv))
178 if (g_settings->getBool("enable_console"))
179 porting::attachOrCreateConsole();
183 if (cmd_args.getFlag("run-unittests")) {
188 GameParams game_params;
190 porting::attachOrCreateConsole();
191 game_params.is_dedicated_server = true;
193 const bool isServer = cmd_args.getFlag("server");
195 porting::attachOrCreateConsole();
196 game_params.is_dedicated_server = isServer;
199 if (!game_configure(&game_params, cmd_args))
202 sanity_check(!game_params.world_path.empty());
204 infostream << "Using commanded world path ["
205 << game_params.world_path << "]" << std::endl;
207 if (game_params.is_dedicated_server)
208 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
211 ClientLauncher launcher;
212 retval = launcher.run(game_params, cmd_args) ? 0 : 1;
217 // Update configuration file
218 if (!g_settings_path.empty())
219 g_settings->updateConfigFile(g_settings_path.c_str());
221 print_modified_quicktune_values();
223 // Stop httpfetch thread (if started)
226 END_DEBUG_EXCEPTION_HANDLER
232 /*****************************************************************************
234 *****************************************************************************/
237 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
239 set_allowed_options(&allowed_options);
241 return cmd_args->parseCommandLine(argc, argv, allowed_options);
244 static void set_allowed_options(OptionList *allowed_options)
246 allowed_options->clear();
248 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
249 _("Show allowed options"))));
250 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
251 _("Show version information"))));
252 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
253 _("Load configuration from specified file"))));
254 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
255 _("Set network port (UDP)"))));
256 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
257 _("Run the unit tests and exit"))));
258 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
259 _("Same as --world (deprecated)"))));
260 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
261 _("Set world path (implies local game)"))));
262 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
263 _("Set world by name (implies local game)"))));
264 allowed_options->insert(std::make_pair("worldlist", ValueSpec(VALUETYPE_STRING,
265 _("Get list of worlds (implies local game) ('path' lists paths, "
266 "'name' lists names, 'both' lists both)"))));
267 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
268 _("Print to console errors only"))));
270 allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
271 _("Coloured logs ('always', 'never' or 'auto'), defaults to 'auto'"
274 allowed_options->insert(std::make_pair("color", ValueSpec(VALUETYPE_STRING,
275 _("Coloured logs ('always' or 'never'), defaults to 'never'"
278 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
279 _("Print more information to console"))));
280 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
281 _("Print even more information to console"))));
282 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
283 _("Print enormous amounts of information to log and console"))));
284 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
285 _("Set logfile path ('' = no logging)"))));
286 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
287 _("Set gameid (\"--gameid list\" prints available ones)"))));
288 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
289 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
290 allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
291 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
292 allowed_options->insert(std::make_pair("migrate-auth", ValueSpec(VALUETYPE_STRING,
293 _("Migrate from current auth backend to another (Only works when using minetestserver or with --server)"))));
294 allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
295 _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
297 allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
298 _("Show available video modes"))));
299 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
300 _("Run speed tests"))));
301 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
302 _("Address to connect to. ('' = local game)"))));
303 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
304 _("Enable random user input, for testing"))));
305 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
306 _("Run dedicated server"))));
307 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
308 _("Set player name"))));
309 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
310 _("Set password"))));
311 allowed_options->insert(std::make_pair("password-file", ValueSpec(VALUETYPE_STRING,
312 _("Set password from contents of file"))));
313 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
314 _("Disable main menu"))));
315 allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
316 _("Starts with the console (Windows only)"))));
321 static void print_help(const OptionList &allowed_options)
323 std::cout << _("Allowed options:") << std::endl;
324 print_allowed_options(allowed_options);
327 static void print_allowed_options(const OptionList &allowed_options)
329 for (const auto &allowed_option : allowed_options) {
330 std::ostringstream os1(std::ios::binary);
331 os1 << " --" << allowed_option.first;
332 if (allowed_option.second.type != VALUETYPE_FLAG)
333 os1 << _(" <value>");
335 std::cout << padStringRight(os1.str(), 30);
337 if (allowed_option.second.help)
338 std::cout << allowed_option.second.help;
340 std::cout << std::endl;
344 static void print_version()
346 std::cout << PROJECT_NAME_C " " << g_version_hash
347 << " (" << porting::getPlatformName() << ")" << std::endl;
349 std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl;
351 std::cout << g_build_info << std::endl;
354 static void list_game_ids()
356 std::set<std::string> gameids = getAvailableGameIds();
357 for (const std::string &gameid : gameids)
358 std::cout << gameid <<std::endl;
361 static void list_worlds(bool print_name, bool print_path)
363 std::cout << _("Available worlds:") << std::endl;
364 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
365 print_worldspecs(worldspecs, std::cout, print_name, print_path);
368 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
369 std::ostream &os, bool print_name, bool print_path)
371 for (const WorldSpec &worldspec : worldspecs) {
372 std::string name = worldspec.name;
373 std::string path = worldspec.path;
374 if (print_name && print_path) {
375 os << "\t" << name << "\t\t" << path << std::endl;
376 } else if (print_name) {
377 os << "\t" << name << std::endl;
378 } else if (print_path) {
379 os << "\t" << path << std::endl;
384 static void print_modified_quicktune_values()
386 bool header_printed = false;
387 std::vector<std::string> names = getQuicktuneNames();
389 for (const std::string &name : names) {
390 QuicktuneValue val = getQuicktuneValue(name);
393 if (!header_printed) {
394 dstream << "Modified quicktune values:" << std::endl;
395 header_printed = true;
397 dstream << name << " = " << val.getString() << std::endl;
401 static void setup_log_params(const Settings &cmd_args)
403 // Quiet mode, print errors only
404 if (cmd_args.getFlag("quiet")) {
405 g_logger.removeOutput(&stderr_output);
406 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
409 // Coloured log messages (see log.h)
410 if (cmd_args.exists("color")) {
411 std::string mode = cmd_args.get("color");
413 Logger::color_mode = LOG_COLOR_AUTO;
414 else if (mode == "always")
415 Logger::color_mode = LOG_COLOR_ALWAYS;
417 Logger::color_mode = LOG_COLOR_NEVER;
420 // If trace is enabled, enable logging of certain things
421 if (cmd_args.getFlag("trace")) {
422 dstream << _("Enabling trace level debug output") << std::endl;
423 g_logger.setTraceEnabled(true);
424 dout_con_ptr = &verbosestream; // This is somewhat old
425 socket_enable_debug_output = true; // Sockets doesn't use log.h
428 // In certain cases, output info level on stderr
429 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
430 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
431 g_logger.addOutput(&stderr_output, LL_INFO);
433 // In certain cases, output verbose level on stderr
434 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
435 g_logger.addOutput(&stderr_output, LL_VERBOSE);
438 static bool create_userdata_path()
443 if (!fs::PathExists(porting::path_user)) {
444 success = fs::CreateDir(porting::path_user);
448 porting::copyAssets();
450 // Create user data directory
451 success = fs::CreateDir(porting::path_user);
457 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
460 set_default_settings(g_settings);
462 // Initialize sockets
464 atexit(sockets_cleanup);
466 if (!read_config_file(cmd_args))
469 init_log_streams(cmd_args);
471 // Initialize random seed
475 // Initialize HTTP fetcher
476 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
478 init_gettext(porting::path_locale.c_str(),
479 g_settings->get("language"), argc, argv);
484 static void startup_message()
486 infostream << PROJECT_NAME << " " << _("with")
487 << " SER_FMT_VER_HIGHEST_READ="
488 << (int)SER_FMT_VER_HIGHEST_READ << ", "
489 << g_build_info << std::endl;
492 static bool read_config_file(const Settings &cmd_args)
494 // Path of configuration file in use
495 sanity_check(g_settings_path == ""); // Sanity check
497 if (cmd_args.exists("config")) {
498 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
500 errorstream << "Could not read configuration from \""
501 << cmd_args.get("config") << "\"" << std::endl;
504 g_settings_path = cmd_args.get("config");
506 std::vector<std::string> filenames;
507 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
508 // Legacy configuration file location
509 filenames.push_back(porting::path_user +
510 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
513 // Try also from a lower level (to aid having the same configuration
514 // for many RUN_IN_PLACE installs)
515 filenames.push_back(porting::path_user +
516 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
519 for (const std::string &filename : filenames) {
520 bool r = g_settings->readConfigFile(filename.c_str());
522 g_settings_path = filename;
527 // If no path found, use the first one (menu creates the file)
528 if (g_settings_path.empty())
529 g_settings_path = filenames[0];
535 static void init_log_streams(const Settings &cmd_args)
537 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
539 if (cmd_args.exists("logfile"))
540 log_filename = cmd_args.get("logfile");
542 g_logger.removeOutput(&file_log_output);
543 std::string conf_loglev = g_settings->get("debug_log_level");
545 // Old integer format
546 if (std::isdigit(conf_loglev[0])) {
547 warningstream << "Deprecated use of debug_log_level with an "
548 "integer value; please update your configuration." << std::endl;
549 static const char *lev_name[] =
550 {"", "error", "action", "info", "verbose"};
551 int lev_i = atoi(conf_loglev.c_str());
552 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
553 warningstream << "Supplied invalid debug_log_level!"
554 " Assuming action level." << std::endl;
557 conf_loglev = lev_name[lev_i];
560 if (log_filename.empty() || conf_loglev.empty()) // No logging
563 LogLevel log_level = Logger::stringToLevel(conf_loglev);
564 if (log_level == LL_MAX) {
565 warningstream << "Supplied unrecognized debug_log_level; "
566 "using maximum." << std::endl;
569 verbosestream << "log_filename = " << log_filename << std::endl;
571 file_log_output.open(log_filename);
572 g_logger.addOutputMaxLevel(&file_log_output, log_level);
575 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
577 game_configure_port(game_params, cmd_args);
579 if (!game_configure_world(game_params, cmd_args)) {
580 errorstream << "No world path specified or found." << std::endl;
584 game_configure_subgame(game_params, cmd_args);
589 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
591 if (cmd_args.exists("port"))
592 game_params->socket_port = cmd_args.getU16("port");
594 game_params->socket_port = g_settings->getU16("port");
596 if (game_params->socket_port == 0)
597 game_params->socket_port = DEFAULT_SERVER_PORT;
600 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
602 if (get_world_from_cmdline(game_params, cmd_args))
605 if (get_world_from_config(game_params, cmd_args))
608 return auto_select_world(game_params);
611 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
613 std::string commanded_world;
616 std::string commanded_worldname;
617 if (cmd_args.exists("worldname"))
618 commanded_worldname = cmd_args.get("worldname");
620 // If a world name was specified, convert it to a path
621 if (!commanded_worldname.empty()) {
622 // Get information about available worlds
623 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
625 for (const WorldSpec &worldspec : worldspecs) {
626 std::string name = worldspec.name;
627 if (name == commanded_worldname) {
628 dstream << _("Using world specified by --worldname on the "
629 "command line") << std::endl;
630 commanded_world = worldspec.path;
636 dstream << _("World") << " '" << commanded_worldname
637 << _("' not available. Available worlds:") << std::endl;
638 print_worldspecs(worldspecs, dstream);
642 game_params->world_path = get_clean_world_path(commanded_world);
643 return !commanded_world.empty();
646 if (cmd_args.exists("world"))
647 commanded_world = cmd_args.get("world");
648 else if (cmd_args.exists("map-dir"))
649 commanded_world = cmd_args.get("map-dir");
650 else if (cmd_args.exists("nonopt0")) // First nameless argument
651 commanded_world = cmd_args.get("nonopt0");
653 game_params->world_path = get_clean_world_path(commanded_world);
654 return !commanded_world.empty();
657 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
660 std::string commanded_world;
662 if (g_settings->exists("map-dir"))
663 commanded_world = g_settings->get("map-dir");
665 game_params->world_path = get_clean_world_path(commanded_world);
667 return !commanded_world.empty();
670 static bool auto_select_world(GameParams *game_params)
672 // No world was specified; try to select it automatically
673 // Get information about available worlds
675 verbosestream << _("Determining world path") << std::endl;
677 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
678 std::string world_path;
680 // If there is only a single world, use it
681 if (worldspecs.size() == 1) {
682 world_path = worldspecs[0].path;
683 dstream <<_("Automatically selecting world at") << " ["
684 << world_path << "]" << std::endl;
685 // If there are multiple worlds, list them
686 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
687 std::cerr << _("Multiple worlds are available.") << std::endl;
688 std::cerr << _("Please select one using --worldname <name>"
689 " or --world <path>") << std::endl;
690 print_worldspecs(worldspecs, std::cerr);
692 // If there are no worlds, automatically create a new one
694 // This is the ultimate default world path
695 world_path = porting::path_user + DIR_DELIM + "worlds" +
697 infostream << "Creating default world at ["
698 << world_path << "]" << std::endl;
701 assert(world_path != ""); // Post-condition
702 game_params->world_path = world_path;
706 static std::string get_clean_world_path(const std::string &path)
708 const std::string worldmt = "world.mt";
709 std::string clean_path;
711 if (path.size() > worldmt.size()
712 && path.substr(path.size() - worldmt.size()) == worldmt) {
713 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
714 clean_path = path.substr(0, path.size() - worldmt.size());
722 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
726 success = get_game_from_cmdline(game_params, cmd_args);
728 success = determine_subgame(game_params);
733 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
735 SubgameSpec commanded_gamespec;
737 if (cmd_args.exists("gameid")) {
738 std::string gameid = cmd_args.get("gameid");
739 commanded_gamespec = findSubgame(gameid);
740 if (!commanded_gamespec.isValid()) {
741 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
744 dstream << _("Using game specified by --gameid on the command line")
746 game_params->game_spec = commanded_gamespec;
753 static bool determine_subgame(GameParams *game_params)
755 SubgameSpec gamespec;
757 assert(game_params->world_path != ""); // Pre-condition
759 verbosestream << _("Determining gameid/gamespec") << std::endl;
760 // If world doesn't exist
761 if (!game_params->world_path.empty()
762 && !getWorldExists(game_params->world_path)) {
763 // Try to take gamespec from command line
764 if (game_params->game_spec.isValid()) {
765 gamespec = game_params->game_spec;
766 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
767 } else { // Otherwise we will be using "minetest"
768 gamespec = findSubgame(g_settings->get("default_game"));
769 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
770 if (!gamespec.isValid()) {
771 errorstream << "Subgame specified in default_game ["
772 << g_settings->get("default_game")
773 << "] is invalid." << std::endl;
777 } else { // World exists
778 std::string world_gameid = getWorldGameId(game_params->world_path, false);
779 // If commanded to use a gameid, do so
780 if (game_params->game_spec.isValid()) {
781 gamespec = game_params->game_spec;
782 if (game_params->game_spec.id != world_gameid) {
783 warningstream << "Using commanded gameid ["
784 << gamespec.id << "]" << " instead of world gameid ["
785 << world_gameid << "]" << std::endl;
788 // If world contains an embedded game, use it;
789 // Otherwise find world from local system.
790 gamespec = findWorldSubgame(game_params->world_path);
791 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
795 if (!gamespec.isValid()) {
796 errorstream << "Subgame [" << gamespec.id << "] could not be found."
801 game_params->game_spec = gamespec;
806 /*****************************************************************************
808 *****************************************************************************/
809 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
811 verbosestream << _("Using world path") << " ["
812 << game_params.world_path << "]" << std::endl;
813 verbosestream << _("Using gameid") << " ["
814 << game_params.game_spec.id << "]" << std::endl;
817 std::string bind_str = g_settings->get("bind_address");
818 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
820 if (g_settings->getBool("ipv6_server")) {
821 bind_addr.setAddress((IPv6AddressBytes*) NULL);
824 bind_addr.Resolve(bind_str.c_str());
825 } catch (ResolveError &e) {
826 infostream << "Resolving bind address \"" << bind_str
827 << "\" failed: " << e.what()
828 << " -- Listening on all addresses." << std::endl;
830 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
831 errorstream << "Unable to listen on "
832 << bind_addr.serializeString()
833 << L" because IPv6 is disabled" << std::endl;
837 // Database migration
838 if (cmd_args.exists("migrate"))
839 return migrate_map_database(game_params, cmd_args);
841 if (cmd_args.exists("migrate-players"))
842 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
844 if (cmd_args.exists("migrate-auth"))
845 return ServerEnvironment::migrateAuthDatabase(game_params, cmd_args);
847 if (cmd_args.exists("terminal")) {
850 std::string admin_nick = g_settings->get("name");
852 name_ok = name_ok && !admin_nick.empty();
853 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
856 if (admin_nick.empty()) {
857 errorstream << "No name given for admin. "
858 << "Please check your minetest.conf that it "
859 << "contains a 'name = ' to your main admin account."
862 errorstream << "Name for admin '"
863 << admin_nick << "' is not valid. "
864 << "Please check that it only contains allowed characters. "
865 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
871 bool &kill = *porting::signal_handler_killstatus();
875 Server server(game_params.world_path, game_params.game_spec,
876 false, bind_addr, true, &iface);
879 g_term_console.setup(&iface, &kill, admin_nick);
881 g_term_console.start();
885 dedicated_server_loop(server, kill);
886 } catch (const ModError &e) {
887 g_term_console.stopAndWaitforThread();
888 errorstream << "ModError: " << e.what() << std::endl;
890 } catch (const ServerError &e) {
891 g_term_console.stopAndWaitforThread();
892 errorstream << "ServerError: " << e.what() << std::endl;
896 // Tell the console to stop, and wait for it to finish,
897 // only then leave context and free iface
898 g_term_console.stop();
899 g_term_console.wait();
901 g_term_console.clearKillStatus();
904 errorstream << "Cmd arg --terminal passed, but "
905 << "compiled without ncurses. Ignoring." << std::endl;
910 Server server(game_params.world_path, game_params.game_spec, false,
916 bool &kill = *porting::signal_handler_killstatus();
917 dedicated_server_loop(server, kill);
919 } catch (const ModError &e) {
920 errorstream << "ModError: " << e.what() << std::endl;
922 } catch (const ServerError &e) {
923 errorstream << "ServerError: " << e.what() << std::endl;
931 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
933 std::string migrate_to = cmd_args.get("migrate");
935 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
936 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
937 errorstream << "Cannot read world.mt!" << std::endl;
941 if (!world_mt.exists("backend")) {
942 errorstream << "Please specify your current backend in world.mt:"
944 << " backend = {sqlite3|leveldb|redis|dummy|postgresql}"
949 std::string backend = world_mt.get("backend");
950 if (backend == migrate_to) {
951 errorstream << "Cannot migrate: new backend is same"
952 << " as the old one" << std::endl;
956 MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
957 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
960 time_t last_update_time = 0;
961 bool &kill = *porting::signal_handler_killstatus();
963 std::vector<v3s16> blocks;
964 old_db->listAllLoadableBlocks(blocks);
966 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
967 if (kill) return false;
970 old_db->loadBlock(*it, &data);
972 new_db->saveBlock(*it, data);
974 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
976 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
977 std::cerr << " Migrated " << count << " blocks, "
978 << (100.0 * count / blocks.size()) << "% completed.\r";
981 last_update_time = time(NULL);
984 std::cerr << std::endl;
989 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
990 world_mt.set("backend", migrate_to);
991 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
992 errorstream << "Failed to update world.mt!" << std::endl;
994 actionstream << "world.mt updated" << std::endl;