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"
44 gui::IGUIEnvironment *guienv = nullptr;
45 gui::IGUIStaticText *guiroot = nullptr;
46 MainMenuManager g_menumgr;
50 return g_menumgr.menuCount() != 0;
53 // Passed to menus to allow disconnecting and exiting
54 MainGameCallback *g_gamecallback = nullptr;
57 ClientLauncher::~ClientLauncher()
64 delete g_gamecallback;
66 delete RenderingEngine::get_instance();
70 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
72 init_args(game_params, cmd_args);
74 // List video modes if requested
76 return RenderingEngine::print_video_modes();
79 if (g_settings->getBool("enable_sound"))
80 g_sound_manager_singleton = createSoundManagerSingleton();
84 errorstream << "Could not initialize game engine." << std::endl;
88 // Speed tests (done after irrlicht is loaded to get timer)
89 if (cmd_args.getFlag("speedtests")) {
90 dstream << "Running speed tests" << std::endl;
95 video::IVideoDriver *video_driver = RenderingEngine::get_video_driver();
96 if (video_driver == NULL) {
97 errorstream << "Could not initialize video driver." << std::endl;
101 RenderingEngine::setXorgClassHint(video_driver->getExposedVideoData(), PROJECT_NAME_C);
102 RenderingEngine::get_instance()->setWindowIcon();
105 This changes the minimum allowed number of vertices in a VBO.
108 //driver->setMinHardwareBufferVertexCount(50);
110 // Create game callback for menus
111 g_gamecallback = new MainGameCallback();
113 RenderingEngine::get_instance()->setResizable(true);
117 RenderingEngine::get_scene_manager()->getParameters()->
118 setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
120 guienv = RenderingEngine::get_gui_env();
121 skin = RenderingEngine::get_gui_env()->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 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
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 = RenderingEngine::get_scene_manager()->createNewSceneManager();
142 g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
143 g_menuclouds->setHeight(100.0f);
144 g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 200, 200, 255));
145 scene::ICameraSceneNode* camera;
146 camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100));
147 camera->setFarValue(10000);
153 ChatBackend chat_backend;
155 // If an error occurs, this is set to something by menu().
156 // It is then displayed before the menu shows on the next call to menu()
157 std::string error_message;
158 bool reconnect_requested = false;
160 bool first_loop = true;
166 bool *kill = porting::signal_handler_killstatus();
168 while (RenderingEngine::run() && !*kill &&
169 !g_gamecallback->shutdown_requested) {
170 // Set the window caption
171 const wchar_t *text = wgettext("Main Menu");
172 RenderingEngine::get_raw_device()->
173 setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
174 L" " + utf8_to_wide(g_version_hash) +
175 L" [" + text + L"]").c_str());
178 try { // This is used for catching disconnects
180 RenderingEngine::get_gui_env()->clear();
183 We need some kind of a root node to be able to add
184 custom gui elements directly on the screen.
185 Otherwise they won't be automatically drawn.
187 guiroot = RenderingEngine::get_gui_env()->addStaticText(L"",
188 core::rect<s32>(0, 0, 10000, 10000));
190 bool game_has_run = launch_game(error_message, reconnect_requested,
191 game_params, cmd_args);
193 // Reset the reconnect_requested flag
194 reconnect_requested = false;
196 // If skip_main_menu, we only want to startup once
197 if (skip_main_menu && !first_loop)
209 // Break out of menu-game loop to shut down cleanly
210 if (!RenderingEngine::get_raw_device()->run() || *kill) {
211 if (!g_settings_path.empty())
212 g_settings->updateConfigFile(g_settings_path.c_str());
216 if (current_playername.length() > PLAYERNAME_SIZE-1) {
217 error_message = gettext("Player name too long.");
218 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
219 g_settings->set("name", playername);
223 RenderingEngine::get_video_driver()->setTextureCreationFlag(
224 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
226 #ifdef HAVE_TOUCHSCREENGUI
227 receiver->m_touchscreengui = new TouchScreenGUI(RenderingEngine::get_raw_device(), receiver);
228 g_touchscreengui = receiver->m_touchscreengui;
242 &reconnect_requested,
244 simple_singleplayer_mode
246 RenderingEngine::get_scene_manager()->clear();
248 #ifdef HAVE_TOUCHSCREENGUI
249 delete g_touchscreengui;
250 g_touchscreengui = NULL;
251 receiver->m_touchscreengui = NULL;
255 catch (con::PeerNotFoundException &e) {
256 error_message = gettext("Connection error (timed out?)");
257 errorstream << error_message << std::endl;
261 catch (std::exception &e) {
262 std::string error_message = "Some exception: \"";
263 error_message += e.what();
264 error_message += "\"";
265 errorstream << error_message << std::endl;
269 // If no main menu, show error and exit
270 if (skip_main_menu) {
271 if (!error_message.empty()) {
272 verbosestream << "error_message = "
273 << error_message << std::endl;
280 g_menuclouds->drop();
281 g_menucloudsmgr->drop();
286 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
289 skip_main_menu = cmd_args.getFlag("go");
291 // FIXME: This is confusing (but correct)
293 /* If world_path is set then override it unless skipping the main menu using
294 * the --go command line param. Else, give preference to the address
295 * supplied on the command line
297 address = g_settings->get("address");
298 if (!game_params.world_path.empty() && !skip_main_menu)
300 else if (cmd_args.exists("address"))
301 address = cmd_args.get("address");
303 playername = g_settings->get("name");
304 if (cmd_args.exists("name"))
305 playername = cmd_args.get("name");
307 list_video_modes = cmd_args.getFlag("videomodes");
309 use_freetype = g_settings->getBool("freetype");
311 random_input = g_settings->getBool("random_input")
312 || cmd_args.getFlag("random-input");
315 bool ClientLauncher::init_engine()
317 receiver = new MyEventReceiver();
318 new RenderingEngine(receiver);
319 return RenderingEngine::get_raw_device() != nullptr;
322 void ClientLauncher::init_input()
325 input = new RandomInputHandler();
327 input = new RealInputHandler(receiver);
329 if (g_settings->getBool("enable_joysticks")) {
330 irr::core::array<irr::SJoystickInfo> infos;
331 std::vector<irr::SJoystickInfo> joystick_infos;
333 // Make sure this is called maximum once per
334 // irrlicht device, otherwise it will give you
335 // multiple events for the same joystick.
336 if (RenderingEngine::get_raw_device()->activateJoysticks(infos)) {
337 infostream << "Joystick support enabled" << std::endl;
338 joystick_infos.reserve(infos.size());
339 for (u32 i = 0; i < infos.size(); i++) {
340 joystick_infos.push_back(infos[i]);
342 input->joystick.onJoystickConnect(joystick_infos);
344 errorstream << "Could not activate joystick support." << std::endl;
349 bool ClientLauncher::launch_game(std::string &error_message,
350 bool reconnect_requested, GameParams &game_params,
351 const Settings &cmd_args)
353 // Initialize menu data
354 MainMenuData menudata;
355 menudata.address = address;
356 menudata.name = playername;
357 menudata.password = password;
358 menudata.port = itos(game_params.socket_port);
359 menudata.script_data.errormessage = error_message;
360 menudata.script_data.reconnect_requested = reconnect_requested;
362 error_message.clear();
364 if (cmd_args.exists("password"))
365 menudata.password = cmd_args.get("password");
367 // If a world was commanded, append and select it
368 if (!game_params.world_path.empty()) {
369 worldspec.gameid = getWorldGameId(game_params.world_path, true);
370 worldspec.name = _("[--world parameter]");
372 if (worldspec.gameid.empty()) { // Create new
373 worldspec.gameid = g_settings->get("default_game");
374 worldspec.name += " [new]";
376 worldspec.path = game_params.world_path;
381 if (!skip_main_menu) {
382 main_menu(&menudata);
384 // Skip further loading if there was an exit signal.
385 if (*porting::signal_handler_killstatus())
388 address = menudata.address;
389 int newport = stoi(menudata.port);
391 game_params.socket_port = newport;
393 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
395 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
397 if (menudata.selected_world >= 0
398 && menudata.selected_world < (int)worldspecs.size()) {
399 g_settings->set("selected_world_path",
400 worldspecs[menudata.selected_world].path);
401 worldspec = worldspecs[menudata.selected_world];
405 if (!menudata.script_data.errormessage.empty()) {
406 /* The calling function will pass this back into this function upon the
407 * next iteration (if any) causing it to be displayed by the GUI
409 error_message = menudata.script_data.errormessage;
413 if (menudata.name.empty() && !simple_singleplayer_mode) {
414 error_message = gettext("Please choose a name!");
415 errorstream << error_message << std::endl;
419 playername = menudata.name;
420 password = menudata.password;
422 current_playername = playername;
423 current_password = password;
424 current_address = address;
425 current_port = game_params.socket_port;
427 // If using simple singleplayer mode, override
428 if (simple_singleplayer_mode) {
429 assert(!skip_main_menu);
430 current_playername = "singleplayer";
431 current_password = "";
432 current_address = "";
433 current_port = myrand_range(49152, 65535);
435 g_settings->set("name", playername);
436 if (!address.empty()) {
437 ServerListSpec server;
438 server["name"] = menudata.servername;
439 server["address"] = menudata.address;
440 server["port"] = menudata.port;
441 server["description"] = menudata.serverdescription;
442 ServerList::insert(server);
446 infostream << "Selected world: " << worldspec.name
447 << " [" << worldspec.path << "]" << std::endl;
449 if (current_address.empty()) { // If local game
450 if (worldspec.path.empty()) {
451 error_message = gettext("No world selected and no address "
452 "provided. Nothing to do.");
453 errorstream << error_message << std::endl;
457 if (!fs::PathExists(worldspec.path)) {
458 error_message = gettext("Provided world path doesn't exist: ")
460 errorstream << error_message << std::endl;
464 // Load gamespec for required game
465 gamespec = findWorldSubgame(worldspec.path);
466 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
467 error_message = gettext("Could not find or load game \"")
468 + worldspec.gameid + "\"";
469 errorstream << error_message << std::endl;
473 if (porting::signal_handler_killstatus())
476 if (game_params.game_spec.isValid() &&
477 game_params.game_spec.id != worldspec.gameid) {
478 warningstream << "Overriding gamespec from \""
479 << worldspec.gameid << "\" to \""
480 << game_params.game_spec.id << "\"" << std::endl;
481 gamespec = game_params.game_spec;
484 if (!gamespec.isValid()) {
485 error_message = gettext("Invalid gamespec.");
486 error_message += " (world.gameid=" + worldspec.gameid + ")";
487 errorstream << error_message << std::endl;
495 void ClientLauncher::main_menu(MainMenuData *menudata)
497 bool *kill = porting::signal_handler_killstatus();
498 video::IVideoDriver *driver = RenderingEngine::get_video_driver();
500 infostream << "Waiting for other menus" << std::endl;
501 while (RenderingEngine::get_raw_device()->run() && !*kill) {
504 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
505 RenderingEngine::get_gui_env()->drawAll();
507 // On some computers framerate doesn't seem to be automatically limited
510 infostream << "Waited for other menus" << std::endl;
512 // Cursor can be non-visible when coming from the game
514 RenderingEngine::get_raw_device()->getCursorControl()->setVisible(true);
518 GUIEngine mymenu(&input->joystick, guiroot, &g_menumgr, menudata, *kill);
520 /* leave scene manager in a clean state */
521 RenderingEngine::get_scene_manager()->clear();
524 void ClientLauncher::speed_tests()
526 // volatile to avoid some potential compiler optimisations
527 volatile static s16 temp16;
528 volatile static f32 tempf;
531 static std::string tempstring;
532 static std::string tempstring2;
540 infostream << "The following test should take around 20ms." << std::endl;
541 TimeTaker timer("Testing std::string speed");
542 const u32 jj = 10000;
543 for (u32 j = 0; j < jj; j++) {
547 for (u32 i = 0; i < ii; i++) {
548 tempstring2 += "asd";
550 for (u32 i = 0; i < ii+1; i++) {
552 if (tempstring == tempstring2)
558 infostream << "All of the following tests should take around 100ms each."
562 TimeTaker timer("Testing floating-point conversion speed");
564 for (u32 i = 0; i < 4000000; i++) {
571 TimeTaker timer("Testing floating-point vector speed");
573 tempv3f1 = v3f(1, 2, 3);
574 tempv3f2 = v3f(4, 5, 6);
575 for (u32 i = 0; i < 10000000; i++) {
576 tempf += tempv3f1.dotProduct(tempv3f2);
577 tempv3f2 += v3f(7, 8, 9);
582 TimeTaker timer("Testing std::map speed");
584 std::map<v2s16, f32> map1;
587 for (s16 y = 0; y < ii; y++) {
588 for (s16 x = 0; x < ii; x++) {
589 map1[v2s16(x, y)] = tempf;
593 for (s16 y = ii - 1; y >= 0; y--) {
594 for (s16 x = 0; x < ii; x++) {
595 tempf = map1[v2s16(x, y)];
601 infostream << "Around 5000/ms should do well here." << std::endl;
602 TimeTaker timer("Testing mutex speed");
615 while(timer.getTimerTime() < 10);
617 u32 dtime = timer.stop();
618 u32 per_ms = n / dtime;
619 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;