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.
20 #include "mainmenumanager.h"
25 #include "guiMainMenu.h"
31 #include "serverlist.h"
32 #include "guiEngine.h"
34 #include "fontengine.h"
35 #include "joystick_controller.h"
36 #include "clientlauncher.h"
41 gui::IGUIEnvironment *guienv = NULL;
42 gui::IGUIStaticText *guiroot = NULL;
43 MainMenuManager g_menumgr;
47 return g_menumgr.menuCount() == 0;
50 // Passed to menus to allow disconnecting and exiting
51 MainGameCallback *g_gamecallback = NULL;
54 // Instance of the time getter
55 static TimeGetter *g_timegetter = NULL;
59 if (g_timegetter == NULL)
61 return g_timegetter->getTime(PRECISION_MILLI);
64 u32 getTime(TimePrecision prec) {
65 if (g_timegetter == NULL)
67 return g_timegetter->getTime(prec);
70 ClientLauncher::~ClientLauncher()
86 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
88 init_args(game_params, cmd_args);
90 // List video modes if requested
92 return print_video_modes();
95 errorstream << "Could not initialize game engine." << std::endl;
100 g_timegetter = new IrrlichtTimeGetter(device);
102 // Speed tests (done after irrlicht is loaded to get timer)
103 if (cmd_args.getFlag("speedtests")) {
104 dstream << "Running speed tests" << std::endl;
109 video::IVideoDriver *video_driver = device->getVideoDriver();
110 if (video_driver == NULL) {
111 errorstream << "Could not initialize video driver." << std::endl;
115 porting::setXorgClassHint(video_driver->getExposedVideoData(), PROJECT_NAME_C);
117 porting::setXorgWindowIcon(device,
118 porting::path_share + "/misc/minetest-xorg-icon-128.png");
121 This changes the minimum allowed number of vertices in a VBO.
124 //driver->setMinHardwareBufferVertexCount(50);
126 // Create game callback for menus
127 g_gamecallback = new MainGameCallback(device);
129 device->setResizable(true);
132 input = new RandomInputHandler();
134 input = new RealInputHandler(device, receiver);
136 smgr = device->getSceneManager();
137 smgr->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
139 guienv = device->getGUIEnvironment();
140 skin = guienv->getSkin();
141 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
142 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
143 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
144 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
145 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
146 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
148 g_fontengine = new FontEngine(g_settings, guienv);
149 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
151 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
152 // Irrlicht 1.8 input colours
153 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
154 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
157 // Create the menu clouds
158 if (!g_menucloudsmgr)
159 g_menucloudsmgr = smgr->createNewSceneManager();
161 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
162 g_menucloudsmgr, -1, rand(), 100);
163 g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
164 scene::ICameraSceneNode* camera;
165 camera = g_menucloudsmgr->addCameraSceneNode(0,
166 v3f(0, 0, 0), v3f(0, 60, 100));
167 camera->setFarValue(10000);
173 ChatBackend chat_backend;
175 // If an error occurs, this is set to something by menu().
176 // It is then displayed before the menu shows on the next call to menu()
177 std::string error_message;
178 bool reconnect_requested = false;
180 bool first_loop = true;
186 bool *kill = porting::signal_handler_killstatus();
188 while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
190 // Set the window caption
191 const wchar_t *text = wgettext("Main Menu");
192 device->setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
193 L" " + utf8_to_wide(g_version_hash) +
194 L" [" + text + L"]").c_str());
197 try { // This is used for catching disconnects
202 We need some kind of a root node to be able to add
203 custom gui elements directly on the screen.
204 Otherwise they won't be automatically drawn.
206 guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
208 bool game_has_run = launch_game(error_message, reconnect_requested,
209 game_params, cmd_args);
211 // Reset the reconnect_requested flag
212 reconnect_requested = false;
214 // If skip_main_menu, we only want to startup once
215 if (skip_main_menu && !first_loop)
227 // Break out of menu-game loop to shut down cleanly
228 if (!device->run() || *kill) {
229 if (g_settings_path != "")
230 g_settings->updateConfigFile(g_settings_path.c_str());
234 if (current_playername.length() > PLAYERNAME_SIZE-1) {
235 error_message = gettext("Player name too long.");
236 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
237 g_settings->set("name", playername);
241 device->getVideoDriver()->setTextureCreationFlag(
242 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
244 #ifdef HAVE_TOUCHSCREENGUI
245 receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
246 g_touchscreengui = receiver->m_touchscreengui;
261 &reconnect_requested,
263 simple_singleplayer_mode
267 #ifdef HAVE_TOUCHSCREENGUI
268 delete g_touchscreengui;
269 g_touchscreengui = NULL;
270 receiver->m_touchscreengui = NULL;
274 catch (con::PeerNotFoundException &e) {
275 error_message = gettext("Connection error (timed out?)");
276 errorstream << error_message << std::endl;
280 catch (std::exception &e) {
281 std::string error_message = "Some exception: \"";
282 error_message += e.what();
283 error_message += "\"";
284 errorstream << error_message << std::endl;
288 // If no main menu, show error and exit
289 if (skip_main_menu) {
290 if (!error_message.empty()) {
291 verbosestream << "error_message = "
292 << error_message << std::endl;
299 g_menuclouds->drop();
300 g_menucloudsmgr->drop();
305 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
308 skip_main_menu = cmd_args.getFlag("go");
310 // FIXME: This is confusing (but correct)
312 /* If world_path is set then override it unless skipping the main menu using
313 * the --go command line param. Else, give preference to the address
314 * supplied on the command line
316 address = g_settings->get("address");
317 if (game_params.world_path != "" && !skip_main_menu)
319 else if (cmd_args.exists("address"))
320 address = cmd_args.get("address");
322 playername = g_settings->get("name");
323 if (cmd_args.exists("name"))
324 playername = cmd_args.get("name");
326 list_video_modes = cmd_args.getFlag("videomodes");
328 use_freetype = g_settings->getBool("freetype");
330 random_input = g_settings->getBool("random_input")
331 || cmd_args.getFlag("random-input");
334 bool ClientLauncher::init_engine()
336 receiver = new MyEventReceiver();
337 create_engine_device();
338 return device != NULL;
341 bool ClientLauncher::launch_game(std::string &error_message,
342 bool reconnect_requested, GameParams &game_params,
343 const Settings &cmd_args)
345 // Initialize menu data
346 MainMenuData menudata;
347 menudata.address = address;
348 menudata.name = playername;
349 menudata.password = password;
350 menudata.port = itos(game_params.socket_port);
351 menudata.script_data.errormessage = error_message;
352 menudata.script_data.reconnect_requested = reconnect_requested;
354 error_message.clear();
356 if (cmd_args.exists("password"))
357 menudata.password = cmd_args.get("password");
359 menudata.enable_public = g_settings->getBool("server_announce");
361 // If a world was commanded, append and select it
362 if (game_params.world_path != "") {
363 worldspec.gameid = getWorldGameId(game_params.world_path, true);
364 worldspec.name = _("[--world parameter]");
366 if (worldspec.gameid == "") { // Create new
367 worldspec.gameid = g_settings->get("default_game");
368 worldspec.name += " [new]";
370 worldspec.path = game_params.world_path;
375 if (!skip_main_menu) {
376 main_menu(&menudata);
378 // Skip further loading if there was an exit signal.
379 if (*porting::signal_handler_killstatus())
382 address = menudata.address;
383 int newport = stoi(menudata.port);
385 game_params.socket_port = newport;
387 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
389 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
391 if (menudata.selected_world >= 0
392 && menudata.selected_world < (int)worldspecs.size()) {
393 g_settings->set("selected_world_path",
394 worldspecs[menudata.selected_world].path);
395 worldspec = worldspecs[menudata.selected_world];
399 if (!menudata.script_data.errormessage.empty()) {
400 /* The calling function will pass this back into this function upon the
401 * next iteration (if any) causing it to be displayed by the GUI
403 error_message = menudata.script_data.errormessage;
407 if (menudata.name == "")
408 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
410 playername = menudata.name;
412 password = menudata.password;
414 g_settings->set("name", playername);
416 current_playername = playername;
417 current_password = password;
418 current_address = address;
419 current_port = game_params.socket_port;
421 // If using simple singleplayer mode, override
422 if (simple_singleplayer_mode) {
423 assert(skip_main_menu == false);
424 current_playername = "singleplayer";
425 current_password = "";
426 current_address = "";
427 current_port = myrand_range(49152, 65535);
428 } else if (address != "") {
429 ServerListSpec server;
430 server["name"] = menudata.servername;
431 server["address"] = menudata.address;
432 server["port"] = menudata.port;
433 server["description"] = menudata.serverdescription;
434 ServerList::insert(server);
437 infostream << "Selected world: " << worldspec.name
438 << " [" << worldspec.path << "]" << std::endl;
440 if (current_address == "") { // If local game
441 if (worldspec.path == "") {
442 error_message = gettext("No world selected and no address "
443 "provided. Nothing to do.");
444 errorstream << error_message << std::endl;
448 if (!fs::PathExists(worldspec.path)) {
449 error_message = gettext("Provided world path doesn't exist: ")
451 errorstream << error_message << std::endl;
455 // Load gamespec for required game
456 gamespec = findWorldSubgame(worldspec.path);
457 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
458 error_message = gettext("Could not find or load game \"")
459 + worldspec.gameid + "\"";
460 errorstream << error_message << std::endl;
464 if (porting::signal_handler_killstatus())
467 if (game_params.game_spec.isValid() &&
468 game_params.game_spec.id != worldspec.gameid) {
469 warningstream << "Overriding gamespec from \""
470 << worldspec.gameid << "\" to \""
471 << game_params.game_spec.id << "\"" << std::endl;
472 gamespec = game_params.game_spec;
475 if (!gamespec.isValid()) {
476 error_message = gettext("Invalid gamespec.");
477 error_message += " (world.gameid=" + worldspec.gameid + ")";
478 errorstream << error_message << std::endl;
486 void ClientLauncher::main_menu(MainMenuData *menudata)
488 bool *kill = porting::signal_handler_killstatus();
489 video::IVideoDriver *driver = device->getVideoDriver();
491 infostream << "Waiting for other menus" << std::endl;
492 while (device->run() && *kill == false) {
495 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
498 // On some computers framerate doesn't seem to be automatically limited
501 infostream << "Waited for other menus" << std::endl;
503 // Cursor can be non-visible when coming from the game
505 device->getCursorControl()->setVisible(true);
509 GUIEngine mymenu(device, &input->joystick, guiroot,
510 &g_menumgr, smgr, menudata, *kill);
512 smgr->clear(); /* leave scene manager in a clean state */
515 bool ClientLauncher::create_engine_device()
517 // Resolution selection
518 bool fullscreen = g_settings->getBool("fullscreen");
519 u16 screenW = g_settings->getU16("screenW");
520 u16 screenH = g_settings->getU16("screenH");
523 bool vsync = g_settings->getBool("vsync");
524 u16 bits = g_settings->getU16("fullscreen_bpp");
525 u16 fsaa = g_settings->getU16("fsaa");
527 // stereo buffer required for pageflip stereo
528 bool stereo_buffer = g_settings->get("3d_mode") == "pageflip";
531 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
532 std::string driverstring = g_settings->get("video_driver");
533 std::vector<video::E_DRIVER_TYPE> drivers
534 = porting::getSupportedVideoDrivers();
536 for (i = 0; i != drivers.size(); i++) {
537 if (!strcasecmp(driverstring.c_str(),
538 porting::getVideoDriverName(drivers[i]))) {
539 driverType = drivers[i];
543 if (i == drivers.size()) {
544 errorstream << "Invalid video_driver specified; "
545 "defaulting to opengl" << std::endl;
548 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
549 params.DriverType = driverType;
550 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
552 params.AntiAlias = fsaa;
553 params.Fullscreen = fullscreen;
554 params.Stencilbuffer = false;
555 params.Stereobuffer = stereo_buffer;
556 params.Vsync = vsync;
557 params.EventReceiver = receiver;
558 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
559 params.ZBufferBits = 24;
561 params.PrivateData = porting::app_global;
562 params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
563 "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
566 device = createDeviceEx(params);
569 if (g_settings->getBool("enable_joysticks")) {
570 irr::core::array<irr::SJoystickInfo> infos;
571 std::vector<irr::SJoystickInfo> joystick_infos;
572 // Make sure this is called maximum once per
573 // irrlicht device, otherwise it will give you
574 // multiple events for the same joystick.
575 if (device->activateJoysticks(infos)) {
576 infostream << "Joystick support enabled" << std::endl;
577 joystick_infos.reserve(infos.size());
578 for (u32 i = 0; i < infos.size(); i++) {
579 joystick_infos.push_back(infos[i]);
582 errorstream << "Could not activate joystick support." << std::endl;
585 porting::initIrrlicht(device);
588 return device != NULL;
591 void ClientLauncher::speed_tests()
593 // volatile to avoid some potential compiler optimisations
594 volatile static s16 temp16;
595 volatile static f32 tempf;
598 static std::string tempstring;
599 static std::string tempstring2;
603 tempstring = std::string();
604 tempstring2 = std::string();
607 infostream << "The following test should take around 20ms." << std::endl;
608 TimeTaker timer("Testing std::string speed");
609 const u32 jj = 10000;
610 for (u32 j = 0; j < jj; j++) {
614 for (u32 i = 0; i < ii; i++) {
615 tempstring2 += "asd";
617 for (u32 i = 0; i < ii+1; i++) {
619 if (tempstring == tempstring2)
625 infostream << "All of the following tests should take around 100ms each."
629 TimeTaker timer("Testing floating-point conversion speed");
631 for (u32 i = 0; i < 4000000; i++) {
638 TimeTaker timer("Testing floating-point vector speed");
640 tempv3f1 = v3f(1, 2, 3);
641 tempv3f2 = v3f(4, 5, 6);
642 for (u32 i = 0; i < 10000000; i++) {
643 tempf += tempv3f1.dotProduct(tempv3f2);
644 tempv3f2 += v3f(7, 8, 9);
649 TimeTaker timer("Testing std::map speed");
651 std::map<v2s16, f32> map1;
654 for (s16 y = 0; y < ii; y++) {
655 for (s16 x = 0; x < ii; x++) {
656 map1[v2s16(x, y)] = tempf;
660 for (s16 y = ii - 1; y >= 0; y--) {
661 for (s16 x = 0; x < ii; x++) {
662 tempf = map1[v2s16(x, y)];
668 infostream << "Around 5000/ms should do well here." << std::endl;
669 TimeTaker timer("Testing mutex speed");
682 while(timer.getTimerTime() < 10);
684 u32 dtime = timer.stop();
685 u32 per_ms = n / dtime;
686 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
690 bool ClientLauncher::print_video_modes()
692 IrrlichtDevice *nulldevice;
694 bool vsync = g_settings->getBool("vsync");
695 u16 fsaa = g_settings->getU16("fsaa");
696 MyEventReceiver* receiver = new MyEventReceiver();
698 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
699 params.DriverType = video::EDT_NULL;
700 params.WindowSize = core::dimension2d<u32>(640, 480);
702 params.AntiAlias = fsaa;
703 params.Fullscreen = false;
704 params.Stencilbuffer = false;
705 params.Vsync = vsync;
706 params.EventReceiver = receiver;
707 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
709 nulldevice = createDeviceEx(params);
711 if (nulldevice == NULL) {
716 std::cout << _("Available video modes (WxHxD):") << std::endl;
718 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
720 if (videomode_list != NULL) {
721 s32 videomode_count = videomode_list->getVideoModeCount();
722 core::dimension2d<u32> videomode_res;
724 for (s32 i = 0; i < videomode_count; ++i) {
725 videomode_res = videomode_list->getVideoModeResolution(i);
726 videomode_depth = videomode_list->getVideoModeDepth(i);
727 std::cout << videomode_res.Width << "x" << videomode_res.Height
728 << "x" << videomode_depth << std::endl;
731 std::cout << _("Active video mode (WxHxD):") << std::endl;
732 videomode_res = videomode_list->getDesktopResolution();
733 videomode_depth = videomode_list->getDesktopDepth();
734 std::cout << videomode_res.Width << "x" << videomode_res.Height
735 << "x" << videomode_depth << std::endl;
742 return videomode_list != NULL;