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();
69 g_sound_manager_singleton.reset();
74 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
76 init_args(game_params, cmd_args);
78 // List video modes if requested
80 return RenderingEngine::print_video_modes();
83 if (g_settings->getBool("enable_sound"))
84 g_sound_manager_singleton = createSoundManagerSingleton();
88 errorstream << "Could not initialize game engine." << std::endl;
92 // Speed tests (done after irrlicht is loaded to get timer)
93 if (cmd_args.getFlag("speedtests")) {
94 dstream << "Running speed tests" << std::endl;
99 video::IVideoDriver *video_driver = RenderingEngine::get_video_driver();
100 if (video_driver == NULL) {
101 errorstream << "Could not initialize video driver." << std::endl;
105 RenderingEngine::setXorgClassHint(video_driver->getExposedVideoData(), PROJECT_NAME_C);
106 RenderingEngine::get_instance()->setWindowIcon();
109 This changes the minimum allowed number of vertices in a VBO.
112 //driver->setMinHardwareBufferVertexCount(50);
114 // Create game callback for menus
115 g_gamecallback = new MainGameCallback();
117 RenderingEngine::get_instance()->setResizable(true);
121 RenderingEngine::get_scene_manager()->getParameters()->
122 setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
124 guienv = RenderingEngine::get_gui_env();
125 skin = RenderingEngine::get_gui_env()->getSkin();
126 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
127 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
128 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
129 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
130 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
131 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
133 g_fontengine = new FontEngine(g_settings, guienv);
134 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
136 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
137 // Irrlicht 1.8 input colours
138 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
139 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
142 // Create the menu clouds
143 if (!g_menucloudsmgr)
144 g_menucloudsmgr = RenderingEngine::get_scene_manager()->createNewSceneManager();
146 g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
147 g_menuclouds->setHeight(100.0f);
148 g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 200, 200, 255));
149 scene::ICameraSceneNode* camera;
150 camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100));
151 camera->setFarValue(10000);
157 ChatBackend chat_backend;
159 // If an error occurs, this is set to something by menu().
160 // It is then displayed before the menu shows on the next call to menu()
161 std::string error_message;
162 bool reconnect_requested = false;
164 bool first_loop = true;
170 bool *kill = porting::signal_handler_killstatus();
172 while (RenderingEngine::run() && !*kill &&
173 !g_gamecallback->shutdown_requested) {
174 // Set the window caption
175 const wchar_t *text = wgettext("Main Menu");
176 RenderingEngine::get_raw_device()->
177 setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
178 L" " + utf8_to_wide(g_version_hash) +
179 L" [" + text + L"]").c_str());
182 try { // This is used for catching disconnects
184 RenderingEngine::get_gui_env()->clear();
187 We need some kind of a root node to be able to add
188 custom gui elements directly on the screen.
189 Otherwise they won't be automatically drawn.
191 guiroot = RenderingEngine::get_gui_env()->addStaticText(L"",
192 core::rect<s32>(0, 0, 10000, 10000));
194 bool game_has_run = launch_game(error_message, reconnect_requested,
195 game_params, cmd_args);
197 // Reset the reconnect_requested flag
198 reconnect_requested = false;
200 // If skip_main_menu, we only want to startup once
201 if (skip_main_menu && !first_loop)
213 // Break out of menu-game loop to shut down cleanly
214 if (!RenderingEngine::get_raw_device()->run() || *kill) {
215 if (!g_settings_path.empty())
216 g_settings->updateConfigFile(g_settings_path.c_str());
220 if (current_playername.length() > PLAYERNAME_SIZE-1) {
221 error_message = gettext("Player name too long.");
222 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
223 g_settings->set("name", playername);
227 RenderingEngine::get_video_driver()->setTextureCreationFlag(
228 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
230 #ifdef HAVE_TOUCHSCREENGUI
231 receiver->m_touchscreengui = new TouchScreenGUI(RenderingEngine::get_raw_device(), receiver);
232 g_touchscreengui = receiver->m_touchscreengui;
246 &reconnect_requested,
248 simple_singleplayer_mode
250 RenderingEngine::get_scene_manager()->clear();
252 #ifdef HAVE_TOUCHSCREENGUI
253 delete g_touchscreengui;
254 g_touchscreengui = NULL;
255 receiver->m_touchscreengui = NULL;
259 catch (con::PeerNotFoundException &e) {
260 error_message = gettext("Connection error (timed out?)");
261 errorstream << error_message << std::endl;
265 catch (std::exception &e) {
266 std::string error_message = "Some exception: \"";
267 error_message += e.what();
268 error_message += "\"";
269 errorstream << error_message << std::endl;
273 // If no main menu, show error and exit
274 if (skip_main_menu) {
275 if (!error_message.empty()) {
276 verbosestream << "error_message = "
277 << error_message << std::endl;
284 g_menuclouds->drop();
285 g_menucloudsmgr->drop();
290 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
293 skip_main_menu = cmd_args.getFlag("go");
295 // FIXME: This is confusing (but correct)
297 /* If world_path is set then override it unless skipping the main menu using
298 * the --go command line param. Else, give preference to the address
299 * supplied on the command line
301 address = g_settings->get("address");
302 if (!game_params.world_path.empty() && !skip_main_menu)
304 else if (cmd_args.exists("address"))
305 address = cmd_args.get("address");
307 playername = g_settings->get("name");
308 if (cmd_args.exists("name"))
309 playername = cmd_args.get("name");
311 list_video_modes = cmd_args.getFlag("videomodes");
313 use_freetype = g_settings->getBool("freetype");
315 random_input = g_settings->getBool("random_input")
316 || cmd_args.getFlag("random-input");
319 bool ClientLauncher::init_engine()
321 receiver = new MyEventReceiver();
322 new RenderingEngine(receiver);
323 return RenderingEngine::get_raw_device() != nullptr;
326 void ClientLauncher::init_input()
329 input = new RandomInputHandler();
331 input = new RealInputHandler(receiver);
333 if (g_settings->getBool("enable_joysticks")) {
334 irr::core::array<irr::SJoystickInfo> infos;
335 std::vector<irr::SJoystickInfo> joystick_infos;
337 // Make sure this is called maximum once per
338 // irrlicht device, otherwise it will give you
339 // multiple events for the same joystick.
340 if (RenderingEngine::get_raw_device()->activateJoysticks(infos)) {
341 infostream << "Joystick support enabled" << std::endl;
342 joystick_infos.reserve(infos.size());
343 for (u32 i = 0; i < infos.size(); i++) {
344 joystick_infos.push_back(infos[i]);
346 input->joystick.onJoystickConnect(joystick_infos);
348 errorstream << "Could not activate joystick support." << std::endl;
353 bool ClientLauncher::launch_game(std::string &error_message,
354 bool reconnect_requested, GameParams &game_params,
355 const Settings &cmd_args)
357 // Initialize menu data
358 MainMenuData menudata;
359 menudata.address = address;
360 menudata.name = playername;
361 menudata.password = password;
362 menudata.port = itos(game_params.socket_port);
363 menudata.script_data.errormessage = error_message;
364 menudata.script_data.reconnect_requested = reconnect_requested;
366 error_message.clear();
368 if (cmd_args.exists("password"))
369 menudata.password = cmd_args.get("password");
371 // If a world was commanded, append and select it
372 if (!game_params.world_path.empty()) {
373 worldspec.gameid = getWorldGameId(game_params.world_path, true);
374 worldspec.name = _("[--world parameter]");
376 if (worldspec.gameid.empty()) { // Create new
377 worldspec.gameid = g_settings->get("default_game");
378 worldspec.name += " [new]";
380 worldspec.path = game_params.world_path;
385 if (!skip_main_menu) {
386 main_menu(&menudata);
388 // Skip further loading if there was an exit signal.
389 if (*porting::signal_handler_killstatus())
392 address = menudata.address;
393 int newport = stoi(menudata.port);
395 game_params.socket_port = newport;
397 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
399 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
401 if (menudata.selected_world >= 0
402 && menudata.selected_world < (int)worldspecs.size()) {
403 g_settings->set("selected_world_path",
404 worldspecs[menudata.selected_world].path);
405 worldspec = worldspecs[menudata.selected_world];
409 if (!menudata.script_data.errormessage.empty()) {
410 /* The calling function will pass this back into this function upon the
411 * next iteration (if any) causing it to be displayed by the GUI
413 error_message = menudata.script_data.errormessage;
417 if (menudata.name.empty() && !simple_singleplayer_mode) {
418 error_message = gettext("Please choose a name!");
419 errorstream << error_message << std::endl;
423 playername = menudata.name;
424 password = menudata.password;
426 current_playername = playername;
427 current_password = password;
428 current_address = address;
429 current_port = game_params.socket_port;
431 // If using simple singleplayer mode, override
432 if (simple_singleplayer_mode) {
433 assert(!skip_main_menu);
434 current_playername = "singleplayer";
435 current_password = "";
436 current_address = "";
437 current_port = myrand_range(49152, 65535);
439 g_settings->set("name", playername);
440 if (!address.empty()) {
441 ServerListSpec server;
442 server["name"] = menudata.servername;
443 server["address"] = menudata.address;
444 server["port"] = menudata.port;
445 server["description"] = menudata.serverdescription;
446 ServerList::insert(server);
450 infostream << "Selected world: " << worldspec.name
451 << " [" << worldspec.path << "]" << std::endl;
453 if (current_address.empty()) { // If local game
454 if (worldspec.path.empty()) {
455 error_message = gettext("No world selected and no address "
456 "provided. Nothing to do.");
457 errorstream << error_message << std::endl;
461 if (!fs::PathExists(worldspec.path)) {
462 error_message = gettext("Provided world path doesn't exist: ")
464 errorstream << error_message << std::endl;
468 // Load gamespec for required game
469 gamespec = findWorldSubgame(worldspec.path);
470 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
471 error_message = gettext("Could not find or load game \"")
472 + worldspec.gameid + "\"";
473 errorstream << error_message << std::endl;
477 if (porting::signal_handler_killstatus())
480 if (game_params.game_spec.isValid() &&
481 game_params.game_spec.id != worldspec.gameid) {
482 warningstream << "Overriding gamespec from \""
483 << worldspec.gameid << "\" to \""
484 << game_params.game_spec.id << "\"" << std::endl;
485 gamespec = game_params.game_spec;
488 if (!gamespec.isValid()) {
489 error_message = gettext("Invalid gamespec.");
490 error_message += " (world.gameid=" + worldspec.gameid + ")";
491 errorstream << error_message << std::endl;
499 void ClientLauncher::main_menu(MainMenuData *menudata)
501 bool *kill = porting::signal_handler_killstatus();
502 video::IVideoDriver *driver = RenderingEngine::get_video_driver();
504 infostream << "Waiting for other menus" << std::endl;
505 while (RenderingEngine::get_raw_device()->run() && !*kill) {
508 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
509 RenderingEngine::get_gui_env()->drawAll();
511 // On some computers framerate doesn't seem to be automatically limited
514 infostream << "Waited for other menus" << std::endl;
516 // Cursor can be non-visible when coming from the game
518 RenderingEngine::get_raw_device()->getCursorControl()->setVisible(true);
522 GUIEngine mymenu(&input->joystick, guiroot, &g_menumgr, menudata, *kill);
524 /* leave scene manager in a clean state */
525 RenderingEngine::get_scene_manager()->clear();
528 void ClientLauncher::speed_tests()
530 // volatile to avoid some potential compiler optimisations
531 volatile static s16 temp16;
532 volatile static f32 tempf;
535 static std::string tempstring;
536 static std::string tempstring2;
544 infostream << "The following test should take around 20ms." << std::endl;
545 TimeTaker timer("Testing std::string speed");
546 const u32 jj = 10000;
547 for (u32 j = 0; j < jj; j++) {
551 for (u32 i = 0; i < ii; i++) {
552 tempstring2 += "asd";
554 for (u32 i = 0; i < ii+1; i++) {
556 if (tempstring == tempstring2)
562 infostream << "All of the following tests should take around 100ms each."
566 TimeTaker timer("Testing floating-point conversion speed");
568 for (u32 i = 0; i < 4000000; i++) {
575 TimeTaker timer("Testing floating-point vector speed");
577 tempv3f1 = v3f(1, 2, 3);
578 tempv3f2 = v3f(4, 5, 6);
579 for (u32 i = 0; i < 10000000; i++) {
580 tempf += tempv3f1.dotProduct(tempv3f2);
581 tempv3f2 += v3f(7, 8, 9);
586 TimeTaker timer("Testing std::map speed");
588 std::map<v2s16, f32> map1;
591 for (s16 y = 0; y < ii; y++) {
592 for (s16 x = 0; x < ii; x++) {
593 map1[v2s16(x, y)] = tempf;
597 for (s16 y = ii - 1; y >= 0; y--) {
598 for (s16 x = 0; x < ii; x++) {
599 tempf = map1[v2s16(x, y)];
605 infostream << "Around 5000/ms should do well here." << std::endl;
606 TimeTaker timer("Testing mutex speed");
619 while(timer.getTimerTime() < 10);
621 u32 dtime = timer.stop();
622 u32 per_ms = n / dtime;
623 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;