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"
62 #include "guiMainMenu.h"
67 #include "defaultsettings.h"
74 #include "xCGUITTFont.h"
76 #include "util/string.h"
78 #include "quicktune.h"
79 #include "serverlist.h"
80 #include "httpfetch.h"
81 #include "guiEngine.h"
82 #include "mapsector.h"
84 #include "database-sqlite3.h"
86 #include "database-leveldb.h"
91 These are loaded from the config file.
93 Settings main_settings;
94 Settings *g_settings = &main_settings;
95 std::string g_settings_path;
98 Profiler main_profiler;
99 Profiler *g_profiler = &main_profiler;
101 // Menu clouds are created later
102 Clouds *g_menuclouds = 0;
103 irr::scene::ISceneManager *g_menucloudsmgr = 0;
110 std::ostream *dout_con_ptr = &dummyout;
111 std::ostream *derr_con_ptr = &verbosestream;
114 std::ostream *dout_server_ptr = &infostream;
115 std::ostream *derr_server_ptr = &errorstream;
118 std::ostream *dout_client_ptr = &infostream;
119 std::ostream *derr_client_ptr = &errorstream;
126 /* mainmenumanager.h */
128 gui::IGUIEnvironment* guienv = NULL;
129 gui::IGUIStaticText *guiroot = NULL;
130 MainMenuManager g_menumgr;
134 return (g_menumgr.menuCount() == 0);
137 // Passed to menus to allow disconnecting and exiting
138 MainGameCallback *g_gamecallback = NULL;
142 gettime.h implementation
149 /* Use imprecise system calls directly (from porting.h) */
150 return porting::getTime(PRECISION_MILLI);
153 u32 getTime(TimePrecision prec)
155 return porting::getTime(prec);
160 // A small helper class
164 virtual u32 getTime(TimePrecision prec) = 0;
167 // A precise irrlicht one
168 class IrrlichtTimeGetter: public TimeGetter
171 IrrlichtTimeGetter(IrrlichtDevice *device):
174 u32 getTime(TimePrecision prec)
176 if (prec == PRECISION_MILLI) {
179 return m_device->getTimer()->getRealTime();
181 return porting::getTime(prec);
185 IrrlichtDevice *m_device;
187 // Not so precise one which works without irrlicht
188 class SimpleTimeGetter: public TimeGetter
191 u32 getTime(TimePrecision prec)
193 return porting::getTime(prec);
197 // A pointer to a global instance of the time getter
199 TimeGetter *g_timegetter = NULL;
203 if(g_timegetter == NULL)
205 return g_timegetter->getTime(PRECISION_MILLI);
208 u32 getTime(TimePrecision prec) {
209 if (g_timegetter == NULL)
211 return g_timegetter->getTime(prec);
215 class StderrLogOutput: public ILogOutput
218 /* line: Full line with timestamp, level and thread */
219 void printLog(const std::string &line)
221 std::cerr<<line<<std::endl;
223 } main_stderr_log_out;
225 class DstreamNoStderrLogOutput: public ILogOutput
228 /* line: Full line with timestamp, level and thread */
229 void printLog(const std::string &line)
231 dstream_no_stderr<<line<<std::endl;
233 } main_dstream_no_stderr_log_out;
238 Event handler for Irrlicht
240 NOTE: Everything possible should be moved out from here,
241 probably to InputHandler and the_game
244 class MyEventReceiver : public IEventReceiver
247 // This is the one method that we have to implement
248 virtual bool OnEvent(const SEvent& event)
251 React to nothing here if a menu is active
253 if(noMenuActive() == false)
255 return g_menumgr.preprocessEvent(event);
258 // Remember whether each key is down or up
259 if(event.EventType == irr::EET_KEY_INPUT_EVENT)
261 if(event.KeyInput.PressedDown) {
262 keyIsDown.set(event.KeyInput);
263 keyWasDown.set(event.KeyInput);
265 keyIsDown.unset(event.KeyInput);
269 if(event.EventType == irr::EET_MOUSE_INPUT_EVENT)
271 if(noMenuActive() == false)
274 middle_active = false;
275 right_active = false;
279 left_active = event.MouseInput.isLeftPressed();
280 middle_active = event.MouseInput.isMiddlePressed();
281 right_active = event.MouseInput.isRightPressed();
283 if(event.MouseInput.Event == EMIE_LMOUSE_PRESSED_DOWN)
287 if(event.MouseInput.Event == EMIE_RMOUSE_PRESSED_DOWN)
291 if(event.MouseInput.Event == EMIE_LMOUSE_LEFT_UP)
295 if(event.MouseInput.Event == EMIE_RMOUSE_LEFT_UP)
297 rightreleased = true;
299 if(event.MouseInput.Event == EMIE_MOUSE_WHEEL)
301 mouse_wheel += event.MouseInput.Wheel;
309 bool IsKeyDown(const KeyPress &keyCode) const
311 return keyIsDown[keyCode];
314 // Checks whether a key was down and resets the state
315 bool WasKeyDown(const KeyPress &keyCode)
317 bool b = keyWasDown[keyCode];
319 keyWasDown.unset(keyCode);
336 rightclicked = false;
337 leftreleased = false;
338 rightreleased = false;
341 middle_active = false;
342 right_active = false;
364 IrrlichtDevice *m_device;
366 // The current state of keys
368 // Whether a key has been pressed or not
373 Separated input handler
376 class RealInputHandler : public InputHandler
379 RealInputHandler(IrrlichtDevice *device, MyEventReceiver *receiver):
384 virtual bool isKeyDown(const KeyPress &keyCode)
386 return m_receiver->IsKeyDown(keyCode);
388 virtual bool wasKeyDown(const KeyPress &keyCode)
390 return m_receiver->WasKeyDown(keyCode);
392 virtual v2s32 getMousePos()
394 return m_device->getCursorControl()->getPosition();
396 virtual void setMousePos(s32 x, s32 y)
398 m_device->getCursorControl()->setPosition(x, y);
401 virtual bool getLeftState()
403 return m_receiver->left_active;
405 virtual bool getRightState()
407 return m_receiver->right_active;
410 virtual bool getLeftClicked()
412 return m_receiver->leftclicked;
414 virtual bool getRightClicked()
416 return m_receiver->rightclicked;
418 virtual void resetLeftClicked()
420 m_receiver->leftclicked = false;
422 virtual void resetRightClicked()
424 m_receiver->rightclicked = false;
427 virtual bool getLeftReleased()
429 return m_receiver->leftreleased;
431 virtual bool getRightReleased()
433 return m_receiver->rightreleased;
435 virtual void resetLeftReleased()
437 m_receiver->leftreleased = false;
439 virtual void resetRightReleased()
441 m_receiver->rightreleased = false;
444 virtual s32 getMouseWheel()
446 return m_receiver->getMouseWheel();
451 m_receiver->clearInput();
454 IrrlichtDevice *m_device;
455 MyEventReceiver *m_receiver;
458 class RandomInputHandler : public InputHandler
466 rightclicked = false;
467 leftreleased = false;
468 rightreleased = false;
471 virtual bool isKeyDown(const KeyPress &keyCode)
473 return keydown[keyCode];
475 virtual bool wasKeyDown(const KeyPress &keyCode)
479 virtual v2s32 getMousePos()
483 virtual void setMousePos(s32 x, s32 y)
485 mousepos = v2s32(x,y);
488 virtual bool getLeftState()
492 virtual bool getRightState()
497 virtual bool getLeftClicked()
501 virtual bool getRightClicked()
505 virtual void resetLeftClicked()
509 virtual void resetRightClicked()
511 rightclicked = false;
514 virtual bool getLeftReleased()
518 virtual bool getRightReleased()
520 return rightreleased;
522 virtual void resetLeftReleased()
524 leftreleased = false;
526 virtual void resetRightReleased()
528 rightreleased = false;
531 virtual s32 getMouseWheel()
536 virtual void step(float dtime)
539 static float counter1 = 0;
543 counter1 = 0.1*Rand(1, 40);
544 keydown.toggle(getKeySetting("keymap_jump"));
548 static float counter1 = 0;
552 counter1 = 0.1*Rand(1, 40);
553 keydown.toggle(getKeySetting("keymap_special1"));
557 static float counter1 = 0;
561 counter1 = 0.1*Rand(1, 40);
562 keydown.toggle(getKeySetting("keymap_forward"));
566 static float counter1 = 0;
570 counter1 = 0.1*Rand(1, 40);
571 keydown.toggle(getKeySetting("keymap_left"));
575 static float counter1 = 0;
579 counter1 = 0.1*Rand(1, 20);
580 mousespeed = v2s32(Rand(-20,20), Rand(-15,20));
584 static float counter1 = 0;
588 counter1 = 0.1*Rand(1, 30);
589 leftdown = !leftdown;
597 static float counter1 = 0;
601 counter1 = 0.1*Rand(1, 15);
602 rightdown = !rightdown;
606 rightreleased = true;
609 mousepos += mousespeed;
612 s32 Rand(s32 min, s32 max)
614 return (myrand()%(max-min+1))+min;
630 // These are defined global so that they're not optimized too much.
631 // Can't change them to volatile.
636 std::string tempstring;
637 std::string tempstring2;
642 infostream<<"The following test should take around 20ms."<<std::endl;
643 TimeTaker timer("Testing std::string speed");
644 const u32 jj = 10000;
645 for(u32 j=0; j<jj; j++)
650 for(u32 i=0; i<ii; i++){
651 tempstring2 += "asd";
653 for(u32 i=0; i<ii+1; i++){
655 if(tempstring == tempstring2)
661 infostream<<"All of the following tests should take around 100ms each."
665 TimeTaker timer("Testing floating-point conversion speed");
667 for(u32 i=0; i<4000000; i++){
674 TimeTaker timer("Testing floating-point vector speed");
676 tempv3f1 = v3f(1,2,3);
677 tempv3f2 = v3f(4,5,6);
678 for(u32 i=0; i<10000000; i++){
679 tempf += tempv3f1.dotProduct(tempv3f2);
680 tempv3f2 += v3f(7,8,9);
685 TimeTaker timer("Testing std::map speed");
687 std::map<v2s16, f32> map1;
690 for(s16 y=0; y<ii; y++){
691 for(s16 x=0; x<ii; x++){
692 map1[v2s16(x,y)] = tempf;
696 for(s16 y=ii-1; y>=0; y--){
697 for(s16 x=0; x<ii; x++){
698 tempf = map1[v2s16(x,y)];
704 infostream<<"Around 5000/ms should do well here."<<std::endl;
705 TimeTaker timer("Testing mutex speed");
718 while(timer.getTimerTime() < 10);
720 u32 dtime = timer.stop();
721 u32 per_ms = n / dtime;
722 infostream<<"Done. "<<dtime<<"ms, "
723 <<per_ms<<"/ms"<<std::endl;
727 static void print_worldspecs(const std::vector<WorldSpec> &worldspecs,
730 for(u32 i=0; i<worldspecs.size(); i++){
731 std::string name = worldspecs[i].name;
732 std::string path = worldspecs[i].path;
733 if(name.find(" ") != std::string::npos)
734 name = std::string("'") + name + "'";
735 path = std::string("'") + path + "'";
736 name = padStringRight(name, 14);
737 os<<" "<<name<<" "<<path<<std::endl;
741 int main(int argc, char *argv[])
749 log_add_output_maxlev(&main_stderr_log_out, LMT_ACTION);
750 log_add_output_all_levs(&main_dstream_no_stderr_log_out);
752 log_register_thread("main");
757 // List all allowed options
758 std::map<std::string, ValueSpec> allowed_options;
759 allowed_options.insert(std::make_pair("help", ValueSpec(VALUETYPE_FLAG,
760 _("Show allowed options"))));
761 allowed_options.insert(std::make_pair("version", ValueSpec(VALUETYPE_FLAG,
762 _("Show version information"))));
763 allowed_options.insert(std::make_pair("config", ValueSpec(VALUETYPE_STRING,
764 _("Load configuration from specified file"))));
765 allowed_options.insert(std::make_pair("port", ValueSpec(VALUETYPE_STRING,
766 _("Set network port (UDP)"))));
767 allowed_options.insert(std::make_pair("disable-unittests", ValueSpec(VALUETYPE_FLAG,
768 _("Disable unit tests"))));
769 allowed_options.insert(std::make_pair("enable-unittests", ValueSpec(VALUETYPE_FLAG,
770 _("Enable unit tests"))));
771 allowed_options.insert(std::make_pair("map-dir", ValueSpec(VALUETYPE_STRING,
772 _("Same as --world (deprecated)"))));
773 allowed_options.insert(std::make_pair("world", ValueSpec(VALUETYPE_STRING,
774 _("Set world path (implies local game) ('list' lists all)"))));
775 allowed_options.insert(std::make_pair("worldname", ValueSpec(VALUETYPE_STRING,
776 _("Set world by name (implies local game)"))));
777 allowed_options.insert(std::make_pair("info", ValueSpec(VALUETYPE_FLAG,
778 _("Print more information to console"))));
779 allowed_options.insert(std::make_pair("verbose", ValueSpec(VALUETYPE_FLAG,
780 _("Print even more information to console"))));
781 allowed_options.insert(std::make_pair("trace", ValueSpec(VALUETYPE_FLAG,
782 _("Print enormous amounts of information to log and console"))));
783 allowed_options.insert(std::make_pair("logfile", ValueSpec(VALUETYPE_STRING,
784 _("Set logfile path ('' = no logging)"))));
785 allowed_options.insert(std::make_pair("gameid", ValueSpec(VALUETYPE_STRING,
786 _("Set gameid (\"--gameid list\" prints available ones)"))));
787 allowed_options.insert(std::make_pair("migrate", ValueSpec(VALUETYPE_STRING,
788 _("Migrate from current map backend to another (Only works when using minetestserver or with --server)"))));
790 allowed_options.insert(std::make_pair("videomodes", ValueSpec(VALUETYPE_FLAG,
791 _("Show available video modes"))));
792 allowed_options.insert(std::make_pair("speedtests", ValueSpec(VALUETYPE_FLAG,
793 _("Run speed tests"))));
794 allowed_options.insert(std::make_pair("address", ValueSpec(VALUETYPE_STRING,
795 _("Address to connect to. ('' = local game)"))));
796 allowed_options.insert(std::make_pair("random-input", ValueSpec(VALUETYPE_FLAG,
797 _("Enable random user input, for testing"))));
798 allowed_options.insert(std::make_pair("server", ValueSpec(VALUETYPE_FLAG,
799 _("Run dedicated server"))));
800 allowed_options.insert(std::make_pair("name", ValueSpec(VALUETYPE_STRING,
801 _("Set player name"))));
802 allowed_options.insert(std::make_pair("password", ValueSpec(VALUETYPE_STRING,
803 _("Set password"))));
804 allowed_options.insert(std::make_pair("go", ValueSpec(VALUETYPE_FLAG,
805 _("Disable main menu"))));
810 bool ret = cmd_args.parseCommandLine(argc, argv, allowed_options);
812 if(ret == false || cmd_args.getFlag("help") || cmd_args.exists("nonopt1"))
814 dstream<<_("Allowed options:")<<std::endl;
815 for(std::map<std::string, ValueSpec>::iterator
816 i = allowed_options.begin();
817 i != allowed_options.end(); ++i)
819 std::ostringstream os1(std::ios::binary);
820 os1<<" --"<<i->first;
821 if(i->second.type == VALUETYPE_FLAG)
825 dstream<<padStringRight(os1.str(), 24);
827 if(i->second.help != NULL)
828 dstream<<i->second.help;
832 return cmd_args.getFlag("help") ? 0 : 1;
835 if(cmd_args.getFlag("version"))
838 dstream<<"minetestserver "<<minetest_version_hash<<std::endl;
840 dstream<<"Minetest "<<minetest_version_hash<<std::endl;
841 dstream<<"Using Irrlicht "<<IRRLICHT_SDK_VERSION<<std::endl;
843 dstream<<"Build info: "<<minetest_build_info<<std::endl;
848 Low-level initialization
851 // If trace is enabled, enable logging of certain things
852 if(cmd_args.getFlag("trace")){
853 dstream<<_("Enabling trace level debug output")<<std::endl;
854 log_trace_level_enabled = true;
855 dout_con_ptr = &verbosestream; // this is somewhat old crap
856 socket_enable_debug_output = true; // socket doesn't use log.h
858 // In certain cases, output info level on stderr
859 if(cmd_args.getFlag("info") || cmd_args.getFlag("verbose") ||
860 cmd_args.getFlag("trace") || cmd_args.getFlag("speedtests"))
861 log_add_output(&main_stderr_log_out, LMT_INFO);
862 // In certain cases, output verbose level on stderr
863 if(cmd_args.getFlag("verbose") || cmd_args.getFlag("trace"))
864 log_add_output(&main_stderr_log_out, LMT_VERBOSE);
866 porting::signal_handler_init();
867 bool &kill = *porting::signal_handler_killstatus();
869 porting::initializePaths();
871 // Create user data directory
872 fs::CreateDir(porting::path_user);
874 infostream<<"path_share = "<<porting::path_share<<std::endl;
875 infostream<<"path_user = "<<porting::path_user<<std::endl;
877 // Initialize debug stacks
879 DSTACK(__FUNCTION_NAME);
882 BEGIN_DEBUG_EXCEPTION_HANDLER
884 // List gameids if requested
885 if(cmd_args.exists("gameid") && cmd_args.get("gameid") == "list")
887 std::set<std::string> gameids = getAvailableGameIds();
888 for(std::set<std::string>::const_iterator i = gameids.begin();
889 i != gameids.end(); i++)
890 dstream<<(*i)<<std::endl;
894 // List worlds if requested
895 if(cmd_args.exists("world") && cmd_args.get("world") == "list"){
896 dstream<<_("Available worlds:")<<std::endl;
897 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
898 print_worldspecs(worldspecs, dstream);
902 // Print startup message
903 infostream<<PROJECT_NAME<<
904 " "<<_("with")<<" SER_FMT_VER_HIGHEST_READ="<<(int)SER_FMT_VER_HIGHEST_READ
905 <<", "<<minetest_build_info
912 // Initialize default settings
913 set_default_settings(g_settings);
915 // Initialize sockets
917 atexit(sockets_cleanup);
923 // Path of configuration file in use
924 g_settings_path = "";
926 if(cmd_args.exists("config"))
928 bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
931 errorstream<<"Could not read configuration from \""
932 <<cmd_args.get("config")<<"\""<<std::endl;
935 g_settings_path = cmd_args.get("config");
939 std::vector<std::string> filenames;
940 filenames.push_back(porting::path_user +
941 DIR_DELIM + "minetest.conf");
942 // Legacy configuration file location
943 filenames.push_back(porting::path_user +
944 DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
946 // Try also from a lower level (to aid having the same configuration
947 // for many RUN_IN_PLACE installs)
948 filenames.push_back(porting::path_user +
949 DIR_DELIM + ".." + DIR_DELIM + ".." + DIR_DELIM + "minetest.conf");
952 for(u32 i=0; i<filenames.size(); i++)
954 bool r = g_settings->readConfigFile(filenames[i].c_str());
957 g_settings_path = filenames[i];
962 // If no path found, use the first one (menu creates the file)
963 if(g_settings_path == "")
964 g_settings_path = filenames[0];
967 // Initialize debug streams
968 #define DEBUGFILE "debug.txt"
970 std::string logfile = DEBUGFILE;
972 std::string logfile = porting::path_user+DIR_DELIM+DEBUGFILE;
974 if(cmd_args.exists("logfile"))
975 logfile = cmd_args.get("logfile");
977 log_remove_output(&main_dstream_no_stderr_log_out);
978 int loglevel = g_settings->getS32("debug_log_level");
980 if (loglevel == 0) //no logging
982 else if (loglevel > 0 && loglevel <= LMT_NUM_VALUES)
983 log_add_output_maxlev(&main_dstream_no_stderr_log_out, (LogMessageLevel)(loglevel - 1));
986 debugstreams_init(false, logfile.c_str());
988 debugstreams_init(false, NULL);
990 infostream<<"logfile = "<<logfile<<std::endl;
992 // Initialize random seed
996 // Initialize HTTP fetcher
997 httpfetch_init(g_settings->getS32("curl_parallel_limit"));
1003 if((ENABLE_TESTS && cmd_args.getFlag("disable-unittests") == false)
1004 || cmd_args.getFlag("enable-unittests") == true)
1009 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),g_settings->get("language"),argc,argv);
1011 init_gettext((porting::path_share + DIR_DELIM + "locale").c_str(),g_settings->get("language"));
1020 if(cmd_args.exists("port"))
1021 port = cmd_args.getU16("port");
1022 else if(g_settings->exists("port"))
1023 port = g_settings->getU16("port");
1028 std::string bind_str = g_settings->get("bind_address");
1029 Address bind_addr(0,0,0,0, port);
1031 bind_addr.Resolve(bind_str.c_str());
1032 } catch (ResolveError &e) {
1033 infostream << "Resolving bind address \"" << bind_str
1034 << "\" failed: " << e.what()
1035 << " -- Listening on all addresses." << std::endl;
1037 if (g_settings->getBool("ipv6_server")) {
1038 bind_addr.setAddress((IPv6AddressBytes*) NULL);
1043 std::string commanded_world = "";
1044 if(cmd_args.exists("world"))
1045 commanded_world = cmd_args.get("world");
1046 else if(cmd_args.exists("map-dir"))
1047 commanded_world = cmd_args.get("map-dir");
1048 else if(cmd_args.exists("nonopt0")) // First nameless argument
1049 commanded_world = cmd_args.get("nonopt0");
1050 else if(g_settings->exists("map-dir"))
1051 commanded_world = g_settings->get("map-dir");
1054 std::string commanded_worldname = "";
1055 if(cmd_args.exists("worldname"))
1056 commanded_worldname = cmd_args.get("worldname");
1058 // Strip world.mt from commanded_world
1060 std::string worldmt = "world.mt";
1061 if(commanded_world.size() > worldmt.size() &&
1062 commanded_world.substr(commanded_world.size()-worldmt.size())
1064 dstream<<_("Supplied world.mt file - stripping it off.")<<std::endl;
1065 commanded_world = commanded_world.substr(
1066 0, commanded_world.size()-worldmt.size());
1070 // If a world name was specified, convert it to a path
1071 if(commanded_worldname != ""){
1072 // Get information about available worlds
1073 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1075 for(u32 i=0; i<worldspecs.size(); i++){
1076 std::string name = worldspecs[i].name;
1077 if(name == commanded_worldname){
1078 if(commanded_world != ""){
1079 dstream<<_("--worldname takes precedence over previously "
1080 "selected world.")<<std::endl;
1082 commanded_world = worldspecs[i].path;
1088 dstream<<_("World")<<" '"<<commanded_worldname<<_("' not "
1089 "available. Available worlds:")<<std::endl;
1090 print_worldspecs(worldspecs, dstream);
1096 SubgameSpec commanded_gamespec;
1097 if(cmd_args.exists("gameid")){
1098 std::string gameid = cmd_args.get("gameid");
1099 commanded_gamespec = findSubgame(gameid);
1100 if(!commanded_gamespec.isValid()){
1101 errorstream<<"Game \""<<gameid<<"\" not found"<<std::endl;
1108 Run dedicated server if asked to or no other option
1111 bool run_dedicated_server = true;
1113 bool run_dedicated_server = cmd_args.getFlag("server");
1115 g_settings->set("server_dedicated", run_dedicated_server ? "true" : "false");
1116 if(run_dedicated_server)
1118 DSTACK("Dedicated server branch");
1119 // Create time getter if built with Irrlicht
1121 g_timegetter = new SimpleTimeGetter();
1125 std::string world_path;
1126 verbosestream<<_("Determining world path")<<std::endl;
1127 bool is_legacy_world = false;
1128 // If a world was commanded, use it
1129 if(commanded_world != ""){
1130 world_path = commanded_world;
1131 infostream<<"Using commanded world path ["<<world_path<<"]"
1134 // No world was specified; try to select it automatically
1137 // Get information about available worlds
1138 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1139 // If a world name was specified, select it
1140 if(commanded_worldname != ""){
1142 for(u32 i=0; i<worldspecs.size(); i++){
1143 std::string name = worldspecs[i].name;
1144 if(name == commanded_worldname){
1145 world_path = worldspecs[i].path;
1149 if(world_path == ""){
1150 dstream<<_("World")<<" '"<<commanded_worldname<<"' "<<_("not "
1151 "available. Available worlds:")<<std::endl;
1152 print_worldspecs(worldspecs, dstream);
1156 // If there is only a single world, use it
1157 if(worldspecs.size() == 1){
1158 world_path = worldspecs[0].path;
1159 dstream<<_("Automatically selecting world at")<<" ["
1160 <<world_path<<"]"<<std::endl;
1161 // If there are multiple worlds, list them
1162 } else if(worldspecs.size() > 1){
1163 dstream<<_("Multiple worlds are available.")<<std::endl;
1164 dstream<<_("Please select one using --worldname <name>"
1165 " or --world <path>")<<std::endl;
1166 print_worldspecs(worldspecs, dstream);
1168 // If there are no worlds, automatically create a new one
1170 // This is the ultimate default world path
1171 world_path = porting::path_user + DIR_DELIM + "worlds" +
1172 DIR_DELIM + "world";
1173 infostream<<"Creating default world at ["
1174 <<world_path<<"]"<<std::endl;
1178 if(world_path == ""){
1179 errorstream<<"No world path specified or found."<<std::endl;
1182 verbosestream<<_("Using world path")<<" ["<<world_path<<"]"<<std::endl;
1184 // We need a gamespec.
1185 SubgameSpec gamespec;
1186 verbosestream<<_("Determining gameid/gamespec")<<std::endl;
1187 // If world doesn't exist
1188 if(!getWorldExists(world_path))
1190 // Try to take gamespec from command line
1191 if(commanded_gamespec.isValid()){
1192 gamespec = commanded_gamespec;
1193 infostream<<"Using commanded gameid ["<<gamespec.id<<"]"<<std::endl;
1195 // Otherwise we will be using "minetest"
1197 gamespec = findSubgame(g_settings->get("default_game"));
1198 infostream<<"Using default gameid ["<<gamespec.id<<"]"<<std::endl;
1204 std::string world_gameid = getWorldGameId(world_path, is_legacy_world);
1205 // If commanded to use a gameid, do so
1206 if(commanded_gamespec.isValid()){
1207 gamespec = commanded_gamespec;
1208 if(commanded_gamespec.id != world_gameid){
1209 errorstream<<"WARNING: Using commanded gameid ["
1210 <<gamespec.id<<"]"<<" instead of world gameid ["
1211 <<world_gameid<<"]"<<std::endl;
1214 // If world contains an embedded game, use it;
1215 // Otherwise find world from local system.
1216 gamespec = findWorldSubgame(world_path);
1217 infostream<<"Using world gameid ["<<gamespec.id<<"]"<<std::endl;
1220 if(!gamespec.isValid()){
1221 errorstream<<"Subgame ["<<gamespec.id<<"] could not be found."
1225 verbosestream<<_("Using gameid")<<" ["<<gamespec.id<<"]"<<std::endl;
1228 Server server(world_path, gamespec, false);
1230 // Database migration
1231 if (cmd_args.exists("migrate")) {
1232 std::string migrate_to = cmd_args.get("migrate");
1234 bool success = world_mt.readConfigFile((world_path + DIR_DELIM + "world.mt").c_str());
1236 errorstream << "Cannot read world.mt" << std::endl;
1239 if (!world_mt.exists("backend")) {
1240 errorstream << "Please specify your current backend in world.mt file:"
1241 << std::endl << " backend = {sqlite3|leveldb|dummy}" << std::endl;
1244 std::string backend = world_mt.get("backend");
1246 if (backend == migrate_to) {
1247 errorstream << "Cannot migrate: new backend is same as the old one" << std::endl;
1250 if (migrate_to == "sqlite3")
1251 new_db = new Database_SQLite3(&(ServerMap&)server.getMap(), world_path);
1253 else if (migrate_to == "leveldb")
1254 new_db = new Database_LevelDB(&(ServerMap&)server.getMap(), world_path);
1257 errorstream << "Migration to " << migrate_to << " is not supported" << std::endl;
1261 std::list<v3s16> blocks;
1262 ServerMap &old_map = ((ServerMap&)server.getMap());
1263 old_map.listAllLoadableBlocks(blocks);
1265 new_db->beginSave();
1266 for (std::list<v3s16>::iterator i = blocks.begin(); i != blocks.end(); ++i) {
1267 MapBlock *block = old_map.loadBlock(*i);
1268 new_db->saveBlock(block);
1269 MapSector *sector = old_map.getSectorNoGenerate(v2s16(i->X, i->Z));
1270 sector->deleteBlock(block);
1272 if (count % 500 == 0)
1273 actionstream << "Migrated " << count << " blocks "
1274 << (100.0 * count / blocks.size()) << "% completed" << std::endl;
1279 actionstream << "Successfully migrated " << count << " blocks" << std::endl;
1280 world_mt.set("backend", migrate_to);
1281 if(!world_mt.updateConfigFile((world_path + DIR_DELIM + "world.mt").c_str()))
1282 errorstream<<"Failed to update world.mt!"<<std::endl;
1284 actionstream<<"world.mt updated"<<std::endl;
1289 server.start(bind_addr);
1292 dedicated_server_loop(server, kill);
1297 #ifndef SERVER // Exclude from dedicated server build
1303 std::string address = g_settings->get("address");
1304 if(commanded_world != "")
1306 else if(cmd_args.exists("address"))
1307 address = cmd_args.get("address");
1309 std::string playername = g_settings->get("name");
1310 if(cmd_args.exists("name"))
1311 playername = cmd_args.get("name");
1313 bool skip_main_menu = cmd_args.getFlag("go");
1316 Device initialization
1319 // Resolution selection
1321 bool fullscreen = g_settings->getBool("fullscreen");
1322 u16 screenW = g_settings->getU16("screenW");
1323 u16 screenH = g_settings->getU16("screenH");
1327 bool vsync = g_settings->getBool("vsync");
1328 u16 bits = g_settings->getU16("fullscreen_bpp");
1329 u16 fsaa = g_settings->getU16("fsaa");
1333 video::E_DRIVER_TYPE driverType;
1335 std::string driverstring = g_settings->get("video_driver");
1337 if(driverstring == "null")
1338 driverType = video::EDT_NULL;
1339 else if(driverstring == "software")
1340 driverType = video::EDT_SOFTWARE;
1341 else if(driverstring == "burningsvideo")
1342 driverType = video::EDT_BURNINGSVIDEO;
1343 else if(driverstring == "direct3d8")
1344 driverType = video::EDT_DIRECT3D8;
1345 else if(driverstring == "direct3d9")
1346 driverType = video::EDT_DIRECT3D9;
1347 else if(driverstring == "opengl")
1348 driverType = video::EDT_OPENGL;
1349 #ifdef _IRR_COMPILE_WITH_OGLES1_
1350 else if(driverstring == "ogles1")
1351 driverType = video::EDT_OGLES1;
1353 #ifdef _IRR_COMPILE_WITH_OGLES2_
1354 else if(driverstring == "ogles2")
1355 driverType = video::EDT_OGLES2;
1359 errorstream<<"WARNING: Invalid video_driver specified; defaulting "
1360 "to opengl"<<std::endl;
1361 driverType = video::EDT_OPENGL;
1365 List video modes if requested
1368 MyEventReceiver receiver;
1370 if(cmd_args.getFlag("videomodes")){
1371 IrrlichtDevice *nulldevice;
1373 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1374 params.DriverType = video::EDT_NULL;
1375 params.WindowSize = core::dimension2d<u32>(640, 480);
1377 params.AntiAlias = fsaa;
1378 params.Fullscreen = false;
1379 params.Stencilbuffer = false;
1380 params.Vsync = vsync;
1381 params.EventReceiver = &receiver;
1382 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
1384 nulldevice = createDeviceEx(params);
1389 dstream<<_("Available video modes (WxHxD):")<<std::endl;
1391 video::IVideoModeList *videomode_list =
1392 nulldevice->getVideoModeList();
1394 if(videomode_list == 0){
1399 s32 videomode_count = videomode_list->getVideoModeCount();
1400 core::dimension2d<u32> videomode_res;
1401 s32 videomode_depth;
1402 for (s32 i = 0; i < videomode_count; ++i){
1403 videomode_res = videomode_list->getVideoModeResolution(i);
1404 videomode_depth = videomode_list->getVideoModeDepth(i);
1405 dstream<<videomode_res.Width<<"x"<<videomode_res.Height
1406 <<"x"<<videomode_depth<<std::endl;
1409 dstream<<_("Active video mode (WxHxD):")<<std::endl;
1410 videomode_res = videomode_list->getDesktopResolution();
1411 videomode_depth = videomode_list->getDesktopDepth();
1412 dstream<<videomode_res.Width<<"x"<<videomode_res.Height
1413 <<"x"<<videomode_depth<<std::endl;
1421 Create device and exit if creation failed
1424 IrrlichtDevice *device;
1426 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
1427 params.DriverType = driverType;
1428 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
1430 params.AntiAlias = fsaa;
1431 params.Fullscreen = fullscreen;
1432 params.Stencilbuffer = false;
1433 params.Vsync = vsync;
1434 params.EventReceiver = &receiver;
1435 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
1437 device = createDeviceEx(params);
1440 return 1; // could not create selected driver.
1443 Continue initialization
1446 video::IVideoDriver* driver = device->getVideoDriver();
1449 This changes the minimum allowed number of vertices in a VBO.
1452 //driver->setMinHardwareBufferVertexCount(50);
1454 // Create time getter
1455 g_timegetter = new IrrlichtTimeGetter(device);
1457 // Create game callback for menus
1458 g_gamecallback = new MainGameCallback(device);
1461 Speed tests (done after irrlicht is loaded to get timer)
1463 if(cmd_args.getFlag("speedtests"))
1465 dstream<<"Running speed tests"<<std::endl;
1471 device->setResizable(true);
1473 bool random_input = g_settings->getBool("random_input")
1474 || cmd_args.getFlag("random-input");
1475 InputHandler *input = NULL;
1477 input = new RandomInputHandler();
1479 input = new RealInputHandler(device, &receiver);
1481 scene::ISceneManager* smgr = device->getSceneManager();
1483 guienv = device->getGUIEnvironment();
1484 gui::IGUISkin* skin = guienv->getSkin();
1485 std::string font_path = g_settings->get("font_path");
1486 gui::IGUIFont *font;
1488 bool use_freetype = g_settings->getBool("freetype");
1490 std::string fallback;
1491 if (is_yes(gettext("needs_fallback_font")))
1492 fallback = "fallback_";
1493 u16 font_size = g_settings->getU16(fallback + "font_size");
1494 font_path = g_settings->get(fallback + "font_path");
1495 u32 font_shadow = g_settings->getU16(fallback + "font_shadow");
1496 u32 font_shadow_alpha = g_settings->getU16(fallback + "font_shadow_alpha");
1497 font = gui::CGUITTFont::createTTFont(guienv, font_path.c_str(), font_size, true, true, font_shadow, font_shadow_alpha);
1499 font = guienv->getFont(font_path.c_str());
1502 font = guienv->getFont(font_path.c_str());
1505 skin->setFont(font);
1507 errorstream<<"WARNING: Font file was not found."
1508 " Using default font."<<std::endl;
1509 // If font was not found, this will get us one
1510 font = skin->getFont();
1513 u32 text_height = font->getDimension(L"Hello, world!").Height;
1514 infostream<<"text_height="<<text_height<<std::endl;
1516 //skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,0,0,0));
1517 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255,255,255,255));
1518 //skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(0,0,0,0));
1519 //skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(0,0,0,0));
1520 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255,0,0,0));
1521 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255,0,0,0));
1522 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255,70,100,50));
1523 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255,255,255,255));
1525 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
1526 // Irrlicht 1.8 input colours
1527 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255,128,128,128));
1528 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255,96,134,49));
1532 // Create the menu clouds
1533 if (!g_menucloudsmgr)
1534 g_menucloudsmgr = smgr->createNewSceneManager();
1536 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
1537 g_menucloudsmgr, -1, rand(), 100);
1538 g_menuclouds->update(v2f(0, 0), video::SColor(255,200,200,255));
1539 scene::ICameraSceneNode* camera;
1540 camera = g_menucloudsmgr->addCameraSceneNode(0,
1541 v3f(0,0,0), v3f(0, 60, 100));
1542 camera->setFarValue(10000);
1548 ChatBackend chat_backend;
1551 If an error occurs, this is set to something and the
1552 menu-game loop is restarted. It is then displayed before
1555 std::wstring error_message = L"";
1557 // The password entered during the menu screen,
1558 std::string password;
1560 bool first_loop = true;
1565 while(device->run() && kill == false)
1567 // Set the window caption
1568 wchar_t* text = wgettext("Main Menu");
1569 device->setWindowCaption((std::wstring(L"Minetest [")+text+L"]").c_str());
1572 // This is used for catching disconnects
1577 Clear everything from the GUIEnvironment
1582 We need some kind of a root node to be able to add
1583 custom gui elements directly on the screen.
1584 Otherwise they won't be automatically drawn.
1586 guiroot = guienv->addStaticText(L"",
1587 core::rect<s32>(0, 0, 10000, 10000));
1589 SubgameSpec gamespec;
1590 WorldSpec worldspec;
1591 bool simple_singleplayer_mode = false;
1593 // These are set up based on the menu and other things
1594 std::string current_playername = "inv£lid";
1595 std::string current_password = "";
1596 std::string current_address = "does-not-exist";
1597 int current_port = 0;
1600 Out-of-game menu loop.
1602 Loop quits when menu returns proper parameters.
1604 while(kill == false)
1606 // If skip_main_menu, only go through here once
1607 if(skip_main_menu && !first_loop){
1613 // Cursor can be non-visible when coming from the game
1614 device->getCursorControl()->setVisible(true);
1615 // Some stuff are left to scene manager when coming from the game
1619 // Initialize menu data
1620 MainMenuData menudata;
1621 menudata.address = address;
1622 menudata.name = playername;
1623 menudata.port = itos(port);
1624 menudata.errormessage = wide_to_narrow(error_message);
1625 error_message = L"";
1626 if(cmd_args.exists("password"))
1627 menudata.password = cmd_args.get("password");
1629 driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
1631 menudata.enable_public = g_settings->getBool("server_announce");
1633 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
1635 // If a world was commanded, append and select it
1636 if(commanded_world != ""){
1638 std::string gameid = getWorldGameId(commanded_world, true);
1639 std::string name = _("[--world parameter]");
1641 gameid = g_settings->get("default_game");
1644 //TODO find within worldspecs and set config
1647 if(skip_main_menu == false)
1649 video::IVideoDriver* driver = device->getVideoDriver();
1651 infostream<<"Waiting for other menus"<<std::endl;
1652 while(device->run() && kill == false)
1656 driver->beginScene(true, true,
1657 video::SColor(255,128,128,128));
1660 // On some computers framerate doesn't seem to be
1661 // automatically limited
1664 infostream<<"Waited for other menus"<<std::endl;
1666 GUIEngine* temp = new GUIEngine(device, guiroot, &g_menumgr,smgr,&menudata,kill);
1669 //once finished you'll never end up here
1673 if(menudata.errormessage != ""){
1674 error_message = narrow_to_wide(menudata.errormessage);
1678 //update worldspecs (necessary as new world may have been created)
1679 worldspecs = getAvailableWorlds();
1681 if (menudata.name == "")
1682 menudata.name = std::string("Guest") + itos(myrand_range(1000,9999));
1684 playername = menudata.name;
1686 password = translatePassword(playername, narrow_to_wide(menudata.password));
1687 //infostream<<"Main: password hash: '"<<password<<"'"<<std::endl;
1689 address = menudata.address;
1690 int newport = stoi(menudata.port);
1694 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
1697 g_settings->set("name", playername);
1699 if((menudata.selected_world >= 0) &&
1700 (menudata.selected_world < (int)worldspecs.size()))
1701 g_settings->set("selected_world_path",
1702 worldspecs[menudata.selected_world].path);
1704 // Break out of menu-game loop to shut down cleanly
1705 if(device->run() == false || kill == true)
1708 current_playername = playername;
1709 current_password = password;
1710 current_address = address;
1711 current_port = port;
1713 // If using simple singleplayer mode, override
1714 if(simple_singleplayer_mode){
1715 current_playername = "singleplayer";
1716 current_password = "";
1717 current_address = "";
1718 current_port = myrand_range(49152, 65535);
1720 else if (address != "")
1722 ServerListSpec server;
1723 server["name"] = menudata.servername;
1724 server["address"] = menudata.address;
1725 server["port"] = menudata.port;
1726 server["description"] = menudata.serverdescription;
1727 ServerList::insert(server);
1730 // Set world path to selected one
1731 if ((menudata.selected_world >= 0) &&
1732 (menudata.selected_world < (int)worldspecs.size())) {
1733 worldspec = worldspecs[menudata.selected_world];
1734 infostream<<"Selected world: "<<worldspec.name
1735 <<" ["<<worldspec.path<<"]"<<std::endl;
1739 if(current_address == "")
1741 if(menudata.selected_world == -1){
1742 error_message = wgettext("No world selected and no address "
1743 "provided. Nothing to do.");
1744 errorstream<<wide_to_narrow(error_message)<<std::endl;
1747 // Load gamespec for required game
1748 gamespec = findWorldSubgame(worldspec.path);
1749 if(!gamespec.isValid() && !commanded_gamespec.isValid()){
1750 error_message = wgettext("Could not find or load game \"")
1751 + narrow_to_wide(worldspec.gameid) + L"\"";
1752 errorstream<<wide_to_narrow(error_message)<<std::endl;
1755 if(commanded_gamespec.isValid() &&
1756 commanded_gamespec.id != worldspec.gameid){
1757 errorstream<<"WARNING: Overriding gamespec from \""
1758 <<worldspec.gameid<<"\" to \""
1759 <<commanded_gamespec.id<<"\""<<std::endl;
1760 gamespec = commanded_gamespec;
1763 if(!gamespec.isValid()){
1764 error_message = wgettext("Invalid gamespec.");
1765 error_message += L" (world_gameid="
1766 +narrow_to_wide(worldspec.gameid)+L")";
1767 errorstream<<wide_to_narrow(error_message)<<std::endl;
1776 // Break out of menu-game loop to shut down cleanly
1777 if(device->run() == false || kill == true) {
1778 if(g_settings_path != "") {
1779 g_settings->updateConfigFile(
1780 g_settings_path.c_str());
1802 simple_singleplayer_mode
1807 catch(con::PeerNotFoundException &e)
1809 error_message = wgettext("Connection error (timed out?)");
1810 errorstream<<wide_to_narrow(error_message)<<std::endl;
1813 catch(std::exception &e)
1815 std::string narrow_message = "Some exception: \"";
1816 narrow_message += e.what();
1817 narrow_message += "\"";
1818 errorstream<<narrow_message<<std::endl;
1819 error_message = narrow_to_wide(narrow_message);
1823 // If no main menu, show error and exit
1826 if(error_message != L""){
1827 verbosestream<<"error_message = "
1828 <<wide_to_narrow(error_message)<<std::endl;
1836 g_menuclouds->drop();
1837 g_menucloudsmgr->drop();
1842 In the end, delete the Irrlicht device.
1853 // Update configuration file
1854 if(g_settings_path != "")
1855 g_settings->updateConfigFile(g_settings_path.c_str());
1857 // Print modified quicktune values
1859 bool header_printed = false;
1860 std::vector<std::string> names = getQuicktuneNames();
1861 for(u32 i=0; i<names.size(); i++){
1862 QuicktuneValue val = getQuicktuneValue(names[i]);
1865 if(!header_printed){
1866 dstream<<"Modified quicktune values:"<<std::endl;
1867 header_printed = true;
1869 dstream<<names[i]<<" = "<<val.getString()<<std::endl;
1873 // Stop httpfetch thread (if started)
1874 httpfetch_cleanup();
1876 END_DEBUG_EXCEPTION_HANDLER(errorstream)
1878 debugstreams_deinit();