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