Fix MSVC compiling error (argc/argv not available to pass to init_gettext)
[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 NDEBUG
21         /*#ifdef _WIN32
22                 #pragma message ("Disabling unit tests")
23         #else
24                 #warning "Disabling unit tests"
25         #endif*/
26         // Disable unit tests
27         #define ENABLE_TESTS 0
28 #else
29         // Enable unit tests
30         #define ENABLE_TESTS 1
31 #endif
32
33 #ifdef _MSC_VER
34 #ifndef SERVER // Dedicated server isn't linked with Irrlicht
35         #pragma comment(lib, "Irrlicht.lib")
36         // This would get rid of the console window
37         //#pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
38 #endif
39         #pragma comment(lib, "zlibwapi.lib")
40         #pragma comment(lib, "Shell32.lib")
41 #endif
42
43 #include "irrlicht.h" // createDevice
44
45 #include "main.h"
46 #include "mainmenumanager.h"
47 #include <iostream>
48 #include <fstream>
49 #include <locale.h>
50 #include "irrlichttypes_extrabloated.h"
51 #include "debug.h"
52 #include "test.h"
53 #include "clouds.h"
54 #include "server.h"
55 #include "constants.h"
56 #include "porting.h"
57 #include "gettime.h"
58 #include "filesys.h"
59 #include "config.h"
60 #include "version.h"
61 #include "guiMainMenu.h"
62 #include "game.h"
63 #include "keycode.h"
64 #include "tile.h"
65 #include "chat.h"
66 #include "defaultsettings.h"
67 #include "gettext.h"
68 #include "settings.h"
69 #include "profiler.h"
70 #include "log.h"
71 #include "mods.h"
72 #if USE_FREETYPE
73 #include "xCGUITTFont.h"
74 #endif
75 #include "util/string.h"
76 #include "subgame.h"
77 #include "quicktune.h"
78 #include "serverlist.h"
79 #include "httpfetch.h"
80 #include "guiEngine.h"
81 #include "mapsector.h"
82 #include "player.h"
83
84 #include "database-sqlite3.h"
85 #ifdef USE_LEVELDB
86 #include "database-leveldb.h"
87 #endif
88
89 #if USE_REDIS
90 #include "database-redis.h"
91 #endif
92
93 #ifdef HAVE_TOUCHSCREENGUI
94 #include "touchscreengui.h"
95 #endif
96
97 /*
98         Settings.
99         These are loaded from the config file.
100 */
101 static Settings main_settings;
102 Settings *g_settings = &main_settings;
103 std::string g_settings_path;
104
105 // Global profiler
106 Profiler main_profiler;
107 Profiler *g_profiler = &main_profiler;
108
109 // Menu clouds are created later
110 Clouds *g_menuclouds = 0;
111 irr::scene::ISceneManager *g_menucloudsmgr = 0;
112
113 /*
114         Debug streams
115 */
116
117 // Connection
118 std::ostream *dout_con_ptr = &dummyout;
119 std::ostream *derr_con_ptr = &verbosestream;
120
121 // Server
122 std::ostream *dout_server_ptr = &infostream;
123 std::ostream *derr_server_ptr = &errorstream;
124
125 // Client
126 std::ostream *dout_client_ptr = &infostream;
127 std::ostream *derr_client_ptr = &errorstream;
128
129 #define DEBUGFILE "debug.txt"
130 #define DEFAULT_SERVER_PORT 30000
131
132 typedef std::map<std::string, ValueSpec> OptionList;
133
134 struct GameParams {
135         u16 socket_port;
136         std::string world_path;
137         SubgameSpec game_spec;
138         bool is_dedicated_server;
139         int log_level;
140 };
141
142 /**********************************************************************
143  * Private functions
144  **********************************************************************/
145
146 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
147 static void set_allowed_options(OptionList *allowed_options);
148
149 static void print_help(const OptionList &allowed_options);
150 static void print_allowed_options(const OptionList &allowed_options);
151 static void print_version();
152 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
153                                                          std::ostream &os);
154 static void print_modified_quicktune_values();
155
156 static void list_game_ids();
157 static void list_worlds();
158 static void setup_log_params(const Settings &cmd_args);
159 static bool create_userdata_path();
160 static bool init_common(int *log_level, const Settings &cmd_args, int argc, char *argv[]);
161 static void startup_message();
162 static bool read_config_file(const Settings &cmd_args);
163 static void init_debug_streams(int *log_level, const Settings &cmd_args);
164
165 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
166 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
167
168 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
169 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
170 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
171 static bool auto_select_world(GameParams *game_params);
172 static std::string get_clean_world_path(const std::string &path);
173
174 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
175 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
176 static bool determine_subgame(GameParams *game_params);
177
178 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
179 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args,
180                 Server *server);
181
182 #ifndef SERVER
183 static bool print_video_modes();
184 static void speed_tests();
185 #endif
186
187 /**********************************************************************/
188
189 #ifndef SERVER
190 /*
191         Random stuff
192 */
193
194 /* mainmenumanager.h */
195
196 gui::IGUIEnvironment* guienv = NULL;
197 gui::IGUIStaticText *guiroot = NULL;
198 MainMenuManager g_menumgr;
199
200 bool noMenuActive()
201 {
202         return (g_menumgr.menuCount() == 0);
203 }
204
205 // Passed to menus to allow disconnecting and exiting
206 MainGameCallback *g_gamecallback = NULL;
207 #endif
208
209 /*
210         gettime.h implementation
211 */
212
213 #ifdef SERVER
214
215 u32 getTimeMs()
216 {
217         /* Use imprecise system calls directly (from porting.h) */
218         return porting::getTime(PRECISION_MILLI);
219 }
220
221 u32 getTime(TimePrecision prec)
222 {
223         return porting::getTime(prec);
224 }
225
226 #else
227
228 // A small helper class
229 class TimeGetter
230 {
231 public:
232         virtual u32 getTime(TimePrecision prec) = 0;
233 };
234
235 // A precise irrlicht one
236 class IrrlichtTimeGetter: public TimeGetter
237 {
238 public:
239         IrrlichtTimeGetter(IrrlichtDevice *device):
240                 m_device(device)
241         {}
242         u32 getTime(TimePrecision prec)
243         {
244                 if (prec == PRECISION_MILLI) {
245                         if (m_device == NULL)
246                                 return 0;
247                         return m_device->getTimer()->getRealTime();
248                 } else {
249                         return porting::getTime(prec);
250                 }
251         }
252 private:
253         IrrlichtDevice *m_device;
254 };
255 // Not so precise one which works without irrlicht
256 class SimpleTimeGetter: public TimeGetter
257 {
258 public:
259         u32 getTime(TimePrecision prec)
260         {
261                 return porting::getTime(prec);
262         }
263 };
264
265 // A pointer to a global instance of the time getter
266 // TODO: why?
267 TimeGetter *g_timegetter = NULL;
268
269 u32 getTimeMs()
270 {
271         if (g_timegetter == NULL)
272                 return 0;
273         return g_timegetter->getTime(PRECISION_MILLI);
274 }
275
276 u32 getTime(TimePrecision prec) {
277         if (g_timegetter == NULL)
278                 return 0;
279         return g_timegetter->getTime(prec);
280 }
281 #endif
282
283 class StderrLogOutput: public ILogOutput
284 {
285 public:
286         /* line: Full line with timestamp, level and thread */
287         void printLog(const std::string &line)
288         {
289                 std::cerr << line << std::endl;
290         }
291 } main_stderr_log_out;
292
293 class DstreamNoStderrLogOutput: public ILogOutput
294 {
295 public:
296         /* line: Full line with timestamp, level and thread */
297         void printLog(const std::string &line)
298         {
299                 dstream_no_stderr << line << std::endl;
300         }
301 } main_dstream_no_stderr_log_out;
302
303 #ifndef SERVER
304
305 /*
306         Event handler for Irrlicht
307
308         NOTE: Everything possible should be moved out from here,
309               probably to InputHandler and the_game
310 */
311
312 class MyEventReceiver : public IEventReceiver
313 {
314 public:
315         // This is the one method that we have to implement
316         virtual bool OnEvent(const SEvent& event)
317         {
318                 /*
319                         React to nothing here if a menu is active
320                 */
321                 if (noMenuActive() == false) {
322 #ifdef HAVE_TOUCHSCREENGUI
323                         if (m_touchscreengui != 0) {
324                                 m_touchscreengui->Toggle(false);
325                         }
326 #endif
327                         return g_menumgr.preprocessEvent(event);
328                 }
329
330                 // Remember whether each key is down or up
331                 if (event.EventType == irr::EET_KEY_INPUT_EVENT) {
332                         if (event.KeyInput.PressedDown) {
333                                 keyIsDown.set(event.KeyInput);
334                                 keyWasDown.set(event.KeyInput);
335                         } else {
336                                 keyIsDown.unset(event.KeyInput);
337                         }
338                 }
339
340 #ifdef HAVE_TOUCHSCREENGUI
341                 // case of touchscreengui we have to handle different events
342                 if ((m_touchscreengui != 0) &&
343                                 (event.EventType == irr::EET_TOUCH_INPUT_EVENT)) {
344                         m_touchscreengui->translateEvent(event);
345                         return true;
346                 }
347 #endif
348                 // handle mouse events
349                 if (event.EventType == irr::EET_MOUSE_INPUT_EVENT) {
350                         if (noMenuActive() == false) {
351                                 left_active = false;
352                                 middle_active = false;
353                                 right_active = false;
354                         } else {
355                                 left_active = event.MouseInput.isLeftPressed();
356                                 middle_active = event.MouseInput.isMiddlePressed();
357                                 right_active = event.MouseInput.isRightPressed();
358
359                                 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
360                                         leftclicked = true;
361                                 }
362                                 if (event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN) {
363                                         rightclicked = true;
364                                 }
365                                 if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
366                                         leftreleased = true;
367                                 }
368                                 if (event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP) {
369                                         rightreleased = true;
370                                 }
371                                 if (event.MouseInput.Event == EMIE_MOUSE_WHEEL) {
372                                         mouse_wheel += event.MouseInput.Wheel;
373                                 }
374                         }
375                 }
376                 if (event.EventType == irr::EET_LOG_TEXT_EVENT) {
377                         dstream << std::string("Irrlicht log: ") + std::string(event.LogEvent.Text)
378                                 << std::endl;
379                         return true;
380                 }
381                 /* always return false in order to continue processing events */
382                 return false;
383         }
384
385         bool IsKeyDown(const KeyPress &keyCode) const
386         {
387                 return keyIsDown[keyCode];
388         }
389
390         // Checks whether a key was down and resets the state
391         bool WasKeyDown(const KeyPress &keyCode)
392         {
393                 bool b = keyWasDown[keyCode];
394                 if (b)
395                         keyWasDown.unset(keyCode);
396                 return b;
397         }
398
399         s32 getMouseWheel()
400         {
401                 s32 a = mouse_wheel;
402                 mouse_wheel = 0;
403                 return a;
404         }
405
406         void clearInput()
407         {
408                 keyIsDown.clear();
409                 keyWasDown.clear();
410
411                 leftclicked = false;
412                 rightclicked = false;
413                 leftreleased = false;
414                 rightreleased = false;
415
416                 left_active = false;
417                 middle_active = false;
418                 right_active = false;
419
420                 mouse_wheel = 0;
421         }
422
423         MyEventReceiver()
424         {
425                 clearInput();
426 #ifdef HAVE_TOUCHSCREENGUI
427                 m_touchscreengui = NULL;
428 #endif
429         }
430
431         bool leftclicked;
432         bool rightclicked;
433         bool leftreleased;
434         bool rightreleased;
435
436         bool left_active;
437         bool middle_active;
438         bool right_active;
439
440         s32 mouse_wheel;
441
442 #ifdef HAVE_TOUCHSCREENGUI
443         TouchScreenGUI* m_touchscreengui;
444 #endif
445
446 private:
447         // The current state of keys
448         KeyList keyIsDown;
449         // Whether a key has been pressed or not
450         KeyList keyWasDown;
451 };
452
453 /*
454         Separated input handler
455 */
456
457 class RealInputHandler : public InputHandler
458 {
459 public:
460         RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
461                 m_device(device),
462                 m_receiver(receiver),
463                 m_mousepos(0,0)
464         {
465         }
466         virtual bool isKeyDown(const KeyPress &keyCode)
467         {
468                 return m_receiver->IsKeyDown(keyCode);
469         }
470         virtual bool wasKeyDown(const KeyPress &keyCode)
471         {
472                 return m_receiver->WasKeyDown(keyCode);
473         }
474         virtual v2s32 getMousePos()
475         {
476                 if (m_device->getCursorControl()) {
477                         return m_device->getCursorControl()->getPosition();
478                 }
479                 else {
480                         return m_mousepos;
481                 }
482         }
483         virtual void setMousePos(s32 x, s32 y)
484         {
485                 if (m_device->getCursorControl()) {
486                         m_device->getCursorControl()->setPosition(x, y);
487                 }
488                 else {
489                         m_mousepos = v2s32(x,y);
490                 }
491         }
492
493         virtual bool getLeftState()
494         {
495                 return m_receiver->left_active;
496         }
497         virtual bool getRightState()
498         {
499                 return m_receiver->right_active;
500         }
501
502         virtual bool getLeftClicked()
503         {
504                 return m_receiver->leftclicked;
505         }
506         virtual bool getRightClicked()
507         {
508                 return m_receiver->rightclicked;
509         }
510         virtual void resetLeftClicked()
511         {
512                 m_receiver->leftclicked = false;
513         }
514         virtual void resetRightClicked()
515         {
516                 m_receiver->rightclicked = false;
517         }
518
519         virtual bool getLeftReleased()
520         {
521                 return m_receiver->leftreleased;
522         }
523         virtual bool getRightReleased()
524         {
525                 return m_receiver->rightreleased;
526         }
527         virtual void resetLeftReleased()
528         {
529                 m_receiver->leftreleased = false;
530         }
531         virtual void resetRightReleased()
532         {
533                 m_receiver->rightreleased = false;
534         }
535
536         virtual s32 getMouseWheel()
537         {
538                 return m_receiver->getMouseWheel();
539         }
540
541         void clear()
542         {
543                 m_receiver->clearInput();
544         }
545 private:
546         IrrlichtDevice  *m_device;
547         MyEventReceiver *m_receiver;
548         v2s32           m_mousepos;
549 };
550
551 class RandomInputHandler : public InputHandler
552 {
553 public:
554         RandomInputHandler()
555         {
556                 leftdown = false;
557                 rightdown = false;
558                 leftclicked = false;
559                 rightclicked = false;
560                 leftreleased = false;
561                 rightreleased = false;
562                 keydown.clear();
563         }
564         virtual bool isKeyDown(const KeyPress &keyCode)
565         {
566                 return keydown[keyCode];
567         }
568         virtual bool wasKeyDown(const KeyPress &keyCode)
569         {
570                 return false;
571         }
572         virtual v2s32 getMousePos()
573         {
574                 return mousepos;
575         }
576         virtual void setMousePos(s32 x, s32 y)
577         {
578                 mousepos = v2s32(x, y);
579         }
580
581         virtual bool getLeftState()
582         {
583                 return leftdown;
584         }
585         virtual bool getRightState()
586         {
587                 return rightdown;
588         }
589
590         virtual bool getLeftClicked()
591         {
592                 return leftclicked;
593         }
594         virtual bool getRightClicked()
595         {
596                 return rightclicked;
597         }
598         virtual void resetLeftClicked()
599         {
600                 leftclicked = false;
601         }
602         virtual void resetRightClicked()
603         {
604                 rightclicked = false;
605         }
606
607         virtual bool getLeftReleased()
608         {
609                 return leftreleased;
610         }
611         virtual bool getRightReleased()
612         {
613                 return rightreleased;
614         }
615         virtual void resetLeftReleased()
616         {
617                 leftreleased = false;
618         }
619         virtual void resetRightReleased()
620         {
621                 rightreleased = false;
622         }
623
624         virtual s32 getMouseWheel()
625         {
626                 return 0;
627         }
628
629         virtual void step(float dtime)
630         {
631                 {
632                         static float counter1 = 0;
633                         counter1 -= dtime;
634                         if (counter1 < 0.0) {
635                                 counter1 = 0.1 * Rand(1, 40);
636                                 keydown.toggle(getKeySetting("keymap_jump"));
637                         }
638                 }
639                 {
640                         static float counter1 = 0;
641                         counter1 -= dtime;
642                         if (counter1 < 0.0) {
643                                 counter1 = 0.1 * Rand(1, 40);
644                                 keydown.toggle(getKeySetting("keymap_special1"));
645                         }
646                 }
647                 {
648                         static float counter1 = 0;
649                         counter1 -= dtime;
650                         if (counter1 < 0.0) {
651                                 counter1 = 0.1 * Rand(1, 40);
652                                 keydown.toggle(getKeySetting("keymap_forward"));
653                         }
654                 }
655                 {
656                         static float counter1 = 0;
657                         counter1 -= dtime;
658                         if (counter1 < 0.0) {
659                                 counter1 = 0.1 * Rand(1, 40);
660                                 keydown.toggle(getKeySetting("keymap_left"));
661                         }
662                 }
663                 {
664                         static float counter1 = 0;
665                         counter1 -= dtime;
666                         if (counter1 < 0.0) {
667                                 counter1 = 0.1 * Rand(1, 20);
668                                 mousespeed = v2s32(Rand(-20, 20), Rand(-15, 20));
669                         }
670                 }
671                 {
672                         static float counter1 = 0;
673                         counter1 -= dtime;
674                         if (counter1 < 0.0) {
675                                 counter1 = 0.1 * Rand(1, 30);
676                                 leftdown = !leftdown;
677                                 if (leftdown)
678                                         leftclicked = true;
679                                 if (!leftdown)
680                                         leftreleased = true;
681                         }
682                 }
683                 {
684                         static float counter1 = 0;
685                         counter1 -= dtime;
686                         if (counter1 < 0.0) {
687                                 counter1 = 0.1 * Rand(1, 15);
688                                 rightdown = !rightdown;
689                                 if (rightdown)
690                                         rightclicked = true;
691                                 if (!rightdown)
692                                         rightreleased = true;
693                         }
694                 }
695                 mousepos += mousespeed;
696         }
697
698         s32 Rand(s32 min, s32 max)
699         {
700                 return (myrand()%(max-min+1))+min;
701         }
702 private:
703         KeyList keydown;
704         v2s32 mousepos;
705         v2s32 mousespeed;
706         bool leftdown;
707         bool rightdown;
708         bool leftclicked;
709         bool rightclicked;
710         bool leftreleased;
711         bool rightreleased;
712 };
713
714
715 class ClientLauncher
716 {
717 public:
718         ClientLauncher() :
719                 list_video_modes(false),
720                 skip_main_menu(false),
721                 use_freetype(false),
722                 random_input(false),
723                 address(""),
724                 playername(""),
725                 password(""),
726                 device(NULL),
727                 input(NULL),
728                 receiver(NULL),
729                 skin(NULL),
730                 font(NULL),
731                 simple_singleplayer_mode(false),
732                 current_playername("inv£lid"),
733                 current_password(""),
734                 current_address("does-not-exist"),
735                 current_port(0)
736         {}
737
738         ~ClientLauncher();
739
740         bool run(GameParams &game_params, const Settings &cmd_args);
741
742 protected:
743         void init_args(GameParams &game_params, const Settings &cmd_args);
744         bool init_engine(int log_level);
745
746         bool launch_game(std::wstring *error_message, GameParams &game_params,
747                         const Settings &cmd_args);
748
749         void main_menu(MainMenuData *menudata);
750         bool create_engine_device(int log_level);
751
752         bool list_video_modes;
753         bool skip_main_menu;
754         bool use_freetype;
755         bool random_input;
756         std::string address;
757         std::string playername;
758         std::string password;
759         IrrlichtDevice *device;
760         InputHandler *input;
761         MyEventReceiver *receiver;
762         gui::IGUISkin *skin;
763         gui::IGUIFont *font;
764         scene::ISceneManager *smgr;
765         SubgameSpec gamespec;
766         WorldSpec worldspec;
767         bool simple_singleplayer_mode;
768
769         // These are set up based on the menu and other things
770         // TODO: Are these required since there's already playername, password, etc
771         std::string current_playername;
772         std::string current_password;
773         std::string current_address;
774         int current_port;
775 };
776
777 #endif // !SERVER
778
779 static OptionList allowed_options;
780
781 int main(int argc, char *argv[])
782 {
783         int retval;
784
785         log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
786         log_add_output_all_levs(&main_dstream_no_stderr_log_out);
787
788         log_register_thread("main");
789
790         Settings cmd_args;
791         bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
792         if (!cmd_args_ok
793                         || cmd_args.getFlag("help")
794                         || cmd_args.exists("nonopt1")) {
795                 print_help(allowed_options);
796                 return cmd_args_ok ? 0 : 1;
797         }
798
799         if (cmd_args.getFlag("version")) {
800                 print_version();
801                 return 0;
802         }
803
804         setup_log_params(cmd_args);
805
806         porting::signal_handler_init();
807         porting::initializePaths();
808
809         if (!create_userdata_path()) {
810                 errorstream << "Cannot create user data directory" << std::endl;
811                 return 1;
812         }
813
814         // Initialize debug stacks
815         debug_stacks_init();
816         DSTACK(__FUNCTION_NAME);
817
818         // Debug handler
819         BEGIN_DEBUG_EXCEPTION_HANDLER
820
821         // List gameids if requested
822         if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
823                 list_game_ids();
824                 return 0;
825         }
826
827         // List worlds if requested
828         if (cmd_args.exists("world") && cmd_args.get("world") == "list") {
829                 list_worlds();
830                 return 0;
831         }
832
833         GameParams game_params;
834         if (!init_common(&game_params.log_level, cmd_args, argc, argv))
835                 return 1;
836
837 #ifndef __ANDROID__
838         // Run unit tests
839         if ((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
840                         || cmd_args.getFlag("enable-unittests") == true) {
841                 run_tests();
842         }
843 #endif
844
845 #ifdef SERVER
846         game_params.is_dedicated_server = true;
847 #else
848         game_params.is_dedicated_server = cmd_args.getFlag("server");
849 #endif
850
851         if (!game_configure(&game_params, cmd_args))
852                 return 1;
853
854         assert(game_params.world_path != "");
855
856         infostream << "Using commanded world path ["
857                    << game_params.world_path << "]" << std::endl;
858
859         //Run dedicated server if asked to or no other option
860         g_settings->set("server_dedicated",
861                         game_params.is_dedicated_server ? "true" : "false");
862
863         if (game_params.is_dedicated_server)
864                 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
865
866 #ifndef SERVER
867         ClientLauncher launcher;
868         retval = launcher.run(game_params, cmd_args) ? 0 : 1;
869 #else
870         retval = 0;
871 #endif
872
873         // Update configuration file
874         if (g_settings_path != "")
875                 g_settings->updateConfigFile(g_settings_path.c_str());
876
877         print_modified_quicktune_values();
878
879         // Stop httpfetch thread (if started)
880         httpfetch_cleanup();
881
882         END_DEBUG_EXCEPTION_HANDLER(errorstream)
883
884         return retval;
885 }
886
887
888 /*****************************************************************************
889  * Startup / Init
890  *****************************************************************************/
891
892
893 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
894 {
895         set_allowed_options(&allowed_options);
896
897         return cmd_args->parseCommandLine(argc, argv, allowed_options);
898 }
899
900 static void set_allowed_options(OptionList *allowed_options)
901 {
902         allowed_options->clear();
903
904         allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
905                         _("Show allowed options"))));
906         allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
907                         _("Show version information"))));
908         allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
909                         _("Load configuration from specified file"))));
910         allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
911                         _("Set network port (UDP)"))));
912         allowed_options->insert(std::make_pair("disable-unittests", ValueSpec(VALUETYPE_FLAG,
913                         _("Disable unit tests"))));
914         allowed_options->insert(std::make_pair("enable-unittests", ValueSpec(VALUETYPE_FLAG,
915                         _("Enable unit tests"))));
916         allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
917                         _("Same as --world (deprecated)"))));
918         allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
919                         _("Set world path (implies local game) ('list' lists all)"))));
920         allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
921                         _("Set world by name (implies local game)"))));
922         allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
923                         _("Print to console errors only"))));
924         allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
925                         _("Print more information to console"))));
926         allowed_options->insert(std::make_pair("verbose",  ValueSpec(VALUETYPE_FLAG,
927                         _("Print even more information to console"))));
928         allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
929                         _("Print enormous amounts of information to log and console"))));
930         allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
931                         _("Set logfile path ('' = no logging)"))));
932         allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
933                         _("Set gameid (\"--gameid list\" prints available ones)"))));
934         allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
935                         _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
936 #ifndef SERVER
937         allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
938                         _("Show available video modes"))));
939         allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
940                         _("Run speed tests"))));
941         allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
942                         _("Address to connect to. ('' = local game)"))));
943         allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
944                         _("Enable random user input, for testing"))));
945         allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
946                         _("Run dedicated server"))));
947         allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
948                         _("Set player name"))));
949         allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
950                         _("Set password"))));
951         allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
952                         _("Disable main menu"))));
953 #endif
954
955 }
956
957 static void print_help(const OptionList &allowed_options)
958 {
959         dstream << _("Allowed options:") << std::endl;
960         print_allowed_options(allowed_options);
961 }
962
963 static void print_allowed_options(const OptionList &allowed_options)
964 {
965         for (OptionList::const_iterator i = allowed_options.begin();
966                         i != allowed_options.end(); ++i) {
967                 std::ostringstream os1(std::ios::binary);
968                 os1 << "  --" << i->first;
969                 if (i->second.type != VALUETYPE_FLAG)
970                         os1 << _(" <value>");
971
972                 dstream << padStringRight(os1.str(), 24);
973
974                 if (i->second.help != NULL)
975                         dstream << i->second.help;
976
977                 dstream << std::endl;
978         }
979 }
980
981 static void print_version()
982 {
983 #ifdef SERVER
984         dstream << "minetestserver " << minetest_version_hash << std::endl;
985 #else
986         dstream << "Minetest " << minetest_version_hash << std::endl;
987         dstream << "Using Irrlicht " << IRRLICHT_SDK_VERSION << std::endl;
988 #endif
989         dstream << "Build info: " << minetest_build_info << std::endl;
990 }
991
992 static void list_game_ids()
993 {
994         std::set<std::string> gameids = getAvailableGameIds();
995         for (std::set<std::string>::const_iterator i = gameids.begin();
996                         i != gameids.end(); i++)
997                 dstream << (*i) <<std::endl;
998 }
999
1000 static void list_worlds()
1001 {
1002         dstream << _("Available worlds:") << std::endl;
1003         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1004         print_worldspecs(worldspecs, dstream);
1005 }
1006
1007 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
1008                                                          std::ostream &os)
1009 {
1010         for (size_t i = 0; i < worldspecs.size(); i++) {
1011                 std::string name = worldspecs[i].name;
1012                 std::string path = worldspecs[i].path;
1013                 if (name.find(" ") != std::string::npos)
1014                         name = std::string("'") + name + "'";
1015                 path = std::string("'") + path + "'";
1016                 name = padStringRight(name, 14);
1017                 os << "  " << name << " " << path << std::endl;
1018         }
1019 }
1020
1021 static void print_modified_quicktune_values()
1022 {
1023         bool header_printed = false;
1024         std::vector<std::string> names = getQuicktuneNames();
1025
1026         for (u32 i = 0; i < names.size(); i++) {
1027                 QuicktuneValue val = getQuicktuneValue(names[i]);
1028                 if (!val.modified)
1029                         continue;
1030                 if (!header_printed) {
1031                         dstream << "Modified quicktune values:" << std::endl;
1032                         header_printed = true;
1033                 }
1034                 dstream << names[i] << " = " << val.getString() << std::endl;
1035         }
1036 }
1037
1038 static void setup_log_params(const Settings &cmd_args)
1039 {
1040         // Quiet mode, print errors only
1041         if (cmd_args.getFlag("quiet")) {
1042                 log_remove_output(&main_stderr_log_out);
1043                 log_add_output_maxlev(&main_stderr_log_out, LMT_ERROR);
1044         }
1045
1046         // If trace is enabled, enable logging of certain things
1047         if (cmd_args.getFlag("trace")) {
1048                 dstream << _("Enabling trace level debug output") << std::endl;
1049                 log_trace_level_enabled = true;
1050                 dout_con_ptr = &verbosestream; // this is somewhat old crap
1051                 socket_enable_debug_output = true; // socket doesn't use log.h
1052         }
1053
1054         // In certain cases, output info level on stderr
1055         if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
1056                         cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
1057                 log_add_output(&main_stderr_log_out, LMT_INFO);
1058
1059         // In certain cases, output verbose level on stderr
1060         if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
1061                 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
1062 }
1063
1064 static bool create_userdata_path()
1065 {
1066         bool success;
1067
1068 #ifdef __ANDROID__
1069         porting::initAndroid();
1070
1071         porting::setExternalStorageDir(porting::jnienv);
1072         if (!fs::PathExists(porting::path_user)) {
1073                 success = fs::CreateDir(porting::path_user);
1074         } else {
1075                 success = true;
1076         }
1077         porting::copyAssets();
1078 #else
1079         // Create user data directory
1080         success = fs::CreateDir(porting::path_user);
1081 #endif
1082
1083         infostream << "path_share = " << porting::path_share << std::endl;
1084         infostream << "path_user  = " << porting::path_user << std::endl;
1085
1086         return success;
1087 }
1088
1089 static bool init_common(int *log_level, const Settings &cmd_args, int argc, char *argv[])
1090 {
1091         startup_message();
1092         set_default_settings(g_settings);
1093
1094         // Initialize sockets
1095         sockets_init();
1096         atexit(sockets_cleanup);
1097
1098         if (!read_config_file(cmd_args))
1099                 return false;
1100
1101         init_debug_streams(log_level, cmd_args);
1102
1103         // Initialize random seed
1104         srand(time(0));
1105         mysrand(time(0));
1106
1107         // Initialize HTTP fetcher
1108         httpfetch_init(g_settings->getS32("curl_parallel_limit"));
1109
1110 #ifdef _MSC_VER
1111         init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),
1112                 g_settings->get("language"), argc, argv);
1113 #else
1114         init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),
1115                 g_settings->get("language"));
1116 #endif
1117
1118         return true;
1119 }
1120
1121 static void startup_message()
1122 {
1123         infostream << PROJECT_NAME << " " << _("with")
1124                    << " SER_FMT_VER_HIGHEST_READ="
1125                << (int)SER_FMT_VER_HIGHEST_READ << ", "
1126                << minetest_build_info << std::endl;
1127 }
1128
1129 static bool read_config_file(const Settings &cmd_args)
1130 {
1131         // Path of configuration file in use
1132         assert(g_settings_path == "");  // Sanity check
1133
1134         if (cmd_args.exists("config")) {
1135                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
1136                 if (!r) {
1137                         errorstream << "Could not read configuration from \""
1138                                     << cmd_args.get("config") << "\"" << std::endl;
1139                         return false;
1140                 }
1141                 g_settings_path = cmd_args.get("config");
1142         } else {
1143                 std::vector<std::string> filenames;
1144                 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
1145                 // Legacy configuration file location
1146                 filenames.push_back(porting::path_user +
1147                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1148
1149 #if RUN_IN_PLACE
1150                 // Try also from a lower level (to aid having the same configuration
1151                 // for many RUN_IN_PLACE installs)
1152                 filenames.push_back(porting::path_user +
1153                                 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1154 #endif
1155
1156                 for (size_t i = 0; i < filenames.size(); i++) {
1157                         bool r = g_settings->readConfigFile(filenames[i].c_str());
1158                         if (r) {
1159                                 g_settings_path = filenames[i];
1160                                 break;
1161                         }
1162                 }
1163
1164                 // If no path found, use the first one (menu creates the file)
1165                 if (g_settings_path == "")
1166                         g_settings_path = filenames[0];
1167         }
1168
1169         return true;
1170 }
1171
1172 static void init_debug_streams(int *log_level, const Settings &cmd_args)
1173 {
1174 #if RUN_IN_PLACE
1175         std::string logfile = DEBUGFILE;
1176 #else
1177         std::string logfile = porting::path_user + DIR_DELIM + DEBUGFILE;
1178 #endif
1179         if (cmd_args.exists("logfile"))
1180                 logfile = cmd_args.get("logfile");
1181
1182         log_remove_output(&main_dstream_no_stderr_log_out);
1183         *log_level = g_settings->getS32("debug_log_level");
1184
1185         if (*log_level == 0) //no logging
1186                 logfile = "";
1187         if (*log_level < 0) {
1188                 dstream << "WARNING: Supplied debug_log_level < 0; Using 0" << std::endl;
1189                 *log_level = 0;
1190         } else if (*log_level > LMT_NUM_VALUES) {
1191                 dstream << "WARNING: Supplied debug_log_level > " << LMT_NUM_VALUES
1192                         << "; Using " << LMT_NUM_VALUES << std::endl;
1193                 *log_level = LMT_NUM_VALUES;
1194         }
1195
1196         log_add_output_maxlev(&main_dstream_no_stderr_log_out,
1197                         (LogMessageLevel)(*log_level - 1));
1198
1199         debugstreams_init(false, logfile == "" ? NULL : logfile.c_str());
1200
1201         infostream << "logfile = " << logfile << std::endl;
1202
1203         atexit(debugstreams_deinit);
1204 }
1205
1206 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
1207 {
1208         game_configure_port(game_params, cmd_args);
1209
1210         if (!game_configure_world(game_params, cmd_args)) {
1211                 errorstream << "No world path specified or found." << std::endl;
1212                 return false;
1213         }
1214
1215         game_configure_subgame(game_params, cmd_args);
1216
1217         return true;
1218 }
1219
1220 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
1221 {
1222         if (cmd_args.exists("port"))
1223                 game_params->socket_port = cmd_args.getU16("port");
1224         else
1225                 game_params->socket_port = g_settings->getU16("port");
1226
1227         if (game_params->socket_port == 0)
1228                 game_params->socket_port = DEFAULT_SERVER_PORT;
1229 }
1230
1231 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
1232 {
1233         if (get_world_from_cmdline(game_params, cmd_args))
1234                 return true;
1235         if (get_world_from_config(game_params, cmd_args))
1236                 return true;
1237
1238         return auto_select_world(game_params);
1239 }
1240
1241 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
1242 {
1243         std::string commanded_world = "";
1244
1245         // World name
1246         std::string commanded_worldname = "";
1247         if (cmd_args.exists("worldname"))
1248                 commanded_worldname = cmd_args.get("worldname");
1249
1250         // If a world name was specified, convert it to a path
1251         if (commanded_worldname != "") {
1252                 // Get information about available worlds
1253                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1254                 bool found = false;
1255                 for (u32 i = 0; i < worldspecs.size(); i++) {
1256                         std::string name = worldspecs[i].name;
1257                         if (name == commanded_worldname) {
1258                                 dstream << _("Using world specified by --worldname on the "
1259                                         "command line") << std::endl;
1260                                 commanded_world = worldspecs[i].path;
1261                                 found = true;
1262                                 break;
1263                         }
1264                 }
1265                 if (!found) {
1266                         dstream << _("World") << " '" << commanded_worldname
1267                                 << _("' not available. Available worlds:") << std::endl;
1268                         print_worldspecs(worldspecs, dstream);
1269                         return false;
1270                 }
1271
1272                 game_params->world_path = get_clean_world_path(commanded_world);
1273                 return commanded_world != "";
1274         }
1275
1276         if (cmd_args.exists("world"))
1277                 commanded_world = cmd_args.get("world");
1278         else if (cmd_args.exists("map-dir"))
1279                 commanded_world = cmd_args.get("map-dir");
1280         else if (cmd_args.exists("nonopt0")) // First nameless argument
1281                 commanded_world = cmd_args.get("nonopt0");
1282
1283         game_params->world_path = get_clean_world_path(commanded_world);
1284         return commanded_world != "";
1285 }
1286
1287 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
1288 {
1289         // World directory
1290         std::string commanded_world = "";
1291
1292         if (g_settings->exists("map-dir"))
1293                 commanded_world = g_settings->get("map-dir");
1294
1295         game_params->world_path = get_clean_world_path(commanded_world);
1296
1297         return commanded_world != "";
1298 }
1299
1300 static bool auto_select_world(GameParams *game_params)
1301 {
1302         // No world was specified; try to select it automatically
1303         // Get information about available worlds
1304
1305         verbosestream << _("Determining world path") << std::endl;
1306
1307         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1308         std::string world_path;
1309
1310         // If there is only a single world, use it
1311         if (worldspecs.size() == 1) {
1312                 world_path = worldspecs[0].path;
1313                 dstream <<_("Automatically selecting world at") << " ["
1314                         << world_path << "]" << std::endl;
1315         // If there are multiple worlds, list them
1316         } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
1317                 dstream << _("Multiple worlds are available.") << std::endl;
1318                 dstream << _("Please select one using --worldname <name>"
1319                                 " or --world <path>") << std::endl;
1320                 print_worldspecs(worldspecs, dstream);
1321                 return false;
1322         // If there are no worlds, automatically create a new one
1323         } else {
1324                 // This is the ultimate default world path
1325                 world_path = porting::path_user + DIR_DELIM + "worlds" +
1326                                 DIR_DELIM + "world";
1327                 infostream << "Creating default world at ["
1328                            << world_path << "]" << std::endl;
1329         }
1330
1331         assert(world_path != "");
1332         game_params->world_path = world_path;
1333         return true;
1334 }
1335
1336 static std::string get_clean_world_path(const std::string &path)
1337 {
1338         const std::string worldmt = "world.mt";
1339         std::string clean_path;
1340
1341         if (path.size() > worldmt.size()
1342                         && path.substr(path.size() - worldmt.size()) == worldmt) {
1343                 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
1344                 clean_path = path.substr(0, path.size() - worldmt.size());
1345         } else {
1346                 clean_path = path;
1347         }
1348         return path;
1349 }
1350
1351
1352 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
1353 {
1354         bool success;
1355
1356         success = get_game_from_cmdline(game_params, cmd_args);
1357         if (!success)
1358                 success = determine_subgame(game_params);
1359
1360         return success;
1361 }
1362
1363 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
1364 {
1365         SubgameSpec commanded_gamespec;
1366
1367         if (cmd_args.exists("gameid")) {
1368                 std::string gameid = cmd_args.get("gameid");
1369                 commanded_gamespec = findSubgame(gameid);
1370                 if (!commanded_gamespec.isValid()) {
1371                         errorstream << "Game \"" << gameid << "\" not found" << std::endl;
1372                         return false;
1373                 }
1374                 dstream << _("Using game specified by --gameid on the command line")
1375                         << std::endl;
1376                 game_params->game_spec = commanded_gamespec;
1377                 return true;
1378         }
1379
1380         return false;
1381 }
1382
1383 static bool determine_subgame(GameParams *game_params)
1384 {
1385         SubgameSpec gamespec;
1386
1387         assert(game_params->world_path != "");  // pre-condition
1388
1389         verbosestream << _("Determining gameid/gamespec") << std::endl;
1390         // If world doesn't exist
1391         if (game_params->world_path != ""
1392                         && !getWorldExists(game_params->world_path)) {
1393                 // Try to take gamespec from command line
1394                 if (game_params->game_spec.isValid()) {
1395                         gamespec = game_params->game_spec;
1396                         infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
1397                 } else { // Otherwise we will be using "minetest"
1398                         gamespec = findSubgame(g_settings->get("default_game"));
1399                         infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
1400                 }
1401         } else { // World exists
1402                 std::string world_gameid = getWorldGameId(game_params->world_path, false);
1403                 // If commanded to use a gameid, do so
1404                 if (game_params->game_spec.isValid()) {
1405                         gamespec = game_params->game_spec;
1406                         if (game_params->game_spec.id != world_gameid) {
1407                                 errorstream << "WARNING: Using commanded gameid ["
1408                                             << gamespec.id << "]" << " instead of world gameid ["
1409                                             << world_gameid << "]" << std::endl;
1410                         }
1411                 } else {
1412                         // If world contains an embedded game, use it;
1413                         // Otherwise find world from local system.
1414                         gamespec = findWorldSubgame(game_params->world_path);
1415                         infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
1416                 }
1417         }
1418
1419         if (!gamespec.isValid()) {
1420                 errorstream << "Subgame [" << gamespec.id << "] could not be found."
1421                             << std::endl;
1422                 return false;
1423         }
1424
1425         game_params->game_spec = gamespec;
1426         return true;
1427 }
1428
1429
1430 /*****************************************************************************
1431  * Dedicated server
1432  *****************************************************************************/
1433 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
1434 {
1435         DSTACK("Dedicated server branch");
1436
1437         verbosestream << _("Using world path") << " ["
1438                       << game_params.world_path << "]" << std::endl;
1439         verbosestream << _("Using gameid") << " ["
1440                       << game_params.game_spec.id << "]" << std::endl;
1441
1442         // Bind address
1443         std::string bind_str = g_settings->get("bind_address");
1444         Address bind_addr(0, 0, 0, 0, game_params.socket_port);
1445
1446         if (g_settings->getBool("ipv6_server")) {
1447                 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1448         }
1449         try {
1450                 bind_addr.Resolve(bind_str.c_str());
1451         } catch (ResolveError &e) {
1452                 infostream << "Resolving bind address \"" << bind_str
1453                            << "\" failed: " << e.what()
1454                            << " -- Listening on all addresses." << std::endl;
1455         }
1456         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1457                 errorstream << "Unable to listen on "
1458                             << bind_addr.serializeString()
1459                             << L" because IPv6 is disabled" << std::endl;
1460                 return false;
1461         }
1462
1463         // Create server
1464         Server server(game_params.world_path,
1465                         game_params.game_spec, false, bind_addr.isIPv6());
1466
1467         // Database migration
1468         if (cmd_args.exists("migrate"))
1469                 return migrate_database(game_params, cmd_args, &server);
1470
1471         server.start(bind_addr);
1472
1473         // Run server
1474         bool &kill = *porting::signal_handler_killstatus();
1475         dedicated_server_loop(server, kill);
1476
1477         return true;
1478 }
1479
1480 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args,
1481                 Server *server)
1482 {
1483         Settings world_mt;
1484         bool success = world_mt.readConfigFile((game_params.world_path
1485                         + DIR_DELIM + "world.mt").c_str());
1486         if (!success) {
1487                 errorstream << "Cannot read world.mt" << std::endl;
1488                 return false;
1489         }
1490
1491         if (!world_mt.exists("backend")) {
1492                 errorstream << "Please specify your current backend in world.mt file:"
1493                             << std::endl << "   backend = {sqlite3|leveldb|redis|dummy}"
1494                             << std::endl;
1495                 return false;
1496         }
1497
1498         std::string backend = world_mt.get("backend");
1499         Database *new_db;
1500         std::string migrate_to = cmd_args.get("migrate");
1501
1502         if (backend == migrate_to) {
1503                 errorstream << "Cannot migrate: new backend is same as the old one"
1504                             << std::endl;
1505                 return false;
1506         }
1507
1508         if (migrate_to == "sqlite3")
1509                 new_db = new Database_SQLite3(&(ServerMap&)server->getMap(),
1510                                 game_params.world_path);
1511 #if USE_LEVELDB
1512         else if (migrate_to == "leveldb")
1513                 new_db = new Database_LevelDB(&(ServerMap&)server->getMap(),
1514                                 game_params.world_path);
1515 #endif
1516 #if USE_REDIS
1517         else if (migrate_to == "redis")
1518                 new_db = new Database_Redis(&(ServerMap&)server->getMap(),
1519                                 game_params.world_path);
1520 #endif
1521         else {
1522                 errorstream << "Migration to " << migrate_to << " is not supported"
1523                             << std::endl;
1524                 return false;
1525         }
1526
1527         std::list<v3s16> blocks;
1528         ServerMap &old_map = ((ServerMap&)server->getMap());
1529         old_map.listAllLoadableBlocks(blocks);
1530         int count = 0;
1531         new_db->beginSave();
1532         for (std::list<v3s16>::iterator i = blocks.begin(); i != blocks.end(); i++) {
1533                 MapBlock *block = old_map.loadBlock(*i);
1534                 if (!block) {
1535                         errorstream << "Failed to load block " << PP(*i) << ", skipping it.";
1536                 } else {
1537                         old_map.saveBlock(block, new_db);
1538                         MapSector *sector = old_map.getSectorNoGenerate(v2s16(i->X, i->Z));
1539                         sector->deleteBlock(block);
1540                 }
1541                 ++count;
1542                 if (count % 500 == 0)
1543                    actionstream << "Migrated " << count << " blocks "
1544                            << (100.0 * count / blocks.size()) << "% completed" << std::endl;
1545         }
1546         new_db->endSave();
1547         delete new_db;
1548
1549         actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1550         world_mt.set("backend", migrate_to);
1551         if (!world_mt.updateConfigFile(
1552                                 (game_params.world_path+ DIR_DELIM + "world.mt").c_str()))
1553                 errorstream << "Failed to update world.mt!" << std::endl;
1554         else
1555                 actionstream << "world.mt updated" << std::endl;
1556
1557         return true;
1558 }
1559
1560
1561 /*****************************************************************************
1562  * Client
1563  *****************************************************************************/
1564 #ifndef SERVER
1565
1566 ClientLauncher::~ClientLauncher()
1567 {
1568         if (receiver)
1569                 delete receiver;
1570
1571         if (input)
1572                 delete input;
1573
1574         if (device)
1575                 device->drop();
1576
1577 #if USE_FREETYPE
1578         if (use_freetype && font != NULL)
1579                 font->drop();
1580 #endif
1581 }
1582
1583 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
1584 {
1585         init_args(game_params, cmd_args);
1586
1587         // List video modes if requested
1588         if (list_video_modes)
1589                 return print_video_modes();
1590
1591         if (!init_engine(game_params.log_level)) {
1592                 errorstream << "Could not initialize game engine." << std::endl;
1593                 return false;
1594         }
1595
1596         late_init_default_settings(g_settings);
1597
1598         // Speed tests (done after irrlicht is loaded to get timer)
1599         if (cmd_args.getFlag("speedtests")) {
1600                 dstream << "Running speed tests" << std::endl;
1601                 speed_tests();
1602                 return true;
1603         }
1604
1605         if (device->getVideoDriver() == NULL) {
1606                 errorstream << "Could not initialize video driver." << std::endl;
1607                 return false;
1608         }
1609
1610         /*
1611                 This changes the minimum allowed number of vertices in a VBO.
1612                 Default is 500.
1613         */
1614         //driver->setMinHardwareBufferVertexCount(50);
1615
1616         // Create time getter
1617         g_timegetter = new IrrlichtTimeGetter(device);
1618
1619         // Create game callback for menus
1620         g_gamecallback = new MainGameCallback(device);
1621
1622         device->setResizable(true);
1623
1624         if (random_input)
1625                 input = new RandomInputHandler();
1626         else
1627                 input = new RealInputHandler(device, receiver);
1628
1629         smgr = device->getSceneManager();
1630
1631         guienv = device->getGUIEnvironment();
1632         skin = guienv->getSkin();
1633         std::string font_path = g_settings->get("font_path");
1634
1635 #if USE_FREETYPE
1636
1637         if (use_freetype) {
1638                 std::string fallback;
1639                 if (is_yes(gettext("needs_fallback_font")))
1640                         fallback = "fallback_";
1641                 u16 font_size = g_settings->getU16(fallback + "font_size");
1642                 font_path = g_settings->get(fallback + "font_path");
1643                 u32 font_shadow = g_settings->getU16(fallback + "font_shadow");
1644                 u32 font_shadow_alpha = g_settings->getU16(fallback + "font_shadow_alpha");
1645                 font = gui::CGUITTFont::createTTFont(guienv,
1646                                 font_path.c_str(), font_size, true, true,
1647                                 font_shadow, font_shadow_alpha);
1648         } else {
1649                 font = guienv->getFont(font_path.c_str());
1650         }
1651 #else
1652         font = guienv->getFont(font_path.c_str());
1653 #endif
1654         if (font)
1655                 skin->setFont(font);
1656         else
1657                 errorstream << "WARNING: Font file was not found. Using default font."
1658                             << std::endl;
1659
1660         font = skin->getFont(); // If font was not found, this will get us one
1661         assert(font);
1662
1663         u32 text_height = font->getDimension(L"Hello, world!").Height;
1664         infostream << "text_height=" << text_height << std::endl;
1665
1666         skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
1667         skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 0, 0, 0));
1668         skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
1669         skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 100, 50));
1670         skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
1671
1672 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1673         // Irrlicht 1.8 input colours
1674         skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
1675         skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
1676 #endif
1677
1678         // Create the menu clouds
1679         if (!g_menucloudsmgr)
1680                 g_menucloudsmgr = smgr->createNewSceneManager();
1681         if (!g_menuclouds)
1682                 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1683                                 g_menucloudsmgr, -1, rand(), 100);
1684         g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
1685         scene::ICameraSceneNode* camera;
1686         camera = g_menucloudsmgr->addCameraSceneNode(0,
1687                                 v3f(0, 0, 0), v3f(0, 60, 100));
1688         camera->setFarValue(10000);
1689
1690         /*
1691                 GUI stuff
1692         */
1693
1694         ChatBackend chat_backend;
1695
1696         // If an error occurs, this is set to something by menu().
1697         // It is then displayed before  the menu shows on the next call to menu()
1698         std::wstring error_message = L"";
1699
1700         bool first_loop = true;
1701
1702         /*
1703                 Menu-game loop
1704         */
1705         bool retval = true;
1706         bool *kill = porting::signal_handler_killstatus();
1707
1708         while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
1709         {
1710                 // Set the window caption
1711                 wchar_t *text = wgettext("Main Menu");
1712                 device->setWindowCaption((std::wstring(L"Minetest [") + text + L"]").c_str());
1713                 delete[] text;
1714
1715                 try {   // This is used for catching disconnects
1716
1717                         guienv->clear();
1718
1719                         /*
1720                                 We need some kind of a root node to be able to add
1721                                 custom gui elements directly on the screen.
1722                                 Otherwise they won't be automatically drawn.
1723                         */
1724                         guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
1725
1726                         bool game_has_run = launch_game(&error_message, game_params, cmd_args);
1727
1728                         // If skip_main_menu, we only want to startup once
1729                         if (skip_main_menu && !first_loop)
1730                                 break;
1731
1732                         first_loop = false;
1733
1734                         if (!game_has_run) {
1735                                 if (skip_main_menu)
1736                                         break;
1737                                 else
1738                                         continue;
1739                         }
1740
1741                         // Break out of menu-game loop to shut down cleanly
1742                         if (!device->run() || *kill) {
1743                                 if (g_settings_path != "")
1744                                         g_settings->updateConfigFile(g_settings_path.c_str());
1745                                 break;
1746                         }
1747
1748                         if (current_playername.length() > PLAYERNAME_SIZE-1) {
1749                                 error_message = wgettext("Player name too long.");
1750                                 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
1751                                 g_settings->set("name", playername);
1752                                 continue;
1753                         }
1754
1755                         device->getVideoDriver()->setTextureCreationFlag(
1756                                         video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
1757
1758 #ifdef HAVE_TOUCHSCREENGUI
1759                         receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
1760                         g_touchscreengui = receiver->m_touchscreengui;
1761 #endif
1762                         the_game(
1763                                 kill,
1764                                 random_input,
1765                                 input,
1766                                 device,
1767                                 font,
1768                                 worldspec.path,
1769                                 current_playername,
1770                                 current_password,
1771                                 current_address,
1772                                 current_port,
1773                                 error_message,
1774                                 chat_backend,
1775                                 gamespec,
1776                                 simple_singleplayer_mode
1777                         );
1778                         smgr->clear();
1779
1780 #ifdef HAVE_TOUCHSCREENGUI
1781                         delete g_touchscreengui;
1782                         g_touchscreengui = NULL;
1783                         receiver->m_touchscreengui = NULL;
1784 #endif
1785
1786                 } //try
1787                 catch (con::PeerNotFoundException &e) {
1788                         error_message = wgettext("Connection error (timed out?)");
1789                         errorstream << wide_to_narrow(error_message) << std::endl;
1790                 }
1791
1792 #ifdef NDEBUG
1793                 catch (std::exception &e) {
1794                         std::string narrow_message = "Some exception: \"";
1795                         narrow_message += e.what();
1796                         narrow_message += "\"";
1797                         errorstream << narrow_message << std::endl;
1798                         error_message = narrow_to_wide(narrow_message);
1799                 }
1800 #endif
1801
1802                 // If no main menu, show error and exit
1803                 if (skip_main_menu) {
1804                         if (error_message != L"") {
1805                                 verbosestream << "error_message = "
1806                                               << wide_to_narrow(error_message) << std::endl;
1807                                 retval = false;
1808                         }
1809                         break;
1810                 }
1811         } // Menu-game loop
1812
1813         g_menuclouds->drop();
1814         g_menucloudsmgr->drop();
1815
1816         return retval;
1817 }
1818
1819 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
1820 {
1821
1822         skip_main_menu = cmd_args.getFlag("go");
1823
1824         // FIXME: This is confusing (but correct)
1825
1826         /* If world_path is set then override it unless skipping the main menu using
1827          * the --go command line param. Else, give preference to the address
1828          * supplied on the command line
1829          */
1830         address = g_settings->get("address");
1831         if (game_params.world_path != "" && !skip_main_menu)
1832                 address = "";
1833         else if (cmd_args.exists("address"))
1834                 address = cmd_args.get("address");
1835
1836         playername = g_settings->get("name");
1837         if (cmd_args.exists("name"))
1838                 playername = cmd_args.get("name");
1839
1840         list_video_modes = cmd_args.getFlag("videomodes");
1841
1842         use_freetype = g_settings->getBool("freetype");
1843
1844         random_input = g_settings->getBool("random_input")
1845                         || cmd_args.getFlag("random-input");
1846 }
1847
1848 bool ClientLauncher::init_engine(int log_level)
1849 {
1850         receiver = new MyEventReceiver();
1851         create_engine_device(log_level);
1852         return device != NULL;
1853 }
1854
1855 bool ClientLauncher::launch_game(std::wstring *error_message,
1856                 GameParams &game_params, const Settings &cmd_args)
1857 {
1858         // Initialize menu data
1859         MainMenuData menudata;
1860         menudata.address      = address;
1861         menudata.name         = playername;
1862         menudata.port         = itos(game_params.socket_port);
1863         menudata.errormessage = wide_to_narrow(*error_message);
1864
1865         *error_message = L"";
1866
1867         if (cmd_args.exists("password"))
1868                 menudata.password = cmd_args.get("password");
1869
1870         menudata.enable_public = g_settings->getBool("server_announce");
1871
1872         // If a world was commanded, append and select it
1873         if (game_params.world_path != "") {
1874                 worldspec.gameid = getWorldGameId(game_params.world_path, true);
1875                 worldspec.name = _("[--world parameter]");
1876
1877                 if (worldspec.gameid == "") {   // Create new
1878                         worldspec.gameid = g_settings->get("default_game");
1879                         worldspec.name += " [new]";
1880                 }
1881                 worldspec.path = game_params.world_path;
1882         }
1883
1884         /* Show the GUI menu
1885          */
1886         if (!skip_main_menu) {
1887                 main_menu(&menudata);
1888
1889                 address = menudata.address;
1890                 int newport = stoi(menudata.port);
1891                 if (newport != 0)
1892                         game_params.socket_port = newport;
1893
1894                 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1895
1896                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1897                 worldspecs = getAvailableWorlds();
1898
1899                 if (menudata.selected_world >= 0
1900                                 && menudata.selected_world < (int)worldspecs.size()) {
1901                         g_settings->set("selected_world_path",
1902                                         worldspecs[menudata.selected_world].path);
1903                         worldspec = worldspecs[menudata.selected_world];
1904                 }
1905         }
1906
1907         if (menudata.errormessage != "") {
1908                 /* The calling function will pass this back into this function upon the
1909                  * next iteration (if any) causing it to be displayed by the GUI
1910                  */
1911                 *error_message = narrow_to_wide(menudata.errormessage);
1912                 return false;
1913         }
1914
1915         if (menudata.name == "")
1916                 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
1917         else
1918                 playername = menudata.name;
1919
1920         password = translatePassword(playername, narrow_to_wide(menudata.password));
1921
1922         g_settings->set("name", playername);
1923
1924         current_playername = playername;
1925         current_password   = password;
1926         current_address    = address;
1927         current_port       = game_params.socket_port;
1928
1929         // If using simple singleplayer mode, override
1930         if (simple_singleplayer_mode) {
1931                 assert(skip_main_menu == false);
1932                 current_playername = "singleplayer";
1933                 current_password = "";
1934                 current_address = "";
1935                 current_port = myrand_range(49152, 65535);
1936         } else if (address != "") {
1937                 ServerListSpec server;
1938                 server["name"] = menudata.servername;
1939                 server["address"] = menudata.address;
1940                 server["port"] = menudata.port;
1941                 server["description"] = menudata.serverdescription;
1942                 ServerList::insert(server);
1943         }
1944
1945         infostream << "Selected world: " << worldspec.name
1946                    << " [" << worldspec.path << "]" << std::endl;
1947
1948         if (current_address == "") { // If local game
1949                 if (worldspec.path == "") {
1950                         *error_message = wgettext("No world selected and no address "
1951                                         "provided. Nothing to do.");
1952                         errorstream << wide_to_narrow(*error_message) << std::endl;
1953                         return false;
1954                 }
1955
1956                 if (!fs::PathExists(worldspec.path)) {
1957                         *error_message = wgettext("Provided world path doesn't exist: ")
1958                                         + narrow_to_wide(worldspec.path);
1959                         errorstream << wide_to_narrow(*error_message) << std::endl;
1960                         return false;
1961                 }
1962
1963                 // Load gamespec for required game
1964                 gamespec = findWorldSubgame(worldspec.path);
1965                 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
1966                         *error_message = wgettext("Could not find or load game \"")
1967                                         + narrow_to_wide(worldspec.gameid) + L"\"";
1968                         errorstream << wide_to_narrow(*error_message) << std::endl;
1969                         return false;
1970                 }
1971                 if (game_params.game_spec.isValid() &&
1972                                 game_params.game_spec.id != worldspec.gameid) {
1973                         errorstream << "WARNING: Overriding gamespec from \""
1974                                     << worldspec.gameid << "\" to \""
1975                                     << game_params.game_spec.id << "\"" << std::endl;
1976                         gamespec = game_params.game_spec;
1977                 }
1978
1979                 if (!gamespec.isValid()) {
1980                         *error_message = wgettext("Invalid gamespec.");
1981                         *error_message += L" (world_gameid="
1982                                         + narrow_to_wide(worldspec.gameid) + L")";
1983                         errorstream << wide_to_narrow(*error_message) << std::endl;
1984                         return false;
1985                 }
1986         }
1987
1988         return true;
1989 }
1990
1991 void ClientLauncher::main_menu(MainMenuData *menudata)
1992 {
1993         bool *kill = porting::signal_handler_killstatus();
1994         video::IVideoDriver *driver = device->getVideoDriver();
1995
1996         infostream << "Waiting for other menus" << std::endl;
1997         while (device->run() && *kill == false) {
1998                 if (noMenuActive())
1999                         break;
2000                 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
2001                 guienv->drawAll();
2002                 driver->endScene();
2003                 // On some computers framerate doesn't seem to be automatically limited
2004                 sleep_ms(25);
2005         }
2006         infostream << "Waited for other menus" << std::endl;
2007
2008         // Cursor can be non-visible when coming from the game
2009 #ifndef ANDROID
2010         device->getCursorControl()->setVisible(true);
2011 #endif
2012
2013         /* show main menu */
2014         GUIEngine mymenu(device, guiroot, &g_menumgr, smgr, menudata, *kill);
2015
2016         smgr->clear();  /* leave scene manager in a clean state */
2017 }
2018
2019 bool ClientLauncher::create_engine_device(int log_level)
2020 {
2021         static const char *driverids[] = {
2022                 "null",
2023                 "software",
2024                 "burningsvideo",
2025                 "direct3d8",
2026                 "direct3d9",
2027                 "opengl"
2028 #ifdef _IRR_COMPILE_WITH_OGLES1_
2029                 ,"ogles1"
2030 #endif
2031 #ifdef _IRR_COMPILE_WITH_OGLES2_
2032                 ,"ogles2"
2033 #endif
2034                 ,"invalid"
2035         };
2036
2037         static const irr::ELOG_LEVEL irr_log_level[5] = {
2038                 ELL_NONE,
2039                 ELL_ERROR,
2040                 ELL_WARNING,
2041                 ELL_INFORMATION,
2042 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
2043                 ELL_INFORMATION
2044 #else
2045                 ELL_DEBUG
2046 #endif
2047         };
2048
2049         // Resolution selection
2050         bool fullscreen = g_settings->getBool("fullscreen");
2051         u16 screenW = g_settings->getU16("screenW");
2052         u16 screenH = g_settings->getU16("screenH");
2053
2054         // bpp, fsaa, vsync
2055         bool vsync = g_settings->getBool("vsync");
2056         u16 bits = g_settings->getU16("fullscreen_bpp");
2057         u16 fsaa = g_settings->getU16("fsaa");
2058
2059         // Determine driver
2060         video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
2061
2062         std::string driverstring = g_settings->get("video_driver");
2063         for (size_t i = 0; i < sizeof driverids / sizeof driverids[0]; i++) {
2064                 if (strcasecmp(driverstring.c_str(), driverids[i]) == 0) {
2065                         driverType = (video::E_DRIVER_TYPE) i;
2066                         break;
2067                 }
2068
2069                 if (strcasecmp("invalid", driverids[i]) == 0) {
2070                         errorstream << "WARNING: Invalid video_driver specified;"
2071                                     << " defaulting to opengl" << std::endl;
2072                         break;
2073                 }
2074         }
2075
2076         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2077         params.DriverType    = driverType;
2078         params.WindowSize    = core::dimension2d<u32>(screenW, screenH);
2079         params.Bits          = bits;
2080         params.AntiAlias     = fsaa;
2081         params.Fullscreen    = fullscreen;
2082         params.Stencilbuffer = false;
2083         params.Vsync         = vsync;
2084         params.EventReceiver = receiver;
2085         params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2086 #ifdef __ANDROID__
2087         params.PrivateData = porting::app_global;
2088         params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
2089                         "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
2090 #endif
2091
2092         device = createDeviceEx(params);
2093
2094         if (device) {
2095                 // Map our log level to irrlicht engine one.
2096                 ILogger* irr_logger = device->getLogger();
2097                 irr_logger->setLogLevel(irr_log_level[log_level]);
2098
2099                 porting::initIrrlicht(device);
2100         }
2101
2102         return device != NULL;
2103 }
2104
2105 // Misc functions
2106
2107 static bool print_video_modes()
2108 {
2109         IrrlichtDevice *nulldevice;
2110
2111         bool vsync = g_settings->getBool("vsync");
2112         u16 fsaa = g_settings->getU16("fsaa");
2113         MyEventReceiver* receiver = new MyEventReceiver();
2114
2115         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2116         params.DriverType    = video::EDT_NULL;
2117         params.WindowSize    = core::dimension2d<u32>(640, 480);
2118         params.Bits          = 24;
2119         params.AntiAlias     = fsaa;
2120         params.Fullscreen    = false;
2121         params.Stencilbuffer = false;
2122         params.Vsync         = vsync;
2123         params.EventReceiver = receiver;
2124         params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2125
2126         nulldevice = createDeviceEx(params);
2127
2128         if (nulldevice == NULL) {
2129                 delete receiver;
2130                 return false;
2131         }
2132
2133         dstream << _("Available video modes (WxHxD):") << std::endl;
2134
2135         video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
2136
2137         if (videomode_list != NULL) {
2138                 s32 videomode_count = videomode_list->getVideoModeCount();
2139                 core::dimension2d<u32> videomode_res;
2140                 s32 videomode_depth;
2141                 for (s32 i = 0; i < videomode_count; ++i) {
2142                         videomode_res = videomode_list->getVideoModeResolution(i);
2143                         videomode_depth = videomode_list->getVideoModeDepth(i);
2144                         dstream << videomode_res.Width << "x" << videomode_res.Height
2145                                 << "x" << videomode_depth << std::endl;
2146                 }
2147
2148                 dstream << _("Active video mode (WxHxD):") << std::endl;
2149                 videomode_res = videomode_list->getDesktopResolution();
2150                 videomode_depth = videomode_list->getDesktopDepth();
2151                 dstream << videomode_res.Width << "x" << videomode_res.Height
2152                         << "x" << videomode_depth << std::endl;
2153
2154         }
2155
2156         nulldevice->drop();
2157         delete receiver;
2158
2159         return videomode_list != NULL;
2160 }
2161
2162 #endif // !SERVER
2163
2164 /*****************************************************************************
2165  * Performance tests
2166  *****************************************************************************/
2167 #ifndef SERVER
2168 static void speed_tests()
2169 {
2170         // volatile to avoid some potential compiler optimisations
2171         volatile static s16 temp16;
2172         volatile static f32 tempf;
2173         static v3f tempv3f1;
2174         static v3f tempv3f2;
2175         static std::string tempstring;
2176         static std::string tempstring2;
2177
2178         tempv3f1 = v3f();
2179         tempv3f2 = v3f();
2180         tempstring = std::string();
2181         tempstring2 = std::string();
2182
2183         {
2184                 infostream << "The following test should take around 20ms." << std::endl;
2185                 TimeTaker timer("Testing std::string speed");
2186                 const u32 jj = 10000;
2187                 for (u32 j = 0; j < jj; j++) {
2188                         tempstring = "";
2189                         tempstring2 = "";
2190                         const u32 ii = 10;
2191                         for (u32 i = 0; i < ii; i++) {
2192                                 tempstring2 += "asd";
2193                         }
2194                         for (u32 i = 0; i < ii+1; i++) {
2195                                 tempstring += "asd";
2196                                 if (tempstring == tempstring2)
2197                                         break;
2198                         }
2199                 }
2200         }
2201
2202         infostream << "All of the following tests should take around 100ms each."
2203                    << std::endl;
2204
2205         {
2206                 TimeTaker timer("Testing floating-point conversion speed");
2207                 tempf = 0.001;
2208                 for (u32 i = 0; i < 4000000; i++) {
2209                         temp16 += tempf;
2210                         tempf += 0.001;
2211                 }
2212         }
2213
2214         {
2215                 TimeTaker timer("Testing floating-point vector speed");
2216
2217                 tempv3f1 = v3f(1, 2, 3);
2218                 tempv3f2 = v3f(4, 5, 6);
2219                 for (u32 i = 0; i < 10000000; i++) {
2220                         tempf += tempv3f1.dotProduct(tempv3f2);
2221                         tempv3f2 += v3f(7, 8, 9);
2222                 }
2223         }
2224
2225         {
2226                 TimeTaker timer("Testing std::map speed");
2227
2228                 std::map<v2s16, f32> map1;
2229                 tempf = -324;
2230                 const s16 ii = 300;
2231                 for (s16 y = 0; y < ii; y++) {
2232                         for (s16 x = 0; x < ii; x++) {
2233                                 map1[v2s16(x, y)] =  tempf;
2234                                 tempf += 1;
2235                         }
2236                 }
2237                 for (s16 y = ii - 1; y >= 0; y--) {
2238                         for (s16 x = 0; x < ii; x++) {
2239                                 tempf = map1[v2s16(x, y)];
2240                         }
2241                 }
2242         }
2243
2244         {
2245                 infostream << "Around 5000/ms should do well here." << std::endl;
2246                 TimeTaker timer("Testing mutex speed");
2247
2248                 JMutex m;
2249                 u32 n = 0;
2250                 u32 i = 0;
2251                 do {
2252                         n += 10000;
2253                         for (; i < n; i++) {
2254                                 m.Lock();
2255                                 m.Unlock();
2256                         }
2257                 }
2258                 // Do at least 10ms
2259                 while(timer.getTimerTime() < 10);
2260
2261                 u32 dtime = timer.stop();
2262                 u32 per_ms = n / dtime;
2263                 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
2264         }
2265 }
2266 #endif