]> git.lizzy.rs Git - dragonfireclient.git/blob - src/main.cpp
Merge pull request #465 from doserj/mod_selection_empty_modname_fix
[dragonfireclient.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         if(run_dedicated_server)
1099         {
1100                 DSTACK("Dedicated server branch");
1101                 // Create time getter if built with Irrlicht
1102 #ifndef SERVER
1103                 g_timegetter = new SimpleTimeGetter();
1104 #endif
1105
1106                 // World directory
1107                 std::string world_path;
1108                 verbosestream<<_("Determining world path")<<std::endl;
1109                 bool is_legacy_world = false;
1110                 // If a world was commanded, use it
1111                 if(commanded_world != ""){
1112                         world_path = commanded_world;
1113                         infostream<<"Using commanded world path ["<<world_path<<"]"
1114                                         <<std::endl;
1115                 }
1116                 // No world was specified; try to select it automatically
1117                 else
1118                 {
1119                         // Get information about available worlds
1120                         std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1121                         // If a world name was specified, select it
1122                         if(commanded_worldname != ""){
1123                                 world_path = "";
1124                                 for(u32 i=0; i<worldspecs.size(); i++){
1125                                         std::string name = worldspecs[i].name;
1126                                         if(name == commanded_worldname){
1127                                                 world_path = worldspecs[i].path;
1128                                                 break;
1129                                         }
1130                                 }
1131                                 if(world_path == ""){
1132                                         dstream<<_("World")<<" '"<<commanded_worldname<<"' "<<_("not "
1133                                                         "available. Available worlds:")<<std::endl;
1134                                         print_worldspecs(worldspecs, dstream);
1135                                         return 1;
1136                                 }
1137                         }
1138                         // If there is only a single world, use it
1139                         if(worldspecs.size() == 1){
1140                                 world_path = worldspecs[0].path;
1141                                 dstream<<_("Automatically selecting world at")<<" ["
1142                                                 <<world_path<<"]"<<std::endl;
1143                         // If there are multiple worlds, list them
1144                         } else if(worldspecs.size() > 1){
1145                                 dstream<<_("Multiple worlds are available.")<<std::endl;
1146                                 dstream<<_("Please select one using --worldname <name>"
1147                                                 " or --world <path>")<<std::endl;
1148                                 print_worldspecs(worldspecs, dstream);
1149                                 return 1;
1150                         // If there are no worlds, automatically create a new one
1151                         } else {
1152                                 // This is the ultimate default world path
1153                                 world_path = porting::path_user + DIR_DELIM + "worlds" +
1154                                                 DIR_DELIM + "world";
1155                                 infostream<<"Creating default world at ["
1156                                                 <<world_path<<"]"<<std::endl;
1157                         }
1158                 }
1159
1160                 if(world_path == ""){
1161                         errorstream<<"No world path specified or found."<<std::endl;
1162                         return 1;
1163                 }
1164                 verbosestream<<_("Using world path")<<" ["<<world_path<<"]"<<std::endl;
1165
1166                 // We need a gamespec.
1167                 SubgameSpec gamespec;
1168                 verbosestream<<_("Determining gameid/gamespec")<<std::endl;
1169                 // If world doesn't exist
1170                 if(!getWorldExists(world_path))
1171                 {
1172                         // Try to take gamespec from command line
1173                         if(commanded_gamespec.isValid()){
1174                                 gamespec = commanded_gamespec;
1175                                 infostream<<"Using commanded gameid ["<<gamespec.id<<"]"<<std::endl;
1176                         }
1177                         // Otherwise we will be using "minetest"
1178                         else{
1179                                 gamespec = findSubgame(g_settings->get("default_game"));
1180                                 infostream<<"Using default gameid ["<<gamespec.id<<"]"<<std::endl;
1181                         }
1182                 }
1183                 // World exists
1184                 else
1185                 {
1186                         std::string world_gameid = getWorldGameId(world_path, is_legacy_world);
1187                         // If commanded to use a gameid, do so
1188                         if(commanded_gamespec.isValid()){
1189                                 gamespec = commanded_gamespec;
1190                                 if(commanded_gamespec.id != world_gameid){
1191                                         errorstream<<"WARNING: Using commanded gameid ["
1192                                                         <<gamespec.id<<"]"<<" instead of world gameid ["
1193                                                         <<world_gameid<<"]"<<std::endl;
1194                                 }
1195                         } else{
1196                                 // If world contains an embedded game, use it;
1197                                 // Otherwise find world from local system.
1198                                 gamespec = findWorldSubgame(world_path);
1199                                 infostream<<"Using world gameid ["<<gamespec.id<<"]"<<std::endl;
1200                         }
1201                 }
1202                 if(!gamespec.isValid()){
1203                         errorstream<<"Subgame ["<<gamespec.id<<"] could not be found."
1204                                         <<std::endl;
1205                         return 1;
1206                 }
1207                 verbosestream<<_("Using gameid")<<" ["<<gamespec.id<<"]"<<std::endl;
1208
1209                 // Create server
1210                 Server server(world_path, configpath, gamespec, false);
1211                 server.start(port);
1212                 
1213                 // Run server
1214                 dedicated_server_loop(server, kill);
1215
1216                 return 0;
1217         }
1218
1219 #ifndef SERVER // Exclude from dedicated server build
1220
1221         /*
1222                 More parameters
1223         */
1224         
1225         std::string address = g_settings->get("address");
1226         if(commanded_world != "")
1227                 address = "";
1228         else if(cmd_args.exists("address"))
1229                 address = cmd_args.get("address");
1230         
1231         std::string playername = g_settings->get("name");
1232         if(cmd_args.exists("name"))
1233                 playername = cmd_args.get("name");
1234         
1235         bool skip_main_menu = cmd_args.getFlag("go");
1236
1237         /*
1238                 Device initialization
1239         */
1240
1241         // Resolution selection
1242         
1243         bool fullscreen = g_settings->getBool("fullscreen");
1244         u16 screenW = g_settings->getU16("screenW");
1245         u16 screenH = g_settings->getU16("screenH");
1246
1247         // bpp, fsaa, vsync
1248
1249         bool vsync = g_settings->getBool("vsync");
1250         u16 bits = g_settings->getU16("fullscreen_bpp");
1251         u16 fsaa = g_settings->getU16("fsaa");
1252
1253         // Determine driver
1254
1255         video::E_DRIVER_TYPE driverType;
1256         
1257         std::string driverstring = g_settings->get("video_driver");
1258
1259         if(driverstring == "null")
1260                 driverType = video::EDT_NULL;
1261         else if(driverstring == "software")
1262                 driverType = video::EDT_SOFTWARE;
1263         else if(driverstring == "burningsvideo")
1264                 driverType = video::EDT_BURNINGSVIDEO;
1265         else if(driverstring == "direct3d8")
1266                 driverType = video::EDT_DIRECT3D8;
1267         else if(driverstring == "direct3d9")
1268                 driverType = video::EDT_DIRECT3D9;
1269         else if(driverstring == "opengl")
1270                 driverType = video::EDT_OPENGL;
1271         else
1272         {
1273                 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1274                                 "to opengl"<<std::endl;
1275                 driverType = video::EDT_OPENGL;
1276         }
1277
1278         /*
1279                 Create device and exit if creation failed
1280         */
1281
1282         MyEventReceiver receiver;
1283
1284         IrrlichtDevice *device;
1285
1286         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1287         params.DriverType    = driverType;
1288         params.WindowSize    = core::dimension2d<u32>(screenW, screenH);
1289         params.Bits          = bits;
1290         params.AntiAlias     = fsaa;
1291         params.Fullscreen    = fullscreen;
1292         params.Stencilbuffer = false;
1293         params.Vsync         = vsync;
1294         params.EventReceiver = &receiver;
1295
1296         device = createDeviceEx(params);
1297
1298         if (device == 0)
1299                 return 1; // could not create selected driver.
1300         
1301         /*
1302                 Continue initialization
1303         */
1304
1305         video::IVideoDriver* driver = device->getVideoDriver();
1306
1307         /*
1308                 This changes the minimum allowed number of vertices in a VBO.
1309                 Default is 500.
1310         */
1311         //driver->setMinHardwareBufferVertexCount(50);
1312
1313         // Create time getter
1314         g_timegetter = new IrrlichtTimeGetter(device);
1315         
1316         // Create game callback for menus
1317         g_gamecallback = new MainGameCallback(device);
1318         
1319         /*
1320                 Speed tests (done after irrlicht is loaded to get timer)
1321         */
1322         if(cmd_args.getFlag("speedtests"))
1323         {
1324                 dstream<<"Running speed tests"<<std::endl;
1325                 SpeedTests();
1326                 return 0;
1327         }
1328         
1329         device->setResizable(true);
1330
1331         bool random_input = g_settings->getBool("random_input")
1332                         || cmd_args.getFlag("random-input");
1333         InputHandler *input = NULL;
1334         if(random_input)
1335                 input = new RandomInputHandler();
1336         else
1337                 input = new RealInputHandler(device, &receiver);
1338         
1339         scene::ISceneManager* smgr = device->getSceneManager();
1340
1341         guienv = device->getGUIEnvironment();
1342         gui::IGUISkin* skin = guienv->getSkin();
1343         #if USE_FREETYPE
1344         std::string font_path = g_settings->get("font_path");
1345         u16 font_size = g_settings->getU16("font_size");
1346         gui::IGUIFont *font = gui::CGUITTFont::createTTFont(guienv, font_path.c_str(), font_size);
1347         #else
1348         gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
1349         #endif
1350         if(font)
1351                 skin->setFont(font);
1352         else
1353                 errorstream<<"WARNING: Font file was not found."
1354                                 " Using default font."<<std::endl;
1355         // If font was not found, this will get us one
1356         font = skin->getFont();
1357         assert(font);
1358         
1359         u32 text_height = font->getDimension(L"Hello, world!").Height;
1360         infostream<<"text_height="<<text_height<<std::endl;
1361
1362         //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1363         skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1364         //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1365         //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1366         skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1367         skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1368         skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50));
1369         skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255));
1370
1371 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1372         // Irrlicht 1.8 input colours
1373         skin->setColor(gui::EGDC_EDITABLE, video::SColor(255,128,128,128));
1374         skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255,96,134,49));
1375 #endif
1376
1377         /*
1378                 GUI stuff
1379         */
1380
1381         ChatBackend chat_backend;
1382
1383         /*
1384                 If an error occurs, this is set to something and the
1385                 menu-game loop is restarted. It is then displayed before
1386                 the menu.
1387         */
1388         std::wstring error_message = L"";
1389
1390         // The password entered during the menu screen,
1391         std::string password;
1392
1393         bool first_loop = true;
1394
1395         /*
1396                 Menu-game loop
1397         */
1398         while(device->run() && kill == false)
1399         {
1400                 // Set the window caption
1401                 device->setWindowCaption((std::wstring(L"Minetest [")+wgettext("Main Menu")+L"]").c_str());
1402
1403                 // This is used for catching disconnects
1404                 try
1405                 {
1406
1407                         /*
1408                                 Clear everything from the GUIEnvironment
1409                         */
1410                         guienv->clear();
1411                         
1412                         /*
1413                                 We need some kind of a root node to be able to add
1414                                 custom gui elements directly on the screen.
1415                                 Otherwise they won't be automatically drawn.
1416                         */
1417                         guiroot = guienv->addStaticText(L"",
1418                                         core::rect<s32>(0, 0, 10000, 10000));
1419                         
1420                         SubgameSpec gamespec;
1421                         WorldSpec worldspec;
1422                         bool simple_singleplayer_mode = false;
1423
1424                         // These are set up based on the menu and other things
1425                         std::string current_playername = "inv£lid";
1426                         std::string current_password = "";
1427                         std::string current_address = "does-not-exist";
1428                         int current_port = 0;
1429
1430                         /*
1431                                 Out-of-game menu loop.
1432
1433                                 Loop quits when menu returns proper parameters.
1434                         */
1435                         while(kill == false)
1436                         {
1437                                 // If skip_main_menu, only go through here once
1438                                 if(skip_main_menu && !first_loop){
1439                                         kill = true;
1440                                         break;
1441                                 }
1442                                 first_loop = false;
1443                                 
1444                                 // Cursor can be non-visible when coming from the game
1445                                 device->getCursorControl()->setVisible(true);
1446                                 // Some stuff are left to scene manager when coming from the game
1447                                 // (map at least?)
1448                                 smgr->clear();
1449                                 
1450                                 // Initialize menu data
1451                                 MainMenuData menudata;
1452                                 if(g_settings->exists("selected_mainmenu_tab"))
1453                                         menudata.selected_tab = g_settings->getS32("selected_mainmenu_tab");
1454                                 menudata.address = narrow_to_wide(address);
1455                                 menudata.name = narrow_to_wide(playername);
1456                                 menudata.port = narrow_to_wide(itos(port));
1457                                 if(cmd_args.exists("password"))
1458                                         menudata.password = narrow_to_wide(cmd_args.get("password"));
1459                                 menudata.fancy_trees = g_settings->getBool("new_style_leaves");
1460                                 menudata.smooth_lighting = g_settings->getBool("smooth_lighting");
1461                                 menudata.clouds_3d = g_settings->getBool("enable_3d_clouds");
1462                                 menudata.opaque_water = g_settings->getBool("opaque_water");
1463                                 menudata.mip_map = g_settings->getBool("mip_map");
1464                                 menudata.anisotropic_filter = g_settings->getBool("anisotropic_filter");
1465                                 menudata.bilinear_filter = g_settings->getBool("bilinear_filter");
1466                                 menudata.trilinear_filter = g_settings->getBool("trilinear_filter");
1467                                 menudata.enable_shaders = g_settings->getS32("enable_shaders");
1468                                 menudata.preload_item_visuals = g_settings->getBool("preload_item_visuals");
1469                                 menudata.enable_particles = g_settings->getBool("enable_particles");
1470                                 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, menudata.mip_map);
1471                                 menudata.creative_mode = g_settings->getBool("creative_mode");
1472                                 menudata.enable_damage = g_settings->getBool("enable_damage");
1473                                 // Default to selecting nothing
1474                                 menudata.selected_world = -1;
1475                                 // Get world listing for the menu
1476                                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1477                                 // If there is only one world, select it
1478                                 if(worldspecs.size() == 1){
1479                                         menudata.selected_world = 0;
1480                                 }
1481                                 // Otherwise try to select according to selected_world_path
1482                                 else if(g_settings->exists("selected_world_path")){
1483                                         std::string trypath = g_settings->get("selected_world_path");
1484                                         for(u32 i=0; i<worldspecs.size(); i++){
1485                                                 if(worldspecs[i].path == trypath){
1486                                                         menudata.selected_world = i;
1487                                                         break;
1488                                                 }
1489                                         }
1490                                 }
1491                                 // If a world was commanded, append and select it
1492                                 if(commanded_world != ""){
1493                                         std::string gameid = getWorldGameId(commanded_world, true);
1494                                         std::string name = _("[--world parameter]");
1495                                         if(gameid == ""){
1496                                                 gameid = g_settings->get("default_game");
1497                                                 name += " [new]";
1498                                         }
1499                                         WorldSpec spec(commanded_world, name, gameid);
1500                                         worldspecs.push_back(spec);
1501                                         menudata.selected_world = worldspecs.size()-1;
1502                                 }
1503                                 // Copy worldspecs to menu
1504                                 menudata.worlds = worldspecs;
1505
1506                                 if(skip_main_menu == false)
1507                                 {
1508                                         video::IVideoDriver* driver = device->getVideoDriver();
1509                                         
1510                                         infostream<<"Waiting for other menus"<<std::endl;
1511                                         while(device->run() && kill == false)
1512                                         {
1513                                                 if(noMenuActive())
1514                                                         break;
1515                                                 driver->beginScene(true, true,
1516                                                                 video::SColor(255,128,128,128));
1517                                                 drawMenuBackground(driver);
1518                                                 guienv->drawAll();
1519                                                 driver->endScene();
1520                                                 // On some computers framerate doesn't seem to be
1521                                                 // automatically limited
1522                                                 sleep_ms(25);
1523                                         }
1524                                         infostream<<"Waited for other menus"<<std::endl;
1525
1526                                         GUIMainMenu *menu =
1527                                                         new GUIMainMenu(guienv, guiroot, -1, 
1528                                                                 &g_menumgr, &menudata, g_gamecallback);
1529                                         menu->allowFocusRemoval(true);
1530
1531                                         if(error_message != L"")
1532                                         {
1533                                                 verbosestream<<"error_message = "
1534                                                                 <<wide_to_narrow(error_message)<<std::endl;
1535
1536                                                 GUIMessageMenu *menu2 =
1537                                                                 new GUIMessageMenu(guienv, guiroot, -1, 
1538                                                                         &g_menumgr, error_message.c_str());
1539                                                 menu2->drop();
1540                                                 error_message = L"";
1541                                         }
1542
1543                                         infostream<<"Created main menu"<<std::endl;
1544
1545                                         while(device->run() && kill == false)
1546                                         {
1547                                                 if(menu->getStatus() == true)
1548                                                         break;
1549
1550                                                 //driver->beginScene(true, true, video::SColor(255,0,0,0));
1551                                                 driver->beginScene(true, true, video::SColor(255,128,128,128));
1552
1553                                                 drawMenuBackground(driver);
1554
1555                                                 guienv->drawAll();
1556                                                 
1557                                                 driver->endScene();
1558                                                 
1559                                                 // On some computers framerate doesn't seem to be
1560                                                 // automatically limited
1561                                                 sleep_ms(25);
1562                                         }
1563                                         
1564                                         infostream<<"Dropping main menu"<<std::endl;
1565
1566                                         menu->drop();
1567                                 }
1568
1569                                 playername = wide_to_narrow(menudata.name);
1570                                 password = translatePassword(playername, menudata.password);
1571                                 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1572
1573                                 address = wide_to_narrow(menudata.address);
1574                                 int newport = stoi(wide_to_narrow(menudata.port));
1575                                 if(newport != 0)
1576                                         port = newport;
1577                                 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1578                                 // Save settings
1579                                 g_settings->setS32("selected_mainmenu_tab", menudata.selected_tab);
1580                                 g_settings->set("new_style_leaves", itos(menudata.fancy_trees));
1581                                 g_settings->set("smooth_lighting", itos(menudata.smooth_lighting));
1582                                 g_settings->set("enable_3d_clouds", itos(menudata.clouds_3d));
1583                                 g_settings->set("opaque_water", itos(menudata.opaque_water));
1584
1585                                 g_settings->set("mip_map", itos(menudata.mip_map));
1586                                 g_settings->set("anisotropic_filter", itos(menudata.anisotropic_filter));
1587                                 g_settings->set("bilinear_filter", itos(menudata.bilinear_filter));
1588                                 g_settings->set("trilinear_filter", itos(menudata.trilinear_filter));
1589
1590                                 g_settings->setS32("enable_shaders", menudata.enable_shaders);
1591                                 g_settings->set("preload_item_visuals", itos(menudata.preload_item_visuals));
1592                                 g_settings->set("enable_particles", itos(menudata.enable_particles));
1593
1594                                 g_settings->set("creative_mode", itos(menudata.creative_mode));
1595                                 g_settings->set("enable_damage", itos(menudata.enable_damage));
1596                                 g_settings->set("name", playername);
1597                                 g_settings->set("address", address);
1598                                 g_settings->set("port", itos(port));
1599                                 if(menudata.selected_world != -1)
1600                                         g_settings->set("selected_world_path",
1601                                                         worldspecs[menudata.selected_world].path);
1602
1603                                 // Break out of menu-game loop to shut down cleanly
1604                                 if(device->run() == false || kill == true)
1605                                         break;
1606                                 
1607                                 current_playername = playername;
1608                                 current_password = password;
1609                                 current_address = address;
1610                                 current_port = port;
1611
1612                                 // If using simple singleplayer mode, override
1613                                 if(simple_singleplayer_mode){
1614                                         current_playername = "singleplayer";
1615                                         current_password = "";
1616                                         current_address = "";
1617                                         current_port = 30011;
1618                                 }
1619                                 else if (address != "")
1620                                 {
1621                                         ServerListSpec server;
1622                                         server.name = menudata.servername;
1623                                         server.address = wide_to_narrow(menudata.address);
1624                                         server.port = wide_to_narrow(menudata.port);
1625                                         server.description = menudata.serverdescription;
1626                                         ServerList::insert(server);
1627                                 }
1628                                 
1629                                 // Set world path to selected one
1630                                 if(menudata.selected_world != -1){
1631                                         worldspec = worldspecs[menudata.selected_world];
1632                                         infostream<<"Selected world: "<<worldspec.name
1633                                                         <<" ["<<worldspec.path<<"]"<<std::endl;
1634                                 }
1635
1636                                 // Only refresh if so requested
1637                                 if(menudata.only_refresh){
1638                                         infostream<<"Refreshing menu"<<std::endl;
1639                                         continue;
1640                                 }
1641                                 
1642                                 // Create new world if requested
1643                                 if(menudata.create_world_name != L"")
1644                                 {
1645                                         std::string path = porting::path_user + DIR_DELIM
1646                                                         "worlds" + DIR_DELIM
1647                                                         + wide_to_narrow(menudata.create_world_name);
1648                                         // Create world if it doesn't exist
1649                                         if(!initializeWorld(path, menudata.create_world_gameid)){
1650                                                 error_message = wgettext("Failed to initialize world");
1651                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1652                                                 continue;
1653                                         }
1654                                         g_settings->set("selected_world_path", path);
1655                                         continue;
1656                                 }
1657
1658                                 // If local game
1659                                 if(current_address == "")
1660                                 {
1661                                         if(menudata.selected_world == -1){
1662                                                 error_message = wgettext("No world selected and no address "
1663                                                                 "provided. Nothing to do.");
1664                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1665                                                 continue;
1666                                         }
1667                                         // Load gamespec for required game
1668                                         gamespec = findWorldSubgame(worldspec.path);
1669                                         if(!gamespec.isValid() && !commanded_gamespec.isValid()){
1670                                                 error_message = wgettext("Could not find or load game \"")
1671                                                                 + narrow_to_wide(worldspec.gameid) + L"\"";
1672                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1673                                                 continue;
1674                                         }
1675                                         if(commanded_gamespec.isValid() &&
1676                                                         commanded_gamespec.id != worldspec.gameid){
1677                                                 errorstream<<"WARNING: Overriding gamespec from \""
1678                                                                 <<worldspec.gameid<<"\" to \""
1679                                                                 <<commanded_gamespec.id<<"\""<<std::endl;
1680                                                 gamespec = commanded_gamespec;
1681                                         }
1682
1683                                         if(!gamespec.isValid()){
1684                                                 error_message = wgettext("Invalid gamespec.");
1685                                                 error_message += L" (world_gameid="
1686                                                                 +narrow_to_wide(worldspec.gameid)+L")";
1687                                                 errorstream<<wide_to_narrow(error_message)<<std::endl;
1688                                                 continue;
1689                                         }
1690                                 }
1691
1692                                 // Continue to game
1693                                 break;
1694                         }
1695                         
1696                         // Break out of menu-game loop to shut down cleanly
1697                         if(device->run() == false || kill == true)
1698                                 break;
1699
1700                         /*
1701                                 Run game
1702                         */
1703                         the_game(
1704                                 kill,
1705                                 random_input,
1706                                 input,
1707                                 device,
1708                                 font,
1709                                 worldspec.path,
1710                                 current_playername,
1711                                 current_password,
1712                                 current_address,
1713                                 current_port,
1714                                 error_message,
1715                                 configpath,
1716                                 chat_backend,
1717                                 gamespec,
1718                                 simple_singleplayer_mode
1719                         );
1720
1721                 } //try
1722                 catch(con::PeerNotFoundException &e)
1723                 {
1724                         error_message = wgettext("Connection error (timed out?)");
1725                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1726                 }
1727                 catch(ServerError &e)
1728                 {
1729                         error_message = narrow_to_wide(e.what());
1730                         errorstream<<wide_to_narrow(error_message)<<std::endl;
1731                 }
1732                 catch(ModError &e)
1733                 {
1734                         errorstream<<e.what()<<std::endl;
1735                         error_message = narrow_to_wide(e.what()) + wgettext("\nCheck debug.txt for details.");
1736                 }
1737 #ifdef NDEBUG
1738                 catch(std::exception &e)
1739                 {
1740                         std::string narrow_message = "Some exception: \"";
1741                         narrow_message += e.what();
1742                         narrow_message += "\"";
1743                         errorstream<<narrow_message<<std::endl;
1744                         error_message = narrow_to_wide(narrow_message);
1745                 }
1746 #endif
1747
1748                 // If no main menu, show error and exit
1749                 if(skip_main_menu)
1750                 {
1751                         if(error_message != L""){
1752                                 verbosestream<<"error_message = "
1753                                                 <<wide_to_narrow(error_message)<<std::endl;
1754                                 retval = 1;
1755                         }
1756                         break;
1757                 }
1758         } // Menu-game loop
1759         
1760         delete input;
1761
1762         /*
1763                 In the end, delete the Irrlicht device.
1764         */
1765         device->drop();
1766
1767 #endif // !SERVER
1768         
1769         // Update configuration file
1770         if(configpath != "")
1771                 g_settings->updateConfigFile(configpath.c_str());
1772         
1773         // Print modified quicktune values
1774         {
1775                 bool header_printed = false;
1776                 std::vector<std::string> names = getQuicktuneNames();
1777                 for(u32 i=0; i<names.size(); i++){
1778                         QuicktuneValue val = getQuicktuneValue(names[i]);
1779                         if(!val.modified)
1780                                 continue;
1781                         if(!header_printed){
1782                                 dstream<<"Modified quicktune values:"<<std::endl;
1783                                 header_printed = true;
1784                         }
1785                         dstream<<names[i]<<" = "<<val.getString()<<std::endl;
1786                 }
1787         }
1788
1789         END_DEBUG_EXCEPTION_HANDLER(errorstream)
1790         
1791         debugstreams_deinit();
1792         
1793         return retval;
1794 }
1795
1796 //END
1797