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