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"
79 #include "guiEngine.h"
83 These are loaded from the config file.
85 Settings main_settings;
86 Settings *g_settings = &main_settings;
89 Profiler main_profiler;
90 Profiler *g_profiler = &main_profiler;
92 // Menu clouds are created later
93 Clouds *g_menuclouds = 0;
94 irr::scene::ISceneManager *g_menucloudsmgr = 0;
101 std::ostream *dout_con_ptr = &dummyout;
102 std::ostream *derr_con_ptr = &verbosestream;
105 std::ostream *dout_server_ptr = &infostream;
106 std::ostream *derr_server_ptr = &errorstream;
109 std::ostream *dout_client_ptr = &infostream;
110 std::ostream *derr_client_ptr = &errorstream;
117 /* mainmenumanager.h */
119 gui::IGUIEnvironment* guienv = NULL;
120 gui::IGUIStaticText *guiroot = NULL;
121 MainMenuManager g_menumgr;
125 return (g_menumgr.menuCount() == 0);
128 // Passed to menus to allow disconnecting and exiting
129 MainGameCallback *g_gamecallback = NULL;
133 gettime.h implementation
140 /* Use imprecise system calls directly (from porting.h) */
141 return porting::getTime(PRECISION_MILLI);
144 u32 getTime(TimePrecision prec)
146 return porting::getTime(prec);
151 // A small helper class
155 virtual u32 getTime(TimePrecision prec) = 0;
158 // A precise irrlicht one
159 class IrrlichtTimeGetter: public TimeGetter
162 IrrlichtTimeGetter(IrrlichtDevice *device):
165 u32 getTime(TimePrecision prec)
167 if (prec == PRECISION_MILLI) {
170 return m_device->getTimer()->getRealTime();
172 return porting::getTime(prec);
176 IrrlichtDevice *m_device;
178 // Not so precise one which works without irrlicht
179 class SimpleTimeGetter: public TimeGetter
182 u32 getTime(TimePrecision prec)
184 return porting::getTime(prec);
188 // A pointer to a global instance of the time getter
190 TimeGetter *g_timegetter = NULL;
194 if(g_timegetter == NULL)
196 return g_timegetter->getTime(PRECISION_MILLI);
199 u32 getTime(TimePrecision prec) {
200 if (g_timegetter == NULL)
202 return g_timegetter->getTime(prec);
206 class StderrLogOutput: public ILogOutput
209 /* line: Full line with timestamp, level and thread */
210 void printLog(const std::string &line)
212 std::cerr<<line<<std::endl;
214 } main_stderr_log_out;
216 class DstreamNoStderrLogOutput: public ILogOutput
219 /* line: Full line with timestamp, level and thread */
220 void printLog(const std::string &line)
222 dstream_no_stderr<<line<<std::endl;
224 } main_dstream_no_stderr_log_out;
229 Event handler for Irrlicht
231 NOTE: Everything possible should be moved out from here,
232 probably to InputHandler and the_game
235 class MyEventReceiver : public IEventReceiver
238 // This is the one method that we have to implement
239 virtual bool OnEvent(const SEvent& event)
242 React to nothing here if a menu is active
244 if(noMenuActive() == false)
249 // Remember whether each key is down or up
250 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
252 if(event.KeyInput.PressedDown) {
253 keyIsDown.set(event.KeyInput);
254 keyWasDown.set(event.KeyInput);
256 keyIsDown.unset(event.KeyInput);
260 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
262 if(noMenuActive() == false)
265 middle_active = false;
266 right_active = false;
270 left_active = event.MouseInput.isLeftPressed();
271 middle_active = event.MouseInput.isMiddlePressed();
272 right_active = event.MouseInput.isRightPressed();
274 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
278 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
282 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
286 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
288 rightreleased = true;
290 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
292 mouse_wheel += event.MouseInput.Wheel;
300 bool IsKeyDown(const KeyPress &keyCode) const
302 return keyIsDown[keyCode];
305 // Checks whether a key was down and resets the state
306 bool WasKeyDown(const KeyPress &keyCode)
308 bool b = keyWasDown[keyCode];
310 keyWasDown.unset(keyCode);
327 rightclicked = false;
328 leftreleased = false;
329 rightreleased = false;
332 middle_active = false;
333 right_active = false;
355 IrrlichtDevice *m_device;
357 // The current state of keys
359 // Whether a key has been pressed or not
364 Separated input handler
367 class RealInputHandler : public InputHandler
370 RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
375 virtual bool isKeyDown(const KeyPress &keyCode)
377 return m_receiver->IsKeyDown(keyCode);
379 virtual bool wasKeyDown(const KeyPress &keyCode)
381 return m_receiver->WasKeyDown(keyCode);
383 virtual v2s32 getMousePos()
385 return m_device->getCursorControl()->getPosition();
387 virtual void setMousePos(s32 x, s32 y)
389 m_device->getCursorControl()->setPosition(x, y);
392 virtual bool getLeftState()
394 return m_receiver->left_active;
396 virtual bool getRightState()
398 return m_receiver->right_active;
401 virtual bool getLeftClicked()
403 return m_receiver->leftclicked;
405 virtual bool getRightClicked()
407 return m_receiver->rightclicked;
409 virtual void resetLeftClicked()
411 m_receiver->leftclicked = false;
413 virtual void resetRightClicked()
415 m_receiver->rightclicked = false;
418 virtual bool getLeftReleased()
420 return m_receiver->leftreleased;
422 virtual bool getRightReleased()
424 return m_receiver->rightreleased;
426 virtual void resetLeftReleased()
428 m_receiver->leftreleased = false;
430 virtual void resetRightReleased()
432 m_receiver->rightreleased = false;
435 virtual s32 getMouseWheel()
437 return m_receiver->getMouseWheel();
442 m_receiver->clearInput();
445 IrrlichtDevice *m_device;
446 MyEventReceiver *m_receiver;
449 class RandomInputHandler : public InputHandler
457 rightclicked = false;
458 leftreleased = false;
459 rightreleased = false;
462 virtual bool isKeyDown(const KeyPress &keyCode)
464 return keydown[keyCode];
466 virtual bool wasKeyDown(const KeyPress &keyCode)
470 virtual v2s32 getMousePos()
474 virtual void setMousePos(s32 x, s32 y)
476 mousepos = v2s32(x,y);
479 virtual bool getLeftState()
483 virtual bool getRightState()
488 virtual bool getLeftClicked()
492 virtual bool getRightClicked()
496 virtual void resetLeftClicked()
500 virtual void resetRightClicked()
502 rightclicked = false;
505 virtual bool getLeftReleased()
509 virtual bool getRightReleased()
511 return rightreleased;
513 virtual void resetLeftReleased()
515 leftreleased = false;
517 virtual void resetRightReleased()
519 rightreleased = false;
522 virtual s32 getMouseWheel()
527 virtual void step(float dtime)
530 static float counter1 = 0;
534 counter1 = 0.1*Rand(1, 40);
535 keydown.toggle(getKeySetting("keymap_jump"));
539 static float counter1 = 0;
543 counter1 = 0.1*Rand(1, 40);
544 keydown.toggle(getKeySetting("keymap_special1"));
548 static float counter1 = 0;
552 counter1 = 0.1*Rand(1, 40);
553 keydown.toggle(getKeySetting("keymap_forward"));
557 static float counter1 = 0;
561 counter1 = 0.1*Rand(1, 40);
562 keydown.toggle(getKeySetting("keymap_left"));
566 static float counter1 = 0;
570 counter1 = 0.1*Rand(1, 20);
571 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
575 static float counter1 = 0;
579 counter1 = 0.1*Rand(1, 30);
580 leftdown = !leftdown;
588 static float counter1 = 0;
592 counter1 = 0.1*Rand(1, 15);
593 rightdown = !rightdown;
597 rightreleased = true;
600 mousepos += mousespeed;
603 s32 Rand(s32 min, s32 max)
605 return (myrand()%(max-min+1))+min;
621 // These are defined global so that they're not optimized too much.
622 // Can't change them to volatile.
627 std::string tempstring;
628 std::string tempstring2;
633 infostream<<"The following test should take around 20ms."<<std::endl;
634 TimeTaker timer("Testing std::string speed");
635 const u32 jj = 10000;
636 for(u32 j=0; j<jj; j++)
641 for(u32 i=0; i<ii; i++){
642 tempstring2 += "asd";
644 for(u32 i=0; i<ii+1; i++){
646 if(tempstring == tempstring2)
652 infostream<<"All of the following tests should take around 100ms each."
656 TimeTaker timer("Testing floating-point conversion speed");
658 for(u32 i=0; i<4000000; i++){
665 TimeTaker timer("Testing floating-point vector speed");
667 tempv3f1 = v3f(1,2,3);
668 tempv3f2 = v3f(4,5,6);
669 for(u32 i=0; i<10000000; i++){
670 tempf += tempv3f1.dotProduct(tempv3f2);
671 tempv3f2 += v3f(7,8,9);
676 TimeTaker timer("Testing std::map speed");
678 std::map<v2s16, f32> map1;
681 for(s16 y=0; y<ii; y++){
682 for(s16 x=0; x<ii; x++){
683 map1[v2s16(x,y)] = tempf;
687 for(s16 y=ii-1; y>=0; y--){
688 for(s16 x=0; x<ii; x++){
689 tempf = map1[v2s16(x,y)];
695 infostream<<"Around 5000/ms should do well here."<<std::endl;
696 TimeTaker timer("Testing mutex speed");
710 while(timer.getTimerTime() < 10);
712 u32 dtime = timer.stop();
713 u32 per_ms = n / dtime;
714 infostream<<"Done. "<<dtime<<"ms, "
715 <<per_ms<<"/ms"<<std::endl;
719 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
722 for(u32 i=0; i<worldspecs.size(); i++){
723 std::string name = worldspecs[i].name;
724 std::string path = worldspecs[i].path;
725 if(name.find(" ") != std::string::npos)
726 name = std::string("'") + name + "'";
727 path = std::string("'") + path + "'";
728 name = padStringRight(name, 14);
729 os<<" "<<name<<" "<<path<<std::endl;
733 int main(int argc, char *argv[])
741 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
742 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
744 log_register_thread("main");
746 // This enables internatonal characters input
747 if( setlocale(LC_ALL, "") == NULL )
749 fprintf( stderr, "%s: warning: could not set default locale\n", argv[0] );
752 // Set locale. This is for forcing '.' as the decimal point.
754 std::locale::global(std::locale(std::locale(""), "C", std::locale::numeric));
755 setlocale(LC_NUMERIC, "C");
756 } catch (const std::exception& ex) {
757 errorstream<<"Could not set numeric locale to C"<<std::endl;
763 // List all allowed options
764 std::map<std::string, ValueSpec> allowed_options;
765 allowed_options.insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
766 _("Show allowed options"))));
767 allowed_options.insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
768 _("Load configuration from specified file"))));
769 allowed_options.insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
770 _("Set network port (UDP)"))));
771 allowed_options.insert(std::make_pair("disable-unittests", ValueSpec(VALUETYPE_FLAG,
772 _("Disable unit tests"))));
773 allowed_options.insert(std::make_pair("enable-unittests", ValueSpec(VALUETYPE_FLAG,
774 _("Enable unit tests"))));
775 allowed_options.insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
776 _("Same as --world (deprecated)"))));
777 allowed_options.insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
778 _("Set world path (implies local game) ('list' lists all)"))));
779 allowed_options.insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
780 _("Set world by name (implies local game)"))));
781 allowed_options.insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
782 _("Print more information to console"))));
783 allowed_options.insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
784 _("Print even more information to console"))));
785 allowed_options.insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
786 _("Print enormous amounts of information to log and console"))));
787 allowed_options.insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
788 _("Set logfile path ('' = no logging)"))));
789 allowed_options.insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
790 _("Set gameid (\"--gameid list\" prints available ones)"))));
792 allowed_options.insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
793 _("Show available video modes"))));
794 allowed_options.insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
795 _("Run speed tests"))));
796 allowed_options.insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
797 _("Address to connect to. ('' = local game)"))));
798 allowed_options.insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
799 _("Enable random user input, for testing"))));
800 allowed_options.insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
801 _("Run dedicated server"))));
802 allowed_options.insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
803 _("Set player name"))));
804 allowed_options.insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
805 _("Set password"))));
806 allowed_options.insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
807 _("Disable main menu"))));
812 bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
814 if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1"))
816 dstream<<_("Allowed options:")<<std::endl;
817 for(std::map<std::string, ValueSpec>::iterator
818 i = allowed_options.begin();
819 i != allowed_options.end(); ++i)
821 std::ostringstream os1(std::ios::binary);
822 os1<<" --"<<i->first;
823 if(i->second.type == VALUETYPE_FLAG)
827 dstream<<padStringRight(os1.str(), 24);
829 if(i->second.help != NULL)
830 dstream<<i->second.help;
834 return cmd_args.getFlag("help") ? 0 : 1;
838 Low-level initialization
841 // If trace is enabled, enable logging of certain things
842 if(cmd_args.getFlag("trace")){
843 dstream<<_("Enabling trace level debug output")<<std::endl;
844 log_trace_level_enabled = true;
845 dout_con_ptr = &verbosestream; // this is somewhat old crap
846 socket_enable_debug_output = true; // socket doesn't use log.h
848 // In certain cases, output info level on stderr
849 if(cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
850 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
851 log_add_output(&main_stderr_log_out, LMT_INFO);
852 // In certain cases, output verbose level on stderr
853 if(cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
854 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
856 porting::signal_handler_init();
857 bool &kill = *porting::signal_handler_killstatus();
859 porting::initializePaths();
861 // Create user data directory
862 fs::CreateDir(porting::path_user);
864 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str());
866 infostream<<"path_share = "<<porting::path_share<<std::endl;
867 infostream<<"path_user = "<<porting::path_user<<std::endl;
869 // Initialize debug stacks
871 DSTACK(__FUNCTION_NAME);
874 BEGIN_DEBUG_EXCEPTION_HANDLER
876 // List gameids if requested
877 if(cmd_args.exists("gameid") && cmd_args.get("gameid") == "list")
879 std::set<std::string> gameids = getAvailableGameIds();
880 for(std::set<std::string>::const_iterator i = gameids.begin();
881 i != gameids.end(); i++)
882 dstream<<(*i)<<std::endl;
886 // List worlds if requested
887 if(cmd_args.exists("world") && cmd_args.get("world") == "list"){
888 dstream<<_("Available worlds:")<<std::endl;
889 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
890 print_worldspecs(worldspecs, dstream);
894 // Print startup message
895 infostream<<PROJECT_NAME<<
896 " "<<_("with")<<" SER_FMT_VER_HIGHEST="<<(int)SER_FMT_VER_HIGHEST
904 // Initialize default settings
905 set_default_settings(g_settings);
907 // Initialize sockets
909 atexit(sockets_cleanup);
915 // Path of configuration file in use
916 std::string configpath = "";
918 if(cmd_args.exists("config"))
920 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
923 errorstream<<"Could not read configuration from \""
924 <<cmd_args.get("config")<<"\""<<std::endl;
927 configpath = cmd_args.get("config");
931 std::vector<std::string> filenames;
932 filenames.push_back(porting::path_user +
933 DIR_DELIM + "minetest.conf");
934 // Legacy configuration file location
935 filenames.push_back(porting::path_user +
936 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
938 // Try also from a lower level (to aid having the same configuration
939 // for many RUN_IN_PLACE installs)
940 filenames.push_back(porting::path_user +
941 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
944 for(u32 i=0; i<filenames.size(); i++)
946 bool r = g_settings->readConfigFile(filenames[i].c_str());
949 configpath = filenames[i];
954 // If no path found, use the first one (menu creates the file)
956 configpath = filenames[0];
959 // Initialize debug streams
960 #define DEBUGFILE "debug.txt"
962 std::string logfile = DEBUGFILE;
964 std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE;
966 if(cmd_args.exists("logfile"))
967 logfile = cmd_args.get("logfile");
969 log_remove_output(&main_dstream_no_stderr_log_out);
970 int loglevel = g_settings->getS32("debug_log_level");
972 if (loglevel == 0) //no logging
974 else if (loglevel > 0 && loglevel <= LMT_NUM_VALUES)
975 log_add_output_maxlev(&main_dstream_no_stderr_log_out, (LogMessageLevel)(loglevel - 1));
978 debugstreams_init(false, logfile.c_str());
980 debugstreams_init(false, NULL);
982 infostream<<"logfile = "<<logfile<<std::endl;
984 // Initialize random seed
992 if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
993 || cmd_args.getFlag("enable-unittests") == true)
1004 if(cmd_args.exists("port"))
1005 port = cmd_args.getU16("port");
1006 else if(g_settings->exists("port"))
1007 port = g_settings->getU16("port");
1012 std::string commanded_world = "";
1013 if(cmd_args.exists("world"))
1014 commanded_world = cmd_args.get("world");
1015 else if(cmd_args.exists("map-dir"))
1016 commanded_world = cmd_args.get("map-dir");
1017 else if(cmd_args.exists("nonopt0")) // First nameless argument
1018 commanded_world = cmd_args.get("nonopt0");
1019 else if(g_settings->exists("map-dir"))
1020 commanded_world = g_settings->get("map-dir");
1023 std::string commanded_worldname = "";
1024 if(cmd_args.exists("worldname"))
1025 commanded_worldname = cmd_args.get("worldname");
1027 // Strip world.mt from commanded_world
1029 std::string worldmt = "world.mt";
1030 if(commanded_world.size() > worldmt.size() &&
1031 commanded_world.substr(commanded_world.size()-worldmt.size())
1033 dstream<<_("Supplied world.mt file - stripping it off.")<<std::endl;
1034 commanded_world = commanded_world.substr(
1035 0, commanded_world.size()-worldmt.size());
1039 // If a world name was specified, convert it to a path
1040 if(commanded_worldname != ""){
1041 // Get information about available worlds
1042 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1044 for(u32 i=0; i<worldspecs.size(); i++){
1045 std::string name = worldspecs[i].name;
1046 if(name == commanded_worldname){
1047 if(commanded_world != ""){
1048 dstream<<_("--worldname takes precedence over previously "
1049 "selected world.")<<std::endl;
1051 commanded_world = worldspecs[i].path;
1057 dstream<<_("World")<<" '"<<commanded_worldname<<_("' not "
1058 "available. Available worlds:")<<std::endl;
1059 print_worldspecs(worldspecs, dstream);
1065 SubgameSpec commanded_gamespec;
1066 if(cmd_args.exists("gameid")){
1067 std::string gameid = cmd_args.get("gameid");
1068 commanded_gamespec = findSubgame(gameid);
1069 if(!commanded_gamespec.isValid()){
1070 errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl;
1076 Run dedicated server if asked to or no other option
1079 bool run_dedicated_server = true;
1081 bool run_dedicated_server = cmd_args.getFlag("server");
1083 g_settings->set("server_dedicated", run_dedicated_server ? "true" : "false");
1084 if(run_dedicated_server)
1086 DSTACK("Dedicated server branch");
1087 // Create time getter if built with Irrlicht
1089 g_timegetter = new SimpleTimeGetter();
1093 std::string world_path;
1094 verbosestream<<_("Determining world path")<<std::endl;
1095 bool is_legacy_world = false;
1096 // If a world was commanded, use it
1097 if(commanded_world != ""){
1098 world_path = commanded_world;
1099 infostream<<"Using commanded world path ["<<world_path<<"]"
1102 // No world was specified; try to select it automatically
1105 // Get information about available worlds
1106 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1107 // If a world name was specified, select it
1108 if(commanded_worldname != ""){
1110 for(u32 i=0; i<worldspecs.size(); i++){
1111 std::string name = worldspecs[i].name;
1112 if(name == commanded_worldname){
1113 world_path = worldspecs[i].path;
1117 if(world_path == ""){
1118 dstream<<_("World")<<" '"<<commanded_worldname<<"' "<<_("not "
1119 "available. Available worlds:")<<std::endl;
1120 print_worldspecs(worldspecs, dstream);
1124 // If there is only a single world, use it
1125 if(worldspecs.size() == 1){
1126 world_path = worldspecs[0].path;
1127 dstream<<_("Automatically selecting world at")<<" ["
1128 <<world_path<<"]"<<std::endl;
1129 // If there are multiple worlds, list them
1130 } else if(worldspecs.size() > 1){
1131 dstream<<_("Multiple worlds are available.")<<std::endl;
1132 dstream<<_("Please select one using --worldname <name>"
1133 " or --world <path>")<<std::endl;
1134 print_worldspecs(worldspecs, dstream);
1136 // If there are no worlds, automatically create a new one
1138 // This is the ultimate default world path
1139 world_path = porting::path_user + DIR_DELIM + "worlds" +
1140 DIR_DELIM + "world";
1141 infostream<<"Creating default world at ["
1142 <<world_path<<"]"<<std::endl;
1146 if(world_path == ""){
1147 errorstream<<"No world path specified or found."<<std::endl;
1150 verbosestream<<_("Using world path")<<" ["<<world_path<<"]"<<std::endl;
1152 // We need a gamespec.
1153 SubgameSpec gamespec;
1154 verbosestream<<_("Determining gameid/gamespec")<<std::endl;
1155 // If world doesn't exist
1156 if(!getWorldExists(world_path))
1158 // Try to take gamespec from command line
1159 if(commanded_gamespec.isValid()){
1160 gamespec = commanded_gamespec;
1161 infostream<<"Using commanded gameid ["<<gamespec.id<<"]"<<std::endl;
1163 // Otherwise we will be using "minetest"
1165 gamespec = findSubgame(g_settings->get("default_game"));
1166 infostream<<"Using default gameid ["<<gamespec.id<<"]"<<std::endl;
1172 std::string world_gameid = getWorldGameId(world_path, is_legacy_world);
1173 // If commanded to use a gameid, do so
1174 if(commanded_gamespec.isValid()){
1175 gamespec = commanded_gamespec;
1176 if(commanded_gamespec.id != world_gameid){
1177 errorstream<<"WARNING: Using commanded gameid ["
1178 <<gamespec.id<<"]"<<" instead of world gameid ["
1179 <<world_gameid<<"]"<<std::endl;
1182 // If world contains an embedded game, use it;
1183 // Otherwise find world from local system.
1184 gamespec = findWorldSubgame(world_path);
1185 infostream<<"Using world gameid ["<<gamespec.id<<"]"<<std::endl;
1188 if(!gamespec.isValid()){
1189 errorstream<<"Subgame ["<<gamespec.id<<"] could not be found."
1193 verbosestream<<_("Using gameid")<<" ["<<gamespec.id<<"]"<<std::endl;
1196 Server server(world_path, configpath, gamespec, false);
1200 dedicated_server_loop(server, kill);
1205 #ifndef SERVER // Exclude from dedicated server build
1211 std::string address = g_settings->get("address");
1212 if(commanded_world != "")
1214 else if(cmd_args.exists("address"))
1215 address = cmd_args.get("address");
1217 std::string playername = g_settings->get("name");
1218 if(cmd_args.exists("name"))
1219 playername = cmd_args.get("name");
1221 bool skip_main_menu = cmd_args.getFlag("go");
1224 Device initialization
1227 // Resolution selection
1229 bool fullscreen = g_settings->getBool("fullscreen");
1230 u16 screenW = g_settings->getU16("screenW");
1231 u16 screenH = g_settings->getU16("screenH");
1235 bool vsync = g_settings->getBool("vsync");
1236 u16 bits = g_settings->getU16("fullscreen_bpp");
1237 u16 fsaa = g_settings->getU16("fsaa");
1241 video::E_DRIVER_TYPE driverType;
1243 std::string driverstring = g_settings->get("video_driver");
1245 if(driverstring == "null")
1246 driverType = video::EDT_NULL;
1247 else if(driverstring == "software")
1248 driverType = video::EDT_SOFTWARE;
1249 else if(driverstring == "burningsvideo")
1250 driverType = video::EDT_BURNINGSVIDEO;
1251 else if(driverstring == "direct3d8")
1252 driverType = video::EDT_DIRECT3D8;
1253 else if(driverstring == "direct3d9")
1254 driverType = video::EDT_DIRECT3D9;
1255 else if(driverstring == "opengl")
1256 driverType = video::EDT_OPENGL;
1257 #ifdef _IRR_COMPILE_WITH_OGLES1_
1258 else if(driverstring == "ogles1")
1259 driverType = video::EDT_OGLES1;
1261 #ifdef _IRR_COMPILE_WITH_OGLES2_
1262 else if(driverstring == "ogles2")
1263 driverType = video::EDT_OGLES2;
1267 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1268 "to opengl"<<std::endl;
1269 driverType = video::EDT_OPENGL;
1273 List video modes if requested
1276 MyEventReceiver receiver;
1278 if(cmd_args.getFlag("videomodes")){
1279 IrrlichtDevice *nulldevice;
1281 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1282 params.DriverType = video::EDT_NULL;
1283 params.WindowSize = core::dimension2d<u32>(640, 480);
1285 params.AntiAlias = fsaa;
1286 params.Fullscreen = false;
1287 params.Stencilbuffer = false;
1288 params.Vsync = vsync;
1289 params.EventReceiver = &receiver;
1291 nulldevice = createDeviceEx(params);
1296 dstream<<_("Available video modes (WxHxD):")<<std::endl;
1298 video::IVideoModeList *videomode_list =
1299 nulldevice->getVideoModeList();
1301 if(videomode_list == 0){
1306 s32 videomode_count = videomode_list->getVideoModeCount();
1307 core::dimension2d<u32> videomode_res;
1308 s32 videomode_depth;
1309 for (s32 i = 0; i < videomode_count; ++i){
1310 videomode_res = videomode_list->getVideoModeResolution(i);
1311 videomode_depth = videomode_list->getVideoModeDepth(i);
1312 dstream<<videomode_res.Width<<"x"<<videomode_res.Height
1313 <<"x"<<videomode_depth<<std::endl;
1316 dstream<<_("Active video mode (WxHxD):")<<std::endl;
1317 videomode_res = videomode_list->getDesktopResolution();
1318 videomode_depth = videomode_list->getDesktopDepth();
1319 dstream<<videomode_res.Width<<"x"<<videomode_res.Height
1320 <<"x"<<videomode_depth<<std::endl;
1328 Create device and exit if creation failed
1331 IrrlichtDevice *device;
1333 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1334 params.DriverType = driverType;
1335 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
1337 params.AntiAlias = fsaa;
1338 params.Fullscreen = fullscreen;
1339 params.Stencilbuffer = false;
1340 params.Vsync = vsync;
1341 params.EventReceiver = &receiver;
1343 device = createDeviceEx(params);
1346 return 1; // could not create selected driver.
1349 Continue initialization
1352 video::IVideoDriver* driver = device->getVideoDriver();
1355 This changes the minimum allowed number of vertices in a VBO.
1358 //driver->setMinHardwareBufferVertexCount(50);
1360 // Create time getter
1361 g_timegetter = new IrrlichtTimeGetter(device);
1363 // Create game callback for menus
1364 g_gamecallback = new MainGameCallback(device);
1367 Speed tests (done after irrlicht is loaded to get timer)
1369 if(cmd_args.getFlag("speedtests"))
1371 dstream<<"Running speed tests"<<std::endl;
1377 device->setResizable(true);
1379 bool random_input = g_settings->getBool("random_input")
1380 || cmd_args.getFlag("random-input");
1381 InputHandler *input = NULL;
1383 input = new RandomInputHandler();
1385 input = new RealInputHandler(device, &receiver);
1387 scene::ISceneManager* smgr = device->getSceneManager();
1389 guienv = device->getGUIEnvironment();
1390 gui::IGUISkin* skin = guienv->getSkin();
1392 std::string font_path = g_settings->get("font_path");
1393 u16 font_size = g_settings->getU16("font_size");
1394 gui::IGUIFont *font = gui::CGUITTFont::createTTFont(guienv, font_path.c_str(), font_size);
1396 gui::IGUIFont* font = guienv->getFont(getTexturePath("fontlucida.png").c_str());
1399 skin->setFont(font);
1401 errorstream<<"WARNING: Font file was not found."
1402 " Using default font."<<std::endl;
1403 // If font was not found, this will get us one
1404 font = skin->getFont();
1407 u32 text_height = font->getDimension(L"Hello, world!").Height;
1408 infostream<<"text_height="<<text_height<<std::endl;
1410 //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1411 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1412 //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1413 //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1414 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1415 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1416 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50));
1417 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255));
1419 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1420 // Irrlicht 1.8 input colours
1421 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255,128,128,128));
1422 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255,96,134,49));
1426 // Create the menu clouds
1427 if (!g_menucloudsmgr)
1428 g_menucloudsmgr = smgr->createNewSceneManager();
1430 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1431 g_menucloudsmgr, -1, rand(), 100);
1432 g_menuclouds->update(v2f(0, 0), video::SColor(255,200,200,255));
1433 scene::ICameraSceneNode* camera;
1434 camera = g_menucloudsmgr->addCameraSceneNode(0,
1435 v3f(0,0,0), v3f(0, 60, 100));
1436 camera->setFarValue(10000);
1442 ChatBackend chat_backend;
1445 If an error occurs, this is set to something and the
1446 menu-game loop is restarted. It is then displayed before
1449 std::wstring error_message = L"";
1451 // The password entered during the menu screen,
1452 std::string password;
1454 bool first_loop = true;
1459 while(device->run() && kill == false)
1461 // Set the window caption
1462 wchar_t* text = wgettext("Main Menu");
1463 device->setWindowCaption((std::wstring(L"Minetest [")+text+L"]").c_str());
1466 // This is used for catching disconnects
1471 Clear everything from the GUIEnvironment
1476 We need some kind of a root node to be able to add
1477 custom gui elements directly on the screen.
1478 Otherwise they won't be automatically drawn.
1480 guiroot = guienv->addStaticText(L"",
1481 core::rect<s32>(0, 0, 10000, 10000));
1483 SubgameSpec gamespec;
1484 WorldSpec worldspec;
1485 bool simple_singleplayer_mode = false;
1487 // These are set up based on the menu and other things
1488 std::string current_playername = "inv£lid";
1489 std::string current_password = "";
1490 std::string current_address = "does-not-exist";
1491 int current_port = 0;
1494 Out-of-game menu loop.
1496 Loop quits when menu returns proper parameters.
1498 while(kill == false)
1500 // If skip_main_menu, only go through here once
1501 if(skip_main_menu && !first_loop){
1507 // Cursor can be non-visible when coming from the game
1508 device->getCursorControl()->setVisible(true);
1509 // Some stuff are left to scene manager when coming from the game
1513 // Initialize menu data
1514 MainMenuData menudata;
1515 menudata.kill = kill;
1516 menudata.address = address;
1517 menudata.name = playername;
1518 menudata.port = itos(port);
1519 menudata.errormessage = wide_to_narrow(error_message);
1520 error_message = L"";
1521 if(cmd_args.exists("password"))
1522 menudata.password = cmd_args.get("password");
1524 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
1526 menudata.enable_public = g_settings->getBool("server_announce");
1528 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1530 // If a world was commanded, append and select it
1531 if(commanded_world != ""){
1533 std::string gameid = getWorldGameId(commanded_world, true);
1534 std::string name = _("[--world parameter]");
1536 gameid = g_settings->get("default_game");
1539 //TODO find within worldspecs and set config
1542 if(skip_main_menu == false)
1544 video::IVideoDriver* driver = device->getVideoDriver();
1546 infostream<<"Waiting for other menus"<<std::endl;
1547 while(device->run() && kill == false)
1551 driver->beginScene(true, true,
1552 video::SColor(255,128,128,128));
1555 // On some computers framerate doesn't seem to be
1556 // automatically limited
1559 infostream<<"Waited for other menus"<<std::endl;
1561 GUIEngine* temp = new GUIEngine(device, guiroot, &g_menumgr,smgr,&menudata);
1564 //once finished you'll never end up here
1566 kill = menudata.kill;
1570 //update worldspecs (necessary as new world may have been created)
1571 worldspecs = getAvailableWorlds();
1573 if (menudata.name == "")
1574 menudata.name = std::string("Guest") + itos(myrand_range(1000,9999));
1576 playername = menudata.name;
1578 password = translatePassword(playername, narrow_to_wide(menudata.password));
1579 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1581 address = menudata.address;
1582 int newport = stoi(menudata.port);
1586 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1589 g_settings->set("name", playername);
1590 g_settings->set("address", address);
1591 g_settings->set("port", itos(port));
1593 if((menudata.selected_world >= 0) &&
1594 (menudata.selected_world < worldspecs.size()))
1595 g_settings->set("selected_world_path",
1596 worldspecs[menudata.selected_world].path);
1598 // Break out of menu-game loop to shut down cleanly
1599 if(device->run() == false || kill == true)
1602 current_playername = playername;
1603 current_password = password;
1604 current_address = address;
1605 current_port = port;
1607 // If using simple singleplayer mode, override
1608 if(simple_singleplayer_mode){
1609 current_playername = "singleplayer";
1610 current_password = "";
1611 current_address = "";
1612 current_port = myrand_range(49152, 65535);
1614 else if (address != "")
1616 ServerListSpec server;
1617 server["name"] = menudata.servername;
1618 server["address"] = menudata.address;
1619 server["port"] = menudata.port;
1620 server["description"] = menudata.serverdescription;
1621 ServerList::insert(server);
1624 // Set world path to selected one
1625 if ((menudata.selected_world >= 0) &&
1626 (menudata.selected_world < worldspecs.size())) {
1627 worldspec = worldspecs[menudata.selected_world];
1628 infostream<<"Selected world: "<<worldspec.name
1629 <<" ["<<worldspec.path<<"]"<<std::endl;
1633 if(current_address == "")
1635 if(menudata.selected_world == -1){
1636 error_message = wgettext("No world selected and no address "
1637 "provided. Nothing to do.");
1638 errorstream<<wide_to_narrow(error_message)<<std::endl;
1641 // Load gamespec for required game
1642 gamespec = findWorldSubgame(worldspec.path);
1643 if(!gamespec.isValid() && !commanded_gamespec.isValid()){
1644 error_message = wgettext("Could not find or load game \"")
1645 + narrow_to_wide(worldspec.gameid) + L"\"";
1646 errorstream<<wide_to_narrow(error_message)<<std::endl;
1649 if(commanded_gamespec.isValid() &&
1650 commanded_gamespec.id != worldspec.gameid){
1651 errorstream<<"WARNING: Overriding gamespec from \""
1652 <<worldspec.gameid<<"\" to \""
1653 <<commanded_gamespec.id<<"\""<<std::endl;
1654 gamespec = commanded_gamespec;
1657 if(!gamespec.isValid()){
1658 error_message = wgettext("Invalid gamespec.");
1659 error_message += L" (world_gameid="
1660 +narrow_to_wide(worldspec.gameid)+L")";
1661 errorstream<<wide_to_narrow(error_message)<<std::endl;
1670 // Break out of menu-game loop to shut down cleanly
1671 if(device->run() == false || kill == true) {
1672 g_settings->updateConfigFile(configpath.c_str());
1694 simple_singleplayer_mode
1699 catch(con::PeerNotFoundException &e)
1701 error_message = wgettext("Connection error (timed out?)");
1702 errorstream<<wide_to_narrow(error_message)<<std::endl;
1705 catch(std::exception &e)
1707 std::string narrow_message = "Some exception: \"";
1708 narrow_message += e.what();
1709 narrow_message += "\"";
1710 errorstream<<narrow_message<<std::endl;
1711 error_message = narrow_to_wide(narrow_message);
1715 // If no main menu, show error and exit
1718 if(error_message != L""){
1719 verbosestream<<"error_message = "
1720 <<wide_to_narrow(error_message)<<std::endl;
1728 g_menuclouds->drop();
1729 g_menucloudsmgr->drop();
1734 In the end, delete the Irrlicht device.
1744 // Update configuration file
1745 if(configpath != "")
1746 g_settings->updateConfigFile(configpath.c_str());
1748 // Print modified quicktune values
1750 bool header_printed = false;
1751 std::vector<std::string> names = getQuicktuneNames();
1752 for(u32 i=0; i<names.size(); i++){
1753 QuicktuneValue val = getQuicktuneValue(names[i]);
1756 if(!header_printed){
1757 dstream<<"Modified quicktune values:"<<std::endl;
1758 header_printed = true;
1760 dstream<<names[i]<<" = "<<val.getString()<<std::endl;
1764 END_DEBUG_EXCEPTION_HANDLER(errorstream)
1766 debugstreams_deinit();