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