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 "gui/mainmenumanager.h"
24 #include "gui/guiMainMenu.h"
30 #include "serverlist.h"
31 #include "gui/guiEngine.h"
32 #include "fontengine.h"
33 #include "clientlauncher.h"
35 #include "renderingengine.h"
36 #include "network/networkexceptions.h"
39 #include "sound_openal.h"
47 gui::IGUIEnvironment *guienv = nullptr;
48 gui::IGUIStaticText *guiroot = nullptr;
49 MainMenuManager g_menumgr;
53 return g_menumgr.menuCount() != 0;
56 // Passed to menus to allow disconnecting and exiting
57 MainGameCallback *g_gamecallback = nullptr;
60 ClientLauncher::~ClientLauncher()
67 delete g_gamecallback;
69 delete RenderingEngine::get_instance();
72 g_sound_manager_singleton.reset();
77 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
79 init_args(game_params, cmd_args);
81 // List video modes if requested
83 return RenderingEngine::print_video_modes();
86 if (g_settings->getBool("enable_sound"))
87 g_sound_manager_singleton = createSoundManagerSingleton();
91 errorstream << "Could not initialize game engine." << std::endl;
95 // Speed tests (done after irrlicht is loaded to get timer)
96 if (cmd_args.getFlag("speedtests")) {
97 dstream << "Running speed tests" << std::endl;
102 if (RenderingEngine::get_video_driver() == NULL) {
103 errorstream << "Could not initialize video driver." << std::endl;
107 RenderingEngine::get_instance()->setupTopLevelWindow(PROJECT_NAME_C);
110 This changes the minimum allowed number of vertices in a VBO.
113 //driver->setMinHardwareBufferVertexCount(50);
115 // Create game callback for menus
116 g_gamecallback = new MainGameCallback();
118 RenderingEngine::get_instance()->setResizable(true);
122 RenderingEngine::get_scene_manager()->getParameters()->
123 setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
125 guienv = RenderingEngine::get_gui_env();
126 skin = RenderingEngine::get_gui_env()->getSkin();
127 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
128 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
129 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
130 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
131 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
132 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
134 float density = porting::getDisplayDensity();
135 skin->setSize(gui::EGDS_CHECK_BOX_WIDTH, (s32)(17.0f * density));
136 skin->setSize(gui::EGDS_SCROLLBAR_SIZE, (s32)(14.0f * density));
137 skin->setSize(gui::EGDS_WINDOW_BUTTON_WIDTH, (s32)(15.0f * density));
138 if (density > 1.5f) {
139 std::string sprite_path = porting::path_user + "/textures/base/pack/";
141 sprite_path.append("checkbox_64.png");
142 else if (density > 2.0f)
143 sprite_path.append("checkbox_32.png");
145 sprite_path.append("checkbox_16.png");
146 // Texture dimensions should be a power of 2
147 gui::IGUISpriteBank *sprites = skin->getSpriteBank();
148 video::IVideoDriver *driver = RenderingEngine::get_video_driver();
149 video::ITexture *sprite_texture = driver->getTexture(sprite_path.c_str());
150 if (sprite_texture) {
151 s32 sprite_id = sprites->addTextureAsSprite(sprite_texture);
153 skin->setIcon(gui::EGDI_CHECK_BOX_CHECKED, sprite_id);
157 g_fontengine = new FontEngine(g_settings, guienv);
158 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
160 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
161 // Irrlicht 1.8 input colours
162 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
163 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
166 // Create the menu clouds
167 if (!g_menucloudsmgr)
168 g_menucloudsmgr = RenderingEngine::get_scene_manager()->createNewSceneManager();
170 g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
171 g_menuclouds->setHeight(100.0f);
172 g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 200, 200, 255));
173 scene::ICameraSceneNode* camera;
174 camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100));
175 camera->setFarValue(10000);
181 ChatBackend chat_backend;
183 // If an error occurs, this is set to something by menu().
184 // It is then displayed before the menu shows on the next call to menu()
185 std::string error_message;
186 bool reconnect_requested = false;
188 bool first_loop = true;
194 bool *kill = porting::signal_handler_killstatus();
196 while (RenderingEngine::run() && !*kill &&
197 !g_gamecallback->shutdown_requested) {
198 // Set the window caption
199 const wchar_t *text = wgettext("Main Menu");
200 RenderingEngine::get_raw_device()->
201 setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
202 L" " + utf8_to_wide(g_version_hash) +
203 L" [" + text + L"]").c_str());
206 try { // This is used for catching disconnects
208 RenderingEngine::get_gui_env()->clear();
211 We need some kind of a root node to be able to add
212 custom gui elements directly on the screen.
213 Otherwise they won't be automatically drawn.
215 guiroot = RenderingEngine::get_gui_env()->addStaticText(L"",
216 core::rect<s32>(0, 0, 10000, 10000));
218 bool game_has_run = launch_game(error_message, reconnect_requested,
219 game_params, cmd_args);
221 // Reset the reconnect_requested flag
222 reconnect_requested = false;
224 // If skip_main_menu, we only want to startup once
225 if (skip_main_menu && !first_loop)
237 // Break out of menu-game loop to shut down cleanly
238 if (!RenderingEngine::get_raw_device()->run() || *kill) {
239 if (!g_settings_path.empty())
240 g_settings->updateConfigFile(g_settings_path.c_str());
244 if (current_playername.length() > PLAYERNAME_SIZE-1) {
245 error_message = gettext("Player name too long.");
246 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
247 g_settings->set("name", playername);
251 RenderingEngine::get_video_driver()->setTextureCreationFlag(
252 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
254 #ifdef HAVE_TOUCHSCREENGUI
255 receiver->m_touchscreengui = new TouchScreenGUI(RenderingEngine::get_raw_device(), receiver);
256 g_touchscreengui = receiver->m_touchscreengui;
270 &reconnect_requested,
272 simple_singleplayer_mode
274 RenderingEngine::get_scene_manager()->clear();
276 #ifdef HAVE_TOUCHSCREENGUI
277 delete g_touchscreengui;
278 g_touchscreengui = NULL;
279 receiver->m_touchscreengui = NULL;
283 catch (con::PeerNotFoundException &e) {
284 error_message = gettext("Connection error (timed out?)");
285 errorstream << error_message << std::endl;
289 catch (std::exception &e) {
290 std::string error_message = "Some exception: \"";
291 error_message += e.what();
292 error_message += "\"";
293 errorstream << error_message << std::endl;
297 // If no main menu, show error and exit
298 if (skip_main_menu) {
299 if (!error_message.empty()) {
300 verbosestream << "error_message = "
301 << error_message << std::endl;
308 g_menuclouds->drop();
309 g_menucloudsmgr->drop();
314 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
317 skip_main_menu = cmd_args.getFlag("go");
319 // FIXME: This is confusing (but correct)
321 /* If world_path is set then override it unless skipping the main menu using
322 * the --go command line param. Else, give preference to the address
323 * supplied on the command line
325 address = g_settings->get("address");
326 if (!game_params.world_path.empty() && !skip_main_menu)
328 else if (cmd_args.exists("address"))
329 address = cmd_args.get("address");
331 playername = g_settings->get("name");
332 if (cmd_args.exists("name"))
333 playername = cmd_args.get("name");
335 list_video_modes = cmd_args.getFlag("videomodes");
337 use_freetype = g_settings->getBool("freetype");
339 random_input = g_settings->getBool("random_input")
340 || cmd_args.getFlag("random-input");
343 bool ClientLauncher::init_engine()
345 receiver = new MyEventReceiver();
346 new RenderingEngine(receiver);
347 return RenderingEngine::get_raw_device() != nullptr;
350 void ClientLauncher::init_input()
353 input = new RandomInputHandler();
355 input = new RealInputHandler(receiver);
357 if (g_settings->getBool("enable_joysticks")) {
358 irr::core::array<irr::SJoystickInfo> infos;
359 std::vector<irr::SJoystickInfo> joystick_infos;
361 // Make sure this is called maximum once per
362 // irrlicht device, otherwise it will give you
363 // multiple events for the same joystick.
364 if (RenderingEngine::get_raw_device()->activateJoysticks(infos)) {
365 infostream << "Joystick support enabled" << std::endl;
366 joystick_infos.reserve(infos.size());
367 for (u32 i = 0; i < infos.size(); i++) {
368 joystick_infos.push_back(infos[i]);
370 input->joystick.onJoystickConnect(joystick_infos);
372 errorstream << "Could not activate joystick support." << std::endl;
377 bool ClientLauncher::launch_game(std::string &error_message,
378 bool reconnect_requested, GameParams &game_params,
379 const Settings &cmd_args)
381 // Initialize menu data
382 MainMenuData menudata;
383 menudata.address = address;
384 menudata.name = playername;
385 menudata.password = password;
386 menudata.port = itos(game_params.socket_port);
387 menudata.script_data.errormessage = error_message;
388 menudata.script_data.reconnect_requested = reconnect_requested;
390 error_message.clear();
392 if (cmd_args.exists("password"))
393 menudata.password = cmd_args.get("password");
395 // If a world was commanded, append and select it
396 if (!game_params.world_path.empty()) {
397 worldspec.gameid = getWorldGameId(game_params.world_path, true);
398 worldspec.name = _("[--world parameter]");
400 if (worldspec.gameid.empty()) { // Create new
401 worldspec.gameid = g_settings->get("default_game");
402 worldspec.name += " [new]";
404 worldspec.path = game_params.world_path;
409 if (!skip_main_menu) {
410 main_menu(&menudata);
412 // Skip further loading if there was an exit signal.
413 if (*porting::signal_handler_killstatus())
416 address = menudata.address;
417 int newport = stoi(menudata.port);
419 game_params.socket_port = newport;
421 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
423 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
425 if (menudata.selected_world >= 0
426 && menudata.selected_world < (int)worldspecs.size()) {
427 g_settings->set("selected_world_path",
428 worldspecs[menudata.selected_world].path);
429 worldspec = worldspecs[menudata.selected_world];
433 if (!menudata.script_data.errormessage.empty()) {
434 /* The calling function will pass this back into this function upon the
435 * next iteration (if any) causing it to be displayed by the GUI
437 error_message = menudata.script_data.errormessage;
441 if (menudata.name.empty() && !simple_singleplayer_mode) {
442 error_message = gettext("Please choose a name!");
443 errorstream << error_message << std::endl;
447 playername = menudata.name;
448 password = menudata.password;
450 current_playername = playername;
451 current_password = password;
452 current_address = address;
453 current_port = game_params.socket_port;
455 // If using simple singleplayer mode, override
456 if (simple_singleplayer_mode) {
457 assert(!skip_main_menu);
458 current_playername = "singleplayer";
459 current_password = "";
460 current_address = "";
461 current_port = myrand_range(49152, 65535);
463 g_settings->set("name", playername);
464 if (!address.empty()) {
465 ServerListSpec server;
466 server["name"] = menudata.servername;
467 server["address"] = menudata.address;
468 server["port"] = menudata.port;
469 server["description"] = menudata.serverdescription;
470 ServerList::insert(server);
474 infostream << "Selected world: " << worldspec.name
475 << " [" << worldspec.path << "]" << std::endl;
477 if (current_address.empty()) { // If local game
478 if (worldspec.path.empty()) {
479 error_message = gettext("No world selected and no address "
480 "provided. Nothing to do.");
481 errorstream << error_message << std::endl;
485 if (!fs::PathExists(worldspec.path)) {
486 error_message = gettext("Provided world path doesn't exist: ")
488 errorstream << error_message << std::endl;
492 // Load gamespec for required game
493 gamespec = findWorldSubgame(worldspec.path);
494 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
495 error_message = gettext("Could not find or load game \"")
496 + worldspec.gameid + "\"";
497 errorstream << error_message << std::endl;
501 if (porting::signal_handler_killstatus())
504 if (game_params.game_spec.isValid() &&
505 game_params.game_spec.id != worldspec.gameid) {
506 warningstream << "Overriding gamespec from \""
507 << worldspec.gameid << "\" to \""
508 << game_params.game_spec.id << "\"" << std::endl;
509 gamespec = game_params.game_spec;
512 if (!gamespec.isValid()) {
513 error_message = gettext("Invalid gamespec.");
514 error_message += " (world.gameid=" + worldspec.gameid + ")";
515 errorstream << error_message << std::endl;
523 void ClientLauncher::main_menu(MainMenuData *menudata)
525 bool *kill = porting::signal_handler_killstatus();
526 video::IVideoDriver *driver = RenderingEngine::get_video_driver();
528 infostream << "Waiting for other menus" << std::endl;
529 while (RenderingEngine::get_raw_device()->run() && !*kill) {
532 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
533 RenderingEngine::get_gui_env()->drawAll();
535 // On some computers framerate doesn't seem to be automatically limited
538 infostream << "Waited for other menus" << std::endl;
540 // Cursor can be non-visible when coming from the game
542 RenderingEngine::get_raw_device()->getCursorControl()->setVisible(true);
546 GUIEngine mymenu(&input->joystick, guiroot, &g_menumgr, menudata, *kill);
548 /* leave scene manager in a clean state */
549 RenderingEngine::get_scene_manager()->clear();
552 void ClientLauncher::speed_tests()
554 // volatile to avoid some potential compiler optimisations
555 volatile static s16 temp16;
556 volatile static f32 tempf;
559 static std::string tempstring;
560 static std::string tempstring2;
568 infostream << "The following test should take around 20ms." << std::endl;
569 TimeTaker timer("Testing std::string speed");
570 const u32 jj = 10000;
571 for (u32 j = 0; j < jj; j++) {
575 for (u32 i = 0; i < ii; i++) {
576 tempstring2 += "asd";
578 for (u32 i = 0; i < ii+1; i++) {
580 if (tempstring == tempstring2)
586 infostream << "All of the following tests should take around 100ms each."
590 TimeTaker timer("Testing floating-point conversion speed");
592 for (u32 i = 0; i < 4000000; i++) {
599 TimeTaker timer("Testing floating-point vector speed");
601 tempv3f1 = v3f(1, 2, 3);
602 tempv3f2 = v3f(4, 5, 6);
603 for (u32 i = 0; i < 10000000; i++) {
604 tempf += tempv3f1.dotProduct(tempv3f2);
605 tempv3f2 += v3f(7, 8, 9);
610 TimeTaker timer("Testing std::map speed");
612 std::map<v2s16, f32> map1;
615 for (s16 y = 0; y < ii; y++) {
616 for (s16 x = 0; x < ii; x++) {
617 map1[v2s16(x, y)] = tempf;
621 for (s16 y = ii - 1; y >= 0; y--) {
622 for (s16 x = 0; x < ii; x++) {
623 tempf = map1[v2s16(x, y)];
629 infostream << "Around 5000/ms should do well here." << std::endl;
630 TimeTaker timer("Testing mutex speed");
643 while(timer.getTimerTime() < 10);
645 u32 dtime = timer.stop();
646 u32 per_ms = n / dtime;
647 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;