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>
55 RenderingEngine *RenderingEngine::s_singleton = nullptr;
58 static gui::GUISkin* createSkin(gui::IGUIEnvironment *environment,
59 gui::EGUI_SKIN_TYPE type, video::IVideoDriver *driver)
61 gui::GUISkin* skin = new gui::GUISkin(type, driver);
63 gui::IGUIFont* builtinfont = environment->getBuiltInFont();
64 gui::IGUIFontBitmap* bitfont = 0;
65 if (builtinfont && builtinfont->getType() == gui::EGFT_BITMAP)
66 bitfont = (gui::IGUIFontBitmap*)builtinfont;
68 gui::IGUISpriteBank* bank = 0;
69 skin->setFont(builtinfont);
72 bank = bitfont->getSpriteBank();
74 skin->setSpriteBank(bank);
80 RenderingEngine::RenderingEngine(IEventReceiver *receiver)
82 sanity_check(!s_singleton);
84 // Resolution selection
85 bool fullscreen = g_settings->getBool("fullscreen");
86 u16 screen_w = g_settings->getU16("screen_w");
87 u16 screen_h = g_settings->getU16("screen_h");
90 bool vsync = g_settings->getBool("vsync");
91 u16 bits = g_settings->getU16("fullscreen_bpp");
92 u16 fsaa = g_settings->getU16("fsaa");
94 // stereo buffer required for pageflip stereo
95 bool stereo_buffer = g_settings->get("3d_mode") == "pageflip";
98 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
99 const std::string &driverstring = g_settings->get("video_driver");
100 std::vector<video::E_DRIVER_TYPE> drivers =
101 RenderingEngine::getSupportedVideoDrivers();
103 for (i = 0; i != drivers.size(); i++) {
104 if (!strcasecmp(driverstring.c_str(),
105 RenderingEngine::getVideoDriverName(drivers[i]))) {
106 driverType = drivers[i];
110 if (i == drivers.size()) {
111 errorstream << "Invalid video_driver specified; "
112 "defaulting to opengl"
116 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
117 params.DriverType = driverType;
118 params.WindowSize = core::dimension2d<u32>(screen_w, screen_h);
120 params.AntiAlias = fsaa;
121 params.Fullscreen = fullscreen;
122 params.Stencilbuffer = false;
123 params.Stereobuffer = stereo_buffer;
124 params.Vsync = vsync;
125 params.EventReceiver = receiver;
126 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
127 params.ZBufferBits = 24;
130 params.PrivateData = porting::app_global;
131 params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM + "media" +
132 DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
136 m_device = createDeviceEx(params);
137 driver = m_device->getVideoDriver();
141 auto skin = createSkin(m_device->getGUIEnvironment(),
142 gui::EGST_WINDOWS_METALLIC, driver);
143 m_device->getGUIEnvironment()->setSkin(skin);
147 RenderingEngine::~RenderingEngine()
151 s_singleton = nullptr;
154 v2u32 RenderingEngine::getWindowSize() const
157 return core->getVirtualSize();
158 return m_device->getVideoDriver()->getScreenSize();
161 void RenderingEngine::setResizable(bool resize)
163 m_device->setResizable(resize);
166 bool RenderingEngine::print_video_modes()
168 IrrlichtDevice *nulldevice;
170 bool vsync = g_settings->getBool("vsync");
171 u16 fsaa = g_settings->getU16("fsaa");
172 MyEventReceiver *receiver = new MyEventReceiver();
174 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
175 params.DriverType = video::EDT_NULL;
176 params.WindowSize = core::dimension2d<u32>(640, 480);
178 params.AntiAlias = fsaa;
179 params.Fullscreen = false;
180 params.Stencilbuffer = false;
181 params.Vsync = vsync;
182 params.EventReceiver = receiver;
183 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
185 nulldevice = createDeviceEx(params);
192 std::cout << _("Available video modes (WxHxD):") << std::endl;
194 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
196 if (videomode_list != NULL) {
197 s32 videomode_count = videomode_list->getVideoModeCount();
198 core::dimension2d<u32> videomode_res;
200 for (s32 i = 0; i < videomode_count; ++i) {
201 videomode_res = videomode_list->getVideoModeResolution(i);
202 videomode_depth = videomode_list->getVideoModeDepth(i);
203 std::cout << videomode_res.Width << "x" << videomode_res.Height
204 << "x" << videomode_depth << std::endl;
207 std::cout << _("Active video mode (WxHxD):") << std::endl;
208 videomode_res = videomode_list->getDesktopResolution();
209 videomode_depth = videomode_list->getDesktopDepth();
210 std::cout << videomode_res.Width << "x" << videomode_res.Height << "x"
211 << videomode_depth << std::endl;
217 return videomode_list != NULL;
220 bool RenderingEngine::setupTopLevelWindow(const std::string &name)
222 // FIXME: It would make more sense for there to be a switch of some
223 // sort here that would call the correct toplevel setup methods for
224 // the environment Minetest is running in but for now not deviating
225 // from the original pattern.
227 /* Setting Xorg properties for the top level window */
228 setupTopLevelXorgWindow(name);
229 /* Done with Xorg properties */
231 /* Setting general properties for the top level window */
232 verbosestream << "Client: Configuring general top level"
233 << " window properties"
236 bool result = setWindowIcon();
238 verbosestream << "Client: Finished configuring general top level"
239 << " window properties"
241 /* Done with general properties */
243 // FIXME: setWindowIcon returns a bool result but it is unused.
244 // For now continue to return this result.
248 void RenderingEngine::setupTopLevelXorgWindow(const std::string &name)
251 const video::SExposedVideoData exposedData = driver->getExposedVideoData();
253 Display *x11_dpl = reinterpret_cast<Display *>(exposedData.OpenGLLinux.X11Display);
254 if (x11_dpl == NULL) {
255 warningstream << "Client: Could not find X11 Display in ExposedVideoData"
260 verbosestream << "Client: Configuring Xorg specific top level"
261 << " window properties"
265 Window x11_win = reinterpret_cast<Window>(exposedData.OpenGLLinux.X11Window);
267 // Set application name and class hints. For now name and class are the same.
268 XClassHint *classhint = XAllocClassHint();
269 classhint->res_name = const_cast<char *>(name.c_str());
270 classhint->res_class = const_cast<char *>(name.c_str());
272 XSetClassHint(x11_dpl, x11_win, classhint);
275 // FIXME: In the future WMNormalHints should be set ... e.g see the
276 // gtk/gdk code (gdk/x11/gdksurface-x11.c) for the setup_top_level
277 // method. But for now (as it would require some significant changes)
278 // leave the code as is.
280 // The following is borrowed from the above gdk source for setting top
281 // level windows. The source indicates and the Xlib docs suggest that
282 // this will set the WM_CLIENT_MACHINE and WM_LOCAL_NAME. This will not
283 // set the WM_CLIENT_MACHINE to a Fully Qualified Domain Name (FQDN) which is
284 // required by the Extended Window Manager Hints (EWMH) spec when setting
285 // the _NET_WM_PID (see further down) but running Minetest in an env
286 // where the window manager is on another machine from Minetest (therefore
287 // making the PID useless) is not expected to be a problem. Further
288 // more, using gtk/gdk as the model it would seem that not using a FQDN is
289 // not an issue for modern Xorg window managers.
291 verbosestream << "Client: Setting Xorg window manager Properties"
294 XSetWMProperties (x11_dpl, x11_win, NULL, NULL, NULL, 0, NULL, NULL, NULL);
296 // Set the _NET_WM_PID window property according to the EWMH spec. _NET_WM_PID
297 // (in conjunction with WM_CLIENT_MACHINE) can be used by window managers to
298 // force a shutdown of an application if it doesn't respond to the destroy
301 verbosestream << "Client: Setting Xorg _NET_WM_PID extened window manager property"
304 Atom NET_WM_PID = XInternAtom(x11_dpl, "_NET_WM_PID", false);
306 pid_t pid = getpid();
307 infostream << "Client: PID is '" << static_cast<long>(pid) << "'"
310 XChangeProperty(x11_dpl, x11_win, NET_WM_PID,
311 XA_CARDINAL, 32, PropModeReplace,
312 reinterpret_cast<unsigned char *>(&pid),1);
314 // Set the WM_CLIENT_LEADER window property here. Minetest has only one
315 // window and that window will always be the leader.
317 verbosestream << "Client: Setting Xorg WM_CLIENT_LEADER property"
320 Atom WM_CLIENT_LEADER = XInternAtom(x11_dpl, "WM_CLIENT_LEADER", false);
322 XChangeProperty (x11_dpl, x11_win, WM_CLIENT_LEADER,
323 XA_WINDOW, 32, PropModeReplace,
324 reinterpret_cast<unsigned char *>(&x11_win), 1);
326 verbosestream << "Client: Finished configuring Xorg specific top level"
327 << " window properties"
333 bool RenderingEngine::setWindowIcon()
335 #if defined(XORG_USED)
337 return setXorgWindowIconFromPath(
338 porting::path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png");
340 // We have semi-support for reading in-place data if we are
341 // compiled with RUN_IN_PLACE. Don't break with this and
342 // also try the path_share location.
343 return setXorgWindowIconFromPath(
344 ICON_DIR "/hicolor/128x128/apps/" PROJECT_NAME ".png") ||
345 setXorgWindowIconFromPath(porting::path_share + "/misc/" PROJECT_NAME
346 "-xorg-icon-128.png");
348 #elif defined(_WIN32)
349 const video::SExposedVideoData exposedData = driver->getExposedVideoData();
350 HWND hWnd; // Window handle
352 switch (driver->getDriverType()) {
353 case video::EDT_DIRECT3D8:
354 hWnd = reinterpret_cast<HWND>(exposedData.D3D8.HWnd);
356 case video::EDT_DIRECT3D9:
357 hWnd = reinterpret_cast<HWND>(exposedData.D3D9.HWnd);
359 case video::EDT_OPENGL:
360 hWnd = reinterpret_cast<HWND>(exposedData.OpenGLWin32.HWnd);
366 // Load the ICON from resource file
367 const HICON hicon = LoadIcon(GetModuleHandle(NULL),
368 MAKEINTRESOURCE(130) // The ID of the ICON defined in
373 SendMessage(hWnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(hicon));
374 SendMessage(hWnd, WM_SETICON, ICON_SMALL,
375 reinterpret_cast<LPARAM>(hicon));
384 bool RenderingEngine::setXorgWindowIconFromPath(const std::string &icon_file)
388 video::IImageLoader *image_loader = NULL;
389 u32 cnt = driver->getImageLoaderCount();
390 for (u32 i = 0; i < cnt; i++) {
391 if (driver->getImageLoader(i)->isALoadableFileExtension(
392 icon_file.c_str())) {
393 image_loader = driver->getImageLoader(i);
399 warningstream << "Could not find image loader for file '" << icon_file
404 io::IReadFile *icon_f =
405 m_device->getFileSystem()->createAndOpenFile(icon_file.c_str());
408 warningstream << "Could not load icon file '" << icon_file << "'"
413 video::IImage *img = image_loader->loadImage(icon_f);
416 warningstream << "Could not load icon file '" << icon_file << "'"
422 u32 height = img->getDimension().Height;
423 u32 width = img->getDimension().Width;
425 size_t icon_buffer_len = 2 + height * width;
426 long *icon_buffer = new long[icon_buffer_len];
428 icon_buffer[0] = width;
429 icon_buffer[1] = height;
431 for (u32 x = 0; x < width; x++) {
432 for (u32 y = 0; y < height; y++) {
433 video::SColor col = img->getPixel(x, y);
435 pixel_val |= (u8)col.getAlpha() << 24;
436 pixel_val |= (u8)col.getRed() << 16;
437 pixel_val |= (u8)col.getGreen() << 8;
438 pixel_val |= (u8)col.getBlue();
439 icon_buffer[2 + x + y * width] = pixel_val;
446 const video::SExposedVideoData &video_data = driver->getExposedVideoData();
448 Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display;
450 if (x11_dpl == NULL) {
451 warningstream << "Could not find x11 display for setting its icon."
453 delete[] icon_buffer;
457 Window x11_win = (Window)video_data.OpenGLLinux.X11Window;
459 Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False);
460 Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False);
461 XChangeProperty(x11_dpl, x11_win, net_wm_icon, cardinal, 32, PropModeReplace,
462 (const unsigned char *)icon_buffer, icon_buffer_len);
464 delete[] icon_buffer;
471 Draws a screen with a single text on it.
472 Text will be removed when the screen is drawn the next time.
473 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
475 void RenderingEngine::_draw_load_screen(const std::wstring &text,
476 gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime,
477 int percent, bool clouds)
479 v2u32 screensize = RenderingEngine::get_instance()->getWindowSize();
481 v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight());
482 v2s32 center(screensize.X / 2, screensize.Y / 2);
483 core::rect<s32> textrect(center - textsize / 2, center + textsize / 2);
485 gui::IGUIStaticText *guitext =
486 guienv->addStaticText(text.c_str(), textrect, false, false);
487 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
489 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
490 if (cloud_menu_background) {
491 g_menuclouds->step(dtime * 3);
492 g_menuclouds->render();
493 get_video_driver()->beginScene(
494 true, true, video::SColor(255, 140, 186, 250));
495 g_menucloudsmgr->drawAll();
497 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
500 if ((percent >= 0) && (percent <= 100)) {
501 video::ITexture *progress_img = tsrc->getTexture("progress_bar.png");
502 video::ITexture *progress_img_bg =
503 tsrc->getTexture("progress_bar_bg.png");
505 if (progress_img && progress_img_bg) {
507 const core::dimension2d<u32> &img_size =
508 progress_img_bg->getSize();
509 u32 imgW = rangelim(img_size.Width, 200, 600);
510 u32 imgH = rangelim(img_size.Height, 24, 72);
512 const core::dimension2d<u32> img_size(256, 48);
513 float imgRatio = (float)img_size.Height / img_size.Width;
514 u32 imgW = screensize.X / 2.2f;
515 u32 imgH = floor(imgW * imgRatio);
517 v2s32 img_pos((screensize.X - imgW) / 2,
518 (screensize.Y - imgH) / 2);
520 draw2DImageFilterScaled(get_video_driver(), progress_img_bg,
521 core::rect<s32>(img_pos.X, img_pos.Y,
524 core::rect<s32>(0, 0, img_size.Width,
528 draw2DImageFilterScaled(get_video_driver(), progress_img,
529 core::rect<s32>(img_pos.X, img_pos.Y,
530 img_pos.X + (percent * imgW) / 100,
532 core::rect<s32>(0, 0,
533 (percent * img_size.Width) / 100,
540 get_video_driver()->endScene();
545 Draws the menu scene including (optional) cloud background.
547 void RenderingEngine::_draw_menu_scene(gui::IGUIEnvironment *guienv,
548 float dtime, bool clouds)
550 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
551 if (cloud_menu_background) {
552 g_menuclouds->step(dtime * 3);
553 g_menuclouds->render();
554 get_video_driver()->beginScene(
555 true, true, video::SColor(255, 140, 186, 250));
556 g_menucloudsmgr->drawAll();
558 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
561 get_video_driver()->endScene();
564 std::vector<core::vector3d<u32>> RenderingEngine::getSupportedVideoModes()
566 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
567 sanity_check(nulldevice);
569 std::vector<core::vector3d<u32>> mlist;
570 video::IVideoModeList *modelist = nulldevice->getVideoModeList();
572 s32 num_modes = modelist->getVideoModeCount();
573 for (s32 i = 0; i != num_modes; i++) {
574 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
575 u32 mode_depth = (u32)modelist->getVideoModeDepth(i);
576 mlist.emplace_back(mode_res.Width, mode_res.Height, mode_depth);
583 std::vector<irr::video::E_DRIVER_TYPE> RenderingEngine::getSupportedVideoDrivers()
585 std::vector<irr::video::E_DRIVER_TYPE> drivers;
587 for (int i = 0; i != irr::video::EDT_COUNT; i++) {
588 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
589 drivers.push_back((irr::video::E_DRIVER_TYPE)i);
595 void RenderingEngine::_initialize(Client *client, Hud *hud)
597 const std::string &draw_mode = g_settings->get("3d_mode");
598 core.reset(createRenderingCore(draw_mode, m_device, client, hud));
602 void RenderingEngine::_finalize()
607 void RenderingEngine::_draw_scene(video::SColor skycolor, bool show_hud,
608 bool show_minimap, bool draw_wield_tool, bool draw_crosshair)
610 core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair);
613 const char *RenderingEngine::getVideoDriverName(irr::video::E_DRIVER_TYPE type)
615 static const char *driver_ids[] = {
626 return driver_ids[type];
629 const char *RenderingEngine::getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
631 static const char *driver_names[] = {
642 return driver_names[type];
648 static float calcDisplayDensity()
650 const char *current_display = getenv("DISPLAY");
652 if (current_display != NULL) {
653 Display *x11display = XOpenDisplay(current_display);
655 if (x11display != NULL) {
657 int dh = DisplayHeight(x11display, 0);
658 int dw = DisplayWidth(x11display, 0);
659 int dh_mm = DisplayHeightMM(x11display, 0);
660 int dw_mm = DisplayWidthMM(x11display, 0);
661 XCloseDisplay(x11display);
663 if (dh_mm != 0 && dw_mm != 0) {
664 float dpi_height = floor(dh / (dh_mm * 0.039370) + 0.5);
665 float dpi_width = floor(dw / (dw_mm * 0.039370) + 0.5);
666 return std::max(dpi_height, dpi_width) / 96.0;
671 /* return manually specified dpi */
672 return g_settings->getFloat("screen_dpi") / 96.0;
675 float RenderingEngine::getDisplayDensity()
677 static float cached_display_density = calcDisplayDensity();
678 return cached_display_density;
682 float RenderingEngine::getDisplayDensity()
684 return g_settings->getFloat("screen_dpi") / 96.0;
688 v2u32 RenderingEngine::getDisplaySize()
690 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
692 core::dimension2d<u32> deskres =
693 nulldevice->getVideoModeList()->getDesktopResolution();
700 float RenderingEngine::getDisplayDensity()
702 return porting::getDisplayDensity();
705 v2u32 RenderingEngine::getDisplaySize()
707 return porting::getDisplaySize();
709 #endif // __ANDROID__