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.
21 #ifndef SERVER // Dedicated server isn't linked with Irrlicht
22 #pragma comment(lib, "Irrlicht.lib")
23 // This would get rid of the console window
24 //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
26 #pragma comment(lib, "zlibwapi.lib")
27 #pragma comment(lib, "Shell32.lib")
30 #include "irrlicht.h" // createDevice
33 #include "mainmenumanager.h"
34 #include "irrlichttypes_extrabloated.h"
40 #include "guiMainMenu.h"
42 #include "defaultsettings.h"
46 #include "quicktune.h"
47 #include "httpfetch.h"
48 #include "guiEngine.h"
50 #include "mapsector.h"
51 #include "fontengine.h"
52 #include "gameparams.h"
55 #include "client/clientlauncher.h"
58 #ifdef HAVE_TOUCHSCREENGUI
59 #include "touchscreengui.h"
64 These are loaded from the config file.
66 static Settings main_settings;
67 Settings *g_settings = &main_settings;
68 std::string g_settings_path;
71 Profiler main_profiler;
72 Profiler *g_profiler = &main_profiler;
74 // Menu clouds are created later
75 Clouds *g_menuclouds = 0;
76 irr::scene::ISceneManager *g_menucloudsmgr = 0;
83 std::ostream *dout_con_ptr = &dummyout;
84 std::ostream *derr_con_ptr = &verbosestream;
87 std::ostream *dout_server_ptr = &infostream;
88 std::ostream *derr_server_ptr = &errorstream;
91 std::ostream *dout_client_ptr = &infostream;
92 std::ostream *derr_client_ptr = &errorstream;
94 #define DEBUGFILE "debug.txt"
95 #define DEFAULT_SERVER_PORT 30000
97 typedef std::map<std::string, ValueSpec> OptionList;
99 /**********************************************************************
101 **********************************************************************/
103 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
104 static void set_allowed_options(OptionList *allowed_options);
106 static void print_help(const OptionList &allowed_options);
107 static void print_allowed_options(const OptionList &allowed_options);
108 static void print_version();
109 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
111 static void print_modified_quicktune_values();
113 static void list_game_ids();
114 static void list_worlds();
115 static void setup_log_params(const Settings &cmd_args);
116 static bool create_userdata_path();
117 static bool init_common(int *log_level, const Settings &cmd_args, int argc, char *argv[]);
118 static void startup_message();
119 static bool read_config_file(const Settings &cmd_args);
120 static void init_debug_streams(int *log_level, const Settings &cmd_args);
122 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
123 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
125 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
126 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
127 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
128 static bool auto_select_world(GameParams *game_params);
129 static std::string get_clean_world_path(const std::string &path);
131 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
132 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
133 static bool determine_subgame(GameParams *game_params);
135 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
136 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args);
138 /**********************************************************************/
145 /* mainmenumanager.h */
147 gui::IGUIEnvironment* guienv = NULL;
148 gui::IGUIStaticText *guiroot = NULL;
149 MainMenuManager g_menumgr;
153 return (g_menumgr.menuCount() == 0);
156 // Passed to menus to allow disconnecting and exiting
157 MainGameCallback *g_gamecallback = NULL;
161 gettime.h implementation
168 /* Use imprecise system calls directly (from porting.h) */
169 return porting::getTime(PRECISION_MILLI);
172 u32 getTime(TimePrecision prec)
174 return porting::getTime(prec);
179 class StderrLogOutput: public ILogOutput
182 /* line: Full line with timestamp, level and thread */
183 void printLog(const std::string &line)
185 std::cerr << line << std::endl;
187 } main_stderr_log_out;
189 class DstreamNoStderrLogOutput: public ILogOutput
192 /* line: Full line with timestamp, level and thread */
193 void printLog(const std::string &line)
195 dstream_no_stderr << line << std::endl;
197 } main_dstream_no_stderr_log_out;
199 static OptionList allowed_options;
201 int main(int argc, char *argv[])
205 debug_set_exception_handler();
207 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
208 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
210 log_register_thread("main");
213 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
215 || cmd_args.getFlag("help")
216 || cmd_args.exists("nonopt1")) {
217 print_help(allowed_options);
218 return cmd_args_ok ? 0 : 1;
221 if (cmd_args.getFlag("version")) {
226 setup_log_params(cmd_args);
228 porting::signal_handler_init();
229 porting::initializePaths();
231 if (!create_userdata_path()) {
232 errorstream << "Cannot create user data directory" << std::endl;
236 // Initialize debug stacks
238 DSTACK(__FUNCTION_NAME);
241 BEGIN_DEBUG_EXCEPTION_HANDLER
243 // List gameids if requested
244 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
249 // List worlds if requested
250 if (cmd_args.exists("world") && cmd_args.get("world") == "list") {
255 GameParams game_params;
256 if (!init_common(&game_params.log_level, cmd_args, argc, argv))
261 if (cmd_args.getFlag("run-unittests")) {
268 game_params.is_dedicated_server = true;
270 game_params.is_dedicated_server = cmd_args.getFlag("server");
273 if (!game_configure(&game_params, cmd_args))
276 sanity_check(game_params.world_path != "");
278 infostream << "Using commanded world path ["
279 << game_params.world_path << "]" << std::endl;
281 //Run dedicated server if asked to or no other option
282 g_settings->set("server_dedicated",
283 game_params.is_dedicated_server ? "true" : "false");
285 if (game_params.is_dedicated_server)
286 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
289 ClientLauncher launcher;
290 retval = launcher.run(game_params, cmd_args) ? 0 : 1;
295 // Update configuration file
296 if (g_settings_path != "")
297 g_settings->updateConfigFile(g_settings_path.c_str());
299 print_modified_quicktune_values();
301 // Stop httpfetch thread (if started)
304 END_DEBUG_EXCEPTION_HANDLER(errorstream)
310 /*****************************************************************************
312 *****************************************************************************/
315 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
317 set_allowed_options(&allowed_options);
319 return cmd_args->parseCommandLine(argc, argv, allowed_options);
322 static void set_allowed_options(OptionList *allowed_options)
324 allowed_options->clear();
326 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
327 _("Show allowed options"))));
328 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
329 _("Show version information"))));
330 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
331 _("Load configuration from specified file"))));
332 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
333 _("Set network port (UDP)"))));
334 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
335 _("Run the unit tests and exit"))));
336 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
337 _("Same as --world (deprecated)"))));
338 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
339 _("Set world path (implies local game) ('list' lists all)"))));
340 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
341 _("Set world by name (implies local game)"))));
342 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
343 _("Print to console errors only"))));
344 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
345 _("Print more information to console"))));
346 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
347 _("Print even more information to console"))));
348 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
349 _("Print enormous amounts of information to log and console"))));
350 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
351 _("Set logfile path ('' = no logging)"))));
352 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
353 _("Set gameid (\"--gameid list\" prints available ones)"))));
354 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
355 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
357 allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
358 _("Show available video modes"))));
359 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
360 _("Run speed tests"))));
361 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
362 _("Address to connect to. ('' = local game)"))));
363 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
364 _("Enable random user input, for testing"))));
365 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
366 _("Run dedicated server"))));
367 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
368 _("Set player name"))));
369 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
370 _("Set password"))));
371 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
372 _("Disable main menu"))));
377 static void print_help(const OptionList &allowed_options)
379 dstream << _("Allowed options:") << std::endl;
380 print_allowed_options(allowed_options);
383 static void print_allowed_options(const OptionList &allowed_options)
385 for (OptionList::const_iterator i = allowed_options.begin();
386 i != allowed_options.end(); ++i) {
387 std::ostringstream os1(std::ios::binary);
388 os1 << " --" << i->first;
389 if (i->second.type != VALUETYPE_FLAG)
390 os1 << _(" <value>");
392 dstream << padStringRight(os1.str(), 24);
394 if (i->second.help != NULL)
395 dstream << i->second.help;
397 dstream << std::endl;
401 static void print_version()
403 dstream << PROJECT_NAME " " << g_version_hash << std::endl;
405 dstream << "Using Irrlicht " << IRRLICHT_SDK_VERSION << std::endl;
407 dstream << "Build info: " << g_build_info << std::endl;
410 static void list_game_ids()
412 std::set<std::string> gameids = getAvailableGameIds();
413 for (std::set<std::string>::const_iterator i = gameids.begin();
414 i != gameids.end(); i++)
415 dstream << (*i) <<std::endl;
418 static void list_worlds()
420 dstream << _("Available worlds:") << std::endl;
421 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
422 print_worldspecs(worldspecs, dstream);
425 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
428 for (size_t i = 0; i < worldspecs.size(); i++) {
429 std::string name = worldspecs[i].name;
430 std::string path = worldspecs[i].path;
431 if (name.find(" ") != std::string::npos)
432 name = std::string("'") + name + "'";
433 path = std::string("'") + path + "'";
434 name = padStringRight(name, 14);
435 os << " " << name << " " << path << std::endl;
439 static void print_modified_quicktune_values()
441 bool header_printed = false;
442 std::vector<std::string> names = getQuicktuneNames();
444 for (u32 i = 0; i < names.size(); i++) {
445 QuicktuneValue val = getQuicktuneValue(names[i]);
448 if (!header_printed) {
449 dstream << "Modified quicktune values:" << std::endl;
450 header_printed = true;
452 dstream << names[i] << " = " << val.getString() << std::endl;
456 static void setup_log_params(const Settings &cmd_args)
458 // Quiet mode, print errors only
459 if (cmd_args.getFlag("quiet")) {
460 log_remove_output(&main_stderr_log_out);
461 log_add_output_maxlev(&main_stderr_log_out, LMT_ERROR);
464 // If trace is enabled, enable logging of certain things
465 if (cmd_args.getFlag("trace")) {
466 dstream << _("Enabling trace level debug output") << std::endl;
467 log_trace_level_enabled = true;
468 dout_con_ptr = &verbosestream; // this is somewhat old crap
469 socket_enable_debug_output = true; // socket doesn't use log.h
472 // In certain cases, output info level on stderr
473 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
474 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
475 log_add_output(&main_stderr_log_out, LMT_INFO);
477 // In certain cases, output verbose level on stderr
478 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
479 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
482 static bool create_userdata_path()
487 porting::initAndroid();
489 porting::setExternalStorageDir(porting::jnienv);
490 if (!fs::PathExists(porting::path_user)) {
491 success = fs::CreateDir(porting::path_user);
495 porting::copyAssets();
497 // Create user data directory
498 success = fs::CreateDir(porting::path_user);
501 infostream << "path_share = " << porting::path_share << std::endl;
502 infostream << "path_user = " << porting::path_user << std::endl;
507 static bool init_common(int *log_level, const Settings &cmd_args, int argc, char *argv[])
510 set_default_settings(g_settings);
512 // Initialize sockets
514 atexit(sockets_cleanup);
516 if (!read_config_file(cmd_args))
519 init_debug_streams(log_level, cmd_args);
521 // Initialize random seed
525 // Initialize HTTP fetcher
526 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
529 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),
530 g_settings->get("language"), argc, argv);
532 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),
533 g_settings->get("language"));
539 static void startup_message()
541 infostream << PROJECT_NAME << " " << _("with")
542 << " SER_FMT_VER_HIGHEST_READ="
543 << (int)SER_FMT_VER_HIGHEST_READ << ", "
544 << g_build_info << std::endl;
547 static bool read_config_file(const Settings &cmd_args)
549 // Path of configuration file in use
550 sanity_check(g_settings_path == ""); // Sanity check
552 if (cmd_args.exists("config")) {
553 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
555 errorstream << "Could not read configuration from \""
556 << cmd_args.get("config") << "\"" << std::endl;
559 g_settings_path = cmd_args.get("config");
561 std::vector<std::string> filenames;
562 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
563 // Legacy configuration file location
564 filenames.push_back(porting::path_user +
565 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
568 // Try also from a lower level (to aid having the same configuration
569 // for many RUN_IN_PLACE installs)
570 filenames.push_back(porting::path_user +
571 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
574 for (size_t i = 0; i < filenames.size(); i++) {
575 bool r = g_settings->readConfigFile(filenames[i].c_str());
577 g_settings_path = filenames[i];
582 // If no path found, use the first one (menu creates the file)
583 if (g_settings_path == "")
584 g_settings_path = filenames[0];
590 static void init_debug_streams(int *log_level, const Settings &cmd_args)
593 std::string logfile = DEBUGFILE;
595 std::string logfile = porting::path_user + DIR_DELIM + DEBUGFILE;
597 if (cmd_args.exists("logfile"))
598 logfile = cmd_args.get("logfile");
600 log_remove_output(&main_dstream_no_stderr_log_out);
601 *log_level = g_settings->getS32("debug_log_level");
603 if (*log_level == 0) //no logging
605 if (*log_level < 0) {
606 dstream << "WARNING: Supplied debug_log_level < 0; Using 0" << std::endl;
608 } else if (*log_level > LMT_NUM_VALUES) {
609 dstream << "WARNING: Supplied debug_log_level > " << LMT_NUM_VALUES
610 << "; Using " << LMT_NUM_VALUES << std::endl;
611 *log_level = LMT_NUM_VALUES;
614 log_add_output_maxlev(&main_dstream_no_stderr_log_out,
615 (LogMessageLevel)(*log_level - 1));
617 debugstreams_init(false, logfile == "" ? NULL : logfile.c_str());
619 infostream << "logfile = " << logfile << std::endl;
621 atexit(debugstreams_deinit);
624 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
626 game_configure_port(game_params, cmd_args);
628 if (!game_configure_world(game_params, cmd_args)) {
629 errorstream << "No world path specified or found." << std::endl;
633 game_configure_subgame(game_params, cmd_args);
638 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
640 if (cmd_args.exists("port"))
641 game_params->socket_port = cmd_args.getU16("port");
643 game_params->socket_port = g_settings->getU16("port");
645 if (game_params->socket_port == 0)
646 game_params->socket_port = DEFAULT_SERVER_PORT;
649 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
651 if (get_world_from_cmdline(game_params, cmd_args))
653 if (get_world_from_config(game_params, cmd_args))
656 return auto_select_world(game_params);
659 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
661 std::string commanded_world = "";
664 std::string commanded_worldname = "";
665 if (cmd_args.exists("worldname"))
666 commanded_worldname = cmd_args.get("worldname");
668 // If a world name was specified, convert it to a path
669 if (commanded_worldname != "") {
670 // Get information about available worlds
671 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
673 for (u32 i = 0; i < worldspecs.size(); i++) {
674 std::string name = worldspecs[i].name;
675 if (name == commanded_worldname) {
676 dstream << _("Using world specified by --worldname on the "
677 "command line") << std::endl;
678 commanded_world = worldspecs[i].path;
684 dstream << _("World") << " '" << commanded_worldname
685 << _("' not available. Available worlds:") << std::endl;
686 print_worldspecs(worldspecs, dstream);
690 game_params->world_path = get_clean_world_path(commanded_world);
691 return commanded_world != "";
694 if (cmd_args.exists("world"))
695 commanded_world = cmd_args.get("world");
696 else if (cmd_args.exists("map-dir"))
697 commanded_world = cmd_args.get("map-dir");
698 else if (cmd_args.exists("nonopt0")) // First nameless argument
699 commanded_world = cmd_args.get("nonopt0");
701 game_params->world_path = get_clean_world_path(commanded_world);
702 return commanded_world != "";
705 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
708 std::string commanded_world = "";
710 if (g_settings->exists("map-dir"))
711 commanded_world = g_settings->get("map-dir");
713 game_params->world_path = get_clean_world_path(commanded_world);
715 return commanded_world != "";
718 static bool auto_select_world(GameParams *game_params)
720 // No world was specified; try to select it automatically
721 // Get information about available worlds
723 verbosestream << _("Determining world path") << std::endl;
725 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
726 std::string world_path;
728 // If there is only a single world, use it
729 if (worldspecs.size() == 1) {
730 world_path = worldspecs[0].path;
731 dstream <<_("Automatically selecting world at") << " ["
732 << world_path << "]" << std::endl;
733 // If there are multiple worlds, list them
734 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
735 dstream << _("Multiple worlds are available.") << std::endl;
736 dstream << _("Please select one using --worldname <name>"
737 " or --world <path>") << std::endl;
738 print_worldspecs(worldspecs, dstream);
740 // If there are no worlds, automatically create a new one
742 // This is the ultimate default world path
743 world_path = porting::path_user + DIR_DELIM + "worlds" +
745 infostream << "Creating default world at ["
746 << world_path << "]" << std::endl;
749 assert(world_path != ""); // Post-condition
750 game_params->world_path = world_path;
754 static std::string get_clean_world_path(const std::string &path)
756 const std::string worldmt = "world.mt";
757 std::string clean_path;
759 if (path.size() > worldmt.size()
760 && path.substr(path.size() - worldmt.size()) == worldmt) {
761 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
762 clean_path = path.substr(0, path.size() - worldmt.size());
770 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
774 success = get_game_from_cmdline(game_params, cmd_args);
776 success = determine_subgame(game_params);
781 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
783 SubgameSpec commanded_gamespec;
785 if (cmd_args.exists("gameid")) {
786 std::string gameid = cmd_args.get("gameid");
787 commanded_gamespec = findSubgame(gameid);
788 if (!commanded_gamespec.isValid()) {
789 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
792 dstream << _("Using game specified by --gameid on the command line")
794 game_params->game_spec = commanded_gamespec;
801 static bool determine_subgame(GameParams *game_params)
803 SubgameSpec gamespec;
805 assert(game_params->world_path != ""); // Pre-condition
807 verbosestream << _("Determining gameid/gamespec") << std::endl;
808 // If world doesn't exist
809 if (game_params->world_path != ""
810 && !getWorldExists(game_params->world_path)) {
811 // Try to take gamespec from command line
812 if (game_params->game_spec.isValid()) {
813 gamespec = game_params->game_spec;
814 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
815 } else { // Otherwise we will be using "minetest"
816 gamespec = findSubgame(g_settings->get("default_game"));
817 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
818 if (!gamespec.isValid()) {
819 errorstream << "Subgame specified in default_game ["
820 << g_settings->get("default_game")
821 << "] is invalid." << std::endl;
825 } else { // World exists
826 std::string world_gameid = getWorldGameId(game_params->world_path, false);
827 // If commanded to use a gameid, do so
828 if (game_params->game_spec.isValid()) {
829 gamespec = game_params->game_spec;
830 if (game_params->game_spec.id != world_gameid) {
831 errorstream << "WARNING: Using commanded gameid ["
832 << gamespec.id << "]" << " instead of world gameid ["
833 << world_gameid << "]" << std::endl;
836 // If world contains an embedded game, use it;
837 // Otherwise find world from local system.
838 gamespec = findWorldSubgame(game_params->world_path);
839 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
843 if (!gamespec.isValid()) {
844 errorstream << "Subgame [" << gamespec.id << "] could not be found."
849 game_params->game_spec = gamespec;
854 /*****************************************************************************
856 *****************************************************************************/
857 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
859 DSTACK("Dedicated server branch");
861 verbosestream << _("Using world path") << " ["
862 << game_params.world_path << "]" << std::endl;
863 verbosestream << _("Using gameid") << " ["
864 << game_params.game_spec.id << "]" << std::endl;
867 std::string bind_str = g_settings->get("bind_address");
868 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
870 if (g_settings->getBool("ipv6_server")) {
871 bind_addr.setAddress((IPv6AddressBytes*) NULL);
874 bind_addr.Resolve(bind_str.c_str());
875 } catch (ResolveError &e) {
876 infostream << "Resolving bind address \"" << bind_str
877 << "\" failed: " << e.what()
878 << " -- Listening on all addresses." << std::endl;
880 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
881 errorstream << "Unable to listen on "
882 << bind_addr.serializeString()
883 << L" because IPv6 is disabled" << std::endl;
887 // Database migration
888 if (cmd_args.exists("migrate"))
889 return migrate_database(game_params, cmd_args);
892 Server server(game_params.world_path,
893 game_params.game_spec, false, bind_addr.isIPv6());
895 server.start(bind_addr);
898 bool &kill = *porting::signal_handler_killstatus();
899 dedicated_server_loop(server, kill);
904 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args)
906 std::string migrate_to = cmd_args.get("migrate");
908 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
909 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
910 errorstream << "Cannot read world.mt!" << std::endl;
913 if (!world_mt.exists("backend")) {
914 errorstream << "Please specify your current backend in world.mt:"
916 << " backend = {sqlite3|leveldb|redis|dummy}"
920 std::string backend = world_mt.get("backend");
921 if (backend == migrate_to) {
922 errorstream << "Cannot migrate: new backend is same"
923 << " as the old one" << std::endl;
926 Database *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
927 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
930 time_t last_update_time = 0;
931 bool &kill = *porting::signal_handler_killstatus();
933 std::vector<v3s16> blocks;
934 old_db->listAllLoadableBlocks(blocks);
936 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
937 if (kill) return false;
939 const std::string &data = old_db->loadBlock(*it);
941 new_db->saveBlock(*it, data);
943 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
945 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
946 std::cerr << " Migrated " << count << " blocks, "
947 << (100.0 * count / blocks.size()) << "% completed.\r";
950 last_update_time = time(NULL);
953 std::cerr << std::endl;
958 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
959 world_mt.set("backend", migrate_to);
960 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
961 errorstream << "Failed to update world.mt!" << std::endl;
963 actionstream << "world.mt updated" << std::endl;