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