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