3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
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.
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.
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.
21 #include <IrrlichtDevice.h>
23 #include "fontengine.h"
26 #include "util/numeric.h"
27 #include "guiscalingfilter.h"
28 #include "localplayer.h"
29 #include "client/hud.h"
32 #include "clientmap.h"
33 #include "renderingengine.h"
34 #include "render/core.h"
35 #include "render/factory.h"
36 #include "inputhandler.h"
38 #include "../gui/guiSkin.h"
40 #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__) && \
41 !defined(SERVER) && !defined(__HAIKU__)
46 #include <X11/Xutil.h>
47 #include <X11/Xatom.h>
59 RenderingEngine *RenderingEngine::s_singleton = nullptr;
62 static gui::GUISkin *createSkin(gui::IGUIEnvironment *environment,
63 gui::EGUI_SKIN_TYPE type, video::IVideoDriver *driver)
65 gui::GUISkin *skin = new gui::GUISkin(type, driver);
67 gui::IGUIFont *builtinfont = environment->getBuiltInFont();
68 gui::IGUIFontBitmap *bitfont = nullptr;
69 if (builtinfont && builtinfont->getType() == gui::EGFT_BITMAP)
70 bitfont = (gui::IGUIFontBitmap*)builtinfont;
72 gui::IGUISpriteBank *bank = 0;
73 skin->setFont(builtinfont);
76 bank = bitfont->getSpriteBank();
78 skin->setSpriteBank(bank);
84 RenderingEngine::RenderingEngine(IEventReceiver *receiver)
86 sanity_check(!s_singleton);
88 // Resolution selection
89 bool fullscreen = g_settings->getBool("fullscreen");
90 u16 screen_w = g_settings->getU16("screen_w");
91 u16 screen_h = g_settings->getU16("screen_h");
94 bool vsync = g_settings->getBool("vsync");
95 u16 bits = g_settings->getU16("fullscreen_bpp");
96 u16 fsaa = g_settings->getU16("fsaa");
98 // stereo buffer required for pageflip stereo
99 bool stereo_buffer = g_settings->get("3d_mode") == "pageflip";
102 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
103 const std::string &driverstring = g_settings->get("video_driver");
104 std::vector<video::E_DRIVER_TYPE> drivers =
105 RenderingEngine::getSupportedVideoDrivers();
107 for (i = 0; i != drivers.size(); i++) {
108 if (!strcasecmp(driverstring.c_str(),
109 RenderingEngine::getVideoDriverName(drivers[i]))) {
110 driverType = drivers[i];
114 if (i == drivers.size()) {
115 errorstream << "Invalid video_driver specified; "
116 "defaulting to opengl"
120 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
121 if (g_logger.getTraceEnabled())
122 params.LoggingLevel = irr::ELL_DEBUG;
123 params.DriverType = driverType;
124 params.WindowSize = core::dimension2d<u32>(screen_w, screen_h);
126 params.AntiAlias = fsaa;
127 params.Fullscreen = fullscreen;
128 params.Stencilbuffer = false;
129 params.Stereobuffer = stereo_buffer;
130 params.Vsync = vsync;
131 params.EventReceiver = receiver;
132 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
133 params.ZBufferBits = 24;
135 params.PrivateData = porting::app_global;
138 // there is no standardized path for these on desktop
139 std::string rel_path = std::string("client") + DIR_DELIM
140 + "shaders" + DIR_DELIM + "Irrlicht";
141 params.OGLES2ShaderPath = (porting::path_share + DIR_DELIM + rel_path + DIR_DELIM).c_str();
144 m_device = createDeviceEx(params);
145 driver = m_device->getVideoDriver();
149 auto skin = createSkin(m_device->getGUIEnvironment(),
150 gui::EGST_WINDOWS_METALLIC, driver);
151 m_device->getGUIEnvironment()->setSkin(skin);
155 RenderingEngine::~RenderingEngine()
158 m_device->closeDevice();
159 s_singleton = nullptr;
162 v2u32 RenderingEngine::getWindowSize() const
165 return core->getVirtualSize();
166 return m_device->getVideoDriver()->getScreenSize();
169 void RenderingEngine::setResizable(bool resize)
171 m_device->setResizable(resize);
174 bool RenderingEngine::print_video_modes()
176 IrrlichtDevice *nulldevice;
178 bool vsync = g_settings->getBool("vsync");
179 u16 fsaa = g_settings->getU16("fsaa");
180 MyEventReceiver *receiver = new MyEventReceiver();
182 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
183 params.DriverType = video::EDT_NULL;
184 params.WindowSize = core::dimension2d<u32>(640, 480);
186 params.AntiAlias = fsaa;
187 params.Fullscreen = false;
188 params.Stencilbuffer = false;
189 params.Vsync = vsync;
190 params.EventReceiver = receiver;
191 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
193 nulldevice = createDeviceEx(params);
200 std::cout << _("Available video modes (WxHxD):") << std::endl;
202 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
204 if (videomode_list != NULL) {
205 s32 videomode_count = videomode_list->getVideoModeCount();
206 core::dimension2d<u32> videomode_res;
208 for (s32 i = 0; i < videomode_count; ++i) {
209 videomode_res = videomode_list->getVideoModeResolution(i);
210 videomode_depth = videomode_list->getVideoModeDepth(i);
211 std::cout << videomode_res.Width << "x" << videomode_res.Height
212 << "x" << videomode_depth << std::endl;
215 std::cout << _("Active video mode (WxHxD):") << std::endl;
216 videomode_res = videomode_list->getDesktopResolution();
217 videomode_depth = videomode_list->getDesktopDepth();
218 std::cout << videomode_res.Width << "x" << videomode_res.Height << "x"
219 << videomode_depth << std::endl;
225 return videomode_list != NULL;
228 void RenderingEngine::cleanupMeshCache()
230 auto mesh_cache = m_device->getSceneManager()->getMeshCache();
231 while (mesh_cache->getMeshCount() != 0) {
232 if (scene::IAnimatedMesh *mesh = mesh_cache->getMeshByIndex(0))
233 m_rendering_engine->get_mesh_cache()->removeMesh(mesh);
237 bool RenderingEngine::setupTopLevelWindow(const std::string &name)
239 // FIXME: It would make more sense for there to be a switch of some
240 // sort here that would call the correct toplevel setup methods for
241 // the environment Minetest is running in.
243 /* Setting Xorg properties for the top level window */
244 setupTopLevelXorgWindow(name);
246 /* Setting general properties for the top level window */
247 verbosestream << "Client: Configuring general top level"
248 << " window properties"
250 bool result = setWindowIcon();
255 void RenderingEngine::setupTopLevelXorgWindow(const std::string &name)
258 const video::SExposedVideoData exposedData = driver->getExposedVideoData();
260 Display *x11_dpl = reinterpret_cast<Display *>(exposedData.OpenGLLinux.X11Display);
261 if (x11_dpl == NULL) {
262 warningstream << "Client: Could not find X11 Display in ExposedVideoData"
267 verbosestream << "Client: Configuring X11-specific top level"
268 << " window properties"
272 Window x11_win = reinterpret_cast<Window>(exposedData.OpenGLLinux.X11Window);
274 // Set application name and class hints. For now name and class are the same.
275 XClassHint *classhint = XAllocClassHint();
276 classhint->res_name = const_cast<char *>(name.c_str());
277 classhint->res_class = const_cast<char *>(name.c_str());
279 XSetClassHint(x11_dpl, x11_win, classhint);
282 // FIXME: In the future WMNormalHints should be set ... e.g see the
283 // gtk/gdk code (gdk/x11/gdksurface-x11.c) for the setup_top_level
284 // method. But for now (as it would require some significant changes)
285 // leave the code as is.
287 // The following is borrowed from the above gdk source for setting top
288 // level windows. The source indicates and the Xlib docs suggest that
289 // this will set the WM_CLIENT_MACHINE and WM_LOCAL_NAME. This will not
290 // set the WM_CLIENT_MACHINE to a Fully Qualified Domain Name (FQDN) which is
291 // required by the Extended Window Manager Hints (EWMH) spec when setting
292 // the _NET_WM_PID (see further down) but running Minetest in an env
293 // where the window manager is on another machine from Minetest (therefore
294 // making the PID useless) is not expected to be a problem. Further
295 // more, using gtk/gdk as the model it would seem that not using a FQDN is
296 // not an issue for modern Xorg window managers.
298 verbosestream << "Client: Setting Xorg window manager Properties"
301 XSetWMProperties (x11_dpl, x11_win, NULL, NULL, NULL, 0, NULL, NULL, NULL);
303 // Set the _NET_WM_PID window property according to the EWMH spec. _NET_WM_PID
304 // (in conjunction with WM_CLIENT_MACHINE) can be used by window managers to
305 // force a shutdown of an application if it doesn't respond to the destroy
308 verbosestream << "Client: Setting Xorg _NET_WM_PID extened window manager property"
311 Atom NET_WM_PID = XInternAtom(x11_dpl, "_NET_WM_PID", false);
313 pid_t pid = getpid();
315 XChangeProperty(x11_dpl, x11_win, NET_WM_PID,
316 XA_CARDINAL, 32, PropModeReplace,
317 reinterpret_cast<unsigned char *>(&pid),1);
319 // Set the WM_CLIENT_LEADER window property here. Minetest has only one
320 // window and that window will always be the leader.
322 verbosestream << "Client: Setting Xorg WM_CLIENT_LEADER property"
325 Atom WM_CLIENT_LEADER = XInternAtom(x11_dpl, "WM_CLIENT_LEADER", false);
327 XChangeProperty (x11_dpl, x11_win, WM_CLIENT_LEADER,
328 XA_WINDOW, 32, PropModeReplace,
329 reinterpret_cast<unsigned char *>(&x11_win), 1);
334 static bool getWindowHandle(irr::video::IVideoDriver *driver, HWND &hWnd)
336 const video::SExposedVideoData exposedData = driver->getExposedVideoData();
338 switch (driver->getDriverType()) {
339 #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9
340 case video::EDT_DIRECT3D8:
341 hWnd = reinterpret_cast<HWND>(exposedData.D3D8.HWnd);
344 case video::EDT_DIRECT3D9:
345 hWnd = reinterpret_cast<HWND>(exposedData.D3D9.HWnd);
348 case video::EDT_OGLES1:
349 case video::EDT_OGLES2:
351 case video::EDT_OPENGL:
352 hWnd = reinterpret_cast<HWND>(exposedData.OpenGLWin32.HWnd);
362 bool RenderingEngine::setWindowIcon()
364 #if defined(XORG_USED)
366 return setXorgWindowIconFromPath(
367 porting::path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png");
369 // We have semi-support for reading in-place data if we are
370 // compiled with RUN_IN_PLACE. Don't break with this and
371 // also try the path_share location.
372 return setXorgWindowIconFromPath(
373 ICON_DIR "/hicolor/128x128/apps/" PROJECT_NAME ".png") ||
374 setXorgWindowIconFromPath(porting::path_share + "/misc/" PROJECT_NAME
375 "-xorg-icon-128.png");
377 #elif defined(_WIN32)
378 HWND hWnd; // Window handle
379 if (!getWindowHandle(driver, hWnd))
382 // Load the ICON from resource file
383 const HICON hicon = LoadIcon(GetModuleHandle(NULL),
384 MAKEINTRESOURCE(130) // The ID of the ICON defined in
389 SendMessage(hWnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(hicon));
390 SendMessage(hWnd, WM_SETICON, ICON_SMALL,
391 reinterpret_cast<LPARAM>(hicon));
400 bool RenderingEngine::setXorgWindowIconFromPath(const std::string &icon_file)
404 video::IImageLoader *image_loader = NULL;
405 u32 cnt = driver->getImageLoaderCount();
406 for (u32 i = 0; i < cnt; i++) {
407 if (driver->getImageLoader(i)->isALoadableFileExtension(
408 icon_file.c_str())) {
409 image_loader = driver->getImageLoader(i);
415 warningstream << "Could not find image loader for file '" << icon_file
420 io::IReadFile *icon_f =
421 m_device->getFileSystem()->createAndOpenFile(icon_file.c_str());
424 warningstream << "Could not load icon file '" << icon_file << "'"
429 video::IImage *img = image_loader->loadImage(icon_f);
432 warningstream << "Could not load icon file '" << icon_file << "'"
438 u32 height = img->getDimension().Height;
439 u32 width = img->getDimension().Width;
441 size_t icon_buffer_len = 2 + height * width;
442 long *icon_buffer = new long[icon_buffer_len];
444 icon_buffer[0] = width;
445 icon_buffer[1] = height;
447 for (u32 x = 0; x < width; x++) {
448 for (u32 y = 0; y < height; y++) {
449 video::SColor col = img->getPixel(x, y);
451 pixel_val |= (u8)col.getAlpha() << 24;
452 pixel_val |= (u8)col.getRed() << 16;
453 pixel_val |= (u8)col.getGreen() << 8;
454 pixel_val |= (u8)col.getBlue();
455 icon_buffer[2 + x + y * width] = pixel_val;
462 const video::SExposedVideoData &video_data = driver->getExposedVideoData();
464 Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display;
466 if (x11_dpl == NULL) {
467 warningstream << "Could not find x11 display for setting its icon."
469 delete[] icon_buffer;
473 Window x11_win = (Window)video_data.OpenGLLinux.X11Window;
475 Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False);
476 Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False);
477 XChangeProperty(x11_dpl, x11_win, net_wm_icon, cardinal, 32, PropModeReplace,
478 (const unsigned char *)icon_buffer, icon_buffer_len);
480 delete[] icon_buffer;
487 Draws a screen with a single text on it.
488 Text will be removed when the screen is drawn the next time.
489 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
491 void RenderingEngine::_draw_load_screen(const std::wstring &text,
492 gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime,
493 int percent, bool clouds)
495 v2u32 screensize = RenderingEngine::get_instance()->getWindowSize();
497 v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight());
498 v2s32 center(screensize.X / 2, screensize.Y / 2);
499 core::rect<s32> textrect(center - textsize / 2, center + textsize / 2);
501 gui::IGUIStaticText *guitext =
502 guienv->addStaticText(text.c_str(), textrect, false, false);
503 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
505 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
506 if (cloud_menu_background) {
507 g_menuclouds->step(dtime * 3);
508 g_menuclouds->render();
509 get_video_driver()->beginScene(
510 true, true, video::SColor(255, 140, 186, 250));
511 g_menucloudsmgr->drawAll();
513 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
516 if ((percent >= 0) && (percent <= 100)) {
517 video::ITexture *progress_img = tsrc->getTexture("progress_bar.png");
518 video::ITexture *progress_img_bg =
519 tsrc->getTexture("progress_bar_bg.png");
521 if (progress_img && progress_img_bg) {
523 const core::dimension2d<u32> &img_size =
524 progress_img_bg->getSize();
525 u32 imgW = rangelim(img_size.Width, 200, 600);
526 u32 imgH = rangelim(img_size.Height, 24, 72);
528 const core::dimension2d<u32> img_size(256, 48);
529 float imgRatio = (float)img_size.Height / img_size.Width;
530 u32 imgW = screensize.X / 2.2f;
531 u32 imgH = floor(imgW * imgRatio);
533 v2s32 img_pos((screensize.X - imgW) / 2,
534 (screensize.Y - imgH) / 2);
536 draw2DImageFilterScaled(get_video_driver(), progress_img_bg,
537 core::rect<s32>(img_pos.X, img_pos.Y,
540 core::rect<s32>(0, 0, img_size.Width,
544 draw2DImageFilterScaled(get_video_driver(), progress_img,
545 core::rect<s32>(img_pos.X, img_pos.Y,
546 img_pos.X + (percent * imgW) / 100,
548 core::rect<s32>(0, 0,
549 (percent * img_size.Width) / 100,
556 get_video_driver()->endScene();
561 Draws the menu scene including (optional) cloud background.
563 void RenderingEngine::_draw_menu_scene(gui::IGUIEnvironment *guienv,
564 float dtime, bool clouds)
566 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
567 if (cloud_menu_background) {
568 g_menuclouds->step(dtime * 3);
569 g_menuclouds->render();
570 get_video_driver()->beginScene(
571 true, true, video::SColor(255, 140, 186, 250));
572 g_menucloudsmgr->drawAll();
574 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
577 get_video_driver()->endScene();
580 std::vector<core::vector3d<u32>> RenderingEngine::getSupportedVideoModes()
582 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
583 sanity_check(nulldevice);
585 std::vector<core::vector3d<u32>> mlist;
586 video::IVideoModeList *modelist = nulldevice->getVideoModeList();
588 s32 num_modes = modelist->getVideoModeCount();
589 for (s32 i = 0; i != num_modes; i++) {
590 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
591 u32 mode_depth = (u32)modelist->getVideoModeDepth(i);
592 mlist.emplace_back(mode_res.Width, mode_res.Height, mode_depth);
599 std::vector<irr::video::E_DRIVER_TYPE> RenderingEngine::getSupportedVideoDrivers()
601 std::vector<irr::video::E_DRIVER_TYPE> drivers;
603 for (int i = 0; i != irr::video::EDT_COUNT; i++) {
604 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
605 drivers.push_back((irr::video::E_DRIVER_TYPE)i);
611 void RenderingEngine::_initialize(Client *client, Hud *hud)
613 const std::string &draw_mode = g_settings->get("3d_mode");
614 core.reset(createRenderingCore(draw_mode, m_device, client, hud));
618 void RenderingEngine::_finalize()
623 void RenderingEngine::_draw_scene(video::SColor skycolor, bool show_hud,
624 bool show_minimap, bool draw_wield_tool, bool draw_crosshair)
626 core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair);
629 const char *RenderingEngine::getVideoDriverName(irr::video::E_DRIVER_TYPE type)
631 static const char *driver_ids[] = {
642 return driver_ids[type];
645 const char *RenderingEngine::getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
647 static const char *driver_names[] = {
658 return driver_names[type];
662 #if defined(XORG_USED)
664 static float calcDisplayDensity()
666 const char *current_display = getenv("DISPLAY");
668 if (current_display != NULL) {
669 Display *x11display = XOpenDisplay(current_display);
671 if (x11display != NULL) {
673 int dh = DisplayHeight(x11display, 0);
674 int dw = DisplayWidth(x11display, 0);
675 int dh_mm = DisplayHeightMM(x11display, 0);
676 int dw_mm = DisplayWidthMM(x11display, 0);
677 XCloseDisplay(x11display);
679 if (dh_mm != 0 && dw_mm != 0) {
680 float dpi_height = floor(dh / (dh_mm * 0.039370) + 0.5);
681 float dpi_width = floor(dw / (dw_mm * 0.039370) + 0.5);
682 return std::max(dpi_height, dpi_width) / 96.0;
687 /* return manually specified dpi */
688 return g_settings->getFloat("screen_dpi") / 96.0;
691 float RenderingEngine::getDisplayDensity()
693 static float cached_display_density = calcDisplayDensity();
694 return cached_display_density;
697 #elif defined(_WIN32)
700 static float calcDisplayDensity(irr::video::IVideoDriver *driver)
703 if (getWindowHandle(driver, hWnd)) {
704 HDC hdc = GetDC(hWnd);
705 float dpi = GetDeviceCaps(hdc, LOGPIXELSX);
706 ReleaseDC(hWnd, hdc);
710 /* return manually specified dpi */
711 return g_settings->getFloat("screen_dpi") / 96.0f;
714 float RenderingEngine::getDisplayDensity()
716 static bool cached = false;
717 static float display_density;
719 display_density = calcDisplayDensity(get_video_driver());
722 return display_density;
727 float RenderingEngine::getDisplayDensity()
729 return g_settings->getFloat("screen_dpi") / 96.0;
734 v2u32 RenderingEngine::getDisplaySize()
736 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
738 core::dimension2d<u32> deskres =
739 nulldevice->getVideoModeList()->getDesktopResolution();
746 float RenderingEngine::getDisplayDensity()
748 return porting::getDisplayDensity();
751 v2u32 RenderingEngine::getDisplaySize()
753 return porting::getDisplaySize();
755 #endif // __ANDROID__