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"
81 #include "guiEngine.h"
85 These are loaded from the config file.
87 Settings main_settings;
88 Settings *g_settings = &main_settings;
91 Profiler main_profiler;
92 Profiler *g_profiler = &main_profiler;
94 // Menu clouds are created later
95 Clouds *g_menuclouds = 0;
96 irr::scene::ISceneManager *g_menucloudsmgr = 0;
103 std::ostream *dout_con_ptr = &dummyout;
104 std::ostream *derr_con_ptr = &verbosestream;
107 std::ostream *dout_server_ptr = &infostream;
108 std::ostream *derr_server_ptr = &errorstream;
111 std::ostream *dout_client_ptr = &infostream;
112 std::ostream *derr_client_ptr = &errorstream;
119 /* mainmenumanager.h */
121 gui::IGUIEnvironment* guienv = NULL;
122 gui::IGUIStaticText *guiroot = NULL;
123 MainMenuManager g_menumgr;
127 return (g_menumgr.menuCount() == 0);
130 // Passed to menus to allow disconnecting and exiting
131 MainGameCallback *g_gamecallback = NULL;
135 gettime.h implementation
142 /* Use imprecise system calls directly (from porting.h) */
143 return porting::getTime(PRECISION_MILLI);
146 u32 getTime(TimePrecision prec)
148 return porting::getTime(prec);
153 // A small helper class
157 virtual u32 getTime(TimePrecision prec) = 0;
160 // A precise irrlicht one
161 class IrrlichtTimeGetter: public TimeGetter
164 IrrlichtTimeGetter(IrrlichtDevice *device):
167 u32 getTime(TimePrecision prec)
169 if (prec == PRECISION_MILLI) {
172 return m_device->getTimer()->getRealTime();
174 return porting::getTime(prec);
178 IrrlichtDevice *m_device;
180 // Not so precise one which works without irrlicht
181 class SimpleTimeGetter: public TimeGetter
184 u32 getTime(TimePrecision prec)
186 return porting::getTime(prec);
190 // A pointer to a global instance of the time getter
192 TimeGetter *g_timegetter = NULL;
196 if(g_timegetter == NULL)
198 return g_timegetter->getTime(PRECISION_MILLI);
201 u32 getTime(TimePrecision prec) {
202 if (g_timegetter == NULL)
204 return g_timegetter->getTime(prec);
208 //Client side main menu music fetcher
210 class MenuMusicFetcher: public OnDemandSoundFetcher
212 std::set<std::string> m_fetched;
215 void fetchSounds(const std::string &name,
216 std::set<std::string> &dst_paths,
217 std::set<std::string> &dst_datas)
219 if(m_fetched.count(name))
221 m_fetched.insert(name);
223 base = porting::path_share + DIR_DELIM + "sounds";
224 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
225 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
226 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
227 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
228 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
229 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
230 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
231 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
232 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
233 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
234 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
235 base = porting::path_user + DIR_DELIM + "sounds";
236 dst_paths.insert(base + DIR_DELIM + name + ".ogg");
237 dst_paths.insert(base + DIR_DELIM + name + ".0.ogg");
238 dst_paths.insert(base + DIR_DELIM + name + ".1.ogg");
239 dst_paths.insert(base + DIR_DELIM + name + ".2.ogg");
240 dst_paths.insert(base + DIR_DELIM + name + ".3.ogg");
241 dst_paths.insert(base + DIR_DELIM + name + ".4.ogg");
242 dst_paths.insert(base + DIR_DELIM + name + ".5.ogg");
243 dst_paths.insert(base + DIR_DELIM + name + ".6.ogg");
244 dst_paths.insert(base + DIR_DELIM + name + ".7.ogg");
245 dst_paths.insert(base + DIR_DELIM + name + ".8.ogg");
246 dst_paths.insert(base + DIR_DELIM + name + ".9.ogg");
251 class StderrLogOutput: public ILogOutput
254 /* line: Full line with timestamp, level and thread */
255 void printLog(const std::string &line)
257 std::cerr<<line<<std::endl;
259 } main_stderr_log_out;
261 class DstreamNoStderrLogOutput: public ILogOutput
264 /* line: Full line with timestamp, level and thread */
265 void printLog(const std::string &line)
267 dstream_no_stderr<<line<<std::endl;
269 } main_dstream_no_stderr_log_out;
274 Event handler for Irrlicht
276 NOTE: Everything possible should be moved out from here,
277 probably to InputHandler and the_game
280 class MyEventReceiver : public IEventReceiver
283 // This is the one method that we have to implement
284 virtual bool OnEvent(const SEvent& event)
287 React to nothing here if a menu is active
289 if(noMenuActive() == false)
294 // Remember whether each key is down or up
295 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
297 if(event.KeyInput.PressedDown) {
298 keyIsDown.set(event.KeyInput);
299 keyWasDown.set(event.KeyInput);
301 keyIsDown.unset(event.KeyInput);
305 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
307 if(noMenuActive() == false)
310 middle_active = false;
311 right_active = false;
315 left_active = event.MouseInput.isLeftPressed();
316 middle_active = event.MouseInput.isMiddlePressed();
317 right_active = event.MouseInput.isRightPressed();
319 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
323 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
327 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
331 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
333 rightreleased = true;
335 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
337 mouse_wheel += event.MouseInput.Wheel;
345 bool IsKeyDown(const KeyPress &keyCode) const
347 return keyIsDown[keyCode];
350 // Checks whether a key was down and resets the state
351 bool WasKeyDown(const KeyPress &keyCode)
353 bool b = keyWasDown[keyCode];
355 keyWasDown.unset(keyCode);
372 rightclicked = false;
373 leftreleased = false;
374 rightreleased = false;
377 middle_active = false;
378 right_active = false;
400 IrrlichtDevice *m_device;
402 // The current state of keys
404 // Whether a key has been pressed or not
409 Separated input handler
412 class RealInputHandler : public InputHandler
415 RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
420 virtual bool isKeyDown(const KeyPress &keyCode)
422 return m_receiver->IsKeyDown(keyCode);
424 virtual bool wasKeyDown(const KeyPress &keyCode)
426 return m_receiver->WasKeyDown(keyCode);
428 virtual v2s32 getMousePos()
430 return m_device->getCursorControl()->getPosition();
432 virtual void setMousePos(s32 x, s32 y)
434 m_device->getCursorControl()->setPosition(x, y);
437 virtual bool getLeftState()
439 return m_receiver->left_active;
441 virtual bool getRightState()
443 return m_receiver->right_active;
446 virtual bool getLeftClicked()
448 return m_receiver->leftclicked;
450 virtual bool getRightClicked()
452 return m_receiver->rightclicked;
454 virtual void resetLeftClicked()
456 m_receiver->leftclicked = false;
458 virtual void resetRightClicked()
460 m_receiver->rightclicked = false;
463 virtual bool getLeftReleased()
465 return m_receiver->leftreleased;
467 virtual bool getRightReleased()
469 return m_receiver->rightreleased;
471 virtual void resetLeftReleased()
473 m_receiver->leftreleased = false;
475 virtual void resetRightReleased()
477 m_receiver->rightreleased = false;
480 virtual s32 getMouseWheel()
482 return m_receiver->getMouseWheel();
487 m_receiver->clearInput();
490 IrrlichtDevice *m_device;
491 MyEventReceiver *m_receiver;
494 class RandomInputHandler : public InputHandler
502 rightclicked = false;
503 leftreleased = false;
504 rightreleased = false;
507 virtual bool isKeyDown(const KeyPress &keyCode)
509 return keydown[keyCode];
511 virtual bool wasKeyDown(const KeyPress &keyCode)
515 virtual v2s32 getMousePos()
519 virtual void setMousePos(s32 x, s32 y)
521 mousepos = v2s32(x,y);
524 virtual bool getLeftState()
528 virtual bool getRightState()
533 virtual bool getLeftClicked()
537 virtual bool getRightClicked()
541 virtual void resetLeftClicked()
545 virtual void resetRightClicked()
547 rightclicked = false;
550 virtual bool getLeftReleased()
554 virtual bool getRightReleased()
556 return rightreleased;
558 virtual void resetLeftReleased()
560 leftreleased = false;
562 virtual void resetRightReleased()
564 rightreleased = false;
567 virtual s32 getMouseWheel()
572 virtual void step(float dtime)
575 static float counter1 = 0;
579 counter1 = 0.1*Rand(1, 40);
580 keydown.toggle(getKeySetting("keymap_jump"));
584 static float counter1 = 0;
588 counter1 = 0.1*Rand(1, 40);
589 keydown.toggle(getKeySetting("keymap_special1"));
593 static float counter1 = 0;
597 counter1 = 0.1*Rand(1, 40);
598 keydown.toggle(getKeySetting("keymap_forward"));
602 static float counter1 = 0;
606 counter1 = 0.1*Rand(1, 40);
607 keydown.toggle(getKeySetting("keymap_left"));
611 static float counter1 = 0;
615 counter1 = 0.1*Rand(1, 20);
616 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
620 static float counter1 = 0;
624 counter1 = 0.1*Rand(1, 30);
625 leftdown = !leftdown;
633 static float counter1 = 0;
637 counter1 = 0.1*Rand(1, 15);
638 rightdown = !rightdown;
642 rightreleased = true;
645 mousepos += mousespeed;
648 s32 Rand(s32 min, s32 max)
650 return (myrand()%(max-min+1))+min;
666 // These are defined global so that they're not optimized too much.
667 // Can't change them to volatile.
672 std::string tempstring;
673 std::string tempstring2;
678 infostream<<"The following test should take around 20ms."<<std::endl;
679 TimeTaker timer("Testing std::string speed");
680 const u32 jj = 10000;
681 for(u32 j=0; j<jj; j++)
686 for(u32 i=0; i<ii; i++){
687 tempstring2 += "asd";
689 for(u32 i=0; i<ii+1; i++){
691 if(tempstring == tempstring2)
697 infostream<<"All of the following tests should take around 100ms each."
701 TimeTaker timer("Testing floating-point conversion speed");
703 for(u32 i=0; i<4000000; i++){
710 TimeTaker timer("Testing floating-point vector speed");
712 tempv3f1 = v3f(1,2,3);
713 tempv3f2 = v3f(4,5,6);
714 for(u32 i=0; i<10000000; i++){
715 tempf += tempv3f1.dotProduct(tempv3f2);
716 tempv3f2 += v3f(7,8,9);
721 TimeTaker timer("Testing std::map speed");
723 std::map<v2s16, f32> map1;
726 for(s16 y=0; y<ii; y++){
727 for(s16 x=0; x<ii; x++){
728 map1[v2s16(x,y)] = tempf;
732 for(s16 y=ii-1; y>=0; y--){
733 for(s16 x=0; x<ii; x++){
734 tempf = map1[v2s16(x,y)];
740 infostream<<"Around 5000/ms should do well here."<<std::endl;
741 TimeTaker timer("Testing mutex speed");
755 while(timer.getTimerTime() < 10);
757 u32 dtime = timer.stop();
758 u32 per_ms = n / dtime;
759 infostream<<"Done. "<<dtime<<"ms, "
760 <<per_ms<<"/ms"<<std::endl;
764 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
767 for(u32 i=0; i<worldspecs.size(); i++){
768 std::string name = worldspecs[i].name;
769 std::string path = worldspecs[i].path;
770 if(name.find(" ") != std::string::npos)
771 name = std::string("'") + name + "'";
772 path = std::string("'") + path + "'";
773 name = padStringRight(name, 14);
774 os<<" "<<name<<" "<<path<<std::endl;
778 int main(int argc, char *argv[])
786 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
787 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
789 log_register_thread("main");
791 // This enables internatonal characters input
792 if( setlocale(LC_ALL, "") == NULL )
794 fprintf( stderr, "%s: warning: could not set default locale\n", argv[0] );
797 // Set locale. This is for forcing '.' as the decimal point.
799 std::locale::global(std::locale(std::locale(""), "C", std::locale::numeric));
800 setlocale(LC_NUMERIC, "C");
801 } catch (const std::exception& ex) {
802 errorstream<<"Could not set numeric locale to C"<<std::endl;
808 // List all allowed options
809 std::map<std::string, ValueSpec> allowed_options;
810 allowed_options.insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
811 _("Show allowed options"))));
812 allowed_options.insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
813 _("Load configuration from specified file"))));
814 allowed_options.insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
815 _("Set network port (UDP)"))));
816 allowed_options.insert(std::make_pair("disable-unittests", ValueSpec(VALUETYPE_FLAG,
817 _("Disable unit tests"))));
818 allowed_options.insert(std::make_pair("enable-unittests", ValueSpec(VALUETYPE_FLAG,
819 _("Enable unit tests"))));
820 allowed_options.insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
821 _("Same as --world (deprecated)"))));
822 allowed_options.insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
823 _("Set world path (implies local game) ('list' lists all)"))));
824 allowed_options.insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
825 _("Set world by name (implies local game)"))));
826 allowed_options.insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
827 _("Print more information to console"))));
828 allowed_options.insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
829 _("Print even more information to console"))));
830 allowed_options.insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
831 _("Print enormous amounts of information to log and console"))));
832 allowed_options.insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
833 _("Set logfile path ('' = no logging)"))));
834 allowed_options.insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
835 _("Set gameid (\"--gameid list\" prints available ones)"))));
837 allowed_options.insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
838 _("Show available video modes"))));
839 allowed_options.insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
840 _("Run speed tests"))));
841 allowed_options.insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
842 _("Address to connect to. ('' = local game)"))));
843 allowed_options.insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
844 _("Enable random user input, for testing"))));
845 allowed_options.insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
846 _("Run dedicated server"))));
847 allowed_options.insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
848 _("Set player name"))));
849 allowed_options.insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
850 _("Set password"))));
851 allowed_options.insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
852 _("Disable main menu"))));
857 bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
859 if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1"))
861 dstream<<_("Allowed options:")<<std::endl;
862 for(std::map<std::string, ValueSpec>::iterator
863 i = allowed_options.begin();
864 i != allowed_options.end(); ++i)
866 std::ostringstream os1(std::ios::binary);
867 os1<<" --"<<i->first;
868 if(i->second.type == VALUETYPE_FLAG)
872 dstream<<padStringRight(os1.str(), 24);
874 if(i->second.help != NULL)
875 dstream<<i->second.help;
879 return cmd_args.getFlag("help") ? 0 : 1;
883 Low-level initialization
886 // If trace is enabled, enable logging of certain things
887 if(cmd_args.getFlag("trace")){
888 dstream<<_("Enabling trace level debug output")<<std::endl;
889 log_trace_level_enabled = true;
890 dout_con_ptr = &verbosestream; // this is somewhat old crap
891 socket_enable_debug_output = true; // socket doesn't use log.h
893 // In certain cases, output info level on stderr
894 if(cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
895 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
896 log_add_output(&main_stderr_log_out, LMT_INFO);
897 // In certain cases, output verbose level on stderr
898 if(cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
899 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
901 porting::signal_handler_init();
902 bool &kill = *porting::signal_handler_killstatus();
904 porting::initializePaths();
906 // Create user data directory
907 fs::CreateDir(porting::path_user);
909 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str());
911 infostream<<"path_share = "<<porting::path_share<<std::endl;
912 infostream<<"path_user = "<<porting::path_user<<std::endl;
914 // Initialize debug stacks
916 DSTACK(__FUNCTION_NAME);
919 BEGIN_DEBUG_EXCEPTION_HANDLER
921 // List gameids if requested
922 if(cmd_args.exists("gameid") && cmd_args.get("gameid") == "list")
924 std::set<std::string> gameids = getAvailableGameIds();
925 for(std::set<std::string>::const_iterator i = gameids.begin();
926 i != gameids.end(); i++)
927 dstream<<(*i)<<std::endl;
931 // List worlds if requested
932 if(cmd_args.exists("world") && cmd_args.get("world") == "list"){
933 dstream<<_("Available worlds:")<<std::endl;
934 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
935 print_worldspecs(worldspecs, dstream);
939 // Print startup message
940 infostream<<PROJECT_NAME<<
941 " "<<_("with")<<" SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
949 // Initialize default settings
950 set_default_settings(g_settings);
952 // Initialize sockets
954 atexit(sockets_cleanup);
960 // Path of configuration file in use
961 std::string configpath = "";
963 if(cmd_args.exists("config"))
965 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
968 errorstream<<"Could not read configuration from \""
969 <<cmd_args.get("config")<<"\""<<std::endl;
972 configpath = cmd_args.get("config");
976 std::vector<std::string> filenames;
977 filenames.push_back(porting::path_user +
978 DIR_DELIM + "minetest.conf");
979 // Legacy configuration file location
980 filenames.push_back(porting::path_user +
981 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
983 // Try also from a lower level (to aid having the same configuration
984 // for many RUN_IN_PLACE installs)
985 filenames.push_back(porting::path_user +
986 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
989 for(u32 i=0; i<filenames.size(); i++)
991 bool r = g_settings->readConfigFile(filenames[i].c_str());
994 configpath = filenames[i];
999 // If no path found, use the first one (menu creates the file)
1000 if(configpath == "")
1001 configpath = filenames[0];
1004 // Initialize debug streams
1005 #define DEBUGFILE "debug.txt"
1007 std::string logfile = DEBUGFILE;
1009 std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE;
1011 if(cmd_args.exists("logfile"))
1012 logfile = cmd_args.get("logfile");
1014 log_remove_output(&main_dstream_no_stderr_log_out);
1015 int loglevel = g_settings->getS32("debug_log_level");
1017 if (loglevel == 0) //no logging
1019 else if (loglevel > 0 && loglevel <= LMT_NUM_VALUES)
1020 log_add_output_maxlev(&main_dstream_no_stderr_log_out, (LogMessageLevel)(loglevel - 1));
1023 debugstreams_init(false, logfile.c_str());
1025 debugstreams_init(false, NULL);
1027 infostream<<"logfile = "<<logfile<<std::endl;
1029 // Initialize random seed
1037 if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
1038 || cmd_args.getFlag("enable-unittests") == true)
1049 if(cmd_args.exists("port"))
1050 port = cmd_args.getU16("port");
1051 else if(g_settings->exists("port"))
1052 port = g_settings->getU16("port");
1057 std::string commanded_world = "";
1058 if(cmd_args.exists("world"))
1059 commanded_world = cmd_args.get("world");
1060 else if(cmd_args.exists("map-dir"))
1061 commanded_world = cmd_args.get("map-dir");
1062 else if(cmd_args.exists("nonopt0")) // First nameless argument
1063 commanded_world = cmd_args.get("nonopt0");
1064 else if(g_settings->exists("map-dir"))
1065 commanded_world = g_settings->get("map-dir");
1068 std::string commanded_worldname = "";
1069 if(cmd_args.exists("worldname"))
1070 commanded_worldname = cmd_args.get("worldname");
1072 // Strip world.mt from commanded_world
1074 std::string worldmt = "world.mt";
1075 if(commanded_world.size() > worldmt.size() &&
1076 commanded_world.substr(commanded_world.size()-worldmt.size())
1078 dstream<<_("Supplied world.mt file - stripping it off.")<<std::endl;
1079 commanded_world = commanded_world.substr(
1080 0, commanded_world.size()-worldmt.size());
1084 // If a world name was specified, convert it to a path
1085 if(commanded_worldname != ""){
1086 // Get information about available worlds
1087 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1089 for(u32 i=0; i<worldspecs.size(); i++){
1090 std::string name = worldspecs[i].name;
1091 if(name == commanded_worldname){
1092 if(commanded_world != ""){
1093 dstream<<_("--worldname takes precedence over previously "
1094 "selected world.")<<std::endl;
1096 commanded_world = worldspecs[i].path;
1102 dstream<<_("World")<<" '"<<commanded_worldname<<_("' not "
1103 "available. Available worlds:")<<std::endl;
1104 print_worldspecs(worldspecs, dstream);
1110 SubgameSpec commanded_gamespec;
1111 if(cmd_args.exists("gameid")){
1112 std::string gameid = cmd_args.get("gameid");
1113 commanded_gamespec = findSubgame(gameid);
1114 if(!commanded_gamespec.isValid()){
1115 errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl;
1121 Run dedicated server if asked to or no other option
1124 bool run_dedicated_server = true;
1126 bool run_dedicated_server = cmd_args.getFlag("server");
1128 g_settings->set("server_dedicated", run_dedicated_server ? "true" : "false");
1129 if(run_dedicated_server)
1131 DSTACK("Dedicated server branch");
1132 // Create time getter if built with Irrlicht
1134 g_timegetter = new SimpleTimeGetter();
1138 std::string world_path;
1139 verbosestream<<_("Determining world path")<<std::endl;
1140 bool is_legacy_world = false;
1141 // If a world was commanded, use it
1142 if(commanded_world != ""){
1143 world_path = commanded_world;
1144 infostream<<"Using commanded world path ["<<world_path<<"]"
1147 // No world was specified; try to select it automatically
1150 // Get information about available worlds
1151 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1152 // If a world name was specified, select it
1153 if(commanded_worldname != ""){
1155 for(u32 i=0; i<worldspecs.size(); i++){
1156 std::string name = worldspecs[i].name;
1157 if(name == commanded_worldname){
1158 world_path = worldspecs[i].path;
1162 if(world_path == ""){
1163 dstream<<_("World")<<" '"<<commanded_worldname<<"' "<<_("not "
1164 "available. Available worlds:")<<std::endl;
1165 print_worldspecs(worldspecs, dstream);
1169 // If there is only a single world, use it
1170 if(worldspecs.size() == 1){
1171 world_path = worldspecs[0].path;
1172 dstream<<_("Automatically selecting world at")<<" ["
1173 <<world_path<<"]"<<std::endl;
1174 // If there are multiple worlds, list them
1175 } else if(worldspecs.size() > 1){
1176 dstream<<_("Multiple worlds are available.")<<std::endl;
1177 dstream<<_("Please select one using --worldname <name>"
1178 " or --world <path>")<<std::endl;
1179 print_worldspecs(worldspecs, dstream);
1181 // If there are no worlds, automatically create a new one
1183 // This is the ultimate default world path
1184 world_path = porting::path_user + DIR_DELIM + "worlds" +
1185 DIR_DELIM + "world";
1186 infostream<<"Creating default world at ["
1187 <<world_path<<"]"<<std::endl;
1191 if(world_path == ""){
1192 errorstream<<"No world path specified or found."<<std::endl;
1195 verbosestream<<_("Using world path")<<" ["<<world_path<<"]"<<std::endl;
1197 // We need a gamespec.
1198 SubgameSpec gamespec;
1199 verbosestream<<_("Determining gameid/gamespec")<<std::endl;
1200 // If world doesn't exist
1201 if(!getWorldExists(world_path))
1203 // Try to take gamespec from command line
1204 if(commanded_gamespec.isValid()){
1205 gamespec = commanded_gamespec;
1206 infostream<<"Using commanded gameid ["<<gamespec.id<<"]"<<std::endl;
1208 // Otherwise we will be using "minetest"
1210 gamespec = findSubgame(g_settings->get("default_game"));
1211 infostream<<"Using default gameid ["<<gamespec.id<<"]"<<std::endl;
1217 std::string world_gameid = getWorldGameId(world_path, is_legacy_world);
1218 // If commanded to use a gameid, do so
1219 if(commanded_gamespec.isValid()){
1220 gamespec = commanded_gamespec;
1221 if(commanded_gamespec.id != world_gameid){
1222 errorstream<<"WARNING: Using commanded gameid ["
1223 <<gamespec.id<<"]"<<" instead of world gameid ["
1224 <<world_gameid<<"]"<<std::endl;
1227 // If world contains an embedded game, use it;
1228 // Otherwise find world from local system.
1229 gamespec = findWorldSubgame(world_path);
1230 infostream<<"Using world gameid ["<<gamespec.id<<"]"<<std::endl;
1233 if(!gamespec.isValid()){
1234 errorstream<<"Subgame ["<<gamespec.id<<"] could not be found."
1238 verbosestream<<_("Using gameid")<<" ["<<gamespec.id<<"]"<<std::endl;
1241 Server server(world_path, configpath, gamespec, false);
1245 dedicated_server_loop(server, kill);
1250 #ifndef SERVER // Exclude from dedicated server build
1256 std::string address = g_settings->get("address");
1257 if(commanded_world != "")
1259 else if(cmd_args.exists("address"))
1260 address = cmd_args.get("address");
1262 std::string playername = g_settings->get("name");
1263 if(cmd_args.exists("name"))
1264 playername = cmd_args.get("name");
1266 bool skip_main_menu = cmd_args.getFlag("go");
1269 Device initialization
1272 // Resolution selection
1274 bool fullscreen = g_settings->getBool("fullscreen");
1275 u16 screenW = g_settings->getU16("screenW");
1276 u16 screenH = g_settings->getU16("screenH");
1280 bool vsync = g_settings->getBool("vsync");
1281 u16 bits = g_settings->getU16("fullscreen_bpp");
1282 u16 fsaa = g_settings->getU16("fsaa");
1286 video::E_DRIVER_TYPE driverType;
1288 std::string driverstring = g_settings->get("video_driver");
1290 if(driverstring == "null")
1291 driverType = video::EDT_NULL;
1292 else if(driverstring == "software")
1293 driverType = video::EDT_SOFTWARE;
1294 else if(driverstring == "burningsvideo")
1295 driverType = video::EDT_BURNINGSVIDEO;
1296 else if(driverstring == "direct3d8")
1297 driverType = video::EDT_DIRECT3D8;
1298 else if(driverstring == "direct3d9")
1299 driverType = video::EDT_DIRECT3D9;
1300 else if(driverstring == "opengl")
1301 driverType = video::EDT_OPENGL;
1302 #ifdef _IRR_COMPILE_WITH_OGLES1_
1303 else if(driverstring == "ogles1")
1304 driverType = video::EDT_OGLES1;
1306 #ifdef _IRR_COMPILE_WITH_OGLES2_
1307 else if(driverstring == "ogles2")
1308 driverType = video::EDT_OGLES2;
1312 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1313 "to opengl"<<std::endl;
1314 driverType = video::EDT_OPENGL;
1318 List video modes if requested
1321 MyEventReceiver receiver;
1323 if(cmd_args.getFlag("videomodes")){
1324 IrrlichtDevice *nulldevice;
1326 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1327 params.DriverType = video::EDT_NULL;
1328 params.WindowSize = core::dimension2d<u32>(640, 480);
1330 params.AntiAlias = fsaa;
1331 params.Fullscreen = false;
1332 params.Stencilbuffer = false;
1333 params.Vsync = vsync;
1334 params.EventReceiver = &receiver;
1336 nulldevice = createDeviceEx(params);
1341 dstream<<_("Available video modes (WxHxD):")<<std::endl;
1343 video::IVideoModeList *videomode_list =
1344 nulldevice->getVideoModeList();
1346 if(videomode_list == 0){
1351 s32 videomode_count = videomode_list->getVideoModeCount();
1352 core::dimension2d<u32> videomode_res;
1353 s32 videomode_depth;
1354 for (s32 i = 0; i < videomode_count; ++i){
1355 videomode_res = videomode_list->getVideoModeResolution(i);
1356 videomode_depth = videomode_list->getVideoModeDepth(i);
1357 dstream<<videomode_res.Width<<"x"<<videomode_res.Height
1358 <<"x"<<videomode_depth<<std::endl;
1361 dstream<<_("Active video mode (WxHxD):")<<std::endl;
1362 videomode_res = videomode_list->getDesktopResolution();
1363 videomode_depth = videomode_list->getDesktopDepth();
1364 dstream<<videomode_res.Width<<"x"<<videomode_res.Height
1365 <<"x"<<videomode_depth<<std::endl;
1373 Create device and exit if creation failed
1376 IrrlichtDevice *device;
1378 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1379 params.DriverType = driverType;
1380 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
1382 params.AntiAlias = fsaa;
1383 params.Fullscreen = fullscreen;
1384 params.Stencilbuffer = false;
1385 params.Vsync = vsync;
1386 params.EventReceiver = &receiver;
1388 device = createDeviceEx(params);
1391 return 1; // could not create selected driver.
1394 Continue initialization
1397 video::IVideoDriver* driver = device->getVideoDriver();
1400 This changes the minimum allowed number of vertices in a VBO.
1403 //driver->setMinHardwareBufferVertexCount(50);
1405 // Create time getter
1406 g_timegetter = new IrrlichtTimeGetter(device);
1408 // Create game callback for menus
1409 g_gamecallback = new MainGameCallback(device);
1412 Speed tests (done after irrlicht is loaded to get timer)
1414 if(cmd_args.getFlag("speedtests"))
1416 dstream<<"Running speed tests"<<std::endl;
1422 device->setResizable(true);
1424 bool random_input = g_settings->getBool("random_input")
1425 || cmd_args.getFlag("random-input");
1426 InputHandler *input = NULL;
1428 input = new RandomInputHandler();
1430 input = new RealInputHandler(device, &receiver);
1432 scene::ISceneManager* smgr = device->getSceneManager();
1434 guienv = device->getGUIEnvironment();
1435 gui::IGUISkin* skin = guienv->getSkin();
1437 std::string font_path = g_settings->get("font_path");
1438 u16 font_size = g_settings->getU16("font_size");
1439 gui::IGUIFont *font = gui::CGUITTFont::createTTFont(guienv, font_path.c_str(), font_size);
1441 gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
1444 skin->setFont(font);
1446 errorstream<<"WARNING: Font file was not found."
1447 " Using default font."<<std::endl;
1448 // If font was not found, this will get us one
1449 font = skin->getFont();
1452 u32 text_height = font->getDimension(L"Hello, world!").Height;
1453 infostream<<"text_height="<<text_height<<std::endl;
1455 //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1456 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1457 //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1458 //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1459 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1460 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1461 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50));
1462 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255));
1464 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1465 // Irrlicht 1.8 input colours
1466 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255,128,128,128));
1467 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255,96,134,49));
1471 // Create the menu clouds
1472 if (!g_menucloudsmgr)
1473 g_menucloudsmgr = smgr->createNewSceneManager();
1475 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1476 g_menucloudsmgr, -1, rand(), 100);
1477 g_menuclouds->update(v2f(0, 0), video::SColor(255,200,200,255));
1478 scene::ICameraSceneNode* camera;
1479 camera = g_menucloudsmgr->addCameraSceneNode(0,
1480 v3f(0,0,0), v3f(0, 60, 100));
1481 camera->setFarValue(10000);
1487 ChatBackend chat_backend;
1490 If an error occurs, this is set to something and the
1491 menu-game loop is restarted. It is then displayed before
1494 std::wstring error_message = L"";
1496 // The password entered during the menu screen,
1497 std::string password;
1499 bool first_loop = true;
1504 while(device->run() && kill == false)
1506 // Set the window caption
1507 wchar_t* text = wgettext("Main Menu");
1508 device->setWindowCaption((std::wstring(L"Minetest [")+text+L"]").c_str());
1511 // This is used for catching disconnects
1516 Clear everything from the GUIEnvironment
1521 We need some kind of a root node to be able to add
1522 custom gui elements directly on the screen.
1523 Otherwise they won't be automatically drawn.
1525 guiroot = guienv->addStaticText(L"",
1526 core::rect<s32>(0, 0, 10000, 10000));
1528 SubgameSpec gamespec;
1529 WorldSpec worldspec;
1530 bool simple_singleplayer_mode = false;
1532 // These are set up based on the menu and other things
1533 std::string current_playername = "inv£lid";
1534 std::string current_password = "";
1535 std::string current_address = "does-not-exist";
1536 int current_port = 0;
1539 Out-of-game menu loop.
1541 Loop quits when menu returns proper parameters.
1543 while(kill == false)
1545 // If skip_main_menu, only go through here once
1546 if(skip_main_menu && !first_loop){
1552 // Cursor can be non-visible when coming from the game
1553 device->getCursorControl()->setVisible(true);
1554 // Some stuff are left to scene manager when coming from the game
1558 // Initialize menu data
1559 MainMenuData menudata;
1560 menudata.kill = kill;
1561 menudata.address = address;
1562 menudata.name = playername;
1563 menudata.port = itos(port);
1564 menudata.errormessage = wide_to_narrow(error_message);
1565 error_message = L"";
1566 if(cmd_args.exists("password"))
1567 menudata.password = cmd_args.get("password");
1569 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
1571 menudata.enable_public = g_settings->getBool("server_announce");
1573 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1575 // If a world was commanded, append and select it
1576 if(commanded_world != ""){
1578 std::string gameid = getWorldGameId(commanded_world, true);
1579 std::string name = _("[--world parameter]");
1581 gameid = g_settings->get("default_game");
1584 //TODO find within worldspecs and set config
1587 if(skip_main_menu == false)
1589 video::IVideoDriver* driver = device->getVideoDriver();
1591 infostream<<"Waiting for other menus"<<std::endl;
1592 while(device->run() && kill == false)
1596 driver->beginScene(true, true,
1597 video::SColor(255,128,128,128));
1600 // On some computers framerate doesn't seem to be
1601 // automatically limited
1604 infostream<<"Waited for other menus"<<std::endl;
1606 GUIEngine* temp = new GUIEngine(device, guiroot, &g_menumgr,smgr,&menudata);
1609 //once finished you'll never end up here
1611 kill = menudata.kill;
1615 //update worldspecs (necessary as new world may have been created)
1616 worldspecs = getAvailableWorlds();
1618 if (menudata.name == "")
1619 menudata.name = std::string("Guest") + itos(myrand_range(1000,9999));
1621 playername = menudata.name;
1623 password = translatePassword(playername, narrow_to_wide(menudata.password));
1624 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1626 address = menudata.address;
1627 int newport = stoi(menudata.port);
1631 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1634 g_settings->set("name", playername);
1635 g_settings->set("address", address);
1636 g_settings->set("port", itos(port));
1638 if((menudata.selected_world >= 0) &&
1639 (menudata.selected_world < worldspecs.size()))
1640 g_settings->set("selected_world_path",
1641 worldspecs[menudata.selected_world].path);
1643 // Break out of menu-game loop to shut down cleanly
1644 if(device->run() == false || kill == true)
1647 current_playername = playername;
1648 current_password = password;
1649 current_address = address;
1650 current_port = port;
1652 // If using simple singleplayer mode, override
1653 if(simple_singleplayer_mode){
1654 current_playername = "singleplayer";
1655 current_password = "";
1656 current_address = "";
1657 current_port = myrand_range(49152, 65535);
1659 else if (address != "")
1661 ServerListSpec server;
1662 server["name"] = menudata.servername;
1663 server["address"] = menudata.address;
1664 server["port"] = menudata.port;
1665 server["description"] = menudata.serverdescription;
1666 ServerList::insert(server);
1669 // Set world path to selected one
1670 if ((menudata.selected_world >= 0) &&
1671 (menudata.selected_world < worldspecs.size())) {
1672 worldspec = worldspecs[menudata.selected_world];
1673 infostream<<"Selected world: "<<worldspec.name
1674 <<" ["<<worldspec.path<<"]"<<std::endl;
1678 if(current_address == "")
1680 if(menudata.selected_world == -1){
1681 error_message = wgettext("No world selected and no address "
1682 "provided. Nothing to do.");
1683 errorstream<<wide_to_narrow(error_message)<<std::endl;
1686 // Load gamespec for required game
1687 gamespec = findWorldSubgame(worldspec.path);
1688 if(!gamespec.isValid() && !commanded_gamespec.isValid()){
1689 error_message = wgettext("Could not find or load game \"")
1690 + narrow_to_wide(worldspec.gameid) + L"\"";
1691 errorstream<<wide_to_narrow(error_message)<<std::endl;
1694 if(commanded_gamespec.isValid() &&
1695 commanded_gamespec.id != worldspec.gameid){
1696 errorstream<<"WARNING: Overriding gamespec from \""
1697 <<worldspec.gameid<<"\" to \""
1698 <<commanded_gamespec.id<<"\""<<std::endl;
1699 gamespec = commanded_gamespec;
1702 if(!gamespec.isValid()){
1703 error_message = wgettext("Invalid gamespec.");
1704 error_message += L" (world_gameid="
1705 +narrow_to_wide(worldspec.gameid)+L")";
1706 errorstream<<wide_to_narrow(error_message)<<std::endl;
1715 // Break out of menu-game loop to shut down cleanly
1716 if(device->run() == false || kill == true) {
1717 g_settings->updateConfigFile(configpath.c_str());
1739 simple_singleplayer_mode
1744 catch(con::PeerNotFoundException &e)
1746 error_message = wgettext("Connection error (timed out?)");
1747 errorstream<<wide_to_narrow(error_message)<<std::endl;
1750 catch(std::exception &e)
1752 std::string narrow_message = "Some exception: \"";
1753 narrow_message += e.what();
1754 narrow_message += "\"";
1755 errorstream<<narrow_message<<std::endl;
1756 error_message = narrow_to_wide(narrow_message);
1760 // If no main menu, show error and exit
1763 if(error_message != L""){
1764 verbosestream<<"error_message = "
1765 <<wide_to_narrow(error_message)<<std::endl;
1773 g_menuclouds->drop();
1774 g_menucloudsmgr->drop();
1779 In the end, delete the Irrlicht device.
1789 // Update configuration file
1790 if(configpath != "")
1791 g_settings->updateConfigFile(configpath.c_str());
1793 // Print modified quicktune values
1795 bool header_printed = false;
1796 std::vector<std::string> names = getQuicktuneNames();
1797 for(u32 i=0; i<names.size(); i++){
1798 QuicktuneValue val = getQuicktuneValue(names[i]);
1801 if(!header_printed){
1802 dstream<<"Modified quicktune values:"<<std::endl;
1803 header_printed = true;
1805 dstream<<names[i]<<" = "<<val.getString()<<std::endl;
1809 END_DEBUG_EXCEPTION_HANDLER(errorstream)
1811 debugstreams_deinit();