Reorganize supported video driver query mechanisms
[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                         if (!gamespec.isValid()) {
1399                                 errorstream << "Subgame specified in default_game ["
1400                                             << g_settings->get("default_game")
1401                                             << "] is invalid." << std::endl;
1402                                 return false;
1403                         }
1404                 }
1405         } else { // World exists
1406                 std::string world_gameid = getWorldGameId(game_params->world_path, false);
1407                 // If commanded to use a gameid, do so
1408                 if (game_params->game_spec.isValid()) {
1409                         gamespec = game_params->game_spec;
1410                         if (game_params->game_spec.id != world_gameid) {
1411                                 errorstream << "WARNING: Using commanded gameid ["
1412                                             << gamespec.id << "]" << " instead of world gameid ["
1413                                             << world_gameid << "]" << std::endl;
1414                         }
1415                 } else {
1416                         // If world contains an embedded game, use it;
1417                         // Otherwise find world from local system.
1418                         gamespec = findWorldSubgame(game_params->world_path);
1419                         infostream << "Using world gameid [" << gamespec.id << "]" << std::endl;
1420                 }
1421         }
1422
1423         if (!gamespec.isValid()) {
1424                 errorstream << "Subgame [" << gamespec.id << "] could not be found."
1425                             << std::endl;
1426                 return false;
1427         }
1428
1429         game_params->game_spec = gamespec;
1430         return true;
1431 }
1432
1433
1434 /*****************************************************************************
1435  * Dedicated server
1436  *****************************************************************************/
1437 static bool run_dedicated_server(const GameParams &game_params, const Settings &cmd_args)
1438 {
1439         DSTACK("Dedicated server branch");
1440
1441         verbosestream << _("Using world path") << " ["
1442                       << game_params.world_path << "]" << std::endl;
1443         verbosestream << _("Using gameid") << " ["
1444                       << game_params.game_spec.id << "]" << std::endl;
1445
1446         // Bind address
1447         std::string bind_str = g_settings->get("bind_address");
1448         Address bind_addr(0, 0, 0, 0, game_params.socket_port);
1449
1450         if (g_settings->getBool("ipv6_server")) {
1451                 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1452         }
1453         try {
1454                 bind_addr.Resolve(bind_str.c_str());
1455         } catch (ResolveError &e) {
1456                 infostream << "Resolving bind address \"" << bind_str
1457                            << "\" failed: " << e.what()
1458                            << " -- Listening on all addresses." << std::endl;
1459         }
1460         if (bind_addr.isIPv6() && !g_settings->getBool("enable_ipv6")) {
1461                 errorstream << "Unable to listen on "
1462                             << bind_addr.serializeString()
1463                             << L" because IPv6 is disabled" << std::endl;
1464                 return false;
1465         }
1466
1467         // Create server
1468         Server server(game_params.world_path,
1469                         game_params.game_spec, false, bind_addr.isIPv6());
1470
1471         // Database migration
1472         if (cmd_args.exists("migrate"))
1473                 return migrate_database(game_params, cmd_args, &server);
1474
1475         server.start(bind_addr);
1476
1477         // Run server
1478         bool &kill = *porting::signal_handler_killstatus();
1479         dedicated_server_loop(server, kill);
1480
1481         return true;
1482 }
1483
1484 static bool migrate_database(const GameParams &game_params, const Settings &cmd_args,
1485                 Server *server)
1486 {
1487         Settings world_mt;
1488         bool success = world_mt.readConfigFile((game_params.world_path
1489                         + DIR_DELIM + "world.mt").c_str());
1490         if (!success) {
1491                 errorstream << "Cannot read world.mt" << std::endl;
1492                 return false;
1493         }
1494
1495         if (!world_mt.exists("backend")) {
1496                 errorstream << "Please specify your current backend in world.mt file:"
1497                             << std::endl << "   backend = {sqlite3|leveldb|redis|dummy}"
1498                             << std::endl;
1499                 return false;
1500         }
1501
1502         std::string backend = world_mt.get("backend");
1503         Database *new_db;
1504         std::string migrate_to = cmd_args.get("migrate");
1505
1506         if (backend == migrate_to) {
1507                 errorstream << "Cannot migrate: new backend is same as the old one"
1508                             << std::endl;
1509                 return false;
1510         }
1511
1512         if (migrate_to == "sqlite3")
1513                 new_db = new Database_SQLite3(&(ServerMap&)server->getMap(),
1514                                 game_params.world_path);
1515 #if USE_LEVELDB
1516         else if (migrate_to == "leveldb")
1517                 new_db = new Database_LevelDB(&(ServerMap&)server->getMap(),
1518                                 game_params.world_path);
1519 #endif
1520 #if USE_REDIS
1521         else if (migrate_to == "redis")
1522                 new_db = new Database_Redis(&(ServerMap&)server->getMap(),
1523                                 game_params.world_path);
1524 #endif
1525         else {
1526                 errorstream << "Migration to " << migrate_to << " is not supported"
1527                             << std::endl;
1528                 return false;
1529         }
1530
1531         std::list<v3s16> blocks;
1532         ServerMap &old_map = ((ServerMap&)server->getMap());
1533         old_map.listAllLoadableBlocks(blocks);
1534         int count = 0;
1535         new_db->beginSave();
1536         for (std::list<v3s16>::iterator i = blocks.begin(); i != blocks.end(); i++) {
1537                 MapBlock *block = old_map.loadBlock(*i);
1538                 if (!block) {
1539                         errorstream << "Failed to load block " << PP(*i) << ", skipping it.";
1540                 } else {
1541                         old_map.saveBlock(block, new_db);
1542                         MapSector *sector = old_map.getSectorNoGenerate(v2s16(i->X, i->Z));
1543                         sector->deleteBlock(block);
1544                 }
1545                 ++count;
1546                 if (count % 500 == 0)
1547                    actionstream << "Migrated " << count << " blocks "
1548                            << (100.0 * count / blocks.size()) << "% completed" << std::endl;
1549         }
1550         new_db->endSave();
1551         delete new_db;
1552
1553         actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1554         world_mt.set("backend", migrate_to);
1555         if (!world_mt.updateConfigFile(
1556                                 (game_params.world_path+ DIR_DELIM + "world.mt").c_str()))
1557                 errorstream << "Failed to update world.mt!" << std::endl;
1558         else
1559                 actionstream << "world.mt updated" << std::endl;
1560
1561         return true;
1562 }
1563
1564
1565 /*****************************************************************************
1566  * Client
1567  *****************************************************************************/
1568 #ifndef SERVER
1569
1570 ClientLauncher::~ClientLauncher()
1571 {
1572         if (receiver)
1573                 delete receiver;
1574
1575         if (input)
1576                 delete input;
1577
1578         if (g_fontengine)
1579                 delete g_fontengine;
1580
1581         if (device)
1582                 device->drop();
1583 }
1584
1585
1586 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
1587 {
1588         init_args(game_params, cmd_args);
1589
1590         // List video modes if requested
1591         if (list_video_modes)
1592                 return print_video_modes();
1593
1594         if (!init_engine(game_params.log_level)) {
1595                 errorstream << "Could not initialize game engine." << std::endl;
1596                 return false;
1597         }
1598
1599         // Speed tests (done after irrlicht is loaded to get timer)
1600         if (cmd_args.getFlag("speedtests")) {
1601                 dstream << "Running speed tests" << std::endl;
1602                 speed_tests();
1603                 return true;
1604         }
1605
1606         video::IVideoDriver *video_driver = device->getVideoDriver();
1607         if (video_driver == NULL) {
1608                 errorstream << "Could not initialize video driver." << std::endl;
1609                 return false;
1610         }
1611
1612         porting::setXorgClassHint(video_driver->getExposedVideoData(), "Minetest");
1613
1614         /*
1615                 This changes the minimum allowed number of vertices in a VBO.
1616                 Default is 500.
1617         */
1618         //driver->setMinHardwareBufferVertexCount(50);
1619
1620         // Create time getter
1621         g_timegetter = new IrrlichtTimeGetter(device);
1622
1623         // Create game callback for menus
1624         g_gamecallback = new MainGameCallback(device);
1625
1626         device->setResizable(true);
1627
1628         if (random_input)
1629                 input = new RandomInputHandler();
1630         else
1631                 input = new RealInputHandler(device, receiver);
1632
1633         smgr = device->getSceneManager();
1634
1635         guienv = device->getGUIEnvironment();
1636         skin = guienv->getSkin();
1637         skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
1638         skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 0, 0, 0));
1639         skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
1640         skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 100, 50));
1641         skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
1642
1643         g_fontengine = new FontEngine(g_settings, guienv);
1644         assert(g_fontengine != NULL);
1645
1646 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1647         // Irrlicht 1.8 input colours
1648         skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
1649         skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
1650 #endif
1651
1652         // Create the menu clouds
1653         if (!g_menucloudsmgr)
1654                 g_menucloudsmgr = smgr->createNewSceneManager();
1655         if (!g_menuclouds)
1656                 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1657                                 g_menucloudsmgr, -1, rand(), 100);
1658         g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
1659         scene::ICameraSceneNode* camera;
1660         camera = g_menucloudsmgr->addCameraSceneNode(0,
1661                                 v3f(0, 0, 0), v3f(0, 60, 100));
1662         camera->setFarValue(10000);
1663
1664         /*
1665                 GUI stuff
1666         */
1667
1668         ChatBackend chat_backend;
1669
1670         // If an error occurs, this is set to something by menu().
1671         // It is then displayed before  the menu shows on the next call to menu()
1672         std::wstring error_message = L"";
1673
1674         bool first_loop = true;
1675
1676         /*
1677                 Menu-game loop
1678         */
1679         bool retval = true;
1680         bool *kill = porting::signal_handler_killstatus();
1681
1682         while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
1683         {
1684                 // Set the window caption
1685                 wchar_t *text = wgettext("Main Menu");
1686                 device->setWindowCaption((std::wstring(L"Minetest [") + text + L"]").c_str());
1687                 delete[] text;
1688
1689                 try {   // This is used for catching disconnects
1690
1691                         guienv->clear();
1692
1693                         /*
1694                                 We need some kind of a root node to be able to add
1695                                 custom gui elements directly on the screen.
1696                                 Otherwise they won't be automatically drawn.
1697                         */
1698                         guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
1699
1700                         bool game_has_run = launch_game(&error_message, game_params, cmd_args);
1701
1702                         // If skip_main_menu, we only want to startup once
1703                         if (skip_main_menu && !first_loop)
1704                                 break;
1705
1706                         first_loop = false;
1707
1708                         if (!game_has_run) {
1709                                 if (skip_main_menu)
1710                                         break;
1711                                 else
1712                                         continue;
1713                         }
1714
1715                         // Break out of menu-game loop to shut down cleanly
1716                         if (!device->run() || *kill) {
1717                                 if (g_settings_path != "")
1718                                         g_settings->updateConfigFile(g_settings_path.c_str());
1719                                 break;
1720                         }
1721
1722                         if (current_playername.length() > PLAYERNAME_SIZE-1) {
1723                                 error_message = wgettext("Player name too long.");
1724                                 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
1725                                 g_settings->set("name", playername);
1726                                 continue;
1727                         }
1728
1729                         device->getVideoDriver()->setTextureCreationFlag(
1730                                         video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
1731
1732 #ifdef HAVE_TOUCHSCREENGUI
1733                         receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
1734                         g_touchscreengui = receiver->m_touchscreengui;
1735 #endif
1736                         the_game(
1737                                 kill,
1738                                 random_input,
1739                                 input,
1740                                 device,
1741                                 worldspec.path,
1742                                 current_playername,
1743                                 current_password,
1744                                 current_address,
1745                                 current_port,
1746                                 error_message,
1747                                 chat_backend,
1748                                 gamespec,
1749                                 simple_singleplayer_mode
1750                         );
1751                         smgr->clear();
1752
1753 #ifdef HAVE_TOUCHSCREENGUI
1754                         delete g_touchscreengui;
1755                         g_touchscreengui = NULL;
1756                         receiver->m_touchscreengui = NULL;
1757 #endif
1758
1759                 } //try
1760                 catch (con::PeerNotFoundException &e) {
1761                         error_message = wgettext("Connection error (timed out?)");
1762                         errorstream << wide_to_narrow(error_message) << std::endl;
1763                 }
1764
1765 #ifdef NDEBUG
1766                 catch (std::exception &e) {
1767                         std::string narrow_message = "Some exception: \"";
1768                         narrow_message += e.what();
1769                         narrow_message += "\"";
1770                         errorstream << narrow_message << std::endl;
1771                         error_message = narrow_to_wide(narrow_message);
1772                 }
1773 #endif
1774
1775                 // If no main menu, show error and exit
1776                 if (skip_main_menu) {
1777                         if (error_message != L"") {
1778                                 verbosestream << "error_message = "
1779                                               << wide_to_narrow(error_message) << std::endl;
1780                                 retval = false;
1781                         }
1782                         break;
1783                 }
1784         } // Menu-game loop
1785
1786         g_menuclouds->drop();
1787         g_menucloudsmgr->drop();
1788
1789         return retval;
1790 }
1791
1792 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
1793 {
1794
1795         skip_main_menu = cmd_args.getFlag("go");
1796
1797         // FIXME: This is confusing (but correct)
1798
1799         /* If world_path is set then override it unless skipping the main menu using
1800          * the --go command line param. Else, give preference to the address
1801          * supplied on the command line
1802          */
1803         address = g_settings->get("address");
1804         if (game_params.world_path != "" && !skip_main_menu)
1805                 address = "";
1806         else if (cmd_args.exists("address"))
1807                 address = cmd_args.get("address");
1808
1809         playername = g_settings->get("name");
1810         if (cmd_args.exists("name"))
1811                 playername = cmd_args.get("name");
1812
1813         list_video_modes = cmd_args.getFlag("videomodes");
1814
1815         use_freetype = g_settings->getBool("freetype");
1816
1817         random_input = g_settings->getBool("random_input")
1818                         || cmd_args.getFlag("random-input");
1819 }
1820
1821 bool ClientLauncher::init_engine(int log_level)
1822 {
1823         receiver = new MyEventReceiver();
1824         create_engine_device(log_level);
1825         return device != NULL;
1826 }
1827
1828 bool ClientLauncher::launch_game(std::wstring *error_message,
1829                 GameParams &game_params, const Settings &cmd_args)
1830 {
1831         // Initialize menu data
1832         MainMenuData menudata;
1833         menudata.address      = address;
1834         menudata.name         = playername;
1835         menudata.port         = itos(game_params.socket_port);
1836         menudata.errormessage = wide_to_narrow(*error_message);
1837
1838         *error_message = L"";
1839
1840         if (cmd_args.exists("password"))
1841                 menudata.password = cmd_args.get("password");
1842
1843         menudata.enable_public = g_settings->getBool("server_announce");
1844
1845         // If a world was commanded, append and select it
1846         if (game_params.world_path != "") {
1847                 worldspec.gameid = getWorldGameId(game_params.world_path, true);
1848                 worldspec.name = _("[--world parameter]");
1849
1850                 if (worldspec.gameid == "") {   // Create new
1851                         worldspec.gameid = g_settings->get("default_game");
1852                         worldspec.name += " [new]";
1853                 }
1854                 worldspec.path = game_params.world_path;
1855         }
1856
1857         /* Show the GUI menu
1858          */
1859         if (!skip_main_menu) {
1860                 main_menu(&menudata);
1861
1862                 // Skip further loading if there was an exit signal.
1863                 if (*porting::signal_handler_killstatus())
1864                         return false;
1865
1866                 address = menudata.address;
1867                 int newport = stoi(menudata.port);
1868                 if (newport != 0)
1869                         game_params.socket_port = newport;
1870
1871                 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1872
1873                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1874
1875                 if (menudata.selected_world >= 0
1876                                 && menudata.selected_world < (int)worldspecs.size()) {
1877                         g_settings->set("selected_world_path",
1878                                         worldspecs[menudata.selected_world].path);
1879                         worldspec = worldspecs[menudata.selected_world];
1880                 }
1881         }
1882
1883         if (menudata.errormessage != "") {
1884                 /* The calling function will pass this back into this function upon the
1885                  * next iteration (if any) causing it to be displayed by the GUI
1886                  */
1887                 *error_message = narrow_to_wide(menudata.errormessage);
1888                 return false;
1889         }
1890
1891         if (menudata.name == "")
1892                 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
1893         else
1894                 playername = menudata.name;
1895
1896         password = translatePassword(playername, narrow_to_wide(menudata.password));
1897
1898         g_settings->set("name", playername);
1899
1900         current_playername = playername;
1901         current_password   = password;
1902         current_address    = address;
1903         current_port       = game_params.socket_port;
1904
1905         // If using simple singleplayer mode, override
1906         if (simple_singleplayer_mode) {
1907                 assert(skip_main_menu == false);
1908                 current_playername = "singleplayer";
1909                 current_password = "";
1910                 current_address = "";
1911                 current_port = myrand_range(49152, 65535);
1912         } else if (address != "") {
1913                 ServerListSpec server;
1914                 server["name"] = menudata.servername;
1915                 server["address"] = menudata.address;
1916                 server["port"] = menudata.port;
1917                 server["description"] = menudata.serverdescription;
1918                 ServerList::insert(server);
1919         }
1920
1921         infostream << "Selected world: " << worldspec.name
1922                    << " [" << worldspec.path << "]" << std::endl;
1923
1924         if (current_address == "") { // If local game
1925                 if (worldspec.path == "") {
1926                         *error_message = wgettext("No world selected and no address "
1927                                         "provided. Nothing to do.");
1928                         errorstream << wide_to_narrow(*error_message) << std::endl;
1929                         return false;
1930                 }
1931
1932                 if (!fs::PathExists(worldspec.path)) {
1933                         *error_message = wgettext("Provided world path doesn't exist: ")
1934                                         + narrow_to_wide(worldspec.path);
1935                         errorstream << wide_to_narrow(*error_message) << std::endl;
1936                         return false;
1937                 }
1938
1939                 // Load gamespec for required game
1940                 gamespec = findWorldSubgame(worldspec.path);
1941                 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
1942                         *error_message = wgettext("Could not find or load game \"")
1943                                         + narrow_to_wide(worldspec.gameid) + L"\"";
1944                         errorstream << wide_to_narrow(*error_message) << std::endl;
1945                         return false;
1946                 }
1947
1948                 if (porting::signal_handler_killstatus())
1949                         return true;
1950
1951                 if (game_params.game_spec.isValid() &&
1952                                 game_params.game_spec.id != worldspec.gameid) {
1953                         errorstream << "WARNING: Overriding gamespec from \""
1954                                     << worldspec.gameid << "\" to \""
1955                                     << game_params.game_spec.id << "\"" << std::endl;
1956                         gamespec = game_params.game_spec;
1957                 }
1958
1959                 if (!gamespec.isValid()) {
1960                         *error_message = wgettext("Invalid gamespec.");
1961                         *error_message += L" (world_gameid="
1962                                         + narrow_to_wide(worldspec.gameid) + L")";
1963                         errorstream << wide_to_narrow(*error_message) << std::endl;
1964                         return false;
1965                 }
1966         }
1967
1968         return true;
1969 }
1970
1971 void ClientLauncher::main_menu(MainMenuData *menudata)
1972 {
1973         bool *kill = porting::signal_handler_killstatus();
1974         video::IVideoDriver *driver = device->getVideoDriver();
1975
1976         infostream << "Waiting for other menus" << std::endl;
1977         while (device->run() && *kill == false) {
1978                 if (noMenuActive())
1979                         break;
1980                 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
1981                 guienv->drawAll();
1982                 driver->endScene();
1983                 // On some computers framerate doesn't seem to be automatically limited
1984                 sleep_ms(25);
1985         }
1986         infostream << "Waited for other menus" << std::endl;
1987
1988         // Cursor can be non-visible when coming from the game
1989 #ifndef ANDROID
1990         device->getCursorControl()->setVisible(true);
1991 #endif
1992
1993         /* show main menu */
1994         GUIEngine mymenu(device, guiroot, &g_menumgr, smgr, menudata, *kill);
1995
1996         smgr->clear();  /* leave scene manager in a clean state */
1997 }
1998
1999 bool ClientLauncher::create_engine_device(int log_level)
2000 {
2001         static const irr::ELOG_LEVEL irr_log_level[5] = {
2002                 ELL_NONE,
2003                 ELL_ERROR,
2004                 ELL_WARNING,
2005                 ELL_INFORMATION,
2006 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
2007                 ELL_INFORMATION
2008 #else
2009                 ELL_DEBUG
2010 #endif
2011         };
2012
2013         // Resolution selection
2014         bool fullscreen = g_settings->getBool("fullscreen");
2015         u16 screenW = g_settings->getU16("screenW");
2016         u16 screenH = g_settings->getU16("screenH");
2017
2018         // bpp, fsaa, vsync
2019         bool vsync = g_settings->getBool("vsync");
2020         u16 bits = g_settings->getU16("fullscreen_bpp");
2021         u16 fsaa = g_settings->getU16("fsaa");
2022
2023         // Determine driver
2024         video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
2025         std::string driverstring = g_settings->get("video_driver");
2026         std::vector<video::E_DRIVER_TYPE> drivers
2027                 = porting::getSupportedVideoDrivers();
2028         u32 i;
2029         for (i = 0; i != drivers.size(); i++) {
2030                 if (!strcasecmp(driverstring.c_str(),
2031                         porting::getVideoDriverName(drivers[i]))) {
2032                         driverType = drivers[i];
2033                         break;
2034                 }
2035         }
2036         if (i == drivers.size()) {
2037                 errorstream << "Invalid video_driver specified; "
2038                         "defaulting to opengl" << std::endl;
2039         }
2040
2041         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2042         params.DriverType    = driverType;
2043         params.WindowSize    = core::dimension2d<u32>(screenW, screenH);
2044         params.Bits          = bits;
2045         params.AntiAlias     = fsaa;
2046         params.Fullscreen    = fullscreen;
2047         params.Stencilbuffer = false;
2048         params.Vsync         = vsync;
2049         params.EventReceiver = receiver;
2050         params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2051 #ifdef __ANDROID__
2052         params.PrivateData = porting::app_global;
2053         params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
2054                         "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
2055 #endif
2056
2057         device = createDeviceEx(params);
2058
2059         if (device) {
2060                 // Map our log level to irrlicht engine one.
2061                 ILogger* irr_logger = device->getLogger();
2062                 irr_logger->setLogLevel(irr_log_level[log_level]);
2063
2064                 porting::initIrrlicht(device);
2065         }
2066
2067         return device != NULL;
2068 }
2069
2070 // Misc functions
2071
2072 static bool print_video_modes()
2073 {
2074         IrrlichtDevice *nulldevice;
2075
2076         bool vsync = g_settings->getBool("vsync");
2077         u16 fsaa = g_settings->getU16("fsaa");
2078         MyEventReceiver* receiver = new MyEventReceiver();
2079
2080         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
2081         params.DriverType    = video::EDT_NULL;
2082         params.WindowSize    = core::dimension2d<u32>(640, 480);
2083         params.Bits          = 24;
2084         params.AntiAlias     = fsaa;
2085         params.Fullscreen    = false;
2086         params.Stencilbuffer = false;
2087         params.Vsync         = vsync;
2088         params.EventReceiver = receiver;
2089         params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
2090
2091         nulldevice = createDeviceEx(params);
2092
2093         if (nulldevice == NULL) {
2094                 delete receiver;
2095                 return false;
2096         }
2097
2098         dstream << _("Available video modes (WxHxD):") << std::endl;
2099
2100         video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
2101
2102         if (videomode_list != NULL) {
2103                 s32 videomode_count = videomode_list->getVideoModeCount();
2104                 core::dimension2d<u32> videomode_res;
2105                 s32 videomode_depth;
2106                 for (s32 i = 0; i < videomode_count; ++i) {
2107                         videomode_res = videomode_list->getVideoModeResolution(i);
2108                         videomode_depth = videomode_list->getVideoModeDepth(i);
2109                         dstream << videomode_res.Width << "x" << videomode_res.Height
2110                                 << "x" << videomode_depth << std::endl;
2111                 }
2112
2113                 dstream << _("Active video mode (WxHxD):") << std::endl;
2114                 videomode_res = videomode_list->getDesktopResolution();
2115                 videomode_depth = videomode_list->getDesktopDepth();
2116                 dstream << videomode_res.Width << "x" << videomode_res.Height
2117                         << "x" << videomode_depth << std::endl;
2118
2119         }
2120
2121         nulldevice->drop();
2122         delete receiver;
2123
2124         return videomode_list != NULL;
2125 }
2126
2127 #endif // !SERVER
2128
2129 /*****************************************************************************
2130  * Performance tests
2131  *****************************************************************************/
2132 #ifndef SERVER
2133 static void speed_tests()
2134 {
2135         // volatile to avoid some potential compiler optimisations
2136         volatile static s16 temp16;
2137         volatile static f32 tempf;
2138         static v3f tempv3f1;
2139         static v3f tempv3f2;
2140         static std::string tempstring;
2141         static std::string tempstring2;
2142
2143         tempv3f1 = v3f();
2144         tempv3f2 = v3f();
2145         tempstring = std::string();
2146         tempstring2 = std::string();
2147
2148         {
2149                 infostream << "The following test should take around 20ms." << std::endl;
2150                 TimeTaker timer("Testing std::string speed");
2151                 const u32 jj = 10000;
2152                 for (u32 j = 0; j < jj; j++) {
2153                         tempstring = "";
2154                         tempstring2 = "";
2155                         const u32 ii = 10;
2156                         for (u32 i = 0; i < ii; i++) {
2157                                 tempstring2 += "asd";
2158                         }
2159                         for (u32 i = 0; i < ii+1; i++) {
2160                                 tempstring += "asd";
2161                                 if (tempstring == tempstring2)
2162                                         break;
2163                         }
2164                 }
2165         }
2166
2167         infostream << "All of the following tests should take around 100ms each."
2168                    << std::endl;
2169
2170         {
2171                 TimeTaker timer("Testing floating-point conversion speed");
2172                 tempf = 0.001;
2173                 for (u32 i = 0; i < 4000000; i++) {
2174                         temp16 += tempf;
2175                         tempf += 0.001;
2176                 }
2177         }
2178
2179         {
2180                 TimeTaker timer("Testing floating-point vector speed");
2181
2182                 tempv3f1 = v3f(1, 2, 3);
2183                 tempv3f2 = v3f(4, 5, 6);
2184                 for (u32 i = 0; i < 10000000; i++) {
2185                         tempf += tempv3f1.dotProduct(tempv3f2);
2186                         tempv3f2 += v3f(7, 8, 9);
2187                 }
2188         }
2189
2190         {
2191                 TimeTaker timer("Testing std::map speed");
2192
2193                 std::map<v2s16, f32> map1;
2194                 tempf = -324;
2195                 const s16 ii = 300;
2196                 for (s16 y = 0; y < ii; y++) {
2197                         for (s16 x = 0; x < ii; x++) {
2198                                 map1[v2s16(x, y)] =  tempf;
2199                                 tempf += 1;
2200                         }
2201                 }
2202                 for (s16 y = ii - 1; y >= 0; y--) {
2203                         for (s16 x = 0; x < ii; x++) {
2204                                 tempf = map1[v2s16(x, y)];
2205                         }
2206                 }
2207         }
2208
2209         {
2210                 infostream << "Around 5000/ms should do well here." << std::endl;
2211                 TimeTaker timer("Testing mutex speed");
2212
2213                 JMutex m;
2214                 u32 n = 0;
2215                 u32 i = 0;
2216                 do {
2217                         n += 10000;
2218                         for (; i < n; i++) {
2219                                 m.Lock();
2220                                 m.Unlock();
2221                         }
2222                 }
2223                 // Do at least 10ms
2224                 while(timer.getTimerTime() < 10);
2225
2226                 u32 dtime = timer.stop();
2227                 u32 per_ms = n / dtime;
2228                 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
2229         }
2230 }
2231 #endif