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.
21 #include "mainmenumanager.h"
26 #include "guiMainMenu.h"
32 #include "serverlist.h"
33 #include "guiEngine.h"
35 #include "fontengine.h"
36 #include "clientlauncher.h"
38 // A pointer to a global instance of the time getter
40 TimeGetter *g_timegetter = NULL;
44 if (g_timegetter == NULL)
46 return g_timegetter->getTime(PRECISION_MILLI);
49 u32 getTime(TimePrecision prec) {
50 if (g_timegetter == NULL)
52 return g_timegetter->getTime(prec);
55 ClientLauncher::~ClientLauncher()
71 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
73 init_args(game_params, cmd_args);
75 // List video modes if requested
77 return print_video_modes();
79 if (!init_engine(game_params.log_level)) {
80 errorstream << "Could not initialize game engine." << std::endl;
84 // Speed tests (done after irrlicht is loaded to get timer)
85 if (cmd_args.getFlag("speedtests")) {
86 dstream << "Running speed tests" << std::endl;
91 video::IVideoDriver *video_driver = device->getVideoDriver();
92 if (video_driver == NULL) {
93 errorstream << "Could not initialize video driver." << std::endl;
97 porting::setXorgClassHint(video_driver->getExposedVideoData(), "Minetest");
100 This changes the minimum allowed number of vertices in a VBO.
103 //driver->setMinHardwareBufferVertexCount(50);
105 // Create time getter
106 g_timegetter = new IrrlichtTimeGetter(device);
108 // Create game callback for menus
109 g_gamecallback = new MainGameCallback(device);
111 device->setResizable(true);
114 input = new RandomInputHandler();
116 input = new RealInputHandler(device, receiver);
118 smgr = device->getSceneManager();
120 guienv = device->getGUIEnvironment();
121 skin = guienv->getSkin();
122 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
123 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
124 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
125 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
126 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
127 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
129 g_fontengine = new FontEngine(g_settings, guienv);
130 assert(g_fontengine != NULL);
132 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
133 // Irrlicht 1.8 input colours
134 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
135 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
138 // Create the menu clouds
139 if (!g_menucloudsmgr)
140 g_menucloudsmgr = smgr->createNewSceneManager();
142 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
143 g_menucloudsmgr, -1, rand(), 100);
144 g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
145 scene::ICameraSceneNode* camera;
146 camera = g_menucloudsmgr->addCameraSceneNode(0,
147 v3f(0, 0, 0), v3f(0, 60, 100));
148 camera->setFarValue(10000);
154 ChatBackend chat_backend;
156 // If an error occurs, this is set to something by menu().
157 // It is then displayed before the menu shows on the next call to menu()
158 std::wstring error_message = L"";
160 bool first_loop = true;
166 bool *kill = porting::signal_handler_killstatus();
168 while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
170 // Set the window caption
171 const wchar_t *text = wgettext("Main Menu");
172 device->setWindowCaption((std::wstring(L"Minetest [") + text + L"]").c_str());
175 try { // This is used for catching disconnects
180 We need some kind of a root node to be able to add
181 custom gui elements directly on the screen.
182 Otherwise they won't be automatically drawn.
184 guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
186 bool game_has_run = launch_game(&error_message, game_params, cmd_args);
188 // If skip_main_menu, we only want to startup once
189 if (skip_main_menu && !first_loop)
201 // Break out of menu-game loop to shut down cleanly
202 if (!device->run() || *kill) {
203 if (g_settings_path != "")
204 g_settings->updateConfigFile(g_settings_path.c_str());
208 if (current_playername.length() > PLAYERNAME_SIZE-1) {
209 error_message = wgettext("Player name too long.");
210 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
211 g_settings->set("name", playername);
215 device->getVideoDriver()->setTextureCreationFlag(
216 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
218 #ifdef HAVE_TOUCHSCREENGUI
219 receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
220 g_touchscreengui = receiver->m_touchscreengui;
235 simple_singleplayer_mode
239 #ifdef HAVE_TOUCHSCREENGUI
240 delete g_touchscreengui;
241 g_touchscreengui = NULL;
242 receiver->m_touchscreengui = NULL;
246 catch (con::PeerNotFoundException &e) {
247 error_message = wgettext("Connection error (timed out?)");
248 errorstream << wide_to_narrow(error_message) << std::endl;
252 catch (std::exception &e) {
253 std::string narrow_message = "Some exception: \"";
254 narrow_message += e.what();
255 narrow_message += "\"";
256 errorstream << narrow_message << std::endl;
257 error_message = narrow_to_wide(narrow_message);
261 // If no main menu, show error and exit
262 if (skip_main_menu) {
263 if (error_message != L"") {
264 verbosestream << "error_message = "
265 << wide_to_narrow(error_message) << std::endl;
272 g_menuclouds->drop();
273 g_menucloudsmgr->drop();
278 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
281 skip_main_menu = cmd_args.getFlag("go");
283 // FIXME: This is confusing (but correct)
285 /* If world_path is set then override it unless skipping the main menu using
286 * the --go command line param. Else, give preference to the address
287 * supplied on the command line
289 address = g_settings->get("address");
290 if (game_params.world_path != "" && !skip_main_menu)
292 else if (cmd_args.exists("address"))
293 address = cmd_args.get("address");
295 playername = g_settings->get("name");
296 if (cmd_args.exists("name"))
297 playername = cmd_args.get("name");
299 list_video_modes = cmd_args.getFlag("videomodes");
301 use_freetype = g_settings->getBool("freetype");
303 random_input = g_settings->getBool("random_input")
304 || cmd_args.getFlag("random-input");
307 bool ClientLauncher::init_engine(int log_level)
309 receiver = new MyEventReceiver();
310 create_engine_device(log_level);
311 return device != NULL;
314 bool ClientLauncher::launch_game(std::wstring *error_message,
315 GameParams &game_params, const Settings &cmd_args)
317 // Initialize menu data
318 MainMenuData menudata;
319 menudata.address = address;
320 menudata.name = playername;
321 menudata.port = itos(game_params.socket_port);
322 menudata.errormessage = wide_to_narrow(*error_message);
324 *error_message = L"";
326 if (cmd_args.exists("password"))
327 menudata.password = cmd_args.get("password");
329 menudata.enable_public = g_settings->getBool("server_announce");
331 // If a world was commanded, append and select it
332 if (game_params.world_path != "") {
333 worldspec.gameid = getWorldGameId(game_params.world_path, true);
334 worldspec.name = _("[--world parameter]");
336 if (worldspec.gameid == "") { // Create new
337 worldspec.gameid = g_settings->get("default_game");
338 worldspec.name += " [new]";
340 worldspec.path = game_params.world_path;
345 if (!skip_main_menu) {
346 main_menu(&menudata);
348 // Skip further loading if there was an exit signal.
349 if (*porting::signal_handler_killstatus())
352 address = menudata.address;
353 int newport = stoi(menudata.port);
355 game_params.socket_port = newport;
357 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
359 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
361 if (menudata.selected_world >= 0
362 && menudata.selected_world < (int)worldspecs.size()) {
363 g_settings->set("selected_world_path",
364 worldspecs[menudata.selected_world].path);
365 worldspec = worldspecs[menudata.selected_world];
369 if (menudata.errormessage != "") {
370 /* The calling function will pass this back into this function upon the
371 * next iteration (if any) causing it to be displayed by the GUI
373 *error_message = narrow_to_wide(menudata.errormessage);
377 if (menudata.name == "")
378 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
380 playername = menudata.name;
382 password = translatePassword(playername, narrow_to_wide(menudata.password));
384 g_settings->set("name", playername);
386 current_playername = playername;
387 current_password = password;
388 current_address = address;
389 current_port = game_params.socket_port;
391 // If using simple singleplayer mode, override
392 if (simple_singleplayer_mode) {
393 assert(skip_main_menu == false);
394 current_playername = "singleplayer";
395 current_password = "";
396 current_address = "";
397 current_port = myrand_range(49152, 65535);
398 } else if (address != "") {
399 ServerListSpec server;
400 server["name"] = menudata.servername;
401 server["address"] = menudata.address;
402 server["port"] = menudata.port;
403 server["description"] = menudata.serverdescription;
404 ServerList::insert(server);
407 infostream << "Selected world: " << worldspec.name
408 << " [" << worldspec.path << "]" << std::endl;
410 if (current_address == "") { // If local game
411 if (worldspec.path == "") {
412 *error_message = wgettext("No world selected and no address "
413 "provided. Nothing to do.");
414 errorstream << wide_to_narrow(*error_message) << std::endl;
418 if (!fs::PathExists(worldspec.path)) {
419 *error_message = wgettext("Provided world path doesn't exist: ")
420 + narrow_to_wide(worldspec.path);
421 errorstream << wide_to_narrow(*error_message) << std::endl;
425 // Load gamespec for required game
426 gamespec = findWorldSubgame(worldspec.path);
427 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
428 *error_message = wgettext("Could not find or load game \"")
429 + narrow_to_wide(worldspec.gameid) + L"\"";
430 errorstream << wide_to_narrow(*error_message) << std::endl;
434 if (porting::signal_handler_killstatus())
437 if (game_params.game_spec.isValid() &&
438 game_params.game_spec.id != worldspec.gameid) {
439 errorstream << "WARNING: Overriding gamespec from \""
440 << worldspec.gameid << "\" to \""
441 << game_params.game_spec.id << "\"" << std::endl;
442 gamespec = game_params.game_spec;
445 if (!gamespec.isValid()) {
446 *error_message = wgettext("Invalid gamespec.");
447 *error_message += L" (world_gameid="
448 + narrow_to_wide(worldspec.gameid) + L")";
449 errorstream << wide_to_narrow(*error_message) << std::endl;
457 void ClientLauncher::main_menu(MainMenuData *menudata)
459 bool *kill = porting::signal_handler_killstatus();
460 video::IVideoDriver *driver = device->getVideoDriver();
462 infostream << "Waiting for other menus" << std::endl;
463 while (device->run() && *kill == false) {
466 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
469 // On some computers framerate doesn't seem to be automatically limited
472 infostream << "Waited for other menus" << std::endl;
474 // Cursor can be non-visible when coming from the game
476 device->getCursorControl()->setVisible(true);
480 GUIEngine mymenu(device, guiroot, &g_menumgr, smgr, menudata, *kill);
482 smgr->clear(); /* leave scene manager in a clean state */
485 bool ClientLauncher::create_engine_device(int log_level)
487 static const irr::ELOG_LEVEL irr_log_level[5] = {
492 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
499 // Resolution selection
500 bool fullscreen = g_settings->getBool("fullscreen");
501 u16 screenW = g_settings->getU16("screenW");
502 u16 screenH = g_settings->getU16("screenH");
505 bool vsync = g_settings->getBool("vsync");
506 u16 bits = g_settings->getU16("fullscreen_bpp");
507 u16 fsaa = g_settings->getU16("fsaa");
510 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
511 std::string driverstring = g_settings->get("video_driver");
512 std::vector<video::E_DRIVER_TYPE> drivers
513 = porting::getSupportedVideoDrivers();
515 for (i = 0; i != drivers.size(); i++) {
516 if (!strcasecmp(driverstring.c_str(),
517 porting::getVideoDriverName(drivers[i]))) {
518 driverType = drivers[i];
522 if (i == drivers.size()) {
523 errorstream << "Invalid video_driver specified; "
524 "defaulting to opengl" << std::endl;
527 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
528 params.DriverType = driverType;
529 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
531 params.AntiAlias = fsaa;
532 params.Fullscreen = fullscreen;
533 params.Stencilbuffer = false;
534 params.Vsync = vsync;
535 params.EventReceiver = receiver;
536 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
538 params.PrivateData = porting::app_global;
539 params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
540 "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
543 device = createDeviceEx(params);
546 // Map our log level to irrlicht engine one.
547 ILogger* irr_logger = device->getLogger();
548 irr_logger->setLogLevel(irr_log_level[log_level]);
550 porting::initIrrlicht(device);
553 return device != NULL;
556 void ClientLauncher::speed_tests()
558 // volatile to avoid some potential compiler optimisations
559 volatile static s16 temp16;
560 volatile static f32 tempf;
563 static std::string tempstring;
564 static std::string tempstring2;
568 tempstring = std::string();
569 tempstring2 = std::string();
572 infostream << "The following test should take around 20ms." << std::endl;
573 TimeTaker timer("Testing std::string speed");
574 const u32 jj = 10000;
575 for (u32 j = 0; j < jj; j++) {
579 for (u32 i = 0; i < ii; i++) {
580 tempstring2 += "asd";
582 for (u32 i = 0; i < ii+1; i++) {
584 if (tempstring == tempstring2)
590 infostream << "All of the following tests should take around 100ms each."
594 TimeTaker timer("Testing floating-point conversion speed");
596 for (u32 i = 0; i < 4000000; i++) {
603 TimeTaker timer("Testing floating-point vector speed");
605 tempv3f1 = v3f(1, 2, 3);
606 tempv3f2 = v3f(4, 5, 6);
607 for (u32 i = 0; i < 10000000; i++) {
608 tempf += tempv3f1.dotProduct(tempv3f2);
609 tempv3f2 += v3f(7, 8, 9);
614 TimeTaker timer("Testing std::map speed");
616 std::map<v2s16, f32> map1;
619 for (s16 y = 0; y < ii; y++) {
620 for (s16 x = 0; x < ii; x++) {
621 map1[v2s16(x, y)] = tempf;
625 for (s16 y = ii - 1; y >= 0; y--) {
626 for (s16 x = 0; x < ii; x++) {
627 tempf = map1[v2s16(x, y)];
633 infostream << "Around 5000/ms should do well here." << std::endl;
634 TimeTaker timer("Testing mutex speed");
647 while(timer.getTimerTime() < 10);
649 u32 dtime = timer.stop();
650 u32 per_ms = n / dtime;
651 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
655 bool ClientLauncher::print_video_modes()
657 IrrlichtDevice *nulldevice;
659 bool vsync = g_settings->getBool("vsync");
660 u16 fsaa = g_settings->getU16("fsaa");
661 MyEventReceiver* receiver = new MyEventReceiver();
663 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
664 params.DriverType = video::EDT_NULL;
665 params.WindowSize = core::dimension2d<u32>(640, 480);
667 params.AntiAlias = fsaa;
668 params.Fullscreen = false;
669 params.Stencilbuffer = false;
670 params.Vsync = vsync;
671 params.EventReceiver = receiver;
672 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
674 nulldevice = createDeviceEx(params);
676 if (nulldevice == NULL) {
681 dstream << _("Available video modes (WxHxD):") << std::endl;
683 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
685 if (videomode_list != NULL) {
686 s32 videomode_count = videomode_list->getVideoModeCount();
687 core::dimension2d<u32> videomode_res;
689 for (s32 i = 0; i < videomode_count; ++i) {
690 videomode_res = videomode_list->getVideoModeResolution(i);
691 videomode_depth = videomode_list->getVideoModeDepth(i);
692 dstream << videomode_res.Width << "x" << videomode_res.Height
693 << "x" << videomode_depth << std::endl;
696 dstream << _("Active video mode (WxHxD):") << std::endl;
697 videomode_res = videomode_list->getDesktopResolution();
698 videomode_depth = videomode_list->getDesktopDepth();
699 dstream << videomode_res.Width << "x" << videomode_res.Height
700 << "x" << videomode_depth << std::endl;
707 return videomode_list != NULL;