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