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"
24 #include "guiMainMenu.h"
29 #include "serverlist.h"
30 #include "guiEngine.h"
31 #include "fontengine.h"
32 #include "clientlauncher.h"
34 #include "renderingengine.h"
38 gui::IGUIEnvironment *guienv = nullptr;
39 gui::IGUIStaticText *guiroot = nullptr;
40 MainMenuManager g_menumgr;
44 return g_menumgr.menuCount() != 0;
47 // Passed to menus to allow disconnecting and exiting
48 MainGameCallback *g_gamecallback = nullptr;
51 ClientLauncher::~ClientLauncher()
58 delete g_gamecallback;
60 delete RenderingEngine::get_instance();
64 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
66 init_args(game_params, cmd_args);
68 // List video modes if requested
70 return RenderingEngine::print_video_modes();
73 errorstream << "Could not initialize game engine." << std::endl;
77 // Speed tests (done after irrlicht is loaded to get timer)
78 if (cmd_args.getFlag("speedtests")) {
79 dstream << "Running speed tests" << std::endl;
84 video::IVideoDriver *video_driver = RenderingEngine::get_video_driver();
85 if (video_driver == NULL) {
86 errorstream << "Could not initialize video driver." << std::endl;
90 RenderingEngine::setXorgClassHint(video_driver->getExposedVideoData(), PROJECT_NAME_C);
91 RenderingEngine::get_instance()->setWindowIcon();
94 This changes the minimum allowed number of vertices in a VBO.
97 //driver->setMinHardwareBufferVertexCount(50);
99 // Create game callback for menus
100 g_gamecallback = new MainGameCallback();
102 RenderingEngine::get_instance()->setResizable(true);
106 RenderingEngine::get_scene_manager()->getParameters()->
107 setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
109 guienv = RenderingEngine::get_gui_env();
110 skin = RenderingEngine::get_gui_env()->getSkin();
111 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
112 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
113 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
114 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
115 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
116 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
118 g_fontengine = new FontEngine(g_settings, guienv);
119 FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
121 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
122 // Irrlicht 1.8 input colours
123 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
124 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
127 // Create the menu clouds
128 if (!g_menucloudsmgr)
129 g_menucloudsmgr = RenderingEngine::get_scene_manager()->createNewSceneManager();
131 g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
132 g_menuclouds->setHeight(100.0f);
133 g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 200, 200, 255));
134 scene::ICameraSceneNode* camera;
135 camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100));
136 camera->setFarValue(10000);
142 ChatBackend chat_backend;
144 // If an error occurs, this is set to something by menu().
145 // It is then displayed before the menu shows on the next call to menu()
146 std::string error_message;
147 bool reconnect_requested = false;
149 bool first_loop = true;
155 bool *kill = porting::signal_handler_killstatus();
157 while (RenderingEngine::run() && !*kill &&
158 !g_gamecallback->shutdown_requested) {
159 // Set the window caption
160 const wchar_t *text = wgettext("Main Menu");
161 RenderingEngine::get_raw_device()->
162 setWindowCaption((utf8_to_wide(PROJECT_NAME_C) +
163 L" " + utf8_to_wide(g_version_hash) +
164 L" [" + text + L"]").c_str());
167 try { // This is used for catching disconnects
169 RenderingEngine::get_gui_env()->clear();
172 We need some kind of a root node to be able to add
173 custom gui elements directly on the screen.
174 Otherwise they won't be automatically drawn.
176 guiroot = RenderingEngine::get_gui_env()->addStaticText(L"",
177 core::rect<s32>(0, 0, 10000, 10000));
179 bool game_has_run = launch_game(error_message, reconnect_requested,
180 game_params, cmd_args);
182 // Reset the reconnect_requested flag
183 reconnect_requested = false;
185 // If skip_main_menu, we only want to startup once
186 if (skip_main_menu && !first_loop)
198 // Break out of menu-game loop to shut down cleanly
199 if (!RenderingEngine::get_raw_device()->run() || *kill) {
200 if (!g_settings_path.empty())
201 g_settings->updateConfigFile(g_settings_path.c_str());
205 if (current_playername.length() > PLAYERNAME_SIZE-1) {
206 error_message = gettext("Player name too long.");
207 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
208 g_settings->set("name", playername);
212 RenderingEngine::get_video_driver()->setTextureCreationFlag(
213 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
215 #ifdef HAVE_TOUCHSCREENGUI
216 receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
217 g_touchscreengui = receiver->m_touchscreengui;
231 &reconnect_requested,
233 simple_singleplayer_mode
235 RenderingEngine::get_scene_manager()->clear();
237 #ifdef HAVE_TOUCHSCREENGUI
238 delete g_touchscreengui;
239 g_touchscreengui = NULL;
240 receiver->m_touchscreengui = NULL;
244 catch (con::PeerNotFoundException &e) {
245 error_message = gettext("Connection error (timed out?)");
246 errorstream << error_message << std::endl;
250 catch (std::exception &e) {
251 std::string error_message = "Some exception: \"";
252 error_message += e.what();
253 error_message += "\"";
254 errorstream << error_message << std::endl;
258 // If no main menu, show error and exit
259 if (skip_main_menu) {
260 if (!error_message.empty()) {
261 verbosestream << "error_message = "
262 << error_message << std::endl;
269 g_menuclouds->drop();
270 g_menucloudsmgr->drop();
275 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
278 skip_main_menu = cmd_args.getFlag("go");
280 // FIXME: This is confusing (but correct)
282 /* If world_path is set then override it unless skipping the main menu using
283 * the --go command line param. Else, give preference to the address
284 * supplied on the command line
286 address = g_settings->get("address");
287 if (!game_params.world_path.empty() && !skip_main_menu)
289 else if (cmd_args.exists("address"))
290 address = cmd_args.get("address");
292 playername = g_settings->get("name");
293 if (cmd_args.exists("name"))
294 playername = cmd_args.get("name");
296 list_video_modes = cmd_args.getFlag("videomodes");
298 use_freetype = g_settings->getBool("freetype");
300 random_input = g_settings->getBool("random_input")
301 || cmd_args.getFlag("random-input");
304 bool ClientLauncher::init_engine()
306 receiver = new MyEventReceiver();
307 new RenderingEngine(receiver);
308 return RenderingEngine::get_raw_device() != nullptr;
311 void ClientLauncher::init_input()
314 input = new RandomInputHandler();
316 input = new RealInputHandler(receiver);
318 if (g_settings->getBool("enable_joysticks")) {
319 irr::core::array<irr::SJoystickInfo> infos;
320 std::vector<irr::SJoystickInfo> joystick_infos;
322 // Make sure this is called maximum once per
323 // irrlicht device, otherwise it will give you
324 // multiple events for the same joystick.
325 if (RenderingEngine::get_raw_device()->activateJoysticks(infos)) {
326 infostream << "Joystick support enabled" << std::endl;
327 joystick_infos.reserve(infos.size());
328 for (u32 i = 0; i < infos.size(); i++) {
329 joystick_infos.push_back(infos[i]);
331 input->joystick.onJoystickConnect(joystick_infos);
333 errorstream << "Could not activate joystick support." << std::endl;
338 bool ClientLauncher::launch_game(std::string &error_message,
339 bool reconnect_requested, GameParams &game_params,
340 const Settings &cmd_args)
342 // Initialize menu data
343 MainMenuData menudata;
344 menudata.address = address;
345 menudata.name = playername;
346 menudata.password = password;
347 menudata.port = itos(game_params.socket_port);
348 menudata.script_data.errormessage = error_message;
349 menudata.script_data.reconnect_requested = reconnect_requested;
351 error_message.clear();
353 if (cmd_args.exists("password"))
354 menudata.password = cmd_args.get("password");
356 // If a world was commanded, append and select it
357 if (!game_params.world_path.empty()) {
358 worldspec.gameid = getWorldGameId(game_params.world_path, true);
359 worldspec.name = _("[--world parameter]");
361 if (worldspec.gameid.empty()) { // Create new
362 worldspec.gameid = g_settings->get("default_game");
363 worldspec.name += " [new]";
365 worldspec.path = game_params.world_path;
370 if (!skip_main_menu) {
371 main_menu(&menudata);
373 // Skip further loading if there was an exit signal.
374 if (*porting::signal_handler_killstatus())
377 address = menudata.address;
378 int newport = stoi(menudata.port);
380 game_params.socket_port = newport;
382 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
384 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
386 if (menudata.selected_world >= 0
387 && menudata.selected_world < (int)worldspecs.size()) {
388 g_settings->set("selected_world_path",
389 worldspecs[menudata.selected_world].path);
390 worldspec = worldspecs[menudata.selected_world];
394 if (!menudata.script_data.errormessage.empty()) {
395 /* The calling function will pass this back into this function upon the
396 * next iteration (if any) causing it to be displayed by the GUI
398 error_message = menudata.script_data.errormessage;
402 if (menudata.name.empty() && !simple_singleplayer_mode) {
403 error_message = gettext("Please choose a name!");
404 errorstream << error_message << std::endl;
408 playername = menudata.name;
409 password = menudata.password;
411 current_playername = playername;
412 current_password = password;
413 current_address = address;
414 current_port = game_params.socket_port;
416 // If using simple singleplayer mode, override
417 if (simple_singleplayer_mode) {
418 assert(!skip_main_menu);
419 current_playername = "singleplayer";
420 current_password = "";
421 current_address = "";
422 current_port = myrand_range(49152, 65535);
424 g_settings->set("name", playername);
425 if (!address.empty()) {
426 ServerListSpec server;
427 server["name"] = menudata.servername;
428 server["address"] = menudata.address;
429 server["port"] = menudata.port;
430 server["description"] = menudata.serverdescription;
431 ServerList::insert(server);
435 infostream << "Selected world: " << worldspec.name
436 << " [" << worldspec.path << "]" << std::endl;
438 if (current_address.empty()) { // If local game
439 if (worldspec.path.empty()) {
440 error_message = gettext("No world selected and no address "
441 "provided. Nothing to do.");
442 errorstream << error_message << std::endl;
446 if (!fs::PathExists(worldspec.path)) {
447 error_message = gettext("Provided world path doesn't exist: ")
449 errorstream << error_message << std::endl;
453 // Load gamespec for required game
454 gamespec = findWorldSubgame(worldspec.path);
455 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
456 error_message = gettext("Could not find or load game \"")
457 + worldspec.gameid + "\"";
458 errorstream << error_message << std::endl;
462 if (porting::signal_handler_killstatus())
465 if (game_params.game_spec.isValid() &&
466 game_params.game_spec.id != worldspec.gameid) {
467 warningstream << "Overriding gamespec from \""
468 << worldspec.gameid << "\" to \""
469 << game_params.game_spec.id << "\"" << std::endl;
470 gamespec = game_params.game_spec;
473 if (!gamespec.isValid()) {
474 error_message = gettext("Invalid gamespec.");
475 error_message += " (world.gameid=" + worldspec.gameid + ")";
476 errorstream << error_message << std::endl;
484 void ClientLauncher::main_menu(MainMenuData *menudata)
486 bool *kill = porting::signal_handler_killstatus();
487 video::IVideoDriver *driver = RenderingEngine::get_video_driver();
489 infostream << "Waiting for other menus" << std::endl;
490 while (RenderingEngine::get_raw_device()->run() && !*kill) {
493 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
494 RenderingEngine::get_gui_env()->drawAll();
496 // On some computers framerate doesn't seem to be automatically limited
499 infostream << "Waited for other menus" << std::endl;
501 // Cursor can be non-visible when coming from the game
503 RenderingEngine::get_raw_device()->getCursorControl()->setVisible(true);
507 GUIEngine mymenu(&input->joystick, guiroot, &g_menumgr, menudata, *kill);
509 /* leave scene manager in a clean state */
510 RenderingEngine::get_scene_manager()->clear();
513 void ClientLauncher::speed_tests()
515 // volatile to avoid some potential compiler optimisations
516 volatile static s16 temp16;
517 volatile static f32 tempf;
520 static std::string tempstring;
521 static std::string tempstring2;
529 infostream << "The following test should take around 20ms." << std::endl;
530 TimeTaker timer("Testing std::string speed");
531 const u32 jj = 10000;
532 for (u32 j = 0; j < jj; j++) {
536 for (u32 i = 0; i < ii; i++) {
537 tempstring2 += "asd";
539 for (u32 i = 0; i < ii+1; i++) {
541 if (tempstring == tempstring2)
547 infostream << "All of the following tests should take around 100ms each."
551 TimeTaker timer("Testing floating-point conversion speed");
553 for (u32 i = 0; i < 4000000; i++) {
560 TimeTaker timer("Testing floating-point vector speed");
562 tempv3f1 = v3f(1, 2, 3);
563 tempv3f2 = v3f(4, 5, 6);
564 for (u32 i = 0; i < 10000000; i++) {
565 tempf += tempv3f1.dotProduct(tempv3f2);
566 tempv3f2 += v3f(7, 8, 9);
571 TimeTaker timer("Testing std::map speed");
573 std::map<v2s16, f32> map1;
576 for (s16 y = 0; y < ii; y++) {
577 for (s16 x = 0; x < ii; x++) {
578 map1[v2s16(x, y)] = tempf;
582 for (s16 y = ii - 1; y >= 0; y--) {
583 for (s16 x = 0; x < ii; x++) {
584 tempf = map1[v2s16(x, y)];
590 infostream << "Around 5000/ms should do well here." << std::endl;
591 TimeTaker timer("Testing mutex speed");
604 while(timer.getTimerTime() < 10);
606 u32 dtime = timer.stop();
607 u32 per_ms = n / dtime;
608 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;