]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client/clientlauncher.cpp
Make Lint Happy
[dragonfireclient.git] / src / client / clientlauncher.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include "gui/mainmenumanager.h"
21 #include "clouds.h"
22 #include "server.h"
23 #include "filesys.h"
24 #include "gui/guiMainMenu.h"
25 #include "game.h"
26 #include "player.h"
27 #include "chat.h"
28 #include "gettext.h"
29 #include "profiler.h"
30 #include "serverlist.h"
31 #include "gui/guiEngine.h"
32 #include "fontengine.h"
33 #include "clientlauncher.h"
34 #include "version.h"
35 #include "renderingengine.h"
36 #include "network/networkexceptions.h"
37
38 #if USE_SOUND
39 #include "sound_openal.h"
40 #endif
41 #ifdef __ANDROID__
42 #include "porting.h"
43 #endif
44
45 /* mainmenumanager.h
46  */
47 gui::IGUIEnvironment *guienv = nullptr;
48 gui::IGUIStaticText *guiroot = nullptr;
49 MainMenuManager g_menumgr;
50
51 bool isMenuActive()
52 {
53         return g_menumgr.menuCount() != 0;
54 }
55
56 // Passed to menus to allow disconnecting and exiting
57 MainGameCallback *g_gamecallback = nullptr;
58
59 #if 0
60 // This can be helpful for the next code cleanup
61 static void dump_start_data(const GameStartData &data)
62 {
63         std::cout <<
64                 "\ndedicated   " << (int)data.is_dedicated_server <<
65                 "\nport        " << data.socket_port <<
66                 "\nworld_path  " << data.world_spec.path <<
67                 "\nworld game  " << data.world_spec.gameid <<
68                 "\ngame path   " << data.game_spec.path <<
69                 "\nplayer name " << data.name <<
70                 "\naddress     " << data.address << std::endl;
71 }
72 #endif
73
74 ClientLauncher::~ClientLauncher()
75 {
76         delete receiver;
77
78         delete input;
79
80         delete g_fontengine;
81         delete g_gamecallback;
82
83         delete RenderingEngine::get_instance();
84
85 #if USE_SOUND
86         g_sound_manager_singleton.reset();
87 #endif
88 }
89
90 bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args)
91 {
92         /* This function is called when a client must be started.
93          * Covered cases:
94          *   - Singleplayer (address but map provided)
95          *   - Join server (no map but address provided)
96          *   - Local server (for main menu only)
97          */
98
99         init_args(start_data, cmd_args);
100
101         // List video modes if requested
102         if (list_video_modes)
103                 return RenderingEngine::print_video_modes();
104
105 #if USE_SOUND
106         if (g_settings->getBool("enable_sound"))
107                 g_sound_manager_singleton = createSoundManagerSingleton();
108 #endif
109
110         if (!init_engine()) {
111                 errorstream << "Could not initialize game engine." << std::endl;
112                 return false;
113         }
114
115         // Speed tests (done after irrlicht is loaded to get timer)
116         if (cmd_args.getFlag("speedtests")) {
117                 dstream << "Running speed tests" << std::endl;
118                 speed_tests();
119                 return true;
120         }
121
122         if (RenderingEngine::get_video_driver() == NULL) {
123                 errorstream << "Could not initialize video driver." << std::endl;
124                 return false;
125         }
126
127         RenderingEngine::get_instance()->setupTopLevelWindow(PROJECT_NAME_C);
128
129         /*
130                 This changes the minimum allowed number of vertices in a VBO.
131                 Default is 500.
132         */
133         // driver->setMinHardwareBufferVertexCount(50);
134
135         // Create game callback for menus
136         g_gamecallback = new MainGameCallback();
137
138         RenderingEngine::get_instance()->setResizable(true);
139
140         init_input();
141
142         RenderingEngine::get_scene_manager()->getParameters()->setAttribute(
143                         scene::ALLOW_ZWRITE_ON_TRANSPARENT, true);
144
145         guienv = RenderingEngine::get_gui_env();
146         skin = RenderingEngine::get_gui_env()->getSkin();
147         skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255));
148         skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0));
149         skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30));
150         skin->setColor(gui::EGDC_3D_SHADOW, video::SColor(255, 0, 0, 0));
151         skin->setColor(gui::EGDC_HIGH_LIGHT, video::SColor(255, 70, 120, 50));
152         skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
153 #ifdef __ANDROID__
154         float density = porting::getDisplayDensity();
155         skin->setSize(gui::EGDS_CHECK_BOX_WIDTH, (s32)(17.0f * density));
156         skin->setSize(gui::EGDS_SCROLLBAR_SIZE, (s32)(14.0f * density));
157         skin->setSize(gui::EGDS_WINDOW_BUTTON_WIDTH, (s32)(15.0f * density));
158         if (density > 1.5f) {
159                 std::string sprite_path = porting::path_user + "/textures/base/pack/";
160                 if (density > 3.5f)
161                         sprite_path.append("checkbox_64.png");
162                 else if (density > 2.0f)
163                         sprite_path.append("checkbox_32.png");
164                 else
165                         sprite_path.append("checkbox_16.png");
166                 // Texture dimensions should be a power of 2
167                 gui::IGUISpriteBank *sprites = skin->getSpriteBank();
168                 video::IVideoDriver *driver = RenderingEngine::get_video_driver();
169                 video::ITexture *sprite_texture = driver->getTexture(sprite_path.c_str());
170                 if (sprite_texture) {
171                         s32 sprite_id = sprites->addTextureAsSprite(sprite_texture);
172                         if (sprite_id != -1)
173                                 skin->setIcon(gui::EGDI_CHECK_BOX_CHECKED, sprite_id);
174                 }
175         }
176 #endif
177         g_fontengine = new FontEngine(g_settings, guienv);
178         FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
179
180 #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) ||                      \
181                 IRRLICHT_VERSION_MAJOR >= 2
182         // Irrlicht 1.8 input colours
183         skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128));
184         skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49));
185 #endif
186
187         // Create the menu clouds
188         if (!g_menucloudsmgr)
189                 g_menucloudsmgr = RenderingEngine::get_scene_manager()
190                                                   ->createNewSceneManager();
191         if (!g_menuclouds)
192                 g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand());
193         g_menuclouds->setHeight(100.0f);
194         g_menuclouds->update(v3f(0, 0, 0), video::SColor(255, 240, 240, 255));
195         scene::ICameraSceneNode *camera;
196         camera = g_menucloudsmgr->addCameraSceneNode(NULL, v3f(0, 0, 0), v3f(0, 60, 100));
197         camera->setFarValue(10000);
198
199         /*
200                 GUI stuff
201         */
202
203         ChatBackend chat_backend;
204
205         // If an error occurs, this is set to something by menu().
206         // It is then displayed before the menu shows on the next call to menu()
207         std::string error_message;
208         bool reconnect_requested = false;
209
210         bool first_loop = true;
211
212         /*
213                 Menu-game loop
214         */
215         bool retval = true;
216         bool *kill = porting::signal_handler_killstatus();
217
218         while (RenderingEngine::run() && !*kill && !g_gamecallback->shutdown_requested) {
219                 // Set the window caption
220                 const wchar_t *text = wgettext("Main Menu");
221                 RenderingEngine::get_raw_device()->setWindowCaption(
222                                 (utf8_to_wide(PROJECT_NAME_C) + L" " +
223                                                 utf8_to_wide(g_version_hash) + L" [" +
224                                                 text + L"]")
225                                                 .c_str());
226                 delete[] text;
227
228                 try { // This is used for catching disconnects
229
230                         RenderingEngine::get_gui_env()->clear();
231
232                         /*
233                                 We need some kind of a root node to be able to add
234                                 custom gui elements directly on the screen.
235                                 Otherwise they won't be automatically drawn.
236                         */
237                         guiroot = RenderingEngine::get_gui_env()->addStaticText(
238                                         L"", core::rect<s32>(0, 0, 10000, 10000));
239
240                         bool game_has_run = launch_game(error_message,
241                                         reconnect_requested, start_data, cmd_args);
242
243                         // Reset the reconnect_requested flag
244                         reconnect_requested = false;
245
246                         // If skip_main_menu, we only want to startup once
247                         if (skip_main_menu && !first_loop)
248                                 break;
249
250                         first_loop = false;
251
252                         if (!game_has_run) {
253                                 if (skip_main_menu)
254                                         break;
255
256                                 continue;
257                         }
258
259                         // Break out of menu-game loop to shut down cleanly
260                         if (!RenderingEngine::get_raw_device()->run() || *kill) {
261                                 if (!g_settings_path.empty())
262                                         g_settings->updateConfigFile(
263                                                         g_settings_path.c_str());
264                                 break;
265                         }
266
267                         RenderingEngine::get_video_driver()->setTextureCreationFlag(
268                                         video::ETCF_CREATE_MIP_MAPS,
269                                         g_settings->getBool("mip_map"));
270
271 #ifdef HAVE_TOUCHSCREENGUI
272                         receiver->m_touchscreengui = new TouchScreenGUI(
273                                         RenderingEngine::get_raw_device(), receiver);
274                         g_touchscreengui = receiver->m_touchscreengui;
275 #endif
276
277                         the_game(kill, input, start_data, error_message, chat_backend,
278                                         &reconnect_requested);
279                         RenderingEngine::get_scene_manager()->clear();
280
281 #ifdef HAVE_TOUCHSCREENGUI
282                         delete g_touchscreengui;
283                         g_touchscreengui = NULL;
284                         receiver->m_touchscreengui = NULL;
285 #endif
286
287                 } // try
288                 catch (con::PeerNotFoundException &e) {
289                         error_message = gettext("Connection error (timed out?)");
290                         errorstream << error_message << std::endl;
291                 }
292
293 #ifdef NDEBUG
294                 catch (std::exception &e) {
295                         std::string error_message = "Some exception: \"";
296                         error_message += e.what();
297                         error_message += "\"";
298                         errorstream << error_message << std::endl;
299                 }
300 #endif
301
302                 // If no main menu, show error and exit
303                 if (skip_main_menu) {
304                         if (!error_message.empty()) {
305                                 verbosestream << "error_message = " << error_message
306                                               << std::endl;
307                                 retval = false;
308                         }
309                         break;
310                 }
311         } // Menu-game loop
312
313         g_menuclouds->drop();
314         g_menucloudsmgr->drop();
315
316         return retval;
317 }
318
319 void ClientLauncher::init_args(GameStartData &start_data, const Settings &cmd_args)
320 {
321         skip_main_menu = cmd_args.getFlag("go");
322
323         start_data.address = g_settings->get("address");
324         if (cmd_args.exists("address")) {
325                 // Join a remote server
326                 start_data.address = cmd_args.get("address");
327                 start_data.world_path.clear();
328         }
329         if (!start_data.world_path.empty()) {
330                 // Start a singleplayer instance
331                 start_data.address = "";
332         }
333
334         start_data.name = g_settings->get("name");
335         if (cmd_args.exists("name"))
336                 start_data.name = cmd_args.get("name");
337
338         list_video_modes = cmd_args.getFlag("videomodes");
339
340         random_input = g_settings->getBool("random_input") ||
341                        cmd_args.getFlag("random-input");
342 }
343
344 bool ClientLauncher::init_engine()
345 {
346         receiver = new MyEventReceiver();
347         new RenderingEngine(receiver);
348         return RenderingEngine::get_raw_device() != nullptr;
349 }
350
351 void ClientLauncher::init_input()
352 {
353         if (random_input)
354                 input = new RandomInputHandler();
355         else
356                 input = new RealInputHandler(receiver);
357
358         if (g_settings->getBool("enable_joysticks")) {
359                 irr::core::array<irr::SJoystickInfo> infos;
360                 std::vector<irr::SJoystickInfo> joystick_infos;
361
362                 // Make sure this is called maximum once per
363                 // irrlicht device, otherwise it will give you
364                 // multiple events for the same joystick.
365                 if (RenderingEngine::get_raw_device()->activateJoysticks(infos)) {
366                         infostream << "Joystick support enabled" << std::endl;
367                         joystick_infos.reserve(infos.size());
368                         for (u32 i = 0; i < infos.size(); i++) {
369                                 joystick_infos.push_back(infos[i]);
370                         }
371                         input->joystick.onJoystickConnect(joystick_infos);
372                 } else {
373                         errorstream << "Could not activate joystick support."
374                                     << std::endl;
375                 }
376         }
377 }
378
379 bool ClientLauncher::launch_game(std::string &error_message, bool reconnect_requested,
380                 GameStartData &start_data, const Settings &cmd_args)
381 {
382         // Prepare and check the start data to launch a game
383         std::string error_message_lua = error_message;
384         error_message.clear();
385
386         if (cmd_args.exists("password"))
387                 start_data.password = cmd_args.get("password");
388
389         if (cmd_args.exists("password-file")) {
390                 std::ifstream passfile(cmd_args.get("password-file"));
391                 if (passfile.good()) {
392                         getline(passfile, start_data.password);
393                 } else {
394                         error_message = gettext("Provided password file "
395                                                 "failed to open: ") +
396                                         cmd_args.get("password-file");
397                         errorstream << error_message << std::endl;
398                         return false;
399                 }
400         }
401
402         // If a world was commanded, append and select it
403         // This is provieded by "get_world_from_cmdline()", main.cpp
404         if (!start_data.world_path.empty()) {
405                 auto &spec = start_data.world_spec;
406
407                 spec.path = start_data.world_path;
408                 spec.gameid = getWorldGameId(spec.path, true);
409                 spec.name = _("[--world parameter]");
410
411                 if (spec.gameid.empty()) { // Create new
412                         spec.gameid = g_settings->get("default_game");
413                         spec.name += " [new]";
414                 }
415         }
416
417         /* Show the GUI menu
418          */
419         std::string server_name, server_description;
420         start_data.local_server = false;
421         if (!skip_main_menu) {
422                 // Initialize menu data
423                 // TODO: Re-use existing structs (GameStartData)
424                 MainMenuData menudata;
425                 menudata.address = start_data.address;
426                 menudata.name = start_data.name;
427                 menudata.password = start_data.password;
428                 menudata.port = itos(start_data.socket_port);
429                 menudata.script_data.errormessage = error_message_lua;
430                 menudata.script_data.reconnect_requested = reconnect_requested;
431
432                 main_menu(&menudata);
433
434                 // Skip further loading if there was an exit signal.
435                 if (*porting::signal_handler_killstatus())
436                         return false;
437
438                 if (!menudata.script_data.errormessage.empty()) {
439                         /* The calling function will pass this back into this function
440                          * upon the next iteration (if any) causing it to be displayed by
441                          * the GUI
442                          */
443                         error_message = menudata.script_data.errormessage;
444                         return false;
445                 }
446
447                 int newport = stoi(menudata.port);
448                 if (newport != 0)
449                         start_data.socket_port = newport;
450
451                 // Update world information using main menu data
452                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
453
454                 int world_index = menudata.selected_world;
455                 if (world_index >= 0 && world_index < (int)worldspecs.size()) {
456                         g_settings->set("selected_world_path",
457                                         worldspecs[world_index].path);
458                         start_data.world_spec = worldspecs[world_index];
459                 }
460
461                 start_data.name = menudata.name;
462                 start_data.password = menudata.password;
463                 start_data.address = std::move(menudata.address);
464                 server_name = menudata.servername;
465                 server_description = menudata.serverdescription;
466
467                 start_data.local_server = !menudata.simple_singleplayer_mode &&
468                                           start_data.address.empty();
469         }
470
471         if (!RenderingEngine::run())
472                 return false;
473
474         if (!start_data.isSinglePlayer() && start_data.name.empty()) {
475                 error_message = gettext("Please choose a name!");
476                 errorstream << error_message << std::endl;
477                 return false;
478         }
479
480         // If using simple singleplayer mode, override
481         if (start_data.isSinglePlayer()) {
482                 start_data.name = "singleplayer";
483                 start_data.password = "";
484                 start_data.socket_port = myrand_range(49152, 65535);
485         } else {
486                 g_settings->set("name", start_data.name);
487                 if (!start_data.address.empty()) {
488                         ServerListSpec server;
489                         server["name"] = server_name;
490                         server["address"] = start_data.address;
491                         server["port"] = itos(start_data.socket_port);
492                         server["description"] = server_description;
493                         ServerList::insert(server);
494                 }
495         }
496
497         if (start_data.name.length() > PLAYERNAME_SIZE - 1) {
498                 error_message = gettext("Player name too long.");
499                 start_data.name.resize(PLAYERNAME_SIZE);
500                 g_settings->set("name", start_data.name);
501                 return false;
502         }
503
504         auto &worldspec = start_data.world_spec;
505         infostream << "Selected world: " << worldspec.name << " [" << worldspec.path
506                    << "]" << std::endl;
507
508         if (start_data.address.empty()) {
509                 // For singleplayer and local server
510                 if (worldspec.path.empty()) {
511                         error_message = gettext("No world selected and no address "
512                                                 "provided. Nothing to do.");
513                         errorstream << error_message << std::endl;
514                         return false;
515                 }
516
517                 if (!fs::PathExists(worldspec.path)) {
518                         error_message = gettext("Provided world path doesn't exist: ") +
519                                         worldspec.path;
520                         errorstream << error_message << std::endl;
521                         return false;
522                 }
523
524                 // Load gamespec for required game
525                 start_data.game_spec = findWorldSubgame(worldspec.path);
526                 if (!start_data.game_spec.isValid()) {
527                         error_message = gettext("Could not find or load game \"") +
528                                         worldspec.gameid + "\"";
529                         errorstream << error_message << std::endl;
530                         return false;
531                 }
532
533                 if (porting::signal_handler_killstatus())
534                         return true;
535
536                 if (!start_data.game_spec.isValid()) {
537                         error_message = gettext("Invalid gamespec.");
538                         error_message += " (world.gameid=" + worldspec.gameid + ")";
539                         errorstream << error_message << std::endl;
540                         return false;
541                 }
542         }
543
544         start_data.world_path = start_data.world_spec.path;
545         return true;
546 }
547
548 void ClientLauncher::main_menu(MainMenuData *menudata)
549 {
550         bool *kill = porting::signal_handler_killstatus();
551         video::IVideoDriver *driver = RenderingEngine::get_video_driver();
552
553         infostream << "Waiting for other menus" << std::endl;
554         while (RenderingEngine::get_raw_device()->run() && !*kill) {
555                 if (!isMenuActive())
556                         break;
557                 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
558                 RenderingEngine::get_gui_env()->drawAll();
559                 driver->endScene();
560                 // On some computers framerate doesn't seem to be automatically limited
561                 sleep_ms(25);
562         }
563         infostream << "Waited for other menus" << std::endl;
564
565         // Cursor can be non-visible when coming from the game
566 #ifndef ANDROID
567         RenderingEngine::get_raw_device()->getCursorControl()->setVisible(true);
568 #endif
569
570         /* show main menu */
571         GUIEngine mymenu(&input->joystick, guiroot, &g_menumgr, menudata, *kill);
572
573         /* leave scene manager in a clean state */
574         RenderingEngine::get_scene_manager()->clear();
575 }
576
577 void ClientLauncher::speed_tests()
578 {
579         // volatile to avoid some potential compiler optimisations
580         volatile static s16 temp16;
581         volatile static f32 tempf;
582         static v3f tempv3f1;
583         static v3f tempv3f2;
584         static std::string tempstring;
585         static std::string tempstring2;
586
587         tempv3f1 = v3f();
588         tempv3f2 = v3f();
589         tempstring.clear();
590         tempstring2.clear();
591
592         {
593                 infostream << "The following test should take around 20ms." << std::endl;
594                 TimeTaker timer("Testing std::string speed");
595                 const u32 jj = 10000;
596                 for (u32 j = 0; j < jj; j++) {
597                         tempstring = "";
598                         tempstring2 = "";
599                         const u32 ii = 10;
600                         for (u32 i = 0; i < ii; i++) {
601                                 tempstring2 += "asd";
602                         }
603                         for (u32 i = 0; i < ii + 1; i++) {
604                                 tempstring += "asd";
605                                 if (tempstring == tempstring2)
606                                         break;
607                         }
608                 }
609         }
610
611         infostream << "All of the following tests should take around 100ms each."
612                    << std::endl;
613
614         {
615                 TimeTaker timer("Testing floating-point conversion speed");
616                 tempf = 0.001;
617                 for (u32 i = 0; i < 4000000; i++) {
618                         temp16 += tempf;
619                         tempf += 0.001;
620                 }
621         }
622
623         {
624                 TimeTaker timer("Testing floating-point vector speed");
625
626                 tempv3f1 = v3f(1, 2, 3);
627                 tempv3f2 = v3f(4, 5, 6);
628                 for (u32 i = 0; i < 10000000; i++) {
629                         tempf += tempv3f1.dotProduct(tempv3f2);
630                         tempv3f2 += v3f(7, 8, 9);
631                 }
632         }
633
634         {
635                 TimeTaker timer("Testing std::map speed");
636
637                 std::map<v2s16, f32> map1;
638                 tempf = -324;
639                 const s16 ii = 300;
640                 for (s16 y = 0; y < ii; y++) {
641                         for (s16 x = 0; x < ii; x++) {
642                                 map1[v2s16(x, y)] = tempf;
643                                 tempf += 1;
644                         }
645                 }
646                 for (s16 y = ii - 1; y >= 0; y--) {
647                         for (s16 x = 0; x < ii; x++) {
648                                 tempf = map1[v2s16(x, y)];
649                         }
650                 }
651         }
652
653         {
654                 infostream << "Around 5000/ms should do well here." << std::endl;
655                 TimeTaker timer("Testing mutex speed");
656
657                 std::mutex m;
658                 u32 n = 0;
659                 u32 i = 0;
660                 do {
661                         n += 10000;
662                         for (; i < n; i++) {
663                                 m.lock();
664                                 m.unlock();
665                         }
666                 }
667                 // Do at least 10ms
668                 while (timer.getTimerTime() < 10);
669
670                 u32 dtime = timer.stop();
671                 u32 per_ms = n / dtime;
672                 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
673         }
674 }