3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
22 #pragma message ("Disabling unit tests")
24 #warning "Disabling unit tests"
27 #define ENABLE_TESTS 0
30 #define ENABLE_TESTS 1
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")
39 #pragma comment(lib, "zlibwapi.lib")
40 #pragma comment(lib, "Shell32.lib")
43 #include "irrlicht.h" // createDevice
46 #include "mainmenumanager.h"
50 #include "irrlichttypes_extrabloated.h"
55 #include "constants.h"
58 #include "guiMessageMenu.h"
61 #include "guiMainMenu.h"
66 #include "defaultsettings.h"
73 #include "xCGUITTFont.h"
75 #include "util/string.h"
77 #include "quicktune.h"
78 #include "serverlist.h"
80 #include "sound_openal.h"
84 These are loaded from the config file.
86 Settings main_settings;
87 Settings *g_settings = &main_settings;
90 Profiler main_profiler;
91 Profiler *g_profiler = &main_profiler;
93 // Menu clouds are created later
94 Clouds *g_menuclouds = 0;
95 irr::scene::ISceneManager *g_menucloudsmgr = 0;
102 std::ostream *dout_con_ptr = &dummyout;
103 std::ostream *derr_con_ptr = &verbosestream;
106 std::ostream *dout_server_ptr = &infostream;
107 std::ostream *derr_server_ptr = &errorstream;
110 std::ostream *dout_client_ptr = &infostream;
111 std::ostream *derr_client_ptr = &errorstream;
118 /* mainmenumanager.h */
120 gui::IGUIEnvironment* guienv = NULL;
121 gui::IGUIStaticText *guiroot = NULL;
122 MainMenuManager g_menumgr;
126 return (g_menumgr.menuCount() == 0);
129 // Passed to menus to allow disconnecting and exiting
130 MainGameCallback *g_gamecallback = NULL;
134 gettime.h implementation
141 /* Use imprecise system calls directly (from porting.h) */
142 return porting::getTime(PRECISION_MILLI);
145 u32 getTime(TimePrecision prec)
147 return porting::getTime(prec);
152 // A small helper class
156 virtual u32 getTime(TimePrecision prec) = 0;
159 // A precise irrlicht one
160 class IrrlichtTimeGetter: public TimeGetter
163 IrrlichtTimeGetter(IrrlichtDevice *device):
166 u32 getTime(TimePrecision prec)
168 if (prec == PRECISION_MILLI) {
171 return m_device->getTimer()->getRealTime();
173 return porting::getTime(prec);
177 IrrlichtDevice *m_device;
179 // Not so precise one which works without irrlicht
180 class SimpleTimeGetter: public TimeGetter
183 u32 getTime(TimePrecision prec)
185 return porting::getTime(prec);
189 // A pointer to a global instance of the time getter
191 TimeGetter *g_timegetter = NULL;
195 if(g_timegetter == NULL)
197 return g_timegetter->getTime(PRECISION_MILLI);
200 u32 getTime(TimePrecision prec) {
201 if (g_timegetter == NULL)
203 return g_timegetter->getTime(prec);
207 //Client side main menu music fetcher
209 class MenuMusicFetcher: public OnDemandSoundFetcher
211 std::set<std::string> m_fetched;
214 void fetchSounds(const std::string &name,
215 std::set<std::string> &dst_paths,
216 std::set<std::string> &dst_datas)
218 if(m_fetched.count(name))
220 m_fetched.insert(name);
222 base = porting::path_share + DIR_DELIM + "sounds";
223 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
224 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
225 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
226 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
227 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
228 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
229 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
230 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
231 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
232 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
233 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
234 base = porting::path_user + DIR_DELIM + "sounds";
235 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
236 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
237 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
238 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
239 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
240 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
241 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
242 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
243 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
244 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
245 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
250 class StderrLogOutput: public ILogOutput
253 /* line: Full line with timestamp, level and thread */
254 void printLog(const std::string &line)
256 std::cerr<<line<<std::endl;
258 } main_stderr_log_out;
260 class DstreamNoStderrLogOutput: public ILogOutput
263 /* line: Full line with timestamp, level and thread */
264 void printLog(const std::string &line)
266 dstream_no_stderr<<line<<std::endl;
268 } main_dstream_no_stderr_log_out;
273 Event handler for Irrlicht
275 NOTE: Everything possible should be moved out from here,
276 probably to InputHandler and the_game
279 class MyEventReceiver : public IEventReceiver
282 // This is the one method that we have to implement
283 virtual bool OnEvent(const SEvent& event)
286 React to nothing here if a menu is active
288 if(noMenuActive() == false)
293 // Remember whether each key is down or up
294 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
296 if(event.KeyInput.PressedDown) {
297 keyIsDown.set(event.KeyInput);
298 keyWasDown.set(event.KeyInput);
300 keyIsDown.unset(event.KeyInput);
304 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
306 if(noMenuActive() == false)
309 middle_active = false;
310 right_active = false;
314 left_active = event.MouseInput.isLeftPressed();
315 middle_active = event.MouseInput.isMiddlePressed();
316 right_active = event.MouseInput.isRightPressed();
318 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
322 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
326 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
330 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
332 rightreleased = true;
334 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
336 mouse_wheel += event.MouseInput.Wheel;
344 bool IsKeyDown(const KeyPress &keyCode) const
346 return keyIsDown[keyCode];
349 // Checks whether a key was down and resets the state
350 bool WasKeyDown(const KeyPress &keyCode)
352 bool b = keyWasDown[keyCode];
354 keyWasDown.unset(keyCode);
371 rightclicked = false;
372 leftreleased = false;
373 rightreleased = false;
376 middle_active = false;
377 right_active = false;
399 IrrlichtDevice *m_device;
401 // The current state of keys
403 // Whether a key has been pressed or not
408 Separated input handler
411 class RealInputHandler : public InputHandler
414 RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
419 virtual bool isKeyDown(const KeyPress &keyCode)
421 return m_receiver->IsKeyDown(keyCode);
423 virtual bool wasKeyDown(const KeyPress &keyCode)
425 return m_receiver->WasKeyDown(keyCode);
427 virtual v2s32 getMousePos()
429 return m_device->getCursorControl()->getPosition();
431 virtual void setMousePos(s32 x, s32 y)
433 m_device->getCursorControl()->setPosition(x, y);
436 virtual bool getLeftState()
438 return m_receiver->left_active;
440 virtual bool getRightState()
442 return m_receiver->right_active;
445 virtual bool getLeftClicked()
447 return m_receiver->leftclicked;
449 virtual bool getRightClicked()
451 return m_receiver->rightclicked;
453 virtual void resetLeftClicked()
455 m_receiver->leftclicked = false;
457 virtual void resetRightClicked()
459 m_receiver->rightclicked = false;
462 virtual bool getLeftReleased()
464 return m_receiver->leftreleased;
466 virtual bool getRightReleased()
468 return m_receiver->rightreleased;
470 virtual void resetLeftReleased()
472 m_receiver->leftreleased = false;
474 virtual void resetRightReleased()
476 m_receiver->rightreleased = false;
479 virtual s32 getMouseWheel()
481 return m_receiver->getMouseWheel();
486 m_receiver->clearInput();
489 IrrlichtDevice *m_device;
490 MyEventReceiver *m_receiver;
493 class RandomInputHandler : public InputHandler
501 rightclicked = false;
502 leftreleased = false;
503 rightreleased = false;
506 virtual bool isKeyDown(const KeyPress &keyCode)
508 return keydown[keyCode];
510 virtual bool wasKeyDown(const KeyPress &keyCode)
514 virtual v2s32 getMousePos()
518 virtual void setMousePos(s32 x, s32 y)
520 mousepos = v2s32(x,y);
523 virtual bool getLeftState()
527 virtual bool getRightState()
532 virtual bool getLeftClicked()
536 virtual bool getRightClicked()
540 virtual void resetLeftClicked()
544 virtual void resetRightClicked()
546 rightclicked = false;
549 virtual bool getLeftReleased()
553 virtual bool getRightReleased()
555 return rightreleased;
557 virtual void resetLeftReleased()
559 leftreleased = false;
561 virtual void resetRightReleased()
563 rightreleased = false;
566 virtual s32 getMouseWheel()
571 virtual void step(float dtime)
574 static float counter1 = 0;
578 counter1 = 0.1*Rand(1, 40);
579 keydown.toggle(getKeySetting("keymap_jump"));
583 static float counter1 = 0;
587 counter1 = 0.1*Rand(1, 40);
588 keydown.toggle(getKeySetting("keymap_special1"));
592 static float counter1 = 0;
596 counter1 = 0.1*Rand(1, 40);
597 keydown.toggle(getKeySetting("keymap_forward"));
601 static float counter1 = 0;
605 counter1 = 0.1*Rand(1, 40);
606 keydown.toggle(getKeySetting("keymap_left"));
610 static float counter1 = 0;
614 counter1 = 0.1*Rand(1, 20);
615 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
619 static float counter1 = 0;
623 counter1 = 0.1*Rand(1, 30);
624 leftdown = !leftdown;
632 static float counter1 = 0;
636 counter1 = 0.1*Rand(1, 15);
637 rightdown = !rightdown;
641 rightreleased = true;
644 mousepos += mousespeed;
647 s32 Rand(s32 min, s32 max)
649 return (myrand()%(max-min+1))+min;
665 std::string current_gameid;
666 video::ITexture *background;
667 video::ITexture *overlay;
668 video::ITexture *header;
669 video::ITexture *footer;
678 static video::ITexture* getMenuTexture(const std::string &tname,
679 video::IVideoDriver* driver, const SubgameSpec *spec)
682 // eg. minetest_menu_background.png (for texture packs)
683 std::string pack_tname = spec->id + "_menu_" + tname + ".png";
684 path = getTexturePath(pack_tname);
686 return driver->getTexture(path.c_str());
687 // eg. games/minetest_game/menu/background.png
688 path = getImagePath(spec->path + DIR_DELIM + "menu" + DIR_DELIM + tname + ".png");
690 return driver->getTexture(path.c_str());
694 void update(video::IVideoDriver* driver, const SubgameSpec *spec)
696 if(spec->id == current_gameid)
698 current_gameid = spec->id;
699 background = getMenuTexture("background", driver, spec);
700 overlay = getMenuTexture("overlay", driver, spec);
701 header = getMenuTexture("header", driver, spec);
702 footer = getMenuTexture("footer", driver, spec);
706 void drawMenuBackground(video::IVideoDriver* driver, const MenuTextures &menutextures)
708 v2u32 screensize = driver->getScreenSize();
709 video::ITexture *texture = menutextures.background;
711 /* If no texture, draw background of solid color */
713 video::SColor color(255,80,58,37);
714 core::rect<s32> rect(0, 0, screensize.X, screensize.Y);
715 driver->draw2DRectangle(color, rect, NULL);
719 /* Draw background texture */
720 v2u32 sourcesize = texture->getSize();
721 driver->draw2DImage(texture,
722 core::rect<s32>(0, 0, screensize.X, screensize.Y),
723 core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y),
727 void drawMenuOverlay(video::IVideoDriver* driver, const MenuTextures &menutextures)
729 v2u32 screensize = driver->getScreenSize();
730 video::ITexture *texture = menutextures.overlay;
732 /* If no texture, draw nothing */
736 /* Draw overlay texture */
737 v2u32 sourcesize = texture->getSize();
738 driver->draw2DImage(texture,
739 core::rect<s32>(0, 0, screensize.X, screensize.Y),
740 core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y),
744 void drawMenuHeader(video::IVideoDriver* driver, const MenuTextures &menutextures)
746 core::dimension2d<u32> screensize = driver->getScreenSize();
747 video::ITexture *texture = menutextures.header;
749 /* If no texture, draw nothing */
753 f32 mult = (((f32)screensize.Width / 2)) /
754 ((f32)texture->getOriginalSize().Width);
756 v2s32 splashsize(((f32)texture->getOriginalSize().Width) * mult,
757 ((f32)texture->getOriginalSize().Height) * mult);
759 // Don't draw the header is there isn't enough room
760 s32 free_space = (((s32)screensize.Height)-320)/2;
761 if (free_space > splashsize.Y) {
762 core::rect<s32> splashrect(0, 0, splashsize.X, splashsize.Y);
763 splashrect += v2s32((screensize.Width/2)-(splashsize.X/2),
764 ((free_space/2)-splashsize.Y/2)+10);
766 video::SColor bgcolor(255,50,50,50);
768 driver->draw2DImage(texture, splashrect,
769 core::rect<s32>(core::position2d<s32>(0,0),
770 core::dimension2di(texture->getSize())),
775 void drawMenuFooter(video::IVideoDriver* driver, const MenuTextures &menutextures)
777 core::dimension2d<u32> screensize = driver->getScreenSize();
778 video::ITexture *texture = menutextures.footer;
780 /* If no texture, draw nothing */
784 f32 mult = (((f32)screensize.Width)) /
785 ((f32)texture->getOriginalSize().Width);
787 v2s32 footersize(((f32)texture->getOriginalSize().Width) * mult,
788 ((f32)texture->getOriginalSize().Height) * mult);
790 // Don't draw the footer if there isn't enough room
791 s32 free_space = (((s32)screensize.Height)-320)/2;
792 if (free_space > footersize.Y) {
793 core::rect<s32> rect(0,0,footersize.X,footersize.Y);
794 rect += v2s32(screensize.Width/2,screensize.Height-footersize.Y);
795 rect -= v2s32(footersize.X/2, 0);
797 driver->draw2DImage(texture, rect,
798 core::rect<s32>(core::position2d<s32>(0,0),
799 core::dimension2di(texture->getSize())),
804 static const SubgameSpec* getMenuGame(const MainMenuData &menudata)
806 for(size_t i=0; i<menudata.games.size(); i++){
807 if(menudata.games[i].id == menudata.selected_game){
808 return &menudata.games[i];
816 // These are defined global so that they're not optimized too much.
817 // Can't change them to volatile.
822 std::string tempstring;
823 std::string tempstring2;
828 infostream<<"The following test should take around 20ms."<<std::endl;
829 TimeTaker timer("Testing std::string speed");
830 const u32 jj = 10000;
831 for(u32 j=0; j<jj; j++)
836 for(u32 i=0; i<ii; i++){
837 tempstring2 += "asd";
839 for(u32 i=0; i<ii+1; i++){
841 if(tempstring == tempstring2)
847 infostream<<"All of the following tests should take around 100ms each."
851 TimeTaker timer("Testing floating-point conversion speed");
853 for(u32 i=0; i<4000000; i++){
860 TimeTaker timer("Testing floating-point vector speed");
862 tempv3f1 = v3f(1,2,3);
863 tempv3f2 = v3f(4,5,6);
864 for(u32 i=0; i<10000000; i++){
865 tempf += tempv3f1.dotProduct(tempv3f2);
866 tempv3f2 += v3f(7,8,9);
871 TimeTaker timer("Testing std::map speed");
873 std::map<v2s16, f32> map1;
876 for(s16 y=0; y<ii; y++){
877 for(s16 x=0; x<ii; x++){
878 map1[v2s16(x,y)] = tempf;
882 for(s16 y=ii-1; y>=0; y--){
883 for(s16 x=0; x<ii; x++){
884 tempf = map1[v2s16(x,y)];
890 infostream<<"Around 5000/ms should do well here."<<std::endl;
891 TimeTaker timer("Testing mutex speed");
905 while(timer.getTimerTime() < 10);
907 u32 dtime = timer.stop();
908 u32 per_ms = n / dtime;
909 infostream<<"Done. "<<dtime<<"ms, "
910 <<per_ms<<"/ms"<<std::endl;
914 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
917 for(u32 i=0; i<worldspecs.size(); i++){
918 std::string name = worldspecs[i].name;
919 std::string path = worldspecs[i].path;
920 if(name.find(" ") != std::string::npos)
921 name = std::string("'") + name + "'";
922 path = std::string("'") + path + "'";
923 name = padStringRight(name, 14);
924 os<<" "<<name<<" "<<path<<std::endl;
928 int main(int argc, char *argv[])
936 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
937 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
939 log_register_thread("main");
941 // This enables internatonal characters input
942 if( setlocale(LC_ALL, "") == NULL )
944 fprintf( stderr, "%s: warning: could not set default locale\n", argv[0] );
947 // Set locale. This is for forcing '.' as the decimal point.
949 std::locale::global(std::locale(std::locale(""), "C", std::locale::numeric));
950 setlocale(LC_NUMERIC, "C");
951 } catch (const std::exception& ex) {
952 errorstream<<"Could not set numeric locale to C"<<std::endl;
958 // List all allowed options
959 std::map<std::string, ValueSpec> allowed_options;
960 allowed_options.insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
961 _("Show allowed options"))));
962 allowed_options.insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
963 _("Load configuration from specified file"))));
964 allowed_options.insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
965 _("Set network port (UDP)"))));
966 allowed_options.insert(std::make_pair("disable-unittests", ValueSpec(VALUETYPE_FLAG,
967 _("Disable unit tests"))));
968 allowed_options.insert(std::make_pair("enable-unittests", ValueSpec(VALUETYPE_FLAG,
969 _("Enable unit tests"))));
970 allowed_options.insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
971 _("Same as --world (deprecated)"))));
972 allowed_options.insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
973 _("Set world path (implies local game) ('list' lists all)"))));
974 allowed_options.insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
975 _("Set world by name (implies local game)"))));
976 allowed_options.insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
977 _("Print more information to console"))));
978 allowed_options.insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
979 _("Print even more information to console"))));
980 allowed_options.insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
981 _("Print enormous amounts of information to log and console"))));
982 allowed_options.insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
983 _("Set logfile path ('' = no logging)"))));
984 allowed_options.insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
985 _("Set gameid (\"--gameid list\" prints available ones)"))));
987 allowed_options.insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
988 _("Show available video modes"))));
989 allowed_options.insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
990 _("Run speed tests"))));
991 allowed_options.insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
992 _("Address to connect to. ('' = local game)"))));
993 allowed_options.insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
994 _("Enable random user input, for testing"))));
995 allowed_options.insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
996 _("Run dedicated server"))));
997 allowed_options.insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
998 _("Set player name"))));
999 allowed_options.insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
1000 _("Set password"))));
1001 allowed_options.insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
1002 _("Disable main menu"))));
1007 bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
1009 if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1"))
1011 dstream<<_("Allowed options:")<<std::endl;
1012 for(std::map<std::string, ValueSpec>::iterator
1013 i = allowed_options.begin();
1014 i != allowed_options.end(); ++i)
1016 std::ostringstream os1(std::ios::binary);
1017 os1<<" --"<<i->first;
1018 if(i->second.type == VALUETYPE_FLAG)
1022 dstream<<padStringRight(os1.str(), 24);
1024 if(i->second.help != NULL)
1025 dstream<<i->second.help;
1029 return cmd_args.getFlag("help") ? 0 : 1;
1033 Low-level initialization
1036 // If trace is enabled, enable logging of certain things
1037 if(cmd_args.getFlag("trace")){
1038 dstream<<_("Enabling trace level debug output")<<std::endl;
1039 log_trace_level_enabled = true;
1040 dout_con_ptr = &verbosestream; // this is somewhat old crap
1041 socket_enable_debug_output = true; // socket doesn't use log.h
1043 // In certain cases, output info level on stderr
1044 if(cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
1045 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
1046 log_add_output(&main_stderr_log_out, LMT_INFO);
1047 // In certain cases, output verbose level on stderr
1048 if(cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
1049 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
1051 porting::signal_handler_init();
1052 bool &kill = *porting::signal_handler_killstatus();
1054 porting::initializePaths();
1056 // Create user data directory
1057 fs::CreateDir(porting::path_user);
1059 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str());
1061 infostream<<"path_share = "<<porting::path_share<<std::endl;
1062 infostream<<"path_user = "<<porting::path_user<<std::endl;
1064 // Initialize debug stacks
1065 debug_stacks_init();
1066 DSTACK(__FUNCTION_NAME);
1069 BEGIN_DEBUG_EXCEPTION_HANDLER
1071 // List gameids if requested
1072 if(cmd_args.exists("gameid") && cmd_args.get("gameid") == "list")
1074 std::set<std::string> gameids = getAvailableGameIds();
1075 for(std::set<std::string>::const_iterator i = gameids.begin();
1076 i != gameids.end(); i++)
1077 dstream<<(*i)<<std::endl;
1081 // List worlds if requested
1082 if(cmd_args.exists("world") && cmd_args.get("world") == "list"){
1083 dstream<<_("Available worlds:")<<std::endl;
1084 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1085 print_worldspecs(worldspecs, dstream);
1089 // Print startup message
1090 infostream<<PROJECT_NAME<<
1091 " "<<_("with")<<" SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
1096 Basic initialization
1099 // Initialize default settings
1100 set_default_settings(g_settings);
1102 // Initialize sockets
1104 atexit(sockets_cleanup);
1110 // Path of configuration file in use
1111 std::string configpath = "";
1113 if(cmd_args.exists("config"))
1115 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
1118 errorstream<<"Could not read configuration from \""
1119 <<cmd_args.get("config")<<"\""<<std::endl;
1122 configpath = cmd_args.get("config");
1126 std::vector<std::string> filenames;
1127 filenames.push_back(porting::path_user +
1128 DIR_DELIM + "minetest.conf");
1129 // Legacy configuration file location
1130 filenames.push_back(porting::path_user +
1131 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1133 // Try also from a lower level (to aid having the same configuration
1134 // for many RUN_IN_PLACE installs)
1135 filenames.push_back(porting::path_user +
1136 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
1139 for(u32 i=0; i<filenames.size(); i++)
1141 bool r = g_settings->readConfigFile(filenames[i].c_str());
1144 configpath = filenames[i];
1149 // If no path found, use the first one (menu creates the file)
1150 if(configpath == "")
1151 configpath = filenames[0];
1154 // Initialize debug streams
1155 #define DEBUGFILE "debug.txt"
1157 std::string logfile = DEBUGFILE;
1159 std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE;
1161 if(cmd_args.exists("logfile"))
1162 logfile = cmd_args.get("logfile");
1164 log_remove_output(&main_dstream_no_stderr_log_out);
1165 int loglevel = g_settings->getS32("debug_log_level");
1167 if (loglevel == 0) //no logging
1169 else if (loglevel > 0 && loglevel <= LMT_NUM_VALUES)
1170 log_add_output_maxlev(&main_dstream_no_stderr_log_out, (LogMessageLevel)(loglevel - 1));
1173 debugstreams_init(false, logfile.c_str());
1175 debugstreams_init(false, NULL);
1177 infostream<<"logfile = "<<logfile<<std::endl;
1179 // Initialize random seed
1187 if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
1188 || cmd_args.getFlag("enable-unittests") == true)
1199 if(cmd_args.exists("port"))
1200 port = cmd_args.getU16("port");
1201 else if(g_settings->exists("port"))
1202 port = g_settings->getU16("port");
1207 std::string commanded_world = "";
1208 if(cmd_args.exists("world"))
1209 commanded_world = cmd_args.get("world");
1210 else if(cmd_args.exists("map-dir"))
1211 commanded_world = cmd_args.get("map-dir");
1212 else if(cmd_args.exists("nonopt0")) // First nameless argument
1213 commanded_world = cmd_args.get("nonopt0");
1214 else if(g_settings->exists("map-dir"))
1215 commanded_world = g_settings->get("map-dir");
1218 std::string commanded_worldname = "";
1219 if(cmd_args.exists("worldname"))
1220 commanded_worldname = cmd_args.get("worldname");
1222 // Strip world.mt from commanded_world
1224 std::string worldmt = "world.mt";
1225 if(commanded_world.size() > worldmt.size() &&
1226 commanded_world.substr(commanded_world.size()-worldmt.size())
1228 dstream<<_("Supplied world.mt file - stripping it off.")<<std::endl;
1229 commanded_world = commanded_world.substr(
1230 0, commanded_world.size()-worldmt.size());
1234 // If a world name was specified, convert it to a path
1235 if(commanded_worldname != ""){
1236 // Get information about available worlds
1237 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1239 for(u32 i=0; i<worldspecs.size(); i++){
1240 std::string name = worldspecs[i].name;
1241 if(name == commanded_worldname){
1242 if(commanded_world != ""){
1243 dstream<<_("--worldname takes precedence over previously "
1244 "selected world.")<<std::endl;
1246 commanded_world = worldspecs[i].path;
1252 dstream<<_("World")<<" '"<<commanded_worldname<<_("' not "
1253 "available. Available worlds:")<<std::endl;
1254 print_worldspecs(worldspecs, dstream);
1260 SubgameSpec commanded_gamespec;
1261 if(cmd_args.exists("gameid")){
1262 std::string gameid = cmd_args.get("gameid");
1263 commanded_gamespec = findSubgame(gameid);
1264 if(!commanded_gamespec.isValid()){
1265 errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl;
1271 Run dedicated server if asked to or no other option
1274 bool run_dedicated_server = true;
1276 bool run_dedicated_server = cmd_args.getFlag("server");
1278 g_settings->set("server_dedicated", run_dedicated_server ? "true" : "false");
1279 if(run_dedicated_server)
1281 DSTACK("Dedicated server branch");
1282 // Create time getter if built with Irrlicht
1284 g_timegetter = new SimpleTimeGetter();
1288 std::string world_path;
1289 verbosestream<<_("Determining world path")<<std::endl;
1290 bool is_legacy_world = false;
1291 // If a world was commanded, use it
1292 if(commanded_world != ""){
1293 world_path = commanded_world;
1294 infostream<<"Using commanded world path ["<<world_path<<"]"
1297 // No world was specified; try to select it automatically
1300 // Get information about available worlds
1301 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1302 // If a world name was specified, select it
1303 if(commanded_worldname != ""){
1305 for(u32 i=0; i<worldspecs.size(); i++){
1306 std::string name = worldspecs[i].name;
1307 if(name == commanded_worldname){
1308 world_path = worldspecs[i].path;
1312 if(world_path == ""){
1313 dstream<<_("World")<<" '"<<commanded_worldname<<"' "<<_("not "
1314 "available. Available worlds:")<<std::endl;
1315 print_worldspecs(worldspecs, dstream);
1319 // If there is only a single world, use it
1320 if(worldspecs.size() == 1){
1321 world_path = worldspecs[0].path;
1322 dstream<<_("Automatically selecting world at")<<" ["
1323 <<world_path<<"]"<<std::endl;
1324 // If there are multiple worlds, list them
1325 } else if(worldspecs.size() > 1){
1326 dstream<<_("Multiple worlds are available.")<<std::endl;
1327 dstream<<_("Please select one using --worldname <name>"
1328 " or --world <path>")<<std::endl;
1329 print_worldspecs(worldspecs, dstream);
1331 // If there are no worlds, automatically create a new one
1333 // This is the ultimate default world path
1334 world_path = porting::path_user + DIR_DELIM + "worlds" +
1335 DIR_DELIM + "world";
1336 infostream<<"Creating default world at ["
1337 <<world_path<<"]"<<std::endl;
1341 if(world_path == ""){
1342 errorstream<<"No world path specified or found."<<std::endl;
1345 verbosestream<<_("Using world path")<<" ["<<world_path<<"]"<<std::endl;
1347 // We need a gamespec.
1348 SubgameSpec gamespec;
1349 verbosestream<<_("Determining gameid/gamespec")<<std::endl;
1350 // If world doesn't exist
1351 if(!getWorldExists(world_path))
1353 // Try to take gamespec from command line
1354 if(commanded_gamespec.isValid()){
1355 gamespec = commanded_gamespec;
1356 infostream<<"Using commanded gameid ["<<gamespec.id<<"]"<<std::endl;
1358 // Otherwise we will be using "minetest"
1360 gamespec = findSubgame(g_settings->get("default_game"));
1361 infostream<<"Using default gameid ["<<gamespec.id<<"]"<<std::endl;
1367 std::string world_gameid = getWorldGameId(world_path, is_legacy_world);
1368 // If commanded to use a gameid, do so
1369 if(commanded_gamespec.isValid()){
1370 gamespec = commanded_gamespec;
1371 if(commanded_gamespec.id != world_gameid){
1372 errorstream<<"WARNING: Using commanded gameid ["
1373 <<gamespec.id<<"]"<<" instead of world gameid ["
1374 <<world_gameid<<"]"<<std::endl;
1377 // If world contains an embedded game, use it;
1378 // Otherwise find world from local system.
1379 gamespec = findWorldSubgame(world_path);
1380 infostream<<"Using world gameid ["<<gamespec.id<<"]"<<std::endl;
1383 if(!gamespec.isValid()){
1384 errorstream<<"Subgame ["<<gamespec.id<<"] could not be found."
1388 verbosestream<<_("Using gameid")<<" ["<<gamespec.id<<"]"<<std::endl;
1391 Server server(world_path, configpath, gamespec, false);
1395 dedicated_server_loop(server, kill);
1400 #ifndef SERVER // Exclude from dedicated server build
1406 std::string address = g_settings->get("address");
1407 if(commanded_world != "")
1409 else if(cmd_args.exists("address"))
1410 address = cmd_args.get("address");
1412 std::string playername = g_settings->get("name");
1413 if(cmd_args.exists("name"))
1414 playername = cmd_args.get("name");
1416 bool skip_main_menu = cmd_args.getFlag("go");
1419 Device initialization
1422 // Resolution selection
1424 bool fullscreen = g_settings->getBool("fullscreen");
1425 u16 screenW = g_settings->getU16("screenW");
1426 u16 screenH = g_settings->getU16("screenH");
1430 bool vsync = g_settings->getBool("vsync");
1431 u16 bits = g_settings->getU16("fullscreen_bpp");
1432 u16 fsaa = g_settings->getU16("fsaa");
1436 video::E_DRIVER_TYPE driverType;
1438 std::string driverstring = g_settings->get("video_driver");
1440 if(driverstring == "null")
1441 driverType = video::EDT_NULL;
1442 else if(driverstring == "software")
1443 driverType = video::EDT_SOFTWARE;
1444 else if(driverstring == "burningsvideo")
1445 driverType = video::EDT_BURNINGSVIDEO;
1446 else if(driverstring == "direct3d8")
1447 driverType = video::EDT_DIRECT3D8;
1448 else if(driverstring == "direct3d9")
1449 driverType = video::EDT_DIRECT3D9;
1450 else if(driverstring == "opengl")
1451 driverType = video::EDT_OPENGL;
1452 #ifdef _IRR_COMPILE_WITH_OGLES1_
1453 else if(driverstring == "ogles1")
1454 driverType = video::EDT_OGLES1;
1456 #ifdef _IRR_COMPILE_WITH_OGLES2_
1457 else if(driverstring == "ogles2")
1458 driverType = video::EDT_OGLES2;
1462 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1463 "to opengl"<<std::endl;
1464 driverType = video::EDT_OPENGL;
1468 List video modes if requested
1471 MyEventReceiver receiver;
1473 if(cmd_args.getFlag("videomodes")){
1474 IrrlichtDevice *nulldevice;
1476 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1477 params.DriverType = video::EDT_NULL;
1478 params.WindowSize = core::dimension2d<u32>(640, 480);
1480 params.AntiAlias = fsaa;
1481 params.Fullscreen = false;
1482 params.Stencilbuffer = false;
1483 params.Vsync = vsync;
1484 params.EventReceiver = &receiver;
1486 nulldevice = createDeviceEx(params);
1491 dstream<<_("Available video modes (WxHxD):")<<std::endl;
1493 video::IVideoModeList *videomode_list =
1494 nulldevice->getVideoModeList();
1496 if(videomode_list == 0){
1501 s32 videomode_count = videomode_list->getVideoModeCount();
1502 core::dimension2d<u32> videomode_res;
1503 s32 videomode_depth;
1504 for (s32 i = 0; i < videomode_count; ++i){
1505 videomode_res = videomode_list->getVideoModeResolution(i);
1506 videomode_depth = videomode_list->getVideoModeDepth(i);
1507 dstream<<videomode_res.Width<<"x"<<videomode_res.Height
1508 <<"x"<<videomode_depth<<std::endl;
1511 dstream<<_("Active video mode (WxHxD):")<<std::endl;
1512 videomode_res = videomode_list->getDesktopResolution();
1513 videomode_depth = videomode_list->getDesktopDepth();
1514 dstream<<videomode_res.Width<<"x"<<videomode_res.Height
1515 <<"x"<<videomode_depth<<std::endl;
1523 Create device and exit if creation failed
1526 IrrlichtDevice *device;
1528 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1529 params.DriverType = driverType;
1530 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
1532 params.AntiAlias = fsaa;
1533 params.Fullscreen = fullscreen;
1534 params.Stencilbuffer = false;
1535 params.Vsync = vsync;
1536 params.EventReceiver = &receiver;
1538 device = createDeviceEx(params);
1541 return 1; // could not create selected driver.
1544 Continue initialization
1547 video::IVideoDriver* driver = device->getVideoDriver();
1550 This changes the minimum allowed number of vertices in a VBO.
1553 //driver->setMinHardwareBufferVertexCount(50);
1555 // Create time getter
1556 g_timegetter = new IrrlichtTimeGetter(device);
1558 // Create game callback for menus
1559 g_gamecallback = new MainGameCallback(device);
1562 Speed tests (done after irrlicht is loaded to get timer)
1564 if(cmd_args.getFlag("speedtests"))
1566 dstream<<"Running speed tests"<<std::endl;
1572 device->setResizable(true);
1574 bool random_input = g_settings->getBool("random_input")
1575 || cmd_args.getFlag("random-input");
1576 InputHandler *input = NULL;
1578 input = new RandomInputHandler();
1580 input = new RealInputHandler(device, &receiver);
1582 scene::ISceneManager* smgr = device->getSceneManager();
1584 guienv = device->getGUIEnvironment();
1585 gui::IGUISkin* skin = guienv->getSkin();
1587 std::string font_path = g_settings->get("font_path");
1588 u16 font_size = g_settings->getU16("font_size");
1589 gui::IGUIFont *font = gui::CGUITTFont::createTTFont(guienv, font_path.c_str(), font_size);
1591 gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
1594 skin->setFont(font);
1596 errorstream<<"WARNING: Font file was not found."
1597 " Using default font."<<std::endl;
1598 // If font was not found, this will get us one
1599 font = skin->getFont();
1602 u32 text_height = font->getDimension(L"Hello, world!").Height;
1603 infostream<<"text_height="<<text_height<<std::endl;
1605 //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1606 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1607 //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1608 //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1609 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1610 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1611 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50));
1612 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255));
1614 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1615 // Irrlicht 1.8 input colours
1616 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255,128,128,128));
1617 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255,96,134,49));
1621 // Create the menu clouds
1622 if (!g_menucloudsmgr)
1623 g_menucloudsmgr = smgr->createNewSceneManager();
1625 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1626 g_menucloudsmgr, -1, rand(), 100);
1627 g_menuclouds->update(v2f(0, 0), video::SColor(255,200,200,255));
1628 scene::ICameraSceneNode* camera;
1629 camera = g_menucloudsmgr->addCameraSceneNode(0,
1630 v3f(0,0,0), v3f(0, 60, 100));
1631 camera->setFarValue(10000);
1637 ChatBackend chat_backend;
1640 If an error occurs, this is set to something and the
1641 menu-game loop is restarted. It is then displayed before
1644 std::wstring error_message = L"";
1646 // The password entered during the menu screen,
1647 std::string password;
1649 bool first_loop = true;
1654 while(device->run() && kill == false)
1656 // Set the window caption
1657 wchar_t* text = wgettext("Main Menu");
1658 device->setWindowCaption((std::wstring(L"Minetest [")+text+L"]").c_str());
1661 // This is used for catching disconnects
1666 Clear everything from the GUIEnvironment
1671 We need some kind of a root node to be able to add
1672 custom gui elements directly on the screen.
1673 Otherwise they won't be automatically drawn.
1675 guiroot = guienv->addStaticText(L"",
1676 core::rect<s32>(0, 0, 10000, 10000));
1678 SubgameSpec gamespec;
1679 WorldSpec worldspec;
1680 bool simple_singleplayer_mode = false;
1682 // These are set up based on the menu and other things
1683 std::string current_playername = "inv£lid";
1684 std::string current_password = "";
1685 std::string current_address = "does-not-exist";
1686 int current_port = 0;
1689 Out-of-game menu loop.
1691 Loop quits when menu returns proper parameters.
1693 while(kill == false)
1695 // If skip_main_menu, only go through here once
1696 if(skip_main_menu && !first_loop){
1702 // Cursor can be non-visible when coming from the game
1703 device->getCursorControl()->setVisible(true);
1704 // Some stuff are left to scene manager when coming from the game
1708 // Initialize menu data
1709 MainMenuData menudata;
1710 if(g_settings->exists("selected_mainmenu_tab"))
1711 menudata.selected_tab = g_settings->getS32("selected_mainmenu_tab");
1712 if(g_settings->exists("selected_serverlist"))
1713 menudata.selected_serverlist = g_settings->getS32("selected_serverlist");
1714 if(g_settings->exists("selected_mainmenu_game")){
1715 menudata.selected_game = g_settings->get("selected_mainmenu_game");
1716 menudata.selected_game_name = findSubgame(menudata.selected_game).name;
1718 menudata.address = narrow_to_wide(address);
1719 menudata.name = narrow_to_wide(playername);
1720 menudata.port = narrow_to_wide(itos(port));
1721 if(cmd_args.exists("password"))
1722 menudata.password = narrow_to_wide(cmd_args.get("password"));
1723 menudata.fancy_trees = g_settings->getBool("new_style_leaves");
1724 menudata.smooth_lighting = g_settings->getBool("smooth_lighting");
1725 menudata.clouds_3d = g_settings->getBool("enable_3d_clouds");
1726 menudata.opaque_water = g_settings->getBool("opaque_water");
1727 menudata.mip_map = g_settings->getBool("mip_map");
1728 menudata.anisotropic_filter = g_settings->getBool("anisotropic_filter");
1729 menudata.bilinear_filter = g_settings->getBool("bilinear_filter");
1730 menudata.trilinear_filter = g_settings->getBool("trilinear_filter");
1731 menudata.enable_shaders = g_settings->getS32("enable_shaders");
1732 menudata.preload_item_visuals = g_settings->getBool("preload_item_visuals");
1733 menudata.enable_particles = g_settings->getBool("enable_particles");
1734 menudata.liquid_finite = g_settings->getBool("liquid_finite");
1735 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, menudata.mip_map);
1736 menudata.creative_mode = g_settings->getBool("creative_mode");
1737 menudata.enable_damage = g_settings->getBool("enable_damage");
1738 menudata.enable_public = g_settings->getBool("server_announce");
1739 // Default to selecting nothing
1740 menudata.selected_world = -1;
1741 // Get world listing for the menu
1742 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1743 // If there is only one world, select it
1744 if(worldspecs.size() == 1){
1745 menudata.selected_world = 0;
1747 // Otherwise try to select according to selected_world_path
1748 else if(g_settings->exists("selected_world_path")){
1749 std::string trypath = g_settings->get("selected_world_path");
1750 for(u32 i=0; i<worldspecs.size(); i++){
1751 if(worldspecs[i].path == trypath){
1752 menudata.selected_world = i;
1757 // If a world was commanded, append and select it
1758 if(commanded_world != ""){
1759 std::string gameid = getWorldGameId(commanded_world, true);
1760 std::string name = _("[--world parameter]");
1762 gameid = g_settings->get("default_game");
1765 WorldSpec spec(commanded_world, name, gameid);
1766 worldspecs.push_back(spec);
1767 menudata.selected_world = worldspecs.size()-1;
1769 // Copy worldspecs to menu
1770 menudata.worlds = worldspecs;
1772 menudata.games = getAvailableGames();
1773 // If selected game doesn't exist, take first from list
1774 if(findSubgame(menudata.selected_game).id == "" &&
1775 !menudata.games.empty()){
1776 menudata.selected_game = menudata.games[0].id;
1778 const SubgameSpec *menugame = getMenuGame(menudata);
1780 MenuTextures menutextures;
1781 menutextures.update(driver, menugame);
1783 if(skip_main_menu == false)
1785 video::IVideoDriver* driver = device->getVideoDriver();
1786 float fps_max = g_settings->getFloat("fps_max");
1787 infostream<<"Waiting for other menus"<<std::endl;
1788 while(device->run() && kill == false)
1792 driver->beginScene(true, true,
1793 video::SColor(255,128,128,128));
1794 drawMenuBackground(driver, menutextures);
1797 // On some computers framerate doesn't seem to be
1798 // automatically limited
1801 infostream<<"Waited for other menus"<<std::endl;
1804 new GUIMainMenu(guienv, guiroot, -1,
1805 &g_menumgr, &menudata, g_gamecallback);
1806 menu->allowFocusRemoval(true);
1808 if(error_message != L"")
1810 verbosestream<<"error_message = "
1811 <<wide_to_narrow(error_message)<<std::endl;
1813 GUIMessageMenu *menu2 =
1814 new GUIMessageMenu(guienv, guiroot, -1,
1815 &g_menumgr, error_message.c_str());
1817 error_message = L"";
1820 // Time is in milliseconds, for clouds
1821 u32 lasttime = device->getTimer()->getTime();
1823 MenuMusicFetcher soundfetcher;
1824 ISoundManager *sound = NULL;
1825 sound = createOpenALSoundManager(&soundfetcher);
1827 sound = &dummySoundManager;
1828 SimpleSoundSpec spec;
1829 spec.name = "main_menu";
1831 s32 handle = sound->playSound(spec, true);
1833 infostream<<"Created main menu"<<std::endl;
1835 while(device->run() && kill == false)
1837 if(menu->getStatus() == true)
1840 // Game can be selected in the menu
1841 menugame = getMenuGame(menudata);
1842 menutextures.update(driver, menugame);
1843 // Clouds for the main menu
1844 bool cloud_menu_background = g_settings->getBool("menu_clouds");
1846 // If game has regular background and no overlay, don't use clouds
1847 if(cloud_menu_background && menutextures.background &&
1848 !menutextures.overlay){
1849 cloud_menu_background = false;
1851 // If game game has overlay and no regular background, always draw clouds
1852 else if(menutextures.overlay && !menutextures.background){
1853 cloud_menu_background = true;
1857 // Time calc for the clouds
1858 f32 dtime=0; // in seconds
1859 if (cloud_menu_background) {
1860 u32 time = device->getTimer()->getTime();
1862 dtime = (time - lasttime) / 1000.0;
1868 //driver->beginScene(true, true, video::SColor(255,0,0,0));
1869 driver->beginScene(true, true, video::SColor(255,140,186,250));
1871 if (cloud_menu_background) {
1872 // *3 otherwise the clouds would move very slowly
1873 g_menuclouds->step(dtime*3);
1874 g_menuclouds->render();
1875 g_menucloudsmgr->drawAll();
1876 drawMenuOverlay(driver, menutextures);
1877 drawMenuHeader(driver, menutextures);
1878 drawMenuFooter(driver, menutextures);
1880 drawMenuBackground(driver, menutextures);
1881 drawMenuHeader(driver, menutextures);
1882 drawMenuFooter(driver, menutextures);
1889 // On some computers framerate doesn't seem to be
1890 // automatically limited
1891 if (cloud_menu_background) {
1892 // Time of frame without fps limit
1895 // not using getRealTime is necessary for wine
1896 u32 time = device->getTimer()->getTime();
1898 busytime_u32 = time - lasttime;
1901 busytime = busytime_u32 / 1000.0;
1904 u32 frametime_min = 1000./fps_max;
1906 if(busytime_u32 < frametime_min) {
1907 u32 sleeptime = frametime_min - busytime_u32;
1908 device->sleep(sleeptime);
1914 sound->stopSound(handle);
1915 if(sound != &dummySoundManager){
1920 infostream<<"Dropping main menu"<<std::endl;
1925 playername = wide_to_narrow(menudata.name);
1926 if (playername == "")
1927 playername = std::string("Guest") + itos(myrand_range(1000,9999));
1928 password = translatePassword(playername, menudata.password);
1929 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1931 address = wide_to_narrow(menudata.address);
1932 int newport = stoi(wide_to_narrow(menudata.port));
1935 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1937 g_settings->setS32("selected_mainmenu_tab", menudata.selected_tab);
1938 g_settings->setS32("selected_serverlist", menudata.selected_serverlist);
1939 g_settings->set("selected_mainmenu_game", menudata.selected_game);
1940 g_settings->set("new_style_leaves", itos(menudata.fancy_trees));
1941 g_settings->set("smooth_lighting", itos(menudata.smooth_lighting));
1942 g_settings->set("enable_3d_clouds", itos(menudata.clouds_3d));
1943 g_settings->set("opaque_water", itos(menudata.opaque_water));
1945 g_settings->set("mip_map", itos(menudata.mip_map));
1946 g_settings->set("anisotropic_filter", itos(menudata.anisotropic_filter));
1947 g_settings->set("bilinear_filter", itos(menudata.bilinear_filter));
1948 g_settings->set("trilinear_filter", itos(menudata.trilinear_filter));
1950 g_settings->setS32("enable_shaders", menudata.enable_shaders);
1951 g_settings->set("preload_item_visuals", itos(menudata.preload_item_visuals));
1952 g_settings->set("enable_particles", itos(menudata.enable_particles));
1953 g_settings->set("liquid_finite", itos(menudata.liquid_finite));
1955 g_settings->set("creative_mode", itos(menudata.creative_mode));
1956 g_settings->set("enable_damage", itos(menudata.enable_damage));
1957 g_settings->set("server_announce", itos(menudata.enable_public));
1958 g_settings->set("name", playername);
1959 g_settings->set("address", address);
1960 g_settings->set("port", itos(port));
1961 if(menudata.selected_world != -1)
1962 g_settings->set("selected_world_path",
1963 worldspecs[menudata.selected_world].path);
1965 // Break out of menu-game loop to shut down cleanly
1966 if(device->run() == false || kill == true)
1969 current_playername = playername;
1970 current_password = password;
1971 current_address = address;
1972 current_port = port;
1974 // If using simple singleplayer mode, override
1975 if(simple_singleplayer_mode){
1976 current_playername = "singleplayer";
1977 current_password = "";
1978 current_address = "";
1979 current_port = 30011;
1981 else if (address != "")
1983 ServerListSpec server;
1984 server["name"] = menudata.servername;
1985 server["address"] = wide_to_narrow(menudata.address);
1986 server["port"] = wide_to_narrow(menudata.port);
1987 server["description"] = menudata.serverdescription;
1988 ServerList::insert(server);
1991 // Set world path to selected one
1992 if(menudata.selected_world != -1){
1993 worldspec = worldspecs[menudata.selected_world];
1994 infostream<<"Selected world: "<<worldspec.name
1995 <<" ["<<worldspec.path<<"]"<<std::endl;
1998 // Only refresh if so requested
1999 if(menudata.only_refresh){
2000 infostream<<"Refreshing menu"<<std::endl;
2004 // Create new world if requested
2005 if(menudata.create_world_name != L"")
2007 std::string path = porting::path_user + DIR_DELIM
2008 "worlds" + DIR_DELIM
2009 + wide_to_narrow(menudata.create_world_name);
2010 // Create world if it doesn't exist
2011 if(!initializeWorld(path, menudata.create_world_gameid)){
2012 error_message = wgettext("Failed to initialize world");
2013 errorstream<<wide_to_narrow(error_message)<<std::endl;
2016 g_settings->set("selected_world_path", path);
2017 g_settings->set("selected_mainmenu_game", menudata.create_world_gameid);
2022 if(current_address == "")
2024 if(menudata.selected_world == -1){
2025 error_message = wgettext("No world selected and no address "
2026 "provided. Nothing to do.");
2027 errorstream<<wide_to_narrow(error_message)<<std::endl;
2030 // Load gamespec for required game
2031 gamespec = findWorldSubgame(worldspec.path);
2032 if(!gamespec.isValid() && !commanded_gamespec.isValid()){
2033 error_message = wgettext("Could not find or load game \"")
2034 + narrow_to_wide(worldspec.gameid) + L"\"";
2035 errorstream<<wide_to_narrow(error_message)<<std::endl;
2038 if(commanded_gamespec.isValid() &&
2039 commanded_gamespec.id != worldspec.gameid){
2040 errorstream<<"WARNING: Overriding gamespec from \""
2041 <<worldspec.gameid<<"\" to \""
2042 <<commanded_gamespec.id<<"\""<<std::endl;
2043 gamespec = commanded_gamespec;
2046 if(!gamespec.isValid()){
2047 error_message = wgettext("Invalid gamespec.");
2048 error_message += L" (world_gameid="
2049 +narrow_to_wide(worldspec.gameid)+L")";
2050 errorstream<<wide_to_narrow(error_message)<<std::endl;
2059 // Break out of menu-game loop to shut down cleanly
2060 if(device->run() == false || kill == true)
2081 simple_singleplayer_mode
2086 catch(con::PeerNotFoundException &e)
2088 error_message = wgettext("Connection error (timed out?)");
2089 errorstream<<wide_to_narrow(error_message)<<std::endl;
2092 catch(std::exception &e)
2094 std::string narrow_message = "Some exception: \"";
2095 narrow_message += e.what();
2096 narrow_message += "\"";
2097 errorstream<<narrow_message<<std::endl;
2098 error_message = narrow_to_wide(narrow_message);
2102 // If no main menu, show error and exit
2105 if(error_message != L""){
2106 verbosestream<<"error_message = "
2107 <<wide_to_narrow(error_message)<<std::endl;
2115 g_menuclouds->drop();
2116 g_menucloudsmgr->drop();
2121 In the end, delete the Irrlicht device.
2129 // Update configuration file
2130 if(configpath != "")
2131 g_settings->updateConfigFile(configpath.c_str());
2133 // Print modified quicktune values
2135 bool header_printed = false;
2136 std::vector<std::string> names = getQuicktuneNames();
2137 for(u32 i=0; i<names.size(); i++){
2138 QuicktuneValue val = getQuicktuneValue(names[i]);
2141 if(!header_printed){
2142 dstream<<"Modified quicktune values:"<<std::endl;
2143 header_printed = true;
2145 dstream<<names[i]<<" = "<<val.getString()<<std::endl;
2149 END_DEBUG_EXCEPTION_HANDLER(errorstream)
2151 debugstreams_deinit();