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