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