7141bec66dcda67290b73ee3e5bd05181d7593ab
[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 #include "util/string.h"
73 #include "subgame.h"
74 #include "quicktune.h"
75 #include "serverlist.h"
76 #include "httpfetch.h"
77 #include "guiEngine.h"
78 #include "mapsector.h"
79 #include "player.h"
80 #include "fontengine.h"
81
82 #include "database-sqlite3.h"
83 #ifdef USE_LEVELDB
84 #include "database-leveldb.h"
85 #endif
86
87 #if USE_REDIS
88 #include "database-redis.h"
89 #endif
90
91 #ifdef HAVE_TOUCHSCREENGUI
92 #include "touchscreengui.h"
93 #endif
94
95 /*
96         Settings.
97         These are loaded from the config file.
98 */
99 static Settings main_settings;
100 Settings *g_settings = &main_settings;
101 std::string g_settings_path;
102
103 // Global profiler
104 Profiler main_profiler;
105 Profiler *g_profiler = &main_profiler;
106
107 // Menu clouds are created later
108 Clouds *g_menuclouds = 0;
109 irr::scene::ISceneManager *g_menucloudsmgr = 0;
110
111 /*
112         Debug streams
113 */
114
115 // Connection
116 std::ostream *dout_con_ptr = &dummyout;
117 std::ostream *derr_con_ptr = &verbosestream;
118
119 // Server
120 std::ostream *dout_server_ptr = &infostream;
121 std::ostream *derr_server_ptr = &errorstream;
122
123 // Client
124 std::ostream *dout_client_ptr = &infostream;
125 std::ostream *derr_client_ptr = &errorstream;
126
127 #define DEBUGFILE "debug.txt"
128 #define DEFAULT_SERVER_PORT 30000
129
130 typedef std::map<std::string, ValueSpec> OptionList;
131
132 struct GameParams {
133         u16 socket_port;
134         std::string world_path;
135         SubgameSpec game_spec;
136         bool is_dedicated_server;
137         int log_level;
138 };
139
140 /**********************************************************************
141  * Private functions
142  **********************************************************************/
143
144 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args);
145 static void set_allowed_options(OptionList *allowed_options);
146
147 static void print_help(const OptionList &allowed_options);
148 static void print_allowed_options(const OptionList &allowed_options);
149 static void print_version();
150 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
151                                                          std::ostream &os);
152 static void print_modified_quicktune_values();
153
154 static void list_game_ids();
155 static void list_worlds();
156 static void setup_log_params(const Settings &cmd_args);
157 static bool create_userdata_path();
158 static bool init_common(int *log_level, const Settings &cmd_args, int argc, char *argv[]);
159 static void startup_message();
160 static bool read_config_file(const Settings &cmd_args);
161 static void init_debug_streams(int *log_level, const Settings &cmd_args);
162
163 static bool game_configure(GameParams *game_params, const Settings &cmd_args);
164 static void game_configure_port(GameParams *game_params, const Settings &cmd_args);
165
166 static bool game_configure_world(GameParams *game_params, const Settings &cmd_args);
167 static bool get_world_from_cmdline(GameParams *game_params, const Settings &cmd_args);
168 static bool get_world_from_config(GameParams *game_params, const Settings &cmd_args);
169 static bool auto_select_world(GameParams *game_params);
170 static std::string get_clean_world_path(const std::string &path);
171
172 static bool game_configure_subgame(GameParams *game_params, const Settings &cmd_args);
173 static bool get_game_from_cmdline(GameParams *game_params, const Settings &cmd_args);
174 static bool determine_subgame(GameParams *game_params);
175
176 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args);
177 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args,
178                 Server *server);
179
180 #ifndef SERVER
181 static bool print_video_modes();
182 static void speed_tests();
183 #endif
184
185 /**********************************************************************/
186
187 #ifndef SERVER
188 /*
189         Random stuff
190 */
191
192 /* mainmenumanager.h */
193
194 gui::IGUIEnvironment* guienv = NULL;
195 gui::IGUIStaticText *guiroot = NULL;
196 MainMenuManager g_menumgr;
197
198 bool noMenuActive()
199 {
200         return (g_menumgr.menuCount() == 0);
201 }
202
203 // Passed to menus to allow disconnecting and exiting
204 MainGameCallback *g_gamecallback = NULL;
205 #endif
206
207 /*
208         gettime.h implementation
209 */
210
211 #ifdef SERVER
212
213 u32 getTimeMs()
214 {
215         /* Use imprecise system calls directly (from porting.h) */
216         return porting::getTime(PRECISION_MILLI);
217 }
218
219 u32 getTime(TimePrecision prec)
220 {
221         return porting::getTime(prec);
222 }
223
224 #else
225
226 // A small helper class
227 class TimeGetter
228 {
229 public:
230         virtual u32 getTime(TimePrecision prec) = 0;
231 };
232
233 // A precise irrlicht one
234 class IrrlichtTimeGetter: public TimeGetter
235 {
236 public:
237         IrrlichtTimeGetter(IrrlichtDevice *device):
238                 m_device(device)
239         {}
240         u32 getTime(TimePrecision prec)
241         {
242                 if (prec == PRECISION_MILLI) {
243                         if (m_device == NULL)
244                                 return 0;
245                         return m_device->getTimer()->getRealTime();
246                 } else {
247                         return porting::getTime(prec);
248                 }
249         }
250 private:
251         IrrlichtDevice *m_device;
252 };
253 // Not so precise one which works without irrlicht
254 class SimpleTimeGetter: public TimeGetter
255 {
256 public:
257         u32 getTime(TimePrecision prec)
258         {
259                 return porting::getTime(prec);
260         }
261 };
262
263 // A pointer to a global instance of the time getter
264 // TODO: why?
265 TimeGetter *g_timegetter = NULL;
266
267 u32 getTimeMs()
268 {
269         if (g_timegetter == NULL)
270                 return 0;
271         return g_timegetter->getTime(PRECISION_MILLI);
272 }
273
274 u32 getTime(TimePrecision prec) {
275         if (g_timegetter == NULL)
276                 return 0;
277         return g_timegetter->getTime(prec);
278 }
279 #endif
280
281 class StderrLogOutput: public ILogOutput
282 {
283 public:
284         /* line: Full line with timestamp, level and thread */
285         void printLog(const std::string &line)
286         {
287                 std::cerr << line << std::endl;
288         }
289 } main_stderr_log_out;
290
291 class DstreamNoStderrLogOutput: public ILogOutput
292 {
293 public:
294         /* line: Full line with timestamp, level and thread */
295         void printLog(const std::string &line)
296         {
297                 dstream_no_stderr << line << std::endl;
298         }
299 } main_dstream_no_stderr_log_out;
300
301 #ifndef SERVER
302
303 /*
304         Event handler for Irrlicht
305
306         NOTE: Everything possible should be moved out from here,
307               probably to InputHandler and the_game
308 */
309
310 class MyEventReceiver : public IEventReceiver
311 {
312 public:
313         // This is the one method that we have to implement
314         virtual bool OnEvent(const SEvent& event)
315         {
316                 /*
317                         React to nothing here if a menu is active
318                 */
319                 if (noMenuActive() == false) {
320 #ifdef HAVE_TOUCHSCREENGUI
321                         if (m_touchscreengui != 0) {
322                                 m_touchscreengui->Toggle(false);
323                         }
324 #endif
325                         return g_menumgr.preprocessEvent(event);
326                 }
327
328                 // Remember whether each key is down or up
329                 if (event.EventType == irr::EET_KEY_INPUT_EVENT) {
330                         if (event.KeyInput.PressedDown) {
331                                 keyIsDown.set(event.KeyInput);
332                                 keyWasDown.set(event.KeyInput);
333                         } else {
334                                 keyIsDown.unset(event.KeyInput);
335                         }
336                 }
337
338 #ifdef HAVE_TOUCHSCREENGUI
339                 // case of touchscreengui we have to handle different events
340                 if ((m_touchscreengui != 0) &&
341                                 (event.EventType == irr::EET_TOUCH_INPUT_EVENT)) {
342                         m_touchscreengui->translateEvent(event);
343                         return true;
344                 }
345 #endif
346                 // handle mouse events
347                 if (event.EventType == irr::EET_MOUSE_INPUT_EVENT) {
348                         if (noMenuActive() == false) {
349                                 left_active = false;
350                                 middle_active = false;
351                                 right_active = false;
352                         } else {
353                                 left_active = event.MouseInput.isLeftPressed();
354                                 middle_active = event.MouseInput.isMiddlePressed();
355                                 right_active = event.MouseInput.isRightPressed();
356
357                                 if (event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN) {
358                                         leftclicked = true;
359                                 }
360                                 if (event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN) {
361                                         rightclicked = true;
362                                 }
363                                 if (event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP) {
364                                         leftreleased = true;
365                                 }
366                                 if (event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP) {
367                                         rightreleased = true;
368                                 }
369                                 if (event.MouseInput.Event == EMIE_MOUSE_WHEEL) {
370                                         mouse_wheel += event.MouseInput.Wheel;
371                                 }
372                         }
373                 }
374                 if (event.EventType == irr::EET_LOG_TEXT_EVENT) {
375                         dstream << std::string("Irrlicht log: ") + std::string(event.LogEvent.Text)
376                                 << std::endl;
377                         return true;
378                 }
379                 /* always return false in order to continue processing events */
380                 return false;
381         }
382
383         bool IsKeyDown(const KeyPress &keyCode) const
384         {
385                 return keyIsDown[keyCode];
386         }
387
388         // Checks whether a key was down and resets the state
389         bool WasKeyDown(const KeyPress &keyCode)
390         {
391                 bool b = keyWasDown[keyCode];
392                 if (b)
393                         keyWasDown.unset(keyCode);
394                 return b;
395         }
396
397         s32 getMouseWheel()
398         {
399                 s32 a = mouse_wheel;
400                 mouse_wheel = 0;
401                 return a;
402         }
403
404         void clearInput()
405         {
406                 keyIsDown.clear();
407                 keyWasDown.clear();
408
409                 leftclicked = false;
410                 rightclicked = false;
411                 leftreleased = false;
412                 rightreleased = false;
413
414                 left_active = false;
415                 middle_active = false;
416                 right_active = false;
417
418                 mouse_wheel = 0;
419         }
420
421         MyEventReceiver()
422         {
423                 clearInput();
424 #ifdef HAVE_TOUCHSCREENGUI
425                 m_touchscreengui = NULL;
426 #endif
427         }
428
429         bool leftclicked;
430         bool rightclicked;
431         bool leftreleased;
432         bool rightreleased;
433
434         bool left_active;
435         bool middle_active;
436         bool right_active;
437
438         s32 mouse_wheel;
439
440 #ifdef HAVE_TOUCHSCREENGUI
441         TouchScreenGUI* m_touchscreengui;
442 #endif
443
444 private:
445         // The current state of keys
446         KeyList keyIsDown;
447         // Whether a key has been pressed or not
448         KeyList keyWasDown;
449 };
450
451 /*
452         Separated input handler
453 */
454
455 class RealInputHandler : public InputHandler
456 {
457 public:
458         RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
459                 m_device(device),
460                 m_receiver(receiver),
461                 m_mousepos(0,0)
462         {
463         }
464         virtual bool isKeyDown(const KeyPress &keyCode)
465         {
466                 return m_receiver->IsKeyDown(keyCode);
467         }
468         virtual bool wasKeyDown(const KeyPress &keyCode)
469         {
470                 return m_receiver->WasKeyDown(keyCode);
471         }
472         virtual v2s32 getMousePos()
473         {
474                 if (m_device->getCursorControl()) {
475                         return m_device->getCursorControl()->getPosition();
476                 }
477                 else {
478                         return m_mousepos;
479                 }
480         }
481         virtual void setMousePos(s32 x, s32 y)
482         {
483                 if (m_device->getCursorControl()) {
484                         m_device->getCursorControl()->setPosition(x, y);
485                 }
486                 else {
487                         m_mousepos = v2s32(x,y);
488                 }
489         }
490
491         virtual bool getLeftState()
492         {
493                 return m_receiver->left_active;
494         }
495         virtual bool getRightState()
496         {
497                 return m_receiver->right_active;
498         }
499
500         virtual bool getLeftClicked()
501         {
502                 return m_receiver->leftclicked;
503         }
504         virtual bool getRightClicked()
505         {
506                 return m_receiver->rightclicked;
507         }
508         virtual void resetLeftClicked()
509         {
510                 m_receiver->leftclicked = false;
511         }
512         virtual void resetRightClicked()
513         {
514                 m_receiver->rightclicked = false;
515         }
516
517         virtual bool getLeftReleased()
518         {
519                 return m_receiver->leftreleased;
520         }
521         virtual bool getRightReleased()
522         {
523                 return m_receiver->rightreleased;
524         }
525         virtual void resetLeftReleased()
526         {
527                 m_receiver->leftreleased = false;
528         }
529         virtual void resetRightReleased()
530         {
531                 m_receiver->rightreleased = false;
532         }
533
534         virtual s32 getMouseWheel()
535         {
536                 return m_receiver->getMouseWheel();
537         }
538
539         void clear()
540         {
541                 m_receiver->clearInput();
542         }
543 private:
544         IrrlichtDevice  *m_device;
545         MyEventReceiver *m_receiver;
546         v2s32           m_mousepos;
547 };
548
549 class RandomInputHandler : public InputHandler
550 {
551 public:
552         RandomInputHandler()
553         {
554                 leftdown = false;
555                 rightdown = false;
556                 leftclicked = false;
557                 rightclicked = false;
558                 leftreleased = false;
559                 rightreleased = false;
560                 keydown.clear();
561         }
562         virtual bool isKeyDown(const KeyPress &keyCode)
563         {
564                 return keydown[keyCode];
565         }
566         virtual bool wasKeyDown(const KeyPress &keyCode)
567         {
568                 return false;
569         }
570         virtual v2s32 getMousePos()
571         {
572                 return mousepos;
573         }
574         virtual void setMousePos(s32 x, s32 y)
575         {
576                 mousepos = v2s32(x, y);
577         }
578
579         virtual bool getLeftState()
580         {
581                 return leftdown;
582         }
583         virtual bool getRightState()
584         {
585                 return rightdown;
586         }
587
588         virtual bool getLeftClicked()
589         {
590                 return leftclicked;
591         }
592         virtual bool getRightClicked()
593         {
594                 return rightclicked;
595         }
596         virtual void resetLeftClicked()
597         {
598                 leftclicked = false;
599         }
600         virtual void resetRightClicked()
601         {
602                 rightclicked = false;
603         }
604
605         virtual bool getLeftReleased()
606         {
607                 return leftreleased;
608         }
609         virtual bool getRightReleased()
610         {
611                 return rightreleased;
612         }
613         virtual void resetLeftReleased()
614         {
615                 leftreleased = false;
616         }
617         virtual void resetRightReleased()
618         {
619                 rightreleased = false;
620         }
621
622         virtual s32 getMouseWheel()
623         {
624                 return 0;
625         }
626
627         virtual void step(float dtime)
628         {
629                 {
630                         static float counter1 = 0;
631                         counter1 -= dtime;
632                         if (counter1 < 0.0) {
633                                 counter1 = 0.1 * Rand(1, 40);
634                                 keydown.toggle(getKeySetting("keymap_jump"));
635                         }
636                 }
637                 {
638                         static float counter1 = 0;
639                         counter1 -= dtime;
640                         if (counter1 < 0.0) {
641                                 counter1 = 0.1 * Rand(1, 40);
642                                 keydown.toggle(getKeySetting("keymap_special1"));
643                         }
644                 }
645                 {
646                         static float counter1 = 0;
647                         counter1 -= dtime;
648                         if (counter1 < 0.0) {
649                                 counter1 = 0.1 * Rand(1, 40);
650                                 keydown.toggle(getKeySetting("keymap_forward"));
651                         }
652                 }
653                 {
654                         static float counter1 = 0;
655                         counter1 -= dtime;
656                         if (counter1 < 0.0) {
657                                 counter1 = 0.1 * Rand(1, 40);
658                                 keydown.toggle(getKeySetting("keymap_left"));
659                         }
660                 }
661                 {
662                         static float counter1 = 0;
663                         counter1 -= dtime;
664                         if (counter1 < 0.0) {
665                                 counter1 = 0.1 * Rand(1, 20);
666                                 mousespeed = v2s32(Rand(-20, 20), Rand(-15, 20));
667                         }
668                 }
669                 {
670                         static float counter1 = 0;
671                         counter1 -= dtime;
672                         if (counter1 < 0.0) {
673                                 counter1 = 0.1 * Rand(1, 30);
674                                 leftdown = !leftdown;
675                                 if (leftdown)
676                                         leftclicked = true;
677                                 if (!leftdown)
678                                         leftreleased = true;
679                         }
680                 }
681                 {
682                         static float counter1 = 0;
683                         counter1 -= dtime;
684                         if (counter1 < 0.0) {
685                                 counter1 = 0.1 * Rand(1, 15);
686                                 rightdown = !rightdown;
687                                 if (rightdown)
688                                         rightclicked = true;
689                                 if (!rightdown)
690                                         rightreleased = true;
691                         }
692                 }
693                 mousepos += mousespeed;
694         }
695
696         s32 Rand(s32 min, s32 max)
697         {
698                 return (myrand()%(max-min+1))+min;
699         }
700 private:
701         KeyList keydown;
702         v2s32 mousepos;
703         v2s32 mousespeed;
704         bool leftdown;
705         bool rightdown;
706         bool leftclicked;
707         bool rightclicked;
708         bool leftreleased;
709         bool rightreleased;
710 };
711
712
713 class ClientLauncher
714 {
715 public:
716         ClientLauncher() :
717                 list_video_modes(false),
718                 skip_main_menu(false),
719                 use_freetype(false),
720                 random_input(false),
721                 address(""),
722                 playername(""),
723                 password(""),
724                 device(NULL),
725                 input(NULL),
726                 receiver(NULL),
727                 skin(NULL),
728                 font(NULL),
729                 simple_singleplayer_mode(false),
730                 current_playername("inv£lid"),
731                 current_password(""),
732                 current_address("does-not-exist"),
733                 current_port(0)
734         {}
735
736         ~ClientLauncher();
737
738         bool run(GameParams &game_params, const Settings &cmd_args);
739
740 protected:
741         void init_args(GameParams &game_params, const Settings &cmd_args);
742         bool init_engine(int log_level);
743
744         bool launch_game(std::wstring *error_message, GameParams &game_params,
745                         const Settings &cmd_args);
746
747         void main_menu(MainMenuData *menudata);
748         bool create_engine_device(int log_level);
749
750         bool list_video_modes;
751         bool skip_main_menu;
752         bool use_freetype;
753         bool random_input;
754         std::string address;
755         std::string playername;
756         std::string password;
757         IrrlichtDevice *device;
758         InputHandler *input;
759         MyEventReceiver *receiver;
760         gui::IGUISkin *skin;
761         gui::IGUIFont *font;
762         scene::ISceneManager *smgr;
763         SubgameSpec gamespec;
764         WorldSpec worldspec;
765         bool simple_singleplayer_mode;
766
767         // These are set up based on the menu and other things
768         // TODO: Are these required since there's already playername, password, etc
769         std::string current_playername;
770         std::string current_password;
771         std::string current_address;
772         int current_port;
773 };
774
775 #endif // !SERVER
776
777 static OptionList allowed_options;
778
779 int main(int argc, char *argv[])
780 {
781         int retval;
782
783         log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
784         log_add_output_all_levs(&main_dstream_no_stderr_log_out);
785
786         log_register_thread("main");
787
788         Settings cmd_args;
789         bool cmd_args_ok = get_cmdline_opts(argc, argv, &cmd_args);
790         if (!cmd_args_ok
791                         || cmd_args.getFlag("help")
792                         || cmd_args.exists("nonopt1")) {
793                 print_help(allowed_options);
794                 return cmd_args_ok ? 0 : 1;
795         }
796
797         if (cmd_args.getFlag("version")) {
798                 print_version();
799                 return 0;
800         }
801
802         setup_log_params(cmd_args);
803
804         porting::signal_handler_init();
805         porting::initializePaths();
806
807         if (!create_userdata_path()) {
808                 errorstream << "Cannot create user data directory" << std::endl;
809                 return 1;
810         }
811
812         // Initialize debug stacks
813         debug_stacks_init();
814         DSTACK(__FUNCTION_NAME);
815
816         // Debug handler
817         BEGIN_DEBUG_EXCEPTION_HANDLER
818
819         // List gameids if requested
820         if (cmd_args.exists("gameid") && cmd_args.get("gameid") == "list") {
821                 list_game_ids();
822                 return 0;
823         }
824
825         // List worlds if requested
826         if (cmd_args.exists("world") && cmd_args.get("world") == "list") {
827                 list_worlds();
828                 return 0;
829         }
830
831         GameParams game_params;
832         if (!init_common(&game_params.log_level, cmd_args, argc, argv))
833                 return 1;
834
835 #ifndef __ANDROID__
836         // Run unit tests
837         if ((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
838                         || cmd_args.getFlag("enable-unittests") == true) {
839                 run_tests();
840         }
841 #endif
842
843 #ifdef SERVER
844         game_params.is_dedicated_server = true;
845 #else
846         game_params.is_dedicated_server = cmd_args.getFlag("server");
847 #endif
848
849         if (!game_configure(&game_params, cmd_args))
850                 return 1;
851
852         assert(game_params.world_path != "");
853
854         infostream << "Using commanded world path ["
855                    << game_params.world_path << "]" << std::endl;
856
857         //Run dedicated server if asked to or no other option
858         g_settings->set("server_dedicated",
859                         game_params.is_dedicated_server ? "true" : "false");
860
861         if (game_params.is_dedicated_server)
862                 return run_dedicated_server(game_params, cmd_args) ? 0 : 1;
863
864 #ifndef SERVER
865         ClientLauncher launcher;
866         retval = launcher.run(game_params, cmd_args) ? 0 : 1;
867 #else
868         retval = 0;
869 #endif
870
871         // Update configuration file
872         if (g_settings_path != "")
873                 g_settings->updateConfigFile(g_settings_path.c_str());
874
875         print_modified_quicktune_values();
876
877         // Stop httpfetch thread (if started)
878         httpfetch_cleanup();
879
880         END_DEBUG_EXCEPTION_HANDLER(errorstream)
881
882         return retval;
883 }
884
885
886 /*****************************************************************************
887  * Startup / Init
888  *****************************************************************************/
889
890
891 static bool get_cmdline_opts(int argc, char *argv[], Settings *cmd_args)
892 {
893         set_allowed_options(&allowed_options);
894
895         return cmd_args->parseCommandLine(argc, argv, allowed_options);
896 }
897
898 static void set_allowed_options(OptionList *allowed_options)
899 {
900         allowed_options->clear();
901
902         allowed_options->insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
903                         _("Show allowed options"))));
904         allowed_options->insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
905                         _("Show version information"))));
906         allowed_options->insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
907                         _("Load configuration from specified file"))));
908         allowed_options->insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
909                         _("Set network port (UDP)"))));
910         allowed_options->insert(std::make_pair("disable-unittests", ValueSpec(VALUETYPE_FLAG,
911                         _("Disable unit tests"))));
912         allowed_options->insert(std::make_pair("enable-unittests", ValueSpec(VALUETYPE_FLAG,
913                         _("Enable unit tests"))));
914         allowed_options->insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
915                         _("Same as --world (deprecated)"))));
916         allowed_options->insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
917                         _("Set world path (implies local game) ('list' lists all)"))));
918         allowed_options->insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
919                         _("Set world by name (implies local game)"))));
920         allowed_options->insert(std::make_pair("quiet", ValueSpec(VALUETYPE_FLAG,
921                         _("Print to console errors only"))));
922         allowed_options->insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
923                         _("Print more information to console"))));
924         allowed_options->insert(std::make_pair("verbose",  ValueSpec(VALUETYPE_FLAG,
925                         _("Print even more information to console"))));
926         allowed_options->insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
927                         _("Print enormous amounts of information to log and console"))));
928         allowed_options->insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
929                         _("Set logfile path ('' = no logging)"))));
930         allowed_options->insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
931                         _("Set gameid (\"--gameid list\" prints available ones)"))));
932         allowed_options->insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
933                         _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
934 #ifndef SERVER
935         allowed_options->insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
936                         _("Show available video modes"))));
937         allowed_options->insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
938                         _("Run speed tests"))));
939         allowed_options->insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
940                         _("Address to connect to. ('' = local game)"))));
941         allowed_options->insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
942                         _("Enable random user input, for testing"))));
943         allowed_options->insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
944                         _("Run dedicated server"))));
945         allowed_options->insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
946                         _("Set player name"))));
947         allowed_options->insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
948                         _("Set password"))));
949         allowed_options->insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
950                         _("Disable main menu"))));
951 #endif
952
953 }
954
955 static void print_help(const OptionList &allowed_options)
956 {
957         dstream << _("Allowed options:") << std::endl;
958         print_allowed_options(allowed_options);
959 }
960
961 static void print_allowed_options(const OptionList &allowed_options)
962 {
963         for (OptionList::const_iterator i = allowed_options.begin();
964                         i != allowed_options.end(); ++i) {
965                 std::ostringstream os1(std::ios::binary);
966                 os1 << "  --" << i->first;
967                 if (i->second.type != VALUETYPE_FLAG)
968                         os1 << _(" <value>");
969
970                 dstream << padStringRight(os1.str(), 24);
971
972                 if (i->second.help != NULL)
973                         dstream << i->second.help;
974
975                 dstream << std::endl;
976         }
977 }
978
979 static void print_version()
980 {
981 #ifdef SERVER
982         dstream << "minetestserver " << minetest_version_hash << std::endl;
983 #else
984         dstream << "Minetest " << minetest_version_hash << std::endl;
985         dstream << "Using Irrlicht " << IRRLICHT_SDK_VERSION << std::endl;
986 #endif
987         dstream << "Build info: " << minetest_build_info << std::endl;
988 }
989
990 static void list_game_ids()
991 {
992         std::set<std::string> gameids = getAvailableGameIds();
993         for (std::set<std::string>::const_iterator i = gameids.begin();
994                         i != gameids.end(); i++)
995                 dstream << (*i) <<std::endl;
996 }
997
998 static void list_worlds()
999 {
1000         dstream << _("Available worlds:") << std::endl;
1001         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1002         print_worldspecs(worldspecs, dstream);
1003 }
1004
1005 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
1006                                                          std::ostream &os)
1007 {
1008         for (size_t i = 0; i < worldspecs.size(); i++) {
1009                 std::string name = worldspecs[i].name;
1010                 std::string path = worldspecs[i].path;
1011                 if (name.find(" ") != std::string::npos)
1012                         name = std::string("'") + name + "'";
1013                 path = std::string("'") + path + "'";
1014                 name = padStringRight(name, 14);
1015                 os << "  " << name << " " << path << std::endl;
1016         }
1017 }
1018
1019 static void print_modified_quicktune_values()
1020 {
1021         bool header_printed = false;
1022         std::vector<std::string> names = getQuicktuneNames();
1023
1024         for (u32 i = 0; i < names.size(); i++) {
1025                 QuicktuneValue val = getQuicktuneValue(names[i]);
1026                 if (!val.modified)
1027                         continue;
1028                 if (!header_printed) {
1029                         dstream << "Modified quicktune values:" << std::endl;
1030                         header_printed = true;
1031                 }
1032                 dstream << names[i] << " = " << val.getString() << std::endl;
1033         }
1034 }
1035
1036 static void setup_log_params(const Settings &cmd_args)
1037 {
1038         // Quiet mode, print errors only
1039         if (cmd_args.getFlag("quiet")) {
1040                 log_remove_output(&main_stderr_log_out);
1041                 log_add_output_maxlev(&main_stderr_log_out, LMT_ERROR);
1042         }
1043
1044         // If trace is enabled, enable logging of certain things
1045         if (cmd_args.getFlag("trace")) {
1046                 dstream << _("Enabling trace level debug output") << std::endl;
1047                 log_trace_level_enabled = true;
1048                 dout_con_ptr = &verbosestream; // this is somewhat old crap
1049                 socket_enable_debug_output = true; // socket doesn't use log.h
1050         }
1051
1052         // In certain cases, output info level on stderr
1053         if (cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
1054                         cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
1055                 log_add_output(&main_stderr_log_out, LMT_INFO);
1056
1057         // In certain cases, output verbose level on stderr
1058         if (cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
1059                 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
1060 }
1061
1062 static bool create_userdata_path()
1063 {
1064         bool success;
1065
1066 #ifdef __ANDROID__
1067         porting::initAndroid();
1068
1069         porting::setExternalStorageDir(porting::jnienv);
1070         if (!fs::PathExists(porting::path_user)) {
1071                 success = fs::CreateDir(porting::path_user);
1072         } else {
1073                 success = true;
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, int argc, char *argv[])
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 (glb_fontengine)
1573                 delete glb_fontengine;
1574
1575         if (device)
1576                 device->drop();
1577 }
1578
1579 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
1580 {
1581         init_args(game_params, cmd_args);
1582
1583         // List video modes if requested
1584         if (list_video_modes)
1585                 return print_video_modes();
1586
1587         if (!init_engine(game_params.log_level)) {
1588                 errorstream << "Could not initialize game engine." << std::endl;
1589                 return false;
1590         }
1591
1592         // Speed tests (done after irrlicht is loaded to get timer)
1593         if (cmd_args.getFlag("speedtests")) {
1594                 dstream << "Running speed tests" << std::endl;
1595                 speed_tests();
1596                 return true;
1597         }
1598
1599         if (device->getVideoDriver() == NULL) {
1600                 errorstream << "Could not initialize video driver." << std::endl;
1601                 return false;
1602         }
1603
1604         /*
1605                 This changes the minimum allowed number of vertices in a VBO.
1606                 Default is 500.
1607         */
1608         //driver->setMinHardwareBufferVertexCount(50);
1609
1610         // Create time getter
1611         g_timegetter = new IrrlichtTimeGetter(device);
1612
1613         // Create game callback for menus
1614         g_gamecallback = new MainGameCallback(device);
1615
1616         device->setResizable(true);
1617
1618         if (random_input)
1619                 input = new RandomInputHandler();
1620         else
1621                 input = new RealInputHandler(device, receiver);
1622
1623         smgr = device->getSceneManager();
1624
1625         guienv = device->getGUIEnvironment();
1626         skin = guienv->getSkin();
1627         skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
1628         skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 0, 0, 0));
1629         skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
1630         skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 100, 50));
1631         skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
1632
1633         glb_fontengine = new FontEngine(g_settings, guienv);
1634         assert(glb_fontengine != NULL);
1635
1636 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1637         // Irrlicht 1.8 input colours
1638         skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
1639         skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
1640 #endif
1641
1642         // Create the menu clouds
1643         if (!g_menucloudsmgr)
1644                 g_menucloudsmgr = smgr->createNewSceneManager();
1645         if (!g_menuclouds)
1646                 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1647                                 g_menucloudsmgr, -1, rand(), 100);
1648         g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
1649         scene::ICameraSceneNode* camera;
1650         camera = g_menucloudsmgr->addCameraSceneNode(0,
1651                                 v3f(0, 0, 0), v3f(0, 60, 100));
1652         camera->setFarValue(10000);
1653
1654         /*
1655                 GUI stuff
1656         */
1657
1658         ChatBackend chat_backend;
1659
1660         // If an error occurs, this is set to something by menu().
1661         // It is then displayed before  the menu shows on the next call to menu()
1662         std::wstring error_message = L"";
1663
1664         bool first_loop = true;
1665
1666         /*
1667                 Menu-game loop
1668         */
1669         bool retval = true;
1670         bool *kill = porting::signal_handler_killstatus();
1671
1672         while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
1673         {
1674                 // Set the window caption
1675                 wchar_t *text = wgettext("Main Menu");
1676                 device->setWindowCaption((std::wstring(L"Minetest [") + text + L"]").c_str());
1677                 delete[] text;
1678
1679                 try {   // This is used for catching disconnects
1680
1681                         guienv->clear();
1682
1683                         /*
1684                                 We need some kind of a root node to be able to add
1685                                 custom gui elements directly on the screen.
1686                                 Otherwise they won't be automatically drawn.
1687                         */
1688                         guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
1689
1690                         bool game_has_run = launch_game(&error_message, game_params, cmd_args);
1691
1692                         // If skip_main_menu, we only want to startup once
1693                         if (skip_main_menu && !first_loop)
1694                                 break;
1695
1696                         first_loop = false;
1697
1698                         if (!game_has_run) {
1699                                 if (skip_main_menu)
1700                                         break;
1701                                 else
1702                                         continue;
1703                         }
1704
1705                         // Break out of menu-game loop to shut down cleanly
1706                         if (!device->run() || *kill) {
1707                                 if (g_settings_path != "")
1708                                         g_settings->updateConfigFile(g_settings_path.c_str());
1709                                 break;
1710                         }
1711
1712                         if (current_playername.length() > PLAYERNAME_SIZE-1) {
1713                                 error_message = wgettext("Player name too long.");
1714                                 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
1715                                 g_settings->set("name", playername);
1716                                 continue;
1717                         }
1718
1719                         device->getVideoDriver()->setTextureCreationFlag(
1720                                         video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
1721
1722 #ifdef HAVE_TOUCHSCREENGUI
1723                         receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
1724                         g_touchscreengui = receiver->m_touchscreengui;
1725 #endif
1726                         the_game(
1727                                 kill,
1728                                 random_input,
1729                                 input,
1730                                 device,
1731                                 worldspec.path,
1732                                 current_playername,
1733                                 current_password,
1734                                 current_address,
1735                                 current_port,
1736                                 error_message,
1737                                 chat_backend,
1738                                 gamespec,
1739                                 simple_singleplayer_mode
1740                         );
1741                         smgr->clear();
1742
1743 #ifdef HAVE_TOUCHSCREENGUI
1744                         delete g_touchscreengui;
1745                         g_touchscreengui = NULL;
1746                         receiver->m_touchscreengui = NULL;
1747 #endif
1748
1749                 } //try
1750                 catch (con::PeerNotFoundException &e) {
1751                         error_message = wgettext("Connection error (timed out?)");
1752                         errorstream << wide_to_narrow(error_message) << std::endl;
1753                 }
1754
1755 #ifdef NDEBUG
1756                 catch (std::exception &e) {
1757                         std::string narrow_message = "Some exception: \"";
1758                         narrow_message += e.what();
1759                         narrow_message += "\"";
1760                         errorstream << narrow_message << std::endl;
1761                         error_message = narrow_to_wide(narrow_message);
1762                 }
1763 #endif
1764
1765                 // If no main menu, show error and exit
1766                 if (skip_main_menu) {
1767                         if (error_message != L"") {
1768                                 verbosestream << "error_message = "
1769                                               << wide_to_narrow(error_message) << std::endl;
1770                                 retval = false;
1771                         }
1772                         break;
1773                 }
1774         } // Menu-game loop
1775
1776         g_menuclouds->drop();
1777         g_menucloudsmgr->drop();
1778
1779         return retval;
1780 }
1781
1782 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
1783 {
1784
1785         skip_main_menu = cmd_args.getFlag("go");
1786
1787         // FIXME: This is confusing (but correct)
1788
1789         /* If world_path is set then override it unless skipping the main menu using
1790          * the --go command line param. Else, give preference to the address
1791          * supplied on the command line
1792          */
1793         address = g_settings->get("address");
1794         if (game_params.world_path != "" && !skip_main_menu)
1795                 address = "";
1796         else if (cmd_args.exists("address"))
1797                 address = cmd_args.get("address");
1798
1799         playername = g_settings->get("name");
1800         if (cmd_args.exists("name"))
1801                 playername = cmd_args.get("name");
1802
1803         list_video_modes = cmd_args.getFlag("videomodes");
1804
1805         use_freetype = g_settings->getBool("freetype");
1806
1807         random_input = g_settings->getBool("random_input")
1808                         || cmd_args.getFlag("random-input");
1809 }
1810
1811 bool ClientLauncher::init_engine(int log_level)
1812 {
1813         receiver = new MyEventReceiver();
1814         create_engine_device(log_level);
1815         return device != NULL;
1816 }
1817
1818 bool ClientLauncher::launch_game(std::wstring *error_message,
1819                 GameParams &game_params, const Settings &cmd_args)
1820 {
1821         // Initialize menu data
1822         MainMenuData menudata;
1823         menudata.address      = address;
1824         menudata.name         = playername;
1825         menudata.port         = itos(game_params.socket_port);
1826         menudata.errormessage = wide_to_narrow(*error_message);
1827
1828         *error_message = L"";
1829
1830         if (cmd_args.exists("password"))
1831                 menudata.password = cmd_args.get("password");
1832
1833         menudata.enable_public = g_settings->getBool("server_announce");
1834
1835         // If a world was commanded, append and select it
1836         if (game_params.world_path != "") {
1837                 worldspec.gameid = getWorldGameId(game_params.world_path, true);
1838                 worldspec.name = _("[--world parameter]");
1839
1840                 if (worldspec.gameid == "") {   // Create new
1841                         worldspec.gameid = g_settings->get("default_game");
1842                         worldspec.name += " [new]";
1843                 }
1844                 worldspec.path = game_params.world_path;
1845         }
1846
1847         /* Show the GUI menu
1848          */
1849         if (!skip_main_menu) {
1850                 main_menu(&menudata);
1851
1852                 address = menudata.address;
1853                 int newport = stoi(menudata.port);
1854                 if (newport != 0)
1855                         game_params.socket_port = newport;
1856
1857                 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1858
1859                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1860                 worldspecs = getAvailableWorlds();
1861
1862                 if (menudata.selected_world >= 0
1863                                 && menudata.selected_world < (int)worldspecs.size()) {
1864                         g_settings->set("selected_world_path",
1865                                         worldspecs[menudata.selected_world].path);
1866                         worldspec = worldspecs[menudata.selected_world];
1867                 }
1868         }
1869
1870         if (menudata.errormessage != "") {
1871                 /* The calling function will pass this back into this function upon the
1872                  * next iteration (if any) causing it to be displayed by the GUI
1873                  */
1874                 *error_message = narrow_to_wide(menudata.errormessage);
1875                 return false;
1876         }
1877
1878         if (menudata.name == "")
1879                 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
1880         else
1881                 playername = menudata.name;
1882
1883         password = translatePassword(playername, narrow_to_wide(menudata.password));
1884
1885         g_settings->set("name", playername);
1886
1887         current_playername = playername;
1888         current_password   = password;
1889         current_address    = address;
1890         current_port       = game_params.socket_port;
1891
1892         // If using simple singleplayer mode, override
1893         if (simple_singleplayer_mode) {
1894                 assert(skip_main_menu == false);
1895                 current_playername = "singleplayer";
1896                 current_password = "";
1897                 current_address = "";
1898                 current_port = myrand_range(49152, 65535);
1899         } else if (address != "") {
1900                 ServerListSpec server;
1901                 server["name"] = menudata.servername;
1902                 server["address"] = menudata.address;
1903                 server["port"] = menudata.port;
1904                 server["description"] = menudata.serverdescription;
1905                 ServerList::insert(server);
1906         }
1907
1908         infostream << "Selected world: " << worldspec.name
1909                    << " [" << worldspec.path << "]" << std::endl;
1910
1911         if (current_address == "") { // If local game
1912                 if (worldspec.path == "") {
1913                         *error_message = wgettext("No world selected and no address "
1914                                         "provided. Nothing to do.");
1915                         errorstream << wide_to_narrow(*error_message) << std::endl;
1916                         return false;
1917                 }
1918
1919                 if (!fs::PathExists(worldspec.path)) {
1920                         *error_message = wgettext("Provided world path doesn't exist: ")
1921                                         + narrow_to_wide(worldspec.path);
1922                         errorstream << wide_to_narrow(*error_message) << std::endl;
1923                         return false;
1924                 }
1925
1926                 // Load gamespec for required game
1927                 gamespec = findWorldSubgame(worldspec.path);
1928                 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
1929                         *error_message = wgettext("Could not find or load game \"")
1930                                         + narrow_to_wide(worldspec.gameid) + L"\"";
1931                         errorstream << wide_to_narrow(*error_message) << std::endl;
1932                         return false;
1933                 }
1934                 if (game_params.game_spec.isValid() &&
1935                                 game_params.game_spec.id != worldspec.gameid) {
1936                         errorstream << "WARNING: Overriding gamespec from \""
1937                                     << worldspec.gameid << "\" to \""
1938                                     << game_params.game_spec.id << "\"" << std::endl;
1939                         gamespec = game_params.game_spec;
1940                 }
1941
1942                 if (!gamespec.isValid()) {
1943                         *error_message = wgettext("Invalid gamespec.");
1944                         *error_message += L" (world_gameid="
1945                                         + narrow_to_wide(worldspec.gameid) + L")";
1946                         errorstream << wide_to_narrow(*error_message) << std::endl;
1947                         return false;
1948                 }
1949         }
1950
1951         return true;
1952 }
1953
1954 void ClientLauncher::main_menu(MainMenuData *menudata)
1955 {
1956         bool *kill = porting::signal_handler_killstatus();
1957         video::IVideoDriver *driver = device->getVideoDriver();
1958
1959         infostream << "Waiting for other menus" << std::endl;
1960         while (device->run() && *kill == false) {
1961                 if (noMenuActive())
1962                         break;
1963                 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
1964                 guienv->drawAll();
1965                 driver->endScene();
1966                 // On some computers framerate doesn't seem to be automatically limited
1967                 sleep_ms(25);
1968         }
1969         infostream << "Waited for other menus" << std::endl;
1970
1971         // Cursor can be non-visible when coming from the game
1972 #ifndef ANDROID
1973         device->getCursorControl()->setVisible(true);
1974 #endif
1975
1976         /* show main menu */
1977         GUIEngine mymenu(device, guiroot, &g_menumgr, smgr, menudata, *kill);
1978
1979         smgr->clear();  /* leave scene manager in a clean state */
1980 }
1981
1982 bool ClientLauncher::create_engine_device(int log_level)
1983 {
1984         static const char *driverids[] = {
1985                 "null",
1986                 "software",
1987                 "burningsvideo",
1988                 "direct3d8",
1989                 "direct3d9",
1990                 "opengl"
1991 #ifdef _IRR_COMPILE_WITH_OGLES1_
1992                 ,"ogles1"
1993 #endif
1994 #ifdef _IRR_COMPILE_WITH_OGLES2_
1995                 ,"ogles2"
1996 #endif
1997                 ,"invalid"
1998         };
1999
2000         static const irr::ELOG_LEVEL irr_log_level[5] = {
2001                 ELL_NONE,
2002                 ELL_ERROR,
2003                 ELL_WARNING,
2004                 ELL_INFORMATION,
2005 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
2006                 ELL_INFORMATION
2007 #else
2008                 ELL_DEBUG
2009 #endif
2010         };
2011
2012         // Resolution selection
2013         bool fullscreen = g_settings->getBool("fullscreen");
2014         u16 screenW = g_settings->getU16("screenW");
2015         u16 screenH = g_settings->getU16("screenH");
2016
2017         // bpp, fsaa, vsync
2018         bool vsync = g_settings->getBool("vsync");
2019         u16 bits = g_settings->getU16("fullscreen_bpp");
2020         u16 fsaa = g_settings->getU16("fsaa");
2021
2022         // Determine driver
2023         video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
2024
2025         std::string driverstring = g_settings->get("video_driver");
2026         for (size_t i = 0; i < sizeof driverids / sizeof driverids[0]; i++) {
2027                 if (strcasecmp(driverstring.c_str(), driverids[i]) == 0) {
2028                         driverType = (video::E_DRIVER_TYPE) i;
2029                         break;
2030                 }
2031
2032                 if (strcasecmp("invalid", driverids[i]) == 0) {
2033                         errorstream << "WARNING: Invalid video_driver specified;"
2034                                     << " defaulting to opengl" << std::endl;
2035                         break;
2036                 }
2037         }
2038
2039         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2040         params.DriverType    = driverType;
2041         params.WindowSize    = core::dimension2d<u32>(screenW, screenH);
2042         params.Bits          = bits;
2043         params.AntiAlias     = fsaa;
2044         params.Fullscreen    = fullscreen;
2045         params.Stencilbuffer = false;
2046         params.Vsync         = vsync;
2047         params.EventReceiver = receiver;
2048         params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2049 #ifdef __ANDROID__
2050         params.PrivateData = porting::app_global;
2051         params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
2052                         "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
2053 #endif
2054
2055         device = createDeviceEx(params);
2056
2057         if (device) {
2058                 // Map our log level to irrlicht engine one.
2059                 ILogger* irr_logger = device->getLogger();
2060                 irr_logger->setLogLevel(irr_log_level[log_level]);
2061
2062                 porting::initIrrlicht(device);
2063         }
2064
2065         return device != NULL;
2066 }
2067
2068 // Misc functions
2069
2070 static bool print_video_modes()
2071 {
2072         IrrlichtDevice *nulldevice;
2073
2074         bool vsync = g_settings->getBool("vsync");
2075         u16 fsaa = g_settings->getU16("fsaa");
2076         MyEventReceiver* receiver = new MyEventReceiver();
2077
2078         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2079         params.DriverType    = video::EDT_NULL;
2080         params.WindowSize    = core::dimension2d<u32>(640, 480);
2081         params.Bits          = 24;
2082         params.AntiAlias     = fsaa;
2083         params.Fullscreen    = false;
2084         params.Stencilbuffer = false;
2085         params.Vsync         = vsync;
2086         params.EventReceiver = receiver;
2087         params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2088
2089         nulldevice = createDeviceEx(params);
2090
2091         if (nulldevice == NULL) {
2092                 delete receiver;
2093                 return false;
2094         }
2095
2096         dstream << _("Available video modes (WxHxD):") << std::endl;
2097
2098         video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
2099
2100         if (videomode_list != NULL) {
2101                 s32 videomode_count = videomode_list->getVideoModeCount();
2102                 core::dimension2d<u32> videomode_res;
2103                 s32 videomode_depth;
2104                 for (s32 i = 0; i < videomode_count; ++i) {
2105                         videomode_res = videomode_list->getVideoModeResolution(i);
2106                         videomode_depth = videomode_list->getVideoModeDepth(i);
2107                         dstream << videomode_res.Width << "x" << videomode_res.Height
2108                                 << "x" << videomode_depth << std::endl;
2109                 }
2110
2111                 dstream << _("Active video mode (WxHxD):") << std::endl;
2112                 videomode_res = videomode_list->getDesktopResolution();
2113                 videomode_depth = videomode_list->getDesktopDepth();
2114                 dstream << videomode_res.Width << "x" << videomode_res.Height
2115                         << "x" << videomode_depth << std::endl;
2116
2117         }
2118
2119         nulldevice->drop();
2120         delete receiver;
2121
2122         return videomode_list != NULL;
2123 }
2124
2125 #endif // !SERVER
2126
2127 /*****************************************************************************
2128  * Performance tests
2129  *****************************************************************************/
2130 #ifndef SERVER
2131 static void speed_tests()
2132 {
2133         // volatile to avoid some potential compiler optimisations
2134         volatile static s16 temp16;
2135         volatile static f32 tempf;
2136         static v3f tempv3f1;
2137         static v3f tempv3f2;
2138         static std::string tempstring;
2139         static std::string tempstring2;
2140
2141         tempv3f1 = v3f();
2142         tempv3f2 = v3f();
2143         tempstring = std::string();
2144         tempstring2 = std::string();
2145
2146         {
2147                 infostream << "The following test should take around 20ms." << std::endl;
2148                 TimeTaker timer("Testing std::string speed");
2149                 const u32 jj = 10000;
2150                 for (u32 j = 0; j < jj; j++) {
2151                         tempstring = "";
2152                         tempstring2 = "";
2153                         const u32 ii = 10;
2154                         for (u32 i = 0; i < ii; i++) {
2155                                 tempstring2 += "asd";
2156                         }
2157                         for (u32 i = 0; i < ii+1; i++) {
2158                                 tempstring += "asd";
2159                                 if (tempstring == tempstring2)
2160                                         break;
2161                         }
2162                 }
2163         }
2164
2165         infostream << "All of the following tests should take around 100ms each."
2166                    << std::endl;
2167
2168         {
2169                 TimeTaker timer("Testing floating-point conversion speed");
2170                 tempf = 0.001;
2171                 for (u32 i = 0; i < 4000000; i++) {
2172                         temp16 += tempf;
2173                         tempf += 0.001;
2174                 }
2175         }
2176
2177         {
2178                 TimeTaker timer("Testing floating-point vector speed");
2179
2180                 tempv3f1 = v3f(1, 2, 3);
2181                 tempv3f2 = v3f(4, 5, 6);
2182                 for (u32 i = 0; i < 10000000; i++) {
2183                         tempf += tempv3f1.dotProduct(tempv3f2);
2184                         tempv3f2 += v3f(7, 8, 9);
2185                 }
2186         }
2187
2188         {
2189                 TimeTaker timer("Testing std::map speed");
2190
2191                 std::map<v2s16, f32> map1;
2192                 tempf = -324;
2193                 const s16 ii = 300;
2194                 for (s16 y = 0; y < ii; y++) {
2195                         for (s16 x = 0; x < ii; x++) {
2196                                 map1[v2s16(x, y)] =  tempf;
2197                                 tempf += 1;
2198                         }
2199                 }
2200                 for (s16 y = ii - 1; y >= 0; y--) {
2201                         for (s16 x = 0; x < ii; x++) {
2202                                 tempf = map1[v2s16(x, y)];
2203                         }
2204                 }
2205         }
2206
2207         {
2208                 infostream << "Around 5000/ms should do well here." << std::endl;
2209                 TimeTaker timer("Testing mutex speed");
2210
2211                 JMutex m;
2212                 u32 n = 0;
2213                 u32 i = 0;
2214                 do {
2215                         n += 10000;
2216                         for (; i < n; i++) {
2217                                 m.Lock();
2218                                 m.Unlock();
2219                         }
2220                 }
2221                 // Do at least 10ms
2222                 while(timer.getTimerTime() < 10);
2223
2224                 u32 dtime = timer.stop();
2225                 u32 per_ms = n / dtime;
2226                 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
2227         }
2228 }
2229 #endif