[CSM] Add basic HUD manipulation. (#6067)
[oweals/minetest.git] / src / client / renderingengine.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include <IrrlichtDevice.h>
22 #include <irrlicht.h>
23 #include "fontengine.h"
24 #include "client.h"
25 #include "clouds.h"
26 #include "util/numeric.h"
27 #include "guiscalingfilter.h"
28 #include "localplayer.h"
29 #include "client/hud.h"
30 #include "camera.h"
31 #include "minimap.h"
32 #include "clientmap.h"
33 #include "renderingengine.h"
34 #include "render/core.h"
35 #include "render/factory.h"
36 #include "inputhandler.h"
37 #include "gettext.h"
38
39 #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__) && \
40                 !defined(SERVER) && !defined(__HAIKU__)
41 #define XORG_USED
42 #endif
43 #ifdef XORG_USED
44 #include <X11/Xlib.h>
45 #include <X11/Xutil.h>
46 #endif
47
48 RenderingEngine *RenderingEngine::s_singleton = nullptr;
49
50 RenderingEngine::RenderingEngine(IEventReceiver *receiver)
51 {
52         sanity_check(!s_singleton);
53
54         // Resolution selection
55         bool fullscreen = g_settings->getBool("fullscreen");
56         u16 screen_w = g_settings->getU16("screen_w");
57         u16 screen_h = g_settings->getU16("screen_h");
58
59         // bpp, fsaa, vsync
60         bool vsync = g_settings->getBool("vsync");
61         u16 bits = g_settings->getU16("fullscreen_bpp");
62         u16 fsaa = g_settings->getU16("fsaa");
63
64         // stereo buffer required for pageflip stereo
65         bool stereo_buffer = g_settings->get("3d_mode") == "pageflip";
66
67         // Determine driver
68         video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
69         const std::string &driverstring = g_settings->get("video_driver");
70         std::vector<video::E_DRIVER_TYPE> drivers =
71                         RenderingEngine::getSupportedVideoDrivers();
72         u32 i;
73         for (i = 0; i != drivers.size(); i++) {
74                 if (!strcasecmp(driverstring.c_str(),
75                                     RenderingEngine::getVideoDriverName(drivers[i]))) {
76                         driverType = drivers[i];
77                         break;
78                 }
79         }
80         if (i == drivers.size()) {
81                 errorstream << "Invalid video_driver specified; "
82                                "defaulting to opengl"
83                             << std::endl;
84         }
85
86         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
87         params.DriverType = driverType;
88         params.WindowSize = core::dimension2d<u32>(screen_w, screen_h);
89         params.Bits = bits;
90         params.AntiAlias = fsaa;
91         params.Fullscreen = fullscreen;
92         params.Stencilbuffer = false;
93         params.Stereobuffer = stereo_buffer;
94         params.Vsync = vsync;
95         params.EventReceiver = receiver;
96         params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
97         params.ZBufferBits = 24;
98 #ifdef __ANDROID__
99         // clang-format off
100         params.PrivateData = porting::app_global;
101         params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM + "media" +
102                 DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
103         // clang-format on
104 #endif
105
106         m_device = createDeviceEx(params);
107         driver = m_device->getVideoDriver();
108
109         s_singleton = this;
110 }
111
112 RenderingEngine::~RenderingEngine()
113 {
114         core.reset();
115         m_device->drop();
116         s_singleton = nullptr;
117 }
118
119 v2u32 RenderingEngine::getWindowSize() const
120 {
121         if (core)
122                 return core->getVirtualSize();
123         return m_device->getVideoDriver()->getScreenSize();
124 }
125
126 void RenderingEngine::setResizable(bool resize)
127 {
128         m_device->setResizable(resize);
129 }
130
131 bool RenderingEngine::print_video_modes()
132 {
133         IrrlichtDevice *nulldevice;
134
135         bool vsync = g_settings->getBool("vsync");
136         u16 fsaa = g_settings->getU16("fsaa");
137         MyEventReceiver *receiver = new MyEventReceiver();
138
139         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
140         params.DriverType = video::EDT_NULL;
141         params.WindowSize = core::dimension2d<u32>(640, 480);
142         params.Bits = 24;
143         params.AntiAlias = fsaa;
144         params.Fullscreen = false;
145         params.Stencilbuffer = false;
146         params.Vsync = vsync;
147         params.EventReceiver = receiver;
148         params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
149
150         nulldevice = createDeviceEx(params);
151
152         if (!nulldevice) {
153                 delete receiver;
154                 return false;
155         }
156
157         std::cout << _("Available video modes (WxHxD):") << std::endl;
158
159         video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
160
161         if (videomode_list != NULL) {
162                 s32 videomode_count = videomode_list->getVideoModeCount();
163                 core::dimension2d<u32> videomode_res;
164                 s32 videomode_depth;
165                 for (s32 i = 0; i < videomode_count; ++i) {
166                         videomode_res = videomode_list->getVideoModeResolution(i);
167                         videomode_depth = videomode_list->getVideoModeDepth(i);
168                         std::cout << videomode_res.Width << "x" << videomode_res.Height
169                                   << "x" << videomode_depth << std::endl;
170                 }
171
172                 std::cout << _("Active video mode (WxHxD):") << std::endl;
173                 videomode_res = videomode_list->getDesktopResolution();
174                 videomode_depth = videomode_list->getDesktopDepth();
175                 std::cout << videomode_res.Width << "x" << videomode_res.Height << "x"
176                           << videomode_depth << std::endl;
177         }
178
179         nulldevice->drop();
180         delete receiver;
181
182         return videomode_list != NULL;
183 }
184
185 void RenderingEngine::setXorgClassHint(
186                 const video::SExposedVideoData &video_data, const std::string &name)
187 {
188 #ifdef XORG_USED
189         if (video_data.OpenGLLinux.X11Display == NULL)
190                 return;
191
192         XClassHint *classhint = XAllocClassHint();
193         classhint->res_name = (char *)name.c_str();
194         classhint->res_class = (char *)name.c_str();
195
196         XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
197                         video_data.OpenGLLinux.X11Window, classhint);
198         XFree(classhint);
199 #endif
200 }
201
202 bool RenderingEngine::setWindowIcon()
203 {
204 #if defined(XORG_USED)
205 #if RUN_IN_PLACE
206         return setXorgWindowIconFromPath(
207                         porting::path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png");
208 #else
209         // We have semi-support for reading in-place data if we are
210         // compiled with RUN_IN_PLACE. Don't break with this and
211         // also try the path_share location.
212         return setXorgWindowIconFromPath(
213                                ICON_DIR "/hicolor/128x128/apps/" PROJECT_NAME ".png") ||
214                setXorgWindowIconFromPath(porting::path_share + "/misc/" PROJECT_NAME
215                                                                "-xorg-icon-128.png");
216 #endif
217 #elif defined(_WIN32)
218         const video::SExposedVideoData exposedData = driver->getExposedVideoData();
219         HWND hWnd; // Window handle
220
221         switch (driver->getDriverType()) {
222         case video::EDT_DIRECT3D8:
223                 hWnd = reinterpret_cast<HWND>(exposedData.D3D8.HWnd);
224                 break;
225         case video::EDT_DIRECT3D9:
226                 hWnd = reinterpret_cast<HWND>(exposedData.D3D9.HWnd);
227                 break;
228         case video::EDT_OPENGL:
229                 hWnd = reinterpret_cast<HWND>(exposedData.OpenGLWin32.HWnd);
230                 break;
231         default:
232                 return false;
233         }
234
235         // Load the ICON from resource file
236         const HICON hicon = LoadIcon(GetModuleHandle(NULL),
237                         MAKEINTRESOURCE(130) // The ID of the ICON defined in
238                                              // winresource.rc
239         );
240
241         if (hicon) {
242                 SendMessage(hWnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(hicon));
243                 SendMessage(hWnd, WM_SETICON, ICON_SMALL,
244                                 reinterpret_cast<LPARAM>(hicon));
245                 return true;
246         }
247         return false;
248 #else
249         return false;
250 #endif
251 }
252
253 bool RenderingEngine::setXorgWindowIconFromPath(const std::string &icon_file)
254 {
255 #ifdef XORG_USED
256
257         video::IImageLoader *image_loader = NULL;
258         u32 cnt = driver->getImageLoaderCount();
259         for (u32 i = 0; i < cnt; i++) {
260                 if (driver->getImageLoader(i)->isALoadableFileExtension(
261                                     icon_file.c_str())) {
262                         image_loader = driver->getImageLoader(i);
263                         break;
264                 }
265         }
266
267         if (!image_loader) {
268                 warningstream << "Could not find image loader for file '" << icon_file
269                               << "'" << std::endl;
270                 return false;
271         }
272
273         io::IReadFile *icon_f =
274                         m_device->getFileSystem()->createAndOpenFile(icon_file.c_str());
275
276         if (!icon_f) {
277                 warningstream << "Could not load icon file '" << icon_file << "'"
278                               << std::endl;
279                 return false;
280         }
281
282         video::IImage *img = image_loader->loadImage(icon_f);
283
284         if (!img) {
285                 warningstream << "Could not load icon file '" << icon_file << "'"
286                               << std::endl;
287                 icon_f->drop();
288                 return false;
289         }
290
291         u32 height = img->getDimension().Height;
292         u32 width = img->getDimension().Width;
293
294         size_t icon_buffer_len = 2 + height * width;
295         long *icon_buffer = new long[icon_buffer_len];
296
297         icon_buffer[0] = width;
298         icon_buffer[1] = height;
299
300         for (u32 x = 0; x < width; x++) {
301                 for (u32 y = 0; y < height; y++) {
302                         video::SColor col = img->getPixel(x, y);
303                         long pixel_val = 0;
304                         pixel_val |= (u8)col.getAlpha() << 24;
305                         pixel_val |= (u8)col.getRed() << 16;
306                         pixel_val |= (u8)col.getGreen() << 8;
307                         pixel_val |= (u8)col.getBlue();
308                         icon_buffer[2 + x + y * width] = pixel_val;
309                 }
310         }
311
312         img->drop();
313         icon_f->drop();
314
315         const video::SExposedVideoData &video_data = driver->getExposedVideoData();
316
317         Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display;
318
319         if (x11_dpl == NULL) {
320                 warningstream << "Could not find x11 display for setting its icon."
321                               << std::endl;
322                 delete[] icon_buffer;
323                 return false;
324         }
325
326         Window x11_win = (Window)video_data.OpenGLLinux.X11Window;
327
328         Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False);
329         Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False);
330         XChangeProperty(x11_dpl, x11_win, net_wm_icon, cardinal, 32, PropModeReplace,
331                         (const unsigned char *)icon_buffer, icon_buffer_len);
332
333         delete[] icon_buffer;
334
335 #endif
336         return true;
337 }
338
339 /*
340         Draws a screen with a single text on it.
341         Text will be removed when the screen is drawn the next time.
342         Additionally, a progressbar can be drawn when percent is set between 0 and 100.
343 */
344 void RenderingEngine::_draw_load_screen(const std::wstring &text,
345                 gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime,
346                 int percent, bool clouds)
347 {
348         v2u32 screensize = RenderingEngine::get_instance()->getWindowSize();
349
350         v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight());
351         v2s32 center(screensize.X / 2, screensize.Y / 2);
352         core::rect<s32> textrect(center - textsize / 2, center + textsize / 2);
353
354         gui::IGUIStaticText *guitext =
355                         guienv->addStaticText(text.c_str(), textrect, false, false);
356         guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
357
358         bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
359         if (cloud_menu_background) {
360                 g_menuclouds->step(dtime * 3);
361                 g_menuclouds->render();
362                 get_video_driver()->beginScene(
363                                 true, true, video::SColor(255, 140, 186, 250));
364                 g_menucloudsmgr->drawAll();
365         } else
366                 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
367
368         // draw progress bar
369         if ((percent >= 0) && (percent <= 100)) {
370                 video::ITexture *progress_img = tsrc->getTexture("progress_bar.png");
371                 video::ITexture *progress_img_bg =
372                                 tsrc->getTexture("progress_bar_bg.png");
373
374                 if (progress_img && progress_img_bg) {
375 #ifndef __ANDROID__
376                         const core::dimension2d<u32> &img_size =
377                                         progress_img_bg->getSize();
378                         u32 imgW = rangelim(img_size.Width, 200, 600);
379                         u32 imgH = rangelim(img_size.Height, 24, 72);
380 #else
381                         const core::dimension2d<u32> img_size(256, 48);
382                         float imgRatio = (float)img_size.Height / img_size.Width;
383                         u32 imgW = screensize.X / 2.2f;
384                         u32 imgH = floor(imgW * imgRatio);
385 #endif
386                         v2s32 img_pos((screensize.X - imgW) / 2,
387                                         (screensize.Y - imgH) / 2);
388
389                         draw2DImageFilterScaled(get_video_driver(), progress_img_bg,
390                                         core::rect<s32>(img_pos.X, img_pos.Y,
391                                                         img_pos.X + imgW,
392                                                         img_pos.Y + imgH),
393                                         core::rect<s32>(0, 0, img_size.Width,
394                                                         img_size.Height),
395                                         0, 0, true);
396
397                         draw2DImageFilterScaled(get_video_driver(), progress_img,
398                                         core::rect<s32>(img_pos.X, img_pos.Y,
399                                                         img_pos.X + (percent * imgW) / 100,
400                                                         img_pos.Y + imgH),
401                                         core::rect<s32>(0, 0,
402                                                         (percent * img_size.Width) / 100,
403                                                         img_size.Height),
404                                         0, 0, true);
405                 }
406         }
407
408         guienv->drawAll();
409         get_video_driver()->endScene();
410         guitext->remove();
411 }
412
413 /*
414         Draws the menu scene including (optional) cloud background.
415 */
416 void RenderingEngine::_draw_menu_scene(gui::IGUIEnvironment *guienv,
417                 float dtime, bool clouds)
418 {
419         bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
420         if (cloud_menu_background) {
421                 g_menuclouds->step(dtime * 3);
422                 g_menuclouds->render();
423                 get_video_driver()->beginScene(
424                                 true, true, video::SColor(255, 140, 186, 250));
425                 g_menucloudsmgr->drawAll();
426         } else
427                 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
428
429         guienv->drawAll();
430         get_video_driver()->endScene();
431 }
432
433 std::vector<core::vector3d<u32>> RenderingEngine::getSupportedVideoModes()
434 {
435         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
436         sanity_check(nulldevice);
437
438         std::vector<core::vector3d<u32>> mlist;
439         video::IVideoModeList *modelist = nulldevice->getVideoModeList();
440
441         s32 num_modes = modelist->getVideoModeCount();
442         for (s32 i = 0; i != num_modes; i++) {
443                 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
444                 u32 mode_depth = (u32)modelist->getVideoModeDepth(i);
445                 mlist.emplace_back(mode_res.Width, mode_res.Height, mode_depth);
446         }
447
448         nulldevice->drop();
449         return mlist;
450 }
451
452 std::vector<irr::video::E_DRIVER_TYPE> RenderingEngine::getSupportedVideoDrivers()
453 {
454         std::vector<irr::video::E_DRIVER_TYPE> drivers;
455
456         for (int i = 0; i != irr::video::EDT_COUNT; i++) {
457                 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
458                         drivers.push_back((irr::video::E_DRIVER_TYPE)i);
459         }
460
461         return drivers;
462 }
463
464 void RenderingEngine::_initialize(Client *client, Hud *hud)
465 {
466         const std::string &draw_mode = g_settings->get("3d_mode");
467         core.reset(createRenderingCore(draw_mode, m_device, client, hud));
468         core->initialize();
469 }
470
471 void RenderingEngine::_finalize()
472 {
473         core.reset();
474 }
475
476 void RenderingEngine::_draw_scene(video::SColor skycolor, bool show_hud,
477                 bool show_minimap, bool draw_wield_tool, bool draw_crosshair)
478 {
479         core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair);
480 }
481
482 const char *RenderingEngine::getVideoDriverName(irr::video::E_DRIVER_TYPE type)
483 {
484         static const char *driver_ids[] = {
485                         "null",
486                         "software",
487                         "burningsvideo",
488                         "direct3d8",
489                         "direct3d9",
490                         "opengl",
491                         "ogles1",
492                         "ogles2",
493         };
494
495         return driver_ids[type];
496 }
497
498 const char *RenderingEngine::getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
499 {
500         static const char *driver_names[] = {
501                         "NULL Driver",
502                         "Software Renderer",
503                         "Burning's Video",
504                         "Direct3D 8",
505                         "Direct3D 9",
506                         "OpenGL",
507                         "OpenGL ES1",
508                         "OpenGL ES2",
509         };
510
511         return driver_names[type];
512 }
513
514 #ifndef __ANDROID__
515 #ifdef XORG_USED
516
517 static float calcDisplayDensity()
518 {
519         const char *current_display = getenv("DISPLAY");
520
521         if (current_display != NULL) {
522                 Display *x11display = XOpenDisplay(current_display);
523
524                 if (x11display != NULL) {
525                         /* try x direct */
526                         float dpi_height = floor(
527                                         DisplayHeight(x11display, 0) /
528                                                         (DisplayHeightMM(x11display, 0) *
529                                                                         0.039370) +
530                                         0.5);
531                         float dpi_width = floor(
532                                         DisplayWidth(x11display, 0) /
533                                                         (DisplayWidthMM(x11display, 0) *
534                                                                         0.039370) +
535                                         0.5);
536
537                         XCloseDisplay(x11display);
538
539                         return std::max(dpi_height, dpi_width) / 96.0;
540                 }
541         }
542
543         /* return manually specified dpi */
544         return g_settings->getFloat("screen_dpi") / 96.0;
545 }
546
547 float RenderingEngine::getDisplayDensity()
548 {
549         static float cached_display_density = calcDisplayDensity();
550         return cached_display_density;
551 }
552
553 #else  // XORG_USED
554 float RenderingEngine::getDisplayDensity()
555 {
556         return g_settings->getFloat("screen_dpi") / 96.0;
557 }
558 #endif // XORG_USED
559
560 v2u32 RenderingEngine::getDisplaySize()
561 {
562         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
563
564         core::dimension2d<u32> deskres =
565                         nulldevice->getVideoModeList()->getDesktopResolution();
566         nulldevice->drop();
567
568         return deskres;
569 }
570 #endif // __ANDROID__