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