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>
22 #include "fontengine.h"
25 #include "util/numeric.h"
26 #include "guiscalingfilter.h"
27 #include "localplayer.h"
28 #include "client/hud.h"
31 #include "clientmap.h"
32 #include "renderingengine.h"
33 #include "render/core.h"
34 #include "render/factory.h"
35 #include "inputhandler.h"
37 #include "../gui/guiSkin.h"
39 #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__) && \
40 !defined(SERVER) && !defined(__HAIKU__)
45 #include <X11/Xutil.h>
46 #include <X11/Xatom.h>
58 RenderingEngine *RenderingEngine::s_singleton = nullptr;
61 static gui::GUISkin *createSkin(gui::IGUIEnvironment *environment,
62 gui::EGUI_SKIN_TYPE type, video::IVideoDriver *driver)
64 gui::GUISkin *skin = new gui::GUISkin(type, driver);
66 gui::IGUIFont *builtinfont = environment->getBuiltInFont();
67 gui::IGUIFontBitmap *bitfont = nullptr;
68 if (builtinfont && builtinfont->getType() == gui::EGFT_BITMAP)
69 bitfont = (gui::IGUIFontBitmap*)builtinfont;
71 gui::IGUISpriteBank *bank = 0;
72 skin->setFont(builtinfont);
75 bank = bitfont->getSpriteBank();
77 skin->setSpriteBank(bank);
83 RenderingEngine::RenderingEngine(IEventReceiver *receiver)
85 sanity_check(!s_singleton);
87 // Resolution selection
88 bool fullscreen = g_settings->getBool("fullscreen");
89 u16 screen_w = g_settings->getU16("screen_w");
90 u16 screen_h = g_settings->getU16("screen_h");
93 bool vsync = g_settings->getBool("vsync");
94 u16 fsaa = g_settings->getU16("fsaa");
96 // stereo buffer required for pageflip stereo
97 bool stereo_buffer = g_settings->get("3d_mode") == "pageflip";
100 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
101 const std::string &driverstring = g_settings->get("video_driver");
102 std::vector<video::E_DRIVER_TYPE> drivers =
103 RenderingEngine::getSupportedVideoDrivers();
105 for (i = 0; i != drivers.size(); i++) {
106 if (!strcasecmp(driverstring.c_str(),
107 RenderingEngine::getVideoDriverInfo(drivers[i]).name.c_str())) {
108 driverType = drivers[i];
112 if (i == drivers.size()) {
113 errorstream << "Invalid video_driver specified; "
114 "defaulting to opengl"
118 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
120 params.LoggingLevel = irr::ELL_DEBUG;
121 params.DriverType = driverType;
122 params.WindowSize = core::dimension2d<u32>(screen_w, screen_h);
123 params.AntiAlias = fsaa;
124 params.Fullscreen = fullscreen;
125 params.Stencilbuffer = false;
126 params.Stereobuffer = stereo_buffer;
127 params.Vsync = vsync;
128 params.EventReceiver = receiver;
129 params.HighPrecisionFPU = true;
131 params.PrivateData = porting::app_global;
134 // there is no standardized path for these on desktop
135 std::string rel_path = std::string("client") + DIR_DELIM
136 + "shaders" + DIR_DELIM + "Irrlicht";
137 params.OGLES2ShaderPath = (porting::path_share + DIR_DELIM + rel_path + DIR_DELIM).c_str();
140 m_device = createDeviceEx(params);
141 driver = m_device->getVideoDriver();
145 auto skin = createSkin(m_device->getGUIEnvironment(),
146 gui::EGST_WINDOWS_METALLIC, driver);
147 m_device->getGUIEnvironment()->setSkin(skin);
151 RenderingEngine::~RenderingEngine()
154 m_device->closeDevice();
155 s_singleton = nullptr;
158 v2u32 RenderingEngine::_getWindowSize() const
161 return core->getVirtualSize();
162 return m_device->getVideoDriver()->getScreenSize();
165 void RenderingEngine::setResizable(bool resize)
167 m_device->setResizable(resize);
170 void RenderingEngine::removeMesh(const scene::IMesh* mesh)
172 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
175 void RenderingEngine::cleanupMeshCache()
177 auto mesh_cache = m_device->getSceneManager()->getMeshCache();
178 while (mesh_cache->getMeshCount() != 0) {
179 if (scene::IAnimatedMesh *mesh = mesh_cache->getMeshByIndex(0))
180 mesh_cache->removeMesh(mesh);
184 bool RenderingEngine::setupTopLevelWindow(const std::string &name)
186 // FIXME: It would make more sense for there to be a switch of some
187 // sort here that would call the correct toplevel setup methods for
188 // the environment Minetest is running in.
190 /* Setting Xorg properties for the top level window */
191 setupTopLevelXorgWindow(name);
193 /* Setting general properties for the top level window */
194 verbosestream << "Client: Configuring general top level"
195 << " window properties"
197 bool result = setWindowIcon();
202 void RenderingEngine::setupTopLevelXorgWindow(const std::string &name)
205 const video::SExposedVideoData exposedData = driver->getExposedVideoData();
207 Display *x11_dpl = reinterpret_cast<Display *>(exposedData.OpenGLLinux.X11Display);
208 if (x11_dpl == NULL) {
209 warningstream << "Client: Could not find X11 Display in ExposedVideoData"
214 verbosestream << "Client: Configuring X11-specific top level"
215 << " window properties"
219 Window x11_win = reinterpret_cast<Window>(exposedData.OpenGLLinux.X11Window);
221 // Set application name and class hints. For now name and class are the same.
222 XClassHint *classhint = XAllocClassHint();
223 classhint->res_name = const_cast<char *>(name.c_str());
224 classhint->res_class = const_cast<char *>(name.c_str());
226 XSetClassHint(x11_dpl, x11_win, classhint);
229 // FIXME: In the future WMNormalHints should be set ... e.g see the
230 // gtk/gdk code (gdk/x11/gdksurface-x11.c) for the setup_top_level
231 // method. But for now (as it would require some significant changes)
232 // leave the code as is.
234 // The following is borrowed from the above gdk source for setting top
235 // level windows. The source indicates and the Xlib docs suggest that
236 // this will set the WM_CLIENT_MACHINE and WM_LOCAL_NAME. This will not
237 // set the WM_CLIENT_MACHINE to a Fully Qualified Domain Name (FQDN) which is
238 // required by the Extended Window Manager Hints (EWMH) spec when setting
239 // the _NET_WM_PID (see further down) but running Minetest in an env
240 // where the window manager is on another machine from Minetest (therefore
241 // making the PID useless) is not expected to be a problem. Further
242 // more, using gtk/gdk as the model it would seem that not using a FQDN is
243 // not an issue for modern Xorg window managers.
245 verbosestream << "Client: Setting Xorg window manager Properties"
248 XSetWMProperties (x11_dpl, x11_win, NULL, NULL, NULL, 0, NULL, NULL, NULL);
250 // Set the _NET_WM_PID window property according to the EWMH spec. _NET_WM_PID
251 // (in conjunction with WM_CLIENT_MACHINE) can be used by window managers to
252 // force a shutdown of an application if it doesn't respond to the destroy
255 verbosestream << "Client: Setting Xorg _NET_WM_PID extended window manager property"
258 Atom NET_WM_PID = XInternAtom(x11_dpl, "_NET_WM_PID", false);
260 pid_t pid = getpid();
262 XChangeProperty(x11_dpl, x11_win, NET_WM_PID,
263 XA_CARDINAL, 32, PropModeReplace,
264 reinterpret_cast<unsigned char *>(&pid),1);
266 // Set the WM_CLIENT_LEADER window property here. Minetest has only one
267 // window and that window will always be the leader.
269 verbosestream << "Client: Setting Xorg WM_CLIENT_LEADER property"
272 Atom WM_CLIENT_LEADER = XInternAtom(x11_dpl, "WM_CLIENT_LEADER", false);
274 XChangeProperty (x11_dpl, x11_win, WM_CLIENT_LEADER,
275 XA_WINDOW, 32, PropModeReplace,
276 reinterpret_cast<unsigned char *>(&x11_win), 1);
281 static bool getWindowHandle(irr::video::IVideoDriver *driver, HWND &hWnd)
283 const video::SExposedVideoData exposedData = driver->getExposedVideoData();
285 switch (driver->getDriverType()) {
287 case video::EDT_OGLES1:
288 case video::EDT_OGLES2:
290 case video::EDT_OPENGL:
291 hWnd = reinterpret_cast<HWND>(exposedData.OpenGLWin32.HWnd);
301 bool RenderingEngine::setWindowIcon()
303 #if defined(XORG_USED)
305 return setXorgWindowIconFromPath(
306 porting::path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png");
308 // We have semi-support for reading in-place data if we are
309 // compiled with RUN_IN_PLACE. Don't break with this and
310 // also try the path_share location.
311 return setXorgWindowIconFromPath(
312 ICON_DIR "/hicolor/128x128/apps/" PROJECT_NAME ".png") ||
313 setXorgWindowIconFromPath(porting::path_share + "/misc/" PROJECT_NAME
314 "-xorg-icon-128.png");
316 #elif defined(_WIN32)
317 HWND hWnd; // Window handle
318 if (!getWindowHandle(driver, hWnd))
321 // Load the ICON from resource file
322 const HICON hicon = LoadIcon(GetModuleHandle(NULL),
323 MAKEINTRESOURCE(130) // The ID of the ICON defined in
328 SendMessage(hWnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(hicon));
329 SendMessage(hWnd, WM_SETICON, ICON_SMALL,
330 reinterpret_cast<LPARAM>(hicon));
339 bool RenderingEngine::setXorgWindowIconFromPath(const std::string &icon_file)
343 video::IImageLoader *image_loader = NULL;
344 u32 cnt = driver->getImageLoaderCount();
345 for (u32 i = 0; i < cnt; i++) {
346 if (driver->getImageLoader(i)->isALoadableFileExtension(
347 icon_file.c_str())) {
348 image_loader = driver->getImageLoader(i);
354 warningstream << "Could not find image loader for file '" << icon_file
359 io::IReadFile *icon_f =
360 m_device->getFileSystem()->createAndOpenFile(icon_file.c_str());
363 warningstream << "Could not load icon file '" << icon_file << "'"
368 video::IImage *img = image_loader->loadImage(icon_f);
371 warningstream << "Could not load icon file '" << icon_file << "'"
377 u32 height = img->getDimension().Height;
378 u32 width = img->getDimension().Width;
380 size_t icon_buffer_len = 2 + height * width;
381 long *icon_buffer = new long[icon_buffer_len];
383 icon_buffer[0] = width;
384 icon_buffer[1] = height;
386 for (u32 x = 0; x < width; x++) {
387 for (u32 y = 0; y < height; y++) {
388 video::SColor col = img->getPixel(x, y);
390 pixel_val |= (u8)col.getAlpha() << 24;
391 pixel_val |= (u8)col.getRed() << 16;
392 pixel_val |= (u8)col.getGreen() << 8;
393 pixel_val |= (u8)col.getBlue();
394 icon_buffer[2 + x + y * width] = pixel_val;
401 const video::SExposedVideoData &video_data = driver->getExposedVideoData();
403 Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display;
405 if (x11_dpl == NULL) {
406 warningstream << "Could not find x11 display for setting its icon."
408 delete[] icon_buffer;
412 Window x11_win = (Window)video_data.OpenGLLinux.X11Window;
414 Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False);
415 Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False);
416 XChangeProperty(x11_dpl, x11_win, net_wm_icon, cardinal, 32, PropModeReplace,
417 (const unsigned char *)icon_buffer, icon_buffer_len);
419 delete[] icon_buffer;
426 Draws a screen with a single text on it.
427 Text will be removed when the screen is drawn the next time.
428 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
430 void RenderingEngine::draw_load_screen(const std::wstring &text,
431 gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime,
432 int percent, bool clouds)
434 v2u32 screensize = getWindowSize();
436 v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight());
437 v2s32 center(screensize.X / 2, screensize.Y / 2);
438 core::rect<s32> textrect(center - textsize / 2, center + textsize / 2);
440 gui::IGUIStaticText *guitext =
441 guienv->addStaticText(text.c_str(), textrect, false, false);
442 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
444 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
445 if (cloud_menu_background) {
446 g_menuclouds->step(dtime * 3);
447 g_menuclouds->render();
448 get_video_driver()->beginScene(
449 true, true, video::SColor(255, 140, 186, 250));
450 g_menucloudsmgr->drawAll();
452 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
455 if ((percent >= 0) && (percent <= 100)) {
456 video::ITexture *progress_img = tsrc->getTexture("progress_bar.png");
457 video::ITexture *progress_img_bg =
458 tsrc->getTexture("progress_bar_bg.png");
460 if (progress_img && progress_img_bg) {
462 const core::dimension2d<u32> &img_size =
463 progress_img_bg->getSize();
464 u32 imgW = rangelim(img_size.Width, 200, 600);
465 u32 imgH = rangelim(img_size.Height, 24, 72);
467 const core::dimension2d<u32> img_size(256, 48);
468 float imgRatio = (float)img_size.Height / img_size.Width;
469 u32 imgW = screensize.X / 2.2f;
470 u32 imgH = floor(imgW * imgRatio);
472 v2s32 img_pos((screensize.X - imgW) / 2,
473 (screensize.Y - imgH) / 2);
475 draw2DImageFilterScaled(get_video_driver(), progress_img_bg,
476 core::rect<s32>(img_pos.X, img_pos.Y,
479 core::rect<s32>(0, 0, img_size.Width,
483 draw2DImageFilterScaled(get_video_driver(), progress_img,
484 core::rect<s32>(img_pos.X, img_pos.Y,
485 img_pos.X + (percent * imgW) / 100,
487 core::rect<s32>(0, 0,
488 (percent * img_size.Width) / 100,
495 get_video_driver()->endScene();
500 Draws the menu scene including (optional) cloud background.
502 void RenderingEngine::draw_menu_scene(gui::IGUIEnvironment *guienv,
503 float dtime, bool clouds)
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 get_video_driver()->endScene();
519 std::vector<irr::video::E_DRIVER_TYPE> RenderingEngine::getSupportedVideoDrivers()
521 // Only check these drivers.
522 // We do not support software and D3D in any capacity.
523 static const irr::video::E_DRIVER_TYPE glDrivers[4] = {
524 irr::video::EDT_NULL,
525 irr::video::EDT_OPENGL,
526 irr::video::EDT_OGLES1,
527 irr::video::EDT_OGLES2,
529 std::vector<irr::video::E_DRIVER_TYPE> drivers;
531 for (int i = 0; i < 4; i++) {
532 if (irr::IrrlichtDevice::isDriverSupported(glDrivers[i]))
533 drivers.push_back(glDrivers[i]);
539 void RenderingEngine::initialize(Client *client, Hud *hud)
541 const std::string &draw_mode = g_settings->get("3d_mode");
542 core.reset(createRenderingCore(draw_mode, m_device, client, hud));
546 void RenderingEngine::finalize()
551 void RenderingEngine::draw_scene(video::SColor skycolor, bool show_hud,
552 bool show_minimap, bool draw_wield_tool, bool draw_crosshair)
554 core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair);
557 const VideoDriverInfo &RenderingEngine::getVideoDriverInfo(irr::video::E_DRIVER_TYPE type)
559 static const std::unordered_map<int, VideoDriverInfo> driver_info_map = {
560 {(int)video::EDT_NULL, {"null", "NULL Driver"}},
561 {(int)video::EDT_OPENGL, {"opengl", "OpenGL"}},
562 {(int)video::EDT_OGLES1, {"ogles1", "OpenGL ES1"}},
563 {(int)video::EDT_OGLES2, {"ogles2", "OpenGL ES2"}},
565 return driver_info_map.at((int)type);
569 #if defined(XORG_USED)
571 static float calcDisplayDensity()
573 const char *current_display = getenv("DISPLAY");
575 if (current_display != NULL) {
576 Display *x11display = XOpenDisplay(current_display);
578 if (x11display != NULL) {
580 int dh = DisplayHeight(x11display, 0);
581 int dw = DisplayWidth(x11display, 0);
582 int dh_mm = DisplayHeightMM(x11display, 0);
583 int dw_mm = DisplayWidthMM(x11display, 0);
584 XCloseDisplay(x11display);
586 if (dh_mm != 0 && dw_mm != 0) {
587 float dpi_height = floor(dh / (dh_mm * 0.039370) + 0.5);
588 float dpi_width = floor(dw / (dw_mm * 0.039370) + 0.5);
589 return std::max(dpi_height, dpi_width) / 96.0;
594 /* return manually specified dpi */
595 return g_settings->getFloat("screen_dpi") / 96.0;
598 float RenderingEngine::getDisplayDensity()
600 static float cached_display_density = calcDisplayDensity();
601 return cached_display_density * g_settings->getFloat("display_density_factor");
604 #elif defined(_WIN32)
607 static float calcDisplayDensity(irr::video::IVideoDriver *driver)
610 if (getWindowHandle(driver, hWnd)) {
611 HDC hdc = GetDC(hWnd);
612 float dpi = GetDeviceCaps(hdc, LOGPIXELSX);
613 ReleaseDC(hWnd, hdc);
617 /* return manually specified dpi */
618 return g_settings->getFloat("screen_dpi") / 96.0f;
621 float RenderingEngine::getDisplayDensity()
623 static bool cached = false;
624 static float display_density;
626 display_density = calcDisplayDensity(get_video_driver());
629 return display_density * g_settings->getFloat("display_density_factor");
634 float RenderingEngine::getDisplayDensity()
636 return (g_settings->getFloat("screen_dpi") / 96.0) * g_settings->getFloat("display_density_factor");
641 v2u32 RenderingEngine::getDisplaySize()
643 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
645 core::dimension2d<u32> deskres =
646 nulldevice->getVideoModeList()->getDesktopResolution();
653 float RenderingEngine::getDisplayDensity()
655 return porting::getDisplayDensity();
658 v2u32 RenderingEngine::getDisplaySize()
660 return porting::getDisplaySize();
662 #endif // __ANDROID__