code
string
repo_name
string
path
string
language
string
license
string
size
int64
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 numzero, Lobachevskiy Vitaliy <numzer0@yandex.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "factory.h" #include <stdexcept> #include "plain.h" #include "anaglyph.h" #include "interlaced.h" #include "pageflip.h" #include "sidebyside.h" RenderingCore *createRenderingCore(const std::string &stereo_mode, IrrlichtDevice *device, Client *client, Hud *hud) { if (stereo_mode == "none") return new RenderingCorePlain(device, client, hud); if (stereo_mode == "anaglyph") return new RenderingCoreAnaglyph(device, client, hud); if (stereo_mode == "interlaced") return new RenderingCoreInterlaced(device, client, hud); #ifdef STEREO_PAGEFLIP_SUPPORTED if (stereo_mode == "pageflip") return new RenderingCorePageflip(device, client, hud); #endif if (stereo_mode == "sidebyside") return new RenderingCoreSideBySide(device, client, hud); if (stereo_mode == "topbottom") return new RenderingCoreSideBySide(device, client, hud, true); if (stereo_mode == "crossview") return new RenderingCoreSideBySide(device, client, hud, false, true); throw std::invalid_argument("Invalid rendering mode: " + stereo_mode); }
pgimeno/minetest
src/client/render/factory.cpp
C++
mit
1,897
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 numzero, Lobachevskiy Vitaliy <numzer0@yandex.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <string> #include "core.h" RenderingCore *createRenderingCore(const std::string &stereo_mode, IrrlichtDevice *device, Client *client, Hud *hud);
pgimeno/minetest
src/client/render/factory.h
C++
mit
1,016
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 numzero, Lobachevskiy Vitaliy <numzer0@yandex.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "interlaced.h" #include "client/client.h" #include "client/shader.h" #include "client/tile.h" RenderingCoreInterlaced::RenderingCoreInterlaced( IrrlichtDevice *_device, Client *_client, Hud *_hud) : RenderingCoreStereo(_device, _client, _hud) { initMaterial(); } void RenderingCoreInterlaced::initMaterial() { IShaderSource *s = client->getShaderSource(); mat.UseMipMaps = false; mat.ZBuffer = false; mat.ZWriteEnable = false; u32 shader = s->getShader("3d_interlaced_merge", TILE_MATERIAL_BASIC, 0); mat.MaterialType = s->getShaderInfo(shader).material; for (int k = 0; k < 3; ++k) { mat.TextureLayer[k].AnisotropicFilter = false; mat.TextureLayer[k].BilinearFilter = false; mat.TextureLayer[k].TrilinearFilter = false; mat.TextureLayer[k].TextureWrapU = video::ETC_CLAMP_TO_EDGE; mat.TextureLayer[k].TextureWrapV = video::ETC_CLAMP_TO_EDGE; } } void RenderingCoreInterlaced::initTextures() { v2u32 image_size{screensize.X, screensize.Y / 2}; left = driver->addRenderTargetTexture( image_size, "3d_render_left", video::ECF_A8R8G8B8); right = driver->addRenderTargetTexture( image_size, "3d_render_right", video::ECF_A8R8G8B8); mask = driver->addTexture(screensize, "3d_render_mask", video::ECF_A8R8G8B8); initMask(); mat.TextureLayer[0].Texture = left; mat.TextureLayer[1].Texture = right; mat.TextureLayer[2].Texture = mask; } void RenderingCoreInterlaced::clearTextures() { driver->removeTexture(left); driver->removeTexture(right); driver->removeTexture(mask); } void RenderingCoreInterlaced::initMask() { u8 *data = reinterpret_cast<u8 *>(mask->lock()); for (u32 j = 0; j < screensize.Y; j++) { u8 val = j % 2 ? 0xff : 0x00; memset(data, val, 4 * screensize.X); data += 4 * screensize.X; } mask->unlock(); } void RenderingCoreInterlaced::drawAll() { renderBothImages(); merge(); drawHUD(); } void RenderingCoreInterlaced::merge() { static const video::S3DVertex vertices[4] = { video::S3DVertex(1.0, -1.0, 0.0, 0.0, 0.0, -1.0, video::SColor(255, 0, 255, 255), 1.0, 0.0), video::S3DVertex(-1.0, -1.0, 0.0, 0.0, 0.0, -1.0, video::SColor(255, 255, 0, 255), 0.0, 0.0), video::S3DVertex(-1.0, 1.0, 0.0, 0.0, 0.0, -1.0, video::SColor(255, 255, 255, 0), 0.0, 1.0), video::S3DVertex(1.0, 1.0, 0.0, 0.0, 0.0, -1.0, video::SColor(255, 255, 255, 255), 1.0, 1.0), }; static const u16 indices[6] = {0, 1, 2, 2, 3, 0}; driver->setMaterial(mat); driver->drawVertexPrimitiveList(&vertices, 4, &indices, 2); } void RenderingCoreInterlaced::useEye(bool _right) { driver->setRenderTarget(_right ? right : left, true, true, skycolor); RenderingCoreStereo::useEye(_right); } void RenderingCoreInterlaced::resetEye() { driver->setRenderTarget(nullptr, false, false, skycolor); RenderingCoreStereo::resetEye(); }
pgimeno/minetest
src/client/render/interlaced.cpp
C++
mit
3,664
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 numzero, Lobachevskiy Vitaliy <numzer0@yandex.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "stereo.h" class RenderingCoreInterlaced : public RenderingCoreStereo { protected: video::ITexture *left = nullptr; video::ITexture *right = nullptr; video::ITexture *mask = nullptr; video::SMaterial mat; void initMaterial(); void initTextures() override; void clearTextures() override; void initMask(); void useEye(bool right) override; void resetEye() override; void merge(); public: RenderingCoreInterlaced(IrrlichtDevice *_device, Client *_client, Hud *_hud); void drawAll() override; };
pgimeno/minetest
src/client/render/interlaced.h
C++
mit
1,389
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 numzero, Lobachevskiy Vitaliy <numzer0@yandex.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "pageflip.h" #ifdef STEREO_PAGEFLIP_SUPPORTED void RenderingCorePageflip::initTextures() { hud = driver->addRenderTargetTexture( screensize, "3d_render_hud", video::ECF_A8R8G8B8); } void RenderingCorePageflip::clearTextures() { driver->removeTexture(hud); } void RenderingCorePageflip::drawAll() { driver->setRenderTarget(hud, true, true, video::SColor(0, 0, 0, 0)); drawHUD(); driver->setRenderTarget(nullptr, false, false, skycolor); renderBothImages(); } void RenderingCorePageflip::useEye(bool _right) { driver->setRenderTarget(_right ? video::ERT_STEREO_RIGHT_BUFFER : video::ERT_STEREO_LEFT_BUFFER, true, true, skycolor); RenderingCoreStereo::useEye(_right); } void RenderingCorePageflip::resetEye() { driver->draw2DImage(hud, v2s32(0, 0)); driver->setRenderTarget(video::ERT_FRAME_BUFFER, false, false, skycolor); RenderingCoreStereo::resetEye(); } #endif // STEREO_PAGEFLIP_SUPPORTED
pgimeno/minetest
src/client/render/pageflip.cpp
C++
mit
1,795
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 numzero, Lobachevskiy Vitaliy <numzer0@yandex.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "stereo.h" // The support is absent in 1.9.0 (dropped in r5068) #if (IRRLICHT_VERSION_MAJOR == 1) && (IRRLICHT_VERSION_MINOR <= 8) #define STEREO_PAGEFLIP_SUPPORTED class RenderingCorePageflip : public RenderingCoreStereo { protected: video::ITexture *hud = nullptr; void initTextures() override; void clearTextures() override; void useEye(bool right) override; void resetEye() override; public: using RenderingCoreStereo::RenderingCoreStereo; void drawAll() override; }; #endif
pgimeno/minetest
src/client/render/pageflip.h
C++
mit
1,372
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 numzero, Lobachevskiy Vitaliy <numzer0@yandex.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "plain.h" #include "settings.h" inline u32 scaledown(u32 coef, u32 size) { return (size + coef - 1) / coef; } RenderingCorePlain::RenderingCorePlain( IrrlichtDevice *_device, Client *_client, Hud *_hud) : RenderingCore(_device, _client, _hud) { scale = g_settings->getU16("undersampling"); } void RenderingCorePlain::initTextures() { if (!scale) return; v2u32 size{scaledown(scale, screensize.X), scaledown(scale, screensize.Y)}; lowres = driver->addRenderTargetTexture( size, "render_lowres", video::ECF_A8R8G8B8); } void RenderingCorePlain::clearTextures() { if (!scale) return; driver->removeTexture(lowres); } void RenderingCorePlain::beforeDraw() { if (!scale) return; driver->setRenderTarget(lowres, true, true, skycolor); } void RenderingCorePlain::upscale() { if (!scale) return; driver->setRenderTarget(0, true, true); v2u32 size{scaledown(scale, screensize.X), scaledown(scale, screensize.Y)}; v2u32 dest_size{scale * size.X, scale * size.Y}; driver->draw2DImage(lowres, core::rect<s32>(0, 0, dest_size.X, dest_size.Y), core::rect<s32>(0, 0, size.X, size.Y)); } void RenderingCorePlain::drawAll() { draw3D(); drawPostFx(); upscale(); drawHUD(); }
pgimeno/minetest
src/client/render/plain.cpp
C++
mit
2,066
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 numzero, Lobachevskiy Vitaliy <numzer0@yandex.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "core.h" class RenderingCorePlain : public RenderingCore { protected: int scale = 0; video::ITexture *lowres = nullptr; void initTextures() override; void clearTextures() override; void beforeDraw() override; void upscale(); public: RenderingCorePlain(IrrlichtDevice *_device, Client *_client, Hud *_hud); void drawAll() override; };
pgimeno/minetest
src/client/render/plain.h
C++
mit
1,226
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 numzero, Lobachevskiy Vitaliy <numzer0@yandex.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "sidebyside.h" #include <ICameraSceneNode.h> #include "client/hud.h" RenderingCoreSideBySide::RenderingCoreSideBySide( IrrlichtDevice *_device, Client *_client, Hud *_hud, bool _horizontal, bool _flipped) : RenderingCoreStereo(_device, _client, _hud), horizontal(_horizontal), flipped(_flipped) { } void RenderingCoreSideBySide::initTextures() { if (horizontal) { image_size = {screensize.X, screensize.Y / 2}; rpos = v2s32(0, screensize.Y / 2); } else { image_size = {screensize.X / 2, screensize.Y}; rpos = v2s32(screensize.X / 2, 0); } virtual_size = image_size; left = driver->addRenderTargetTexture( image_size, "3d_render_left", video::ECF_A8R8G8B8); right = driver->addRenderTargetTexture( image_size, "3d_render_right", video::ECF_A8R8G8B8); } void RenderingCoreSideBySide::clearTextures() { driver->removeTexture(left); driver->removeTexture(right); } void RenderingCoreSideBySide::drawAll() { driver->OnResize(image_size); // HACK to make GUI smaller renderBothImages(); driver->OnResize(screensize); driver->draw2DImage(left, {}); driver->draw2DImage(right, rpos); } void RenderingCoreSideBySide::useEye(bool _right) { driver->setRenderTarget(_right ? right : left, true, true, skycolor); RenderingCoreStereo::useEye(_right ^ flipped); } void RenderingCoreSideBySide::resetEye() { hud->resizeHotbar(); drawHUD(); driver->setRenderTarget(nullptr, false, false, skycolor); RenderingCoreStereo::resetEye(); }
pgimeno/minetest
src/client/render/sidebyside.cpp
C++
mit
2,326
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 numzero, Lobachevskiy Vitaliy <numzer0@yandex.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "stereo.h" class RenderingCoreSideBySide : public RenderingCoreStereo { protected: video::ITexture *left = nullptr; video::ITexture *right = nullptr; bool horizontal = false; bool flipped = false; core::dimension2du image_size; v2s32 rpos; void initTextures() override; void clearTextures() override; void useEye(bool right) override; void resetEye() override; public: RenderingCoreSideBySide(IrrlichtDevice *_device, Client *_client, Hud *_hud, bool _horizontal = false, bool _flipped = false); void drawAll() override; };
pgimeno/minetest
src/client/render/sidebyside.h
C++
mit
1,423
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 numzero, Lobachevskiy Vitaliy <numzer0@yandex.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stereo.h" #include "client/camera.h" #include "constants.h" #include "settings.h" RenderingCoreStereo::RenderingCoreStereo( IrrlichtDevice *_device, Client *_client, Hud *_hud) : RenderingCore(_device, _client, _hud) { eye_offset = BS * g_settings->getFloat("3d_paralax_strength"); } void RenderingCoreStereo::beforeDraw() { cam = camera->getCameraNode(); base_transform = cam->getRelativeTransformation(); } void RenderingCoreStereo::useEye(bool right) { core::matrix4 move; move.setTranslation( core::vector3df(right ? eye_offset : -eye_offset, 0.0f, 0.0f)); cam->setPosition((base_transform * move).getTranslation()); } void RenderingCoreStereo::resetEye() { cam->setPosition(base_transform.getTranslation()); } void RenderingCoreStereo::renderBothImages() { useEye(false); draw3D(); resetEye(); useEye(true); draw3D(); resetEye(); }
pgimeno/minetest
src/client/render/stereo.cpp
C++
mit
1,729
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 numzero, Lobachevskiy Vitaliy <numzer0@yandex.ru> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "core.h" class RenderingCoreStereo : public RenderingCore { protected: scene::ICameraSceneNode *cam; core::matrix4 base_transform; float eye_offset; void beforeDraw() override; virtual void useEye(bool right); virtual void resetEye(); void renderBothImages(); public: RenderingCoreStereo(IrrlichtDevice *_device, Client *_client, Hud *_hud); };
pgimeno/minetest
src/client/render/stereo.h
C++
mit
1,237
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <IrrlichtDevice.h> #include <irrlicht.h> #include "fontengine.h" #include "client.h" #include "clouds.h" #include "util/numeric.h" #include "guiscalingfilter.h" #include "localplayer.h" #include "client/hud.h" #include "camera.h" #include "minimap.h" #include "clientmap.h" #include "renderingengine.h" #include "render/core.h" #include "render/factory.h" #include "inputhandler.h" #include "gettext.h" #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__) && \ !defined(SERVER) && !defined(__HAIKU__) #define XORG_USED #endif #ifdef XORG_USED #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #endif #ifdef __ANDROID__ #include "filesys.h" #endif RenderingEngine *RenderingEngine::s_singleton = nullptr; RenderingEngine::RenderingEngine(IEventReceiver *receiver) { sanity_check(!s_singleton); // Resolution selection bool fullscreen = g_settings->getBool("fullscreen"); u16 screen_w = g_settings->getU16("screen_w"); u16 screen_h = g_settings->getU16("screen_h"); // bpp, fsaa, vsync bool vsync = g_settings->getBool("vsync"); u16 bits = g_settings->getU16("fullscreen_bpp"); u16 fsaa = g_settings->getU16("fsaa"); // stereo buffer required for pageflip stereo bool stereo_buffer = g_settings->get("3d_mode") == "pageflip"; // Determine driver video::E_DRIVER_TYPE driverType = video::EDT_OPENGL; const std::string &driverstring = g_settings->get("video_driver"); std::vector<video::E_DRIVER_TYPE> drivers = RenderingEngine::getSupportedVideoDrivers(); u32 i; for (i = 0; i != drivers.size(); i++) { if (!strcasecmp(driverstring.c_str(), RenderingEngine::getVideoDriverName(drivers[i]))) { driverType = drivers[i]; break; } } if (i == drivers.size()) { errorstream << "Invalid video_driver specified; " "defaulting to opengl" << std::endl; } SIrrlichtCreationParameters params = SIrrlichtCreationParameters(); params.DriverType = driverType; params.WindowSize = core::dimension2d<u32>(screen_w, screen_h); params.Bits = bits; params.AntiAlias = fsaa; params.Fullscreen = fullscreen; params.Stencilbuffer = false; params.Stereobuffer = stereo_buffer; params.Vsync = vsync; params.EventReceiver = receiver; params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu"); params.ZBufferBits = 24; #ifdef __ANDROID__ // clang-format off params.PrivateData = porting::app_global; params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM + "media" + DIR_DELIM + "Shaders" + DIR_DELIM).c_str(); // clang-format on #endif m_device = createDeviceEx(params); driver = m_device->getVideoDriver(); s_singleton = this; } RenderingEngine::~RenderingEngine() { core.reset(); m_device->drop(); s_singleton = nullptr; } v2u32 RenderingEngine::getWindowSize() const { if (core) return core->getVirtualSize(); return m_device->getVideoDriver()->getScreenSize(); } void RenderingEngine::setResizable(bool resize) { m_device->setResizable(resize); } bool RenderingEngine::print_video_modes() { IrrlichtDevice *nulldevice; bool vsync = g_settings->getBool("vsync"); u16 fsaa = g_settings->getU16("fsaa"); MyEventReceiver *receiver = new MyEventReceiver(); SIrrlichtCreationParameters params = SIrrlichtCreationParameters(); params.DriverType = video::EDT_NULL; params.WindowSize = core::dimension2d<u32>(640, 480); params.Bits = 24; params.AntiAlias = fsaa; params.Fullscreen = false; params.Stencilbuffer = false; params.Vsync = vsync; params.EventReceiver = receiver; params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu"); nulldevice = createDeviceEx(params); if (!nulldevice) { delete receiver; return false; } std::cout << _("Available video modes (WxHxD):") << std::endl; video::IVideoModeList *videomode_list = nulldevice->getVideoModeList(); if (videomode_list != NULL) { s32 videomode_count = videomode_list->getVideoModeCount(); core::dimension2d<u32> videomode_res; s32 videomode_depth; for (s32 i = 0; i < videomode_count; ++i) { videomode_res = videomode_list->getVideoModeResolution(i); videomode_depth = videomode_list->getVideoModeDepth(i); std::cout << videomode_res.Width << "x" << videomode_res.Height << "x" << videomode_depth << std::endl; } std::cout << _("Active video mode (WxHxD):") << std::endl; videomode_res = videomode_list->getDesktopResolution(); videomode_depth = videomode_list->getDesktopDepth(); std::cout << videomode_res.Width << "x" << videomode_res.Height << "x" << videomode_depth << std::endl; } nulldevice->drop(); delete receiver; return videomode_list != NULL; } bool RenderingEngine::setupTopLevelWindow(const std::string &name) { // FIXME: It would make more sense for there to be a switch of some // sort here that would call the correct toplevel setup methods for // the environment Minetest is running in but for now not deviating // from the original pattern. /* Setting Xorg properties for the top level window */ setupTopLevelXorgWindow(name); /* Done with Xorg properties */ /* Setting general properties for the top level window */ verbosestream << "Client: Configuring general top level" << " window properties" << std::endl; bool result = setWindowIcon(); verbosestream << "Client: Finished configuring general top level" << " window properties" << std::endl; /* Done with general properties */ // FIXME: setWindowIcon returns a bool result but it is unused. // For now continue to return this result. return result; } void RenderingEngine::setupTopLevelXorgWindow(const std::string &name) { #ifdef XORG_USED const video::SExposedVideoData exposedData = driver->getExposedVideoData(); Display *x11_dpl = reinterpret_cast<Display *>(exposedData.OpenGLLinux.X11Display); if (x11_dpl == NULL) { warningstream << "Client: Could not find X11 Display in ExposedVideoData" << std::endl; return; } verbosestream << "Client: Configuring Xorg specific top level" << " window properties" << std::endl; Window x11_win = reinterpret_cast<Window>(exposedData.OpenGLLinux.X11Window); // Set application name and class hints. For now name and class are the same. XClassHint *classhint = XAllocClassHint(); classhint->res_name = const_cast<char *>(name.c_str()); classhint->res_class = const_cast<char *>(name.c_str()); XSetClassHint(x11_dpl, x11_win, classhint); XFree(classhint); // FIXME: In the future WMNormalHints should be set ... e.g see the // gtk/gdk code (gdk/x11/gdksurface-x11.c) for the setup_top_level // method. But for now (as it would require some significant changes) // leave the code as is. // The following is borrowed from the above gdk source for setting top // level windows. The source indicates and the Xlib docs suggest that // this will set the WM_CLIENT_MACHINE and WM_LOCAL_NAME. This will not // set the WM_CLIENT_MACHINE to a Fully Qualified Domain Name (FQDN) which is // required by the Extended Window Manager Hints (EWMH) spec when setting // the _NET_WM_PID (see further down) but running Minetest in an env // where the window manager is on another machine from Minetest (therefore // making the PID useless) is not expected to be a problem. Further // more, using gtk/gdk as the model it would seem that not using a FQDN is // not an issue for modern Xorg window managers. verbosestream << "Client: Setting Xorg window manager Properties" << std::endl; XSetWMProperties (x11_dpl, x11_win, NULL, NULL, NULL, 0, NULL, NULL, NULL); // Set the _NET_WM_PID window property according to the EWMH spec. _NET_WM_PID // (in conjunction with WM_CLIENT_MACHINE) can be used by window managers to // force a shutdown of an application if it doesn't respond to the destroy // window message. verbosestream << "Client: Setting Xorg _NET_WM_PID extened window manager property" << std::endl; Atom NET_WM_PID = XInternAtom(x11_dpl, "_NET_WM_PID", false); pid_t pid = getpid(); infostream << "Client: PID is '" << static_cast<long>(pid) << "'" << std::endl; XChangeProperty(x11_dpl, x11_win, NET_WM_PID, XA_CARDINAL, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&pid),1); // Set the WM_CLIENT_LEADER window property here. Minetest has only one // window and that window will always be the leader. verbosestream << "Client: Setting Xorg WM_CLIENT_LEADER property" << std::endl; Atom WM_CLIENT_LEADER = XInternAtom(x11_dpl, "WM_CLIENT_LEADER", false); XChangeProperty (x11_dpl, x11_win, WM_CLIENT_LEADER, XA_WINDOW, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&x11_win), 1); verbosestream << "Client: Finished configuring Xorg specific top level" << " window properties" << std::endl; #endif } bool RenderingEngine::setWindowIcon() { #if defined(XORG_USED) #if RUN_IN_PLACE return setXorgWindowIconFromPath( porting::path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png"); #else // We have semi-support for reading in-place data if we are // compiled with RUN_IN_PLACE. Don't break with this and // also try the path_share location. return setXorgWindowIconFromPath( ICON_DIR "/hicolor/128x128/apps/" PROJECT_NAME ".png") || setXorgWindowIconFromPath(porting::path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png"); #endif #elif defined(_WIN32) const video::SExposedVideoData exposedData = driver->getExposedVideoData(); HWND hWnd; // Window handle switch (driver->getDriverType()) { case video::EDT_DIRECT3D8: hWnd = reinterpret_cast<HWND>(exposedData.D3D8.HWnd); break; case video::EDT_DIRECT3D9: hWnd = reinterpret_cast<HWND>(exposedData.D3D9.HWnd); break; case video::EDT_OPENGL: hWnd = reinterpret_cast<HWND>(exposedData.OpenGLWin32.HWnd); break; default: return false; } // Load the ICON from resource file const HICON hicon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(130) // The ID of the ICON defined in // winresource.rc ); if (hicon) { SendMessage(hWnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(hicon)); SendMessage(hWnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(hicon)); return true; } return false; #else return false; #endif } bool RenderingEngine::setXorgWindowIconFromPath(const std::string &icon_file) { #ifdef XORG_USED video::IImageLoader *image_loader = NULL; u32 cnt = driver->getImageLoaderCount(); for (u32 i = 0; i < cnt; i++) { if (driver->getImageLoader(i)->isALoadableFileExtension( icon_file.c_str())) { image_loader = driver->getImageLoader(i); break; } } if (!image_loader) { warningstream << "Could not find image loader for file '" << icon_file << "'" << std::endl; return false; } io::IReadFile *icon_f = m_device->getFileSystem()->createAndOpenFile(icon_file.c_str()); if (!icon_f) { warningstream << "Could not load icon file '" << icon_file << "'" << std::endl; return false; } video::IImage *img = image_loader->loadImage(icon_f); if (!img) { warningstream << "Could not load icon file '" << icon_file << "'" << std::endl; icon_f->drop(); return false; } u32 height = img->getDimension().Height; u32 width = img->getDimension().Width; size_t icon_buffer_len = 2 + height * width; long *icon_buffer = new long[icon_buffer_len]; icon_buffer[0] = width; icon_buffer[1] = height; for (u32 x = 0; x < width; x++) { for (u32 y = 0; y < height; y++) { video::SColor col = img->getPixel(x, y); long pixel_val = 0; pixel_val |= (u8)col.getAlpha() << 24; pixel_val |= (u8)col.getRed() << 16; pixel_val |= (u8)col.getGreen() << 8; pixel_val |= (u8)col.getBlue(); icon_buffer[2 + x + y * width] = pixel_val; } } img->drop(); icon_f->drop(); const video::SExposedVideoData &video_data = driver->getExposedVideoData(); Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display; if (x11_dpl == NULL) { warningstream << "Could not find x11 display for setting its icon." << std::endl; delete[] icon_buffer; return false; } Window x11_win = (Window)video_data.OpenGLLinux.X11Window; Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False); Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False); XChangeProperty(x11_dpl, x11_win, net_wm_icon, cardinal, 32, PropModeReplace, (const unsigned char *)icon_buffer, icon_buffer_len); delete[] icon_buffer; #endif return true; } /* Draws a screen with a single text on it. Text will be removed when the screen is drawn the next time. Additionally, a progressbar can be drawn when percent is set between 0 and 100. */ void RenderingEngine::_draw_load_screen(const std::wstring &text, gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime, int percent, bool clouds) { v2u32 screensize = RenderingEngine::get_instance()->getWindowSize(); v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight()); v2s32 center(screensize.X / 2, screensize.Y / 2); core::rect<s32> textrect(center - textsize / 2, center + textsize / 2); gui::IGUIStaticText *guitext = guienv->addStaticText(text.c_str(), textrect, false, false); guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT); bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds"); if (cloud_menu_background) { g_menuclouds->step(dtime * 3); g_menuclouds->render(); get_video_driver()->beginScene( true, true, video::SColor(255, 140, 186, 250)); g_menucloudsmgr->drawAll(); } else get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0)); // draw progress bar if ((percent >= 0) && (percent <= 100)) { video::ITexture *progress_img = tsrc->getTexture("progress_bar.png"); video::ITexture *progress_img_bg = tsrc->getTexture("progress_bar_bg.png"); if (progress_img && progress_img_bg) { #ifndef __ANDROID__ const core::dimension2d<u32> &img_size = progress_img_bg->getSize(); u32 imgW = rangelim(img_size.Width, 200, 600); u32 imgH = rangelim(img_size.Height, 24, 72); #else const core::dimension2d<u32> img_size(256, 48); float imgRatio = (float)img_size.Height / img_size.Width; u32 imgW = screensize.X / 2.2f; u32 imgH = floor(imgW * imgRatio); #endif v2s32 img_pos((screensize.X - imgW) / 2, (screensize.Y - imgH) / 2); draw2DImageFilterScaled(get_video_driver(), progress_img_bg, core::rect<s32>(img_pos.X, img_pos.Y, img_pos.X + imgW, img_pos.Y + imgH), core::rect<s32>(0, 0, img_size.Width, img_size.Height), 0, 0, true); draw2DImageFilterScaled(get_video_driver(), progress_img, core::rect<s32>(img_pos.X, img_pos.Y, img_pos.X + (percent * imgW) / 100, img_pos.Y + imgH), core::rect<s32>(0, 0, (percent * img_size.Width) / 100, img_size.Height), 0, 0, true); } } guienv->drawAll(); get_video_driver()->endScene(); guitext->remove(); } /* Draws the menu scene including (optional) cloud background. */ void RenderingEngine::_draw_menu_scene(gui::IGUIEnvironment *guienv, float dtime, bool clouds) { bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds"); if (cloud_menu_background) { g_menuclouds->step(dtime * 3); g_menuclouds->render(); get_video_driver()->beginScene( true, true, video::SColor(255, 140, 186, 250)); g_menucloudsmgr->drawAll(); } else get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0)); guienv->drawAll(); get_video_driver()->endScene(); } std::vector<core::vector3d<u32>> RenderingEngine::getSupportedVideoModes() { IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL); sanity_check(nulldevice); std::vector<core::vector3d<u32>> mlist; video::IVideoModeList *modelist = nulldevice->getVideoModeList(); s32 num_modes = modelist->getVideoModeCount(); for (s32 i = 0; i != num_modes; i++) { core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i); u32 mode_depth = (u32)modelist->getVideoModeDepth(i); mlist.emplace_back(mode_res.Width, mode_res.Height, mode_depth); } nulldevice->drop(); return mlist; } std::vector<irr::video::E_DRIVER_TYPE> RenderingEngine::getSupportedVideoDrivers() { std::vector<irr::video::E_DRIVER_TYPE> drivers; for (int i = 0; i != irr::video::EDT_COUNT; i++) { if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i)) drivers.push_back((irr::video::E_DRIVER_TYPE)i); } return drivers; } void RenderingEngine::_initialize(Client *client, Hud *hud) { const std::string &draw_mode = g_settings->get("3d_mode"); core.reset(createRenderingCore(draw_mode, m_device, client, hud)); core->initialize(); } void RenderingEngine::_finalize() { core.reset(); } void RenderingEngine::_draw_scene(video::SColor skycolor, bool show_hud, bool show_minimap, bool draw_wield_tool, bool draw_crosshair) { core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair); } const char *RenderingEngine::getVideoDriverName(irr::video::E_DRIVER_TYPE type) { static const char *driver_ids[] = { "null", "software", "burningsvideo", "direct3d8", "direct3d9", "opengl", "ogles1", "ogles2", }; return driver_ids[type]; } const char *RenderingEngine::getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type) { static const char *driver_names[] = { "NULL Driver", "Software Renderer", "Burning's Video", "Direct3D 8", "Direct3D 9", "OpenGL", "OpenGL ES1", "OpenGL ES2", }; return driver_names[type]; } #ifndef __ANDROID__ #ifdef XORG_USED static float calcDisplayDensity() { const char *current_display = getenv("DISPLAY"); if (current_display != NULL) { Display *x11display = XOpenDisplay(current_display); if (x11display != NULL) { /* try x direct */ int dh = DisplayHeight(x11display, 0); int dw = DisplayWidth(x11display, 0); int dh_mm = DisplayHeightMM(x11display, 0); int dw_mm = DisplayWidthMM(x11display, 0); XCloseDisplay(x11display); if (dh_mm != 0 && dw_mm != 0) { float dpi_height = floor(dh / (dh_mm * 0.039370) + 0.5); float dpi_width = floor(dw / (dw_mm * 0.039370) + 0.5); return std::max(dpi_height, dpi_width) / 96.0; } } } /* return manually specified dpi */ return g_settings->getFloat("screen_dpi") / 96.0; } float RenderingEngine::getDisplayDensity() { static float cached_display_density = calcDisplayDensity(); return cached_display_density; } #else // XORG_USED float RenderingEngine::getDisplayDensity() { return g_settings->getFloat("screen_dpi") / 96.0; } #endif // XORG_USED v2u32 RenderingEngine::getDisplaySize() { IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL); core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution(); nulldevice->drop(); return deskres; } #else // __ANDROID__ float RenderingEngine::getDisplayDensity() { return porting::getDisplayDensity(); } v2u32 RenderingEngine::getDisplaySize() { return porting::getDisplaySize(); } #endif // __ANDROID__
pgimeno/minetest
src/client/renderingengine.cpp
C++
mit
19,918
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <vector> #include <memory> #include <string> #include "irrlichttypes_extrabloated.h" #include "debug.h" class ITextureSource; class Camera; class Client; class LocalPlayer; class Hud; class Minimap; class RenderingCore; class RenderingEngine { public: RenderingEngine(IEventReceiver *eventReceiver); ~RenderingEngine(); v2u32 getWindowSize() const; void setResizable(bool resize); video::IVideoDriver *getVideoDriver() { return driver; } static const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type); static const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type); static float getDisplayDensity(); static v2u32 getDisplaySize(); bool setupTopLevelWindow(const std::string &name); void setupTopLevelXorgWindow(const std::string &name); bool setWindowIcon(); bool setXorgWindowIconFromPath(const std::string &icon_file); static bool print_video_modes(); static RenderingEngine *get_instance() { return s_singleton; } static io::IFileSystem *get_filesystem() { sanity_check(s_singleton && s_singleton->m_device); return s_singleton->m_device->getFileSystem(); } static video::IVideoDriver *get_video_driver() { sanity_check(s_singleton && s_singleton->m_device); return s_singleton->m_device->getVideoDriver(); } static scene::IMeshCache *get_mesh_cache() { sanity_check(s_singleton && s_singleton->m_device); return s_singleton->m_device->getSceneManager()->getMeshCache(); } static scene::ISceneManager *get_scene_manager() { sanity_check(s_singleton && s_singleton->m_device); return s_singleton->m_device->getSceneManager(); } static irr::IrrlichtDevice *get_raw_device() { sanity_check(s_singleton && s_singleton->m_device); return s_singleton->m_device; } static u32 get_timer_time() { sanity_check(s_singleton && s_singleton->m_device && s_singleton->m_device->getTimer()); return s_singleton->m_device->getTimer()->getTime(); } static gui::IGUIEnvironment *get_gui_env() { sanity_check(s_singleton && s_singleton->m_device); return s_singleton->m_device->getGUIEnvironment(); } inline static void draw_load_screen(const std::wstring &text, gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime = 0, int percent = 0, bool clouds = true) { s_singleton->_draw_load_screen( text, guienv, tsrc, dtime, percent, clouds); } inline static void draw_menu_scene( gui::IGUIEnvironment *guienv, float dtime, bool clouds) { s_singleton->_draw_menu_scene(guienv, dtime, clouds); } inline static void draw_scene(video::SColor skycolor, bool show_hud, bool show_minimap, bool draw_wield_tool, bool draw_crosshair) { s_singleton->_draw_scene(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair); } inline static void initialize(Client *client, Hud *hud) { s_singleton->_initialize(client, hud); } inline static void finalize() { s_singleton->_finalize(); } static bool run() { sanity_check(s_singleton && s_singleton->m_device); return s_singleton->m_device->run(); } static std::vector<core::vector3d<u32>> getSupportedVideoModes(); static std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers(); private: void _draw_load_screen(const std::wstring &text, gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime = 0, int percent = 0, bool clouds = true); void _draw_menu_scene(gui::IGUIEnvironment *guienv, float dtime = 0, bool clouds = true); void _draw_scene(video::SColor skycolor, bool show_hud, bool show_minimap, bool draw_wield_tool, bool draw_crosshair); void _initialize(Client *client, Hud *hud); void _finalize(); std::unique_ptr<RenderingCore> core; irr::IrrlichtDevice *m_device = nullptr; irr::video::IVideoDriver *driver; static RenderingEngine *s_singleton; };
pgimeno/minetest
src/client/renderingengine.h
C++
mit
4,681
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013 Kahrl <kahrl@gmx.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <fstream> #include <iterator> #include "shader.h" #include "irrlichttypes_extrabloated.h" #include "debug.h" #include "filesys.h" #include "util/container.h" #include "util/thread.h" #include "settings.h" #include <ICameraSceneNode.h> #include <IGPUProgrammingServices.h> #include <IMaterialRenderer.h> #include <IMaterialRendererServices.h> #include <IShaderConstantSetCallBack.h> #include "client/renderingengine.h" #include "EShaderTypes.h" #include "log.h" #include "gamedef.h" #include "client/tile.h" /* A cache from shader name to shader path */ MutexedMap<std::string, std::string> g_shadername_to_path_cache; /* Gets the path to a shader by first checking if the file name_of_shader/filename exists in shader_path and if not, using the data path. If not found, returns "". Utilizes a thread-safe cache. */ std::string getShaderPath(const std::string &name_of_shader, const std::string &filename) { std::string combined = name_of_shader + DIR_DELIM + filename; std::string fullpath; /* Check from cache */ bool incache = g_shadername_to_path_cache.get(combined, &fullpath); if(incache) return fullpath; /* Check from shader_path */ std::string shader_path = g_settings->get("shader_path"); if (!shader_path.empty()) { std::string testpath = shader_path + DIR_DELIM + combined; if(fs::PathExists(testpath)) fullpath = testpath; } /* Check from default data directory */ if (fullpath.empty()) { std::string rel_path = std::string("client") + DIR_DELIM + "shaders" + DIR_DELIM + name_of_shader + DIR_DELIM + filename; std::string testpath = porting::path_share + DIR_DELIM + rel_path; if(fs::PathExists(testpath)) fullpath = testpath; } // Add to cache (also an empty result is cached) g_shadername_to_path_cache.set(combined, fullpath); // Finally return it return fullpath; } /* SourceShaderCache: A cache used for storing source shaders. */ class SourceShaderCache { public: void insert(const std::string &name_of_shader, const std::string &filename, const std::string &program, bool prefer_local) { std::string combined = name_of_shader + DIR_DELIM + filename; // Try to use local shader instead if asked to if(prefer_local){ std::string path = getShaderPath(name_of_shader, filename); if(!path.empty()){ std::string p = readFile(path); if (!p.empty()) { m_programs[combined] = p; return; } } } m_programs[combined] = program; } std::string get(const std::string &name_of_shader, const std::string &filename) { std::string combined = name_of_shader + DIR_DELIM + filename; StringMap::iterator n = m_programs.find(combined); if (n != m_programs.end()) return n->second; return ""; } // Primarily fetches from cache, secondarily tries to read from filesystem std::string getOrLoad(const std::string &name_of_shader, const std::string &filename) { std::string combined = name_of_shader + DIR_DELIM + filename; StringMap::iterator n = m_programs.find(combined); if (n != m_programs.end()) return n->second; std::string path = getShaderPath(name_of_shader, filename); if (path.empty()) { infostream << "SourceShaderCache::getOrLoad(): No path found for \"" << combined << "\"" << std::endl; return ""; } infostream << "SourceShaderCache::getOrLoad(): Loading path \"" << path << "\"" << std::endl; std::string p = readFile(path); if (!p.empty()) { m_programs[combined] = p; return p; } return ""; } private: StringMap m_programs; std::string readFile(const std::string &path) { std::ifstream is(path.c_str(), std::ios::binary); if(!is.is_open()) return ""; std::ostringstream tmp_os; tmp_os << is.rdbuf(); return tmp_os.str(); } }; /* ShaderCallback: Sets constants that can be used in shaders */ class ShaderCallback : public video::IShaderConstantSetCallBack { std::vector<IShaderConstantSetter*> m_setters; public: ShaderCallback(const std::vector<IShaderConstantSetterFactory *> &factories) { for (IShaderConstantSetterFactory *factory : factories) m_setters.push_back(factory->create()); } ~ShaderCallback() { for (IShaderConstantSetter *setter : m_setters) delete setter; } virtual void OnSetConstants(video::IMaterialRendererServices *services, s32 userData) { video::IVideoDriver *driver = services->getVideoDriver(); sanity_check(driver != NULL); bool is_highlevel = userData; for (IShaderConstantSetter *setter : m_setters) setter->onSetConstants(services, is_highlevel); } }; /* MainShaderConstantSetter: Set basic constants required for almost everything */ class MainShaderConstantSetter : public IShaderConstantSetter { CachedVertexShaderSetting<float, 16> m_world_view_proj; CachedVertexShaderSetting<float, 16> m_world; public: MainShaderConstantSetter() : m_world_view_proj("mWorldViewProj"), m_world("mWorld") {} ~MainShaderConstantSetter() = default; virtual void onSetConstants(video::IMaterialRendererServices *services, bool is_highlevel) { video::IVideoDriver *driver = services->getVideoDriver(); sanity_check(driver); // Set clip matrix core::matrix4 worldViewProj; worldViewProj = driver->getTransform(video::ETS_PROJECTION); worldViewProj *= driver->getTransform(video::ETS_VIEW); worldViewProj *= driver->getTransform(video::ETS_WORLD); if (is_highlevel) m_world_view_proj.set(*reinterpret_cast<float(*)[16]>(worldViewProj.pointer()), services); else services->setVertexShaderConstant(worldViewProj.pointer(), 0, 4); // Set world matrix core::matrix4 world = driver->getTransform(video::ETS_WORLD); if (is_highlevel) m_world.set(*reinterpret_cast<float(*)[16]>(world.pointer()), services); else services->setVertexShaderConstant(world.pointer(), 4, 4); } }; class MainShaderConstantSetterFactory : public IShaderConstantSetterFactory { public: virtual IShaderConstantSetter* create() { return new MainShaderConstantSetter(); } }; /* ShaderSource */ class ShaderSource : public IWritableShaderSource { public: ShaderSource(); ~ShaderSource(); /* - If shader material specified by name is found from cache, return the cached id. - Otherwise generate the shader material, add to cache and return id. The id 0 points to a null shader. Its material is EMT_SOLID. */ u32 getShaderIdDirect(const std::string &name, const u8 material_type, const u8 drawtype); /* If shader specified by the name pointed by the id doesn't exist, create it, then return id. Can be called from any thread. If called from some other thread and not found in cache, the call is queued to the main thread for processing. */ u32 getShader(const std::string &name, const u8 material_type, const u8 drawtype); ShaderInfo getShaderInfo(u32 id); // Processes queued shader requests from other threads. // Shall be called from the main thread. void processQueue(); // Insert a shader program into the cache without touching the // filesystem. Shall be called from the main thread. void insertSourceShader(const std::string &name_of_shader, const std::string &filename, const std::string &program); // Rebuild shaders from the current set of source shaders // Shall be called from the main thread. void rebuildShaders(); void addShaderConstantSetterFactory(IShaderConstantSetterFactory *setter) { m_setter_factories.push_back(setter); } private: // The id of the thread that is allowed to use irrlicht directly std::thread::id m_main_thread; // Cache of source shaders // This should be only accessed from the main thread SourceShaderCache m_sourcecache; // A shader id is index in this array. // The first position contains a dummy shader. std::vector<ShaderInfo> m_shaderinfo_cache; // The former container is behind this mutex std::mutex m_shaderinfo_cache_mutex; // Queued shader fetches (to be processed by the main thread) RequestQueue<std::string, u32, u8, u8> m_get_shader_queue; // Global constant setter factories std::vector<IShaderConstantSetterFactory *> m_setter_factories; // Shader callbacks std::vector<ShaderCallback *> m_callbacks; }; IWritableShaderSource *createShaderSource() { return new ShaderSource(); } /* Generate shader given the shader name. */ ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtype, std::vector<ShaderCallback *> &callbacks, const std::vector<IShaderConstantSetterFactory *> &setter_factories, SourceShaderCache *sourcecache); /* Load shader programs */ void load_shaders(const std::string &name, SourceShaderCache *sourcecache, video::E_DRIVER_TYPE drivertype, bool enable_shaders, std::string &vertex_program, std::string &pixel_program, std::string &geometry_program, bool &is_highlevel); ShaderSource::ShaderSource() { m_main_thread = std::this_thread::get_id(); // Add a dummy ShaderInfo as the first index, named "" m_shaderinfo_cache.emplace_back(); // Add main global constant setter addShaderConstantSetterFactory(new MainShaderConstantSetterFactory()); } ShaderSource::~ShaderSource() { for (ShaderCallback *callback : m_callbacks) { delete callback; } for (IShaderConstantSetterFactory *setter_factorie : m_setter_factories) { delete setter_factorie; } } u32 ShaderSource::getShader(const std::string &name, const u8 material_type, const u8 drawtype) { /* Get shader */ if (std::this_thread::get_id() == m_main_thread) { return getShaderIdDirect(name, material_type, drawtype); } /*errorstream<<"getShader(): Queued: name=\""<<name<<"\""<<std::endl;*/ // We're gonna ask the result to be put into here static ResultQueue<std::string, u32, u8, u8> result_queue; // Throw a request in m_get_shader_queue.add(name, 0, 0, &result_queue); /* infostream<<"Waiting for shader from main thread, name=\"" <<name<<"\""<<std::endl;*/ while(true) { GetResult<std::string, u32, u8, u8> result = result_queue.pop_frontNoEx(); if (result.key == name) { return result.item; } errorstream << "Got shader with invalid name: " << result.key << std::endl; } infostream << "getShader(): Failed" << std::endl; return 0; } /* This method generates all the shaders */ u32 ShaderSource::getShaderIdDirect(const std::string &name, const u8 material_type, const u8 drawtype) { //infostream<<"getShaderIdDirect(): name=\""<<name<<"\""<<std::endl; // Empty name means shader 0 if (name.empty()) { infostream<<"getShaderIdDirect(): name is empty"<<std::endl; return 0; } // Check if already have such instance for(u32 i=0; i<m_shaderinfo_cache.size(); i++){ ShaderInfo *info = &m_shaderinfo_cache[i]; if(info->name == name && info->material_type == material_type && info->drawtype == drawtype) return i; } /* Calling only allowed from main thread */ if (std::this_thread::get_id() != m_main_thread) { errorstream<<"ShaderSource::getShaderIdDirect() " "called not from main thread"<<std::endl; return 0; } ShaderInfo info = generate_shader(name, material_type, drawtype, m_callbacks, m_setter_factories, &m_sourcecache); /* Add shader to caches (add dummy shaders too) */ MutexAutoLock lock(m_shaderinfo_cache_mutex); u32 id = m_shaderinfo_cache.size(); m_shaderinfo_cache.push_back(info); infostream<<"getShaderIdDirect(): " <<"Returning id="<<id<<" for name \""<<name<<"\""<<std::endl; return id; } ShaderInfo ShaderSource::getShaderInfo(u32 id) { MutexAutoLock lock(m_shaderinfo_cache_mutex); if(id >= m_shaderinfo_cache.size()) return ShaderInfo(); return m_shaderinfo_cache[id]; } void ShaderSource::processQueue() { } void ShaderSource::insertSourceShader(const std::string &name_of_shader, const std::string &filename, const std::string &program) { /*infostream<<"ShaderSource::insertSourceShader(): " "name_of_shader=\""<<name_of_shader<<"\", " "filename=\""<<filename<<"\""<<std::endl;*/ sanity_check(std::this_thread::get_id() == m_main_thread); m_sourcecache.insert(name_of_shader, filename, program, true); } void ShaderSource::rebuildShaders() { MutexAutoLock lock(m_shaderinfo_cache_mutex); /*// Oh well... just clear everything, they'll load sometime. m_shaderinfo_cache.clear(); m_name_to_id.clear();*/ /* FIXME: Old shader materials can't be deleted in Irrlicht, or can they? (This would be nice to do in the destructor too) */ // Recreate shaders for (ShaderInfo &i : m_shaderinfo_cache) { ShaderInfo *info = &i; if (!info->name.empty()) { *info = generate_shader(info->name, info->material_type, info->drawtype, m_callbacks, m_setter_factories, &m_sourcecache); } } } ShaderInfo generate_shader(const std::string &name, u8 material_type, u8 drawtype, std::vector<ShaderCallback *> &callbacks, const std::vector<IShaderConstantSetterFactory *> &setter_factories, SourceShaderCache *sourcecache) { ShaderInfo shaderinfo; shaderinfo.name = name; shaderinfo.material_type = material_type; shaderinfo.drawtype = drawtype; shaderinfo.material = video::EMT_SOLID; switch (material_type) { case TILE_MATERIAL_OPAQUE: case TILE_MATERIAL_LIQUID_OPAQUE: case TILE_MATERIAL_WAVING_LIQUID_OPAQUE: shaderinfo.base_material = video::EMT_SOLID; break; case TILE_MATERIAL_ALPHA: case TILE_MATERIAL_LIQUID_TRANSPARENT: case TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT: shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL; break; case TILE_MATERIAL_BASIC: case TILE_MATERIAL_WAVING_LEAVES: case TILE_MATERIAL_WAVING_PLANTS: case TILE_MATERIAL_WAVING_LIQUID_BASIC: shaderinfo.base_material = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; break; } bool enable_shaders = g_settings->getBool("enable_shaders"); if (!enable_shaders) return shaderinfo; video::IVideoDriver *driver = RenderingEngine::get_video_driver(); video::IGPUProgrammingServices *gpu = driver->getGPUProgrammingServices(); if(!gpu){ errorstream<<"generate_shader(): " "failed to generate \""<<name<<"\", " "GPU programming not supported." <<std::endl; return shaderinfo; } // Choose shader language depending on driver type and settings // Then load shaders std::string vertex_program; std::string pixel_program; std::string geometry_program; bool is_highlevel; load_shaders(name, sourcecache, driver->getDriverType(), enable_shaders, vertex_program, pixel_program, geometry_program, is_highlevel); // Check hardware/driver support if (!vertex_program.empty() && !driver->queryFeature(video::EVDF_VERTEX_SHADER_1_1) && !driver->queryFeature(video::EVDF_ARB_VERTEX_PROGRAM_1)){ infostream<<"generate_shader(): vertex shaders disabled " "because of missing driver/hardware support." <<std::endl; vertex_program = ""; } if (!pixel_program.empty() && !driver->queryFeature(video::EVDF_PIXEL_SHADER_1_1) && !driver->queryFeature(video::EVDF_ARB_FRAGMENT_PROGRAM_1)){ infostream<<"generate_shader(): pixel shaders disabled " "because of missing driver/hardware support." <<std::endl; pixel_program = ""; } if (!geometry_program.empty() && !driver->queryFeature(video::EVDF_GEOMETRY_SHADER)){ infostream<<"generate_shader(): geometry shaders disabled " "because of missing driver/hardware support." <<std::endl; geometry_program = ""; } // If no shaders are used, don't make a separate material type if (vertex_program.empty() && pixel_program.empty() && geometry_program.empty()) return shaderinfo; // Create shaders header std::string shaders_header = "#version 120\n"; static const char* drawTypes[] = { "NDT_NORMAL", "NDT_AIRLIKE", "NDT_LIQUID", "NDT_FLOWINGLIQUID", "NDT_GLASSLIKE", "NDT_ALLFACES", "NDT_ALLFACES_OPTIONAL", "NDT_TORCHLIKE", "NDT_SIGNLIKE", "NDT_PLANTLIKE", "NDT_FENCELIKE", "NDT_RAILLIKE", "NDT_NODEBOX", "NDT_GLASSLIKE_FRAMED", "NDT_FIRELIKE", "NDT_GLASSLIKE_FRAMED_OPTIONAL", "NDT_PLANTLIKE_ROOTED", }; for (int i = 0; i < 14; i++){ shaders_header += "#define "; shaders_header += drawTypes[i]; shaders_header += " "; shaders_header += itos(i); shaders_header += "\n"; } static const char* materialTypes[] = { "TILE_MATERIAL_BASIC", "TILE_MATERIAL_ALPHA", "TILE_MATERIAL_LIQUID_TRANSPARENT", "TILE_MATERIAL_LIQUID_OPAQUE", "TILE_MATERIAL_WAVING_LEAVES", "TILE_MATERIAL_WAVING_PLANTS", "TILE_MATERIAL_OPAQUE", "TILE_MATERIAL_WAVING_LIQUID_BASIC", "TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT", "TILE_MATERIAL_WAVING_LIQUID_OPAQUE", }; for (int i = 0; i < 10; i++){ shaders_header += "#define "; shaders_header += materialTypes[i]; shaders_header += " "; shaders_header += itos(i); shaders_header += "\n"; } shaders_header += "#define MATERIAL_TYPE "; shaders_header += itos(material_type); shaders_header += "\n"; shaders_header += "#define DRAW_TYPE "; shaders_header += itos(drawtype); shaders_header += "\n"; if (g_settings->getBool("generate_normalmaps")) { shaders_header += "#define GENERATE_NORMALMAPS 1\n"; } else { shaders_header += "#define GENERATE_NORMALMAPS 0\n"; } shaders_header += "#define NORMALMAPS_STRENGTH "; shaders_header += ftos(g_settings->getFloat("normalmaps_strength")); shaders_header += "\n"; float sample_step; int smooth = (int)g_settings->getFloat("normalmaps_smooth"); switch (smooth){ case 0: sample_step = 0.0078125; // 1.0 / 128.0 break; case 1: sample_step = 0.00390625; // 1.0 / 256.0 break; case 2: sample_step = 0.001953125; // 1.0 / 512.0 break; default: sample_step = 0.0078125; break; } shaders_header += "#define SAMPLE_STEP "; shaders_header += ftos(sample_step); shaders_header += "\n"; if (g_settings->getBool("enable_bumpmapping")) shaders_header += "#define ENABLE_BUMPMAPPING\n"; if (g_settings->getBool("enable_parallax_occlusion")){ int mode = g_settings->getFloat("parallax_occlusion_mode"); float scale = g_settings->getFloat("parallax_occlusion_scale"); float bias = g_settings->getFloat("parallax_occlusion_bias"); int iterations = g_settings->getFloat("parallax_occlusion_iterations"); shaders_header += "#define ENABLE_PARALLAX_OCCLUSION\n"; shaders_header += "#define PARALLAX_OCCLUSION_MODE "; shaders_header += itos(mode); shaders_header += "\n"; shaders_header += "#define PARALLAX_OCCLUSION_SCALE "; shaders_header += ftos(scale); shaders_header += "\n"; shaders_header += "#define PARALLAX_OCCLUSION_BIAS "; shaders_header += ftos(bias); shaders_header += "\n"; shaders_header += "#define PARALLAX_OCCLUSION_ITERATIONS "; shaders_header += itos(iterations); shaders_header += "\n"; } shaders_header += "#define USE_NORMALMAPS "; if (g_settings->getBool("enable_bumpmapping") || g_settings->getBool("enable_parallax_occlusion")) shaders_header += "1\n"; else shaders_header += "0\n"; if (g_settings->getBool("enable_waving_water")){ shaders_header += "#define ENABLE_WAVING_WATER 1\n"; shaders_header += "#define WATER_WAVE_HEIGHT "; shaders_header += ftos(g_settings->getFloat("water_wave_height")); shaders_header += "\n"; shaders_header += "#define WATER_WAVE_LENGTH "; shaders_header += ftos(g_settings->getFloat("water_wave_length")); shaders_header += "\n"; shaders_header += "#define WATER_WAVE_SPEED "; shaders_header += ftos(g_settings->getFloat("water_wave_speed")); shaders_header += "\n"; } else{ shaders_header += "#define ENABLE_WAVING_WATER 0\n"; } shaders_header += "#define ENABLE_WAVING_LEAVES "; if (g_settings->getBool("enable_waving_leaves")) shaders_header += "1\n"; else shaders_header += "0\n"; shaders_header += "#define ENABLE_WAVING_PLANTS "; if (g_settings->getBool("enable_waving_plants")) shaders_header += "1\n"; else shaders_header += "0\n"; if (g_settings->getBool("tone_mapping")) shaders_header += "#define ENABLE_TONE_MAPPING\n"; shaders_header += "#define FOG_START "; shaders_header += ftos(rangelim(g_settings->getFloat("fog_start"), 0.0f, 0.99f)); shaders_header += "\n"; // Call addHighLevelShaderMaterial() or addShaderMaterial() const c8* vertex_program_ptr = 0; const c8* pixel_program_ptr = 0; const c8* geometry_program_ptr = 0; if (!vertex_program.empty()) { vertex_program = shaders_header + vertex_program; vertex_program_ptr = vertex_program.c_str(); } if (!pixel_program.empty()) { pixel_program = shaders_header + pixel_program; pixel_program_ptr = pixel_program.c_str(); } if (!geometry_program.empty()) { geometry_program = shaders_header + geometry_program; geometry_program_ptr = geometry_program.c_str(); } ShaderCallback *cb = new ShaderCallback(setter_factories); s32 shadermat = -1; if(is_highlevel){ infostream<<"Compiling high level shaders for "<<name<<std::endl; shadermat = gpu->addHighLevelShaderMaterial( vertex_program_ptr, // Vertex shader program "vertexMain", // Vertex shader entry point video::EVST_VS_1_1, // Vertex shader version pixel_program_ptr, // Pixel shader program "pixelMain", // Pixel shader entry point video::EPST_PS_1_2, // Pixel shader version geometry_program_ptr, // Geometry shader program "geometryMain", // Geometry shader entry point video::EGST_GS_4_0, // Geometry shader version scene::EPT_TRIANGLES, // Geometry shader input scene::EPT_TRIANGLE_STRIP, // Geometry shader output 0, // Support maximum number of vertices cb, // Set-constant callback shaderinfo.base_material, // Base material 1 // Userdata passed to callback ); if(shadermat == -1){ errorstream<<"generate_shader(): " "failed to generate \""<<name<<"\", " "addHighLevelShaderMaterial failed." <<std::endl; dumpShaderProgram(warningstream, "Vertex", vertex_program); dumpShaderProgram(warningstream, "Pixel", pixel_program); dumpShaderProgram(warningstream, "Geometry", geometry_program); delete cb; return shaderinfo; } } else{ infostream<<"Compiling assembly shaders for "<<name<<std::endl; shadermat = gpu->addShaderMaterial( vertex_program_ptr, // Vertex shader program pixel_program_ptr, // Pixel shader program cb, // Set-constant callback shaderinfo.base_material, // Base material 0 // Userdata passed to callback ); if(shadermat == -1){ errorstream<<"generate_shader(): " "failed to generate \""<<name<<"\", " "addShaderMaterial failed." <<std::endl; dumpShaderProgram(warningstream, "Vertex", vertex_program); dumpShaderProgram(warningstream,"Pixel", pixel_program); delete cb; return shaderinfo; } } callbacks.push_back(cb); // HACK, TODO: investigate this better // Grab the material renderer once more so minetest doesn't crash on exit driver->getMaterialRenderer(shadermat)->grab(); // Apply the newly created material type shaderinfo.material = (video::E_MATERIAL_TYPE) shadermat; return shaderinfo; } void load_shaders(const std::string &name, SourceShaderCache *sourcecache, video::E_DRIVER_TYPE drivertype, bool enable_shaders, std::string &vertex_program, std::string &pixel_program, std::string &geometry_program, bool &is_highlevel) { vertex_program = ""; pixel_program = ""; geometry_program = ""; is_highlevel = false; if(enable_shaders){ // Look for high level shaders if(drivertype == video::EDT_DIRECT3D9){ // Direct3D 9: HLSL // (All shaders in one file) vertex_program = sourcecache->getOrLoad(name, "d3d9.hlsl"); pixel_program = vertex_program; geometry_program = vertex_program; } else if(drivertype == video::EDT_OPENGL){ // OpenGL: GLSL vertex_program = sourcecache->getOrLoad(name, "opengl_vertex.glsl"); pixel_program = sourcecache->getOrLoad(name, "opengl_fragment.glsl"); geometry_program = sourcecache->getOrLoad(name, "opengl_geometry.glsl"); } if (!vertex_program.empty() || !pixel_program.empty() || !geometry_program.empty()){ is_highlevel = true; return; } } } void dumpShaderProgram(std::ostream &output_stream, const std::string &program_type, const std::string &program) { output_stream << program_type << " shader program:" << std::endl << "----------------------------------" << std::endl; size_t pos = 0; size_t prev = 0; s16 line = 1; while ((pos = program.find('\n', prev)) != std::string::npos) { output_stream << line++ << ": "<< program.substr(prev, pos - prev) << std::endl; prev = pos + 1; } output_stream << line << ": " << program.substr(prev) << std::endl << "End of " << program_type << " shader program." << std::endl << " " << std::endl; }
pgimeno/minetest
src/client/shader.cpp
C++
mit
25,461
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2013 Kahrl <kahrl@gmx.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <IMaterialRendererServices.h> #include "irrlichttypes_bloated.h" #include <string> class IGameDef; /* shader.{h,cpp}: Shader handling stuff. */ /* Gets the path to a shader by first checking if the file name_of_shader/filename exists in shader_path and if not, using the data path. If not found, returns "". Utilizes a thread-safe cache. */ std::string getShaderPath(const std::string &name_of_shader, const std::string &filename); struct ShaderInfo { std::string name = ""; video::E_MATERIAL_TYPE base_material = video::EMT_SOLID; video::E_MATERIAL_TYPE material = video::EMT_SOLID; u8 drawtype = 0; u8 material_type = 0; ShaderInfo() = default; virtual ~ShaderInfo() = default; }; /* Setter of constants for shaders */ namespace irr { namespace video { class IMaterialRendererServices; } } class IShaderConstantSetter { public: virtual ~IShaderConstantSetter() = default; virtual void onSetConstants(video::IMaterialRendererServices *services, bool is_highlevel) = 0; }; class IShaderConstantSetterFactory { public: virtual ~IShaderConstantSetterFactory() = default; virtual IShaderConstantSetter* create() = 0; }; template <typename T, std::size_t count=1> class CachedShaderSetting { const char *m_name; T m_sent[count]; bool has_been_set = false; bool is_pixel; protected: CachedShaderSetting(const char *name, bool is_pixel) : m_name(name), is_pixel(is_pixel) {} public: void set(const T value[count], video::IMaterialRendererServices *services) { if (has_been_set && std::equal(m_sent, m_sent + count, value)) return; if (is_pixel) services->setPixelShaderConstant(m_name, value, count); else services->setVertexShaderConstant(m_name, value, count); std::copy(value, value + count, m_sent); has_been_set = true; } }; template <typename T, std::size_t count = 1> class CachedPixelShaderSetting : public CachedShaderSetting<T, count> { public: CachedPixelShaderSetting(const char *name) : CachedShaderSetting<T, count>(name, true){} }; template <typename T, std::size_t count = 1> class CachedVertexShaderSetting : public CachedShaderSetting<T, count> { public: CachedVertexShaderSetting(const char *name) : CachedShaderSetting<T, count>(name, false){} }; /* ShaderSource creates and caches shaders. */ class IShaderSource { public: IShaderSource() = default; virtual ~IShaderSource() = default; virtual u32 getShaderIdDirect(const std::string &name, const u8 material_type, const u8 drawtype){return 0;} virtual ShaderInfo getShaderInfo(u32 id){return ShaderInfo();} virtual u32 getShader(const std::string &name, const u8 material_type, const u8 drawtype){return 0;} }; class IWritableShaderSource : public IShaderSource { public: IWritableShaderSource() = default; virtual ~IWritableShaderSource() = default; virtual u32 getShaderIdDirect(const std::string &name, const u8 material_type, const u8 drawtype){return 0;} virtual ShaderInfo getShaderInfo(u32 id){return ShaderInfo();} virtual u32 getShader(const std::string &name, const u8 material_type, const u8 drawtype){return 0;} virtual void processQueue()=0; virtual void insertSourceShader(const std::string &name_of_shader, const std::string &filename, const std::string &program)=0; virtual void rebuildShaders()=0; virtual void addShaderConstantSetterFactory(IShaderConstantSetterFactory *setter) = 0; }; IWritableShaderSource *createShaderSource(); void dumpShaderProgram(std::ostream &output_stream, const std::string &program_type, const std::string &program);
pgimeno/minetest
src/client/shader.h
C++
mit
4,393
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "sky.h" #include "IVideoDriver.h" #include "ISceneManager.h" #include "ICameraSceneNode.h" #include "S3DVertex.h" #include "client/tile.h" #include "noise.h" // easeCurve #include "profiler.h" #include "util/numeric.h" #include <cmath> #include "client/renderingengine.h" #include "settings.h" #include "camera.h" // CameraModes Sky::Sky(s32 id, ITextureSource *tsrc): scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(), RenderingEngine::get_scene_manager(), id) { setAutomaticCulling(scene::EAC_OFF); m_box.MaxEdge.set(0, 0, 0); m_box.MinEdge.set(0, 0, 0); // Create material video::SMaterial mat; mat.Lighting = false; #ifdef __ANDROID__ mat.ZBuffer = video::ECFN_DISABLED; #else mat.ZBuffer = video::ECFN_NEVER; #endif mat.ZWriteEnable = false; mat.AntiAliasing = 0; mat.TextureLayer[0].TextureWrapU = video::ETC_CLAMP_TO_EDGE; mat.TextureLayer[0].TextureWrapV = video::ETC_CLAMP_TO_EDGE; mat.BackfaceCulling = false; m_materials[0] = mat; m_materials[1] = mat; //m_materials[1].MaterialType = video::EMT_TRANSPARENT_VERTEX_ALPHA; m_materials[1].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; m_materials[2] = mat; m_materials[2].setTexture(0, tsrc->getTextureForMesh("sunrisebg.png")); m_materials[2].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; //m_materials[2].MaterialType = video::EMT_TRANSPARENT_ADD_COLOR; m_sun_texture = tsrc->isKnownSourceImage("sun.png") ? tsrc->getTextureForMesh("sun.png") : NULL; m_moon_texture = tsrc->isKnownSourceImage("moon.png") ? tsrc->getTextureForMesh("moon.png") : NULL; m_sun_tonemap = tsrc->isKnownSourceImage("sun_tonemap.png") ? tsrc->getTexture("sun_tonemap.png") : NULL; m_moon_tonemap = tsrc->isKnownSourceImage("moon_tonemap.png") ? tsrc->getTexture("moon_tonemap.png") : NULL; if (m_sun_texture) { m_materials[3] = mat; m_materials[3].setTexture(0, m_sun_texture); m_materials[3].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; if (m_sun_tonemap) m_materials[3].Lighting = true; } if (m_moon_texture) { m_materials[4] = mat; m_materials[4].setTexture(0, m_moon_texture); m_materials[4].MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; if (m_moon_tonemap) m_materials[4].Lighting = true; } for (v3f &star : m_stars) { star = v3f( myrand_range(-10000, 10000), myrand_range(-10000, 10000), myrand_range(-10000, 10000) ); star.normalize(); } m_directional_colored_fog = g_settings->getBool("directional_colored_fog"); } void Sky::OnRegisterSceneNode() { if (IsVisible) SceneManager->registerNodeForRendering(this, scene::ESNRP_SKY_BOX); scene::ISceneNode::OnRegisterSceneNode(); } void Sky::render() { if (!m_visible) return; video::IVideoDriver* driver = SceneManager->getVideoDriver(); scene::ICameraSceneNode* camera = SceneManager->getActiveCamera(); if (!camera || !driver) return; ScopeProfiler sp(g_profiler, "Sky::render()", SPT_AVG); // Draw perspective skybox core::matrix4 translate(AbsoluteTransformation); translate.setTranslation(camera->getAbsolutePosition()); // Draw the sky box between the near and far clip plane const f32 viewDistance = (camera->getNearValue() + camera->getFarValue()) * 0.5f; core::matrix4 scale; scale.setScale(core::vector3df(viewDistance, viewDistance, viewDistance)); driver->setTransform(video::ETS_WORLD, translate * scale); if (m_sunlight_seen) { float sunsize = 0.07; video::SColorf suncolor_f(1, 1, 0, 1); //suncolor_f.r = 1; //suncolor_f.g = MYMAX(0.3, MYMIN(1.0, 0.7 + m_time_brightness * 0.5)); //suncolor_f.b = MYMAX(0.0, m_brightness * 0.95); video::SColorf suncolor2_f(1, 1, 1, 1); // The values below were probably meant to be suncolor2_f instead of a // reassignment of suncolor_f. However, the resulting colour was chosen // and is our long-running classic colour. So preserve, but comment-out // the unnecessary first assignments above. suncolor_f.r = 1; suncolor_f.g = MYMAX(0.3, MYMIN(1.0, 0.85 + m_time_brightness * 0.5)); suncolor_f.b = MYMAX(0.0, m_brightness); float moonsize = 0.04; video::SColorf mooncolor_f(0.50, 0.57, 0.65, 1); video::SColorf mooncolor2_f(0.85, 0.875, 0.9, 1); float nightlength = 0.415; float wn = nightlength / 2; float wicked_time_of_day = 0; if (m_time_of_day > wn && m_time_of_day < 1.0 - wn) wicked_time_of_day = (m_time_of_day - wn) / (1.0 - wn * 2) * 0.5 + 0.25; else if (m_time_of_day < 0.5) wicked_time_of_day = m_time_of_day / wn * 0.25; else wicked_time_of_day = 1.0 - ((1.0 - m_time_of_day) / wn * 0.25); /*std::cerr<<"time_of_day="<<m_time_of_day<<" -> " <<"wicked_time_of_day="<<wicked_time_of_day<<std::endl;*/ video::SColor suncolor = suncolor_f.toSColor(); video::SColor suncolor2 = suncolor2_f.toSColor(); video::SColor mooncolor = mooncolor_f.toSColor(); video::SColor mooncolor2 = mooncolor2_f.toSColor(); // Calculate offset normalized to the X dimension of a 512x1 px tonemap float offset = (1.0 - fabs(sin((m_time_of_day - 0.5) * irr::core::PI))) * 511; if (m_sun_tonemap) { u8 * texels = (u8 *)m_sun_tonemap->lock(); video::SColor* texel = (video::SColor *)(texels + (u32)offset * 4); video::SColor texel_color (255, texel->getRed(), texel->getGreen(), texel->getBlue()); m_sun_tonemap->unlock(); m_materials[3].EmissiveColor = texel_color; } if (m_moon_tonemap) { u8 * texels = (u8 *)m_moon_tonemap->lock(); video::SColor* texel = (video::SColor *)(texels + (u32)offset * 4); video::SColor texel_color (255, texel->getRed(), texel->getGreen(), texel->getBlue()); m_moon_tonemap->unlock(); m_materials[4].EmissiveColor = texel_color; } const f32 t = 1.0f; const f32 o = 0.0f; static const u16 indices[4] = {0, 1, 2, 3}; video::S3DVertex vertices[4]; driver->setMaterial(m_materials[1]); video::SColor cloudyfogcolor = m_bgcolor; // Draw far cloudy fog thing blended with skycolor for (u32 j = 0; j < 4; j++) { video::SColor c = cloudyfogcolor.getInterpolated(m_skycolor, 0.45); vertices[0] = video::S3DVertex(-1, 0.08, -1, 0, 0, 1, c, t, t); vertices[1] = video::S3DVertex( 1, 0.08, -1, 0, 0, 1, c, o, t); vertices[2] = video::S3DVertex( 1, 0.12, -1, 0, 0, 1, c, o, o); vertices[3] = video::S3DVertex(-1, 0.12, -1, 0, 0, 1, c, t, o); for (video::S3DVertex &vertex : vertices) { if (j == 0) // Don't switch {} else if (j == 1) // Switch from -Z (south) to +X (east) vertex.Pos.rotateXZBy(90); else if (j == 2) // Switch from -Z (south) to -X (west) vertex.Pos.rotateXZBy(-90); else // Switch from -Z (south) to +Z (north) vertex.Pos.rotateXZBy(-180); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); } // Draw far cloudy fog thing at and below all horizons for (u32 j = 0; j < 4; j++) { video::SColor c = cloudyfogcolor; vertices[0] = video::S3DVertex(-1, -1.0, -1, 0, 0, 1, c, t, t); vertices[1] = video::S3DVertex( 1, -1.0, -1, 0, 0, 1, c, o, t); vertices[2] = video::S3DVertex( 1, 0.08, -1, 0, 0, 1, c, o, o); vertices[3] = video::S3DVertex(-1, 0.08, -1, 0, 0, 1, c, t, o); for (video::S3DVertex &vertex : vertices) { if (j == 0) // Don't switch {} else if (j == 1) // Switch from -Z (south) to +X (east) vertex.Pos.rotateXZBy(90); else if (j == 2) // Switch from -Z (south) to -X (west) vertex.Pos.rotateXZBy(-90); else // Switch from -Z (south) to +Z (north) vertex.Pos.rotateXZBy(-180); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); } // If sun, moon and stars are (temporarily) disabled, abort here if (!m_bodies_visible) return; // Draw stars before sun and moon to be behind them do { driver->setMaterial(m_materials[1]); // Tune values so that stars first appear just after the sun // disappears over the horizon, and disappear just before the sun // appears over the horizon. // Also tune so that stars are at full brightness from time 20000 to // time 4000. float starbrightness = MYMAX(0, MYMIN(1, (0.25 - fabs(wicked_time_of_day < 0.5 ? wicked_time_of_day : (1.0 - wicked_time_of_day))) * 20)); float f = starbrightness; float d = 0.007 / 2; video::SColor starcolor(255, f * 90, f * 90, f * 90); // Stars are only drawn when brighter than skycolor if (starcolor.getBlue() < m_skycolor.getBlue()) break; #ifdef __ANDROID__ u16 indices[SKY_STAR_COUNT * 3]; video::S3DVertex vertices[SKY_STAR_COUNT * 3]; for (u32 i = 0; i < SKY_STAR_COUNT; i++) { indices[i * 3 + 0] = i * 3 + 0; indices[i * 3 + 1] = i * 3 + 1; indices[i * 3 + 2] = i * 3 + 2; v3f r = m_stars[i]; core::CMatrix4<f32> a; a.buildRotateFromTo(v3f(0, 1, 0), r); v3f p = v3f(-d, 1, -d); v3f p1 = v3f(d, 1, 0); v3f p2 = v3f(-d, 1, d); a.rotateVect(p); a.rotateVect(p1); a.rotateVect(p2); p.rotateXYBy(wicked_time_of_day * 360 - 90); p1.rotateXYBy(wicked_time_of_day * 360 - 90); p2.rotateXYBy(wicked_time_of_day * 360 - 90); vertices[i * 3 + 0].Pos = p; vertices[i * 3 + 0].Color = starcolor; vertices[i * 3 + 1].Pos = p1; vertices[i * 3 + 1].Color = starcolor; vertices[i * 3 + 2].Pos = p2; vertices[i * 3 + 2].Color = starcolor; } driver->drawIndexedTriangleList(vertices, SKY_STAR_COUNT * 3, indices, SKY_STAR_COUNT); #else u16 indices[SKY_STAR_COUNT * 4]; video::S3DVertex vertices[SKY_STAR_COUNT * 4]; for (u32 i = 0; i < SKY_STAR_COUNT; i++) { indices[i * 4 + 0] = i * 4 + 0; indices[i * 4 + 1] = i * 4 + 1; indices[i * 4 + 2] = i * 4 + 2; indices[i * 4 + 3] = i * 4 + 3; v3f r = m_stars[i]; core::CMatrix4<f32> a; a.buildRotateFromTo(v3f(0, 1, 0), r); v3f p = v3f(-d, 1, -d); v3f p1 = v3f( d, 1, -d); v3f p2 = v3f( d, 1, d); v3f p3 = v3f(-d, 1, d); a.rotateVect(p); a.rotateVect(p1); a.rotateVect(p2); a.rotateVect(p3); p.rotateXYBy(wicked_time_of_day * 360 - 90); p1.rotateXYBy(wicked_time_of_day * 360 - 90); p2.rotateXYBy(wicked_time_of_day * 360 - 90); p3.rotateXYBy(wicked_time_of_day * 360 - 90); vertices[i * 4 + 0].Pos = p; vertices[i * 4 + 0].Color = starcolor; vertices[i * 4 + 1].Pos = p1; vertices[i * 4 + 1].Color = starcolor; vertices[i * 4 + 2].Pos = p2; vertices[i * 4 + 2].Color = starcolor; vertices[i * 4 + 3].Pos = p3; vertices[i * 4 + 3].Color = starcolor; } driver->drawVertexPrimitiveList(vertices, SKY_STAR_COUNT * 4, indices, SKY_STAR_COUNT, video::EVT_STANDARD, scene::EPT_QUADS, video::EIT_16BIT); #endif } while(false); // Draw sunrise/sunset horizon glow texture (textures/base/pack/sunrisebg.png) { driver->setMaterial(m_materials[2]); float mid1 = 0.25; float mid = wicked_time_of_day < 0.5 ? mid1 : (1.0 - mid1); float a_ = 1.0f - std::fabs(wicked_time_of_day - mid) * 35.0f; float a = easeCurve(MYMAX(0, MYMIN(1, a_))); //std::cerr<<"a_="<<a_<<" a="<<a<<std::endl; video::SColor c(255, 255, 255, 255); float y = -(1.0 - a) * 0.22; vertices[0] = video::S3DVertex(-1, -0.05 + y, -1, 0, 0, 1, c, t, t); vertices[1] = video::S3DVertex( 1, -0.05 + y, -1, 0, 0, 1, c, o, t); vertices[2] = video::S3DVertex( 1, 0.2 + y, -1, 0, 0, 1, c, o, o); vertices[3] = video::S3DVertex(-1, 0.2 + y, -1, 0, 0, 1, c, t, o); for (video::S3DVertex &vertex : vertices) { if (wicked_time_of_day < 0.5) // Switch from -Z (south) to +X (east) vertex.Pos.rotateXZBy(90); else // Switch from -Z (south) to -X (west) vertex.Pos.rotateXZBy(-90); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); } // Draw sun if (wicked_time_of_day > 0.15 && wicked_time_of_day < 0.85) { if (!m_sun_texture) { driver->setMaterial(m_materials[1]); float d = sunsize * 1.7; video::SColor c = suncolor; c.setAlpha(0.05 * 255); vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, c, t, t); vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, c, o, t); vertices[2] = video::S3DVertex( d, d, -1, 0, 0, 1, c, o, o); vertices[3] = video::S3DVertex(-d, d, -1, 0, 0, 1, c, t, o); for (video::S3DVertex &vertex : vertices) { // Switch from -Z (south) to +X (east) vertex.Pos.rotateXZBy(90); vertex.Pos.rotateXYBy(wicked_time_of_day * 360 - 90); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); d = sunsize * 1.2; c = suncolor; c.setAlpha(0.15 * 255); vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, c, t, t); vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, c, o, t); vertices[2] = video::S3DVertex( d, d, -1, 0, 0, 1, c, o, o); vertices[3] = video::S3DVertex(-d, d, -1, 0, 0, 1, c, t, o); for (video::S3DVertex &vertex : vertices) { // Switch from -Z (south) to +X (east) vertex.Pos.rotateXZBy(90); vertex.Pos.rotateXYBy(wicked_time_of_day * 360 - 90); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); d = sunsize; vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, suncolor, t, t); vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, suncolor, o, t); vertices[2] = video::S3DVertex( d, d, -1, 0, 0, 1, suncolor, o, o); vertices[3] = video::S3DVertex(-d, d, -1, 0, 0, 1, suncolor, t, o); for (video::S3DVertex &vertex : vertices) { // Switch from -Z (south) to +X (east) vertex.Pos.rotateXZBy(90); vertex.Pos.rotateXYBy(wicked_time_of_day * 360 - 90); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); d = sunsize * 0.7; vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, suncolor2, t, t); vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, suncolor2, o, t); vertices[2] = video::S3DVertex( d, d, -1, 0, 0, 1, suncolor2, o, o); vertices[3] = video::S3DVertex(-d, d, -1, 0, 0, 1, suncolor2, t, o); for (video::S3DVertex &vertex : vertices) { // Switch from -Z (south) to +X (east) vertex.Pos.rotateXZBy(90); vertex.Pos.rotateXYBy(wicked_time_of_day * 360 - 90); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); } else { driver->setMaterial(m_materials[3]); float d = sunsize * 1.7; video::SColor c; if (m_sun_tonemap) c = video::SColor (0, 0, 0, 0); else c = video::SColor (255, 255, 255, 255); vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, c, t, t); vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, c, o, t); vertices[2] = video::S3DVertex( d, d, -1, 0, 0, 1, c, o, o); vertices[3] = video::S3DVertex(-d, d, -1, 0, 0, 1, c, t, o); for (video::S3DVertex &vertex : vertices) { // Switch from -Z (south) to +X (east) vertex.Pos.rotateXZBy(90); vertex.Pos.rotateXYBy(wicked_time_of_day * 360 - 90); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); } } // Draw moon if (wicked_time_of_day < 0.3 || wicked_time_of_day > 0.7) { if (!m_moon_texture) { driver->setMaterial(m_materials[1]); float d = moonsize * 1.9; video::SColor c = mooncolor; c.setAlpha(0.05 * 255); vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, c, t, t); vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, c, o, t); vertices[2] = video::S3DVertex( d, d, -1, 0, 0, 1, c, o, o); vertices[3] = video::S3DVertex(-d, d, -1, 0, 0, 1, c, t, o); for (video::S3DVertex &vertex : vertices) { // Switch from -Z (south) to -X (west) vertex.Pos.rotateXZBy(-90); vertex.Pos.rotateXYBy(wicked_time_of_day * 360 - 90); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); d = moonsize * 1.3; c = mooncolor; c.setAlpha(0.15 * 255); vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, c, t, t); vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, c, o, t); vertices[2] = video::S3DVertex( d, d, -1, 0, 0, 1, c, o, o); vertices[3] = video::S3DVertex(-d, d, -1, 0, 0, 1, c, t, o); for (video::S3DVertex &vertex : vertices) { // Switch from -Z (south) to -X (west) vertex.Pos.rotateXZBy(-90); vertex.Pos.rotateXYBy(wicked_time_of_day * 360 - 90); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); d = moonsize; vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, mooncolor, t, t); vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, mooncolor, o, t); vertices[2] = video::S3DVertex( d, d, -1, 0, 0, 1, mooncolor, o, o); vertices[3] = video::S3DVertex(-d, d, -1, 0, 0, 1, mooncolor, t, o); for (video::S3DVertex &vertex : vertices) { // Switch from -Z (south) to -X (west) vertex.Pos.rotateXZBy(-90); vertex.Pos.rotateXYBy(wicked_time_of_day * 360 - 90); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); float d2 = moonsize * 0.6; vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, mooncolor2, t, t); vertices[1] = video::S3DVertex( d2,-d, -1, 0, 0, 1, mooncolor2, o, t); vertices[2] = video::S3DVertex( d2, d2, -1, 0, 0, 1, mooncolor2, o, o); vertices[3] = video::S3DVertex(-d, d2, -1, 0, 0, 1, mooncolor2, t, o); for (video::S3DVertex &vertex : vertices) { // Switch from -Z (south) to -X (west) vertex.Pos.rotateXZBy(-90); vertex.Pos.rotateXYBy(wicked_time_of_day * 360 - 90); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); } else { driver->setMaterial(m_materials[4]); float d = moonsize * 1.9; video::SColor c; if (m_moon_tonemap) c = video::SColor (0, 0, 0, 0); else c = video::SColor (255, 255, 255, 255); vertices[0] = video::S3DVertex(-d, -d, -1, 0, 0, 1, c, t, t); vertices[1] = video::S3DVertex( d, -d, -1, 0, 0, 1, c, o, t); vertices[2] = video::S3DVertex( d, d, -1, 0, 0, 1, c, o, o); vertices[3] = video::S3DVertex(-d, d, -1, 0, 0, 1, c, t, o); for (video::S3DVertex &vertex : vertices) { // Switch from -Z (south) to -X (west) vertex.Pos.rotateXZBy(-90); vertex.Pos.rotateXYBy(wicked_time_of_day * 360 - 90); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); } } // Draw far cloudy fog thing below all horizons in front of sun, moon // and stars. driver->setMaterial(m_materials[1]); for (u32 j = 0; j < 4; j++) { video::SColor c = cloudyfogcolor; vertices[0] = video::S3DVertex(-1, -1.0, -1, 0, 0, 1, c, t, t); vertices[1] = video::S3DVertex( 1, -1.0, -1, 0, 0, 1, c, o, t); vertices[2] = video::S3DVertex( 1, -0.02, -1, 0, 0, 1, c, o, o); vertices[3] = video::S3DVertex(-1, -0.02, -1, 0, 0, 1, c, t, o); for (video::S3DVertex &vertex : vertices) { if (j == 0) // Don't switch {} else if (j == 1) // Switch from -Z (south) to +X (east) vertex.Pos.rotateXZBy(90); else if (j == 2) // Switch from -Z (south) to -X (west) vertex.Pos.rotateXZBy(-90); else // Switch from -Z (south) to +Z (north) vertex.Pos.rotateXZBy(-180); } driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); } // Draw bottom far cloudy fog thing in front of sun, moon and stars video::SColor c = cloudyfogcolor; vertices[0] = video::S3DVertex(-1, -1.0, -1, 0, 1, 0, c, t, t); vertices[1] = video::S3DVertex( 1, -1.0, -1, 0, 1, 0, c, o, t); vertices[2] = video::S3DVertex( 1, -1.0, 1, 0, 1, 0, c, o, o); vertices[3] = video::S3DVertex(-1, -1.0, 1, 0, 1, 0, c, t, o); driver->drawIndexedTriangleFan(&vertices[0], 4, indices, 2); } } void Sky::update(float time_of_day, float time_brightness, float direct_brightness, bool sunlight_seen, CameraMode cam_mode, float yaw, float pitch) { // Stabilize initial brightness and color values by flooding updates if (m_first_update) { /*dstream<<"First update with time_of_day="<<time_of_day <<" time_brightness="<<time_brightness <<" direct_brightness="<<direct_brightness <<" sunlight_seen="<<sunlight_seen<<std::endl;*/ m_first_update = false; for (u32 i = 0; i < 100; i++) { update(time_of_day, time_brightness, direct_brightness, sunlight_seen, cam_mode, yaw, pitch); } return; } m_time_of_day = time_of_day; m_time_brightness = time_brightness; m_sunlight_seen = sunlight_seen; m_bodies_visible = true; bool is_dawn = (time_brightness >= 0.20 && time_brightness < 0.35); /* Development colours video::SColorf bgcolor_bright_normal_f(170. / 255, 200. / 255, 230. / 255, 1.0); video::SColorf bgcolor_bright_dawn_f(0.666, 200. / 255 * 0.7, 230. / 255 * 0.5, 1.0); video::SColorf bgcolor_bright_dawn_f(0.666, 0.549, 0.220, 1.0); video::SColorf bgcolor_bright_dawn_f(0.666 * 1.2, 0.549 * 1.0, 0.220 * 1.0, 1.0); video::SColorf bgcolor_bright_dawn_f(0.666 * 1.2, 0.549 * 1.0, 0.220 * 1.2, 1.0); video::SColorf cloudcolor_bright_dawn_f(1.0, 0.591, 0.4); video::SColorf cloudcolor_bright_dawn_f(1.0, 0.65, 0.44); video::SColorf cloudcolor_bright_dawn_f(1.0, 0.7, 0.5); */ video::SColorf bgcolor_bright_normal_f = video::SColor(255, 155, 193, 240); video::SColorf bgcolor_bright_indoor_f = video::SColor(255, 100, 100, 100); video::SColorf bgcolor_bright_dawn_f = video::SColor(255, 186, 193, 240); video::SColorf bgcolor_bright_night_f = video::SColor(255, 64, 144, 255); video::SColorf skycolor_bright_normal_f = video::SColor(255, 140, 186, 250); video::SColorf skycolor_bright_dawn_f = video::SColor(255, 180, 186, 250); video::SColorf skycolor_bright_night_f = video::SColor(255, 0, 107, 255); // pure white: becomes "diffuse light component" for clouds video::SColorf cloudcolor_bright_normal_f = video::SColor(255, 255, 255, 255); // dawn-factoring version of pure white (note: R is above 1.0) video::SColorf cloudcolor_bright_dawn_f(255.0f/240.0f, 223.0f/240.0f, 191.0f/255.0f); float cloud_color_change_fraction = 0.95; if (sunlight_seen) { if (std::fabs(time_brightness - m_brightness) < 0.2f) { m_brightness = m_brightness * 0.95 + time_brightness * 0.05; } else { m_brightness = m_brightness * 0.80 + time_brightness * 0.20; cloud_color_change_fraction = 0.0; } } else { if (direct_brightness < m_brightness) m_brightness = m_brightness * 0.95 + direct_brightness * 0.05; else m_brightness = m_brightness * 0.98 + direct_brightness * 0.02; } m_clouds_visible = true; float color_change_fraction = 0.98f; if (sunlight_seen) { if (is_dawn) { // Dawn m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated( bgcolor_bright_dawn_f, color_change_fraction); m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated( skycolor_bright_dawn_f, color_change_fraction); m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated( cloudcolor_bright_dawn_f, color_change_fraction); } else { if (time_brightness < 0.13f) { // Night m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated( bgcolor_bright_night_f, color_change_fraction); m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated( skycolor_bright_night_f, color_change_fraction); } else { // Day m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated( bgcolor_bright_normal_f, color_change_fraction); m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated( skycolor_bright_normal_f, color_change_fraction); } m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated( cloudcolor_bright_normal_f, color_change_fraction); } } else { m_bgcolor_bright_f = m_bgcolor_bright_f.getInterpolated( bgcolor_bright_indoor_f, color_change_fraction); m_skycolor_bright_f = m_skycolor_bright_f.getInterpolated( bgcolor_bright_indoor_f, color_change_fraction); m_cloudcolor_bright_f = m_cloudcolor_bright_f.getInterpolated( cloudcolor_bright_normal_f, color_change_fraction); m_clouds_visible = false; } video::SColor bgcolor_bright = m_bgcolor_bright_f.toSColor(); m_bgcolor = video::SColor( 255, bgcolor_bright.getRed() * m_brightness, bgcolor_bright.getGreen() * m_brightness, bgcolor_bright.getBlue() * m_brightness ); video::SColor skycolor_bright = m_skycolor_bright_f.toSColor(); m_skycolor = video::SColor( 255, skycolor_bright.getRed() * m_brightness, skycolor_bright.getGreen() * m_brightness, skycolor_bright.getBlue() * m_brightness ); // Horizon coloring based on sun and moon direction during sunset and sunrise video::SColor pointcolor = video::SColor(m_bgcolor.getAlpha(), 255, 255, 255); if (m_directional_colored_fog) { if (m_horizon_blend() != 0) { // Calculate hemisphere value from yaw, (inverted in third person front view) s8 dir_factor = 1; if (cam_mode > CAMERA_MODE_THIRD) dir_factor = -1; f32 pointcolor_blend = wrapDegrees_0_360(yaw * dir_factor + 90); if (pointcolor_blend > 180) pointcolor_blend = 360 - pointcolor_blend; pointcolor_blend /= 180; // Bound view angle to determine where transition starts and ends pointcolor_blend = rangelim(1 - pointcolor_blend * 1.375, 0, 1 / 1.375) * 1.375; // Combine the colors when looking up or down, otherwise turning looks weird pointcolor_blend += (0.5 - pointcolor_blend) * (1 - MYMIN((90 - std::fabs(pitch)) / 90 * 1.5, 1)); // Invert direction to match where the sun and moon are rising if (m_time_of_day > 0.5) pointcolor_blend = 1 - pointcolor_blend; // Horizon colors of sun and moon f32 pointcolor_light = rangelim(m_time_brightness * 3, 0.2, 1); video::SColorf pointcolor_sun_f(1, 1, 1, 1); if (m_sun_tonemap) { pointcolor_sun_f.r = pointcolor_light * (float)m_materials[3].EmissiveColor.getRed() / 255; pointcolor_sun_f.b = pointcolor_light * (float)m_materials[3].EmissiveColor.getBlue() / 255; pointcolor_sun_f.g = pointcolor_light * (float)m_materials[3].EmissiveColor.getGreen() / 255; } else { pointcolor_sun_f.r = pointcolor_light * 1; pointcolor_sun_f.b = pointcolor_light * (0.25 + (rangelim(m_time_brightness, 0.25, 0.75) - 0.25) * 2 * 0.75); pointcolor_sun_f.g = pointcolor_light * (pointcolor_sun_f.b * 0.375 + (rangelim(m_time_brightness, 0.05, 0.15) - 0.05) * 10 * 0.625); } video::SColorf pointcolor_moon_f(0.5 * pointcolor_light, 0.6 * pointcolor_light, 0.8 * pointcolor_light, 1); if (m_moon_tonemap) { pointcolor_moon_f.r = pointcolor_light * (float)m_materials[4].EmissiveColor.getRed() / 255; pointcolor_moon_f.b = pointcolor_light * (float)m_materials[4].EmissiveColor.getBlue() / 255; pointcolor_moon_f.g = pointcolor_light * (float)m_materials[4].EmissiveColor.getGreen() / 255; } video::SColor pointcolor_sun = pointcolor_sun_f.toSColor(); video::SColor pointcolor_moon = pointcolor_moon_f.toSColor(); // Calculate the blend color pointcolor = m_mix_scolor(pointcolor_moon, pointcolor_sun, pointcolor_blend); } m_bgcolor = m_mix_scolor(m_bgcolor, pointcolor, m_horizon_blend() * 0.5); m_skycolor = m_mix_scolor(m_skycolor, pointcolor, m_horizon_blend() * 0.25); } float cloud_direct_brightness = 0.0f; if (sunlight_seen) { if (!m_directional_colored_fog) { cloud_direct_brightness = time_brightness; // Boost cloud brightness relative to sky, at dawn, dusk and at night if (time_brightness < 0.7f) cloud_direct_brightness *= 1.3f; } else { cloud_direct_brightness = std::fmin(m_horizon_blend() * 0.15f + m_time_brightness, 1.0f); // Set the same minimum cloud brightness at night if (time_brightness < 0.5f) cloud_direct_brightness = std::fmax(cloud_direct_brightness, time_brightness * 1.3f); } } else { cloud_direct_brightness = direct_brightness; } m_cloud_brightness = m_cloud_brightness * cloud_color_change_fraction + cloud_direct_brightness * (1.0 - cloud_color_change_fraction); m_cloudcolor_f = video::SColorf( m_cloudcolor_bright_f.r * m_cloud_brightness, m_cloudcolor_bright_f.g * m_cloud_brightness, m_cloudcolor_bright_f.b * m_cloud_brightness, 1.0 ); if (m_directional_colored_fog) { m_cloudcolor_f = m_mix_scolorf(m_cloudcolor_f, video::SColorf(pointcolor), m_horizon_blend() * 0.25); } }
pgimeno/minetest
src/client/sky.cpp
C++
mit
28,944
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <ISceneNode.h> #include "camera.h" #include "irrlichttypes_extrabloated.h" #pragma once #define SKY_MATERIAL_COUNT 5 #define SKY_STAR_COUNT 200 class ITextureSource; // Skybox, rendered with zbuffer turned off, before all other nodes. class Sky : public scene::ISceneNode { public: //! constructor Sky(s32 id, ITextureSource *tsrc); virtual void OnRegisterSceneNode(); //! renders the node. virtual void render(); virtual const aabb3f &getBoundingBox() const { return m_box; } // Used by Irrlicht for optimizing rendering virtual video::SMaterial &getMaterial(u32 i) { return m_materials[i]; } // Used by Irrlicht for optimizing rendering virtual u32 getMaterialCount() const { return SKY_MATERIAL_COUNT; } void update(float m_time_of_day, float time_brightness, float direct_brightness, bool sunlight_seen, CameraMode cam_mode, float yaw, float pitch); float getBrightness() { return m_brightness; } const video::SColor &getBgColor() const { return m_visible ? m_bgcolor : m_fallback_bg_color; } const video::SColor &getSkyColor() const { return m_visible ? m_skycolor : m_fallback_bg_color; } bool getCloudsVisible() const { return m_clouds_visible && m_clouds_enabled; } const video::SColorf &getCloudColor() const { return m_cloudcolor_f; } void setVisible(bool visible) { m_visible = visible; } // Set only from set_sky API void setCloudsEnabled(bool clouds_enabled) { m_clouds_enabled = clouds_enabled; } void setFallbackBgColor(const video::SColor &fallback_bg_color) { m_fallback_bg_color = fallback_bg_color; } void overrideColors(const video::SColor &bgcolor, const video::SColor &skycolor) { m_bgcolor = bgcolor; m_skycolor = skycolor; } void setBodiesVisible(bool visible) { m_bodies_visible = visible; } private: aabb3f m_box; video::SMaterial m_materials[SKY_MATERIAL_COUNT]; // How much sun & moon transition should affect horizon color float m_horizon_blend() { if (!m_sunlight_seen) return 0; float x = m_time_of_day >= 0.5 ? (1 - m_time_of_day) * 2 : m_time_of_day * 2; if (x <= 0.3) return 0; if (x <= 0.4) // when the sun and moon are aligned return (x - 0.3) * 10; if (x <= 0.5) return (0.5 - x) * 10; return 0; } // Mix two colors by a given amount video::SColor m_mix_scolor(video::SColor col1, video::SColor col2, f32 factor) { video::SColor result = video::SColor( col1.getAlpha() * (1 - factor) + col2.getAlpha() * factor, col1.getRed() * (1 - factor) + col2.getRed() * factor, col1.getGreen() * (1 - factor) + col2.getGreen() * factor, col1.getBlue() * (1 - factor) + col2.getBlue() * factor); return result; } video::SColorf m_mix_scolorf(video::SColorf col1, video::SColorf col2, f32 factor) { video::SColorf result = video::SColorf(col1.r * (1 - factor) + col2.r * factor, col1.g * (1 - factor) + col2.g * factor, col1.b * (1 - factor) + col2.b * factor, col1.a * (1 - factor) + col2.a * factor); return result; } bool m_visible = true; // Used when m_visible=false video::SColor m_fallback_bg_color = video::SColor(255, 255, 255, 255); bool m_first_update = true; float m_time_of_day; float m_time_brightness; bool m_sunlight_seen; float m_brightness = 0.5f; float m_cloud_brightness = 0.5f; bool m_clouds_visible; // Whether clouds are disabled due to player underground bool m_clouds_enabled = true; // Initialised to true, reset only by set_sky API bool m_directional_colored_fog; bool m_bodies_visible = true; // sun, moon, stars video::SColorf m_bgcolor_bright_f = video::SColorf(1.0f, 1.0f, 1.0f, 1.0f); video::SColorf m_skycolor_bright_f = video::SColorf(1.0f, 1.0f, 1.0f, 1.0f); video::SColorf m_cloudcolor_bright_f = video::SColorf(1.0f, 1.0f, 1.0f, 1.0f); video::SColor m_bgcolor; video::SColor m_skycolor; video::SColorf m_cloudcolor_f; v3f m_stars[SKY_STAR_COUNT]; video::ITexture *m_sun_texture; video::ITexture *m_moon_texture; video::ITexture *m_sun_tonemap; video::ITexture *m_moon_tonemap; };
pgimeno/minetest
src/client/sky.h
C++
mit
4,817
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "sound.h" // Global DummySoundManager singleton DummySoundManager dummySoundManager;
pgimeno/minetest
src/client/sound.cpp
C++
mit
880
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <set> #include <string> #include "irr_v3d.h" #include "../sound.h" class OnDemandSoundFetcher { public: virtual void fetchSounds(const std::string &name, std::set<std::string> &dst_paths, std::set<std::string> &dst_datas) = 0; }; class ISoundManager { public: virtual ~ISoundManager() = default; // Multiple sounds can be loaded per name; when played, the sound // should be chosen randomly from alternatives // Return value determines success/failure virtual bool loadSoundFile( const std::string &name, const std::string &filepath) = 0; virtual bool loadSoundData( const std::string &name, const std::string &filedata) = 0; virtual void updateListener( const v3f &pos, const v3f &vel, const v3f &at, const v3f &up) = 0; virtual void setListenerGain(float gain) = 0; // playSound functions return -1 on failure, otherwise a handle to the // sound. If name=="", call should be ignored without error. virtual int playSound(const std::string &name, bool loop, float volume, float fade = 0.0f, float pitch = 1.0f) = 0; virtual int playSoundAt(const std::string &name, bool loop, float volume, v3f pos, float pitch = 1.0f) = 0; virtual void stopSound(int sound) = 0; virtual bool soundExists(int sound) = 0; virtual void updateSoundPosition(int sound, v3f pos) = 0; virtual bool updateSoundGain(int id, float gain) = 0; virtual float getSoundGain(int id) = 0; virtual void step(float dtime) = 0; virtual void fadeSound(int sound, float step, float gain) = 0; int playSound(const SimpleSoundSpec &spec, bool loop) { return playSound(spec.name, loop, spec.gain, spec.fade, spec.pitch); } int playSoundAt(const SimpleSoundSpec &spec, bool loop, const v3f &pos) { return playSoundAt(spec.name, loop, spec.gain, pos, spec.pitch); } }; class DummySoundManager : public ISoundManager { public: virtual bool loadSoundFile(const std::string &name, const std::string &filepath) { return true; } virtual bool loadSoundData(const std::string &name, const std::string &filedata) { return true; } void updateListener(const v3f &pos, const v3f &vel, const v3f &at, const v3f &up) { } void setListenerGain(float gain) {} int playSound(const std::string &name, bool loop, float volume, float fade, float pitch) { return 0; } int playSoundAt(const std::string &name, bool loop, float volume, v3f pos, float pitch) { return 0; } void stopSound(int sound) {} bool soundExists(int sound) { return false; } void updateSoundPosition(int sound, v3f pos) {} bool updateSoundGain(int id, float gain) { return false; } float getSoundGain(int id) { return 0; } void step(float dtime) {} void fadeSound(int sound, float step, float gain) {} }; // Global DummySoundManager singleton extern DummySoundManager dummySoundManager;
pgimeno/minetest
src/client/sound.h
C++
mit
3,597
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> OpenAL support based on work by: Copyright (C) 2011 Sebastian 'Bahamada' Rühl Copyright (C) 2011 Cyriaque 'Cisoun' Skrapits <cysoun@gmail.com> Copyright (C) 2011 Giuseppe Bilotta <giuseppe.bilotta@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; ifnot, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "sound_openal.h" #if defined(_WIN32) #include <al.h> #include <alc.h> //#include <alext.h> #elif defined(__APPLE__) #include <OpenAL/al.h> #include <OpenAL/alc.h> //#include <OpenAL/alext.h> #else #include <AL/al.h> #include <AL/alc.h> #include <AL/alext.h> #endif #include <cmath> #include <vorbis/vorbisfile.h> #include <cassert> #include "log.h" #include "util/numeric.h" // myrand() #include "porting.h" #include <vector> #include <fstream> #include <unordered_map> #include <unordered_set> #define BUFFER_SIZE 30000 std::shared_ptr<SoundManagerSingleton> g_sound_manager_singleton; typedef std::unique_ptr<ALCdevice, void (*)(ALCdevice *p)> unique_ptr_alcdevice; typedef std::unique_ptr<ALCcontext, void(*)(ALCcontext *p)> unique_ptr_alccontext; static void delete_alcdevice(ALCdevice *p) { if (p) alcCloseDevice(p); } static void delete_alccontext(ALCcontext *p) { if (p) { alcMakeContextCurrent(nullptr); alcDestroyContext(p); } } static const char *alErrorString(ALenum err) { switch (err) { case AL_NO_ERROR: return "no error"; case AL_INVALID_NAME: return "invalid name"; case AL_INVALID_ENUM: return "invalid enum"; case AL_INVALID_VALUE: return "invalid value"; case AL_INVALID_OPERATION: return "invalid operation"; case AL_OUT_OF_MEMORY: return "out of memory"; default: return "<unknown OpenAL error>"; } } static ALenum warn_if_error(ALenum err, const char *desc) { if(err == AL_NO_ERROR) return err; warningstream<<desc<<": "<<alErrorString(err)<<std::endl; return err; } void f3_set(ALfloat *f3, v3f v) { f3[0] = v.X; f3[1] = v.Y; f3[2] = v.Z; } struct SoundBuffer { ALenum format; ALsizei freq; ALuint buffer_id; std::vector<char> buffer; }; SoundBuffer *load_opened_ogg_file(OggVorbis_File *oggFile, const std::string &filename_for_logging) { int endian = 0; // 0 for Little-Endian, 1 for Big-Endian int bitStream; long bytes; char array[BUFFER_SIZE]; // Local fixed size array vorbis_info *pInfo; SoundBuffer *snd = new SoundBuffer; // Get some information about the OGG file pInfo = ov_info(oggFile, -1); // Check the number of channels... always use 16-bit samples if(pInfo->channels == 1) snd->format = AL_FORMAT_MONO16; else snd->format = AL_FORMAT_STEREO16; // The frequency of the sampling rate snd->freq = pInfo->rate; // Keep reading until all is read do { // Read up to a buffer's worth of decoded sound data bytes = ov_read(oggFile, array, BUFFER_SIZE, endian, 2, 1, &bitStream); if(bytes < 0) { ov_clear(oggFile); infostream << "Audio: Error decoding " << filename_for_logging << std::endl; delete snd; return nullptr; } // Append to end of buffer snd->buffer.insert(snd->buffer.end(), array, array + bytes); } while (bytes > 0); alGenBuffers(1, &snd->buffer_id); alBufferData(snd->buffer_id, snd->format, &(snd->buffer[0]), snd->buffer.size(), snd->freq); ALenum error = alGetError(); if(error != AL_NO_ERROR){ infostream << "Audio: OpenAL error: " << alErrorString(error) << "preparing sound buffer" << std::endl; } infostream << "Audio file " << filename_for_logging << " loaded" << std::endl; // Clean up! ov_clear(oggFile); return snd; } SoundBuffer *load_ogg_from_file(const std::string &path) { OggVorbis_File oggFile; // Try opening the given file. // This requires libvorbis >= 1.3.2, as // previous versions expect a non-const char * if (ov_fopen(path.c_str(), &oggFile) != 0) { infostream << "Audio: Error opening " << path << " for decoding" << std::endl; return nullptr; } return load_opened_ogg_file(&oggFile, path); } struct BufferSource { const char *buf; size_t cur_offset; size_t len; }; size_t buffer_sound_read_func(void *ptr, size_t size, size_t nmemb, void *datasource) { BufferSource *s = (BufferSource *)datasource; size_t copied_size = MYMIN(s->len - s->cur_offset, size); memcpy(ptr, s->buf + s->cur_offset, copied_size); s->cur_offset += copied_size; return copied_size; } int buffer_sound_seek_func(void *datasource, ogg_int64_t offset, int whence) { BufferSource *s = (BufferSource *)datasource; if (whence == SEEK_SET) { if (offset < 0 || (size_t)MYMAX(offset, 0) >= s->len) { // offset out of bounds return -1; } s->cur_offset = offset; return 0; } else if (whence == SEEK_CUR) { if ((size_t)MYMIN(-offset, 0) > s->cur_offset || s->cur_offset + offset > s->len) { // offset out of bounds return -1; } s->cur_offset += offset; return 0; } // invalid whence param (SEEK_END doesn't have to be supported) return -1; } long BufferSourceell_func(void *datasource) { BufferSource *s = (BufferSource *)datasource; return s->cur_offset; } static ov_callbacks g_buffer_ov_callbacks = { &buffer_sound_read_func, &buffer_sound_seek_func, nullptr, &BufferSourceell_func }; SoundBuffer *load_ogg_from_buffer(const std::string &buf, const std::string &id_for_log) { OggVorbis_File oggFile; BufferSource s; s.buf = buf.c_str(); s.cur_offset = 0; s.len = buf.size(); if (ov_open_callbacks(&s, &oggFile, nullptr, 0, g_buffer_ov_callbacks) != 0) { infostream << "Audio: Error opening " << id_for_log << " for decoding" << std::endl; return nullptr; } return load_opened_ogg_file(&oggFile, id_for_log); } struct PlayingSound { ALuint source_id; bool loop; }; class SoundManagerSingleton { public: unique_ptr_alcdevice m_device; unique_ptr_alccontext m_context; public: SoundManagerSingleton() : m_device(nullptr, delete_alcdevice), m_context(nullptr, delete_alccontext) { if (!(m_device = unique_ptr_alcdevice(alcOpenDevice(nullptr), delete_alcdevice))) throw std::runtime_error("Audio: Global Initialization: Device Open"); if (!(m_context = unique_ptr_alccontext( alcCreateContext(m_device.get(), nullptr), delete_alccontext))) { throw std::runtime_error("Audio: Global Initialization: Context Create"); } if (!alcMakeContextCurrent(m_context.get())) throw std::runtime_error("Audio: Global Initialization: Context Current"); alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED); if (alGetError() != AL_NO_ERROR) throw std::runtime_error("Audio: Global Initialization: OpenAL Error"); infostream << "Audio: Global Initialized: OpenAL " << alGetString(AL_VERSION) << ", using " << alcGetString(m_device.get(), ALC_DEVICE_SPECIFIER) << std::endl; } ~SoundManagerSingleton() { infostream << "Audio: Global Deinitialized." << std::endl; } }; class OpenALSoundManager: public ISoundManager { private: OnDemandSoundFetcher *m_fetcher; ALCdevice *m_device; ALCcontext *m_context; int m_next_id; std::unordered_map<std::string, std::vector<SoundBuffer*>> m_buffers; std::unordered_map<int, PlayingSound*> m_sounds_playing; struct FadeState { FadeState() = default; FadeState(float step, float current_gain, float target_gain): step(step), current_gain(current_gain), target_gain(target_gain) {} float step; float current_gain; float target_gain; }; std::unordered_map<int, FadeState> m_sounds_fading; float m_fade_delay; public: OpenALSoundManager(SoundManagerSingleton *smg, OnDemandSoundFetcher *fetcher): m_fetcher(fetcher), m_device(smg->m_device.get()), m_context(smg->m_context.get()), m_next_id(1), m_fade_delay(0) { infostream << "Audio: Initialized: OpenAL " << std::endl; } ~OpenALSoundManager() { infostream << "Audio: Deinitializing..." << std::endl; std::unordered_set<int> source_del_list; for (const auto &sp : m_sounds_playing) source_del_list.insert(sp.first); for (const auto &id : source_del_list) deleteSound(id); for (auto &buffer : m_buffers) { for (SoundBuffer *sb : buffer.second) { delete sb; } buffer.second.clear(); } m_buffers.clear(); infostream << "Audio: Deinitialized." << std::endl; } void step(float dtime) { doFades(dtime); } void addBuffer(const std::string &name, SoundBuffer *buf) { std::unordered_map<std::string, std::vector<SoundBuffer*>>::iterator i = m_buffers.find(name); if(i != m_buffers.end()){ i->second.push_back(buf); return; } std::vector<SoundBuffer*> bufs; bufs.push_back(buf); m_buffers[name] = bufs; } SoundBuffer* getBuffer(const std::string &name) { std::unordered_map<std::string, std::vector<SoundBuffer*>>::iterator i = m_buffers.find(name); if(i == m_buffers.end()) return nullptr; std::vector<SoundBuffer*> &bufs = i->second; int j = myrand() % bufs.size(); return bufs[j]; } PlayingSound* createPlayingSound(SoundBuffer *buf, bool loop, float volume, float pitch) { infostream << "OpenALSoundManager: Creating playing sound" << std::endl; assert(buf); PlayingSound *sound = new PlayingSound; assert(sound); warn_if_error(alGetError(), "before createPlayingSound"); alGenSources(1, &sound->source_id); alSourcei(sound->source_id, AL_BUFFER, buf->buffer_id); alSourcei(sound->source_id, AL_SOURCE_RELATIVE, true); alSource3f(sound->source_id, AL_POSITION, 0, 0, 0); alSource3f(sound->source_id, AL_VELOCITY, 0, 0, 0); alSourcei(sound->source_id, AL_LOOPING, loop ? AL_TRUE : AL_FALSE); volume = std::fmax(0.0f, volume); alSourcef(sound->source_id, AL_GAIN, volume); alSourcef(sound->source_id, AL_PITCH, pitch); alSourcePlay(sound->source_id); warn_if_error(alGetError(), "createPlayingSound"); return sound; } PlayingSound* createPlayingSoundAt(SoundBuffer *buf, bool loop, float volume, v3f pos, float pitch) { infostream << "OpenALSoundManager: Creating positional playing sound" << std::endl; assert(buf); PlayingSound *sound = new PlayingSound; assert(sound); warn_if_error(alGetError(), "before createPlayingSoundAt"); alGenSources(1, &sound->source_id); alSourcei(sound->source_id, AL_BUFFER, buf->buffer_id); alSourcei(sound->source_id, AL_SOURCE_RELATIVE, false); alSource3f(sound->source_id, AL_POSITION, pos.X, pos.Y, pos.Z); alSource3f(sound->source_id, AL_VELOCITY, 0, 0, 0); // Use alDistanceModel(AL_INVERSE_DISTANCE_CLAMPED) and set reference // distance to clamp gain at <1 node distance, to avoid excessive // volume when closer alSourcef(sound->source_id, AL_REFERENCE_DISTANCE, 10.0f); alSourcei(sound->source_id, AL_LOOPING, loop ? AL_TRUE : AL_FALSE); // Multiply by 3 to compensate for reducing AL_REFERENCE_DISTANCE from // the previous value of 30 to the new value of 10 volume = std::fmax(0.0f, volume * 3.0f); alSourcef(sound->source_id, AL_GAIN, volume); alSourcef(sound->source_id, AL_PITCH, pitch); alSourcePlay(sound->source_id); warn_if_error(alGetError(), "createPlayingSoundAt"); return sound; } int playSoundRaw(SoundBuffer *buf, bool loop, float volume, float pitch) { assert(buf); PlayingSound *sound = createPlayingSound(buf, loop, volume, pitch); if(!sound) return -1; int id = m_next_id++; m_sounds_playing[id] = sound; return id; } int playSoundRawAt(SoundBuffer *buf, bool loop, float volume, const v3f &pos, float pitch) { assert(buf); PlayingSound *sound = createPlayingSoundAt(buf, loop, volume, pos, pitch); if(!sound) return -1; int id = m_next_id++; m_sounds_playing[id] = sound; return id; } void deleteSound(int id) { std::unordered_map<int, PlayingSound*>::iterator i = m_sounds_playing.find(id); if(i == m_sounds_playing.end()) return; PlayingSound *sound = i->second; alDeleteSources(1, &sound->source_id); delete sound; m_sounds_playing.erase(id); } /* If buffer does not exist, consult the fetcher */ SoundBuffer* getFetchBuffer(const std::string &name) { SoundBuffer *buf = getBuffer(name); if(buf) return buf; if(!m_fetcher) return nullptr; std::set<std::string> paths; std::set<std::string> datas; m_fetcher->fetchSounds(name, paths, datas); for (const std::string &path : paths) { loadSoundFile(name, path); } for (const std::string &data : datas) { loadSoundData(name, data); } return getBuffer(name); } // Remove stopped sounds void maintain() { verbosestream<<"OpenALSoundManager::maintain(): " <<m_sounds_playing.size()<<" playing sounds, " <<m_buffers.size()<<" sound names loaded"<<std::endl; std::unordered_set<int> del_list; for (const auto &sp : m_sounds_playing) { int id = sp.first; PlayingSound *sound = sp.second; // If not playing, remove it { ALint state; alGetSourcei(sound->source_id, AL_SOURCE_STATE, &state); if(state != AL_PLAYING){ del_list.insert(id); } } } if(!del_list.empty()) verbosestream<<"OpenALSoundManager::maintain(): deleting " <<del_list.size()<<" playing sounds"<<std::endl; for (int i : del_list) { deleteSound(i); } } /* Interface */ bool loadSoundFile(const std::string &name, const std::string &filepath) { SoundBuffer *buf = load_ogg_from_file(filepath); if (buf) addBuffer(name, buf); return false; } bool loadSoundData(const std::string &name, const std::string &filedata) { SoundBuffer *buf = load_ogg_from_buffer(filedata, name); if (buf) addBuffer(name, buf); return false; } void updateListener(const v3f &pos, const v3f &vel, const v3f &at, const v3f &up) { alListener3f(AL_POSITION, pos.X, pos.Y, pos.Z); alListener3f(AL_VELOCITY, vel.X, vel.Y, vel.Z); ALfloat f[6]; f3_set(f, at); f3_set(f+3, -up); alListenerfv(AL_ORIENTATION, f); warn_if_error(alGetError(), "updateListener"); } void setListenerGain(float gain) { alListenerf(AL_GAIN, gain); } int playSound(const std::string &name, bool loop, float volume, float fade, float pitch) { maintain(); if (name.empty()) return 0; SoundBuffer *buf = getFetchBuffer(name); if(!buf){ infostream << "OpenALSoundManager: \"" << name << "\" not found." << std::endl; return -1; } int handle = -1; if (fade > 0) { handle = playSoundRaw(buf, loop, 0.0f, pitch); fadeSound(handle, fade, volume); } else { handle = playSoundRaw(buf, loop, volume, pitch); } return handle; } int playSoundAt(const std::string &name, bool loop, float volume, v3f pos, float pitch) { maintain(); if (name.empty()) return 0; SoundBuffer *buf = getFetchBuffer(name); if(!buf){ infostream << "OpenALSoundManager: \"" << name << "\" not found." << std::endl; return -1; } return playSoundRawAt(buf, loop, volume, pos, pitch); } void stopSound(int sound) { maintain(); deleteSound(sound); } void fadeSound(int soundid, float step, float gain) { m_sounds_fading[soundid] = FadeState(step, getSoundGain(soundid), gain); } void doFades(float dtime) { m_fade_delay += dtime; if (m_fade_delay < 0.1f) return; float chkGain = 0; for (auto i = m_sounds_fading.begin(); i != m_sounds_fading.end();) { if (i->second.step < 0.f) chkGain = -(i->second.current_gain); else chkGain = i->second.current_gain; if (chkGain < i->second.target_gain) { i->second.current_gain += (i->second.step * m_fade_delay); i->second.current_gain = rangelim(i->second.current_gain, 0, 1); updateSoundGain(i->first, i->second.current_gain); ++i; } else { if (i->second.target_gain <= 0.f) stopSound(i->first); m_sounds_fading.erase(i++); } } m_fade_delay = 0; } bool soundExists(int sound) { maintain(); return (m_sounds_playing.count(sound) != 0); } void updateSoundPosition(int id, v3f pos) { auto i = m_sounds_playing.find(id); if (i == m_sounds_playing.end()) return; PlayingSound *sound = i->second; alSourcei(sound->source_id, AL_SOURCE_RELATIVE, false); alSource3f(sound->source_id, AL_POSITION, pos.X, pos.Y, pos.Z); alSource3f(sound->source_id, AL_VELOCITY, 0, 0, 0); alSourcef(sound->source_id, AL_REFERENCE_DISTANCE, 30.0); } bool updateSoundGain(int id, float gain) { auto i = m_sounds_playing.find(id); if (i == m_sounds_playing.end()) return false; PlayingSound *sound = i->second; alSourcef(sound->source_id, AL_GAIN, gain); return true; } float getSoundGain(int id) { auto i = m_sounds_playing.find(id); if (i == m_sounds_playing.end()) return 0; PlayingSound *sound = i->second; ALfloat gain; alGetSourcef(sound->source_id, AL_GAIN, &gain); return gain; } }; std::shared_ptr<SoundManagerSingleton> createSoundManagerSingleton() { return std::shared_ptr<SoundManagerSingleton>(new SoundManagerSingleton()); } ISoundManager *createOpenALSoundManager(SoundManagerSingleton *smg, OnDemandSoundFetcher *fetcher) { return new OpenALSoundManager(smg, fetcher); };
pgimeno/minetest
src/client/sound_openal.cpp
C++
mit
17,580
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <memory> #include "sound.h" class SoundManagerSingleton; extern std::shared_ptr<SoundManagerSingleton> g_sound_manager_singleton; std::shared_ptr<SoundManagerSingleton> createSoundManagerSingleton(); ISoundManager *createOpenALSoundManager( SoundManagerSingleton *smg, OnDemandSoundFetcher *fetcher);
pgimeno/minetest
src/client/sound_openal.h
C++
mit
1,114
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "tile.h" #include <algorithm> #include <ICameraSceneNode.h> #include "util/string.h" #include "util/container.h" #include "util/thread.h" #include "filesys.h" #include "settings.h" #include "mesh.h" #include "gamedef.h" #include "util/strfnd.h" #include "imagefilters.h" #include "guiscalingfilter.h" #include "renderingengine.h" #ifdef __ANDROID__ #include <GLES/gl.h> #endif /* A cache from texture name to texture path */ MutexedMap<std::string, std::string> g_texturename_to_path_cache; /* Replaces the filename extension. eg: std::string image = "a/image.png" replace_ext(image, "jpg") -> image = "a/image.jpg" Returns true on success. */ static bool replace_ext(std::string &path, const char *ext) { if (ext == NULL) return false; // Find place of last dot, fail if \ or / found. s32 last_dot_i = -1; for (s32 i=path.size()-1; i>=0; i--) { if (path[i] == '.') { last_dot_i = i; break; } if (path[i] == '\\' || path[i] == '/') break; } // If not found, return an empty string if (last_dot_i == -1) return false; // Else make the new path path = path.substr(0, last_dot_i+1) + ext; return true; } /* Find out the full path of an image by trying different filename extensions. If failed, return "". */ std::string getImagePath(std::string path) { // A NULL-ended list of possible image extensions const char *extensions[] = { "png", "jpg", "bmp", "tga", "pcx", "ppm", "psd", "wal", "rgb", NULL }; // If there is no extension, add one if (removeStringEnd(path, extensions).empty()) path = path + ".png"; // Check paths until something is found to exist const char **ext = extensions; do{ bool r = replace_ext(path, *ext); if (!r) return ""; if (fs::PathExists(path)) return path; } while((++ext) != NULL); return ""; } /* Gets the path to a texture by first checking if the texture exists in texture_path and if not, using the data path. Checks all supported extensions by replacing the original extension. If not found, returns "". Utilizes a thread-safe cache. */ std::string getTexturePath(const std::string &filename) { std::string fullpath; /* Check from cache */ bool incache = g_texturename_to_path_cache.get(filename, &fullpath); if (incache) return fullpath; /* Check from texture_path */ for (const auto &path : getTextureDirs()) { std::string testpath = path + DIR_DELIM + filename; // Check all filename extensions. Returns "" if not found. fullpath = getImagePath(testpath); if (!fullpath.empty()) break; } /* Check from default data directory */ if (fullpath.empty()) { std::string base_path = porting::path_share + DIR_DELIM + "textures" + DIR_DELIM + "base" + DIR_DELIM + "pack"; std::string testpath = base_path + DIR_DELIM + filename; // Check all filename extensions. Returns "" if not found. fullpath = getImagePath(testpath); } // Add to cache (also an empty result is cached) g_texturename_to_path_cache.set(filename, fullpath); // Finally return it return fullpath; } void clearTextureNameCache() { g_texturename_to_path_cache.clear(); } /* Stores internal information about a texture. */ struct TextureInfo { std::string name; video::ITexture *texture; TextureInfo( const std::string &name_, video::ITexture *texture_=NULL ): name(name_), texture(texture_) { } }; /* SourceImageCache: A cache used for storing source images. */ class SourceImageCache { public: ~SourceImageCache() { for (auto &m_image : m_images) { m_image.second->drop(); } m_images.clear(); } void insert(const std::string &name, video::IImage *img, bool prefer_local) { assert(img); // Pre-condition // Remove old image std::map<std::string, video::IImage*>::iterator n; n = m_images.find(name); if (n != m_images.end()){ if (n->second) n->second->drop(); } video::IImage* toadd = img; bool need_to_grab = true; // Try to use local texture instead if asked to if (prefer_local){ std::string path = getTexturePath(name); if (!path.empty()) { video::IImage *img2 = RenderingEngine::get_video_driver()-> createImageFromFile(path.c_str()); if (img2){ toadd = img2; need_to_grab = false; } } } if (need_to_grab) toadd->grab(); m_images[name] = toadd; } video::IImage* get(const std::string &name) { std::map<std::string, video::IImage*>::iterator n; n = m_images.find(name); if (n != m_images.end()) return n->second; return NULL; } // Primarily fetches from cache, secondarily tries to read from filesystem video::IImage *getOrLoad(const std::string &name) { std::map<std::string, video::IImage*>::iterator n; n = m_images.find(name); if (n != m_images.end()){ n->second->grab(); // Grab for caller return n->second; } video::IVideoDriver *driver = RenderingEngine::get_video_driver(); std::string path = getTexturePath(name); if (path.empty()) { infostream<<"SourceImageCache::getOrLoad(): No path found for \"" <<name<<"\""<<std::endl; return NULL; } infostream<<"SourceImageCache::getOrLoad(): Loading path \""<<path <<"\""<<std::endl; video::IImage *img = driver->createImageFromFile(path.c_str()); if (img){ m_images[name] = img; img->grab(); // Grab for caller } return img; } private: std::map<std::string, video::IImage*> m_images; }; /* TextureSource */ class TextureSource : public IWritableTextureSource { public: TextureSource(); virtual ~TextureSource(); /* Example case: Now, assume a texture with the id 1 exists, and has the name "stone.png^mineral1". Then a random thread calls getTextureId for a texture called "stone.png^mineral1^crack0". ...Now, WTF should happen? Well: - getTextureId strips off stuff recursively from the end until the remaining part is found, or nothing is left when something is stripped out But it is slow to search for textures by names and modify them like that? - ContentFeatures is made to contain ids for the basic plain textures - Crack textures can be slow by themselves, but the framework must be fast. Example case #2: - Assume a texture with the id 1 exists, and has the name "stone.png^mineral_coal.png". - Now getNodeTile() stumbles upon a node which uses texture id 1, and determines that MATERIAL_FLAG_CRACK must be applied to the tile - MapBlockMesh::animate() finds the MATERIAL_FLAG_CRACK and has received the current crack level 0 from the client. It finds out the name of the texture with getTextureName(1), appends "^crack0" to it and gets a new texture id with getTextureId("stone.png^mineral_coal.png^crack0"). */ /* Gets a texture id from cache or - if main thread, generates the texture, adds to cache and returns id. - if other thread, adds to request queue and waits for main thread. The id 0 points to a NULL texture. It is returned in case of error. */ u32 getTextureId(const std::string &name); // Finds out the name of a cached texture. std::string getTextureName(u32 id); /* If texture specified by the name pointed by the id doesn't exist, create it, then return the cached texture. Can be called from any thread. If called from some other thread and not found in cache, the call is queued to the main thread for processing. */ video::ITexture* getTexture(u32 id); video::ITexture* getTexture(const std::string &name, u32 *id = NULL); /* Get a texture specifically intended for mesh application, i.e. not HUD, compositing, or other 2D use. This texture may be a different size and may have had additional filters applied. */ video::ITexture* getTextureForMesh(const std::string &name, u32 *id); virtual Palette* getPalette(const std::string &name); bool isKnownSourceImage(const std::string &name) { bool is_known = false; bool cache_found = m_source_image_existence.get(name, &is_known); if (cache_found) return is_known; // Not found in cache; find out if a local file exists is_known = (!getTexturePath(name).empty()); m_source_image_existence.set(name, is_known); return is_known; } // Processes queued texture requests from other threads. // Shall be called from the main thread. void processQueue(); // Insert an image into the cache without touching the filesystem. // Shall be called from the main thread. void insertSourceImage(const std::string &name, video::IImage *img); // Rebuild images and textures from the current set of source images // Shall be called from the main thread. void rebuildImagesAndTextures(); video::ITexture* getNormalTexture(const std::string &name); video::SColor getTextureAverageColor(const std::string &name); video::ITexture *getShaderFlagsTexture(bool normamap_present); private: // The id of the thread that is allowed to use irrlicht directly std::thread::id m_main_thread; // Cache of source images // This should be only accessed from the main thread SourceImageCache m_sourcecache; // Generate a texture u32 generateTexture(const std::string &name); // Generate image based on a string like "stone.png" or "[crack:1:0". // if baseimg is NULL, it is created. Otherwise stuff is made on it. bool generateImagePart(std::string part_of_name, video::IImage *& baseimg); /*! Generates an image from a full string like * "stone.png^mineral_coal.png^[crack:1:0". * Shall be called from the main thread. * The returned Image should be dropped. */ video::IImage* generateImage(const std::string &name); // Thread-safe cache of what source images are known (true = known) MutexedMap<std::string, bool> m_source_image_existence; // A texture id is index in this array. // The first position contains a NULL texture. std::vector<TextureInfo> m_textureinfo_cache; // Maps a texture name to an index in the former. std::map<std::string, u32> m_name_to_id; // The two former containers are behind this mutex std::mutex m_textureinfo_cache_mutex; // Queued texture fetches (to be processed by the main thread) RequestQueue<std::string, u32, u8, u8> m_get_texture_queue; // Textures that have been overwritten with other ones // but can't be deleted because the ITexture* might still be used std::vector<video::ITexture*> m_texture_trash; // Maps image file names to loaded palettes. std::unordered_map<std::string, Palette> m_palettes; // Cached settings needed for making textures from meshes bool m_setting_trilinear_filter; bool m_setting_bilinear_filter; bool m_setting_anisotropic_filter; }; IWritableTextureSource *createTextureSource() { return new TextureSource(); } TextureSource::TextureSource() { m_main_thread = std::this_thread::get_id(); // Add a NULL TextureInfo as the first index, named "" m_textureinfo_cache.emplace_back(""); m_name_to_id[""] = 0; // Cache some settings // Note: Since this is only done once, the game must be restarted // for these settings to take effect m_setting_trilinear_filter = g_settings->getBool("trilinear_filter"); m_setting_bilinear_filter = g_settings->getBool("bilinear_filter"); m_setting_anisotropic_filter = g_settings->getBool("anisotropic_filter"); } TextureSource::~TextureSource() { video::IVideoDriver *driver = RenderingEngine::get_video_driver(); unsigned int textures_before = driver->getTextureCount(); for (const auto &iter : m_textureinfo_cache) { //cleanup texture if (iter.texture) driver->removeTexture(iter.texture); } m_textureinfo_cache.clear(); for (auto t : m_texture_trash) { //cleanup trashed texture driver->removeTexture(t); } infostream << "~TextureSource() "<< textures_before << "/" << driver->getTextureCount() << std::endl; } u32 TextureSource::getTextureId(const std::string &name) { //infostream<<"getTextureId(): \""<<name<<"\""<<std::endl; { /* See if texture already exists */ MutexAutoLock lock(m_textureinfo_cache_mutex); std::map<std::string, u32>::iterator n; n = m_name_to_id.find(name); if (n != m_name_to_id.end()) { return n->second; } } /* Get texture */ if (std::this_thread::get_id() == m_main_thread) { return generateTexture(name); } infostream<<"getTextureId(): Queued: name=\""<<name<<"\""<<std::endl; // We're gonna ask the result to be put into here static ResultQueue<std::string, u32, u8, u8> result_queue; // Throw a request in m_get_texture_queue.add(name, 0, 0, &result_queue); try { while(true) { // Wait result for a second GetResult<std::string, u32, u8, u8> result = result_queue.pop_front(1000); if (result.key == name) { return result.item; } } } catch(ItemNotFoundException &e) { errorstream << "Waiting for texture " << name << " timed out." << std::endl; return 0; } infostream << "getTextureId(): Failed" << std::endl; return 0; } // Draw an image on top of an another one, using the alpha channel of the // source image static void blit_with_alpha(video::IImage *src, video::IImage *dst, v2s32 src_pos, v2s32 dst_pos, v2u32 size); // Like blit_with_alpha, but only modifies destination pixels that // are fully opaque static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst, v2s32 src_pos, v2s32 dst_pos, v2u32 size); // Apply a color to an image. Uses an int (0-255) to calculate the ratio. // If the ratio is 255 or -1 and keep_alpha is true, then it multiples the // color alpha with the destination alpha. // Otherwise, any pixels that are not fully transparent get the color alpha. static void apply_colorize(video::IImage *dst, v2u32 dst_pos, v2u32 size, const video::SColor &color, int ratio, bool keep_alpha); // paint a texture using the given color static void apply_multiplication(video::IImage *dst, v2u32 dst_pos, v2u32 size, const video::SColor &color); // Apply a mask to an image static void apply_mask(video::IImage *mask, video::IImage *dst, v2s32 mask_pos, v2s32 dst_pos, v2u32 size); // Draw or overlay a crack static void draw_crack(video::IImage *crack, video::IImage *dst, bool use_overlay, s32 frame_count, s32 progression, video::IVideoDriver *driver, u8 tiles = 1); // Brighten image void brighten(video::IImage *image); // Parse a transform name u32 parseImageTransform(const std::string& s); // Apply transform to image dimension core::dimension2d<u32> imageTransformDimension(u32 transform, core::dimension2d<u32> dim); // Apply transform to image data void imageTransform(u32 transform, video::IImage *src, video::IImage *dst); /* This method generates all the textures */ u32 TextureSource::generateTexture(const std::string &name) { //infostream << "generateTexture(): name=\"" << name << "\"" << std::endl; // Empty name means texture 0 if (name.empty()) { infostream<<"generateTexture(): name is empty"<<std::endl; return 0; } { /* See if texture already exists */ MutexAutoLock lock(m_textureinfo_cache_mutex); std::map<std::string, u32>::iterator n; n = m_name_to_id.find(name); if (n != m_name_to_id.end()) { return n->second; } } /* Calling only allowed from main thread */ if (std::this_thread::get_id() != m_main_thread) { errorstream<<"TextureSource::generateTexture() " "called not from main thread"<<std::endl; return 0; } video::IVideoDriver *driver = RenderingEngine::get_video_driver(); sanity_check(driver); video::IImage *img = generateImage(name); video::ITexture *tex = NULL; if (img != NULL) { #ifdef __ANDROID__ img = Align2Npot2(img, driver); #endif // Create texture from resulting image tex = driver->addTexture(name.c_str(), img); guiScalingCache(io::path(name.c_str()), driver, img); img->drop(); } /* Add texture to caches (add NULL textures too) */ MutexAutoLock lock(m_textureinfo_cache_mutex); u32 id = m_textureinfo_cache.size(); TextureInfo ti(name, tex); m_textureinfo_cache.push_back(ti); m_name_to_id[name] = id; return id; } std::string TextureSource::getTextureName(u32 id) { MutexAutoLock lock(m_textureinfo_cache_mutex); if (id >= m_textureinfo_cache.size()) { errorstream<<"TextureSource::getTextureName(): id="<<id <<" >= m_textureinfo_cache.size()=" <<m_textureinfo_cache.size()<<std::endl; return ""; } return m_textureinfo_cache[id].name; } video::ITexture* TextureSource::getTexture(u32 id) { MutexAutoLock lock(m_textureinfo_cache_mutex); if (id >= m_textureinfo_cache.size()) return NULL; return m_textureinfo_cache[id].texture; } video::ITexture* TextureSource::getTexture(const std::string &name, u32 *id) { u32 actual_id = getTextureId(name); if (id){ *id = actual_id; } return getTexture(actual_id); } video::ITexture* TextureSource::getTextureForMesh(const std::string &name, u32 *id) { return getTexture(name + "^[applyfiltersformesh", id); } Palette* TextureSource::getPalette(const std::string &name) { // Only the main thread may load images sanity_check(std::this_thread::get_id() == m_main_thread); if (name.empty()) return NULL; auto it = m_palettes.find(name); if (it == m_palettes.end()) { // Create palette video::IImage *img = generateImage(name); if (!img) { warningstream << "TextureSource::getPalette(): palette \"" << name << "\" could not be loaded." << std::endl; return NULL; } Palette new_palette; u32 w = img->getDimension().Width; u32 h = img->getDimension().Height; // Real area of the image u32 area = h * w; if (area == 0) return NULL; if (area > 256) { warningstream << "TextureSource::getPalette(): the specified" << " palette image \"" << name << "\" is larger than 256" << " pixels, using the first 256." << std::endl; area = 256; } else if (256 % area != 0) warningstream << "TextureSource::getPalette(): the " << "specified palette image \"" << name << "\" does not " << "contain power of two pixels." << std::endl; // We stretch the palette so it will fit 256 values // This many param2 values will have the same color u32 step = 256 / area; // For each pixel in the image for (u32 i = 0; i < area; i++) { video::SColor c = img->getPixel(i % w, i / w); // Fill in palette with 'step' colors for (u32 j = 0; j < step; j++) new_palette.push_back(c); } img->drop(); // Fill in remaining elements while (new_palette.size() < 256) new_palette.emplace_back(0xFFFFFFFF); m_palettes[name] = new_palette; it = m_palettes.find(name); } if (it != m_palettes.end()) return &((*it).second); return NULL; } void TextureSource::processQueue() { /* Fetch textures */ //NOTE this is only thread safe for ONE consumer thread! if (!m_get_texture_queue.empty()) { GetRequest<std::string, u32, u8, u8> request = m_get_texture_queue.pop(); /*infostream<<"TextureSource::processQueue(): " <<"got texture request with " <<"name=\""<<request.key<<"\"" <<std::endl;*/ m_get_texture_queue.pushResult(request, generateTexture(request.key)); } } void TextureSource::insertSourceImage(const std::string &name, video::IImage *img) { //infostream<<"TextureSource::insertSourceImage(): name="<<name<<std::endl; sanity_check(std::this_thread::get_id() == m_main_thread); m_sourcecache.insert(name, img, true); m_source_image_existence.set(name, true); } void TextureSource::rebuildImagesAndTextures() { MutexAutoLock lock(m_textureinfo_cache_mutex); video::IVideoDriver *driver = RenderingEngine::get_video_driver(); sanity_check(driver); // Recreate textures for (TextureInfo &ti : m_textureinfo_cache) { video::IImage *img = generateImage(ti.name); #ifdef __ANDROID__ img = Align2Npot2(img, driver); #endif // Create texture from resulting image video::ITexture *t = NULL; if (img) { t = driver->addTexture(ti.name.c_str(), img); guiScalingCache(io::path(ti.name.c_str()), driver, img); img->drop(); } video::ITexture *t_old = ti.texture; // Replace texture ti.texture = t; if (t_old) m_texture_trash.push_back(t_old); } } inline static void applyShadeFactor(video::SColor &color, u32 factor) { u32 f = core::clamp<u32>(factor, 0, 256); color.setRed(color.getRed() * f / 256); color.setGreen(color.getGreen() * f / 256); color.setBlue(color.getBlue() * f / 256); } static video::IImage *createInventoryCubeImage( video::IImage *top, video::IImage *left, video::IImage *right) { core::dimension2du size_top = top->getDimension(); core::dimension2du size_left = left->getDimension(); core::dimension2du size_right = right->getDimension(); u32 size = npot2(std::max({ size_top.Width, size_top.Height, size_left.Width, size_left.Height, size_right.Width, size_right.Height, })); // It must be divisible by 4, to let everything work correctly. // But it is a power of 2, so being at least 4 is the same. // And the resulting texture should't be too large as well. size = core::clamp<u32>(size, 4, 64); // With such parameters, the cube fits exactly, touching each image line // from `0` to `cube_size - 1`. (Note that division is exact here). u32 cube_size = 9 * size; u32 offset = size / 2; video::IVideoDriver *driver = RenderingEngine::get_video_driver(); auto lock_image = [size, driver] (video::IImage *&image) -> const u32 * { image->grab(); core::dimension2du dim = image->getDimension(); video::ECOLOR_FORMAT format = image->getColorFormat(); if (dim.Width != size || dim.Height != size || format != video::ECF_A8R8G8B8) { video::IImage *scaled = driver->createImage(video::ECF_A8R8G8B8, {size, size}); image->copyToScaling(scaled); image->drop(); image = scaled; } sanity_check(image->getPitch() == 4 * size); return reinterpret_cast<u32 *>(image->lock()); }; auto free_image = [] (video::IImage *image) -> void { image->unlock(); image->drop(); }; video::IImage *result = driver->createImage(video::ECF_A8R8G8B8, {cube_size, cube_size}); sanity_check(result->getPitch() == 4 * cube_size); result->fill(video::SColor(0x00000000u)); u32 *target = reinterpret_cast<u32 *>(result->lock()); // Draws single cube face // `shade_factor` is face brightness, in range [0.0, 1.0] // (xu, xv, x1; yu, yv, y1) form coordinate transformation matrix // `offsets` list pixels to be drawn for single source pixel auto draw_image = [=] (video::IImage *image, float shade_factor, s16 xu, s16 xv, s16 x1, s16 yu, s16 yv, s16 y1, std::initializer_list<v2s16> offsets) -> void { u32 brightness = core::clamp<u32>(256 * shade_factor, 0, 256); const u32 *source = lock_image(image); for (u16 v = 0; v < size; v++) { for (u16 u = 0; u < size; u++) { video::SColor pixel(*source); applyShadeFactor(pixel, brightness); s16 x = xu * u + xv * v + x1; s16 y = yu * u + yv * v + y1; for (const auto &off : offsets) target[(y + off.Y) * cube_size + (x + off.X) + offset] = pixel.color; source++; } } free_image(image); }; draw_image(top, 1.000000f, 4, -4, 4 * (size - 1), 2, 2, 0, { {2, 0}, {3, 0}, {4, 0}, {5, 0}, {0, 1}, {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {6, 1}, {7, 1}, {2, 2}, {3, 2}, {4, 2}, {5, 2}, }); draw_image(left, 0.836660f, 4, 0, 0, 2, 5, 2 * size, { {0, 0}, {1, 0}, {0, 1}, {1, 1}, {2, 1}, {3, 1}, {0, 2}, {1, 2}, {2, 2}, {3, 2}, {0, 3}, {1, 3}, {2, 3}, {3, 3}, {0, 4}, {1, 4}, {2, 4}, {3, 4}, {2, 5}, {3, 5}, }); draw_image(right, 0.670820f, 4, 0, 4 * size, -2, 5, 4 * size - 2, { {2, 0}, {3, 0}, {0, 1}, {1, 1}, {2, 1}, {3, 1}, {0, 2}, {1, 2}, {2, 2}, {3, 2}, {0, 3}, {1, 3}, {2, 3}, {3, 3}, {0, 4}, {1, 4}, {2, 4}, {3, 4}, {0, 5}, {1, 5}, }); result->unlock(); return result; } video::IImage* TextureSource::generateImage(const std::string &name) { // Get the base image const char separator = '^'; const char escape = '\\'; const char paren_open = '('; const char paren_close = ')'; // Find last separator in the name s32 last_separator_pos = -1; u8 paren_bal = 0; for (s32 i = name.size() - 1; i >= 0; i--) { if (i > 0 && name[i-1] == escape) continue; switch (name[i]) { case separator: if (paren_bal == 0) { last_separator_pos = i; i = -1; // break out of loop } break; case paren_open: if (paren_bal == 0) { errorstream << "generateImage(): unbalanced parentheses" << "(extranous '(') while generating texture \"" << name << "\"" << std::endl; return NULL; } paren_bal--; break; case paren_close: paren_bal++; break; default: break; } } if (paren_bal > 0) { errorstream << "generateImage(): unbalanced parentheses" << "(missing matching '(') while generating texture \"" << name << "\"" << std::endl; return NULL; } video::IImage *baseimg = NULL; /* If separator was found, make the base image using a recursive call. */ if (last_separator_pos != -1) { baseimg = generateImage(name.substr(0, last_separator_pos)); } /* Parse out the last part of the name of the image and act according to it */ std::string last_part_of_name = name.substr(last_separator_pos + 1); /* If this name is enclosed in parentheses, generate it and blit it onto the base image */ if (last_part_of_name[0] == paren_open && last_part_of_name[last_part_of_name.size() - 1] == paren_close) { std::string name2 = last_part_of_name.substr(1, last_part_of_name.size() - 2); video::IImage *tmp = generateImage(name2); if (!tmp) { errorstream << "generateImage(): " "Failed to generate \"" << name2 << "\"" << std::endl; return NULL; } core::dimension2d<u32> dim = tmp->getDimension(); if (baseimg) { blit_with_alpha(tmp, baseimg, v2s32(0, 0), v2s32(0, 0), dim); tmp->drop(); } else { baseimg = tmp; } } else if (!generateImagePart(last_part_of_name, baseimg)) { // Generate image according to part of name errorstream << "generateImage(): " "Failed to generate \"" << last_part_of_name << "\"" << std::endl; } // If no resulting image, print a warning if (baseimg == NULL) { errorstream << "generateImage(): baseimg is NULL (attempted to" " create texture \"" << name << "\")" << std::endl; } return baseimg; } #ifdef __ANDROID__ #include <GLES/gl.h> /** * Check and align image to npot2 if required by hardware * @param image image to check for npot2 alignment * @param driver driver to use for image operations * @return image or copy of image aligned to npot2 */ inline u16 get_GL_major_version() { const GLubyte *gl_version = glGetString(GL_VERSION); return (u16) (gl_version[0] - '0'); } video::IImage * Align2Npot2(video::IImage * image, video::IVideoDriver* driver) { if (image == NULL) { return image; } core::dimension2d<u32> dim = image->getDimension(); // Only GLES2 is trusted to correctly report npot support // Note: we cache the boolean result. GL context will never change on Android. static const bool hasNPotSupport = get_GL_major_version() > 1 && glGetString(GL_EXTENSIONS) && strstr((char *)glGetString(GL_EXTENSIONS), "GL_OES_texture_npot"); if (hasNPotSupport) return image; unsigned int height = npot2(dim.Height); unsigned int width = npot2(dim.Width); if ((dim.Height == height) && (dim.Width == width)) { return image; } if (dim.Height > height) { height *= 2; } if (dim.Width > width) { width *= 2; } video::IImage *targetimage = driver->createImage(video::ECF_A8R8G8B8, core::dimension2d<u32>(width, height)); if (targetimage != NULL) { image->copyToScaling(targetimage); } image->drop(); return targetimage; } #endif static std::string unescape_string(const std::string &str, const char esc = '\\') { std::string out; size_t pos = 0, cpos; out.reserve(str.size()); while (1) { cpos = str.find_first_of(esc, pos); if (cpos == std::string::npos) { out += str.substr(pos); break; } out += str.substr(pos, cpos - pos) + str[cpos + 1]; pos = cpos + 2; } return out; } bool TextureSource::generateImagePart(std::string part_of_name, video::IImage *& baseimg) { const char escape = '\\'; // same as in generateImage() video::IVideoDriver *driver = RenderingEngine::get_video_driver(); sanity_check(driver); // Stuff starting with [ are special commands if (part_of_name.empty() || part_of_name[0] != '[') { video::IImage *image = m_sourcecache.getOrLoad(part_of_name); #ifdef __ANDROID__ image = Align2Npot2(image, driver); #endif if (image == NULL) { if (!part_of_name.empty()) { // Do not create normalmap dummies if (part_of_name.find("_normal.png") != std::string::npos) { warningstream << "generateImage(): Could not load normal map \"" << part_of_name << "\"" << std::endl; return true; } errorstream << "generateImage(): Could not load image \"" << part_of_name << "\" while building texture; " "Creating a dummy image" << std::endl; } // Just create a dummy image //core::dimension2d<u32> dim(2,2); core::dimension2d<u32> dim(1,1); image = driver->createImage(video::ECF_A8R8G8B8, dim); sanity_check(image != NULL); /*image->setPixel(0,0, video::SColor(255,255,0,0)); image->setPixel(1,0, video::SColor(255,0,255,0)); image->setPixel(0,1, video::SColor(255,0,0,255)); image->setPixel(1,1, video::SColor(255,255,0,255));*/ image->setPixel(0,0, video::SColor(255,myrand()%256, myrand()%256,myrand()%256)); /*image->setPixel(1,0, video::SColor(255,myrand()%256, myrand()%256,myrand()%256)); image->setPixel(0,1, video::SColor(255,myrand()%256, myrand()%256,myrand()%256)); image->setPixel(1,1, video::SColor(255,myrand()%256, myrand()%256,myrand()%256));*/ } // If base image is NULL, load as base. if (baseimg == NULL) { //infostream<<"Setting "<<part_of_name<<" as base"<<std::endl; /* Copy it this way to get an alpha channel. Otherwise images with alpha cannot be blitted on images that don't have alpha in the original file. */ core::dimension2d<u32> dim = image->getDimension(); baseimg = driver->createImage(video::ECF_A8R8G8B8, dim); image->copyTo(baseimg); } // Else blit on base. else { //infostream<<"Blitting "<<part_of_name<<" on base"<<std::endl; // Size of the copied area core::dimension2d<u32> dim = image->getDimension(); //core::dimension2d<u32> dim(16,16); // Position to copy the blitted to in the base image core::position2d<s32> pos_to(0,0); // Position to copy the blitted from in the blitted image core::position2d<s32> pos_from(0,0); // Blit /*image->copyToWithAlpha(baseimg, pos_to, core::rect<s32>(pos_from, dim), video::SColor(255,255,255,255), NULL);*/ core::dimension2d<u32> dim_dst = baseimg->getDimension(); if (dim == dim_dst) { blit_with_alpha(image, baseimg, pos_from, pos_to, dim); } else if (dim.Width * dim.Height < dim_dst.Width * dim_dst.Height) { // Upscale overlying image video::IImage *scaled_image = RenderingEngine::get_video_driver()-> createImage(video::ECF_A8R8G8B8, dim_dst); image->copyToScaling(scaled_image); blit_with_alpha(scaled_image, baseimg, pos_from, pos_to, dim_dst); scaled_image->drop(); } else { // Upscale base image video::IImage *scaled_base = RenderingEngine::get_video_driver()-> createImage(video::ECF_A8R8G8B8, dim); baseimg->copyToScaling(scaled_base); baseimg->drop(); baseimg = scaled_base; blit_with_alpha(image, baseimg, pos_from, pos_to, dim); } } //cleanup image->drop(); } else { // A special texture modification /*infostream<<"generateImage(): generating special " <<"modification \""<<part_of_name<<"\"" <<std::endl;*/ /* [crack:N:P [cracko:N:P Adds a cracking texture N = animation frame count, P = crack progression */ if (str_starts_with(part_of_name, "[crack")) { if (baseimg == NULL) { errorstream<<"generateImagePart(): baseimg == NULL " <<"for part_of_name=\""<<part_of_name <<"\", cancelling."<<std::endl; return false; } // Crack image number and overlay option // Format: crack[o][:<tiles>]:<frame_count>:<frame> bool use_overlay = (part_of_name[6] == 'o'); Strfnd sf(part_of_name); sf.next(":"); s32 frame_count = stoi(sf.next(":")); s32 progression = stoi(sf.next(":")); s32 tiles = 1; // Check whether there is the <tiles> argument, that is, // whether there are 3 arguments. If so, shift values // as the first and not the last argument is optional. auto s = sf.next(":"); if (!s.empty()) { tiles = frame_count; frame_count = progression; progression = stoi(s); } if (progression >= 0) { /* Load crack image. It is an image with a number of cracking stages horizontally tiled. */ video::IImage *img_crack = m_sourcecache.getOrLoad( "crack_anylength.png"); if (img_crack) { draw_crack(img_crack, baseimg, use_overlay, frame_count, progression, driver, tiles); img_crack->drop(); } } } /* [combine:WxH:X,Y=filename:X,Y=filename2 Creates a bigger texture from any amount of smaller ones */ else if (str_starts_with(part_of_name, "[combine")) { Strfnd sf(part_of_name); sf.next(":"); u32 w0 = stoi(sf.next("x")); u32 h0 = stoi(sf.next(":")); core::dimension2d<u32> dim(w0,h0); if (baseimg == NULL) { baseimg = driver->createImage(video::ECF_A8R8G8B8, dim); baseimg->fill(video::SColor(0,0,0,0)); } while (!sf.at_end()) { u32 x = stoi(sf.next(",")); u32 y = stoi(sf.next("=")); std::string filename = unescape_string(sf.next_esc(":", escape), escape); infostream<<"Adding \""<<filename <<"\" to combined ("<<x<<","<<y<<")" <<std::endl; video::IImage *img = generateImage(filename); if (img) { core::dimension2d<u32> dim = img->getDimension(); infostream<<"Size "<<dim.Width <<"x"<<dim.Height<<std::endl; core::position2d<s32> pos_base(x, y); video::IImage *img2 = driver->createImage(video::ECF_A8R8G8B8, dim); img->copyTo(img2); img->drop(); /*img2->copyToWithAlpha(baseimg, pos_base, core::rect<s32>(v2s32(0,0), dim), video::SColor(255,255,255,255), NULL);*/ blit_with_alpha(img2, baseimg, v2s32(0,0), pos_base, dim); img2->drop(); } else { errorstream << "generateImagePart(): Failed to load image \"" << filename << "\" for [combine" << std::endl; } } } /* [brighten */ else if (str_starts_with(part_of_name, "[brighten")) { if (baseimg == NULL) { errorstream<<"generateImagePart(): baseimg==NULL " <<"for part_of_name=\""<<part_of_name <<"\", cancelling."<<std::endl; return false; } brighten(baseimg); } /* [noalpha Make image completely opaque. Used for the leaves texture when in old leaves mode, so that the transparent parts don't look completely black when simple alpha channel is used for rendering. */ else if (str_starts_with(part_of_name, "[noalpha")) { if (baseimg == NULL){ errorstream<<"generateImagePart(): baseimg==NULL " <<"for part_of_name=\""<<part_of_name <<"\", cancelling."<<std::endl; return false; } core::dimension2d<u32> dim = baseimg->getDimension(); // Set alpha to full for (u32 y=0; y<dim.Height; y++) for (u32 x=0; x<dim.Width; x++) { video::SColor c = baseimg->getPixel(x,y); c.setAlpha(255); baseimg->setPixel(x,y,c); } } /* [makealpha:R,G,B Convert one color to transparent. */ else if (str_starts_with(part_of_name, "[makealpha:")) { if (baseimg == NULL) { errorstream<<"generateImagePart(): baseimg == NULL " <<"for part_of_name=\""<<part_of_name <<"\", cancelling."<<std::endl; return false; } Strfnd sf(part_of_name.substr(11)); u32 r1 = stoi(sf.next(",")); u32 g1 = stoi(sf.next(",")); u32 b1 = stoi(sf.next("")); core::dimension2d<u32> dim = baseimg->getDimension(); /*video::IImage *oldbaseimg = baseimg; baseimg = driver->createImage(video::ECF_A8R8G8B8, dim); oldbaseimg->copyTo(baseimg); oldbaseimg->drop();*/ // Set alpha to full for (u32 y=0; y<dim.Height; y++) for (u32 x=0; x<dim.Width; x++) { video::SColor c = baseimg->getPixel(x,y); u32 r = c.getRed(); u32 g = c.getGreen(); u32 b = c.getBlue(); if (!(r == r1 && g == g1 && b == b1)) continue; c.setAlpha(0); baseimg->setPixel(x,y,c); } } /* [transformN Rotates and/or flips the image. N can be a number (between 0 and 7) or a transform name. Rotations are counter-clockwise. 0 I identity 1 R90 rotate by 90 degrees 2 R180 rotate by 180 degrees 3 R270 rotate by 270 degrees 4 FX flip X 5 FXR90 flip X then rotate by 90 degrees 6 FY flip Y 7 FYR90 flip Y then rotate by 90 degrees Note: Transform names can be concatenated to produce their product (applies the first then the second). The resulting transform will be equivalent to one of the eight existing ones, though (see: dihedral group). */ else if (str_starts_with(part_of_name, "[transform")) { if (baseimg == NULL) { errorstream<<"generateImagePart(): baseimg == NULL " <<"for part_of_name=\""<<part_of_name <<"\", cancelling."<<std::endl; return false; } u32 transform = parseImageTransform(part_of_name.substr(10)); core::dimension2d<u32> dim = imageTransformDimension( transform, baseimg->getDimension()); video::IImage *image = driver->createImage( baseimg->getColorFormat(), dim); sanity_check(image != NULL); imageTransform(transform, baseimg, image); baseimg->drop(); baseimg = image; } /* [inventorycube{topimage{leftimage{rightimage In every subimage, replace ^ with &. Create an "inventory cube". NOTE: This should be used only on its own. Example (a grass block (not actually used in game): "[inventorycube{grass.png{mud.png&grass_side.png{mud.png&grass_side.png" */ else if (str_starts_with(part_of_name, "[inventorycube")) { if (baseimg != NULL){ errorstream<<"generateImagePart(): baseimg != NULL " <<"for part_of_name=\""<<part_of_name <<"\", cancelling."<<std::endl; return false; } str_replace(part_of_name, '&', '^'); Strfnd sf(part_of_name); sf.next("{"); std::string imagename_top = sf.next("{"); std::string imagename_left = sf.next("{"); std::string imagename_right = sf.next("{"); // Generate images for the faces of the cube video::IImage *img_top = generateImage(imagename_top); video::IImage *img_left = generateImage(imagename_left); video::IImage *img_right = generateImage(imagename_right); if (img_top == NULL || img_left == NULL || img_right == NULL) { errorstream << "generateImagePart(): Failed to create textures" << " for inventorycube \"" << part_of_name << "\"" << std::endl; baseimg = generateImage(imagename_top); return true; } baseimg = createInventoryCubeImage(img_top, img_left, img_right); // Face images are not needed anymore img_top->drop(); img_left->drop(); img_right->drop(); return true; } /* [lowpart:percent:filename Adds the lower part of a texture */ else if (str_starts_with(part_of_name, "[lowpart:")) { Strfnd sf(part_of_name); sf.next(":"); u32 percent = stoi(sf.next(":")); std::string filename = unescape_string(sf.next_esc(":", escape), escape); if (baseimg == NULL) baseimg = driver->createImage(video::ECF_A8R8G8B8, v2u32(16,16)); video::IImage *img = generateImage(filename); if (img) { core::dimension2d<u32> dim = img->getDimension(); core::position2d<s32> pos_base(0, 0); video::IImage *img2 = driver->createImage(video::ECF_A8R8G8B8, dim); img->copyTo(img2); img->drop(); core::position2d<s32> clippos(0, 0); clippos.Y = dim.Height * (100-percent) / 100; core::dimension2d<u32> clipdim = dim; clipdim.Height = clipdim.Height * percent / 100 + 1; core::rect<s32> cliprect(clippos, clipdim); img2->copyToWithAlpha(baseimg, pos_base, core::rect<s32>(v2s32(0,0), dim), video::SColor(255,255,255,255), &cliprect); img2->drop(); } } /* [verticalframe:N:I Crops a frame of a vertical animation. N = frame count, I = frame index */ else if (str_starts_with(part_of_name, "[verticalframe:")) { Strfnd sf(part_of_name); sf.next(":"); u32 frame_count = stoi(sf.next(":")); u32 frame_index = stoi(sf.next(":")); if (baseimg == NULL){ errorstream<<"generateImagePart(): baseimg != NULL " <<"for part_of_name=\""<<part_of_name <<"\", cancelling."<<std::endl; return false; } v2u32 frame_size = baseimg->getDimension(); frame_size.Y /= frame_count; video::IImage *img = driver->createImage(video::ECF_A8R8G8B8, frame_size); if (!img){ errorstream<<"generateImagePart(): Could not create image " <<"for part_of_name=\""<<part_of_name <<"\", cancelling."<<std::endl; return false; } // Fill target image with transparency img->fill(video::SColor(0,0,0,0)); core::dimension2d<u32> dim = frame_size; core::position2d<s32> pos_dst(0, 0); core::position2d<s32> pos_src(0, frame_index * frame_size.Y); baseimg->copyToWithAlpha(img, pos_dst, core::rect<s32>(pos_src, dim), video::SColor(255,255,255,255), NULL); // Replace baseimg baseimg->drop(); baseimg = img; } /* [mask:filename Applies a mask to an image */ else if (str_starts_with(part_of_name, "[mask:")) { if (baseimg == NULL) { errorstream << "generateImage(): baseimg == NULL " << "for part_of_name=\"" << part_of_name << "\", cancelling." << std::endl; return false; } Strfnd sf(part_of_name); sf.next(":"); std::string filename = unescape_string(sf.next_esc(":", escape), escape); video::IImage *img = generateImage(filename); if (img) { apply_mask(img, baseimg, v2s32(0, 0), v2s32(0, 0), img->getDimension()); img->drop(); } else { errorstream << "generateImage(): Failed to load \"" << filename << "\"."; } } /* [multiply:color multiplys a given color to any pixel of an image color = color as ColorString */ else if (str_starts_with(part_of_name, "[multiply:")) { Strfnd sf(part_of_name); sf.next(":"); std::string color_str = sf.next(":"); if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg != NULL " << "for part_of_name=\"" << part_of_name << "\", cancelling." << std::endl; return false; } video::SColor color; if (!parseColorString(color_str, color, false)) return false; apply_multiplication(baseimg, v2u32(0, 0), baseimg->getDimension(), color); } /* [colorize:color Overlays image with given color color = color as ColorString */ else if (str_starts_with(part_of_name, "[colorize:")) { Strfnd sf(part_of_name); sf.next(":"); std::string color_str = sf.next(":"); std::string ratio_str = sf.next(":"); if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg != NULL " << "for part_of_name=\"" << part_of_name << "\", cancelling." << std::endl; return false; } video::SColor color; int ratio = -1; bool keep_alpha = false; if (!parseColorString(color_str, color, false)) return false; if (is_number(ratio_str)) ratio = mystoi(ratio_str, 0, 255); else if (ratio_str == "alpha") keep_alpha = true; apply_colorize(baseimg, v2u32(0, 0), baseimg->getDimension(), color, ratio, keep_alpha); } /* [applyfiltersformesh Internal modifier */ else if (str_starts_with(part_of_name, "[applyfiltersformesh")) { // Apply the "clean transparent" filter, if configured. if (g_settings->getBool("texture_clean_transparent")) imageCleanTransparent(baseimg, 127); /* Upscale textures to user's requested minimum size. This is a trick to make * filters look as good on low-res textures as on high-res ones, by making * low-res textures BECOME high-res ones. This is helpful for worlds that * mix high- and low-res textures, or for mods with least-common-denominator * textures that don't have the resources to offer high-res alternatives. */ const bool filter = m_setting_trilinear_filter || m_setting_bilinear_filter; const s32 scaleto = filter ? g_settings->getS32("texture_min_size") : 1; if (scaleto > 1) { const core::dimension2d<u32> dim = baseimg->getDimension(); /* Calculate scaling needed to make the shortest texture dimension * equal to the target minimum. If e.g. this is a vertical frames * animation, the short dimension will be the real size. */ if ((dim.Width == 0) || (dim.Height == 0)) { errorstream << "generateImagePart(): Illegal 0 dimension " << "for part_of_name=\""<< part_of_name << "\", cancelling." << std::endl; return false; } u32 xscale = scaleto / dim.Width; u32 yscale = scaleto / dim.Height; u32 scale = (xscale > yscale) ? xscale : yscale; // Never downscale; only scale up by 2x or more. if (scale > 1) { u32 w = scale * dim.Width; u32 h = scale * dim.Height; const core::dimension2d<u32> newdim = core::dimension2d<u32>(w, h); video::IImage *newimg = driver->createImage( baseimg->getColorFormat(), newdim); baseimg->copyToScaling(newimg); baseimg->drop(); baseimg = newimg; } } } /* [resize:WxH Resizes the base image to the given dimensions */ else if (str_starts_with(part_of_name, "[resize")) { if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg == NULL " << "for part_of_name=\""<< part_of_name << "\", cancelling." << std::endl; return false; } Strfnd sf(part_of_name); sf.next(":"); u32 width = stoi(sf.next("x")); u32 height = stoi(sf.next("")); core::dimension2d<u32> dim(width, height); video::IImage *image = RenderingEngine::get_video_driver()-> createImage(video::ECF_A8R8G8B8, dim); baseimg->copyToScaling(image); baseimg->drop(); baseimg = image; } /* [opacity:R Makes the base image transparent according to the given ratio. R must be between 0 and 255. 0 means totally transparent. 255 means totally opaque. */ else if (str_starts_with(part_of_name, "[opacity:")) { if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg == NULL " << "for part_of_name=\"" << part_of_name << "\", cancelling." << std::endl; return false; } Strfnd sf(part_of_name); sf.next(":"); u32 ratio = mystoi(sf.next(""), 0, 255); core::dimension2d<u32> dim = baseimg->getDimension(); for (u32 y = 0; y < dim.Height; y++) for (u32 x = 0; x < dim.Width; x++) { video::SColor c = baseimg->getPixel(x, y); c.setAlpha(floor((c.getAlpha() * ratio) / 255 + 0.5)); baseimg->setPixel(x, y, c); } } /* [invert:mode Inverts the given channels of the base image. Mode may contain the characters "r", "g", "b", "a". Only the channels that are mentioned in the mode string will be inverted. */ else if (str_starts_with(part_of_name, "[invert:")) { if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg == NULL " << "for part_of_name=\"" << part_of_name << "\", cancelling." << std::endl; return false; } Strfnd sf(part_of_name); sf.next(":"); std::string mode = sf.next(""); u32 mask = 0; if (mode.find('a') != std::string::npos) mask |= 0xff000000UL; if (mode.find('r') != std::string::npos) mask |= 0x00ff0000UL; if (mode.find('g') != std::string::npos) mask |= 0x0000ff00UL; if (mode.find('b') != std::string::npos) mask |= 0x000000ffUL; core::dimension2d<u32> dim = baseimg->getDimension(); for (u32 y = 0; y < dim.Height; y++) for (u32 x = 0; x < dim.Width; x++) { video::SColor c = baseimg->getPixel(x, y); c.color ^= mask; baseimg->setPixel(x, y, c); } } /* [sheet:WxH:X,Y Retrieves a tile at position X,Y (in tiles) from the base image it assumes to be a tilesheet with dimensions W,H (in tiles). */ else if (part_of_name.substr(0,7) == "[sheet:") { if (baseimg == NULL) { errorstream << "generateImagePart(): baseimg != NULL " << "for part_of_name=\"" << part_of_name << "\", cancelling." << std::endl; return false; } Strfnd sf(part_of_name); sf.next(":"); u32 w0 = stoi(sf.next("x")); u32 h0 = stoi(sf.next(":")); u32 x0 = stoi(sf.next(",")); u32 y0 = stoi(sf.next(":")); core::dimension2d<u32> img_dim = baseimg->getDimension(); core::dimension2d<u32> tile_dim(v2u32(img_dim) / v2u32(w0, h0)); video::IImage *img = driver->createImage( video::ECF_A8R8G8B8, tile_dim); if (!img) { errorstream << "generateImagePart(): Could not create image " << "for part_of_name=\"" << part_of_name << "\", cancelling." << std::endl; return false; } img->fill(video::SColor(0,0,0,0)); v2u32 vdim(tile_dim); core::rect<s32> rect(v2s32(x0 * vdim.X, y0 * vdim.Y), tile_dim); baseimg->copyToWithAlpha(img, v2s32(0), rect, video::SColor(255,255,255,255), NULL); // Replace baseimg baseimg->drop(); baseimg = img; } else { errorstream << "generateImagePart(): Invalid " " modification: \"" << part_of_name << "\"" << std::endl; } } return true; } /* Draw an image on top of an another one, using the alpha channel of the source image This exists because IImage::copyToWithAlpha() doesn't seem to always work. */ static void blit_with_alpha(video::IImage *src, video::IImage *dst, v2s32 src_pos, v2s32 dst_pos, v2u32 size) { for (u32 y0=0; y0<size.Y; y0++) for (u32 x0=0; x0<size.X; x0++) { s32 src_x = src_pos.X + x0; s32 src_y = src_pos.Y + y0; s32 dst_x = dst_pos.X + x0; s32 dst_y = dst_pos.Y + y0; video::SColor src_c = src->getPixel(src_x, src_y); video::SColor dst_c = dst->getPixel(dst_x, dst_y); dst_c = src_c.getInterpolated(dst_c, (float)src_c.getAlpha()/255.0f); dst->setPixel(dst_x, dst_y, dst_c); } } /* Draw an image on top of an another one, using the alpha channel of the source image; only modify fully opaque pixels in destinaion */ static void blit_with_alpha_overlay(video::IImage *src, video::IImage *dst, v2s32 src_pos, v2s32 dst_pos, v2u32 size) { for (u32 y0=0; y0<size.Y; y0++) for (u32 x0=0; x0<size.X; x0++) { s32 src_x = src_pos.X + x0; s32 src_y = src_pos.Y + y0; s32 dst_x = dst_pos.X + x0; s32 dst_y = dst_pos.Y + y0; video::SColor src_c = src->getPixel(src_x, src_y); video::SColor dst_c = dst->getPixel(dst_x, dst_y); if (dst_c.getAlpha() == 255 && src_c.getAlpha() != 0) { dst_c = src_c.getInterpolated(dst_c, (float)src_c.getAlpha()/255.0f); dst->setPixel(dst_x, dst_y, dst_c); } } } // This function has been disabled because it is currently unused. // Feel free to re-enable if you find it handy. #if 0 /* Draw an image on top of an another one, using the specified ratio modify all partially-opaque pixels in the destination. */ static void blit_with_interpolate_overlay(video::IImage *src, video::IImage *dst, v2s32 src_pos, v2s32 dst_pos, v2u32 size, int ratio) { for (u32 y0 = 0; y0 < size.Y; y0++) for (u32 x0 = 0; x0 < size.X; x0++) { s32 src_x = src_pos.X + x0; s32 src_y = src_pos.Y + y0; s32 dst_x = dst_pos.X + x0; s32 dst_y = dst_pos.Y + y0; video::SColor src_c = src->getPixel(src_x, src_y); video::SColor dst_c = dst->getPixel(dst_x, dst_y); if (dst_c.getAlpha() > 0 && src_c.getAlpha() != 0) { if (ratio == -1) dst_c = src_c.getInterpolated(dst_c, (float)src_c.getAlpha()/255.0f); else dst_c = src_c.getInterpolated(dst_c, (float)ratio/255.0f); dst->setPixel(dst_x, dst_y, dst_c); } } } #endif /* Apply color to destination */ static void apply_colorize(video::IImage *dst, v2u32 dst_pos, v2u32 size, const video::SColor &color, int ratio, bool keep_alpha) { u32 alpha = color.getAlpha(); video::SColor dst_c; if ((ratio == -1 && alpha == 255) || ratio == 255) { // full replacement of color if (keep_alpha) { // replace the color with alpha = dest alpha * color alpha dst_c = color; for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++) for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) { u32 dst_alpha = dst->getPixel(x, y).getAlpha(); if (dst_alpha > 0) { dst_c.setAlpha(dst_alpha * alpha / 255); dst->setPixel(x, y, dst_c); } } } else { // replace the color including the alpha for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++) for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) if (dst->getPixel(x, y).getAlpha() > 0) dst->setPixel(x, y, color); } } else { // interpolate between the color and destination float interp = (ratio == -1 ? color.getAlpha() / 255.0f : ratio / 255.0f); for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++) for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) { dst_c = dst->getPixel(x, y); if (dst_c.getAlpha() > 0) { dst_c = color.getInterpolated(dst_c, interp); dst->setPixel(x, y, dst_c); } } } } /* Apply color to destination */ static void apply_multiplication(video::IImage *dst, v2u32 dst_pos, v2u32 size, const video::SColor &color) { video::SColor dst_c; for (u32 y = dst_pos.Y; y < dst_pos.Y + size.Y; y++) for (u32 x = dst_pos.X; x < dst_pos.X + size.X; x++) { dst_c = dst->getPixel(x, y); dst_c.set( dst_c.getAlpha(), (dst_c.getRed() * color.getRed()) / 255, (dst_c.getGreen() * color.getGreen()) / 255, (dst_c.getBlue() * color.getBlue()) / 255 ); dst->setPixel(x, y, dst_c); } } /* Apply mask to destination */ static void apply_mask(video::IImage *mask, video::IImage *dst, v2s32 mask_pos, v2s32 dst_pos, v2u32 size) { for (u32 y0 = 0; y0 < size.Y; y0++) { for (u32 x0 = 0; x0 < size.X; x0++) { s32 mask_x = x0 + mask_pos.X; s32 mask_y = y0 + mask_pos.Y; s32 dst_x = x0 + dst_pos.X; s32 dst_y = y0 + dst_pos.Y; video::SColor mask_c = mask->getPixel(mask_x, mask_y); video::SColor dst_c = dst->getPixel(dst_x, dst_y); dst_c.color &= mask_c.color; dst->setPixel(dst_x, dst_y, dst_c); } } } video::IImage *create_crack_image(video::IImage *crack, s32 frame_index, core::dimension2d<u32> size, u8 tiles, video::IVideoDriver *driver) { core::dimension2d<u32> strip_size = crack->getDimension(); core::dimension2d<u32> frame_size(strip_size.Width, strip_size.Width); core::dimension2d<u32> tile_size(size / tiles); s32 frame_count = strip_size.Height / strip_size.Width; if (frame_index >= frame_count) frame_index = frame_count - 1; core::rect<s32> frame(v2s32(0, frame_index * frame_size.Height), frame_size); video::IImage *result = nullptr; // extract crack frame video::IImage *crack_tile = driver->createImage(video::ECF_A8R8G8B8, tile_size); if (!crack_tile) return nullptr; if (tile_size == frame_size) { crack->copyTo(crack_tile, v2s32(0, 0), frame); } else { video::IImage *crack_frame = driver->createImage(video::ECF_A8R8G8B8, frame_size); if (!crack_frame) goto exit__has_tile; crack->copyTo(crack_frame, v2s32(0, 0), frame); crack_frame->copyToScaling(crack_tile); crack_frame->drop(); } if (tiles == 1) return crack_tile; // tile it result = driver->createImage(video::ECF_A8R8G8B8, size); if (!result) goto exit__has_tile; result->fill({}); for (u8 i = 0; i < tiles; i++) for (u8 j = 0; j < tiles; j++) crack_tile->copyTo(result, v2s32(i * tile_size.Width, j * tile_size.Height)); exit__has_tile: crack_tile->drop(); return result; } static void draw_crack(video::IImage *crack, video::IImage *dst, bool use_overlay, s32 frame_count, s32 progression, video::IVideoDriver *driver, u8 tiles) { // Dimension of destination image core::dimension2d<u32> dim_dst = dst->getDimension(); // Limit frame_count if (frame_count > (s32) dim_dst.Height) frame_count = dim_dst.Height; if (frame_count < 1) frame_count = 1; // Dimension of the scaled crack stage, // which is the same as the dimension of a single destination frame core::dimension2d<u32> frame_size( dim_dst.Width, dim_dst.Height / frame_count ); video::IImage *crack_scaled = create_crack_image(crack, progression, frame_size, tiles, driver); if (!crack_scaled) return; auto blit = use_overlay ? blit_with_alpha_overlay : blit_with_alpha; for (s32 i = 0; i < frame_count; ++i) { v2s32 dst_pos(0, frame_size.Height * i); blit(crack_scaled, dst, v2s32(0,0), dst_pos, frame_size); } crack_scaled->drop(); } void brighten(video::IImage *image) { if (image == NULL) return; core::dimension2d<u32> dim = image->getDimension(); for (u32 y=0; y<dim.Height; y++) for (u32 x=0; x<dim.Width; x++) { video::SColor c = image->getPixel(x,y); c.setRed(0.5 * 255 + 0.5 * (float)c.getRed()); c.setGreen(0.5 * 255 + 0.5 * (float)c.getGreen()); c.setBlue(0.5 * 255 + 0.5 * (float)c.getBlue()); image->setPixel(x,y,c); } } u32 parseImageTransform(const std::string& s) { int total_transform = 0; std::string transform_names[8]; transform_names[0] = "i"; transform_names[1] = "r90"; transform_names[2] = "r180"; transform_names[3] = "r270"; transform_names[4] = "fx"; transform_names[6] = "fy"; std::size_t pos = 0; while(pos < s.size()) { int transform = -1; for (int i = 0; i <= 7; ++i) { const std::string &name_i = transform_names[i]; if (s[pos] == ('0' + i)) { transform = i; pos++; break; } if (!(name_i.empty()) && lowercase(s.substr(pos, name_i.size())) == name_i) { transform = i; pos += name_i.size(); break; } } if (transform < 0) break; // Multiply total_transform and transform in the group D4 int new_total = 0; if (transform < 4) new_total = (transform + total_transform) % 4; else new_total = (transform - total_transform + 8) % 4; if ((transform >= 4) ^ (total_transform >= 4)) new_total += 4; total_transform = new_total; } return total_transform; } core::dimension2d<u32> imageTransformDimension(u32 transform, core::dimension2d<u32> dim) { if (transform % 2 == 0) return dim; return core::dimension2d<u32>(dim.Height, dim.Width); } void imageTransform(u32 transform, video::IImage *src, video::IImage *dst) { if (src == NULL || dst == NULL) return; core::dimension2d<u32> dstdim = dst->getDimension(); // Pre-conditions assert(dstdim == imageTransformDimension(transform, src->getDimension())); assert(transform <= 7); /* Compute the transformation from source coordinates (sx,sy) to destination coordinates (dx,dy). */ int sxn = 0; int syn = 2; if (transform == 0) // identity sxn = 0, syn = 2; // sx = dx, sy = dy else if (transform == 1) // rotate by 90 degrees ccw sxn = 3, syn = 0; // sx = (H-1) - dy, sy = dx else if (transform == 2) // rotate by 180 degrees sxn = 1, syn = 3; // sx = (W-1) - dx, sy = (H-1) - dy else if (transform == 3) // rotate by 270 degrees ccw sxn = 2, syn = 1; // sx = dy, sy = (W-1) - dx else if (transform == 4) // flip x sxn = 1, syn = 2; // sx = (W-1) - dx, sy = dy else if (transform == 5) // flip x then rotate by 90 degrees ccw sxn = 2, syn = 0; // sx = dy, sy = dx else if (transform == 6) // flip y sxn = 0, syn = 3; // sx = dx, sy = (H-1) - dy else if (transform == 7) // flip y then rotate by 90 degrees ccw sxn = 3, syn = 1; // sx = (H-1) - dy, sy = (W-1) - dx for (u32 dy=0; dy<dstdim.Height; dy++) for (u32 dx=0; dx<dstdim.Width; dx++) { u32 entries[4] = {dx, dstdim.Width-1-dx, dy, dstdim.Height-1-dy}; u32 sx = entries[sxn]; u32 sy = entries[syn]; video::SColor c = src->getPixel(sx,sy); dst->setPixel(dx,dy,c); } } video::ITexture* TextureSource::getNormalTexture(const std::string &name) { if (isKnownSourceImage("override_normal.png")) return getTexture("override_normal.png"); std::string fname_base = name; static const char *normal_ext = "_normal.png"; static const u32 normal_ext_size = strlen(normal_ext); size_t pos = fname_base.find('.'); std::string fname_normal = fname_base.substr(0, pos) + normal_ext; if (isKnownSourceImage(fname_normal)) { // look for image extension and replace it size_t i = 0; while ((i = fname_base.find('.', i)) != std::string::npos) { fname_base.replace(i, 4, normal_ext); i += normal_ext_size; } return getTexture(fname_base); } return NULL; } video::SColor TextureSource::getTextureAverageColor(const std::string &name) { video::IVideoDriver *driver = RenderingEngine::get_video_driver(); video::SColor c(0, 0, 0, 0); video::ITexture *texture = getTexture(name); video::IImage *image = driver->createImage(texture, core::position2d<s32>(0, 0), texture->getOriginalSize()); u32 total = 0; u32 tR = 0; u32 tG = 0; u32 tB = 0; core::dimension2d<u32> dim = image->getDimension(); u16 step = 1; if (dim.Width > 16) step = dim.Width / 16; for (u16 x = 0; x < dim.Width; x += step) { for (u16 y = 0; y < dim.Width; y += step) { c = image->getPixel(x,y); if (c.getAlpha() > 0) { total++; tR += c.getRed(); tG += c.getGreen(); tB += c.getBlue(); } } } image->drop(); if (total > 0) { c.setRed(tR / total); c.setGreen(tG / total); c.setBlue(tB / total); } c.setAlpha(255); return c; } video::ITexture *TextureSource::getShaderFlagsTexture(bool normalmap_present) { std::string tname = "__shaderFlagsTexture"; tname += normalmap_present ? "1" : "0"; if (isKnownSourceImage(tname)) { return getTexture(tname); } video::IVideoDriver *driver = RenderingEngine::get_video_driver(); video::IImage *flags_image = driver->createImage( video::ECF_A8R8G8B8, core::dimension2d<u32>(1, 1)); sanity_check(flags_image != NULL); video::SColor c(255, normalmap_present ? 255 : 0, 0, 0); flags_image->setPixel(0, 0, c); insertSourceImage(tname, flags_image); flags_image->drop(); return getTexture(tname); } std::vector<std::string> getTextureDirs() { return fs::GetRecursiveDirs(g_settings->get("texture_path")); }
pgimeno/minetest
src/client/tile.cpp
C++
mit
63,252
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" #include "irr_v3d.h" #include <ITexture.h> #include <string> #include <vector> #include <SMaterial.h> #include <memory> #include "util/numeric.h" #if __ANDROID__ #include <IVideoDriver.h> #endif class IGameDef; struct TileSpec; struct TileDef; typedef std::vector<video::SColor> Palette; /* tile.{h,cpp}: Texture handling stuff. */ /* Find out the full path of an image by trying different filename extensions. If failed, return "". TODO: Should probably be moved out from here, because things needing this function do not need anything else from this header */ std::string getImagePath(std::string path); /* Gets the path to a texture by first checking if the texture exists in texture_path and if not, using the data path. Checks all supported extensions by replacing the original extension. If not found, returns "". Utilizes a thread-safe cache. */ std::string getTexturePath(const std::string &filename); void clearTextureNameCache(); /* TextureSource creates and caches textures. */ class ISimpleTextureSource { public: ISimpleTextureSource() = default; virtual ~ISimpleTextureSource() = default; virtual video::ITexture* getTexture( const std::string &name, u32 *id = nullptr) = 0; }; class ITextureSource : public ISimpleTextureSource { public: ITextureSource() = default; virtual ~ITextureSource() = default; virtual u32 getTextureId(const std::string &name)=0; virtual std::string getTextureName(u32 id)=0; virtual video::ITexture* getTexture(u32 id)=0; virtual video::ITexture* getTexture( const std::string &name, u32 *id = nullptr)=0; virtual video::ITexture* getTextureForMesh( const std::string &name, u32 *id = nullptr) = 0; /*! * Returns a palette from the given texture name. * The pointer is valid until the texture source is * destructed. * Should be called from the main thread. */ virtual Palette* getPalette(const std::string &name) = 0; virtual bool isKnownSourceImage(const std::string &name)=0; virtual video::ITexture* getNormalTexture(const std::string &name)=0; virtual video::SColor getTextureAverageColor(const std::string &name)=0; virtual video::ITexture *getShaderFlagsTexture(bool normalmap_present)=0; }; class IWritableTextureSource : public ITextureSource { public: IWritableTextureSource() = default; virtual ~IWritableTextureSource() = default; virtual u32 getTextureId(const std::string &name)=0; virtual std::string getTextureName(u32 id)=0; virtual video::ITexture* getTexture(u32 id)=0; virtual video::ITexture* getTexture( const std::string &name, u32 *id = nullptr)=0; virtual bool isKnownSourceImage(const std::string &name)=0; virtual void processQueue()=0; virtual void insertSourceImage(const std::string &name, video::IImage *img)=0; virtual void rebuildImagesAndTextures()=0; virtual video::ITexture* getNormalTexture(const std::string &name)=0; virtual video::SColor getTextureAverageColor(const std::string &name)=0; virtual video::ITexture *getShaderFlagsTexture(bool normalmap_present)=0; }; IWritableTextureSource *createTextureSource(); #ifdef __ANDROID__ video::IImage * Align2Npot2(video::IImage * image, irr::video::IVideoDriver* driver); #endif enum MaterialType{ TILE_MATERIAL_BASIC, TILE_MATERIAL_ALPHA, TILE_MATERIAL_LIQUID_TRANSPARENT, TILE_MATERIAL_LIQUID_OPAQUE, TILE_MATERIAL_WAVING_LEAVES, TILE_MATERIAL_WAVING_PLANTS, TILE_MATERIAL_OPAQUE, TILE_MATERIAL_WAVING_LIQUID_BASIC, TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT, TILE_MATERIAL_WAVING_LIQUID_OPAQUE, }; // Material flags // Should backface culling be enabled? #define MATERIAL_FLAG_BACKFACE_CULLING 0x01 // Should a crack be drawn? #define MATERIAL_FLAG_CRACK 0x02 // Should the crack be drawn on transparent pixels (unset) or not (set)? // Ignored if MATERIAL_FLAG_CRACK is not set. #define MATERIAL_FLAG_CRACK_OVERLAY 0x04 #define MATERIAL_FLAG_ANIMATION 0x08 //#define MATERIAL_FLAG_HIGHLIGHTED 0x10 #define MATERIAL_FLAG_TILEABLE_HORIZONTAL 0x20 #define MATERIAL_FLAG_TILEABLE_VERTICAL 0x40 /* This fully defines the looks of a tile. The SMaterial of a tile is constructed according to this. */ struct FrameSpec { FrameSpec() = default; u32 texture_id = 0; video::ITexture *texture = nullptr; video::ITexture *normal_texture = nullptr; video::ITexture *flags_texture = nullptr; }; #define MAX_TILE_LAYERS 2 //! Defines a layer of a tile. struct TileLayer { TileLayer() = default; /*! * Two layers are equal if they can be merged. */ bool operator==(const TileLayer &other) const { return texture_id == other.texture_id && material_type == other.material_type && material_flags == other.material_flags && color == other.color && scale == other.scale; } /*! * Two tiles are not equal if they must have different vertices. */ bool operator!=(const TileLayer &other) const { return !(*this == other); } // Sets everything else except the texture in the material void applyMaterialOptions(video::SMaterial &material) const { switch (material_type) { case TILE_MATERIAL_OPAQUE: case TILE_MATERIAL_LIQUID_OPAQUE: case TILE_MATERIAL_WAVING_LIQUID_OPAQUE: material.MaterialType = video::EMT_SOLID; break; case TILE_MATERIAL_BASIC: case TILE_MATERIAL_WAVING_LEAVES: case TILE_MATERIAL_WAVING_PLANTS: case TILE_MATERIAL_WAVING_LIQUID_BASIC: material.MaterialTypeParam = 0.5; material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF; break; case TILE_MATERIAL_ALPHA: case TILE_MATERIAL_LIQUID_TRANSPARENT: case TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT: material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; break; default: break; } material.BackfaceCulling = (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) != 0; if (!(material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL)) { material.TextureLayer[0].TextureWrapU = video::ETC_CLAMP_TO_EDGE; } if (!(material_flags & MATERIAL_FLAG_TILEABLE_VERTICAL)) { material.TextureLayer[0].TextureWrapV = video::ETC_CLAMP_TO_EDGE; } } void applyMaterialOptionsWithShaders(video::SMaterial &material) const { material.BackfaceCulling = (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) != 0; if (!(material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL)) { material.TextureLayer[0].TextureWrapU = video::ETC_CLAMP_TO_EDGE; material.TextureLayer[1].TextureWrapU = video::ETC_CLAMP_TO_EDGE; } if (!(material_flags & MATERIAL_FLAG_TILEABLE_VERTICAL)) { material.TextureLayer[0].TextureWrapV = video::ETC_CLAMP_TO_EDGE; material.TextureLayer[1].TextureWrapV = video::ETC_CLAMP_TO_EDGE; } } bool isTileable() const { return (material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL) && (material_flags & MATERIAL_FLAG_TILEABLE_VERTICAL); } // Ordered for size, please do not reorder video::ITexture *texture = nullptr; video::ITexture *normal_texture = nullptr; video::ITexture *flags_texture = nullptr; u32 shader_id = 0; u32 texture_id = 0; u16 animation_frame_length_ms = 0; u8 animation_frame_count = 1; u8 material_type = TILE_MATERIAL_BASIC; u8 material_flags = //0 // <- DEBUG, Use the one below MATERIAL_FLAG_BACKFACE_CULLING | MATERIAL_FLAG_TILEABLE_HORIZONTAL| MATERIAL_FLAG_TILEABLE_VERTICAL; //! If true, the tile has its own color. bool has_color = false; std::shared_ptr<std::vector<FrameSpec>> frames = nullptr; /*! * The color of the tile, or if the tile does not own * a color then the color of the node owning this tile. */ video::SColor color; u8 scale; }; /*! * Defines a face of a node. May have up to two layers. */ struct TileSpec { TileSpec() = default; /*! * Returns true if this tile can be merged with the other tile. */ bool isTileable(const TileSpec &other) const { for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { if (layers[layer] != other.layers[layer]) return false; if (!layers[layer].isTileable()) return false; } return rotation == 0 && rotation == other.rotation && emissive_light == other.emissive_light; } //! If true, the tile rotation is ignored. bool world_aligned = false; //! Tile rotation. u8 rotation = 0; //! This much light does the tile emit. u8 emissive_light = 0; //! The first is base texture, the second is overlay. TileLayer layers[MAX_TILE_LAYERS]; }; std::vector<std::string> getTextureDirs();
pgimeno/minetest
src/client/tile.h
C++
mit
9,189
/* Minetest Copyright (C) 2010-2014 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "wieldmesh.h" #include "settings.h" #include "shader.h" #include "inventory.h" #include "client.h" #include "itemdef.h" #include "nodedef.h" #include "mesh.h" #include "content_mapblock.h" #include "mapblock_mesh.h" #include "client/meshgen/collector.h" #include "client/tile.h" #include "log.h" #include "util/numeric.h" #include <map> #include <IMeshManipulator.h> #define WIELD_SCALE_FACTOR 30.0 #define WIELD_SCALE_FACTOR_EXTRUDED 40.0 #define MIN_EXTRUSION_MESH_RESOLUTION 16 #define MAX_EXTRUSION_MESH_RESOLUTION 512 static scene::IMesh *createExtrusionMesh(int resolution_x, int resolution_y) { const f32 r = 0.5; scene::IMeshBuffer *buf = new scene::SMeshBuffer(); video::SColor c(255,255,255,255); v3f scale(1.0, 1.0, 0.1); // Front and back { video::S3DVertex vertices[8] = { // z- video::S3DVertex(-r,+r,-r, 0,0,-1, c, 0,0), video::S3DVertex(+r,+r,-r, 0,0,-1, c, 1,0), video::S3DVertex(+r,-r,-r, 0,0,-1, c, 1,1), video::S3DVertex(-r,-r,-r, 0,0,-1, c, 0,1), // z+ video::S3DVertex(-r,+r,+r, 0,0,+1, c, 0,0), video::S3DVertex(-r,-r,+r, 0,0,+1, c, 0,1), video::S3DVertex(+r,-r,+r, 0,0,+1, c, 1,1), video::S3DVertex(+r,+r,+r, 0,0,+1, c, 1,0), }; u16 indices[12] = {0,1,2,2,3,0,4,5,6,6,7,4}; buf->append(vertices, 8, indices, 12); } f32 pixelsize_x = 1 / (f32) resolution_x; f32 pixelsize_y = 1 / (f32) resolution_y; for (int i = 0; i < resolution_x; ++i) { f32 pixelpos_x = i * pixelsize_x - 0.5; f32 x0 = pixelpos_x; f32 x1 = pixelpos_x + pixelsize_x; f32 tex0 = (i + 0.1) * pixelsize_x; f32 tex1 = (i + 0.9) * pixelsize_x; video::S3DVertex vertices[8] = { // x- video::S3DVertex(x0,-r,-r, -1,0,0, c, tex0,1), video::S3DVertex(x0,-r,+r, -1,0,0, c, tex1,1), video::S3DVertex(x0,+r,+r, -1,0,0, c, tex1,0), video::S3DVertex(x0,+r,-r, -1,0,0, c, tex0,0), // x+ video::S3DVertex(x1,-r,-r, +1,0,0, c, tex0,1), video::S3DVertex(x1,+r,-r, +1,0,0, c, tex0,0), video::S3DVertex(x1,+r,+r, +1,0,0, c, tex1,0), video::S3DVertex(x1,-r,+r, +1,0,0, c, tex1,1), }; u16 indices[12] = {0,1,2,2,3,0,4,5,6,6,7,4}; buf->append(vertices, 8, indices, 12); } for (int i = 0; i < resolution_y; ++i) { f32 pixelpos_y = i * pixelsize_y - 0.5; f32 y0 = -pixelpos_y - pixelsize_y; f32 y1 = -pixelpos_y; f32 tex0 = (i + 0.1) * pixelsize_y; f32 tex1 = (i + 0.9) * pixelsize_y; video::S3DVertex vertices[8] = { // y- video::S3DVertex(-r,y0,-r, 0,-1,0, c, 0,tex0), video::S3DVertex(+r,y0,-r, 0,-1,0, c, 1,tex0), video::S3DVertex(+r,y0,+r, 0,-1,0, c, 1,tex1), video::S3DVertex(-r,y0,+r, 0,-1,0, c, 0,tex1), // y+ video::S3DVertex(-r,y1,-r, 0,+1,0, c, 0,tex0), video::S3DVertex(-r,y1,+r, 0,+1,0, c, 0,tex1), video::S3DVertex(+r,y1,+r, 0,+1,0, c, 1,tex1), video::S3DVertex(+r,y1,-r, 0,+1,0, c, 1,tex0), }; u16 indices[12] = {0,1,2,2,3,0,4,5,6,6,7,4}; buf->append(vertices, 8, indices, 12); } // Create mesh object scene::SMesh *mesh = new scene::SMesh(); mesh->addMeshBuffer(buf); buf->drop(); scaleMesh(mesh, scale); // also recalculates bounding box return mesh; } /* Caches extrusion meshes so that only one of them per resolution is needed. Also caches one cube (for convenience). E.g. there is a single extrusion mesh that is used for all 16x16 px images, another for all 256x256 px images, and so on. WARNING: Not thread safe. This should not be a problem since rendering related classes (such as WieldMeshSceneNode) will be used from the rendering thread only. */ class ExtrusionMeshCache: public IReferenceCounted { public: // Constructor ExtrusionMeshCache() { for (int resolution = MIN_EXTRUSION_MESH_RESOLUTION; resolution <= MAX_EXTRUSION_MESH_RESOLUTION; resolution *= 2) { m_extrusion_meshes[resolution] = createExtrusionMesh(resolution, resolution); } m_cube = createCubeMesh(v3f(1.0, 1.0, 1.0)); } // Destructor virtual ~ExtrusionMeshCache() { for (auto &extrusion_meshe : m_extrusion_meshes) { extrusion_meshe.second->drop(); } m_cube->drop(); } // Get closest extrusion mesh for given image dimensions // Caller must drop the returned pointer scene::IMesh* create(core::dimension2d<u32> dim) { // handle non-power of two textures inefficiently without cache if (!is_power_of_two(dim.Width) || !is_power_of_two(dim.Height)) { return createExtrusionMesh(dim.Width, dim.Height); } int maxdim = MYMAX(dim.Width, dim.Height); std::map<int, scene::IMesh*>::iterator it = m_extrusion_meshes.lower_bound(maxdim); if (it == m_extrusion_meshes.end()) { // no viable resolution found; use largest one it = m_extrusion_meshes.find(MAX_EXTRUSION_MESH_RESOLUTION); sanity_check(it != m_extrusion_meshes.end()); } scene::IMesh *mesh = it->second; mesh->grab(); return mesh; } // Returns a 1x1x1 cube mesh with one meshbuffer (material) per face // Caller must drop the returned pointer scene::IMesh* createCube() { m_cube->grab(); return m_cube; } private: std::map<int, scene::IMesh*> m_extrusion_meshes; scene::IMesh *m_cube; }; ExtrusionMeshCache *g_extrusion_mesh_cache = NULL; WieldMeshSceneNode::WieldMeshSceneNode(scene::ISceneManager *mgr, s32 id, bool lighting): scene::ISceneNode(mgr->getRootSceneNode(), mgr, id), m_material_type(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF), m_lighting(lighting) { m_enable_shaders = g_settings->getBool("enable_shaders"); m_anisotropic_filter = g_settings->getBool("anisotropic_filter"); m_bilinear_filter = g_settings->getBool("bilinear_filter"); m_trilinear_filter = g_settings->getBool("trilinear_filter"); // If this is the first wield mesh scene node, create a cache // for extrusion meshes (and a cube mesh), otherwise reuse it if (!g_extrusion_mesh_cache) g_extrusion_mesh_cache = new ExtrusionMeshCache(); else g_extrusion_mesh_cache->grab(); // Disable bounding box culling for this scene node // since we won't calculate the bounding box. setAutomaticCulling(scene::EAC_OFF); // Create the child scene node scene::IMesh *dummymesh = g_extrusion_mesh_cache->createCube(); m_meshnode = SceneManager->addMeshSceneNode(dummymesh, this, -1); m_meshnode->setReadOnlyMaterials(false); m_meshnode->setVisible(false); dummymesh->drop(); // m_meshnode grabbed it } WieldMeshSceneNode::~WieldMeshSceneNode() { sanity_check(g_extrusion_mesh_cache); if (g_extrusion_mesh_cache->drop()) g_extrusion_mesh_cache = nullptr; } void WieldMeshSceneNode::setCube(const ContentFeatures &f, v3f wield_scale) { scene::IMesh *cubemesh = g_extrusion_mesh_cache->createCube(); scene::SMesh *copy = cloneMesh(cubemesh); cubemesh->drop(); postProcessNodeMesh(copy, f, false, true, &m_material_type, &m_colors, true); changeToMesh(copy); copy->drop(); m_meshnode->setScale(wield_scale * WIELD_SCALE_FACTOR); } void WieldMeshSceneNode::setExtruded(const std::string &imagename, const std::string &overlay_name, v3f wield_scale, ITextureSource *tsrc, u8 num_frames) { video::ITexture *texture = tsrc->getTexture(imagename); if (!texture) { changeToMesh(nullptr); return; } video::ITexture *overlay_texture = overlay_name.empty() ? NULL : tsrc->getTexture(overlay_name); core::dimension2d<u32> dim = texture->getSize(); // Detect animation texture and pull off top frame instead of using entire thing if (num_frames > 1) { u32 frame_height = dim.Height / num_frames; dim = core::dimension2d<u32>(dim.Width, frame_height); } scene::IMesh *original = g_extrusion_mesh_cache->create(dim); scene::SMesh *mesh = cloneMesh(original); original->drop(); //set texture mesh->getMeshBuffer(0)->getMaterial().setTexture(0, tsrc->getTexture(imagename)); if (overlay_texture) { scene::IMeshBuffer *copy = cloneMeshBuffer(mesh->getMeshBuffer(0)); copy->getMaterial().setTexture(0, overlay_texture); mesh->addMeshBuffer(copy); copy->drop(); } changeToMesh(mesh); mesh->drop(); m_meshnode->setScale(wield_scale * WIELD_SCALE_FACTOR_EXTRUDED); // Customize materials for (u32 layer = 0; layer < m_meshnode->getMaterialCount(); layer++) { video::SMaterial &material = m_meshnode->getMaterial(layer); material.TextureLayer[0].TextureWrapU = video::ETC_CLAMP_TO_EDGE; material.TextureLayer[0].TextureWrapV = video::ETC_CLAMP_TO_EDGE; material.MaterialType = m_material_type; material.MaterialTypeParam = 0.5f; material.setFlag(video::EMF_BACK_FACE_CULLING, true); // Enable bi/trilinear filtering only for high resolution textures if (dim.Width > 32) { material.setFlag(video::EMF_BILINEAR_FILTER, m_bilinear_filter); material.setFlag(video::EMF_TRILINEAR_FILTER, m_trilinear_filter); } else { material.setFlag(video::EMF_BILINEAR_FILTER, false); material.setFlag(video::EMF_TRILINEAR_FILTER, false); } material.setFlag(video::EMF_ANISOTROPIC_FILTER, m_anisotropic_filter); // mipmaps cause "thin black line" artifacts #if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2 material.setFlag(video::EMF_USE_MIP_MAPS, false); #endif if (m_enable_shaders) { material.setTexture(2, tsrc->getShaderFlagsTexture(false)); } } } scene::SMesh *createSpecialNodeMesh(Client *client, content_t id, std::vector<ItemPartColor> *colors) { MeshMakeData mesh_make_data(client, false, false); MeshCollector collector; mesh_make_data.setSmoothLighting(false); MapblockMeshGenerator gen(&mesh_make_data, &collector); gen.renderSingle(id); colors->clear(); scene::SMesh *mesh = new scene::SMesh(); for (auto &prebuffers : collector.prebuffers) for (PreMeshBuffer &p : prebuffers) { if (p.layer.material_flags & MATERIAL_FLAG_ANIMATION) { const FrameSpec &frame = (*p.layer.frames)[0]; p.layer.texture = frame.texture; p.layer.normal_texture = frame.normal_texture; } for (video::S3DVertex &v : p.vertices) v.Color.setAlpha(255); scene::SMeshBuffer *buf = new scene::SMeshBuffer(); buf->Material.setTexture(0, p.layer.texture); p.layer.applyMaterialOptions(buf->Material); mesh->addMeshBuffer(buf); buf->append(&p.vertices[0], p.vertices.size(), &p.indices[0], p.indices.size()); buf->drop(); colors->push_back( ItemPartColor(p.layer.has_color, p.layer.color)); } return mesh; } void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client, bool check_wield_image) { ITextureSource *tsrc = client->getTextureSource(); IItemDefManager *idef = client->getItemDefManager(); IShaderSource *shdrsrc = client->getShaderSource(); const NodeDefManager *ndef = client->getNodeDefManager(); const ItemDefinition &def = item.getDefinition(idef); const ContentFeatures &f = ndef->get(def.name); content_t id = ndef->getId(def.name); scene::SMesh *mesh = nullptr; if (m_enable_shaders) { u32 shader_id = shdrsrc->getShader("wielded_shader", TILE_MATERIAL_BASIC, NDT_NORMAL); m_material_type = shdrsrc->getShaderInfo(shader_id).material; } // Color-related m_colors.clear(); m_base_color = idef->getItemstackColor(item, client); // If wield_image needs to be checked and is defined, it overrides everything else if (!def.wield_image.empty() && check_wield_image) { setExtruded(def.wield_image, def.wield_overlay, def.wield_scale, tsrc, 1); m_colors.emplace_back(); // overlay is white, if present m_colors.emplace_back(true, video::SColor(0xFFFFFFFF)); return; } // Handle nodes // See also CItemDefManager::createClientCached() if (def.type == ITEM_NODE) { if (f.mesh_ptr[0]) { // e.g. mesh nodes and nodeboxes mesh = cloneMesh(f.mesh_ptr[0]); postProcessNodeMesh(mesh, f, m_enable_shaders, true, &m_material_type, &m_colors); changeToMesh(mesh); mesh->drop(); // mesh is pre-scaled by BS * f->visual_scale m_meshnode->setScale( def.wield_scale * WIELD_SCALE_FACTOR / (BS * f.visual_scale)); } else { switch (f.drawtype) { case NDT_AIRLIKE: { changeToMesh(nullptr); break; } case NDT_PLANTLIKE: { setExtruded(tsrc->getTextureName(f.tiles[0].layers[0].texture_id), tsrc->getTextureName(f.tiles[0].layers[1].texture_id), def.wield_scale, tsrc, f.tiles[0].layers[0].animation_frame_count); // Add color const TileLayer &l0 = f.tiles[0].layers[0]; m_colors.emplace_back(l0.has_color, l0.color); const TileLayer &l1 = f.tiles[0].layers[1]; m_colors.emplace_back(l1.has_color, l1.color); break; } case NDT_PLANTLIKE_ROOTED: { setExtruded(tsrc->getTextureName(f.special_tiles[0].layers[0].texture_id), "", def.wield_scale, tsrc, f.special_tiles[0].layers[0].animation_frame_count); // Add color const TileLayer &l0 = f.special_tiles[0].layers[0]; m_colors.emplace_back(l0.has_color, l0.color); break; } case NDT_NORMAL: case NDT_ALLFACES: case NDT_LIQUID: case NDT_FLOWINGLIQUID: { setCube(f, def.wield_scale); break; } default: { mesh = createSpecialNodeMesh(client, id, &m_colors); changeToMesh(mesh); mesh->drop(); m_meshnode->setScale( def.wield_scale * WIELD_SCALE_FACTOR / (BS * f.visual_scale)); } } } u32 material_count = m_meshnode->getMaterialCount(); for (u32 i = 0; i < material_count; ++i) { video::SMaterial &material = m_meshnode->getMaterial(i); material.MaterialType = m_material_type; material.MaterialTypeParam = 0.5f; material.setFlag(video::EMF_BACK_FACE_CULLING, true); material.setFlag(video::EMF_BILINEAR_FILTER, m_bilinear_filter); material.setFlag(video::EMF_TRILINEAR_FILTER, m_trilinear_filter); } return; } else if (!def.inventory_image.empty()) { setExtruded(def.inventory_image, def.inventory_overlay, def.wield_scale, tsrc, 1); m_colors.emplace_back(); // overlay is white, if present m_colors.emplace_back(true, video::SColor(0xFFFFFFFF)); return; } // no wield mesh found changeToMesh(nullptr); } void WieldMeshSceneNode::setColor(video::SColor c) { assert(!m_lighting); scene::IMesh *mesh = m_meshnode->getMesh(); if (!mesh) return; u8 red = c.getRed(); u8 green = c.getGreen(); u8 blue = c.getBlue(); u32 mc = mesh->getMeshBufferCount(); for (u32 j = 0; j < mc; j++) { video::SColor bc(m_base_color); if ((m_colors.size() > j) && (m_colors[j].override_base)) bc = m_colors[j].color; video::SColor buffercolor(255, bc.getRed() * red / 255, bc.getGreen() * green / 255, bc.getBlue() * blue / 255); scene::IMeshBuffer *buf = mesh->getMeshBuffer(j); colorizeMeshBuffer(buf, &buffercolor); } } void WieldMeshSceneNode::render() { // note: if this method is changed to actually do something, // you probably should implement OnRegisterSceneNode as well } void WieldMeshSceneNode::changeToMesh(scene::IMesh *mesh) { if (!mesh) { scene::IMesh *dummymesh = g_extrusion_mesh_cache->createCube(); m_meshnode->setVisible(false); m_meshnode->setMesh(dummymesh); dummymesh->drop(); // m_meshnode grabbed it } else { m_meshnode->setMesh(mesh); } m_meshnode->setMaterialFlag(video::EMF_LIGHTING, m_lighting); // need to normalize normals when lighting is enabled (because of setScale()) m_meshnode->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, m_lighting); m_meshnode->setVisible(true); } void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result) { ITextureSource *tsrc = client->getTextureSource(); IItemDefManager *idef = client->getItemDefManager(); const NodeDefManager *ndef = client->getNodeDefManager(); const ItemDefinition &def = item.getDefinition(idef); const ContentFeatures &f = ndef->get(def.name); content_t id = ndef->getId(def.name); FATAL_ERROR_IF(!g_extrusion_mesh_cache, "Extrusion mesh cache is not yet initialized"); scene::SMesh *mesh = nullptr; // Shading is on by default result->needs_shading = true; // If inventory_image is defined, it overrides everything else if (!def.inventory_image.empty()) { mesh = getExtrudedMesh(tsrc, def.inventory_image, def.inventory_overlay); result->buffer_colors.emplace_back(); // overlay is white, if present result->buffer_colors.emplace_back(true, video::SColor(0xFFFFFFFF)); // Items with inventory images do not need shading result->needs_shading = false; } else if (def.type == ITEM_NODE) { if (f.mesh_ptr[0]) { mesh = cloneMesh(f.mesh_ptr[0]); scaleMesh(mesh, v3f(0.12, 0.12, 0.12)); postProcessNodeMesh(mesh, f, false, false, nullptr, &result->buffer_colors); } else { switch (f.drawtype) { case NDT_PLANTLIKE: { mesh = getExtrudedMesh(tsrc, tsrc->getTextureName(f.tiles[0].layers[0].texture_id), tsrc->getTextureName(f.tiles[0].layers[1].texture_id)); // Add color const TileLayer &l0 = f.tiles[0].layers[0]; result->buffer_colors.emplace_back(l0.has_color, l0.color); const TileLayer &l1 = f.tiles[0].layers[1]; result->buffer_colors.emplace_back(l1.has_color, l1.color); break; } case NDT_PLANTLIKE_ROOTED: { mesh = getExtrudedMesh(tsrc, tsrc->getTextureName(f.special_tiles[0].layers[0].texture_id), ""); // Add color const TileLayer &l0 = f.special_tiles[0].layers[0]; result->buffer_colors.emplace_back(l0.has_color, l0.color); break; } case NDT_NORMAL: case NDT_ALLFACES: case NDT_LIQUID: case NDT_FLOWINGLIQUID: { scene::IMesh *cube = g_extrusion_mesh_cache->createCube(); mesh = cloneMesh(cube); cube->drop(); scaleMesh(mesh, v3f(1.2, 1.2, 1.2)); // add overlays postProcessNodeMesh(mesh, f, false, false, nullptr, &result->buffer_colors); break; } default: { mesh = createSpecialNodeMesh(client, id, &result->buffer_colors); scaleMesh(mesh, v3f(0.12, 0.12, 0.12)); } } } u32 mc = mesh->getMeshBufferCount(); for (u32 i = 0; i < mc; ++i) { scene::IMeshBuffer *buf = mesh->getMeshBuffer(i); video::SMaterial &material = buf->getMaterial(); material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; material.MaterialTypeParam = 0.5f; material.setFlag(video::EMF_BILINEAR_FILTER, false); material.setFlag(video::EMF_TRILINEAR_FILTER, false); material.setFlag(video::EMF_BACK_FACE_CULLING, true); material.setFlag(video::EMF_LIGHTING, false); } rotateMeshXZby(mesh, -45); rotateMeshYZby(mesh, -30); } result->mesh = mesh; } scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename, const std::string &overlay_name) { // check textures video::ITexture *texture = tsrc->getTextureForMesh(imagename); if (!texture) { return NULL; } video::ITexture *overlay_texture = (overlay_name.empty()) ? NULL : tsrc->getTexture(overlay_name); // get mesh core::dimension2d<u32> dim = texture->getSize(); scene::IMesh *original = g_extrusion_mesh_cache->create(dim); scene::SMesh *mesh = cloneMesh(original); original->drop(); //set texture mesh->getMeshBuffer(0)->getMaterial().setTexture(0, tsrc->getTexture(imagename)); if (overlay_texture) { scene::IMeshBuffer *copy = cloneMeshBuffer(mesh->getMeshBuffer(0)); copy->getMaterial().setTexture(0, overlay_texture); mesh->addMeshBuffer(copy); copy->drop(); } // Customize materials for (u32 layer = 0; layer < mesh->getMeshBufferCount(); layer++) { video::SMaterial &material = mesh->getMeshBuffer(layer)->getMaterial(); material.TextureLayer[0].TextureWrapU = video::ETC_CLAMP_TO_EDGE; material.TextureLayer[0].TextureWrapV = video::ETC_CLAMP_TO_EDGE; material.setFlag(video::EMF_BILINEAR_FILTER, false); material.setFlag(video::EMF_TRILINEAR_FILTER, false); material.setFlag(video::EMF_BACK_FACE_CULLING, true); material.setFlag(video::EMF_LIGHTING, false); material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; material.MaterialTypeParam = 0.5f; } scaleMesh(mesh, v3f(2.0, 2.0, 2.0)); return mesh; } void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, bool use_shaders, bool set_material, const video::E_MATERIAL_TYPE *mattype, std::vector<ItemPartColor> *colors, bool apply_scale) { u32 mc = mesh->getMeshBufferCount(); // Allocate colors for existing buffers colors->clear(); for (u32 i = 0; i < mc; ++i) colors->push_back(ItemPartColor()); for (u32 i = 0; i < mc; ++i) { const TileSpec *tile = &(f.tiles[i]); scene::IMeshBuffer *buf = mesh->getMeshBuffer(i); for (int layernum = 0; layernum < MAX_TILE_LAYERS; layernum++) { const TileLayer *layer = &tile->layers[layernum]; if (layer->texture_id == 0) continue; if (layernum != 0) { scene::IMeshBuffer *copy = cloneMeshBuffer(buf); copy->getMaterial() = buf->getMaterial(); mesh->addMeshBuffer(copy); copy->drop(); buf = copy; colors->push_back( ItemPartColor(layer->has_color, layer->color)); } else { (*colors)[i] = ItemPartColor(layer->has_color, layer->color); } video::SMaterial &material = buf->getMaterial(); if (set_material) layer->applyMaterialOptions(material); if (mattype) { material.MaterialType = *mattype; } if (layer->animation_frame_count > 1) { const FrameSpec &animation_frame = (*layer->frames)[0]; material.setTexture(0, animation_frame.texture); } else { material.setTexture(0, layer->texture); } if (use_shaders) { if (layer->normal_texture) { if (layer->animation_frame_count > 1) { const FrameSpec &animation_frame = (*layer->frames)[0]; material.setTexture(1, animation_frame.normal_texture); } else material.setTexture(1, layer->normal_texture); } material.setTexture(2, layer->flags_texture); } if (apply_scale && tile->world_aligned) { u32 n = buf->getVertexCount(); for (u32 k = 0; k != n; ++k) buf->getTCoords(k) /= layer->scale; } } } }
pgimeno/minetest
src/client/wieldmesh.cpp
C++
mit
22,575
/* Minetest Copyright (C) 2010-2014 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <string> #include <vector> #include "irrlichttypes_extrabloated.h" struct ItemStack; class Client; class ITextureSource; struct ContentFeatures; /*! * Holds color information of an item mesh's buffer. */ struct ItemPartColor { /*! * If this is false, the global base color of the item * will be used instead of the specific color of the * buffer. */ bool override_base = false; /*! * The color of the buffer. */ video::SColor color = 0; ItemPartColor() = default; ItemPartColor(bool override, video::SColor color) : override_base(override), color(color) { } }; struct ItemMesh { scene::IMesh *mesh = nullptr; /*! * Stores the color of each mesh buffer. */ std::vector<ItemPartColor> buffer_colors; /*! * If false, all faces of the item should have the same brightness. * Disables shading based on normal vectors. */ bool needs_shading = true; ItemMesh() = default; }; /* Wield item scene node, renders the wield mesh of some item */ class WieldMeshSceneNode : public scene::ISceneNode { public: WieldMeshSceneNode(scene::ISceneManager *mgr, s32 id = -1, bool lighting = false); virtual ~WieldMeshSceneNode(); void setCube(const ContentFeatures &f, v3f wield_scale); void setExtruded(const std::string &imagename, const std::string &overlay_image, v3f wield_scale, ITextureSource *tsrc, u8 num_frames); void setItem(const ItemStack &item, Client *client, bool check_wield_image = true); // Sets the vertex color of the wield mesh. // Must only be used if the constructor was called with lighting = false void setColor(video::SColor color); scene::IMesh *getMesh() { return m_meshnode->getMesh(); } virtual void render(); virtual const aabb3f &getBoundingBox() const { return m_bounding_box; } private: void changeToMesh(scene::IMesh *mesh); // Child scene node with the current wield mesh scene::IMeshSceneNode *m_meshnode = nullptr; video::E_MATERIAL_TYPE m_material_type; // True if EMF_LIGHTING should be enabled. bool m_lighting; bool m_enable_shaders; bool m_anisotropic_filter; bool m_bilinear_filter; bool m_trilinear_filter; /*! * Stores the colors of the mesh's mesh buffers. * This does not include lighting. */ std::vector<ItemPartColor> m_colors; /*! * The base color of this mesh. This is the default * for all mesh buffers. */ video::SColor m_base_color; // Bounding box culling is disabled for this type of scene node, // so this variable is just required so we can implement // getBoundingBox() and is set to an empty box. aabb3f m_bounding_box; }; void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result); scene::SMesh *getExtrudedMesh(ITextureSource *tsrc, const std::string &imagename, const std::string &overlay_name); /*! * Applies overlays, textures and optionally materials to the given mesh and * extracts tile colors for colorization. * \param mattype overrides the buffer's material type, but can also * be NULL to leave the original material. * \param colors returns the colors of the mesh buffers in the mesh. */ void postProcessNodeMesh(scene::SMesh *mesh, const ContentFeatures &f, bool use_shaders, bool set_material, const video::E_MATERIAL_TYPE *mattype, std::vector<ItemPartColor> *colors, bool apply_scale = false);
pgimeno/minetest
src/client/wieldmesh.h
C++
mit
4,101
/* Minetest Copyright (C) 2010-2014 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <sstream> #include "clientiface.h" #include "network/connection.h" #include "network/serveropcodes.h" #include "remoteplayer.h" #include "settings.h" #include "mapblock.h" #include "serverenvironment.h" #include "map.h" #include "emerge.h" #include "content_sao.h" // TODO this is used for cleanup of only #include "log.h" #include "util/srp.h" #include "face_position_cache.h" const char *ClientInterface::statenames[] = { "Invalid", "Disconnecting", "Denied", "Created", "AwaitingInit2", "HelloSent", "InitDone", "DefinitionsSent", "Active", "SudoMode", }; std::string ClientInterface::state2Name(ClientState state) { return statenames[state]; } RemoteClient::RemoteClient() : m_max_simul_sends(g_settings->getU16("max_simultaneous_block_sends_per_client")), m_min_time_from_building( g_settings->getFloat("full_block_send_enable_min_time_from_building")), m_max_send_distance(g_settings->getS16("max_block_send_distance")), m_block_optimize_distance(g_settings->getS16("block_send_optimize_distance")), m_max_gen_distance(g_settings->getS16("max_block_generate_distance")), m_occ_cull(g_settings->getBool("server_side_occlusion_culling")) { } void RemoteClient::ResendBlockIfOnWire(v3s16 p) { // if this block is on wire, mark it for sending again as soon as possible if (m_blocks_sending.find(p) != m_blocks_sending.end()) { SetBlockNotSent(p); } } LuaEntitySAO *getAttachedObject(PlayerSAO *sao, ServerEnvironment *env) { if (!sao->isAttached()) return nullptr; int id; std::string bone; v3f dummy; sao->getAttachment(&id, &bone, &dummy, &dummy); ServerActiveObject *ao = env->getActiveObject(id); while (id && ao) { ao->getAttachment(&id, &bone, &dummy, &dummy); if (id) ao = env->getActiveObject(id); } return dynamic_cast<LuaEntitySAO *>(ao); } void RemoteClient::GetNextBlocks ( ServerEnvironment *env, EmergeManager * emerge, float dtime, std::vector<PrioritySortedBlockTransfer> &dest) { // Increment timers m_nothing_to_send_pause_timer -= dtime; m_nearest_unsent_reset_timer += dtime; if (m_nothing_to_send_pause_timer >= 0) return; RemotePlayer *player = env->getPlayer(peer_id); // This can happen sometimes; clients and players are not in perfect sync. if (!player) return; PlayerSAO *sao = player->getPlayerSAO(); if (!sao) return; // Won't send anything if already sending if (m_blocks_sending.size() >= m_max_simul_sends) { //infostream<<"Not sending any blocks, Queue full."<<std::endl; return; } v3f playerpos = sao->getBasePosition(); // if the player is attached, get the velocity from the attached object LuaEntitySAO *lsao = getAttachedObject(sao, env); const v3f &playerspeed = lsao? lsao->getVelocity() : player->getSpeed(); v3f playerspeeddir(0,0,0); if (playerspeed.getLength() > 1.0f * BS) playerspeeddir = playerspeed / playerspeed.getLength(); // Predict to next block v3f playerpos_predicted = playerpos + playerspeeddir * (MAP_BLOCKSIZE * BS); v3s16 center_nodepos = floatToInt(playerpos_predicted, BS); v3s16 center = getNodeBlockPos(center_nodepos); // Camera position and direction v3f camera_pos = sao->getEyePosition(); v3f camera_dir = v3f(0,0,1); camera_dir.rotateYZBy(sao->getLookPitch()); camera_dir.rotateXZBy(sao->getRotation().Y); /*infostream<<"camera_dir=("<<camera_dir.X<<","<<camera_dir.Y<<"," <<camera_dir.Z<<")"<<std::endl;*/ /* Get the starting value of the block finder radius. */ if (m_last_center != center) { m_nearest_unsent_d = 0; m_last_center = center; } /*infostream<<"m_nearest_unsent_reset_timer=" <<m_nearest_unsent_reset_timer<<std::endl;*/ // Reset periodically to workaround for some bugs or stuff if (m_nearest_unsent_reset_timer > 20.0f) { m_nearest_unsent_reset_timer = 0.0f; m_nearest_unsent_d = 0; //infostream<<"Resetting m_nearest_unsent_d for " // <<server->getPlayerName(peer_id)<<std::endl; } //s16 last_nearest_unsent_d = m_nearest_unsent_d; s16 d_start = m_nearest_unsent_d; //infostream<<"d_start="<<d_start<<std::endl; u16 max_simul_sends_usually = m_max_simul_sends; /* Check the time from last addNode/removeNode. Decrease send rate if player is building stuff. */ m_time_from_building += dtime; if (m_time_from_building < m_min_time_from_building) { max_simul_sends_usually = LIMITED_MAX_SIMULTANEOUS_BLOCK_SENDS; } /* Number of blocks sending + number of blocks selected for sending */ u32 num_blocks_selected = m_blocks_sending.size(); /* next time d will be continued from the d from which the nearest unsent block was found this time. This is because not necessarily any of the blocks found this time are actually sent. */ s32 new_nearest_unsent_d = -1; // Get view range and camera fov (radians) from the client s16 wanted_range = sao->getWantedRange() + 1; float camera_fov = sao->getFov(); // Distrust client-sent FOV and get server-set player object property // zoom FOV (degrees) as a check to avoid hacked clients using FOV to load // distant world. // (zoom is disabled by value 0) float prop_zoom_fov = sao->getZoomFOV() < 0.001f ? 0.0f : std::max(camera_fov, sao->getZoomFOV() * core::DEGTORAD); const s16 full_d_max = std::min(adjustDist(m_max_send_distance, prop_zoom_fov), wanted_range); const s16 d_opt = std::min(adjustDist(m_block_optimize_distance, prop_zoom_fov), wanted_range); const s16 d_blocks_in_sight = full_d_max * BS * MAP_BLOCKSIZE; s16 d_max = full_d_max; s16 d_max_gen = std::min(adjustDist(m_max_gen_distance, prop_zoom_fov), wanted_range); // Don't loop very much at a time, adjust with distance, // do more work per RTT with greater distances. s16 max_d_increment_at_time = full_d_max / 9 + 1; if (d_max > d_start + max_d_increment_at_time) d_max = d_start + max_d_increment_at_time; // cos(angle between velocity and camera) * |velocity| // Limit to 0.0f in case player moves backwards. f32 dot = rangelim(camera_dir.dotProduct(playerspeed), 0.0f, 300.0f); // Reduce the field of view when a player moves and looks forward. // limit max fov effect to 50%, 60% at 20n/s fly speed camera_fov = camera_fov / (1 + dot / 300.0f); s32 nearest_emerged_d = -1; s32 nearest_emergefull_d = -1; s32 nearest_sent_d = -1; //bool queue_is_full = false; const v3s16 cam_pos_nodes = floatToInt(camera_pos, BS); s16 d; for (d = d_start; d <= d_max; d++) { /* Get the border/face dot coordinates of a "d-radiused" box */ std::vector<v3s16> list = FacePositionCache::getFacePositions(d); std::vector<v3s16>::iterator li; for (li = list.begin(); li != list.end(); ++li) { v3s16 p = *li + center; /* Send throttling - Don't allow too many simultaneous transfers - EXCEPT when the blocks are very close Also, don't send blocks that are already flying. */ // Start with the usual maximum u16 max_simul_dynamic = max_simul_sends_usually; // If block is very close, allow full maximum if (d <= BLOCK_SEND_DISABLE_LIMITS_MAX_D) max_simul_dynamic = m_max_simul_sends; // Don't select too many blocks for sending if (num_blocks_selected >= max_simul_dynamic) { //queue_is_full = true; goto queue_full_break; } // Don't send blocks that are currently being transferred if (m_blocks_sending.find(p) != m_blocks_sending.end()) continue; /* Do not go over max mapgen limit */ if (blockpos_over_max_limit(p)) continue; // If this is true, inexistent block will be made from scratch bool generate = d <= d_max_gen; /* Don't generate or send if not in sight FIXME This only works if the client uses a small enough FOV setting. The default of 72 degrees is fine. Also retrieve a smaller view cone in the direction of the player's movement. (0.1 is about 4 degrees) */ f32 dist; if (!(isBlockInSight(p, camera_pos, camera_dir, camera_fov, d_blocks_in_sight, &dist) || (playerspeed.getLength() > 1.0f * BS && isBlockInSight(p, camera_pos, playerspeeddir, 0.1f, d_blocks_in_sight)))) { continue; } /* Don't send already sent blocks */ if (m_blocks_sent.find(p) != m_blocks_sent.end()) continue; /* Check if map has this block */ MapBlock *block = env->getMap().getBlockNoCreateNoEx(p); bool surely_not_found_on_disk = false; bool block_is_invalid = false; if (block) { // Reset usage timer, this block will be of use in the future. block->resetUsageTimer(); // Block is dummy if data doesn't exist. // It means it has been not found from disk and not generated if (block->isDummy()) { surely_not_found_on_disk = true; } if (!block->isGenerated()) block_is_invalid = true; /* If block is not close, don't send it unless it is near ground level. Block is near ground level if night-time mesh differs from day-time mesh. */ if (d >= d_opt) { if (!block->getIsUnderground() && !block->getDayNightDiff()) continue; } if (m_occ_cull && !block_is_invalid && env->getMap().isBlockOccluded(block, cam_pos_nodes)) { continue; } } /* If block has been marked to not exist on disk (dummy) and generating new ones is not wanted, skip block. */ if (!generate && surely_not_found_on_disk) { // get next one. continue; } /* Add inexistent block to emerge queue. */ if (block == NULL || surely_not_found_on_disk || block_is_invalid) { if (emerge->enqueueBlockEmerge(peer_id, p, generate)) { if (nearest_emerged_d == -1) nearest_emerged_d = d; } else { if (nearest_emergefull_d == -1) nearest_emergefull_d = d; goto queue_full_break; } // get next one. continue; } if (nearest_sent_d == -1) nearest_sent_d = d; /* Add block to send queue */ PrioritySortedBlockTransfer q((float)dist, p, peer_id); dest.push_back(q); num_blocks_selected += 1; } } queue_full_break: // If nothing was found for sending and nothing was queued for // emerging, continue next time browsing from here if (nearest_emerged_d != -1) { new_nearest_unsent_d = nearest_emerged_d; } else if (nearest_emergefull_d != -1) { new_nearest_unsent_d = nearest_emergefull_d; } else { if (d > full_d_max) { new_nearest_unsent_d = 0; m_nothing_to_send_pause_timer = 2.0f; } else { if (nearest_sent_d != -1) new_nearest_unsent_d = nearest_sent_d; else new_nearest_unsent_d = d; } } if (new_nearest_unsent_d != -1) m_nearest_unsent_d = new_nearest_unsent_d; } void RemoteClient::GotBlock(v3s16 p) { if (m_blocks_modified.find(p) == m_blocks_modified.end()) { if (m_blocks_sending.find(p) != m_blocks_sending.end()) m_blocks_sending.erase(p); else m_excess_gotblocks++; m_blocks_sent.insert(p); } } void RemoteClient::SentBlock(v3s16 p) { if (m_blocks_modified.find(p) != m_blocks_modified.end()) m_blocks_modified.erase(p); if (m_blocks_sending.find(p) == m_blocks_sending.end()) m_blocks_sending[p] = 0.0f; else infostream<<"RemoteClient::SentBlock(): Sent block" " already in m_blocks_sending"<<std::endl; } void RemoteClient::SetBlockNotSent(v3s16 p) { m_nearest_unsent_d = 0; m_nothing_to_send_pause_timer = 0; if (m_blocks_sending.find(p) != m_blocks_sending.end()) m_blocks_sending.erase(p); if (m_blocks_sent.find(p) != m_blocks_sent.end()) m_blocks_sent.erase(p); m_blocks_modified.insert(p); } void RemoteClient::SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks) { m_nearest_unsent_d = 0; m_nothing_to_send_pause_timer = 0; for (auto &block : blocks) { v3s16 p = block.first; m_blocks_modified.insert(p); if (m_blocks_sending.find(p) != m_blocks_sending.end()) m_blocks_sending.erase(p); if (m_blocks_sent.find(p) != m_blocks_sent.end()) m_blocks_sent.erase(p); } } void RemoteClient::notifyEvent(ClientStateEvent event) { std::ostringstream myerror; switch (m_state) { case CS_Invalid: //intentionally do nothing break; case CS_Created: switch (event) { case CSE_Hello: m_state = CS_HelloSent; break; case CSE_InitLegacy: m_state = CS_AwaitingInit2; break; case CSE_Disconnect: m_state = CS_Disconnecting; break; case CSE_SetDenied: m_state = CS_Denied; break; /* GotInit2 SetDefinitionsSent SetMediaSent */ default: myerror << "Created: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); } break; case CS_Denied: /* don't do anything if in denied state */ break; case CS_HelloSent: switch(event) { case CSE_AuthAccept: m_state = CS_AwaitingInit2; if (chosen_mech == AUTH_MECHANISM_SRP || chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD) srp_verifier_delete((SRPVerifier *) auth_data); chosen_mech = AUTH_MECHANISM_NONE; break; case CSE_Disconnect: m_state = CS_Disconnecting; break; case CSE_SetDenied: m_state = CS_Denied; if (chosen_mech == AUTH_MECHANISM_SRP || chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD) srp_verifier_delete((SRPVerifier *) auth_data); chosen_mech = AUTH_MECHANISM_NONE; break; default: myerror << "HelloSent: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); } break; case CS_AwaitingInit2: switch(event) { case CSE_GotInit2: confirmSerializationVersion(); m_state = CS_InitDone; break; case CSE_Disconnect: m_state = CS_Disconnecting; break; case CSE_SetDenied: m_state = CS_Denied; break; /* Init SetDefinitionsSent SetMediaSent */ default: myerror << "InitSent: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); } break; case CS_InitDone: switch(event) { case CSE_SetDefinitionsSent: m_state = CS_DefinitionsSent; break; case CSE_Disconnect: m_state = CS_Disconnecting; break; case CSE_SetDenied: m_state = CS_Denied; break; /* Init GotInit2 SetMediaSent */ default: myerror << "InitDone: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); } break; case CS_DefinitionsSent: switch(event) { case CSE_SetClientReady: m_state = CS_Active; break; case CSE_Disconnect: m_state = CS_Disconnecting; break; case CSE_SetDenied: m_state = CS_Denied; break; /* Init GotInit2 SetDefinitionsSent */ default: myerror << "DefinitionsSent: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); } break; case CS_Active: switch(event) { case CSE_SetDenied: m_state = CS_Denied; break; case CSE_Disconnect: m_state = CS_Disconnecting; break; case CSE_SudoSuccess: m_state = CS_SudoMode; if (chosen_mech == AUTH_MECHANISM_SRP) srp_verifier_delete((SRPVerifier *) auth_data); chosen_mech = AUTH_MECHANISM_NONE; break; /* Init GotInit2 SetDefinitionsSent SetMediaSent SetDenied */ default: myerror << "Active: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); break; } break; case CS_SudoMode: switch(event) { case CSE_SetDenied: m_state = CS_Denied; break; case CSE_Disconnect: m_state = CS_Disconnecting; break; case CSE_SudoLeave: m_state = CS_Active; break; default: myerror << "Active: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); break; } break; case CS_Disconnecting: /* we are already disconnecting */ break; } } u64 RemoteClient::uptime() const { return porting::getTimeS() - m_connection_time; } ClientInterface::ClientInterface(const std::shared_ptr<con::Connection> & con) : m_con(con), m_env(NULL), m_print_info_timer(0.0f) { } ClientInterface::~ClientInterface() { /* Delete clients */ { MutexAutoLock clientslock(m_clients_mutex); for (auto &client_it : m_clients) { // Delete client delete client_it.second; } } } std::vector<session_t> ClientInterface::getClientIDs(ClientState min_state) { std::vector<session_t> reply; MutexAutoLock clientslock(m_clients_mutex); for (const auto &m_client : m_clients) { if (m_client.second->getState() >= min_state) reply.push_back(m_client.second->peer_id); } return reply; } void ClientInterface::markBlockposAsNotSent(const v3s16 &pos) { MutexAutoLock clientslock(m_clients_mutex); for (const auto &client : m_clients) { if (client.second->getState() >= CS_Active) client.second->SetBlockNotSent(pos); } } /** * Verify if user limit was reached. * User limit count all clients from HelloSent state (MT protocol user) to Active state * @return true if user limit was reached */ bool ClientInterface::isUserLimitReached() { return getClientIDs(CS_HelloSent).size() >= g_settings->getU16("max_users"); } void ClientInterface::step(float dtime) { m_print_info_timer += dtime; if (m_print_info_timer >= 30.0f) { m_print_info_timer = 0.0f; UpdatePlayerList(); } } void ClientInterface::UpdatePlayerList() { if (m_env) { std::vector<session_t> clients = getClientIDs(); m_clients_names.clear(); if (!clients.empty()) infostream<<"Players:"<<std::endl; for (session_t i : clients) { RemotePlayer *player = m_env->getPlayer(i); if (player == NULL) continue; infostream << "* " << player->getName() << "\t"; { MutexAutoLock clientslock(m_clients_mutex); RemoteClient* client = lockedGetClientNoEx(i); if (client) client->PrintInfo(infostream); } m_clients_names.emplace_back(player->getName()); } } } void ClientInterface::send(session_t peer_id, u8 channelnum, NetworkPacket *pkt, bool reliable) { m_con->Send(peer_id, channelnum, pkt, reliable); } void ClientInterface::sendToAll(NetworkPacket *pkt) { MutexAutoLock clientslock(m_clients_mutex); for (auto &client_it : m_clients) { RemoteClient *client = client_it.second; if (client->net_proto_version != 0) { m_con->Send(client->peer_id, clientCommandFactoryTable[pkt->getCommand()].channel, pkt, clientCommandFactoryTable[pkt->getCommand()].reliable); } } } void ClientInterface::sendToAllCompat(NetworkPacket *pkt, NetworkPacket *legacypkt, u16 min_proto_ver) { MutexAutoLock clientslock(m_clients_mutex); for (auto &client_it : m_clients) { RemoteClient *client = client_it.second; NetworkPacket *pkt_to_send = nullptr; if (client->net_proto_version >= min_proto_ver) { pkt_to_send = pkt; } else if (client->net_proto_version != 0) { pkt_to_send = legacypkt; } else { warningstream << "Client with unhandled version to handle: '" << client->net_proto_version << "'"; continue; } m_con->Send(client->peer_id, clientCommandFactoryTable[pkt_to_send->getCommand()].channel, pkt_to_send, clientCommandFactoryTable[pkt_to_send->getCommand()].reliable); } } RemoteClient* ClientInterface::getClientNoEx(session_t peer_id, ClientState state_min) { MutexAutoLock clientslock(m_clients_mutex); RemoteClientMap::const_iterator n = m_clients.find(peer_id); // The client may not exist; clients are immediately removed if their // access is denied, and this event occurs later then. if (n == m_clients.end()) return NULL; if (n->second->getState() >= state_min) return n->second; return NULL; } RemoteClient* ClientInterface::lockedGetClientNoEx(session_t peer_id, ClientState state_min) { RemoteClientMap::const_iterator n = m_clients.find(peer_id); // The client may not exist; clients are immediately removed if their // access is denied, and this event occurs later then. if (n == m_clients.end()) return NULL; if (n->second->getState() >= state_min) return n->second; return NULL; } ClientState ClientInterface::getClientState(session_t peer_id) { MutexAutoLock clientslock(m_clients_mutex); RemoteClientMap::const_iterator n = m_clients.find(peer_id); // The client may not exist; clients are immediately removed if their // access is denied, and this event occurs later then. if (n == m_clients.end()) return CS_Invalid; return n->second->getState(); } void ClientInterface::setPlayerName(session_t peer_id, const std::string &name) { MutexAutoLock clientslock(m_clients_mutex); RemoteClientMap::iterator n = m_clients.find(peer_id); // The client may not exist; clients are immediately removed if their // access is denied, and this event occurs later then. if (n != m_clients.end()) n->second->setName(name); } void ClientInterface::DeleteClient(session_t peer_id) { MutexAutoLock conlock(m_clients_mutex); // Error check RemoteClientMap::iterator n = m_clients.find(peer_id); // The client may not exist; clients are immediately removed if their // access is denied, and this event occurs later then. if (n == m_clients.end()) return; /* Mark objects to be not known by the client */ //TODO this should be done by client destructor!!! RemoteClient *client = n->second; // Handle objects for (u16 id : client->m_known_objects) { // Get object ServerActiveObject* obj = m_env->getActiveObject(id); if(obj && obj->m_known_by_count > 0) obj->m_known_by_count--; } // Delete client delete m_clients[peer_id]; m_clients.erase(peer_id); } void ClientInterface::CreateClient(session_t peer_id) { MutexAutoLock conlock(m_clients_mutex); // Error check RemoteClientMap::iterator n = m_clients.find(peer_id); // The client shouldn't already exist if (n != m_clients.end()) return; // Create client RemoteClient *client = new RemoteClient(); client->peer_id = peer_id; m_clients[client->peer_id] = client; } void ClientInterface::event(session_t peer_id, ClientStateEvent event) { { MutexAutoLock clientlock(m_clients_mutex); // Error check RemoteClientMap::iterator n = m_clients.find(peer_id); // No client to deliver event if (n == m_clients.end()) return; n->second->notifyEvent(event); } if ((event == CSE_SetClientReady) || (event == CSE_Disconnect) || (event == CSE_SetDenied)) { UpdatePlayerList(); } } u16 ClientInterface::getProtocolVersion(session_t peer_id) { MutexAutoLock conlock(m_clients_mutex); // Error check RemoteClientMap::iterator n = m_clients.find(peer_id); // No client to get version if (n == m_clients.end()) return 0; return n->second->net_proto_version; } void ClientInterface::setClientVersion(session_t peer_id, u8 major, u8 minor, u8 patch, const std::string &full) { MutexAutoLock conlock(m_clients_mutex); // Error check RemoteClientMap::iterator n = m_clients.find(peer_id); // No client to set versions if (n == m_clients.end()) return; n->second->setVersionInfo(major, minor, patch, full); }
pgimeno/minetest
src/clientiface.cpp
C++
mit
23,533
/* Minetest Copyright (C) 2010-2014 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irr_v3d.h" // for irrlicht datatypes #include "constants.h" #include "serialization.h" // for SER_FMT_VER_INVALID #include "network/networkpacket.h" #include "network/networkprotocol.h" #include "porting.h" #include <list> #include <vector> #include <set> #include <mutex> class MapBlock; class ServerEnvironment; class EmergeManager; /* * State Transitions Start (peer connect) | v /-----------------\ | | | Created | | | \-----------------/ | depending of the incoming packet ---------------------------------------- v +-----------------------------+ |IN: | | TOSERVER_INIT | +-----------------------------+ | invalid playername | or denied by mod v +-----------------------------+ |OUT: | | TOCLIENT_HELLO | +-----------------------------+ | | v /-----------------\ /-----------------\ | | | | | AwaitingInit2 |<--------- | HelloSent | | | | | | \-----------------/ | \-----------------/ | | | +-----------------------------+ | *-----------------------------* Auth fails |IN: | | |Authentication, depending on |------------------ | TOSERVER_INIT2 | | | packet sent by client | | +-----------------------------+ | *-----------------------------* | | | | | | | | Authentication | v | | successful | /-----------------\ | v | | | | +-----------------------------+ | | InitDone | | |OUT: | | | | | | TOCLIENT_AUTH_ACCEPT | | \-----------------/ | +-----------------------------+ | | | | | +-----------------------------+ --------------------- | |OUT: | | | TOCLIENT_MOVEMENT | | | TOCLIENT_ITEMDEF | | | TOCLIENT_NODEDEF | | | TOCLIENT_ANNOUNCE_MEDIA | | | TOCLIENT_DETACHED_INVENTORY | | | TOCLIENT_TIME_OF_DAY | | +-----------------------------+ | | | | | | ----------------------------- | v | | | /-----------------\ v | | | +-----------------------------+ | | DefinitionsSent | |IN: | | | | | TOSERVER_REQUEST_MEDIA | | \-----------------/ | | | | +-----------------------------+ | | ^ | | | ----------------------------- | v v +-----------------------------+ --------------------------------+ |IN: | | ^ | TOSERVER_CLIENT_READY | v | +-----------------------------+ +------------------------+ | | |OUT: | | v | TOCLIENT_ACCESS_DENIED | | +-----------------------------+ +------------------------+ | |OUT: | | | | TOCLIENT_MOVE_PLAYER | v | | TOCLIENT_PRIVILEGES | /-----------------\ | | TOCLIENT_INVENTORY_FORMSPEC | | | | | UpdateCrafting | | Denied | | | TOCLIENT_INVENTORY | | | | | TOCLIENT_HP (opt) | \-----------------/ | | TOCLIENT_BREATH | | | TOCLIENT_DEATHSCREEN | | +-----------------------------+ | | | v | /-----------------\ async mod action (ban, kick) | | |--------------------------------------------------------------- ---->| Active | | | |---------------------------------------------- | \-----------------/ timeout v | | | +-----------------------------+ | | | |OUT: | | | | | TOCLIENT_DISCONNECT | | | | +-----------------------------+ | | | | | | v v | | +-----------------------------+ /-----------------\ | | |IN: | | | | | | TOSERVER_DISCONNECT |------------------->| Disconnecting | | | +-----------------------------+ | | | | \-----------------/ | | any auth packet which was | | allowed in TOCLIENT_AUTH_ACCEPT | v | *-----------------------------* Auth +-------------------------------+ | |Authentication, depending on | succeeds |OUT: | | | packet sent by client |---------->| TOCLIENT_ACCEPT_SUDO_MODE | | *-----------------------------* +-------------------------------+ | | | | | Auth fails /-----------------\ | v | | | +-------------------------------+ | SudoMode | | |OUT: | | | | | TOCLIENT_DENY_SUDO_MODE | \-----------------/ | +-------------------------------+ | | | v | | +-----------------------------+ | | sets password accordingly |IN: | -------------------+-------------------------------| TOSERVER_FIRST_SRP | +-----------------------------+ */ namespace con { class Connection; } // Also make sure to update the ClientInterface::statenames // array when modifying these enums enum ClientState { CS_Invalid, CS_Disconnecting, CS_Denied, CS_Created, CS_AwaitingInit2, CS_HelloSent, CS_InitDone, CS_DefinitionsSent, CS_Active, CS_SudoMode }; enum ClientStateEvent { CSE_Hello, CSE_AuthAccept, CSE_InitLegacy, CSE_GotInit2, CSE_SetDenied, CSE_SetDefinitionsSent, CSE_SetClientReady, CSE_SudoSuccess, CSE_SudoLeave, CSE_Disconnect }; /* Used for queueing and sorting block transfers in containers Lower priority number means higher priority. */ struct PrioritySortedBlockTransfer { PrioritySortedBlockTransfer(float a_priority, const v3s16 &a_pos, session_t a_peer_id) { priority = a_priority; pos = a_pos; peer_id = a_peer_id; } bool operator < (const PrioritySortedBlockTransfer &other) const { return priority < other.priority; } float priority; v3s16 pos; session_t peer_id; }; class RemoteClient { public: // peer_id=0 means this client has no associated peer // NOTE: If client is made allowed to exist while peer doesn't, // this has to be set to 0 when there is no peer. // Also, the client must be moved to some other container. session_t peer_id = PEER_ID_INEXISTENT; // The serialization version to use with the client u8 serialization_version = SER_FMT_VER_INVALID; // u16 net_proto_version = 0; /* Authentication information */ std::string enc_pwd = ""; bool create_player_on_auth_success = false; AuthMechanism chosen_mech = AUTH_MECHANISM_NONE; void *auth_data = nullptr; u32 allowed_auth_mechs = 0; u32 allowed_sudo_mechs = 0; bool isSudoMechAllowed(AuthMechanism mech) { return allowed_sudo_mechs & mech; } bool isMechAllowed(AuthMechanism mech) { return allowed_auth_mechs & mech; } RemoteClient(); ~RemoteClient() = default; /* Finds block that should be sent next to the client. Environment should be locked when this is called. dtime is used for resetting send radius at slow interval */ void GetNextBlocks(ServerEnvironment *env, EmergeManager* emerge, float dtime, std::vector<PrioritySortedBlockTransfer> &dest); void GotBlock(v3s16 p); void SentBlock(v3s16 p); void SetBlockNotSent(v3s16 p); void SetBlocksNotSent(std::map<v3s16, MapBlock*> &blocks); /** * tell client about this block being modified right now. * this information is required to requeue the block in case it's "on wire" * while modification is processed by server * @param p position of modified block */ void ResendBlockIfOnWire(v3s16 p); u32 getSendingCount() const { return m_blocks_sending.size(); } bool isBlockSent(v3s16 p) const { return m_blocks_sent.find(p) != m_blocks_sent.end(); } // Increments timeouts and removes timed-out blocks from list // NOTE: This doesn't fix the server-not-sending-block bug // because it is related to emerging, not sending. //void RunSendingTimeouts(float dtime, float timeout); void PrintInfo(std::ostream &o) { o<<"RemoteClient "<<peer_id<<": " <<"m_blocks_sent.size()="<<m_blocks_sent.size() <<", m_blocks_sending.size()="<<m_blocks_sending.size() <<", m_nearest_unsent_d="<<m_nearest_unsent_d <<", m_excess_gotblocks="<<m_excess_gotblocks <<std::endl; m_excess_gotblocks = 0; } // Time from last placing or removing blocks float m_time_from_building = 9999; /* List of active objects that the client knows of. */ std::set<u16> m_known_objects; ClientState getState() const { return m_state; } std::string getName() const { return m_name; } void setName(const std::string &name) { m_name = name; } /* update internal client state */ void notifyEvent(ClientStateEvent event); /* set expected serialization version */ void setPendingSerializationVersion(u8 version) { m_pending_serialization_version = version; } void setDeployedCompressionMode(u16 byteFlag) { m_deployed_compression = byteFlag; } void confirmSerializationVersion() { serialization_version = m_pending_serialization_version; } /* get uptime */ u64 uptime() const; /* set version information */ void setVersionInfo(u8 major, u8 minor, u8 patch, const std::string &full) { m_version_major = major; m_version_minor = minor; m_version_patch = patch; m_full_version = full; } /* read version information */ u8 getMajor() const { return m_version_major; } u8 getMinor() const { return m_version_minor; } u8 getPatch() const { return m_version_patch; } private: // Version is stored in here after INIT before INIT2 u8 m_pending_serialization_version = SER_FMT_VER_INVALID; /* current state of client */ ClientState m_state = CS_Created; /* Blocks that have been sent to client. - These don't have to be sent again. - A block is cleared from here when client says it has deleted it from it's memory List of block positions. No MapBlock* is stored here because the blocks can get deleted. */ std::set<v3s16> m_blocks_sent; s16 m_nearest_unsent_d = 0; v3s16 m_last_center; float m_nearest_unsent_reset_timer = 0.0f; const u16 m_max_simul_sends; const float m_min_time_from_building; const s16 m_max_send_distance; const s16 m_block_optimize_distance; const s16 m_max_gen_distance; const bool m_occ_cull; /* Blocks that are currently on the line. This is used for throttling the sending of blocks. - The size of this list is limited to some value Block is added when it is sent with BLOCKDATA. Block is removed when GOTBLOCKS is received. Value is time from sending. (not used at the moment) */ std::map<v3s16, float> m_blocks_sending; /* Blocks that have been modified since last sending them. These blocks will not be marked as sent, even if the client reports it has received them to account for blocks that are being modified while on the line. List of block positions. */ std::set<v3s16> m_blocks_modified; /* Count of excess GotBlocks(). There is an excess amount because the client sometimes gets a block so late that the server sends it again, and the client then sends two GOTBLOCKs. This is resetted by PrintInfo() */ u32 m_excess_gotblocks = 0; // CPU usage optimization float m_nothing_to_send_pause_timer = 0.0f; /* name of player using this client */ std::string m_name = ""; /* client information */ u8 m_version_major = 0; u8 m_version_minor = 0; u8 m_version_patch = 0; std::string m_full_version = "unknown"; u16 m_deployed_compression = 0; /* time this client was created */ const u64 m_connection_time = porting::getTimeS(); }; typedef std::unordered_map<u16, RemoteClient*> RemoteClientMap; class ClientInterface { public: friend class Server; ClientInterface(const std::shared_ptr<con::Connection> &con); ~ClientInterface(); /* run sync step */ void step(float dtime); /* get list of active client id's */ std::vector<session_t> getClientIDs(ClientState min_state=CS_Active); /* mark block as not sent to active client sessions */ void markBlockposAsNotSent(const v3s16 &pos); /* verify is server user limit was reached */ bool isUserLimitReached(); /* get list of client player names */ const std::vector<std::string> &getPlayerNames() const { return m_clients_names; } /* send message to client */ void send(session_t peer_id, u8 channelnum, NetworkPacket *pkt, bool reliable); /* send to all clients */ void sendToAll(NetworkPacket *pkt); void sendToAllCompat(NetworkPacket *pkt, NetworkPacket *legacypkt, u16 min_proto_ver); /* delete a client */ void DeleteClient(session_t peer_id); /* create client */ void CreateClient(session_t peer_id); /* get a client by peer_id */ RemoteClient *getClientNoEx(session_t peer_id, ClientState state_min = CS_Active); /* get client by peer_id (make sure you have list lock before!*/ RemoteClient *lockedGetClientNoEx(session_t peer_id, ClientState state_min = CS_Active); /* get state of client by id*/ ClientState getClientState(session_t peer_id); /* set client playername */ void setPlayerName(session_t peer_id, const std::string &name); /* get protocol version of client */ u16 getProtocolVersion(session_t peer_id); /* set client version */ void setClientVersion(session_t peer_id, u8 major, u8 minor, u8 patch, const std::string &full); /* event to update client state */ void event(session_t peer_id, ClientStateEvent event); /* Set environment. Do not call this function if environment is already set */ void setEnv(ServerEnvironment *env) { assert(m_env == NULL); // pre-condition m_env = env; } static std::string state2Name(ClientState state); protected: //TODO find way to avoid this functions void lock() { m_clients_mutex.lock(); } void unlock() { m_clients_mutex.unlock(); } RemoteClientMap& getClientList() { return m_clients; } private: /* update internal player list */ void UpdatePlayerList(); // Connection std::shared_ptr<con::Connection> m_con; std::mutex m_clients_mutex; // Connected clients (behind the con mutex) RemoteClientMap m_clients; std::vector<std::string> m_clients_names; //for announcing masterserver // Environment ServerEnvironment *m_env; float m_print_info_timer; static const char *statenames[]; };
pgimeno/minetest
src/clientiface.h
C++
mit
19,555
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes_bloated.h" class ClientEnvironment; class ClientSimpleObject { protected: public: bool m_to_be_removed = false; ClientSimpleObject() = default; virtual ~ClientSimpleObject() = default; virtual void step(float dtime) {} };
pgimeno/minetest
src/clientsimpleobject.h
C++
mit
1,052
/* Minetest Copyright (C) 2017 bendeutsch, Ben Deutsch <ben@bendeutsch.de> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once struct CloudParams { float density; video::SColor color_bright; video::SColor color_ambient; float thickness; float height; v2f speed; };
pgimeno/minetest
src/cloudparams.h
C++
mit
941
// Filled in by the build system #pragma once #define PROJECT_NAME "@PROJECT_NAME@" #define PROJECT_NAME_C "@PROJECT_NAME_CAPITALIZED@" #define VERSION_MAJOR @VERSION_MAJOR@ #define VERSION_MINOR @VERSION_MINOR@ #define VERSION_PATCH @VERSION_PATCH@ #define VERSION_EXTRA "@VERSION_EXTRA@" #define VERSION_STRING "@VERSION_STRING@" #define PRODUCT_VERSION_STRING "@VERSION_MAJOR@.@VERSION_MINOR@" #define STATIC_SHAREDIR "@SHAREDIR@" #define STATIC_LOCALEDIR "@LOCALEDIR@" #define BUILD_TYPE "@CMAKE_BUILD_TYPE@" #define ICON_DIR "@ICONDIR@" #cmakedefine01 RUN_IN_PLACE #cmakedefine01 USE_GETTEXT #cmakedefine01 USE_CURL #cmakedefine01 USE_SOUND #cmakedefine01 USE_FREETYPE #cmakedefine01 USE_CURSES #cmakedefine01 USE_LEVELDB #cmakedefine01 USE_LUAJIT #cmakedefine01 USE_POSTGRESQL #cmakedefine01 USE_SPATIAL #cmakedefine01 USE_SYSTEM_GMP #cmakedefine01 USE_REDIS #cmakedefine01 HAVE_ENDIAN_H #cmakedefine01 CURSES_HAVE_CURSES_H #cmakedefine01 CURSES_HAVE_NCURSES_H #cmakedefine01 CURSES_HAVE_NCURSES_NCURSES_H #cmakedefine01 CURSES_HAVE_NCURSES_CURSES_H #cmakedefine01 CURSES_HAVE_NCURSESW_NCURSES_H #cmakedefine01 CURSES_HAVE_NCURSESW_CURSES_H
pgimeno/minetest
src/cmake_config.h.in
in
mit
1,149
// Filled in by the build system // Separated from cmake_config.h to avoid excessive rebuilds on every commit #pragma once #define VERSION_GITHASH "@VERSION_GITHASH@"
pgimeno/minetest
src/cmake_config_githash.h.in
in
mit
169
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "collision.h" #include <cmath> #include "mapblock.h" #include "map.h" #include "nodedef.h" #include "gamedef.h" #ifndef SERVER #include "client/clientenvironment.h" #endif #include "serverenvironment.h" #include "serverobject.h" #include "util/timetaker.h" #include "profiler.h" // float error is 10 - 9.96875 = 0.03125 //#define COLL_ZERO 0.032 // broken unit tests #define COLL_ZERO 0 struct NearbyCollisionInfo { NearbyCollisionInfo(bool is_ul, bool is_obj, int bouncy, const v3s16 &pos, const aabb3f &box) : is_unloaded(is_ul), is_object(is_obj), bouncy(bouncy), position(pos), box(box) {} bool is_unloaded; bool is_step_up = false; bool is_object; int bouncy; v3s16 position; aabb3f box; }; // Helper function: // Checks for collision of a moving aabbox with a static aabbox // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision // The time after which the collision occurs is stored in dtime. int axisAlignedCollision( const aabb3f &staticbox, const aabb3f &movingbox, const v3f &speed, f32 d, f32 *dtime) { //TimeTaker tt("axisAlignedCollision"); f32 xsize = (staticbox.MaxEdge.X - staticbox.MinEdge.X) - COLL_ZERO; // reduce box size for solve collision stuck (flying sand) f32 ysize = (staticbox.MaxEdge.Y - staticbox.MinEdge.Y); // - COLL_ZERO; // Y - no sense for falling, but maybe try later f32 zsize = (staticbox.MaxEdge.Z - staticbox.MinEdge.Z) - COLL_ZERO; aabb3f relbox( movingbox.MinEdge.X - staticbox.MinEdge.X, movingbox.MinEdge.Y - staticbox.MinEdge.Y, movingbox.MinEdge.Z - staticbox.MinEdge.Z, movingbox.MaxEdge.X - staticbox.MinEdge.X, movingbox.MaxEdge.Y - staticbox.MinEdge.Y, movingbox.MaxEdge.Z - staticbox.MinEdge.Z ); if(speed.X > 0) // Check for collision with X- plane { if (relbox.MaxEdge.X <= d) { *dtime = -relbox.MaxEdge.X / speed.X; if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) && (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) && (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) && (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO)) return 0; } else if(relbox.MinEdge.X > xsize) { return -1; } } else if(speed.X < 0) // Check for collision with X+ plane { if (relbox.MinEdge.X >= xsize - d) { *dtime = (xsize - relbox.MinEdge.X) / speed.X; if ((relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) && (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO) && (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) && (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO)) return 0; } else if(relbox.MaxEdge.X < 0) { return -1; } } // NO else if here if(speed.Y > 0) // Check for collision with Y- plane { if (relbox.MaxEdge.Y <= d) { *dtime = -relbox.MaxEdge.Y / speed.Y; if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) && (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) && (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) && (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO)) return 1; } else if(relbox.MinEdge.Y > ysize) { return -1; } } else if(speed.Y < 0) // Check for collision with Y+ plane { if (relbox.MinEdge.Y >= ysize - d) { *dtime = (ysize - relbox.MinEdge.Y) / speed.Y; if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) && (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) && (relbox.MinEdge.Z + speed.Z * (*dtime) < zsize) && (relbox.MaxEdge.Z + speed.Z * (*dtime) > COLL_ZERO)) return 1; } else if(relbox.MaxEdge.Y < 0) { return -1; } } // NO else if here if(speed.Z > 0) // Check for collision with Z- plane { if (relbox.MaxEdge.Z <= d) { *dtime = -relbox.MaxEdge.Z / speed.Z; if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) && (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) && (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) && (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO)) return 2; } //else if(relbox.MinEdge.Z > zsize) //{ // return -1; //} } else if(speed.Z < 0) // Check for collision with Z+ plane { if (relbox.MinEdge.Z >= zsize - d) { *dtime = (zsize - relbox.MinEdge.Z) / speed.Z; if ((relbox.MinEdge.X + speed.X * (*dtime) < xsize) && (relbox.MaxEdge.X + speed.X * (*dtime) > COLL_ZERO) && (relbox.MinEdge.Y + speed.Y * (*dtime) < ysize) && (relbox.MaxEdge.Y + speed.Y * (*dtime) > COLL_ZERO)) return 2; } //else if(relbox.MaxEdge.Z < 0) //{ // return -1; //} } return -1; } // Helper function: // Checks if moving the movingbox up by the given distance would hit a ceiling. bool wouldCollideWithCeiling( const std::vector<NearbyCollisionInfo> &cinfo, const aabb3f &movingbox, f32 y_increase, f32 d) { //TimeTaker tt("wouldCollideWithCeiling"); assert(y_increase >= 0); // pre-condition for (const auto &it : cinfo) { const aabb3f &staticbox = it.box; if ((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) && (movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) && (movingbox.MinEdge.X < staticbox.MaxEdge.X) && (movingbox.MaxEdge.X > staticbox.MinEdge.X) && (movingbox.MinEdge.Z < staticbox.MaxEdge.Z) && (movingbox.MaxEdge.Z > staticbox.MinEdge.Z)) return true; } return false; } static inline void getNeighborConnectingFace(const v3s16 &p, const NodeDefManager *nodedef, Map *map, MapNode n, int v, int *neighbors) { MapNode n2 = map->getNodeNoEx(p); if (nodedef->nodeboxConnects(n, n2, v)) *neighbors |= v; } collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef, f32 pos_max_d, const aabb3f &box_0, f32 stepheight, f32 dtime, v3f *pos_f, v3f *speed_f, v3f accel_f, ActiveObject *self, bool collideWithObjects) { static bool time_notification_done = false; Map *map = &env->getMap(); //TimeTaker tt("collisionMoveSimple"); ScopeProfiler sp(g_profiler, "collisionMoveSimple avg", SPT_AVG); collisionMoveResult result; /* Calculate new velocity */ if (dtime > 0.5f) { if (!time_notification_done) { time_notification_done = true; infostream << "collisionMoveSimple: maximum step interval exceeded," " lost movement details!"<<std::endl; } dtime = 0.5f; } else { time_notification_done = false; } *speed_f += accel_f * dtime; // If there is no speed, there are no collisions if (speed_f->getLength() == 0) return result; // Limit speed for avoiding hangs speed_f->Y = rangelim(speed_f->Y, -5000, 5000); speed_f->X = rangelim(speed_f->X, -5000, 5000); speed_f->Z = rangelim(speed_f->Z, -5000, 5000); /* Collect node boxes in movement range */ std::vector<NearbyCollisionInfo> cinfo; { //TimeTaker tt2("collisionMoveSimple collect boxes"); ScopeProfiler sp2(g_profiler, "collisionMoveSimple collect boxes avg", SPT_AVG); v3f newpos_f = *pos_f + *speed_f * dtime; v3f minpos_f( MYMIN(pos_f->X, newpos_f.X), MYMIN(pos_f->Y, newpos_f.Y) + 0.01f * BS, // bias rounding, player often at +/-n.5 MYMIN(pos_f->Z, newpos_f.Z) ); v3f maxpos_f( MYMAX(pos_f->X, newpos_f.X), MYMAX(pos_f->Y, newpos_f.Y), MYMAX(pos_f->Z, newpos_f.Z) ); v3s16 min = floatToInt(minpos_f + box_0.MinEdge, BS) - v3s16(1, 1, 1); v3s16 max = floatToInt(maxpos_f + box_0.MaxEdge, BS) + v3s16(1, 1, 1); bool any_position_valid = false; v3s16 p; for (p.X = min.X; p.X <= max.X; p.X++) for (p.Y = min.Y; p.Y <= max.Y; p.Y++) for (p.Z = min.Z; p.Z <= max.Z; p.Z++) { bool is_position_valid; MapNode n = map->getNodeNoEx(p, &is_position_valid); if (is_position_valid && n.getContent() != CONTENT_IGNORE) { // Object collides into walkable nodes any_position_valid = true; const NodeDefManager *nodedef = gamedef->getNodeDefManager(); const ContentFeatures &f = nodedef->get(n); if (!f.walkable) continue; int n_bouncy_value = itemgroup_get(f.groups, "bouncy"); int neighbors = 0; if (f.drawtype == NDT_NODEBOX && f.node_box.type == NODEBOX_CONNECTED) { v3s16 p2 = p; p2.Y++; getNeighborConnectingFace(p2, nodedef, map, n, 1, &neighbors); p2 = p; p2.Y--; getNeighborConnectingFace(p2, nodedef, map, n, 2, &neighbors); p2 = p; p2.Z--; getNeighborConnectingFace(p2, nodedef, map, n, 4, &neighbors); p2 = p; p2.X--; getNeighborConnectingFace(p2, nodedef, map, n, 8, &neighbors); p2 = p; p2.Z++; getNeighborConnectingFace(p2, nodedef, map, n, 16, &neighbors); p2 = p; p2.X++; getNeighborConnectingFace(p2, nodedef, map, n, 32, &neighbors); } std::vector<aabb3f> nodeboxes; n.getCollisionBoxes(gamedef->ndef(), &nodeboxes, neighbors); // Calculate float position only once v3f posf = intToFloat(p, BS); for (auto box : nodeboxes) { box.MinEdge += posf; box.MaxEdge += posf; cinfo.emplace_back(false, false, n_bouncy_value, p, box); } } else { // Collide with unloaded nodes (position invalid) and loaded // CONTENT_IGNORE nodes (position valid) aabb3f box = getNodeBox(p, BS); cinfo.emplace_back(true, false, 0, p, box); } } // Do not move if world has not loaded yet, since custom node boxes // are not available for collision detection. // This also intentionally occurs in the case of the object being positioned // solely on loaded CONTENT_IGNORE nodes, no matter where they come from. if (!any_position_valid) { *speed_f = v3f(0, 0, 0); return result; } } // tt2 if(collideWithObjects) { ScopeProfiler sp2(g_profiler, "collisionMoveSimple objects avg", SPT_AVG); //TimeTaker tt3("collisionMoveSimple collect object boxes"); /* add object boxes to cinfo */ std::vector<ActiveObject*> objects; #ifndef SERVER ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env); if (c_env != 0) { // Calculate distance by speed, add own extent and 1.5m of tolerance f32 distance = speed_f->getLength() * dtime + box_0.getExtent().getLength() + 1.5f * BS; std::vector<DistanceSortedActiveObject> clientobjects; c_env->getActiveObjects(*pos_f, distance, clientobjects); for (auto &clientobject : clientobjects) { // Do collide with everything but itself and the parent CAO if (!self || (self != clientobject.obj && self != clientobject.obj->getParent())) { objects.push_back((ActiveObject*) clientobject.obj); } } } else #endif { ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env); if (s_env != NULL) { // Calculate distance by speed, add own extent and 1.5m of tolerance f32 distance = speed_f->getLength() * dtime + box_0.getExtent().getLength() + 1.5f * BS; std::vector<u16> s_objects; s_env->getObjectsInsideRadius(s_objects, *pos_f, distance); for (u16 obj_id : s_objects) { ServerActiveObject *current = s_env->getActiveObject(obj_id); if (!self || (self != current && self != current->getParent())) { objects.push_back((ActiveObject*)current); } } } } for (std::vector<ActiveObject*>::const_iterator iter = objects.begin(); iter != objects.end(); ++iter) { ActiveObject *object = *iter; if (object) { aabb3f object_collisionbox; if (object->getCollisionBox(&object_collisionbox) && object->collideWithObjects()) { cinfo.emplace_back(false, true, 0, v3s16(), object_collisionbox); } } } } //tt3 /* Collision detection */ /* Collision uncertainty radius Make it a bit larger than the maximum distance of movement */ f32 d = pos_max_d * 1.1f; // A fairly large value in here makes moving smoother //f32 d = 0.15*BS; // This should always apply, otherwise there are glitches assert(d > pos_max_d); // invariant int loopcount = 0; while(dtime > BS * 1e-10f) { //TimeTaker tt3("collisionMoveSimple dtime loop"); ScopeProfiler sp2(g_profiler, "collisionMoveSimple dtime loop avg", SPT_AVG); // Avoid infinite loop loopcount++; if (loopcount >= 100) { warningstream << "collisionMoveSimple: Loop count exceeded, aborting to avoid infiniite loop" << std::endl; break; } aabb3f movingbox = box_0; movingbox.MinEdge += *pos_f; movingbox.MaxEdge += *pos_f; int nearest_collided = -1; f32 nearest_dtime = dtime; int nearest_boxindex = -1; /* Go through every nodebox, find nearest collision */ for (u32 boxindex = 0; boxindex < cinfo.size(); boxindex++) { const NearbyCollisionInfo &box_info = cinfo[boxindex]; // Ignore if already stepped up this nodebox. if (box_info.is_step_up) continue; // Find nearest collision of the two boxes (raytracing-like) f32 dtime_tmp; int collided = axisAlignedCollision(box_info.box, movingbox, *speed_f, d, &dtime_tmp); if (collided == -1 || dtime_tmp >= nearest_dtime) continue; nearest_dtime = dtime_tmp; nearest_collided = collided; nearest_boxindex = boxindex; } if (nearest_collided == -1) { // No collision with any collision box. *pos_f += *speed_f * dtime; dtime = 0; // Set to 0 to avoid "infinite" loop due to small FP numbers } else { // Otherwise, a collision occurred. NearbyCollisionInfo &nearest_info = cinfo[nearest_boxindex]; const aabb3f& cbox = nearest_info.box; // Check for stairs. bool step_up = (nearest_collided != 1) && // must not be Y direction (movingbox.MinEdge.Y < cbox.MaxEdge.Y) && (movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) && (!wouldCollideWithCeiling(cinfo, movingbox, cbox.MaxEdge.Y - movingbox.MinEdge.Y, d)); // Get bounce multiplier float bounce = -(float)nearest_info.bouncy / 100.0f; // Move to the point of collision and reduce dtime by nearest_dtime if (nearest_dtime < 0) { // Handle negative nearest_dtime (can be caused by the d allowance) if (!step_up) { if (nearest_collided == 0) pos_f->X += speed_f->X * nearest_dtime; if (nearest_collided == 1) pos_f->Y += speed_f->Y * nearest_dtime; if (nearest_collided == 2) pos_f->Z += speed_f->Z * nearest_dtime; } } else { *pos_f += *speed_f * nearest_dtime; dtime -= nearest_dtime; } bool is_collision = true; if (nearest_info.is_unloaded) is_collision = false; CollisionInfo info; if (nearest_info.is_object) info.type = COLLISION_OBJECT; else info.type = COLLISION_NODE; info.node_p = nearest_info.position; info.old_speed = *speed_f; info.plane = nearest_collided; // Set the speed component that caused the collision to zero if (step_up) { // Special case: Handle stairs nearest_info.is_step_up = true; is_collision = false; } else if (nearest_collided == 0) { // X if (fabs(speed_f->X) > BS * 3) speed_f->X *= bounce; else speed_f->X = 0; result.collides = true; } else if (nearest_collided == 1) { // Y if(fabs(speed_f->Y) > BS * 3) speed_f->Y *= bounce; else speed_f->Y = 0; result.collides = true; } else if (nearest_collided == 2) { // Z if (fabs(speed_f->Z) > BS * 3) speed_f->Z *= bounce; else speed_f->Z = 0; result.collides = true; } info.new_speed = *speed_f; if (info.new_speed.getDistanceFrom(info.old_speed) < 0.1f * BS) is_collision = false; if (is_collision) { result.collisions.push_back(info); } } } /* Final touches: Check if standing on ground, step up stairs. */ aabb3f box = box_0; box.MinEdge += *pos_f; box.MaxEdge += *pos_f; for (const auto &box_info : cinfo) { const aabb3f &cbox = box_info.box; /* See if the object is touching ground. Object touches ground if object's minimum Y is near node's maximum Y and object's X-Z-area overlaps with the node's X-Z-area. Use 0.15*BS so that it is easier to get on a node. */ if (cbox.MaxEdge.X - d > box.MinEdge.X && cbox.MinEdge.X + d < box.MaxEdge.X && cbox.MaxEdge.Z - d > box.MinEdge.Z && cbox.MinEdge.Z + d < box.MaxEdge.Z) { if (box_info.is_step_up) { pos_f->Y += cbox.MaxEdge.Y - box.MinEdge.Y; box = box_0; box.MinEdge += *pos_f; box.MaxEdge += *pos_f; } if (std::fabs(cbox.MaxEdge.Y - box.MinEdge.Y) < 0.15f * BS) { result.touching_ground = true; if (box_info.is_object) result.standing_on_object = true; } } } return result; }
pgimeno/minetest
src/collision.cpp
C++
mit
17,062
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes_bloated.h" #include <vector> class Map; class IGameDef; class Environment; class ActiveObject; enum CollisionType { COLLISION_NODE, COLLISION_OBJECT, }; struct CollisionInfo { CollisionInfo() = default; CollisionType type = COLLISION_NODE; v3s16 node_p = v3s16(-32768,-32768,-32768); // COLLISION_NODE v3f old_speed; v3f new_speed; int plane = -1; }; struct collisionMoveResult { collisionMoveResult() = default; bool touching_ground = false; bool collides = false; bool standing_on_object = false; std::vector<CollisionInfo> collisions; }; // Moves using a single iteration; speed should not exceed pos_max_d/dtime collisionMoveResult collisionMoveSimple(Environment *env,IGameDef *gamedef, f32 pos_max_d, const aabb3f &box_0, f32 stepheight, f32 dtime, v3f *pos_f, v3f *speed_f, v3f accel_f, ActiveObject *self=NULL, bool collideWithObjects=true); // Helper function: // Checks for collision of a moving aabbox with a static aabbox // Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision // dtime receives time until first collision, invalid if -1 is returned int axisAlignedCollision( const aabb3f &staticbox, const aabb3f &movingbox, const v3f &speed, f32 d, f32 *dtime); // Helper function: // Checks if moving the movingbox up by the given distance would hit a ceiling. bool wouldCollideWithCeiling( const std::vector<aabb3f> &staticboxes, const aabb3f &movingbox, f32 y_increase, f32 d);
pgimeno/minetest
src/collision.h
C++
mit
2,288
/* If CMake is used, includes the cmake-generated cmake_config.h. Otherwise use default values */ #pragma once #define STRINGIFY(x) #x #define STR(x) STRINGIFY(x) #if defined USE_CMAKE_CONFIG_H #include "cmake_config.h" #elif defined (__ANDROID__) || defined (ANDROID) #define PROJECT_NAME "minetest" #define PROJECT_NAME_C "Minetest" #define STATIC_SHAREDIR "" #include "android_version.h" #ifdef NDEBUG #define BUILD_TYPE "Release" #else #define BUILD_TYPE "Debug" #endif #else #ifdef NDEBUG #define BUILD_TYPE "Release" #else #define BUILD_TYPE "Debug" #endif #endif #define BUILD_INFO \ "BUILD_TYPE=" BUILD_TYPE "\n" \ "RUN_IN_PLACE=" STR(RUN_IN_PLACE) "\n" \ "USE_GETTEXT=" STR(USE_GETTEXT) "\n" \ "USE_SOUND=" STR(USE_SOUND) "\n" \ "USE_CURL=" STR(USE_CURL) "\n" \ "USE_FREETYPE=" STR(USE_FREETYPE) "\n" \ "USE_LUAJIT=" STR(USE_LUAJIT) "\n" \ "STATIC_SHAREDIR=" STR(STATIC_SHAREDIR);
pgimeno/minetest
src/config.h
C++
mit
953
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once /* All kinds of constants. Cross-platform compatibility crap should go in porting.h. Some things here are legacy crap. */ /* Connection */ #define PEER_ID_INEXISTENT 0 #define PEER_ID_SERVER 1 // Define for simulating the quirks of sending through internet. // Causes the socket class to deliberately drop random packets. // This disables unit testing of socket and connection. #define INTERNET_SIMULATOR 0 #define INTERNET_SIMULATOR_PACKET_LOSS 10 // 10 = easy, 4 = hard #define CONNECTION_TIMEOUT 30 #define RESEND_TIMEOUT_MIN 0.1 #define RESEND_TIMEOUT_MAX 3.0 // resend_timeout = avg_rtt * this #define RESEND_TIMEOUT_FACTOR 4 /* Server */ // This many blocks are sent when player is building #define LIMITED_MAX_SIMULTANEOUS_BLOCK_SENDS 0 // Override for the previous one when distance of block is very low #define BLOCK_SEND_DISABLE_LIMITS_MAX_D 1 /* Map-related things */ // The absolute working limit is (2^15 - viewing_range). // I really don't want to make every algorithm to check if it's going near // the limit or not, so this is lower. // This is the maximum value the setting map_generation_limit can be #define MAX_MAP_GENERATION_LIMIT (31000) // Size of node in floating-point units // The original idea behind this is to disallow plain casts between // floating-point and integer positions, which potentially give wrong // results. (negative coordinates, values between nodes, ...) // Use floatToInt(p, BS) and intToFloat(p, BS). #define BS 10.0f // Dimension of a MapBlock #define MAP_BLOCKSIZE 16 // This makes mesh updates too slow, as many meshes are updated during // the main loop (related to TempMods and day/night) //#define MAP_BLOCKSIZE 32 // Player step height in nodes #define PLAYER_DEFAULT_STEPHEIGHT 0.6f /* Old stuff that shouldn't be hardcoded */ // Size of player's main inventory #define PLAYER_INVENTORY_SIZE (8 * 4) // Default maximum hit points of a player #define PLAYER_MAX_HP_DEFAULT 20 // Default maximal breath of a player #define PLAYER_MAX_BREATH_DEFAULT 11 // Number of different files to try to save a player to if the first fails // (because of a case-insensitive filesystem) // TODO: Use case-insensitive player names instead of this hack. #define PLAYER_FILE_ALTERNATE_TRIES 1000 // For screenshots a serial number is appended to the filename + datetimestamp // if filename + datetimestamp is not unique. // This is the maximum number of attempts to try and add a serial to the end of // the file attempting to ensure a unique filename #define SCREENSHOT_MAX_SERIAL_TRIES 1000 /* GUI related things */ // TODO: implement dpi-based scaling for windows and remove this hack #if defined(_WIN32) #define TTF_DEFAULT_FONT_SIZE (18) #else #define TTF_DEFAULT_FONT_SIZE (16) #endif #define DEFAULT_FONT_SIZE (10)
pgimeno/minetest
src/constants.h
C++
mit
3,605
set(content_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/content.cpp ${CMAKE_CURRENT_SOURCE_DIR}/packages.cpp ${CMAKE_CURRENT_SOURCE_DIR}/mods.cpp ${CMAKE_CURRENT_SOURCE_DIR}/subgames.cpp PARENT_SCOPE )
pgimeno/minetest
src/content/CMakeLists.txt
Text
mit
196
/* Minetest Copyright (C) 2018 rubenwardy <rw@rubenwardy.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <fstream> #include "content/content.h" #include "content/subgames.h" #include "content/mods.h" #include "filesys.h" #include "settings.h" enum ContentType { ECT_UNKNOWN, ECT_MOD, ECT_MODPACK, ECT_GAME, ECT_TXP }; ContentType getContentType(const ContentSpec &spec) { std::ifstream modpack_is((spec.path + DIR_DELIM + "modpack.txt").c_str()); if (modpack_is.good()) { modpack_is.close(); return ECT_MODPACK; } std::ifstream modpack2_is((spec.path + DIR_DELIM + "modpack.conf").c_str()); if (modpack2_is.good()) { modpack2_is.close(); return ECT_MODPACK; } std::ifstream init_is((spec.path + DIR_DELIM + "init.lua").c_str()); if (init_is.good()) { init_is.close(); return ECT_MOD; } std::ifstream game_is((spec.path + DIR_DELIM + "game.conf").c_str()); if (game_is.good()) { game_is.close(); return ECT_GAME; } std::ifstream txp_is((spec.path + DIR_DELIM + "texture_pack.conf").c_str()); if (txp_is.good()) { txp_is.close(); return ECT_TXP; } return ECT_UNKNOWN; } void parseContentInfo(ContentSpec &spec) { std::string conf_path; switch (getContentType(spec)) { case ECT_MOD: spec.type = "mod"; conf_path = spec.path + DIR_DELIM + "mod.conf"; break; case ECT_MODPACK: spec.type = "modpack"; conf_path = spec.path + DIR_DELIM + "modpack.conf"; break; case ECT_GAME: spec.type = "game"; conf_path = spec.path + DIR_DELIM + "game.conf"; break; case ECT_TXP: spec.type = "txp"; conf_path = spec.path + DIR_DELIM + "texture_pack.conf"; break; default: spec.type = "unknown"; break; } Settings conf; if (!conf_path.empty() && conf.readConfigFile(conf_path.c_str())) { if (conf.exists("name")) spec.name = conf.get("name"); if (conf.exists("description")) spec.desc = conf.get("description"); if (conf.exists("author")) spec.author = conf.get("author"); if (conf.exists("release")) spec.release = conf.getS32("release"); } if (spec.desc.empty()) { std::ifstream is((spec.path + DIR_DELIM + "description.txt").c_str()); spec.desc = std::string((std::istreambuf_iterator<char>(is)), std::istreambuf_iterator<char>()); } }
pgimeno/minetest
src/content/content.cpp
C++
mit
2,915
/* Minetest Copyright (C) 2018 rubenwardy <rw@rubenwardy.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "config.h" #include "convert_json.h" #include "irrlichttypes.h" struct ContentSpec { std::string type; std::string author; u32 release = 0; std::string name; std::string desc; std::string path; }; void parseContentInfo(ContentSpec &spec);
pgimeno/minetest
src/content/content.h
C++
mit
1,039
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <cctype> #include <fstream> #include <json/json.h> #include <algorithm> #include "content/mods.h" #include "filesys.h" #include "log.h" #include "content/subgames.h" #include "settings.h" #include "porting.h" #include "convert_json.h" bool parseDependsString(std::string &dep, std::unordered_set<char> &symbols) { dep = trim(dep); symbols.clear(); size_t pos = dep.size(); while (pos > 0 && !string_allowed(dep.substr(pos - 1, 1), MODNAME_ALLOWED_CHARS)) { // last character is a symbol, not part of the modname symbols.insert(dep[pos - 1]); --pos; } dep = trim(dep.substr(0, pos)); return !dep.empty(); } void parseModContents(ModSpec &spec) { // NOTE: this function works in mutual recursion with getModsInPath Settings info; info.readConfigFile((spec.path + DIR_DELIM + "mod.conf").c_str()); if (info.exists("name")) spec.name = info.get("name"); if (info.exists("author")) spec.author = info.get("author"); if (info.exists("release")) spec.release = info.getS32("release"); spec.depends.clear(); spec.optdepends.clear(); spec.is_modpack = false; spec.modpack_content.clear(); // Handle modpacks (defined by containing modpack.txt) std::ifstream modpack_is((spec.path + DIR_DELIM + "modpack.txt").c_str()); std::ifstream modpack2_is((spec.path + DIR_DELIM + "modpack.conf").c_str()); if (modpack_is.good() || modpack2_is.good()) { if (modpack_is.good()) modpack_is.close(); if (modpack2_is.good()) modpack2_is.close(); spec.is_modpack = true; spec.modpack_content = getModsInPath(spec.path, true); } else { // Attempt to load dependencies from mod.conf bool mod_conf_has_depends = false; if (info.exists("depends")) { mod_conf_has_depends = true; std::string dep = info.get("depends"); // clang-format off dep.erase(std::remove_if(dep.begin(), dep.end(), static_cast<int (*)(int)>(&std::isspace)), dep.end()); // clang-format on for (const auto &dependency : str_split(dep, ',')) { spec.depends.insert(dependency); } } if (info.exists("optional_depends")) { mod_conf_has_depends = true; std::string dep = info.get("optional_depends"); // clang-format off dep.erase(std::remove_if(dep.begin(), dep.end(), static_cast<int (*)(int)>(&std::isspace)), dep.end()); // clang-format on for (const auto &dependency : str_split(dep, ',')) { spec.optdepends.insert(dependency); } } // Fallback to depends.txt if (!mod_conf_has_depends) { std::vector<std::string> dependencies; std::ifstream is((spec.path + DIR_DELIM + "depends.txt").c_str()); while (is.good()) { std::string dep; std::getline(is, dep); dependencies.push_back(dep); } for (auto &dependency : dependencies) { std::unordered_set<char> symbols; if (parseDependsString(dependency, symbols)) { if (symbols.count('?') != 0) { spec.optdepends.insert(dependency); } else { spec.depends.insert(dependency); } } } } if (info.exists("description")) { spec.desc = info.get("description"); } else { std::ifstream is((spec.path + DIR_DELIM + "description.txt") .c_str()); spec.desc = std::string((std::istreambuf_iterator<char>(is)), std::istreambuf_iterator<char>()); } } } std::map<std::string, ModSpec> getModsInPath( const std::string &path, bool part_of_modpack) { // NOTE: this function works in mutual recursion with parseModContents std::map<std::string, ModSpec> result; std::vector<fs::DirListNode> dirlist = fs::GetDirListing(path); std::string modpath; for (const fs::DirListNode &dln : dirlist) { if (!dln.dir) continue; const std::string &modname = dln.name; // Ignore all directories beginning with a ".", especially // VCS directories like ".git" or ".svn" if (modname[0] == '.') continue; modpath.clear(); modpath.append(path).append(DIR_DELIM).append(modname); ModSpec spec(modname, modpath, part_of_modpack); parseModContents(spec); result.insert(std::make_pair(modname, spec)); } return result; } std::vector<ModSpec> flattenMods(std::map<std::string, ModSpec> mods) { std::vector<ModSpec> result; for (const auto &it : mods) { const ModSpec &mod = it.second; if (mod.is_modpack) { std::vector<ModSpec> content = flattenMods(mod.modpack_content); result.reserve(result.size() + content.size()); result.insert(result.end(), content.begin(), content.end()); } else // not a modpack { result.push_back(mod); } } return result; } ModConfiguration::ModConfiguration(const std::string &worldpath) { } void ModConfiguration::printUnsatisfiedModsError() const { for (const ModSpec &mod : m_unsatisfied_mods) { errorstream << "mod \"" << mod.name << "\" has unsatisfied dependencies: "; for (const std::string &unsatisfied_depend : mod.unsatisfied_depends) errorstream << " \"" << unsatisfied_depend << "\""; errorstream << std::endl; } } void ModConfiguration::addModsInPath(const std::string &path) { addMods(flattenMods(getModsInPath(path))); } void ModConfiguration::addMods(const std::vector<ModSpec> &new_mods) { // Maintain a map of all existing m_unsatisfied_mods. // Keys are mod names and values are indices into m_unsatisfied_mods. std::map<std::string, u32> existing_mods; for (u32 i = 0; i < m_unsatisfied_mods.size(); ++i) { existing_mods[m_unsatisfied_mods[i].name] = i; } // Add new mods for (int want_from_modpack = 1; want_from_modpack >= 0; --want_from_modpack) { // First iteration: // Add all the mods that come from modpacks // Second iteration: // Add all the mods that didn't come from modpacks std::set<std::string> seen_this_iteration; for (const ModSpec &mod : new_mods) { if (mod.part_of_modpack != (bool)want_from_modpack) continue; if (existing_mods.count(mod.name) == 0) { // GOOD CASE: completely new mod. m_unsatisfied_mods.push_back(mod); existing_mods[mod.name] = m_unsatisfied_mods.size() - 1; } else if (seen_this_iteration.count(mod.name) == 0) { // BAD CASE: name conflict in different levels. u32 oldindex = existing_mods[mod.name]; const ModSpec &oldmod = m_unsatisfied_mods[oldindex]; warningstream << "Mod name conflict detected: \"" << mod.name << "\"" << std::endl << "Will not load: " << oldmod.path << std::endl << "Overridden by: " << mod.path << std::endl; m_unsatisfied_mods[oldindex] = mod; // If there was a "VERY BAD CASE" name conflict // in an earlier level, ignore it. m_name_conflicts.erase(mod.name); } else { // VERY BAD CASE: name conflict in the same level. u32 oldindex = existing_mods[mod.name]; const ModSpec &oldmod = m_unsatisfied_mods[oldindex]; warningstream << "Mod name conflict detected: \"" << mod.name << "\"" << std::endl << "Will not load: " << oldmod.path << std::endl << "Will not load: " << mod.path << std::endl; m_unsatisfied_mods[oldindex] = mod; m_name_conflicts.insert(mod.name); } seen_this_iteration.insert(mod.name); } } } void ModConfiguration::addModsFromConfig( const std::string &settings_path, const std::set<std::string> &mods) { Settings conf; std::set<std::string> load_mod_names; conf.readConfigFile(settings_path.c_str()); std::vector<std::string> names = conf.getNames(); for (const std::string &name : names) { if (name.compare(0, 9, "load_mod_") == 0 && conf.get(name) != "false" && conf.get(name) != "nil") load_mod_names.insert(name.substr(9)); } std::vector<ModSpec> addon_mods; for (const std::string &i : mods) { std::vector<ModSpec> addon_mods_in_path = flattenMods(getModsInPath(i)); for (std::vector<ModSpec>::const_iterator it = addon_mods_in_path.begin(); it != addon_mods_in_path.end(); ++it) { const ModSpec &mod = *it; if (load_mod_names.count(mod.name) != 0) addon_mods.push_back(mod); else conf.setBool("load_mod_" + mod.name, false); } } conf.updateConfigFile(settings_path.c_str()); addMods(addon_mods); checkConflictsAndDeps(); // complain about mods declared to be loaded, but not found for (const ModSpec &addon_mod : addon_mods) load_mod_names.erase(addon_mod.name); std::vector<ModSpec> unsatisfiedMods = getUnsatisfiedMods(); for (const ModSpec &unsatisfiedMod : unsatisfiedMods) load_mod_names.erase(unsatisfiedMod.name); if (!load_mod_names.empty()) { errorstream << "The following mods could not be found:"; for (const std::string &mod : load_mod_names) errorstream << " \"" << mod << "\""; errorstream << std::endl; } } void ModConfiguration::checkConflictsAndDeps() { // report on name conflicts if (!m_name_conflicts.empty()) { std::string s = "Unresolved name conflicts for mods "; for (std::unordered_set<std::string>::const_iterator it = m_name_conflicts.begin(); it != m_name_conflicts.end(); ++it) { if (it != m_name_conflicts.begin()) s += ", "; s += std::string("\"") + (*it) + "\""; } s += "."; throw ModError(s); } // get the mods in order resolveDependencies(); } void ModConfiguration::resolveDependencies() { // Step 1: Compile a list of the mod names we're working with std::set<std::string> modnames; for (const ModSpec &mod : m_unsatisfied_mods) { modnames.insert(mod.name); } // Step 2: get dependencies (including optional dependencies) // of each mod, split mods into satisfied and unsatisfied std::list<ModSpec> satisfied; std::list<ModSpec> unsatisfied; for (ModSpec mod : m_unsatisfied_mods) { mod.unsatisfied_depends = mod.depends; // check which optional dependencies actually exist for (const std::string &optdep : mod.optdepends) { if (modnames.count(optdep) != 0) mod.unsatisfied_depends.insert(optdep); } // if a mod has no depends it is initially satisfied if (mod.unsatisfied_depends.empty()) satisfied.push_back(mod); else unsatisfied.push_back(mod); } // Step 3: mods without unmet dependencies can be appended to // the sorted list. while (!satisfied.empty()) { ModSpec mod = satisfied.back(); m_sorted_mods.push_back(mod); satisfied.pop_back(); for (auto it = unsatisfied.begin(); it != unsatisfied.end();) { ModSpec &mod2 = *it; mod2.unsatisfied_depends.erase(mod.name); if (mod2.unsatisfied_depends.empty()) { satisfied.push_back(mod2); it = unsatisfied.erase(it); } else { ++it; } } } // Step 4: write back list of unsatisfied mods m_unsatisfied_mods.assign(unsatisfied.begin(), unsatisfied.end()); } #ifndef SERVER ClientModConfiguration::ClientModConfiguration(const std::string &path) : ModConfiguration(path) { std::set<std::string> paths; std::string path_user = porting::path_user + DIR_DELIM + "clientmods"; paths.insert(path); paths.insert(path_user); std::string settings_path = path_user + DIR_DELIM + "mods.conf"; addModsFromConfig(settings_path, paths); } #endif ModMetadata::ModMetadata(const std::string &mod_name) : m_mod_name(mod_name) { } void ModMetadata::clear() { Metadata::clear(); m_modified = true; } bool ModMetadata::save(const std::string &root_path) { Json::Value json; for (StringMap::const_iterator it = m_stringvars.begin(); it != m_stringvars.end(); ++it) { json[it->first] = it->second; } if (!fs::PathExists(root_path)) { if (!fs::CreateAllDirs(root_path)) { errorstream << "ModMetadata[" << m_mod_name << "]: Unable to save. '" << root_path << "' tree cannot be created." << std::endl; return false; } } else if (!fs::IsDir(root_path)) { errorstream << "ModMetadata[" << m_mod_name << "]: Unable to save. '" << root_path << "' is not a directory." << std::endl; return false; } bool w_ok = fs::safeWriteToFile( root_path + DIR_DELIM + m_mod_name, fastWriteJson(json)); if (w_ok) { m_modified = false; } else { errorstream << "ModMetadata[" << m_mod_name << "]: failed write file." << std::endl; } return w_ok; } bool ModMetadata::load(const std::string &root_path) { m_stringvars.clear(); std::ifstream is((root_path + DIR_DELIM + m_mod_name).c_str(), std::ios_base::binary); if (!is.good()) { return false; } Json::Value root; Json::CharReaderBuilder builder; builder.settings_["collectComments"] = false; std::string errs; if (!Json::parseFromStream(builder, is, &root, &errs)) { errorstream << "ModMetadata[" << m_mod_name << "]: failed read data " "(Json decoding failure). Message: " << errs << std::endl; return false; } const Json::Value::Members attr_list = root.getMemberNames(); for (const auto &it : attr_list) { Json::Value attr_value = root[it]; m_stringvars[it] = attr_value.asString(); } return true; } bool ModMetadata::setString(const std::string &name, const std::string &var) { m_modified = Metadata::setString(name, var); return m_modified; }
pgimeno/minetest
src/content/mods.cpp
C++
mit
13,720
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" #include <list> #include <set> #include <vector> #include <string> #include <map> #include <json/json.h> #include <unordered_set> #include "util/basic_macros.h" #include "config.h" #include "metadata.h" #define MODNAME_ALLOWED_CHARS "abcdefghijklmnopqrstuvwxyz0123456789_" struct ModSpec { std::string name; std::string author; std::string path; std::string desc; int release = 0; // if normal mod: std::unordered_set<std::string> depends; std::unordered_set<std::string> optdepends; std::unordered_set<std::string> unsatisfied_depends; bool part_of_modpack = false; bool is_modpack = false; // if modpack: std::map<std::string, ModSpec> modpack_content; ModSpec(const std::string &name = "", const std::string &path = "") : name(name), path(path) { } ModSpec(const std::string &name, const std::string &path, bool part_of_modpack) : name(name), path(path), part_of_modpack(part_of_modpack) { } }; // Retrieves depends, optdepends, is_modpack and modpack_content void parseModContents(ModSpec &mod); std::map<std::string, ModSpec> getModsInPath( const std::string &path, bool part_of_modpack = false); // replaces modpack Modspecs with their content std::vector<ModSpec> flattenMods(std::map<std::string, ModSpec> mods); // a ModConfiguration is a subset of installed mods, expected to have // all dependencies fullfilled, so it can be used as a list of mods to // load when the game starts. class ModConfiguration { public: // checks if all dependencies are fullfilled. bool isConsistent() const { return m_unsatisfied_mods.empty(); } const std::vector<ModSpec> &getMods() const { return m_sorted_mods; } const std::vector<ModSpec> &getUnsatisfiedMods() const { return m_unsatisfied_mods; } void printUnsatisfiedModsError() const; protected: ModConfiguration(const std::string &worldpath); // adds all mods in the given path. used for games, modpacks // and world-specific mods (worldmods-folders) void addModsInPath(const std::string &path); // adds all mods in the set. void addMods(const std::vector<ModSpec> &new_mods); void addModsFromConfig(const std::string &settings_path, const std::set<std::string> &mods); void checkConflictsAndDeps(); protected: // list of mods sorted such that they can be loaded in the // given order with all dependencies being fullfilled. I.e., // every mod in this list has only dependencies on mods which // appear earlier in the vector. std::vector<ModSpec> m_sorted_mods; private: // move mods from m_unsatisfied_mods to m_sorted_mods // in an order that satisfies dependencies void resolveDependencies(); // mods with unmet dependencies. Before dependencies are resolved, // this is where all mods are stored. Afterwards this contains // only the ones with really unsatisfied dependencies. std::vector<ModSpec> m_unsatisfied_mods; // set of mod names for which an unresolved name conflict // exists. A name conflict happens when two or more mods // at the same level have the same name but different paths. // Levels (mods in higher levels override mods in lower levels): // 1. game mod in modpack; 2. game mod; // 3. world mod in modpack; 4. world mod; // 5. addon mod in modpack; 6. addon mod. std::unordered_set<std::string> m_name_conflicts; // Deleted default constructor ModConfiguration() = default; }; #ifndef SERVER class ClientModConfiguration : public ModConfiguration { public: ClientModConfiguration(const std::string &path); }; #endif class ModMetadata : public Metadata { public: ModMetadata() = delete; ModMetadata(const std::string &mod_name); ~ModMetadata() = default; virtual void clear(); bool save(const std::string &root_path); bool load(const std::string &root_path); bool isModified() const { return m_modified; } const std::string &getModName() const { return m_mod_name; } virtual bool setString(const std::string &name, const std::string &var); private: std::string m_mod_name; bool m_modified = false; };
pgimeno/minetest
src/content/mods.h
C++
mit
4,807
/* Minetest Copyright (C) 2018 rubenwardy <rw@rubenwardy.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "content/packages.h" #include "log.h" #include "filesys.h" #include "porting.h" #include "settings.h" #include "content/mods.h" #include "content/subgames.h" std::string Package::getDownloadURL(const std::string &baseURL) const { return baseURL + "/packages/" + author + "/" + name + "/releases/" + std::to_string(release) + "/download/"; } #if USE_CURL std::vector<Package> getPackagesFromURL(const std::string &url) { std::vector<std::string> extra_headers; extra_headers.emplace_back("Accept: application/json"); Json::Value json = fetchJsonValue(url, &extra_headers); if (!json.isArray()) { errorstream << "Invalid JSON download " << std::endl; return std::vector<Package>(); } std::vector<Package> packages; // Note: `unsigned int` is required to index JSON for (unsigned int i = 0; i < json.size(); ++i) { Package package; package.author = json[i]["author"].asString(); package.name = json[i]["name"].asString(); package.title = json[i]["title"].asString(); package.type = json[i]["type"].asString(); package.shortDesc = json[i]["shortDesc"].asString(); package.release = json[i]["release"].asInt(); if (json[i].isMember("thumbnail")) package.thumbnail = json[i]["thumbnail"].asString(); if (package.valid()) packages.push_back(package); else errorstream << "Invalid package at " << i << std::endl; } return packages; } #endif
pgimeno/minetest
src/content/packages.cpp
C++
mit
2,172
/* Minetest Copyright (C) 2018 rubenwardy <rw@rubenwardy.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "config.h" #include "convert_json.h" #include "irrlichttypes.h" struct Package { std::string author; std::string name; // Technical name std::string title; std::string type; // One of "mod", "game", or "txp" std::string shortDesc; u32 release; std::string thumbnail; bool valid() const { return !(author.empty() || name.empty() || title.empty() || type.empty() || release <= 0); } std::string getDownloadURL(const std::string &baseURL) const; }; #if USE_CURL std::vector<Package> getPackagesFromURL(const std::string &url); #else inline std::vector<Package> getPackagesFromURL(const std::string &url) { return std::vector<Package>(); } #endif
pgimeno/minetest
src/content/packages.h
C++
mit
1,458
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "content/subgames.h" #include "porting.h" #include "filesys.h" #include "settings.h" #include "log.h" #include "util/strfnd.h" #include "defaultsettings.h" // for override_default_settings #include "mapgen/mapgen.h" // for MapgenParams #include "util/string.h" #ifndef SERVER #include "client/tile.h" // getImagePath #endif bool getGameMinetestConfig(const std::string &game_path, Settings &conf) { std::string conf_path = game_path + DIR_DELIM + "minetest.conf"; return conf.readConfigFile(conf_path.c_str()); } struct GameFindPath { std::string path; bool user_specific; GameFindPath(const std::string &path, bool user_specific) : path(path), user_specific(user_specific) { } }; std::string getSubgamePathEnv() { char *subgame_path = getenv("MINETEST_SUBGAME_PATH"); return subgame_path ? std::string(subgame_path) : ""; } SubgameSpec findSubgame(const std::string &id) { if (id.empty()) return SubgameSpec(); std::string share = porting::path_share; std::string user = porting::path_user; // Get games install locations Strfnd search_paths(getSubgamePathEnv()); // Get all possible paths fo game std::vector<GameFindPath> find_paths; while (!search_paths.at_end()) { std::string path = search_paths.next(PATH_DELIM); path.append(DIR_DELIM).append(id); find_paths.emplace_back(path, false); path.append("_game"); find_paths.emplace_back(path, false); } std::string game_base = DIR_DELIM; game_base = game_base.append("games").append(DIR_DELIM).append(id); std::string game_suffixed = game_base + "_game"; find_paths.emplace_back(user + game_suffixed, true); find_paths.emplace_back(user + game_base, true); find_paths.emplace_back(share + game_suffixed, false); find_paths.emplace_back(share + game_base, false); // Find game directory std::string game_path; bool user_game = true; // Game is in user's directory for (const GameFindPath &find_path : find_paths) { const std::string &try_path = find_path.path; if (fs::PathExists(try_path)) { game_path = try_path; user_game = find_path.user_specific; break; } } if (game_path.empty()) return SubgameSpec(); std::string gamemod_path = game_path + DIR_DELIM + "mods"; // Find mod directories std::set<std::string> mods_paths; if (!user_game) mods_paths.insert(share + DIR_DELIM + "mods"); if (user != share || user_game) mods_paths.insert(user + DIR_DELIM + "mods"); // Get meta std::string conf_path = game_path + DIR_DELIM + "game.conf"; Settings conf; conf.readConfigFile(conf_path.c_str()); std::string game_name; if (conf.exists("name")) game_name = conf.get("name"); else game_name = id; std::string game_author; if (conf.exists("author")) game_author = conf.get("author"); int game_release = 0; if (conf.exists("release")) game_release = conf.getS32("release"); std::string menuicon_path; #ifndef SERVER menuicon_path = getImagePath( game_path + DIR_DELIM + "menu" + DIR_DELIM + "icon.png"); #endif return SubgameSpec(id, game_path, gamemod_path, mods_paths, game_name, menuicon_path, game_author, game_release); } SubgameSpec findWorldSubgame(const std::string &world_path) { std::string world_gameid = getWorldGameId(world_path, true); // See if world contains an embedded game; if so, use it. std::string world_gamepath = world_path + DIR_DELIM + "game"; if (fs::PathExists(world_gamepath)) { SubgameSpec gamespec; gamespec.id = world_gameid; gamespec.path = world_gamepath; gamespec.gamemods_path = world_gamepath + DIR_DELIM + "mods"; Settings conf; std::string conf_path = world_gamepath + DIR_DELIM + "game.conf"; conf.readConfigFile(conf_path.c_str()); if (conf.exists("name")) gamespec.name = conf.get("name"); else gamespec.name = world_gameid; return gamespec; } return findSubgame(world_gameid); } std::set<std::string> getAvailableGameIds() { std::set<std::string> gameids; std::set<std::string> gamespaths; gamespaths.insert(porting::path_share + DIR_DELIM + "games"); gamespaths.insert(porting::path_user + DIR_DELIM + "games"); Strfnd search_paths(getSubgamePathEnv()); while (!search_paths.at_end()) gamespaths.insert(search_paths.next(PATH_DELIM)); for (const std::string &gamespath : gamespaths) { std::vector<fs::DirListNode> dirlist = fs::GetDirListing(gamespath); for (const fs::DirListNode &dln : dirlist) { if (!dln.dir) continue; // If configuration file is not found or broken, ignore game Settings conf; std::string conf_path = gamespath + DIR_DELIM + dln.name + DIR_DELIM + "game.conf"; if (!conf.readConfigFile(conf_path.c_str())) continue; // Add it to result const char *ends[] = {"_game", NULL}; std::string shorter = removeStringEnd(dln.name, ends); if (!shorter.empty()) gameids.insert(shorter); else gameids.insert(dln.name); } } return gameids; } std::vector<SubgameSpec> getAvailableGames() { std::vector<SubgameSpec> specs; std::set<std::string> gameids = getAvailableGameIds(); specs.reserve(gameids.size()); for (const auto &gameid : gameids) specs.push_back(findSubgame(gameid)); return specs; } #define LEGACY_GAMEID "minetest" bool getWorldExists(const std::string &world_path) { return (fs::PathExists(world_path + DIR_DELIM + "map_meta.txt") || fs::PathExists(world_path + DIR_DELIM + "world.mt")); } std::string getWorldGameId(const std::string &world_path, bool can_be_legacy) { std::string conf_path = world_path + DIR_DELIM + "world.mt"; Settings conf; bool succeeded = conf.readConfigFile(conf_path.c_str()); if (!succeeded) { if (can_be_legacy) { // If map_meta.txt exists, it is probably an old minetest world if (fs::PathExists(world_path + DIR_DELIM + "map_meta.txt")) return LEGACY_GAMEID; } return ""; } if (!conf.exists("gameid")) return ""; // The "mesetint" gameid has been discarded if (conf.get("gameid") == "mesetint") return "minetest"; return conf.get("gameid"); } std::string getWorldPathEnv() { char *world_path = getenv("MINETEST_WORLD_PATH"); return world_path ? std::string(world_path) : ""; } std::vector<WorldSpec> getAvailableWorlds() { std::vector<WorldSpec> worlds; std::set<std::string> worldspaths; Strfnd search_paths(getWorldPathEnv()); while (!search_paths.at_end()) worldspaths.insert(search_paths.next(PATH_DELIM)); worldspaths.insert(porting::path_user + DIR_DELIM + "worlds"); infostream << "Searching worlds..." << std::endl; for (const std::string &worldspath : worldspaths) { infostream << " In " << worldspath << ": " << std::endl; std::vector<fs::DirListNode> dirvector = fs::GetDirListing(worldspath); for (const fs::DirListNode &dln : dirvector) { if (!dln.dir) continue; std::string fullpath = worldspath + DIR_DELIM + dln.name; std::string name = dln.name; // Just allow filling in the gameid always for now bool can_be_legacy = true; std::string gameid = getWorldGameId(fullpath, can_be_legacy); WorldSpec spec(fullpath, name, gameid); if (!spec.isValid()) { infostream << "(invalid: " << name << ") "; } else { infostream << name << " "; worlds.push_back(spec); } } infostream << std::endl; } // Check old world location do { std::string fullpath = porting::path_user + DIR_DELIM + "world"; if (!fs::PathExists(fullpath)) break; std::string name = "Old World"; std::string gameid = getWorldGameId(fullpath, true); WorldSpec spec(fullpath, name, gameid); infostream << "Old world found." << std::endl; worlds.push_back(spec); } while (false); infostream << worlds.size() << " found." << std::endl; return worlds; } bool loadGameConfAndInitWorld(const std::string &path, const SubgameSpec &gamespec) { // Override defaults with those provided by the game. // We clear and reload the defaults because the defaults // might have been overridden by other subgame config // files that were loaded before. g_settings->clearDefaults(); set_default_settings(g_settings); Settings game_defaults; getGameMinetestConfig(gamespec.path, game_defaults); override_default_settings(g_settings, &game_defaults); infostream << "Initializing world at " << path << std::endl; fs::CreateAllDirs(path); // Create world.mt if does not already exist std::string worldmt_path = path + DIR_DELIM "world.mt"; if (!fs::PathExists(worldmt_path)) { Settings conf; conf.set("gameid", gamespec.id); conf.set("backend", "sqlite3"); conf.set("player_backend", "sqlite3"); conf.set("auth_backend", "sqlite3"); conf.setBool("creative_mode", g_settings->getBool("creative_mode")); conf.setBool("enable_damage", g_settings->getBool("enable_damage")); if (!conf.updateConfigFile(worldmt_path.c_str())) return false; } // Create map_meta.txt if does not already exist std::string map_meta_path = path + DIR_DELIM + "map_meta.txt"; if (!fs::PathExists(map_meta_path)) { verbosestream << "Creating map_meta.txt (" << map_meta_path << ")" << std::endl; fs::CreateAllDirs(path); std::ostringstream oss(std::ios_base::binary); Settings conf; MapgenParams params; params.readParams(g_settings); params.writeParams(&conf); conf.writeLines(oss); oss << "[end_of_params]\n"; fs::safeWriteToFile(map_meta_path, oss.str()); } return true; }
pgimeno/minetest
src/content/subgames.cpp
C++
mit
10,082
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <string> #include <set> #include <vector> class Settings; struct SubgameSpec { std::string id; std::string name; std::string author; int release; std::string path; std::string gamemods_path; std::set<std::string> addon_mods_paths; std::string menuicon_path; SubgameSpec(const std::string &id = "", const std::string &path = "", const std::string &gamemods_path = "", const std::set<std::string> &addon_mods_paths = std::set<std::string>(), const std::string &name = "", const std::string &menuicon_path = "", const std::string &author = "", int release = 0) : id(id), name(name), author(author), release(release), path(path), gamemods_path(gamemods_path), addon_mods_paths(addon_mods_paths), menuicon_path(menuicon_path) { } bool isValid() const { return (!id.empty() && !path.empty()); } }; // minetest.conf bool getGameMinetestConfig(const std::string &game_path, Settings &conf); SubgameSpec findSubgame(const std::string &id); SubgameSpec findWorldSubgame(const std::string &world_path); std::set<std::string> getAvailableGameIds(); std::vector<SubgameSpec> getAvailableGames(); bool getWorldExists(const std::string &world_path); std::string getWorldGameId(const std::string &world_path, bool can_be_legacy = false); struct WorldSpec { std::string path; std::string name; std::string gameid; WorldSpec(const std::string &path = "", const std::string &name = "", const std::string &gameid = "") : path(path), name(name), gameid(gameid) { } bool isValid() const { return (!name.empty() && !path.empty() && !gameid.empty()); } }; std::vector<WorldSpec> getAvailableWorlds(); // loads the subgame's config and creates world directory // and world.mt if they don't exist bool loadGameConfAndInitWorld(const std::string &path, const SubgameSpec &gamespec);
pgimeno/minetest
src/content/subgames.h
C++
mit
2,641
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "content_mapnode.h" #include "irrlichttypes_bloated.h" #include "mapnode.h" #include "nodedef.h" #include "nameidmapping.h" #include "util/string.h" /* Legacy node content type IDs Ranges: 0x000...0x07f (0...127): param2 is fully usable 126 and 127 are reserved (CONTENT_AIR and CONTENT_IGNORE). 0x800...0xfff (2048...4095): higher 4 bits of param2 are not usable */ #define CONTENT_STONE 0 #define CONTENT_WATER 2 #define CONTENT_TORCH 3 #define CONTENT_WATERSOURCE 9 #define CONTENT_SIGN_WALL 14 #define CONTENT_CHEST 15 #define CONTENT_FURNACE 16 #define CONTENT_LOCKABLE_CHEST 17 #define CONTENT_FENCE 21 #define CONTENT_RAIL 30 #define CONTENT_LADDER 31 #define CONTENT_LAVA 32 #define CONTENT_LAVASOURCE 33 #define CONTENT_GRASS 0x800 //1 #define CONTENT_TREE 0x801 //4 #define CONTENT_LEAVES 0x802 //5 #define CONTENT_GRASS_FOOTSTEPS 0x803 //6 #define CONTENT_MESE 0x804 //7 #define CONTENT_MUD 0x805 //8 #define CONTENT_CLOUD 0x806 //10 #define CONTENT_COALSTONE 0x807 //11 #define CONTENT_WOOD 0x808 //12 #define CONTENT_SAND 0x809 //13 #define CONTENT_COBBLE 0x80a //18 #define CONTENT_STEEL 0x80b //19 #define CONTENT_GLASS 0x80c //20 #define CONTENT_MOSSYCOBBLE 0x80d //22 #define CONTENT_GRAVEL 0x80e //23 #define CONTENT_SANDSTONE 0x80f //24 #define CONTENT_CACTUS 0x810 //25 #define CONTENT_BRICK 0x811 //26 #define CONTENT_CLAY 0x812 //27 #define CONTENT_PAPYRUS 0x813 //28 #define CONTENT_BOOKSHELF 0x814 //29 #define CONTENT_JUNGLETREE 0x815 #define CONTENT_JUNGLEGRASS 0x816 #define CONTENT_NC 0x817 #define CONTENT_NC_RB 0x818 #define CONTENT_APPLE 0x819 #define CONTENT_SAPLING 0x820 /* A conversion table for backwards compatibility. Maps <=v19 content types to current ones. Should never be touched. */ content_t trans_table_19[21][2] = { {CONTENT_GRASS, 1}, {CONTENT_TREE, 4}, {CONTENT_LEAVES, 5}, {CONTENT_GRASS_FOOTSTEPS, 6}, {CONTENT_MESE, 7}, {CONTENT_MUD, 8}, {CONTENT_CLOUD, 10}, {CONTENT_COALSTONE, 11}, {CONTENT_WOOD, 12}, {CONTENT_SAND, 13}, {CONTENT_COBBLE, 18}, {CONTENT_STEEL, 19}, {CONTENT_GLASS, 20}, {CONTENT_MOSSYCOBBLE, 22}, {CONTENT_GRAVEL, 23}, {CONTENT_SANDSTONE, 24}, {CONTENT_CACTUS, 25}, {CONTENT_BRICK, 26}, {CONTENT_CLAY, 27}, {CONTENT_PAPYRUS, 28}, {CONTENT_BOOKSHELF, 29}, }; MapNode mapnode_translate_to_internal(MapNode n_from, u8 version) { MapNode result = n_from; if(version <= 19) { content_t c_from = n_from.getContent(); for (const auto &tt_i : trans_table_19) { if (tt_i[1] == c_from) { result.setContent(tt_i[0]); break; } } } return result; } void content_mapnode_get_name_id_mapping(NameIdMapping *nimap) { nimap->set(0, "default:stone"); nimap->set(2, "default:water_flowing"); nimap->set(3, "default:torch"); nimap->set(9, "default:water_source"); nimap->set(14, "default:sign_wall"); nimap->set(15, "default:chest"); nimap->set(16, "default:furnace"); nimap->set(17, "default:chest_locked"); nimap->set(21, "default:fence_wood"); nimap->set(30, "default:rail"); nimap->set(31, "default:ladder"); nimap->set(32, "default:lava_flowing"); nimap->set(33, "default:lava_source"); nimap->set(0x800, "default:dirt_with_grass"); nimap->set(0x801, "default:tree"); nimap->set(0x802, "default:leaves"); nimap->set(0x803, "default:dirt_with_grass_footsteps"); nimap->set(0x804, "default:mese"); nimap->set(0x805, "default:dirt"); nimap->set(0x806, "default:cloud"); nimap->set(0x807, "default:coalstone"); nimap->set(0x808, "default:wood"); nimap->set(0x809, "default:sand"); nimap->set(0x80a, "default:cobble"); nimap->set(0x80b, "default:steelblock"); nimap->set(0x80c, "default:glass"); nimap->set(0x80d, "default:mossycobble"); nimap->set(0x80e, "default:gravel"); nimap->set(0x80f, "default:sandstone"); nimap->set(0x810, "default:cactus"); nimap->set(0x811, "default:brick"); nimap->set(0x812, "default:clay"); nimap->set(0x813, "default:papyrus"); nimap->set(0x814, "default:bookshelf"); nimap->set(0x815, "default:jungletree"); nimap->set(0x816, "default:junglegrass"); nimap->set(0x817, "default:nyancat"); nimap->set(0x818, "default:nyancat_rainbow"); nimap->set(0x819, "default:apple"); nimap->set(0x820, "default:sapling"); // Static types nimap->set(CONTENT_IGNORE, "ignore"); nimap->set(CONTENT_AIR, "air"); }
pgimeno/minetest
src/content_mapnode.cpp
C++
mit
5,081
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "mapnode.h" /* Legacy node definitions */ // Backwards compatibility for non-extended content types in v19 extern content_t trans_table_19[21][2]; MapNode mapnode_translate_to_internal(MapNode n_from, u8 version); // Get legacy node name mapping for loading old blocks class NameIdMapping; void content_mapnode_get_name_id_mapping(NameIdMapping *nimap);
pgimeno/minetest
src/content_mapnode.h
C++
mit
1,171
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "content_nodemeta.h" #include "nodemetadata.h" #include "nodetimer.h" #include "inventory.h" #include "log.h" #include "serialization.h" #include "util/serialize.h" #include "util/string.h" #include "constants.h" // MAP_BLOCKSIZE #include <sstream> #define NODEMETA_GENERIC 1 #define NODEMETA_SIGN 14 #define NODEMETA_CHEST 15 #define NODEMETA_FURNACE 16 #define NODEMETA_LOCKABLE_CHEST 17 // Returns true if node timer must be set static bool content_nodemeta_deserialize_legacy_body( std::istream &is, s16 id, NodeMetadata *meta) { meta->clear(); if(id == NODEMETA_GENERIC) // GenericNodeMetadata (0.4-dev) { meta->getInventory()->deSerialize(is); deSerializeLongString(is); // m_text deSerializeString(is); // m_owner meta->setString("infotext",deSerializeString(is)); meta->setString("formspec",deSerializeString(is)); readU8(is); // m_allow_text_input readU8(is); // m_allow_removal readU8(is); // m_enforce_owner int num_vars = readU32(is); for(int i=0; i<num_vars; i++){ std::string name = deSerializeString(is); std::string var = deSerializeLongString(is); meta->setString(name, var); } return false; } else if(id == NODEMETA_SIGN) // SignNodeMetadata { meta->setString("text", deSerializeString(is)); //meta->setString("infotext","\"${text}\""); meta->setString("infotext", std::string("\"") + meta->getString("text") + "\""); meta->setString("formspec","field[text;;${text}]"); return false; } else if(id == NODEMETA_CHEST) // ChestNodeMetadata { meta->getInventory()->deSerialize(is); // Rename inventory list "0" to "main" Inventory *inv = meta->getInventory(); if(!inv->getList("main") && inv->getList("0")){ inv->getList("0")->setName("main"); } assert(inv->getList("main") && !inv->getList("0")); meta->setString("formspec","size[8,9]" "list[current_name;main;0,0;8,4;]" "list[current_player;main;0,5;8,4;]"); return false; } else if(id == NODEMETA_LOCKABLE_CHEST) // LockingChestNodeMetadata { meta->setString("owner", deSerializeString(is)); meta->getInventory()->deSerialize(is); // Rename inventory list "0" to "main" Inventory *inv = meta->getInventory(); if(!inv->getList("main") && inv->getList("0")){ inv->getList("0")->setName("main"); } assert(inv->getList("main") && !inv->getList("0")); meta->setString("formspec","size[8,9]" "list[current_name;main;0,0;8,4;]" "list[current_player;main;0,5;8,4;]"); return false; } else if(id == NODEMETA_FURNACE) // FurnaceNodeMetadata { meta->getInventory()->deSerialize(is); int temp = 0; is>>temp; meta->setString("fuel_totaltime", ftos((float)temp/10)); temp = 0; is>>temp; meta->setString("fuel_time", ftos((float)temp/10)); temp = 0; is>>temp; //meta->setString("src_totaltime", ftos((float)temp/10)); temp = 0; is>>temp; meta->setString("src_time", ftos((float)temp/10)); meta->setString("formspec","size[8,9]" "list[current_name;fuel;2,3;1,1;]" "list[current_name;src;2,1;1,1;]" "list[current_name;dst;5,1;2,2;]" "list[current_player;main;0,5;8,4;]"); return true; } else { throw SerializationError("Unknown legacy node metadata"); } } static bool content_nodemeta_deserialize_legacy_meta( std::istream &is, NodeMetadata *meta) { // Read id s16 id = readS16(is); // Read data std::string data = deSerializeString(is); std::istringstream tmp_is(data, std::ios::binary); return content_nodemeta_deserialize_legacy_body(tmp_is, id, meta); } void content_nodemeta_deserialize_legacy(std::istream &is, NodeMetadataList *meta, NodeTimerList *timers, IItemDefManager *item_def_mgr) { meta->clear(); timers->clear(); u16 version = readU16(is); if(version > 1) { infostream<<FUNCTION_NAME<<": version "<<version<<" not supported" <<std::endl; throw SerializationError(FUNCTION_NAME); } u16 count = readU16(is); for(u16 i=0; i<count; i++) { u16 p16 = readU16(is); v3s16 p(0,0,0); p.Z += p16 / MAP_BLOCKSIZE / MAP_BLOCKSIZE; p16 -= p.Z * MAP_BLOCKSIZE * MAP_BLOCKSIZE; p.Y += p16 / MAP_BLOCKSIZE; p16 -= p.Y * MAP_BLOCKSIZE; p.X += p16; if(meta->get(p) != NULL) { warningstream<<FUNCTION_NAME<<": " <<"already set data at position" <<"("<<p.X<<","<<p.Y<<","<<p.Z<<"): Ignoring." <<std::endl; continue; } NodeMetadata *data = new NodeMetadata(item_def_mgr); bool need_timer = content_nodemeta_deserialize_legacy_meta(is, data); meta->set(p, data); if(need_timer) timers->set(NodeTimer(1., 0., p)); } }
pgimeno/minetest
src/content_nodemeta.cpp
C++
mit
5,335
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <iostream> class NodeMetadataList; class NodeTimerList; class IItemDefManager; /* Legacy nodemeta definitions */ void content_nodemeta_deserialize_legacy(std::istream &is, NodeMetadataList *meta, NodeTimerList *timers, IItemDefManager *item_def_mgr);
pgimeno/minetest
src/content_nodemeta.h
C++
mit
1,072
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "content_sao.h" #include "util/serialize.h" #include "collision.h" #include "environment.h" #include "tool.h" // For ToolCapabilities #include "gamedef.h" #include "nodedef.h" #include "remoteplayer.h" #include "server.h" #include "scripting_server.h" #include "genericobject.h" #include "settings.h" #include <algorithm> #include <cmath> std::map<u16, ServerActiveObject::Factory> ServerActiveObject::m_types; /* TestSAO */ class TestSAO : public ServerActiveObject { public: TestSAO(ServerEnvironment *env, v3f pos): ServerActiveObject(env, pos), m_timer1(0), m_age(0) { ServerActiveObject::registerType(getType(), create); } ActiveObjectType getType() const { return ACTIVEOBJECT_TYPE_TEST; } static ServerActiveObject* create(ServerEnvironment *env, v3f pos, const std::string &data) { return new TestSAO(env, pos); } void step(float dtime, bool send_recommended) { m_age += dtime; if(m_age > 10) { m_pending_removal = true; return; } m_base_position.Y += dtime * BS * 2; if(m_base_position.Y > 8*BS) m_base_position.Y = 2*BS; if (!send_recommended) return; m_timer1 -= dtime; if(m_timer1 < 0.0) { m_timer1 += 0.125; std::string data; data += itos(0); // 0 = position data += " "; data += itos(m_base_position.X); data += " "; data += itos(m_base_position.Y); data += " "; data += itos(m_base_position.Z); ActiveObjectMessage aom(getId(), false, data); m_messages_out.push(aom); } } bool getCollisionBox(aabb3f *toset) const { return false; } virtual bool getSelectionBox(aabb3f *toset) const { return false; } bool collideWithObjects() const { return false; } private: float m_timer1; float m_age; }; // Prototype (registers item for deserialization) TestSAO proto_TestSAO(NULL, v3f(0,0,0)); /* UnitSAO */ UnitSAO::UnitSAO(ServerEnvironment *env, v3f pos): ServerActiveObject(env, pos) { // Initialize something to armor groups m_armor_groups["fleshy"] = 100; } ServerActiveObject *UnitSAO::getParent() const { if (!m_attachment_parent_id) return nullptr; // Check if the parent still exists ServerActiveObject *obj = m_env->getActiveObject(m_attachment_parent_id); return obj; } void UnitSAO::setArmorGroups(const ItemGroupList &armor_groups) { m_armor_groups = armor_groups; m_armor_groups_sent = false; } const ItemGroupList &UnitSAO::getArmorGroups() { return m_armor_groups; } void UnitSAO::setAnimation(v2f frame_range, float frame_speed, float frame_blend, bool frame_loop) { // store these so they can be updated to clients m_animation_range = frame_range; m_animation_speed = frame_speed; m_animation_blend = frame_blend; m_animation_loop = frame_loop; m_animation_sent = false; } void UnitSAO::getAnimation(v2f *frame_range, float *frame_speed, float *frame_blend, bool *frame_loop) { *frame_range = m_animation_range; *frame_speed = m_animation_speed; *frame_blend = m_animation_blend; *frame_loop = m_animation_loop; } void UnitSAO::setAnimationSpeed(float frame_speed) { m_animation_speed = frame_speed; m_animation_speed_sent = false; } void UnitSAO::setBonePosition(const std::string &bone, v3f position, v3f rotation) { // store these so they can be updated to clients m_bone_position[bone] = core::vector2d<v3f>(position, rotation); m_bone_position_sent = false; } void UnitSAO::getBonePosition(const std::string &bone, v3f *position, v3f *rotation) { *position = m_bone_position[bone].X; *rotation = m_bone_position[bone].Y; } void UnitSAO::setAttachment(int parent_id, const std::string &bone, v3f position, v3f rotation) { // Attachments need to be handled on both the server and client. // If we just attach on the server, we can only copy the position of the parent. Attachments // are still sent to clients at an interval so players might see them lagging, plus we can't // read and attach to skeletal bones. // If we just attach on the client, the server still sees the child at its original location. // This breaks some things so we also give the server the most accurate representation // even if players only see the client changes. int old_parent = m_attachment_parent_id; m_attachment_parent_id = parent_id; m_attachment_bone = bone; m_attachment_position = position; m_attachment_rotation = rotation; m_attachment_sent = false; if (parent_id != old_parent) { onDetach(old_parent); onAttach(parent_id); } } void UnitSAO::getAttachment(int *parent_id, std::string *bone, v3f *position, v3f *rotation) { *parent_id = m_attachment_parent_id; *bone = m_attachment_bone; *position = m_attachment_position; *rotation = m_attachment_rotation; } void UnitSAO::clearChildAttachments() { for (int child_id : m_attachment_child_ids) { // Child can be NULL if it was deleted earlier if (ServerActiveObject *child = m_env->getActiveObject(child_id)) child->setAttachment(0, "", v3f(0, 0, 0), v3f(0, 0, 0)); } m_attachment_child_ids.clear(); } void UnitSAO::clearParentAttachment() { ServerActiveObject *parent = nullptr; if (m_attachment_parent_id) { parent = m_env->getActiveObject(m_attachment_parent_id); setAttachment(0, "", m_attachment_position, m_attachment_rotation); } else { setAttachment(0, "", v3f(0, 0, 0), v3f(0, 0, 0)); } // Do it if (parent) parent->removeAttachmentChild(m_id); } void UnitSAO::addAttachmentChild(int child_id) { m_attachment_child_ids.insert(child_id); } void UnitSAO::removeAttachmentChild(int child_id) { m_attachment_child_ids.erase(child_id); } const std::unordered_set<int> &UnitSAO::getAttachmentChildIds() { return m_attachment_child_ids; } void UnitSAO::onAttach(int parent_id) { if (!parent_id) return; ServerActiveObject *parent = m_env->getActiveObject(parent_id); if (!parent || parent->isGone()) return; // Do not try to notify soon gone parent if (parent->getType() == ACTIVEOBJECT_TYPE_LUAENTITY) { // Call parent's on_attach field m_env->getScriptIface()->luaentity_on_attach_child(parent_id, this); } } void UnitSAO::onDetach(int parent_id) { if (!parent_id) return; ServerActiveObject *parent = m_env->getActiveObject(parent_id); if (getType() == ACTIVEOBJECT_TYPE_LUAENTITY) m_env->getScriptIface()->luaentity_on_detach(m_id, parent); if (!parent || parent->isGone()) return; // Do not try to notify soon gone parent if (parent->getType() == ACTIVEOBJECT_TYPE_LUAENTITY) m_env->getScriptIface()->luaentity_on_detach_child(parent_id, this); } ObjectProperties* UnitSAO::accessObjectProperties() { return &m_prop; } void UnitSAO::notifyObjectPropertiesModified() { m_properties_sent = false; } /* LuaEntitySAO */ // Prototype (registers item for deserialization) LuaEntitySAO proto_LuaEntitySAO(NULL, v3f(0,0,0), "_prototype", ""); LuaEntitySAO::LuaEntitySAO(ServerEnvironment *env, v3f pos, const std::string &name, const std::string &state): UnitSAO(env, pos), m_init_name(name), m_init_state(state) { // Only register type if no environment supplied if(env == NULL){ ServerActiveObject::registerType(getType(), create); return; } } LuaEntitySAO::~LuaEntitySAO() { if(m_registered){ m_env->getScriptIface()->luaentity_Remove(m_id); } for (u32 attached_particle_spawner : m_attached_particle_spawners) { m_env->deleteParticleSpawner(attached_particle_spawner, false); } } void LuaEntitySAO::addedToEnvironment(u32 dtime_s) { ServerActiveObject::addedToEnvironment(dtime_s); // Create entity from name m_registered = m_env->getScriptIface()-> luaentity_Add(m_id, m_init_name.c_str()); if(m_registered){ // Get properties m_env->getScriptIface()-> luaentity_GetProperties(m_id, &m_prop); // Initialize HP from properties m_hp = m_prop.hp_max; // Activate entity, supplying serialized state m_env->getScriptIface()-> luaentity_Activate(m_id, m_init_state, dtime_s); } else { m_prop.infotext = m_init_name; } } ServerActiveObject* LuaEntitySAO::create(ServerEnvironment *env, v3f pos, const std::string &data) { std::string name; std::string state; u16 hp = 1; v3f velocity; v3f rotation; while (!data.empty()) { // breakable, run for one iteration std::istringstream is(data, std::ios::binary); // 'version' does not allow to incrementally extend the parameter list thus // we need another variable to build on top of 'version=1'. Ugly hack but works™ u8 version2 = 0; u8 version = readU8(is); name = deSerializeString(is); state = deSerializeLongString(is); if (version < 1) break; hp = readU16(is); velocity = readV3F1000(is); // yaw must be yaw to be backwards-compatible rotation.Y = readF1000(is); if (is.good()) // EOF for old formats version2 = readU8(is); if (version2 < 1) // PROTOCOL_VERSION < 37 break; // version2 >= 1 rotation.X = readF1000(is); rotation.Z = readF1000(is); // if (version2 < 2) // break; // <read new values> break; } // create object infostream << "LuaEntitySAO::create(name=\"" << name << "\" state=\"" << state << "\")" << std::endl; LuaEntitySAO *sao = new LuaEntitySAO(env, pos, name, state); sao->m_hp = hp; sao->m_velocity = velocity; sao->m_rotation = rotation; return sao; } void LuaEntitySAO::step(float dtime, bool send_recommended) { if(!m_properties_sent) { m_properties_sent = true; std::string str = getPropertyPacket(); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } // If attached, check that our parent is still there. If it isn't, detach. if(m_attachment_parent_id && !isAttached()) { m_attachment_parent_id = 0; m_attachment_bone = ""; m_attachment_position = v3f(0,0,0); m_attachment_rotation = v3f(0,0,0); sendPosition(false, true); } m_last_sent_position_timer += dtime; // Each frame, parent position is copied if the object is attached, otherwise it's calculated normally // If the object gets detached this comes into effect automatically from the last known origin if(isAttached()) { v3f pos = m_env->getActiveObject(m_attachment_parent_id)->getBasePosition(); m_base_position = pos; m_velocity = v3f(0,0,0); m_acceleration = v3f(0,0,0); } else { if(m_prop.physical){ aabb3f box = m_prop.collisionbox; box.MinEdge *= BS; box.MaxEdge *= BS; collisionMoveResult moveresult; f32 pos_max_d = BS*0.25; // Distance per iteration v3f p_pos = m_base_position; v3f p_velocity = m_velocity; v3f p_acceleration = m_acceleration; moveresult = collisionMoveSimple(m_env, m_env->getGameDef(), pos_max_d, box, m_prop.stepheight, dtime, &p_pos, &p_velocity, p_acceleration, this, m_prop.collideWithObjects); // Apply results m_base_position = p_pos; m_velocity = p_velocity; m_acceleration = p_acceleration; } else { m_base_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration; m_velocity += dtime * m_acceleration; } if (m_prop.automatic_face_movement_dir && (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) { float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI + m_prop.automatic_face_movement_dir_offset; float max_rotation_delta = dtime * m_prop.automatic_face_movement_max_rotation_per_sec; m_rotation.Y = wrapDegrees_0_360(m_rotation.Y); wrappedApproachShortest(m_rotation.Y, target_yaw, max_rotation_delta, 360.f); } } if(m_registered){ m_env->getScriptIface()->luaentity_Step(m_id, dtime); } if (!send_recommended) return; if(!isAttached()) { // TODO: force send when acceleration changes enough? float minchange = 0.2*BS; if(m_last_sent_position_timer > 1.0){ minchange = 0.01*BS; } else if(m_last_sent_position_timer > 0.2){ minchange = 0.05*BS; } float move_d = m_base_position.getDistanceFrom(m_last_sent_position); move_d += m_last_sent_move_precision; float vel_d = m_velocity.getDistanceFrom(m_last_sent_velocity); if (move_d > minchange || vel_d > minchange || std::fabs(m_rotation.X - m_last_sent_rotation.X) > 1.0f || std::fabs(m_rotation.Y - m_last_sent_rotation.Y) > 1.0f || std::fabs(m_rotation.Z - m_last_sent_rotation.Z) > 1.0f) { sendPosition(true, false); } } if (!m_armor_groups_sent) { m_armor_groups_sent = true; std::string str = gob_cmd_update_armor_groups( m_armor_groups); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } if (!m_animation_sent) { m_animation_sent = true; std::string str = gob_cmd_update_animation( m_animation_range, m_animation_speed, m_animation_blend, m_animation_loop); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } if (!m_animation_speed_sent) { m_animation_speed_sent = true; std::string str = gob_cmd_update_animation_speed(m_animation_speed); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } if (!m_bone_position_sent) { m_bone_position_sent = true; for (std::unordered_map<std::string, core::vector2d<v3f>>::const_iterator ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii){ std::string str = gob_cmd_update_bone_position((*ii).first, (*ii).second.X, (*ii).second.Y); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } } if (!m_attachment_sent) { m_attachment_sent = true; std::string str = gob_cmd_update_attachment(m_attachment_parent_id, m_attachment_bone, m_attachment_position, m_attachment_rotation); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } } std::string LuaEntitySAO::getClientInitializationData(u16 protocol_version) { std::ostringstream os(std::ios::binary); // PROTOCOL_VERSION >= 37 writeU8(os, 1); // version os << serializeString(""); // name writeU8(os, 0); // is_player writeU16(os, getId()); //id writeV3F32(os, m_base_position); writeV3F32(os, m_rotation); writeU16(os, m_hp); std::ostringstream msg_os(std::ios::binary); msg_os << serializeLongString(getPropertyPacket()); // message 1 msg_os << serializeLongString(gob_cmd_update_armor_groups(m_armor_groups)); // 2 msg_os << serializeLongString(gob_cmd_update_animation( m_animation_range, m_animation_speed, m_animation_blend, m_animation_loop)); // 3 for (std::unordered_map<std::string, core::vector2d<v3f>>::const_iterator ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) { msg_os << serializeLongString(gob_cmd_update_bone_position((*ii).first, (*ii).second.X, (*ii).second.Y)); // m_bone_position.size } msg_os << serializeLongString(gob_cmd_update_attachment(m_attachment_parent_id, m_attachment_bone, m_attachment_position, m_attachment_rotation)); // 4 int message_count = 4 + m_bone_position.size(); for (std::unordered_set<int>::const_iterator ii = m_attachment_child_ids.begin(); (ii != m_attachment_child_ids.end()); ++ii) { if (ServerActiveObject *obj = m_env->getActiveObject(*ii)) { message_count++; msg_os << serializeLongString(gob_cmd_update_infant(*ii, obj->getSendType(), obj->getClientInitializationData(protocol_version))); } } msg_os << serializeLongString(gob_cmd_set_texture_mod(m_current_texture_modifier)); message_count++; writeU8(os, message_count); os.write(msg_os.str().c_str(), msg_os.str().size()); // return result return os.str(); } void LuaEntitySAO::getStaticData(std::string *result) const { verbosestream<<FUNCTION_NAME<<std::endl; std::ostringstream os(std::ios::binary); // version must be 1 to keep backwards-compatibility. See version2 writeU8(os, 1); // name os<<serializeString(m_init_name); // state if(m_registered){ std::string state = m_env->getScriptIface()-> luaentity_GetStaticdata(m_id); os<<serializeLongString(state); } else { os<<serializeLongString(m_init_state); } writeU16(os, m_hp); writeV3F1000(os, m_velocity); // yaw writeF1000(os, m_rotation.Y); // version2. Increase this variable for new values writeU8(os, 1); // PROTOCOL_VERSION >= 37 writeF1000(os, m_rotation.X); writeF1000(os, m_rotation.Z); // <write new values> *result = os.str(); } int LuaEntitySAO::punch(v3f dir, const ToolCapabilities *toolcap, ServerActiveObject *puncher, float time_from_last_punch) { if (!m_registered) { // Delete unknown LuaEntities when punched m_pending_removal = true; return 0; } ItemStack *punchitem = NULL; ItemStack punchitem_static; if (puncher) { punchitem_static = puncher->getWieldedItem(); punchitem = &punchitem_static; } PunchDamageResult result = getPunchDamage( m_armor_groups, toolcap, punchitem, time_from_last_punch); bool damage_handled = m_env->getScriptIface()->luaentity_Punch(m_id, puncher, time_from_last_punch, toolcap, dir, result.did_punch ? result.damage : 0); if (!damage_handled) { if (result.did_punch) { setHP((s32)getHP() - result.damage, PlayerHPChangeReason(PlayerHPChangeReason::SET_HP)); if (result.damage > 0) { std::string punchername = puncher ? puncher->getDescription() : "nil"; actionstream << getDescription() << " punched by " << punchername << ", damage " << result.damage << " hp, health now " << getHP() << " hp" << std::endl; } std::string str = gob_cmd_punched(getHP()); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } } if (getHP() == 0 && !isGone()) { m_pending_removal = true; clearParentAttachment(); clearChildAttachments(); m_env->getScriptIface()->luaentity_on_death(m_id, puncher); } return result.wear; } void LuaEntitySAO::rightClick(ServerActiveObject *clicker) { if (!m_registered) return; m_env->getScriptIface()->luaentity_Rightclick(m_id, clicker); } void LuaEntitySAO::setPos(const v3f &pos) { if(isAttached()) return; m_base_position = pos; sendPosition(false, true); } void LuaEntitySAO::moveTo(v3f pos, bool continuous) { if(isAttached()) return; m_base_position = pos; if(!continuous) sendPosition(true, true); } float LuaEntitySAO::getMinimumSavedMovement() { return 0.1 * BS; } std::string LuaEntitySAO::getDescription() { std::ostringstream os(std::ios::binary); os<<"LuaEntitySAO at ("; os<<(m_base_position.X/BS)<<","; os<<(m_base_position.Y/BS)<<","; os<<(m_base_position.Z/BS); os<<")"; return os.str(); } void LuaEntitySAO::setHP(s32 hp, const PlayerHPChangeReason &reason) { m_hp = rangelim(hp, 0, U16_MAX); } u16 LuaEntitySAO::getHP() const { return m_hp; } void LuaEntitySAO::setVelocity(v3f velocity) { m_velocity = velocity; } v3f LuaEntitySAO::getVelocity() { return m_velocity; } void LuaEntitySAO::setAcceleration(v3f acceleration) { m_acceleration = acceleration; } v3f LuaEntitySAO::getAcceleration() { return m_acceleration; } void LuaEntitySAO::setTextureMod(const std::string &mod) { std::string str = gob_cmd_set_texture_mod(mod); m_current_texture_modifier = mod; // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } std::string LuaEntitySAO::getTextureMod() const { return m_current_texture_modifier; } void LuaEntitySAO::setSprite(v2s16 p, int num_frames, float framelength, bool select_horiz_by_yawpitch) { std::string str = gob_cmd_set_sprite( p, num_frames, framelength, select_horiz_by_yawpitch ); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } std::string LuaEntitySAO::getName() { return m_init_name; } std::string LuaEntitySAO::getPropertyPacket() { return gob_cmd_set_properties(m_prop); } void LuaEntitySAO::sendPosition(bool do_interpolate, bool is_movement_end) { // If the object is attached client-side, don't waste bandwidth sending its position to clients if(isAttached()) return; m_last_sent_move_precision = m_base_position.getDistanceFrom( m_last_sent_position); m_last_sent_position_timer = 0; m_last_sent_position = m_base_position; m_last_sent_velocity = m_velocity; //m_last_sent_acceleration = m_acceleration; m_last_sent_rotation = m_rotation; float update_interval = m_env->getSendRecommendedInterval(); std::string str = gob_cmd_update_position( m_base_position, m_velocity, m_acceleration, m_rotation, do_interpolate, is_movement_end, update_interval ); // create message and add to list ActiveObjectMessage aom(getId(), false, str); m_messages_out.push(aom); } bool LuaEntitySAO::getCollisionBox(aabb3f *toset) const { if (m_prop.physical) { //update collision box toset->MinEdge = m_prop.collisionbox.MinEdge * BS; toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS; toset->MinEdge += m_base_position; toset->MaxEdge += m_base_position; return true; } return false; } bool LuaEntitySAO::getSelectionBox(aabb3f *toset) const { if (!m_prop.is_visible || !m_prop.pointable) { return false; } toset->MinEdge = m_prop.selectionbox.MinEdge * BS; toset->MaxEdge = m_prop.selectionbox.MaxEdge * BS; return true; } bool LuaEntitySAO::collideWithObjects() const { return m_prop.collideWithObjects; } /* PlayerSAO */ // No prototype, PlayerSAO does not need to be deserialized PlayerSAO::PlayerSAO(ServerEnvironment *env_, RemotePlayer *player_, session_t peer_id_, bool is_singleplayer): UnitSAO(env_, v3f(0,0,0)), m_player(player_), m_peer_id(peer_id_), m_is_singleplayer(is_singleplayer) { assert(m_peer_id != 0); // pre-condition m_prop.hp_max = PLAYER_MAX_HP_DEFAULT; m_prop.breath_max = PLAYER_MAX_BREATH_DEFAULT; m_prop.physical = false; m_prop.weight = 75; m_prop.collisionbox = aabb3f(-0.3f, 0.0f, -0.3f, 0.3f, 1.77f, 0.3f); m_prop.selectionbox = aabb3f(-0.3f, 0.0f, -0.3f, 0.3f, 1.77f, 0.3f); m_prop.pointable = true; // Start of default appearance, this should be overwritten by Lua m_prop.visual = "upright_sprite"; m_prop.visual_size = v3f(1, 2, 1); m_prop.textures.clear(); m_prop.textures.emplace_back("player.png"); m_prop.textures.emplace_back("player_back.png"); m_prop.colors.clear(); m_prop.colors.emplace_back(255, 255, 255, 255); m_prop.spritediv = v2s16(1,1); m_prop.eye_height = 1.625f; // End of default appearance m_prop.is_visible = true; m_prop.backface_culling = false; m_prop.makes_footstep_sound = true; m_prop.stepheight = PLAYER_DEFAULT_STEPHEIGHT * BS; m_hp = m_prop.hp_max; m_breath = m_prop.breath_max; // Disable zoom in survival mode using a value of 0 m_prop.zoom_fov = g_settings->getBool("creative_mode") ? 15.0f : 0.0f; } PlayerSAO::~PlayerSAO() { if(m_inventory != &m_player->inventory) delete m_inventory; } void PlayerSAO::finalize(RemotePlayer *player, const std::set<std::string> &privs) { assert(player); m_player = player; m_privs = privs; m_inventory = &m_player->inventory; } v3f PlayerSAO::getEyeOffset() const { return v3f(0, BS * m_prop.eye_height, 0); } std::string PlayerSAO::getDescription() { return std::string("player ") + m_player->getName(); } // Called after id has been set and has been inserted in environment void PlayerSAO::addedToEnvironment(u32 dtime_s) { ServerActiveObject::addedToEnvironment(dtime_s); ServerActiveObject::setBasePosition(m_base_position); m_player->setPlayerSAO(this); m_player->setPeerId(m_peer_id); m_last_good_position = m_base_position; } // Called before removing from environment void PlayerSAO::removingFromEnvironment() { ServerActiveObject::removingFromEnvironment(); if (m_player->getPlayerSAO() == this) { unlinkPlayerSessionAndSave(); for (u32 attached_particle_spawner : m_attached_particle_spawners) { m_env->deleteParticleSpawner(attached_particle_spawner, false); } } } std::string PlayerSAO::getClientInitializationData(u16 protocol_version) { std::ostringstream os(std::ios::binary); // Protocol >= 15 writeU8(os, 1); // version os << serializeString(m_player->getName()); // name writeU8(os, 1); // is_player writeS16(os, getId()); // id writeV3F32(os, m_base_position); writeV3F32(os, m_rotation); writeU16(os, getHP()); std::ostringstream msg_os(std::ios::binary); msg_os << serializeLongString(getPropertyPacket()); // message 1 msg_os << serializeLongString(gob_cmd_update_armor_groups(m_armor_groups)); // 2 msg_os << serializeLongString(gob_cmd_update_animation( m_animation_range, m_animation_speed, m_animation_blend, m_animation_loop)); // 3 for (std::unordered_map<std::string, core::vector2d<v3f>>::const_iterator ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) { msg_os << serializeLongString(gob_cmd_update_bone_position((*ii).first, (*ii).second.X, (*ii).second.Y)); // m_bone_position.size } msg_os << serializeLongString(gob_cmd_update_attachment(m_attachment_parent_id, m_attachment_bone, m_attachment_position, m_attachment_rotation)); // 4 msg_os << serializeLongString(gob_cmd_update_physics_override(m_physics_override_speed, m_physics_override_jump, m_physics_override_gravity, m_physics_override_sneak, m_physics_override_sneak_glitch, m_physics_override_new_move)); // 5 // (GENERIC_CMD_UPDATE_NAMETAG_ATTRIBUTES) : Deprecated, for backwards compatibility only. msg_os << serializeLongString(gob_cmd_update_nametag_attributes(m_prop.nametag_color)); // 6 int message_count = 6 + m_bone_position.size(); for (std::unordered_set<int>::const_iterator ii = m_attachment_child_ids.begin(); ii != m_attachment_child_ids.end(); ++ii) { if (ServerActiveObject *obj = m_env->getActiveObject(*ii)) { message_count++; msg_os << serializeLongString(gob_cmd_update_infant(*ii, obj->getSendType(), obj->getClientInitializationData(protocol_version))); } } writeU8(os, message_count); os.write(msg_os.str().c_str(), msg_os.str().size()); // return result return os.str(); } void PlayerSAO::getStaticData(std::string * result) const { FATAL_ERROR("Deprecated function"); } void PlayerSAO::step(float dtime, bool send_recommended) { if (m_drowning_interval.step(dtime, 2.0f)) { // Get nose/mouth position, approximate with eye position v3s16 p = floatToInt(getEyePosition(), BS); MapNode n = m_env->getMap().getNodeNoEx(p); const ContentFeatures &c = m_env->getGameDef()->ndef()->get(n); // If node generates drown if (c.drowning > 0 && m_hp > 0) { if (m_breath > 0) setBreath(m_breath - 1); // No more breath, damage player if (m_breath == 0) { PlayerHPChangeReason reason(PlayerHPChangeReason::DROWNING); setHP(m_hp - c.drowning, reason); m_env->getGameDef()->SendPlayerHPOrDie(this, reason); } } } if (m_breathing_interval.step(dtime, 0.5f)) { // Get nose/mouth position, approximate with eye position v3s16 p = floatToInt(getEyePosition(), BS); MapNode n = m_env->getMap().getNodeNoEx(p); const ContentFeatures &c = m_env->getGameDef()->ndef()->get(n); // If player is alive & no drowning & not in ignore, breathe if (m_breath < m_prop.breath_max && c.drowning == 0 && n.getContent() != CONTENT_IGNORE && m_hp > 0) setBreath(m_breath + 1); } if (m_node_hurt_interval.step(dtime, 1.0f)) { u32 damage_per_second = 0; // Lowest and highest damage points are 0.1 within collisionbox float dam_top = m_prop.collisionbox.MaxEdge.Y - 0.1f; // Sequence of damage points, starting 0.1 above feet and progressing // upwards in 1 node intervals, stopping below top damage point. for (float dam_height = 0.1f; dam_height < dam_top; dam_height++) { v3s16 p = floatToInt(m_base_position + v3f(0.0f, dam_height * BS, 0.0f), BS); MapNode n = m_env->getMap().getNodeNoEx(p); damage_per_second = std::max(damage_per_second, m_env->getGameDef()->ndef()->get(n).damage_per_second); } // Top damage point v3s16 ptop = floatToInt(m_base_position + v3f(0.0f, dam_top * BS, 0.0f), BS); MapNode ntop = m_env->getMap().getNodeNoEx(ptop); damage_per_second = std::max(damage_per_second, m_env->getGameDef()->ndef()->get(ntop).damage_per_second); if (damage_per_second != 0 && m_hp > 0) { s32 newhp = (s32)m_hp - (s32)damage_per_second; PlayerHPChangeReason reason(PlayerHPChangeReason::NODE_DAMAGE); setHP(newhp, reason); m_env->getGameDef()->SendPlayerHPOrDie(this, reason); } } if (!m_properties_sent) { m_properties_sent = true; std::string str = getPropertyPacket(); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } // If attached, check that our parent is still there. If it isn't, detach. if (m_attachment_parent_id && !isAttached()) { m_attachment_parent_id = 0; m_attachment_bone = ""; m_attachment_position = v3f(0.0f, 0.0f, 0.0f); m_attachment_rotation = v3f(0.0f, 0.0f, 0.0f); setBasePosition(m_last_good_position); m_env->getGameDef()->SendMovePlayer(m_peer_id); } //dstream<<"PlayerSAO::step: dtime: "<<dtime<<std::endl; // Set lag pool maximums based on estimated lag const float LAG_POOL_MIN = 5.0f; float lag_pool_max = m_env->getMaxLagEstimate() * 2.0f; if(lag_pool_max < LAG_POOL_MIN) lag_pool_max = LAG_POOL_MIN; m_dig_pool.setMax(lag_pool_max); m_move_pool.setMax(lag_pool_max); // Increment cheat prevention timers m_dig_pool.add(dtime); m_move_pool.add(dtime); m_time_from_last_teleport += dtime; m_time_from_last_punch += dtime; m_nocheat_dig_time += dtime; // Each frame, parent position is copied if the object is attached, // otherwise it's calculated normally. // If the object gets detached this comes into effect automatically from // the last known origin. if (isAttached()) { v3f pos = m_env->getActiveObject(m_attachment_parent_id)->getBasePosition(); m_last_good_position = pos; setBasePosition(pos); } if (!send_recommended) return; // If the object is attached client-side, don't waste bandwidth sending its // position or rotation to clients. if (m_position_not_sent && !isAttached()) { m_position_not_sent = false; float update_interval = m_env->getSendRecommendedInterval(); v3f pos; if (isAttached()) // Just in case we ever do send attachment position too pos = m_env->getActiveObject(m_attachment_parent_id)->getBasePosition(); else pos = m_base_position; std::string str = gob_cmd_update_position( pos, v3f(0.0f, 0.0f, 0.0f), v3f(0.0f, 0.0f, 0.0f), m_rotation, true, false, update_interval ); // create message and add to list ActiveObjectMessage aom(getId(), false, str); m_messages_out.push(aom); } if (!m_armor_groups_sent) { m_armor_groups_sent = true; std::string str = gob_cmd_update_armor_groups( m_armor_groups); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } if (!m_physics_override_sent) { m_physics_override_sent = true; std::string str = gob_cmd_update_physics_override(m_physics_override_speed, m_physics_override_jump, m_physics_override_gravity, m_physics_override_sneak, m_physics_override_sneak_glitch, m_physics_override_new_move); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } if (!m_animation_sent) { m_animation_sent = true; std::string str = gob_cmd_update_animation( m_animation_range, m_animation_speed, m_animation_blend, m_animation_loop); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } if (!m_bone_position_sent) { m_bone_position_sent = true; for (std::unordered_map<std::string, core::vector2d<v3f>>::const_iterator ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) { std::string str = gob_cmd_update_bone_position((*ii).first, (*ii).second.X, (*ii).second.Y); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } } if (!m_attachment_sent) { m_attachment_sent = true; std::string str = gob_cmd_update_attachment(m_attachment_parent_id, m_attachment_bone, m_attachment_position, m_attachment_rotation); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } } void PlayerSAO::setBasePosition(const v3f &position) { if (m_player && position != m_base_position) m_player->setDirty(true); // This needs to be ran for attachments too ServerActiveObject::setBasePosition(position); // Updating is not wanted/required for player migration if (m_env) { m_position_not_sent = true; } } void PlayerSAO::setPos(const v3f &pos) { if(isAttached()) return; setBasePosition(pos); // Movement caused by this command is always valid m_last_good_position = pos; m_move_pool.empty(); m_time_from_last_teleport = 0.0; m_env->getGameDef()->SendMovePlayer(m_peer_id); } void PlayerSAO::moveTo(v3f pos, bool continuous) { if(isAttached()) return; setBasePosition(pos); // Movement caused by this command is always valid m_last_good_position = pos; m_move_pool.empty(); m_time_from_last_teleport = 0.0; m_env->getGameDef()->SendMovePlayer(m_peer_id); } void PlayerSAO::setPlayerYaw(const float yaw) { v3f rotation(0, yaw, 0); if (m_player && yaw != m_rotation.Y) m_player->setDirty(true); // Set player model yaw, not look view UnitSAO::setRotation(rotation); } void PlayerSAO::setFov(const float fov) { if (m_player && fov != m_fov) m_player->setDirty(true); m_fov = fov; } void PlayerSAO::setWantedRange(const s16 range) { if (m_player && range != m_wanted_range) m_player->setDirty(true); m_wanted_range = range; } void PlayerSAO::setPlayerYawAndSend(const float yaw) { setPlayerYaw(yaw); m_env->getGameDef()->SendMovePlayer(m_peer_id); } void PlayerSAO::setLookPitch(const float pitch) { if (m_player && pitch != m_pitch) m_player->setDirty(true); m_pitch = pitch; } void PlayerSAO::setLookPitchAndSend(const float pitch) { setLookPitch(pitch); m_env->getGameDef()->SendMovePlayer(m_peer_id); } int PlayerSAO::punch(v3f dir, const ToolCapabilities *toolcap, ServerActiveObject *puncher, float time_from_last_punch) { if (!toolcap) return 0; // No effect if PvP disabled if (!g_settings->getBool("enable_pvp")) { if (puncher->getType() == ACTIVEOBJECT_TYPE_PLAYER) { std::string str = gob_cmd_punched(getHP()); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); return 0; } } HitParams hitparams = getHitParams(m_armor_groups, toolcap, time_from_last_punch); std::string punchername = "nil"; if (puncher != 0) punchername = puncher->getDescription(); PlayerSAO *playersao = m_player->getPlayerSAO(); bool damage_handled = m_env->getScriptIface()->on_punchplayer(playersao, puncher, time_from_last_punch, toolcap, dir, hitparams.hp); if (!damage_handled) { setHP((s32)getHP() - (s32)hitparams.hp, PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, puncher)); } else { // override client prediction if (puncher->getType() == ACTIVEOBJECT_TYPE_PLAYER) { std::string str = gob_cmd_punched(getHP()); // create message and add to list ActiveObjectMessage aom(getId(), true, str); m_messages_out.push(aom); } } actionstream << "Player " << m_player->getName() << " punched by " << punchername; if (!damage_handled) { actionstream << ", damage " << hitparams.hp << " HP"; } else { actionstream << ", damage handled by lua"; } actionstream << std::endl; return hitparams.wear; } void PlayerSAO::setHP(s32 hp, const PlayerHPChangeReason &reason) { s32 oldhp = m_hp; s32 hp_change = m_env->getScriptIface()->on_player_hpchange(this, hp - oldhp, reason); if (hp_change == 0) return; hp = rangelim(oldhp + hp_change, 0, m_prop.hp_max); if (hp < oldhp && !g_settings->getBool("enable_damage")) return; m_hp = hp; // Update properties on death if ((hp == 0) != (oldhp == 0)) m_properties_sent = false; } void PlayerSAO::setBreath(const u16 breath, bool send) { if (m_player && breath != m_breath) m_player->setDirty(true); m_breath = MYMIN(breath, m_prop.breath_max); if (send) m_env->getGameDef()->SendPlayerBreath(this); } Inventory* PlayerSAO::getInventory() { return m_inventory; } const Inventory* PlayerSAO::getInventory() const { return m_inventory; } InventoryLocation PlayerSAO::getInventoryLocation() const { InventoryLocation loc; loc.setPlayer(m_player->getName()); return loc; } std::string PlayerSAO::getWieldList() const { return "main"; } ItemStack PlayerSAO::getWieldedItem() const { const Inventory *inv = getInventory(); ItemStack ret; const InventoryList *mlist = inv->getList(getWieldList()); if (mlist && getWieldIndex() < (s32)mlist->getSize()) ret = mlist->getItem(getWieldIndex()); return ret; } ItemStack PlayerSAO::getWieldedItemOrHand() const { const Inventory *inv = getInventory(); ItemStack ret; const InventoryList *mlist = inv->getList(getWieldList()); if (mlist && getWieldIndex() < (s32)mlist->getSize()) ret = mlist->getItem(getWieldIndex()); if (ret.name.empty()) { const InventoryList *hlist = inv->getList("hand"); if (hlist) ret = hlist->getItem(0); } return ret; } bool PlayerSAO::setWieldedItem(const ItemStack &item) { Inventory *inv = getInventory(); if (inv) { InventoryList *mlist = inv->getList(getWieldList()); if (mlist) { mlist->changeItem(getWieldIndex(), item); return true; } } return false; } int PlayerSAO::getWieldIndex() const { return m_wield_index; } void PlayerSAO::setWieldIndex(int i) { if(i != m_wield_index) { m_wield_index = i; } } void PlayerSAO::disconnected() { m_peer_id = 0; m_pending_removal = true; } void PlayerSAO::unlinkPlayerSessionAndSave() { assert(m_player->getPlayerSAO() == this); m_player->setPeerId(PEER_ID_INEXISTENT); m_env->savePlayer(m_player); m_player->setPlayerSAO(NULL); m_env->removePlayer(m_player); } std::string PlayerSAO::getPropertyPacket() { m_prop.is_visible = (true); return gob_cmd_set_properties(m_prop); } bool PlayerSAO::checkMovementCheat() { if (isAttached() || m_is_singleplayer || g_settings->getBool("disable_anticheat")) { m_last_good_position = m_base_position; return false; } bool cheated = false; /* Check player movements NOTE: Actually the server should handle player physics like the client does and compare player's position to what is calculated on our side. This is required when eg. players fly due to an explosion. Altough a node-based alternative might be possible too, and much more lightweight. */ float player_max_walk = 0; // horizontal movement float player_max_jump = 0; // vertical upwards movement if (m_privs.count("fast") != 0) player_max_walk = m_player->movement_speed_fast; // Fast speed else player_max_walk = m_player->movement_speed_walk; // Normal speed player_max_walk *= m_physics_override_speed; player_max_jump = m_player->movement_speed_jump * m_physics_override_jump; // FIXME: Bouncy nodes cause practically unbound increase in Y speed, // until this can be verified correctly, tolerate higher jumping speeds player_max_jump *= 2.0; // Don't divide by zero! if (player_max_walk < 0.0001f) player_max_walk = 0.0001f; if (player_max_jump < 0.0001f) player_max_jump = 0.0001f; v3f diff = (m_base_position - m_last_good_position); float d_vert = diff.Y; diff.Y = 0; float d_horiz = diff.getLength(); float required_time = d_horiz / player_max_walk; // FIXME: Checking downwards movement is not easily possible currently, // the server could calculate speed differences to examine the gravity if (d_vert > 0) { // In certain cases (water, ladders) walking speed is applied vertically float s = MYMAX(player_max_jump, player_max_walk); required_time = MYMAX(required_time, d_vert / s); } if (m_move_pool.grab(required_time)) { m_last_good_position = m_base_position; } else { const float LAG_POOL_MIN = 5.0; float lag_pool_max = m_env->getMaxLagEstimate() * 2.0; lag_pool_max = MYMAX(lag_pool_max, LAG_POOL_MIN); if (m_time_from_last_teleport > lag_pool_max) { actionstream << "Player " << m_player->getName() << " moved too fast; resetting position" << std::endl; cheated = true; } setBasePosition(m_last_good_position); } return cheated; } bool PlayerSAO::getCollisionBox(aabb3f *toset) const { //update collision box toset->MinEdge = m_prop.collisionbox.MinEdge * BS; toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS; toset->MinEdge += m_base_position; toset->MaxEdge += m_base_position; return true; } bool PlayerSAO::getSelectionBox(aabb3f *toset) const { if (!m_prop.is_visible || !m_prop.pointable) { return false; } toset->MinEdge = m_prop.selectionbox.MinEdge * BS; toset->MaxEdge = m_prop.selectionbox.MaxEdge * BS; return true; } float PlayerSAO::getZoomFOV() const { return m_prop.zoom_fov; }
pgimeno/minetest
src/content_sao.cpp
C++
mit
41,750
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "network/networkprotocol.h" #include "util/numeric.h" #include "serverobject.h" #include "itemgroup.h" #include "object_properties.h" #include "constants.h" class UnitSAO: public ServerActiveObject { public: UnitSAO(ServerEnvironment *env, v3f pos); virtual ~UnitSAO() = default; void setRotation(v3f rotation) { m_rotation = rotation; } const v3f &getRotation() const { return m_rotation; } v3f getRadRotation() { return m_rotation * core::DEGTORAD; } // Deprecated f32 getRadYawDep() const { return (m_rotation.Y + 90.) * core::DEGTORAD; } u16 getHP() const { return m_hp; } // Use a function, if isDead can be defined by other conditions bool isDead() const { return m_hp == 0; } inline bool isAttached() const { return getParent(); } void setArmorGroups(const ItemGroupList &armor_groups); const ItemGroupList &getArmorGroups(); void setAnimation(v2f frame_range, float frame_speed, float frame_blend, bool frame_loop); void getAnimation(v2f *frame_range, float *frame_speed, float *frame_blend, bool *frame_loop); void setAnimationSpeed(float frame_speed); void setBonePosition(const std::string &bone, v3f position, v3f rotation); void getBonePosition(const std::string &bone, v3f *position, v3f *rotation); void setAttachment(int parent_id, const std::string &bone, v3f position, v3f rotation); void getAttachment(int *parent_id, std::string *bone, v3f *position, v3f *rotation); void clearChildAttachments(); void clearParentAttachment(); void addAttachmentChild(int child_id); void removeAttachmentChild(int child_id); const std::unordered_set<int> &getAttachmentChildIds(); ServerActiveObject *getParent() const; ObjectProperties* accessObjectProperties(); void notifyObjectPropertiesModified(); protected: u16 m_hp = 1; v3f m_rotation; bool m_properties_sent = true; ObjectProperties m_prop; ItemGroupList m_armor_groups; bool m_armor_groups_sent = false; v2f m_animation_range; float m_animation_speed = 0.0f; float m_animation_blend = 0.0f; bool m_animation_loop = true; bool m_animation_sent = false; bool m_animation_speed_sent = false; // Stores position and rotation for each bone name std::unordered_map<std::string, core::vector2d<v3f>> m_bone_position; bool m_bone_position_sent = false; int m_attachment_parent_id = 0; std::unordered_set<int> m_attachment_child_ids; std::string m_attachment_bone = ""; v3f m_attachment_position; v3f m_attachment_rotation; bool m_attachment_sent = false; private: void onAttach(int parent_id); void onDetach(int parent_id); }; /* LuaEntitySAO needs some internals exposed. */ class LuaEntitySAO : public UnitSAO { public: LuaEntitySAO(ServerEnvironment *env, v3f pos, const std::string &name, const std::string &state); ~LuaEntitySAO(); ActiveObjectType getType() const { return ACTIVEOBJECT_TYPE_LUAENTITY; } ActiveObjectType getSendType() const { return ACTIVEOBJECT_TYPE_GENERIC; } virtual void addedToEnvironment(u32 dtime_s); static ServerActiveObject* create(ServerEnvironment *env, v3f pos, const std::string &data); void step(float dtime, bool send_recommended); std::string getClientInitializationData(u16 protocol_version); bool isStaticAllowed() const { return m_prop.static_save; } void getStaticData(std::string *result) const; int punch(v3f dir, const ToolCapabilities *toolcap=NULL, ServerActiveObject *puncher=NULL, float time_from_last_punch=1000000); void rightClick(ServerActiveObject *clicker); void setPos(const v3f &pos); void moveTo(v3f pos, bool continuous); float getMinimumSavedMovement(); std::string getDescription(); void setHP(s32 hp, const PlayerHPChangeReason &reason); u16 getHP() const; /* LuaEntitySAO-specific */ void setVelocity(v3f velocity); void addVelocity(v3f velocity) { m_velocity += velocity; } v3f getVelocity(); void setAcceleration(v3f acceleration); v3f getAcceleration(); void setTextureMod(const std::string &mod); std::string getTextureMod() const; void setSprite(v2s16 p, int num_frames, float framelength, bool select_horiz_by_yawpitch); std::string getName(); bool getCollisionBox(aabb3f *toset) const; bool getSelectionBox(aabb3f *toset) const; bool collideWithObjects() const; private: std::string getPropertyPacket(); void sendPosition(bool do_interpolate, bool is_movement_end); std::string m_init_name; std::string m_init_state; bool m_registered = false; v3f m_velocity; v3f m_acceleration; v3f m_last_sent_position; v3f m_last_sent_velocity; v3f m_last_sent_rotation; float m_last_sent_position_timer = 0.0f; float m_last_sent_move_precision = 0.0f; std::string m_current_texture_modifier = ""; }; /* PlayerSAO needs some internals exposed. */ class LagPool { float m_pool = 15.0f; float m_max = 15.0f; public: LagPool() = default; void setMax(float new_max) { m_max = new_max; if(m_pool > new_max) m_pool = new_max; } void add(float dtime) { m_pool -= dtime; if(m_pool < 0) m_pool = 0; } void empty() { m_pool = m_max; } bool grab(float dtime) { if(dtime <= 0) return true; if(m_pool + dtime > m_max) return false; m_pool += dtime; return true; } }; class RemotePlayer; class PlayerSAO : public UnitSAO { public: PlayerSAO(ServerEnvironment *env_, RemotePlayer *player_, session_t peer_id_, bool is_singleplayer); ~PlayerSAO(); ActiveObjectType getType() const { return ACTIVEOBJECT_TYPE_PLAYER; } ActiveObjectType getSendType() const { return ACTIVEOBJECT_TYPE_GENERIC; } std::string getDescription(); /* Active object <-> environment interface */ void addedToEnvironment(u32 dtime_s); void removingFromEnvironment(); bool isStaticAllowed() const { return false; } std::string getClientInitializationData(u16 protocol_version); void getStaticData(std::string *result) const; void step(float dtime, bool send_recommended); void setBasePosition(const v3f &position); void setPos(const v3f &pos); void moveTo(v3f pos, bool continuous); void setPlayerYaw(const float yaw); // Data should not be sent at player initialization void setPlayerYawAndSend(const float yaw); void setLookPitch(const float pitch); // Data should not be sent at player initialization void setLookPitchAndSend(const float pitch); f32 getLookPitch() const { return m_pitch; } f32 getRadLookPitch() const { return m_pitch * core::DEGTORAD; } // Deprecated f32 getRadLookPitchDep() const { return -1.0 * m_pitch * core::DEGTORAD; } void setFov(const float pitch); f32 getFov() const { return m_fov; } void setWantedRange(const s16 range); s16 getWantedRange() const { return m_wanted_range; } /* Interaction interface */ int punch(v3f dir, const ToolCapabilities *toolcap, ServerActiveObject *puncher, float time_from_last_punch); void rightClick(ServerActiveObject *clicker) {} void setHP(s32 hp, const PlayerHPChangeReason &reason); void setHPRaw(u16 hp) { m_hp = hp; } s16 readDamage(); u16 getBreath() const { return m_breath; } void setBreath(const u16 breath, bool send = true); /* Inventory interface */ Inventory* getInventory(); const Inventory* getInventory() const; InventoryLocation getInventoryLocation() const; std::string getWieldList() const; ItemStack getWieldedItem() const; ItemStack getWieldedItemOrHand() const; bool setWieldedItem(const ItemStack &item); int getWieldIndex() const; void setWieldIndex(int i); /* PlayerSAO-specific */ void disconnected(); RemotePlayer *getPlayer() { return m_player; } session_t getPeerID() const { return m_peer_id; } // Cheat prevention v3f getLastGoodPosition() const { return m_last_good_position; } float resetTimeFromLastPunch() { float r = m_time_from_last_punch; m_time_from_last_punch = 0.0; return r; } void noCheatDigStart(const v3s16 &p) { m_nocheat_dig_pos = p; m_nocheat_dig_time = 0; } v3s16 getNoCheatDigPos() { return m_nocheat_dig_pos; } float getNoCheatDigTime() { return m_nocheat_dig_time; } void noCheatDigEnd() { m_nocheat_dig_pos = v3s16(32767, 32767, 32767); } LagPool& getDigPool() { return m_dig_pool; } // Returns true if cheated bool checkMovementCheat(); // Other void updatePrivileges(const std::set<std::string> &privs, bool is_singleplayer) { m_privs = privs; m_is_singleplayer = is_singleplayer; } bool getCollisionBox(aabb3f *toset) const; bool getSelectionBox(aabb3f *toset) const; bool collideWithObjects() const { return true; } void finalize(RemotePlayer *player, const std::set<std::string> &privs); v3f getEyePosition() const { return m_base_position + getEyeOffset(); } v3f getEyeOffset() const; float getZoomFOV() const; inline Metadata &getMeta() { return m_meta; } private: std::string getPropertyPacket(); void unlinkPlayerSessionAndSave(); RemotePlayer *m_player = nullptr; session_t m_peer_id = 0; Inventory *m_inventory = nullptr; // Cheat prevention LagPool m_dig_pool; LagPool m_move_pool; v3f m_last_good_position; float m_time_from_last_teleport = 0.0f; float m_time_from_last_punch = 0.0f; v3s16 m_nocheat_dig_pos = v3s16(32767, 32767, 32767); float m_nocheat_dig_time = 0.0f; // Timers IntervalLimiter m_breathing_interval; IntervalLimiter m_drowning_interval; IntervalLimiter m_node_hurt_interval; int m_wield_index = 0; bool m_position_not_sent = false; // Cached privileges for enforcement std::set<std::string> m_privs; bool m_is_singleplayer; u16 m_breath = PLAYER_MAX_BREATH_DEFAULT; f32 m_pitch = 0.0f; f32 m_fov = 0.0f; s16 m_wanted_range = 0.0f; Metadata m_meta; public: float m_physics_override_speed = 1.0f; float m_physics_override_jump = 1.0f; float m_physics_override_gravity = 1.0f; bool m_physics_override_sneak = true; bool m_physics_override_sneak_glitch = false; bool m_physics_override_new_move = true; bool m_physics_override_sent = false; }; struct PlayerHPChangeReason { enum Type : u8 { SET_HP, PLAYER_PUNCH, FALL, NODE_DAMAGE, DROWNING, RESPAWN }; Type type = SET_HP; ServerActiveObject *object; bool from_mod = false; int lua_reference = -1; inline bool hasLuaReference() const { return lua_reference >= 0; } bool setTypeFromString(const std::string &typestr) { if (typestr == "set_hp") type = SET_HP; else if (typestr == "punch") type = PLAYER_PUNCH; else if (typestr == "fall") type = FALL; else if (typestr == "node_damage") type = NODE_DAMAGE; else if (typestr == "drown") type = DROWNING; else if (typestr == "respawn") type = RESPAWN; else return false; return true; } std::string getTypeAsString() const { switch (type) { case PlayerHPChangeReason::SET_HP: return "set_hp"; case PlayerHPChangeReason::PLAYER_PUNCH: return "punch"; case PlayerHPChangeReason::FALL: return "fall"; case PlayerHPChangeReason::NODE_DAMAGE: return "node_damage"; case PlayerHPChangeReason::DROWNING: return "drown"; case PlayerHPChangeReason::RESPAWN: return "respawn"; default: return "?"; } } PlayerHPChangeReason(Type type, ServerActiveObject *object=NULL): type(type), object(object) {} };
pgimeno/minetest
src/content_sao.h
C++
mit
11,932
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <vector> #include <iostream> #include <sstream> #include "convert_json.h" #include "content/mods.h" #include "config.h" #include "log.h" #include "settings.h" #include "httpfetch.h" #include "porting.h" Json::Value fetchJsonValue(const std::string &url, std::vector<std::string> *extra_headers) { HTTPFetchRequest fetch_request; HTTPFetchResult fetch_result; fetch_request.url = url; fetch_request.caller = HTTPFETCH_SYNC; if (extra_headers != NULL) fetch_request.extra_headers = *extra_headers; httpfetch_sync(fetch_request, fetch_result); if (!fetch_result.succeeded) { return Json::Value(); } Json::Value root; std::istringstream stream(fetch_result.data); Json::CharReaderBuilder builder; builder.settings_["collectComments"] = false; std::string errs; if (!Json::parseFromStream(builder, stream, &root, &errs)) { errorstream << "URL: " << url << std::endl; errorstream << "Failed to parse json data " << errs << std::endl; if (fetch_result.data.size() > 100) { errorstream << "Data (" << fetch_result.data.size() << " bytes) printed to warningstream." << std::endl; warningstream << "data: \"" << fetch_result.data << "\"" << std::endl; } else { errorstream << "data: \"" << fetch_result.data << "\"" << std::endl; } return Json::Value(); } return root; } std::string fastWriteJson(const Json::Value &value) { std::ostringstream oss; Json::StreamWriterBuilder builder; builder["indentation"] = ""; std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter()); writer->write(value, &oss); return oss.str(); }
pgimeno/minetest
src/convert_json.cpp
C++
mit
2,378
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <json/json.h> Json::Value fetchJsonValue(const std::string &url, std::vector<std::string> *extra_headers); std::string fastWriteJson(const Json::Value &value);
pgimeno/minetest
src/convert_json.h
C++
mit
972
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "craftdef.h" #include "irrlichttypes.h" #include "log.h" #include <sstream> #include <set> #include <algorithm> #include "gamedef.h" #include "inventory.h" #include "util/serialize.h" #include "util/string.h" #include "util/numeric.h" #include "util/strfnd.h" #include "exceptions.h" inline bool isGroupRecipeStr(const std::string &rec_name) { return str_starts_with(rec_name, std::string("group:")); } inline u64 getHashForString(const std::string &recipe_str) { /*errorstream << "Hashing craft string \"" << recipe_str << '"';*/ return murmur_hash_64_ua(recipe_str.data(), recipe_str.length(), 0xdeadbeef); } static u64 getHashForGrid(CraftHashType type, const std::vector<std::string> &grid_names) { switch (type) { case CRAFT_HASH_TYPE_ITEM_NAMES: { std::ostringstream os; bool is_first = true; for (const std::string &grid_name : grid_names) { if (!grid_name.empty()) { os << (is_first ? "" : "\n") << grid_name; is_first = false; } } return getHashForString(os.str()); } case CRAFT_HASH_TYPE_COUNT: { u64 cnt = 0; for (const std::string &grid_name : grid_names) if (!grid_name.empty()) cnt++; return cnt; } case CRAFT_HASH_TYPE_UNHASHED: return 0; } // invalid CraftHashType assert(false); return 0; } // Check if input matches recipe // Takes recipe groups into account static bool inputItemMatchesRecipe(const std::string &inp_name, const std::string &rec_name, IItemDefManager *idef) { // Exact name if (inp_name == rec_name) return true; // Group if (isGroupRecipeStr(rec_name) && idef->isKnown(inp_name)) { const struct ItemDefinition &def = idef->get(inp_name); Strfnd f(rec_name.substr(6)); bool all_groups_match = true; do { std::string check_group = f.next(","); if (itemgroup_get(def.groups, check_group) == 0) { all_groups_match = false; break; } } while (!f.at_end()); if (all_groups_match) return true; } // Didn't match return false; } // Deserialize an itemstring then return the name of the item static std::string craftGetItemName(const std::string &itemstring, IGameDef *gamedef) { ItemStack item; item.deSerialize(itemstring, gamedef->idef()); return item.name; } // (mapcar craftGetItemName itemstrings) static std::vector<std::string> craftGetItemNames( const std::vector<std::string> &itemstrings, IGameDef *gamedef) { std::vector<std::string> result; result.reserve(itemstrings.size()); for (const auto &itemstring : itemstrings) { result.push_back(craftGetItemName(itemstring, gamedef)); } return result; } // Get name of each item, and return them as a new list. static std::vector<std::string> craftGetItemNames( const std::vector<ItemStack> &items, IGameDef *gamedef) { std::vector<std::string> result; result.reserve(items.size()); for (const auto &item : items) { result.push_back(item.name); } return result; } // convert a list of item names, to ItemStacks. static std::vector<ItemStack> craftGetItems( const std::vector<std::string> &items, IGameDef *gamedef) { std::vector<ItemStack> result; result.reserve(items.size()); for (const auto &item : items) { result.emplace_back(std::string(item), (u16)1, (u16)0, gamedef->getItemDefManager()); } return result; } // Compute bounding rectangle given a matrix of items // Returns false if every item is "" static bool craftGetBounds(const std::vector<std::string> &items, unsigned int width, unsigned int &min_x, unsigned int &max_x, unsigned int &min_y, unsigned int &max_y) { bool success = false; unsigned int x = 0; unsigned int y = 0; for (const std::string &item : items) { // Is this an actual item? if (!item.empty()) { if (!success) { // This is the first nonempty item min_x = max_x = x; min_y = max_y = y; success = true; } else { if (x < min_x) min_x = x; if (x > max_x) max_x = x; if (y < min_y) min_y = y; if (y > max_y) max_y = y; } } // Step coordinate x++; if (x == width) { x = 0; y++; } } return success; } // Removes 1 from each item stack static void craftDecrementInput(CraftInput &input, IGameDef *gamedef) { for (auto &item : input.items) { if (item.count != 0) item.remove(1); } } // Removes 1 from each item stack with replacement support // Example: if replacements contains the pair ("bucket:bucket_water", "bucket:bucket_empty"), // a water bucket will not be removed but replaced by an empty bucket. static void craftDecrementOrReplaceInput(CraftInput &input, std::vector<ItemStack> &output_replacements, const CraftReplacements &replacements, IGameDef *gamedef) { if (replacements.pairs.empty()) { craftDecrementInput(input, gamedef); return; } // Make a copy of the replacements pair list std::vector<std::pair<std::string, std::string> > pairs = replacements.pairs; for (auto &item : input.items) { // Find an appropriate replacement bool found_replacement = false; for (auto j = pairs.begin(); j != pairs.end(); ++j) { if (inputItemMatchesRecipe(item.name, j->first, gamedef->idef())) { if (item.count == 1) { item.deSerialize(j->second, gamedef->idef()); found_replacement = true; pairs.erase(j); break; } ItemStack rep; rep.deSerialize(j->second, gamedef->idef()); item.remove(1); found_replacement = true; output_replacements.push_back(rep); break; } } // No replacement was found, simply decrement count by one if (!found_replacement && item.count > 0) item.remove(1); } } // Dump an itemstring matrix static std::string craftDumpMatrix(const std::vector<std::string> &items, unsigned int width) { std::ostringstream os(std::ios::binary); os << "{ "; unsigned int x = 0; for(std::vector<std::string>::size_type i = 0; i < items.size(); i++, x++) { if (x == width) { os << "; "; x = 0; } else if (x != 0) { os << ","; } os << '"' << items[i] << '"'; } os << " }"; return os.str(); } // Dump an item matrix std::string craftDumpMatrix(const std::vector<ItemStack> &items, unsigned int width) { std::ostringstream os(std::ios::binary); os << "{ "; unsigned int x = 0; for (std::vector<ItemStack>::size_type i = 0; i < items.size(); i++, x++) { if (x == width) { os << "; "; x = 0; } else if (x != 0) { os << ","; } os << '"' << (items[i].getItemString()) << '"'; } os << " }"; return os.str(); } /* CraftInput */ std::string CraftInput::dump() const { std::ostringstream os(std::ios::binary); os << "(method=" << ((int)method) << ", items=" << craftDumpMatrix(items, width) << ")"; return os.str(); } /* CraftOutput */ std::string CraftOutput::dump() const { std::ostringstream os(std::ios::binary); os << "(item=\"" << item << "\", time=" << time << ")"; return os.str(); } /* CraftReplacements */ std::string CraftReplacements::dump() const { std::ostringstream os(std::ios::binary); os<<"{"; const char *sep = ""; for (const auto &repl_p : pairs) { os << sep << '"' << (repl_p.first) << "\"=>\"" << (repl_p.second) << '"'; sep = ","; } os << "}"; return os.str(); } /* CraftDefinitionShaped */ std::string CraftDefinitionShaped::getName() const { return "shaped"; } bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) const { if (input.method != CRAFT_METHOD_NORMAL) return false; // Get input item matrix std::vector<std::string> inp_names = craftGetItemNames(input.items, gamedef); unsigned int inp_width = input.width; if (inp_width == 0) return false; while (inp_names.size() % inp_width != 0) inp_names.emplace_back(""); // Get input bounds unsigned int inp_min_x = 0, inp_max_x = 0, inp_min_y = 0, inp_max_y = 0; if (!craftGetBounds(inp_names, inp_width, inp_min_x, inp_max_x, inp_min_y, inp_max_y)) return false; // it was empty std::vector<std::string> rec_names; if (hash_inited) rec_names = recipe_names; else rec_names = craftGetItemNames(recipe, gamedef); // Get recipe item matrix unsigned int rec_width = width; if (rec_width == 0) return false; while (rec_names.size() % rec_width != 0) rec_names.emplace_back(""); // Get recipe bounds unsigned int rec_min_x=0, rec_max_x=0, rec_min_y=0, rec_max_y=0; if (!craftGetBounds(rec_names, rec_width, rec_min_x, rec_max_x, rec_min_y, rec_max_y)) return false; // it was empty // Different sizes? if (inp_max_x - inp_min_x != rec_max_x - rec_min_x || inp_max_y - inp_min_y != rec_max_y - rec_min_y) return false; // Verify that all item names in the bounding box are equal unsigned int w = inp_max_x - inp_min_x + 1; unsigned int h = inp_max_y - inp_min_y + 1; for (unsigned int y=0; y < h; y++) { unsigned int inp_y = (inp_min_y + y) * inp_width; unsigned int rec_y = (rec_min_y + y) * rec_width; for (unsigned int x=0; x < w; x++) { unsigned int inp_x = inp_min_x + x; unsigned int rec_x = rec_min_x + x; if (!inputItemMatchesRecipe( inp_names[inp_y + inp_x], rec_names[rec_y + rec_x], gamedef->idef())) { return false; } } } return true; } CraftOutput CraftDefinitionShaped::getOutput(const CraftInput &input, IGameDef *gamedef) const { return CraftOutput(output, 0); } CraftInput CraftDefinitionShaped::getInput(const CraftOutput &output, IGameDef *gamedef) const { return CraftInput(CRAFT_METHOD_NORMAL,width,craftGetItems(recipe,gamedef)); } void CraftDefinitionShaped::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements, IGameDef *gamedef) const { craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef); } CraftHashType CraftDefinitionShaped::getHashType() const { assert(hash_inited); // Pre-condition bool has_group = false; for (const auto &recipe_name : recipe_names) { if (isGroupRecipeStr(recipe_name)) { has_group = true; break; } } if (has_group) return CRAFT_HASH_TYPE_COUNT; return CRAFT_HASH_TYPE_ITEM_NAMES; } u64 CraftDefinitionShaped::getHash(CraftHashType type) const { assert(hash_inited); // Pre-condition assert((type == CRAFT_HASH_TYPE_ITEM_NAMES) || (type == CRAFT_HASH_TYPE_COUNT)); // Pre-condition std::vector<std::string> rec_names = recipe_names; std::sort(rec_names.begin(), rec_names.end()); return getHashForGrid(type, rec_names); } void CraftDefinitionShaped::initHash(IGameDef *gamedef) { if (hash_inited) return; hash_inited = true; recipe_names = craftGetItemNames(recipe, gamedef); } std::string CraftDefinitionShaped::dump() const { std::ostringstream os(std::ios::binary); os << "(shaped, output=\"" << output << "\", recipe=" << craftDumpMatrix(recipe, width) << ", replacements=" << replacements.dump() << ")"; return os.str(); } /* CraftDefinitionShapeless */ std::string CraftDefinitionShapeless::getName() const { return "shapeless"; } bool CraftDefinitionShapeless::check(const CraftInput &input, IGameDef *gamedef) const { if (input.method != CRAFT_METHOD_NORMAL) return false; // Filter empty items out of input std::vector<std::string> input_filtered; for (const auto &item : input.items) { if (!item.name.empty()) input_filtered.push_back(item.name); } // If there is a wrong number of items in input, no match if (input_filtered.size() != recipe.size()) { /*dstream<<"Number of input items ("<<input_filtered.size() <<") does not match recipe size ("<<recipe.size()<<") " <<"of recipe with output="<<output<<std::endl;*/ return false; } std::vector<std::string> recipe_copy; if (hash_inited) recipe_copy = recipe_names; else { recipe_copy = craftGetItemNames(recipe, gamedef); std::sort(recipe_copy.begin(), recipe_copy.end()); } // Try with all permutations of the recipe, // start from the lexicographically first permutation (=sorted), // recipe_names is pre-sorted do { // If all items match, the recipe matches bool all_match = true; //dstream<<"Testing recipe (output="<<output<<"):"; for (size_t i=0; i<recipe.size(); i++) { //dstream<<" ("<<input_filtered[i]<<" == "<<recipe_copy[i]<<")"; if (!inputItemMatchesRecipe(input_filtered[i], recipe_copy[i], gamedef->idef())) { all_match = false; break; } } //dstream<<" -> match="<<all_match<<std::endl; if (all_match) return true; } while (std::next_permutation(recipe_copy.begin(), recipe_copy.end())); return false; } CraftOutput CraftDefinitionShapeless::getOutput(const CraftInput &input, IGameDef *gamedef) const { return CraftOutput(output, 0); } CraftInput CraftDefinitionShapeless::getInput(const CraftOutput &output, IGameDef *gamedef) const { return CraftInput(CRAFT_METHOD_NORMAL, 0, craftGetItems(recipe, gamedef)); } void CraftDefinitionShapeless::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements, IGameDef *gamedef) const { craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef); } CraftHashType CraftDefinitionShapeless::getHashType() const { assert(hash_inited); // Pre-condition bool has_group = false; for (const auto &recipe_name : recipe_names) { if (isGroupRecipeStr(recipe_name)) { has_group = true; break; } } if (has_group) return CRAFT_HASH_TYPE_COUNT; return CRAFT_HASH_TYPE_ITEM_NAMES; } u64 CraftDefinitionShapeless::getHash(CraftHashType type) const { assert(hash_inited); // Pre-condition assert(type == CRAFT_HASH_TYPE_ITEM_NAMES || type == CRAFT_HASH_TYPE_COUNT); // Pre-condition return getHashForGrid(type, recipe_names); } void CraftDefinitionShapeless::initHash(IGameDef *gamedef) { if (hash_inited) return; hash_inited = true; recipe_names = craftGetItemNames(recipe, gamedef); std::sort(recipe_names.begin(), recipe_names.end()); } std::string CraftDefinitionShapeless::dump() const { std::ostringstream os(std::ios::binary); os << "(shapeless, output=\"" << output << "\", recipe=" << craftDumpMatrix(recipe, recipe.size()) << ", replacements=" << replacements.dump() << ")"; return os.str(); } /* CraftDefinitionToolRepair */ static ItemStack craftToolRepair( const ItemStack &item1, const ItemStack &item2, float additional_wear, IGameDef *gamedef) { IItemDefManager *idef = gamedef->idef(); if (item1.count != 1 || item2.count != 1 || item1.name != item2.name || idef->get(item1.name).type != ITEM_TOOL || itemgroup_get(idef->get(item1.name).groups, "disable_repair") == 1) { // Failure return ItemStack(); } s32 item1_uses = 65536 - (u32) item1.wear; s32 item2_uses = 65536 - (u32) item2.wear; s32 new_uses = item1_uses + item2_uses; s32 new_wear = 65536 - new_uses + floor(additional_wear * 65536 + 0.5); if (new_wear >= 65536) return ItemStack(); if (new_wear < 0) new_wear = 0; ItemStack repaired = item1; repaired.wear = new_wear; return repaired; } std::string CraftDefinitionToolRepair::getName() const { return "toolrepair"; } bool CraftDefinitionToolRepair::check(const CraftInput &input, IGameDef *gamedef) const { if (input.method != CRAFT_METHOD_NORMAL) return false; ItemStack item1; ItemStack item2; for (const auto &item : input.items) { if (!item.empty()) { if (item1.empty()) item1 = item; else if (item2.empty()) item2 = item; else return false; } } ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef); return !repaired.empty(); } CraftOutput CraftDefinitionToolRepair::getOutput(const CraftInput &input, IGameDef *gamedef) const { ItemStack item1; ItemStack item2; for (const auto &item : input.items) { if (!item.empty()) { if (item1.empty()) item1 = item; else if (item2.empty()) item2 = item; } } ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef); return CraftOutput(repaired.getItemString(), 0); } CraftInput CraftDefinitionToolRepair::getInput(const CraftOutput &output, IGameDef *gamedef) const { std::vector<ItemStack> stack; stack.emplace_back(); return CraftInput(CRAFT_METHOD_COOKING, additional_wear, stack); } void CraftDefinitionToolRepair::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements, IGameDef *gamedef) const { craftDecrementInput(input, gamedef); } std::string CraftDefinitionToolRepair::dump() const { std::ostringstream os(std::ios::binary); os << "(toolrepair, additional_wear=" << additional_wear << ")"; return os.str(); } /* CraftDefinitionCooking */ std::string CraftDefinitionCooking::getName() const { return "cooking"; } bool CraftDefinitionCooking::check(const CraftInput &input, IGameDef *gamedef) const { if (input.method != CRAFT_METHOD_COOKING) return false; // Filter empty items out of input std::vector<std::string> input_filtered; for (const auto &item : input.items) { const std::string &name = item.name; if (!name.empty()) input_filtered.push_back(name); } // If there is a wrong number of items in input, no match if (input_filtered.size() != 1) { /*dstream<<"Number of input items ("<<input_filtered.size() <<") does not match recipe size (1) " <<"of cooking recipe with output="<<output<<std::endl;*/ return false; } // Check the single input item return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef()); } CraftOutput CraftDefinitionCooking::getOutput(const CraftInput &input, IGameDef *gamedef) const { return CraftOutput(output, cooktime); } CraftInput CraftDefinitionCooking::getInput(const CraftOutput &output, IGameDef *gamedef) const { std::vector<std::string> rec; rec.push_back(recipe); return CraftInput(CRAFT_METHOD_COOKING,cooktime,craftGetItems(rec,gamedef)); } void CraftDefinitionCooking::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements, IGameDef *gamedef) const { craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef); } CraftHashType CraftDefinitionCooking::getHashType() const { if (isGroupRecipeStr(recipe_name)) return CRAFT_HASH_TYPE_COUNT; return CRAFT_HASH_TYPE_ITEM_NAMES; } u64 CraftDefinitionCooking::getHash(CraftHashType type) const { if (type == CRAFT_HASH_TYPE_ITEM_NAMES) { return getHashForString(recipe_name); } if (type == CRAFT_HASH_TYPE_COUNT) { return 1; } // illegal hash type for this CraftDefinition (pre-condition) assert(false); return 0; } void CraftDefinitionCooking::initHash(IGameDef *gamedef) { if (hash_inited) return; hash_inited = true; recipe_name = craftGetItemName(recipe, gamedef); } std::string CraftDefinitionCooking::dump() const { std::ostringstream os(std::ios::binary); os << "(cooking, output=\"" << output << "\", recipe=\"" << recipe << "\", cooktime=" << cooktime << ")" << ", replacements=" << replacements.dump() << ")"; return os.str(); } /* CraftDefinitionFuel */ std::string CraftDefinitionFuel::getName() const { return "fuel"; } bool CraftDefinitionFuel::check(const CraftInput &input, IGameDef *gamedef) const { if (input.method != CRAFT_METHOD_FUEL) return false; // Filter empty items out of input std::vector<std::string> input_filtered; for (const auto &item : input.items) { const std::string &name = item.name; if (!name.empty()) input_filtered.push_back(name); } // If there is a wrong number of items in input, no match if (input_filtered.size() != 1) { /*dstream<<"Number of input items ("<<input_filtered.size() <<") does not match recipe size (1) " <<"of fuel recipe with burntime="<<burntime<<std::endl;*/ return false; } // Check the single input item return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef()); } CraftOutput CraftDefinitionFuel::getOutput(const CraftInput &input, IGameDef *gamedef) const { return CraftOutput("", burntime); } CraftInput CraftDefinitionFuel::getInput(const CraftOutput &output, IGameDef *gamedef) const { std::vector<std::string> rec; rec.push_back(recipe); return CraftInput(CRAFT_METHOD_COOKING,(int)burntime,craftGetItems(rec,gamedef)); } void CraftDefinitionFuel::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements, IGameDef *gamedef) const { craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef); } CraftHashType CraftDefinitionFuel::getHashType() const { if (isGroupRecipeStr(recipe_name)) return CRAFT_HASH_TYPE_COUNT; return CRAFT_HASH_TYPE_ITEM_NAMES; } u64 CraftDefinitionFuel::getHash(CraftHashType type) const { if (type == CRAFT_HASH_TYPE_ITEM_NAMES) { return getHashForString(recipe_name); } if (type == CRAFT_HASH_TYPE_COUNT) { return 1; } // illegal hash type for this CraftDefinition (pre-condition) assert(false); return 0; } void CraftDefinitionFuel::initHash(IGameDef *gamedef) { if (hash_inited) return; hash_inited = true; recipe_name = craftGetItemName(recipe, gamedef); } std::string CraftDefinitionFuel::dump() const { std::ostringstream os(std::ios::binary); os << "(fuel, recipe=\"" << recipe << "\", burntime=" << burntime << ")" << ", replacements=" << replacements.dump() << ")"; return os.str(); } /* Craft definition manager */ class CCraftDefManager: public IWritableCraftDefManager { public: CCraftDefManager() { m_craft_defs.resize(craft_hash_type_max + 1); } virtual ~CCraftDefManager() { clear(); } virtual bool getCraftResult(CraftInput &input, CraftOutput &output, std::vector<ItemStack> &output_replacement, bool decrementInput, IGameDef *gamedef) const { output.item = ""; output.time = 0; // If all input items are empty, abort. bool all_empty = true; for (const auto &item : input.items) { if (!item.empty()) { all_empty = false; break; } } if (all_empty) return false; std::vector<std::string> input_names; input_names = craftGetItemNames(input.items, gamedef); std::sort(input_names.begin(), input_names.end()); // Try hash types with increasing collision rate, and return if found. for (int type = 0; type <= craft_hash_type_max; type++) { u64 hash = getHashForGrid((CraftHashType) type, input_names); /*errorstream << "Checking type " << type << " with hash " << hash << std::endl;*/ // We'd like to do "const [...] hash_collisions = m_craft_defs[type][hash];" // but that doesn't compile for some reason. This does. auto col_iter = (m_craft_defs[type]).find(hash); if (col_iter == (m_craft_defs[type]).end()) continue; const std::vector<CraftDefinition*> &hash_collisions = col_iter->second; // Walk crafting definitions from back to front, so that later // definitions can override earlier ones. for (std::vector<CraftDefinition*>::size_type i = hash_collisions.size(); i > 0; i--) { CraftDefinition *def = hash_collisions[i - 1]; /*errorstream << "Checking " << input.dump() << std::endl << " against " << def->dump() << std::endl;*/ if (def->check(input, gamedef)) { // Check if the crafted node/item exists CraftOutput out = def->getOutput(input, gamedef); ItemStack is; is.deSerialize(out.item, gamedef->idef()); if (!is.isKnown(gamedef->idef())) { infostream << "trying to craft non-existent " << out.item << ", ignoring recipe" << std::endl; continue; } // Get output, then decrement input (if requested) output = out; if (decrementInput) def->decrementInput(input, output_replacement, gamedef); /*errorstream << "Check RETURNS TRUE" << std::endl;*/ return true; } } } return false; } virtual std::vector<CraftDefinition*> getCraftRecipes(CraftOutput &output, IGameDef *gamedef, unsigned limit=0) const { std::vector<CraftDefinition*> recipes; auto vec_iter = m_output_craft_definitions.find(output.item); if (vec_iter == m_output_craft_definitions.end()) return recipes; const std::vector<CraftDefinition*> &vec = vec_iter->second; recipes.reserve(limit ? MYMIN(limit, vec.size()) : vec.size()); for (std::vector<CraftDefinition*>::size_type i = vec.size(); i > 0; i--) { CraftDefinition *def = vec[i - 1]; if (limit && recipes.size() >= limit) break; recipes.push_back(def); } return recipes; } virtual bool clearCraftRecipesByOutput(const CraftOutput &output, IGameDef *gamedef) { auto vec_iter = m_output_craft_definitions.find(output.item); if (vec_iter == m_output_craft_definitions.end()) return false; std::vector<CraftDefinition*> &vec = vec_iter->second; for (auto def : vec) { // Recipes are not yet hashed at this point std::vector<CraftDefinition*> &unhashed_inputs_vec = m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0]; std::vector<CraftDefinition*> new_vec_by_input; /* We will preallocate necessary memory addresses, so we don't need to reallocate them later. This would save us some performance. */ new_vec_by_input.reserve(unhashed_inputs_vec.size()); for (auto &i2 : unhashed_inputs_vec) { if (def != i2) { new_vec_by_input.push_back(i2); } } m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].swap(new_vec_by_input); } m_output_craft_definitions.erase(output.item); return true; } virtual bool clearCraftRecipesByInput(CraftMethod craft_method, unsigned int craft_grid_width, const std::vector<std::string> &recipe, IGameDef *gamedef) { bool all_empty = true; for (const auto &i : recipe) { if (!i.empty()) { all_empty = false; break; } } if (all_empty) return false; CraftInput input(craft_method, craft_grid_width, craftGetItems(recipe, gamedef)); // Recipes are not yet hashed at this point std::vector<CraftDefinition*> &unhashed_inputs_vec = m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0]; std::vector<CraftDefinition*> new_vec_by_input; bool got_hit = false; for (std::vector<CraftDefinition*>::size_type i = unhashed_inputs_vec.size(); i > 0; i--) { CraftDefinition *def = unhashed_inputs_vec[i - 1]; /* If the input doesn't match the recipe definition, this recipe definition later will be added back in source map. */ if (!def->check(input, gamedef)) { new_vec_by_input.push_back(def); continue; } CraftOutput output = def->getOutput(input, gamedef); got_hit = true; auto vec_iter = m_output_craft_definitions.find(output.item); if (vec_iter == m_output_craft_definitions.end()) continue; std::vector<CraftDefinition*> &vec = vec_iter->second; std::vector<CraftDefinition*> new_vec_by_output; /* We will preallocate necessary memory addresses, so we don't need to reallocate them later. This would save us some performance. */ new_vec_by_output.reserve(vec.size()); for (auto &vec_i : vec) { /* If pointers from map by input and output are not same, we will add 'CraftDefinition*' to a new vector. */ if (def != vec_i) { /* Adding dereferenced iterator value (which are 'CraftDefinition' reference) to a new vector. */ new_vec_by_output.push_back(vec_i); } } // Swaps assigned to current key value with new vector for output map. m_output_craft_definitions[output.item].swap(new_vec_by_output); } if (got_hit) // Swaps value with new vector for input map. m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].swap(new_vec_by_input); return got_hit; } virtual std::string dump() const { std::ostringstream os(std::ios::binary); os << "Crafting definitions:\n"; for (int type = 0; type <= craft_hash_type_max; ++type) { for (auto it = m_craft_defs[type].begin(); it != m_craft_defs[type].end(); ++it) { for (std::vector<CraftDefinition*>::size_type i = 0; i < it->second.size(); i++) { os << "type " << type << " hash " << it->first << " def " << it->second[i]->dump() << "\n"; } } } return os.str(); } virtual void registerCraft(CraftDefinition *def, IGameDef *gamedef) { verbosestream << "registerCraft: registering craft definition: " << def->dump() << std::endl; m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].push_back(def); CraftInput input; std::string output_name = craftGetItemName( def->getOutput(input, gamedef).item, gamedef); m_output_craft_definitions[output_name].push_back(def); } virtual void clear() { for (int type = 0; type <= craft_hash_type_max; ++type) { for (auto &it : m_craft_defs[type]) { for (auto &iit : it.second) { delete iit; } it.second.clear(); } m_craft_defs[type].clear(); } m_output_craft_definitions.clear(); } virtual void initHashes(IGameDef *gamedef) { // Move the CraftDefs from the unhashed layer into layers higher up. std::vector<CraftDefinition *> &unhashed = m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0]; for (auto def : unhashed) { // Initialize and get the definition's hash def->initHash(gamedef); CraftHashType type = def->getHashType(); u64 hash = def->getHash(type); // Enter the definition m_craft_defs[type][hash].push_back(def); } unhashed.clear(); } private: std::vector<std::unordered_map<u64, std::vector<CraftDefinition*> > > m_craft_defs; std::unordered_map<std::string, std::vector<CraftDefinition*> > m_output_craft_definitions; }; IWritableCraftDefManager* createCraftDefManager() { return new CCraftDefManager(); }
pgimeno/minetest
src/craftdef.cpp
C++
mit
29,985
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <string> #include <iostream> #include <vector> #include <utility> #include "gamedef.h" #include "inventory.h" /* Crafting methods. The crafting method depends on the inventory list that the crafting input comes from. */ enum CraftMethod { // Crafting grid CRAFT_METHOD_NORMAL, // Cooking something in a furnace CRAFT_METHOD_COOKING, // Using something as fuel for a furnace CRAFT_METHOD_FUEL, }; /* The type a hash can be. The earlier a type is mentioned in this enum, the earlier it is tried at crafting, and the less likely is a collision. Changing order causes changes in behaviour, so know what you do. */ enum CraftHashType { // Hashes the normalized names of the recipe's elements. // Only recipes without group usage can be found here, // because groups can't be guessed efficiently. CRAFT_HASH_TYPE_ITEM_NAMES, // Counts the non-empty slots. CRAFT_HASH_TYPE_COUNT, // This layer both spares an extra variable, and helps to retain (albeit rarely used) functionality. Maps to 0. // Before hashes are "initialized", all hashes reside here, after initialisation, none are. CRAFT_HASH_TYPE_UNHASHED }; const int craft_hash_type_max = (int) CRAFT_HASH_TYPE_UNHASHED; /* Input: The contents of the crafting slots, arranged in matrix form */ struct CraftInput { CraftMethod method = CRAFT_METHOD_NORMAL; unsigned int width = 0; std::vector<ItemStack> items; CraftInput() = default; CraftInput(CraftMethod method_, unsigned int width_, const std::vector<ItemStack> &items_): method(method_), width(width_), items(items_) {} std::string dump() const; }; /* Output: Result of crafting operation */ struct CraftOutput { // Used for normal crafting and cooking, itemstring std::string item = ""; // Used for cooking (cook time) and fuel (burn time), seconds float time = 0.0f; CraftOutput() = default; CraftOutput(const std::string &item_, float time_): item(item_), time(time_) {} std::string dump() const; }; /* A list of replacements. A replacement indicates that a specific input item should not be deleted (when crafting) but replaced with a different item. Each replacements is a pair (itemstring to remove, itemstring to replace with) Example: If ("bucket:bucket_water", "bucket:bucket_empty") is a replacement pair, the crafting input slot that contained a water bucket will contain an empty bucket after crafting. Note: replacements only work correctly when stack_max of the item to be replaced is 1. It is up to the mod writer to ensure this. */ struct CraftReplacements { // List of replacements std::vector<std::pair<std::string, std::string> > pairs; CraftReplacements() = default; CraftReplacements(const std::vector<std::pair<std::string, std::string> > &pairs_): pairs(pairs_) {} std::string dump() const; }; /* Crafting definition base class */ class CraftDefinition { public: CraftDefinition() = default; virtual ~CraftDefinition() = default; // Returns type of crafting definition virtual std::string getName() const=0; // Checks whether the recipe is applicable virtual bool check(const CraftInput &input, IGameDef *gamedef) const=0; // Returns the output structure, meaning depends on crafting method // The implementation can assume that check(input) returns true virtual CraftOutput getOutput(const CraftInput &input, IGameDef *gamedef) const=0; // the inverse of the above virtual CraftInput getInput(const CraftOutput &output, IGameDef *gamedef) const=0; // Decreases count of every input item virtual void decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements, IGameDef *gamedef) const=0; virtual CraftHashType getHashType() const = 0; virtual u64 getHash(CraftHashType type) const = 0; // to be called after all mods are loaded, so that we catch all aliases virtual void initHash(IGameDef *gamedef) = 0; virtual std::string dump() const=0; }; /* A plain-jane (shaped) crafting definition Supported crafting method: CRAFT_METHOD_NORMAL. Requires the input items to be arranged exactly like in the recipe. */ class CraftDefinitionShaped: public CraftDefinition { public: CraftDefinitionShaped() = delete; CraftDefinitionShaped( const std::string &output_, unsigned int width_, const std::vector<std::string> &recipe_, const CraftReplacements &replacements_): output(output_), width(width_), recipe(recipe_), replacements(replacements_) {} virtual ~CraftDefinitionShaped() = default; virtual std::string getName() const; virtual bool check(const CraftInput &input, IGameDef *gamedef) const; virtual CraftOutput getOutput(const CraftInput &input, IGameDef *gamedef) const; virtual CraftInput getInput(const CraftOutput &output, IGameDef *gamedef) const; virtual void decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements, IGameDef *gamedef) const; virtual CraftHashType getHashType() const; virtual u64 getHash(CraftHashType type) const; virtual void initHash(IGameDef *gamedef); virtual std::string dump() const; private: // Output itemstring std::string output = ""; // Width of recipe unsigned int width = 1; // Recipe matrix (itemstrings) std::vector<std::string> recipe; // Recipe matrix (item names) std::vector<std::string> recipe_names; // bool indicating if initHash has been called already bool hash_inited = false; // Replacement items for decrementInput() CraftReplacements replacements; }; /* A shapeless crafting definition Supported crafting method: CRAFT_METHOD_NORMAL. Input items can arranged in any way. */ class CraftDefinitionShapeless: public CraftDefinition { public: CraftDefinitionShapeless() = delete; CraftDefinitionShapeless( const std::string &output_, const std::vector<std::string> &recipe_, const CraftReplacements &replacements_): output(output_), recipe(recipe_), replacements(replacements_) {} virtual ~CraftDefinitionShapeless() = default; virtual std::string getName() const; virtual bool check(const CraftInput &input, IGameDef *gamedef) const; virtual CraftOutput getOutput(const CraftInput &input, IGameDef *gamedef) const; virtual CraftInput getInput(const CraftOutput &output, IGameDef *gamedef) const; virtual void decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements, IGameDef *gamedef) const; virtual CraftHashType getHashType() const; virtual u64 getHash(CraftHashType type) const; virtual void initHash(IGameDef *gamedef); virtual std::string dump() const; private: // Output itemstring std::string output; // Recipe list (itemstrings) std::vector<std::string> recipe; // Recipe list (item names) std::vector<std::string> recipe_names; // bool indicating if initHash has been called already bool hash_inited = false; // Replacement items for decrementInput() CraftReplacements replacements; }; /* Tool repair crafting definition Supported crafting method: CRAFT_METHOD_NORMAL. Put two damaged tools into the crafting grid, get one tool back. There should only be one crafting definition of this type. */ class CraftDefinitionToolRepair: public CraftDefinition { public: CraftDefinitionToolRepair() = delete; CraftDefinitionToolRepair(float additional_wear_): additional_wear(additional_wear_) {} virtual ~CraftDefinitionToolRepair() = default; virtual std::string getName() const; virtual bool check(const CraftInput &input, IGameDef *gamedef) const; virtual CraftOutput getOutput(const CraftInput &input, IGameDef *gamedef) const; virtual CraftInput getInput(const CraftOutput &output, IGameDef *gamedef) const; virtual void decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements, IGameDef *gamedef) const; virtual CraftHashType getHashType() const { return CRAFT_HASH_TYPE_COUNT; } virtual u64 getHash(CraftHashType type) const { return 2; } virtual void initHash(IGameDef *gamedef) {} virtual std::string dump() const; private: // This is a constant that is added to the wear of the result. // May be positive or negative, allowed range [-1,1]. // 1 = new tool is completely broken // 0 = simply add remaining uses of both input tools // -1 = new tool is completely pristine float additional_wear = 0.0f; }; /* A cooking (in furnace) definition Supported crafting method: CRAFT_METHOD_COOKING. */ class CraftDefinitionCooking: public CraftDefinition { public: CraftDefinitionCooking() = delete; CraftDefinitionCooking( const std::string &output_, const std::string &recipe_, float cooktime_, const CraftReplacements &replacements_): output(output_), recipe(recipe_), cooktime(cooktime_), replacements(replacements_) {} virtual ~CraftDefinitionCooking() = default; virtual std::string getName() const; virtual bool check(const CraftInput &input, IGameDef *gamedef) const; virtual CraftOutput getOutput(const CraftInput &input, IGameDef *gamedef) const; virtual CraftInput getInput(const CraftOutput &output, IGameDef *gamedef) const; virtual void decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements, IGameDef *gamedef) const; virtual CraftHashType getHashType() const; virtual u64 getHash(CraftHashType type) const; virtual void initHash(IGameDef *gamedef); virtual std::string dump() const; private: // Output itemstring std::string output; // Recipe itemstring std::string recipe; // Recipe item name std::string recipe_name; // bool indicating if initHash has been called already bool hash_inited = false; // Time in seconds float cooktime; // Replacement items for decrementInput() CraftReplacements replacements; }; /* A fuel (for furnace) definition Supported crafting method: CRAFT_METHOD_FUEL. */ class CraftDefinitionFuel: public CraftDefinition { public: CraftDefinitionFuel() = delete; CraftDefinitionFuel(const std::string &recipe_, float burntime_, const CraftReplacements &replacements_): recipe(recipe_), burntime(burntime_), replacements(replacements_) {} virtual ~CraftDefinitionFuel() = default; virtual std::string getName() const; virtual bool check(const CraftInput &input, IGameDef *gamedef) const; virtual CraftOutput getOutput(const CraftInput &input, IGameDef *gamedef) const; virtual CraftInput getInput(const CraftOutput &output, IGameDef *gamedef) const; virtual void decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements, IGameDef *gamedef) const; virtual CraftHashType getHashType() const; virtual u64 getHash(CraftHashType type) const; virtual void initHash(IGameDef *gamedef); virtual std::string dump() const; private: // Recipe itemstring std::string recipe; // Recipe item name std::string recipe_name; // bool indicating if initHash has been called already bool hash_inited = false; // Time in seconds float burntime; // Replacement items for decrementInput() CraftReplacements replacements; }; /* Crafting definition manager */ class ICraftDefManager { public: ICraftDefManager() = default; virtual ~ICraftDefManager() = default; // The main crafting function virtual bool getCraftResult(CraftInput &input, CraftOutput &output, std::vector<ItemStack> &output_replacements, bool decrementInput, IGameDef *gamedef) const=0; virtual std::vector<CraftDefinition*> getCraftRecipes(CraftOutput &output, IGameDef *gamedef, unsigned limit=0) const=0; // Print crafting recipes for debugging virtual std::string dump() const=0; }; class IWritableCraftDefManager : public ICraftDefManager { public: IWritableCraftDefManager() = default; virtual ~IWritableCraftDefManager() = default; // The main crafting function virtual bool getCraftResult(CraftInput &input, CraftOutput &output, std::vector<ItemStack> &output_replacements, bool decrementInput, IGameDef *gamedef) const=0; virtual std::vector<CraftDefinition*> getCraftRecipes(CraftOutput &output, IGameDef *gamedef, unsigned limit=0) const=0; virtual bool clearCraftRecipesByOutput(const CraftOutput &output, IGameDef *gamedef) = 0; virtual bool clearCraftRecipesByInput(CraftMethod craft_method, unsigned int craft_grid_width, const std::vector<std::string> &recipe, IGameDef *gamedef) = 0; // Print crafting recipes for debugging virtual std::string dump() const=0; // Add a crafting definition. // After calling this, the pointer belongs to the manager. virtual void registerCraft(CraftDefinition *def, IGameDef *gamedef) = 0; // Delete all crafting definitions virtual void clear()=0; // To be called after all mods are loaded, so that we catch all aliases virtual void initHashes(IGameDef *gamedef) = 0; }; IWritableCraftDefManager* createCraftDefManager();
pgimeno/minetest
src/craftdef.h
C++
mit
13,450
set(database_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/database.cpp ${CMAKE_CURRENT_SOURCE_DIR}/database-dummy.cpp ${CMAKE_CURRENT_SOURCE_DIR}/database-files.cpp ${CMAKE_CURRENT_SOURCE_DIR}/database-leveldb.cpp ${CMAKE_CURRENT_SOURCE_DIR}/database-postgresql.cpp ${CMAKE_CURRENT_SOURCE_DIR}/database-redis.cpp ${CMAKE_CURRENT_SOURCE_DIR}/database-sqlite3.cpp PARENT_SCOPE )
pgimeno/minetest
src/database/CMakeLists.txt
Text
mit
373
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* Dummy database class */ #include "database-dummy.h" bool Database_Dummy::saveBlock(const v3s16 &pos, const std::string &data) { m_database[getBlockAsInteger(pos)] = data; return true; } void Database_Dummy::loadBlock(const v3s16 &pos, std::string *block) { s64 i = getBlockAsInteger(pos); auto it = m_database.find(i); if (it == m_database.end()) { *block = ""; return; } *block = it->second; } bool Database_Dummy::deleteBlock(const v3s16 &pos) { m_database.erase(getBlockAsInteger(pos)); return true; } void Database_Dummy::listAllLoadableBlocks(std::vector<v3s16> &dst) { dst.reserve(m_database.size()); for (std::map<s64, std::string>::const_iterator x = m_database.begin(); x != m_database.end(); ++x) { dst.push_back(getIntegerAsBlock(x->first)); } }
pgimeno/minetest
src/database/database-dummy.cpp
C++
mit
1,574
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <map> #include <string> #include "database.h" #include "irrlichttypes.h" class Database_Dummy : public MapDatabase, public PlayerDatabase { public: bool saveBlock(const v3s16 &pos, const std::string &data); void loadBlock(const v3s16 &pos, std::string *block); bool deleteBlock(const v3s16 &pos); void listAllLoadableBlocks(std::vector<v3s16> &dst); void savePlayer(RemotePlayer *player) {} bool loadPlayer(RemotePlayer *player, PlayerSAO *sao) { return true; } bool removePlayer(const std::string &name) { return true; } void listPlayers(std::vector<std::string> &res) {} void beginSave() {} void endSave() {} private: std::map<s64, std::string> m_database; };
pgimeno/minetest
src/database/database-dummy.h
C++
mit
1,485
/* Minetest Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <cassert> #include <json/json.h> #include "database-files.h" #include "content_sao.h" #include "remoteplayer.h" #include "settings.h" #include "porting.h" #include "filesys.h" #include "util/string.h" // !!! WARNING !!! // This backend is intended to be used on Minetest 0.4.16 only for the transition backend // for player files PlayerDatabaseFiles::PlayerDatabaseFiles(const std::string &savedir) : m_savedir(savedir) { fs::CreateDir(m_savedir); } void PlayerDatabaseFiles::serialize(std::ostringstream &os, RemotePlayer *player) { // Utilize a Settings object for storing values Settings args; args.setS32("version", 1); args.set("name", player->getName()); sanity_check(player->getPlayerSAO()); args.setU16("hp", player->getPlayerSAO()->getHP()); args.setV3F("position", player->getPlayerSAO()->getBasePosition()); args.setFloat("pitch", player->getPlayerSAO()->getLookPitch()); args.setFloat("yaw", player->getPlayerSAO()->getRotation().Y); args.setU16("breath", player->getPlayerSAO()->getBreath()); std::string extended_attrs; player->serializeExtraAttributes(extended_attrs); args.set("extended_attributes", extended_attrs); args.writeLines(os); os << "PlayerArgsEnd\n"; player->inventory.serialize(os); } void PlayerDatabaseFiles::savePlayer(RemotePlayer *player) { fs::CreateDir(m_savedir); std::string savedir = m_savedir + DIR_DELIM; std::string path = savedir + player->getName(); bool path_found = false; RemotePlayer testplayer("", NULL); for (u32 i = 0; i < PLAYER_FILE_ALTERNATE_TRIES && !path_found; i++) { if (!fs::PathExists(path)) { path_found = true; continue; } // Open and deserialize file to check player name std::ifstream is(path.c_str(), std::ios_base::binary); if (!is.good()) { errorstream << "Failed to open " << path << std::endl; return; } testplayer.deSerialize(is, path, NULL); is.close(); if (strcmp(testplayer.getName(), player->getName()) == 0) { path_found = true; continue; } path = savedir + player->getName() + itos(i); } if (!path_found) { errorstream << "Didn't find free file for player " << player->getName() << std::endl; return; } // Open and serialize file std::ostringstream ss(std::ios_base::binary); serialize(ss, player); if (!fs::safeWriteToFile(path, ss.str())) { infostream << "Failed to write " << path << std::endl; } player->onSuccessfulSave(); } bool PlayerDatabaseFiles::removePlayer(const std::string &name) { std::string players_path = m_savedir + DIR_DELIM; std::string path = players_path + name; RemotePlayer temp_player("", NULL); for (u32 i = 0; i < PLAYER_FILE_ALTERNATE_TRIES; i++) { // Open file and deserialize std::ifstream is(path.c_str(), std::ios_base::binary); if (!is.good()) continue; temp_player.deSerialize(is, path, NULL); is.close(); if (temp_player.getName() == name) { fs::DeleteSingleFileOrEmptyDirectory(path); return true; } path = players_path + name + itos(i); } return false; } bool PlayerDatabaseFiles::loadPlayer(RemotePlayer *player, PlayerSAO *sao) { std::string players_path = m_savedir + DIR_DELIM; std::string path = players_path + player->getName(); const std::string player_to_load = player->getName(); for (u32 i = 0; i < PLAYER_FILE_ALTERNATE_TRIES; i++) { // Open file and deserialize std::ifstream is(path.c_str(), std::ios_base::binary); if (!is.good()) continue; player->deSerialize(is, path, sao); is.close(); if (player->getName() == player_to_load) return true; path = players_path + player_to_load + itos(i); } infostream << "Player file for player " << player_to_load << " not found" << std::endl; return false; } void PlayerDatabaseFiles::listPlayers(std::vector<std::string> &res) { std::vector<fs::DirListNode> files = fs::GetDirListing(m_savedir); // list files into players directory for (std::vector<fs::DirListNode>::const_iterator it = files.begin(); it != files.end(); ++it) { // Ignore directories if (it->dir) continue; const std::string &filename = it->name; std::string full_path = m_savedir + DIR_DELIM + filename; std::ifstream is(full_path.c_str(), std::ios_base::binary); if (!is.good()) continue; RemotePlayer player(filename.c_str(), NULL); // Null env & dummy peer_id PlayerSAO playerSAO(NULL, &player, 15789, false); player.deSerialize(is, "", &playerSAO); is.close(); res.emplace_back(player.getName()); } } AuthDatabaseFiles::AuthDatabaseFiles(const std::string &savedir) : m_savedir(savedir) { readAuthFile(); } bool AuthDatabaseFiles::getAuth(const std::string &name, AuthEntry &res) { const auto res_i = m_auth_list.find(name); if (res_i == m_auth_list.end()) { return false; } res = res_i->second; return true; } bool AuthDatabaseFiles::saveAuth(const AuthEntry &authEntry) { m_auth_list[authEntry.name] = authEntry; // save entire file return writeAuthFile(); } bool AuthDatabaseFiles::createAuth(AuthEntry &authEntry) { m_auth_list[authEntry.name] = authEntry; // save entire file return writeAuthFile(); } bool AuthDatabaseFiles::deleteAuth(const std::string &name) { if (!m_auth_list.erase(name)) { // did not delete anything -> hadn't existed return false; } return writeAuthFile(); } void AuthDatabaseFiles::listNames(std::vector<std::string> &res) { res.clear(); res.reserve(m_auth_list.size()); for (const auto &res_pair : m_auth_list) { res.push_back(res_pair.first); } } void AuthDatabaseFiles::reload() { readAuthFile(); } bool AuthDatabaseFiles::readAuthFile() { std::string path = m_savedir + DIR_DELIM + "auth.txt"; std::ifstream file(path, std::ios::binary); if (!file.good()) { return false; } m_auth_list.clear(); while (file.good()) { std::string line; std::getline(file, line); std::vector<std::string> parts = str_split(line, ':'); if (parts.size() < 3) // also: empty line at end continue; const std::string &name = parts[0]; const std::string &password = parts[1]; std::vector<std::string> privileges = str_split(parts[2], ','); s64 last_login = parts.size() > 3 ? atol(parts[3].c_str()) : 0; m_auth_list[name] = { 1, name, password, privileges, last_login, }; } return true; } bool AuthDatabaseFiles::writeAuthFile() { std::string path = m_savedir + DIR_DELIM + "auth.txt"; std::ostringstream output(std::ios_base::binary); for (const auto &auth_i : m_auth_list) { const AuthEntry &authEntry = auth_i.second; output << authEntry.name << ":" << authEntry.password << ":"; output << str_join(authEntry.privileges, ","); output << ":" << authEntry.last_login; output << std::endl; } if (!fs::safeWriteToFile(path, output.str())) { infostream << "Failed to write " << path << std::endl; return false; } return true; }
pgimeno/minetest
src/database/database-files.cpp
C++
mit
7,597
/* Minetest Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once // !!! WARNING !!! // This backend is intended to be used on Minetest 0.4.16 only for the transition backend // for player files #include "database.h" #include <unordered_map> class PlayerDatabaseFiles : public PlayerDatabase { public: PlayerDatabaseFiles(const std::string &savedir); virtual ~PlayerDatabaseFiles() = default; void savePlayer(RemotePlayer *player); bool loadPlayer(RemotePlayer *player, PlayerSAO *sao); bool removePlayer(const std::string &name); void listPlayers(std::vector<std::string> &res); private: void serialize(std::ostringstream &os, RemotePlayer *player); std::string m_savedir; }; class AuthDatabaseFiles : public AuthDatabase { public: AuthDatabaseFiles(const std::string &savedir); virtual ~AuthDatabaseFiles() = default; virtual bool getAuth(const std::string &name, AuthEntry &res); virtual bool saveAuth(const AuthEntry &authEntry); virtual bool createAuth(AuthEntry &authEntry); virtual bool deleteAuth(const std::string &name); virtual void listNames(std::vector<std::string> &res); virtual void reload(); private: std::unordered_map<std::string, AuthEntry> m_auth_list; std::string m_savedir; bool readAuthFile(); bool writeAuthFile(); };
pgimeno/minetest
src/database/database-files.h
C++
mit
2,008
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #if USE_LEVELDB #include "database-leveldb.h" #include "log.h" #include "filesys.h" #include "exceptions.h" #include "util/string.h" #include "leveldb/db.h" #define ENSURE_STATUS_OK(s) \ if (!(s).ok()) { \ throw DatabaseException(std::string("LevelDB error: ") + \ (s).ToString()); \ } Database_LevelDB::Database_LevelDB(const std::string &savedir) { leveldb::Options options; options.create_if_missing = true; leveldb::Status status = leveldb::DB::Open(options, savedir + DIR_DELIM + "map.db", &m_database); ENSURE_STATUS_OK(status); } Database_LevelDB::~Database_LevelDB() { delete m_database; } bool Database_LevelDB::saveBlock(const v3s16 &pos, const std::string &data) { leveldb::Status status = m_database->Put(leveldb::WriteOptions(), i64tos(getBlockAsInteger(pos)), data); if (!status.ok()) { warningstream << "saveBlock: LevelDB error saving block " << PP(pos) << ": " << status.ToString() << std::endl; return false; } return true; } void Database_LevelDB::loadBlock(const v3s16 &pos, std::string *block) { std::string datastr; leveldb::Status status = m_database->Get(leveldb::ReadOptions(), i64tos(getBlockAsInteger(pos)), &datastr); *block = (status.ok()) ? datastr : ""; } bool Database_LevelDB::deleteBlock(const v3s16 &pos) { leveldb::Status status = m_database->Delete(leveldb::WriteOptions(), i64tos(getBlockAsInteger(pos))); if (!status.ok()) { warningstream << "deleteBlock: LevelDB error deleting block " << PP(pos) << ": " << status.ToString() << std::endl; return false; } return true; } void Database_LevelDB::listAllLoadableBlocks(std::vector<v3s16> &dst) { leveldb::Iterator* it = m_database->NewIterator(leveldb::ReadOptions()); for (it->SeekToFirst(); it->Valid(); it->Next()) { dst.push_back(getIntegerAsBlock(stoi64(it->key().ToString()))); } ENSURE_STATUS_OK(it->status()); // Check for any errors found during the scan delete it; } #endif // USE_LEVELDB
pgimeno/minetest
src/database/database-leveldb.cpp
C++
mit
2,765
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "config.h" #if USE_LEVELDB #include <string> #include "database.h" #include "leveldb/db.h" class Database_LevelDB : public MapDatabase { public: Database_LevelDB(const std::string &savedir); ~Database_LevelDB(); bool saveBlock(const v3s16 &pos, const std::string &data); void loadBlock(const v3s16 &pos, std::string *block); bool deleteBlock(const v3s16 &pos); void listAllLoadableBlocks(std::vector<v3s16> &dst); void beginSave() {} void endSave() {} private: leveldb::DB *m_database; }; #endif // USE_LEVELDB
pgimeno/minetest
src/database/database-leveldb.h
C++
mit
1,335
/* Copyright (C) 2016 Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #if USE_POSTGRESQL #include "database-postgresql.h" #ifdef _WIN32 // Without this some of the network functions are not found on mingw #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif #include <windows.h> #include <winsock2.h> #else #include <netinet/in.h> #endif #include "debug.h" #include "exceptions.h" #include "settings.h" #include "content_sao.h" #include "remoteplayer.h" Database_PostgreSQL::Database_PostgreSQL(const std::string &connect_string) : m_connect_string(connect_string) { if (m_connect_string.empty()) { throw SettingNotFoundException( "Set pgsql_connection string in world.mt to " "use the postgresql backend\n" "Notes:\n" "pgsql_connection has the following form: \n" "\tpgsql_connection = host=127.0.0.1 port=5432 user=mt_user " "password=mt_password dbname=minetest_world\n" "mt_user should have CREATE TABLE, INSERT, SELECT, UPDATE and " "DELETE rights on the database.\n" "Don't create mt_user as a SUPERUSER!"); } } Database_PostgreSQL::~Database_PostgreSQL() { PQfinish(m_conn); } void Database_PostgreSQL::connectToDatabase() { m_conn = PQconnectdb(m_connect_string.c_str()); if (PQstatus(m_conn) != CONNECTION_OK) { throw DatabaseException(std::string( "PostgreSQL database error: ") + PQerrorMessage(m_conn)); } m_pgversion = PQserverVersion(m_conn); /* * We are using UPSERT feature from PostgreSQL 9.5 * to have the better performance where possible. */ if (m_pgversion < 90500) { warningstream << "Your PostgreSQL server lacks UPSERT " << "support. Use version 9.5 or better if possible." << std::endl; } infostream << "PostgreSQL Database: Version " << m_pgversion << " Connection made." << std::endl; createDatabase(); initStatements(); } void Database_PostgreSQL::verifyDatabase() { if (PQstatus(m_conn) == CONNECTION_OK) return; PQreset(m_conn); ping(); } void Database_PostgreSQL::ping() { if (PQping(m_connect_string.c_str()) != PQPING_OK) { throw DatabaseException(std::string( "PostgreSQL database error: ") + PQerrorMessage(m_conn)); } } bool Database_PostgreSQL::initialized() const { return (PQstatus(m_conn) == CONNECTION_OK); } PGresult *Database_PostgreSQL::checkResults(PGresult *result, bool clear) { ExecStatusType statusType = PQresultStatus(result); switch (statusType) { case PGRES_COMMAND_OK: case PGRES_TUPLES_OK: break; case PGRES_FATAL_ERROR: default: throw DatabaseException( std::string("PostgreSQL database error: ") + PQresultErrorMessage(result)); } if (clear) PQclear(result); return result; } void Database_PostgreSQL::createTableIfNotExists(const std::string &table_name, const std::string &definition) { std::string sql_check_table = "SELECT relname FROM pg_class WHERE relname='" + table_name + "';"; PGresult *result = checkResults(PQexec(m_conn, sql_check_table.c_str()), false); // If table doesn't exist, create it if (!PQntuples(result)) { checkResults(PQexec(m_conn, definition.c_str())); } PQclear(result); } void Database_PostgreSQL::beginSave() { verifyDatabase(); checkResults(PQexec(m_conn, "BEGIN;")); } void Database_PostgreSQL::endSave() { checkResults(PQexec(m_conn, "COMMIT;")); } MapDatabasePostgreSQL::MapDatabasePostgreSQL(const std::string &connect_string): Database_PostgreSQL(connect_string), MapDatabase() { connectToDatabase(); } void MapDatabasePostgreSQL::createDatabase() { createTableIfNotExists("blocks", "CREATE TABLE blocks (" "posX INT NOT NULL," "posY INT NOT NULL," "posZ INT NOT NULL," "data BYTEA," "PRIMARY KEY (posX,posY,posZ)" ");" ); infostream << "PostgreSQL: Map Database was initialized." << std::endl; } void MapDatabasePostgreSQL::initStatements() { prepareStatement("read_block", "SELECT data FROM blocks " "WHERE posX = $1::int4 AND posY = $2::int4 AND " "posZ = $3::int4"); if (getPGVersion() < 90500) { prepareStatement("write_block_insert", "INSERT INTO blocks (posX, posY, posZ, data) SELECT " "$1::int4, $2::int4, $3::int4, $4::bytea " "WHERE NOT EXISTS (SELECT true FROM blocks " "WHERE posX = $1::int4 AND posY = $2::int4 AND " "posZ = $3::int4)"); prepareStatement("write_block_update", "UPDATE blocks SET data = $4::bytea " "WHERE posX = $1::int4 AND posY = $2::int4 AND " "posZ = $3::int4"); } else { prepareStatement("write_block", "INSERT INTO blocks (posX, posY, posZ, data) VALUES " "($1::int4, $2::int4, $3::int4, $4::bytea) " "ON CONFLICT ON CONSTRAINT blocks_pkey DO " "UPDATE SET data = $4::bytea"); } prepareStatement("delete_block", "DELETE FROM blocks WHERE " "posX = $1::int4 AND posY = $2::int4 AND posZ = $3::int4"); prepareStatement("list_all_loadable_blocks", "SELECT posX, posY, posZ FROM blocks"); } bool MapDatabasePostgreSQL::saveBlock(const v3s16 &pos, const std::string &data) { // Verify if we don't overflow the platform integer with the mapblock size if (data.size() > INT_MAX) { errorstream << "Database_PostgreSQL::saveBlock: Data truncation! " << "data.size() over 0xFFFFFFFF (== " << data.size() << ")" << std::endl; return false; } verifyDatabase(); s32 x, y, z; x = htonl(pos.X); y = htonl(pos.Y); z = htonl(pos.Z); const void *args[] = { &x, &y, &z, data.c_str() }; const int argLen[] = { sizeof(x), sizeof(y), sizeof(z), (int)data.size() }; const int argFmt[] = { 1, 1, 1, 1 }; if (getPGVersion() < 90500) { execPrepared("write_block_update", ARRLEN(args), args, argLen, argFmt); execPrepared("write_block_insert", ARRLEN(args), args, argLen, argFmt); } else { execPrepared("write_block", ARRLEN(args), args, argLen, argFmt); } return true; } void MapDatabasePostgreSQL::loadBlock(const v3s16 &pos, std::string *block) { verifyDatabase(); s32 x, y, z; x = htonl(pos.X); y = htonl(pos.Y); z = htonl(pos.Z); const void *args[] = { &x, &y, &z }; const int argLen[] = { sizeof(x), sizeof(y), sizeof(z) }; const int argFmt[] = { 1, 1, 1 }; PGresult *results = execPrepared("read_block", ARRLEN(args), args, argLen, argFmt, false); *block = ""; if (PQntuples(results)) *block = std::string(PQgetvalue(results, 0, 0), PQgetlength(results, 0, 0)); PQclear(results); } bool MapDatabasePostgreSQL::deleteBlock(const v3s16 &pos) { verifyDatabase(); s32 x, y, z; x = htonl(pos.X); y = htonl(pos.Y); z = htonl(pos.Z); const void *args[] = { &x, &y, &z }; const int argLen[] = { sizeof(x), sizeof(y), sizeof(z) }; const int argFmt[] = { 1, 1, 1 }; execPrepared("delete_block", ARRLEN(args), args, argLen, argFmt); return true; } void MapDatabasePostgreSQL::listAllLoadableBlocks(std::vector<v3s16> &dst) { verifyDatabase(); PGresult *results = execPrepared("list_all_loadable_blocks", 0, NULL, NULL, NULL, false, false); int numrows = PQntuples(results); for (int row = 0; row < numrows; ++row) dst.push_back(pg_to_v3s16(results, 0, 0)); PQclear(results); } /* * Player Database */ PlayerDatabasePostgreSQL::PlayerDatabasePostgreSQL(const std::string &connect_string): Database_PostgreSQL(connect_string), PlayerDatabase() { connectToDatabase(); } void PlayerDatabasePostgreSQL::createDatabase() { createTableIfNotExists("player", "CREATE TABLE player (" "name VARCHAR(60) NOT NULL," "pitch NUMERIC(15, 7) NOT NULL," "yaw NUMERIC(15, 7) NOT NULL," "posX NUMERIC(15, 7) NOT NULL," "posY NUMERIC(15, 7) NOT NULL," "posZ NUMERIC(15, 7) NOT NULL," "hp INT NOT NULL," "breath INT NOT NULL," "creation_date TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT NOW()," "modification_date TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT NOW()," "PRIMARY KEY (name)" ");" ); createTableIfNotExists("player_inventories", "CREATE TABLE player_inventories (" "player VARCHAR(60) NOT NULL," "inv_id INT NOT NULL," "inv_width INT NOT NULL," "inv_name TEXT NOT NULL DEFAULT ''," "inv_size INT NOT NULL," "PRIMARY KEY(player, inv_id)," "CONSTRAINT player_inventories_fkey FOREIGN KEY (player) REFERENCES " "player (name) ON DELETE CASCADE" ");" ); createTableIfNotExists("player_inventory_items", "CREATE TABLE player_inventory_items (" "player VARCHAR(60) NOT NULL," "inv_id INT NOT NULL," "slot_id INT NOT NULL," "item TEXT NOT NULL DEFAULT ''," "PRIMARY KEY(player, inv_id, slot_id)," "CONSTRAINT player_inventory_items_fkey FOREIGN KEY (player) REFERENCES " "player (name) ON DELETE CASCADE" ");" ); createTableIfNotExists("player_metadata", "CREATE TABLE player_metadata (" "player VARCHAR(60) NOT NULL," "attr VARCHAR(256) NOT NULL," "value TEXT," "PRIMARY KEY(player, attr)," "CONSTRAINT player_metadata_fkey FOREIGN KEY (player) REFERENCES " "player (name) ON DELETE CASCADE" ");" ); infostream << "PostgreSQL: Player Database was inited." << std::endl; } void PlayerDatabasePostgreSQL::initStatements() { if (getPGVersion() < 90500) { prepareStatement("create_player", "INSERT INTO player(name, pitch, yaw, posX, posY, posZ, hp, breath) VALUES " "($1, $2, $3, $4, $5, $6, $7::int, $8::int)"); prepareStatement("update_player", "UPDATE SET pitch = $2, yaw = $3, posX = $4, posY = $5, posZ = $6, hp = $7::int, " "breath = $8::int, modification_date = NOW() WHERE name = $1"); } else { prepareStatement("save_player", "INSERT INTO player(name, pitch, yaw, posX, posY, posZ, hp, breath) VALUES " "($1, $2, $3, $4, $5, $6, $7::int, $8::int)" "ON CONFLICT ON CONSTRAINT player_pkey DO UPDATE SET pitch = $2, yaw = $3, " "posX = $4, posY = $5, posZ = $6, hp = $7::int, breath = $8::int, " "modification_date = NOW()"); } prepareStatement("remove_player", "DELETE FROM player WHERE name = $1"); prepareStatement("load_player_list", "SELECT name FROM player"); prepareStatement("remove_player_inventories", "DELETE FROM player_inventories WHERE player = $1"); prepareStatement("remove_player_inventory_items", "DELETE FROM player_inventory_items WHERE player = $1"); prepareStatement("add_player_inventory", "INSERT INTO player_inventories (player, inv_id, inv_width, inv_name, inv_size) VALUES " "($1, $2::int, $3::int, $4, $5::int)"); prepareStatement("add_player_inventory_item", "INSERT INTO player_inventory_items (player, inv_id, slot_id, item) VALUES " "($1, $2::int, $3::int, $4)"); prepareStatement("load_player_inventories", "SELECT inv_id, inv_width, inv_name, inv_size FROM player_inventories " "WHERE player = $1 ORDER BY inv_id"); prepareStatement("load_player_inventory_items", "SELECT slot_id, item FROM player_inventory_items WHERE " "player = $1 AND inv_id = $2::int"); prepareStatement("load_player", "SELECT pitch, yaw, posX, posY, posZ, hp, breath FROM player WHERE name = $1"); prepareStatement("remove_player_metadata", "DELETE FROM player_metadata WHERE player = $1"); prepareStatement("save_player_metadata", "INSERT INTO player_metadata (player, attr, value) VALUES ($1, $2, $3)"); prepareStatement("load_player_metadata", "SELECT attr, value FROM player_metadata WHERE player = $1"); } bool PlayerDatabasePostgreSQL::playerDataExists(const std::string &playername) { verifyDatabase(); const char *values[] = { playername.c_str() }; PGresult *results = execPrepared("load_player", 1, values, false); bool res = (PQntuples(results) > 0); PQclear(results); return res; } void PlayerDatabasePostgreSQL::savePlayer(RemotePlayer *player) { PlayerSAO* sao = player->getPlayerSAO(); if (!sao) return; verifyDatabase(); v3f pos = sao->getBasePosition(); std::string pitch = ftos(sao->getLookPitch()); std::string yaw = ftos(sao->getRotation().Y); std::string posx = ftos(pos.X); std::string posy = ftos(pos.Y); std::string posz = ftos(pos.Z); std::string hp = itos(sao->getHP()); std::string breath = itos(sao->getBreath()); const char *values[] = { player->getName(), pitch.c_str(), yaw.c_str(), posx.c_str(), posy.c_str(), posz.c_str(), hp.c_str(), breath.c_str() }; const char* rmvalues[] = { player->getName() }; beginSave(); if (getPGVersion() < 90500) { if (!playerDataExists(player->getName())) execPrepared("create_player", 8, values, true, false); else execPrepared("update_player", 8, values, true, false); } else execPrepared("save_player", 8, values, true, false); // Write player inventories execPrepared("remove_player_inventories", 1, rmvalues); execPrepared("remove_player_inventory_items", 1, rmvalues); std::vector<const InventoryList*> inventory_lists = sao->getInventory()->getLists(); for (u16 i = 0; i < inventory_lists.size(); i++) { const InventoryList* list = inventory_lists[i]; const std::string &name = list->getName(); std::string width = itos(list->getWidth()), inv_id = itos(i), lsize = itos(list->getSize()); const char* inv_values[] = { player->getName(), inv_id.c_str(), width.c_str(), name.c_str(), lsize.c_str() }; execPrepared("add_player_inventory", 5, inv_values); for (u32 j = 0; j < list->getSize(); j++) { std::ostringstream os; list->getItem(j).serialize(os); std::string itemStr = os.str(), slotId = itos(j); const char* invitem_values[] = { player->getName(), inv_id.c_str(), slotId.c_str(), itemStr.c_str() }; execPrepared("add_player_inventory_item", 4, invitem_values); } } execPrepared("remove_player_metadata", 1, rmvalues); const StringMap &attrs = sao->getMeta().getStrings(); for (const auto &attr : attrs) { const char *meta_values[] = { player->getName(), attr.first.c_str(), attr.second.c_str() }; execPrepared("save_player_metadata", 3, meta_values); } endSave(); player->onSuccessfulSave(); } bool PlayerDatabasePostgreSQL::loadPlayer(RemotePlayer *player, PlayerSAO *sao) { sanity_check(sao); verifyDatabase(); const char *values[] = { player->getName() }; PGresult *results = execPrepared("load_player", 1, values, false, false); // Player not found, return not found if (!PQntuples(results)) { PQclear(results); return false; } sao->setLookPitch(pg_to_float(results, 0, 0)); sao->setRotation(v3f(0, pg_to_float(results, 0, 1), 0)); sao->setBasePosition(v3f( pg_to_float(results, 0, 2), pg_to_float(results, 0, 3), pg_to_float(results, 0, 4)) ); sao->setHPRaw((u16) pg_to_int(results, 0, 5)); sao->setBreath((u16) pg_to_int(results, 0, 6), false); PQclear(results); // Load inventory results = execPrepared("load_player_inventories", 1, values, false, false); int resultCount = PQntuples(results); for (int row = 0; row < resultCount; ++row) { InventoryList* invList = player->inventory. addList(PQgetvalue(results, row, 2), pg_to_uint(results, row, 3)); invList->setWidth(pg_to_uint(results, row, 1)); u32 invId = pg_to_uint(results, row, 0); std::string invIdStr = itos(invId); const char* values2[] = { player->getName(), invIdStr.c_str() }; PGresult *results2 = execPrepared("load_player_inventory_items", 2, values2, false, false); int resultCount2 = PQntuples(results2); for (int row2 = 0; row2 < resultCount2; row2++) { const std::string itemStr = PQgetvalue(results2, row2, 1); if (itemStr.length() > 0) { ItemStack stack; stack.deSerialize(itemStr); invList->changeItem(pg_to_uint(results2, row2, 0), stack); } } PQclear(results2); } PQclear(results); results = execPrepared("load_player_metadata", 1, values, false); int numrows = PQntuples(results); for (int row = 0; row < numrows; row++) { sao->getMeta().setString(PQgetvalue(results, row, 0), PQgetvalue(results, row, 1)); } sao->getMeta().setModified(false); PQclear(results); return true; } bool PlayerDatabasePostgreSQL::removePlayer(const std::string &name) { if (!playerDataExists(name)) return false; verifyDatabase(); const char *values[] = { name.c_str() }; execPrepared("remove_player", 1, values); return true; } void PlayerDatabasePostgreSQL::listPlayers(std::vector<std::string> &res) { verifyDatabase(); PGresult *results = execPrepared("load_player_list", 0, NULL, false); int numrows = PQntuples(results); for (int row = 0; row < numrows; row++) res.emplace_back(PQgetvalue(results, row, 0)); PQclear(results); } #endif // USE_POSTGRESQL
pgimeno/minetest
src/database/database-postgresql.cpp
C++
mit
17,135
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <string> #include <libpq-fe.h> #include "database.h" #include "util/basic_macros.h" class Settings; class Database_PostgreSQL: public Database { public: Database_PostgreSQL(const std::string &connect_string); ~Database_PostgreSQL(); void beginSave(); void endSave(); bool initialized() const; protected: // Conversion helpers inline int pg_to_int(PGresult *res, int row, int col) { return atoi(PQgetvalue(res, row, col)); } inline u32 pg_to_uint(PGresult *res, int row, int col) { return (u32) atoi(PQgetvalue(res, row, col)); } inline float pg_to_float(PGresult *res, int row, int col) { return (float) atof(PQgetvalue(res, row, col)); } inline v3s16 pg_to_v3s16(PGresult *res, int row, int col) { return v3s16( pg_to_int(res, row, col), pg_to_int(res, row, col + 1), pg_to_int(res, row, col + 2) ); } inline PGresult *execPrepared(const char *stmtName, const int paramsNumber, const void **params, const int *paramsLengths = NULL, const int *paramsFormats = NULL, bool clear = true, bool nobinary = true) { return checkResults(PQexecPrepared(m_conn, stmtName, paramsNumber, (const char* const*) params, paramsLengths, paramsFormats, nobinary ? 1 : 0), clear); } inline PGresult *execPrepared(const char *stmtName, const int paramsNumber, const char **params, bool clear = true, bool nobinary = true) { return execPrepared(stmtName, paramsNumber, (const void **)params, NULL, NULL, clear, nobinary); } void createTableIfNotExists(const std::string &table_name, const std::string &definition); void verifyDatabase(); // Database initialization void connectToDatabase(); virtual void createDatabase() = 0; virtual void initStatements() = 0; inline void prepareStatement(const std::string &name, const std::string &sql) { checkResults(PQprepare(m_conn, name.c_str(), sql.c_str(), 0, NULL)); } const int getPGVersion() const { return m_pgversion; } private: // Database connectivity checks void ping(); // Database usage PGresult *checkResults(PGresult *res, bool clear = true); // Attributes std::string m_connect_string; PGconn *m_conn = nullptr; int m_pgversion = 0; }; class MapDatabasePostgreSQL : private Database_PostgreSQL, public MapDatabase { public: MapDatabasePostgreSQL(const std::string &connect_string); virtual ~MapDatabasePostgreSQL() = default; bool saveBlock(const v3s16 &pos, const std::string &data); void loadBlock(const v3s16 &pos, std::string *block); bool deleteBlock(const v3s16 &pos); void listAllLoadableBlocks(std::vector<v3s16> &dst); void beginSave() { Database_PostgreSQL::beginSave(); } void endSave() { Database_PostgreSQL::endSave(); } protected: virtual void createDatabase(); virtual void initStatements(); }; class PlayerDatabasePostgreSQL : private Database_PostgreSQL, public PlayerDatabase { public: PlayerDatabasePostgreSQL(const std::string &connect_string); virtual ~PlayerDatabasePostgreSQL() = default; void savePlayer(RemotePlayer *player); bool loadPlayer(RemotePlayer *player, PlayerSAO *sao); bool removePlayer(const std::string &name); void listPlayers(std::vector<std::string> &res); protected: virtual void createDatabase(); virtual void initStatements(); private: bool playerDataExists(const std::string &playername); };
pgimeno/minetest
src/database/database-postgresql.h
C++
mit
4,107
/* Minetest Copyright (C) 2014 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #if USE_REDIS #include "database-redis.h" #include "settings.h" #include "log.h" #include "exceptions.h" #include "util/string.h" #include <hiredis.h> #include <cassert> Database_Redis::Database_Redis(Settings &conf) { std::string tmp; try { tmp = conf.get("redis_address"); hash = conf.get("redis_hash"); } catch (SettingNotFoundException &) { throw SettingNotFoundException("Set redis_address and " "redis_hash in world.mt to use the redis backend"); } const char *addr = tmp.c_str(); int port = conf.exists("redis_port") ? conf.getU16("redis_port") : 6379; // if redis_address contains '/' assume unix socket, else hostname/ip ctx = tmp.find('/') != std::string::npos ? redisConnectUnix(addr) : redisConnect(addr, port); if (!ctx) { throw DatabaseException("Cannot allocate redis context"); } else if (ctx->err) { std::string err = std::string("Connection error: ") + ctx->errstr; redisFree(ctx); throw DatabaseException(err); } if (conf.exists("redis_password")) { tmp = conf.get("redis_password"); redisReply *reply = static_cast<redisReply *>(redisCommand(ctx, "AUTH %s", tmp.c_str())); if (!reply) throw DatabaseException("Redis authentication failed"); if (reply->type == REDIS_REPLY_ERROR) { std::string err = "Redis authentication failed: " + std::string(reply->str, reply->len); freeReplyObject(reply); throw DatabaseException(err); } freeReplyObject(reply); } } Database_Redis::~Database_Redis() { redisFree(ctx); } void Database_Redis::beginSave() { redisReply *reply = static_cast<redisReply *>(redisCommand(ctx, "MULTI")); if (!reply) { throw DatabaseException(std::string( "Redis command 'MULTI' failed: ") + ctx->errstr); } freeReplyObject(reply); } void Database_Redis::endSave() { redisReply *reply = static_cast<redisReply *>(redisCommand(ctx, "EXEC")); if (!reply) { throw DatabaseException(std::string( "Redis command 'EXEC' failed: ") + ctx->errstr); } freeReplyObject(reply); } bool Database_Redis::saveBlock(const v3s16 &pos, const std::string &data) { std::string tmp = i64tos(getBlockAsInteger(pos)); redisReply *reply = static_cast<redisReply *>(redisCommand(ctx, "HSET %s %s %b", hash.c_str(), tmp.c_str(), data.c_str(), data.size())); if (!reply) { warningstream << "saveBlock: redis command 'HSET' failed on " "block " << PP(pos) << ": " << ctx->errstr << std::endl; freeReplyObject(reply); return false; } if (reply->type == REDIS_REPLY_ERROR) { warningstream << "saveBlock: saving block " << PP(pos) << " failed: " << std::string(reply->str, reply->len) << std::endl; freeReplyObject(reply); return false; } freeReplyObject(reply); return true; } void Database_Redis::loadBlock(const v3s16 &pos, std::string *block) { std::string tmp = i64tos(getBlockAsInteger(pos)); redisReply *reply = static_cast<redisReply *>(redisCommand(ctx, "HGET %s %s", hash.c_str(), tmp.c_str())); if (!reply) { throw DatabaseException(std::string( "Redis command 'HGET %s %s' failed: ") + ctx->errstr); } switch (reply->type) { case REDIS_REPLY_STRING: { *block = std::string(reply->str, reply->len); // std::string copies the memory so this won't cause any problems freeReplyObject(reply); return; } case REDIS_REPLY_ERROR: { std::string errstr(reply->str, reply->len); freeReplyObject(reply); errorstream << "loadBlock: loading block " << PP(pos) << " failed: " << errstr << std::endl; throw DatabaseException(std::string( "Redis command 'HGET %s %s' errored: ") + errstr); } case REDIS_REPLY_NIL: { *block = ""; // block not found in database freeReplyObject(reply); return; } } errorstream << "loadBlock: loading block " << PP(pos) << " returned invalid reply type " << reply->type << ": " << std::string(reply->str, reply->len) << std::endl; freeReplyObject(reply); throw DatabaseException(std::string( "Redis command 'HGET %s %s' gave invalid reply.")); } bool Database_Redis::deleteBlock(const v3s16 &pos) { std::string tmp = i64tos(getBlockAsInteger(pos)); redisReply *reply = static_cast<redisReply *>(redisCommand(ctx, "HDEL %s %s", hash.c_str(), tmp.c_str())); if (!reply) { throw DatabaseException(std::string( "Redis command 'HDEL %s %s' failed: ") + ctx->errstr); } else if (reply->type == REDIS_REPLY_ERROR) { warningstream << "deleteBlock: deleting block " << PP(pos) << " failed: " << std::string(reply->str, reply->len) << std::endl; freeReplyObject(reply); return false; } freeReplyObject(reply); return true; } void Database_Redis::listAllLoadableBlocks(std::vector<v3s16> &dst) { redisReply *reply = static_cast<redisReply *>(redisCommand(ctx, "HKEYS %s", hash.c_str())); if (!reply) { throw DatabaseException(std::string( "Redis command 'HKEYS %s' failed: ") + ctx->errstr); } switch (reply->type) { case REDIS_REPLY_ARRAY: dst.reserve(reply->elements); for (size_t i = 0; i < reply->elements; i++) { assert(reply->element[i]->type == REDIS_REPLY_STRING); dst.push_back(getIntegerAsBlock(stoi64(reply->element[i]->str))); } break; case REDIS_REPLY_ERROR: throw DatabaseException(std::string( "Failed to get keys from database: ") + std::string(reply->str, reply->len)); } freeReplyObject(reply); } #endif // USE_REDIS
pgimeno/minetest
src/database/database-redis.cpp
C++
mit
6,098
/* Minetest Copyright (C) 2014 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "config.h" #if USE_REDIS #include <hiredis.h> #include <string> #include "database.h" class Settings; class Database_Redis : public MapDatabase { public: Database_Redis(Settings &conf); ~Database_Redis(); void beginSave(); void endSave(); bool saveBlock(const v3s16 &pos, const std::string &data); void loadBlock(const v3s16 &pos, std::string *block); bool deleteBlock(const v3s16 &pos); void listAllLoadableBlocks(std::vector<v3s16> &dst); private: redisContext *ctx = nullptr; std::string hash = ""; }; #endif // USE_REDIS
pgimeno/minetest
src/database/database-redis.h
C++
mit
1,351
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* SQLite format specification: blocks: (PK) INT id BLOB data */ #include "database-sqlite3.h" #include "log.h" #include "filesys.h" #include "exceptions.h" #include "settings.h" #include "porting.h" #include "util/string.h" #include "content_sao.h" #include "remoteplayer.h" #include <cassert> // When to print messages when the database is being held locked by another process // Note: I've seen occasional delays of over 250ms while running minetestmapper. #define BUSY_INFO_TRESHOLD 100 // Print first informational message after 100ms. #define BUSY_WARNING_TRESHOLD 250 // Print warning message after 250ms. Lag is increased. #define BUSY_ERROR_TRESHOLD 1000 // Print error message after 1000ms. Significant lag. #define BUSY_FATAL_TRESHOLD 3000 // Allow SQLITE_BUSY to be returned, which will cause a minetest crash. #define BUSY_ERROR_INTERVAL 10000 // Safety net: report again every 10 seconds #define SQLRES(s, r, m) \ if ((s) != (r)) { \ throw DatabaseException(std::string(m) + ": " +\ sqlite3_errmsg(m_database)); \ } #define SQLOK(s, m) SQLRES(s, SQLITE_OK, m) #define PREPARE_STATEMENT(name, query) \ SQLOK(sqlite3_prepare_v2(m_database, query, -1, &m_stmt_##name, NULL),\ "Failed to prepare query '" query "'") #define SQLOK_ERRSTREAM(s, m) \ if ((s) != SQLITE_OK) { \ errorstream << (m) << ": " \ << sqlite3_errmsg(m_database) << std::endl; \ } #define FINALIZE_STATEMENT(statement) SQLOK_ERRSTREAM(sqlite3_finalize(statement), \ "Failed to finalize " #statement) int Database_SQLite3::busyHandler(void *data, int count) { s64 &first_time = reinterpret_cast<s64 *>(data)[0]; s64 &prev_time = reinterpret_cast<s64 *>(data)[1]; s64 cur_time = porting::getTimeMs(); if (count == 0) { first_time = cur_time; prev_time = first_time; } else { while (cur_time < prev_time) cur_time += s64(1)<<32; } if (cur_time - first_time < BUSY_INFO_TRESHOLD) { ; // do nothing } else if (cur_time - first_time >= BUSY_INFO_TRESHOLD && prev_time - first_time < BUSY_INFO_TRESHOLD) { infostream << "SQLite3 database has been locked for " << cur_time - first_time << " ms." << std::endl; } else if (cur_time - first_time >= BUSY_WARNING_TRESHOLD && prev_time - first_time < BUSY_WARNING_TRESHOLD) { warningstream << "SQLite3 database has been locked for " << cur_time - first_time << " ms." << std::endl; } else if (cur_time - first_time >= BUSY_ERROR_TRESHOLD && prev_time - first_time < BUSY_ERROR_TRESHOLD) { errorstream << "SQLite3 database has been locked for " << cur_time - first_time << " ms; this causes lag." << std::endl; } else if (cur_time - first_time >= BUSY_FATAL_TRESHOLD && prev_time - first_time < BUSY_FATAL_TRESHOLD) { errorstream << "SQLite3 database has been locked for " << cur_time - first_time << " ms - giving up!" << std::endl; } else if ((cur_time - first_time) / BUSY_ERROR_INTERVAL != (prev_time - first_time) / BUSY_ERROR_INTERVAL) { // Safety net: keep reporting every BUSY_ERROR_INTERVAL errorstream << "SQLite3 database has been locked for " << (cur_time - first_time) / 1000 << " seconds!" << std::endl; } prev_time = cur_time; // Make sqlite transaction fail if delay exceeds BUSY_FATAL_TRESHOLD return cur_time - first_time < BUSY_FATAL_TRESHOLD; } Database_SQLite3::Database_SQLite3(const std::string &savedir, const std::string &dbname) : m_savedir(savedir), m_dbname(dbname) { } void Database_SQLite3::beginSave() { verifyDatabase(); SQLRES(sqlite3_step(m_stmt_begin), SQLITE_DONE, "Failed to start SQLite3 transaction"); sqlite3_reset(m_stmt_begin); } void Database_SQLite3::endSave() { verifyDatabase(); SQLRES(sqlite3_step(m_stmt_end), SQLITE_DONE, "Failed to commit SQLite3 transaction"); sqlite3_reset(m_stmt_end); } void Database_SQLite3::openDatabase() { if (m_database) return; std::string dbp = m_savedir + DIR_DELIM + m_dbname + ".sqlite"; // Open the database connection if (!fs::CreateAllDirs(m_savedir)) { infostream << "Database_SQLite3: Failed to create directory \"" << m_savedir << "\"" << std::endl; throw FileNotGoodException("Failed to create database " "save directory"); } bool needs_create = !fs::PathExists(dbp); SQLOK(sqlite3_open_v2(dbp.c_str(), &m_database, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL), std::string("Failed to open SQLite3 database file ") + dbp); SQLOK(sqlite3_busy_handler(m_database, Database_SQLite3::busyHandler, m_busy_handler_data), "Failed to set SQLite3 busy handler"); if (needs_create) { createDatabase(); } std::string query_str = std::string("PRAGMA synchronous = ") + itos(g_settings->getU16("sqlite_synchronous")); SQLOK(sqlite3_exec(m_database, query_str.c_str(), NULL, NULL, NULL), "Failed to modify sqlite3 synchronous mode"); SQLOK(sqlite3_exec(m_database, "PRAGMA foreign_keys = ON", NULL, NULL, NULL), "Failed to enable sqlite3 foreign key support"); } void Database_SQLite3::verifyDatabase() { if (m_initialized) return; openDatabase(); PREPARE_STATEMENT(begin, "BEGIN;"); PREPARE_STATEMENT(end, "COMMIT;"); initStatements(); m_initialized = true; } Database_SQLite3::~Database_SQLite3() { FINALIZE_STATEMENT(m_stmt_begin) FINALIZE_STATEMENT(m_stmt_end) SQLOK_ERRSTREAM(sqlite3_close(m_database), "Failed to close database"); } /* * Map database */ MapDatabaseSQLite3::MapDatabaseSQLite3(const std::string &savedir): Database_SQLite3(savedir, "map"), MapDatabase() { } MapDatabaseSQLite3::~MapDatabaseSQLite3() { FINALIZE_STATEMENT(m_stmt_read) FINALIZE_STATEMENT(m_stmt_write) FINALIZE_STATEMENT(m_stmt_list) FINALIZE_STATEMENT(m_stmt_delete) } void MapDatabaseSQLite3::createDatabase() { assert(m_database); // Pre-condition SQLOK(sqlite3_exec(m_database, "CREATE TABLE IF NOT EXISTS `blocks` (\n" " `pos` INT PRIMARY KEY,\n" " `data` BLOB\n" ");\n", NULL, NULL, NULL), "Failed to create database table"); } void MapDatabaseSQLite3::initStatements() { PREPARE_STATEMENT(read, "SELECT `data` FROM `blocks` WHERE `pos` = ? LIMIT 1"); #ifdef __ANDROID__ PREPARE_STATEMENT(write, "INSERT INTO `blocks` (`pos`, `data`) VALUES (?, ?)"); #else PREPARE_STATEMENT(write, "REPLACE INTO `blocks` (`pos`, `data`) VALUES (?, ?)"); #endif PREPARE_STATEMENT(delete, "DELETE FROM `blocks` WHERE `pos` = ?"); PREPARE_STATEMENT(list, "SELECT `pos` FROM `blocks`"); verbosestream << "ServerMap: SQLite3 database opened." << std::endl; } inline void MapDatabaseSQLite3::bindPos(sqlite3_stmt *stmt, const v3s16 &pos, int index) { SQLOK(sqlite3_bind_int64(stmt, index, getBlockAsInteger(pos)), "Internal error: failed to bind query at " __FILE__ ":" TOSTRING(__LINE__)); } bool MapDatabaseSQLite3::deleteBlock(const v3s16 &pos) { verifyDatabase(); bindPos(m_stmt_delete, pos); bool good = sqlite3_step(m_stmt_delete) == SQLITE_DONE; sqlite3_reset(m_stmt_delete); if (!good) { warningstream << "deleteBlock: Block failed to delete " << PP(pos) << ": " << sqlite3_errmsg(m_database) << std::endl; } return good; } bool MapDatabaseSQLite3::saveBlock(const v3s16 &pos, const std::string &data) { verifyDatabase(); #ifdef __ANDROID__ /** * Note: For some unknown reason SQLite3 fails to REPLACE blocks on Android, * deleting them and then inserting works. */ bindPos(m_stmt_read, pos); if (sqlite3_step(m_stmt_read) == SQLITE_ROW) { deleteBlock(pos); } sqlite3_reset(m_stmt_read); #endif bindPos(m_stmt_write, pos); SQLOK(sqlite3_bind_blob(m_stmt_write, 2, data.data(), data.size(), NULL), "Internal error: failed to bind query at " __FILE__ ":" TOSTRING(__LINE__)); SQLRES(sqlite3_step(m_stmt_write), SQLITE_DONE, "Failed to save block") sqlite3_reset(m_stmt_write); return true; } void MapDatabaseSQLite3::loadBlock(const v3s16 &pos, std::string *block) { verifyDatabase(); bindPos(m_stmt_read, pos); if (sqlite3_step(m_stmt_read) != SQLITE_ROW) { sqlite3_reset(m_stmt_read); return; } const char *data = (const char *) sqlite3_column_blob(m_stmt_read, 0); size_t len = sqlite3_column_bytes(m_stmt_read, 0); *block = (data) ? std::string(data, len) : ""; sqlite3_step(m_stmt_read); // We should never get more than 1 row, so ok to reset sqlite3_reset(m_stmt_read); } void MapDatabaseSQLite3::listAllLoadableBlocks(std::vector<v3s16> &dst) { verifyDatabase(); while (sqlite3_step(m_stmt_list) == SQLITE_ROW) dst.push_back(getIntegerAsBlock(sqlite3_column_int64(m_stmt_list, 0))); sqlite3_reset(m_stmt_list); } /* * Player Database */ PlayerDatabaseSQLite3::PlayerDatabaseSQLite3(const std::string &savedir): Database_SQLite3(savedir, "players"), PlayerDatabase() { } PlayerDatabaseSQLite3::~PlayerDatabaseSQLite3() { FINALIZE_STATEMENT(m_stmt_player_load) FINALIZE_STATEMENT(m_stmt_player_add) FINALIZE_STATEMENT(m_stmt_player_update) FINALIZE_STATEMENT(m_stmt_player_remove) FINALIZE_STATEMENT(m_stmt_player_list) FINALIZE_STATEMENT(m_stmt_player_add_inventory) FINALIZE_STATEMENT(m_stmt_player_add_inventory_items) FINALIZE_STATEMENT(m_stmt_player_remove_inventory) FINALIZE_STATEMENT(m_stmt_player_remove_inventory_items) FINALIZE_STATEMENT(m_stmt_player_load_inventory) FINALIZE_STATEMENT(m_stmt_player_load_inventory_items) FINALIZE_STATEMENT(m_stmt_player_metadata_load) FINALIZE_STATEMENT(m_stmt_player_metadata_add) FINALIZE_STATEMENT(m_stmt_player_metadata_remove) }; void PlayerDatabaseSQLite3::createDatabase() { assert(m_database); // Pre-condition SQLOK(sqlite3_exec(m_database, "CREATE TABLE IF NOT EXISTS `player` (" "`name` VARCHAR(50) NOT NULL," "`pitch` NUMERIC(11, 4) NOT NULL," "`yaw` NUMERIC(11, 4) NOT NULL," "`posX` NUMERIC(11, 4) NOT NULL," "`posY` NUMERIC(11, 4) NOT NULL," "`posZ` NUMERIC(11, 4) NOT NULL," "`hp` INT NOT NULL," "`breath` INT NOT NULL," "`creation_date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," "`modification_date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," "PRIMARY KEY (`name`));", NULL, NULL, NULL), "Failed to create player table"); SQLOK(sqlite3_exec(m_database, "CREATE TABLE IF NOT EXISTS `player_metadata` (" " `player` VARCHAR(50) NOT NULL," " `metadata` VARCHAR(256) NOT NULL," " `value` TEXT," " PRIMARY KEY(`player`, `metadata`)," " FOREIGN KEY (`player`) REFERENCES player (`name`) ON DELETE CASCADE );", NULL, NULL, NULL), "Failed to create player metadata table"); SQLOK(sqlite3_exec(m_database, "CREATE TABLE IF NOT EXISTS `player_inventories` (" " `player` VARCHAR(50) NOT NULL," " `inv_id` INT NOT NULL," " `inv_width` INT NOT NULL," " `inv_name` TEXT NOT NULL DEFAULT ''," " `inv_size` INT NOT NULL," " PRIMARY KEY(player, inv_id)," " FOREIGN KEY (`player`) REFERENCES player (`name`) ON DELETE CASCADE );", NULL, NULL, NULL), "Failed to create player inventory table"); SQLOK(sqlite3_exec(m_database, "CREATE TABLE `player_inventory_items` (" " `player` VARCHAR(50) NOT NULL," " `inv_id` INT NOT NULL," " `slot_id` INT NOT NULL," " `item` TEXT NOT NULL DEFAULT ''," " PRIMARY KEY(player, inv_id, slot_id)," " FOREIGN KEY (`player`) REFERENCES player (`name`) ON DELETE CASCADE );", NULL, NULL, NULL), "Failed to create player inventory items table"); } void PlayerDatabaseSQLite3::initStatements() { PREPARE_STATEMENT(player_load, "SELECT `pitch`, `yaw`, `posX`, `posY`, `posZ`, `hp`, " "`breath`" "FROM `player` WHERE `name` = ?") PREPARE_STATEMENT(player_add, "INSERT INTO `player` (`name`, `pitch`, `yaw`, `posX`, " "`posY`, `posZ`, `hp`, `breath`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") PREPARE_STATEMENT(player_update, "UPDATE `player` SET `pitch` = ?, `yaw` = ?, " "`posX` = ?, `posY` = ?, `posZ` = ?, `hp` = ?, `breath` = ?, " "`modification_date` = CURRENT_TIMESTAMP WHERE `name` = ?") PREPARE_STATEMENT(player_remove, "DELETE FROM `player` WHERE `name` = ?") PREPARE_STATEMENT(player_list, "SELECT `name` FROM `player`") PREPARE_STATEMENT(player_add_inventory, "INSERT INTO `player_inventories` " "(`player`, `inv_id`, `inv_width`, `inv_name`, `inv_size`) VALUES (?, ?, ?, ?, ?)") PREPARE_STATEMENT(player_add_inventory_items, "INSERT INTO `player_inventory_items` " "(`player`, `inv_id`, `slot_id`, `item`) VALUES (?, ?, ?, ?)") PREPARE_STATEMENT(player_remove_inventory, "DELETE FROM `player_inventories` " "WHERE `player` = ?") PREPARE_STATEMENT(player_remove_inventory_items, "DELETE FROM `player_inventory_items` " "WHERE `player` = ?") PREPARE_STATEMENT(player_load_inventory, "SELECT `inv_id`, `inv_width`, `inv_name`, " "`inv_size` FROM `player_inventories` WHERE `player` = ? ORDER BY inv_id") PREPARE_STATEMENT(player_load_inventory_items, "SELECT `slot_id`, `item` " "FROM `player_inventory_items` WHERE `player` = ? AND `inv_id` = ?") PREPARE_STATEMENT(player_metadata_load, "SELECT `metadata`, `value` FROM " "`player_metadata` WHERE `player` = ?") PREPARE_STATEMENT(player_metadata_add, "INSERT INTO `player_metadata` " "(`player`, `metadata`, `value`) VALUES (?, ?, ?)") PREPARE_STATEMENT(player_metadata_remove, "DELETE FROM `player_metadata` " "WHERE `player` = ?") verbosestream << "ServerEnvironment: SQLite3 database opened (players)." << std::endl; } bool PlayerDatabaseSQLite3::playerDataExists(const std::string &name) { verifyDatabase(); str_to_sqlite(m_stmt_player_load, 1, name); bool res = (sqlite3_step(m_stmt_player_load) == SQLITE_ROW); sqlite3_reset(m_stmt_player_load); return res; } void PlayerDatabaseSQLite3::savePlayer(RemotePlayer *player) { PlayerSAO* sao = player->getPlayerSAO(); sanity_check(sao); const v3f &pos = sao->getBasePosition(); // Begin save in brace is mandatory if (!playerDataExists(player->getName())) { beginSave(); str_to_sqlite(m_stmt_player_add, 1, player->getName()); double_to_sqlite(m_stmt_player_add, 2, sao->getLookPitch()); double_to_sqlite(m_stmt_player_add, 3, sao->getRotation().Y); double_to_sqlite(m_stmt_player_add, 4, pos.X); double_to_sqlite(m_stmt_player_add, 5, pos.Y); double_to_sqlite(m_stmt_player_add, 6, pos.Z); int64_to_sqlite(m_stmt_player_add, 7, sao->getHP()); int64_to_sqlite(m_stmt_player_add, 8, sao->getBreath()); sqlite3_vrfy(sqlite3_step(m_stmt_player_add), SQLITE_DONE); sqlite3_reset(m_stmt_player_add); } else { beginSave(); double_to_sqlite(m_stmt_player_update, 1, sao->getLookPitch()); double_to_sqlite(m_stmt_player_update, 2, sao->getRotation().Y); double_to_sqlite(m_stmt_player_update, 3, pos.X); double_to_sqlite(m_stmt_player_update, 4, pos.Y); double_to_sqlite(m_stmt_player_update, 5, pos.Z); int64_to_sqlite(m_stmt_player_update, 6, sao->getHP()); int64_to_sqlite(m_stmt_player_update, 7, sao->getBreath()); str_to_sqlite(m_stmt_player_update, 8, player->getName()); sqlite3_vrfy(sqlite3_step(m_stmt_player_update), SQLITE_DONE); sqlite3_reset(m_stmt_player_update); } // Write player inventories str_to_sqlite(m_stmt_player_remove_inventory, 1, player->getName()); sqlite3_vrfy(sqlite3_step(m_stmt_player_remove_inventory), SQLITE_DONE); sqlite3_reset(m_stmt_player_remove_inventory); str_to_sqlite(m_stmt_player_remove_inventory_items, 1, player->getName()); sqlite3_vrfy(sqlite3_step(m_stmt_player_remove_inventory_items), SQLITE_DONE); sqlite3_reset(m_stmt_player_remove_inventory_items); std::vector<const InventoryList*> inventory_lists = sao->getInventory()->getLists(); for (u16 i = 0; i < inventory_lists.size(); i++) { const InventoryList* list = inventory_lists[i]; str_to_sqlite(m_stmt_player_add_inventory, 1, player->getName()); int_to_sqlite(m_stmt_player_add_inventory, 2, i); int_to_sqlite(m_stmt_player_add_inventory, 3, list->getWidth()); str_to_sqlite(m_stmt_player_add_inventory, 4, list->getName()); int_to_sqlite(m_stmt_player_add_inventory, 5, list->getSize()); sqlite3_vrfy(sqlite3_step(m_stmt_player_add_inventory), SQLITE_DONE); sqlite3_reset(m_stmt_player_add_inventory); for (u32 j = 0; j < list->getSize(); j++) { std::ostringstream os; list->getItem(j).serialize(os); std::string itemStr = os.str(); str_to_sqlite(m_stmt_player_add_inventory_items, 1, player->getName()); int_to_sqlite(m_stmt_player_add_inventory_items, 2, i); int_to_sqlite(m_stmt_player_add_inventory_items, 3, j); str_to_sqlite(m_stmt_player_add_inventory_items, 4, itemStr); sqlite3_vrfy(sqlite3_step(m_stmt_player_add_inventory_items), SQLITE_DONE); sqlite3_reset(m_stmt_player_add_inventory_items); } } str_to_sqlite(m_stmt_player_metadata_remove, 1, player->getName()); sqlite3_vrfy(sqlite3_step(m_stmt_player_metadata_remove), SQLITE_DONE); sqlite3_reset(m_stmt_player_metadata_remove); const StringMap &attrs = sao->getMeta().getStrings(); for (const auto &attr : attrs) { str_to_sqlite(m_stmt_player_metadata_add, 1, player->getName()); str_to_sqlite(m_stmt_player_metadata_add, 2, attr.first); str_to_sqlite(m_stmt_player_metadata_add, 3, attr.second); sqlite3_vrfy(sqlite3_step(m_stmt_player_metadata_add), SQLITE_DONE); sqlite3_reset(m_stmt_player_metadata_add); } endSave(); player->onSuccessfulSave(); } bool PlayerDatabaseSQLite3::loadPlayer(RemotePlayer *player, PlayerSAO *sao) { verifyDatabase(); str_to_sqlite(m_stmt_player_load, 1, player->getName()); if (sqlite3_step(m_stmt_player_load) != SQLITE_ROW) { sqlite3_reset(m_stmt_player_load); return false; } sao->setLookPitch(sqlite_to_float(m_stmt_player_load, 0)); sao->setPlayerYaw(sqlite_to_float(m_stmt_player_load, 1)); sao->setBasePosition(sqlite_to_v3f(m_stmt_player_load, 2)); sao->setHPRaw((u16) MYMIN(sqlite_to_int(m_stmt_player_load, 5), U16_MAX)); sao->setBreath((u16) MYMIN(sqlite_to_int(m_stmt_player_load, 6), U16_MAX), false); sqlite3_reset(m_stmt_player_load); // Load inventory str_to_sqlite(m_stmt_player_load_inventory, 1, player->getName()); while (sqlite3_step(m_stmt_player_load_inventory) == SQLITE_ROW) { InventoryList *invList = player->inventory.addList( sqlite_to_string(m_stmt_player_load_inventory, 2), sqlite_to_uint(m_stmt_player_load_inventory, 3)); invList->setWidth(sqlite_to_uint(m_stmt_player_load_inventory, 1)); u32 invId = sqlite_to_uint(m_stmt_player_load_inventory, 0); str_to_sqlite(m_stmt_player_load_inventory_items, 1, player->getName()); int_to_sqlite(m_stmt_player_load_inventory_items, 2, invId); while (sqlite3_step(m_stmt_player_load_inventory_items) == SQLITE_ROW) { const std::string itemStr = sqlite_to_string(m_stmt_player_load_inventory_items, 1); if (itemStr.length() > 0) { ItemStack stack; stack.deSerialize(itemStr); invList->changeItem(sqlite_to_uint(m_stmt_player_load_inventory_items, 0), stack); } } sqlite3_reset(m_stmt_player_load_inventory_items); } sqlite3_reset(m_stmt_player_load_inventory); str_to_sqlite(m_stmt_player_metadata_load, 1, sao->getPlayer()->getName()); while (sqlite3_step(m_stmt_player_metadata_load) == SQLITE_ROW) { std::string attr = sqlite_to_string(m_stmt_player_metadata_load, 0); std::string value = sqlite_to_string(m_stmt_player_metadata_load, 1); sao->getMeta().setString(attr, value); } sao->getMeta().setModified(false); sqlite3_reset(m_stmt_player_metadata_load); return true; } bool PlayerDatabaseSQLite3::removePlayer(const std::string &name) { if (!playerDataExists(name)) return false; str_to_sqlite(m_stmt_player_remove, 1, name); sqlite3_vrfy(sqlite3_step(m_stmt_player_remove), SQLITE_DONE); sqlite3_reset(m_stmt_player_remove); return true; } void PlayerDatabaseSQLite3::listPlayers(std::vector<std::string> &res) { verifyDatabase(); while (sqlite3_step(m_stmt_player_list) == SQLITE_ROW) res.push_back(sqlite_to_string(m_stmt_player_list, 0)); sqlite3_reset(m_stmt_player_list); } /* * Auth database */ AuthDatabaseSQLite3::AuthDatabaseSQLite3(const std::string &savedir) : Database_SQLite3(savedir, "auth"), AuthDatabase() { } AuthDatabaseSQLite3::~AuthDatabaseSQLite3() { FINALIZE_STATEMENT(m_stmt_read) FINALIZE_STATEMENT(m_stmt_write) FINALIZE_STATEMENT(m_stmt_create) FINALIZE_STATEMENT(m_stmt_delete) FINALIZE_STATEMENT(m_stmt_list_names) FINALIZE_STATEMENT(m_stmt_read_privs) FINALIZE_STATEMENT(m_stmt_write_privs) FINALIZE_STATEMENT(m_stmt_delete_privs) FINALIZE_STATEMENT(m_stmt_last_insert_rowid) } void AuthDatabaseSQLite3::createDatabase() { assert(m_database); // Pre-condition SQLOK(sqlite3_exec(m_database, "CREATE TABLE IF NOT EXISTS `auth` (" "`id` INTEGER PRIMARY KEY AUTOINCREMENT," "`name` VARCHAR(32) UNIQUE," "`password` VARCHAR(512)," "`last_login` INTEGER" ");", NULL, NULL, NULL), "Failed to create auth table"); SQLOK(sqlite3_exec(m_database, "CREATE TABLE IF NOT EXISTS `user_privileges` (" "`id` INTEGER," "`privilege` VARCHAR(32)," "PRIMARY KEY (id, privilege)" "CONSTRAINT fk_id FOREIGN KEY (id) REFERENCES auth (id) ON DELETE CASCADE" ");", NULL, NULL, NULL), "Failed to create auth privileges table"); } void AuthDatabaseSQLite3::initStatements() { PREPARE_STATEMENT(read, "SELECT id, name, password, last_login FROM auth WHERE name = ?"); PREPARE_STATEMENT(write, "UPDATE auth set name = ?, password = ?, last_login = ? WHERE id = ?"); PREPARE_STATEMENT(create, "INSERT INTO auth (name, password, last_login) VALUES (?, ?, ?)"); PREPARE_STATEMENT(delete, "DELETE FROM auth WHERE name = ?"); PREPARE_STATEMENT(list_names, "SELECT name FROM auth ORDER BY name DESC"); PREPARE_STATEMENT(read_privs, "SELECT privilege FROM user_privileges WHERE id = ?"); PREPARE_STATEMENT(write_privs, "INSERT OR IGNORE INTO user_privileges (id, privilege) VALUES (?, ?)"); PREPARE_STATEMENT(delete_privs, "DELETE FROM user_privileges WHERE id = ?"); PREPARE_STATEMENT(last_insert_rowid, "SELECT last_insert_rowid()"); } bool AuthDatabaseSQLite3::getAuth(const std::string &name, AuthEntry &res) { verifyDatabase(); str_to_sqlite(m_stmt_read, 1, name); if (sqlite3_step(m_stmt_read) != SQLITE_ROW) { sqlite3_reset(m_stmt_read); return false; } res.id = sqlite_to_uint(m_stmt_read, 0); res.name = sqlite_to_string(m_stmt_read, 1); res.password = sqlite_to_string(m_stmt_read, 2); res.last_login = sqlite_to_int64(m_stmt_read, 3); sqlite3_reset(m_stmt_read); int64_to_sqlite(m_stmt_read_privs, 1, res.id); while (sqlite3_step(m_stmt_read_privs) == SQLITE_ROW) { res.privileges.emplace_back(sqlite_to_string(m_stmt_read_privs, 0)); } sqlite3_reset(m_stmt_read_privs); return true; } bool AuthDatabaseSQLite3::saveAuth(const AuthEntry &authEntry) { beginSave(); str_to_sqlite(m_stmt_write, 1, authEntry.name); str_to_sqlite(m_stmt_write, 2, authEntry.password); int64_to_sqlite(m_stmt_write, 3, authEntry.last_login); int64_to_sqlite(m_stmt_write, 4, authEntry.id); sqlite3_vrfy(sqlite3_step(m_stmt_write), SQLITE_DONE); sqlite3_reset(m_stmt_write); writePrivileges(authEntry); endSave(); return true; } bool AuthDatabaseSQLite3::createAuth(AuthEntry &authEntry) { beginSave(); // id autoincrements str_to_sqlite(m_stmt_create, 1, authEntry.name); str_to_sqlite(m_stmt_create, 2, authEntry.password); int64_to_sqlite(m_stmt_create, 3, authEntry.last_login); sqlite3_vrfy(sqlite3_step(m_stmt_create), SQLITE_DONE); sqlite3_reset(m_stmt_create); // obtain id and write back to original authEntry sqlite3_step(m_stmt_last_insert_rowid); authEntry.id = sqlite_to_uint(m_stmt_last_insert_rowid, 0); sqlite3_reset(m_stmt_last_insert_rowid); writePrivileges(authEntry); endSave(); return true; } bool AuthDatabaseSQLite3::deleteAuth(const std::string &name) { verifyDatabase(); str_to_sqlite(m_stmt_delete, 1, name); sqlite3_vrfy(sqlite3_step(m_stmt_delete), SQLITE_DONE); int changes = sqlite3_changes(m_database); sqlite3_reset(m_stmt_delete); // privileges deleted by foreign key on delete cascade return changes > 0; } void AuthDatabaseSQLite3::listNames(std::vector<std::string> &res) { verifyDatabase(); while (sqlite3_step(m_stmt_list_names) == SQLITE_ROW) { res.push_back(sqlite_to_string(m_stmt_list_names, 0)); } sqlite3_reset(m_stmt_list_names); } void AuthDatabaseSQLite3::reload() { // noop for SQLite } void AuthDatabaseSQLite3::writePrivileges(const AuthEntry &authEntry) { int64_to_sqlite(m_stmt_delete_privs, 1, authEntry.id); sqlite3_vrfy(sqlite3_step(m_stmt_delete_privs), SQLITE_DONE); sqlite3_reset(m_stmt_delete_privs); for (const std::string &privilege : authEntry.privileges) { int64_to_sqlite(m_stmt_write_privs, 1, authEntry.id); str_to_sqlite(m_stmt_write_privs, 2, privilege); sqlite3_vrfy(sqlite3_step(m_stmt_write_privs), SQLITE_DONE); sqlite3_reset(m_stmt_write_privs); } }
pgimeno/minetest
src/database/database-sqlite3.cpp
C++
mit
25,537
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <cstring> #include <string> #include "database.h" #include "exceptions.h" extern "C" { #include "sqlite3.h" } class Database_SQLite3 : public Database { public: virtual ~Database_SQLite3(); void beginSave(); void endSave(); bool initialized() const { return m_initialized; } protected: Database_SQLite3(const std::string &savedir, const std::string &dbname); // Open and initialize the database if needed void verifyDatabase(); // Convertors inline void str_to_sqlite(sqlite3_stmt *s, int iCol, const std::string &str) const { sqlite3_vrfy(sqlite3_bind_text(s, iCol, str.c_str(), str.size(), NULL)); } inline void str_to_sqlite(sqlite3_stmt *s, int iCol, const char *str) const { sqlite3_vrfy(sqlite3_bind_text(s, iCol, str, strlen(str), NULL)); } inline void int_to_sqlite(sqlite3_stmt *s, int iCol, int val) const { sqlite3_vrfy(sqlite3_bind_int(s, iCol, val)); } inline void int64_to_sqlite(sqlite3_stmt *s, int iCol, s64 val) const { sqlite3_vrfy(sqlite3_bind_int64(s, iCol, (sqlite3_int64) val)); } inline void double_to_sqlite(sqlite3_stmt *s, int iCol, double val) const { sqlite3_vrfy(sqlite3_bind_double(s, iCol, val)); } inline std::string sqlite_to_string(sqlite3_stmt *s, int iCol) { const char* text = reinterpret_cast<const char*>(sqlite3_column_text(s, iCol)); return std::string(text ? text : ""); } inline s32 sqlite_to_int(sqlite3_stmt *s, int iCol) { return sqlite3_column_int(s, iCol); } inline u32 sqlite_to_uint(sqlite3_stmt *s, int iCol) { return (u32) sqlite3_column_int(s, iCol); } inline s64 sqlite_to_int64(sqlite3_stmt *s, int iCol) { return (s64) sqlite3_column_int64(s, iCol); } inline u64 sqlite_to_uint64(sqlite3_stmt *s, int iCol) { return (u64) sqlite3_column_int64(s, iCol); } inline float sqlite_to_float(sqlite3_stmt *s, int iCol) { return (float) sqlite3_column_double(s, iCol); } inline const v3f sqlite_to_v3f(sqlite3_stmt *s, int iCol) { return v3f(sqlite_to_float(s, iCol), sqlite_to_float(s, iCol + 1), sqlite_to_float(s, iCol + 2)); } // Query verifiers helpers inline void sqlite3_vrfy(int s, const std::string &m = "", int r = SQLITE_OK) const { if (s != r) throw DatabaseException(m + ": " + sqlite3_errmsg(m_database)); } inline void sqlite3_vrfy(const int s, const int r, const std::string &m = "") const { sqlite3_vrfy(s, m, r); } // Create the database structure virtual void createDatabase() = 0; virtual void initStatements() = 0; sqlite3 *m_database = nullptr; private: // Open the database void openDatabase(); bool m_initialized = false; std::string m_savedir = ""; std::string m_dbname = ""; sqlite3_stmt *m_stmt_begin = nullptr; sqlite3_stmt *m_stmt_end = nullptr; s64 m_busy_handler_data[2]; static int busyHandler(void *data, int count); }; class MapDatabaseSQLite3 : private Database_SQLite3, public MapDatabase { public: MapDatabaseSQLite3(const std::string &savedir); virtual ~MapDatabaseSQLite3(); bool saveBlock(const v3s16 &pos, const std::string &data); void loadBlock(const v3s16 &pos, std::string *block); bool deleteBlock(const v3s16 &pos); void listAllLoadableBlocks(std::vector<v3s16> &dst); void beginSave() { Database_SQLite3::beginSave(); } void endSave() { Database_SQLite3::endSave(); } protected: virtual void createDatabase(); virtual void initStatements(); private: void bindPos(sqlite3_stmt *stmt, const v3s16 &pos, int index = 1); // Map sqlite3_stmt *m_stmt_read = nullptr; sqlite3_stmt *m_stmt_write = nullptr; sqlite3_stmt *m_stmt_list = nullptr; sqlite3_stmt *m_stmt_delete = nullptr; }; class PlayerDatabaseSQLite3 : private Database_SQLite3, public PlayerDatabase { public: PlayerDatabaseSQLite3(const std::string &savedir); virtual ~PlayerDatabaseSQLite3(); void savePlayer(RemotePlayer *player); bool loadPlayer(RemotePlayer *player, PlayerSAO *sao); bool removePlayer(const std::string &name); void listPlayers(std::vector<std::string> &res); protected: virtual void createDatabase(); virtual void initStatements(); private: bool playerDataExists(const std::string &name); // Players sqlite3_stmt *m_stmt_player_load = nullptr; sqlite3_stmt *m_stmt_player_add = nullptr; sqlite3_stmt *m_stmt_player_update = nullptr; sqlite3_stmt *m_stmt_player_remove = nullptr; sqlite3_stmt *m_stmt_player_list = nullptr; sqlite3_stmt *m_stmt_player_load_inventory = nullptr; sqlite3_stmt *m_stmt_player_load_inventory_items = nullptr; sqlite3_stmt *m_stmt_player_add_inventory = nullptr; sqlite3_stmt *m_stmt_player_add_inventory_items = nullptr; sqlite3_stmt *m_stmt_player_remove_inventory = nullptr; sqlite3_stmt *m_stmt_player_remove_inventory_items = nullptr; sqlite3_stmt *m_stmt_player_metadata_load = nullptr; sqlite3_stmt *m_stmt_player_metadata_remove = nullptr; sqlite3_stmt *m_stmt_player_metadata_add = nullptr; }; class AuthDatabaseSQLite3 : private Database_SQLite3, public AuthDatabase { public: AuthDatabaseSQLite3(const std::string &savedir); virtual ~AuthDatabaseSQLite3(); virtual bool getAuth(const std::string &name, AuthEntry &res); virtual bool saveAuth(const AuthEntry &authEntry); virtual bool createAuth(AuthEntry &authEntry); virtual bool deleteAuth(const std::string &name); virtual void listNames(std::vector<std::string> &res); virtual void reload(); protected: virtual void createDatabase(); virtual void initStatements(); private: virtual void writePrivileges(const AuthEntry &authEntry); sqlite3_stmt *m_stmt_read = nullptr; sqlite3_stmt *m_stmt_write = nullptr; sqlite3_stmt *m_stmt_create = nullptr; sqlite3_stmt *m_stmt_delete = nullptr; sqlite3_stmt *m_stmt_list_names = nullptr; sqlite3_stmt *m_stmt_read_privs = nullptr; sqlite3_stmt *m_stmt_write_privs = nullptr; sqlite3_stmt *m_stmt_delete_privs = nullptr; sqlite3_stmt *m_stmt_last_insert_rowid = nullptr; };
pgimeno/minetest
src/database/database-sqlite3.h
C++
mit
6,690
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "database.h" #include "irrlichttypes.h" /**************** * Black magic! * **************** * The position hashing is very messed up. * It's a lot more complicated than it looks. */ static inline s16 unsigned_to_signed(u16 i, u16 max_positive) { if (i < max_positive) { return i; } return i - (max_positive * 2); } // Modulo of a negative number does not work consistently in C static inline s64 pythonmodulo(s64 i, s16 mod) { if (i >= 0) { return i % mod; } return mod - ((-i) % mod); } s64 MapDatabase::getBlockAsInteger(const v3s16 &pos) { return (u64) pos.Z * 0x1000000 + (u64) pos.Y * 0x1000 + (u64) pos.X; } v3s16 MapDatabase::getIntegerAsBlock(s64 i) { v3s16 pos; pos.X = unsigned_to_signed(pythonmodulo(i, 4096), 2048); i = (i - pos.X) / 4096; pos.Y = unsigned_to_signed(pythonmodulo(i, 4096), 2048); i = (i - pos.Y) / 4096; pos.Z = unsigned_to_signed(pythonmodulo(i, 4096), 2048); return pos; }
pgimeno/minetest
src/database/database.cpp
C++
mit
1,736
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <set> #include <string> #include <vector> #include "irr_v3d.h" #include "irrlichttypes.h" #include "util/basic_macros.h" class Database { public: virtual void beginSave() = 0; virtual void endSave() = 0; virtual bool initialized() const { return true; } }; class MapDatabase : public Database { public: virtual ~MapDatabase() = default; virtual bool saveBlock(const v3s16 &pos, const std::string &data) = 0; virtual void loadBlock(const v3s16 &pos, std::string *block) = 0; virtual bool deleteBlock(const v3s16 &pos) = 0; static s64 getBlockAsInteger(const v3s16 &pos); static v3s16 getIntegerAsBlock(s64 i); virtual void listAllLoadableBlocks(std::vector<v3s16> &dst) = 0; }; class PlayerSAO; class RemotePlayer; class PlayerDatabase { public: virtual ~PlayerDatabase() = default; virtual void savePlayer(RemotePlayer *player) = 0; virtual bool loadPlayer(RemotePlayer *player, PlayerSAO *sao) = 0; virtual bool removePlayer(const std::string &name) = 0; virtual void listPlayers(std::vector<std::string> &res) = 0; }; struct AuthEntry { u64 id; std::string name; std::string password; std::vector<std::string> privileges; s64 last_login; }; class AuthDatabase { public: virtual ~AuthDatabase() = default; virtual bool getAuth(const std::string &name, AuthEntry &res) = 0; virtual bool saveAuth(const AuthEntry &authEntry) = 0; virtual bool createAuth(AuthEntry &authEntry) = 0; virtual bool deleteAuth(const std::string &name) = 0; virtual void listNames(std::vector<std::string> &res) = 0; virtual void reload() = 0; };
pgimeno/minetest
src/database/database.h
C++
mit
2,369
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once inline u32 time_to_daynight_ratio(float time_of_day, bool smooth) { float t = time_of_day; if (t < 0.0f) t += ((int)(-t) / 24000) * 24000.0f; if (t >= 24000.0f) t -= ((int)(t) / 24000) * 24000.0f; if (t > 12000.0f) t = 24000.0f - t; const float values[9][2] = { {4250.0f + 125.0f, 150.0f}, {4500.0f + 125.0f, 150.0f}, {4750.0f + 125.0f, 250.0f}, {5000.0f + 125.0f, 350.0f}, {5250.0f + 125.0f, 500.0f}, {5500.0f + 125.0f, 675.0f}, {5750.0f + 125.0f, 875.0f}, {6000.0f + 125.0f, 1000.0f}, {6250.0f + 125.0f, 1000.0f}, }; if (!smooth) { float lastt = values[0][0]; for (u32 i = 1; i < 9; i++) { float t0 = values[i][0]; float switch_t = (t0 + lastt) / 2.0f; lastt = t0; if (switch_t <= t) continue; return values[i][1]; } return 1000; } if (t <= 4625.0f) // 4500 + 125 return values[0][1]; else if (t >= 6125.0f) // 6000 + 125 return 1000; for (u32 i = 0; i < 9; i++) { if (values[i][0] <= t) continue; float td0 = values[i][0] - values[i - 1][0]; float f = (t - values[i - 1][0]) / td0; return f * values[i][1] + (1.0f - f) * values[i - 1][1]; } return 1000; }
pgimeno/minetest
src/daynightratio.h
C++
mit
1,948
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "porting.h" #include "debug.h" #include "exceptions.h" #include <cstdio> #include <cstdlib> #include <cstring> #include <map> #include <sstream> #include <thread> #include "threading/mutex_auto_lock.h" #include "config.h" #ifdef _MSC_VER #include <dbghelp.h> #include "version.h" #include "filesys.h" #endif #if USE_CURSES #include "terminal_chat_console.h" #endif /* Assert */ void sanity_check_fn(const char *assertion, const char *file, unsigned int line, const char *function) { #if USE_CURSES g_term_console.stopAndWaitforThread(); #endif errorstream << std::endl << "In thread " << std::hex << std::this_thread::get_id() << ":" << std::endl; errorstream << file << ":" << line << ": " << function << ": An engine assumption '" << assertion << "' failed." << std::endl; abort(); } void fatal_error_fn(const char *msg, const char *file, unsigned int line, const char *function) { #if USE_CURSES g_term_console.stopAndWaitforThread(); #endif errorstream << std::endl << "In thread " << std::hex << std::this_thread::get_id() << ":" << std::endl; errorstream << file << ":" << line << ": " << function << ": A fatal error occurred: " << msg << std::endl; abort(); } #ifdef _MSC_VER const char *Win32ExceptionCodeToString(DWORD exception_code) { switch (exception_code) { case EXCEPTION_ACCESS_VIOLATION: return "Access violation"; case EXCEPTION_DATATYPE_MISALIGNMENT: return "Misaligned data access"; case EXCEPTION_BREAKPOINT: return "Breakpoint reached"; case EXCEPTION_SINGLE_STEP: return "Single debug step"; case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: return "Array access out of bounds"; case EXCEPTION_FLT_DENORMAL_OPERAND: return "Denormal floating point operand"; case EXCEPTION_FLT_DIVIDE_BY_ZERO: return "Floating point division by zero"; case EXCEPTION_FLT_INEXACT_RESULT: return "Inaccurate floating point result"; case EXCEPTION_FLT_INVALID_OPERATION: return "Invalid floating point operation"; case EXCEPTION_FLT_OVERFLOW: return "Floating point exponent overflow"; case EXCEPTION_FLT_STACK_CHECK: return "Floating point stack overflow or underflow"; case EXCEPTION_FLT_UNDERFLOW: return "Floating point exponent underflow"; case EXCEPTION_INT_DIVIDE_BY_ZERO: return "Integer division by zero"; case EXCEPTION_INT_OVERFLOW: return "Integer overflow"; case EXCEPTION_PRIV_INSTRUCTION: return "Privileged instruction executed"; case EXCEPTION_IN_PAGE_ERROR: return "Could not access or load page"; case EXCEPTION_ILLEGAL_INSTRUCTION: return "Illegal instruction encountered"; case EXCEPTION_NONCONTINUABLE_EXCEPTION: return "Attempted to continue after fatal exception"; case EXCEPTION_STACK_OVERFLOW: return "Stack overflow"; case EXCEPTION_INVALID_DISPOSITION: return "Invalid disposition returned to the exception dispatcher"; case EXCEPTION_GUARD_PAGE: return "Attempted guard page access"; case EXCEPTION_INVALID_HANDLE: return "Invalid handle"; } return "Unknown exception"; } long WINAPI Win32ExceptionHandler(struct _EXCEPTION_POINTERS *pExceptInfo) { char buf[512]; MINIDUMP_EXCEPTION_INFORMATION mdei; MINIDUMP_USER_STREAM_INFORMATION mdusi; MINIDUMP_USER_STREAM mdus; bool minidump_created = false; std::string dumpfile = porting::path_user + DIR_DELIM PROJECT_NAME ".dmp"; std::string version_str(PROJECT_NAME " "); version_str += g_version_hash; HANDLE hFile = CreateFileA(dumpfile.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) goto minidump_failed; if (SetEndOfFile(hFile) == FALSE) goto minidump_failed; mdei.ClientPointers = NULL; mdei.ExceptionPointers = pExceptInfo; mdei.ThreadId = GetCurrentThreadId(); mdus.Type = CommentStreamA; mdus.BufferSize = version_str.size(); mdus.Buffer = (PVOID)version_str.c_str(); mdusi.UserStreamArray = &mdus; mdusi.UserStreamCount = 1; if (MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &mdei, &mdusi, NULL) == FALSE) goto minidump_failed; minidump_created = true; minidump_failed: CloseHandle(hFile); DWORD excode = pExceptInfo->ExceptionRecord->ExceptionCode; _snprintf(buf, sizeof(buf), " >> === FATAL ERROR ===\n" " >> %s (Exception 0x%08X) at 0x%p\n", Win32ExceptionCodeToString(excode), excode, pExceptInfo->ExceptionRecord->ExceptionAddress); dstream << buf; if (minidump_created) dstream << " >> Saved dump to " << dumpfile << std::endl; else dstream << " >> Failed to save dump" << std::endl; return EXCEPTION_EXECUTE_HANDLER; } #endif void debug_set_exception_handler() { #ifdef _MSC_VER SetUnhandledExceptionFilter(Win32ExceptionHandler); #endif }
pgimeno/minetest
src/debug.cpp
C++
mit
5,530
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <iostream> #include <exception> #include <cassert> #include "gettime.h" #include "log.h" #ifdef _WIN32 #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif #include <windows.h> #ifdef _MSC_VER #include <eh.h> #endif #define NORETURN __declspec(noreturn) #define FUNCTION_NAME __FUNCTION__ #else #define NORETURN __attribute__ ((__noreturn__)) #define FUNCTION_NAME __PRETTY_FUNCTION__ #endif // Whether to catch all std::exceptions. // When "catching", the program will abort with an error message. // In debug mode, leave these for the debugger and don't catch them. #ifdef NDEBUG #define CATCH_UNHANDLED_EXCEPTIONS 1 #else #define CATCH_UNHANDLED_EXCEPTIONS 0 #endif /* Abort program execution immediately */ NORETURN extern void fatal_error_fn( const char *msg, const char *file, unsigned int line, const char *function); #define FATAL_ERROR(msg) \ fatal_error_fn((msg), __FILE__, __LINE__, FUNCTION_NAME) #define FATAL_ERROR_IF(expr, msg) \ ((expr) \ ? fatal_error_fn((msg), __FILE__, __LINE__, FUNCTION_NAME) \ : (void)(0)) /* sanity_check() Equivalent to assert() but persists in Release builds (i.e. when NDEBUG is defined) */ NORETURN extern void sanity_check_fn( const char *assertion, const char *file, unsigned int line, const char *function); #define SANITY_CHECK(expr) \ ((expr) \ ? (void)(0) \ : sanity_check_fn(#expr, __FILE__, __LINE__, FUNCTION_NAME)) #define sanity_check(expr) SANITY_CHECK(expr) void debug_set_exception_handler(); /* These should be put into every thread */ #if CATCH_UNHANDLED_EXCEPTIONS == 1 #define BEGIN_DEBUG_EXCEPTION_HANDLER try { #define END_DEBUG_EXCEPTION_HANDLER \ } catch (std::exception &e) { \ errorstream << "An unhandled exception occurred: " \ << e.what() << std::endl; \ FATAL_ERROR(e.what()); \ } #else // Dummy ones #define BEGIN_DEBUG_EXCEPTION_HANDLER #define END_DEBUG_EXCEPTION_HANDLER #endif
pgimeno/minetest
src/debug.h
C++
mit
2,829
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "settings.h" #include "porting.h" #include "filesys.h" #include "config.h" #include "constants.h" #include "porting.h" #include "util/string.h" void set_default_settings(Settings *settings) { // Client and server settings->setDefault("language", ""); settings->setDefault("name", ""); settings->setDefault("bind_address", ""); settings->setDefault("serverlist_url", "servers.minetest.net"); // Client settings->setDefault("address", ""); settings->setDefault("enable_sound", "true"); settings->setDefault("sound_volume", "0.8"); settings->setDefault("mute_sound", "false"); settings->setDefault("enable_mesh_cache", "false"); settings->setDefault("mesh_generation_interval", "0"); settings->setDefault("meshgen_block_cache_size", "20"); settings->setDefault("enable_vbo", "true"); settings->setDefault("free_move", "false"); settings->setDefault("pitch_move", "false"); settings->setDefault("fast_move", "false"); settings->setDefault("noclip", "false"); settings->setDefault("screenshot_path", "."); settings->setDefault("screenshot_format", "png"); settings->setDefault("screenshot_quality", "0"); settings->setDefault("client_unload_unused_data_timeout", "600"); settings->setDefault("client_mapblock_limit", "5000"); settings->setDefault("enable_build_where_you_stand", "false"); settings->setDefault("curl_timeout", "5000"); settings->setDefault("curl_parallel_limit", "8"); settings->setDefault("curl_file_download_timeout", "300000"); settings->setDefault("curl_verify_cert", "true"); settings->setDefault("enable_remote_media_server", "true"); settings->setDefault("enable_client_modding", "false"); settings->setDefault("max_out_chat_queue_size", "20"); settings->setDefault("pause_on_lost_focus", "false"); settings->setDefault("enable_register_confirmation", "true"); // Keymap settings->setDefault("remote_port", "30000"); settings->setDefault("keymap_forward", "KEY_KEY_W"); settings->setDefault("keymap_autoforward", ""); settings->setDefault("keymap_backward", "KEY_KEY_S"); settings->setDefault("keymap_left", "KEY_KEY_A"); settings->setDefault("keymap_right", "KEY_KEY_D"); settings->setDefault("keymap_jump", "KEY_SPACE"); settings->setDefault("keymap_sneak", "KEY_LSHIFT"); settings->setDefault("keymap_drop", "KEY_KEY_Q"); settings->setDefault("keymap_zoom", "KEY_KEY_Z"); settings->setDefault("keymap_inventory", "KEY_KEY_I"); settings->setDefault("keymap_special1", "KEY_KEY_E"); settings->setDefault("keymap_chat", "KEY_KEY_T"); settings->setDefault("keymap_cmd", "/"); settings->setDefault("keymap_cmd_local", "."); settings->setDefault("keymap_minimap", "KEY_F9"); settings->setDefault("keymap_console", "KEY_F10"); settings->setDefault("keymap_rangeselect", "KEY_KEY_R"); settings->setDefault("keymap_freemove", "KEY_KEY_K"); settings->setDefault("keymap_pitchmove", "KEY_KEY_P"); settings->setDefault("keymap_fastmove", "KEY_KEY_J"); settings->setDefault("keymap_noclip", "KEY_KEY_H"); settings->setDefault("keymap_hotbar_next", "KEY_KEY_N"); settings->setDefault("keymap_hotbar_previous", "KEY_KEY_B"); settings->setDefault("keymap_mute", "KEY_KEY_M"); settings->setDefault("keymap_increase_volume", ""); settings->setDefault("keymap_decrease_volume", ""); settings->setDefault("keymap_cinematic", ""); settings->setDefault("keymap_toggle_hud", "KEY_F1"); settings->setDefault("keymap_toggle_chat", "KEY_F2"); settings->setDefault("keymap_toggle_fog", "KEY_F3"); #if DEBUG settings->setDefault("keymap_toggle_update_camera", "KEY_F4"); #else settings->setDefault("keymap_toggle_update_camera", ""); #endif settings->setDefault("keymap_toggle_debug", "KEY_F5"); settings->setDefault("keymap_toggle_profiler", "KEY_F6"); settings->setDefault("keymap_camera_mode", "KEY_F7"); settings->setDefault("keymap_screenshot", "KEY_F12"); settings->setDefault("keymap_increase_viewing_range_min", "+"); settings->setDefault("keymap_decrease_viewing_range_min", "-"); settings->setDefault("keymap_slot1", "KEY_KEY_1"); settings->setDefault("keymap_slot2", "KEY_KEY_2"); settings->setDefault("keymap_slot3", "KEY_KEY_3"); settings->setDefault("keymap_slot4", "KEY_KEY_4"); settings->setDefault("keymap_slot5", "KEY_KEY_5"); settings->setDefault("keymap_slot6", "KEY_KEY_6"); settings->setDefault("keymap_slot7", "KEY_KEY_7"); settings->setDefault("keymap_slot8", "KEY_KEY_8"); settings->setDefault("keymap_slot9", "KEY_KEY_9"); settings->setDefault("keymap_slot10", "KEY_KEY_0"); settings->setDefault("keymap_slot11", ""); settings->setDefault("keymap_slot12", ""); settings->setDefault("keymap_slot13", ""); settings->setDefault("keymap_slot14", ""); settings->setDefault("keymap_slot15", ""); settings->setDefault("keymap_slot16", ""); settings->setDefault("keymap_slot17", ""); settings->setDefault("keymap_slot18", ""); settings->setDefault("keymap_slot19", ""); settings->setDefault("keymap_slot20", ""); settings->setDefault("keymap_slot21", ""); settings->setDefault("keymap_slot22", ""); settings->setDefault("keymap_slot23", ""); settings->setDefault("keymap_slot24", ""); settings->setDefault("keymap_slot25", ""); settings->setDefault("keymap_slot26", ""); settings->setDefault("keymap_slot27", ""); settings->setDefault("keymap_slot28", ""); settings->setDefault("keymap_slot29", ""); settings->setDefault("keymap_slot30", ""); settings->setDefault("keymap_slot31", ""); settings->setDefault("keymap_slot32", ""); // Some (temporary) keys for debugging settings->setDefault("keymap_quicktune_prev", "KEY_HOME"); settings->setDefault("keymap_quicktune_next", "KEY_END"); settings->setDefault("keymap_quicktune_dec", "KEY_NEXT"); settings->setDefault("keymap_quicktune_inc", "KEY_PRIOR"); // Visuals #ifdef NDEBUG settings->setDefault("show_debug", "false"); #else settings->setDefault("show_debug", "true"); #endif settings->setDefault("fsaa", "0"); settings->setDefault("undersampling", "0"); settings->setDefault("world_aligned_mode", "enable"); settings->setDefault("autoscale_mode", "disable"); settings->setDefault("enable_fog", "true"); settings->setDefault("fog_start", "0.4"); settings->setDefault("3d_mode", "none"); settings->setDefault("3d_paralax_strength", "0.025"); settings->setDefault("tooltip_show_delay", "400"); settings->setDefault("tooltip_append_itemname", "false"); settings->setDefault("fps_max", "60"); settings->setDefault("pause_fps_max", "20"); settings->setDefault("viewing_range", "100"); settings->setDefault("near_plane", "0.1"); settings->setDefault("screen_w", "1024"); settings->setDefault("screen_h", "600"); settings->setDefault("autosave_screensize", "true"); settings->setDefault("fullscreen", "false"); settings->setDefault("fullscreen_bpp", "24"); settings->setDefault("vsync", "false"); settings->setDefault("fov", "72"); settings->setDefault("leaves_style", "fancy"); settings->setDefault("connected_glass", "false"); settings->setDefault("smooth_lighting", "true"); settings->setDefault("lighting_alpha", "0.0"); settings->setDefault("lighting_beta", "1.5"); settings->setDefault("display_gamma", "1.0"); settings->setDefault("lighting_boost", "0.2"); settings->setDefault("lighting_boost_center", "0.5"); settings->setDefault("lighting_boost_spread", "0.2"); settings->setDefault("texture_path", ""); settings->setDefault("shader_path", ""); settings->setDefault("video_driver", "opengl"); settings->setDefault("cinematic", "false"); settings->setDefault("camera_smoothing", "0"); settings->setDefault("cinematic_camera_smoothing", "0.7"); settings->setDefault("enable_clouds", "true"); settings->setDefault("view_bobbing_amount", "1.0"); settings->setDefault("fall_bobbing_amount", "0.03"); settings->setDefault("enable_3d_clouds", "true"); settings->setDefault("cloud_radius", "12"); settings->setDefault("menu_clouds", "true"); settings->setDefault("opaque_water", "false"); settings->setDefault("console_height", "0.6"); settings->setDefault("console_color", "(0,0,0)"); settings->setDefault("console_alpha", "200"); settings->setDefault("formspec_fullscreen_bg_color", "(0,0,0)"); settings->setDefault("formspec_fullscreen_bg_opacity", "140"); settings->setDefault("formspec_default_bg_color", "(0,0,0)"); settings->setDefault("formspec_default_bg_opacity", "140"); settings->setDefault("selectionbox_color", "(0,0,0)"); settings->setDefault("selectionbox_width", "2"); settings->setDefault("node_highlighting", "box"); settings->setDefault("crosshair_color", "(255,255,255)"); settings->setDefault("crosshair_alpha", "255"); settings->setDefault("recent_chat_messages", "6"); settings->setDefault("hud_scaling", "1.0"); settings->setDefault("gui_scaling", "1.0"); settings->setDefault("gui_scaling_filter", "false"); settings->setDefault("gui_scaling_filter_txr2img", "true"); settings->setDefault("desynchronize_mapblock_texture_animation", "true"); settings->setDefault("hud_hotbar_max_width", "1.0"); settings->setDefault("enable_local_map_saving", "false"); settings->setDefault("show_entity_selectionbox", "true"); settings->setDefault("texture_clean_transparent", "false"); settings->setDefault("texture_min_size", "64"); settings->setDefault("ambient_occlusion_gamma", "2.2"); settings->setDefault("enable_shaders", "true"); settings->setDefault("enable_particles", "true"); settings->setDefault("arm_inertia", "true"); settings->setDefault("enable_minimap", "true"); settings->setDefault("minimap_shape_round", "true"); settings->setDefault("minimap_double_scan_height", "true"); // Effects settings->setDefault("directional_colored_fog", "true"); settings->setDefault("inventory_items_animations", "false"); settings->setDefault("mip_map", "false"); settings->setDefault("anisotropic_filter", "false"); settings->setDefault("bilinear_filter", "false"); settings->setDefault("trilinear_filter", "false"); settings->setDefault("tone_mapping", "false"); settings->setDefault("enable_bumpmapping", "false"); settings->setDefault("enable_parallax_occlusion", "false"); settings->setDefault("generate_normalmaps", "false"); settings->setDefault("normalmaps_strength", "0.6"); settings->setDefault("normalmaps_smooth", "1"); settings->setDefault("parallax_occlusion_mode", "1"); settings->setDefault("parallax_occlusion_iterations", "4"); settings->setDefault("parallax_occlusion_scale", "0.08"); settings->setDefault("parallax_occlusion_bias", "0.04"); settings->setDefault("enable_waving_water", "false"); settings->setDefault("water_wave_height", "1.0"); settings->setDefault("water_wave_length", "20.0"); settings->setDefault("water_wave_speed", "5.0"); settings->setDefault("enable_waving_leaves", "false"); settings->setDefault("enable_waving_plants", "false"); // Input settings->setDefault("invert_mouse", "false"); settings->setDefault("mouse_sensitivity", "0.2"); settings->setDefault("repeat_rightclick_time", "0.25"); settings->setDefault("safe_dig_and_place", "false"); settings->setDefault("random_input", "false"); settings->setDefault("aux1_descends", "false"); settings->setDefault("doubletap_jump", "false"); settings->setDefault("always_fly_fast", "true"); #ifdef __ANDROID__ settings->setDefault("autojump", "true"); #else settings->setDefault("autojump", "false"); #endif settings->setDefault("continuous_forward", "false"); settings->setDefault("enable_joysticks", "false"); settings->setDefault("joystick_id", "0"); settings->setDefault("joystick_type", ""); settings->setDefault("repeat_joystick_button_time", "0.17"); settings->setDefault("joystick_frustum_sensitivity", "170"); // Main menu settings->setDefault("main_menu_style", "full"); settings->setDefault("main_menu_path", ""); settings->setDefault("serverlist_file", "favoriteservers.txt"); #if USE_FREETYPE settings->setDefault("freetype", "true"); settings->setDefault("font_path", porting::getDataPath("fonts" DIR_DELIM "Arimo-Regular.ttf")); settings->setDefault("font_shadow", "1"); settings->setDefault("font_shadow_alpha", "127"); settings->setDefault("mono_font_path", porting::getDataPath("fonts" DIR_DELIM "Cousine-Regular.ttf")); settings->setDefault("fallback_font_path", porting::getDataPath("fonts" DIR_DELIM "DroidSansFallbackFull.ttf")); settings->setDefault("fallback_font_shadow", "1"); settings->setDefault("fallback_font_shadow_alpha", "128"); std::string font_size_str = std::to_string(TTF_DEFAULT_FONT_SIZE); settings->setDefault("fallback_font_size", font_size_str); #else settings->setDefault("freetype", "false"); settings->setDefault("font_path", porting::getDataPath("fonts" DIR_DELIM "mono_dejavu_sans")); settings->setDefault("mono_font_path", porting::getDataPath("fonts" DIR_DELIM "mono_dejavu_sans")); std::string font_size_str = std::to_string(DEFAULT_FONT_SIZE); #endif settings->setDefault("font_size", font_size_str); settings->setDefault("mono_font_size", font_size_str); settings->setDefault("contentdb_url", "https://content.minetest.net"); #ifdef __ANDROID__ settings->setDefault("contentdb_flag_blacklist", "nonfree, android_default"); #else settings->setDefault("contentdb_flag_blacklist", "nonfree, desktop_default"); #endif // Server settings->setDefault("disable_escape_sequences", "false"); settings->setDefault("strip_color_codes", "false"); // Network settings->setDefault("enable_ipv6", "true"); settings->setDefault("ipv6_server", "false"); settings->setDefault("max_packets_per_iteration","1024"); settings->setDefault("port", "30000"); settings->setDefault("strict_protocol_version_checking", "false"); settings->setDefault("player_transfer_distance", "0"); settings->setDefault("max_simultaneous_block_sends_per_client", "40"); settings->setDefault("time_send_interval", "5"); settings->setDefault("default_game", "minetest"); settings->setDefault("motd", ""); settings->setDefault("max_users", "15"); settings->setDefault("creative_mode", "false"); settings->setDefault("enable_damage", "true"); settings->setDefault("default_password", ""); settings->setDefault("default_privs", "interact, shout"); settings->setDefault("enable_pvp", "true"); settings->setDefault("enable_mod_channels", "false"); settings->setDefault("disallow_empty_password", "false"); settings->setDefault("disable_anticheat", "false"); settings->setDefault("enable_rollback_recording", "false"); #ifdef NDEBUG settings->setDefault("deprecated_lua_api_handling", "legacy"); #else settings->setDefault("deprecated_lua_api_handling", "log"); #endif settings->setDefault("kick_msg_shutdown", "Server shutting down."); settings->setDefault("kick_msg_crash", "This server has experienced an internal error. You will now be disconnected."); settings->setDefault("ask_reconnect_on_crash", "false"); settings->setDefault("profiler_print_interval", "0"); settings->setDefault("active_object_send_range_blocks", "4"); settings->setDefault("active_block_range", "3"); //settings->setDefault("max_simultaneous_block_sends_per_client", "1"); // This causes frametime jitter on client side, or does it? settings->setDefault("max_block_send_distance", "10"); settings->setDefault("block_send_optimize_distance", "4"); settings->setDefault("server_side_occlusion_culling", "true"); settings->setDefault("csm_restriction_flags", "62"); settings->setDefault("csm_restriction_noderange", "0"); settings->setDefault("max_clearobjects_extra_loaded_blocks", "4096"); settings->setDefault("time_speed", "72"); settings->setDefault("world_start_time", "5250"); settings->setDefault("server_unload_unused_data_timeout", "29"); settings->setDefault("max_objects_per_block", "64"); settings->setDefault("server_map_save_interval", "5.3"); settings->setDefault("chat_message_max_size", "500"); settings->setDefault("chat_message_limit_per_10sec", "8.0"); settings->setDefault("chat_message_limit_trigger_kick", "50"); settings->setDefault("sqlite_synchronous", "2"); settings->setDefault("full_block_send_enable_min_time_from_building", "2.0"); settings->setDefault("dedicated_server_step", "0.09"); settings->setDefault("active_block_mgmt_interval", "2.0"); settings->setDefault("abm_interval", "1.0"); settings->setDefault("nodetimer_interval", "0.2"); settings->setDefault("ignore_world_load_errors", "false"); settings->setDefault("remote_media", ""); settings->setDefault("debug_log_level", "action"); settings->setDefault("emergequeue_limit_total", "512"); settings->setDefault("emergequeue_limit_diskonly", "64"); settings->setDefault("emergequeue_limit_generate", "64"); settings->setDefault("num_emerge_threads", "1"); settings->setDefault("secure.enable_security", "true"); settings->setDefault("secure.trusted_mods", ""); settings->setDefault("secure.http_mods", ""); // Physics settings->setDefault("movement_acceleration_default", "3"); settings->setDefault("movement_acceleration_air", "2"); settings->setDefault("movement_acceleration_fast", "10"); settings->setDefault("movement_speed_walk", "4"); settings->setDefault("movement_speed_crouch", "1.35"); settings->setDefault("movement_speed_fast", "20"); settings->setDefault("movement_speed_climb", "3"); settings->setDefault("movement_speed_jump", "6.5"); settings->setDefault("movement_liquid_fluidity", "1"); settings->setDefault("movement_liquid_fluidity_smooth", "0.5"); settings->setDefault("movement_liquid_sink", "10"); settings->setDefault("movement_gravity", "9.81"); // Liquids settings->setDefault("liquid_loop_max", "100000"); settings->setDefault("liquid_queue_purge_time", "0"); settings->setDefault("liquid_update", "1.0"); // Mapgen settings->setDefault("mg_name", "v7"); settings->setDefault("water_level", "1"); settings->setDefault("mapgen_limit", "31000"); settings->setDefault("chunksize", "5"); settings->setDefault("mg_flags", "dungeons"); settings->setDefault("fixed_map_seed", ""); settings->setDefault("max_block_generate_distance", "8"); settings->setDefault("projecting_dungeons", "true"); settings->setDefault("enable_mapgen_debug_info", "false"); // Server list announcing settings->setDefault("server_announce", "false"); settings->setDefault("server_url", ""); settings->setDefault("server_address", ""); settings->setDefault("server_name", ""); settings->setDefault("server_description", ""); settings->setDefault("high_precision_fpu", "true"); settings->setDefault("enable_console", "false"); // Altered settings for macOS #if defined(__MACH__) && defined(__APPLE__) settings->setDefault("keymap_sneak", "KEY_SHIFT"); settings->setDefault("fps_max", "0"); #endif // Altered settings for Android #ifdef __ANDROID__ settings->setDefault("screen_w", "0"); settings->setDefault("screen_h", "0"); settings->setDefault("enable_shaders", "false"); settings->setDefault("fullscreen", "true"); settings->setDefault("video_driver", "ogles1"); settings->setDefault("touchtarget", "true"); settings->setDefault("TMPFolder","/sdcard/" PROJECT_NAME_C "/tmp/"); settings->setDefault("touchscreen_threshold","20"); settings->setDefault("fixed_virtual_joystick", "false"); settings->setDefault("virtual_joystick_triggers_aux", "false"); settings->setDefault("smooth_lighting", "false"); settings->setDefault("max_simultaneous_block_sends_per_client", "10"); settings->setDefault("emergequeue_limit_diskonly", "16"); settings->setDefault("emergequeue_limit_generate", "16"); settings->setDefault("max_block_generate_distance", "5"); settings->setDefault("enable_3d_clouds", "false"); settings->setDefault("fps_max", "30"); settings->setDefault("pause_fps_max", "10"); settings->setDefault("max_objects_per_block", "20"); settings->setDefault("sqlite_synchronous", "1"); settings->setDefault("server_map_save_interval", "15"); settings->setDefault("client_mapblock_limit", "1000"); settings->setDefault("active_block_range", "2"); settings->setDefault("viewing_range", "50"); settings->setDefault("leaves_style", "simple"); settings->setDefault("curl_verify_cert","false"); // Apply settings according to screen size float x_inches = ((double) porting::getDisplaySize().X / (160 * porting::getDisplayDensity())); if (x_inches < 3.7f) { settings->setDefault("hud_scaling", "0.6"); settings->setDefault("font_size", "14"); settings->setDefault("mono_font_size", "14"); } else if (x_inches < 4.5f) { settings->setDefault("hud_scaling", "0.7"); settings->setDefault("font_size", "14"); settings->setDefault("mono_font_size", "14"); } else if (x_inches < 6.0f) { settings->setDefault("hud_scaling", "0.85"); settings->setDefault("font_size", "14"); settings->setDefault("mono_font_size", "14"); } // Tablets >= 6.0 use non-Android defaults for these settings #else settings->setDefault("screen_dpi", "72"); #endif } void override_default_settings(Settings *settings, Settings *from) { std::vector<std::string> names = from->getNames(); for (const auto &name : names) { settings->setDefault(name, from->get(name)); } }
pgimeno/minetest
src/defaultsettings.cpp
C++
mit
21,790
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once class Settings; /** * initialize basic default settings * @param settings pointer to settings */ void set_default_settings(Settings *settings); /** * override a default settings by settings from another settings element * @param settings target settings pointer * @param from source settings pointer */ void override_default_settings(Settings *settings, Settings *from);
pgimeno/minetest
src/defaultsettings.h
C++
mit
1,179
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> Copyright (C) 2010-2013 kwolekr, Ryan Kwolek <kwolekr@minetest.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "emerge.h" #include <iostream> #include <queue> #include "util/container.h" #include "util/thread.h" #include "threading/event.h" #include "config.h" #include "constants.h" #include "environment.h" #include "log.h" #include "map.h" #include "mapblock.h" #include "mapgen/mg_biome.h" #include "mapgen/mg_ore.h" #include "mapgen/mg_decoration.h" #include "mapgen/mg_schematic.h" #include "nodedef.h" #include "profiler.h" #include "scripting_server.h" #include "server.h" #include "serverobject.h" #include "settings.h" #include "voxel.h" class EmergeThread : public Thread { public: bool enable_mapgen_debug_info; int id; EmergeThread(Server *server, int ethreadid); ~EmergeThread() = default; void *run(); void signal(); // Requires queue mutex held bool pushBlock(const v3s16 &pos); void cancelPendingItems(); static void runCompletionCallbacks( const v3s16 &pos, EmergeAction action, const EmergeCallbackList &callbacks); private: Server *m_server; ServerMap *m_map; EmergeManager *m_emerge; Mapgen *m_mapgen; Event m_queue_event; std::queue<v3s16> m_block_queue; bool popBlockEmerge(v3s16 *pos, BlockEmergeData *bedata); EmergeAction getBlockOrStartGen( const v3s16 &pos, bool allow_gen, MapBlock **block, BlockMakeData *data); MapBlock *finishGen(v3s16 pos, BlockMakeData *bmdata, std::map<v3s16, MapBlock *> *modified_blocks); friend class EmergeManager; }; class MapEditEventAreaIgnorer { public: MapEditEventAreaIgnorer(VoxelArea *ignorevariable, const VoxelArea &a): m_ignorevariable(ignorevariable) { if(m_ignorevariable->getVolume() == 0) *m_ignorevariable = a; else m_ignorevariable = NULL; } ~MapEditEventAreaIgnorer() { if(m_ignorevariable) { assert(m_ignorevariable->getVolume() != 0); *m_ignorevariable = VoxelArea(); } } private: VoxelArea *m_ignorevariable; }; //// //// EmergeManager //// EmergeManager::EmergeManager(Server *server) { this->ndef = server->getNodeDefManager(); this->biomemgr = new BiomeManager(server); this->oremgr = new OreManager(server); this->decomgr = new DecorationManager(server); this->schemmgr = new SchematicManager(server); // Note that accesses to this variable are not synchronized. // This is because the *only* thread ever starting or stopping // EmergeThreads should be the ServerThread. enable_mapgen_debug_info = g_settings->getBool("enable_mapgen_debug_info"); s16 nthreads = 1; g_settings->getS16NoEx("num_emerge_threads", nthreads); // If automatic, leave a proc for the main thread and one for // some other misc thread if (nthreads == 0) nthreads = Thread::getNumberOfProcessors() - 2; if (nthreads < 1) nthreads = 1; verbosestream << "Using " << nthreads << " emerge threads." << std::endl; m_qlimit_total = g_settings->getU16("emergequeue_limit_total"); if (!g_settings->getU16NoEx("emergequeue_limit_diskonly", m_qlimit_diskonly)) m_qlimit_diskonly = nthreads * 5 + 1; if (!g_settings->getU16NoEx("emergequeue_limit_generate", m_qlimit_generate)) m_qlimit_generate = nthreads + 1; // don't trust user input for something very important like this if (m_qlimit_total < 1) m_qlimit_total = 1; if (m_qlimit_diskonly < 1) m_qlimit_diskonly = 1; if (m_qlimit_generate < 1) m_qlimit_generate = 1; for (s16 i = 0; i < nthreads; i++) m_threads.push_back(new EmergeThread(server, i)); infostream << "EmergeManager: using " << nthreads << " threads" << std::endl; } EmergeManager::~EmergeManager() { for (u32 i = 0; i != m_threads.size(); i++) { EmergeThread *thread = m_threads[i]; if (m_threads_active) { thread->stop(); thread->signal(); thread->wait(); } delete thread; // Mapgen init might not be finished if there is an error during startup. if (m_mapgens.size() > i) delete m_mapgens[i]; } delete biomemgr; delete oremgr; delete decomgr; delete schemmgr; } void EmergeManager::initMapgens(MapgenParams *params) { FATAL_ERROR_IF(!m_mapgens.empty(), "Mapgen already initialised."); mgparams = params; for (u32 i = 0; i != m_threads.size(); i++) m_mapgens.push_back(Mapgen::createMapgen(params->mgtype, params, this)); } Mapgen *EmergeManager::getCurrentMapgen() { if (!m_threads_active) return nullptr; for (u32 i = 0; i != m_threads.size(); i++) { if (m_threads[i]->isCurrentThread()) return m_threads[i]->m_mapgen; } return nullptr; } void EmergeManager::startThreads() { if (m_threads_active) return; for (u32 i = 0; i != m_threads.size(); i++) m_threads[i]->start(); m_threads_active = true; } void EmergeManager::stopThreads() { if (!m_threads_active) return; // Request thread stop in parallel for (u32 i = 0; i != m_threads.size(); i++) { m_threads[i]->stop(); m_threads[i]->signal(); } // Then do the waiting for each for (u32 i = 0; i != m_threads.size(); i++) m_threads[i]->wait(); m_threads_active = false; } bool EmergeManager::isRunning() { return m_threads_active; } bool EmergeManager::enqueueBlockEmerge( session_t peer_id, v3s16 blockpos, bool allow_generate, bool ignore_queue_limits) { u16 flags = 0; if (allow_generate) flags |= BLOCK_EMERGE_ALLOW_GEN; if (ignore_queue_limits) flags |= BLOCK_EMERGE_FORCE_QUEUE; return enqueueBlockEmergeEx(blockpos, peer_id, flags, NULL, NULL); } bool EmergeManager::enqueueBlockEmergeEx( v3s16 blockpos, session_t peer_id, u16 flags, EmergeCompletionCallback callback, void *callback_param) { EmergeThread *thread = NULL; bool entry_already_exists = false; { MutexAutoLock queuelock(m_queue_mutex); if (!pushBlockEmergeData(blockpos, peer_id, flags, callback, callback_param, &entry_already_exists)) return false; if (entry_already_exists) return true; thread = getOptimalThread(); thread->pushBlock(blockpos); } thread->signal(); return true; } // // Mapgen-related helper functions // // TODO(hmmmm): Move this to ServerMap v3s16 EmergeManager::getContainingChunk(v3s16 blockpos) { return getContainingChunk(blockpos, mgparams->chunksize); } // TODO(hmmmm): Move this to ServerMap v3s16 EmergeManager::getContainingChunk(v3s16 blockpos, s16 chunksize) { s16 coff = -chunksize / 2; v3s16 chunk_offset(coff, coff, coff); return getContainerPos(blockpos - chunk_offset, chunksize) * chunksize + chunk_offset; } int EmergeManager::getSpawnLevelAtPoint(v2s16 p) { if (m_mapgens.empty() || !m_mapgens[0]) { errorstream << "EmergeManager: getSpawnLevelAtPoint() called" " before mapgen init" << std::endl; return 0; } return m_mapgens[0]->getSpawnLevelAtPoint(p); } int EmergeManager::getGroundLevelAtPoint(v2s16 p) { if (m_mapgens.empty() || !m_mapgens[0]) { errorstream << "EmergeManager: getGroundLevelAtPoint() called" " before mapgen init" << std::endl; return 0; } return m_mapgens[0]->getGroundLevelAtPoint(p); } // TODO(hmmmm): Move this to ServerMap bool EmergeManager::isBlockUnderground(v3s16 blockpos) { #if 0 v2s16 p = v2s16((blockpos.X * MAP_BLOCKSIZE) + MAP_BLOCKSIZE / 2, (blockpos.Y * MAP_BLOCKSIZE) + MAP_BLOCKSIZE / 2); int ground_level = getGroundLevelAtPoint(p); return blockpos.Y * (MAP_BLOCKSIZE + 1) <= min(water_level, ground_level); #endif // Use a simple heuristic; the above method is wildly inaccurate anyway. return blockpos.Y * (MAP_BLOCKSIZE + 1) <= mgparams->water_level; } bool EmergeManager::pushBlockEmergeData( v3s16 pos, u16 peer_requested, u16 flags, EmergeCompletionCallback callback, void *callback_param, bool *entry_already_exists) { u16 &count_peer = m_peer_queue_count[peer_requested]; if ((flags & BLOCK_EMERGE_FORCE_QUEUE) == 0) { if (m_blocks_enqueued.size() >= m_qlimit_total) return false; if (peer_requested != PEER_ID_INEXISTENT) { u16 qlimit_peer = (flags & BLOCK_EMERGE_ALLOW_GEN) ? m_qlimit_generate : m_qlimit_diskonly; if (count_peer >= qlimit_peer) return false; } } std::pair<std::map<v3s16, BlockEmergeData>::iterator, bool> findres; findres = m_blocks_enqueued.insert(std::make_pair(pos, BlockEmergeData())); BlockEmergeData &bedata = findres.first->second; *entry_already_exists = !findres.second; if (callback) bedata.callbacks.emplace_back(callback, callback_param); if (*entry_already_exists) { bedata.flags |= flags; } else { bedata.flags = flags; bedata.peer_requested = peer_requested; count_peer++; } return true; } bool EmergeManager::popBlockEmergeData(v3s16 pos, BlockEmergeData *bedata) { std::map<v3s16, BlockEmergeData>::iterator it; std::unordered_map<u16, u16>::iterator it2; it = m_blocks_enqueued.find(pos); if (it == m_blocks_enqueued.end()) return false; *bedata = it->second; it2 = m_peer_queue_count.find(bedata->peer_requested); if (it2 == m_peer_queue_count.end()) return false; u16 &count_peer = it2->second; assert(count_peer != 0); count_peer--; m_blocks_enqueued.erase(it); return true; } EmergeThread *EmergeManager::getOptimalThread() { size_t nthreads = m_threads.size(); FATAL_ERROR_IF(nthreads == 0, "No emerge threads!"); size_t index = 0; size_t nitems_lowest = m_threads[0]->m_block_queue.size(); for (size_t i = 1; i < nthreads; i++) { size_t nitems = m_threads[i]->m_block_queue.size(); if (nitems < nitems_lowest) { index = i; nitems_lowest = nitems; } } return m_threads[index]; } //// //// EmergeThread //// EmergeThread::EmergeThread(Server *server, int ethreadid) : enable_mapgen_debug_info(false), id(ethreadid), m_server(server), m_map(NULL), m_emerge(NULL), m_mapgen(NULL) { m_name = "Emerge-" + itos(ethreadid); } void EmergeThread::signal() { m_queue_event.signal(); } bool EmergeThread::pushBlock(const v3s16 &pos) { m_block_queue.push(pos); return true; } void EmergeThread::cancelPendingItems() { MutexAutoLock queuelock(m_emerge->m_queue_mutex); while (!m_block_queue.empty()) { BlockEmergeData bedata; v3s16 pos; pos = m_block_queue.front(); m_block_queue.pop(); m_emerge->popBlockEmergeData(pos, &bedata); runCompletionCallbacks(pos, EMERGE_CANCELLED, bedata.callbacks); } } void EmergeThread::runCompletionCallbacks(const v3s16 &pos, EmergeAction action, const EmergeCallbackList &callbacks) { for (size_t i = 0; i != callbacks.size(); i++) { EmergeCompletionCallback callback; void *param; callback = callbacks[i].first; param = callbacks[i].second; callback(pos, action, param); } } bool EmergeThread::popBlockEmerge(v3s16 *pos, BlockEmergeData *bedata) { MutexAutoLock queuelock(m_emerge->m_queue_mutex); if (m_block_queue.empty()) return false; *pos = m_block_queue.front(); m_block_queue.pop(); m_emerge->popBlockEmergeData(*pos, bedata); return true; } EmergeAction EmergeThread::getBlockOrStartGen( const v3s16 &pos, bool allow_gen, MapBlock **block, BlockMakeData *bmdata) { MutexAutoLock envlock(m_server->m_env_mutex); // 1). Attempt to fetch block from memory *block = m_map->getBlockNoCreateNoEx(pos); if (*block && !(*block)->isDummy()) { if ((*block)->isGenerated()) return EMERGE_FROM_MEMORY; } else { // 2). Attempt to load block from disk if it was not in the memory *block = m_map->loadBlock(pos); if (*block && (*block)->isGenerated()) return EMERGE_FROM_DISK; } // 3). Attempt to start generation if (allow_gen && m_map->initBlockMake(pos, bmdata)) return EMERGE_GENERATED; // All attempts failed; cancel this block emerge return EMERGE_CANCELLED; } MapBlock *EmergeThread::finishGen(v3s16 pos, BlockMakeData *bmdata, std::map<v3s16, MapBlock *> *modified_blocks) { MutexAutoLock envlock(m_server->m_env_mutex); ScopeProfiler sp(g_profiler, "EmergeThread: after Mapgen::makeChunk", SPT_AVG); /* Perform post-processing on blocks (invalidate lighting, queue liquid transforms, etc.) to finish block make */ m_map->finishBlockMake(bmdata, modified_blocks); MapBlock *block = m_map->getBlockNoCreateNoEx(pos); if (!block) { errorstream << "EmergeThread::finishGen: Couldn't grab block we " "just generated: " << PP(pos) << std::endl; return NULL; } v3s16 minp = bmdata->blockpos_min * MAP_BLOCKSIZE; v3s16 maxp = bmdata->blockpos_max * MAP_BLOCKSIZE + v3s16(1,1,1) * (MAP_BLOCKSIZE - 1); // Ignore map edit events, they will not need to be sent // to anybody because the block hasn't been sent to anybody MapEditEventAreaIgnorer ign( &m_server->m_ignore_map_edit_events_area, VoxelArea(minp, maxp)); /* Run Lua on_generated callbacks */ try { m_server->getScriptIface()->environment_OnGenerated( minp, maxp, m_mapgen->blockseed); } catch (LuaError &e) { m_server->setAsyncFatalError("Lua: finishGen" + std::string(e.what())); } /* Clear generate notifier events */ Mapgen *mg = m_emerge->getCurrentMapgen(); mg->gennotify.clearEvents(); EMERGE_DBG_OUT("ended up with: " << analyze_block(block)); /* Activate the block */ m_server->m_env->activateBlock(block, 0); return block; } void *EmergeThread::run() { BEGIN_DEBUG_EXCEPTION_HANDLER v3s16 pos; m_map = (ServerMap *)&(m_server->m_env->getMap()); m_emerge = m_server->m_emerge; m_mapgen = m_emerge->m_mapgens[id]; enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info; try { while (!stopRequested()) { std::map<v3s16, MapBlock *> modified_blocks; BlockEmergeData bedata; BlockMakeData bmdata; EmergeAction action; MapBlock *block; if (!popBlockEmerge(&pos, &bedata)) { m_queue_event.wait(); continue; } if (blockpos_over_max_limit(pos)) continue; bool allow_gen = bedata.flags & BLOCK_EMERGE_ALLOW_GEN; EMERGE_DBG_OUT("pos=" PP(pos) " allow_gen=" << allow_gen); action = getBlockOrStartGen(pos, allow_gen, &block, &bmdata); if (action == EMERGE_GENERATED) { { ScopeProfiler sp(g_profiler, "EmergeThread: Mapgen::makeChunk", SPT_AVG); TimeTaker t("mapgen::make_block()"); m_mapgen->makeChunk(&bmdata); if (!enable_mapgen_debug_info) t.stop(true); // Hide output } block = finishGen(pos, &bmdata, &modified_blocks); } runCompletionCallbacks(pos, action, bedata.callbacks); if (block) modified_blocks[pos] = block; if (!modified_blocks.empty()) m_server->SetBlocksNotSent(modified_blocks); } } catch (VersionMismatchException &e) { std::ostringstream err; err << "World data version mismatch in MapBlock " << PP(pos) << std::endl << "----" << std::endl << "\"" << e.what() << "\"" << std::endl << "See debug.txt." << std::endl << "World probably saved by a newer version of " PROJECT_NAME_C "." << std::endl; m_server->setAsyncFatalError(err.str()); } catch (SerializationError &e) { std::ostringstream err; err << "Invalid data in MapBlock " << PP(pos) << std::endl << "----" << std::endl << "\"" << e.what() << "\"" << std::endl << "See debug.txt." << std::endl << "You can ignore this using [ignore_world_load_errors = true]." << std::endl; m_server->setAsyncFatalError(err.str()); } END_DEBUG_EXCEPTION_HANDLER return NULL; }
pgimeno/minetest
src/emerge.cpp
C++
mit
15,878
/* Minetest Copyright (C) 2010-2013 kwolekr, Ryan Kwolek <kwolekr@minetest.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <map> #include <mutex> #include "network/networkprotocol.h" #include "irr_v3d.h" #include "util/container.h" #include "mapgen/mapgen.h" // for MapgenParams #include "map.h" #define BLOCK_EMERGE_ALLOW_GEN (1 << 0) #define BLOCK_EMERGE_FORCE_QUEUE (1 << 1) #define EMERGE_DBG_OUT(x) { \ if (enable_mapgen_debug_info) \ infostream << "EmergeThread: " x << std::endl; \ } class EmergeThread; class NodeDefManager; class Settings; class BiomeManager; class OreManager; class DecorationManager; class SchematicManager; class Server; // Structure containing inputs/outputs for chunk generation struct BlockMakeData { MMVManip *vmanip = nullptr; u64 seed = 0; v3s16 blockpos_min; v3s16 blockpos_max; v3s16 blockpos_requested; UniqueQueue<v3s16> transforming_liquid; const NodeDefManager *nodedef = nullptr; BlockMakeData() = default; ~BlockMakeData() { delete vmanip; } }; // Result from processing an item on the emerge queue enum EmergeAction { EMERGE_CANCELLED, EMERGE_ERRORED, EMERGE_FROM_MEMORY, EMERGE_FROM_DISK, EMERGE_GENERATED, }; // Callback typedef void (*EmergeCompletionCallback)( v3s16 blockpos, EmergeAction action, void *param); typedef std::vector< std::pair< EmergeCompletionCallback, void * > > EmergeCallbackList; struct BlockEmergeData { u16 peer_requested; u16 flags; EmergeCallbackList callbacks; }; class EmergeManager { public: const NodeDefManager *ndef; bool enable_mapgen_debug_info; // Generation Notify u32 gen_notify_on = 0; std::set<u32> gen_notify_on_deco_ids; // Parameters passed to mapgens owned by ServerMap // TODO(hmmmm): Remove this after mapgen helper methods using them // are moved to ServerMap MapgenParams *mgparams; // Hackish workaround: // For now, EmergeManager must hold onto a ptr to the Map's setting manager // since the Map can only be accessed through the Environment, and the // Environment is not created until after script initialization. MapSettingsManager *map_settings_mgr; // Managers of various map generation-related components BiomeManager *biomemgr; OreManager *oremgr; DecorationManager *decomgr; SchematicManager *schemmgr; // Methods EmergeManager(Server *server); ~EmergeManager(); DISABLE_CLASS_COPY(EmergeManager); void initMapgens(MapgenParams *mgparams); void startThreads(); void stopThreads(); bool isRunning(); bool enqueueBlockEmerge( session_t peer_id, v3s16 blockpos, bool allow_generate, bool ignore_queue_limits=false); bool enqueueBlockEmergeEx( v3s16 blockpos, session_t peer_id, u16 flags, EmergeCompletionCallback callback, void *callback_param); v3s16 getContainingChunk(v3s16 blockpos); Mapgen *getCurrentMapgen(); // Mapgen helpers methods int getSpawnLevelAtPoint(v2s16 p); int getGroundLevelAtPoint(v2s16 p); bool isBlockUnderground(v3s16 blockpos); static v3s16 getContainingChunk(v3s16 blockpos, s16 chunksize); private: std::vector<Mapgen *> m_mapgens; std::vector<EmergeThread *> m_threads; bool m_threads_active = false; std::mutex m_queue_mutex; std::map<v3s16, BlockEmergeData> m_blocks_enqueued; std::unordered_map<u16, u16> m_peer_queue_count; u16 m_qlimit_total; u16 m_qlimit_diskonly; u16 m_qlimit_generate; // Requires m_queue_mutex held EmergeThread *getOptimalThread(); bool pushBlockEmergeData( v3s16 pos, u16 peer_requested, u16 flags, EmergeCompletionCallback callback, void *callback_param, bool *entry_already_exists); bool popBlockEmergeData(v3s16 pos, BlockEmergeData *bedata); friend class EmergeThread; };
pgimeno/minetest
src/emerge.h
C++
mit
4,412
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <fstream> #include "environment.h" #include "collision.h" #include "raycast.h" #include "serverobject.h" #include "scripting_server.h" #include "server.h" #include "daynightratio.h" #include "emerge.h" Environment::Environment(IGameDef *gamedef): m_time_of_day_speed(0.0f), m_day_count(0), m_gamedef(gamedef) { m_cache_enable_shaders = g_settings->getBool("enable_shaders"); m_cache_active_block_mgmt_interval = g_settings->getFloat("active_block_mgmt_interval"); m_cache_abm_interval = g_settings->getFloat("abm_interval"); m_cache_nodetimer_interval = g_settings->getFloat("nodetimer_interval"); m_time_of_day = g_settings->getU32("world_start_time"); m_time_of_day_f = (float)m_time_of_day / 24000.0f; } u32 Environment::getDayNightRatio() { MutexAutoLock lock(this->m_time_lock); if (m_enable_day_night_ratio_override) return m_day_night_ratio_override; return time_to_daynight_ratio(m_time_of_day_f * 24000, m_cache_enable_shaders); } void Environment::setTimeOfDaySpeed(float speed) { m_time_of_day_speed = speed; } void Environment::setDayNightRatioOverride(bool enable, u32 value) { MutexAutoLock lock(this->m_time_lock); m_enable_day_night_ratio_override = enable; m_day_night_ratio_override = value; } void Environment::setTimeOfDay(u32 time) { MutexAutoLock lock(this->m_time_lock); if (m_time_of_day > time) ++m_day_count; m_time_of_day = time; m_time_of_day_f = (float)time / 24000.0; } u32 Environment::getTimeOfDay() { MutexAutoLock lock(this->m_time_lock); return m_time_of_day; } float Environment::getTimeOfDayF() { MutexAutoLock lock(this->m_time_lock); return m_time_of_day_f; } /* Check if a node is pointable */ inline static bool isPointableNode(const MapNode &n, const NodeDefManager *nodedef , bool liquids_pointable) { const ContentFeatures &features = nodedef->get(n); return features.pointable || (liquids_pointable && features.isLiquid()); } void Environment::continueRaycast(RaycastState *state, PointedThing *result) { const NodeDefManager *nodedef = getMap().getNodeDefManager(); if (state->m_initialization_needed) { // Add objects if (state->m_objects_pointable) { std::vector<PointedThing> found; getSelectedActiveObjects(state->m_shootline, found); for (const PointedThing &pointed : found) { state->m_found.push(pointed); } } // Set search range core::aabbox3d<s16> maximal_exceed = nodedef->getSelectionBoxIntUnion(); state->m_search_range.MinEdge = -maximal_exceed.MaxEdge; state->m_search_range.MaxEdge = -maximal_exceed.MinEdge; // Setting is done state->m_initialization_needed = false; } // The index of the first pointed thing that was not returned // before. The last index which needs to be tested. s16 lastIndex = state->m_iterator.m_last_index; if (!state->m_found.empty()) { lastIndex = state->m_iterator.getIndex( floatToInt(state->m_found.top().intersection_point, BS)); } Map &map = getMap(); // If a node is found, this is the center of the // first nodebox the shootline meets. v3f found_boxcenter(0, 0, 0); // The untested nodes are in this range. core::aabbox3d<s16> new_nodes; while (state->m_iterator.m_current_index <= lastIndex) { // Test the nodes around the current node in search_range. new_nodes = state->m_search_range; new_nodes.MinEdge += state->m_iterator.m_current_node_pos; new_nodes.MaxEdge += state->m_iterator.m_current_node_pos; // Only check new nodes v3s16 delta = state->m_iterator.m_current_node_pos - state->m_previous_node; if (delta.X > 0) { new_nodes.MinEdge.X = new_nodes.MaxEdge.X; } else if (delta.X < 0) { new_nodes.MaxEdge.X = new_nodes.MinEdge.X; } else if (delta.Y > 0) { new_nodes.MinEdge.Y = new_nodes.MaxEdge.Y; } else if (delta.Y < 0) { new_nodes.MaxEdge.Y = new_nodes.MinEdge.Y; } else if (delta.Z > 0) { new_nodes.MinEdge.Z = new_nodes.MaxEdge.Z; } else if (delta.Z < 0) { new_nodes.MaxEdge.Z = new_nodes.MinEdge.Z; } // For each untested node for (s16 x = new_nodes.MinEdge.X; x <= new_nodes.MaxEdge.X; x++) for (s16 y = new_nodes.MinEdge.Y; y <= new_nodes.MaxEdge.Y; y++) for (s16 z = new_nodes.MinEdge.Z; z <= new_nodes.MaxEdge.Z; z++) { MapNode n; v3s16 np(x, y, z); bool is_valid_position; n = map.getNodeNoEx(np, &is_valid_position); if (!(is_valid_position && isPointableNode(n, nodedef, state->m_liquids_pointable))) { continue; } PointedThing result; std::vector<aabb3f> boxes; n.getSelectionBoxes(nodedef, &boxes, n.getNeighbors(np, &map)); // Is there a collision with a selection box? bool is_colliding = false; // Minimal distance of all collisions float min_distance_sq = 10000000; // ID of the current box (loop counter) u16 id = 0; v3f npf = intToFloat(np, BS); // This loop translates the boxes to their in-world place. for (aabb3f &box : boxes) { box.MinEdge += npf; box.MaxEdge += npf; v3f intersection_point; v3s16 intersection_normal; if (!boxLineCollision(box, state->m_shootline.start, state->m_shootline.getVector(), &intersection_point, &intersection_normal)) { ++id; continue; } f32 distanceSq = (intersection_point - state->m_shootline.start).getLengthSQ(); // If this is the nearest collision, save it if (min_distance_sq > distanceSq) { min_distance_sq = distanceSq; result.intersection_point = intersection_point; result.intersection_normal = intersection_normal; result.box_id = id; found_boxcenter = box.getCenter(); is_colliding = true; } ++id; } // If there wasn't a collision, stop if (!is_colliding) { continue; } result.type = POINTEDTHING_NODE; result.node_undersurface = np; result.distanceSq = min_distance_sq; // Set undersurface and abovesurface nodes f32 d = 0.002 * BS; v3f fake_intersection = result.intersection_point; // Move intersection towards its source block. if (fake_intersection.X < found_boxcenter.X) { fake_intersection.X += d; } else { fake_intersection.X -= d; } if (fake_intersection.Y < found_boxcenter.Y) { fake_intersection.Y += d; } else { fake_intersection.Y -= d; } if (fake_intersection.Z < found_boxcenter.Z) { fake_intersection.Z += d; } else { fake_intersection.Z -= d; } result.node_real_undersurface = floatToInt( fake_intersection, BS); result.node_abovesurface = result.node_real_undersurface + result.intersection_normal; // Push found PointedThing state->m_found.push(result); // If this is nearer than the old nearest object, // the search can be shorter s16 newIndex = state->m_iterator.getIndex( result.node_real_undersurface); if (newIndex < lastIndex) { lastIndex = newIndex; } } // Next node state->m_previous_node = state->m_iterator.m_current_node_pos; state->m_iterator.next(); } // Return empty PointedThing if nothing left on the ray if (state->m_found.empty()) { result->type = POINTEDTHING_NOTHING; } else { *result = state->m_found.top(); state->m_found.pop(); } } void Environment::stepTimeOfDay(float dtime) { MutexAutoLock lock(this->m_time_lock); // Cached in order to prevent the two reads we do to give // different results (can be written by code not under the lock) f32 cached_time_of_day_speed = m_time_of_day_speed; f32 speed = cached_time_of_day_speed * 24000. / (24. * 3600); m_time_conversion_skew += dtime; u32 units = (u32)(m_time_conversion_skew * speed); bool sync_f = false; if (units > 0) { // Sync at overflow if (m_time_of_day + units >= 24000) { sync_f = true; ++m_day_count; } m_time_of_day = (m_time_of_day + units) % 24000; if (sync_f) m_time_of_day_f = (float)m_time_of_day / 24000.0; } if (speed > 0) { m_time_conversion_skew -= (f32)units / speed; } if (!sync_f) { m_time_of_day_f += cached_time_of_day_speed / 24 / 3600 * dtime; if (m_time_of_day_f > 1.0) m_time_of_day_f -= 1.0; if (m_time_of_day_f < 0.0) m_time_of_day_f += 1.0; } } u32 Environment::getDayCount() { // Atomic<u32> counter return m_day_count; }
pgimeno/minetest
src/environment.cpp
C++
mit
8,968
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once /* This class is the game's environment. It contains: - The map - Players - Other objects - The current time in the game - etc. */ #include <list> #include <queue> #include <map> #include <atomic> #include <mutex> #include "irr_v3d.h" #include "network/networkprotocol.h" // for AccessDeniedCode #include "util/basic_macros.h" class IGameDef; class Map; struct PointedThing; class RaycastState; class Environment { public: // Environment will delete the map passed to the constructor Environment(IGameDef *gamedef); virtual ~Environment() = default; DISABLE_CLASS_COPY(Environment); /* Step everything in environment. - Move players - Step mobs - Run timers of map */ virtual void step(f32 dtime) = 0; virtual Map &getMap() = 0; u32 getDayNightRatio(); // 0-23999 virtual void setTimeOfDay(u32 time); u32 getTimeOfDay(); float getTimeOfDayF(); void stepTimeOfDay(float dtime); void setTimeOfDaySpeed(float speed); void setDayNightRatioOverride(bool enable, u32 value); u32 getDayCount(); /*! * Gets the objects pointed by the shootline as * pointed things. * If this is a client environment, the local player * won't be returned. * @param[in] shootline_on_map the shootline for * the test in world coordinates * * @param[out] objects found objects */ virtual void getSelectedActiveObjects(const core::line3d<f32> &shootline_on_map, std::vector<PointedThing> &objects) = 0; /*! * Returns the next node or object the shootline meets. * @param state current state of the raycast * @result output, will contain the next pointed thing */ void continueRaycast(RaycastState *state, PointedThing *result); // counter used internally when triggering ABMs u32 m_added_objects; IGameDef *getGameDef() { return m_gamedef; } protected: std::atomic<float> m_time_of_day_speed; /* * Below: values managed by m_time_lock */ // Time of day in milli-hours (0-23999), determines day and night u32 m_time_of_day; // Time of day in 0...1 float m_time_of_day_f; // Stores the skew created by the float -> u32 conversion // to be applied at next conversion, so that there is no real skew. float m_time_conversion_skew = 0.0f; // Overriding the day-night ratio is useful for custom sky visuals bool m_enable_day_night_ratio_override = false; u32 m_day_night_ratio_override = 0.0f; // Days from the server start, accounts for time shift // in game (e.g. /time or bed usage) std::atomic<u32> m_day_count; /* * Above: values managed by m_time_lock */ /* TODO: Add a callback function so these can be updated when a setting * changes. At this point in time it doesn't matter (e.g. /set * is documented to change server settings only) * * TODO: Local caching of settings is not optimal and should at some stage * be updated to use a global settings object for getting thse values * (as opposed to the this local caching). This can be addressed in * a later release. */ bool m_cache_enable_shaders; float m_cache_active_block_mgmt_interval; float m_cache_abm_interval; float m_cache_nodetimer_interval; IGameDef *m_gamedef; private: std::mutex m_time_lock; };
pgimeno/minetest
src/environment.h
C++
mit
4,010
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" class MtEvent { public: enum Type : u8 { VIEW_BOBBING_STEP = 0, CAMERA_PUNCH_LEFT, CAMERA_PUNCH_RIGHT, PLAYER_FALLING_DAMAGE, PLAYER_DAMAGE, NODE_DUG, PLAYER_JUMP, PLAYER_REGAIN_GROUND, TYPE_MAX, }; virtual ~MtEvent() = default; virtual Type getType() const = 0; }; // An event with no parameters and customizable name class SimpleTriggerEvent : public MtEvent { Type type; public: SimpleTriggerEvent(Type type) : type(type) {} Type getType() const override { return type; } }; class MtEventReceiver { public: virtual ~MtEventReceiver() = default; virtual void onEvent(MtEvent *e) = 0; }; typedef void (*event_receive_func)(MtEvent *e, void *data); class MtEventManager { public: virtual ~MtEventManager() = default; virtual void put(MtEvent *e) = 0; virtual void reg(MtEvent::Type type, event_receive_func f, void *data) = 0; // If data==NULL, every occurence of f is deregistered. virtual void dereg(MtEvent::Type type, event_receive_func f, void *data) = 0; };
pgimeno/minetest
src/event.h
C++
mit
1,830
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <exception> #include <string> class BaseException : public std::exception { public: BaseException(const std::string &s) throw(): m_s(s) {} ~BaseException() throw() = default; virtual const char * what() const throw() { return m_s.c_str(); } protected: std::string m_s; }; class AlreadyExistsException : public BaseException { public: AlreadyExistsException(const std::string &s): BaseException(s) {} }; class VersionMismatchException : public BaseException { public: VersionMismatchException(const std::string &s): BaseException(s) {} }; class FileNotGoodException : public BaseException { public: FileNotGoodException(const std::string &s): BaseException(s) {} }; class DatabaseException : public BaseException { public: DatabaseException(const std::string &s): BaseException(s) {} }; class SerializationError : public BaseException { public: SerializationError(const std::string &s): BaseException(s) {} }; class PacketError : public BaseException { public: PacketError(const std::string &s): BaseException(s) {} }; class SettingNotFoundException : public BaseException { public: SettingNotFoundException(const std::string &s): BaseException(s) {} }; class InvalidFilenameException : public BaseException { public: InvalidFilenameException(const std::string &s): BaseException(s) {} }; class ItemNotFoundException : public BaseException { public: ItemNotFoundException(const std::string &s): BaseException(s) {} }; class ServerError : public BaseException { public: ServerError(const std::string &s): BaseException(s) {} }; class ClientStateError : public BaseException { public: ClientStateError(const std::string &s): BaseException(s) {} }; class PrngException : public BaseException { public: PrngException(const std::string &s): BaseException(s) {} }; class ModError : public BaseException { public: ModError(const std::string &s): BaseException(s) {} }; /* Some "old-style" interrupts: */ class InvalidNoiseParamsException : public BaseException { public: InvalidNoiseParamsException(): BaseException("One or more noise parameters were invalid or require " "too much memory") {} InvalidNoiseParamsException(const std::string &s): BaseException(s) {} }; class InvalidPositionException : public BaseException { public: InvalidPositionException(): BaseException("Somebody tried to get/set something in a nonexistent position.") {} InvalidPositionException(const std::string &s): BaseException(s) {} };
pgimeno/minetest
src/exceptions.h
C++
mit
3,276
/* Minetest Copyright (C) 2015 Nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "face_position_cache.h" #include "threading/mutex_auto_lock.h" std::unordered_map<u16, std::vector<v3s16>> FacePositionCache::cache; std::mutex FacePositionCache::cache_mutex; // Calculate the borders of a "d-radius" cube const std::vector<v3s16> &FacePositionCache::getFacePositions(u16 d) { MutexAutoLock lock(cache_mutex); std::unordered_map<u16, std::vector<v3s16>>::const_iterator it = cache.find(d); if (it != cache.end()) return it->second; return generateFacePosition(d); } const std::vector<v3s16> &FacePositionCache::generateFacePosition(u16 d) { cache[d] = std::vector<v3s16>(); std::vector<v3s16> &c = cache[d]; if (d == 0) { c.emplace_back(0,0,0); return c; } if (d == 1) { // This is an optimized sequence of coordinates. c.emplace_back(0, 1, 0); // Top c.emplace_back(0, 0, 1); // Back c.emplace_back(-1, 0, 0); // Left c.emplace_back(1, 0, 0); // Right c.emplace_back(0, 0,-1); // Front c.emplace_back(0,-1, 0); // Bottom // 6 c.emplace_back(-1, 0, 1); // Back left c.emplace_back(1, 0, 1); // Back right c.emplace_back(-1, 0,-1); // Front left c.emplace_back(1, 0,-1); // Front right c.emplace_back(-1,-1, 0); // Bottom left c.emplace_back(1,-1, 0); // Bottom right c.emplace_back(0,-1, 1); // Bottom back c.emplace_back(0,-1,-1); // Bottom front c.emplace_back(-1, 1, 0); // Top left c.emplace_back(1, 1, 0); // Top right c.emplace_back(0, 1, 1); // Top back c.emplace_back(0, 1,-1); // Top front // 18 c.emplace_back(-1, 1, 1); // Top back-left c.emplace_back(1, 1, 1); // Top back-right c.emplace_back(-1, 1,-1); // Top front-left c.emplace_back(1, 1,-1); // Top front-right c.emplace_back(-1,-1, 1); // Bottom back-left c.emplace_back(1,-1, 1); // Bottom back-right c.emplace_back(-1,-1,-1); // Bottom front-left c.emplace_back(1,-1,-1); // Bottom front-right // 26 return c; } // Take blocks in all sides, starting from y=0 and going +-y for (s16 y = 0; y <= d - 1; y++) { // Left and right side, including borders for (s16 z =- d; z <= d; z++) { c.emplace_back(d, y, z); c.emplace_back(-d, y, z); if (y != 0) { c.emplace_back(d, -y, z); c.emplace_back(-d, -y, z); } } // Back and front side, excluding borders for (s16 x = -d + 1; x <= d - 1; x++) { c.emplace_back(x, y, d); c.emplace_back(x, y, -d); if (y != 0) { c.emplace_back(x, -y, d); c.emplace_back(x, -y, -d); } } } // Take the bottom and top face with borders // -d < x < d, y = +-d, -d < z < d for (s16 x = -d; x <= d; x++) for (s16 z = -d; z <= d; z++) { c.emplace_back(x, -d, z); c.emplace_back(x, d, z); } return c; }
pgimeno/minetest
src/face_position_cache.cpp
C++
mit
3,452
/* Minetest Copyright (C) 2015 Nerzhul, Loic Blot <loic.blot@unix-experience.fr> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irr_v3d.h" #include <map> #include <vector> #include <unordered_map> #include <mutex> /* * This class permits caching getFacePosition call results. * This reduces CPU usage and vector calls. */ class FacePositionCache { public: static const std::vector<v3s16> &getFacePositions(u16 d); private: static const std::vector<v3s16> &generateFacePosition(u16 d); static std::unordered_map<u16, std::vector<v3s16>> cache; static std::mutex cache_mutex; };
pgimeno/minetest
src/face_position_cache.h
C++
mit
1,272
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "filesys.h" #include "util/string.h" #include <iostream> #include <cstdio> #include <cstring> #include <cerrno> #include <fstream> #include "log.h" #include "config.h" #include "porting.h" #ifdef __ANDROID__ #include "settings.h" // For g_settings #endif namespace fs { #ifdef _WIN32 // WINDOWS #define _WIN32_WINNT 0x0501 #include <windows.h> #include <shlwapi.h> std::vector<DirListNode> GetDirListing(const std::string &pathstring) { std::vector<DirListNode> listing; WIN32_FIND_DATA FindFileData; HANDLE hFind = INVALID_HANDLE_VALUE; DWORD dwError; std::string dirSpec = pathstring + "\\*"; // Find the first file in the directory. hFind = FindFirstFile(dirSpec.c_str(), &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { dwError = GetLastError(); if (dwError != ERROR_FILE_NOT_FOUND && dwError != ERROR_PATH_NOT_FOUND) { errorstream << "GetDirListing: FindFirstFile error." << " Error is " << dwError << std::endl; } } else { // NOTE: // Be very sure to not include '..' in the results, it will // result in an epic failure when deleting stuff. DirListNode node; node.name = FindFileData.cFileName; node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; if (node.name != "." && node.name != "..") listing.push_back(node); // List all the other files in the directory. while (FindNextFile(hFind, &FindFileData) != 0) { DirListNode node; node.name = FindFileData.cFileName; node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; if(node.name != "." && node.name != "..") listing.push_back(node); } dwError = GetLastError(); FindClose(hFind); if (dwError != ERROR_NO_MORE_FILES) { errorstream << "GetDirListing: FindNextFile error." << " Error is " << dwError << std::endl; listing.clear(); return listing; } } return listing; } bool CreateDir(const std::string &path) { bool r = CreateDirectory(path.c_str(), NULL); if(r == true) return true; if(GetLastError() == ERROR_ALREADY_EXISTS) return true; return false; } bool PathExists(const std::string &path) { return (GetFileAttributes(path.c_str()) != INVALID_FILE_ATTRIBUTES); } bool IsPathAbsolute(const std::string &path) { return !PathIsRelative(path.c_str()); } bool IsDir(const std::string &path) { DWORD attr = GetFileAttributes(path.c_str()); return (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY)); } bool IsDirDelimiter(char c) { return c == '/' || c == '\\'; } bool RecursiveDelete(const std::string &path) { infostream << "Recursively deleting \"" << path << "\"" << std::endl; if (!IsDir(path)) { infostream << "RecursiveDelete: Deleting file " << path << std::endl; if (!DeleteFile(path.c_str())) { errorstream << "RecursiveDelete: Failed to delete file " << path << std::endl; return false; } return true; } infostream << "RecursiveDelete: Deleting content of directory " << path << std::endl; std::vector<DirListNode> content = GetDirListing(path); for (const DirListNode &n: content) { std::string fullpath = path + DIR_DELIM + n.name; if (!RecursiveDelete(fullpath)) { errorstream << "RecursiveDelete: Failed to recurse to " << fullpath << std::endl; return false; } } infostream << "RecursiveDelete: Deleting directory " << path << std::endl; if (!RemoveDirectory(path.c_str())) { errorstream << "Failed to recursively delete directory " << path << std::endl; return false; } return true; } bool DeleteSingleFileOrEmptyDirectory(const std::string &path) { DWORD attr = GetFileAttributes(path.c_str()); bool is_directory = (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY)); if(!is_directory) { bool did = DeleteFile(path.c_str()); return did; } else { bool did = RemoveDirectory(path.c_str()); return did; } } std::string TempPath() { DWORD bufsize = GetTempPath(0, NULL); if(bufsize == 0){ errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl; return ""; } std::vector<char> buf(bufsize); DWORD len = GetTempPath(bufsize, &buf[0]); if(len == 0 || len > bufsize){ errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl; return ""; } return std::string(buf.begin(), buf.begin() + len); } #else // POSIX #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <sys/wait.h> #include <unistd.h> std::vector<DirListNode> GetDirListing(const std::string &pathstring) { std::vector<DirListNode> listing; DIR *dp; struct dirent *dirp; if((dp = opendir(pathstring.c_str())) == NULL) { //infostream<<"Error("<<errno<<") opening "<<pathstring<<std::endl; return listing; } while ((dirp = readdir(dp)) != NULL) { // NOTE: // Be very sure to not include '..' in the results, it will // result in an epic failure when deleting stuff. if(strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0) continue; DirListNode node; node.name = dirp->d_name; int isdir = -1; // -1 means unknown /* POSIX doesn't define d_type member of struct dirent and certain filesystems on glibc/Linux will only return DT_UNKNOWN for the d_type member. Also we don't know whether symlinks are directories or not. */ #ifdef _DIRENT_HAVE_D_TYPE if(dirp->d_type != DT_UNKNOWN && dirp->d_type != DT_LNK) isdir = (dirp->d_type == DT_DIR); #endif /* _DIRENT_HAVE_D_TYPE */ /* Was d_type DT_UNKNOWN, DT_LNK or nonexistent? If so, try stat(). */ if(isdir == -1) { struct stat statbuf{}; if (stat((pathstring + "/" + node.name).c_str(), &statbuf)) continue; isdir = ((statbuf.st_mode & S_IFDIR) == S_IFDIR); } node.dir = isdir; listing.push_back(node); } closedir(dp); return listing; } bool CreateDir(const std::string &path) { int r = mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (r == 0) { return true; } // If already exists, return true if (errno == EEXIST) return true; return false; } bool PathExists(const std::string &path) { struct stat st{}; return (stat(path.c_str(),&st) == 0); } bool IsPathAbsolute(const std::string &path) { return path[0] == '/'; } bool IsDir(const std::string &path) { struct stat statbuf{}; if(stat(path.c_str(), &statbuf)) return false; // Actually error; but certainly not a directory return ((statbuf.st_mode & S_IFDIR) == S_IFDIR); } bool IsDirDelimiter(char c) { return c == '/'; } bool RecursiveDelete(const std::string &path) { /* Execute the 'rm' command directly, by fork() and execve() */ infostream<<"Removing \""<<path<<"\""<<std::endl; //return false; pid_t child_pid = fork(); if(child_pid == 0) { // Child char argv_data[3][10000]; #ifdef __ANDROID__ strcpy(argv_data[0], "/system/bin/rm"); #else strcpy(argv_data[0], "/bin/rm"); #endif strcpy(argv_data[1], "-rf"); strncpy(argv_data[2], path.c_str(), sizeof(argv_data[2]) - 1); char *argv[4]; argv[0] = argv_data[0]; argv[1] = argv_data[1]; argv[2] = argv_data[2]; argv[3] = NULL; verbosestream<<"Executing '"<<argv[0]<<"' '"<<argv[1]<<"' '" <<argv[2]<<"'"<<std::endl; execv(argv[0], argv); // Execv shouldn't return. Failed. _exit(1); } else { // Parent int child_status; pid_t tpid; do{ tpid = wait(&child_status); //if(tpid != child_pid) process_terminated(tpid); }while(tpid != child_pid); return (child_status == 0); } } bool DeleteSingleFileOrEmptyDirectory(const std::string &path) { if (IsDir(path)) { bool did = (rmdir(path.c_str()) == 0); if (!did) errorstream << "rmdir errno: " << errno << ": " << strerror(errno) << std::endl; return did; } bool did = (unlink(path.c_str()) == 0); if (!did) errorstream << "unlink errno: " << errno << ": " << strerror(errno) << std::endl; return did; } std::string TempPath() { /* Should the environment variables TMPDIR, TMP and TEMP and the macro P_tmpdir (if defined by stdio.h) be checked before falling back on /tmp? Probably not, because this function is intended to be compatible with lua's os.tmpname which under the default configuration hardcodes mkstemp("/tmp/lua_XXXXXX"). */ #ifdef __ANDROID__ return g_settings->get("TMPFolder"); #else return DIR_DELIM "tmp"; #endif } #endif void GetRecursiveDirs(std::vector<std::string> &dirs, const std::string &dir) { static const std::set<char> chars_to_ignore = { '_', '.' }; if (dir.empty() || !IsDir(dir)) return; dirs.push_back(dir); fs::GetRecursiveSubPaths(dir, dirs, false, chars_to_ignore); } std::vector<std::string> GetRecursiveDirs(const std::string &dir) { std::vector<std::string> result; GetRecursiveDirs(result, dir); return result; } void GetRecursiveSubPaths(const std::string &path, std::vector<std::string> &dst, bool list_files, const std::set<char> &ignore) { std::vector<DirListNode> content = GetDirListing(path); for (const auto &n : content) { std::string fullpath = path + DIR_DELIM + n.name; if (ignore.count(n.name[0])) continue; if (list_files || n.dir) dst.push_back(fullpath); if (n.dir) GetRecursiveSubPaths(fullpath, dst, list_files, ignore); } } bool DeletePaths(const std::vector<std::string> &paths) { bool success = true; // Go backwards to succesfully delete the output of GetRecursiveSubPaths for(int i=paths.size()-1; i>=0; i--){ const std::string &path = paths[i]; bool did = DeleteSingleFileOrEmptyDirectory(path); if(!did){ errorstream<<"Failed to delete "<<path<<std::endl; success = false; } } return success; } bool RecursiveDeleteContent(const std::string &path) { infostream<<"Removing content of \""<<path<<"\""<<std::endl; std::vector<DirListNode> list = GetDirListing(path); for (const DirListNode &dln : list) { if(trim(dln.name) == "." || trim(dln.name) == "..") continue; std::string childpath = path + DIR_DELIM + dln.name; bool r = RecursiveDelete(childpath); if(!r) { errorstream << "Removing \"" << childpath << "\" failed" << std::endl; return false; } } return true; } bool CreateAllDirs(const std::string &path) { std::vector<std::string> tocreate; std::string basepath = path; while(!PathExists(basepath)) { tocreate.push_back(basepath); basepath = RemoveLastPathComponent(basepath); if(basepath.empty()) break; } for(int i=tocreate.size()-1;i>=0;i--) if(!CreateDir(tocreate[i])) return false; return true; } bool CopyFileContents(const std::string &source, const std::string &target) { FILE *sourcefile = fopen(source.c_str(), "rb"); if(sourcefile == NULL){ errorstream<<source<<": can't open for reading: " <<strerror(errno)<<std::endl; return false; } FILE *targetfile = fopen(target.c_str(), "wb"); if(targetfile == NULL){ errorstream<<target<<": can't open for writing: " <<strerror(errno)<<std::endl; fclose(sourcefile); return false; } size_t total = 0; bool retval = true; bool done = false; char readbuffer[BUFSIZ]; while(!done){ size_t readbytes = fread(readbuffer, 1, sizeof(readbuffer), sourcefile); total += readbytes; if(ferror(sourcefile)){ errorstream<<source<<": IO error: " <<strerror(errno)<<std::endl; retval = false; done = true; } if(readbytes > 0){ fwrite(readbuffer, 1, readbytes, targetfile); } if(feof(sourcefile) || ferror(sourcefile)){ // flush destination file to catch write errors // (e.g. disk full) fflush(targetfile); done = true; } if(ferror(targetfile)){ errorstream<<target<<": IO error: " <<strerror(errno)<<std::endl; retval = false; done = true; } } infostream<<"copied "<<total<<" bytes from " <<source<<" to "<<target<<std::endl; fclose(sourcefile); fclose(targetfile); return retval; } bool CopyDir(const std::string &source, const std::string &target) { if(PathExists(source)){ if(!PathExists(target)){ fs::CreateAllDirs(target); } bool retval = true; std::vector<DirListNode> content = fs::GetDirListing(source); for (const auto &dln : content) { std::string sourcechild = source + DIR_DELIM + dln.name; std::string targetchild = target + DIR_DELIM + dln.name; if(dln.dir){ if(!fs::CopyDir(sourcechild, targetchild)){ retval = false; } } else { if(!fs::CopyFileContents(sourcechild, targetchild)){ retval = false; } } } return retval; } return false; } bool PathStartsWith(const std::string &path, const std::string &prefix) { size_t pathsize = path.size(); size_t pathpos = 0; size_t prefixsize = prefix.size(); size_t prefixpos = 0; for(;;){ bool delim1 = pathpos == pathsize || IsDirDelimiter(path[pathpos]); bool delim2 = prefixpos == prefixsize || IsDirDelimiter(prefix[prefixpos]); if(delim1 != delim2) return false; if(delim1){ while(pathpos < pathsize && IsDirDelimiter(path[pathpos])) ++pathpos; while(prefixpos < prefixsize && IsDirDelimiter(prefix[prefixpos])) ++prefixpos; if(prefixpos == prefixsize) return true; if(pathpos == pathsize) return false; } else{ size_t len = 0; do{ char pathchar = path[pathpos+len]; char prefixchar = prefix[prefixpos+len]; if(FILESYS_CASE_INSENSITIVE){ pathchar = tolower(pathchar); prefixchar = tolower(prefixchar); } if(pathchar != prefixchar) return false; ++len; } while(pathpos+len < pathsize && !IsDirDelimiter(path[pathpos+len]) && prefixpos+len < prefixsize && !IsDirDelimiter( prefix[prefixpos+len])); pathpos += len; prefixpos += len; } } } std::string RemoveLastPathComponent(const std::string &path, std::string *removed, int count) { if(removed) *removed = ""; size_t remaining = path.size(); for(int i = 0; i < count; ++i){ // strip a dir delimiter while(remaining != 0 && IsDirDelimiter(path[remaining-1])) remaining--; // strip a path component size_t component_end = remaining; while(remaining != 0 && !IsDirDelimiter(path[remaining-1])) remaining--; size_t component_start = remaining; // strip a dir delimiter while(remaining != 0 && IsDirDelimiter(path[remaining-1])) remaining--; if(removed){ std::string component = path.substr(component_start, component_end - component_start); if(i) *removed = component + DIR_DELIM + *removed; else *removed = component; } } return path.substr(0, remaining); } std::string RemoveRelativePathComponents(std::string path) { size_t pos = path.size(); size_t dotdot_count = 0; while (pos != 0) { size_t component_with_delim_end = pos; // skip a dir delimiter while (pos != 0 && IsDirDelimiter(path[pos-1])) pos--; // strip a path component size_t component_end = pos; while (pos != 0 && !IsDirDelimiter(path[pos-1])) pos--; size_t component_start = pos; std::string component = path.substr(component_start, component_end - component_start); bool remove_this_component = false; if (component == ".") { remove_this_component = true; } else if (component == "..") { remove_this_component = true; dotdot_count += 1; } else if (dotdot_count != 0) { remove_this_component = true; dotdot_count -= 1; } if (remove_this_component) { while (pos != 0 && IsDirDelimiter(path[pos-1])) pos--; if (component_start == 0) { // We need to remove the delemiter too path = path.substr(component_with_delim_end, std::string::npos); } else { path = path.substr(0, pos) + DIR_DELIM + path.substr(component_with_delim_end, std::string::npos); } if (pos > 0) pos++; } } if (dotdot_count > 0) return ""; // remove trailing dir delimiters pos = path.size(); while (pos != 0 && IsDirDelimiter(path[pos-1])) pos--; return path.substr(0, pos); } std::string AbsolutePath(const std::string &path) { #ifdef _WIN32 char *abs_path = _fullpath(NULL, path.c_str(), MAX_PATH); #else char *abs_path = realpath(path.c_str(), NULL); #endif if (!abs_path) return ""; std::string abs_path_str(abs_path); free(abs_path); return abs_path_str; } const char *GetFilenameFromPath(const char *path) { const char *filename = strrchr(path, DIR_DELIM_CHAR); return filename ? filename + 1 : path; } bool safeWriteToFile(const std::string &path, const std::string &content) { std::string tmp_file = path + ".~mt"; // Write to a tmp file std::ofstream os(tmp_file.c_str(), std::ios::binary); if (!os.good()) return false; os << content; os.flush(); os.close(); if (os.fail()) { // Remove the temporary file because writing it failed and it's useless. remove(tmp_file.c_str()); return false; } bool rename_success = false; // Move the finished temporary file over the real file #ifdef _WIN32 // When creating the file, it can cause Windows Search indexer, virus scanners and other apps // to query the file. This can make the move file call below fail. // We retry up to 5 times, with a 1ms sleep between, before we consider the whole operation failed int number_attempts = 0; while (number_attempts < 5) { rename_success = MoveFileEx(tmp_file.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH); if (rename_success) break; sleep_ms(1); ++number_attempts; } #else // On POSIX compliant systems rename() is specified to be able to swap the // file in place of the destination file, making this a truly error-proof // transaction. rename_success = rename(tmp_file.c_str(), path.c_str()) == 0; #endif if (!rename_success) { warningstream << "Failed to write to file: " << path.c_str() << std::endl; // Remove the temporary file because moving it over the target file // failed. remove(tmp_file.c_str()); return false; } return true; } bool Rename(const std::string &from, const std::string &to) { return rename(from.c_str(), to.c_str()) == 0; } } // namespace fs
pgimeno/minetest
src/filesys.cpp
C++
mit
18,639
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <set> #include <string> #include <vector> #include "exceptions.h" #ifdef _WIN32 // WINDOWS #define DIR_DELIM "\\" #define DIR_DELIM_CHAR '\\' #define FILESYS_CASE_INSENSITIVE true #define PATH_DELIM ";" #else // POSIX #define DIR_DELIM "/" #define DIR_DELIM_CHAR '/' #define FILESYS_CASE_INSENSITIVE false #define PATH_DELIM ":" #endif namespace fs { struct DirListNode { std::string name; bool dir; }; std::vector<DirListNode> GetDirListing(const std::string &path); // Returns true if already exists bool CreateDir(const std::string &path); bool PathExists(const std::string &path); bool IsPathAbsolute(const std::string &path); bool IsDir(const std::string &path); bool IsDirDelimiter(char c); // Only pass full paths to this one. True on success. // NOTE: The WIN32 version returns always true. bool RecursiveDelete(const std::string &path); bool DeleteSingleFileOrEmptyDirectory(const std::string &path); // Returns path to temp directory, can return "" on error std::string TempPath(); /* Returns a list of subdirectories, including the path itself, but excluding hidden directories (whose names start with . or _) */ void GetRecursiveDirs(std::vector<std::string> &dirs, const std::string &dir); std::vector<std::string> GetRecursiveDirs(const std::string &dir); /* Multiplatform */ /* The path itself not included, returns a list of all subpaths. dst - vector that contains all the subpaths. list files - include files in the list of subpaths. ignore - paths that start with these charcters will not be listed. */ void GetRecursiveSubPaths(const std::string &path, std::vector<std::string> &dst, bool list_files, const std::set<char> &ignore = {}); // Tries to delete all, returns false if any failed bool DeletePaths(const std::vector<std::string> &paths); // Only pass full paths to this one. True on success. bool RecursiveDeleteContent(const std::string &path); // Create all directories on the given path that don't already exist. bool CreateAllDirs(const std::string &path); // Copy a regular file bool CopyFileContents(const std::string &source, const std::string &target); // Copy directory and all subdirectories // Omits files and subdirectories that start with a period bool CopyDir(const std::string &source, const std::string &target); // Check if one path is prefix of another // For example, "/tmp" is a prefix of "/tmp" and "/tmp/file" but not "/tmp2" // Ignores case differences and '/' vs. '\\' on Windows bool PathStartsWith(const std::string &path, const std::string &prefix); // Remove last path component and the dir delimiter before and/or after it, // returns "" if there is only one path component. // removed: If non-NULL, receives the removed component(s). // count: Number of components to remove std::string RemoveLastPathComponent(const std::string &path, std::string *removed = NULL, int count = 1); // Remove "." and ".." path components and for every ".." removed, remove // the last normal path component before it. Unlike AbsolutePath, // this does not resolve symlinks and check for existence of directories. std::string RemoveRelativePathComponents(std::string path); // Returns the absolute path for the passed path, with "." and ".." path // components and symlinks removed. Returns "" on error. std::string AbsolutePath(const std::string &path); // Returns the filename from a path or the entire path if no directory // delimiter is found. const char *GetFilenameFromPath(const char *path); bool safeWriteToFile(const std::string &path, const std::string &content); bool Rename(const std::string &from, const std::string &to); } // namespace fs
pgimeno/minetest
src/filesys.h
C++
mit
4,475
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <string> #include <vector> #include "irrlichttypes.h" class IItemDefManager; class NodeDefManager; class ICraftDefManager; class ITextureSource; class IShaderSource; class IRollbackManager; class EmergeManager; class Camera; class ModChannel; class ModMetadata; namespace irr { namespace scene { class IAnimatedMesh; class ISceneManager; }} struct ModSpec; /* An interface for fetching game-global definitions like tool and mapnode properties */ class IGameDef { public: // These are thread-safe IF they are not edited while running threads. // Thus, first they are set up and then they are only read. virtual IItemDefManager* getItemDefManager()=0; virtual const NodeDefManager* getNodeDefManager()=0; virtual ICraftDefManager* getCraftDefManager()=0; // Used for keeping track of names/ids of unknown nodes virtual u16 allocateUnknownNodeId(const std::string &name)=0; // Only usable on the server, and NOT thread-safe. It is usable from the // environment thread. virtual IRollbackManager* getRollbackManager() { return NULL; } // Shorthands IItemDefManager *idef() { return getItemDefManager(); } const NodeDefManager *ndef() { return getNodeDefManager(); } ICraftDefManager *cdef() { return getCraftDefManager(); } IRollbackManager *rollback() { return getRollbackManager(); } virtual const std::vector<ModSpec> &getMods() const = 0; virtual const ModSpec* getModSpec(const std::string &modname) const = 0; virtual std::string getWorldPath() const { return ""; } virtual std::string getModStoragePath() const = 0; virtual bool registerModStorage(ModMetadata *storage) = 0; virtual void unregisterModStorage(const std::string &name) = 0; virtual bool joinModChannel(const std::string &channel) = 0; virtual bool leaveModChannel(const std::string &channel) = 0; virtual bool sendModChannelMessage(const std::string &channel, const std::string &message) = 0; virtual ModChannel *getModChannel(const std::string &channel) = 0; };
pgimeno/minetest
src/gamedef.h
C++
mit
2,789
/* Minetest Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" struct SubgameSpec; struct GameParams { u16 socket_port; std::string world_path; SubgameSpec game_spec; bool is_dedicated_server; };
pgimeno/minetest
src/gameparams.h
C++
mit
970
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "genericobject.h" #include <sstream> #include "util/serialize.h" std::string gob_cmd_set_properties(const ObjectProperties &prop) { std::ostringstream os(std::ios::binary); writeU8(os, GENERIC_CMD_SET_PROPERTIES); prop.serialize(os); return os.str(); } ObjectProperties gob_read_set_properties(std::istream &is) { ObjectProperties prop; prop.deSerialize(is); return prop; } std::string gob_cmd_update_position( v3f position, v3f velocity, v3f acceleration, v3f rotation, bool do_interpolate, bool is_movement_end, f32 update_interval ){ std::ostringstream os(std::ios::binary); // command writeU8(os, GENERIC_CMD_UPDATE_POSITION); // pos writeV3F32(os, position); // velocity writeV3F32(os, velocity); // acceleration writeV3F32(os, acceleration); // rotation writeV3F32(os, rotation); // do_interpolate writeU8(os, do_interpolate); // is_end_position (for interpolation) writeU8(os, is_movement_end); // update_interval (for interpolation) writeF32(os, update_interval); return os.str(); } std::string gob_cmd_set_texture_mod(const std::string &mod) { std::ostringstream os(std::ios::binary); // command writeU8(os, GENERIC_CMD_SET_TEXTURE_MOD); // parameters os<<serializeString(mod); return os.str(); } std::string gob_cmd_set_sprite( v2s16 p, u16 num_frames, f32 framelength, bool select_horiz_by_yawpitch ){ std::ostringstream os(std::ios::binary); // command writeU8(os, GENERIC_CMD_SET_SPRITE); // parameters writeV2S16(os, p); writeU16(os, num_frames); writeF32(os, framelength); writeU8(os, select_horiz_by_yawpitch); return os.str(); } std::string gob_cmd_punched(u16 result_hp) { std::ostringstream os(std::ios::binary); // command writeU8(os, GENERIC_CMD_PUNCHED); // result_hp writeU16(os, result_hp); return os.str(); } std::string gob_cmd_update_armor_groups(const ItemGroupList &armor_groups) { std::ostringstream os(std::ios::binary); writeU8(os, GENERIC_CMD_UPDATE_ARMOR_GROUPS); writeU16(os, armor_groups.size()); for (const auto &armor_group : armor_groups) { os<<serializeString(armor_group.first); writeS16(os, armor_group.second); } return os.str(); } std::string gob_cmd_update_physics_override(float physics_override_speed, float physics_override_jump, float physics_override_gravity, bool sneak, bool sneak_glitch, bool new_move) { std::ostringstream os(std::ios::binary); // command writeU8(os, GENERIC_CMD_SET_PHYSICS_OVERRIDE); // parameters writeF32(os, physics_override_speed); writeF32(os, physics_override_jump); writeF32(os, physics_override_gravity); // these are sent inverted so we get true when the server sends nothing writeU8(os, !sneak); writeU8(os, !sneak_glitch); writeU8(os, !new_move); return os.str(); } std::string gob_cmd_update_animation(v2f frames, float frame_speed, float frame_blend, bool frame_loop) { std::ostringstream os(std::ios::binary); // command writeU8(os, GENERIC_CMD_SET_ANIMATION); // parameters writeV2F32(os, frames); writeF32(os, frame_speed); writeF32(os, frame_blend); // these are sent inverted so we get true when the server sends nothing writeU8(os, !frame_loop); return os.str(); } std::string gob_cmd_update_animation_speed(float frame_speed) { std::ostringstream os(std::ios::binary); // command writeU8(os, GENERIC_CMD_SET_ANIMATION_SPEED); // parameters writeF32(os, frame_speed); return os.str(); } std::string gob_cmd_update_bone_position(const std::string &bone, v3f position, v3f rotation) { std::ostringstream os(std::ios::binary); // command writeU8(os, GENERIC_CMD_SET_BONE_POSITION); // parameters os<<serializeString(bone); writeV3F32(os, position); writeV3F32(os, rotation); return os.str(); } std::string gob_cmd_update_attachment(int parent_id, const std::string &bone, v3f position, v3f rotation) { std::ostringstream os(std::ios::binary); // command writeU8(os, GENERIC_CMD_ATTACH_TO); // parameters writeS16(os, parent_id); os<<serializeString(bone); writeV3F32(os, position); writeV3F32(os, rotation); return os.str(); } std::string gob_cmd_update_nametag_attributes(video::SColor color) { std::ostringstream os(std::ios::binary); // command writeU8(os, GENERIC_CMD_UPDATE_NAMETAG_ATTRIBUTES); // parameters writeU8(os, 1); // version for forward compatibility writeARGB8(os, color); return os.str(); } std::string gob_cmd_update_infant(u16 id, u8 type, const std::string &client_initialization_data) { std::ostringstream os(std::ios::binary); // command writeU8(os, GENERIC_CMD_SPAWN_INFANT); // parameters writeU16(os, id); writeU8(os, type); os<<serializeLongString(client_initialization_data); return os.str(); }
pgimeno/minetest
src/genericobject.cpp
C++
mit
5,455
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include <string> #include "irrlichttypes_bloated.h" #include <iostream> #include "itemgroup.h" enum GenericCMD { GENERIC_CMD_SET_PROPERTIES, GENERIC_CMD_UPDATE_POSITION, GENERIC_CMD_SET_TEXTURE_MOD, GENERIC_CMD_SET_SPRITE, GENERIC_CMD_PUNCHED, GENERIC_CMD_UPDATE_ARMOR_GROUPS, GENERIC_CMD_SET_ANIMATION, GENERIC_CMD_SET_BONE_POSITION, GENERIC_CMD_ATTACH_TO, GENERIC_CMD_SET_PHYSICS_OVERRIDE, GENERIC_CMD_UPDATE_NAMETAG_ATTRIBUTES, GENERIC_CMD_SPAWN_INFANT, GENERIC_CMD_SET_ANIMATION_SPEED }; #include "object_properties.h" std::string gob_cmd_set_properties(const ObjectProperties &prop); ObjectProperties gob_read_set_properties(std::istream &is); std::string gob_cmd_update_position( v3f position, v3f velocity, v3f acceleration, v3f rotation, bool do_interpolate, bool is_movement_end, f32 update_interval ); std::string gob_cmd_set_texture_mod(const std::string &mod); std::string gob_cmd_set_sprite( v2s16 p, u16 num_frames, f32 framelength, bool select_horiz_by_yawpitch ); std::string gob_cmd_punched(u16 result_hp); std::string gob_cmd_update_armor_groups(const ItemGroupList &armor_groups); std::string gob_cmd_update_physics_override(float physics_override_speed, float physics_override_jump, float physics_override_gravity, bool sneak, bool sneak_glitch, bool new_move); std::string gob_cmd_update_animation(v2f frames, float frame_speed, float frame_blend, bool frame_loop); std::string gob_cmd_update_animation_speed(float frame_speed); std::string gob_cmd_update_bone_position(const std::string &bone, v3f position, v3f rotation); std::string gob_cmd_update_attachment(int parent_id, const std::string &bone, v3f position, v3f rotation); std::string gob_cmd_update_nametag_attributes(video::SColor color); std::string gob_cmd_update_infant(u16 id, u8 type, const std::string &client_initialization_data);
pgimeno/minetest
src/genericobject.h
C++
mit
2,667
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <string> #include <cstring> #include <iostream> #include <cstdlib> #include "gettext.h" #include "util/string.h" #include "log.h" #if USE_GETTEXT && defined(_MSC_VER) #include <windows.h> #include <map> #include <direct.h> #include "filesys.h" #define setlocale(category, localename) \ setlocale(category, MSVC_LocaleLookup(localename)) static std::map<std::wstring, std::wstring> glb_supported_locales; /******************************************************************************/ BOOL CALLBACK UpdateLocaleCallback(LPTSTR pStr) { char* endptr = 0; int LOCALEID = strtol(pStr, &endptr,16); wchar_t buffer[LOCALE_NAME_MAX_LENGTH]; memset(buffer, 0, sizeof(buffer)); if (GetLocaleInfoW( LOCALEID, LOCALE_SISO639LANGNAME, buffer, LOCALE_NAME_MAX_LENGTH)) { std::wstring name = buffer; memset(buffer, 0, sizeof(buffer)); GetLocaleInfoW( LOCALEID, LOCALE_SISO3166CTRYNAME, buffer, LOCALE_NAME_MAX_LENGTH); std::wstring country = buffer; memset(buffer, 0, sizeof(buffer)); GetLocaleInfoW( LOCALEID, LOCALE_SENGLISHLANGUAGENAME, buffer, LOCALE_NAME_MAX_LENGTH); std::wstring languagename = buffer; /* set both short and long variant */ glb_supported_locales[name] = languagename; glb_supported_locales[name + L"_" + country] = languagename; } return true; } /******************************************************************************/ const char* MSVC_LocaleLookup(const char* raw_shortname) { /* NULL is used to read locale only so we need to return it too */ if (raw_shortname == NULL) return NULL; std::string shortname(raw_shortname); if (shortname == "C") return "C"; if (shortname == "") return ""; static std::string last_raw_value = ""; static std::string last_full_name = ""; static bool first_use = true; if (last_raw_value == shortname) { return last_full_name.c_str(); } if (first_use) { EnumSystemLocalesA(UpdateLocaleCallback, LCID_SUPPORTED | LCID_ALTERNATE_SORTS); first_use = false; } last_raw_value = shortname; if (glb_supported_locales.find(utf8_to_wide(shortname)) != glb_supported_locales.end()) { last_full_name = wide_to_utf8( glb_supported_locales[utf8_to_wide(shortname)]); return last_full_name.c_str(); } /* empty string is system default */ errorstream << "MSVC_LocaleLookup: unsupported locale: \"" << shortname << "\" switching to system default!" << std::endl; return ""; } #endif /******************************************************************************/ void init_gettext(const char *path, const std::string &configured_language, int argc, char *argv[]) { #if USE_GETTEXT // First, try to set user override environment if (!configured_language.empty()) { #ifndef _WIN32 // Add user specified locale to environment setenv("LANGUAGE", configured_language.c_str(), 1); // Reload locale with changed environment setlocale(LC_ALL, ""); #elif defined(_MSC_VER) std::string current_language; const char *env_lang = getenv("LANGUAGE"); if (env_lang) current_language = env_lang; _putenv(("LANGUAGE=" + configured_language).c_str()); SetEnvironmentVariableA("LANGUAGE", configured_language.c_str()); #ifndef SERVER // Hack to force gettext to see the right environment if (current_language != configured_language) { errorstream << "MSVC localization workaround active. " "Restarting " PROJECT_NAME_C " in a new environment!" << std::endl; std::string parameters; for (unsigned int i = 1; i < argc; i++) { if (!parameters.empty()) parameters += ' '; parameters += argv[i]; } const char *ptr_parameters = NULL; if (!parameters.empty()) ptr_parameters = parameters.c_str(); // Allow calling without an extension std::string app_name = argv[0]; if (app_name.compare(app_name.size() - 4, 4, ".exe") != 0) app_name += ".exe"; STARTUPINFO startup_info = {0}; PROCESS_INFORMATION process_info = {0}; bool success = CreateProcess(app_name.c_str(), (char *)ptr_parameters, NULL, NULL, false, DETACHED_PROCESS | CREATE_UNICODE_ENVIRONMENT, NULL, NULL, &startup_info, &process_info); if (success) { exit(0); // NOTREACHED } else { char buffer[1024]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), buffer, sizeof(buffer) - 1, NULL); errorstream << "*******************************************************" << std::endl; errorstream << "CMD: " << app_name << std::endl; errorstream << "Failed to restart with current locale: " << std::endl; errorstream << buffer; errorstream << "Expect language to be broken!" << std::endl; errorstream << "*******************************************************" << std::endl; } } #else errorstream << "*******************************************************" << std::endl; errorstream << "Can't apply locale workaround for server!" << std::endl; errorstream << "Expect language to be broken!" << std::endl; errorstream << "*******************************************************" << std::endl; #endif setlocale(LC_ALL, configured_language.c_str()); #else // Mingw _putenv(("LANGUAGE=" + configured_language).c_str()); setlocale(LC_ALL, ""); #endif // ifndef _WIN32 } else { /* set current system default locale */ setlocale(LC_ALL, ""); } #if defined(_WIN32) if (getenv("LANGUAGE") != 0) { setlocale(LC_ALL, getenv("LANGUAGE")); } #ifdef _MSC_VER else if (getenv("LANG") != 0) { setlocale(LC_ALL, getenv("LANG")); } #endif #endif static std::string name = lowercase(PROJECT_NAME); bindtextdomain(name.c_str(), path); textdomain(name.c_str()); #if defined(_WIN32) // Set character encoding for Win32 char *tdomain = textdomain( (char *) NULL ); if( tdomain == NULL ) { errorstream << "Warning: domainname parameter is the null pointer" << ", default domain is not set" << std::endl; tdomain = (char *) "messages"; } /* char *codeset = */bind_textdomain_codeset( tdomain, "UTF-8" ); //errorstream << "Gettext debug: domainname = " << tdomain << "; codeset = "<< codeset << std::endl; #endif // defined(_WIN32) #else /* set current system default locale */ setlocale(LC_ALL, ""); #endif // if USE_GETTEXT /* no matter what locale is used we need number format to be "C" */ /* to ensure formspec parameters are evaluated correct! */ setlocale(LC_NUMERIC, "C"); infostream << "Message locale is now set to: " << setlocale(LC_ALL, 0) << std::endl; }
pgimeno/minetest
src/gettext.cpp
C++
mit
7,306
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "config.h" // for USE_GETTEXT #include <string> #if USE_GETTEXT #include <libintl.h> #else // In certain environments, some standard headers like <iomanip> // and <locale> include libintl.h. If libintl.h is included after // we define our gettext macro below, this causes a syntax error // at the declaration of the gettext function in libintl.h. // Fix this by including such a header before defining the macro. // See issue #4446. // Note that we can't include libintl.h directly since we're in // the USE_GETTEXT=0 case and can't assume that gettext is installed. #include <locale> #define gettext(String) String #endif #define _(String) gettext(String) #define gettext_noop(String) (String) #define N_(String) gettext_noop((String)) void init_gettext(const char *path, const std::string &configured_language, int argc, char *argv[]); extern wchar_t *utf8_to_wide_c(const char *str); // You must free the returned string! // The returned string is allocated using new inline const wchar_t *wgettext(const char *str) { // We must check here that is not an empty string to avoid trying to translate it return str[0] ? utf8_to_wide_c(gettext(str)) : utf8_to_wide_c(""); } inline std::string strgettext(const std::string &text) { return text.empty() ? "" : gettext(text.c_str()); }
pgimeno/minetest
src/gettext.h
C++
mit
2,111
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes.h" #include <ctime> #include <string> enum TimePrecision { PRECISION_SECONDS, PRECISION_MILLI, PRECISION_MICRO, PRECISION_NANO }; inline std::string getTimestamp() { time_t t = time(NULL); // This is not really thread-safe but it won't break anything // except its own output, so just go with it. struct tm *tm = localtime(&t); char cs[20]; // YYYY-MM-DD HH:MM:SS + '\0' strftime(cs, 20, "%Y-%m-%d %H:%M:%S", tm); return cs; }
pgimeno/minetest
src/gettime.h
C++
mit
1,263
set(gui_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/guiChatConsole.cpp ${CMAKE_CURRENT_SOURCE_DIR}/guiConfirmRegistration.cpp ${CMAKE_CURRENT_SOURCE_DIR}/guiEditBoxWithScrollbar.cpp ${CMAKE_CURRENT_SOURCE_DIR}/guiEngine.cpp ${CMAKE_CURRENT_SOURCE_DIR}/guiFormSpecMenu.cpp ${CMAKE_CURRENT_SOURCE_DIR}/guiKeyChangeMenu.cpp ${CMAKE_CURRENT_SOURCE_DIR}/guiPasswordChange.cpp ${CMAKE_CURRENT_SOURCE_DIR}/guiPathSelectMenu.cpp ${CMAKE_CURRENT_SOURCE_DIR}/guiTable.cpp ${CMAKE_CURRENT_SOURCE_DIR}/guiVolumeChange.cpp ${CMAKE_CURRENT_SOURCE_DIR}/intlGUIEditBox.cpp ${CMAKE_CURRENT_SOURCE_DIR}/modalMenu.cpp ${CMAKE_CURRENT_SOURCE_DIR}/profilergraph.cpp PARENT_SCOPE )
pgimeno/minetest
src/gui/CMakeLists.txt
Text
mit
663
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "guiChatConsole.h" #include "chat.h" #include "client/client.h" #include "debug.h" #include "gettime.h" #include "client/keycode.h" #include "settings.h" #include "porting.h" #include "client/tile.h" #include "client/fontengine.h" #include "log.h" #include "gettext.h" #include <string> #if USE_FREETYPE #include "irrlicht_changes/CGUITTFont.h" #endif inline u32 clamp_u8(s32 value) { return (u32) MYMIN(MYMAX(value, 0), 255); } GUIChatConsole::GUIChatConsole( gui::IGUIEnvironment* env, gui::IGUIElement* parent, s32 id, ChatBackend* backend, Client* client, IMenuManager* menumgr ): IGUIElement(gui::EGUIET_ELEMENT, env, parent, id, core::rect<s32>(0,0,100,100)), m_chat_backend(backend), m_client(client), m_menumgr(menumgr), m_animate_time_old(porting::getTimeMs()) { // load background settings s32 console_alpha = g_settings->getS32("console_alpha"); m_background_color.setAlpha(clamp_u8(console_alpha)); // load the background texture depending on settings ITextureSource *tsrc = client->getTextureSource(); if (tsrc->isKnownSourceImage("background_chat.jpg")) { m_background = tsrc->getTexture("background_chat.jpg"); m_background_color.setRed(255); m_background_color.setGreen(255); m_background_color.setBlue(255); } else { v3f console_color = g_settings->getV3F("console_color"); m_background_color.setRed(clamp_u8(myround(console_color.X))); m_background_color.setGreen(clamp_u8(myround(console_color.Y))); m_background_color.setBlue(clamp_u8(myround(console_color.Z))); } m_font = g_fontengine->getFont(FONT_SIZE_UNSPECIFIED, FM_Mono); if (!m_font) { errorstream << "GUIChatConsole: Unable to load mono font "; } else { core::dimension2d<u32> dim = m_font->getDimension(L"M"); m_fontsize = v2u32(dim.Width, dim.Height); m_font->grab(); } m_fontsize.X = MYMAX(m_fontsize.X, 1); m_fontsize.Y = MYMAX(m_fontsize.Y, 1); // set default cursor options setCursor(true, true, 2.0, 0.1); } GUIChatConsole::~GUIChatConsole() { if (m_font) m_font->drop(); } void GUIChatConsole::openConsole(f32 scale) { assert(scale > 0.0f && scale <= 1.0f); m_open = true; m_desired_height_fraction = scale; m_desired_height = scale * m_screensize.Y; reformatConsole(); m_animate_time_old = porting::getTimeMs(); IGUIElement::setVisible(true); Environment->setFocus(this); m_menumgr->createdMenu(this); } bool GUIChatConsole::isOpen() const { return m_open; } bool GUIChatConsole::isOpenInhibited() const { return m_open_inhibited > 0; } void GUIChatConsole::closeConsole() { m_open = false; Environment->removeFocus(this); m_menumgr->deletingMenu(this); } void GUIChatConsole::closeConsoleAtOnce() { closeConsole(); m_height = 0; recalculateConsolePosition(); } f32 GUIChatConsole::getDesiredHeight() const { return m_desired_height_fraction; } void GUIChatConsole::replaceAndAddToHistory(std::wstring line) { ChatPrompt& prompt = m_chat_backend->getPrompt(); prompt.addToHistory(prompt.getLine()); prompt.replace(line); } void GUIChatConsole::setCursor( bool visible, bool blinking, f32 blink_speed, f32 relative_height) { if (visible) { if (blinking) { // leave m_cursor_blink unchanged m_cursor_blink_speed = blink_speed; } else { m_cursor_blink = 0x8000; // on m_cursor_blink_speed = 0.0; } } else { m_cursor_blink = 0; // off m_cursor_blink_speed = 0.0; } m_cursor_height = relative_height; } void GUIChatConsole::draw() { if(!IsVisible) return; video::IVideoDriver* driver = Environment->getVideoDriver(); // Check screen size v2u32 screensize = driver->getScreenSize(); if (screensize != m_screensize) { // screen size has changed // scale current console height to new window size if (m_screensize.Y != 0) m_height = m_height * screensize.Y / m_screensize.Y; m_screensize = screensize; m_desired_height = m_desired_height_fraction * m_screensize.Y; reformatConsole(); } // Animation u64 now = porting::getTimeMs(); animate(now - m_animate_time_old); m_animate_time_old = now; // Draw console elements if visible if (m_height > 0) { drawBackground(); drawText(); drawPrompt(); } gui::IGUIElement::draw(); } void GUIChatConsole::reformatConsole() { s32 cols = m_screensize.X / m_fontsize.X - 2; // make room for a margin (looks better) s32 rows = m_desired_height / m_fontsize.Y - 1; // make room for the input prompt if (cols <= 0 || rows <= 0) cols = rows = 0; recalculateConsolePosition(); m_chat_backend->reformat(cols, rows); } void GUIChatConsole::recalculateConsolePosition() { core::rect<s32> rect(0, 0, m_screensize.X, m_height); DesiredRect = rect; recalculateAbsolutePosition(false); } void GUIChatConsole::animate(u32 msec) { // animate the console height s32 goal = m_open ? m_desired_height : 0; // Set invisible if close animation finished (reset by openConsole) // This function (animate()) is never called once its visibility becomes false so do not // actually set visible to false before the inhibited period is over if (!m_open && m_height == 0 && m_open_inhibited == 0) IGUIElement::setVisible(false); if (m_height != goal) { s32 max_change = msec * m_screensize.Y * (m_height_speed / 1000.0); if (max_change == 0) max_change = 1; if (m_height < goal) { // increase height if (m_height + max_change < goal) m_height += max_change; else m_height = goal; } else { // decrease height if (m_height > goal + max_change) m_height -= max_change; else m_height = goal; } recalculateConsolePosition(); } // blink the cursor if (m_cursor_blink_speed != 0.0) { u32 blink_increase = 0x10000 * msec * (m_cursor_blink_speed / 1000.0); if (blink_increase == 0) blink_increase = 1; m_cursor_blink = ((m_cursor_blink + blink_increase) & 0xffff); } // decrease open inhibit counter if (m_open_inhibited > msec) m_open_inhibited -= msec; else m_open_inhibited = 0; } void GUIChatConsole::drawBackground() { video::IVideoDriver* driver = Environment->getVideoDriver(); if (m_background != NULL) { core::rect<s32> sourcerect(0, -m_height, m_screensize.X, 0); driver->draw2DImage( m_background, v2s32(0, 0), sourcerect, &AbsoluteClippingRect, m_background_color, false); } else { driver->draw2DRectangle( m_background_color, core::rect<s32>(0, 0, m_screensize.X, m_height), &AbsoluteClippingRect); } } void GUIChatConsole::drawText() { if (m_font == NULL) return; ChatBuffer& buf = m_chat_backend->getConsoleBuffer(); for (u32 row = 0; row < buf.getRows(); ++row) { const ChatFormattedLine& line = buf.getFormattedLine(row); if (line.fragments.empty()) continue; s32 line_height = m_fontsize.Y; s32 y = row * line_height + m_height - m_desired_height; if (y + line_height < 0) continue; for (const ChatFormattedFragment &fragment : line.fragments) { s32 x = (fragment.column + 1) * m_fontsize.X; core::rect<s32> destrect( x, y, x + m_fontsize.X * fragment.text.size(), y + m_fontsize.Y); #if USE_FREETYPE // Draw colored text if FreeType is enabled irr::gui::CGUITTFont *tmp = dynamic_cast<irr::gui::CGUITTFont *>(m_font); tmp->draw( fragment.text, destrect, video::SColor(255, 255, 255, 255), false, false, &AbsoluteClippingRect); #else // Otherwise use standard text m_font->draw( fragment.text.c_str(), destrect, video::SColor(255, 255, 255, 255), false, false, &AbsoluteClippingRect); #endif } } } void GUIChatConsole::drawPrompt() { if (!m_font) return; u32 row = m_chat_backend->getConsoleBuffer().getRows(); s32 line_height = m_fontsize.Y; s32 y = row * line_height + m_height - m_desired_height; ChatPrompt& prompt = m_chat_backend->getPrompt(); std::wstring prompt_text = prompt.getVisiblePortion(); // FIXME Draw string at once, not character by character // That will only work with the cursor once we have a monospace font for (u32 i = 0; i < prompt_text.size(); ++i) { wchar_t ws[2] = {prompt_text[i], 0}; s32 x = (1 + i) * m_fontsize.X; core::rect<s32> destrect( x, y, x + m_fontsize.X, y + m_fontsize.Y); m_font->draw( ws, destrect, video::SColor(255, 255, 255, 255), false, false, &AbsoluteClippingRect); } // Draw the cursor during on periods if ((m_cursor_blink & 0x8000) != 0) { s32 cursor_pos = prompt.getVisibleCursorPosition(); if (cursor_pos >= 0) { s32 cursor_len = prompt.getCursorLength(); video::IVideoDriver* driver = Environment->getVideoDriver(); s32 x = (1 + cursor_pos) * m_fontsize.X; core::rect<s32> destrect( x, y + m_fontsize.Y * (1.0 - m_cursor_height), x + m_fontsize.X * MYMAX(cursor_len, 1), y + m_fontsize.Y * (cursor_len ? m_cursor_height+1 : 1) ); video::SColor cursor_color(255,255,255,255); driver->draw2DRectangle( cursor_color, destrect, &AbsoluteClippingRect); } } } bool GUIChatConsole::OnEvent(const SEvent& event) { ChatPrompt &prompt = m_chat_backend->getPrompt(); if(event.EventType == EET_KEY_INPUT_EVENT && event.KeyInput.PressedDown) { // Key input if (KeyPress(event.KeyInput) == getKeySetting("keymap_console")) { closeConsole(); // inhibit open so the_game doesn't reopen immediately m_open_inhibited = 50; m_close_on_enter = false; return true; } if (event.KeyInput.Key == KEY_ESCAPE) { closeConsoleAtOnce(); m_close_on_enter = false; // inhibit open so the_game doesn't reopen immediately m_open_inhibited = 1; // so the ESCAPE button doesn't open the "pause menu" return true; } else if(event.KeyInput.Key == KEY_PRIOR) { m_chat_backend->scrollPageUp(); return true; } else if(event.KeyInput.Key == KEY_NEXT) { m_chat_backend->scrollPageDown(); return true; } else if(event.KeyInput.Key == KEY_RETURN) { prompt.addToHistory(prompt.getLine()); std::wstring text = prompt.replace(L""); m_client->typeChatMessage(text); if (m_close_on_enter) { closeConsoleAtOnce(); m_close_on_enter = false; } return true; } else if(event.KeyInput.Key == KEY_UP) { // Up pressed // Move back in history prompt.historyPrev(); return true; } else if(event.KeyInput.Key == KEY_DOWN) { // Down pressed // Move forward in history prompt.historyNext(); return true; } else if(event.KeyInput.Key == KEY_LEFT || event.KeyInput.Key == KEY_RIGHT) { // Left/right pressed // Move/select character/word to the left depending on control and shift keys ChatPrompt::CursorOp op = event.KeyInput.Shift ? ChatPrompt::CURSOROP_SELECT : ChatPrompt::CURSOROP_MOVE; ChatPrompt::CursorOpDir dir = event.KeyInput.Key == KEY_LEFT ? ChatPrompt::CURSOROP_DIR_LEFT : ChatPrompt::CURSOROP_DIR_RIGHT; ChatPrompt::CursorOpScope scope = event.KeyInput.Control ? ChatPrompt::CURSOROP_SCOPE_WORD : ChatPrompt::CURSOROP_SCOPE_CHARACTER; prompt.cursorOperation(op, dir, scope); return true; } else if(event.KeyInput.Key == KEY_HOME) { // Home pressed // move to beginning of line prompt.cursorOperation( ChatPrompt::CURSOROP_MOVE, ChatPrompt::CURSOROP_DIR_LEFT, ChatPrompt::CURSOROP_SCOPE_LINE); return true; } else if(event.KeyInput.Key == KEY_END) { // End pressed // move to end of line prompt.cursorOperation( ChatPrompt::CURSOROP_MOVE, ChatPrompt::CURSOROP_DIR_RIGHT, ChatPrompt::CURSOROP_SCOPE_LINE); return true; } else if(event.KeyInput.Key == KEY_BACK) { // Backspace or Ctrl-Backspace pressed // delete character / word to the left ChatPrompt::CursorOpScope scope = event.KeyInput.Control ? ChatPrompt::CURSOROP_SCOPE_WORD : ChatPrompt::CURSOROP_SCOPE_CHARACTER; prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_LEFT, scope); return true; } else if(event.KeyInput.Key == KEY_DELETE) { // Delete or Ctrl-Delete pressed // delete character / word to the right ChatPrompt::CursorOpScope scope = event.KeyInput.Control ? ChatPrompt::CURSOROP_SCOPE_WORD : ChatPrompt::CURSOROP_SCOPE_CHARACTER; prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_RIGHT, scope); return true; } else if(event.KeyInput.Key == KEY_KEY_A && event.KeyInput.Control) { // Ctrl-A pressed // Select all text prompt.cursorOperation( ChatPrompt::CURSOROP_SELECT, ChatPrompt::CURSOROP_DIR_LEFT, // Ignored ChatPrompt::CURSOROP_SCOPE_LINE); return true; } else if(event.KeyInput.Key == KEY_KEY_C && event.KeyInput.Control) { // Ctrl-C pressed // Copy text to clipboard if (prompt.getCursorLength() <= 0) return true; std::wstring wselected = prompt.getSelection(); std::string selected(wselected.begin(), wselected.end()); Environment->getOSOperator()->copyToClipboard(selected.c_str()); return true; } else if(event.KeyInput.Key == KEY_KEY_V && event.KeyInput.Control) { // Ctrl-V pressed // paste text from clipboard if (prompt.getCursorLength() > 0) { // Delete selected section of text prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_LEFT, // Ignored ChatPrompt::CURSOROP_SCOPE_SELECTION); } IOSOperator *os_operator = Environment->getOSOperator(); const c8 *text = os_operator->getTextFromClipboard(); if (!text) return true; std::basic_string<unsigned char> str((const unsigned char*)text); prompt.input(std::wstring(str.begin(), str.end())); return true; } else if(event.KeyInput.Key == KEY_KEY_X && event.KeyInput.Control) { // Ctrl-X pressed // Cut text to clipboard if (prompt.getCursorLength() <= 0) return true; std::wstring wselected = prompt.getSelection(); std::string selected(wselected.begin(), wselected.end()); Environment->getOSOperator()->copyToClipboard(selected.c_str()); prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_LEFT, // Ignored ChatPrompt::CURSOROP_SCOPE_SELECTION); return true; } else if(event.KeyInput.Key == KEY_KEY_U && event.KeyInput.Control) { // Ctrl-U pressed // kill line to left end prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_LEFT, ChatPrompt::CURSOROP_SCOPE_LINE); return true; } else if(event.KeyInput.Key == KEY_KEY_K && event.KeyInput.Control) { // Ctrl-K pressed // kill line to right end prompt.cursorOperation( ChatPrompt::CURSOROP_DELETE, ChatPrompt::CURSOROP_DIR_RIGHT, ChatPrompt::CURSOROP_SCOPE_LINE); return true; } else if(event.KeyInput.Key == KEY_TAB) { // Tab or Shift-Tab pressed // Nick completion std::list<std::string> names = m_client->getConnectedPlayerNames(); bool backwards = event.KeyInput.Shift; prompt.nickCompletion(names, backwards); return true; } else if (!iswcntrl(event.KeyInput.Char) && !event.KeyInput.Control) { #if defined(__linux__) && (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9) wchar_t wc = L'_'; mbtowc( &wc, (char *) &event.KeyInput.Char, sizeof(event.KeyInput.Char) ); prompt.input(wc); #else prompt.input(event.KeyInput.Char); #endif return true; } } else if(event.EventType == EET_MOUSE_INPUT_EVENT) { if(event.MouseInput.Event == EMIE_MOUSE_WHEEL) { s32 rows = myround(-3.0 * event.MouseInput.Wheel); m_chat_backend->scroll(rows); } } return Parent ? Parent->OnEvent(event) : false; } void GUIChatConsole::setVisible(bool visible) { m_open = visible; IGUIElement::setVisible(visible); if (!visible) { m_height = 0; recalculateConsolePosition(); } }
pgimeno/minetest
src/gui/guiChatConsole.cpp
C++
mit
16,602
/* Minetest Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes_extrabloated.h" #include "modalMenu.h" #include "chat.h" #include "config.h" class Client; class GUIChatConsole : public gui::IGUIElement { public: GUIChatConsole(gui::IGUIEnvironment* env, gui::IGUIElement* parent, s32 id, ChatBackend* backend, Client* client, IMenuManager* menumgr); virtual ~GUIChatConsole(); // Open the console (height = desired fraction of screen size) // This doesn't open immediately but initiates an animation. // You should call isOpenInhibited() before this. void openConsole(f32 scale); bool isOpen() const; // Check if the console should not be opened at the moment // This is to avoid reopening the console immediately after closing bool isOpenInhibited() const; // Close the console, equivalent to openConsole(0). // This doesn't close immediately but initiates an animation. void closeConsole(); // Close the console immediately, without animation. void closeConsoleAtOnce(); // Set whether to close the console after the user presses enter. void setCloseOnEnter(bool close) { m_close_on_enter = close; } // Return the desired height (fraction of screen size) // Zero if the console is closed or getting closed f32 getDesiredHeight() const; // Replace actual line when adding the actual to the history (if there is any) void replaceAndAddToHistory(std::wstring line); // Change how the cursor looks void setCursor( bool visible, bool blinking = false, f32 blink_speed = 1.0, f32 relative_height = 1.0); // Irrlicht draw method virtual void draw(); bool canTakeFocus(gui::IGUIElement* element) { return false; } virtual bool OnEvent(const SEvent& event); virtual void setVisible(bool visible); private: void reformatConsole(); void recalculateConsolePosition(); // These methods are called by draw void animate(u32 msec); void drawBackground(); void drawText(); void drawPrompt(); private: ChatBackend* m_chat_backend; Client* m_client; IMenuManager* m_menumgr; // current screen size v2u32 m_screensize; // used to compute how much time passed since last animate() u64 m_animate_time_old; // should the console be opened or closed? bool m_open = false; // should it close after you press enter? bool m_close_on_enter = false; // current console height [pixels] s32 m_height = 0; // desired height [pixels] f32 m_desired_height = 0.0f; // desired height [screen height fraction] f32 m_desired_height_fraction = 0.0f; // console open/close animation speed [screen height fraction / second] f32 m_height_speed = 5.0f; // if nonzero, opening the console is inhibited [milliseconds] u32 m_open_inhibited = 0; // cursor blink frame (16-bit value) // cursor is off during [0,32767] and on during [32768,65535] u32 m_cursor_blink = 0; // cursor blink speed [on/off toggles / second] f32 m_cursor_blink_speed = 0.0f; // cursor height [line height] f32 m_cursor_height = 0.0f; // background texture video::ITexture *m_background = nullptr; // background color (including alpha) video::SColor m_background_color = video::SColor(255, 0, 0, 0); // font gui::IGUIFont *m_font = nullptr; v2u32 m_fontsize; };
pgimeno/minetest
src/gui/guiChatConsole.h
C++
mit
3,965
/* Minetest Copyright (C) 2018 srifqi, Muhammad Rifqi Priyo Susanto <muhammadrifqipriyosusanto@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "guiConfirmRegistration.h" #include "client/client.h" #include <IGUICheckBox.h> #include <IGUIButton.h> #include <IGUIStaticText.h> #include <IGUIFont.h> #include "intlGUIEditBox.h" #include "porting.h" #include "gettext.h" // Continuing from guiPasswordChange.cpp const int ID_confirmPassword = 262; const int ID_confirm = 263; const int ID_message = 264; const int ID_cancel = 265; GUIConfirmRegistration::GUIConfirmRegistration(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, IMenuManager *menumgr, Client *client, const std::string &playername, const std::string &password, bool *aborted) : GUIModalMenu(env, parent, id, menumgr), m_client(client), m_playername(playername), m_password(password), m_aborted(aborted) { #ifdef __ANDROID__ m_touchscreen_visible = false; #endif } GUIConfirmRegistration::~GUIConfirmRegistration() { removeChildren(); } void GUIConfirmRegistration::removeChildren() { const core::list<gui::IGUIElement *> &children = getChildren(); core::list<gui::IGUIElement *> children_copy; for (gui::IGUIElement *i : children) children_copy.push_back(i); for (gui::IGUIElement *i : children_copy) i->remove(); } void GUIConfirmRegistration::regenerateGui(v2u32 screensize) { acceptInput(); removeChildren(); /* Calculate new sizes and positions */ const float s = m_gui_scale; DesiredRect = core::rect<s32>( screensize.X / 2 - 600 * s / 2, screensize.Y / 2 - 360 * s / 2, screensize.X / 2 + 600 * s / 2, screensize.Y / 2 + 360 * s / 2 ); recalculateAbsolutePosition(false); v2s32 size = DesiredRect.getSize(); v2s32 topleft_client(0, 0); const wchar_t *text; /* Add stuff */ s32 ypos = 30 * s; { core::rect<s32> rect2(0, 0, 540 * s, 180 * s); rect2 += topleft_client + v2s32(30 * s, ypos); static const std::string info_text_template = strgettext( "You are about to join this server with the name \"%s\" for the " "first time.\n" "If you proceed, a new account using your credentials will be " "created on this server.\n" "Please retype your password and click 'Register and Join' to " "confirm account creation, or click 'Cancel' to abort."); char info_text_buf[1024]; porting::mt_snprintf(info_text_buf, sizeof(info_text_buf), info_text_template.c_str(), m_playername.c_str()); wchar_t *info_text_buf_wide = utf8_to_wide_c(info_text_buf); gui::IGUIEditBox *e = new gui::intlGUIEditBox(info_text_buf_wide, true, Environment, this, ID_message, rect2, false, true); delete[] info_text_buf_wide; e->drop(); e->setMultiLine(true); e->setWordWrap(true); e->setTextAlignment(gui::EGUIA_UPPERLEFT, gui::EGUIA_CENTER); } ypos += 210 * s; { core::rect<s32> rect2(0, 0, 540 * s, 30 * s); rect2 += topleft_client + v2s32(30 * s, ypos); gui::IGUIEditBox *e = Environment->addEditBox(m_pass_confirm.c_str(), rect2, true, this, ID_confirmPassword); e->setPasswordBox(true); } ypos += 60 * s; { core::rect<s32> rect2(0, 0, 230 * s, 35 * s); rect2 = rect2 + v2s32(size.X / 2 - 220 * s, ypos); text = wgettext("Register and Join"); Environment->addButton(rect2, this, ID_confirm, text); delete[] text; } { core::rect<s32> rect2(0, 0, 120 * s, 35 * s); rect2 = rect2 + v2s32(size.X / 2 + 70 * s, ypos); text = wgettext("Cancel"); Environment->addButton(rect2, this, ID_cancel, text); delete[] text; } { core::rect<s32> rect2(0, 0, 200 * s, 20 * s); rect2 += topleft_client + v2s32(30 * s, ypos - 40 * s); text = wgettext("Passwords do not match!"); IGUIElement *e = Environment->addStaticText( text, rect2, false, true, this, ID_message); e->setVisible(false); delete[] text; } } void GUIConfirmRegistration::drawMenu() { gui::IGUISkin *skin = Environment->getSkin(); if (!skin) return; video::IVideoDriver *driver = Environment->getVideoDriver(); video::SColor bgcolor(140, 0, 0, 0); driver->draw2DRectangle(bgcolor, AbsoluteRect, &AbsoluteClippingRect); gui::IGUIElement::draw(); #ifdef __ANDROID__ getAndroidUIInput(); #endif } void GUIConfirmRegistration::closeMenu(bool goNext) { if (goNext) { m_client->confirmRegistration(); } else { *m_aborted = true; infostream << "Connect aborted [Escape]" << std::endl; } quitMenu(); } void GUIConfirmRegistration::acceptInput() { gui::IGUIElement *e; e = getElementFromId(ID_confirmPassword); if (e) m_pass_confirm = e->getText(); } bool GUIConfirmRegistration::processInput() { std::wstring m_password_ws = narrow_to_wide(m_password); if (m_password_ws != m_pass_confirm) { gui::IGUIElement *e = getElementFromId(ID_message); if (e) e->setVisible(true); return false; } return true; } bool GUIConfirmRegistration::OnEvent(const SEvent &event) { if (event.EventType == EET_KEY_INPUT_EVENT) { // clang-format off if ((event.KeyInput.Key == KEY_ESCAPE || event.KeyInput.Key == KEY_CANCEL) && event.KeyInput.PressedDown) { closeMenu(false); return true; } // clang-format on if (event.KeyInput.Key == KEY_RETURN && event.KeyInput.PressedDown) { acceptInput(); if (processInput()) closeMenu(true); return true; } } if (event.EventType != EET_GUI_EVENT) return Parent ? Parent->OnEvent(event) : false; if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST && isVisible()) { if (!canTakeFocus(event.GUIEvent.Element)) { dstream << "GUIConfirmRegistration: Not allowing focus " "change." << std::endl; // Returning true disables focus change return true; } } else if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED) { switch (event.GUIEvent.Caller->getID()) { case ID_confirm: acceptInput(); if (processInput()) closeMenu(true); return true; case ID_cancel: closeMenu(false); return true; } } else if (event.GUIEvent.EventType == gui::EGET_EDITBOX_ENTER) { switch (event.GUIEvent.Caller->getID()) { case ID_confirmPassword: acceptInput(); if (processInput()) closeMenu(true); return true; } } return false; } #ifdef __ANDROID__ bool GUIConfirmRegistration::getAndroidUIInput() { if (!hasAndroidUIInput() || m_jni_field_name != "password") return false; std::string text = porting::getInputDialogValue(); gui::IGUIElement *e = getElementFromId(ID_confirmPassword); if (e) e->setText(utf8_to_wide(text).c_str()); m_jni_field_name.clear(); return false; } #endif
pgimeno/minetest
src/gui/guiConfirmRegistration.cpp
C++
mit
7,209
/* Minetest Copyright (C) 2018 srifqi, Muhammad Rifqi Priyo Susanto <muhammadrifqipriyosusanto@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "irrlichttypes_extrabloated.h" #include "modalMenu.h" #include <string> class Client; class GUIConfirmRegistration : public GUIModalMenu { public: GUIConfirmRegistration(gui::IGUIEnvironment *env, gui::IGUIElement *parent, s32 id, IMenuManager *menumgr, Client *client, const std::string &playername, const std::string &password, bool *aborted); ~GUIConfirmRegistration(); void removeChildren(); /* Remove and re-add (or reposition) stuff */ void regenerateGui(v2u32 screensize); void drawMenu(); void closeMenu(bool goNext); void acceptInput(); bool processInput(); bool OnEvent(const SEvent &event); #ifdef __ANDROID__ bool getAndroidUIInput(); #endif private: std::wstring getLabelByID(s32 id) { return L""; } std::string getNameByID(s32 id) { return "password"; } Client *m_client = nullptr; const std::string &m_playername; const std::string &m_password; bool *m_aborted = nullptr; std::wstring m_pass_confirm = L""; };
pgimeno/minetest
src/gui/guiConfirmRegistration.h
C++
mit
1,804
// Copyright (C) 2002-2012 Nikolaus Gebhardt // Modified by Mustapha T. // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "guiEditBoxWithScrollbar.h" #include "IGUISkin.h" #include "IGUIEnvironment.h" #include "IGUIFont.h" #include "IVideoDriver.h" #include "rect.h" #include "porting.h" #include "Keycodes.h" /* todo: optional scrollbars [done] ctrl+left/right to select word double click/ctrl click: word select + drag to select whole words, triple click to select line optional? dragging selected text numerical */ //! constructor GUIEditBoxWithScrollBar::GUIEditBoxWithScrollBar(const wchar_t* text, bool border, IGUIEnvironment* environment, IGUIElement* parent, s32 id, const core::rect<s32>& rectangle, bool writable, bool has_vscrollbar) : IGUIEditBox(environment, parent, id, rectangle), m_mouse_marking(false), m_border(border), m_background(true), m_override_color_enabled(false), m_mark_begin(0), m_mark_end(0), m_override_color(video::SColor(101, 255, 255, 255)), m_override_font(0), m_last_break_font(0), m_operator(0), m_blink_start_time(0), m_cursor_pos(0), m_hscroll_pos(0), m_vscroll_pos(0), m_max(0), m_word_wrap(false), m_multiline(false), m_autoscroll(true), m_passwordbox(false), m_passwordchar(L'*'), m_halign(EGUIA_UPPERLEFT), m_valign(EGUIA_CENTER), m_current_text_rect(0, 0, 1, 1), m_frame_rect(rectangle), m_scrollbar_width(0), m_vscrollbar(NULL), m_writable(writable), m_bg_color_used(false) { #ifdef _DEBUG setDebugName("GUIEditBoxWithScrollBar"); #endif Text = text; if (Environment) m_operator = Environment->getOSOperator(); if (m_operator) m_operator->grab(); // this element can be tabbed to setTabStop(true); setTabOrder(-1); if (has_vscrollbar) { createVScrollBar(); } calculateFrameRect(); breakText(); calculateScrollPos(); setWritable(writable); } //! destructor GUIEditBoxWithScrollBar::~GUIEditBoxWithScrollBar() { if (m_override_font) m_override_font->drop(); if (m_operator) m_operator->drop(); m_vscrollbar->remove(); } //! Sets another skin independent font. void GUIEditBoxWithScrollBar::setOverrideFont(IGUIFont* font) { if (m_override_font == font) return; if (m_override_font) m_override_font->drop(); m_override_font = font; if (m_override_font) m_override_font->grab(); breakText(); } //! Gets the override font (if any) IGUIFont * GUIEditBoxWithScrollBar::getOverrideFont() const { return m_override_font; } //! Get the font which is used right now for drawing IGUIFont* GUIEditBoxWithScrollBar::getActiveFont() const { if (m_override_font) return m_override_font; IGUISkin* skin = Environment->getSkin(); if (skin) return skin->getFont(); return 0; } //! Sets another color for the text. void GUIEditBoxWithScrollBar::setOverrideColor(video::SColor color) { m_override_color = color; m_override_color_enabled = true; } video::SColor GUIEditBoxWithScrollBar::getOverrideColor() const { return m_override_color; } //! Turns the border on or off void GUIEditBoxWithScrollBar::setDrawBorder(bool border) { m_border = border; } //! Sets whether to draw the background void GUIEditBoxWithScrollBar::setDrawBackground(bool draw) { m_background = draw; } //! Sets if the text should use the overide color or the color in the gui skin. void GUIEditBoxWithScrollBar::enableOverrideColor(bool enable) { m_override_color_enabled = enable; } bool GUIEditBoxWithScrollBar::isOverrideColorEnabled() const { return m_override_color_enabled; } //! Enables or disables word wrap void GUIEditBoxWithScrollBar::setWordWrap(bool enable) { m_word_wrap = enable; breakText(); } void GUIEditBoxWithScrollBar::updateAbsolutePosition() { core::rect<s32> old_absolute_rect(AbsoluteRect); IGUIElement::updateAbsolutePosition(); if (old_absolute_rect != AbsoluteRect) { calculateFrameRect(); breakText(); calculateScrollPos(); } } //! Checks if word wrap is enabled bool GUIEditBoxWithScrollBar::isWordWrapEnabled() const { return m_word_wrap; } //! Enables or disables newlines. void GUIEditBoxWithScrollBar::setMultiLine(bool enable) { m_multiline = enable; } //! Checks if multi line editing is enabled bool GUIEditBoxWithScrollBar::isMultiLineEnabled() const { return m_multiline; } void GUIEditBoxWithScrollBar::setPasswordBox(bool password_box, wchar_t password_char) { m_passwordbox = password_box; if (m_passwordbox) { m_passwordchar = password_char; setMultiLine(false); setWordWrap(false); m_broken_text.clear(); } } bool GUIEditBoxWithScrollBar::isPasswordBox() const { return m_passwordbox; } //! Sets text justification void GUIEditBoxWithScrollBar::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical) { m_halign = horizontal; m_valign = vertical; } //! called if an event happened. bool GUIEditBoxWithScrollBar::OnEvent(const SEvent& event) { if (isEnabled()) { switch (event.EventType) { case EET_GUI_EVENT: if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) { if (event.GUIEvent.Caller == this) { m_mouse_marking = false; setTextMarkers(0, 0); } } break; case EET_KEY_INPUT_EVENT: if (processKey(event)) return true; break; case EET_MOUSE_INPUT_EVENT: if (processMouse(event)) return true; break; default: break; } } return IGUIElement::OnEvent(event); } bool GUIEditBoxWithScrollBar::processKey(const SEvent& event) { if (!m_writable) { return false; } if (!event.KeyInput.PressedDown) return false; bool text_changed = false; s32 new_mark_begin = m_mark_begin; s32 new_mark_end = m_mark_end; // control shortcut handling if (event.KeyInput.Control) { // german backlash '\' entered with control + '?' if (event.KeyInput.Char == '\\') { inputChar(event.KeyInput.Char); return true; } switch (event.KeyInput.Key) { case KEY_KEY_A: // select all new_mark_begin = 0; new_mark_end = Text.size(); break; case KEY_KEY_C: // copy to clipboard if (!m_passwordbox && m_operator && m_mark_begin != m_mark_end) { const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; core::stringc s; s = Text.subString(realmbgn, realmend - realmbgn).c_str(); m_operator->copyToClipboard(s.c_str()); } break; case KEY_KEY_X: // cut to the clipboard if (!m_passwordbox && m_operator && m_mark_begin != m_mark_end) { const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; // copy core::stringc sc; sc = Text.subString(realmbgn, realmend - realmbgn).c_str(); m_operator->copyToClipboard(sc.c_str()); if (isEnabled()) { // delete core::stringw s; s = Text.subString(0, realmbgn); s.append(Text.subString(realmend, Text.size() - realmend)); Text = s; m_cursor_pos = realmbgn; new_mark_begin = 0; new_mark_end = 0; text_changed = true; } } break; case KEY_KEY_V: if (!isEnabled()) break; // paste from the clipboard if (m_operator) { const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; // add new character const c8* p = m_operator->getTextFromClipboard(); if (p) { if (m_mark_begin == m_mark_end) { // insert text core::stringw s = Text.subString(0, m_cursor_pos); s.append(p); s.append(Text.subString(m_cursor_pos, Text.size() - m_cursor_pos)); if (!m_max || s.size() <= m_max) // thx to Fish FH for fix { Text = s; s = p; m_cursor_pos += s.size(); } } else { // replace text core::stringw s = Text.subString(0, realmbgn); s.append(p); s.append(Text.subString(realmend, Text.size() - realmend)); if (!m_max || s.size() <= m_max) // thx to Fish FH for fix { Text = s; s = p; m_cursor_pos = realmbgn + s.size(); } } } new_mark_begin = 0; new_mark_end = 0; text_changed = true; } break; case KEY_HOME: // move/highlight to start of text if (event.KeyInput.Shift) { new_mark_end = m_cursor_pos; new_mark_begin = 0; m_cursor_pos = 0; } else { m_cursor_pos = 0; new_mark_begin = 0; new_mark_end = 0; } break; case KEY_END: // move/highlight to end of text if (event.KeyInput.Shift) { new_mark_begin = m_cursor_pos; new_mark_end = Text.size(); m_cursor_pos = 0; } else { m_cursor_pos = Text.size(); new_mark_begin = 0; new_mark_end = 0; } break; default: return false; } } // default keyboard handling else switch (event.KeyInput.Key) { case KEY_END: { s32 p = Text.size(); if (m_word_wrap || m_multiline) { p = getLineFromPos(m_cursor_pos); p = m_broken_text_positions[p] + (s32)m_broken_text[p].size(); if (p > 0 && (Text[p - 1] == L'\r' || Text[p - 1] == L'\n')) p -= 1; } if (event.KeyInput.Shift) { if (m_mark_begin == m_mark_end) new_mark_begin = m_cursor_pos; new_mark_end = p; } else { new_mark_begin = 0; new_mark_end = 0; } m_cursor_pos = p; m_blink_start_time = porting::getTimeMs(); } break; case KEY_HOME: { s32 p = 0; if (m_word_wrap || m_multiline) { p = getLineFromPos(m_cursor_pos); p = m_broken_text_positions[p]; } if (event.KeyInput.Shift) { if (m_mark_begin == m_mark_end) new_mark_begin = m_cursor_pos; new_mark_end = p; } else { new_mark_begin = 0; new_mark_end = 0; } m_cursor_pos = p; m_blink_start_time = porting::getTimeMs(); } break; case KEY_RETURN: if (m_multiline) { inputChar(L'\n'); } else { calculateScrollPos(); sendGuiEvent(EGET_EDITBOX_ENTER); } return true; case KEY_LEFT: if (event.KeyInput.Shift) { if (m_cursor_pos > 0) { if (m_mark_begin == m_mark_end) new_mark_begin = m_cursor_pos; new_mark_end = m_cursor_pos - 1; } } else { new_mark_begin = 0; new_mark_end = 0; } if (m_cursor_pos > 0) m_cursor_pos--; m_blink_start_time = porting::getTimeMs(); break; case KEY_RIGHT: if (event.KeyInput.Shift) { if (Text.size() > (u32)m_cursor_pos) { if (m_mark_begin == m_mark_end) new_mark_begin = m_cursor_pos; new_mark_end = m_cursor_pos + 1; } } else { new_mark_begin = 0; new_mark_end = 0; } if (Text.size() > (u32)m_cursor_pos) m_cursor_pos++; m_blink_start_time = porting::getTimeMs(); break; case KEY_UP: if (m_multiline || (m_word_wrap && m_broken_text.size() > 1)) { s32 lineNo = getLineFromPos(m_cursor_pos); s32 mb = (m_mark_begin == m_mark_end) ? m_cursor_pos : (m_mark_begin > m_mark_end ? m_mark_begin : m_mark_end); if (lineNo > 0) { s32 cp = m_cursor_pos - m_broken_text_positions[lineNo]; if ((s32)m_broken_text[lineNo - 1].size() < cp) m_cursor_pos = m_broken_text_positions[lineNo - 1] + core::max_((u32)1, m_broken_text[lineNo - 1].size()) - 1; else m_cursor_pos = m_broken_text_positions[lineNo - 1] + cp; } if (event.KeyInput.Shift) { new_mark_begin = mb; new_mark_end = m_cursor_pos; } else { new_mark_begin = 0; new_mark_end = 0; } } else { return false; } break; case KEY_DOWN: if (m_multiline || (m_word_wrap && m_broken_text.size() > 1)) { s32 lineNo = getLineFromPos(m_cursor_pos); s32 mb = (m_mark_begin == m_mark_end) ? m_cursor_pos : (m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end); if (lineNo < (s32)m_broken_text.size() - 1) { s32 cp = m_cursor_pos - m_broken_text_positions[lineNo]; if ((s32)m_broken_text[lineNo + 1].size() < cp) m_cursor_pos = m_broken_text_positions[lineNo + 1] + core::max_((u32)1, m_broken_text[lineNo + 1].size()) - 1; else m_cursor_pos = m_broken_text_positions[lineNo + 1] + cp; } if (event.KeyInput.Shift) { new_mark_begin = mb; new_mark_end = m_cursor_pos; } else { new_mark_begin = 0; new_mark_end = 0; } } else { return false; } break; case KEY_BACK: if (!isEnabled()) break; if (Text.size()) { core::stringw s; if (m_mark_begin != m_mark_end) { // delete marked text const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; s = Text.subString(0, realmbgn); s.append(Text.subString(realmend, Text.size() - realmend)); Text = s; m_cursor_pos = realmbgn; } else { // delete text behind cursor if (m_cursor_pos > 0) s = Text.subString(0, m_cursor_pos - 1); else s = L""; s.append(Text.subString(m_cursor_pos, Text.size() - m_cursor_pos)); Text = s; --m_cursor_pos; } if (m_cursor_pos < 0) m_cursor_pos = 0; m_blink_start_time = porting::getTimeMs(); // os::Timer::getTime(); new_mark_begin = 0; new_mark_end = 0; text_changed = true; } break; case KEY_DELETE: if (!isEnabled()) break; if (Text.size() != 0) { core::stringw s; if (m_mark_begin != m_mark_end) { // delete marked text const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; s = Text.subString(0, realmbgn); s.append(Text.subString(realmend, Text.size() - realmend)); Text = s; m_cursor_pos = realmbgn; } else { // delete text before cursor s = Text.subString(0, m_cursor_pos); s.append(Text.subString(m_cursor_pos + 1, Text.size() - m_cursor_pos - 1)); Text = s; } if (m_cursor_pos > (s32)Text.size()) m_cursor_pos = (s32)Text.size(); m_blink_start_time = porting::getTimeMs(); // os::Timer::getTime(); new_mark_begin = 0; new_mark_end = 0; text_changed = true; } break; case KEY_ESCAPE: case KEY_TAB: case KEY_SHIFT: case KEY_F1: case KEY_F2: case KEY_F3: case KEY_F4: case KEY_F5: case KEY_F6: case KEY_F7: case KEY_F8: case KEY_F9: case KEY_F10: case KEY_F11: case KEY_F12: case KEY_F13: case KEY_F14: case KEY_F15: case KEY_F16: case KEY_F17: case KEY_F18: case KEY_F19: case KEY_F20: case KEY_F21: case KEY_F22: case KEY_F23: case KEY_F24: // ignore these keys return false; default: inputChar(event.KeyInput.Char); return true; } // Set new text markers setTextMarkers(new_mark_begin, new_mark_end); // break the text if it has changed if (text_changed) { breakText(); calculateScrollPos(); sendGuiEvent(EGET_EDITBOX_CHANGED); } else { calculateScrollPos(); } return true; } //! draws the element and its children void GUIEditBoxWithScrollBar::draw() { if (!IsVisible) return; const bool focus = Environment->hasFocus(this); IGUISkin* skin = Environment->getSkin(); if (!skin) return; video::SColor default_bg_color; video::SColor bg_color; default_bg_color = m_writable ? skin->getColor(EGDC_WINDOW) : video::SColor(0); bg_color = m_bg_color_used ? m_bg_color : default_bg_color; if (!m_border && m_background) { skin->draw2DRectangle(this, bg_color, AbsoluteRect, &AbsoluteClippingRect); } // draw the border if (m_border) { if (m_writable) { skin->draw3DSunkenPane(this, bg_color, false, m_background, AbsoluteRect, &AbsoluteClippingRect); } calculateFrameRect(); } core::rect<s32> local_clip_rect = m_frame_rect; local_clip_rect.clipAgainst(AbsoluteClippingRect); // draw the text IGUIFont* font = getActiveFont(); s32 cursor_line = 0; s32 charcursorpos = 0; if (font) { if (m_last_break_font != font) { breakText(); } // calculate cursor pos core::stringw *txt_line = &Text; s32 start_pos = 0; core::stringw s, s2; // get mark position const bool ml = (!m_passwordbox && (m_word_wrap || m_multiline)); const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; const s32 hline_start = ml ? getLineFromPos(realmbgn) : 0; const s32 hline_count = ml ? getLineFromPos(realmend) - hline_start + 1 : 1; const s32 line_count = ml ? m_broken_text.size() : 1; // Save the override color information. // Then, alter it if the edit box is disabled. const bool prevOver = m_override_color_enabled; const video::SColor prevColor = m_override_color; if (Text.size()) { if (!isEnabled() && !m_override_color_enabled) { m_override_color_enabled = true; m_override_color = skin->getColor(EGDC_GRAY_TEXT); } for (s32 i = 0; i < line_count; ++i) { setTextRect(i); // clipping test - don't draw anything outside the visible area core::rect<s32> c = local_clip_rect; c.clipAgainst(m_current_text_rect); if (!c.isValid()) continue; // get current line if (m_passwordbox) { if (m_broken_text.size() != 1) { m_broken_text.clear(); m_broken_text.emplace_back(); } if (m_broken_text[0].size() != Text.size()){ m_broken_text[0] = Text; for (u32 q = 0; q < Text.size(); ++q) { m_broken_text[0][q] = m_passwordchar; } } txt_line = &m_broken_text[0]; start_pos = 0; } else { txt_line = ml ? &m_broken_text[i] : &Text; start_pos = ml ? m_broken_text_positions[i] : 0; } // draw normal text font->draw(txt_line->c_str(), m_current_text_rect, m_override_color_enabled ? m_override_color : skin->getColor(EGDC_BUTTON_TEXT), false, true, &local_clip_rect); // draw mark and marked text if (focus && m_mark_begin != m_mark_end && i >= hline_start && i < hline_start + hline_count) { s32 mbegin = 0, mend = 0; s32 lineStartPos = 0, lineEndPos = txt_line->size(); if (i == hline_start) { // highlight start is on this line s = txt_line->subString(0, realmbgn - start_pos); mbegin = font->getDimension(s.c_str()).Width; // deal with kerning mbegin += font->getKerningWidth( &((*txt_line)[realmbgn - start_pos]), realmbgn - start_pos > 0 ? &((*txt_line)[realmbgn - start_pos - 1]) : 0); lineStartPos = realmbgn - start_pos; } if (i == hline_start + hline_count - 1) { // highlight end is on this line s2 = txt_line->subString(0, realmend - start_pos); mend = font->getDimension(s2.c_str()).Width; lineEndPos = (s32)s2.size(); } else { mend = font->getDimension(txt_line->c_str()).Width; } m_current_text_rect.UpperLeftCorner.X += mbegin; m_current_text_rect.LowerRightCorner.X = m_current_text_rect.UpperLeftCorner.X + mend - mbegin; // draw mark skin->draw2DRectangle(this, skin->getColor(EGDC_HIGH_LIGHT), m_current_text_rect, &local_clip_rect); // draw marked text s = txt_line->subString(lineStartPos, lineEndPos - lineStartPos); if (s.size()) font->draw(s.c_str(), m_current_text_rect, m_override_color_enabled ? m_override_color : skin->getColor(EGDC_HIGH_LIGHT_TEXT), false, true, &local_clip_rect); } } // Return the override color information to its previous settings. m_override_color_enabled = prevOver; m_override_color = prevColor; } // draw cursor if (IsEnabled && m_writable) { if (m_word_wrap || m_multiline) { cursor_line = getLineFromPos(m_cursor_pos); txt_line = &m_broken_text[cursor_line]; start_pos = m_broken_text_positions[cursor_line]; } s = txt_line->subString(0, m_cursor_pos - start_pos); charcursorpos = font->getDimension(s.c_str()).Width + font->getKerningWidth(L"_", m_cursor_pos - start_pos > 0 ? &((*txt_line)[m_cursor_pos - start_pos - 1]) : 0); if (focus && (porting::getTimeMs() - m_blink_start_time) % 700 < 350) { setTextRect(cursor_line); m_current_text_rect.UpperLeftCorner.X += charcursorpos; font->draw(L"_", m_current_text_rect, m_override_color_enabled ? m_override_color : skin->getColor(EGDC_BUTTON_TEXT), false, true, &local_clip_rect); } } } // draw children IGUIElement::draw(); } //! Sets the new caption of this element. void GUIEditBoxWithScrollBar::setText(const wchar_t* text) { Text = text; if (u32(m_cursor_pos) > Text.size()) m_cursor_pos = Text.size(); m_hscroll_pos = 0; breakText(); } //! Enables or disables automatic scrolling with cursor position //! \param enable: If set to true, the text will move around with the cursor position void GUIEditBoxWithScrollBar::setAutoScroll(bool enable) { m_autoscroll = enable; } //! Checks to see if automatic scrolling is enabled //! \return true if automatic scrolling is enabled, false if not bool GUIEditBoxWithScrollBar::isAutoScrollEnabled() const { return m_autoscroll; } //! Gets the area of the text in the edit box //! \return Returns the size in pixels of the text core::dimension2du GUIEditBoxWithScrollBar::getTextDimension() { core::rect<s32> ret; setTextRect(0); ret = m_current_text_rect; for (u32 i = 1; i < m_broken_text.size(); ++i) { setTextRect(i); ret.addInternalPoint(m_current_text_rect.UpperLeftCorner); ret.addInternalPoint(m_current_text_rect.LowerRightCorner); } return core::dimension2du(ret.getSize()); } //! Sets the maximum amount of characters which may be entered in the box. //! \param max: Maximum amount of characters. If 0, the character amount is //! infinity. void GUIEditBoxWithScrollBar::setMax(u32 max) { m_max = max; if (Text.size() > m_max && m_max != 0) Text = Text.subString(0, m_max); } //! Returns maximum amount of characters, previously set by setMax(); u32 GUIEditBoxWithScrollBar::getMax() const { return m_max; } bool GUIEditBoxWithScrollBar::processMouse(const SEvent& event) { switch (event.MouseInput.Event) { case irr::EMIE_LMOUSE_LEFT_UP: if (Environment->hasFocus(this)) { m_cursor_pos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); if (m_mouse_marking) { setTextMarkers(m_mark_begin, m_cursor_pos); } m_mouse_marking = false; calculateScrollPos(); return true; } break; case irr::EMIE_MOUSE_MOVED: { if (m_mouse_marking) { m_cursor_pos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); setTextMarkers(m_mark_begin, m_cursor_pos); calculateScrollPos(); return true; } } break; case EMIE_LMOUSE_PRESSED_DOWN: if (!Environment->hasFocus(this)) { m_blink_start_time = porting::getTimeMs(); m_mouse_marking = true; m_cursor_pos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); setTextMarkers(m_cursor_pos, m_cursor_pos); calculateScrollPos(); return true; } else { if (!AbsoluteClippingRect.isPointInside( core::position2d<s32>(event.MouseInput.X, event.MouseInput.Y))) { return false; } else { // move cursor m_cursor_pos = getCursorPos(event.MouseInput.X, event.MouseInput.Y); s32 newMarkBegin = m_mark_begin; if (!m_mouse_marking) newMarkBegin = m_cursor_pos; m_mouse_marking = true; setTextMarkers(newMarkBegin, m_cursor_pos); calculateScrollPos(); return true; } } default: break; } return false; } s32 GUIEditBoxWithScrollBar::getCursorPos(s32 x, s32 y) { IGUIFont* font = getActiveFont(); const u32 line_count = (m_word_wrap || m_multiline) ? m_broken_text.size() : 1; core::stringw *txt_line = 0; s32 start_pos = 0; x += 3; for (u32 i = 0; i < line_count; ++i) { setTextRect(i); if (i == 0 && y < m_current_text_rect.UpperLeftCorner.Y) y = m_current_text_rect.UpperLeftCorner.Y; if (i == line_count - 1 && y > m_current_text_rect.LowerRightCorner.Y) y = m_current_text_rect.LowerRightCorner.Y; // is it inside this region? if (y >= m_current_text_rect.UpperLeftCorner.Y && y <= m_current_text_rect.LowerRightCorner.Y) { // we've found the clicked line txt_line = (m_word_wrap || m_multiline) ? &m_broken_text[i] : &Text; start_pos = (m_word_wrap || m_multiline) ? m_broken_text_positions[i] : 0; break; } } if (x < m_current_text_rect.UpperLeftCorner.X) x = m_current_text_rect.UpperLeftCorner.X; if (!txt_line) return 0; s32 idx = font->getCharacterFromPos(txt_line->c_str(), x - m_current_text_rect.UpperLeftCorner.X); // click was on or left of the line if (idx != -1) return idx + start_pos; // click was off the right edge of the line, go to end. return txt_line->size() + start_pos; } //! Breaks the single text line. void GUIEditBoxWithScrollBar::breakText() { if ((!m_word_wrap && !m_multiline)) return; m_broken_text.clear(); // need to reallocate :/ m_broken_text_positions.clear(); IGUIFont* font = getActiveFont(); if (!font) return; m_last_break_font = font; core::stringw line; core::stringw word; core::stringw whitespace; s32 last_line_start = 0; s32 size = Text.size(); s32 length = 0; s32 el_width = RelativeRect.getWidth() - 6; wchar_t c; for (s32 i = 0; i < size; ++i) { c = Text[i]; bool line_break = false; if (c == L'\r') { // Mac or Windows breaks line_break = true; c = 0; if (Text[i + 1] == L'\n') { // Windows breaks // TODO: I (Michael) think that we shouldn't change the text given by the user for whatever reason. // Instead rework the cursor positioning to be able to handle this (but not in stable release // branch as users might already expect this behavior). Text.erase(i + 1); --size; if (m_cursor_pos > i) --m_cursor_pos; } } else if (c == L'\n') { // Unix breaks line_break = true; c = 0; } // don't break if we're not a multi-line edit box if (!m_multiline) line_break = false; if (c == L' ' || c == 0 || i == (size - 1)) { // here comes the next whitespace, look if // we can break the last word to the next line // We also break whitespace, otherwise cursor would vanish beside the right border. s32 whitelgth = font->getDimension(whitespace.c_str()).Width; s32 worldlgth = font->getDimension(word.c_str()).Width; if (m_word_wrap && length + worldlgth + whitelgth > el_width && line.size() > 0) { // break to next line length = worldlgth; m_broken_text.push_back(line); m_broken_text_positions.push_back(last_line_start); last_line_start = i - (s32)word.size(); line = word; } else { // add word to line line += whitespace; line += word; length += whitelgth + worldlgth; } word = L""; whitespace = L""; if (c) whitespace += c; // compute line break if (line_break) { line += whitespace; line += word; m_broken_text.push_back(line); m_broken_text_positions.push_back(last_line_start); last_line_start = i + 1; line = L""; word = L""; whitespace = L""; length = 0; } } else { // yippee this is a word.. word += c; } } line += whitespace; line += word; m_broken_text.push_back(line); m_broken_text_positions.push_back(last_line_start); } // TODO: that function does interpret VAlign according to line-index (indexed line is placed on top-center-bottom) // but HAlign according to line-width (pixels) and not by row. // Intuitively I suppose HAlign handling is better as VScrollPos should handle the line-scrolling. // But please no one change this without also rewriting (and this time fucking testing!!!) autoscrolling (I noticed this when fixing the old autoscrolling). void GUIEditBoxWithScrollBar::setTextRect(s32 line) { if (line < 0) return; IGUIFont* font = getActiveFont(); if (!font) return; core::dimension2du d; // get text dimension const u32 line_count = (m_word_wrap || m_multiline) ? m_broken_text.size() : 1; if (m_word_wrap || m_multiline) { d = font->getDimension(m_broken_text[line].c_str()); } else { d = font->getDimension(Text.c_str()); d.Height = AbsoluteRect.getHeight(); } d.Height += font->getKerningHeight(); // justification switch (m_halign) { case EGUIA_CENTER: // align to h centre m_current_text_rect.UpperLeftCorner.X = (m_frame_rect.getWidth() / 2) - (d.Width / 2); m_current_text_rect.LowerRightCorner.X = (m_frame_rect.getWidth() / 2) + (d.Width / 2); break; case EGUIA_LOWERRIGHT: // align to right edge m_current_text_rect.UpperLeftCorner.X = m_frame_rect.getWidth() - d.Width; m_current_text_rect.LowerRightCorner.X = m_frame_rect.getWidth(); break; default: // align to left edge m_current_text_rect.UpperLeftCorner.X = 0; m_current_text_rect.LowerRightCorner.X = d.Width; } switch (m_valign) { case EGUIA_CENTER: // align to v centre m_current_text_rect.UpperLeftCorner.Y = (m_frame_rect.getHeight() / 2) - (line_count*d.Height) / 2 + d.Height*line; break; case EGUIA_LOWERRIGHT: // align to bottom edge m_current_text_rect.UpperLeftCorner.Y = m_frame_rect.getHeight() - line_count*d.Height + d.Height*line; break; default: // align to top edge m_current_text_rect.UpperLeftCorner.Y = d.Height*line; break; } m_current_text_rect.UpperLeftCorner.X -= m_hscroll_pos; m_current_text_rect.LowerRightCorner.X -= m_hscroll_pos; m_current_text_rect.UpperLeftCorner.Y -= m_vscroll_pos; m_current_text_rect.LowerRightCorner.Y = m_current_text_rect.UpperLeftCorner.Y + d.Height; m_current_text_rect += m_frame_rect.UpperLeftCorner; } s32 GUIEditBoxWithScrollBar::getLineFromPos(s32 pos) { if (!m_word_wrap && !m_multiline) return 0; s32 i = 0; while (i < (s32)m_broken_text_positions.size()) { if (m_broken_text_positions[i] > pos) return i - 1; ++i; } return (s32)m_broken_text_positions.size() - 1; } void GUIEditBoxWithScrollBar::inputChar(wchar_t c) { if (!isEnabled()) return; if (c != 0) { if (Text.size() < m_max || m_max == 0) { core::stringw s; if (m_mark_begin != m_mark_end) { // replace marked text const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; s = Text.subString(0, realmbgn); s.append(c); s.append(Text.subString(realmend, Text.size() - realmend)); Text = s; m_cursor_pos = realmbgn + 1; } else { // add new character s = Text.subString(0, m_cursor_pos); s.append(c); s.append(Text.subString(m_cursor_pos, Text.size() - m_cursor_pos)); Text = s; ++m_cursor_pos; } m_blink_start_time = porting::getTimeMs(); setTextMarkers(0, 0); } } breakText(); calculateScrollPos(); sendGuiEvent(EGET_EDITBOX_CHANGED); } // calculate autoscroll void GUIEditBoxWithScrollBar::calculateScrollPos() { if (!m_autoscroll) return; IGUISkin* skin = Environment->getSkin(); if (!skin) return; IGUIFont* font = m_override_font ? m_override_font : skin->getFont(); if (!font) return; s32 curs_line = getLineFromPos(m_cursor_pos); if (curs_line < 0) return; setTextRect(curs_line); const bool has_broken_text = m_multiline || m_word_wrap; // Check horizonal scrolling // NOTE: Calculations different to vertical scrolling because setTextRect interprets VAlign relative to line but HAlign not relative to row { // get cursor position IGUIFont* font = getActiveFont(); if (!font) return; // get cursor area irr::u32 cursor_width = font->getDimension(L"_").Width; core::stringw *txt_line = has_broken_text ? &m_broken_text[curs_line] : &Text; s32 cpos = has_broken_text ? m_cursor_pos - m_broken_text_positions[curs_line] : m_cursor_pos; // column s32 cstart = font->getDimension(txt_line->subString(0, cpos).c_str()).Width; // pixels from text-start s32 cend = cstart + cursor_width; s32 txt_width = font->getDimension(txt_line->c_str()).Width; if (txt_width < m_frame_rect.getWidth()) { // TODO: Needs a clean left and right gap removal depending on HAlign, similar to vertical scrolling tests for top/bottom. // This check just fixes the case where it was most noticable (text smaller than clipping area). m_hscroll_pos = 0; setTextRect(curs_line); } if (m_current_text_rect.UpperLeftCorner.X + cstart < m_frame_rect.UpperLeftCorner.X) { // cursor to the left of the clipping area m_hscroll_pos -= m_frame_rect.UpperLeftCorner.X - (m_current_text_rect.UpperLeftCorner.X + cstart); setTextRect(curs_line); // TODO: should show more characters to the left when we're scrolling left // and the cursor reaches the border. } else if (m_current_text_rect.UpperLeftCorner.X + cend > m_frame_rect.LowerRightCorner.X) { // cursor to the right of the clipping area m_hscroll_pos += (m_current_text_rect.UpperLeftCorner.X + cend) - m_frame_rect.LowerRightCorner.X; setTextRect(curs_line); } } // calculate vertical scrolling if (has_broken_text) { irr::u32 line_height = font->getDimension(L"A").Height + font->getKerningHeight(); // only up to 1 line fits? if (line_height >= (irr::u32)m_frame_rect.getHeight()) { m_vscroll_pos = 0; setTextRect(curs_line); s32 unscrolledPos = m_current_text_rect.UpperLeftCorner.Y; s32 pivot = m_frame_rect.UpperLeftCorner.Y; switch (m_valign) { case EGUIA_CENTER: pivot += m_frame_rect.getHeight() / 2; unscrolledPos += line_height / 2; break; case EGUIA_LOWERRIGHT: pivot += m_frame_rect.getHeight(); unscrolledPos += line_height; break; default: break; } m_vscroll_pos = unscrolledPos - pivot; setTextRect(curs_line); } else { // First 2 checks are necessary when people delete lines setTextRect(0); if (m_current_text_rect.UpperLeftCorner.Y > m_frame_rect.UpperLeftCorner.Y && m_valign != EGUIA_LOWERRIGHT) { // first line is leaving a gap on top m_vscroll_pos = 0; } else if (m_valign != EGUIA_UPPERLEFT) { u32 lastLine = m_broken_text_positions.empty() ? 0 : m_broken_text_positions.size() - 1; setTextRect(lastLine); if (m_current_text_rect.LowerRightCorner.Y < m_frame_rect.LowerRightCorner.Y) { // last line is leaving a gap on bottom m_vscroll_pos -= m_frame_rect.LowerRightCorner.Y - m_current_text_rect.LowerRightCorner.Y; } } setTextRect(curs_line); if (m_current_text_rect.UpperLeftCorner.Y < m_frame_rect.UpperLeftCorner.Y) { // text above valid area m_vscroll_pos -= m_frame_rect.UpperLeftCorner.Y - m_current_text_rect.UpperLeftCorner.Y; setTextRect(curs_line); } else if (m_current_text_rect.LowerRightCorner.Y > m_frame_rect.LowerRightCorner.Y){ // text below valid area m_vscroll_pos += m_current_text_rect.LowerRightCorner.Y - m_frame_rect.LowerRightCorner.Y; setTextRect(curs_line); } } } if (m_vscrollbar) { m_vscrollbar->setPos(m_vscroll_pos); } } void GUIEditBoxWithScrollBar::calculateFrameRect() { m_frame_rect = AbsoluteRect; IGUISkin *skin = 0; if (Environment) skin = Environment->getSkin(); if (m_border && skin) { m_frame_rect.UpperLeftCorner.X += skin->getSize(EGDS_TEXT_DISTANCE_X) + 1; m_frame_rect.UpperLeftCorner.Y += skin->getSize(EGDS_TEXT_DISTANCE_Y) + 1; m_frame_rect.LowerRightCorner.X -= skin->getSize(EGDS_TEXT_DISTANCE_X) + 1; m_frame_rect.LowerRightCorner.Y -= skin->getSize(EGDS_TEXT_DISTANCE_Y) + 1; } updateVScrollBar(); } //! set text markers void GUIEditBoxWithScrollBar::setTextMarkers(s32 begin, s32 end) { if (begin != m_mark_begin || end != m_mark_end) { m_mark_begin = begin; m_mark_end = end; sendGuiEvent(EGET_EDITBOX_MARKING_CHANGED); } } //! send some gui event to parent void GUIEditBoxWithScrollBar::sendGuiEvent(EGUI_EVENT_TYPE type) { if (Parent) { SEvent e; e.EventType = EET_GUI_EVENT; e.GUIEvent.Caller = this; e.GUIEvent.Element = 0; e.GUIEvent.EventType = type; Parent->OnEvent(e); } } //! create a vertical scroll bar void GUIEditBoxWithScrollBar::createVScrollBar() { IGUISkin *skin = 0; if (Environment) skin = Environment->getSkin(); m_scrollbar_width = skin ? skin->getSize(gui::EGDS_SCROLLBAR_SIZE) : 16; RelativeRect.LowerRightCorner.X -= m_scrollbar_width + 4; irr::core::rect<s32> scrollbarrect = m_frame_rect; scrollbarrect.UpperLeftCorner.X += m_frame_rect.getWidth() - m_scrollbar_width; m_vscrollbar = Environment->addScrollBar(false, scrollbarrect, getParent(), getID()); m_vscrollbar->setVisible(false); m_vscrollbar->setSmallStep(1); m_vscrollbar->setLargeStep(1); } void GUIEditBoxWithScrollBar::updateVScrollBar() { if (!m_vscrollbar) { return; } // OnScrollBarChanged(...) if (m_vscrollbar->getPos() != m_vscroll_pos) { s32 deltaScrollY = m_vscrollbar->getPos() - m_vscroll_pos; m_current_text_rect.UpperLeftCorner.Y -= deltaScrollY; m_current_text_rect.LowerRightCorner.Y -= deltaScrollY; s32 scrollymax = getTextDimension().Height - m_frame_rect.getHeight(); if (scrollymax != m_vscrollbar->getMax()) { // manage a newline or a deleted line m_vscrollbar->setMax(scrollymax); calculateScrollPos(); } else { // manage a newline or a deleted line m_vscroll_pos = m_vscrollbar->getPos(); } } // check if a vertical scrollbar is needed ? if (getTextDimension().Height > (u32) m_frame_rect.getHeight()) { m_frame_rect.LowerRightCorner.X -= m_scrollbar_width; s32 scrollymax = getTextDimension().Height - m_frame_rect.getHeight(); if (scrollymax != m_vscrollbar->getMax()) { m_vscrollbar->setMax(scrollymax); } if (!m_vscrollbar->isVisible()) { m_vscrollbar->setVisible(true); } } else { if (m_vscrollbar->isVisible()) { m_vscrollbar->setVisible(false); m_vscroll_pos = 0; m_vscrollbar->setPos(0); m_vscrollbar->setMax(1); } } } //! set true if this editbox is writable void GUIEditBoxWithScrollBar::setWritable(bool writable) { m_writable = writable; } //! Change the background color void GUIEditBoxWithScrollBar::setBackgroundColor(const video::SColor &bg_color) { m_bg_color = bg_color; m_bg_color_used = true; } //! Writes attributes of the element. void GUIEditBoxWithScrollBar::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options = 0) const { // IGUIEditBox::serializeAttributes(out,options); out->addBool("Border", m_border); out->addBool("Background", m_background); out->addBool("OverrideColorEnabled", m_override_color_enabled); out->addColor("OverrideColor", m_override_color); // out->addFont("OverrideFont", OverrideFont); out->addInt("MaxChars", m_max); out->addBool("WordWrap", m_word_wrap); out->addBool("MultiLine", m_multiline); out->addBool("AutoScroll", m_autoscroll); out->addBool("PasswordBox", m_passwordbox); core::stringw ch = L" "; ch[0] = m_passwordchar; out->addString("PasswordChar", ch.c_str()); out->addEnum("HTextAlign", m_halign, GUIAlignmentNames); out->addEnum("VTextAlign", m_valign, GUIAlignmentNames); out->addBool("Writable", m_writable); IGUIEditBox::serializeAttributes(out, options); } //! Reads attributes of the element void GUIEditBoxWithScrollBar::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options = 0) { IGUIEditBox::deserializeAttributes(in, options); setDrawBorder(in->getAttributeAsBool("Border")); setDrawBackground(in->getAttributeAsBool("Background")); setOverrideColor(in->getAttributeAsColor("OverrideColor")); enableOverrideColor(in->getAttributeAsBool("OverrideColorEnabled")); setMax(in->getAttributeAsInt("MaxChars")); setWordWrap(in->getAttributeAsBool("WordWrap")); setMultiLine(in->getAttributeAsBool("MultiLine")); setAutoScroll(in->getAttributeAsBool("AutoScroll")); core::stringw ch = in->getAttributeAsStringW("PasswordChar"); if (!ch.size()) setPasswordBox(in->getAttributeAsBool("PasswordBox")); else setPasswordBox(in->getAttributeAsBool("PasswordBox"), ch[0]); setTextAlignment((EGUI_ALIGNMENT)in->getAttributeAsEnumeration("HTextAlign", GUIAlignmentNames), (EGUI_ALIGNMENT)in->getAttributeAsEnumeration("VTextAlign", GUIAlignmentNames)); // setOverrideFont(in->getAttributeAsFont("OverrideFont")); setWritable(in->getAttributeAsBool("Writable")); } bool GUIEditBoxWithScrollBar::isDrawBackgroundEnabled() const { return false; } bool GUIEditBoxWithScrollBar::isDrawBorderEnabled() const { return false; } void GUIEditBoxWithScrollBar::setCursorChar(const wchar_t cursorChar) { } wchar_t GUIEditBoxWithScrollBar::getCursorChar() const { return '|'; } void GUIEditBoxWithScrollBar::setCursorBlinkTime(irr::u32 timeMs) { } irr::u32 GUIEditBoxWithScrollBar::getCursorBlinkTime() const { return 500; }
pgimeno/minetest
src/gui/guiEditBoxWithScrollbar.cpp
C++
mit
40,726
// Copyright (C) 2002-2012 Nikolaus Gebhardt, Modified by Mustapha Tachouct // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef GUIEDITBOXWITHSCROLLBAR_HEADER #define GUIEDITBOXWITHSCROLLBAR_HEADER #include "IGUIEditBox.h" #include "IOSOperator.h" #include "IGUIScrollBar.h" #include <vector> using namespace irr; using namespace irr::gui; class GUIEditBoxWithScrollBar : public IGUIEditBox { public: //! constructor GUIEditBoxWithScrollBar(const wchar_t* text, bool border, IGUIEnvironment* environment, IGUIElement* parent, s32 id, const core::rect<s32>& rectangle, bool writable = true, bool has_vscrollbar = true); //! destructor virtual ~GUIEditBoxWithScrollBar(); //! Sets another skin independent font. virtual void setOverrideFont(IGUIFont* font = 0); //! Gets the override font (if any) /** \return The override font (may be 0) */ virtual IGUIFont* getOverrideFont() const; //! Get the font which is used right now for drawing /** Currently this is the override font when one is set and the font of the active skin otherwise */ virtual IGUIFont* getActiveFont() const; //! Sets another color for the text. virtual void setOverrideColor(video::SColor color); //! Gets the override color virtual video::SColor getOverrideColor() const; //! Sets if the text should use the overide color or the //! color in the gui skin. virtual void enableOverrideColor(bool enable); //! Checks if an override color is enabled /** \return true if the override color is enabled, false otherwise */ virtual bool isOverrideColorEnabled(void) const; //! Sets whether to draw the background virtual void setDrawBackground(bool draw); //! Turns the border on or off virtual void setDrawBorder(bool border); //! Enables or disables word wrap for using the edit box as multiline text editor. virtual void setWordWrap(bool enable); //! Checks if word wrap is enabled //! \return true if word wrap is enabled, false otherwise virtual bool isWordWrapEnabled() const; //! Enables or disables newlines. /** \param enable: If set to true, the EGET_EDITBOX_ENTER event will not be fired, instead a newline character will be inserted. */ virtual void setMultiLine(bool enable); //! Checks if multi line editing is enabled //! \return true if mult-line is enabled, false otherwise virtual bool isMultiLineEnabled() const; //! Enables or disables automatic scrolling with cursor position //! \param enable: If set to true, the text will move around with the cursor position virtual void setAutoScroll(bool enable); //! Checks to see if automatic scrolling is enabled //! \return true if automatic scrolling is enabled, false if not virtual bool isAutoScrollEnabled() const; //! Gets the size area of the text in the edit box //! \return Returns the size in pixels of the text virtual core::dimension2du getTextDimension(); //! Sets text justification virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical); //! called if an event happened. virtual bool OnEvent(const SEvent& event); //! draws the element and its children virtual void draw(); //! Sets the new caption of this element. virtual void setText(const wchar_t* text); //! Sets the maximum amount of characters which may be entered in the box. //! \param max: Maximum amount of characters. If 0, the character amount is //! infinity. virtual void setMax(u32 max); //! Returns maximum amount of characters, previously set by setMax(); virtual u32 getMax() const; //! Sets whether the edit box is a password box. Setting this to true will /** disable MultiLine, WordWrap and the ability to copy with ctrl+c or ctrl+x \param passwordBox: true to enable password, false to disable \param passwordChar: the character that is displayed instead of letters */ virtual void setPasswordBox(bool passwordBox, wchar_t passwordChar = L'*'); //! Returns true if the edit box is currently a password box. virtual bool isPasswordBox() const; //! Updates the absolute position, splits text if required virtual void updateAbsolutePosition(); virtual void setWritable(bool writable); //! Change the background color virtual void setBackgroundColor(const video::SColor &bg_color); //! Writes attributes of the element. virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const; //! Reads attributes of the element virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options); virtual bool isDrawBackgroundEnabled() const; virtual bool isDrawBorderEnabled() const; virtual void setCursorChar(const wchar_t cursorChar); virtual wchar_t getCursorChar() const; virtual void setCursorBlinkTime(irr::u32 timeMs); virtual irr::u32 getCursorBlinkTime() const; protected: //! Breaks the single text line. void breakText(); //! sets the area of the given line void setTextRect(s32 line); //! returns the line number that the cursor is on s32 getLineFromPos(s32 pos); //! adds a letter to the edit box void inputChar(wchar_t c); //! calculates the current scroll position void calculateScrollPos(); //! calculated the FrameRect void calculateFrameRect(); //! send some gui event to parent void sendGuiEvent(EGUI_EVENT_TYPE type); //! set text markers void setTextMarkers(s32 begin, s32 end); //! create a Vertical ScrollBar void createVScrollBar(); //! update the vertical scrollBar (visibilty & position) void updateVScrollBar(); bool processKey(const SEvent& event); bool processMouse(const SEvent& event); s32 getCursorPos(s32 x, s32 y); bool m_mouse_marking; bool m_border; bool m_background; bool m_override_color_enabled; s32 m_mark_begin; s32 m_mark_end; video::SColor m_override_color; gui::IGUIFont *m_override_font, *m_last_break_font; IOSOperator* m_operator; u32 m_blink_start_time; s32 m_cursor_pos; s32 m_hscroll_pos, m_vscroll_pos; // scroll position in characters u32 m_max; bool m_word_wrap, m_multiline, m_autoscroll, m_passwordbox; wchar_t m_passwordchar; EGUI_ALIGNMENT m_halign, m_valign; std::vector<core::stringw> m_broken_text; std::vector<s32> m_broken_text_positions; core::rect<s32> m_current_text_rect, m_frame_rect; // temporary values u32 m_scrollbar_width; IGUIScrollBar *m_vscrollbar; bool m_writable; bool m_bg_color_used; video::SColor m_bg_color; }; #endif // GUIEDITBOXWITHSCROLLBAR_HEADER
pgimeno/minetest
src/gui/guiEditBoxWithScrollbar.h
C++
mit
6,499
/* Minetest Copyright (C) 2013 sapier This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "guiEngine.h" #include <IGUIStaticText.h> #include <ICameraSceneNode.h> #include "client/renderingengine.h" #include "scripting_mainmenu.h" #include "util/numeric.h" #include "config.h" #include "version.h" #include "porting.h" #include "filesys.h" #include "settings.h" #include "guiMainMenu.h" #include "sound.h" #include "client/sound_openal.h" #include "client/clouds.h" #include "httpfetch.h" #include "log.h" #include "client/fontengine.h" #include "client/guiscalingfilter.h" #include "irrlicht_changes/static_text.h" #ifdef __ANDROID__ #include "client/tile.h" #include <GLES/gl.h> #endif /******************************************************************************/ void TextDestGuiEngine::gotText(const StringMap &fields) { m_engine->getScriptIface()->handleMainMenuButtons(fields); } /******************************************************************************/ void TextDestGuiEngine::gotText(const std::wstring &text) { m_engine->getScriptIface()->handleMainMenuEvent(wide_to_utf8(text)); } /******************************************************************************/ MenuTextureSource::~MenuTextureSource() { for (const std::string &texture_to_delete : m_to_delete) { const char *tname = texture_to_delete.c_str(); video::ITexture *texture = m_driver->getTexture(tname); m_driver->removeTexture(texture); } } /******************************************************************************/ video::ITexture *MenuTextureSource::getTexture(const std::string &name, u32 *id) { if (id) *id = 0; if (name.empty()) return NULL; m_to_delete.insert(name); #ifdef __ANDROID__ video::ITexture *retval = m_driver->findTexture(name.c_str()); if (retval) return retval; video::IImage *image = m_driver->createImageFromFile(name.c_str()); if (!image) return NULL; image = Align2Npot2(image, m_driver); retval = m_driver->addTexture(name.c_str(), image); image->drop(); return retval; #else return m_driver->getTexture(name.c_str()); #endif } /******************************************************************************/ /** MenuMusicFetcher */ /******************************************************************************/ void MenuMusicFetcher::fetchSounds(const std::string &name, std::set<std::string> &dst_paths, std::set<std::string> &dst_datas) { if(m_fetched.count(name)) return; m_fetched.insert(name); std::string base; base = porting::path_share + DIR_DELIM + "sounds"; dst_paths.insert(base + DIR_DELIM + name + ".ogg"); int i; for(i=0; i<10; i++) dst_paths.insert(base + DIR_DELIM + name + "."+itos(i)+".ogg"); base = porting::path_user + DIR_DELIM + "sounds"; dst_paths.insert(base + DIR_DELIM + name + ".ogg"); for(i=0; i<10; i++) dst_paths.insert(base + DIR_DELIM + name + "."+itos(i)+".ogg"); } /******************************************************************************/ /** GUIEngine */ /******************************************************************************/ GUIEngine::GUIEngine(JoystickController *joystick, gui::IGUIElement *parent, IMenuManager *menumgr, MainMenuData *data, bool &kill) : m_parent(parent), m_menumanager(menumgr), m_smgr(RenderingEngine::get_scene_manager()), m_data(data), m_kill(kill) { //initialize texture pointers for (image_definition &texture : m_textures) { texture.texture = NULL; } // is deleted by guiformspec! m_buttonhandler = new TextDestGuiEngine(this); //create texture source m_texture_source = new MenuTextureSource(RenderingEngine::get_video_driver()); //create soundmanager MenuMusicFetcher soundfetcher; #if USE_SOUND if (g_settings->getBool("enable_sound")) m_sound_manager = createOpenALSoundManager(g_sound_manager_singleton.get(), &soundfetcher); #endif if(!m_sound_manager) m_sound_manager = &dummySoundManager; //create topleft header m_toplefttext = L""; core::rect<s32> rect(0, 0, g_fontengine->getTextWidth(m_toplefttext.c_str()), g_fontengine->getTextHeight()); rect += v2s32(4, 0); m_irr_toplefttext = gui::StaticText::add(RenderingEngine::get_gui_env(), m_toplefttext, rect, false, true, 0, -1); //create formspecsource m_formspecgui = new FormspecFormSource(""); /* Create menu */ m_menu = new GUIFormSpecMenu(joystick, m_parent, -1, m_menumanager, NULL /* &client */, m_texture_source, m_formspecgui, m_buttonhandler, "", false); m_menu->allowClose(false); m_menu->lockSize(true,v2u32(800,600)); // Initialize scripting infostream << "GUIEngine: Initializing Lua" << std::endl; m_script = new MainMenuScripting(this); try { m_script->setMainMenuData(&m_data->script_data); m_data->script_data.errormessage = ""; if (!loadMainMenuScript()) { errorstream << "No future without main menu!" << std::endl; abort(); } run(); } catch (LuaError &e) { errorstream << "Main menu error: " << e.what() << std::endl; m_data->script_data.errormessage = e.what(); } m_menu->quitMenu(); m_menu->drop(); m_menu = NULL; } /******************************************************************************/ bool GUIEngine::loadMainMenuScript() { // Set main menu path (for core.get_mainmenu_path()) m_scriptdir = g_settings->get("main_menu_path"); if (m_scriptdir.empty()) { m_scriptdir = porting::path_share + DIR_DELIM + "builtin" + DIR_DELIM + "mainmenu"; } // Load builtin (which will load the main menu script) std::string script = porting::path_share + DIR_DELIM "builtin" + DIR_DELIM "init.lua"; try { m_script->loadScript(script); // Menu script loaded return true; } catch (const ModError &e) { errorstream << "GUIEngine: execution of menu script failed: " << e.what() << std::endl; } return false; } /******************************************************************************/ void GUIEngine::run() { // Always create clouds because they may or may not be // needed based on the game selected video::IVideoDriver *driver = RenderingEngine::get_video_driver(); cloudInit(); unsigned int text_height = g_fontengine->getTextHeight(); irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"), g_settings->getU16("screen_h")); static const video::SColor sky_color(255, 140, 186, 250); // Reset fog color { video::SColor fog_color; video::E_FOG_TYPE fog_type = video::EFT_FOG_LINEAR; f32 fog_start = 0; f32 fog_end = 0; f32 fog_density = 0; bool fog_pixelfog = false; bool fog_rangefog = false; driver->getFog(fog_color, fog_type, fog_start, fog_end, fog_density, fog_pixelfog, fog_rangefog); driver->setFog(sky_color, fog_type, fog_start, fog_end, fog_density, fog_pixelfog, fog_rangefog); } while (RenderingEngine::run() && (!m_startgame) && (!m_kill)) { const irr::core::dimension2d<u32> &current_screen_size = RenderingEngine::get_video_driver()->getScreenSize(); // Verify if window size has changed and save it if it's the case // Ensure evaluating settings->getBool after verifying screensize // First condition is cheaper if (previous_screen_size != current_screen_size && current_screen_size != irr::core::dimension2d<u32>(0,0) && g_settings->getBool("autosave_screensize")) { g_settings->setU16("screen_w", current_screen_size.Width); g_settings->setU16("screen_h", current_screen_size.Height); previous_screen_size = current_screen_size; } //check if we need to update the "upper left corner"-text if (text_height != g_fontengine->getTextHeight()) { updateTopLeftTextSize(); text_height = g_fontengine->getTextHeight(); } driver->beginScene(true, true, sky_color); if (m_clouds_enabled) { cloudPreProcess(); drawOverlay(driver); } else drawBackground(driver); drawHeader(driver); drawFooter(driver); RenderingEngine::get_gui_env()->drawAll(); driver->endScene(); if (m_clouds_enabled) cloudPostProcess(); else sleep_ms(25); m_script->step(); #ifdef __ANDROID__ m_menu->getAndroidUIInput(); #endif } } /******************************************************************************/ GUIEngine::~GUIEngine() { if (m_sound_manager != &dummySoundManager){ delete m_sound_manager; m_sound_manager = NULL; } infostream<<"GUIEngine: Deinitializing scripting"<<std::endl; delete m_script; m_irr_toplefttext->setText(L""); //clean up texture pointers for (image_definition &texture : m_textures) { if (texture.texture) RenderingEngine::get_video_driver()->removeTexture(texture.texture); } delete m_texture_source; if (m_cloud.clouds) m_cloud.clouds->drop(); } /******************************************************************************/ void GUIEngine::cloudInit() { m_cloud.clouds = new Clouds(m_smgr, -1, rand()); m_cloud.clouds->setHeight(100.0f); m_cloud.clouds->update(v3f(0, 0, 0), video::SColor(255,240,240,255)); m_cloud.camera = m_smgr->addCameraSceneNode(0, v3f(0,0,0), v3f(0, 60, 100)); m_cloud.camera->setFarValue(10000); m_cloud.lasttime = RenderingEngine::get_timer_time(); } /******************************************************************************/ void GUIEngine::cloudPreProcess() { u32 time = RenderingEngine::get_timer_time(); if(time > m_cloud.lasttime) m_cloud.dtime = (time - m_cloud.lasttime) / 1000.0; else m_cloud.dtime = 0; m_cloud.lasttime = time; m_cloud.clouds->step(m_cloud.dtime*3); m_cloud.clouds->render(); m_smgr->drawAll(); } /******************************************************************************/ void GUIEngine::cloudPostProcess() { float fps_max = g_settings->getFloat("pause_fps_max"); // Time of frame without fps limit u32 busytime_u32; // not using getRealTime is necessary for wine u32 time = RenderingEngine::get_timer_time(); if(time > m_cloud.lasttime) busytime_u32 = time - m_cloud.lasttime; else busytime_u32 = 0; // FPS limiter u32 frametime_min = 1000./fps_max; if (busytime_u32 < frametime_min) { u32 sleeptime = frametime_min - busytime_u32; RenderingEngine::get_raw_device()->sleep(sleeptime); } } /******************************************************************************/ void GUIEngine::drawBackground(video::IVideoDriver *driver) { v2u32 screensize = driver->getScreenSize(); video::ITexture* texture = m_textures[TEX_LAYER_BACKGROUND].texture; /* If no texture, draw background of solid color */ if(!texture){ video::SColor color(255,80,58,37); core::rect<s32> rect(0, 0, screensize.X, screensize.Y); driver->draw2DRectangle(color, rect, NULL); return; } v2u32 sourcesize = texture->getOriginalSize(); if (m_textures[TEX_LAYER_BACKGROUND].tile) { v2u32 tilesize( MYMAX(sourcesize.X,m_textures[TEX_LAYER_BACKGROUND].minsize), MYMAX(sourcesize.Y,m_textures[TEX_LAYER_BACKGROUND].minsize)); for (unsigned int x = 0; x < screensize.X; x += tilesize.X ) { for (unsigned int y = 0; y < screensize.Y; y += tilesize.Y ) { draw2DImageFilterScaled(driver, texture, core::rect<s32>(x, y, x+tilesize.X, y+tilesize.Y), core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y), NULL, NULL, true); } } return; } /* Draw background texture */ draw2DImageFilterScaled(driver, texture, core::rect<s32>(0, 0, screensize.X, screensize.Y), core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y), NULL, NULL, true); } /******************************************************************************/ void GUIEngine::drawOverlay(video::IVideoDriver *driver) { v2u32 screensize = driver->getScreenSize(); video::ITexture* texture = m_textures[TEX_LAYER_OVERLAY].texture; /* If no texture, draw nothing */ if(!texture) return; /* Draw background texture */ v2u32 sourcesize = texture->getOriginalSize(); draw2DImageFilterScaled(driver, texture, core::rect<s32>(0, 0, screensize.X, screensize.Y), core::rect<s32>(0, 0, sourcesize.X, sourcesize.Y), NULL, NULL, true); } /******************************************************************************/ void GUIEngine::drawHeader(video::IVideoDriver *driver) { core::dimension2d<u32> screensize = driver->getScreenSize(); video::ITexture* texture = m_textures[TEX_LAYER_HEADER].texture; /* If no texture, draw nothing */ if(!texture) return; f32 mult = (((f32)screensize.Width / 2.0)) / ((f32)texture->getOriginalSize().Width); v2s32 splashsize(((f32)texture->getOriginalSize().Width) * mult, ((f32)texture->getOriginalSize().Height) * mult); // Don't draw the header if there isn't enough room s32 free_space = (((s32)screensize.Height)-320)/2; if (free_space > splashsize.Y) { core::rect<s32> splashrect(0, 0, splashsize.X, splashsize.Y); splashrect += v2s32((screensize.Width/2)-(splashsize.X/2), ((free_space/2)-splashsize.Y/2)+10); video::SColor bgcolor(255,50,50,50); draw2DImageFilterScaled(driver, texture, splashrect, core::rect<s32>(core::position2d<s32>(0,0), core::dimension2di(texture->getOriginalSize())), NULL, NULL, true); } } /******************************************************************************/ void GUIEngine::drawFooter(video::IVideoDriver *driver) { core::dimension2d<u32> screensize = driver->getScreenSize(); video::ITexture* texture = m_textures[TEX_LAYER_FOOTER].texture; /* If no texture, draw nothing */ if(!texture) return; f32 mult = (((f32)screensize.Width)) / ((f32)texture->getOriginalSize().Width); v2s32 footersize(((f32)texture->getOriginalSize().Width) * mult, ((f32)texture->getOriginalSize().Height) * mult); // Don't draw the footer if there isn't enough room s32 free_space = (((s32)screensize.Height)-320)/2; if (free_space > footersize.Y) { core::rect<s32> rect(0,0,footersize.X,footersize.Y); rect += v2s32(screensize.Width/2,screensize.Height-footersize.Y); rect -= v2s32(footersize.X/2, 0); draw2DImageFilterScaled(driver, texture, rect, core::rect<s32>(core::position2d<s32>(0,0), core::dimension2di(texture->getOriginalSize())), NULL, NULL, true); } } /******************************************************************************/ bool GUIEngine::setTexture(texture_layer layer, std::string texturepath, bool tile_image, unsigned int minsize) { video::IVideoDriver *driver = RenderingEngine::get_video_driver(); if (m_textures[layer].texture) { driver->removeTexture(m_textures[layer].texture); m_textures[layer].texture = NULL; } if (texturepath.empty() || !fs::PathExists(texturepath)) { return false; } m_textures[layer].texture = driver->getTexture(texturepath.c_str()); m_textures[layer].tile = tile_image; m_textures[layer].minsize = minsize; if (!m_textures[layer].texture) { return false; } return true; } /******************************************************************************/ bool GUIEngine::downloadFile(const std::string &url, const std::string &target) { #if USE_CURL std::ofstream target_file(target.c_str(), std::ios::out | std::ios::binary); if (!target_file.good()) { return false; } HTTPFetchRequest fetch_request; HTTPFetchResult fetch_result; fetch_request.url = url; fetch_request.caller = HTTPFETCH_SYNC; fetch_request.timeout = g_settings->getS32("curl_file_download_timeout"); httpfetch_sync(fetch_request, fetch_result); if (!fetch_result.succeeded) { target_file.close(); fs::DeleteSingleFileOrEmptyDirectory(target); return false; } target_file << fetch_result.data; return true; #else return false; #endif } /******************************************************************************/ void GUIEngine::setTopleftText(const std::string &text) { m_toplefttext = translate_string(utf8_to_wide(text)); updateTopLeftTextSize(); } /******************************************************************************/ void GUIEngine::updateTopLeftTextSize() { core::rect<s32> rect(0, 0, g_fontengine->getTextWidth(m_toplefttext.c_str()), g_fontengine->getTextHeight()); rect += v2s32(4, 0); m_irr_toplefttext->remove(); m_irr_toplefttext = gui::StaticText::add(RenderingEngine::get_gui_env(), m_toplefttext, rect, false, true, 0, -1); } /******************************************************************************/ s32 GUIEngine::playSound(SimpleSoundSpec spec, bool looped) { s32 handle = m_sound_manager->playSound(spec, looped); return handle; } /******************************************************************************/ void GUIEngine::stopSound(s32 handle) { m_sound_manager->stopSound(handle); } /******************************************************************************/ unsigned int GUIEngine::queueAsync(const std::string &serialized_func, const std::string &serialized_params) { return m_script->queueAsync(serialized_func, serialized_params); }
pgimeno/minetest
src/gui/guiEngine.cpp
C++
mit
17,531