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