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