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 // This would get rid of the console window
21 //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
23 #include "irrlicht.h" // createDevice
25 #include "mainmenumanager.h"
26 #include "irrlichttypes_extrabloated.h"
28 #include "unittest/test.h"
32 #include "guiMainMenu.h"
34 #include "defaultsettings.h"
37 #include "quicktune.h"
38 #include "httpfetch.h"
39 #include "guiEngine.h"
42 #include "mapsector.h"
43 #include "fontengine.h"
44 #include "gameparams.h"
48 #include "terminal_chat_console.h"
51 #include "client/clientlauncher.h"
54 #ifdef HAVE_TOUCHSCREENGUI
55 #include "touchscreengui.h"
58 #if !defined(SERVER) && \
59 (IRRLICHT_VERSION_MAJOR == 1) && \
60 (IRRLICHT_VERSION_MINOR == 8) && \
61 (IRRLICHT_VERSION_REVISION == 2)
62 #error "Irrlicht 1.8.2 is known to be broken - please update Irrlicht to version >= 1.8.3"
65 #define DEBUGFILE "debug.txt"
66 #define DEFAULT_SERVER_PORT 30000
68 typedef std::map<std::string, ValueSpec> OptionList;
70 /**********************************************************************
72 **********************************************************************/
74 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
75 static void set_allowed_options(OptionList *allowed_options);
77 static void print_help(const OptionList &allowed_options);
78 static void print_allowed_options(const OptionList &allowed_options);
79 static void print_version();
80 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
82 static void print_modified_quicktune_values();
84 static void list_game_ids();
85 static void list_worlds();
86 static void setup_log_params(const Settings &cmd_args);
87 static bool create_userdata_path();
88 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
89 static void startup_message();
90 static bool read_config_file(const Settings &cmd_args);
91 static void init_log_streams(const Settings &cmd_args);
93 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
94 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
96 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
97 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
98 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
99 static bool auto_select_world(GameParams *game_params);
100 static std::string get_clean_world_path(const std::string &path);
102 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
103 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
104 static bool determine_subgame(GameParams *game_params);
106 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
107 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args);
109 /**********************************************************************/
112 gettime.h implementation
119 /* Use imprecise system calls directly (from porting.h) */
120 return porting::getTime(PRECISION_MILLI);
123 u32 getTime(TimePrecision prec)
125 return porting::getTime(prec);
130 FileLogOutput file_log_output;
132 static OptionList allowed_options;
134 int main(int argc, char *argv[])
138 debug_set_exception_handler();
140 g_logger.registerThread("Main");
141 g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
144 bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
146 || cmd_args.getFlag("help")
147 || cmd_args.exists("nonopt1")) {
148 print_help(allowed_options);
149 return cmd_args_ok ? 0 : 1;
152 if (cmd_args.getFlag("version")) {
157 setup_log_params(cmd_args);
159 porting::signal_handler_init();
162 porting::initAndroid();
163 porting::initializePathsAndroid();
165 porting::initializePaths();
168 if (!create_userdata_path()) {
169 errorstream << "Cannot create user data directory" << std::endl;
173 // Initialize debug stacks
174 DSTACK(FUNCTION_NAME);
177 BEGIN_DEBUG_EXCEPTION_HANDLER
179 // List gameids if requested
180 if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
185 // List worlds if requested
186 if (cmd_args.exists("world") && cmd_args.get("world") == "list") {
191 if (!init_common(cmd_args, argc, argv))
196 if (cmd_args.getFlag("run-unittests")) {
201 GameParams game_params;
203 game_params.is_dedicated_server = true;
205 game_params.is_dedicated_server = cmd_args.getFlag("server");
208 if (!game_configure(&game_params, cmd_args))
211 sanity_check(!game_params.world_path.empty());
213 infostream << "Using commanded world path ["
214 << game_params.world_path << "]" << std::endl;
216 if (game_params.is_dedicated_server)
217 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
220 ClientLauncher launcher;
221 retval = launcher.run(game_params, cmd_args) ? 0 : 1;
226 // Update configuration file
227 if (g_settings_path != "")
228 g_settings->updateConfigFile(g_settings_path.c_str());
230 print_modified_quicktune_values();
232 // Stop httpfetch thread (if started)
235 END_DEBUG_EXCEPTION_HANDLER
241 /*****************************************************************************
243 *****************************************************************************/
246 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
248 set_allowed_options(&allowed_options);
250 return cmd_args->parseCommandLine(argc, argv, allowed_options);
253 static void set_allowed_options(OptionList *allowed_options)
255 allowed_options->clear();
257 allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
258 _("Show allowed options"))));
259 allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
260 _("Show version information"))));
261 allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
262 _("Load configuration from specified file"))));
263 allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
264 _("Set network port (UDP)"))));
265 allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
266 _("Run the unit tests and exit"))));
267 allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
268 _("Same as --world (deprecated)"))));
269 allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
270 _("Set world path (implies local game) ('list' lists all)"))));
271 allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
272 _("Set world by name (implies local game)"))));
273 allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
274 _("Print to console errors only"))));
275 allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
276 _("Print more information to console"))));
277 allowed_options->insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
278 _("Print even more information to console"))));
279 allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
280 _("Print enormous amounts of information to log and console"))));
281 allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
282 _("Set logfile path ('' = no logging)"))));
283 allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
284 _("Set gameid (\"--gameid list\" prints available ones)"))));
285 allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
286 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
287 allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
288 _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
290 allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
291 _("Show available video modes"))));
292 allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
293 _("Run speed tests"))));
294 allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
295 _("Address to connect to. ('' = local game)"))));
296 allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
297 _("Enable random user input, for testing"))));
298 allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
299 _("Run dedicated server"))));
300 allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
301 _("Set player name"))));
302 allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
303 _("Set password"))));
304 allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
305 _("Disable main menu"))));
310 static void print_help(const OptionList &allowed_options)
312 std::cout << _("Allowed options:") << std::endl;
313 print_allowed_options(allowed_options);
316 static void print_allowed_options(const OptionList &allowed_options)
318 for (OptionList::const_iterator i = allowed_options.begin();
319 i != allowed_options.end(); ++i) {
320 std::ostringstream os1(std::ios::binary);
321 os1 << " --" << i->first;
322 if (i->second.type != VALUETYPE_FLAG)
323 os1 << _(" <value>");
325 std::cout << padStringRight(os1.str(), 24);
327 if (i->second.help != NULL)
328 std::cout << i->second.help;
330 std::cout << std::endl;
334 static void print_version()
336 std::cout << PROJECT_NAME_C " " << g_version_hash
337 << " (" << porting::getPlatformName() << ")" << std::endl;
339 std::cout << "Using Irrlicht " << IRRLICHT_SDK_VERSION << std::endl;
341 std::cout << "Build info: " << g_build_info << std::endl;
344 static void list_game_ids()
346 std::set<std::string> gameids = getAvailableGameIds();
347 for (std::set<std::string>::const_iterator i = gameids.begin();
348 i != gameids.end(); ++i)
349 std::cout << (*i) <<std::endl;
352 static void list_worlds()
354 std::cout << _("Available worlds:") << std::endl;
355 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
356 print_worldspecs(worldspecs, std::cout);
359 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
362 for (size_t i = 0; i < worldspecs.size(); i++) {
363 std::string name = worldspecs[i].name;
364 std::string path = worldspecs[i].path;
365 if (name.find(" ") != std::string::npos)
366 name = std::string("'") + name + "'";
367 path = std::string("'") + path + "'";
368 name = padStringRight(name, 14);
369 os << " " << name << " " << path << std::endl;
373 static void print_modified_quicktune_values()
375 bool header_printed = false;
376 std::vector<std::string> names = getQuicktuneNames();
378 for (u32 i = 0; i < names.size(); i++) {
379 QuicktuneValue val = getQuicktuneValue(names[i]);
382 if (!header_printed) {
383 dstream << "Modified quicktune values:" << std::endl;
384 header_printed = true;
386 dstream << names[i] << " = " << val.getString() << std::endl;
390 static void setup_log_params(const Settings &cmd_args)
392 // Quiet mode, print errors only
393 if (cmd_args.getFlag("quiet")) {
394 g_logger.removeOutput(&stderr_output);
395 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
398 // If trace is enabled, enable logging of certain things
399 if (cmd_args.getFlag("trace")) {
400 dstream << _("Enabling trace level debug output") << std::endl;
401 g_logger.setTraceEnabled(true);
402 dout_con_ptr = &verbosestream; // This is somewhat old
403 socket_enable_debug_output = true; // Sockets doesn't use log.h
406 // In certain cases, output info level on stderr
407 if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
408 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
409 g_logger.addOutput(&stderr_output, LL_INFO);
411 // In certain cases, output verbose level on stderr
412 if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
413 g_logger.addOutput(&stderr_output, LL_VERBOSE);
416 static bool create_userdata_path()
421 if (!fs::PathExists(porting::path_user)) {
422 success = fs::CreateDir(porting::path_user);
426 porting::copyAssets();
428 // Create user data directory
429 success = fs::CreateDir(porting::path_user);
435 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
438 set_default_settings(g_settings);
440 // Initialize sockets
442 atexit(sockets_cleanup);
444 if (!read_config_file(cmd_args))
447 init_log_streams(cmd_args);
449 // Initialize random seed
453 // Initialize HTTP fetcher
454 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
456 init_gettext(porting::path_locale.c_str(),
457 g_settings->get("language"), argc, argv);
462 static void startup_message()
464 infostream << PROJECT_NAME << " " << _("with")
465 << " SER_FMT_VER_HIGHEST_READ="
466 << (int)SER_FMT_VER_HIGHEST_READ << ", "
467 << g_build_info << std::endl;
470 static bool read_config_file(const Settings &cmd_args)
472 // Path of configuration file in use
473 sanity_check(g_settings_path == ""); // Sanity check
475 if (cmd_args.exists("config")) {
476 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
478 errorstream << "Could not read configuration from \""
479 << cmd_args.get("config") << "\"" << std::endl;
482 g_settings_path = cmd_args.get("config");
484 std::vector<std::string> filenames;
485 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
486 // Legacy configuration file location
487 filenames.push_back(porting::path_user +
488 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
491 // Try also from a lower level (to aid having the same configuration
492 // for many RUN_IN_PLACE installs)
493 filenames.push_back(porting::path_user +
494 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
497 for (size_t i = 0; i < filenames.size(); i++) {
498 bool r = g_settings->readConfigFile(filenames[i].c_str());
500 g_settings_path = filenames[i];
505 // If no path found, use the first one (menu creates the file)
506 if (g_settings_path == "")
507 g_settings_path = filenames[0];
513 static void init_log_streams(const Settings &cmd_args)
516 std::string log_filename = DEBUGFILE;
518 std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
520 if (cmd_args.exists("logfile"))
521 log_filename = cmd_args.get("logfile");
523 g_logger.removeOutput(&file_log_output);
524 std::string conf_loglev = g_settings->get("debug_log_level");
526 // Old integer format
527 if (std::isdigit(conf_loglev[0])) {
528 warningstream << "Deprecated use of debug_log_level with an "
529 "integer value; please update your configuration." << std::endl;
530 static const char *lev_name[] =
531 {"", "error", "action", "info", "verbose"};
532 int lev_i = atoi(conf_loglev.c_str());
533 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
534 warningstream << "Supplied invalid debug_log_level!"
535 " Assuming action level." << std::endl;
538 conf_loglev = lev_name[lev_i];
541 if (log_filename.empty() || conf_loglev.empty()) // No logging
544 LogLevel log_level = Logger::stringToLevel(conf_loglev);
545 if (log_level == LL_MAX) {
546 warningstream << "Supplied unrecognized debug_log_level; "
547 "using maximum." << std::endl;
550 verbosestream << "log_filename = " << log_filename << std::endl;
552 file_log_output.open(log_filename.c_str());
553 g_logger.addOutputMaxLevel(&file_log_output, log_level);
556 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
558 game_configure_port(game_params, cmd_args);
560 if (!game_configure_world(game_params, cmd_args)) {
561 errorstream << "No world path specified or found." << std::endl;
565 game_configure_subgame(game_params, cmd_args);
570 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
572 if (cmd_args.exists("port"))
573 game_params->socket_port = cmd_args.getU16("port");
575 game_params->socket_port = g_settings->getU16("port");
577 if (game_params->socket_port == 0)
578 game_params->socket_port = DEFAULT_SERVER_PORT;
581 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
583 if (get_world_from_cmdline(game_params, cmd_args))
585 if (get_world_from_config(game_params, cmd_args))
588 return auto_select_world(game_params);
591 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
593 std::string commanded_world = "";
596 std::string commanded_worldname = "";
597 if (cmd_args.exists("worldname"))
598 commanded_worldname = cmd_args.get("worldname");
600 // If a world name was specified, convert it to a path
601 if (commanded_worldname != "") {
602 // Get information about available worlds
603 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
605 for (u32 i = 0; i < worldspecs.size(); i++) {
606 std::string name = worldspecs[i].name;
607 if (name == commanded_worldname) {
608 dstream << _("Using world specified by --worldname on the "
609 "command line") << std::endl;
610 commanded_world = worldspecs[i].path;
616 dstream << _("World") << " '" << commanded_worldname
617 << _("' not available. Available worlds:") << std::endl;
618 print_worldspecs(worldspecs, dstream);
622 game_params->world_path = get_clean_world_path(commanded_world);
623 return commanded_world != "";
626 if (cmd_args.exists("world"))
627 commanded_world = cmd_args.get("world");
628 else if (cmd_args.exists("map-dir"))
629 commanded_world = cmd_args.get("map-dir");
630 else if (cmd_args.exists("nonopt0")) // First nameless argument
631 commanded_world = cmd_args.get("nonopt0");
633 game_params->world_path = get_clean_world_path(commanded_world);
634 return commanded_world != "";
637 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
640 std::string commanded_world = "";
642 if (g_settings->exists("map-dir"))
643 commanded_world = g_settings->get("map-dir");
645 game_params->world_path = get_clean_world_path(commanded_world);
647 return commanded_world != "";
650 static bool auto_select_world(GameParams *game_params)
652 // No world was specified; try to select it automatically
653 // Get information about available worlds
655 verbosestream << _("Determining world path") << std::endl;
657 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
658 std::string world_path;
660 // If there is only a single world, use it
661 if (worldspecs.size() == 1) {
662 world_path = worldspecs[0].path;
663 dstream <<_("Automatically selecting world at") << " ["
664 << world_path << "]" << std::endl;
665 // If there are multiple worlds, list them
666 } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
667 std::cerr << _("Multiple worlds are available.") << std::endl;
668 std::cerr << _("Please select one using --worldname <name>"
669 " or --world <path>") << std::endl;
670 print_worldspecs(worldspecs, std::cerr);
672 // If there are no worlds, automatically create a new one
674 // This is the ultimate default world path
675 world_path = porting::path_user + DIR_DELIM + "worlds" +
677 infostream << "Creating default world at ["
678 << world_path << "]" << std::endl;
681 assert(world_path != ""); // Post-condition
682 game_params->world_path = world_path;
686 static std::string get_clean_world_path(const std::string &path)
688 const std::string worldmt = "world.mt";
689 std::string clean_path;
691 if (path.size() > worldmt.size()
692 && path.substr(path.size() - worldmt.size()) == worldmt) {
693 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
694 clean_path = path.substr(0, path.size() - worldmt.size());
702 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
706 success = get_game_from_cmdline(game_params, cmd_args);
708 success = determine_subgame(game_params);
713 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
715 SubgameSpec commanded_gamespec;
717 if (cmd_args.exists("gameid")) {
718 std::string gameid = cmd_args.get("gameid");
719 commanded_gamespec = findSubgame(gameid);
720 if (!commanded_gamespec.isValid()) {
721 errorstream << "Game \"" << gameid << "\" not found" << std::endl;
724 dstream << _("Using game specified by --gameid on the command line")
726 game_params->game_spec = commanded_gamespec;
733 static bool determine_subgame(GameParams *game_params)
735 SubgameSpec gamespec;
737 assert(game_params->world_path != ""); // Pre-condition
739 verbosestream << _("Determining gameid/gamespec") << std::endl;
740 // If world doesn't exist
741 if (game_params->world_path != ""
742 && !getWorldExists(game_params->world_path)) {
743 // Try to take gamespec from command line
744 if (game_params->game_spec.isValid()) {
745 gamespec = game_params->game_spec;
746 infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
747 } else { // Otherwise we will be using "minetest"
748 gamespec = findSubgame(g_settings->get("default_game"));
749 infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
750 if (!gamespec.isValid()) {
751 errorstream << "Subgame specified in default_game ["
752 << g_settings->get("default_game")
753 << "] is invalid." << std::endl;
757 } else { // World exists
758 std::string world_gameid = getWorldGameId(game_params->world_path, false);
759 // If commanded to use a gameid, do so
760 if (game_params->game_spec.isValid()) {
761 gamespec = game_params->game_spec;
762 if (game_params->game_spec.id != world_gameid) {
763 warningstream << "Using commanded gameid ["
764 << gamespec.id << "]" << " instead of world gameid ["
765 << world_gameid << "]" << std::endl;
768 // If world contains an embedded game, use it;
769 // Otherwise find world from local system.
770 gamespec = findWorldSubgame(game_params->world_path);
771 infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
775 if (!gamespec.isValid()) {
776 errorstream << "Subgame [" << gamespec.id << "] could not be found."
781 game_params->game_spec = gamespec;
786 /*****************************************************************************
788 *****************************************************************************/
789 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
791 DSTACK("Dedicated server branch");
793 verbosestream << _("Using world path") << " ["
794 << game_params.world_path << "]" << std::endl;
795 verbosestream << _("Using gameid") << " ["
796 << game_params.game_spec.id << "]" << std::endl;
799 std::string bind_str = g_settings->get("bind_address");
800 Address bind_addr(0, 0, 0, 0, game_params.socket_port);
802 if (g_settings->getBool("ipv6_server")) {
803 bind_addr.setAddress((IPv6AddressBytes*) NULL);
806 bind_addr.Resolve(bind_str.c_str());
807 } catch (ResolveError &e) {
808 infostream << "Resolving bind address \"" << bind_str
809 << "\" failed: " << e.what()
810 << " -- Listening on all addresses." << std::endl;
812 if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
813 errorstream << "Unable to listen on "
814 << bind_addr.serializeString()
815 << L" because IPv6 is disabled" << std::endl;
819 // Database migration
820 if (cmd_args.exists("migrate"))
821 return migrate_database(game_params, cmd_args);
823 if (cmd_args.exists("terminal")) {
826 std::string admin_nick = g_settings->get("name");
828 name_ok = name_ok && !admin_nick.empty();
829 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
832 if (admin_nick.empty()) {
833 errorstream << "No name given for admin. "
834 << "Please check your minetest.conf that it "
835 << "contains a 'name = ' to your main admin account."
838 errorstream << "Name for admin '"
839 << admin_nick << "' is not valid. "
840 << "Please check that it only contains allowed characters. "
841 << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
847 bool &kill = *porting::signal_handler_killstatus();
851 Server server(game_params.world_path, game_params.game_spec,
852 false, bind_addr.isIPv6(), true, &iface);
854 g_term_console.setup(&iface, &kill, admin_nick);
856 g_term_console.start();
858 server.start(bind_addr);
860 dedicated_server_loop(server, kill);
861 } catch (const ModError &e) {
862 g_term_console.stopAndWaitforThread();
863 errorstream << "ModError: " << e.what() << std::endl;
865 } catch (const ServerError &e) {
866 g_term_console.stopAndWaitforThread();
867 errorstream << "ServerError: " << e.what() << std::endl;
871 // Tell the console to stop, and wait for it to finish,
872 // only then leave context and free iface
873 g_term_console.stop();
874 g_term_console.wait();
876 g_term_console.clearKillStatus();
879 errorstream << "Cmd arg --terminal passed, but "
880 << "compiled without ncurses. Ignoring." << std::endl;
885 Server server(game_params.world_path, game_params.game_spec, false,
886 bind_addr.isIPv6(), true);
887 server.start(bind_addr);
890 bool &kill = *porting::signal_handler_killstatus();
891 dedicated_server_loop(server, kill);
893 } catch (const ModError &e) {
894 errorstream << "ModError: " << e.what() << std::endl;
896 } catch (const ServerError &e) {
897 errorstream << "ServerError: " << e.what() << std::endl;
905 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args)
907 std::string migrate_to = cmd_args.get("migrate");
909 std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
910 if (!world_mt.readConfigFile(world_mt_path.c_str())) {
911 errorstream << "Cannot read world.mt!" << std::endl;
914 if (!world_mt.exists("backend")) {
915 errorstream << "Please specify your current backend in world.mt:"
917 << " backend = {sqlite3|leveldb|redis|dummy}"
921 std::string backend = world_mt.get("backend");
922 if (backend == migrate_to) {
923 errorstream << "Cannot migrate: new backend is same"
924 << " as the old one" << std::endl;
927 Database *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
928 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
931 time_t last_update_time = 0;
932 bool &kill = *porting::signal_handler_killstatus();
934 std::vector<v3s16> blocks;
935 old_db->listAllLoadableBlocks(blocks);
937 for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
938 if (kill) return false;
941 old_db->loadBlock(*it, &data);
943 new_db->saveBlock(*it, data);
945 errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
947 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
948 std::cerr << " Migrated " << count << " blocks, "
949 << (100.0 * count / blocks.size()) << "% completed.\r";
952 last_update_time = time(NULL);
955 std::cerr << std::endl;
960 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
961 world_mt.set("backend", migrate_to);
962 if (!world_mt.updateConfigFile(world_mt_path.c_str()))
963 errorstream << "Failed to update world.mt!" << std::endl;
965 actionstream << "world.mt updated" << std::endl;