]> git.lizzy.rs Git - dragonfireclient.git/blob - src/main.cpp
8ba24f307d6e6fdd89b8855cc205485adbe1cc5e
[dragonfireclient.git] / src / main.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #ifdef 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);
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))
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         }
1075         porting::copyAssets();
1076 #else
1077         // Create user data directory
1078         success = fs::CreateDir(porting::path_user);
1079 #endif
1080
1081         infostream << "path_share = " << porting::path_share << std::endl;
1082         infostream << "path_user  = " << porting::path_user << std::endl;
1083
1084         return success;
1085 }
1086
1087 static bool init_common(int *log_level, const Settings &cmd_args)
1088 {
1089         startup_message();
1090         set_default_settings(g_settings);
1091
1092         // Initialize sockets
1093         sockets_init();
1094         atexit(sockets_cleanup);
1095
1096         if (!read_config_file(cmd_args))
1097                 return false;
1098
1099         init_debug_streams(log_level, cmd_args);
1100
1101         // Initialize random seed
1102         srand(time(0));
1103         mysrand(time(0));
1104
1105         // Initialize HTTP fetcher
1106         httpfetch_init(g_settings->getS32("curl_parallel_limit"));
1107
1108 #ifdef _MSC_VER
1109         init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),
1110                 g_settings->get("language"), argc, argv);
1111 #else
1112         init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),
1113                 g_settings->get("language"));
1114 #endif
1115
1116         return true;
1117 }
1118
1119 static void startup_message()
1120 {
1121         infostream << PROJECT_NAME << " " << _("with")
1122                    << " SER_FMT_VER_HIGHEST_READ="
1123                << (int)SER_FMT_VER_HIGHEST_READ << ", "
1124                << minetest_build_info << std::endl;
1125 }
1126
1127 static bool read_config_file(const Settings &cmd_args)
1128 {
1129         // Path of configuration file in use
1130         assert(g_settings_path == "");  // Sanity check
1131
1132         if (cmd_args.exists("config")) {
1133                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
1134                 if (!r) {
1135                         errorstream << "Could not read configuration from \""
1136                                     << cmd_args.get("config") << "\"" << std::endl;
1137                         return false;
1138                 }
1139                 g_settings_path = cmd_args.get("config");
1140         } else {
1141                 std::vector<std::string> filenames;
1142                 filenames.push_back(porting::path_user + DIR_DELIM + "minetest.conf");
1143                 // Legacy configuration file location
1144                 filenames.push_back(porting::path_user +
1145                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1146
1147 #if RUN_IN_PLACE
1148                 // Try also from a lower level (to aid having the same configuration
1149                 // for many RUN_IN_PLACE installs)
1150                 filenames.push_back(porting::path_user +
1151                                 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1152 #endif
1153
1154                 for (size_t i = 0; i < filenames.size(); i++) {
1155                         bool r = g_settings->readConfigFile(filenames[i].c_str());
1156                         if (r) {
1157                                 g_settings_path = filenames[i];
1158                                 break;
1159                         }
1160                 }
1161
1162                 // If no path found, use the first one (menu creates the file)
1163                 if (g_settings_path == "")
1164                         g_settings_path = filenames[0];
1165         }
1166
1167         return true;
1168 }
1169
1170 static void init_debug_streams(int *log_level, const Settings &cmd_args)
1171 {
1172 #if RUN_IN_PLACE
1173         std::string logfile = DEBUGFILE;
1174 #else
1175         std::string logfile = porting::path_user + DIR_DELIM + DEBUGFILE;
1176 #endif
1177         if (cmd_args.exists("logfile"))
1178                 logfile = cmd_args.get("logfile");
1179
1180         log_remove_output(&main_dstream_no_stderr_log_out);
1181         *log_level = g_settings->getS32("debug_log_level");
1182
1183         if (*log_level == 0) //no logging
1184                 logfile = "";
1185         if (*log_level < 0) {
1186                 dstream << "WARNING: Supplied debug_log_level < 0; Using 0" << std::endl;
1187                 *log_level = 0;
1188         } else if (*log_level > LMT_NUM_VALUES) {
1189                 dstream << "WARNING: Supplied debug_log_level > " << LMT_NUM_VALUES
1190                         << "; Using " << LMT_NUM_VALUES << std::endl;
1191                 *log_level = LMT_NUM_VALUES;
1192         }
1193
1194         log_add_output_maxlev(&main_dstream_no_stderr_log_out,
1195                         (LogMessageLevel)(*log_level - 1));
1196
1197         debugstreams_init(false, logfile == "" ? NULL : logfile.c_str());
1198
1199         infostream << "logfile = " << logfile << std::endl;
1200
1201         atexit(debugstreams_deinit);
1202 }
1203
1204 static bool game_configure(GameParams *game_params, const Settings &cmd_args)
1205 {
1206         game_configure_port(game_params, cmd_args);
1207
1208         if (!game_configure_world(game_params, cmd_args)) {
1209                 errorstream << "No world path specified or found." << std::endl;
1210                 return false;
1211         }
1212
1213         game_configure_subgame(game_params, cmd_args);
1214
1215         return true;
1216 }
1217
1218 static void game_configure_port(GameParams *game_params, const Settings &cmd_args)
1219 {
1220         if (cmd_args.exists("port"))
1221                 game_params->socket_port = cmd_args.getU16("port");
1222         else
1223                 game_params->socket_port = g_settings->getU16("port");
1224
1225         if (game_params->socket_port == 0)
1226                 game_params->socket_port = DEFAULT_SERVER_PORT;
1227 }
1228
1229 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args)
1230 {
1231         if (get_world_from_cmdline(game_params, cmd_args))
1232                 return true;
1233         if (get_world_from_config(game_params, cmd_args))
1234                 return true;
1235
1236         return auto_select_world(game_params);
1237 }
1238
1239 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args)
1240 {
1241         std::string commanded_world = "";
1242
1243         // World name
1244         std::string commanded_worldname = "";
1245         if (cmd_args.exists("worldname"))
1246                 commanded_worldname = cmd_args.get("worldname");
1247
1248         // If a world name was specified, convert it to a path
1249         if (commanded_worldname != "") {
1250                 // Get information about available worlds
1251                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1252                 bool found = false;
1253                 for (u32 i = 0; i < worldspecs.size(); i++) {
1254                         std::string name = worldspecs[i].name;
1255                         if (name == commanded_worldname) {
1256                                 dstream << _("Using world specified by --worldname on the "
1257                                         "command line") << std::endl;
1258                                 commanded_world = worldspecs[i].path;
1259                                 found = true;
1260                                 break;
1261                         }
1262                 }
1263                 if (!found) {
1264                         dstream << _("World") << " '" << commanded_worldname
1265                                 << _("' not available. Available worlds:") << std::endl;
1266                         print_worldspecs(worldspecs, dstream);
1267                         return false;
1268                 }
1269
1270                 game_params->world_path = get_clean_world_path(commanded_world);
1271                 return commanded_world != "";
1272         }
1273
1274         if (cmd_args.exists("world"))
1275                 commanded_world = cmd_args.get("world");
1276         else if (cmd_args.exists("map-dir"))
1277                 commanded_world = cmd_args.get("map-dir");
1278         else if (cmd_args.exists("nonopt0")) // First nameless argument
1279                 commanded_world = cmd_args.get("nonopt0");
1280
1281         game_params->world_path = get_clean_world_path(commanded_world);
1282         return commanded_world != "";
1283 }
1284
1285 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args)
1286 {
1287         // World directory
1288         std::string commanded_world = "";
1289
1290         if (g_settings->exists("map-dir"))
1291                 commanded_world = g_settings->get("map-dir");
1292
1293         game_params->world_path = get_clean_world_path(commanded_world);
1294
1295         return commanded_world != "";
1296 }
1297
1298 static bool auto_select_world(GameParams *game_params)
1299 {
1300         // No world was specified; try to select it automatically
1301         // Get information about available worlds
1302
1303         verbosestream << _("Determining world path") << std::endl;
1304
1305         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1306         std::string world_path;
1307
1308         // If there is only a single world, use it
1309         if (worldspecs.size() == 1) {
1310                 world_path = worldspecs[0].path;
1311                 dstream <<_("Automatically selecting world at") << " ["
1312                         << world_path << "]" << std::endl;
1313         // If there are multiple worlds, list them
1314         } else if (worldspecs.size() > 1 && game_params->is_dedicated_server) {
1315                 dstream << _("Multiple worlds are available.") << std::endl;
1316                 dstream << _("Please select one using --worldname <name>"
1317                                 " or --world <path>") << std::endl;
1318                 print_worldspecs(worldspecs, dstream);
1319                 return false;
1320         // If there are no worlds, automatically create a new one
1321         } else {
1322                 // This is the ultimate default world path
1323                 world_path = porting::path_user + DIR_DELIM + "worlds" +
1324                                 DIR_DELIM + "world";
1325                 infostream << "Creating default world at ["
1326                            << world_path << "]" << std::endl;
1327         }
1328
1329         assert(world_path != "");
1330         game_params->world_path = world_path;
1331         return true;
1332 }
1333
1334 static std::string get_clean_world_path(const std::string &path)
1335 {
1336         const std::string worldmt = "world.mt";
1337         std::string clean_path;
1338
1339         if (path.size() > worldmt.size()
1340                         && path.substr(path.size() - worldmt.size()) == worldmt) {
1341                 dstream << _("Supplied world.mt file - stripping it off.") << std::endl;
1342                 clean_path = path.substr(0, path.size() - worldmt.size());
1343         } else {
1344                 clean_path = path;
1345         }
1346         return path;
1347 }
1348
1349
1350 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args)
1351 {
1352         bool success;
1353
1354         success = get_game_from_cmdline(game_params, cmd_args);
1355         if (!success)
1356                 success = determine_subgame(game_params);
1357
1358         return success;
1359 }
1360
1361 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args)
1362 {
1363         SubgameSpec commanded_gamespec;
1364
1365         if (cmd_args.exists("gameid")) {
1366                 std::string gameid = cmd_args.get("gameid");
1367                 commanded_gamespec = findSubgame(gameid);
1368                 if (!commanded_gamespec.isValid()) {
1369                         errorstream << "Game \"" << gameid << "\" not found" << std::endl;
1370                         return false;
1371                 }
1372                 dstream << _("Using game specified by --gameid on the command line")
1373                         << std::endl;
1374                 game_params->game_spec = commanded_gamespec;
1375                 return true;
1376         }
1377
1378         return false;
1379 }
1380
1381 static bool determine_subgame(GameParams *game_params)
1382 {
1383         SubgameSpec gamespec;
1384
1385         assert(game_params->world_path != "");  // pre-condition
1386
1387         verbosestream << _("Determining gameid/gamespec") << std::endl;
1388         // If world doesn't exist
1389         if (game_params->world_path != ""
1390                         && !getWorldExists(game_params->world_path)) {
1391                 // Try to take gamespec from command line
1392                 if (game_params->game_spec.isValid()) {
1393                         gamespec = game_params->game_spec;
1394                         infostream << "Using commanded gameid [" << gamespec.id << "]" << std::endl;
1395                 } else { // Otherwise we will be using "minetest"
1396                         gamespec = findSubgame(g_settings->get("default_game"));
1397                         infostream << "Using default gameid [" << gamespec.id << "]" << std::endl;
1398                 }
1399         } else { // World exists
1400                 std::string world_gameid = getWorldGameId(game_params->world_path, false);
1401                 // If commanded to use a gameid, do so
1402                 if (game_params->game_spec.isValid()) {
1403                         gamespec = game_params->game_spec;
1404                         if (game_params->game_spec.id != world_gameid) {
1405                                 errorstream << "WARNING: Using commanded gameid ["
1406                                             << gamespec.id << "]" << " instead of world gameid ["
1407                                             << world_gameid << "]" << std::endl;
1408                         }
1409                 } else {
1410                         // If world contains an embedded game, use it;
1411                         // Otherwise find world from local system.
1412                         gamespec = findWorldSubgame(game_params->world_path);
1413                         infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
1414                 }
1415         }
1416
1417         if (!gamespec.isValid()) {
1418                 errorstream << "Subgame [" << gamespec.id << "] could not be found."
1419                             << std::endl;
1420                 return false;
1421         }
1422
1423         game_params->game_spec = gamespec;
1424         return true;
1425 }
1426
1427
1428 /*****************************************************************************
1429  * Dedicated server
1430  *****************************************************************************/
1431 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
1432 {
1433         DSTACK("Dedicated server branch");
1434
1435         verbosestream << _("Using world path") << " ["
1436                       << game_params.world_path << "]" << std::endl;
1437         verbosestream << _("Using gameid") << " ["
1438                       << game_params.game_spec.id << "]" << std::endl;
1439
1440         // Bind address
1441         std::string bind_str = g_settings->get("bind_address");
1442         Address bind_addr(0, 0, 0, 0, game_params.socket_port);
1443
1444         if (g_settings->getBool("ipv6_server")) {
1445                 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1446         }
1447         try {
1448                 bind_addr.Resolve(bind_str.c_str());
1449         } catch (ResolveError &e) {
1450                 infostream << "Resolving bind address \"" << bind_str
1451                            << "\" failed: " << e.what()
1452                            << " -- Listening on all addresses." << std::endl;
1453         }
1454         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1455                 errorstream << "Unable to listen on "
1456                             << bind_addr.serializeString()
1457                             << L" because IPv6 is disabled" << std::endl;
1458                 return false;
1459         }
1460
1461         // Create server
1462         Server server(game_params.world_path,
1463                         game_params.game_spec, false, bind_addr.isIPv6());
1464
1465         // Database migration
1466         if (cmd_args.exists("migrate"))
1467                 return migrate_database(game_params, cmd_args, &server);
1468
1469         server.start(bind_addr);
1470
1471         // Run server
1472         bool &kill = *porting::signal_handler_killstatus();
1473         dedicated_server_loop(server, kill);
1474
1475         return true;
1476 }
1477
1478 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args,
1479                 Server *server)
1480 {
1481         Settings world_mt;
1482         bool success = world_mt.readConfigFile((game_params.world_path
1483                         + DIR_DELIM + "world.mt").c_str());
1484         if (!success) {
1485                 errorstream << "Cannot read world.mt" << std::endl;
1486                 return false;
1487         }
1488
1489         if (!world_mt.exists("backend")) {
1490                 errorstream << "Please specify your current backend in world.mt file:"
1491                             << std::endl << "   backend = {sqlite3|leveldb|redis|dummy}"
1492                             << std::endl;
1493                 return false;
1494         }
1495
1496         std::string backend = world_mt.get("backend");
1497         Database *new_db;
1498         std::string migrate_to = cmd_args.get("migrate");
1499
1500         if (backend == migrate_to) {
1501                 errorstream << "Cannot migrate: new backend is same as the old one"
1502                             << std::endl;
1503                 return false;
1504         }
1505
1506         if (migrate_to == "sqlite3")
1507                 new_db = new Database_SQLite3(&(ServerMap&)server->getMap(),
1508                                 game_params.world_path);
1509 #if USE_LEVELDB
1510         else if (migrate_to == "leveldb")
1511                 new_db = new Database_LevelDB(&(ServerMap&)server->getMap(),
1512                                 game_params.world_path);
1513 #endif
1514 #if USE_REDIS
1515         else if (migrate_to == "redis")
1516                 new_db = new Database_Redis(&(ServerMap&)server->getMap(),
1517                                 game_params.world_path);
1518 #endif
1519         else {
1520                 errorstream << "Migration to " << migrate_to << " is not supported"
1521                             << std::endl;
1522                 return false;
1523         }
1524
1525         std::list<v3s16> blocks;
1526         ServerMap &old_map = ((ServerMap&)server->getMap());
1527         old_map.listAllLoadableBlocks(blocks);
1528         int count = 0;
1529         new_db->beginSave();
1530         for (std::list<v3s16>::iterator i = blocks.begin(); i != blocks.end(); i++) {
1531                 MapBlock *block = old_map.loadBlock(*i);
1532                 if (!block) {
1533                         errorstream << "Failed to load block " << PP(*i) << ", skipping it.";
1534                 } else {
1535                         old_map.saveBlock(block, new_db);
1536                         MapSector *sector = old_map.getSectorNoGenerate(v2s16(i->X, i->Z));
1537                         sector->deleteBlock(block);
1538                 }
1539                 ++count;
1540                 if (count % 500 == 0)
1541                    actionstream << "Migrated " << count << " blocks "
1542                            << (100.0 * count / blocks.size()) << "% completed" << std::endl;
1543         }
1544         new_db->endSave();
1545         delete new_db;
1546
1547         actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1548         world_mt.set("backend", migrate_to);
1549         if (!world_mt.updateConfigFile(
1550                                 (game_params.world_path+ DIR_DELIM + "world.mt").c_str()))
1551                 errorstream << "Failed to update world.mt!" << std::endl;
1552         else
1553                 actionstream << "world.mt updated" << std::endl;
1554
1555         return true;
1556 }
1557
1558
1559 /*****************************************************************************
1560  * Client
1561  *****************************************************************************/
1562 #ifndef SERVER
1563
1564 ClientLauncher::~ClientLauncher()
1565 {
1566         if (receiver)
1567                 delete receiver;
1568
1569         if (input)
1570                 delete input;
1571
1572         if (device)
1573                 device->drop();
1574
1575 #if USE_FREETYPE
1576         if (use_freetype && font != NULL)
1577                 font->drop();
1578 #endif
1579 }
1580
1581 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
1582 {
1583         init_args(game_params, cmd_args);
1584
1585         // List video modes if requested
1586         if (list_video_modes)
1587                 return print_video_modes();
1588
1589         if (!init_engine(game_params.log_level)) {
1590                 errorstream << "Could not initialize game engine." << std::endl;
1591                 return false;
1592         }
1593
1594         late_init_default_settings(g_settings);
1595
1596         // Speed tests (done after irrlicht is loaded to get timer)
1597         if (cmd_args.getFlag("speedtests")) {
1598                 dstream << "Running speed tests" << std::endl;
1599                 speed_tests();
1600                 return true;
1601         }
1602
1603         if (device->getVideoDriver() == NULL) {
1604                 errorstream << "Could not initialize video driver." << std::endl;
1605                 return false;
1606         }
1607
1608         /*
1609                 This changes the minimum allowed number of vertices in a VBO.
1610                 Default is 500.
1611         */
1612         //driver->setMinHardwareBufferVertexCount(50);
1613
1614         // Create time getter
1615         g_timegetter = new IrrlichtTimeGetter(device);
1616
1617         // Create game callback for menus
1618         g_gamecallback = new MainGameCallback(device);
1619
1620         device->setResizable(true);
1621
1622         if (random_input)
1623                 input = new RandomInputHandler();
1624         else
1625                 input = new RealInputHandler(device, receiver);
1626
1627         smgr = device->getSceneManager();
1628
1629         guienv = device->getGUIEnvironment();
1630         skin = guienv->getSkin();
1631         std::string font_path = g_settings->get("font_path");
1632
1633 #if USE_FREETYPE
1634
1635         if (use_freetype) {
1636                 std::string fallback;
1637                 if (is_yes(gettext("needs_fallback_font")))
1638                         fallback = "fallback_";
1639                 u16 font_size = g_settings->getU16(fallback + "font_size");
1640                 font_path = g_settings->get(fallback + "font_path");
1641                 u32 font_shadow = g_settings->getU16(fallback + "font_shadow");
1642                 u32 font_shadow_alpha = g_settings->getU16(fallback + "font_shadow_alpha");
1643                 font = gui::CGUITTFont::createTTFont(guienv,
1644                                 font_path.c_str(), font_size, true, true,
1645                                 font_shadow, font_shadow_alpha);
1646         } else {
1647                 font = guienv->getFont(font_path.c_str());
1648         }
1649 #else
1650         font = guienv->getFont(font_path.c_str());
1651 #endif
1652         if (font)
1653                 skin->setFont(font);
1654         else
1655                 errorstream << "WARNING: Font file was not found. Using default font."
1656                             << std::endl;
1657
1658         font = skin->getFont(); // If font was not found, this will get us one
1659         assert(font);
1660
1661         u32 text_height = font->getDimension(L"Hello, world!").Height;
1662         infostream << "text_height=" << text_height << std::endl;
1663
1664         skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
1665         skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 0, 0, 0));
1666         skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
1667         skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 100, 50));
1668         skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
1669
1670 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1671         // Irrlicht 1.8 input colours
1672         skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
1673         skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
1674 #endif
1675
1676         // Create the menu clouds
1677         if (!g_menucloudsmgr)
1678                 g_menucloudsmgr = smgr->createNewSceneManager();
1679         if (!g_menuclouds)
1680                 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1681                                 g_menucloudsmgr, -1, rand(), 100);
1682         g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
1683         scene::ICameraSceneNode* camera;
1684         camera = g_menucloudsmgr->addCameraSceneNode(0,
1685                                 v3f(0, 0, 0), v3f(0, 60, 100));
1686         camera->setFarValue(10000);
1687
1688         /*
1689                 GUI stuff
1690         */
1691
1692         ChatBackend chat_backend;
1693
1694         // If an error occurs, this is set to something by menu().
1695         // It is then displayed before  the menu shows on the next call to menu()
1696         std::wstring error_message = L"";
1697
1698         bool first_loop = true;
1699
1700         /*
1701                 Menu-game loop
1702         */
1703         bool retval = true;
1704         bool *kill = porting::signal_handler_killstatus();
1705
1706         while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
1707         {
1708                 // Set the window caption
1709                 wchar_t *text = wgettext("Main Menu");
1710                 device->setWindowCaption((std::wstring(L"Minetest [") + text + L"]").c_str());
1711                 delete[] text;
1712
1713                 try {   // This is used for catching disconnects
1714
1715                         guienv->clear();
1716
1717                         /*
1718                                 We need some kind of a root node to be able to add
1719                                 custom gui elements directly on the screen.
1720                                 Otherwise they won't be automatically drawn.
1721                         */
1722                         guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
1723
1724                         bool game_has_run = launch_game(&error_message, game_params, cmd_args);
1725
1726                         // If skip_main_menu, we only want to startup once
1727                         if (skip_main_menu && !first_loop)
1728                                 break;
1729
1730                         first_loop = false;
1731
1732                         if (!game_has_run) {
1733                                 if (skip_main_menu)
1734                                         break;
1735                                 else
1736                                         continue;
1737                         }
1738
1739                         // Break out of menu-game loop to shut down cleanly
1740                         if (!device->run() || *kill) {
1741                                 if (g_settings_path != "")
1742                                         g_settings->updateConfigFile(g_settings_path.c_str());
1743                                 break;
1744                         }
1745
1746                         if (current_playername.length() > PLAYERNAME_SIZE-1) {
1747                                 error_message = wgettext("Player name too long.");
1748                                 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
1749                                 g_settings->set("name", playername);
1750                                 continue;
1751                         }
1752
1753                         device->getVideoDriver()->setTextureCreationFlag(
1754                                         video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
1755
1756 #ifdef HAVE_TOUCHSCREENGUI
1757                         receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
1758                         g_touchscreengui = receiver->m_touchscreengui;
1759 #endif
1760                         the_game(
1761                                 kill,
1762                                 random_input,
1763                                 input,
1764                                 device,
1765                                 font,
1766                                 worldspec.path,
1767                                 current_playername,
1768                                 current_password,
1769                                 current_address,
1770                                 current_port,
1771                                 error_message,
1772                                 chat_backend,
1773                                 gamespec,
1774                                 simple_singleplayer_mode
1775                         );
1776                         smgr->clear();
1777
1778 #ifdef HAVE_TOUCHSCREENGUI
1779                         delete g_touchscreengui;
1780                         g_touchscreengui = NULL;
1781                         receiver->m_touchscreengui = NULL;
1782 #endif
1783
1784                 } //try
1785                 catch (con::PeerNotFoundException &e) {
1786                         error_message = wgettext("Connection error (timed out?)");
1787                         errorstream << wide_to_narrow(error_message) << std::endl;
1788                 }
1789
1790 #ifdef NDEBUG
1791                 catch (std::exception &e) {
1792                         std::string narrow_message = "Some exception: \"";
1793                         narrow_message += e.what();
1794                         narrow_message += "\"";
1795                         errorstream << narrow_message << std::endl;
1796                         error_message = narrow_to_wide(narrow_message);
1797                 }
1798 #endif
1799
1800                 // If no main menu, show error and exit
1801                 if (skip_main_menu) {
1802                         if (error_message != L"") {
1803                                 verbosestream << "error_message = "
1804                                               << wide_to_narrow(error_message) << std::endl;
1805                                 retval = false;
1806                         }
1807                         break;
1808                 }
1809         } // Menu-game loop
1810
1811         g_menuclouds->drop();
1812         g_menucloudsmgr->drop();
1813
1814         return retval;
1815 }
1816
1817 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
1818 {
1819         address = g_settings->get("address");
1820         if (game_params.world_path != "")
1821                 address = "";
1822         else if (cmd_args.exists("address"))
1823                 address = cmd_args.get("address");
1824
1825         playername = g_settings->get("name");
1826         if (cmd_args.exists("name"))
1827                 playername = cmd_args.get("name");
1828
1829         skip_main_menu = cmd_args.getFlag("go");
1830
1831         list_video_modes = cmd_args.getFlag("videomodes");
1832
1833         use_freetype = g_settings->getBool("freetype");
1834
1835         random_input = g_settings->getBool("random_input")
1836                         || cmd_args.getFlag("random-input");
1837 }
1838
1839 bool ClientLauncher::init_engine(int log_level)
1840 {
1841         receiver = new MyEventReceiver();
1842         create_engine_device(log_level);
1843         return device != NULL;
1844 }
1845
1846 bool ClientLauncher::launch_game(std::wstring *error_message,
1847                 GameParams &game_params, const Settings &cmd_args)
1848 {
1849         // Initialize menu data
1850         MainMenuData menudata;
1851         menudata.address      = address;
1852         menudata.name         = playername;
1853         menudata.port         = itos(game_params.socket_port);
1854         menudata.errormessage = wide_to_narrow(*error_message);
1855
1856         *error_message = L"";
1857
1858         if (cmd_args.exists("password"))
1859                 menudata.password = cmd_args.get("password");
1860
1861         menudata.enable_public = g_settings->getBool("server_announce");
1862
1863         // If a world was commanded, append and select it
1864         if (game_params.world_path != "") {
1865                 worldspec.gameid = getWorldGameId(game_params.world_path, true);
1866                 worldspec.name = _("[--world parameter]");
1867
1868                 if (worldspec.gameid == "") {   // Create new
1869                         worldspec.gameid = g_settings->get("default_game");
1870                         worldspec.name += " [new]";
1871                 }
1872                 worldspec.path = game_params.world_path;
1873         }
1874
1875         /* Show the GUI menu
1876          */
1877         if (!skip_main_menu) {
1878                 main_menu(&menudata);
1879
1880                 address = menudata.address;
1881                 int newport = stoi(menudata.port);
1882                 if (newport != 0)
1883                         game_params.socket_port = newport;
1884
1885                 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1886
1887                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1888                 worldspecs = getAvailableWorlds();
1889
1890                 if (menudata.selected_world >= 0
1891                                 && menudata.selected_world < (int)worldspecs.size()) {
1892                         g_settings->set("selected_world_path",
1893                                         worldspecs[menudata.selected_world].path);
1894                         worldspec = worldspecs[menudata.selected_world];
1895                 }
1896         }
1897
1898         if (menudata.errormessage != "") {
1899                 /* The calling function will pass this back into this function upon the
1900                  * next iteration (if any) causing it to be displayed by the GUI
1901                  */
1902                 *error_message = narrow_to_wide(menudata.errormessage);
1903                 return false;
1904         }
1905
1906         if (menudata.name == "")
1907                 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
1908         else
1909                 playername = menudata.name;
1910
1911         password = translatePassword(playername, narrow_to_wide(menudata.password));
1912
1913         g_settings->set("name", playername);
1914
1915         current_playername = playername;
1916         current_password   = password;
1917         current_address    = address;
1918         current_port       = game_params.socket_port;
1919
1920         // If using simple singleplayer mode, override
1921         if (simple_singleplayer_mode) {
1922                 assert(skip_main_menu == false);
1923                 current_playername = "singleplayer";
1924                 current_password = "";
1925                 current_address = "";
1926                 current_port = myrand_range(49152, 65535);
1927         } else if (address != "") {
1928                 ServerListSpec server;
1929                 server["name"] = menudata.servername;
1930                 server["address"] = menudata.address;
1931                 server["port"] = menudata.port;
1932                 server["description"] = menudata.serverdescription;
1933                 ServerList::insert(server);
1934         }
1935
1936         infostream << "Selected world: " << worldspec.name
1937                    << " [" << worldspec.path << "]" << std::endl;
1938
1939         if (current_address == "") { // If local game
1940                 if (worldspec.path == "") {
1941                         *error_message = wgettext("No world selected and no address "
1942                                         "provided. Nothing to do.");
1943                         errorstream << wide_to_narrow(*error_message) << std::endl;
1944                         return false;
1945                 }
1946
1947                 if (!fs::PathExists(worldspec.path)) {
1948                         *error_message = wgettext("Provided world path doesn't exist: ")
1949                                         + narrow_to_wide(worldspec.path);
1950                         errorstream << wide_to_narrow(*error_message) << std::endl;
1951                         return false;
1952                 }
1953
1954                 // Load gamespec for required game
1955                 gamespec = findWorldSubgame(worldspec.path);
1956                 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
1957                         *error_message = wgettext("Could not find or load game \"")
1958                                         + narrow_to_wide(worldspec.gameid) + L"\"";
1959                         errorstream << wide_to_narrow(*error_message) << std::endl;
1960                         return false;
1961                 }
1962                 if (game_params.game_spec.isValid() &&
1963                                 game_params.game_spec.id != worldspec.gameid) {
1964                         errorstream << "WARNING: Overriding gamespec from \""
1965                                     << worldspec.gameid << "\" to \""
1966                                     << game_params.game_spec.id << "\"" << std::endl;
1967                         gamespec = game_params.game_spec;
1968                 }
1969
1970                 if (!gamespec.isValid()) {
1971                         *error_message = wgettext("Invalid gamespec.");
1972                         *error_message += L" (world_gameid="
1973                                         + narrow_to_wide(worldspec.gameid) + L")";
1974                         errorstream << wide_to_narrow(*error_message) << std::endl;
1975                         return false;
1976                 }
1977         }
1978
1979         return true;
1980 }
1981
1982 void ClientLauncher::main_menu(MainMenuData *menudata)
1983 {
1984         bool *kill = porting::signal_handler_killstatus();
1985         video::IVideoDriver *driver = device->getVideoDriver();
1986
1987         infostream << "Waiting for other menus" << std::endl;
1988         while (device->run() && *kill == false) {
1989                 if (noMenuActive())
1990                         break;
1991                 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
1992                 guienv->drawAll();
1993                 driver->endScene();
1994                 // On some computers framerate doesn't seem to be automatically limited
1995                 sleep_ms(25);
1996         }
1997         infostream << "Waited for other menus" << std::endl;
1998
1999         // Cursor can be non-visible when coming from the game
2000 #ifndef ANDROID
2001         device->getCursorControl()->setVisible(true);
2002 #endif
2003
2004         /* show main menu */
2005         GUIEngine mymenu(device, guiroot, &g_menumgr, smgr, menudata, *kill);
2006
2007         smgr->clear();  /* leave scene manager in a clean state */
2008 }
2009
2010 bool ClientLauncher::create_engine_device(int log_level)
2011 {
2012         static const char *driverids[] = {
2013                 "null",
2014                 "software",
2015                 "burningsvideo",
2016                 "direct3d8",
2017                 "direct3d9",
2018                 "opengl"
2019 #ifdef _IRR_COMPILE_WITH_OGLES1_
2020                 ,"ogles1"
2021 #endif
2022 #ifdef _IRR_COMPILE_WITH_OGLES2_
2023                 ,"ogles2"
2024 #endif
2025                 ,"invalid"
2026         };
2027
2028         static const irr::ELOG_LEVEL irr_log_level[5] = {
2029                 ELL_NONE,
2030                 ELL_ERROR,
2031                 ELL_WARNING,
2032                 ELL_INFORMATION,
2033 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
2034                 ELL_INFORMATION
2035 #else
2036                 ELL_DEBUG
2037 #endif
2038         };
2039
2040         // Resolution selection
2041         bool fullscreen = g_settings->getBool("fullscreen");
2042         u16 screenW = g_settings->getU16("screenW");
2043         u16 screenH = g_settings->getU16("screenH");
2044
2045         // bpp, fsaa, vsync
2046         bool vsync = g_settings->getBool("vsync");
2047         u16 bits = g_settings->getU16("fullscreen_bpp");
2048         u16 fsaa = g_settings->getU16("fsaa");
2049
2050         // Determine driver
2051         video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
2052
2053         std::string driverstring = g_settings->get("video_driver");
2054         for (size_t i = 0; i < sizeof driverids / sizeof driverids[0]; i++) {
2055                 if (strcasecmp(driverstring.c_str(), driverids[i]) == 0) {
2056                         driverType = (video::E_DRIVER_TYPE) i;
2057                         break;
2058                 }
2059
2060                 if (strcasecmp("invalid", driverids[i]) == 0) {
2061                         errorstream << "WARNING: Invalid video_driver specified;"
2062                                     << " defaulting to opengl" << std::endl;
2063                         break;
2064                 }
2065         }
2066
2067         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2068         params.DriverType    = driverType;
2069         params.WindowSize    = core::dimension2d<u32>(screenW, screenH);
2070         params.Bits          = bits;
2071         params.AntiAlias     = fsaa;
2072         params.Fullscreen    = fullscreen;
2073         params.Stencilbuffer = false;
2074         params.Vsync         = vsync;
2075         params.EventReceiver = receiver;
2076         params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2077 #ifdef __ANDROID__
2078         params.PrivateData = porting::app_global;
2079         params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
2080                         "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
2081 #endif
2082
2083         device = createDeviceEx(params);
2084
2085         if (device) {
2086                 // Map our log level to irrlicht engine one.
2087                 ILogger* irr_logger = device->getLogger();
2088                 irr_logger->setLogLevel(irr_log_level[log_level]);
2089
2090                 porting::initIrrlicht(device);
2091         }
2092
2093         return device != NULL;
2094 }
2095
2096 // Misc functions
2097
2098 static bool print_video_modes()
2099 {
2100         IrrlichtDevice *nulldevice;
2101
2102         bool vsync = g_settings->getBool("vsync");
2103         u16 fsaa = g_settings->getU16("fsaa");
2104         MyEventReceiver* receiver = new MyEventReceiver();
2105
2106         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2107         params.DriverType    = video::EDT_NULL;
2108         params.WindowSize    = core::dimension2d<u32>(640, 480);
2109         params.Bits          = 24;
2110         params.AntiAlias     = fsaa;
2111         params.Fullscreen    = false;
2112         params.Stencilbuffer = false;
2113         params.Vsync         = vsync;
2114         params.EventReceiver = receiver;
2115         params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2116
2117         nulldevice = createDeviceEx(params);
2118
2119         if (nulldevice == NULL) {
2120                 delete receiver;
2121                 return false;
2122         }
2123
2124         dstream << _("Available video modes (WxHxD):") << std::endl;
2125
2126         video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
2127
2128         if (videomode_list != NULL) {
2129                 s32 videomode_count = videomode_list->getVideoModeCount();
2130                 core::dimension2d<u32> videomode_res;
2131                 s32 videomode_depth;
2132                 for (s32 i = 0; i < videomode_count; ++i) {
2133                         videomode_res = videomode_list->getVideoModeResolution(i);
2134                         videomode_depth = videomode_list->getVideoModeDepth(i);
2135                         dstream << videomode_res.Width << "x" << videomode_res.Height
2136                                 << "x" << videomode_depth << std::endl;
2137                 }
2138
2139                 dstream << _("Active video mode (WxHxD):") << std::endl;
2140                 videomode_res = videomode_list->getDesktopResolution();
2141                 videomode_depth = videomode_list->getDesktopDepth();
2142                 dstream << videomode_res.Width << "x" << videomode_res.Height
2143                         << "x" << videomode_depth << std::endl;
2144
2145         }
2146
2147         nulldevice->drop();
2148         delete receiver;
2149
2150         return videomode_list != NULL;
2151 }
2152
2153 #endif // !SERVER
2154
2155 /*****************************************************************************
2156  * Performance tests
2157  *****************************************************************************/
2158 #ifndef SERVER
2159 static void speed_tests()
2160 {
2161         // volatile to avoid some potential compiler optimisations
2162         volatile static s16 temp16;
2163         volatile static f32 tempf;
2164         static v3f tempv3f1;
2165         static v3f tempv3f2;
2166         static std::string tempstring;
2167         static std::string tempstring2;
2168
2169         tempv3f1 = v3f();
2170         tempv3f2 = v3f();
2171         tempstring = std::string();
2172         tempstring2 = std::string();
2173
2174         {
2175                 infostream << "The following test should take around 20ms." << std::endl;
2176                 TimeTaker timer("Testing std::string speed");
2177                 const u32 jj = 10000;
2178                 for (u32 j = 0; j < jj; j++) {
2179                         tempstring = "";
2180                         tempstring2 = "";
2181                         const u32 ii = 10;
2182                         for (u32 i = 0; i < ii; i++) {
2183                                 tempstring2 += "asd";
2184                         }
2185                         for (u32 i = 0; i < ii+1; i++) {
2186                                 tempstring += "asd";
2187                                 if (tempstring == tempstring2)
2188                                         break;
2189                         }
2190                 }
2191         }
2192
2193         infostream << "All of the following tests should take around 100ms each."
2194                    << std::endl;
2195
2196         {
2197                 TimeTaker timer("Testing floating-point conversion speed");
2198                 tempf = 0.001;
2199                 for (u32 i = 0; i < 4000000; i++) {
2200                         temp16 += tempf;
2201                         tempf += 0.001;
2202                 }
2203         }
2204
2205         {
2206                 TimeTaker timer("Testing floating-point vector speed");
2207
2208                 tempv3f1 = v3f(1, 2, 3);
2209                 tempv3f2 = v3f(4, 5, 6);
2210                 for (u32 i = 0; i < 10000000; i++) {
2211                         tempf += tempv3f1.dotProduct(tempv3f2);
2212                         tempv3f2 += v3f(7, 8, 9);
2213                 }
2214         }
2215
2216         {
2217                 TimeTaker timer("Testing std::map speed");
2218
2219                 std::map<v2s16, f32> map1;
2220                 tempf = -324;
2221                 const s16 ii = 300;
2222                 for (s16 y = 0; y < ii; y++) {
2223                         for (s16 x = 0; x < ii; x++) {
2224                                 map1[v2s16(x, y)] =  tempf;
2225                                 tempf += 1;
2226                         }
2227                 }
2228                 for (s16 y = ii - 1; y >= 0; y--) {
2229                         for (s16 x = 0; x < ii; x++) {
2230                                 tempf = map1[v2s16(x, y)];
2231                         }
2232                 }
2233         }
2234
2235         {
2236                 infostream << "Around 5000/ms should do well here." << std::endl;
2237                 TimeTaker timer("Testing mutex speed");
2238
2239                 JMutex m;
2240                 u32 n = 0;
2241                 u32 i = 0;
2242                 do {
2243                         n += 10000;
2244                         for (; i < n; i++) {
2245                                 m.Lock();
2246                                 m.Unlock();
2247                         }
2248                 }
2249                 // Do at least 10ms
2250                 while(timer.getTimerTime() < 10);
2251
2252                 u32 dtime = timer.stop();
2253                 u32 per_ms = n / dtime;
2254                 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
2255         }
2256 }
2257 #endif