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"
40 gui::IGUIEnvironment *guienv = nullptr;
41 gui::IGUIStaticText *guiroot = nullptr;
42 MainMenuManager g_menumgr;
46 return g_menumgr.menuCount() != 0;
49 // Passed to menus to allow disconnecting and exiting
50 MainGameCallback *g_gamecallback = nullptr;
53 ClientLauncher::~ClientLauncher()
60 delete g_gamecallback;
62 delete RenderingEngine::get_instance();
66 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
68 init_args(game_params, cmd_args);
70 // List video modes if requested
72 return RenderingEngine::print_video_modes();
75 errorstream << "Could not initialize game engine." << std::endl;
79 // Speed tests (done after irrlicht is loaded to get timer)
80 if (cmd_args.getFlag("speedtests")) {
81 dstream << "Running speed tests" << std::endl;
86 video::IVideoDriver *video_driver = RenderingEngine::get_video_driver();
87 if (video_driver == NULL) {
88 errorstream << "Could not initialize video driver." << std::endl;
92 RenderingEngine::setXorgClassHint(video_driver->getExposedVideoData(), PROJECT_NAME_C);
93 RenderingEngine::get_instance()->setWindowIcon();
96 This changes the minimum allowed number of vertices in a VBO.
99 //driver->setMinHardwareBufferVertexCount(50);
101 // Create game callback for menus
102 g_gamecallback = new MainGameCallback();
104 RenderingEngine::get_instance()->setResizable(true);
108 RenderingEngine::get_scene_manager()->getParameters()->
109 setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
111 guienv = RenderingEngine::get_gui_env();
112 skin = RenderingEngine::get_gui_env()->getSkin();
113 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
114 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
115 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
116 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
117 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
118 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
120 g_fontengine = new FontEngine(g_settings, guienv);
121 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
123 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
124 // Irrlicht 1.8 input colours
125 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
126 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
129 // Create the menu clouds
130 if (!g_menucloudsmgr)
131 g_menucloudsmgr = RenderingEngine::get_scene_manager()->createNewSceneManager();
133 g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
134 g_menuclouds->setHeight(100.0f);
135 g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 200, 200, 255));
136 scene::ICameraSceneNode* camera;
137 camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100));
138 camera->setFarValue(10000);
144 ChatBackend chat_backend;
146 // If an error occurs, this is set to something by menu().
147 // It is then displayed before the menu shows on the next call to menu()
148 std::string error_message;
149 bool reconnect_requested = false;
151 bool first_loop = true;
157 bool *kill = porting::signal_handler_killstatus();
159 while (RenderingEngine::run() && !*kill &&
160 !g_gamecallback->shutdown_requested) {
161 // Set the window caption
162 const wchar_t *text = wgettext("Main Menu");
163 RenderingEngine::get_raw_device()->
164 setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
165 L" " + utf8_to_wide(g_version_hash) +
166 L" [" + text + L"]").c_str());
169 try { // This is used for catching disconnects
171 RenderingEngine::get_gui_env()->clear();
174 We need some kind of a root node to be able to add
175 custom gui elements directly on the screen.
176 Otherwise they won't be automatically drawn.
178 guiroot = RenderingEngine::get_gui_env()->addStaticText(L"",
179 core::rect<s32>(0, 0, 10000, 10000));
181 bool game_has_run = launch_game(error_message, reconnect_requested,
182 game_params, cmd_args);
184 // Reset the reconnect_requested flag
185 reconnect_requested = false;
187 // If skip_main_menu, we only want to startup once
188 if (skip_main_menu && !first_loop)
200 // Break out of menu-game loop to shut down cleanly
201 if (!RenderingEngine::get_raw_device()->run() || *kill) {
202 if (!g_settings_path.empty())
203 g_settings->updateConfigFile(g_settings_path.c_str());
207 if (current_playername.length() > PLAYERNAME_SIZE-1) {
208 error_message = gettext("Player name too long.");
209 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
210 g_settings->set("name", playername);
214 RenderingEngine::get_video_driver()->setTextureCreationFlag(
215 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
217 #ifdef HAVE_TOUCHSCREENGUI
218 receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
219 g_touchscreengui = receiver->m_touchscreengui;
233 &reconnect_requested,
235 simple_singleplayer_mode
237 RenderingEngine::get_scene_manager()->clear();
239 #ifdef HAVE_TOUCHSCREENGUI
240 delete g_touchscreengui;
241 g_touchscreengui = NULL;
242 receiver->m_touchscreengui = NULL;
246 catch (con::PeerNotFoundException &e) {
247 error_message = gettext("Connection error (timed out?)");
248 errorstream << error_message << std::endl;
252 catch (std::exception &e) {
253 std::string error_message = "Some exception: \"";
254 error_message += e.what();
255 error_message += "\"";
256 errorstream << error_message << std::endl;
260 // If no main menu, show error and exit
261 if (skip_main_menu) {
262 if (!error_message.empty()) {
263 verbosestream << "error_message = "
264 << error_message << std::endl;
271 g_menuclouds->drop();
272 g_menucloudsmgr->drop();
277 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
280 skip_main_menu = cmd_args.getFlag("go");
282 // FIXME: This is confusing (but correct)
284 /* If world_path is set then override it unless skipping the main menu using
285 * the --go command line param. Else, give preference to the address
286 * supplied on the command line
288 address = g_settings->get("address");
289 if (!game_params.world_path.empty() && !skip_main_menu)
291 else if (cmd_args.exists("address"))
292 address = cmd_args.get("address");
294 playername = g_settings->get("name");
295 if (cmd_args.exists("name"))
296 playername = cmd_args.get("name");
298 list_video_modes = cmd_args.getFlag("videomodes");
300 use_freetype = g_settings->getBool("freetype");
302 random_input = g_settings->getBool("random_input")
303 || cmd_args.getFlag("random-input");
306 bool ClientLauncher::init_engine()
308 receiver = new MyEventReceiver();
309 new RenderingEngine(receiver);
310 return RenderingEngine::get_raw_device() != nullptr;
313 void ClientLauncher::init_input()
316 input = new RandomInputHandler();
318 input = new RealInputHandler(receiver);
320 if (g_settings->getBool("enable_joysticks")) {
321 irr::core::array<irr::SJoystickInfo> infos;
322 std::vector<irr::SJoystickInfo> joystick_infos;
324 // Make sure this is called maximum once per
325 // irrlicht device, otherwise it will give you
326 // multiple events for the same joystick.
327 if (RenderingEngine::get_raw_device()->activateJoysticks(infos)) {
328 infostream << "Joystick support enabled" << std::endl;
329 joystick_infos.reserve(infos.size());
330 for (u32 i = 0; i < infos.size(); i++) {
331 joystick_infos.push_back(infos[i]);
333 input->joystick.onJoystickConnect(joystick_infos);
335 errorstream << "Could not activate joystick support." << std::endl;
340 bool ClientLauncher::launch_game(std::string &error_message,
341 bool reconnect_requested, GameParams &game_params,
342 const Settings &cmd_args)
344 // Initialize menu data
345 MainMenuData menudata;
346 menudata.address = address;
347 menudata.name = playername;
348 menudata.password = password;
349 menudata.port = itos(game_params.socket_port);
350 menudata.script_data.errormessage = error_message;
351 menudata.script_data.reconnect_requested = reconnect_requested;
353 error_message.clear();
355 if (cmd_args.exists("password"))
356 menudata.password = cmd_args.get("password");
358 // If a world was commanded, append and select it
359 if (!game_params.world_path.empty()) {
360 worldspec.gameid = getWorldGameId(game_params.world_path, true);
361 worldspec.name = _("[--world parameter]");
363 if (worldspec.gameid.empty()) { // Create new
364 worldspec.gameid = g_settings->get("default_game");
365 worldspec.name += " [new]";
367 worldspec.path = game_params.world_path;
372 if (!skip_main_menu) {
373 main_menu(&menudata);
375 // Skip further loading if there was an exit signal.
376 if (*porting::signal_handler_killstatus())
379 address = menudata.address;
380 int newport = stoi(menudata.port);
382 game_params.socket_port = newport;
384 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
386 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
388 if (menudata.selected_world >= 0
389 && menudata.selected_world < (int)worldspecs.size()) {
390 g_settings->set("selected_world_path",
391 worldspecs[menudata.selected_world].path);
392 worldspec = worldspecs[menudata.selected_world];
396 if (!menudata.script_data.errormessage.empty()) {
397 /* The calling function will pass this back into this function upon the
398 * next iteration (if any) causing it to be displayed by the GUI
400 error_message = menudata.script_data.errormessage;
404 if (menudata.name.empty() && !simple_singleplayer_mode) {
405 error_message = gettext("Please choose a name!");
406 errorstream << error_message << std::endl;
410 playername = menudata.name;
411 password = menudata.password;
413 current_playername = playername;
414 current_password = password;
415 current_address = address;
416 current_port = game_params.socket_port;
418 // If using simple singleplayer mode, override
419 if (simple_singleplayer_mode) {
420 assert(!skip_main_menu);
421 current_playername = "singleplayer";
422 current_password = "";
423 current_address = "";
424 current_port = myrand_range(49152, 65535);
426 g_settings->set("name", playername);
427 if (!address.empty()) {
428 ServerListSpec server;
429 server["name"] = menudata.servername;
430 server["address"] = menudata.address;
431 server["port"] = menudata.port;
432 server["description"] = menudata.serverdescription;
433 ServerList::insert(server);
437 infostream << "Selected world: " << worldspec.name
438 << " [" << worldspec.path << "]" << std::endl;
440 if (current_address.empty()) { // If local game
441 if (worldspec.path.empty()) {
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 = RenderingEngine::get_video_driver();
491 infostream << "Waiting for other menus" << std::endl;
492 while (RenderingEngine::get_raw_device()->run() && !*kill) {
495 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
496 RenderingEngine::get_gui_env()->drawAll();
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 RenderingEngine::get_raw_device()->getCursorControl()->setVisible(true);
509 GUIEngine mymenu(&input->joystick, guiroot, &g_menumgr, menudata, *kill);
511 /* leave scene manager in a clean state */
512 RenderingEngine::get_scene_manager()->clear();
515 void ClientLauncher::speed_tests()
517 // volatile to avoid some potential compiler optimisations
518 volatile static s16 temp16;
519 volatile static f32 tempf;
522 static std::string tempstring;
523 static std::string tempstring2;
531 infostream << "The following test should take around 20ms." << std::endl;
532 TimeTaker timer("Testing std::string speed");
533 const u32 jj = 10000;
534 for (u32 j = 0; j < jj; j++) {
538 for (u32 i = 0; i < ii; i++) {
539 tempstring2 += "asd";
541 for (u32 i = 0; i < ii+1; i++) {
543 if (tempstring == tempstring2)
549 infostream << "All of the following tests should take around 100ms each."
553 TimeTaker timer("Testing floating-point conversion speed");
555 for (u32 i = 0; i < 4000000; i++) {
562 TimeTaker timer("Testing floating-point vector speed");
564 tempv3f1 = v3f(1, 2, 3);
565 tempv3f2 = v3f(4, 5, 6);
566 for (u32 i = 0; i < 10000000; i++) {
567 tempf += tempv3f1.dotProduct(tempv3f2);
568 tempv3f2 += v3f(7, 8, 9);
573 TimeTaker timer("Testing std::map speed");
575 std::map<v2s16, f32> map1;
578 for (s16 y = 0; y < ii; y++) {
579 for (s16 x = 0; x < ii; x++) {
580 map1[v2s16(x, y)] = tempf;
584 for (s16 y = ii - 1; y >= 0; y--) {
585 for (s16 x = 0; x < ii; x++) {
586 tempf = map1[v2s16(x, y)];
592 infostream << "Around 5000/ms should do well here." << std::endl;
593 TimeTaker timer("Testing mutex speed");
606 while(timer.getTimerTime() < 10);
608 u32 dtime = timer.stop();
609 u32 per_ms = n / dtime;
610 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;