]> git.lizzy.rs Git - minetest.git/blob - src/client/clientlauncher.cpp
Re-apply 4a6582c13c36cab457b78f32338c6bb4ab9ea58b broken since 146f77fdb750833c649de7...
[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 "main.h"
21 #include "mainmenumanager.h"
22 #include "debug.h"
23 #include "clouds.h"
24 #include "server.h"
25 #include "filesys.h"
26 #include "guiMainMenu.h"
27 #include "game.h"
28 #include "chat.h"
29 #include "gettext.h"
30 #include "profiler.h"
31 #include "log.h"
32 #include "serverlist.h"
33 #include "guiEngine.h"
34 #include "player.h"
35 #include "fontengine.h"
36 #include "clientlauncher.h"
37
38 // A pointer to a global instance of the time getter
39 // TODO: why?
40 TimeGetter *g_timegetter = NULL;
41
42 u32 getTimeMs()
43 {
44         if (g_timegetter == NULL)
45                 return 0;
46         return g_timegetter->getTime(PRECISION_MILLI);
47 }
48
49 u32 getTime(TimePrecision prec) {
50         if (g_timegetter == NULL)
51                 return 0;
52         return g_timegetter->getTime(prec);
53 }
54
55 ClientLauncher::~ClientLauncher()
56 {
57         if (receiver)
58                 delete receiver;
59
60         if (input)
61                 delete input;
62
63         if (g_fontengine)
64                 delete g_fontengine;
65
66         if (device)
67                 device->drop();
68 }
69
70
71 bool ClientLauncher::run(GameParams &game_params, const Settings &cmd_args)
72 {
73         init_args(game_params, cmd_args);
74
75         // List video modes if requested
76         if (list_video_modes)
77                 return print_video_modes();
78
79         if (!init_engine(game_params.log_level)) {
80                 errorstream << "Could not initialize game engine." << std::endl;
81                 return false;
82         }
83
84         // Speed tests (done after irrlicht is loaded to get timer)
85         if (cmd_args.getFlag("speedtests")) {
86                 dstream << "Running speed tests" << std::endl;
87                 speed_tests();
88                 return true;
89         }
90
91         video::IVideoDriver *video_driver = device->getVideoDriver();
92         if (video_driver == NULL) {
93                 errorstream << "Could not initialize video driver." << std::endl;
94                 return false;
95         }
96
97         porting::setXorgClassHint(video_driver->getExposedVideoData(), "Minetest");
98
99         /*
100                 This changes the minimum allowed number of vertices in a VBO.
101                 Default is 500.
102         */
103         //driver->setMinHardwareBufferVertexCount(50);
104
105         // Create time getter
106         g_timegetter = new IrrlichtTimeGetter(device);
107
108         // Create game callback for menus
109         g_gamecallback = new MainGameCallback(device);
110
111         device->setResizable(true);
112
113         if (random_input)
114                 input = new RandomInputHandler();
115         else
116                 input = new RealInputHandler(device, receiver);
117
118         smgr = device->getSceneManager();
119
120         guienv = device->getGUIEnvironment();
121         skin = guienv->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         assert(g_fontengine != NULL);
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 = smgr->createNewSceneManager();
141         if (!g_menuclouds)
142                 g_menuclouds = new Clouds(g_menucloudsmgr->getRootSceneNode(),
143                                 g_menucloudsmgr, -1, rand(), 100);
144         g_menuclouds->update(v2f(0, 0), video::SColor(255, 200, 200, 255));
145         scene::ICameraSceneNode* camera;
146         camera = g_menucloudsmgr->addCameraSceneNode(0,
147                                 v3f(0, 0, 0), v3f(0, 60, 100));
148         camera->setFarValue(10000);
149
150         /*
151                 GUI stuff
152         */
153
154         ChatBackend chat_backend;
155
156         // If an error occurs, this is set to something by menu().
157         // It is then displayed before  the menu shows on the next call to menu()
158         std::wstring error_message = L"";
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 (device->run() && !*kill && !g_gamecallback->shutdown_requested)
169         {
170                 // Set the window caption
171                 const wchar_t *text = wgettext("Main Menu");
172                 device->setWindowCaption((std::wstring(L"Minetest [") + text + L"]").c_str());
173                 delete[] text;
174
175                 try {   // This is used for catching disconnects
176
177                         guienv->clear();
178
179                         /*
180                                 We need some kind of a root node to be able to add
181                                 custom gui elements directly on the screen.
182                                 Otherwise they won't be automatically drawn.
183                         */
184                         guiroot = guienv->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000));
185
186                         bool game_has_run = launch_game(&error_message, game_params, cmd_args);
187
188                         // If skip_main_menu, we only want to startup once
189                         if (skip_main_menu && !first_loop)
190                                 break;
191
192                         first_loop = false;
193
194                         if (!game_has_run) {
195                                 if (skip_main_menu)
196                                         break;
197                                 else
198                                         continue;
199                         }
200
201                         // Break out of menu-game loop to shut down cleanly
202                         if (!device->run() || *kill) {
203                                 if (g_settings_path != "")
204                                         g_settings->updateConfigFile(g_settings_path.c_str());
205                                 break;
206                         }
207
208                         if (current_playername.length() > PLAYERNAME_SIZE-1) {
209                                 error_message = wgettext("Player name too long.");
210                                 playername = current_playername.substr(0, PLAYERNAME_SIZE-1);
211                                 g_settings->set("name", playername);
212                                 continue;
213                         }
214
215                         device->getVideoDriver()->setTextureCreationFlag(
216                                         video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map"));
217
218 #ifdef HAVE_TOUCHSCREENGUI
219                         receiver->m_touchscreengui = new TouchScreenGUI(device, receiver);
220                         g_touchscreengui = receiver->m_touchscreengui;
221 #endif
222                         the_game(
223                                 kill,
224                                 random_input,
225                                 input,
226                                 device,
227                                 worldspec.path,
228                                 current_playername,
229                                 current_password,
230                                 current_address,
231                                 current_port,
232                                 error_message,
233                                 chat_backend,
234                                 gamespec,
235                                 simple_singleplayer_mode
236                         );
237                         smgr->clear();
238
239 #ifdef HAVE_TOUCHSCREENGUI
240                         delete g_touchscreengui;
241                         g_touchscreengui = NULL;
242                         receiver->m_touchscreengui = NULL;
243 #endif
244
245                 } //try
246                 catch (con::PeerNotFoundException &e) {
247                         error_message = wgettext("Connection error (timed out?)");
248                         errorstream << wide_to_narrow(error_message) << std::endl;
249                 }
250
251 #ifdef NDEBUG
252                 catch (std::exception &e) {
253                         std::string narrow_message = "Some exception: \"";
254                         narrow_message += e.what();
255                         narrow_message += "\"";
256                         errorstream << narrow_message << std::endl;
257                         error_message = narrow_to_wide(narrow_message);
258                 }
259 #endif
260
261                 // If no main menu, show error and exit
262                 if (skip_main_menu) {
263                         if (error_message != L"") {
264                                 verbosestream << "error_message = "
265                                               << wide_to_narrow(error_message) << std::endl;
266                                 retval = false;
267                         }
268                         break;
269                 }
270         } // Menu-game loop
271
272         g_menuclouds->drop();
273         g_menucloudsmgr->drop();
274
275         return retval;
276 }
277
278 void ClientLauncher::init_args(GameParams &game_params, const Settings &cmd_args)
279 {
280
281         skip_main_menu = cmd_args.getFlag("go");
282
283         // FIXME: This is confusing (but correct)
284
285         /* If world_path is set then override it unless skipping the main menu using
286          * the --go command line param. Else, give preference to the address
287          * supplied on the command line
288          */
289         address = g_settings->get("address");
290         if (game_params.world_path != "" && !skip_main_menu)
291                 address = "";
292         else if (cmd_args.exists("address"))
293                 address = cmd_args.get("address");
294
295         playername = g_settings->get("name");
296         if (cmd_args.exists("name"))
297                 playername = cmd_args.get("name");
298
299         list_video_modes = cmd_args.getFlag("videomodes");
300
301         use_freetype = g_settings->getBool("freetype");
302
303         random_input = g_settings->getBool("random_input")
304                         || cmd_args.getFlag("random-input");
305 }
306
307 bool ClientLauncher::init_engine(int log_level)
308 {
309         receiver = new MyEventReceiver();
310         create_engine_device(log_level);
311         return device != NULL;
312 }
313
314 bool ClientLauncher::launch_game(std::wstring *error_message,
315                 GameParams &game_params, const Settings &cmd_args)
316 {
317         // Initialize menu data
318         MainMenuData menudata;
319         menudata.address      = address;
320         menudata.name         = playername;
321         menudata.port         = itos(game_params.socket_port);
322         menudata.errormessage = wide_to_narrow(*error_message);
323
324         *error_message = L"";
325
326         if (cmd_args.exists("password"))
327                 menudata.password = cmd_args.get("password");
328
329         menudata.enable_public = g_settings->getBool("server_announce");
330
331         // If a world was commanded, append and select it
332         if (game_params.world_path != "") {
333                 worldspec.gameid = getWorldGameId(game_params.world_path, true);
334                 worldspec.name = _("[--world parameter]");
335
336                 if (worldspec.gameid == "") {   // Create new
337                         worldspec.gameid = g_settings->get("default_game");
338                         worldspec.name += " [new]";
339                 }
340                 worldspec.path = game_params.world_path;
341         }
342
343         /* Show the GUI menu
344          */
345         if (!skip_main_menu) {
346                 main_menu(&menudata);
347
348                 // Skip further loading if there was an exit signal.
349                 if (*porting::signal_handler_killstatus())
350                         return false;
351
352                 address = menudata.address;
353                 int newport = stoi(menudata.port);
354                 if (newport != 0)
355                         game_params.socket_port = newport;
356
357                 simple_singleplayer_mode = menudata.simple_singleplayer_mode;
358
359                 std::vector<WorldSpec> worldspecs = getAvailableWorlds();
360
361                 if (menudata.selected_world >= 0
362                                 && menudata.selected_world < (int)worldspecs.size()) {
363                         g_settings->set("selected_world_path",
364                                         worldspecs[menudata.selected_world].path);
365                         worldspec = worldspecs[menudata.selected_world];
366                 }
367         }
368
369         if (menudata.errormessage != "") {
370                 /* The calling function will pass this back into this function upon the
371                  * next iteration (if any) causing it to be displayed by the GUI
372                  */
373                 *error_message = narrow_to_wide(menudata.errormessage);
374                 return false;
375         }
376
377         if (menudata.name == "")
378                 menudata.name = std::string("Guest") + itos(myrand_range(1000, 9999));
379         else
380                 playername = menudata.name;
381
382         password = translatePassword(playername, narrow_to_wide(menudata.password));
383
384         g_settings->set("name", playername);
385
386         current_playername = playername;
387         current_password   = password;
388         current_address    = address;
389         current_port       = game_params.socket_port;
390
391         // If using simple singleplayer mode, override
392         if (simple_singleplayer_mode) {
393                 assert(skip_main_menu == false);
394                 current_playername = "singleplayer";
395                 current_password = "";
396                 current_address = "";
397                 current_port = myrand_range(49152, 65535);
398         } else if (address != "") {
399                 ServerListSpec server;
400                 server["name"] = menudata.servername;
401                 server["address"] = menudata.address;
402                 server["port"] = menudata.port;
403                 server["description"] = menudata.serverdescription;
404                 ServerList::insert(server);
405         }
406
407         infostream << "Selected world: " << worldspec.name
408                    << " [" << worldspec.path << "]" << std::endl;
409
410         if (current_address == "") { // If local game
411                 if (worldspec.path == "") {
412                         *error_message = wgettext("No world selected and no address "
413                                         "provided. Nothing to do.");
414                         errorstream << wide_to_narrow(*error_message) << std::endl;
415                         return false;
416                 }
417
418                 if (!fs::PathExists(worldspec.path)) {
419                         *error_message = wgettext("Provided world path doesn't exist: ")
420                                         + narrow_to_wide(worldspec.path);
421                         errorstream << wide_to_narrow(*error_message) << std::endl;
422                         return false;
423                 }
424
425                 // Load gamespec for required game
426                 gamespec = findWorldSubgame(worldspec.path);
427                 if (!gamespec.isValid() && !game_params.game_spec.isValid()) {
428                         *error_message = wgettext("Could not find or load game \"")
429                                         + narrow_to_wide(worldspec.gameid) + L"\"";
430                         errorstream << wide_to_narrow(*error_message) << std::endl;
431                         return false;
432                 }
433
434                 if (porting::signal_handler_killstatus())
435                         return true;
436
437                 if (game_params.game_spec.isValid() &&
438                                 game_params.game_spec.id != worldspec.gameid) {
439                         errorstream << "WARNING: Overriding gamespec from \""
440                                     << worldspec.gameid << "\" to \""
441                                     << game_params.game_spec.id << "\"" << std::endl;
442                         gamespec = game_params.game_spec;
443                 }
444
445                 if (!gamespec.isValid()) {
446                         *error_message = wgettext("Invalid gamespec.");
447                         *error_message += L" (world_gameid="
448                                         + narrow_to_wide(worldspec.gameid) + L")";
449                         errorstream << wide_to_narrow(*error_message) << std::endl;
450                         return false;
451                 }
452         }
453
454         return true;
455 }
456
457 void ClientLauncher::main_menu(MainMenuData *menudata)
458 {
459         bool *kill = porting::signal_handler_killstatus();
460         video::IVideoDriver *driver = device->getVideoDriver();
461
462         infostream << "Waiting for other menus" << std::endl;
463         while (device->run() && *kill == false) {
464                 if (noMenuActive())
465                         break;
466                 driver->beginScene(true, true, video::SColor(255, 128, 128, 128));
467                 guienv->drawAll();
468                 driver->endScene();
469                 // On some computers framerate doesn't seem to be automatically limited
470                 sleep_ms(25);
471         }
472         infostream << "Waited for other menus" << std::endl;
473
474         // Cursor can be non-visible when coming from the game
475 #ifndef ANDROID
476         device->getCursorControl()->setVisible(true);
477 #endif
478
479         /* show main menu */
480         GUIEngine mymenu(device, guiroot, &g_menumgr, smgr, menudata, *kill);
481
482         smgr->clear();  /* leave scene manager in a clean state */
483 }
484
485 bool ClientLauncher::create_engine_device(int log_level)
486 {
487         static const irr::ELOG_LEVEL irr_log_level[5] = {
488                 ELL_NONE,
489                 ELL_ERROR,
490                 ELL_WARNING,
491                 ELL_INFORMATION,
492 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8)
493                 ELL_INFORMATION
494 #else
495                 ELL_DEBUG
496 #endif
497         };
498
499         // Resolution selection
500         bool fullscreen = g_settings->getBool("fullscreen");
501         u16 screenW = g_settings->getU16("screenW");
502         u16 screenH = g_settings->getU16("screenH");
503
504         // bpp, fsaa, vsync
505         bool vsync = g_settings->getBool("vsync");
506         u16 bits = g_settings->getU16("fullscreen_bpp");
507         u16 fsaa = g_settings->getU16("fsaa");
508
509         // Determine driver
510         video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
511         std::string driverstring = g_settings->get("video_driver");
512         std::vector<video::E_DRIVER_TYPE> drivers
513                 = porting::getSupportedVideoDrivers();
514         u32 i;
515         for (i = 0; i != drivers.size(); i++) {
516                 if (!strcasecmp(driverstring.c_str(),
517                         porting::getVideoDriverName(drivers[i]))) {
518                         driverType = drivers[i];
519                         break;
520                 }
521         }
522         if (i == drivers.size()) {
523                 errorstream << "Invalid video_driver specified; "
524                         "defaulting to opengl" << std::endl;
525         }
526
527         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
528         params.DriverType    = driverType;
529         params.WindowSize    = core::dimension2d<u32>(screenW, screenH);
530         params.Bits          = bits;
531         params.AntiAlias     = fsaa;
532         params.Fullscreen    = fullscreen;
533         params.Stencilbuffer = false;
534         params.Vsync         = vsync;
535         params.EventReceiver = receiver;
536         params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
537 #ifdef __ANDROID__
538         params.PrivateData = porting::app_global;
539         params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM +
540                         "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
541 #endif
542
543         device = createDeviceEx(params);
544
545         if (device) {
546                 // Map our log level to irrlicht engine one.
547                 ILogger* irr_logger = device->getLogger();
548                 irr_logger->setLogLevel(irr_log_level[log_level]);
549
550                 porting::initIrrlicht(device);
551         }
552
553         return device != NULL;
554 }
555
556 void ClientLauncher::speed_tests()
557 {
558         // volatile to avoid some potential compiler optimisations
559         volatile static s16 temp16;
560         volatile static f32 tempf;
561         static v3f tempv3f1;
562         static v3f tempv3f2;
563         static std::string tempstring;
564         static std::string tempstring2;
565
566         tempv3f1 = v3f();
567         tempv3f2 = v3f();
568         tempstring = std::string();
569         tempstring2 = std::string();
570
571         {
572                 infostream << "The following test should take around 20ms." << std::endl;
573                 TimeTaker timer("Testing std::string speed");
574                 const u32 jj = 10000;
575                 for (u32 j = 0; j < jj; j++) {
576                         tempstring = "";
577                         tempstring2 = "";
578                         const u32 ii = 10;
579                         for (u32 i = 0; i < ii; i++) {
580                                 tempstring2 += "asd";
581                         }
582                         for (u32 i = 0; i < ii+1; i++) {
583                                 tempstring += "asd";
584                                 if (tempstring == tempstring2)
585                                         break;
586                         }
587                 }
588         }
589
590         infostream << "All of the following tests should take around 100ms each."
591                    << std::endl;
592
593         {
594                 TimeTaker timer("Testing floating-point conversion speed");
595                 tempf = 0.001;
596                 for (u32 i = 0; i < 4000000; i++) {
597                         temp16 += tempf;
598                         tempf += 0.001;
599                 }
600         }
601
602         {
603                 TimeTaker timer("Testing floating-point vector speed");
604
605                 tempv3f1 = v3f(1, 2, 3);
606                 tempv3f2 = v3f(4, 5, 6);
607                 for (u32 i = 0; i < 10000000; i++) {
608                         tempf += tempv3f1.dotProduct(tempv3f2);
609                         tempv3f2 += v3f(7, 8, 9);
610                 }
611         }
612
613         {
614                 TimeTaker timer("Testing std::map speed");
615
616                 std::map<v2s16, f32> map1;
617                 tempf = -324;
618                 const s16 ii = 300;
619                 for (s16 y = 0; y < ii; y++) {
620                         for (s16 x = 0; x < ii; x++) {
621                                 map1[v2s16(x, y)] =  tempf;
622                                 tempf += 1;
623                         }
624                 }
625                 for (s16 y = ii - 1; y >= 0; y--) {
626                         for (s16 x = 0; x < ii; x++) {
627                                 tempf = map1[v2s16(x, y)];
628                         }
629                 }
630         }
631
632         {
633                 infostream << "Around 5000/ms should do well here." << std::endl;
634                 TimeTaker timer("Testing mutex speed");
635
636                 JMutex m;
637                 u32 n = 0;
638                 u32 i = 0;
639                 do {
640                         n += 10000;
641                         for (; i < n; i++) {
642                                 m.Lock();
643                                 m.Unlock();
644                         }
645                 }
646                 // Do at least 10ms
647                 while(timer.getTimerTime() < 10);
648
649                 u32 dtime = timer.stop();
650                 u32 per_ms = n / dtime;
651                 infostream << "Done. " << dtime << "ms, " << per_ms << "/ms" << std::endl;
652         }
653 }
654
655 bool ClientLauncher::print_video_modes()
656 {
657         IrrlichtDevice *nulldevice;
658
659         bool vsync = g_settings->getBool("vsync");
660         u16 fsaa = g_settings->getU16("fsaa");
661         MyEventReceiver* receiver = new MyEventReceiver();
662
663         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
664         params.DriverType    = video::EDT_NULL;
665         params.WindowSize    = core::dimension2d<u32>(640, 480);
666         params.Bits          = 24;
667         params.AntiAlias     = fsaa;
668         params.Fullscreen    = false;
669         params.Stencilbuffer = false;
670         params.Vsync         = vsync;
671         params.EventReceiver = receiver;
672         params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
673
674         nulldevice = createDeviceEx(params);
675
676         if (nulldevice == NULL) {
677                 delete receiver;
678                 return false;
679         }
680
681         dstream << _("Available video modes (WxHxD):") << std::endl;
682
683         video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
684
685         if (videomode_list != NULL) {
686                 s32 videomode_count = videomode_list->getVideoModeCount();
687                 core::dimension2d<u32> videomode_res;
688                 s32 videomode_depth;
689                 for (s32 i = 0; i < videomode_count; ++i) {
690                         videomode_res = videomode_list->getVideoModeResolution(i);
691                         videomode_depth = videomode_list->getVideoModeDepth(i);
692                         dstream << videomode_res.Width << "x" << videomode_res.Height
693                                 << "x" << videomode_depth << std::endl;
694                 }
695
696                 dstream << _("Active video mode (WxHxD):") << std::endl;
697                 videomode_res = videomode_list->getDesktopResolution();
698                 videomode_depth = videomode_list->getDesktopDepth();
699                 dstream << videomode_res.Width << "x" << videomode_res.Height
700                         << "x" << videomode_depth << std::endl;
701
702         }
703
704         nulldevice->drop();
705         delete receiver;
706
707         return videomode_list != NULL;
708 }