new auto masterserver
[oweals/minetest.git] / src / main.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 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 "server.h"
54 #include "constants.h"
55 #include "porting.h"
56 #include "gettime.h"
57 #include "guiMessageMenu.h"
58 #include "filesys.h"
59 #include "config.h"
60 #include "guiMainMenu.h"
61 #include "game.h"
62 #include "keycode.h"
63 #include "tile.h"
64 #include "chat.h"
65 #include "defaultsettings.h"
66 #include "gettext.h"
67 #include "settings.h"
68 #include "profiler.h"
69 #include "log.h"
70 #include "mods.h"
71 #if USE_FREETYPE
72 #include "xCGUITTFont.h"
73 #endif
74 #include "util/string.h"
75 #include "subgame.h"
76 #include "quicktune.h"
77 #include "serverlist.h"
78
79 /*
80         Settings.
81         These are loaded from the config file.
82 */
83 Settings main_settings;
84 Settings *g_settings = &main_settings;
85
86 // Global profiler
87 Profiler main_profiler;
88 Profiler *g_profiler = &main_profiler;
89
90 /*
91         Debug streams
92 */
93
94 // Connection
95 std::ostream *dout_con_ptr = &dummyout;
96 std::ostream *derr_con_ptr = &verbosestream;
97
98 // Server
99 std::ostream *dout_server_ptr = &infostream;
100 std::ostream *derr_server_ptr = &errorstream;
101
102 // Client
103 std::ostream *dout_client_ptr = &infostream;
104 std::ostream *derr_client_ptr = &errorstream;
105
106 #ifndef SERVER
107 /*
108         Random stuff
109 */
110
111 /* mainmenumanager.h */
112
113 gui::IGUIEnvironment* guienv = NULL;
114 gui::IGUIStaticText *guiroot = NULL;
115 MainMenuManager g_menumgr;
116
117 bool noMenuActive()
118 {
119         return (g_menumgr.menuCount() == 0);
120 }
121
122 // Passed to menus to allow disconnecting and exiting
123 MainGameCallback *g_gamecallback = NULL;
124 #endif
125
126 /*
127         gettime.h implementation
128 */
129
130 #ifdef SERVER
131
132 u32 getTimeMs()
133 {
134         /* Use imprecise system calls directly (from porting.h) */
135         return porting::getTimeMs();
136 }
137
138 #else
139
140 // A small helper class
141 class TimeGetter
142 {
143 public:
144         virtual u32 getTime() = 0;
145 };
146
147 // A precise irrlicht one
148 class IrrlichtTimeGetter: public TimeGetter
149 {
150 public:
151         IrrlichtTimeGetter(IrrlichtDevice *device):
152                 m_device(device)
153         {}
154         u32 getTime()
155         {
156                 if(m_device == NULL)
157                         return 0;
158                 return m_device->getTimer()->getRealTime();
159         }
160 private:
161         IrrlichtDevice *m_device;
162 };
163 // Not so precise one which works without irrlicht
164 class SimpleTimeGetter: public TimeGetter
165 {
166 public:
167         u32 getTime()
168         {
169                 return porting::getTimeMs();
170         }
171 };
172
173 // A pointer to a global instance of the time getter
174 // TODO: why?
175 TimeGetter *g_timegetter = NULL;
176
177 u32 getTimeMs()
178 {
179         if(g_timegetter == NULL)
180                 return 0;
181         return g_timegetter->getTime();
182 }
183
184 #endif
185
186 class StderrLogOutput: public ILogOutput
187 {
188 public:
189         /* line: Full line with timestamp, level and thread */
190         void printLog(const std::string &line)
191         {
192                 std::cerr<<line<<std::endl;
193         }
194 } main_stderr_log_out;
195
196 class DstreamNoStderrLogOutput: public ILogOutput
197 {
198 public:
199         /* line: Full line with timestamp, level and thread */
200         void printLog(const std::string &line)
201         {
202                 dstream_no_stderr<<line<<std::endl;
203         }
204 } main_dstream_no_stderr_log_out;
205
206 #ifndef SERVER
207
208 /*
209         Event handler for Irrlicht
210
211         NOTE: Everything possible should be moved out from here,
212               probably to InputHandler and the_game
213 */
214
215 class MyEventReceiver : public IEventReceiver
216 {
217 public:
218         // This is the one method that we have to implement
219         virtual bool OnEvent(const SEvent& event)
220         {
221                 /*
222                         React to nothing here if a menu is active
223                 */
224                 if(noMenuActive() == false)
225                 {
226                         return false;
227                 }
228
229                 // Remember whether each key is down or up
230                 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
231                 {
232                         if(event.KeyInput.PressedDown) {
233                                 keyIsDown.set(event.KeyInput);
234                                 keyWasDown.set(event.KeyInput);
235                         } else {
236                                 keyIsDown.unset(event.KeyInput);
237                         }
238                 }
239
240                 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
241                 {
242                         if(noMenuActive() == false)
243                         {
244                                 left_active = false;
245                                 middle_active = false;
246                                 right_active = false;
247                         }
248                         else
249                         {
250                                 left_active = event.MouseInput.isLeftPressed();
251                                 middle_active = event.MouseInput.isMiddlePressed();
252                                 right_active = event.MouseInput.isRightPressed();
253
254                                 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
255                                 {
256                                         leftclicked = true;
257                                 }
258                                 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
259                                 {
260                                         rightclicked = true;
261                                 }
262                                 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
263                                 {
264                                         leftreleased = true;
265                                 }
266                                 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
267                                 {
268                                         rightreleased = true;
269                                 }
270                                 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
271                                 {
272                                         mouse_wheel += event.MouseInput.Wheel;
273                                 }
274                         }
275                 }
276
277                 return false;
278         }
279
280         bool IsKeyDown(const KeyPress &keyCode) const
281         {
282                 return keyIsDown[keyCode];
283         }
284         
285         // Checks whether a key was down and resets the state
286         bool WasKeyDown(const KeyPress &keyCode)
287         {
288                 bool b = keyWasDown[keyCode];
289                 if (b)
290                         keyWasDown.unset(keyCode);
291                 return b;
292         }
293
294         s32 getMouseWheel()
295         {
296                 s32 a = mouse_wheel;
297                 mouse_wheel = 0;
298                 return a;
299         }
300
301         void clearInput()
302         {
303                 keyIsDown.clear();
304                 keyWasDown.clear();
305
306                 leftclicked = false;
307                 rightclicked = false;
308                 leftreleased = false;
309                 rightreleased = false;
310
311                 left_active = false;
312                 middle_active = false;
313                 right_active = false;
314
315                 mouse_wheel = 0;
316         }
317
318         MyEventReceiver()
319         {
320                 clearInput();
321         }
322
323         bool leftclicked;
324         bool rightclicked;
325         bool leftreleased;
326         bool rightreleased;
327
328         bool left_active;
329         bool middle_active;
330         bool right_active;
331
332         s32 mouse_wheel;
333
334 private:
335         IrrlichtDevice *m_device;
336         
337         // The current state of keys
338         KeyList keyIsDown;
339         // Whether a key has been pressed or not
340         KeyList keyWasDown;
341 };
342
343 /*
344         Separated input handler
345 */
346
347 class RealInputHandler : public InputHandler
348 {
349 public:
350         RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
351                 m_device(device),
352                 m_receiver(receiver)
353         {
354         }
355         virtual bool isKeyDown(const KeyPress &keyCode)
356         {
357                 return m_receiver->IsKeyDown(keyCode);
358         }
359         virtual bool wasKeyDown(const KeyPress &keyCode)
360         {
361                 return m_receiver->WasKeyDown(keyCode);
362         }
363         virtual v2s32 getMousePos()
364         {
365                 return m_device->getCursorControl()->getPosition();
366         }
367         virtual void setMousePos(s32 x, s32 y)
368         {
369                 m_device->getCursorControl()->setPosition(x, y);
370         }
371
372         virtual bool getLeftState()
373         {
374                 return m_receiver->left_active;
375         }
376         virtual bool getRightState()
377         {
378                 return m_receiver->right_active;
379         }
380         
381         virtual bool getLeftClicked()
382         {
383                 return m_receiver->leftclicked;
384         }
385         virtual bool getRightClicked()
386         {
387                 return m_receiver->rightclicked;
388         }
389         virtual void resetLeftClicked()
390         {
391                 m_receiver->leftclicked = false;
392         }
393         virtual void resetRightClicked()
394         {
395                 m_receiver->rightclicked = false;
396         }
397
398         virtual bool getLeftReleased()
399         {
400                 return m_receiver->leftreleased;
401         }
402         virtual bool getRightReleased()
403         {
404                 return m_receiver->rightreleased;
405         }
406         virtual void resetLeftReleased()
407         {
408                 m_receiver->leftreleased = false;
409         }
410         virtual void resetRightReleased()
411         {
412                 m_receiver->rightreleased = false;
413         }
414
415         virtual s32 getMouseWheel()
416         {
417                 return m_receiver->getMouseWheel();
418         }
419
420         void clear()
421         {
422                 m_receiver->clearInput();
423         }
424 private:
425         IrrlichtDevice *m_device;
426         MyEventReceiver *m_receiver;
427 };
428
429 class RandomInputHandler : public InputHandler
430 {
431 public:
432         RandomInputHandler()
433         {
434                 leftdown = false;
435                 rightdown = false;
436                 leftclicked = false;
437                 rightclicked = false;
438                 leftreleased = false;
439                 rightreleased = false;
440                 keydown.clear();
441         }
442         virtual bool isKeyDown(const KeyPress &keyCode)
443         {
444                 return keydown[keyCode];
445         }
446         virtual bool wasKeyDown(const KeyPress &keyCode)
447         {
448                 return false;
449         }
450         virtual v2s32 getMousePos()
451         {
452                 return mousepos;
453         }
454         virtual void setMousePos(s32 x, s32 y)
455         {
456                 mousepos = v2s32(x,y);
457         }
458
459         virtual bool getLeftState()
460         {
461                 return leftdown;
462         }
463         virtual bool getRightState()
464         {
465                 return rightdown;
466         }
467
468         virtual bool getLeftClicked()
469         {
470                 return leftclicked;
471         }
472         virtual bool getRightClicked()
473         {
474                 return rightclicked;
475         }
476         virtual void resetLeftClicked()
477         {
478                 leftclicked = false;
479         }
480         virtual void resetRightClicked()
481         {
482                 rightclicked = false;
483         }
484
485         virtual bool getLeftReleased()
486         {
487                 return leftreleased;
488         }
489         virtual bool getRightReleased()
490         {
491                 return rightreleased;
492         }
493         virtual void resetLeftReleased()
494         {
495                 leftreleased = false;
496         }
497         virtual void resetRightReleased()
498         {
499                 rightreleased = false;
500         }
501
502         virtual s32 getMouseWheel()
503         {
504                 return 0;
505         }
506
507         virtual void step(float dtime)
508         {
509                 {
510                         static float counter1 = 0;
511                         counter1 -= dtime;
512                         if(counter1 < 0.0)
513                         {
514                                 counter1 = 0.1*Rand(1, 40);
515                                 keydown.toggle(getKeySetting("keymap_jump"));
516                         }
517                 }
518                 {
519                         static float counter1 = 0;
520                         counter1 -= dtime;
521                         if(counter1 < 0.0)
522                         {
523                                 counter1 = 0.1*Rand(1, 40);
524                                 keydown.toggle(getKeySetting("keymap_special1"));
525                         }
526                 }
527                 {
528                         static float counter1 = 0;
529                         counter1 -= dtime;
530                         if(counter1 < 0.0)
531                         {
532                                 counter1 = 0.1*Rand(1, 40);
533                                 keydown.toggle(getKeySetting("keymap_forward"));
534                         }
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_left"));
543                         }
544                 }
545                 {
546                         static float counter1 = 0;
547                         counter1 -= dtime;
548                         if(counter1 < 0.0)
549                         {
550                                 counter1 = 0.1*Rand(1, 20);
551                                 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
552                         }
553                 }
554                 {
555                         static float counter1 = 0;
556                         counter1 -= dtime;
557                         if(counter1 < 0.0)
558                         {
559                                 counter1 = 0.1*Rand(1, 30);
560                                 leftdown = !leftdown;
561                                 if(leftdown)
562                                         leftclicked = true;
563                                 if(!leftdown)
564                                         leftreleased = true;
565                         }
566                 }
567                 {
568                         static float counter1 = 0;
569                         counter1 -= dtime;
570                         if(counter1 < 0.0)
571                         {
572                                 counter1 = 0.1*Rand(1, 15);
573                                 rightdown = !rightdown;
574                                 if(rightdown)
575                                         rightclicked = true;
576                                 if(!rightdown)
577                                         rightreleased = true;
578                         }
579                 }
580                 mousepos += mousespeed;
581         }
582
583         s32 Rand(s32 min, s32 max)
584         {
585                 return (myrand()%(max-min+1))+min;
586         }
587 private:
588         KeyList keydown;
589         v2s32 mousepos;
590         v2s32 mousespeed;
591         bool leftdown;
592         bool rightdown;
593         bool leftclicked;
594         bool rightclicked;
595         bool leftreleased;
596         bool rightreleased;
597 };
598
599 void drawMenuBackground(video::IVideoDriver* driver)
600 {
601         core::dimension2d<u32> screensize = driver->getScreenSize();
602                 
603         video::ITexture *bgtexture =
604                         driver->getTexture(getTexturePath("menubg.png").c_str());
605         if(bgtexture)
606         {
607                 s32 scaledsize = 128;
608                 
609                 // The important difference between destsize and screensize is
610                 // that destsize is rounded to whole scaled pixels.
611                 // These formulas use component-wise multiplication and division of v2u32.
612                 v2u32 texturesize = bgtexture->getSize();
613                 v2u32 sourcesize = texturesize * screensize / scaledsize + v2u32(1,1);
614                 v2u32 destsize = scaledsize * sourcesize / texturesize;
615                 
616                 // Default texture wrapping mode in Irrlicht is ETC_REPEAT.
617                 driver->draw2DImage(bgtexture,
618                         core::rect<s32>(0, 0, destsize.X, destsize.Y),
619                         core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y),
620                         NULL, NULL, true);
621         }
622         
623         video::ITexture *logotexture =
624                         driver->getTexture(getTexturePath("menulogo.png").c_str());
625         if(logotexture)
626         {
627                 v2s32 logosize(logotexture->getOriginalSize().Width,
628                                 logotexture->getOriginalSize().Height);
629                 logosize *= 4;
630
631                 video::SColor bgcolor(255,50,50,50);
632                 core::rect<s32> bgrect(0, screensize.Height-logosize.Y-20,
633                                 screensize.Width, screensize.Height);
634                 driver->draw2DRectangle(bgcolor, bgrect, NULL);
635
636                 core::rect<s32> rect(0,0,logosize.X,logosize.Y);
637                 rect += v2s32(screensize.Width/2,screensize.Height-10-logosize.Y);
638                 rect -= v2s32(logosize.X/2, 0);
639                 driver->draw2DImage(logotexture, rect,
640                         core::rect<s32>(core::position2d<s32>(0,0),
641                         core::dimension2di(logotexture->getSize())),
642                         NULL, NULL, true);
643         }
644 }
645
646 #endif
647
648 // These are defined global so that they're not optimized too much.
649 // Can't change them to volatile.
650 s16 temp16;
651 f32 tempf;
652 v3f tempv3f1;
653 v3f tempv3f2;
654 std::string tempstring;
655 std::string tempstring2;
656
657 void SpeedTests()
658 {
659         {
660                 infostream<<"The following test should take around 20ms."<<std::endl;
661                 TimeTaker timer("Testing std::string speed");
662                 const u32 jj = 10000;
663                 for(u32 j=0; j<jj; j++)
664                 {
665                         tempstring = "";
666                         tempstring2 = "";
667                         const u32 ii = 10;
668                         for(u32 i=0; i<ii; i++){
669                                 tempstring2 += "asd";
670                         }
671                         for(u32 i=0; i<ii+1; i++){
672                                 tempstring += "asd";
673                                 if(tempstring == tempstring2)
674                                         break;
675                         }
676                 }
677         }
678         
679         infostream<<"All of the following tests should take around 100ms each."
680                         <<std::endl;
681
682         {
683                 TimeTaker timer("Testing floating-point conversion speed");
684                 tempf = 0.001;
685                 for(u32 i=0; i<4000000; i++){
686                         temp16 += tempf;
687                         tempf += 0.001;
688                 }
689         }
690         
691         {
692                 TimeTaker timer("Testing floating-point vector speed");
693
694                 tempv3f1 = v3f(1,2,3);
695                 tempv3f2 = v3f(4,5,6);
696                 for(u32 i=0; i<10000000; i++){
697                         tempf += tempv3f1.dotProduct(tempv3f2);
698                         tempv3f2 += v3f(7,8,9);
699                 }
700         }
701
702         {
703                 TimeTaker timer("Testing core::map speed");
704                 
705                 core::map<v2s16, f32> map1;
706                 tempf = -324;
707                 const s16 ii=300;
708                 for(s16 y=0; y<ii; y++){
709                         for(s16 x=0; x<ii; x++){
710                                 map1.insert(v2s16(x,y), tempf);
711                                 tempf += 1;
712                         }
713                 }
714                 for(s16 y=ii-1; y>=0; y--){
715                         for(s16 x=0; x<ii; x++){
716                                 tempf = map1[v2s16(x,y)];
717                         }
718                 }
719         }
720
721         {
722                 infostream<<"Around 5000/ms should do well here."<<std::endl;
723                 TimeTaker timer("Testing mutex speed");
724                 
725                 JMutex m;
726                 m.Init();
727                 u32 n = 0;
728                 u32 i = 0;
729                 do{
730                         n += 10000;
731                         for(; i<n; i++){
732                                 m.Lock();
733                                 m.Unlock();
734                         }
735                 }
736                 // Do at least 10ms
737                 while(timer.getTime() < 10);
738
739                 u32 dtime = timer.stop();
740                 u32 per_ms = n / dtime;
741                 infostream<<"Done. "<<dtime<<"ms, "
742                                 <<per_ms<<"/ms"<<std::endl;
743         }
744 }
745
746 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
747                 std::ostream &os)
748 {
749         for(u32 i=0; i<worldspecs.size(); i++){
750                 std::string name = worldspecs[i].name;
751                 std::string path = worldspecs[i].path;
752                 if(name.find(" ") != std::string::npos)
753                         name = std::string("'") + name + "'";
754                 path = std::string("'") + path + "'";
755                 name = padStringRight(name, 14);
756                 os<<"  "<<name<<" "<<path<<std::endl;
757         }
758 }
759
760 int main(int argc, char *argv[])
761 {
762         int retval = 0;
763
764         /*
765                 Initialization
766         */
767
768         log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
769         log_add_output_all_levs(&main_dstream_no_stderr_log_out);
770
771         log_register_thread("main");
772
773         // This enables internatonal characters input
774         if( setlocale(LC_ALL, "") == NULL )
775         {
776                 fprintf( stderr, "%s: warning: could not set default locale\n", argv[0] );
777         }
778
779         // Set locale. This is for forcing '.' as the decimal point.
780         try {
781                 std::locale::global(std::locale(std::locale(""), "C", std::locale::numeric));
782                 setlocale(LC_NUMERIC, "C");
783         } catch (const std::exception& ex) {
784                 errorstream<<"Could not set numeric locale to C"<<std::endl;
785         }
786         /*
787                 Parse command line
788         */
789         
790         // List all allowed options
791         core::map<std::string, ValueSpec> allowed_options;
792         allowed_options.insert("help", ValueSpec(VALUETYPE_FLAG,
793                         _("Show allowed options")));
794         allowed_options.insert("config", ValueSpec(VALUETYPE_STRING,
795                         _("Load configuration from specified file")));
796         allowed_options.insert("port", ValueSpec(VALUETYPE_STRING,
797                         _("Set network port (UDP)")));
798         allowed_options.insert("disable-unittests", ValueSpec(VALUETYPE_FLAG,
799                         _("Disable unit tests")));
800         allowed_options.insert("enable-unittests", ValueSpec(VALUETYPE_FLAG,
801                         _("Enable unit tests")));
802         allowed_options.insert("map-dir", ValueSpec(VALUETYPE_STRING,
803                         _("Same as --world (deprecated)")));
804         allowed_options.insert("world", ValueSpec(VALUETYPE_STRING,
805                         _("Set world path (implies local game) ('list' lists all)")));
806         allowed_options.insert("worldname", ValueSpec(VALUETYPE_STRING,
807                         _("Set world by name (implies local game)")));
808         allowed_options.insert("info", ValueSpec(VALUETYPE_FLAG,
809                         _("Print more information to console")));
810         allowed_options.insert("verbose", ValueSpec(VALUETYPE_FLAG,
811                         _("Print even more information to console")));
812         allowed_options.insert("trace", ValueSpec(VALUETYPE_FLAG,
813                         _("Print enormous amounts of information to log and console")));
814         allowed_options.insert("logfile", ValueSpec(VALUETYPE_STRING,
815                         _("Set logfile path ('' = no logging)")));
816         allowed_options.insert("gameid", ValueSpec(VALUETYPE_STRING,
817                         _("Set gameid (\"--gameid list\" prints available ones)")));
818 #ifndef SERVER
819         allowed_options.insert("speedtests", ValueSpec(VALUETYPE_FLAG,
820                         _("Run speed tests")));
821         allowed_options.insert("address", ValueSpec(VALUETYPE_STRING,
822                         _("Address to connect to. ('' = local game)")));
823         allowed_options.insert("random-input", ValueSpec(VALUETYPE_FLAG,
824                         _("Enable random user input, for testing")));
825         allowed_options.insert("server", ValueSpec(VALUETYPE_FLAG,
826                         _("Run dedicated server")));
827         allowed_options.insert("name", ValueSpec(VALUETYPE_STRING,
828                         _("Set player name")));
829         allowed_options.insert("password", ValueSpec(VALUETYPE_STRING,
830                         _("Set password")));
831         allowed_options.insert("go", ValueSpec(VALUETYPE_FLAG,
832                         _("Disable main menu")));
833 #endif
834
835         Settings cmd_args;
836         
837         bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
838
839         if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1"))
840         {
841                 dstream<<_("Allowed options:")<<std::endl;
842                 for(core::map<std::string, ValueSpec>::Iterator
843                                 i = allowed_options.getIterator();
844                                 i.atEnd() == false; i++)
845                 {
846                         std::ostringstream os1(std::ios::binary);
847                         os1<<"  --"<<i.getNode()->getKey();
848                         if(i.getNode()->getValue().type == VALUETYPE_FLAG)
849                                 {}
850                         else
851                                 os1<<_(" <value>");
852                         dstream<<padStringRight(os1.str(), 24);
853
854                         if(i.getNode()->getValue().help != NULL)
855                                 dstream<<i.getNode()->getValue().help;
856                         dstream<<std::endl;
857                 }
858
859                 return cmd_args.getFlag("help") ? 0 : 1;
860         }
861         
862         /*
863                 Low-level initialization
864         */
865         
866         // If trace is enabled, enable logging of certain things
867         if(cmd_args.getFlag("trace")){
868                 dstream<<_("Enabling trace level debug output")<<std::endl;
869                 log_trace_level_enabled = true;
870                 dout_con_ptr = &verbosestream; // this is somewhat old crap
871                 socket_enable_debug_output = true; // socket doesn't use log.h
872         }
873         // In certain cases, output info level on stderr
874         if(cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
875                         cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
876                 log_add_output(&main_stderr_log_out, LMT_INFO);
877         // In certain cases, output verbose level on stderr
878         if(cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
879                 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
880
881         porting::signal_handler_init();
882         bool &kill = *porting::signal_handler_killstatus();
883         
884         porting::initializePaths();
885
886         // Create user data directory
887         fs::CreateDir(porting::path_user);
888
889         init_gettext((porting::path_share + DIR_DELIM + "locale").c_str());
890         
891         // Initialize debug streams
892 #define DEBUGFILE "debug.txt"
893 #if RUN_IN_PLACE
894         std::string logfile = DEBUGFILE;
895 #else
896         std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE;
897 #endif
898         if(cmd_args.exists("logfile"))
899                 logfile = cmd_args.get("logfile");
900         if(logfile != "")
901                 debugstreams_init(false, logfile.c_str());
902         else
903                 debugstreams_init(false, NULL);
904
905         infostream<<"logfile    = "<<logfile<<std::endl;
906         infostream<<"path_share = "<<porting::path_share<<std::endl;
907         infostream<<"path_user  = "<<porting::path_user<<std::endl;
908
909         // Initialize debug stacks
910         debug_stacks_init();
911         DSTACK(__FUNCTION_NAME);
912
913         // Debug handler
914         BEGIN_DEBUG_EXCEPTION_HANDLER
915         
916         // List gameids if requested
917         if(cmd_args.exists("gameid") && cmd_args.get("gameid") == "list")
918         {
919                 std::set<std::string> gameids = getAvailableGameIds();
920                 for(std::set<std::string>::const_iterator i = gameids.begin();
921                                 i != gameids.end(); i++)
922                         dstream<<(*i)<<std::endl;
923                 return 0;
924         }
925         
926         // List worlds if requested
927         if(cmd_args.exists("world") && cmd_args.get("world") == "list"){
928                 dstream<<_("Available worlds:")<<std::endl;
929                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
930                 print_worldspecs(worldspecs, dstream);
931                 return 0;
932         }
933         
934         // Print startup message
935         infostream<<PROJECT_NAME<<
936                         " "<<_("with")<<" SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
937                         <<", "<<BUILD_INFO
938                         <<std::endl;
939         
940         /*
941                 Basic initialization
942         */
943
944         // Initialize default settings
945         set_default_settings(g_settings);
946         
947         // Initialize sockets
948         sockets_init();
949         atexit(sockets_cleanup);
950         
951         /*
952                 Read config file
953         */
954         
955         // Path of configuration file in use
956         std::string configpath = "";
957         
958         if(cmd_args.exists("config"))
959         {
960                 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
961                 if(r == false)
962                 {
963                         errorstream<<"Could not read configuration from \""
964                                         <<cmd_args.get("config")<<"\""<<std::endl;
965                         return 1;
966                 }
967                 configpath = cmd_args.get("config");
968         }
969         else
970         {
971                 core::array<std::string> filenames;
972                 filenames.push_back(porting::path_user +
973                                 DIR_DELIM + "minetest.conf");
974                 // Legacy configuration file location
975                 filenames.push_back(porting::path_user +
976                                 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
977 #if RUN_IN_PLACE
978                 // Try also from a lower level (to aid having the same configuration
979                 // for many RUN_IN_PLACE installs)
980                 filenames.push_back(porting::path_user +
981                                 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
982 #endif
983
984                 for(u32 i=0; i<filenames.size(); i++)
985                 {
986                         bool r = g_settings->readConfigFile(filenames[i].c_str());
987                         if(r)
988                         {
989                                 configpath = filenames[i];
990                                 break;
991                         }
992                 }
993                 
994                 // If no path found, use the first one (menu creates the file)
995                 if(configpath == "")
996                         configpath = filenames[0];
997         }
998
999         // Initialize random seed
1000         srand(time(0));
1001         mysrand(time(0));
1002
1003         /*
1004                 Run unit tests
1005         */
1006
1007         if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
1008                         || cmd_args.getFlag("enable-unittests") == true)
1009         {
1010                 run_tests();
1011         }
1012         
1013         /*
1014                 Game parameters
1015         */
1016
1017         // Port
1018         u16 port = 30000;
1019         if(cmd_args.exists("port"))
1020                 port = cmd_args.getU16("port");
1021         else if(g_settings->exists("port"))
1022                 port = g_settings->getU16("port");
1023         if(port == 0)
1024                 port = 30000;
1025         
1026         // World directory
1027         std::string commanded_world = "";
1028         if(cmd_args.exists("world"))
1029                 commanded_world = cmd_args.get("world");
1030         else if(cmd_args.exists("map-dir"))
1031                 commanded_world = cmd_args.get("map-dir");
1032         else if(cmd_args.exists("nonopt0")) // First nameless argument
1033                 commanded_world = cmd_args.get("nonopt0");
1034         else if(g_settings->exists("map-dir"))
1035                 commanded_world = g_settings->get("map-dir");
1036         
1037         // World name
1038         std::string commanded_worldname = "";
1039         if(cmd_args.exists("worldname"))
1040                 commanded_worldname = cmd_args.get("worldname");
1041         
1042         // Strip world.mt from commanded_world
1043         {
1044                 std::string worldmt = "world.mt";
1045                 if(commanded_world.size() > worldmt.size() &&
1046                                 commanded_world.substr(commanded_world.size()-worldmt.size())
1047                                 == worldmt){
1048                         dstream<<_("Supplied world.mt file - stripping it off.")<<std::endl;
1049                         commanded_world = commanded_world.substr(
1050                                         0, commanded_world.size()-worldmt.size());
1051                 }
1052         }
1053         
1054         // If a world name was specified, convert it to a path
1055         if(commanded_worldname != ""){
1056                 // Get information about available worlds
1057                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1058                 bool found = false;
1059                 for(u32 i=0; i<worldspecs.size(); i++){
1060                         std::string name = worldspecs[i].name;
1061                         if(name == commanded_worldname){
1062                                 if(commanded_world != ""){
1063                                         dstream<<_("--worldname takes precedence over previously "
1064                                                         "selected world.")<<std::endl;
1065                                 }
1066                                 commanded_world = worldspecs[i].path;
1067                                 found = true;
1068                                 break;
1069                         }
1070                 }
1071                 if(!found){
1072                         dstream<<_("World")<<" '"<<commanded_worldname<<_("' not "
1073                                         "available. Available worlds:")<<std::endl;
1074                         print_worldspecs(worldspecs, dstream);
1075                         return 1;
1076                 }
1077         }
1078
1079         // Gamespec
1080         SubgameSpec commanded_gamespec;
1081         if(cmd_args.exists("gameid")){
1082                 std::string gameid = cmd_args.get("gameid");
1083                 commanded_gamespec = findSubgame(gameid);
1084                 if(!commanded_gamespec.isValid()){
1085                         errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl;
1086                         return 1;
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                 // Create server
1211                 Server server(world_path, configpath, gamespec, false);
1212                 server.start(port);
1213                 
1214                 // Run server
1215                 dedicated_server_loop(server, kill);
1216
1217                 return 0;
1218         }
1219
1220 #ifndef SERVER // Exclude from dedicated server build
1221
1222         /*
1223                 More parameters
1224         */
1225         
1226         std::string address = g_settings->get("address");
1227         if(commanded_world != "")
1228                 address = "";
1229         else if(cmd_args.exists("address"))
1230                 address = cmd_args.get("address");
1231         
1232         std::string playername = g_settings->get("name");
1233         if(cmd_args.exists("name"))
1234                 playername = cmd_args.get("name");
1235         
1236         bool skip_main_menu = cmd_args.getFlag("go");
1237
1238         /*
1239                 Device initialization
1240         */
1241
1242         // Resolution selection
1243         
1244         bool fullscreen = g_settings->getBool("fullscreen");
1245         u16 screenW = g_settings->getU16("screenW");
1246         u16 screenH = g_settings->getU16("screenH");
1247
1248         // bpp, fsaa, vsync
1249
1250         bool vsync = g_settings->getBool("vsync");
1251         u16 bits = g_settings->getU16("fullscreen_bpp");
1252         u16 fsaa = g_settings->getU16("fsaa");
1253
1254         // Determine driver
1255
1256         video::E_DRIVER_TYPE driverType;
1257         
1258         std::string driverstring = g_settings->get("video_driver");
1259
1260         if(driverstring == "null")
1261                 driverType = video::EDT_NULL;
1262         else if(driverstring == "software")
1263                 driverType = video::EDT_SOFTWARE;
1264         else if(driverstring == "burningsvideo")
1265                 driverType = video::EDT_BURNINGSVIDEO;
1266         else if(driverstring == "direct3d8")
1267                 driverType = video::EDT_DIRECT3D8;
1268         else if(driverstring == "direct3d9")
1269                 driverType = video::EDT_DIRECT3D9;
1270         else if(driverstring == "opengl")
1271                 driverType = video::EDT_OPENGL;
1272         else
1273         {
1274                 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1275                                 "to opengl"<<std::endl;
1276                 driverType = video::EDT_OPENGL;
1277         }
1278
1279         /*
1280                 Create device and exit if creation failed
1281         */
1282
1283         MyEventReceiver receiver;
1284
1285         IrrlichtDevice *device;
1286
1287         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1288         params.DriverType    = driverType;
1289         params.WindowSize    = core::dimension2d<u32>(screenW, screenH);
1290         params.Bits          = bits;
1291         params.AntiAlias     = fsaa;
1292         params.Fullscreen    = fullscreen;
1293         params.Stencilbuffer = false;
1294         params.Vsync         = vsync;
1295         params.EventReceiver = &receiver;
1296
1297         device = createDeviceEx(params);
1298
1299         if (device == 0)
1300                 return 1; // could not create selected driver.
1301         
1302         /*
1303                 Continue initialization
1304         */
1305
1306         video::IVideoDriver* driver = device->getVideoDriver();
1307
1308         /*
1309                 This changes the minimum allowed number of vertices in a VBO.
1310                 Default is 500.
1311         */
1312         //driver->setMinHardwareBufferVertexCount(50);
1313
1314         // Create time getter
1315         g_timegetter = new IrrlichtTimeGetter(device);
1316         
1317         // Create game callback for menus
1318         g_gamecallback = new MainGameCallback(device);
1319         
1320         /*
1321                 Speed tests (done after irrlicht is loaded to get timer)
1322         */
1323         if(cmd_args.getFlag("speedtests"))
1324         {
1325                 dstream<<"Running speed tests"<<std::endl;
1326                 SpeedTests();
1327                 return 0;
1328         }
1329         
1330         device->setResizable(true);
1331
1332         bool random_input = g_settings->getBool("random_input")
1333                         || cmd_args.getFlag("random-input");
1334         InputHandler *input = NULL;
1335         if(random_input)
1336                 input = new RandomInputHandler();
1337         else
1338                 input = new RealInputHandler(device, &receiver);
1339         
1340         scene::ISceneManager* smgr = device->getSceneManager();
1341
1342         guienv = device->getGUIEnvironment();
1343         gui::IGUISkin* skin = guienv->getSkin();
1344         #if USE_FREETYPE
1345         std::string font_path = g_settings->get("font_path");
1346         u16 font_size = g_settings->getU16("font_size");
1347         gui::IGUIFont *font = gui::CGUITTFont::createTTFont(guienv, font_path.c_str(), font_size);
1348         #else
1349         gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
1350         #endif
1351         if(font)
1352                 skin->setFont(font);
1353         else
1354                 errorstream<<"WARNING: Font file was not found."
1355                                 " Using default font."<<std::endl;
1356         // If font was not found, this will get us one
1357         font = skin->getFont();
1358         assert(font);
1359         
1360         u32 text_height = font->getDimension(L"Hello, world!").Height;
1361         infostream<<"text_height="<<text_height<<std::endl;
1362
1363         //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1364         skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1365         //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1366         //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1367         skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1368         skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1369         skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50));
1370         skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255));
1371
1372 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1373         // Irrlicht 1.8 input colours
1374         skin->setColor(gui::EGDC_EDITABLE, video::SColor(255,128,128,128));
1375         skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255,96,134,49));
1376 #endif
1377
1378         /*
1379                 GUI stuff
1380         */
1381
1382         ChatBackend chat_backend;
1383
1384         /*
1385                 If an error occurs, this is set to something and the
1386                 menu-game loop is restarted. It is then displayed before
1387                 the menu.
1388         */
1389         std::wstring error_message = L"";
1390
1391         // The password entered during the menu screen,
1392         std::string password;
1393
1394         bool first_loop = true;
1395
1396         /*
1397                 Menu-game loop
1398         */
1399         while(device->run() && kill == false)
1400         {
1401                 // Set the window caption
1402                 device->setWindowCaption((std::wstring(L"Minetest [")+wgettext("Main Menu")+L"]").c_str());
1403
1404                 // This is used for catching disconnects
1405                 try
1406                 {
1407
1408                         /*
1409                                 Clear everything from the GUIEnvironment
1410                         */
1411                         guienv->clear();
1412                         
1413                         /*
1414                                 We need some kind of a root node to be able to add
1415                                 custom gui elements directly on the screen.
1416                                 Otherwise they won't be automatically drawn.
1417                         */
1418                         guiroot = guienv->addStaticText(L"",
1419                                         core::rect<s32>(0, 0, 10000, 10000));
1420                         
1421                         SubgameSpec gamespec;
1422                         WorldSpec worldspec;
1423                         bool simple_singleplayer_mode = false;
1424
1425                         // These are set up based on the menu and other things
1426                         std::string current_playername = "inv£lid";
1427                         std::string current_password = "";
1428                         std::string current_address = "does-not-exist";
1429                         int current_port = 0;
1430
1431                         /*
1432                                 Out-of-game menu loop.
1433
1434                                 Loop quits when menu returns proper parameters.
1435                         */
1436                         while(kill == false)
1437                         {
1438                                 // If skip_main_menu, only go through here once
1439                                 if(skip_main_menu && !first_loop){
1440                                         kill = true;
1441                                         break;
1442                                 }
1443                                 first_loop = false;
1444                                 
1445                                 // Cursor can be non-visible when coming from the game
1446                                 device->getCursorControl()->setVisible(true);
1447                                 // Some stuff are left to scene manager when coming from the game
1448                                 // (map at least?)
1449                                 smgr->clear();
1450                                 
1451                                 // Initialize menu data
1452                                 MainMenuData menudata;
1453                                 if(g_settings->exists("selected_mainmenu_tab"))
1454                                         menudata.selected_tab = g_settings->getS32("selected_mainmenu_tab");
1455                                 menudata.address = narrow_to_wide(address);
1456                                 menudata.name = narrow_to_wide(playername);
1457                                 menudata.port = narrow_to_wide(itos(port));
1458                                 if(cmd_args.exists("password"))
1459                                         menudata.password = narrow_to_wide(cmd_args.get("password"));
1460                                 menudata.fancy_trees = g_settings->getBool("new_style_leaves");
1461                                 menudata.smooth_lighting = g_settings->getBool("smooth_lighting");
1462                                 menudata.clouds_3d = g_settings->getBool("enable_3d_clouds");
1463                                 menudata.opaque_water = g_settings->getBool("opaque_water");
1464                                 menudata.mip_map = g_settings->getBool("mip_map");
1465                                 menudata.anisotropic_filter = g_settings->getBool("anisotropic_filter");
1466                                 menudata.bilinear_filter = g_settings->getBool("bilinear_filter");
1467                                 menudata.trilinear_filter = g_settings->getBool("trilinear_filter");
1468                                 menudata.enable_shaders = g_settings->getS32("enable_shaders");
1469                                 menudata.preload_item_visuals = g_settings->getBool("preload_item_visuals");
1470                                 menudata.enable_particles = g_settings->getBool("enable_particles");
1471                                 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, menudata.mip_map);
1472                                 menudata.creative_mode = g_settings->getBool("creative_mode");
1473                                 menudata.enable_damage = g_settings->getBool("enable_damage");
1474                                 // Default to selecting nothing
1475                                 menudata.selected_world = -1;
1476                                 // Get world listing for the menu
1477                                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1478                                 // If there is only one world, select it
1479                                 if(worldspecs.size() == 1){
1480                                         menudata.selected_world = 0;
1481                                 }
1482                                 // Otherwise try to select according to selected_world_path
1483                                 else if(g_settings->exists("selected_world_path")){
1484                                         std::string trypath = g_settings->get("selected_world_path");
1485                                         for(u32 i=0; i<worldspecs.size(); i++){
1486                                                 if(worldspecs[i].path == trypath){
1487                                                         menudata.selected_world = i;
1488                                                         break;
1489                                                 }
1490                                         }
1491                                 }
1492                                 // If a world was commanded, append and select it
1493                                 if(commanded_world != ""){
1494                                         std::string gameid = getWorldGameId(commanded_world, true);
1495                                         std::string name = _("[--world parameter]");
1496                                         if(gameid == ""){
1497                                                 gameid = g_settings->get("default_game");
1498                                                 name += " [new]";
1499                                         }
1500                                         WorldSpec spec(commanded_world, name, gameid);
1501                                         worldspecs.push_back(spec);
1502                                         menudata.selected_world = worldspecs.size()-1;
1503                                 }
1504                                 // Copy worldspecs to menu
1505                                 menudata.worlds = worldspecs;
1506
1507                                 if(skip_main_menu == false)
1508                                 {
1509                                         video::IVideoDriver* driver = device->getVideoDriver();
1510                                         
1511                                         infostream<<"Waiting for other menus"<<std::endl;
1512                                         while(device->run() && kill == false)
1513                                         {
1514                                                 if(noMenuActive())
1515                                                         break;
1516                                                 driver->beginScene(true, true,
1517                                                                 video::SColor(255,128,128,128));
1518                                                 drawMenuBackground(driver);
1519                                                 guienv->drawAll();
1520                                                 driver->endScene();
1521                                                 // On some computers framerate doesn't seem to be
1522                                                 // automatically limited
1523                                                 sleep_ms(25);
1524                                         }
1525                                         infostream<<"Waited for other menus"<<std::endl;
1526
1527                                         GUIMainMenu *menu =
1528                                                         new GUIMainMenu(guienv, guiroot, -1, 
1529                                                                 &g_menumgr, &menudata, g_gamecallback);
1530                                         menu->allowFocusRemoval(true);
1531
1532                                         if(error_message != L"")
1533                                         {
1534                                                 verbosestream<<"error_message = "
1535                                                                 <<wide_to_narrow(error_message)<<std::endl;
1536
1537                                                 GUIMessageMenu *menu2 =
1538                                                                 new GUIMessageMenu(guienv, guiroot, -1, 
1539                                                                         &g_menumgr, error_message.c_str());
1540                                                 menu2->drop();
1541                                                 error_message = L"";
1542                                         }
1543
1544                                         infostream<<"Created main menu"<<std::endl;
1545
1546                                         while(device->run() && kill == false)
1547                                         {
1548                                                 if(menu->getStatus() == true)
1549                                                         break;
1550
1551                                                 //driver->beginScene(true, true, video::SColor(255,0,0,0));
1552                                                 driver->beginScene(true, true, video::SColor(255,128,128,128));
1553
1554                                                 drawMenuBackground(driver);
1555
1556                                                 guienv->drawAll();
1557                                                 
1558                                                 driver->endScene();
1559                                                 
1560                                                 // On some computers framerate doesn't seem to be
1561                                                 // automatically limited
1562                                                 sleep_ms(25);
1563                                         }
1564                                         
1565                                         infostream<<"Dropping main menu"<<std::endl;
1566
1567                                         menu->drop();
1568                                 }
1569
1570                                 playername = wide_to_narrow(menudata.name);
1571                                 password = translatePassword(playername, menudata.password);
1572                                 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1573
1574                                 address = wide_to_narrow(menudata.address);
1575                                 int newport = stoi(wide_to_narrow(menudata.port));
1576                                 if(newport != 0)
1577                                         port = newport;
1578                                 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1579                                 // Save settings
1580                                 g_settings->setS32("selected_mainmenu_tab", menudata.selected_tab);
1581                                 g_settings->set("new_style_leaves", itos(menudata.fancy_trees));
1582                                 g_settings->set("smooth_lighting", itos(menudata.smooth_lighting));
1583                                 g_settings->set("enable_3d_clouds", itos(menudata.clouds_3d));
1584                                 g_settings->set("opaque_water", itos(menudata.opaque_water));
1585
1586                                 g_settings->set("mip_map", itos(menudata.mip_map));
1587                                 g_settings->set("anisotropic_filter", itos(menudata.anisotropic_filter));
1588                                 g_settings->set("bilinear_filter", itos(menudata.bilinear_filter));
1589                                 g_settings->set("trilinear_filter", itos(menudata.trilinear_filter));
1590
1591                                 g_settings->setS32("enable_shaders", menudata.enable_shaders);
1592                                 g_settings->set("preload_item_visuals", itos(menudata.preload_item_visuals));
1593                                 g_settings->set("enable_particles", itos(menudata.enable_particles));
1594
1595                                 g_settings->set("creative_mode", itos(menudata.creative_mode));
1596                                 g_settings->set("enable_damage", itos(menudata.enable_damage));
1597                                 g_settings->set("server_announce", itos(menudata.enable_public));
1598                                 g_settings->set("name", playername);
1599                                 g_settings->set("address", address);
1600                                 g_settings->set("port", itos(port));
1601                                 if(menudata.selected_world != -1)
1602                                         g_settings->set("selected_world_path",
1603                                                         worldspecs[menudata.selected_world].path);
1604
1605                                 // Break out of menu-game loop to shut down cleanly
1606                                 if(device->run() == false || kill == true)
1607                                         break;
1608                                 
1609                                 current_playername = playername;
1610                                 current_password = password;
1611                                 current_address = address;
1612                                 current_port = port;
1613
1614                                 // If using simple singleplayer mode, override
1615                                 if(simple_singleplayer_mode){
1616                                         current_playername = "singleplayer";
1617                                         current_password = "";
1618                                         current_address = "";
1619                                         current_port = 30011;
1620                                 }
1621                                 else if (address != "")
1622                                 {
1623                                         ServerListSpec server;
1624                                         server["name"] = menudata.servername;
1625                                         server["address"] = wide_to_narrow(menudata.address);
1626                                         server["port"] = wide_to_narrow(menudata.port);
1627                                         server["description"] = menudata.serverdescription;
1628                                         ServerList::insert(server);
1629                                 }
1630                                 
1631                                 // Set world path to selected one
1632                                 if(menudata.selected_world != -1){
1633                                         worldspec = worldspecs[menudata.selected_world];
1634                                         infostream<<"Selected world: "<<worldspec.name
1635                                                         <<" ["<<worldspec.path<<"]"<<std::endl;
1636                                 }
1637
1638                                 // Only refresh if so requested
1639                                 if(menudata.only_refresh){
1640                                         infostream<<"Refreshing menu"<<std::endl;
1641                                         continue;
1642                                 }
1643                                 
1644                                 // Create new world if requested
1645                                 if(menudata.create_world_name != L"")
1646                                 {
1647                                         std::string path = porting::path_user + DIR_DELIM
1648                                                         "worlds" + DIR_DELIM
1649                                                         + wide_to_narrow(menudata.create_world_name);
1650                                         // Create world if it doesn't exist
1651                                         if(!initializeWorld(path, menudata.create_world_gameid)){
1652                                                 error_message = wgettext("Failed to initialize world");
1653                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1654                                                 continue;
1655                                         }
1656                                         g_settings->set("selected_world_path", path);
1657                                         continue;
1658                                 }
1659
1660                                 // If local game
1661                                 if(current_address == "")
1662                                 {
1663                                         if(menudata.selected_world == -1){
1664                                                 error_message = wgettext("No world selected and no address "
1665                                                                 "provided. Nothing to do.");
1666                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1667                                                 continue;
1668                                         }
1669                                         // Load gamespec for required game
1670                                         gamespec = findWorldSubgame(worldspec.path);
1671                                         if(!gamespec.isValid() && !commanded_gamespec.isValid()){
1672                                                 error_message = wgettext("Could not find or load game \"")
1673                                                                 + narrow_to_wide(worldspec.gameid) + L"\"";
1674                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1675                                                 continue;
1676                                         }
1677                                         if(commanded_gamespec.isValid() &&
1678                                                         commanded_gamespec.id != worldspec.gameid){
1679                                                 errorstream<<"WARNING: Overriding gamespec from \""
1680                                                                 <<worldspec.gameid<<"\" to \""
1681                                                                 <<commanded_gamespec.id<<"\""<<std::endl;
1682                                                 gamespec = commanded_gamespec;
1683                                         }
1684
1685                                         if(!gamespec.isValid()){
1686                                                 error_message = wgettext("Invalid gamespec.");
1687                                                 error_message += L" (world_gameid="
1688                                                                 +narrow_to_wide(worldspec.gameid)+L")";
1689                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1690                                                 continue;
1691                                         }
1692                                 }
1693
1694                                 // Continue to game
1695                                 break;
1696                         }
1697                         
1698                         // Break out of menu-game loop to shut down cleanly
1699                         if(device->run() == false || kill == true)
1700                                 break;
1701
1702                         /*
1703                                 Run game
1704                         */
1705                         the_game(
1706                                 kill,
1707                                 random_input,
1708                                 input,
1709                                 device,
1710                                 font,
1711                                 worldspec.path,
1712                                 current_playername,
1713                                 current_password,
1714                                 current_address,
1715                                 current_port,
1716                                 error_message,
1717                                 configpath,
1718                                 chat_backend,
1719                                 gamespec,
1720                                 simple_singleplayer_mode
1721                         );
1722
1723                 } //try
1724                 catch(con::PeerNotFoundException &e)
1725                 {
1726                         error_message = wgettext("Connection error (timed out?)");
1727                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1728                 }
1729                 catch(ServerError &e)
1730                 {
1731                         error_message = narrow_to_wide(e.what());
1732                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1733                 }
1734                 catch(ModError &e)
1735                 {
1736                         errorstream<<e.what()<<std::endl;
1737                         error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
1738                 }
1739 #ifdef NDEBUG
1740                 catch(std::exception &e)
1741                 {
1742                         std::string narrow_message = "Some exception: \"";
1743                         narrow_message += e.what();
1744                         narrow_message += "\"";
1745                         errorstream<<narrow_message<<std::endl;
1746                         error_message = narrow_to_wide(narrow_message);
1747                 }
1748 #endif
1749
1750                 // If no main menu, show error and exit
1751                 if(skip_main_menu)
1752                 {
1753                         if(error_message != L""){
1754                                 verbosestream<<"error_message = "
1755                                                 <<wide_to_narrow(error_message)<<std::endl;
1756                                 retval = 1;
1757                         }
1758                         break;
1759                 }
1760         } // Menu-game loop
1761         
1762         delete input;
1763
1764         /*
1765                 In the end, delete the Irrlicht device.
1766         */
1767         device->drop();
1768
1769 #endif // !SERVER
1770         
1771         // Update configuration file
1772         if(configpath != "")
1773                 g_settings->updateConfigFile(configpath.c_str());
1774         
1775         // Print modified quicktune values
1776         {
1777                 bool header_printed = false;
1778                 std::vector<std::string> names = getQuicktuneNames();
1779                 for(u32 i=0; i<names.size(); i++){
1780                         QuicktuneValue val = getQuicktuneValue(names[i]);
1781                         if(!val.modified)
1782                                 continue;
1783                         if(!header_printed){
1784                                 dstream<<"Modified quicktune values:"<<std::endl;
1785                                 header_printed = true;
1786                         }
1787                         dstream<<names[i]<<" = "<<val.getString()<<std::endl;
1788                 }
1789         }
1790
1791         END_DEBUG_EXCEPTION_HANDLER(errorstream)
1792         
1793         debugstreams_deinit();
1794         
1795         return retval;
1796 }
1797
1798 //END
1799