]> git.lizzy.rs Git - minetest.git/blob - src/main.cpp
Allow mesh and nodeboxes to wave like plants or leaves. (#3497)
[minetest.git] / src / main.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include "irrlicht.h" // createDevice
21
22 #include "mainmenumanager.h"
23 #include "irrlichttypes_extrabloated.h"
24 #include "debug.h"
25 #include "unittest/test.h"
26 #include "server.h"
27 #include "filesys.h"
28 #include "version.h"
29 #include "guiMainMenu.h"
30 #include "game.h"
31 #include "defaultsettings.h"
32 #include "gettext.h"
33 #include "log.h"
34 #include "quicktune.h"
35 #include "httpfetch.h"
36 #include "guiEngine.h"
37 #include "map.h"
38 #include "player.h"
39 #include "mapsector.h"
40 #include "fontengine.h"
41 #include "gameparams.h"
42 #include "database.h"
43 #include "config.h"
44 #include "porting.h"
45 #if USE_CURSES
46         #include "terminal_chat_console.h"
47 #endif
48 #ifndef SERVER
49 #include "client/clientlauncher.h"
50
51 #endif
52
53 #ifdef HAVE_TOUCHSCREENGUI
54         #include "touchscreengui.h"
55 #endif
56
57 #if !defined(SERVER) && \
58         (IRRLICHT_VERSION_MAJOR == 1) && \
59         (IRRLICHT_VERSION_MINOR == 8) && \
60         (IRRLICHT_VERSION_REVISION == 2)
61         #error "Irrlicht 1.8.2 is known to be broken - please update Irrlicht to version >= 1.8.3"
62 #endif
63
64 #define DEBUGFILE "debug.txt"
65 #define DEFAULT_SERVER_PORT 30000
66
67 typedef std::map<std::string, ValueSpec> OptionList;
68
69 /**********************************************************************
70  * Private functions
71  **********************************************************************/
72
73 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
74 static void set_allowed_options(OptionList *allowed_options);
75
76 static void print_help(const OptionList &allowed_options);
77 static void print_allowed_options(const OptionList &allowed_options);
78 static void print_version();
79 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
80                                                          std::ostream &os);
81 static void print_modified_quicktune_values();
82
83 static void list_game_ids();
84 static void list_worlds();
85 static void setup_log_params(const Settings &cmd_args);
86 static bool create_userdata_path();
87 static bool init_common(const Settings &cmd_args, int argc, char *argv[]);
88 static void startup_message();
89 static bool read_config_file(const Settings &cmd_args);
90 static void init_log_streams(const Settings &cmd_args);
91
92 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
93 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
94
95 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
96 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
97 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
98 static bool auto_select_world(GameParams *game_params);
99 static std::string get_clean_world_path(const std::string &path);
100
101 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
102 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
103 static bool determine_subgame(GameParams *game_params);
104
105 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
106 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args);
107
108 /**********************************************************************/
109
110 /*
111         gettime.h implementation
112 */
113
114 #ifdef SERVER
115
116 u32 getTimeMs()
117 {
118         /* Use imprecise system calls directly (from porting.h) */
119         return porting::getTime(PRECISION_MILLI);
120 }
121
122 u32 getTime(TimePrecision prec)
123 {
124         return porting::getTime(prec);
125 }
126
127 #endif
128
129 FileLogOutput file_log_output;
130
131 static OptionList allowed_options;
132
133 int main(int argc, char *argv[])
134 {
135         int retval;
136         debug_set_exception_handler();
137
138         g_logger.registerThread("Main");
139         g_logger.addOutputMaxLevel(&stderr_output, LL_ACTION);
140
141         Settings cmd_args;
142         bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
143         if (!cmd_args_ok
144                         || cmd_args.getFlag("help")
145                         || cmd_args.exists("nonopt1")) {
146                 porting::attachOrCreateConsole();
147                 print_help(allowed_options);
148                 return cmd_args_ok ? 0 : 1;
149         }
150         if (cmd_args.getFlag("console"))
151                 porting::attachOrCreateConsole();
152
153         if (cmd_args.getFlag("version")) {
154                 porting::attachOrCreateConsole();
155                 print_version();
156                 return 0;
157         }
158
159         setup_log_params(cmd_args);
160
161         porting::signal_handler_init();
162
163 #ifdef __ANDROID__
164         porting::initAndroid();
165         porting::initializePathsAndroid();
166 #else
167         porting::initializePaths();
168 #endif
169
170         if (!create_userdata_path()) {
171                 errorstream << "Cannot create user data directory" << std::endl;
172                 return 1;
173         }
174
175         // Initialize debug stacks
176         DSTACK(FUNCTION_NAME);
177
178         // Debug handler
179         BEGIN_DEBUG_EXCEPTION_HANDLER
180
181         // List gameids if requested
182         if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
183                 list_game_ids();
184                 return 0;
185         }
186
187         // List worlds if requested
188         if (cmd_args.exists("world") && cmd_args.get("world") == "list") {
189                 list_worlds();
190                 return 0;
191         }
192
193         if (!init_common(cmd_args, argc, argv))
194                 return 1;
195
196         if (g_settings->getBool("enable_console"))
197                 porting::attachOrCreateConsole();
198
199 #ifndef __ANDROID__
200         // Run unit tests
201         if (cmd_args.getFlag("run-unittests")) {
202                 return run_tests();
203         }
204 #endif
205
206         GameParams game_params;
207 #ifdef SERVER
208         porting::attachOrCreateConsole();
209         game_params.is_dedicated_server = true;
210 #else
211         const bool isServer = cmd_args.getFlag("server");
212         if (isServer)
213                 porting::attachOrCreateConsole();
214         game_params.is_dedicated_server = isServer;
215 #endif
216
217         if (!game_configure(&game_params, cmd_args))
218                 return 1;
219
220         sanity_check(!game_params.world_path.empty());
221
222         infostream << "Using commanded world path ["
223                    << game_params.world_path << "]" << std::endl;
224
225         if (game_params.is_dedicated_server)
226                 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
227
228 #ifndef SERVER
229         ClientLauncher launcher;
230         retval = launcher.run(game_params, cmd_args) ? 0 : 1;
231 #else
232         retval = 0;
233 #endif
234
235         // Update configuration file
236         if (g_settings_path != "")
237                 g_settings->updateConfigFile(g_settings_path.c_str());
238
239         print_modified_quicktune_values();
240
241         // Stop httpfetch thread (if started)
242         httpfetch_cleanup();
243
244         END_DEBUG_EXCEPTION_HANDLER
245
246         return retval;
247 }
248
249
250 /*****************************************************************************
251  * Startup / Init
252  *****************************************************************************/
253
254
255 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
256 {
257         set_allowed_options(&allowed_options);
258
259         return cmd_args->parseCommandLine(argc, argv, allowed_options);
260 }
261
262 static void set_allowed_options(OptionList *allowed_options)
263 {
264         allowed_options->clear();
265
266         allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
267                         _("Show allowed options"))));
268         allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
269                         _("Show version information"))));
270         allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
271                         _("Load configuration from specified file"))));
272         allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
273                         _("Set network port (UDP)"))));
274         allowed_options->insert(std::make_pair("run-unittests", ValueSpec(VALUETYPE_FLAG,
275                         _("Run the unit tests and exit"))));
276         allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
277                         _("Same as --world (deprecated)"))));
278         allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
279                         _("Set world path (implies local game) ('list' lists all)"))));
280         allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
281                         _("Set world by name (implies local game)"))));
282         allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
283                         _("Print to console errors only"))));
284         allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
285                         _("Print more information to console"))));
286         allowed_options->insert(std::make_pair("verbose",  ValueSpec(VALUETYPE_FLAG,
287                         _("Print even more information to console"))));
288         allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
289                         _("Print enormous amounts of information to log and console"))));
290         allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
291                         _("Set logfile path ('' = no logging)"))));
292         allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
293                         _("Set gameid (\"--gameid list\" prints available ones)"))));
294         allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
295                         _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
296         allowed_options->insert(std::make_pair("migrate-players", ValueSpec(VALUETYPE_STRING,
297                 _("Migrate from current players backend to another (Only works when using minetestserver or with --server)"))));
298         allowed_options->insert(std::make_pair("terminal", ValueSpec(VALUETYPE_FLAG,
299                         _("Feature an interactive terminal (Only works when using minetestserver or with --server)"))));
300 #ifndef SERVER
301         allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
302                         _("Show available video modes"))));
303         allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
304                         _("Run speed tests"))));
305         allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
306                         _("Address to connect to. ('' = local game)"))));
307         allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
308                         _("Enable random user input, for testing"))));
309         allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
310                         _("Run dedicated server"))));
311         allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
312                         _("Set player name"))));
313         allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
314                         _("Set password"))));
315         allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
316                         _("Disable main menu"))));
317         allowed_options->insert(std::make_pair("console", ValueSpec(VALUETYPE_FLAG,
318                 _("Starts with the console (Windows only)"))));
319 #endif
320
321 }
322
323 static void print_help(const OptionList &allowed_options)
324 {
325         std::cout << _("Allowed options:") << std::endl;
326         print_allowed_options(allowed_options);
327 }
328
329 static void print_allowed_options(const OptionList &allowed_options)
330 {
331         for (OptionList::const_iterator i = allowed_options.begin();
332                         i != allowed_options.end(); ++i) {
333                 std::ostringstream os1(std::ios::binary);
334                 os1 << "  --" << i->first;
335                 if (i->second.type != VALUETYPE_FLAG)
336                         os1 << _(" <value>");
337
338                 std::cout << padStringRight(os1.str(), 30);
339
340                 if (i->second.help != NULL)
341                         std::cout << i->second.help;
342
343                 std::cout << std::endl;
344         }
345 }
346
347 static void print_version()
348 {
349         std::cout << PROJECT_NAME_C " " << g_version_hash
350                   << " (" << porting::getPlatformName() << ")" << std::endl;
351 #ifndef SERVER
352         std::cout << "Using Irrlicht " << IRRLICHT_SDK_VERSION << std::endl;
353 #endif
354         std::cout << "Build info: " << g_build_info << std::endl;
355 }
356
357 static void list_game_ids()
358 {
359         std::set<std::string> gameids = getAvailableGameIds();
360         for (std::set<std::string>::const_iterator i = gameids.begin();
361                         i != gameids.end(); ++i)
362                 std::cout << (*i) <<std::endl;
363 }
364
365 static void list_worlds()
366 {
367         std::cout << _("Available worlds:") << std::endl;
368         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
369         print_worldspecs(worldspecs, std::cout);
370 }
371
372 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
373                                                          std::ostream &os)
374 {
375         for (size_t i = 0; i < worldspecs.size(); i++) {
376                 std::string name = worldspecs[i].name;
377                 std::string path = worldspecs[i].path;
378                 if (name.find(" ") != std::string::npos)
379                         name = std::string("'") + name + "'";
380                 path = std::string("'") + path + "'";
381                 name = padStringRight(name, 14);
382                 os << "  " << name << " " << path << std::endl;
383         }
384 }
385
386 static void print_modified_quicktune_values()
387 {
388         bool header_printed = false;
389         std::vector<std::string> names = getQuicktuneNames();
390
391         for (u32 i = 0; i < names.size(); i++) {
392                 QuicktuneValue val = getQuicktuneValue(names[i]);
393                 if (!val.modified)
394                         continue;
395                 if (!header_printed) {
396                         dstream << "Modified quicktune values:" << std::endl;
397                         header_printed = true;
398                 }
399                 dstream << names[i] << " = " << val.getString() << std::endl;
400         }
401 }
402
403 static void setup_log_params(const Settings &cmd_args)
404 {
405         // Quiet mode, print errors only
406         if (cmd_args.getFlag("quiet")) {
407                 g_logger.removeOutput(&stderr_output);
408                 g_logger.addOutputMaxLevel(&stderr_output, LL_ERROR);
409         }
410
411         // If trace is enabled, enable logging of certain things
412         if (cmd_args.getFlag("trace")) {
413                 dstream << _("Enabling trace level debug output") << std::endl;
414                 g_logger.setTraceEnabled(true);
415                 dout_con_ptr = &verbosestream; // This is somewhat old
416                 socket_enable_debug_output = true; // Sockets doesn't use log.h
417         }
418
419         // In certain cases, output info level on stderr
420         if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
421                         cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
422                 g_logger.addOutput(&stderr_output, LL_INFO);
423
424         // In certain cases, output verbose level on stderr
425         if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
426                 g_logger.addOutput(&stderr_output, LL_VERBOSE);
427 }
428
429 static bool create_userdata_path()
430 {
431         bool success;
432
433 #ifdef __ANDROID__
434         if (!fs::PathExists(porting::path_user)) {
435                 success = fs::CreateDir(porting::path_user);
436         } else {
437                 success = true;
438         }
439         porting::copyAssets();
440 #else
441         // Create user data directory
442         success = fs::CreateDir(porting::path_user);
443 #endif
444
445         return success;
446 }
447
448 static bool init_common(const Settings &cmd_args, int argc, char *argv[])
449 {
450         startup_message();
451         set_default_settings(g_settings);
452
453         // Initialize sockets
454         sockets_init();
455         atexit(sockets_cleanup);
456
457         if (!read_config_file(cmd_args))
458                 return false;
459
460         init_log_streams(cmd_args);
461
462         // Initialize random seed
463         srand(time(0));
464         mysrand(time(0));
465
466         // Initialize HTTP fetcher
467         httpfetch_init(g_settings->getS32("curl_parallel_limit"));
468
469         init_gettext(porting::path_locale.c_str(),
470                 g_settings->get("language"), argc, argv);
471
472         return true;
473 }
474
475 static void startup_message()
476 {
477         infostream << PROJECT_NAME << " " << _("with")
478                    << " SER_FMT_VER_HIGHEST_READ="
479                << (int)SER_FMT_VER_HIGHEST_READ << ", "
480                << g_build_info << std::endl;
481 }
482
483 static bool read_config_file(const Settings &cmd_args)
484 {
485         // Path of configuration file in use
486         sanity_check(g_settings_path == "");    // Sanity check
487
488         if (cmd_args.exists("config")) {
489                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
490                 if (!r) {
491                         errorstream << "Could not read configuration from \""
492                                     << cmd_args.get("config") << "\"" << std::endl;
493                         return false;
494                 }
495                 g_settings_path = cmd_args.get("config");
496         } else {
497                 std::vector<std::string> filenames;
498                 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
499                 // Legacy configuration file location
500                 filenames.push_back(porting::path_user +
501                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
502
503 #if RUN_IN_PLACE
504                 // Try also from a lower level (to aid having the same configuration
505                 // for many RUN_IN_PLACE installs)
506                 filenames.push_back(porting::path_user +
507                                 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
508 #endif
509
510                 for (size_t i = 0; i < filenames.size(); i++) {
511                         bool r = g_settings->readConfigFile(filenames[i].c_str());
512                         if (r) {
513                                 g_settings_path = filenames[i];
514                                 break;
515                         }
516                 }
517
518                 // If no path found, use the first one (menu creates the file)
519                 if (g_settings_path == "")
520                         g_settings_path = filenames[0];
521         }
522
523         return true;
524 }
525
526 static void init_log_streams(const Settings &cmd_args)
527 {
528 #if RUN_IN_PLACE
529         std::string log_filename = DEBUGFILE;
530 #else
531         std::string log_filename = porting::path_user + DIR_DELIM + DEBUGFILE;
532 #endif
533         if (cmd_args.exists("logfile"))
534                 log_filename = cmd_args.get("logfile");
535
536         g_logger.removeOutput(&file_log_output);
537         std::string conf_loglev = g_settings->get("debug_log_level");
538
539         // Old integer format
540         if (std::isdigit(conf_loglev[0])) {
541                 warningstream << "Deprecated use of debug_log_level with an "
542                         "integer value; please update your configuration." << std::endl;
543                 static const char *lev_name[] =
544                         {"", "error", "action", "info", "verbose"};
545                 int lev_i = atoi(conf_loglev.c_str());
546                 if (lev_i < 0 || lev_i >= (int)ARRLEN(lev_name)) {
547                         warningstream << "Supplied invalid debug_log_level!"
548                                 "  Assuming action level." << std::endl;
549                         lev_i = 2;
550                 }
551                 conf_loglev = lev_name[lev_i];
552         }
553
554         if (log_filename.empty() || conf_loglev.empty())  // No logging
555                 return;
556
557         LogLevel log_level = Logger::stringToLevel(conf_loglev);
558         if (log_level == LL_MAX) {
559                 warningstream << "Supplied unrecognized debug_log_level; "
560                         "using maximum." << std::endl;
561         }
562
563         verbosestream << "log_filename = " << log_filename << std::endl;
564
565         file_log_output.open(log_filename.c_str());
566         g_logger.addOutputMaxLevel(&file_log_output, log_level);
567 }
568
569 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
570 {
571         game_configure_port(game_params, cmd_args);
572
573         if (!game_configure_world(game_params, cmd_args)) {
574                 errorstream << "No world path specified or found." << std::endl;
575                 return false;
576         }
577
578         game_configure_subgame(game_params, cmd_args);
579
580         return true;
581 }
582
583 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
584 {
585         if (cmd_args.exists("port"))
586                 game_params->socket_port = cmd_args.getU16("port");
587         else
588                 game_params->socket_port = g_settings->getU16("port");
589
590         if (game_params->socket_port == 0)
591                 game_params->socket_port = DEFAULT_SERVER_PORT;
592 }
593
594 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
595 {
596         if (get_world_from_cmdline(game_params, cmd_args))
597                 return true;
598         if (get_world_from_config(game_params, cmd_args))
599                 return true;
600
601         return auto_select_world(game_params);
602 }
603
604 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
605 {
606         std::string commanded_world = "";
607
608         // World name
609         std::string commanded_worldname = "";
610         if (cmd_args.exists("worldname"))
611                 commanded_worldname = cmd_args.get("worldname");
612
613         // If a world name was specified, convert it to a path
614         if (commanded_worldname != "") {
615                 // Get information about available worlds
616                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
617                 bool found = false;
618                 for (u32 i = 0; i < worldspecs.size(); i++) {
619                         std::string name = worldspecs[i].name;
620                         if (name == commanded_worldname) {
621                                 dstream << _("Using world specified by --worldname on the "
622                                         "command line") << std::endl;
623                                 commanded_world = worldspecs[i].path;
624                                 found = true;
625                                 break;
626                         }
627                 }
628                 if (!found) {
629                         dstream << _("World") << " '" << commanded_worldname
630                                 << _("' not available. Available worlds:") << std::endl;
631                         print_worldspecs(worldspecs, dstream);
632                         return false;
633                 }
634
635                 game_params->world_path = get_clean_world_path(commanded_world);
636                 return commanded_world != "";
637         }
638
639         if (cmd_args.exists("world"))
640                 commanded_world = cmd_args.get("world");
641         else if (cmd_args.exists("map-dir"))
642                 commanded_world = cmd_args.get("map-dir");
643         else if (cmd_args.exists("nonopt0")) // First nameless argument
644                 commanded_world = cmd_args.get("nonopt0");
645
646         game_params->world_path = get_clean_world_path(commanded_world);
647         return commanded_world != "";
648 }
649
650 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
651 {
652         // World directory
653         std::string commanded_world = "";
654
655         if (g_settings->exists("map-dir"))
656                 commanded_world = g_settings->get("map-dir");
657
658         game_params->world_path = get_clean_world_path(commanded_world);
659
660         return commanded_world != "";
661 }
662
663 static bool auto_select_world(GameParams *game_params)
664 {
665         // No world was specified; try to select it automatically
666         // Get information about available worlds
667
668         verbosestream << _("Determining world path") << std::endl;
669
670         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
671         std::string world_path;
672
673         // If there is only a single world, use it
674         if (worldspecs.size() == 1) {
675                 world_path = worldspecs[0].path;
676                 dstream <<_("Automatically selecting world at") << " ["
677                         << world_path << "]" << std::endl;
678         // If there are multiple worlds, list them
679         } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
680                 std::cerr << _("Multiple worlds are available.") << std::endl;
681                 std::cerr << _("Please select one using --worldname <name>"
682                                 " or --world <path>") << std::endl;
683                 print_worldspecs(worldspecs, std::cerr);
684                 return false;
685         // If there are no worlds, automatically create a new one
686         } else {
687                 // This is the ultimate default world path
688                 world_path = porting::path_user + DIR_DELIM + "worlds" +
689                                 DIR_DELIM + "world";
690                 infostream << "Creating default world at ["
691                            << world_path << "]" << std::endl;
692         }
693
694         assert(world_path != "");       // Post-condition
695         game_params->world_path = world_path;
696         return true;
697 }
698
699 static std::string get_clean_world_path(const std::string &path)
700 {
701         const std::string worldmt = "world.mt";
702         std::string clean_path;
703
704         if (path.size() > worldmt.size()
705                         && path.substr(path.size() - worldmt.size()) == worldmt) {
706                 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
707                 clean_path = path.substr(0, path.size() - worldmt.size());
708         } else {
709                 clean_path = path;
710         }
711         return path;
712 }
713
714
715 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
716 {
717         bool success;
718
719         success = get_game_from_cmdline(game_params, cmd_args);
720         if (!success)
721                 success = determine_subgame(game_params);
722
723         return success;
724 }
725
726 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
727 {
728         SubgameSpec commanded_gamespec;
729
730         if (cmd_args.exists("gameid")) {
731                 std::string gameid = cmd_args.get("gameid");
732                 commanded_gamespec = findSubgame(gameid);
733                 if (!commanded_gamespec.isValid()) {
734                         errorstream << "Game \"" << gameid << "\" not found" << std::endl;
735                         return false;
736                 }
737                 dstream << _("Using game specified by --gameid on the command line")
738                         << std::endl;
739                 game_params->game_spec = commanded_gamespec;
740                 return true;
741         }
742
743         return false;
744 }
745
746 static bool determine_subgame(GameParams *game_params)
747 {
748         SubgameSpec gamespec;
749
750         assert(game_params->world_path != "");  // Pre-condition
751
752         verbosestream << _("Determining gameid/gamespec") << std::endl;
753         // If world doesn't exist
754         if (game_params->world_path != ""
755                         && !getWorldExists(game_params->world_path)) {
756                 // Try to take gamespec from command line
757                 if (game_params->game_spec.isValid()) {
758                         gamespec = game_params->game_spec;
759                         infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
760                 } else { // Otherwise we will be using "minetest"
761                         gamespec = findSubgame(g_settings->get("default_game"));
762                         infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
763                         if (!gamespec.isValid()) {
764                                 errorstream << "Subgame specified in default_game ["
765                                             << g_settings->get("default_game")
766                                             << "] is invalid." << std::endl;
767                                 return false;
768                         }
769                 }
770         } else { // World exists
771                 std::string world_gameid = getWorldGameId(game_params->world_path, false);
772                 // If commanded to use a gameid, do so
773                 if (game_params->game_spec.isValid()) {
774                         gamespec = game_params->game_spec;
775                         if (game_params->game_spec.id != world_gameid) {
776                                 warningstream << "Using commanded gameid ["
777                                             << gamespec.id << "]" << " instead of world gameid ["
778                                             << world_gameid << "]" << std::endl;
779                         }
780                 } else {
781                         // If world contains an embedded game, use it;
782                         // Otherwise find world from local system.
783                         gamespec = findWorldSubgame(game_params->world_path);
784                         infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
785                 }
786         }
787
788         if (!gamespec.isValid()) {
789                 errorstream << "Subgame [" << gamespec.id << "] could not be found."
790                             << std::endl;
791                 return false;
792         }
793
794         game_params->game_spec = gamespec;
795         return true;
796 }
797
798
799 /*****************************************************************************
800  * Dedicated server
801  *****************************************************************************/
802 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
803 {
804         DSTACK("Dedicated server branch");
805
806         verbosestream << _("Using world path") << " ["
807                       << game_params.world_path << "]" << std::endl;
808         verbosestream << _("Using gameid") << " ["
809                       << game_params.game_spec.id << "]" << std::endl;
810
811         // Bind address
812         std::string bind_str = g_settings->get("bind_address");
813         Address bind_addr(0, 0, 0, 0, game_params.socket_port);
814
815         if (g_settings->getBool("ipv6_server")) {
816                 bind_addr.setAddress((IPv6AddressBytes*) NULL);
817         }
818         try {
819                 bind_addr.Resolve(bind_str.c_str());
820         } catch (ResolveError &e) {
821                 infostream << "Resolving bind address \"" << bind_str
822                            << "\" failed: " << e.what()
823                            << " -- Listening on all addresses." << std::endl;
824         }
825         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
826                 errorstream << "Unable to listen on "
827                             << bind_addr.serializeString()
828                             << L" because IPv6 is disabled" << std::endl;
829                 return false;
830         }
831
832         // Database migration
833         if (cmd_args.exists("migrate"))
834                 return migrate_map_database(game_params, cmd_args);
835         else if (cmd_args.exists("migrate-players"))
836                 return ServerEnvironment::migratePlayersDatabase(game_params, cmd_args);
837
838         if (cmd_args.exists("terminal")) {
839 #if USE_CURSES
840                 bool name_ok = true;
841                 std::string admin_nick = g_settings->get("name");
842
843                 name_ok = name_ok && !admin_nick.empty();
844                 name_ok = name_ok && string_allowed(admin_nick, PLAYERNAME_ALLOWED_CHARS);
845
846                 if (!name_ok) {
847                         if (admin_nick.empty()) {
848                                 errorstream << "No name given for admin. "
849                                         << "Please check your minetest.conf that it "
850                                         << "contains a 'name = ' to your main admin account."
851                                         << std::endl;
852                         } else {
853                                 errorstream << "Name for admin '"
854                                         << admin_nick << "' is not valid. "
855                                         << "Please check that it only contains allowed characters. "
856                                         << "Valid characters are: " << PLAYERNAME_ALLOWED_CHARS_USER_EXPL
857                                         << std::endl;
858                         }
859                         return false;
860                 }
861                 ChatInterface iface;
862                 bool &kill = *porting::signal_handler_killstatus();
863
864                 try {
865                         // Create server
866                         Server server(game_params.world_path, game_params.game_spec,
867                                         false, bind_addr.isIPv6(), true, &iface);
868
869                         g_term_console.setup(&iface, &kill, admin_nick);
870
871                         g_term_console.start();
872
873                         server.start(bind_addr);
874                         // Run server
875                         dedicated_server_loop(server, kill);
876                 } catch (const ModError &e) {
877                         g_term_console.stopAndWaitforThread();
878                         errorstream << "ModError: " << e.what() << std::endl;
879                         return false;
880                 } catch (const ServerError &e) {
881                         g_term_console.stopAndWaitforThread();
882                         errorstream << "ServerError: " << e.what() << std::endl;
883                         return false;
884                 }
885
886                 // Tell the console to stop, and wait for it to finish,
887                 // only then leave context and free iface
888                 g_term_console.stop();
889                 g_term_console.wait();
890
891                 g_term_console.clearKillStatus();
892         } else {
893 #else
894                 errorstream << "Cmd arg --terminal passed, but "
895                         << "compiled without ncurses. Ignoring." << std::endl;
896         } {
897 #endif
898                 try {
899                         // Create server
900                         Server server(game_params.world_path, game_params.game_spec, false,
901                                 bind_addr.isIPv6(), true);
902                         server.start(bind_addr);
903
904                         // Run server
905                         bool &kill = *porting::signal_handler_killstatus();
906                         dedicated_server_loop(server, kill);
907
908                 } catch (const ModError &e) {
909                         errorstream << "ModError: " << e.what() << std::endl;
910                         return false;
911                 } catch (const ServerError &e) {
912                         errorstream << "ServerError: " << e.what() << std::endl;
913                         return false;
914                 }
915         }
916
917         return true;
918 }
919
920 static bool migrate_map_database(const GameParams &game_params, const Settings &cmd_args)
921 {
922         std::string migrate_to = cmd_args.get("migrate");
923         Settings world_mt;
924         std::string world_mt_path = game_params.world_path + DIR_DELIM + "world.mt";
925         if (!world_mt.readConfigFile(world_mt_path.c_str())) {
926                 errorstream << "Cannot read world.mt!" << std::endl;
927                 return false;
928         }
929
930         if (!world_mt.exists("backend")) {
931                 errorstream << "Please specify your current backend in world.mt:"
932                         << std::endl
933                         << "    backend = {sqlite3|leveldb|redis|dummy|postgresql}"
934                         << std::endl;
935                 return false;
936         }
937
938         std::string backend = world_mt.get("backend");
939         if (backend == migrate_to) {
940                 errorstream << "Cannot migrate: new backend is same"
941                         << " as the old one" << std::endl;
942                 return false;
943         }
944
945         MapDatabase *old_db = ServerMap::createDatabase(backend, game_params.world_path, world_mt),
946                 *new_db = ServerMap::createDatabase(migrate_to, game_params.world_path, world_mt);
947
948         u32 count = 0;
949         time_t last_update_time = 0;
950         bool &kill = *porting::signal_handler_killstatus();
951
952         std::vector<v3s16> blocks;
953         old_db->listAllLoadableBlocks(blocks);
954         new_db->beginSave();
955         for (std::vector<v3s16>::const_iterator it = blocks.begin(); it != blocks.end(); ++it) {
956                 if (kill) return false;
957
958                 std::string data;
959                 old_db->loadBlock(*it, &data);
960                 if (!data.empty()) {
961                         new_db->saveBlock(*it, data);
962                 } else {
963                         errorstream << "Failed to load block " << PP(*it) << ", skipping it." << std::endl;
964                 }
965                 if (++count % 0xFF == 0 && time(NULL) - last_update_time >= 1) {
966                         std::cerr << " Migrated " << count << " blocks, "
967                                 << (100.0 * count / blocks.size()) << "% completed.\r";
968                         new_db->endSave();
969                         new_db->beginSave();
970                         last_update_time = time(NULL);
971                 }
972         }
973         std::cerr << std::endl;
974         new_db->endSave();
975         delete old_db;
976         delete new_db;
977
978         actionstream << "Successfully migrated " << count << " blocks" << std::endl;
979         world_mt.set("backend", migrate_to);
980         if (!world_mt.updateConfigFile(world_mt_path.c_str()))
981                 errorstream << "Failed to update world.mt!" << std::endl;
982         else
983                 actionstream << "world.mt updated" << std::endl;
984
985         return true;
986 }