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"
40 gui::IGUIEnvironment *guienv = NULL;
41 gui::IGUIStaticText *guiroot = NULL;
42 MainMenuManager g_menumgr;
46 return g_menumgr.menuCount() == 0;
49 // Passed to menus to allow disconnecting and exiting
50 MainGameCallback *g_gamecallback = NULL;
53 // Instance of the time getter
54 static TimeGetter *g_timegetter = NULL;
58 if (g_timegetter == NULL)
60 return g_timegetter->getTime(PRECISION_MILLI);
63 u32 getTime(TimePrecision prec) {
64 if (g_timegetter == NULL)
66 return g_timegetter->getTime(prec);
69 ClientLauncher::~ClientLauncher()
85 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
87 init_args(game_params, cmd_args);
89 // List video modes if requested
91 return print_video_modes();
94 errorstream << "Could not initialize game engine." << std::endl;
99 g_timegetter = new IrrlichtTimeGetter(device);
101 // Speed tests (done after irrlicht is loaded to get timer)
102 if (cmd_args.getFlag("speedtests")) {
103 dstream << "Running speed tests" << std::endl;
108 video::IVideoDriver *video_driver = device->getVideoDriver();
109 if (video_driver == NULL) {
110 errorstream << "Could not initialize video driver." << std::endl;
114 porting::setXorgClassHint(video_driver->getExposedVideoData(), PROJECT_NAME_C);
117 This changes the minimum allowed number of vertices in a VBO.
120 //driver->setMinHardwareBufferVertexCount(50);
122 // Create game callback for menus
123 g_gamecallback = new MainGameCallback(device);
125 device->setResizable(true);
128 input = new RandomInputHandler();
130 input = new RealInputHandler(device, receiver);
132 smgr = device->getSceneManager();
133 smgr->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
135 guienv = device->getGUIEnvironment();
136 skin = guienv->getSkin();
137 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
138 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
139 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
140 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
141 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
142 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
144 g_fontengine = new FontEngine(g_settings, guienv);
145 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
147 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
148 // Irrlicht 1.8 input colours
149 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
150 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
153 // Create the menu clouds
154 if (!g_menucloudsmgr)
155 g_menucloudsmgr = smgr->createNewSceneManager();
157 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
158 g_menucloudsmgr, -1, rand(), 100);
159 g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
160 scene::ICameraSceneNode* camera;
161 camera = g_menucloudsmgr->addCameraSceneNode(0,
162 v3f(0, 0, 0), v3f(0, 60, 100));
163 camera->setFarValue(10000);
169 ChatBackend chat_backend;
171 // If an error occurs, this is set to something by menu().
172 // It is then displayed before the menu shows on the next call to menu()
173 std::string error_message;
174 bool reconnect_requested = false;
176 bool first_loop = true;
182 bool *kill = porting::signal_handler_killstatus();
184 while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
186 // Set the window caption
187 const wchar_t *text = wgettext("Main Menu");
188 device->setWindowCaption((utf8_to_wide(PROJECT_NAME_C) + L" [" + text + L"]").c_str());
191 try { // This is used for catching disconnects
196 We need some kind of a root node to be able to add
197 custom gui elements directly on the screen.
198 Otherwise they won't be automatically drawn.
200 guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
202 bool game_has_run = launch_game(error_message, reconnect_requested,
203 game_params, cmd_args);
205 // Reset the reconnect_requested flag
206 reconnect_requested = false;
208 // If skip_main_menu, we only want to startup once
209 if (skip_main_menu && !first_loop)
221 // Break out of menu-game loop to shut down cleanly
222 if (!device->run() || *kill) {
223 if (g_settings_path != "")
224 g_settings->updateConfigFile(g_settings_path.c_str());
228 if (current_playername.length() > PLAYERNAME_SIZE-1) {
229 error_message = gettext("Player name too long.");
230 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
231 g_settings->set("name", playername);
235 device->getVideoDriver()->setTextureCreationFlag(
236 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
238 #ifdef HAVE_TOUCHSCREENGUI
239 receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
240 g_touchscreengui = receiver->m_touchscreengui;
255 &reconnect_requested,
257 simple_singleplayer_mode
261 #ifdef HAVE_TOUCHSCREENGUI
262 delete g_touchscreengui;
263 g_touchscreengui = NULL;
264 receiver->m_touchscreengui = NULL;
268 catch (con::PeerNotFoundException &e) {
269 error_message = gettext("Connection error (timed out?)");
270 errorstream << error_message << std::endl;
274 catch (std::exception &e) {
275 std::string error_message = "Some exception: \"";
276 error_message += e.what();
277 error_message += "\"";
278 errorstream << error_message << std::endl;
282 // If no main menu, show error and exit
283 if (skip_main_menu) {
284 if (!error_message.empty()) {
285 verbosestream << "error_message = "
286 << error_message << std::endl;
293 g_menuclouds->drop();
294 g_menucloudsmgr->drop();
299 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
302 skip_main_menu = cmd_args.getFlag("go");
304 // FIXME: This is confusing (but correct)
306 /* If world_path is set then override it unless skipping the main menu using
307 * the --go command line param. Else, give preference to the address
308 * supplied on the command line
310 address = g_settings->get("address");
311 if (game_params.world_path != "" && !skip_main_menu)
313 else if (cmd_args.exists("address"))
314 address = cmd_args.get("address");
316 playername = g_settings->get("name");
317 if (cmd_args.exists("name"))
318 playername = cmd_args.get("name");
320 list_video_modes = cmd_args.getFlag("videomodes");
322 use_freetype = g_settings->getBool("freetype");
324 random_input = g_settings->getBool("random_input")
325 || cmd_args.getFlag("random-input");
328 bool ClientLauncher::init_engine()
330 receiver = new MyEventReceiver();
331 create_engine_device();
332 return device != NULL;
335 bool ClientLauncher::launch_game(std::string &error_message,
336 bool reconnect_requested, GameParams &game_params,
337 const Settings &cmd_args)
339 // Initialize menu data
340 MainMenuData menudata;
341 menudata.address = address;
342 menudata.name = playername;
343 menudata.password = password;
344 menudata.port = itos(game_params.socket_port);
345 menudata.script_data.errormessage = error_message;
346 menudata.script_data.reconnect_requested = reconnect_requested;
348 error_message.clear();
350 if (cmd_args.exists("password"))
351 menudata.password = cmd_args.get("password");
353 menudata.enable_public = g_settings->getBool("server_announce");
355 // If a world was commanded, append and select it
356 if (game_params.world_path != "") {
357 worldspec.gameid = getWorldGameId(game_params.world_path, true);
358 worldspec.name = _("[--world parameter]");
360 if (worldspec.gameid == "") { // Create new
361 worldspec.gameid = g_settings->get("default_game");
362 worldspec.name += " [new]";
364 worldspec.path = game_params.world_path;
369 if (!skip_main_menu) {
370 main_menu(&menudata);
372 // Skip further loading if there was an exit signal.
373 if (*porting::signal_handler_killstatus())
376 address = menudata.address;
377 int newport = stoi(menudata.port);
379 game_params.socket_port = newport;
381 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
383 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
385 if (menudata.selected_world >= 0
386 && menudata.selected_world < (int)worldspecs.size()) {
387 g_settings->set("selected_world_path",
388 worldspecs[menudata.selected_world].path);
389 worldspec = worldspecs[menudata.selected_world];
393 if (!menudata.script_data.errormessage.empty()) {
394 /* The calling function will pass this back into this function upon the
395 * next iteration (if any) causing it to be displayed by the GUI
397 error_message = menudata.script_data.errormessage;
401 if (menudata.name == "")
402 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
404 playername = menudata.name;
406 password = menudata.password;
408 g_settings->set("name", playername);
410 current_playername = playername;
411 current_password = password;
412 current_address = address;
413 current_port = game_params.socket_port;
415 // If using simple singleplayer mode, override
416 if (simple_singleplayer_mode) {
417 assert(skip_main_menu == false);
418 current_playername = "singleplayer";
419 current_password = "";
420 current_address = "";
421 current_port = myrand_range(49152, 65535);
422 } else if (address != "") {
423 ServerListSpec server;
424 server["name"] = menudata.servername;
425 server["address"] = menudata.address;
426 server["port"] = menudata.port;
427 server["description"] = menudata.serverdescription;
428 ServerList::insert(server);
431 infostream << "Selected world: " << worldspec.name
432 << " [" << worldspec.path << "]" << std::endl;
434 if (current_address == "") { // If local game
435 if (worldspec.path == "") {
436 error_message = gettext("No world selected and no address "
437 "provided. Nothing to do.");
438 errorstream << error_message << std::endl;
442 if (!fs::PathExists(worldspec.path)) {
443 error_message = gettext("Provided world path doesn't exist: ")
445 errorstream << error_message << std::endl;
449 // Load gamespec for required game
450 gamespec = findWorldSubgame(worldspec.path);
451 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
452 error_message = gettext("Could not find or load game \"")
453 + worldspec.gameid + "\"";
454 errorstream << error_message << std::endl;
458 if (porting::signal_handler_killstatus())
461 if (game_params.game_spec.isValid() &&
462 game_params.game_spec.id != worldspec.gameid) {
463 warningstream << "Overriding gamespec from \""
464 << worldspec.gameid << "\" to \""
465 << game_params.game_spec.id << "\"" << std::endl;
466 gamespec = game_params.game_spec;
469 if (!gamespec.isValid()) {
470 error_message = gettext("Invalid gamespec.");
471 error_message += " (world.gameid=" + worldspec.gameid + ")";
472 errorstream << error_message << std::endl;
480 void ClientLauncher::main_menu(MainMenuData *menudata)
482 bool *kill = porting::signal_handler_killstatus();
483 video::IVideoDriver *driver = device->getVideoDriver();
485 infostream << "Waiting for other menus" << std::endl;
486 while (device->run() && *kill == false) {
489 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
492 // On some computers framerate doesn't seem to be automatically limited
495 infostream << "Waited for other menus" << std::endl;
497 // Cursor can be non-visible when coming from the game
499 device->getCursorControl()->setVisible(true);
503 GUIEngine mymenu(device, &input->joystick, guiroot,
504 &g_menumgr, smgr, menudata, *kill);
506 smgr->clear(); /* leave scene manager in a clean state */
509 bool ClientLauncher::create_engine_device()
511 // Resolution selection
512 bool fullscreen = g_settings->getBool("fullscreen");
513 u16 screenW = g_settings->getU16("screenW");
514 u16 screenH = g_settings->getU16("screenH");
517 bool vsync = g_settings->getBool("vsync");
518 u16 bits = g_settings->getU16("fullscreen_bpp");
519 u16 fsaa = g_settings->getU16("fsaa");
521 // stereo buffer required for pageflip stereo
522 bool stereo_buffer = g_settings->get("3d_mode") == "pageflip";
525 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
526 std::string driverstring = g_settings->get("video_driver");
527 std::vector<video::E_DRIVER_TYPE> drivers
528 = porting::getSupportedVideoDrivers();
530 for (i = 0; i != drivers.size(); i++) {
531 if (!strcasecmp(driverstring.c_str(),
532 porting::getVideoDriverName(drivers[i]))) {
533 driverType = drivers[i];
537 if (i == drivers.size()) {
538 errorstream << "Invalid video_driver specified; "
539 "defaulting to opengl" << std::endl;
542 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
543 params.DriverType = driverType;
544 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
546 params.AntiAlias = fsaa;
547 params.Fullscreen = fullscreen;
548 params.Stencilbuffer = false;
549 params.Stereobuffer = stereo_buffer;
550 params.Vsync = vsync;
551 params.EventReceiver = receiver;
552 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
553 params.ZBufferBits = 24;
555 params.PrivateData = porting::app_global;
556 params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
557 "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
560 device = createDeviceEx(params);
563 if (g_settings->getBool("enable_joysticks")) {
564 irr::core::array<irr::SJoystickInfo> infos;
565 std::vector<irr::SJoystickInfo> joystick_infos;
566 // Make sure this is called maximum once per
567 // irrlicht device, otherwise it will give you
568 // multiple events for the same joystick.
569 if (device->activateJoysticks(infos)) {
570 infostream << "Joystick support enabled" << std::endl;
571 joystick_infos.reserve(infos.size());
572 for (u32 i = 0; i < infos.size(); i++) {
573 joystick_infos.push_back(infos[i]);
576 errorstream << "Could not activate joystick support." << std::endl;
579 porting::initIrrlicht(device);
582 return device != NULL;
585 void ClientLauncher::speed_tests()
587 // volatile to avoid some potential compiler optimisations
588 volatile static s16 temp16;
589 volatile static f32 tempf;
592 static std::string tempstring;
593 static std::string tempstring2;
597 tempstring = std::string();
598 tempstring2 = std::string();
601 infostream << "The following test should take around 20ms." << std::endl;
602 TimeTaker timer("Testing std::string speed");
603 const u32 jj = 10000;
604 for (u32 j = 0; j < jj; j++) {
608 for (u32 i = 0; i < ii; i++) {
609 tempstring2 += "asd";
611 for (u32 i = 0; i < ii+1; i++) {
613 if (tempstring == tempstring2)
619 infostream << "All of the following tests should take around 100ms each."
623 TimeTaker timer("Testing floating-point conversion speed");
625 for (u32 i = 0; i < 4000000; i++) {
632 TimeTaker timer("Testing floating-point vector speed");
634 tempv3f1 = v3f(1, 2, 3);
635 tempv3f2 = v3f(4, 5, 6);
636 for (u32 i = 0; i < 10000000; i++) {
637 tempf += tempv3f1.dotProduct(tempv3f2);
638 tempv3f2 += v3f(7, 8, 9);
643 TimeTaker timer("Testing std::map speed");
645 std::map<v2s16, f32> map1;
648 for (s16 y = 0; y < ii; y++) {
649 for (s16 x = 0; x < ii; x++) {
650 map1[v2s16(x, y)] = tempf;
654 for (s16 y = ii - 1; y >= 0; y--) {
655 for (s16 x = 0; x < ii; x++) {
656 tempf = map1[v2s16(x, y)];
662 infostream << "Around 5000/ms should do well here." << std::endl;
663 TimeTaker timer("Testing mutex speed");
676 while(timer.getTimerTime() < 10);
678 u32 dtime = timer.stop();
679 u32 per_ms = n / dtime;
680 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
684 bool ClientLauncher::print_video_modes()
686 IrrlichtDevice *nulldevice;
688 bool vsync = g_settings->getBool("vsync");
689 u16 fsaa = g_settings->getU16("fsaa");
690 MyEventReceiver* receiver = new MyEventReceiver();
692 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
693 params.DriverType = video::EDT_NULL;
694 params.WindowSize = core::dimension2d<u32>(640, 480);
696 params.AntiAlias = fsaa;
697 params.Fullscreen = false;
698 params.Stencilbuffer = false;
699 params.Vsync = vsync;
700 params.EventReceiver = receiver;
701 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
703 nulldevice = createDeviceEx(params);
705 if (nulldevice == NULL) {
710 std::cout << _("Available video modes (WxHxD):") << std::endl;
712 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
714 if (videomode_list != NULL) {
715 s32 videomode_count = videomode_list->getVideoModeCount();
716 core::dimension2d<u32> videomode_res;
718 for (s32 i = 0; i < videomode_count; ++i) {
719 videomode_res = videomode_list->getVideoModeResolution(i);
720 videomode_depth = videomode_list->getVideoModeDepth(i);
721 std::cout << videomode_res.Width << "x" << videomode_res.Height
722 << "x" << videomode_depth << std::endl;
725 std::cout << _("Active video mode (WxHxD):") << std::endl;
726 videomode_res = videomode_list->getDesktopResolution();
727 videomode_depth = videomode_list->getDesktopDepth();
728 std::cout << videomode_res.Width << "x" << videomode_res.Height
729 << "x" << videomode_depth << std::endl;
736 return videomode_list != NULL;