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.
21 #include "mainmenumanager.h"
26 #include "guiMainMenu.h"
32 #include "serverlist.h"
33 #include "guiEngine.h"
35 #include "fontengine.h"
36 #include "clientlauncher.h"
38 // A pointer to a global instance of the time getter
40 TimeGetter *g_timegetter = NULL;
44 if (g_timegetter == NULL)
46 return g_timegetter->getTime(PRECISION_MILLI);
49 u32 getTime(TimePrecision prec) {
50 if (g_timegetter == NULL)
52 return g_timegetter->getTime(prec);
55 ClientLauncher::~ClientLauncher()
71 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
73 init_args(game_params, cmd_args);
75 // List video modes if requested
77 return print_video_modes();
79 if (!init_engine(game_params.log_level)) {
80 errorstream << "Could not initialize game engine." << std::endl;
84 // Speed tests (done after irrlicht is loaded to get timer)
85 if (cmd_args.getFlag("speedtests")) {
86 dstream << "Running speed tests" << std::endl;
91 video::IVideoDriver *video_driver = device->getVideoDriver();
92 if (video_driver == NULL) {
93 errorstream << "Could not initialize video driver." << std::endl;
97 porting::setXorgClassHint(video_driver->getExposedVideoData(), "Minetest");
100 This changes the minimum allowed number of vertices in a VBO.
103 //driver->setMinHardwareBufferVertexCount(50);
105 // Create time getter
106 g_timegetter = new IrrlichtTimeGetter(device);
108 // Create game callback for menus
109 g_gamecallback = new MainGameCallback(device);
111 device->setResizable(true);
114 input = new RandomInputHandler();
116 input = new RealInputHandler(device, receiver);
118 smgr = device->getSceneManager();
119 smgr->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
121 guienv = device->getGUIEnvironment();
122 skin = guienv->getSkin();
123 skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
124 skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
125 skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
126 skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
127 skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
128 skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
130 g_fontengine = new FontEngine(g_settings, guienv);
131 assert(g_fontengine != NULL);
133 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
134 // Irrlicht 1.8 input colours
135 skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
136 skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
139 // Create the menu clouds
140 if (!g_menucloudsmgr)
141 g_menucloudsmgr = smgr->createNewSceneManager();
143 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
144 g_menucloudsmgr, -1, rand(), 100);
145 g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
146 scene::ICameraSceneNode* camera;
147 camera = g_menucloudsmgr->addCameraSceneNode(0,
148 v3f(0, 0, 0), v3f(0, 60, 100));
149 camera->setFarValue(10000);
155 ChatBackend chat_backend;
157 // If an error occurs, this is set to something by menu().
158 // It is then displayed before the menu shows on the next call to menu()
159 std::wstring error_message = L"";
161 bool first_loop = true;
167 bool *kill = porting::signal_handler_killstatus();
169 while (device->run() && !*kill && !g_gamecallback->shutdown_requested)
171 // Set the window caption
172 const wchar_t *text = wgettext("Main Menu");
173 device->setWindowCaption((std::wstring(L"Minetest [") + text + L"]").c_str());
176 try { // This is used for catching disconnects
181 We need some kind of a root node to be able to add
182 custom gui elements directly on the screen.
183 Otherwise they won't be automatically drawn.
185 guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
187 bool game_has_run = launch_game(&error_message, game_params, cmd_args);
189 // If skip_main_menu, we only want to startup once
190 if (skip_main_menu && !first_loop)
202 // Break out of menu-game loop to shut down cleanly
203 if (!device->run() || *kill) {
204 if (g_settings_path != "")
205 g_settings->updateConfigFile(g_settings_path.c_str());
209 if (current_playername.length() > PLAYERNAME_SIZE-1) {
210 error_message = wgettext("Player name too long.");
211 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
212 g_settings->set("name", playername);
216 device->getVideoDriver()->setTextureCreationFlag(
217 video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
219 #ifdef HAVE_TOUCHSCREENGUI
220 receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
221 g_touchscreengui = receiver->m_touchscreengui;
236 simple_singleplayer_mode
240 #ifdef HAVE_TOUCHSCREENGUI
241 delete g_touchscreengui;
242 g_touchscreengui = NULL;
243 receiver->m_touchscreengui = NULL;
247 catch (con::PeerNotFoundException &e) {
248 error_message = wgettext("Connection error (timed out?)");
249 errorstream << wide_to_narrow(error_message) << std::endl;
253 catch (std::exception &e) {
254 std::string narrow_message = "Some exception: \"";
255 narrow_message += e.what();
256 narrow_message += "\"";
257 errorstream << narrow_message << std::endl;
258 error_message = narrow_to_wide(narrow_message);
262 // If no main menu, show error and exit
263 if (skip_main_menu) {
264 if (error_message != L"") {
265 verbosestream << "error_message = "
266 << wide_to_narrow(error_message) << std::endl;
273 g_menuclouds->drop();
274 g_menucloudsmgr->drop();
279 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
282 skip_main_menu = cmd_args.getFlag("go");
284 // FIXME: This is confusing (but correct)
286 /* If world_path is set then override it unless skipping the main menu using
287 * the --go command line param. Else, give preference to the address
288 * supplied on the command line
290 address = g_settings->get("address");
291 if (game_params.world_path != "" && !skip_main_menu)
293 else if (cmd_args.exists("address"))
294 address = cmd_args.get("address");
296 playername = g_settings->get("name");
297 if (cmd_args.exists("name"))
298 playername = cmd_args.get("name");
300 list_video_modes = cmd_args.getFlag("videomodes");
302 use_freetype = g_settings->getBool("freetype");
304 random_input = g_settings->getBool("random_input")
305 || cmd_args.getFlag("random-input");
308 bool ClientLauncher::init_engine(int log_level)
310 receiver = new MyEventReceiver();
311 create_engine_device(log_level);
312 return device != NULL;
315 bool ClientLauncher::launch_game(std::wstring *error_message,
316 GameParams &game_params, const Settings &cmd_args)
318 // Initialize menu data
319 MainMenuData menudata;
320 menudata.address = address;
321 menudata.name = playername;
322 menudata.port = itos(game_params.socket_port);
323 menudata.errormessage = wide_to_narrow(*error_message);
325 *error_message = L"";
327 if (cmd_args.exists("password"))
328 menudata.password = cmd_args.get("password");
330 menudata.enable_public = g_settings->getBool("server_announce");
332 // If a world was commanded, append and select it
333 if (game_params.world_path != "") {
334 worldspec.gameid = getWorldGameId(game_params.world_path, true);
335 worldspec.name = _("[--world parameter]");
337 if (worldspec.gameid == "") { // Create new
338 worldspec.gameid = g_settings->get("default_game");
339 worldspec.name += " [new]";
341 worldspec.path = game_params.world_path;
346 if (!skip_main_menu) {
347 main_menu(&menudata);
349 // Skip further loading if there was an exit signal.
350 if (*porting::signal_handler_killstatus())
353 address = menudata.address;
354 int newport = stoi(menudata.port);
356 game_params.socket_port = newport;
358 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
360 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
362 if (menudata.selected_world >= 0
363 && menudata.selected_world < (int)worldspecs.size()) {
364 g_settings->set("selected_world_path",
365 worldspecs[menudata.selected_world].path);
366 worldspec = worldspecs[menudata.selected_world];
370 if (menudata.errormessage != "") {
371 /* The calling function will pass this back into this function upon the
372 * next iteration (if any) causing it to be displayed by the GUI
374 *error_message = narrow_to_wide(menudata.errormessage);
378 if (menudata.name == "")
379 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
381 playername = menudata.name;
383 password = translatePassword(playername, narrow_to_wide(menudata.password));
385 g_settings->set("name", playername);
387 current_playername = playername;
388 current_password = password;
389 current_address = address;
390 current_port = game_params.socket_port;
392 // If using simple singleplayer mode, override
393 if (simple_singleplayer_mode) {
394 assert(skip_main_menu == false);
395 current_playername = "singleplayer";
396 current_password = "";
397 current_address = "";
398 current_port = myrand_range(49152, 65535);
399 } else if (address != "") {
400 ServerListSpec server;
401 server["name"] = menudata.servername;
402 server["address"] = menudata.address;
403 server["port"] = menudata.port;
404 server["description"] = menudata.serverdescription;
405 ServerList::insert(server);
408 infostream << "Selected world: " << worldspec.name
409 << " [" << worldspec.path << "]" << std::endl;
411 if (current_address == "") { // If local game
412 if (worldspec.path == "") {
413 *error_message = wgettext("No world selected and no address "
414 "provided. Nothing to do.");
415 errorstream << wide_to_narrow(*error_message) << std::endl;
419 if (!fs::PathExists(worldspec.path)) {
420 *error_message = wgettext("Provided world path doesn't exist: ")
421 + narrow_to_wide(worldspec.path);
422 errorstream << wide_to_narrow(*error_message) << std::endl;
426 // Load gamespec for required game
427 gamespec = findWorldSubgame(worldspec.path);
428 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
429 *error_message = wgettext("Could not find or load game \"")
430 + narrow_to_wide(worldspec.gameid) + L"\"";
431 errorstream << wide_to_narrow(*error_message) << std::endl;
435 if (porting::signal_handler_killstatus())
438 if (game_params.game_spec.isValid() &&
439 game_params.game_spec.id != worldspec.gameid) {
440 errorstream << "WARNING: Overriding gamespec from \""
441 << worldspec.gameid << "\" to \""
442 << game_params.game_spec.id << "\"" << std::endl;
443 gamespec = game_params.game_spec;
446 if (!gamespec.isValid()) {
447 *error_message = wgettext("Invalid gamespec.");
448 *error_message += L" (world_gameid="
449 + narrow_to_wide(worldspec.gameid) + L")";
450 errorstream << wide_to_narrow(*error_message) << std::endl;
458 void ClientLauncher::main_menu(MainMenuData *menudata)
460 bool *kill = porting::signal_handler_killstatus();
461 video::IVideoDriver *driver = device->getVideoDriver();
463 infostream << "Waiting for other menus" << std::endl;
464 while (device->run() && *kill == false) {
467 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
470 // On some computers framerate doesn't seem to be automatically limited
473 infostream << "Waited for other menus" << std::endl;
475 // Cursor can be non-visible when coming from the game
477 device->getCursorControl()->setVisible(true);
481 GUIEngine mymenu(device, guiroot, &g_menumgr, smgr, menudata, *kill);
483 smgr->clear(); /* leave scene manager in a clean state */
486 bool ClientLauncher::create_engine_device(int log_level)
488 static const irr::ELOG_LEVEL irr_log_level[5] = {
493 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
500 // Resolution selection
501 bool fullscreen = g_settings->getBool("fullscreen");
502 u16 screenW = g_settings->getU16("screenW");
503 u16 screenH = g_settings->getU16("screenH");
506 bool vsync = g_settings->getBool("vsync");
507 u16 bits = g_settings->getU16("fullscreen_bpp");
508 u16 fsaa = g_settings->getU16("fsaa");
511 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
512 std::string driverstring = g_settings->get("video_driver");
513 std::vector<video::E_DRIVER_TYPE> drivers
514 = porting::getSupportedVideoDrivers();
516 for (i = 0; i != drivers.size(); i++) {
517 if (!strcasecmp(driverstring.c_str(),
518 porting::getVideoDriverName(drivers[i]))) {
519 driverType = drivers[i];
523 if (i == drivers.size()) {
524 errorstream << "Invalid video_driver specified; "
525 "defaulting to opengl" << std::endl;
528 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
529 params.DriverType = driverType;
530 params.WindowSize = core::dimension2d<u32>(screenW, screenH);
532 params.AntiAlias = fsaa;
533 params.Fullscreen = fullscreen;
534 params.Stencilbuffer = false;
535 params.Vsync = vsync;
536 params.EventReceiver = receiver;
537 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
539 params.PrivateData = porting::app_global;
540 params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
541 "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
544 device = createDeviceEx(params);
547 // Map our log level to irrlicht engine one.
548 ILogger* irr_logger = device->getLogger();
549 irr_logger->setLogLevel(irr_log_level[log_level]);
551 porting::initIrrlicht(device);
554 return device != NULL;
557 void ClientLauncher::speed_tests()
559 // volatile to avoid some potential compiler optimisations
560 volatile static s16 temp16;
561 volatile static f32 tempf;
564 static std::string tempstring;
565 static std::string tempstring2;
569 tempstring = std::string();
570 tempstring2 = std::string();
573 infostream << "The following test should take around 20ms." << std::endl;
574 TimeTaker timer("Testing std::string speed");
575 const u32 jj = 10000;
576 for (u32 j = 0; j < jj; j++) {
580 for (u32 i = 0; i < ii; i++) {
581 tempstring2 += "asd";
583 for (u32 i = 0; i < ii+1; i++) {
585 if (tempstring == tempstring2)
591 infostream << "All of the following tests should take around 100ms each."
595 TimeTaker timer("Testing floating-point conversion speed");
597 for (u32 i = 0; i < 4000000; i++) {
604 TimeTaker timer("Testing floating-point vector speed");
606 tempv3f1 = v3f(1, 2, 3);
607 tempv3f2 = v3f(4, 5, 6);
608 for (u32 i = 0; i < 10000000; i++) {
609 tempf += tempv3f1.dotProduct(tempv3f2);
610 tempv3f2 += v3f(7, 8, 9);
615 TimeTaker timer("Testing std::map speed");
617 std::map<v2s16, f32> map1;
620 for (s16 y = 0; y < ii; y++) {
621 for (s16 x = 0; x < ii; x++) {
622 map1[v2s16(x, y)] = tempf;
626 for (s16 y = ii - 1; y >= 0; y--) {
627 for (s16 x = 0; x < ii; x++) {
628 tempf = map1[v2s16(x, y)];
634 infostream << "Around 5000/ms should do well here." << std::endl;
635 TimeTaker timer("Testing mutex speed");
648 while(timer.getTimerTime() < 10);
650 u32 dtime = timer.stop();
651 u32 per_ms = n / dtime;
652 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
656 bool ClientLauncher::print_video_modes()
658 IrrlichtDevice *nulldevice;
660 bool vsync = g_settings->getBool("vsync");
661 u16 fsaa = g_settings->getU16("fsaa");
662 MyEventReceiver* receiver = new MyEventReceiver();
664 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
665 params.DriverType = video::EDT_NULL;
666 params.WindowSize = core::dimension2d<u32>(640, 480);
668 params.AntiAlias = fsaa;
669 params.Fullscreen = false;
670 params.Stencilbuffer = false;
671 params.Vsync = vsync;
672 params.EventReceiver = receiver;
673 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
675 nulldevice = createDeviceEx(params);
677 if (nulldevice == NULL) {
682 dstream << _("Available video modes (WxHxD):") << std::endl;
684 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
686 if (videomode_list != NULL) {
687 s32 videomode_count = videomode_list->getVideoModeCount();
688 core::dimension2d<u32> videomode_res;
690 for (s32 i = 0; i < videomode_count; ++i) {
691 videomode_res = videomode_list->getVideoModeResolution(i);
692 videomode_depth = videomode_list->getVideoModeDepth(i);
693 dstream << videomode_res.Width << "x" << videomode_res.Height
694 << "x" << videomode_depth << std::endl;
697 dstream << _("Active video mode (WxHxD):") << std::endl;
698 videomode_res = videomode_list->getDesktopResolution();
699 videomode_depth = videomode_list->getDesktopDepth();
700 dstream << videomode_res.Width << "x" << videomode_res.Height
701 << "x" << videomode_depth << std::endl;
708 return videomode_list != NULL;