diff options
Diffstat (limited to 'src')
228 files changed, 4534 insertions, 8756 deletions
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index b6bba6e8d..9526e88f9 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -55,7 +55,7 @@ if(NOT USE_CURL) endif() -option(ENABLE_GETTEXT "Use GetText for internationalization" TRUE) +option(ENABLE_GETTEXT "Use GetText for internationalization" ${BUILD_CLIENT}) set(USE_GETTEXT FALSE) if(ENABLE_GETTEXT) @@ -63,14 +63,13 @@ if(ENABLE_GETTEXT) if(GETTEXTLIB_FOUND) if(WIN32) message(STATUS "GetText library: ${GETTEXT_LIBRARY}") - message(STATUS "GetText DLL: ${GETTEXT_DLL}") - message(STATUS "GetText iconv DLL: ${GETTEXT_ICONV_DLL}") + message(STATUS "GetText DLL(s): ${GETTEXT_DLL}") endif() set(USE_GETTEXT TRUE) message(STATUS "GetText enabled; locales found: ${GETTEXT_AVAILABLE_LOCALES}") endif(GETTEXTLIB_FOUND) else() - mark_as_advanced(GETTEXT_ICONV_DLL GETTEXT_INCLUDE_DIR GETTEXT_LIBRARY GETTEXT_MSGFMT) + mark_as_advanced(GETTEXT_INCLUDE_DIR GETTEXT_LIBRARY GETTEXT_MSGFMT) message(STATUS "GetText disabled.") endif() @@ -103,11 +102,11 @@ endif() option(ENABLE_GLES "Use OpenGL ES instead of OpenGL" FALSE) mark_as_advanced(ENABLE_GLES) if(BUILD_CLIENT) - if(ENABLE_GLES) - find_package(OpenGLES2 REQUIRED) - else() - # transitive dependency from Irrlicht (see longer explanation below) - if(NOT WIN32) + # transitive dependency from Irrlicht (see longer explanation below) + if(NOT WIN32) + if(ENABLE_GLES) + find_package(OpenGLES2 REQUIRED) + else() set(OPENGL_GL_PREFERENCE "LEGACY" CACHE STRING "See CMake Policy CMP0072 for reference. GLVND is broken on some nvidia setups") set(OpenGL_GL_PREFERENCE ${OPENGL_GL_PREFERENCE}) @@ -121,13 +120,13 @@ endif() option(ENABLE_FREETYPE "Enable FreeType2 (TrueType fonts and basic unicode support)" TRUE) set(USE_FREETYPE FALSE) -if(ENABLE_FREETYPE) +if(BUILD_CLIENT AND ENABLE_FREETYPE) find_package(Freetype) if(FREETYPE_FOUND) message(STATUS "Freetype enabled.") set(USE_FREETYPE TRUE) endif() -endif(ENABLE_FREETYPE) +endif() option(ENABLE_CURSES "Enable ncurses console" TRUE) set(USE_CURSES FALSE) @@ -147,7 +146,17 @@ option(ENABLE_POSTGRESQL "Enable PostgreSQL backend" TRUE) set(USE_POSTGRESQL FALSE) if(ENABLE_POSTGRESQL) - find_package("PostgreSQL") + if(CMAKE_VERSION VERSION_LESS "3.20") + find_package(PostgreSQL QUIET) + # Before CMake 3.20 FindPostgreSQL.cmake always looked for server includes + # but we don't need them, so continue anyway if only those are missing. + if(PostgreSQL_INCLUDE_DIR AND PostgreSQL_LIBRARY) + set(PostgreSQL_FOUND TRUE) + set(PostgreSQL_INCLUDE_DIRS ${PostgreSQL_INCLUDE_DIR}) + endif() + else() + find_package(PostgreSQL) + endif() if(PostgreSQL_FOUND) set(USE_POSTGRESQL TRUE) @@ -268,8 +277,10 @@ if(WIN32) if(ENABLE_SOUND) set(OPENAL_DLL "" CACHE FILEPATH "Path to OpenAL32.dll for installation (optional)") set(OGG_DLL "" CACHE FILEPATH "Path to libogg.dll for installation (optional)") - set(VORBIS_DLL "" CACHE FILEPATH "Path to libvorbis.dll for installation (optional)") - set(VORBISFILE_DLL "" CACHE FILEPATH "Path to libvorbisfile.dll for installation (optional)") + set(VORBIS_DLL "" CACHE FILEPATH "Path to Vorbis DLLs for installation (optional)") + endif() + if(USE_GETTEXT) + set(GETTEXT_DLL "" CACHE FILEPATH "Path to Intl/Iconv DLLs for installation (optional)") endif() if(USE_LUAJIT) set(LUA_DLL "" CACHE FILEPATH "Path to luajit-5.1.dll for installation (optional)") @@ -295,7 +306,6 @@ else() endif(NOT HAIKU AND NOT APPLE) find_package(JPEG REQUIRED) - find_package(BZip2 REQUIRED) find_package(PNG REQUIRED) if(APPLE) find_library(CARBON_LIB Carbon REQUIRED) @@ -526,13 +536,16 @@ if(USE_CURL) endif() -set(EXECUTABLE_OUTPUT_PATH "${CMAKE_SOURCE_DIR}/bin") - +# When cross-compiling assume the user doesn't want to run the executable anyway, +# otherwise place it in <source dir>/bin/ since Minetest can only run from there. +if(NOT CMAKE_CROSSCOMPILING) + set(EXECUTABLE_OUTPUT_PATH "${CMAKE_SOURCE_DIR}/bin") +endif() if(BUILD_CLIENT) add_executable(${PROJECT_NAME} ${client_SRCS} ${extra_windows_SRCS}) add_dependencies(${PROJECT_NAME} GenerateVersion) - set(client_LIBS + target_link_libraries( ${PROJECT_NAME} ${ZLIB_LIBRARIES} ${IRRLICHT_LIBRARY} @@ -548,9 +561,14 @@ if(BUILD_CLIENT) ${PLATFORM_LIBS} ${CLIENT_PLATFORM_LIBS} ) - target_link_libraries( - ${client_LIBS} - ) + if(NOT USE_LUAJIT) + set_target_properties(${PROJECT_NAME} PROPERTIES + # This is necessary for dynamic Lua modules + # to work when Lua is statically linked (issue #10806) + ENABLE_EXPORTS 1 + ) + endif() + if(ENABLE_GLES) target_link_libraries( ${PROJECT_NAME} @@ -621,7 +639,15 @@ if(BUILD_SERVER) ${PLATFORM_LIBS} ) set_target_properties(${PROJECT_NAME}server PROPERTIES - COMPILE_DEFINITIONS "SERVER") + COMPILE_DEFINITIONS "SERVER") + if(NOT USE_LUAJIT) + set_target_properties(${PROJECT_NAME}server PROPERTIES + # This is necessary for dynamic Lua modules + # to work when Lua is statically linked (issue #10806) + ENABLE_EXPORTS 1 + ) + endif() + if (USE_GETTEXT) target_link_libraries(${PROJECT_NAME}server ${GETTEXT_LIBRARY}) endif() @@ -655,7 +681,10 @@ endif(BUILD_SERVER) # see issue #4638 set(GETTEXT_BLACKLISTED_LOCALES ar + dv he + hi + kn ky ms_Arab th @@ -666,7 +695,7 @@ option(APPLY_LOCALE_BLACKLIST "Use a blacklist to avoid broken locales" TRUE) if (GETTEXTLIB_FOUND AND APPLY_LOCALE_BLACKLIST) set(GETTEXT_USED_LOCALES "") foreach(LOCALE ${GETTEXT_AVAILABLE_LOCALES}) - if (NOT ";${GETTEXT_BLACKLISTED_LOCALES};" MATCHES ";${LOCALE};") + if (NOT "${LOCALE}" IN_LIST GETTEXT_BLACKLISTED_LOCALES) list(APPEND GETTEXT_USED_LOCALES ${LOCALE}) endif() endforeach() @@ -700,7 +729,7 @@ if(MSVC) # Flags that cannot be shared between cl and clang-cl # https://clang.llvm.org/docs/UsersManual.html#clang-cl - if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") + if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fuse-ld=lld") # Disable pragma-pack warning @@ -718,7 +747,7 @@ else() else() set(RELEASE_WARNING_FLAGS "") endif() - if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang") + if(CMAKE_CXX_COMPILER_ID MATCHES "(Apple)?Clang") set(WARNING_FLAGS "${WARNING_FLAGS} -Wsign-compare") endif() @@ -755,7 +784,7 @@ else() else() set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${MATH_FLAGS}") endif() - endif(CMAKE_SYSTEM_NAME MATCHES "(Darwin|BSD|DragonFly)") + endif() set(CMAKE_CXX_FLAGS_SEMIDEBUG "-g -O1 -Wall ${WARNING_FLAGS} ${OTHER_FLAGS}") set(CMAKE_CXX_FLAGS_DEBUG "-g -O0 -Wall ${WARNING_FLAGS} ${OTHER_FLAGS}") @@ -792,7 +821,7 @@ if(WIN32) FILES_MATCHING PATTERN "*.dll") else() # Use the old-style way to install dll's - if(USE_SOUND) + if(BUILD_CLIENT AND USE_SOUND) if(OPENAL_DLL) install(FILES ${OPENAL_DLL} DESTINATION ${BINDIR}) endif() @@ -802,9 +831,6 @@ if(WIN32) if(VORBIS_DLL) install(FILES ${VORBIS_DLL} DESTINATION ${BINDIR}) endif() - if(VORBISFILE_DLL) - install(FILES ${VORBISFILE_DLL} DESTINATION ${BINDIR}) - endif() endif() if(CURL_DLL) install(FILES ${CURL_DLL} DESTINATION ${BINDIR}) @@ -812,7 +838,7 @@ if(WIN32) if(ZLIB_DLL) install(FILES ${ZLIB_DLL} DESTINATION ${BINDIR}) endif() - if(FREETYPE_DLL) + if(BUILD_CLIENT AND FREETYPE_DLL) install(FILES ${FREETYPE_DLL} DESTINATION ${BINDIR}) endif() if(SQLITE3_DLL) @@ -824,6 +850,12 @@ if(WIN32) if(LUA_DLL) install(FILES ${LUA_DLL} DESTINATION ${BINDIR}) endif() + if(BUILD_CLIENT AND IRRLICHT_DLL) + install(FILES ${IRRLICHT_DLL} DESTINATION ${BINDIR}) + endif() + if(BUILD_CLIENT AND USE_GETTEXT AND GETTEXT_DLL) + install(FILES ${GETTEXT_DLL} DESTINATION ${BINDIR}) + endif() endif() endif() @@ -851,6 +883,7 @@ if(BUILD_CLIENT) endforeach() endif() + # Install necessary fonts depending on configuration if(USE_FREETYPE) install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/../fonts" DESTINATION "${SHAREDIR}" FILES_MATCHING PATTERN "*.ttf" PATTERN "*.txt") @@ -858,22 +891,6 @@ if(BUILD_CLIENT) install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/../fonts" DESTINATION "${SHAREDIR}" FILES_MATCHING PATTERN "*.png" PATTERN "*.xml") endif() - - if(WIN32) - if(NOT VCPKG_APPLOCAL_DEPS) - if(DEFINED IRRLICHT_DLL) - install(FILES ${IRRLICHT_DLL} DESTINATION ${BINDIR}) - endif() - if(USE_GETTEXT) - if(DEFINED GETTEXT_DLL) - install(FILES ${GETTEXT_DLL} DESTINATION ${BINDIR}) - endif() - if(DEFINED GETTEXT_ICONV_DLL) - install(FILES ${GETTEXT_ICONV_DLL} DESTINATION ${BINDIR}) - endif() - endif() - endif() - endif() endif(BUILD_CLIENT) if(BUILD_SERVER) diff --git a/src/activeobject.h b/src/activeobject.h index 0829858ad..1d8a3712b 100644 --- a/src/activeobject.h +++ b/src/activeobject.h @@ -28,11 +28,11 @@ enum ActiveObjectType { ACTIVEOBJECT_TYPE_INVALID = 0, ACTIVEOBJECT_TYPE_TEST = 1, // Obsolete stuff - ACTIVEOBJECT_TYPE_ITEM = 2, -// ACTIVEOBJECT_TYPE_RAT = 3, -// ACTIVEOBJECT_TYPE_OERKKI1 = 4, -// ACTIVEOBJECT_TYPE_FIREFLY = 5, - ACTIVEOBJECT_TYPE_MOBV2 = 6, +// ACTIVEOBJECT_TYPE_ITEM = 2, +// ACTIVEOBJECT_TYPE_RAT = 3, +// ACTIVEOBJECT_TYPE_OERKKI1 = 4, +// ACTIVEOBJECT_TYPE_FIREFLY = 5, +// ACTIVEOBJECT_TYPE_MOBV2 = 6, // End obsolete stuff ACTIVEOBJECT_TYPE_LUAENTITY = 7, // Special type, not stored as a static object diff --git a/src/activeobjectmgr.h b/src/activeobjectmgr.h index 5139d61dd..835f19dc2 100644 --- a/src/activeobjectmgr.h +++ b/src/activeobjectmgr.h @@ -25,7 +25,8 @@ with this program; if not, write to the Free Software Foundation, Inc., class TestClientActiveObjectMgr; class TestServerActiveObjectMgr; -template <typename T> class ActiveObjectMgr +template <typename T> +class ActiveObjectMgr { friend class ::TestClientActiveObjectMgr; friend class ::TestServerActiveObjectMgr; diff --git a/src/chat.cpp b/src/chat.cpp index 2f65e68b3..c9317a079 100644 --- a/src/chat.cpp +++ b/src/chat.cpp @@ -485,8 +485,8 @@ void ChatPrompt::nickCompletion(const std::list<std::string>& names, bool backwa // find all names that start with the selected prefix std::vector<std::wstring> completions; for (const std::string &name : names) { - if (str_starts_with(narrow_to_wide(name), prefix, true)) { - std::wstring completion = narrow_to_wide(name); + std::wstring completion = utf8_to_wide(name); + if (str_starts_with(completion, prefix, true)) { if (prefix_start == 0) completion += L": "; completions.push_back(completion); diff --git a/src/client/camera.cpp b/src/client/camera.cpp index 91d319c90..52bedcba9 100644 --- a/src/client/camera.cpp +++ b/src/client/camera.cpp @@ -35,6 +35,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/numeric.h" #include "constants.h" #include "fontengine.h" +#include "guiscalingfilter.h" #include "script/scripting_client.h" #define CAMERA_OFFSET_STEP 200 @@ -43,11 +44,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #define WIELDMESH_AMPLITUDE_X 7.0f #define WIELDMESH_AMPLITUDE_Y 10.0f -Camera::Camera(MapDrawControl &draw_control, Client *client): +Camera::Camera(MapDrawControl &draw_control, Client *client, RenderingEngine *rendering_engine): m_draw_control(draw_control), m_client(client) { - scene::ISceneManager *smgr = RenderingEngine::get_scene_manager(); + auto smgr = rendering_engine->get_scene_manager(); // note: making the camera node a child of the player node // would lead to unexpected behaviour, so we don't do that. m_playernode = smgr->addEmptySceneNode(smgr->getRootSceneNode()); @@ -79,6 +80,7 @@ Camera::Camera(MapDrawControl &draw_control, Client *client): m_cache_fov = std::fmax(g_settings->getFloat("fov"), 45.0f); m_arm_inertia = g_settings->getBool("arm_inertia"); m_nametags.clear(); + m_show_nametag_backgrounds = g_settings->getBool("show_nametag_backgrounds"); } Camera::~Camera() @@ -540,7 +542,7 @@ void Camera::update(LocalPlayer* player, f32 frametime, f32 busytime, f32 tool_r m_curr_fov_degrees = rangelim(m_curr_fov_degrees, 1.0f, 160.0f); // FOV and aspect ratio - const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); + const v2u32 &window_size = RenderingEngine::getWindowSize(); m_aspect = (f32) window_size.X / (f32) window_size.Y; m_fov_y = m_curr_fov_degrees * M_PI / 180.0; // Increase vertical FOV on lower aspect ratios (<16:10) @@ -663,7 +665,7 @@ void Camera::wield(const ItemStack &item) void Camera::drawWieldedTool(irr::core::matrix4* translation) { // Clear Z buffer so that the wielded tool stays in front of world geometry - m_wieldmgr->getVideoDriver()->clearZBuffer(); + m_wieldmgr->getVideoDriver()->clearBuffers(video::ECBF_DEPTH); // Draw the wielded node (in a separate scene manager) scene::ICameraSceneNode* cam = m_wieldmgr->getActiveCamera(); @@ -696,18 +698,14 @@ void Camera::drawNametags() v2u32 screensize = driver->getScreenSize(); for (const Nametag *nametag : m_nametags) { - if (nametag->nametag_color.getAlpha() == 0) { - // Enforce hiding nametag, - // because if freetype is enabled, a grey - // shadow can remain. - continue; - } - v3f pos = nametag->parent_node->getAbsolutePosition() + nametag->nametag_pos * BS; + // Nametags are hidden in GenericCAO::updateNametag() + + v3f pos = nametag->parent_node->getAbsolutePosition() + nametag->pos * BS; f32 transformed_pos[4] = { pos.X, pos.Y, pos.Z, 1.0f }; trans.multiplyWith1x4Matrix(transformed_pos); if (transformed_pos[3] > 0) { std::wstring nametag_colorless = - unescape_translate(utf8_to_wide(nametag->nametag_text)); + unescape_translate(utf8_to_wide(nametag->text)); core::dimension2d<u32> textsize = font->getDimension( nametag_colorless.c_str()); f32 zDiv = transformed_pos[3] == 0.0f ? 1.0f : @@ -718,28 +716,38 @@ void Camera::drawNametags() screen_pos.Y = screensize.Y * (0.5 - transformed_pos[1] * zDiv * 0.5) - textsize.Height / 2; core::rect<s32> size(0, 0, textsize.Width, textsize.Height); - core::rect<s32> bg_size(-2, 0, textsize.Width+2, textsize.Height); - - video::SColor textColor = nametag->nametag_color; + core::rect<s32> bg_size(-2, 0, std::max(textsize.Width+2, (u32) nametag->images_dim.Width), textsize.Height + nametag->images_dim.Height); - bool darkBackground = textColor.getLuminance() > 186; - video::SColor backgroundColor = darkBackground - ? video::SColor(50, 50, 50, 50) - : video::SColor(50, 255, 255, 255); - driver->draw2DRectangle(backgroundColor, bg_size + screen_pos); + auto bgcolor = nametag->getBgColor(m_show_nametag_backgrounds); + if (bgcolor.getAlpha() != 0) + driver->draw2DRectangle(bgcolor, bg_size + screen_pos); font->draw( - translate_string(utf8_to_wide(nametag->nametag_text)).c_str(), - size + screen_pos, textColor); + translate_string(utf8_to_wide(nametag->text)).c_str(), + size + screen_pos, nametag->textcolor); + + v2s32 image_pos(screen_pos); + image_pos.Y += textsize.Height; + + const video::SColor color(255, 255, 255, 255); + const video::SColor colors[] = {color, color, color, color}; + + for (video::ITexture *texture : nametag->images) { + core::dimension2di imgsize(texture->getOriginalSize()); + core::rect<s32> rect(core::position2d<s32>(0, 0), imgsize); + draw2DImageFilterScaled(driver, texture, rect + image_pos, rect, NULL, colors, true); + image_pos += core::dimension2di(imgsize.Width, 0); + } + } } } - Nametag *Camera::addNametag(scene::ISceneNode *parent_node, - const std::string &nametag_text, video::SColor nametag_color, - const v3f &pos) + const std::string &text, video::SColor textcolor, + Optional<video::SColor> bgcolor, const v3f &pos, + const std::vector<std::string> &images) { - Nametag *nametag = new Nametag(parent_node, nametag_text, nametag_color, pos); + Nametag *nametag = new Nametag(parent_node, text, textcolor, bgcolor, pos, m_client->tsrc(), images); m_nametags.push_back(nametag); return nametag; } diff --git a/src/client/camera.h b/src/client/camera.h index 16a1961be..30fac5289 100644 --- a/src/client/camera.h +++ b/src/client/camera.h @@ -25,27 +25,74 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <ICameraSceneNode.h> #include <ISceneNode.h> #include <list> +#include "util/Optional.h" class LocalPlayer; struct MapDrawControl; class Client; +class RenderingEngine; class WieldMeshSceneNode; -struct Nametag { +struct Nametag +{ + scene::ISceneNode *parent_node; + std::string text; + video::SColor textcolor; + Optional<video::SColor> bgcolor; + v3f pos; + ITextureSource *texture_source; + std::vector<video::ITexture *> images; + core::dimension2di images_dim; + Nametag(scene::ISceneNode *a_parent_node, - const std::string &a_nametag_text, - const video::SColor &a_nametag_color, - const v3f &a_nametag_pos): + const std::string &text, + const video::SColor &textcolor, + const Optional<video::SColor> &bgcolor, + const v3f &pos, + ITextureSource *tsrc, + const std::vector<std::string> &image_names): parent_node(a_parent_node), - nametag_text(a_nametag_text), - nametag_color(a_nametag_color), - nametag_pos(a_nametag_pos) + text(text), + textcolor(textcolor), + bgcolor(bgcolor), + pos(pos), + texture_source(tsrc), + images(), + images_dim(0, 0) { + setImages(image_names); + } + + void setImages(const std::vector<std::string> &image_names) + { + images.clear(); + images_dim = core::dimension2di(0, 0); + + for (const std::string &image_name : image_names) { + video::ITexture *texture = texture_source->getTexture(image_name); + core::dimension2di imgsize(texture->getOriginalSize()); + + images_dim.Width += imgsize.Width; + if (images_dim.Height < imgsize.Height) + images_dim.Height = imgsize.Height; + + images.push_back(texture); + } + } + + video::SColor getBgColor(bool use_fallback) const + { + if (bgcolor) + return bgcolor.value(); + else if (!use_fallback) + return video::SColor(0, 0, 0, 0); + else if (textcolor.getLuminance() > 186) + // Dark background for light text + return video::SColor(50, 50, 50, 50); + else + // Light background for dark text + return video::SColor(50, 255, 255, 255); } - scene::ISceneNode *parent_node; - std::string nametag_text; - video::SColor nametag_color; - v3f nametag_pos; }; enum CameraMode {CAMERA_MODE_FIRST, CAMERA_MODE_THIRD, CAMERA_MODE_THIRD_FRONT}; @@ -58,7 +105,7 @@ enum CameraMode {CAMERA_MODE_FIRST, CAMERA_MODE_THIRD, CAMERA_MODE_THIRD_FRONT}; class Camera { public: - Camera(MapDrawControl &draw_control, Client *client); + Camera(MapDrawControl &draw_control, Client *client, RenderingEngine *rendering_engine); ~Camera(); // Get camera scene node. @@ -164,8 +211,9 @@ public: } Nametag *addNametag(scene::ISceneNode *parent_node, - const std::string &nametag_text, video::SColor nametag_color, - const v3f &pos); + const std::string &text, video::SColor textcolor, + Optional<video::SColor> bgcolor, const v3f &pos, + const std::vector<std::string> &image_names); void removeNametag(Nametag *nametag); @@ -245,4 +293,5 @@ private: bool m_arm_inertia; std::list<Nametag *> m_nametags; + bool m_show_nametag_backgrounds; }; diff --git a/src/client/client.cpp b/src/client/client.cpp index 9bbb57668..57f8e6593 100644 --- a/src/client/client.cpp +++ b/src/client/client.cpp @@ -98,6 +98,7 @@ Client::Client( NodeDefManager *nodedef, ISoundManager *sound, MtEventManager *event, + RenderingEngine *rendering_engine, bool ipv6, GameUI *game_ui ): @@ -108,8 +109,9 @@ Client::Client( m_nodedef(nodedef), m_sound(sound), m_event(event), + m_rendering_engine(rendering_engine), m_env( - new ClientMap(this, control, 666), + new ClientMap(this, rendering_engine, control, 666), tsrc, this ), m_particle_manager(&m_env), @@ -160,20 +162,6 @@ void Client::loadMods() scanModIntoMemory(BUILTIN_MOD_NAME, getBuiltinLuaPath()); m_script->loadModFromMemory(BUILTIN_MOD_NAME); - // TODO Uncomment when server-sent CSM and verifying of builtin are complete - /* - // Don't load client-provided mods if disabled by server - if (checkCSMRestrictionFlag(CSMRestrictionFlags::CSM_RF_LOAD_CLIENT_MODS)) { - warningstream << "Client-provided mod loading is disabled by server." << - std::endl; - // If builtin integrity is wrong, disconnect user - if (!checkBuiltinIntegrity()) { - // TODO disconnect user - } - return; - } - */ - ClientModConfiguration modconf(getClientModsLuaPath()); m_mods = modconf.getMods(); // complain about mods with unsatisfied dependencies @@ -219,12 +207,6 @@ void Client::loadMods() m_script->on_minimap_ready(m_minimap); } -bool Client::checkBuiltinIntegrity() -{ - // TODO - return true; -} - void Client::scanModSubfolder(const std::string &mod_name, const std::string &mod_path, std::string mod_subpath) { @@ -321,12 +303,7 @@ Client::~Client() } // cleanup 3d model meshes on client shutdown - while (RenderingEngine::get_mesh_cache()->getMeshCount() != 0) { - scene::IAnimatedMesh *mesh = RenderingEngine::get_mesh_cache()->getMeshByIndex(0); - - if (mesh) - RenderingEngine::get_mesh_cache()->removeMesh(mesh); - } + m_rendering_engine->cleanupMeshCache(); delete m_minimap; m_minimap = nullptr; @@ -683,15 +660,11 @@ bool Client::loadMedia(const std::string &data, const std::string &filename, TRACESTREAM(<< "Client: Attempting to load image " << "file \"" << filename << "\"" << std::endl); - io::IFileSystem *irrfs = RenderingEngine::get_filesystem(); - video::IVideoDriver *vdrv = RenderingEngine::get_video_driver(); + io::IFileSystem *irrfs = m_rendering_engine->get_filesystem(); + video::IVideoDriver *vdrv = m_rendering_engine->get_video_driver(); - // Silly irrlicht's const-incorrectness - Buffer<char> data_rw(data.c_str(), data.size()); - - // Create an irrlicht memory file io::IReadFile *rfile = irrfs->createMemoryReadFile( - *data_rw, data_rw.getSize(), "_tempreadfile"); + data.c_str(), data.size(), "_tempreadfile"); FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file."); @@ -930,9 +903,9 @@ void Client::Send(NetworkPacket* pkt) // Will fill up 12 + 12 + 4 + 4 + 4 bytes void writePlayerPos(LocalPlayer *myplayer, ClientMap *clientMap, NetworkPacket *pkt) -{ +{ v3f pf = myplayer->getLegitPosition() * 100; - v3f sf = myplayer->getLegitSpeed() * 100; + v3f sf = myplayer->getSendSpeed() * 100; s32 pitch = myplayer->getPitch() * 100; s32 yaw = myplayer->getYaw() * 100; u32 keyPressed = myplayer->keyPressed; @@ -1219,7 +1192,7 @@ void Client::sendChatMessage(const std::wstring &message) if (canSendChatMessage()) { u32 now = time(NULL); float time_passed = now - m_last_chat_message_sent; - m_last_chat_message_sent = time(NULL); + m_last_chat_message_sent = now; m_chat_message_allowance += time_passed * (CLIENT_CHAT_MESSAGE_LIMIT_PER_10S / 8.0f); if (m_chat_message_allowance > CLIENT_CHAT_MESSAGE_LIMIT_PER_10S) @@ -1298,13 +1271,12 @@ void Client::sendPlayerPos(v3f pos) // Save bandwidth by only updating position when // player is not dead and something changed - // FIXME: This part causes breakages in mods like 3d_armor, and has been commented for now - // if (m_activeobjects_received && player->isDead()) - // return; + if (m_activeobjects_received && player->isDead()) + return; if ( player->last_position == pos && - player->last_speed == player->getLegitSpeed() && + player->last_speed == player->getSendSpeed() && player->last_pitch == player->getPitch() && player->last_yaw == player->getYaw() && player->last_keyPressed == player->keyPressed && @@ -1313,7 +1285,7 @@ void Client::sendPlayerPos(v3f pos) return; player->last_position = pos; - player->last_speed = player->getLegitSpeed(); + player->last_speed = player->getSendSpeed(); player->last_pitch = player->getPitch(); player->last_yaw = player->getYaw(); player->last_keyPressed = player->keyPressed; @@ -1448,6 +1420,11 @@ bool Client::updateWieldedItem() return true; } +scene::ISceneManager* Client::getSceneManager() +{ + return m_rendering_engine->get_scene_manager(); +} + Inventory* Client::getInventory(const InventoryLocation &loc) { switch(loc.type){ @@ -1663,17 +1640,17 @@ void Client::addUpdateMeshTaskForNode(v3s16 nodepos, bool ack_to_server, bool ur void Client::updateAllMapBlocks() { v3s16 currentBlock = getNodeBlockPos(floatToInt(m_env.getLocalPlayer()->getPosition(), BS)); - + for (s16 X = currentBlock.X - 2; X <= currentBlock.X + 2; X++) for (s16 Y = currentBlock.Y - 2; Y <= currentBlock.Y + 2; Y++) for (s16 Z = currentBlock.Z - 2; Z <= currentBlock.Z + 2; Z++) addUpdateMeshTask(v3s16(X, Y, Z), false, true); - + Map &map = m_env.getMap(); - + std::vector<v3s16> positions; map.listAllLoadedBlocks(positions); - + for (v3s16 p : positions) { addUpdateMeshTask(p, false, false); } @@ -1710,7 +1687,7 @@ typedef struct TextureUpdateArgs { ITextureSource *tsrc; } TextureUpdateArgs; -void texture_update_progress(void *args, u32 progress, u32 max_progress) +void Client::showUpdateProgressTexture(void *args, u32 progress, u32 max_progress) { TextureUpdateArgs* targs = (TextureUpdateArgs*) args; u16 cur_percent = ceil(progress / (double) max_progress * 100.); @@ -1729,7 +1706,7 @@ void texture_update_progress(void *args, u32 progress, u32 max_progress) targs->last_time_ms = time_ms; std::basic_stringstream<wchar_t> strm; strm << targs->text_base << " " << targs->last_percent << "%..."; - RenderingEngine::draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0, + m_rendering_engine->draw_load_screen(strm.str(), targs->guienv, targs->tsrc, 0, 72 + (u16) ((18. / 100.) * (double) targs->last_percent), true); } } @@ -1750,21 +1727,21 @@ void Client::afterContentReceived() // Rebuild inherited images and recreate textures infostream<<"- Rebuilding images and textures"<<std::endl; - RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 70); + m_rendering_engine->draw_load_screen(text, guienv, m_tsrc, 0, 70); m_tsrc->rebuildImagesAndTextures(); delete[] text; // Rebuild shaders infostream<<"- Rebuilding shaders"<<std::endl; text = wgettext("Rebuilding shaders..."); - RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 71); + m_rendering_engine->draw_load_screen(text, guienv, m_tsrc, 0, 71); m_shsrc->rebuildShaders(); delete[] text; // Update node aliases infostream<<"- Updating node aliases"<<std::endl; text = wgettext("Initializing nodes..."); - RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 72); + m_rendering_engine->draw_load_screen(text, guienv, m_tsrc, 0, 72); m_nodedef->updateAliases(m_itemdef); for (const auto &path : getTextureDirs()) { TextureOverrideSource override_source(path + DIR_DELIM + "override.txt"); @@ -1783,7 +1760,7 @@ void Client::afterContentReceived() tu_args.last_percent = 0; tu_args.text_base = wgettext("Initializing nodes"); tu_args.tsrc = m_tsrc; - m_nodedef->updateTextures(this, texture_update_progress, &tu_args); + m_nodedef->updateTextures(this, &tu_args); delete[] tu_args.text_base; // Start mesh update thread after setting up content definitions @@ -1797,7 +1774,7 @@ void Client::afterContentReceived() m_script->on_client_ready(m_env.getLocalPlayer()); text = wgettext("Done!"); - RenderingEngine::draw_load_screen(text, guienv, m_tsrc, 0, 100); + m_rendering_engine->draw_load_screen(text, guienv, m_tsrc, 0, 100); infostream<<"Client::afterContentReceived() done"<<std::endl; delete[] text; } @@ -1815,7 +1792,7 @@ float Client::getCurRate() void Client::makeScreenshot() { - irr::video::IVideoDriver *driver = RenderingEngine::get_video_driver(); + irr::video::IVideoDriver *driver = m_rendering_engine->get_video_driver(); irr::video::IImage* const raw_image = driver->createScreenShot(); if (!raw_image) @@ -1875,7 +1852,7 @@ void Client::makeScreenshot() sstr << "Failed to save screenshot '" << filename << "'"; } pushToChatQueue(new ChatMessage(CHATMESSAGE_TYPE_SYSTEM, - narrow_to_wide(sstr.str()))); + utf8_to_wide(sstr.str()))); infostream << sstr.str() << std::endl; image->drop(); } @@ -1965,16 +1942,17 @@ scene::IAnimatedMesh* Client::getMesh(const std::string &filename, bool cache) // Create the mesh, remove it from cache and return it // This allows unique vertex colors and other properties for each instance - Buffer<char> data_rw(data.c_str(), data.size()); // Const-incorrect Irrlicht - io::IReadFile *rfile = RenderingEngine::get_filesystem()->createMemoryReadFile( - *data_rw, data_rw.getSize(), filename.c_str()); + io::IReadFile *rfile = m_rendering_engine->get_filesystem()->createMemoryReadFile( + data.c_str(), data.size(), filename.c_str()); FATAL_ERROR_IF(!rfile, "Could not create/open RAM file"); - scene::IAnimatedMesh *mesh = RenderingEngine::get_scene_manager()->getMesh(rfile); + scene::IAnimatedMesh *mesh = m_rendering_engine->get_scene_manager()->getMesh(rfile); rfile->drop(); + if (!mesh) + return nullptr; mesh->grab(); if (!cache) - RenderingEngine::get_mesh_cache()->removeMesh(mesh); + m_rendering_engine->removeMesh(mesh); return mesh; } diff --git a/src/client/client.h b/src/client/client.h index 979636eba..8d7f63c0c 100644 --- a/src/client/client.h +++ b/src/client/client.h @@ -45,6 +45,7 @@ struct ClientEvent; struct MeshMakeData; struct ChatMessage; class MapBlockMesh; +class RenderingEngine; class IWritableTextureSource; class IWritableShaderSource; class ISoundManager; @@ -122,6 +123,7 @@ public: NodeDefManager *nodedef, ISoundManager *sound, MtEventManager *event, + RenderingEngine *rendering_engine, bool ipv6, GameUI *game_ui ); @@ -346,6 +348,7 @@ public: float mediaReceiveProgress(); void afterContentReceived(); + void showUpdateProgressTexture(void *args, u32 progress, u32 max_progress); float getRTT(); float getCurRate(); @@ -354,6 +357,7 @@ public: void setCamera(Camera* camera) { m_camera = camera; } Camera* getCamera () { return m_camera; } + scene::ISceneManager *getSceneManager(); bool shouldShowMinimap() const; @@ -381,6 +385,7 @@ public: // Insert a media file appropriately into the appropriate manager bool loadMedia(const std::string &data, const std::string &filename, bool from_media_push = false); + // Send a request for conventional media transfer void request_media(const std::vector<std::string> &file_requests); @@ -418,16 +423,6 @@ public: return false; } - u32 getCSMNodeRangeLimit() const - { - return m_csm_restriction_noderange; - } - - inline std::unordered_map<u32, u32> &getHUDTranslationMap() - { - return m_hud_server_to_client; - } - bool joinModChannel(const std::string &channel) override; bool leaveModChannel(const std::string &channel) override; bool sendModChannelMessage(const std::string &channel, @@ -445,7 +440,6 @@ public: private: void loadMods(); - bool checkBuiltinIntegrity(); // Virtual methods from con::PeerHandler void peerAdded(con::Peer *peer) override; @@ -487,6 +481,7 @@ private: NodeDefManager *m_nodedef; ISoundManager *m_sound; MtEventManager *m_event; + RenderingEngine *m_rendering_engine; ClientEnvironment m_env; @@ -568,9 +563,6 @@ private: // Relation of client id to object id std::unordered_map<int, u16> m_sounds_to_objects; - // Map server hud ids to client hud ids - std::unordered_map<u32, u32> m_hud_server_to_client; - // Privileges std::unordered_set<std::string> m_privileges; @@ -593,7 +585,6 @@ private: // Client modding ClientScripting *m_script = nullptr; - bool m_modding_enabled; std::unordered_map<std::string, ModMetadata *> m_mod_storages; float m_mod_storage_save_timer = 10.0f; std::vector<ModSpec> m_mods; diff --git a/src/client/clientenvironment.cpp b/src/client/clientenvironment.cpp index 5f44c30ac..f9c20b2df 100644 --- a/src/client/clientenvironment.cpp +++ b/src/client/clientenvironment.cpp @@ -235,7 +235,16 @@ void ClientEnvironment::step(float dtime) &player_collisions); } - bool player_immortal = lplayer->getCAO() && lplayer->getCAO()->isImmortal(); + bool player_immortal = false; + f32 player_fall_factor = 1.0f; + GenericCAO *playercao = lplayer->getCAO(); + if (playercao) { + player_immortal = playercao->isImmortal(); + int addp_p = itemgroup_get(playercao->getGroups(), + "fall_damage_add_percent"); + // convert armor group into an usable fall damage factor + player_fall_factor = 1.0f + (float)addp_p / 100.0f; + } for (const CollisionInfo &info : player_collisions) { v3f speed_diff = info.new_speed - info.old_speed;; @@ -248,17 +257,20 @@ void ClientEnvironment::step(float dtime) speed_diff.Z = 0; f32 pre_factor = 1; // 1 hp per node/s f32 tolerance = BS*14; // 5 without damage - f32 post_factor = 1; // 1 hp per node/s if (info.type == COLLISION_NODE) { const ContentFeatures &f = m_client->ndef()-> get(m_map->getNode(info.node_p)); - // Determine fall damage multiplier - int addp = itemgroup_get(f.groups, "fall_damage_add_percent"); - pre_factor = 1.0f + (float)addp / 100.0f; + // Determine fall damage modifier + int addp_n = itemgroup_get(f.groups, "fall_damage_add_percent"); + // convert node group to an usable fall damage factor + f32 node_fall_factor = 1.0f + (float)addp_n / 100.0f; + // combine both player fall damage modifiers + pre_factor = node_fall_factor * player_fall_factor; } float speed = pre_factor * speed_diff.getLength(); - if (speed > tolerance && !player_immortal) { - f32 damage_f = (speed - tolerance) / BS * post_factor; + + if (speed > tolerance && !player_immortal && pre_factor > 0.0f) { + f32 damage_f = (speed - tolerance) / BS; u16 damage = (u16)MYMIN(damage_f + 0.5, U16_MAX); if (damage != 0) { damageLocalPlayer(damage, true); @@ -334,20 +346,13 @@ GenericCAO* ClientEnvironment::getGenericCAO(u16 id) return NULL; } -bool isFreeClientActiveObjectId(const u16 id, - ClientActiveObjectMap &objects) -{ - return id != 0 && objects.find(id) == objects.end(); - -} - u16 ClientEnvironment::addActiveObject(ClientActiveObject *object) { // Register object. If failed return zero id if (!m_ao_manager.registerObject(object)) return 0; - object->addToScene(m_texturesource); + object->addToScene(m_texturesource, m_client->getSceneManager()); // Update lighting immediately object->updateLight(getDayNightRatio()); @@ -359,6 +364,7 @@ void ClientEnvironment::addActiveObject(u16 id, u8 type, { ClientActiveObject* obj = ClientActiveObject::create((ActiveObjectType) type, m_client, this); + if(obj == NULL) { infostream<<"ClientEnvironment::addActiveObject(): " @@ -369,6 +375,9 @@ void ClientEnvironment::addActiveObject(u16 id, u8 type, obj->setId(id); + if (m_client->modsLoaded()) + m_client->getScript()->addObjectReference(dynamic_cast<ActiveObject*>(obj)); + try { obj->initialize(init_data); @@ -401,9 +410,14 @@ void ClientEnvironment::removeActiveObject(u16 id) { // Get current attachment childs to detach them visually std::unordered_set<int> attachment_childs; - if (auto *obj = getActiveObject(id)) + auto *obj = getActiveObject(id); + if (obj) { attachment_childs = obj->getAttachmentChildIds(); + if (m_client->modsLoaded()) + m_client->getScript()->removeObjectReference(dynamic_cast<ActiveObject*>(obj)); + } + m_ao_manager.removeObject(id); // Perform a proper detach in Irrlicht diff --git a/src/client/clientevent.h b/src/client/clientevent.h index 9bd31efce..2215aecbd 100644 --- a/src/client/clientevent.h +++ b/src/client/clientevent.h @@ -52,6 +52,31 @@ enum ClientEventType : u8 CLIENTEVENT_MAX, }; +struct ClientEventHudAdd +{ + u32 server_id; + u8 type; + v2f pos, scale; + std::string name; + std::string text, text2; + u32 number, item, dir; + v2f align, offset; + v3f world_pos; + v2s32 size; + s16 z_index; +}; + +struct ClientEventHudChange +{ + u32 id; + HudElementStat stat; + v2f v2fdata; + std::string sdata; + u32 data; + v3f v3fdata; + v2s32 v2s32data; +}; + struct ClientEvent { ClientEventType type; @@ -93,38 +118,12 @@ struct ClientEvent { u32 id; } delete_particlespawner; - struct - { - u32 server_id; - u8 type; - v2f *pos; - std::string *name; - v2f *scale; - std::string *text; - u32 number; - u32 item; - u32 dir; - v2f *align; - v2f *offset; - v3f *world_pos; - v2s32 *size; - s16 z_index; - std::string *text2; - } hudadd; + ClientEventHudAdd *hudadd; struct { u32 id; } hudrm; - struct - { - u32 id; - HudElementStat stat; - v2f *v2fdata; - std::string *sdata; - u32 data; - v3f *v3fdata; - v2s32 *v2s32data; - } hudchange; + ClientEventHudChange *hudchange; SkyboxParams *set_sky; struct { diff --git a/src/client/clientlauncher.cpp b/src/client/clientlauncher.cpp index 29427f609..6db5f2e70 100644 --- a/src/client/clientlauncher.cpp +++ b/src/client/clientlauncher.cpp @@ -80,7 +80,7 @@ ClientLauncher::~ClientLauncher() delete g_fontengine; delete g_gamecallback; - delete RenderingEngine::get_instance(); + delete m_rendering_engine; #if USE_SOUND g_sound_manager_singleton.reset(); @@ -101,7 +101,7 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) // List video modes if requested if (list_video_modes) - return RenderingEngine::print_video_modes(); + return m_rendering_engine->print_video_modes(); #if USE_SOUND if (g_settings->getBool("enable_sound")) @@ -120,12 +120,12 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) return true; } - if (RenderingEngine::get_video_driver() == NULL) { + if (m_rendering_engine->get_video_driver() == NULL) { errorstream << "Could not initialize video driver." << std::endl; return false; } - RenderingEngine::get_instance()->setupTopLevelWindow(PROJECT_NAME_C); + m_rendering_engine->setupTopLevelWindow(PROJECT_NAME_C); /* This changes the minimum allowed number of vertices in a VBO. @@ -136,15 +136,15 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) // Create game callback for menus g_gamecallback = new MainGameCallback(); - RenderingEngine::get_instance()->setResizable(true); + m_rendering_engine->setResizable(true); init_input(); - RenderingEngine::get_scene_manager()->getParameters()-> + m_rendering_engine->get_scene_manager()->getParameters()-> setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true); - guienv = RenderingEngine::get_gui_env(); - skin = RenderingEngine::get_gui_env()->getSkin(); + guienv = m_rendering_engine->get_gui_env(); + skin = guienv->getSkin(); skin->setColor(gui::EGDC_BUTTON_TEXT, video::SColor(255, 255, 255, 255)); skin->setColor(gui::EGDC_3D_LIGHT, video::SColor(0, 0, 0, 0)); skin->setColor(gui::EGDC_3D_HIGH_LIGHT, video::SColor(255, 30, 30, 30)); @@ -166,7 +166,7 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) sprite_path.append("checkbox_16.png"); // Texture dimensions should be a power of 2 gui::IGUISpriteBank *sprites = skin->getSpriteBank(); - video::IVideoDriver *driver = RenderingEngine::get_video_driver(); + video::IVideoDriver *driver = m_rendering_engine->get_video_driver(); video::ITexture *sprite_texture = driver->getTexture(sprite_path.c_str()); if (sprite_texture) { s32 sprite_id = sprites->addTextureAsSprite(sprite_texture); @@ -175,18 +175,16 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) } } #endif - g_fontengine = new FontEngine(g_settings, guienv); + g_fontengine = new FontEngine(guienv); FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed."); -#if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2 // Irrlicht 1.8 input colours skin->setColor(gui::EGDC_EDITABLE, video::SColor(255, 128, 128, 128)); skin->setColor(gui::EGDC_FOCUSED_EDITABLE, video::SColor(255, 96, 134, 49)); -#endif // Create the menu clouds if (!g_menucloudsmgr) - g_menucloudsmgr = RenderingEngine::get_scene_manager()->createNewSceneManager(); + g_menucloudsmgr = m_rendering_engine->get_scene_manager()->createNewSceneManager(); if (!g_menuclouds) g_menuclouds = new Clouds(g_menucloudsmgr, -1, rand()); g_menuclouds->setHeight(100.0f); @@ -214,11 +212,11 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) bool retval = true; bool *kill = porting::signal_handler_killstatus(); - while (RenderingEngine::run() && !*kill && + while (m_rendering_engine->run() && !*kill && !g_gamecallback->shutdown_requested) { // Set the window caption const wchar_t *text = wgettext("Main Menu"); - RenderingEngine::get_raw_device()-> + m_rendering_engine->get_raw_device()-> setWindowCaption((utf8_to_wide(PROJECT_NAME_C) + L" " + utf8_to_wide(g_version_hash) + L" [" + text + L"]").c_str()); @@ -226,14 +224,14 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) try { // This is used for catching disconnects - RenderingEngine::get_gui_env()->clear(); + m_rendering_engine->get_gui_env()->clear(); /* We need some kind of a root node to be able to add custom gui elements directly on the screen. Otherwise they won't be automatically drawn. */ - guiroot = RenderingEngine::get_gui_env()->addStaticText(L"", + guiroot = m_rendering_engine->get_gui_env()->addStaticText(L"", core::rect<s32>(0, 0, 10000, 10000)); bool game_has_run = launch_game(error_message, reconnect_requested, @@ -256,29 +254,30 @@ bool ClientLauncher::run(GameStartData &start_data, const Settings &cmd_args) } // Break out of menu-game loop to shut down cleanly - if (!RenderingEngine::get_raw_device()->run() || *kill) { + if (!m_rendering_engine->run() || *kill) { if (!g_settings_path.empty()) g_settings->updateConfigFile(g_settings_path.c_str()); break; } - RenderingEngine::get_video_driver()->setTextureCreationFlag( + m_rendering_engine->get_video_driver()->setTextureCreationFlag( video::ETCF_CREATE_MIP_MAPS, g_settings->getBool("mip_map")); #ifdef HAVE_TOUCHSCREENGUI - receiver->m_touchscreengui = new TouchScreenGUI(RenderingEngine::get_raw_device(), receiver); + receiver->m_touchscreengui = new TouchScreenGUI(m_rendering_engine->get_raw_device(), receiver); g_touchscreengui = receiver->m_touchscreengui; #endif the_game( kill, input, + m_rendering_engine, start_data, error_message, chat_backend, &reconnect_requested ); - RenderingEngine::get_scene_manager()->clear(); + m_rendering_engine->get_scene_manager()->clear(); #ifdef HAVE_TOUCHSCREENGUI delete g_touchscreengui; @@ -346,8 +345,8 @@ void ClientLauncher::init_args(GameStartData &start_data, const Settings &cmd_ar bool ClientLauncher::init_engine() { receiver = new MyEventReceiver(); - new RenderingEngine(receiver); - return RenderingEngine::get_raw_device() != nullptr; + m_rendering_engine = new RenderingEngine(receiver); + return m_rendering_engine->get_raw_device() != nullptr; } void ClientLauncher::init_input() @@ -364,7 +363,7 @@ void ClientLauncher::init_input() // Make sure this is called maximum once per // irrlicht device, otherwise it will give you // multiple events for the same joystick. - if (RenderingEngine::get_raw_device()->activateJoysticks(infos)) { + if (m_rendering_engine->get_raw_device()->activateJoysticks(infos)) { infostream << "Joystick support enabled" << std::endl; joystick_infos.reserve(infos.size()); for (u32 i = 0; i < infos.size(); i++) { @@ -471,7 +470,7 @@ bool ClientLauncher::launch_game(std::string &error_message, start_data.address.empty() && !start_data.name.empty(); } - if (!RenderingEngine::run()) + if (!m_rendering_engine->run()) return false; if (!start_data.isSinglePlayer() && start_data.name.empty()) { @@ -487,14 +486,6 @@ bool ClientLauncher::launch_game(std::string &error_message, start_data.socket_port = myrand_range(49152, 65535); } else { g_settings->set("name", start_data.name); - if (!start_data.address.empty()) { - ServerListSpec server; - server["name"] = server_name; - server["address"] = start_data.address; - server["port"] = itos(start_data.socket_port); - server["description"] = server_description; - ServerList::insert(server); - } } if (start_data.name.length() > PLAYERNAME_SIZE - 1) { @@ -551,14 +542,14 @@ bool ClientLauncher::launch_game(std::string &error_message, void ClientLauncher::main_menu(MainMenuData *menudata) { bool *kill = porting::signal_handler_killstatus(); - video::IVideoDriver *driver = RenderingEngine::get_video_driver(); + video::IVideoDriver *driver = m_rendering_engine->get_video_driver(); infostream << "Waiting for other menus" << std::endl; - while (RenderingEngine::get_raw_device()->run() && !*kill) { + while (m_rendering_engine->run() && !*kill) { if (!isMenuActive()) break; driver->beginScene(true, true, video::SColor(255, 128, 128, 128)); - RenderingEngine::get_gui_env()->drawAll(); + m_rendering_engine->get_gui_env()->drawAll(); driver->endScene(); // On some computers framerate doesn't seem to be automatically limited sleep_ms(25); @@ -567,14 +558,14 @@ void ClientLauncher::main_menu(MainMenuData *menudata) // Cursor can be non-visible when coming from the game #ifndef ANDROID - RenderingEngine::get_raw_device()->getCursorControl()->setVisible(true); + m_rendering_engine->get_raw_device()->getCursorControl()->setVisible(true); #endif /* show main menu */ - GUIEngine mymenu(&input->joystick, guiroot, &g_menumgr, menudata, *kill); + GUIEngine mymenu(&input->joystick, guiroot, m_rendering_engine, &g_menumgr, menudata, *kill); /* leave scene manager in a clean state */ - RenderingEngine::get_scene_manager()->clear(); + m_rendering_engine->get_scene_manager()->clear(); } void ClientLauncher::speed_tests() diff --git a/src/client/clientlauncher.h b/src/client/clientlauncher.h index b280d8e6b..79727e1fe 100644 --- a/src/client/clientlauncher.h +++ b/src/client/clientlauncher.h @@ -49,6 +49,7 @@ private: bool list_video_modes = false; bool skip_main_menu = false; bool random_input = false; + RenderingEngine *m_rendering_engine = nullptr; InputHandler *input = nullptr; MyEventReceiver *receiver = nullptr; gui::IGUISkin *skin = nullptr; diff --git a/src/client/clientmap.cpp b/src/client/clientmap.cpp index 68fd41e39..29a7fd3ba 100644 --- a/src/client/clientmap.cpp +++ b/src/client/clientmap.cpp @@ -64,12 +64,13 @@ void MeshBufListList::add(scene::IMeshBuffer *buf, v3s16 position, u8 layer) ClientMap::ClientMap( Client *client, + RenderingEngine *rendering_engine, MapDrawControl &control, s32 id ): Map(client), - scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(), - RenderingEngine::get_scene_manager(), id), + scene::ISceneNode(rendering_engine->get_scene_manager()->getRootSceneNode(), + rendering_engine->get_scene_manager(), id), m_client(client), m_control(control) { @@ -165,6 +166,9 @@ void ClientMap::updateDrawList() v3s16 p_blocks_max; getBlocksInViewRange(cam_pos_nodes, &p_blocks_min, &p_blocks_max); + // Read the vision range, unless unlimited range is enabled. + float range = m_control.range_all ? 1e7 : m_control.wanted_range; + // Number of blocks currently loaded by the client u32 blocks_loaded = 0; // Number of blocks with mesh in rendering range @@ -182,6 +186,7 @@ void ClientMap::updateDrawList() occlusion_culling_enabled = false; } + // Uncomment to debug occluded blocks in the wireframe mode // TODO: Include this as a flag for an extended debugging setting //if (occlusion_culling_enabled && m_control.show_wireframe) @@ -218,32 +223,34 @@ void ClientMap::updateDrawList() continue; } - float range = 100000 * BS; - if (!m_control.range_all) - range = m_control.wanted_range * BS; + v3s16 block_coord = block->getPos(); + v3s16 block_position = block->getPosRelative() + MAP_BLOCKSIZE / 2; - float d = 0.0; - if (!isBlockInSight(block->getPos(), camera_position, - camera_direction, camera_fov, range, &d)) - continue; + // First, perform a simple distance check, with a padding of one extra block. + if (!m_control.range_all && + block_position.getDistanceFrom(cam_pos_nodes) > range + MAP_BLOCKSIZE) + continue; // Out of range, skip. + // Keep the block alive as long as it is in range. + block->resetUsageTimer(); blocks_in_range_with_mesh++; - /* - Occlusion culling - */ + // Frustum culling + float d = 0.0; + if (!isBlockInSight(block_coord, camera_position, + camera_direction, camera_fov, range * BS, &d)) + continue; + + // Occlusion culling if ((!m_control.range_all && d > m_control.wanted_range * BS) || (occlusion_culling_enabled && isBlockOccluded(block, cam_pos_nodes))) { blocks_occlusion_culled++; continue; } - // This block is in range. Reset usage timer. - block->resetUsageTimer(); - // Add to set block->refGrab(); - m_drawlist[block->getPos()] = block; + m_drawlist[block_coord] = block; sector_blocks_drawn++; } // foreach sectorblocks @@ -282,8 +289,6 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) const u32 daynight_ratio = m_client->getEnv().getDayNightRatio(); const v3f camera_position = m_camera_position; - const v3f camera_direction = m_camera_direction; - const f32 camera_fov = m_camera_fov; /* Get all blocks and draw all visible ones @@ -310,10 +315,9 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) if (!block->mesh) continue; - float d = 0.0; - if (!isBlockInSight(block->getPos(), camera_position, - camera_direction, camera_fov, 100000 * BS, &d)) - continue; + v3f block_pos_r = intToFloat(block->getPosRelative() + MAP_BLOCKSIZE / 2, BS); + float d = camera_position.getDistanceFrom(block_pos_r); + d = MYMAX(0,d - BLOCK_MAX_RADIUS); // Mesh animation if (pass == scene::ESNRP_SOLID) { @@ -496,12 +500,12 @@ int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor, static v3f z_directions[50] = { v3f(-100, 0, 0) }; - static f32 z_offsets[sizeof(z_directions)/sizeof(*z_directions)] = { + static f32 z_offsets[50] = { -1000, }; - if(z_directions[0].X < -99){ - for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){ + if (z_directions[0].X < -99) { + for (u32 i = 0; i < ARRLEN(z_directions); i++) { // Assumes FOV of 72 and 16/9 aspect ratio z_directions[i] = v3f( 0.02 * myrand_range(-100, 100), @@ -517,7 +521,8 @@ int ClientMap::getBackgroundBrightness(float max_d, u32 daylight_factor, if(sunlight_min_d > 35*BS) sunlight_min_d = 35*BS; std::vector<int> values; - for(u32 i=0; i<sizeof(z_directions)/sizeof(*z_directions); i++){ + values.reserve(ARRLEN(z_directions)); + for (u32 i = 0; i < ARRLEN(z_directions); i++) { v3f z_dir = z_directions[i]; core::CMatrix4<f32> a; a.buildRotateFromTo(v3f(0,1,0), z_dir); diff --git a/src/client/clientmap.h b/src/client/clientmap.h index 57cc4427e..80add4a44 100644 --- a/src/client/clientmap.h +++ b/src/client/clientmap.h @@ -68,6 +68,7 @@ class ClientMap : public Map, public scene::ISceneNode public: ClientMap( Client *client, + RenderingEngine *rendering_engine, MapDrawControl &control, s32 id ); diff --git a/src/client/clientmedia.cpp b/src/client/clientmedia.cpp index c4c08c05d..0f9ba5356 100644 --- a/src/client/clientmedia.cpp +++ b/src/client/clientmedia.cpp @@ -216,7 +216,6 @@ void ClientMediaDownloader::initialStep(Client *client) // This is the first time we use httpfetch, so alloc a caller ID m_httpfetch_caller = httpfetch_caller_alloc(); - m_httpfetch_timeout = g_settings->getS32("curl_timeout"); // Set the active fetch limit to curl_parallel_limit or 84, // whichever is greater. This gives us some leeway so that @@ -258,8 +257,6 @@ void ClientMediaDownloader::initialStep(Client *client) remote->baseurl + MTHASHSET_FILE_NAME; fetch_request.caller = m_httpfetch_caller; fetch_request.request_id = m_httpfetch_next_id; // == i - fetch_request.timeout = m_httpfetch_timeout; - fetch_request.connect_timeout = m_httpfetch_timeout; fetch_request.method = HTTP_POST; fetch_request.raw_data = required_hash_set; fetch_request.extra_headers.emplace_back( @@ -432,9 +429,8 @@ void ClientMediaDownloader::startRemoteMediaTransfers() fetch_request.url = url; fetch_request.caller = m_httpfetch_caller; fetch_request.request_id = m_httpfetch_next_id; - fetch_request.timeout = 0; // no data timeout! - fetch_request.connect_timeout = - m_httpfetch_timeout; + fetch_request.timeout = + g_settings->getS32("curl_file_download_timeout"); httpfetch_async(fetch_request); m_remote_file_transfers.insert(std::make_pair( diff --git a/src/client/clientmedia.h b/src/client/clientmedia.h index 5a918535b..e97a0f24b 100644 --- a/src/client/clientmedia.h +++ b/src/client/clientmedia.h @@ -137,7 +137,6 @@ private: // Status of remote transfers unsigned long m_httpfetch_caller; unsigned long m_httpfetch_next_id = 0; - long m_httpfetch_timeout = 0; s32 m_httpfetch_active = 0; s32 m_httpfetch_active_limit = 0; s32 m_outstanding_hash_sets = 0; diff --git a/src/client/clientobject.h b/src/client/clientobject.h index 4a1743d72..c0b14497c 100644 --- a/src/client/clientobject.h +++ b/src/client/clientobject.h @@ -44,7 +44,7 @@ public: ClientActiveObject(u16 id, Client *client, ClientEnvironment *env); virtual ~ClientActiveObject(); - virtual void addToScene(ITextureSource *tsrc) {} + virtual void addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr) = 0; virtual void removeFromScene(bool permanent) {} virtual void updateLight(u32 day_night_ratio) {} diff --git a/src/client/clouds.cpp b/src/client/clouds.cpp index 253dee8b9..5008047af 100644 --- a/src/client/clouds.cpp +++ b/src/client/clouds.cpp @@ -30,7 +30,7 @@ with this program; if not, write to the Free Software Foundation, Inc., // Menu clouds are created later class Clouds; Clouds *g_menuclouds = NULL; -irr::scene::ISceneManager *g_menucloudsmgr = NULL; +scene::ISceneManager *g_menucloudsmgr = NULL; // Constant for now static constexpr const float cloud_size = BS * 64.0f; @@ -170,7 +170,7 @@ void Clouds::render() // Read noise - std::vector<char> grid(m_cloud_radius_i * 2 * m_cloud_radius_i * 2); // vector<bool> is broken + std::vector<bool> grid(m_cloud_radius_i * 2 * m_cloud_radius_i * 2); std::vector<video::S3DVertex> vertices; vertices.reserve(16 * m_cloud_radius_i * m_cloud_radius_i); diff --git a/src/client/clouds.h b/src/client/clouds.h index a4d810faa..c009a05b7 100644 --- a/src/client/clouds.h +++ b/src/client/clouds.h @@ -29,8 +29,7 @@ class Clouds; extern Clouds *g_menuclouds; // Scene manager used for menu clouds -namespace irr{namespace scene{class ISceneManager;}} -extern irr::scene::ISceneManager *g_menucloudsmgr; +extern scene::ISceneManager *g_menucloudsmgr; class Clouds : public scene::ISceneNode { diff --git a/src/client/content_cao.cpp b/src/client/content_cao.cpp index c44c167b5..1259fcbd3 100644 --- a/src/client/content_cao.cpp +++ b/src/client/content_cao.cpp @@ -24,7 +24,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <IMeshManipulator.h> #include <IAnimatedMeshSceneNode.h> #include "client/client.h" -#include "client/renderingengine.h" #include "client/sound.h" #include "client/tile.h" #include "util/basic_macros.h" @@ -190,7 +189,7 @@ public: static ClientActiveObject* create(Client *client, ClientEnvironment *env); - void addToScene(ITextureSource *tsrc); + void addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr); void removeFromScene(bool permanent); void updateLight(u32 day_night_ratio); void updateNodePos(); @@ -221,7 +220,7 @@ ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env) return new TestCAO(client, env); } -void TestCAO::addToScene(ITextureSource *tsrc) +void TestCAO::addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr) { if(m_node != NULL) return; @@ -250,7 +249,7 @@ void TestCAO::addToScene(ITextureSource *tsrc) // Add to mesh mesh->addMeshBuffer(buf); buf->drop(); - m_node = RenderingEngine::get_scene_manager()->addMeshSceneNode(mesh, NULL); + m_node = smgr->addMeshSceneNode(mesh, NULL); mesh->drop(); updateNodePos(); } @@ -595,9 +594,9 @@ void GenericCAO::removeFromScene(bool permanent) m_client->getMinimap()->removeMarker(&m_marker); } -void GenericCAO::addToScene(ITextureSource *tsrc) +void GenericCAO::addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr) { - m_smgr = RenderingEngine::get_scene_manager(); + m_smgr = smgr; if (getSceneNode() != NULL) { return; @@ -629,8 +628,7 @@ void GenericCAO::addToScene(ITextureSource *tsrc) } auto grabMatrixNode = [this] { - m_matrixnode = RenderingEngine::get_scene_manager()-> - addDummyTransformationSceneNode(); + m_matrixnode = m_smgr->addDummyTransformationSceneNode(); m_matrixnode->grab(); }; @@ -648,7 +646,7 @@ void GenericCAO::addToScene(ITextureSource *tsrc) if (m_prop.visual == "sprite") { grabMatrixNode(); - m_spritenode = RenderingEngine::get_scene_manager()->addBillboardSceneNode( + m_spritenode = m_smgr->addBillboardSceneNode( m_matrixnode, v2f(1, 1), v3f(0,0,0), -1); m_spritenode->grab(); m_spritenode->setMaterialTexture(0, @@ -733,8 +731,7 @@ void GenericCAO::addToScene(ITextureSource *tsrc) mesh->addMeshBuffer(buf); buf->drop(); } - m_meshnode = RenderingEngine::get_scene_manager()-> - addMeshSceneNode(mesh, m_matrixnode); + m_meshnode = m_smgr->addMeshSceneNode(mesh, m_matrixnode); m_meshnode->grab(); mesh->drop(); // Set it to use the materials of the meshbuffers directly. @@ -743,8 +740,7 @@ void GenericCAO::addToScene(ITextureSource *tsrc) } else if (m_prop.visual == "cube") { grabMatrixNode(); scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS)); - m_meshnode = RenderingEngine::get_scene_manager()-> - addMeshSceneNode(mesh, m_matrixnode); + m_meshnode = m_smgr->addMeshSceneNode(mesh, m_matrixnode); m_meshnode->grab(); mesh->drop(); @@ -757,8 +753,7 @@ void GenericCAO::addToScene(ITextureSource *tsrc) grabMatrixNode(); scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true); if (mesh) { - m_animated_meshnode = RenderingEngine::get_scene_manager()-> - addAnimatedMeshSceneNode(mesh, m_matrixnode); + m_animated_meshnode = m_smgr->addAnimatedMeshSceneNode(mesh, m_matrixnode); m_animated_meshnode->grab(); mesh->drop(); // The scene node took hold of it @@ -799,8 +794,7 @@ void GenericCAO::addToScene(ITextureSource *tsrc) infostream << "serialized form: " << m_prop.wield_item << std::endl; item.deSerialize(m_prop.wield_item, m_client->idef()); } - m_wield_meshnode = new WieldMeshSceneNode( - RenderingEngine::get_scene_manager(), -1); + m_wield_meshnode = new WieldMeshSceneNode(m_smgr, -1); m_wield_meshnode->setItem(item, m_client, (m_prop.visual == "wielditem")); @@ -828,16 +822,22 @@ void GenericCAO::addToScene(ITextureSource *tsrc) updateAttachments(); setNodeLight(m_last_light); updateMeshCulling(); + + if (m_client->modsLoaded()) + m_client->getScript()->on_object_add(m_id); + + if (m_client->modsLoaded()) + m_client->getScript()->on_object_properties_change(m_id); } void GenericCAO::updateLight(u32 day_night_ratio) -{ +{ if (m_glow < 0) return; u8 light_at_pos = 0; bool pos_ok = false; - + v3s16 pos[3]; u16 npos = getLightPosition(pos); for (u16 i = 0; i < npos; i++) { @@ -940,7 +940,7 @@ void GenericCAO::updateNametag() //if (m_is_local_player && ! g_settings->getBool("freecam")) // No nametag for local player //return; - if (m_prop.nametag.empty()) { + if (m_prop.nametag.empty() || m_prop.nametag_color.getAlpha() == 0) { // Delete nametag if (m_nametag) { m_client->getCamera()->removeNametag(m_nametag); @@ -958,12 +958,15 @@ void GenericCAO::updateNametag() if (!m_nametag) { // Add nametag m_nametag = m_client->getCamera()->addNametag(node, - m_prop.nametag, m_prop.nametag_color, pos); + m_prop.nametag, m_prop.nametag_color, + m_prop.nametag_bgcolor, pos, nametag_images); } else { // Update nametag - m_nametag->nametag_text = m_prop.nametag; - m_nametag->nametag_color = m_prop.nametag_color; - m_nametag->nametag_pos = pos; + m_nametag->text = m_prop.nametag; + m_nametag->textcolor = m_prop.nametag_color; + m_nametag->bgcolor = m_prop.nametag_bgcolor; + m_nametag->pos = pos; + m_nametag->setImages(nametag_images); } } @@ -1080,7 +1083,7 @@ void GenericCAO::step(float dtime, ClientEnvironment *env) } removeFromScene(false); - addToScene(m_client->tsrc()); + addToScene(m_client->tsrc(), m_smgr); // Attachments, part 2: Now that the parent has been refreshed, put its attachments back for (u16 cao_id : m_attachment_child_ids) { @@ -1479,11 +1482,8 @@ void GenericCAO::updateAnimation() if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed) m_animated_meshnode->setAnimationSpeed(m_animation_speed); m_animated_meshnode->setTransitionTime(m_animation_blend); -// Requires Irrlicht 1.8 or greater -#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1 if (m_animated_meshnode->getLoopMode() != m_animation_loop) m_animated_meshnode->setLoopMode(m_animation_loop); -#endif } void GenericCAO::updateAnimationSpeed() @@ -1499,10 +1499,10 @@ void GenericCAO::updateBonePosition() if (m_bone_position.empty() || !m_animated_meshnode) return; - m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render + m_animated_meshnode->setJointMode(scene::EJUOR_CONTROL); // To write positions to the mesh on render for (auto &it : m_bone_position) { std::string bone_name = it.first; - irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str()); + scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str()); if (bone) { bone->setPosition(it.second.X); bone->setRotation(it.second.Y); @@ -1511,7 +1511,7 @@ void GenericCAO::updateBonePosition() // search through bones to find mistakenly rotated bones due to bug in Irrlicht for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) { - irr::scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i); + scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i); if (!bone) continue; @@ -1627,6 +1627,57 @@ bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const (uses_legacy_texture && old.textures != new_.textures); } +void GenericCAO::setProperties(ObjectProperties newprops) +{ + // Check what exactly changed + bool expire_visuals = visualExpiryRequired(newprops); + bool textures_changed = m_prop.textures != newprops.textures; + + // Apply changes + m_prop = std::move(newprops); + + m_selection_box = m_prop.selectionbox; + m_selection_box.MinEdge *= BS; + m_selection_box.MaxEdge *= BS; + + m_tx_size.X = 1.0f / m_prop.spritediv.X; + m_tx_size.Y = 1.0f / m_prop.spritediv.Y; + + if(!m_initial_tx_basepos_set){ + m_initial_tx_basepos_set = true; + m_tx_basepos = m_prop.initial_sprite_basepos; + } + if (m_is_local_player) { + LocalPlayer *player = m_env->getLocalPlayer(); + player->makes_footstep_sound = m_prop.makes_footstep_sound; + aabb3f collision_box = m_prop.collisionbox; + collision_box.MinEdge *= BS; + collision_box.MaxEdge *= BS; + player->setCollisionbox(collision_box); + player->setEyeHeight(m_prop.eye_height); + player->setZoomFOV(m_prop.zoom_fov); + } + + if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty()) + m_prop.nametag = m_name; + if (m_is_local_player) + m_prop.show_on_minimap = false; + + if (expire_visuals) { + expireVisuals(); + } else { + infostream << "GenericCAO: properties updated but expiring visuals" + << " not necessary" << std::endl; + if (textures_changed) { + // don't update while punch texture modifier is active + if (m_reset_textures_timer < 0) + updateTextures(m_current_texture_modifier); + } + updateNametag(); + updateMarker(); + } +} + void GenericCAO::processMessage(const std::string &data) { //infostream<<"GenericCAO: Got message"<<std::endl; @@ -1638,54 +1689,12 @@ void GenericCAO::processMessage(const std::string &data) newprops.show_on_minimap = m_is_player; // default newprops.deSerialize(is); + setProperties(newprops); - // Check what exactly changed - bool expire_visuals = visualExpiryRequired(newprops); - bool textures_changed = m_prop.textures != newprops.textures; - - // Apply changes - m_prop = std::move(newprops); - - m_selection_box = m_prop.selectionbox; - m_selection_box.MinEdge *= BS; - m_selection_box.MaxEdge *= BS; - - m_tx_size.X = 1.0f / m_prop.spritediv.X; - m_tx_size.Y = 1.0f / m_prop.spritediv.Y; + // notify CSM + if (m_client->modsLoaded()) + m_client->getScript()->on_object_properties_change(m_id); - if(!m_initial_tx_basepos_set){ - m_initial_tx_basepos_set = true; - m_tx_basepos = m_prop.initial_sprite_basepos; - } - if (m_is_local_player) { - LocalPlayer *player = m_env->getLocalPlayer(); - player->makes_footstep_sound = m_prop.makes_footstep_sound; - aabb3f collision_box = m_prop.collisionbox; - collision_box.MinEdge *= BS; - collision_box.MaxEdge *= BS; - player->setCollisionbox(collision_box); - player->setEyeHeight(m_prop.eye_height); - player->setZoomFOV(m_prop.zoom_fov); - } - - if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty()) - m_prop.nametag = m_name; - if (m_is_local_player) - m_prop.show_on_minimap = false; - - if (expire_visuals) { - expireVisuals(); - } else { - infostream << "GenericCAO: properties updated but expiring visuals" - << " not necessary" << std::endl; - if (textures_changed) { - // don't update while punch texture modifier is active - if (m_reset_textures_timer < 0) - updateTextures(m_current_texture_modifier); - } - updateNametag(); - updateMarker(); - } } else if (cmd == AO_CMD_UPDATE_POSITION) { // Not sent by the server if this object is an attachment. // We might however get here if the server notices the object being detached before the client. @@ -1750,10 +1759,10 @@ void GenericCAO::processMessage(const std::string &data) if(m_is_local_player) { Client *client = m_env->getGameDef(); - + if (client->modsLoaded() && client->getScript()->on_recieve_physics_override(override_speed, override_jump, override_gravity, sneak, sneak_glitch, new_move)) return; - + LocalPlayer *player = m_env->getLocalPlayer(); player->physics_override_speed = override_speed; player->physics_override_jump = override_jump; @@ -1849,6 +1858,9 @@ void GenericCAO::processMessage(const std::string &data) // Same as 'ObjectRef::l_remove' if (!m_is_player) clearChildAttachments(); + } else { + if (m_client->modsLoaded()) + m_client->getScript()->on_object_hp_change(m_id); } } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) { m_armor_groups.clear(); @@ -1944,7 +1956,7 @@ void GenericCAO::updateMeshCulling() return; } - irr::scene::ISceneNode *node = getSceneNode(); + scene::ISceneNode *node = getSceneNode(); if (!node) return; diff --git a/src/client/content_cao.h b/src/client/content_cao.h index 09c26bd9c..7e9bb6671 100644 --- a/src/client/content_cao.h +++ b/src/client/content_cao.h @@ -181,7 +181,7 @@ public: { return m_velocity; } - + inline const u16 getHp() const { return m_hp; @@ -189,6 +189,8 @@ public: const bool isImmortal(); + inline const ObjectProperties &getProperties() const { return m_prop; } + scene::ISceneNode *getSceneNode() const; scene::IAnimatedMeshSceneNode *getAnimatedMeshSceneNode() const; @@ -260,7 +262,7 @@ public: void removeFromScene(bool permanent); - void addToScene(ITextureSource *tsrc); + void addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr); inline void expireVisuals() { @@ -307,13 +309,17 @@ public: { return m_prop.infotext; } - + float m_waiting_for_reattach; - + ObjectProperties *getProperties() { return &m_prop; } + void setProperties(ObjectProperties newprops); + void updateMeshCulling(); + + std::vector<std::string> nametag_images = {}; }; diff --git a/src/client/content_mapblock.cpp b/src/client/content_mapblock.cpp index df2748212..810c57138 100644 --- a/src/client/content_mapblock.cpp +++ b/src/client/content_mapblock.cpp @@ -60,18 +60,16 @@ static constexpr u16 quad_indices[] = {0, 1, 2, 2, 3, 0}; const std::string MapblockMeshGenerator::raillike_groupname = "connect_to_raillike"; -MapblockMeshGenerator::MapblockMeshGenerator(MeshMakeData *input, MeshCollector *output) +MapblockMeshGenerator::MapblockMeshGenerator(MeshMakeData *input, MeshCollector *output, + scene::IMeshManipulator *mm): + data(input), + collector(output), + nodedef(data->m_client->ndef()), + meshmanip(mm), + blockpos_nodes(data->m_blockpos * MAP_BLOCKSIZE) { - data = input; - collector = output; - - nodedef = data->m_client->ndef(); - meshmanip = RenderingEngine::get_scene_manager()->getMeshManipulator(); - enable_mesh_cache = g_settings->getBool("enable_mesh_cache") && !data->m_smooth_lighting; // Mesh cache is not supported with smooth lighting - - blockpos_nodes = data->m_blockpos * MAP_BLOCKSIZE; } void MapblockMeshGenerator::useTile(int index, u8 set_flags, u8 reset_flags, bool special) @@ -513,10 +511,10 @@ f32 MapblockMeshGenerator::getCornerLevel(int i, int k) count++; } else if (content == CONTENT_AIR) { air_count++; - if (air_count >= 2) - return -0.5 * BS + 0.2; } } + if (air_count >= 2) + return -0.5 * BS + 0.2; if (count > 0) return sum / count; return 0; @@ -968,7 +966,7 @@ void MapblockMeshGenerator::drawPlantlike() draw_style = PLANT_STYLE_CROSS; scale = BS / 2 * f->visual_scale; offset = v3f(0, 0, 0); - rotate_degree = 0; + rotate_degree = 0.0f; random_offset_Y = false; face_num = 0; plant_height = 1.0; @@ -988,7 +986,8 @@ void MapblockMeshGenerator::drawPlantlike() break; case CPT2_DEGROTATE: - rotate_degree = n.param2 * 2; + case CPT2_COLORED_DEGROTATE: + rotate_degree = 1.5f * n.getDegRotate(nodedef); break; case CPT2_LEVELED: @@ -1343,6 +1342,7 @@ void MapblockMeshGenerator::drawMeshNode() u8 facedir = 0; scene::IMesh* mesh; bool private_mesh; // as a grab/drop pair is not thread-safe + int degrotate = 0; if (f->param_type_2 == CPT2_FACEDIR || f->param_type_2 == CPT2_COLORED_FACEDIR) { @@ -1354,9 +1354,12 @@ void MapblockMeshGenerator::drawMeshNode() facedir = n.getWallMounted(nodedef); if (!enable_mesh_cache) facedir = wallmounted_to_facedir[facedir]; + } else if (f->param_type_2 == CPT2_DEGROTATE || + f->param_type_2 == CPT2_COLORED_DEGROTATE) { + degrotate = n.getDegRotate(nodedef); } - if (!data->m_smooth_lighting && f->mesh_ptr[facedir]) { + if (!data->m_smooth_lighting && f->mesh_ptr[facedir] && !degrotate) { // use cached meshes private_mesh = false; mesh = f->mesh_ptr[facedir]; @@ -1364,7 +1367,10 @@ void MapblockMeshGenerator::drawMeshNode() // no cache, clone and rotate mesh private_mesh = true; mesh = cloneMesh(f->mesh_ptr[0]); - rotateMeshBy6dFacedir(mesh, facedir); + if (facedir) + rotateMeshBy6dFacedir(mesh, facedir); + else if (degrotate) + rotateMeshXZby(mesh, 1.5f * degrotate); recalculateBoundingBox(mesh); meshmanip->recalculateNormals(mesh, true, false); } else diff --git a/src/client/content_mapblock.h b/src/client/content_mapblock.h index 487d84a07..237cc7847 100644 --- a/src/client/content_mapblock.h +++ b/src/client/content_mapblock.h @@ -139,7 +139,7 @@ public: // plantlike-specific PlantlikeStyle draw_style; v3f offset; - int rotate_degree; + float rotate_degree; bool random_offset_Y; int face_num; float plant_height; @@ -172,7 +172,8 @@ public: void drawNode(); public: - MapblockMeshGenerator(MeshMakeData *input, MeshCollector *output); + MapblockMeshGenerator(MeshMakeData *input, MeshCollector *output, + scene::IMeshManipulator *mm); void generate(); void renderSingle(content_t node, u8 param2 = 0x00); }; diff --git a/src/client/fontengine.cpp b/src/client/fontengine.cpp index a55420846..0382c2f18 100644 --- a/src/client/fontengine.cpp +++ b/src/client/fontengine.cpp @@ -42,8 +42,7 @@ static void font_setting_changed(const std::string &name, void *userdata) } /******************************************************************************/ -FontEngine::FontEngine(Settings* main_settings, gui::IGUIEnvironment* env) : - m_settings(main_settings), +FontEngine::FontEngine(gui::IGUIEnvironment* env) : m_env(env) { @@ -51,34 +50,29 @@ FontEngine::FontEngine(Settings* main_settings, gui::IGUIEnvironment* env) : i = (FontMode) FONT_SIZE_UNSPECIFIED; } - assert(m_settings != NULL); // pre-condition + assert(g_settings != NULL); // pre-condition assert(m_env != NULL); // pre-condition assert(m_env->getSkin() != NULL); // pre-condition readSettings(); - if (m_currentMode == FM_Standard) { - m_settings->registerChangedCallback("font_size", font_setting_changed, NULL); - m_settings->registerChangedCallback("font_bold", font_setting_changed, NULL); - m_settings->registerChangedCallback("font_italic", font_setting_changed, NULL); - m_settings->registerChangedCallback("font_path", font_setting_changed, NULL); - m_settings->registerChangedCallback("font_path_bold", font_setting_changed, NULL); - m_settings->registerChangedCallback("font_path_italic", font_setting_changed, NULL); - m_settings->registerChangedCallback("font_path_bolditalic", font_setting_changed, NULL); - m_settings->registerChangedCallback("font_shadow", font_setting_changed, NULL); - m_settings->registerChangedCallback("font_shadow_alpha", font_setting_changed, NULL); - } - else if (m_currentMode == FM_Fallback) { - m_settings->registerChangedCallback("fallback_font_size", font_setting_changed, NULL); - m_settings->registerChangedCallback("fallback_font_path", font_setting_changed, NULL); - m_settings->registerChangedCallback("fallback_font_shadow", font_setting_changed, NULL); - m_settings->registerChangedCallback("fallback_font_shadow_alpha", font_setting_changed, NULL); + if (m_currentMode != FM_Simple) { + g_settings->registerChangedCallback("font_size", font_setting_changed, NULL); + g_settings->registerChangedCallback("font_bold", font_setting_changed, NULL); + g_settings->registerChangedCallback("font_italic", font_setting_changed, NULL); + g_settings->registerChangedCallback("font_path", font_setting_changed, NULL); + g_settings->registerChangedCallback("font_path_bold", font_setting_changed, NULL); + g_settings->registerChangedCallback("font_path_italic", font_setting_changed, NULL); + g_settings->registerChangedCallback("font_path_bolditalic", font_setting_changed, NULL); + g_settings->registerChangedCallback("font_shadow", font_setting_changed, NULL); + g_settings->registerChangedCallback("font_shadow_alpha", font_setting_changed, NULL); + g_settings->registerChangedCallback("fallback_font_path", font_setting_changed, NULL); } - m_settings->registerChangedCallback("mono_font_path", font_setting_changed, NULL); - m_settings->registerChangedCallback("mono_font_size", font_setting_changed, NULL); - m_settings->registerChangedCallback("screen_dpi", font_setting_changed, NULL); - m_settings->registerChangedCallback("gui_scaling", font_setting_changed, NULL); + g_settings->registerChangedCallback("mono_font_path", font_setting_changed, NULL); + g_settings->registerChangedCallback("mono_font_size", font_setting_changed, NULL); + g_settings->registerChangedCallback("screen_dpi", font_setting_changed, NULL); + g_settings->registerChangedCallback("gui_scaling", font_setting_changed, NULL); } /******************************************************************************/ @@ -103,6 +97,11 @@ void FontEngine::cleanCache() /******************************************************************************/ irr::gui::IGUIFont *FontEngine::getFont(FontSpec spec) { + return getFont(spec, false); +} + +irr::gui::IGUIFont *FontEngine::getFont(FontSpec spec, bool may_fail) +{ if (spec.mode == FM_Unspecified) { spec.mode = m_currentMode; } else if (m_currentMode == FM_Simple) { @@ -113,6 +112,10 @@ irr::gui::IGUIFont *FontEngine::getFont(FontSpec spec) // Support for those could be added, but who cares? spec.bold = false; spec.italic = false; + } else if (spec.mode == _FM_Fallback) { + // Fallback font doesn't support these either + spec.bold = false; + spec.italic = false; } // Fallback to default size @@ -131,6 +134,13 @@ irr::gui::IGUIFont *FontEngine::getFont(FontSpec spec) else font = initFont(spec); + if (!font && !may_fail) { + errorstream << "Minetest cannot continue without a valid font. " + "Please correct the 'font_path' setting or install the font " + "file in the proper location." << std::endl; + abort(); + } + m_font_cache[spec.getHash()][spec.size] = font; return font; @@ -205,30 +215,19 @@ unsigned int FontEngine::getFontSize(FontMode mode) void FontEngine::readSettings() { if (USE_FREETYPE && g_settings->getBool("freetype")) { - m_default_size[FM_Standard] = m_settings->getU16("font_size"); - m_default_size[FM_Fallback] = m_settings->getU16("fallback_font_size"); - m_default_size[FM_Mono] = m_settings->getU16("mono_font_size"); - - /*~ DO NOT TRANSLATE THIS LITERALLY! - This is a special string. Put either "no" or "yes" - into the translation field (literally). - Choose "yes" if the language requires use of the fallback - font, "no" otherwise. - The fallback font is (normally) required for languages with - non-Latin script, like Chinese. - When in doubt, test your translation. */ - m_currentMode = is_yes(gettext("needs_fallback_font")) ? - FM_Fallback : FM_Standard; - - m_default_bold = m_settings->getBool("font_bold"); - m_default_italic = m_settings->getBool("font_italic"); + m_default_size[FM_Standard] = g_settings->getU16("font_size"); + m_default_size[_FM_Fallback] = g_settings->getU16("font_size"); + m_default_size[FM_Mono] = g_settings->getU16("mono_font_size"); + + m_default_bold = g_settings->getBool("font_bold"); + m_default_italic = g_settings->getBool("font_italic"); } else { m_currentMode = FM_Simple; } - m_default_size[FM_Simple] = m_settings->getU16("font_size"); - m_default_size[FM_SimpleMono] = m_settings->getU16("mono_font_size"); + m_default_size[FM_Simple] = g_settings->getU16("font_size"); + m_default_size[FM_SimpleMono] = g_settings->getU16("mono_font_size"); cleanCache(); updateFontCache(); @@ -244,7 +243,7 @@ void FontEngine::updateSkin() m_env->getSkin()->setFont(font); else errorstream << "FontEngine: Default font file: " << - "\n\t\"" << m_settings->get("font_path") << "\"" << + "\n\t\"" << g_settings->get("font_path") << "\"" << "\n\trequired for current screen configuration was not found" << " or was invalid file format." << "\n\tUsing irrlicht default font." << std::endl; @@ -272,18 +271,8 @@ gui::IGUIFont *FontEngine::initFont(const FontSpec &spec) assert(spec.size != FONT_SIZE_UNSPECIFIED); std::string setting_prefix = ""; - - switch (spec.mode) { - case FM_Fallback: - setting_prefix = "fallback_"; - break; - case FM_Mono: - case FM_SimpleMono: - setting_prefix = "mono_"; - break; - default: - break; - } + if (spec.mode == FM_Mono) + setting_prefix = "mono_"; std::string setting_suffix = ""; if (spec.bold) @@ -292,7 +281,7 @@ gui::IGUIFont *FontEngine::initFont(const FontSpec &spec) setting_suffix.append("_italic"); u32 size = std::floor(RenderingEngine::getDisplayDensity() * - m_settings->getFloat("gui_scaling") * spec.size); + g_settings->getFloat("gui_scaling") * spec.size); if (size == 0) { errorstream << "FontEngine: attempt to use font size 0" << std::endl; @@ -306,38 +295,41 @@ gui::IGUIFont *FontEngine::initFont(const FontSpec &spec) g_settings->getU16NoEx(setting_prefix + "font_shadow_alpha", font_shadow_alpha); - std::string wanted_font_path; - wanted_font_path = g_settings->get(setting_prefix + "font_path" + setting_suffix); + std::string path_setting; + if (spec.mode == _FM_Fallback) + path_setting = "fallback_font_path"; + else + path_setting = setting_prefix + "font_path" + setting_suffix; std::string fallback_settings[] = { - wanted_font_path, - m_settings->get("fallback_font_path"), - m_settings->getDefault(setting_prefix + "font_path") + g_settings->get(path_setting), + Settings::getLayer(SL_DEFAULTS)->get(path_setting) }; #if USE_FREETYPE for (const std::string &font_path : fallback_settings) { - irr::gui::IGUIFont *font = gui::CGUITTFont::createTTFont(m_env, + gui::CGUITTFont *font = gui::CGUITTFont::createTTFont(m_env, font_path.c_str(), size, true, true, font_shadow, font_shadow_alpha); - if (font) - return font; - - errorstream << "FontEngine: Cannot load '" << font_path << + if (!font) { + errorstream << "FontEngine: Cannot load '" << font_path << "'. Trying to fall back to another path." << std::endl; - } - + continue; + } - // give up - errorstream << "minetest can not continue without a valid font. " - "Please correct the 'font_path' setting or install the font " - "file in the proper location" << std::endl; + if (spec.mode != _FM_Fallback) { + FontSpec spec2(spec); + spec2.mode = _FM_Fallback; + font->setFallback(getFont(spec2, true)); + } + return font; + } #else - errorstream << "FontEngine: Tried to load freetype fonts but Minetest was" - " not compiled with that library." << std::endl; + errorstream << "FontEngine: Tried to load TTF font but Minetest was" + " compiled without Freetype." << std::endl; #endif - abort(); + return nullptr; } /** initialize a font without freetype */ @@ -346,7 +338,7 @@ gui::IGUIFont *FontEngine::initSimpleFont(const FontSpec &spec) assert(spec.mode == FM_Simple || spec.mode == FM_SimpleMono); assert(spec.size != FONT_SIZE_UNSPECIFIED); - const std::string &font_path = m_settings->get( + const std::string &font_path = g_settings->get( (spec.mode == FM_SimpleMono) ? "mono_font_path" : "font_path"); size_t pos_dot = font_path.find_last_of('.'); @@ -364,7 +356,7 @@ gui::IGUIFont *FontEngine::initSimpleFont(const FontSpec &spec) u32 size = std::floor( RenderingEngine::getDisplayDensity() * - m_settings->getFloat("gui_scaling") * + g_settings->getFloat("gui_scaling") * spec.size); irr::gui::IGUIFont *font = nullptr; diff --git a/src/client/fontengine.h b/src/client/fontengine.h index c6efa0df4..3d389ea48 100644 --- a/src/client/fontengine.h +++ b/src/client/fontengine.h @@ -22,6 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <map> #include <vector> #include "util/basic_macros.h" +#include "irrlichttypes.h" #include <IGUIFont.h> #include <IGUISkin.h> #include <IGUIEnvironment.h> @@ -32,7 +33,7 @@ with this program; if not, write to the Free Software Foundation, Inc., enum FontMode : u8 { FM_Standard = 0, FM_Mono, - FM_Fallback, + _FM_Fallback, // do not use directly FM_Simple, FM_SimpleMono, FM_MaxMode, @@ -46,7 +47,7 @@ struct FontSpec { bold(bold), italic(italic) {} - u16 getHash() + u16 getHash() const { return (mode << 2) | (static_cast<u8>(bold) << 1) | static_cast<u8>(italic); } @@ -61,7 +62,7 @@ class FontEngine { public: - FontEngine(Settings* main_settings, gui::IGUIEnvironment* env); + FontEngine(gui::IGUIEnvironment* env); ~FontEngine(); @@ -127,17 +128,16 @@ public: /** get font size for a specific mode */ unsigned int getFontSize(FontMode mode); - /** initialize font engine */ - void initialize(Settings* main_settings, gui::IGUIEnvironment* env); - /** update internal parameters from settings */ void readSettings(); private: + irr::gui::IGUIFont *getFont(FontSpec spec, bool may_fail); + /** update content of font cache in case of a setting change made it invalid */ void updateFontCache(); - /** initialize a new font */ + /** initialize a new TTF font */ gui::IGUIFont *initFont(const FontSpec &spec); /** initialize a font without freetype */ @@ -149,9 +149,6 @@ private: /** clean cache */ void cleanCache(); - /** pointer to settings for registering callbacks or reading config */ - Settings* m_settings = nullptr; - /** pointer to irrlicht gui environment */ gui::IGUIEnvironment* m_env = nullptr; diff --git a/src/client/game.cpp b/src/client/game.cpp index 10c3a7ceb..5bfe55e66 100644 --- a/src/client/game.cpp +++ b/src/client/game.cpp @@ -68,6 +68,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/pointedthing.h" #include "util/quicktune_shortcutter.h" #include "irrlicht_changes/static_text.h" +#include "irr_ptr.h" #include "version.h" #include "script/scripting_client.h" #include "hud.h" @@ -152,7 +153,7 @@ Game::~Game() delete itemdef_manager; delete draw_control; - extendedResourceCleanup(); + clearTextureNameCache(); g_settings->deregisterChangedCallback("doubletap_jump", &settingChangedCallback, this); @@ -190,6 +191,7 @@ Game::~Game() bool Game::startup(bool *kill, InputHandler *input, + RenderingEngine *rendering_engine, const GameStartData &start_data, std::string &error_message, bool *reconnect, @@ -197,21 +199,21 @@ bool Game::startup(bool *kill, { // "cache" - this->device = RenderingEngine::get_raw_device(); + m_rendering_engine = rendering_engine; + device = m_rendering_engine->get_raw_device(); this->kill = kill; this->error_message = &error_message; - this->reconnect_requested = reconnect; + reconnect_requested = reconnect; this->input = input; this->chat_backend = chat_backend; - this->simple_singleplayer_mode = start_data.isSinglePlayer(); + simple_singleplayer_mode = start_data.isSinglePlayer(); input->keycache.populate(); driver = device->getVideoDriver(); - smgr = RenderingEngine::get_scene_manager(); + smgr = m_rendering_engine->get_scene_manager(); - RenderingEngine::get_scene_manager()->getParameters()-> - setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true); + smgr->getParameters()->setAttribute(scene::OBJ_LOADER_IGNORE_MATERIAL_FILES, true); // Reinit runData runData = GameRunData(); @@ -232,7 +234,7 @@ bool Game::startup(bool *kill, if (!createClient(start_data)) return false; - RenderingEngine::initialize(client, hud); + m_rendering_engine->initialize(client, hud); return true; } @@ -249,7 +251,7 @@ void Game::run() Profiler::GraphValues dummyvalues; g_profiler->graphGet(dummyvalues); - draw_times.last_time = RenderingEngine::get_timer_time(); + draw_times.last_time = m_rendering_engine->get_timer_time(); set_light_table(g_settings->getFloat("display_gamma")); @@ -261,12 +263,12 @@ void Game::run() irr::core::dimension2d<u32> previous_screen_size(g_settings->getU16("screen_w"), g_settings->getU16("screen_h")); - while (RenderingEngine::run() + while (m_rendering_engine->run() && !(*kill || g_gamecallback->shutdown_requested || (server && server->isShutdownRequested()))) { const irr::core::dimension2d<u32> ¤t_screen_size = - RenderingEngine::get_video_driver()->getScreenSize(); + m_rendering_engine->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 @@ -279,7 +281,7 @@ void Game::run() } // Calculate dtime = - // RenderingEngine::run() from this iteration + // m_rendering_engine->run() from this iteration // + Sleep time until the wanted FPS are reached limitFps(&draw_times, &dtime); @@ -328,7 +330,7 @@ void Game::run() void Game::shutdown() { - RenderingEngine::finalize(); + m_rendering_engine->finalize(); #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8 if (g_settings->get("3d_mode") == "pageflip") { driver->setRenderTarget(irr::video::ERT_STEREO_BOTH_BUFFERS); @@ -487,7 +489,7 @@ bool Game::createClient(const GameStartData &start_data) { showOverlayMessage(N_("Creating client..."), 0, 10); - draw_control = new MapDrawControl; + draw_control = new MapDrawControl(); if (!draw_control) return false; @@ -528,7 +530,7 @@ bool Game::createClient(const GameStartData &start_data) /* Camera */ - camera = new Camera(*draw_control, client); + camera = new Camera(*draw_control, client, m_rendering_engine); if (!camera->successfullyCreated(*error_message)) return false; client->setCamera(camera); @@ -540,7 +542,7 @@ bool Game::createClient(const GameStartData &start_data) /* Skybox */ - sky = new Sky(-1, texture_src, shader_src); + sky = new Sky(-1, m_rendering_engine, texture_src, shader_src); scsf->setSky(sky); skybox = NULL; // This is used/set later on in the main run loop @@ -562,16 +564,28 @@ bool Game::createClient(const GameStartData &start_data) std::wstring str = utf8_to_wide(PROJECT_NAME_C); str += L" "; str += utf8_to_wide(g_version_hash); + { + const wchar_t *text = nullptr; + if (simple_singleplayer_mode) + text = wgettext("Singleplayer"); + else + text = wgettext("Multiplayer"); + str += L" ["; + str += text; + str += L"]"; + delete text; + } str += L" ["; str += L"Minetest Hackclient"; str += L"]"; + device->setWindowCaption(str.c_str()); LocalPlayer *player = client->getEnv().getLocalPlayer(); player->hurt_tilt_timer = 0; player->hurt_tilt_strength = 0; - hud = new Hud(guienv, client, player, &player->inventory); + hud = new Hud(client, player, &player->inventory); mapper = client->getMinimap(); @@ -662,7 +676,7 @@ bool Game::connectToServer(const GameStartData &start_data, start_data.password, start_data.address, *draw_control, texture_src, shader_src, itemdef_manager, nodedef_manager, sound, eventmgr, - connect_address.isIPv6(), m_game_ui.get()); + m_rendering_engine, connect_address.isIPv6(), m_game_ui.get()); client->m_simple_singleplayer_mode = simple_singleplayer_mode; @@ -684,9 +698,9 @@ bool Game::connectToServer(const GameStartData &start_data, f32 dtime; f32 wait_time = 0; // in seconds - fps_control.last_time = RenderingEngine::get_timer_time(); + fps_control.last_time = m_rendering_engine->get_timer_time(); - while (RenderingEngine::run()) { + while (m_rendering_engine->run()) { limitFps(&fps_control, &dtime); @@ -723,7 +737,7 @@ bool Game::connectToServer(const GameStartData &start_data, if (client->m_is_registration_confirmation_state) { if (registration_confirmation_shown) { // Keep drawing the GUI - RenderingEngine::draw_menu_scene(guienv, dtime, true); + m_rendering_engine->draw_menu_scene(guienv, dtime, true); } else { registration_confirmation_shown = true; (new GUIConfirmRegistration(guienv, guienv->getRootGUIElement(), -1, @@ -733,7 +747,7 @@ bool Game::connectToServer(const GameStartData &start_data, } else { wait_time += dtime; // Only time out if we aren't waiting for the server we started - if (!start_data.isSinglePlayer() && wait_time > 10) { + if (!start_data.address.empty() && wait_time > 10) { *error_message = "Connection timed out."; errorstream << *error_message << std::endl; break; @@ -759,9 +773,9 @@ bool Game::getServerContent(bool *aborted) FpsControl fps_control = { 0 }; f32 dtime; // in seconds - fps_control.last_time = RenderingEngine::get_timer_time(); + fps_control.last_time = m_rendering_engine->get_timer_time(); - while (RenderingEngine::run()) { + while (m_rendering_engine->run()) { limitFps(&fps_control, &dtime); @@ -799,13 +813,13 @@ bool Game::getServerContent(bool *aborted) if (!client->itemdefReceived()) { const wchar_t *text = wgettext("Item definitions..."); progress = 25; - RenderingEngine::draw_load_screen(text, guienv, texture_src, + m_rendering_engine->draw_load_screen(text, guienv, texture_src, dtime, progress); delete[] text; } else if (!client->nodedefReceived()) { const wchar_t *text = wgettext("Node definitions..."); progress = 30; - RenderingEngine::draw_load_screen(text, guienv, texture_src, + m_rendering_engine->draw_load_screen(text, guienv, texture_src, dtime, progress); delete[] text; } else { @@ -832,7 +846,7 @@ bool Game::getServerContent(bool *aborted) } progress = 30 + client->mediaReceiveProgress() * 35 + 0.5; - RenderingEngine::draw_load_screen(utf8_to_wide(message.str()), guienv, + m_rendering_engine->draw_load_screen(utf8_to_wide(message.str()), guienv, texture_src, dtime, progress); } } @@ -1149,6 +1163,8 @@ void Game::processKeyInput() toggleCinematic(); } else if (wasKeyDown(KeyType::SCREENSHOT)) { client->makeScreenshot(); + } else if (wasKeyDown(KeyType::TOGGLE_BLOCK_BOUNDS)) { + hud->toggleBlockBounds(); } else if (wasKeyDown(KeyType::TOGGLE_HUD)) { m_game_ui->toggleHud(); } else if (wasKeyDown(KeyType::MINIMAP)) { @@ -1263,8 +1279,8 @@ void Game::openInventory() || !client->getScript()->on_inventory_open(fs_src->m_client->getInventory(inventoryloc))) { TextDest *txt_dst = new TextDestPlayerInventory(client); auto *&formspec = m_game_ui->updateFormspec(""); - GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src, - txt_dst, client->getFormspecPrepend(), sound); + GUIFormSpecMenu::create(formspec, client, m_rendering_engine->get_gui_env(), + &input->joystick, fs_src, txt_dst, client->getFormspecPrepend(), sound); formspec->setFormSpec(fs_src->getForm(), inventoryloc); } @@ -1604,7 +1620,6 @@ void Game::checkZoomEnabled() m_game_ui->showTranslatedStatusText("Zoom currently disabled by game or mod"); } - void Game::updateCameraDirection(CameraOrientation *cam, float dtime) { if ((device->isWindowActive() && device->isWindowFocused() @@ -1640,6 +1655,18 @@ void Game::updateCameraDirection(CameraOrientation *cam, float dtime) } } +// Get the factor to multiply with sensitivity to get the same mouse/joystick +// responsiveness independently of FOV. +f32 Game::getSensitivityScaleFactor() const +{ + f32 fov_y = client->getCamera()->getFovY(); + + // Multiply by a constant such that it becomes 1.0 at 72 degree FOV and + // 16:9 aspect ratio to minimize disruption of existing sensitivity + // settings. + return tan(fov_y / 2.0f) * 1.3763818698f; +} + void Game::updateCameraOrientation(CameraOrientation *cam, float dtime) { #ifdef HAVE_TOUCHSCREENGUI @@ -1655,8 +1682,9 @@ void Game::updateCameraOrientation(CameraOrientation *cam, float dtime) dist.Y = -dist.Y; } - cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity; - cam->camera_pitch += dist.Y * m_cache_mouse_sensitivity; + f32 sens_scale = getSensitivityScaleFactor(); + cam->camera_yaw -= dist.X * m_cache_mouse_sensitivity * sens_scale; + cam->camera_pitch += dist.Y * m_cache_mouse_sensitivity * sens_scale; if (dist.X != 0 || dist.Y != 0) input->setMousePos(center.X, center.Y); @@ -1665,7 +1693,8 @@ void Game::updateCameraOrientation(CameraOrientation *cam, float dtime) #endif if (m_cache_enable_joysticks) { - f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime; + f32 sens_scale = getSensitivityScaleFactor(); + f32 c = m_cache_joystick_frustum_sensitivity * (1.f / 32767.f) * dtime * sens_scale; cam->camera_yaw -= input->joystick.getAxisWithoutDead(JA_FRUSTUM_HORIZONTAL) * c; cam->camera_pitch += input->joystick.getAxisWithoutDead(JA_FRUSTUM_VERTICAL) * c; } @@ -1688,7 +1717,7 @@ void Game::updatePlayerControl(const CameraOrientation &cam) input->isKeyDown(KeyType::LEFT), input->isKeyDown(KeyType::RIGHT), isKeyDown(KeyType::JUMP), - isKeyDown(KeyType::SPECIAL1), + isKeyDown(KeyType::AUX1), isKeyDown(KeyType::SNEAK), isKeyDown(KeyType::ZOOM), isKeyDown(KeyType::DIG), @@ -1705,7 +1734,7 @@ void Game::updatePlayerControl(const CameraOrientation &cam) ( (u32)(isKeyDown(KeyType::LEFT) & 0x1) << 2) | ( (u32)(isKeyDown(KeyType::RIGHT) & 0x1) << 3) | ( (u32)(isKeyDown(KeyType::JUMP) & 0x1) << 4) | - ( (u32)(isKeyDown(KeyType::SPECIAL1) & 0x1) << 5) | + ( (u32)(isKeyDown(KeyType::AUX1) & 0x1) << 5) | ( (u32)(isKeyDown(KeyType::SNEAK) & 0x1) << 6) | ( (u32)(isKeyDown(KeyType::DIG) & 0x1) << 7) | ( (u32)(isKeyDown(KeyType::PLACE) & 0x1) << 8) | @@ -1754,6 +1783,9 @@ inline void Game::step(f32 *dtime) if (can_be_and_is_paused) { // This is for a singleplayer server *dtime = 0; // No time passes } else { + if (simple_singleplayer_mode && !paused_animated_nodes.empty()) + resumeAnimation(); + if (server) server->step(*dtime); @@ -1761,6 +1793,33 @@ inline void Game::step(f32 *dtime) } } +static void pauseNodeAnimation(PausedNodesList &paused, scene::ISceneNode *node) { + if (!node) + return; + for (auto &&child: node->getChildren()) + pauseNodeAnimation(paused, child); + if (node->getType() != scene::ESNT_ANIMATED_MESH) + return; + auto animated_node = static_cast<scene::IAnimatedMeshSceneNode *>(node); + float speed = animated_node->getAnimationSpeed(); + if (!speed) + return; + paused.push_back({grab(animated_node), speed}); + animated_node->setAnimationSpeed(0.0f); +} + +void Game::pauseAnimation() +{ + pauseNodeAnimation(paused_animated_nodes, smgr->getRootSceneNode()); +} + +void Game::resumeAnimation() +{ + for (auto &&pair: paused_animated_nodes) + pair.first->setAnimationSpeed(pair.second); + paused_animated_nodes.clear(); +} + const ClientEventHandler Game::clientEventHandler[CLIENTEVENT_MAX] = { {&Game::handleClientEvent_None}, {&Game::handleClientEvent_PlayerDamage}, @@ -1794,14 +1853,18 @@ void Game::handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation // Damage flash and hurt tilt are not used at death if (client->getHP() > 0) { - runData.damage_flash += 95.0f + 3.2f * event->player_damage.amount; - runData.damage_flash = MYMIN(runData.damage_flash, 127.0f); - LocalPlayer *player = client->getEnv().getLocalPlayer(); + f32 hp_max = player->getCAO() ? + player->getCAO()->getProperties()->hp_max : PLAYER_MAX_HP_DEFAULT; + f32 damage_ratio = event->player_damage.amount / hp_max; + + runData.damage_flash += 95.0f + 64.f * damage_ratio; + runData.damage_flash = MYMIN(runData.damage_flash, 127.0f); + player->hurt_tilt_timer = 1.5f; player->hurt_tilt_strength = - rangelim(event->player_damage.amount / 4.0f, 1.0f, 4.0f); + rangelim(damage_ratio * 5.0f, 1.0f, 4.0f); } // Play damage sound @@ -1845,8 +1908,8 @@ void Game::handleClientEvent_ShowFormSpec(ClientEvent *event, CameraOrientation new TextDestPlayerInventory(client, *(event->show_formspec.formname)); auto *&formspec = m_game_ui->updateFormspec(*(event->show_formspec.formname)); - GUIFormSpecMenu::create(formspec, client, &input->joystick, - fs_src, txt_dst, client->getFormspecPrepend(), sound); + GUIFormSpecMenu::create(formspec, client, m_rendering_engine->get_gui_env(), + &input->joystick, fs_src, txt_dst, client->getFormspecPrepend(), sound); } delete event->show_formspec.formspec; @@ -1865,7 +1928,7 @@ void Game::handleClientEvent_ShowLocalFormSpec(ClientEvent *event, CameraOrienta FormspecFormSource *fs_src = new FormspecFormSource(*event->show_formspec.formspec); LocalFormspecHandler *txt_dst = new LocalFormspecHandler(*event->show_formspec.formname, client); - GUIFormSpecMenu::create(m_game_ui->getFormspecGUI(), client, &input->joystick, + GUIFormSpecMenu::create(m_game_ui->getFormspecGUI(), client, m_rendering_engine->get_gui_env(), &input->joystick, fs_src, txt_dst, client->getFormspecPrepend(), sound); } @@ -1883,132 +1946,100 @@ void Game::handleClientEvent_HandleParticleEvent(ClientEvent *event, void Game::handleClientEvent_HudAdd(ClientEvent *event, CameraOrientation *cam) { LocalPlayer *player = client->getEnv().getLocalPlayer(); - auto &hud_server_to_client = client->getHUDTranslationMap(); - u32 server_id = event->hudadd.server_id; + u32 server_id = event->hudadd->server_id; // ignore if we already have a HUD with that ID - auto i = hud_server_to_client.find(server_id); - if (i != hud_server_to_client.end()) { - delete event->hudadd.pos; - delete event->hudadd.name; - delete event->hudadd.scale; - delete event->hudadd.text; - delete event->hudadd.align; - delete event->hudadd.offset; - delete event->hudadd.world_pos; - delete event->hudadd.size; - delete event->hudadd.text2; + auto i = m_hud_server_to_client.find(server_id); + if (i != m_hud_server_to_client.end()) { + delete event->hudadd; return; } HudElement *e = new HudElement; - e->type = (HudElementType)event->hudadd.type; - e->pos = *event->hudadd.pos; - e->name = *event->hudadd.name; - e->scale = *event->hudadd.scale; - e->text = *event->hudadd.text; - e->number = event->hudadd.number; - e->item = event->hudadd.item; - e->dir = event->hudadd.dir; - e->align = *event->hudadd.align; - e->offset = *event->hudadd.offset; - e->world_pos = *event->hudadd.world_pos; - e->size = *event->hudadd.size; - e->z_index = event->hudadd.z_index; - e->text2 = *event->hudadd.text2; - hud_server_to_client[server_id] = player->addHud(e); - - delete event->hudadd.pos; - delete event->hudadd.name; - delete event->hudadd.scale; - delete event->hudadd.text; - delete event->hudadd.align; - delete event->hudadd.offset; - delete event->hudadd.world_pos; - delete event->hudadd.size; - delete event->hudadd.text2; + e->type = static_cast<HudElementType>(event->hudadd->type); + e->pos = event->hudadd->pos; + e->name = event->hudadd->name; + e->scale = event->hudadd->scale; + e->text = event->hudadd->text; + e->number = event->hudadd->number; + e->item = event->hudadd->item; + e->dir = event->hudadd->dir; + e->align = event->hudadd->align; + e->offset = event->hudadd->offset; + e->world_pos = event->hudadd->world_pos; + e->size = event->hudadd->size; + e->z_index = event->hudadd->z_index; + e->text2 = event->hudadd->text2; + m_hud_server_to_client[server_id] = player->addHud(e); + + delete event->hudadd; } void Game::handleClientEvent_HudRemove(ClientEvent *event, CameraOrientation *cam) { LocalPlayer *player = client->getEnv().getLocalPlayer(); - HudElement *e = player->removeHud(event->hudrm.id); - delete e; + + auto i = m_hud_server_to_client.find(event->hudrm.id); + if (i != m_hud_server_to_client.end()) { + HudElement *e = player->removeHud(i->second); + delete e; + m_hud_server_to_client.erase(i); + } + } void Game::handleClientEvent_HudChange(ClientEvent *event, CameraOrientation *cam) { LocalPlayer *player = client->getEnv().getLocalPlayer(); - u32 id = event->hudchange.id; - HudElement *e = player->getHud(id); + HudElement *e = nullptr; + + auto i = m_hud_server_to_client.find(event->hudchange->id); + if (i != m_hud_server_to_client.end()) { + e = player->getHud(i->second); + } - if (e == NULL) { - delete event->hudchange.v3fdata; - delete event->hudchange.v2fdata; - delete event->hudchange.sdata; - delete event->hudchange.v2s32data; + if (e == nullptr) { + delete event->hudchange; return; } - switch (event->hudchange.stat) { - case HUD_STAT_POS: - e->pos = *event->hudchange.v2fdata; - break; +#define CASE_SET(statval, prop, dataprop) \ + case statval: \ + e->prop = event->hudchange->dataprop; \ + break - case HUD_STAT_NAME: - e->name = *event->hudchange.sdata; - break; + switch (event->hudchange->stat) { + CASE_SET(HUD_STAT_POS, pos, v2fdata); - case HUD_STAT_SCALE: - e->scale = *event->hudchange.v2fdata; - break; + CASE_SET(HUD_STAT_NAME, name, sdata); - case HUD_STAT_TEXT: - e->text = *event->hudchange.sdata; - break; + CASE_SET(HUD_STAT_SCALE, scale, v2fdata); - case HUD_STAT_NUMBER: - e->number = event->hudchange.data; - break; + CASE_SET(HUD_STAT_TEXT, text, sdata); - case HUD_STAT_ITEM: - e->item = event->hudchange.data; - break; + CASE_SET(HUD_STAT_NUMBER, number, data); - case HUD_STAT_DIR: - e->dir = event->hudchange.data; - break; + CASE_SET(HUD_STAT_ITEM, item, data); - case HUD_STAT_ALIGN: - e->align = *event->hudchange.v2fdata; - break; + CASE_SET(HUD_STAT_DIR, dir, data); - case HUD_STAT_OFFSET: - e->offset = *event->hudchange.v2fdata; - break; + CASE_SET(HUD_STAT_ALIGN, align, v2fdata); - case HUD_STAT_WORLD_POS: - e->world_pos = *event->hudchange.v3fdata; - break; + CASE_SET(HUD_STAT_OFFSET, offset, v2fdata); - case HUD_STAT_SIZE: - e->size = *event->hudchange.v2s32data; - break; + CASE_SET(HUD_STAT_WORLD_POS, world_pos, v3fdata); - case HUD_STAT_Z_INDEX: - e->z_index = event->hudchange.data; - break; + CASE_SET(HUD_STAT_SIZE, size, v2s32data); - case HUD_STAT_TEXT2: - e->text2 = *event->hudchange.sdata; - break; + CASE_SET(HUD_STAT_Z_INDEX, z_index, data); + + CASE_SET(HUD_STAT_TEXT2, text2, sdata); } - delete event->hudchange.v3fdata; - delete event->hudchange.v2fdata; - delete event->hudchange.sdata; - delete event->hudchange.v2s32data; +#undef CASE_SET + + delete event->hudchange; } void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam) @@ -2063,6 +2094,7 @@ void Game::handleClientEvent_SetSky(ClientEvent *event, CameraOrientation *cam) "custom" ); } + delete event->set_sky; } @@ -2563,9 +2595,10 @@ void Game::handlePointingAtNode(const PointedThing &pointed, bool Game::nodePlacement(const ItemDefinition &selected_def, const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos, - const PointedThing &pointed, const NodeMetadata *meta) + const PointedThing &pointed, const NodeMetadata *meta, bool force) { - std::string prediction = selected_def.node_placement_prediction; + const auto &prediction = selected_def.node_placement_prediction; + const NodeDefManager *nodedef = client->ndef(); ClientMap &map = client->getEnv().getClientMap(); MapNode node; @@ -2579,7 +2612,7 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, // formspec in meta if (meta && !meta->getString("formspec").empty() && !input->isRandom() - && !isKeyDown(KeyType::SNEAK)) { + && !isKeyDown(KeyType::SNEAK) && !force) { // on_rightclick callbacks are called anyway if (nodedef_manager->get(map.getNode(nodepos)).rightclickable) client->interact(INTERACT_PLACE, pointed); @@ -2594,8 +2627,8 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, TextDest *txt_dst = new TextDestNodeMetadata(nodepos, client); auto *&formspec = m_game_ui->updateFormspec(""); - GUIFormSpecMenu::create(formspec, client, &input->joystick, fs_src, - txt_dst, client->getFormspecPrepend(), sound); + GUIFormSpecMenu::create(formspec, client, m_rendering_engine->get_gui_env(), + &input->joystick, fs_src, txt_dst, client->getFormspecPrepend(), sound); formspec->setFormSpec(meta->getString("formspec"), inventoryloc); return false; @@ -2603,7 +2636,7 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, // on_rightclick callback if (prediction.empty() || (nodedef->get(node).rightclickable && - !isKeyDown(KeyType::SNEAK))) { + !isKeyDown(KeyType::SNEAK) && !force)) { // Report to server client->interact(INTERACT_PLACE, pointed); return false; @@ -2635,8 +2668,7 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, if (!found) { errorstream << "Node placement prediction failed for " - << selected_def.name << " (places " - << prediction + << selected_def.name << " (places " << prediction << ") - Name not known" << std::endl; // Handle this as if prediction was empty // Report to server @@ -2647,9 +2679,14 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, const ContentFeatures &predicted_f = nodedef->get(id); // Predict param2 for facedir and wallmounted nodes + // Compare core.item_place_node() for what the server does u8 param2 = 0; - if (predicted_f.param_type_2 == CPT2_WALLMOUNTED || + const u8 place_param2 = selected_def.place_param2; + + if (place_param2) { + param2 = place_param2; + } else if (predicted_f.param_type_2 == CPT2_WALLMOUNTED || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED) { v3s16 dir = nodepos - neighbourpos; @@ -2660,9 +2697,7 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, } else { param2 = dir.Z < 0 ? 5 : 4; } - } - - if (predicted_f.param_type_2 == CPT2_FACEDIR || + } else if (predicted_f.param_type_2 == CPT2_FACEDIR || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR) { v3s16 dir = nodepos - floatToInt(client->getEnv().getLocalPlayer()->getPosition(), BS); @@ -2673,11 +2708,9 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, } } - assert(param2 <= 5); - - //Check attachment if node is in group attached_node - if (((ItemGroupList) predicted_f.groups)["attached_node"] != 0) { - static v3s16 wallmounted_dirs[8] = { + // Check attachment if node is in group attached_node + if (itemgroup_get(predicted_f.groups, "attached_node") != 0) { + const static v3s16 wallmounted_dirs[8] = { v3s16(0, 1, 0), v3s16(0, -1, 0), v3s16(1, 0, 0), @@ -2702,11 +2735,11 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, } // Apply color - if ((predicted_f.param_type_2 == CPT2_COLOR + if (!place_param2 && (predicted_f.param_type_2 == CPT2_COLOR || predicted_f.param_type_2 == CPT2_COLORED_FACEDIR || predicted_f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) { - const std::string &indexstr = selected_item.metadata.getString( - "palette_index", 0); + const auto &indexstr = selected_item.metadata. + getString("palette_index", 0); if (!indexstr.empty()) { s32 index = mystoi(indexstr); if (predicted_f.param_type_2 == CPT2_COLOR) { @@ -2746,11 +2779,10 @@ bool Game::nodePlacement(const ItemDefinition &selected_def, soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed; return false; } - } catch (InvalidPositionException &e) { + } catch (const InvalidPositionException &e) { errorstream << "Node placement prediction failed for " << selected_def.name << " (places " - << prediction - << ") - Position not loaded" << std::endl; + << prediction << ") - Position not loaded" << std::endl; soundmaker->m_player_rightpunch_sound = selected_def.sound_place_failed; return false; } @@ -3158,7 +3190,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, } catch (SettingNotFoundException) { } #endif - RenderingEngine::draw_scene(skycolor, m_game_ui->m_flags.show_hud, + m_rendering_engine->draw_scene(skycolor, m_game_ui->m_flags.show_hud, m_game_ui->m_flags.show_minimap, draw_wield_tool, draw_crosshair); /* @@ -3297,7 +3329,7 @@ inline void Game::limitFps(FpsControl *fps_timings, f32 *dtime) void Game::showOverlayMessage(const char *msg, float dtime, int percent, bool draw_clouds) { const wchar_t *wmsg = wgettext(msg); - RenderingEngine::draw_load_screen(wmsg, guienv, texture_src, dtime, percent, + m_rendering_engine->draw_load_screen(wmsg, guienv, texture_src, dtime, percent, draw_clouds); delete[] wmsg; } @@ -3380,27 +3412,6 @@ bool Game::wasKeyReleased(GameKeyType k) ****************************************************************************/ /****************************************************************************/ -void Game::extendedResourceCleanup() -{ - // Extended resource accounting - infostream << "Irrlicht resources after cleanup:" << std::endl; - infostream << "\tRemaining meshes : " - << RenderingEngine::get_mesh_cache()->getMeshCount() << std::endl; - infostream << "\tRemaining textures : " - << driver->getTextureCount() << std::endl; - - for (unsigned int i = 0; i < driver->getTextureCount(); i++) { - irr::video::ITexture *texture = driver->getTextureByIndex(i); - infostream << "\t\t" << i << ":" << texture->getName().getPath().c_str() - << std::endl; - } - - clearTextureNameCache(); - infostream << "\tRemaining materials: " - << driver-> getMaterialRendererCount() - << " (note: irrlicht doesn't support removing renderers)" << std::endl; -} - void Game::showDeathFormspec() { static std::string formspec_str = @@ -3418,8 +3429,8 @@ void Game::showDeathFormspec() LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_DEATH_SCREEN", client); auto *&formspec = m_game_ui->getFormspecGUI(); - GUIFormSpecMenu::create(formspec, client, &input->joystick, - fs_src, txt_dst, client->getFormspecPrepend(), sound); + GUIFormSpecMenu::create(formspec, client, m_rendering_engine->get_gui_env(), + &input->joystick, fs_src, txt_dst, client->getFormspecPrepend(), sound); formspec->setFocus("btn_respawn"); } @@ -3560,10 +3571,13 @@ void Game::showPauseMenu() LocalFormspecHandler *txt_dst = new LocalFormspecHandler("MT_PAUSE_MENU"); auto *&formspec = m_game_ui->getFormspecGUI(); - GUIFormSpecMenu::create(formspec, client, &input->joystick, - fs_src, txt_dst, client->getFormspecPrepend(), sound); + GUIFormSpecMenu::create(formspec, client, m_rendering_engine->get_gui_env(), + &input->joystick, fs_src, txt_dst, client->getFormspecPrepend(), sound); formspec->setFocus("btn_continue"); formspec->doPause = true; + + if (simple_singleplayer_mode) + pauseAnimation(); } /****************************************************************************/ @@ -3576,6 +3590,7 @@ Game *g_game; void the_game(bool *kill, InputHandler *input, + RenderingEngine *rendering_engine, const GameStartData &start_data, std::string &error_message, ChatBackend &chat_backend, @@ -3592,8 +3607,8 @@ void the_game(bool *kill, try { - if (game.startup(kill, input, start_data, error_message, - reconnect_requested, &chat_backend)) { + if (game.startup(kill, input, rendering_engine, start_data, + error_message, reconnect_requested, &chat_backend)) { game.run(); } diff --git a/src/client/game.h b/src/client/game.h index fd93ef82d..8197b9a9b 100644 --- a/src/client/game.h +++ b/src/client/game.h @@ -68,6 +68,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/pointedthing.h" #include "util/quicktune_shortcutter.h" #include "irrlicht_changes/static_text.h" +#include "irr_ptr.h" #include "version.h" #include "script/scripting_client.h" #include "hud.h" @@ -75,7 +76,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <string> class InputHandler; -class ChatBackend; /* to avoid having to include chat.h */ +class ChatBackend; +class RenderingEngine; struct SubgameSpec; struct GameStartData; @@ -188,13 +190,7 @@ struct LocalFormspecHandler : public TextDest return; } - if (fields.find("quit") != fields.end()) { - return; - } - - if (fields.find("btn_continue") != fields.end()) { - return; - } + return; } if (m_formname == "MT_DEATH_SCREEN") { @@ -422,12 +418,7 @@ public: }; -// before 1.8 there isn't a "integer interface", only float -#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8) -typedef f32 SamplerLayer_t; -#else typedef s32 SamplerLayer_t; -#endif class GameGlobalShaderConstantSetter : public IShaderConstantSetter @@ -448,6 +439,7 @@ class GameGlobalShaderConstantSetter : public IShaderConstantSetter CachedPixelShaderSetting<float, 3> m_camera_offset_pixel; CachedPixelShaderSetting<float, 3> m_camera_offset_vertex; CachedPixelShaderSetting<SamplerLayer_t> m_base_texture; + CachedPixelShaderSetting<SamplerLayer_t> m_normal_texture; Client *m_client; public: @@ -481,6 +473,7 @@ public: m_camera_offset_pixel("cameraOffset"), m_camera_offset_vertex("cameraOffset"), m_base_texture("baseTexture"), + m_normal_texture("normalTexture"), m_client(client) { g_settings->registerChangedCallback("enable_fog", settingsCallback, this); @@ -533,43 +526,26 @@ public: float eye_position_array[3]; v3f epos = m_client->getEnv().getLocalPlayer()->getEyePosition(); -#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8) - eye_position_array[0] = epos.X; - eye_position_array[1] = epos.Y; - eye_position_array[2] = epos.Z; -#else epos.getAs3Values(eye_position_array); -#endif m_eye_position_pixel.set(eye_position_array, services); m_eye_position_vertex.set(eye_position_array, services); if (m_client->getMinimap()) { float minimap_yaw_array[3]; v3f minimap_yaw = m_client->getMinimap()->getYawVec(); -#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8) - minimap_yaw_array[0] = minimap_yaw.X; - minimap_yaw_array[1] = minimap_yaw.Y; - minimap_yaw_array[2] = minimap_yaw.Z; -#else minimap_yaw.getAs3Values(minimap_yaw_array); -#endif m_minimap_yaw.set(minimap_yaw_array, services); } float camera_offset_array[3]; v3f offset = intToFloat(m_client->getCamera()->getOffset(), BS); -#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8) - camera_offset_array[0] = offset.X; - camera_offset_array[1] = offset.Y; - camera_offset_array[2] = offset.Z; -#else offset.getAs3Values(camera_offset_array); -#endif m_camera_offset_pixel.set(camera_offset_array, services); m_camera_offset_vertex.set(camera_offset_array, services); - SamplerLayer_t base_tex = 0; + SamplerLayer_t base_tex = 0, normal_tex = 1; m_base_texture.set(&base_tex, services); + m_normal_texture.set(&normal_tex, services); } }; @@ -666,6 +642,8 @@ struct ClientEventHandler void (Game::*handler)(ClientEvent *, CameraOrientation *); }; +using PausedNodesList = std::vector<std::pair<irr_ptr<scene::IAnimatedMeshSceneNode>, float>>; + class Game { public: Game(); @@ -673,6 +651,7 @@ public: bool startup(bool *kill, InputHandler *input, + RenderingEngine *rendering_engine, const GameStartData &game_params, std::string &error_message, bool *reconnect, @@ -682,8 +661,6 @@ public: void run(); void shutdown(); - void extendedResourceCleanup(); - // Basic initialisation bool init(const std::string &map_dir, const std::string &address, u16 port, const SubgameSpec &gamespec); @@ -804,6 +781,9 @@ public: void showDeathFormspec(); void showPauseMenu(); + void pauseAnimation(); + void resumeAnimation(); + // ClientEvent handlers void handleClientEvent_None(ClientEvent *event, CameraOrientation *cam); void handleClientEvent_PlayerDamage(ClientEvent *event, CameraOrientation *cam); @@ -828,9 +808,11 @@ public: bool nodePlacement(const ItemDefinition &selected_def, const ItemStack &selected_item, const v3s16 &nodepos, const v3s16 &neighbourpos, const PointedThing &pointed, - const NodeMetadata *meta); + const NodeMetadata *meta, bool force = false); static const ClientEventHandler clientEventHandler[CLIENTEVENT_MAX]; + f32 getSensitivityScaleFactor() const; + InputHandler *input = nullptr; Client *client = nullptr; @@ -865,6 +847,9 @@ public: Hud *hud = nullptr; Minimap *mapper = nullptr; + // Map server hud ids to client hud ids + std::unordered_map<u32, u32> m_hud_server_to_client; + GameRunData runData; Flags m_flags; @@ -873,12 +858,14 @@ public: these items (e.g. device) */ IrrlichtDevice *device; + RenderingEngine *m_rendering_engine; video::IVideoDriver *driver; scene::ISceneManager *smgr; bool *kill; std::string *error_message; bool *reconnect_requested; scene::ISceneNode *skybox; + PausedNodesList paused_animated_nodes; bool simple_singleplayer_mode; /* End 'cache' */ @@ -927,6 +914,7 @@ extern Game *g_game; void the_game(bool *kill, InputHandler *input, + RenderingEngine *rendering_engine, const GameStartData &start_data, std::string &error_message, ChatBackend &chat_backend, diff --git a/src/client/gameui.cpp b/src/client/gameui.cpp index 0c1da3915..c97ae93b8 100644 --- a/src/client/gameui.cpp +++ b/src/client/gameui.cpp @@ -55,7 +55,7 @@ void GameUI::init() { m_guitext_coords = gui::StaticText::add(guienv, L"", core::rect<s32>(0, 0, 0, 0), false, false, guiroot); - + // First line of debug text m_guitext = gui::StaticText::add(guienv, utf8_to_wide(PROJECT_NAME_C).c_str(), core::rect<s32>(0, 0, 0, 0), false, false, guiroot); @@ -102,7 +102,8 @@ void GameUI::update(const RunStats &stats, Client *client, MapDrawControl *draw_ { LocalPlayer *player = client->getEnv().getLocalPlayer(); v3f player_position = player->getPosition(); - v2u32 screensize = RenderingEngine::get_instance()->getWindowSize(); + + v2u32 screensize = RenderingEngine::getWindowSize(); bool show_coords = g_settings->getBool("coords"); @@ -115,7 +116,7 @@ void GameUI::update(const RunStats &stats, Client *client, MapDrawControl *draw_ setStaticText(m_guitext_coords, utf8_to_wide(os.str()).c_str()); m_guitext_coords->setRelativePosition(core::rect<s32>(5, screensize.Y - 5 - g_fontengine->getTextHeight(), screensize.X, screensize.Y)); } - + m_guitext_coords->setVisible(show_coords); if (m_flags.show_debug) { @@ -238,9 +239,9 @@ void GameUI::setChatText(const EnrichedString &chat_text, u32 recent_chat_count) { // Update gui element size and position - - const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); - + + const v2u32 &window_size = RenderingEngine::getWindowSize(); + s32 chat_y = window_size.Y - 150 - m_guitext_chat->getTextHeight(); if (m_flags.show_debug) @@ -276,7 +277,7 @@ void GameUI::updateProfiler() core::position2di upper_left(6, 50); core::position2di lower_right = upper_left; lower_right.X += size.Width + 10; - lower_right.Y += size.Height; + lower_right.Y += size.Height; m_guitext_profiler->setRelativePosition(core::rect<s32>(upper_left, lower_right)); } diff --git a/src/client/gameui.h b/src/client/gameui.h index 8a1b5650d..f04fd97b8 100644 --- a/src/client/gameui.h +++ b/src/client/gameui.h @@ -20,6 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once +#include "irrlichttypes.h" #include <IGUIEnvironment.h> #include "gui/guiFormSpecMenu.h" #include "util/enriched_string.h" diff --git a/src/client/guiscalingfilter.cpp b/src/client/guiscalingfilter.cpp index 406c096e6..232219237 100644 --- a/src/client/guiscalingfilter.cpp +++ b/src/client/guiscalingfilter.cpp @@ -23,7 +23,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/numeric.h" #include <cstdio> #include "client/renderingengine.h" -#include "client/tile.h" // hasNPotSupport() /* Maintain a static cache to store the images that correspond to textures * in a format that's manipulable by code. Some platforms exhibit issues @@ -102,7 +101,7 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, if (!g_settings->getBool("gui_scaling_filter_txr2img")) return src; srcimg = driver->createImageFromData(src->getColorFormat(), - src->getSize(), src->lock(), false); + src->getSize(), src->lock(video::ETLM_READ_ONLY), false); src->unlock(); g_imgCache[origname] = srcimg; } @@ -117,7 +116,7 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, #if ENABLE_GLES // Some platforms are picky about textures being powers of 2, so expand // the image dimensions to the next power of 2, if necessary. - if (!hasNPotSupport()) { + if (!driver->queryFeature(video::EVDF_TEXTURE_NPOT)) { video::IImage *po2img = driver->createImage(src->getColorFormat(), core::dimension2d<u32>(npot2((u32)destrect.getWidth()), npot2((u32)destrect.getHeight()))); @@ -129,7 +128,7 @@ video::ITexture *guiScalingResizeCached(video::IVideoDriver *driver, #endif // Convert the scaled image back into a texture. - scaled = driver->addTexture(scalename, destimg, NULL); + scaled = driver->addTexture(scalename, destimg); destimg->drop(); g_txrCache[scalename] = scaled; diff --git a/src/client/hud.cpp b/src/client/hud.cpp index e956c2738..391af0995 100644 --- a/src/client/hud.cpp +++ b/src/client/hud.cpp @@ -45,11 +45,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #define OBJECT_CROSSHAIR_LINE_SIZE 8 #define CROSSHAIR_LINE_SIZE 10 -Hud::Hud(gui::IGUIEnvironment *guienv, Client *client, LocalPlayer *player, +Hud::Hud(Client *client, LocalPlayer *player, Inventory *inventory) { driver = RenderingEngine::get_video_driver(); - this->guienv = guienv; this->client = client; this->player = player; this->inventory = inventory; @@ -149,7 +148,7 @@ void Hud::drawItem(const ItemStack &item, const core::rect<s32>& rect, bool selected) { if (selected) { - /* draw hihlighting around selected item */ + /* draw highlighting around selected item */ if (use_hotbar_selected_image) { core::rect<s32> imgrect2 = rect; imgrect2.UpperLeftCorner.X -= (m_padding*2); @@ -315,7 +314,7 @@ bool Hud::calculateScreenPos(const v3s16 &camera_offset, HudElement *e, v2s32 *p { v3f w_pos = e->world_pos * BS; scene::ICameraSceneNode* camera = - RenderingEngine::get_scene_manager()->getActiveCamera(); + client->getSceneManager()->getActiveCamera(); w_pos -= intToFloat(camera_offset, BS); core::matrix4 trans = camera->getProjectionMatrix(); trans *= camera->getViewMatrix(); @@ -336,22 +335,22 @@ void Hud::drawLuaElements(const v3s16 &camera_offset) irr::gui::IGUIFont* font = g_fontengine->getFont(); // Reorder elements by z_index - std::vector<size_t> ids; + std::vector<HudElement*> elems; + elems.reserve(player->maxHudId()); for (size_t i = 0; i != player->maxHudId(); i++) { HudElement *e = player->getHud(i); if (!e) continue; - auto it = ids.begin(); - while (it != ids.end() && player->getHud(*it)->z_index <= e->z_index) + auto it = elems.begin(); + while (it != elems.end() && (*it)->z_index <= e->z_index) ++it; - ids.insert(it, i); + elems.insert(it, e); } - for (size_t i : ids) { - HudElement *e = player->getHud(i); + for (HudElement *e : elems) { v2s32 pos(floor(e->pos.X * (float) m_screensize.X + 0.5), floor(e->pos.Y * (float) m_screensize.Y + 0.5)); @@ -475,7 +474,7 @@ void Hud::drawLuaElements(const v3s16 &camera_offset) // Angle according to camera view v3f fore(0.f, 0.f, 1.f); - scene::ICameraSceneNode *cam = RenderingEngine::get_scene_manager()->getActiveCamera(); + scene::ICameraSceneNode *cam = client->getSceneManager()->getActiveCamera(); cam->getAbsoluteTransformation().rotateVect(fore); int angle = - fore.getHorizontalAngle().Y; @@ -522,8 +521,8 @@ void Hud::drawLuaElements(const v3s16 &camera_offset) client->getMinimap()->drawMinimap(rect); break; } default: - infostream << "Hud::drawLuaElements: ignoring drawform " << e->type << - " of hud element ID " << i << " due to unrecognized type" << std::endl; + infostream << "Hud::drawLuaElements: ignoring drawform " << e->type + << " due to unrecognized type" << std::endl; } } } @@ -571,8 +570,6 @@ void Hud::drawCompassTranslate(HudElement *e, video::ITexture *texture, void Hud::drawCompassRotate(HudElement *e, video::ITexture *texture, const core::rect<s32> &rect, int angle) { - core::dimension2di imgsize(texture->getOriginalSize()); - core::rect<s32> oldViewPort = driver->getViewPort(); core::matrix4 oldProjMat = driver->getTransform(video::ETS_PROJECTION); core::matrix4 oldViewMat = driver->getTransform(video::ETS_VIEW); @@ -749,7 +746,7 @@ void Hud::drawHotbar(u16 playeritem) { s32 width = hotbar_itemcount * (m_hotbar_imagesize + m_padding * 2); v2s32 pos = centerlowerpos - v2s32(width / 2, m_hotbar_imagesize + m_padding * 3); - const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); + const v2u32 &window_size = RenderingEngine::getWindowSize(); if ((float) width / (float) window_size.X <= g_settings->getFloat("hud_hotbar_max_width")) { if (player->hud_flags & HUD_FLAG_HOTBAR_VISIBLE) { @@ -864,6 +861,54 @@ void Hud::drawSelectionMesh() } } +void Hud::toggleBlockBounds() +{ + m_block_bounds_mode = static_cast<BlockBoundsMode>(m_block_bounds_mode + 1); + + if (m_block_bounds_mode >= BLOCK_BOUNDS_MAX) { + m_block_bounds_mode = BLOCK_BOUNDS_OFF; + } +} + +void Hud::drawBlockBounds() +{ + if (m_block_bounds_mode == BLOCK_BOUNDS_OFF) { + return; + } + + video::SMaterial old_material = driver->getMaterial2D(); + driver->setMaterial(m_selection_material); + + v3s16 pos = player->getStandingNodePos(); + + v3s16 blockPos( + floorf((float) pos.X / MAP_BLOCKSIZE), + floorf((float) pos.Y / MAP_BLOCKSIZE), + floorf((float) pos.Z / MAP_BLOCKSIZE) + ); + + v3f offset = intToFloat(client->getCamera()->getOffset(), BS); + + s8 radius = m_block_bounds_mode == BLOCK_BOUNDS_ALL ? 2 : 0; + + v3f halfNode = v3f(BS, BS, BS) / 2.0f; + + for (s8 x = -radius; x <= radius; x++) + for (s8 y = -radius; y <= radius; y++) + for (s8 z = -radius; z <= radius; z++) { + v3s16 blockOffset(x, y, z); + + aabb3f box( + intToFloat((blockPos + blockOffset) * MAP_BLOCKSIZE, BS) - offset - halfNode, + intToFloat(((blockPos + blockOffset) * MAP_BLOCKSIZE) + (MAP_BLOCKSIZE - 1), BS) - offset + halfNode + ); + + driver->draw3DBox(box, video::SColor(255, 255, 0, 0)); + } + + driver->setMaterial(old_material); +} + void Hud::updateSelectionMesh(const v3s16 &camera_offset) { m_camera_offset = camera_offset; @@ -910,7 +955,7 @@ void Hud::updateSelectionMesh(const v3s16 &camera_offset) } void Hud::resizeHotbar() { - const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); + const v2u32 &window_size = RenderingEngine::getWindowSize(); if (m_screensize != window_size) { m_hotbar_imagesize = floor(HOTBAR_IMAGE_SIZE * @@ -947,12 +992,20 @@ void drawItemStack( return; } + const static thread_local bool enable_animations = + g_settings->getBool("inventory_items_animations"); + const ItemDefinition &def = item.getDefinition(client->idef()); - ItemMesh *imesh = client->idef()->getWieldMesh(def.name, client); - if (imesh && imesh->mesh) { + bool draw_overlay = false; + + // Render as mesh if animated or no inventory image + if ((enable_animations && rotation_kind < IT_ROT_NONE) || def.inventory_image.empty()) { + ItemMesh *imesh = client->idef()->getWieldMesh(def.name, client); + if (!imesh || !imesh->mesh) + return; scene::IMesh *mesh = imesh->mesh; - driver->clearZBuffer(); + driver->clearBuffers(video::ECBF_DEPTH); s32 delta = 0; if (rotation_kind < IT_ROT_NONE) { MeshTimeInfo &ti = rotation_time_infos[rotation_kind]; @@ -994,9 +1047,6 @@ void drawItemStack( core::matrix4 matrix; matrix.makeIdentity(); - static thread_local bool enable_animations = - g_settings->getBool("inventory_items_animations"); - if (enable_animations) { float timer_f = (float) delta / 5000.f; matrix.setRotationDegrees(v3f( @@ -1042,15 +1092,29 @@ void drawItemStack( driver->setTransform(video::ETS_PROJECTION, oldProjMat); driver->setViewPort(oldViewPort); - // draw the inventory_overlay - if (def.type == ITEM_NODE && def.inventory_image.empty() && - !def.inventory_overlay.empty()) { - ITextureSource *tsrc = client->getTextureSource(); - video::ITexture *overlay_texture = tsrc->getTexture(def.inventory_overlay); - core::dimension2d<u32> dimens = overlay_texture->getOriginalSize(); - core::rect<s32> srcrect(0, 0, dimens.Width, dimens.Height); - draw2DImageFilterScaled(driver, overlay_texture, rect, srcrect, clip, 0, true); - } + draw_overlay = def.type == ITEM_NODE && def.inventory_image.empty(); + } else { // Otherwise just draw as 2D + video::ITexture *texture = client->idef()->getInventoryTexture(def.name, client); + if (!texture) + return; + video::SColor color = + client->idef()->getItemstackColor(item, client); + const video::SColor colors[] = { color, color, color, color }; + + draw2DImageFilterScaled(driver, texture, rect, + core::rect<s32>({0, 0}, core::dimension2di(texture->getOriginalSize())), + clip, colors, true); + + draw_overlay = true; + } + + // draw the inventory_overlay + if (!def.inventory_overlay.empty() && draw_overlay) { + ITextureSource *tsrc = client->getTextureSource(); + video::ITexture *overlay_texture = tsrc->getTexture(def.inventory_overlay); + core::dimension2d<u32> dimens = overlay_texture->getOriginalSize(); + core::rect<s32> srcrect(0, 0, dimens.Width, dimens.Height); + draw2DImageFilterScaled(driver, overlay_texture, rect, srcrect, clip, 0, true); } if (def.type == ITEM_TOOL && item.wear != 0) { diff --git a/src/client/hud.h b/src/client/hud.h index d46545d71..d341105d2 100644 --- a/src/client/hud.h +++ b/src/client/hud.h @@ -35,14 +35,6 @@ struct ItemStack; class Hud { public: - video::IVideoDriver *driver; - scene::ISceneManager *smgr; - gui::IGUIEnvironment *guienv; - Client *client; - LocalPlayer *player; - Inventory *inventory; - ITextureSource *tsrc; - video::SColor crosshair_argb; video::SColor selectionbox_argb; @@ -55,10 +47,13 @@ public: bool pointing_at_object = false; - Hud(gui::IGUIEnvironment *guienv, Client *client, LocalPlayer *player, + Hud(Client *client, LocalPlayer *player, Inventory *inventory); ~Hud(); + void toggleBlockBounds(); + void drawBlockBounds(); + void drawHotbar(u16 playeritem); void resizeHotbar(); void drawCrosshair(); @@ -103,6 +98,12 @@ private: void drawCompassRotate(HudElement *e, video::ITexture *texture, const core::rect<s32> &rect, int way); + Client *client = nullptr; + video::IVideoDriver *driver = nullptr; + LocalPlayer *player = nullptr; + Inventory *inventory = nullptr; + ITextureSource *tsrc = nullptr; + float m_hud_scaling; // cached minetest setting float m_scale_factor; v3s16 m_camera_offset; @@ -125,6 +126,14 @@ private: scene::SMeshBuffer m_rotation_mesh_buffer; + enum BlockBoundsMode + { + BLOCK_BOUNDS_OFF, + BLOCK_BOUNDS_CURRENT, + BLOCK_BOUNDS_ALL, + BLOCK_BOUNDS_MAX + } m_block_bounds_mode = BLOCK_BOUNDS_OFF; + enum { HIGHLIGHT_BOX, diff --git a/src/client/imagefilters.cpp b/src/client/imagefilters.cpp index 0fa501410..7b2ef9822 100644 --- a/src/client/imagefilters.cpp +++ b/src/client/imagefilters.cpp @@ -19,63 +19,134 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "imagefilters.h" #include "util/numeric.h" #include <cmath> +#include <cassert> +#include <vector> + +// Simple 2D bitmap class with just the functionality needed here +class Bitmap { + u32 linesize, lines; + std::vector<u8> data; + + static inline u32 bytepos(u32 index) { return index >> 3; } + static inline u8 bitpos(u32 index) { return index & 7; } + +public: + Bitmap(u32 width, u32 height) : linesize(width), lines(height), + data(bytepos(width * height) + 1) {} + + inline bool get(u32 x, u32 y) const { + u32 index = y * linesize + x; + return data[bytepos(index)] & (1 << bitpos(index)); + } + + inline void set(u32 x, u32 y) { + u32 index = y * linesize + x; + data[bytepos(index)] |= 1 << bitpos(index); + } + + inline bool all() const { + for (u32 i = 0; i < data.size() - 1; i++) { + if (data[i] != 0xff) + return false; + } + // last byte not entirely filled + for (u8 i = 0; i < bitpos(linesize * lines); i++) { + bool value_of_bit = data.back() & (1 << i); + if (!value_of_bit) + return false; + } + return true; + } + + inline void copy(Bitmap &to) const { + assert(to.linesize == linesize && to.lines == lines); + to.data = data; + } +}; /* Fill in RGB values for transparent pixels, to correct for odd colors * appearing at borders when blending. This is because many PNG optimizers * like to discard RGB values of transparent pixels, but when blending then - * with non-transparent neighbors, their RGB values will shpw up nonetheless. + * with non-transparent neighbors, their RGB values will show up nonetheless. * * This function modifies the original image in-place. * * Parameter "threshold" is the alpha level below which pixels are considered - * transparent. Should be 127 for 3d where alpha is threshold, but 0 for - * 2d where alpha is blended. + * transparent. Should be 127 when the texture is used with ALPHA_CHANNEL_REF, + * 0 when alpha blending is used. */ void imageCleanTransparent(video::IImage *src, u32 threshold) { core::dimension2d<u32> dim = src->getDimension(); - // Walk each pixel looking for fully transparent ones. + Bitmap bitmap(dim.Width, dim.Height); + + // First pass: Mark all opaque pixels // Note: loop y around x for better cache locality. for (u32 ctry = 0; ctry < dim.Height; ctry++) for (u32 ctrx = 0; ctrx < dim.Width; ctrx++) { + if (src->getPixel(ctrx, ctry).getAlpha() > threshold) + bitmap.set(ctrx, ctry); + } + + // Exit early if all pixels opaque + if (bitmap.all()) + return; + + Bitmap newmap = bitmap; + + // Then repeatedly look for transparent pixels, filling them in until + // we're finished (capped at 50 iterations). + for (u32 iter = 0; iter < 50; iter++) { - // Ignore opaque pixels. - irr::video::SColor c = src->getPixel(ctrx, ctry); - if (c.getAlpha() > threshold) + for (u32 ctry = 0; ctry < dim.Height; ctry++) + for (u32 ctrx = 0; ctrx < dim.Width; ctrx++) { + // Skip pixels we have already processed + if (bitmap.get(ctrx, ctry)) continue; - // Sample size and total weighted r, g, b values. + video::SColor c = src->getPixel(ctrx, ctry); + + // Sample size and total weighted r, g, b values u32 ss = 0, sr = 0, sg = 0, sb = 0; - // Walk each neighbor pixel (clipped to image bounds). + // Walk each neighbor pixel (clipped to image bounds) for (u32 sy = (ctry < 1) ? 0 : (ctry - 1); sy <= (ctry + 1) && sy < dim.Height; sy++) for (u32 sx = (ctrx < 1) ? 0 : (ctrx - 1); sx <= (ctrx + 1) && sx < dim.Width; sx++) { - - // Ignore transparent pixels. - irr::video::SColor d = src->getPixel(sx, sy); - if (d.getAlpha() <= threshold) + // Ignore pixels we haven't processed + if (!bitmap.get(sx, sy)) continue; - - // Add RGB values weighted by alpha. - u32 a = d.getAlpha(); + + // Add RGB values weighted by alpha IF the pixel is opaque, otherwise + // use full weight since we want to propagate colors. + video::SColor d = src->getPixel(sx, sy); + u32 a = d.getAlpha() <= threshold ? 255 : d.getAlpha(); ss += a; sr += a * d.getRed(); sg += a * d.getGreen(); sb += a * d.getBlue(); } - // If we found any neighbor RGB data, set pixel to average - // weighted by alpha. + // Set pixel to average weighted by alpha if (ss > 0) { c.setRed(sr / ss); c.setGreen(sg / ss); c.setBlue(sb / ss); src->setPixel(ctrx, ctry, c); + newmap.set(ctrx, ctry); } } + + if (newmap.all()) + return; + + // Apply changes to bitmap for next run. This is done so we don't introduce + // a bias in color propagation in the direction pixels are processed. + newmap.copy(bitmap); + + } } /* Scale a region of an image into another image, using nearest-neighbor with diff --git a/src/client/imagefilters.h b/src/client/imagefilters.h index 5676faf85..c9bdefbb6 100644 --- a/src/client/imagefilters.h +++ b/src/client/imagefilters.h @@ -23,13 +23,13 @@ with this program; if not, write to the Free Software Foundation, Inc., /* Fill in RGB values for transparent pixels, to correct for odd colors * appearing at borders when blending. This is because many PNG optimizers * like to discard RGB values of transparent pixels, but when blending then - * with non-transparent neighbors, their RGB values will shpw up nonetheless. + * with non-transparent neighbors, their RGB values will show up nonetheless. * * This function modifies the original image in-place. * * Parameter "threshold" is the alpha level below which pixels are considered - * transparent. Should be 127 for 3d where alpha is threshold, but 0 for - * 2d where alpha is blended. + * transparent. Should be 127 when the texture is used with ALPHA_CHANNEL_REF, + * 0 when alpha blending is used. */ void imageCleanTransparent(video::IImage *src, u32 threshold); diff --git a/src/client/inputhandler.cpp b/src/client/inputhandler.cpp index 544c0e344..d833db2f1 100644 --- a/src/client/inputhandler.cpp +++ b/src/client/inputhandler.cpp @@ -35,7 +35,7 @@ void KeyCache::populate() key[KeyType::LEFT] = getKeySetting("keymap_left"); key[KeyType::RIGHT] = getKeySetting("keymap_right"); key[KeyType::JUMP] = getKeySetting("keymap_jump"); - key[KeyType::SPECIAL1] = getKeySetting("keymap_special1"); + key[KeyType::AUX1] = getKeySetting("keymap_aux1"); key[KeyType::SNEAK] = getKeySetting("keymap_sneak"); key[KeyType::DIG] = getKeySetting("keymap_dig"); key[KeyType::PLACE] = getKeySetting("keymap_place"); @@ -61,6 +61,7 @@ void KeyCache::populate() key[KeyType::DEC_VOLUME] = getKeySetting("keymap_decrease_volume"); key[KeyType::CINEMATIC] = getKeySetting("keymap_cinematic"); key[KeyType::SCREENSHOT] = getKeySetting("keymap_screenshot"); + key[KeyType::TOGGLE_BLOCK_BOUNDS] = getKeySetting("keymap_toggle_block_bounds"); key[KeyType::TOGGLE_HUD] = getKeySetting("keymap_toggle_hud"); key[KeyType::TOGGLE_CHAT] = getKeySetting("keymap_toggle_chat"); key[KeyType::TOGGLE_FOG] = getKeySetting("keymap_toggle_fog"); @@ -123,17 +124,12 @@ bool MyEventReceiver::OnEvent(const SEvent &event) if (event.EventType == irr::EET_KEY_INPUT_EVENT) { const KeyPress &keyCode = event.KeyInput; if (keysListenedFor[keyCode]) { - // If the key is being held down then the OS may - // send a continuous stream of keydown events. - // In this case, we don't want to let this - // stream reach the application as it will cause - // certain actions to repeat constantly. if (event.KeyInput.PressedDown) { - if (!IsKeyDown(keyCode)) { - keyWasDown.set(keyCode); + if (!IsKeyDown(keyCode)) keyWasPressed.set(keyCode); - } + keyIsDown.set(keyCode); + keyWasDown.set(keyCode); } else { if (IsKeyDown(keyCode)) keyWasReleased.set(keyCode); @@ -234,7 +230,7 @@ void RandomInputHandler::step(float dtime) { static RandomInputHandlerSimData rnd_data[] = { { "keymap_jump", 0.0f, 40 }, - { "keymap_special1", 0.0f, 40 }, + { "keymap_aux1", 0.0f, 40 }, { "keymap_forward", 0.0f, 40 }, { "keymap_left", 0.0f, 40 }, { "keymap_dig", 0.0f, 30 }, diff --git a/src/client/inputhandler.h b/src/client/inputhandler.h index 766cd5266..efe9442d5 100644 --- a/src/client/inputhandler.h +++ b/src/client/inputhandler.h @@ -201,7 +201,7 @@ public: // The current state of keys KeyList keyIsDown; - // Whether a key was down + // Like keyIsDown but only reset when that key is read KeyList keyWasDown; // Whether a key has just been pressed diff --git a/src/client/joystick_controller.cpp b/src/client/joystick_controller.cpp index f61ae4ae6..919db5315 100644 --- a/src/client/joystick_controller.cpp +++ b/src/client/joystick_controller.cpp @@ -79,7 +79,7 @@ JoystickLayout create_default_layout() // Accessible without any modifier pressed JLO_B_PB(KeyType::JUMP, bm | 1 << 0, 1 << 0); - JLO_B_PB(KeyType::SPECIAL1, bm | 1 << 1, 1 << 1); + JLO_B_PB(KeyType::AUX1, bm | 1 << 1, 1 << 1); // Accessible with start button not pressed, but four pressed // TODO find usage for button 0 @@ -126,11 +126,11 @@ JoystickLayout create_xbox_layout() // 4 Buttons JLO_B_PB(KeyType::JUMP, 1 << 0, 1 << 0); // A/green JLO_B_PB(KeyType::ESC, 1 << 1, 1 << 1); // B/red - JLO_B_PB(KeyType::SPECIAL1, 1 << 2, 1 << 2); // X/blue + JLO_B_PB(KeyType::AUX1, 1 << 2, 1 << 2); // X/blue JLO_B_PB(KeyType::INVENTORY, 1 << 3, 1 << 3); // Y/yellow // Analog Sticks - JLO_B_PB(KeyType::SPECIAL1, 1 << 11, 1 << 11); // left + JLO_B_PB(KeyType::AUX1, 1 << 11, 1 << 11); // left JLO_B_PB(KeyType::SNEAK, 1 << 12, 1 << 12); // right // Triggers diff --git a/src/client/keycode.cpp b/src/client/keycode.cpp index 6a0e9f569..fac077f0f 100644 --- a/src/client/keycode.cpp +++ b/src/client/keycode.cpp @@ -197,7 +197,6 @@ static const struct table_key table[] = { DEFINEKEY1(KEY_MODECHANGE, N_("IME Mode Change")) DEFINEKEY1(KEY_APPS, N_("Apps")) DEFINEKEY1(KEY_SLEEP, N_("Sleep")) -#if !(IRRLICHT_VERSION_MAJOR <= 1 && IRRLICHT_VERSION_MINOR <= 7 && IRRLICHT_VERSION_REVISION < 3) DEFINEKEY1(KEY_OEM_1, "OEM 1") // KEY_OEM_[0-9] and KEY_OEM_102 are assigned to multiple DEFINEKEY1(KEY_OEM_2, "OEM 2") // different chars (on different platforms too) and thus w/o char DEFINEKEY1(KEY_OEM_3, "OEM 3") @@ -208,7 +207,6 @@ static const struct table_key table[] = { DEFINEKEY1(KEY_OEM_8, "OEM 8") DEFINEKEY1(KEY_OEM_AX, "OEM AX") DEFINEKEY1(KEY_OEM_102, "OEM 102") -#endif DEFINEKEY1(KEY_ATTN, "Attn") DEFINEKEY1(KEY_CRSEL, "CrSel") DEFINEKEY1(KEY_EXSEL, "ExSel") @@ -316,7 +314,8 @@ KeyPress::KeyPress(const char *name) int chars_read = mbtowc(&Char, name, 1); FATAL_ERROR_IF(chars_read != 1, "Unexpected multibyte character"); m_name = ""; - warningstream << "KeyPress: Unknown key '" << name << "', falling back to first char."; + warningstream << "KeyPress: Unknown key '" << name + << "', falling back to first char." << std::endl; } KeyPress::KeyPress(const irr::SEvent::SKeyInput &in, bool prefer_character) diff --git a/src/client/keys.h b/src/client/keys.h index d4f3dd4c1..b81b571b2 100644 --- a/src/client/keys.h +++ b/src/client/keys.h @@ -32,7 +32,7 @@ public: LEFT, RIGHT, JUMP, - SPECIAL1, + AUX1, SNEAK, AUTOFORWARD, DIG, @@ -60,6 +60,7 @@ public: DEC_VOLUME, CINEMATIC, SCREENSHOT, + TOGGLE_BLOCK_BOUNDS, TOGGLE_HUD, TOGGLE_CHAT, TOGGLE_FOG, diff --git a/src/client/localplayer.cpp b/src/client/localplayer.cpp index ddec04cb5..24a12c35e 100644 --- a/src/client/localplayer.cpp +++ b/src/client/localplayer.cpp @@ -172,7 +172,7 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d, { if (m_cao && m_cao->m_waiting_for_reattach > 0) m_cao->m_waiting_for_reattach -= dtime; - + // Node at feet position, update each ClientEnvironment::step() if (!collision_info || collision_info->empty()) m_standing_node = floatToInt(m_position, BS); @@ -461,8 +461,6 @@ void LocalPlayer::move(f32 dtime, Environment *env, f32 pos_max_d, m_speed.Y += jumpspeed; } setSpeed(m_speed); - if (! m_freecam) - m_legit_speed = m_speed; m_can_jump = false; } @@ -711,6 +709,16 @@ v3s16 LocalPlayer::getLightPosition() const return floatToInt(m_position + v3f(0.0f, BS * 1.5f, 0.0f), BS); } +v3f LocalPlayer::getSendSpeed() +{ + v3f speed = getLegitSpeed(); + + if (m_client->modsLoaded()) + speed = m_client->getScript()->get_send_speed(speed); + + return speed; +} + v3f LocalPlayer::getEyeOffset() const { float eye_height = camera_barely_in_ceiling ? m_eye_height - 0.125f : m_eye_height; diff --git a/src/client/localplayer.h b/src/client/localplayer.h index 0e071d2b4..eaac216d3 100644 --- a/src/client/localplayer.h +++ b/src/client/localplayer.h @@ -140,8 +140,10 @@ public: v3f getPosition() const { return m_position; } v3f getLegitPosition() const { return m_legit_position; } - - v3f getLegitSpeed() const { return m_legit_speed; } + + v3f getLegitSpeed() const { return m_freecam ? m_legit_speed : m_speed; } + + v3f getSendSpeed(); inline void setLegitPosition(const v3f &position) { @@ -151,18 +153,18 @@ public: setPosition(position); } - inline void freecamEnable() + inline void freecamEnable() { m_freecam = true; } - - inline void freecamDisable() + + inline void freecamDisable() { m_freecam = false; setPosition(m_legit_position); setSpeed(m_legit_speed); } - + // Non-transformed eye offset getters // For accurate positions, use the Camera functions v3f getEyePosition() const { return m_position + getEyeOffset(); } @@ -184,13 +186,13 @@ public: { added_velocity += vel; } - + void tryReattach(int id); - + bool isWaitingForReattach() const; - + bool canWalkOn(const ContentFeatures &f); - + private: void accelerate(const v3f &target_speed, const f32 max_increase_H, const f32 max_increase_V, const bool use_pitch); diff --git a/src/client/mapblock_mesh.cpp b/src/client/mapblock_mesh.cpp index b7c5ea16a..8877e0549 100644 --- a/src/client/mapblock_mesh.cpp +++ b/src/client/mapblock_mesh.cpp @@ -407,7 +407,7 @@ static void getNodeVertexDirs(const v3s16 &dir, v3s16 *vertex_dirs) static void getNodeTextureCoords(v3f base, const v3f &scale, const v3s16 &dir, float *u, float *v) { - if (dir.X > 0 || dir.Y > 0 || dir.Z < 0) + if (dir.X > 0 || dir.Y != 0 || dir.Z < 0) base -= scale; if (dir == v3s16(0,0,1)) { *u = -base.X - 1; @@ -425,8 +425,8 @@ static void getNodeTextureCoords(v3f base, const v3f &scale, const v3s16 &dir, f *u = base.X + 1; *v = -base.Z - 2; } else if (dir == v3s16(0,-1,0)) { - *u = base.X; - *v = base.Z; + *u = base.X + 1; + *v = base.Z + 1; } } @@ -1140,8 +1140,8 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): */ { - MapblockMeshGenerator generator(data, &collector); - generator.generate(); + MapblockMeshGenerator(data, &collector, + data->m_client->getSceneManager()->getMeshManipulator()).generate(); } /* @@ -1244,13 +1244,6 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): } if (m_mesh[layer]) { -#if 0 - // Usually 1-700 faces and 1-7 materials - std::cout << "Updated MapBlock has " << fastfaces_new.size() - << " faces and uses " << m_mesh[layer]->getMeshBufferCount() - << " materials (meshbuffers)" << std::endl; -#endif - // Use VBO for mesh (this just would set this for ever buffer) if (m_enable_vbo) m_mesh[layer]->setHardwareMappingHint(scene::EHM_STATIC); diff --git a/src/client/mapblock_mesh.h b/src/client/mapblock_mesh.h index 6f454d348..80075fce2 100644 --- a/src/client/mapblock_mesh.h +++ b/src/client/mapblock_mesh.h @@ -125,8 +125,6 @@ public: m_animation_force_timer--; } - void updateCameraOffset(v3s16 camera_offset); - std::set<v3s16> esp_nodes; private: diff --git a/src/client/mesh.cpp b/src/client/mesh.cpp index 2400a374c..e43139218 100644 --- a/src/client/mesh.cpp +++ b/src/client/mesh.cpp @@ -27,14 +27,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <SAnimatedMesh.h> #include <IAnimatedMeshSceneNode.h> -// In Irrlicht 1.8 the signature of ITexture::lock was changed from -// (bool, u32) to (E_TEXTURE_LOCK_MODE, u32). -#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7 -#define MY_ETLM_READ_ONLY true -#else -#define MY_ETLM_READ_ONLY video::ETLM_READ_ONLY -#endif - inline static void applyShadeFactor(video::SColor& color, float factor) { color.setRed(core::clamp(core::round32(color.getRed()*factor), 0, 255)); diff --git a/src/client/mesh_generator_thread.h b/src/client/mesh_generator_thread.h index 8e13dec3e..f393e2368 100644 --- a/src/client/mesh_generator_thread.h +++ b/src/client/mesh_generator_thread.h @@ -40,7 +40,6 @@ struct QueuedMeshUpdate { v3s16 p = v3s16(-1337, -1337, -1337); bool ack_block_to_server = false; - bool urgent = false; int crack_level = -1; v3s16 crack_pos; MeshMakeData *data = nullptr; // This is generated in MeshUpdateQueue::pop() diff --git a/src/client/minimap.cpp b/src/client/minimap.cpp index 187428273..3013e1406 100644 --- a/src/client/minimap.cpp +++ b/src/client/minimap.cpp @@ -304,7 +304,7 @@ void Minimap::setModeIndex(size_t index) data->mode = m_modes[index]; m_current_mode_index = index; } else { - data->mode = MinimapModeDef{MINIMAP_TYPE_OFF, N_("Minimap hidden"), 0, 0, ""}; + data->mode = MinimapModeDef{MINIMAP_TYPE_OFF, gettext("Minimap hidden"), 0, 0, ""}; m_current_mode_index = 0; } @@ -330,25 +330,26 @@ void Minimap::addMode(MinimapModeDef mode) if (mode.label == "") { switch (mode.type) { case MINIMAP_TYPE_OFF: - mode.label = N_("Minimap hidden"); + mode.label = gettext("Minimap hidden"); break; case MINIMAP_TYPE_SURFACE: - mode.label = N_("Minimap in surface mode, Zoom x%d"); + mode.label = gettext("Minimap in surface mode, Zoom x%d"); if (mode.map_size > 0) zoom = 256 / mode.map_size; break; case MINIMAP_TYPE_RADAR: - mode.label = N_("Minimap in radar mode, Zoom x%d"); + mode.label = gettext("Minimap in radar mode, Zoom x%d"); if (mode.map_size > 0) zoom = 512 / mode.map_size; break; case MINIMAP_TYPE_TEXTURE: - mode.label = N_("Minimap in texture mode"); + mode.label = gettext("Minimap in texture mode"); break; default: break; } } + // else: Custom labels need mod-provided client-side translation if (zoom >= 0) { char label_buf[1024]; @@ -490,7 +491,8 @@ video::ITexture *Minimap::getMinimapTexture() // Want to use texture source, to : 1 find texture, 2 cache it video::ITexture* texture = m_tsrc->getTexture(data->mode.texture); video::IImage* image = driver->createImageFromData( - texture->getColorFormat(), texture->getSize(), texture->lock(), true, false); + texture->getColorFormat(), texture->getSize(), + texture->lock(video::ETLM_READ_ONLY), true, false); texture->unlock(); auto dim = image->getDimension(); @@ -575,7 +577,7 @@ scene::SMeshBuffer *Minimap::getMinimapMeshBuffer() void Minimap::drawMinimap() { // Non hud managed minimap drawing (legacy minimap) - v2u32 screensize = RenderingEngine::get_instance()->getWindowSize(); + v2u32 screensize = RenderingEngine::getWindowSize(); const u32 size = 0.25 * screensize.Y; drawMinimap(core::rect<s32>( diff --git a/src/client/minimap.h b/src/client/minimap.h index 4a2c462f8..87c9668ee 100644 --- a/src/client/minimap.h +++ b/src/client/minimap.h @@ -138,7 +138,6 @@ public: size_t getMaxModeIndex() const { return m_modes.size() - 1; }; void nextMode(); - void setModesFromString(std::string modes_string); MinimapModeDef getModeDef() const { return data->mode; } video::ITexture *getMinimapTexture(); diff --git a/src/client/particles.cpp b/src/client/particles.cpp index 7acd996dc..288826a5f 100644 --- a/src/client/particles.cpp +++ b/src/client/particles.cpp @@ -64,8 +64,8 @@ Particle::Particle( v2f texsize, video::SColor color ): - scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(), - RenderingEngine::get_scene_manager()) + scene::ISceneNode(((Client *)gamedef)->getSceneManager()->getRootSceneNode(), + ((Client *)gamedef)->getSceneManager()) { // Misc m_gamedef = gamedef; diff --git a/src/client/render/anaglyph.cpp b/src/client/render/anaglyph.cpp index 9ba4464a2..153e77400 100644 --- a/src/client/render/anaglyph.cpp +++ b/src/client/render/anaglyph.cpp @@ -40,7 +40,7 @@ void RenderingCoreAnaglyph::setupMaterial(int color_mask) void RenderingCoreAnaglyph::useEye(bool right) { RenderingCoreStereo::useEye(right); - driver->clearZBuffer(); + driver->clearBuffers(video::ECBF_DEPTH); setupMaterial(right ? video::ECP_GREEN | video::ECP_BLUE : video::ECP_RED); } diff --git a/src/client/render/core.cpp b/src/client/render/core.cpp index 794ec0186..99af085f9 100644 --- a/src/client/render/core.cpp +++ b/src/client/render/core.cpp @@ -163,6 +163,7 @@ void RenderingCore::draw3D() driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); if (!show_hud) return; + hud->drawBlockBounds(); hud->drawSelectionMesh(); if (draw_entity_esp || draw_entity_tracers || draw_player_esp || draw_player_tracers || draw_node_esp || draw_node_tracers) drawTracersAndESP(); diff --git a/src/client/render/factory.cpp b/src/client/render/factory.cpp index 30f9480fc..7fcec40dd 100644 --- a/src/client/render/factory.cpp +++ b/src/client/render/factory.cpp @@ -19,7 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc., */ #include "factory.h" -#include <stdexcept> +#include "log.h" #include "plain.h" #include "anaglyph.h" #include "interlaced.h" @@ -45,5 +45,8 @@ RenderingCore *createRenderingCore(const std::string &stereo_mode, IrrlichtDevic 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); + + // fallback to plain renderer + errorstream << "Invalid rendering mode: " << stereo_mode << std::endl; + return new RenderingCorePlain(device, client, hud); } diff --git a/src/client/render/interlaced.cpp b/src/client/render/interlaced.cpp index ce8e92f21..3f79a8eb5 100644 --- a/src/client/render/interlaced.cpp +++ b/src/client/render/interlaced.cpp @@ -35,7 +35,11 @@ void RenderingCoreInterlaced::initMaterial() IShaderSource *s = client->getShaderSource(); mat.UseMipMaps = false; mat.ZBuffer = false; +#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8 + mat.ZWriteEnable = video::EZW_OFF; +#else mat.ZWriteEnable = false; +#endif u32 shader = s->getShader("3d_interlaced_merge", TILE_MATERIAL_BASIC); mat.MaterialType = s->getShaderInfo(shader).material; for (int k = 0; k < 3; ++k) { diff --git a/src/client/renderingengine.cpp b/src/client/renderingengine.cpp index 22c8a8102..138012414 100644 --- a/src/client/renderingengine.cpp +++ b/src/client/renderingengine.cpp @@ -118,6 +118,8 @@ RenderingEngine::RenderingEngine(IEventReceiver *receiver) } SIrrlichtCreationParameters params = SIrrlichtCreationParameters(); + if (g_logger.getTraceEnabled()) + params.LoggingLevel = irr::ELL_DEBUG; params.DriverType = driverType; params.WindowSize = core::dimension2d<u32>(screen_w, screen_h); params.Bits = bits; @@ -153,11 +155,11 @@ RenderingEngine::RenderingEngine(IEventReceiver *receiver) RenderingEngine::~RenderingEngine() { core.reset(); - m_device->drop(); + m_device->closeDevice(); s_singleton = nullptr; } -v2u32 RenderingEngine::getWindowSize() const +v2u32 RenderingEngine::_getWindowSize() const { if (core) return core->getVirtualSize(); @@ -223,6 +225,20 @@ bool RenderingEngine::print_video_modes() return videomode_list != NULL; } +void RenderingEngine::removeMesh(const scene::IMesh* mesh) +{ + m_device->getSceneManager()->getMeshCache()->removeMesh(mesh); +} + +void RenderingEngine::cleanupMeshCache() +{ + auto mesh_cache = m_device->getSceneManager()->getMeshCache(); + while (mesh_cache->getMeshCount() != 0) { + if (scene::IAnimatedMesh *mesh = mesh_cache->getMeshByIndex(0)) + mesh_cache->removeMesh(mesh); + } +} + bool RenderingEngine::setupTopLevelWindow(const std::string &name) { // FIXME: It would make more sense for there to be a switch of some @@ -325,12 +341,18 @@ static bool getWindowHandle(irr::video::IVideoDriver *driver, HWND &hWnd) const video::SExposedVideoData exposedData = driver->getExposedVideoData(); switch (driver->getDriverType()) { +#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9 case video::EDT_DIRECT3D8: hWnd = reinterpret_cast<HWND>(exposedData.D3D8.HWnd); break; +#endif case video::EDT_DIRECT3D9: hWnd = reinterpret_cast<HWND>(exposedData.D3D9.HWnd); break; +#if ENABLE_GLES + case video::EDT_OGLES1: + case video::EDT_OGLES2: +#endif case video::EDT_OPENGL: hWnd = reinterpret_cast<HWND>(exposedData.OpenGLWin32.HWnd); break; @@ -470,11 +492,11 @@ bool RenderingEngine::setXorgWindowIconFromPath(const std::string &icon_file) 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, +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(); + v2u32 screensize = getWindowSize(); v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight()); v2s32 center(screensize.X / 2, screensize.Y / 2); @@ -542,7 +564,7 @@ void RenderingEngine::_draw_load_screen(const std::wstring &text, /* Draws the menu scene including (optional) cloud background. */ -void RenderingEngine::_draw_menu_scene(gui::IGUIEnvironment *guienv, +void RenderingEngine::draw_menu_scene(gui::IGUIEnvironment *guienv, float dtime, bool clouds) { bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds"); @@ -590,19 +612,19 @@ std::vector<irr::video::E_DRIVER_TYPE> RenderingEngine::getSupportedVideoDrivers return drivers; } -void RenderingEngine::_initialize(Client *client, Hud *hud) +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() +void RenderingEngine::finalize() { core.reset(); } -void RenderingEngine::_draw_scene(video::SColor skycolor, bool show_hud, +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); diff --git a/src/client/renderingengine.h b/src/client/renderingengine.h index 34cc60630..28ddc8652 100644 --- a/src/client/renderingengine.h +++ b/src/client/renderingengine.h @@ -41,7 +41,6 @@ public: RenderingEngine(IEventReceiver *eventReceiver); ~RenderingEngine(); - v2u32 getWindowSize() const; void setResizable(bool resize); video::IVideoDriver *getVideoDriver() { return driver; } @@ -56,31 +55,30 @@ public: bool setWindowIcon(); bool setXorgWindowIconFromPath(const std::string &icon_file); static bool print_video_modes(); + void cleanupMeshCache(); - static RenderingEngine *get_instance() { return s_singleton; } + void removeMesh(const scene::IMesh* mesh); - static io::IFileSystem *get_filesystem() + static v2u32 getWindowSize() { - sanity_check(s_singleton && s_singleton->m_device); - return s_singleton->m_device->getFileSystem(); + sanity_check(s_singleton); + return s_singleton->_getWindowSize(); } - static video::IVideoDriver *get_video_driver() + io::IFileSystem *get_filesystem() { - sanity_check(s_singleton && s_singleton->m_device); - return s_singleton->m_device->getVideoDriver(); + return m_device->getFileSystem(); } - static scene::IMeshCache *get_mesh_cache() + static video::IVideoDriver *get_video_driver() { sanity_check(s_singleton && s_singleton->m_device); - return s_singleton->m_device->getSceneManager()->getMeshCache(); + return s_singleton->m_device->getVideoDriver(); } - static scene::ISceneManager *get_scene_manager() + scene::ISceneManager *get_scene_manager() { - sanity_check(s_singleton && s_singleton->m_device); - return s_singleton->m_device->getSceneManager(); + return m_device->getSceneManager(); } static irr::IrrlichtDevice *get_raw_device() @@ -89,70 +87,37 @@ public: return s_singleton->m_device; } - static u32 get_timer_time() + u32 get_timer_time() { - sanity_check(s_singleton && s_singleton->m_device && - s_singleton->m_device->getTimer()); - return s_singleton->m_device->getTimer()->getTime(); + return m_device->getTimer()->getTime(); } - static gui::IGUIEnvironment *get_gui_env() + gui::IGUIEnvironment *get_gui_env() { - sanity_check(s_singleton && s_singleton->m_device); - return s_singleton->m_device->getGUIEnvironment(); + return m_device->getGUIEnvironment(); } - inline static void draw_load_screen(const std::wstring &text, + 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); - } + float dtime = 0, int percent = 0, bool clouds = true); - inline static void draw_menu_scene( - gui::IGUIEnvironment *guienv, float dtime, bool clouds) - { - s_singleton->_draw_menu_scene(guienv, dtime, clouds); - } + void draw_menu_scene(gui::IGUIEnvironment *guienv, float dtime, bool clouds); + void draw_scene(video::SColor skycolor, bool show_hud, + bool show_minimap, bool draw_wield_tool, bool draw_crosshair); - 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); - } + void initialize(Client *client, Hud *hud); + void finalize(); - inline static void initialize(Client *client, Hud *hud) + bool run() { - 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(); + return 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(); + v2u32 _getWindowSize() const; std::unique_ptr<RenderingCore> core; irr::IrrlichtDevice *m_device = nullptr; diff --git a/src/client/shader.cpp b/src/client/shader.cpp index b3e4911f4..58946b90f 100644 --- a/src/client/shader.cpp +++ b/src/client/shader.cpp @@ -579,8 +579,10 @@ ShaderInfo ShaderSource::generateShader(const std::string &name, if (use_gles) { shaders_header << R"( #version 100 - )"; + )"; vertex_header = R"( + precision mediump float; + uniform highp mat4 mWorldView; uniform highp mat4 mWorldViewProj; uniform mediump mat4 mTexture; @@ -592,17 +594,17 @@ ShaderInfo ShaderSource::generateShader(const std::string &name, attribute mediump vec3 inVertexNormal; attribute mediump vec4 inVertexTangent; attribute mediump vec4 inVertexBinormal; - )"; + )"; fragment_header = R"( precision mediump float; - )"; + )"; } else { shaders_header << R"( #version 120 #define lowp #define mediump #define highp - )"; + )"; vertex_header = R"( #define mWorldView gl_ModelViewMatrix #define mWorldViewProj gl_ModelViewProjectionMatrix @@ -615,7 +617,7 @@ ShaderInfo ShaderSource::generateShader(const std::string &name, #define inVertexNormal gl_Normal #define inVertexTangent gl_MultiTexCoord1 #define inVertexBinormal gl_MultiTexCoord2 - )"; + )"; } bool use_discard = use_gles; diff --git a/src/client/shader.h b/src/client/shader.h index d99182693..49a563115 100644 --- a/src/client/shader.h +++ b/src/client/shader.h @@ -20,8 +20,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once -#include <IMaterialRendererServices.h> #include "irrlichttypes_bloated.h" +#include <IMaterialRendererServices.h> #include <string> #include "tile.h" #include "nodedef.h" @@ -96,9 +96,10 @@ public: if (has_been_set && std::equal(m_sent, m_sent + count, value)) return; if (is_pixel) - services->setPixelShaderConstant(m_name, value, count); + services->setPixelShaderConstant(services->getPixelShaderConstantID(m_name), value, count); else - services->setVertexShaderConstant(m_name, value, count); + services->setVertexShaderConstant(services->getVertexShaderConstantID(m_name), value, count); + std::copy(value, value + count, m_sent); has_been_set = true; } diff --git a/src/client/sky.cpp b/src/client/sky.cpp index 3a40321dd..47296a7a5 100644 --- a/src/client/sky.cpp +++ b/src/client/sky.cpp @@ -39,12 +39,13 @@ static video::SMaterial baseMaterial() { video::SMaterial mat; mat.Lighting = false; -#if ENABLE_GLES +#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8 mat.ZBuffer = video::ECFN_DISABLED; + mat.ZWriteEnable = video::EZW_OFF; #else + mat.ZWriteEnable = false; 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; @@ -52,10 +53,12 @@ static video::SMaterial baseMaterial() return mat; }; -Sky::Sky(s32 id, ITextureSource *tsrc, IShaderSource *ssrc) : - scene::ISceneNode(RenderingEngine::get_scene_manager()->getRootSceneNode(), - RenderingEngine::get_scene_manager(), id) +Sky::Sky(s32 id, RenderingEngine *rendering_engine, ITextureSource *tsrc, IShaderSource *ssrc) : + scene::ISceneNode(rendering_engine->get_scene_manager()->getRootSceneNode(), + rendering_engine->get_scene_manager(), id) { + m_seed = (u64)myrand() << 32 | myrand(); + setAutomaticCulling(scene::EAC_OFF); m_box.MaxEdge.set(0, 0, 0); m_box.MinEdge.set(0, 0, 0); @@ -81,13 +84,13 @@ Sky::Sky(s32 id, ITextureSource *tsrc, IShaderSource *ssrc) : // Ensures that sun and moon textures and tonemaps are correct. setSkyDefaults(); m_sun_texture = tsrc->isKnownSourceImage(m_sun_params.texture) ? - tsrc->getTextureForMesh(m_sun_params.texture) : NULL; + tsrc->getTextureForMesh(m_sun_params.texture) : nullptr; m_moon_texture = tsrc->isKnownSourceImage(m_moon_params.texture) ? - tsrc->getTextureForMesh(m_moon_params.texture) : NULL; + tsrc->getTextureForMesh(m_moon_params.texture) : nullptr; m_sun_tonemap = tsrc->isKnownSourceImage(m_sun_params.tonemap) ? - tsrc->getTexture(m_sun_params.tonemap) : NULL; + tsrc->getTexture(m_sun_params.tonemap) : nullptr; m_moon_tonemap = tsrc->isKnownSourceImage(m_moon_params.tonemap) ? - tsrc->getTexture(m_moon_params.tonemap) : NULL; + tsrc->getTexture(m_moon_params.tonemap) : nullptr; if (m_sun_texture) { m_materials[3] = baseMaterial(); @@ -743,14 +746,14 @@ void Sky::place_sky_body( } } -void Sky::setSunTexture(std::string sun_texture, - std::string sun_tonemap, ITextureSource *tsrc) +void Sky::setSunTexture(const std::string &sun_texture, + const std::string &sun_tonemap, ITextureSource *tsrc) { // Ignore matching textures (with modifiers) entirely, // but lets at least update the tonemap before hand. m_sun_params.tonemap = sun_tonemap; m_sun_tonemap = tsrc->isKnownSourceImage(m_sun_params.tonemap) ? - tsrc->getTexture(m_sun_params.tonemap) : NULL; + tsrc->getTexture(m_sun_params.tonemap) : nullptr; m_materials[3].Lighting = !!m_sun_tonemap; if (m_sun_params.texture == sun_texture) @@ -779,7 +782,7 @@ void Sky::setSunTexture(std::string sun_texture, } } -void Sky::setSunriseTexture(std::string sunglow_texture, +void Sky::setSunriseTexture(const std::string &sunglow_texture, ITextureSource* tsrc) { // Ignore matching textures (with modifiers) entirely. @@ -791,14 +794,14 @@ void Sky::setSunriseTexture(std::string sunglow_texture, ); } -void Sky::setMoonTexture(std::string moon_texture, - std::string moon_tonemap, ITextureSource *tsrc) +void Sky::setMoonTexture(const std::string &moon_texture, + const std::string &moon_tonemap, ITextureSource *tsrc) { // Ignore matching textures (with modifiers) entirely, // but lets at least update the tonemap before hand. m_moon_params.tonemap = moon_tonemap; m_moon_tonemap = tsrc->isKnownSourceImage(m_moon_params.tonemap) ? - tsrc->getTexture(m_moon_params.tonemap) : NULL; + tsrc->getTexture(m_moon_params.tonemap) : nullptr; m_materials[4].Lighting = !!m_moon_tonemap; if (m_moon_params.texture == moon_texture) @@ -832,7 +835,6 @@ void Sky::setStarCount(u16 star_count, bool force_update) // Allow force updating star count at game init. if (m_star_params.count != star_count || force_update) { m_star_params.count = star_count; - m_seed = (u64)myrand() << 32 | myrand(); updateStars(); } } @@ -892,7 +894,7 @@ void Sky::setSkyColors(const SkyColor &sky_color) } void Sky::setHorizonTint(video::SColor sun_tint, video::SColor moon_tint, - std::string use_sun_tint) + const std::string &use_sun_tint) { // Change sun and moon tinting: m_sky_params.fog_sun_tint = sun_tint; @@ -906,7 +908,7 @@ void Sky::setHorizonTint(video::SColor sun_tint, video::SColor moon_tint, m_default_tint = true; } -void Sky::addTextureToSkybox(std::string texture, int material_id, +void Sky::addTextureToSkybox(const std::string &texture, int material_id, ITextureSource *tsrc) { // Sanity check for more than six textures. diff --git a/src/client/sky.h b/src/client/sky.h index 10e1cd976..121a16bb7 100644 --- a/src/client/sky.h +++ b/src/client/sky.h @@ -17,10 +17,10 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ +#include "irrlichttypes_extrabloated.h" #include <ISceneNode.h> #include <array> #include "camera.h" -#include "irrlichttypes_extrabloated.h" #include "irr_ptr.h" #include "shader.h" #include "skyparams.h" @@ -36,7 +36,7 @@ class Sky : public scene::ISceneNode { public: //! constructor - Sky(s32 id, ITextureSource *tsrc, IShaderSource *ssrc); + Sky(s32 id, RenderingEngine *rendering_engine, ITextureSource *tsrc, IShaderSource *ssrc); virtual void OnRegisterSceneNode(); @@ -65,15 +65,15 @@ public: } void setSunVisible(bool sun_visible) { m_sun_params.visible = sun_visible; } - void setSunTexture(std::string sun_texture, - std::string sun_tonemap, ITextureSource *tsrc); + void setSunTexture(const std::string &sun_texture, + const std::string &sun_tonemap, ITextureSource *tsrc); void setSunScale(f32 sun_scale) { m_sun_params.scale = sun_scale; } void setSunriseVisible(bool glow_visible) { m_sun_params.sunrise_visible = glow_visible; } - void setSunriseTexture(std::string sunglow_texture, ITextureSource* tsrc); + void setSunriseTexture(const std::string &sunglow_texture, ITextureSource* tsrc); void setMoonVisible(bool moon_visible) { m_moon_params.visible = moon_visible; } - void setMoonTexture(std::string moon_texture, - std::string moon_tonemap, ITextureSource *tsrc); + void setMoonTexture(const std::string &moon_texture, + const std::string &moon_tonemap, ITextureSource *tsrc); void setMoonScale(f32 moon_scale) { m_moon_params.scale = moon_scale; } void setStarsVisible(bool stars_visible) { m_star_params.visible = stars_visible; } @@ -87,21 +87,21 @@ public: 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) + void setFallbackBgColor(video::SColor fallback_bg_color) { m_fallback_bg_color = fallback_bg_color; } - void overrideColors(const video::SColor &bgcolor, const video::SColor &skycolor) + void overrideColors(video::SColor bgcolor, video::SColor skycolor) { m_bgcolor = bgcolor; m_skycolor = skycolor; } void setSkyColors(const SkyColor &sky_color); void setHorizonTint(video::SColor sun_tint, video::SColor moon_tint, - std::string use_sun_tint); + const std::string &use_sun_tint); void setInClouds(bool clouds) { m_in_clouds = clouds; } void clearSkyboxTextures() { m_sky_params.textures.clear(); } - void addTextureToSkybox(std::string texture, int material_id, + void addTextureToSkybox(const std::string &texture, int material_id, ITextureSource *tsrc); const video::SColorf &getCurrentStarColor() const { return m_star_color; } @@ -126,7 +126,7 @@ private: } // Mix two colors by a given amount - video::SColor m_mix_scolor(video::SColor col1, video::SColor col2, f32 factor) + static 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, @@ -135,7 +135,7 @@ private: col1.getBlue() * (1 - factor) + col2.getBlue() * factor); return result; } - video::SColorf m_mix_scolorf(video::SColorf col1, video::SColorf col2, f32 factor) + static 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, diff --git a/src/client/sound_openal.cpp b/src/client/sound_openal.cpp index f4e61f93e..8dceeede6 100644 --- a/src/client/sound_openal.cpp +++ b/src/client/sound_openal.cpp @@ -671,8 +671,8 @@ public: 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); + alSource3f(sound->source_id, AL_VELOCITY, 0.0f, 0.0f, 0.0f); + alSourcef(sound->source_id, AL_REFERENCE_DISTANCE, 10.0f); } bool updateSoundGain(int id, float gain) diff --git a/src/client/tile.cpp b/src/client/tile.cpp index 37836d0df..96312ea27 100644 --- a/src/client/tile.cpp +++ b/src/client/tile.cpp @@ -34,15 +34,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "guiscalingfilter.h" #include "renderingengine.h" - -#if ENABLE_GLES -#ifdef _IRR_COMPILE_WITH_OGLES1_ -#include <GLES/gl.h> -#else -#include <GLES2/gl2.h> -#endif -#endif - /* A cache from texture name to texture path */ @@ -427,9 +418,9 @@ private: std::unordered_map<std::string, Palette> m_palettes; // Cached settings needed for making textures from meshes + bool m_setting_mipmap; bool m_setting_trilinear_filter; bool m_setting_bilinear_filter; - bool m_setting_anisotropic_filter; }; IWritableTextureSource *createTextureSource() @@ -448,9 +439,9 @@ TextureSource::TextureSource() // Cache some settings // Note: Since this is only done once, the game must be restarted // for these settings to take effect + m_setting_mipmap = g_settings->getBool("mip_map"); 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() @@ -669,7 +660,7 @@ video::ITexture* TextureSource::getTexture(const std::string &name, u32 *id) video::ITexture* TextureSource::getTextureForMesh(const std::string &name, u32 *id) { static thread_local bool filter_needed = - g_settings->getBool("texture_clean_transparent") || + g_settings->getBool("texture_clean_transparent") || m_setting_mipmap || ((m_setting_trilinear_filter || m_setting_bilinear_filter) && g_settings->getS32("texture_min_size") > 1); // Avoid duplicating texture if it won't actually change @@ -839,17 +830,16 @@ static video::IImage *createInventoryCubeImage( image = scaled; } sanity_check(image->getPitch() == 4 * size); - return reinterpret_cast<u32 *>(image->lock()); + return reinterpret_cast<u32 *>(image->getData()); }; 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()); + u32 *target = reinterpret_cast<u32 *>(result->getData()); // Draws single cube face // `shade_factor` is face brightness, in range [0.0, 1.0] @@ -908,7 +898,6 @@ static video::IImage *createInventoryCubeImage( {0, 5}, {1, 5}, }); - result->unlock(); return result; } @@ -1015,42 +1004,19 @@ video::IImage* TextureSource::generateImage(const std::string &name) #if ENABLE_GLES - -static inline u16 get_GL_major_version() -{ - const GLubyte *gl_version = glGetString(GL_VERSION); - return (u16) (gl_version[0] - '0'); -} - -/** - * Check if hardware requires npot2 aligned textures - * @return true if alignment NOT(!) requires, false otherwise - */ - -bool hasNPotSupport() -{ - // Only GLES2 is trusted to correctly report npot support - // Note: we cache the boolean result, the GL context will never change. - static const bool supported = get_GL_major_version() > 1 && - glGetString(GL_EXTENSIONS) && - strstr((char *)glGetString(GL_EXTENSIONS), "GL_OES_texture_npot"); - return supported; -} - /** * 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 */ - -video::IImage * Align2Npot2(video::IImage * image, - video::IVideoDriver* driver) +video::IImage *Align2Npot2(video::IImage *image, + video::IVideoDriver *driver) { if (image == NULL) return image; - if (hasNPotSupport()) + if (driver->queryFeature(video::EVDF_TEXTURE_NPOT)) return image; core::dimension2d<u32> dim = image->getDimension(); @@ -1640,8 +1606,8 @@ bool TextureSource::generateImagePart(std::string part_of_name, return false; } - // Apply the "clean transparent" filter, if configured. - if (g_settings->getBool("texture_clean_transparent")) + // Apply the "clean transparent" filter, if needed + if (m_setting_mipmap || g_settings->getBool("texture_clean_transparent")) imageCleanTransparent(baseimg, 127); /* Upscale textures to user's requested minimum size. This is a trick to make @@ -2226,9 +2192,14 @@ 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); + if (!texture) + return c; video::IImage *image = driver->createImage(texture, core::position2d<s32>(0, 0), texture->getOriginalSize()); + if (!image) + return c; + u32 total = 0; u32 tR = 0; u32 tG = 0; diff --git a/src/client/tile.h b/src/client/tile.h index 49c46f749..fcdc46460 100644 --- a/src/client/tile.h +++ b/src/client/tile.h @@ -134,8 +134,7 @@ public: IWritableTextureSource *createTextureSource(); #if ENABLE_GLES -bool hasNPotSupport(); -video::IImage * Align2Npot2(video::IImage * image, irr::video::IVideoDriver* driver); +video::IImage *Align2Npot2(video::IImage *image, video::IVideoDriver *driver); #endif enum MaterialType{ diff --git a/src/client/wieldmesh.cpp b/src/client/wieldmesh.cpp index ad583210a..08fd49fc0 100644 --- a/src/client/wieldmesh.cpp +++ b/src/client/wieldmesh.cpp @@ -294,32 +294,36 @@ void WieldMeshSceneNode::setExtruded(const std::string &imagename, } 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, const ContentFeatures &f) +static scene::SMesh *createSpecialNodeMesh(Client *client, MapNode n, + std::vector<ItemPartColor> *colors, const ContentFeatures &f) { MeshMakeData mesh_make_data(client, false); MeshCollector collector; mesh_make_data.setSmoothLighting(false); - MapblockMeshGenerator gen(&mesh_make_data, &collector); - u8 param2 = 0; - if (f.param_type_2 == CPT2_WALLMOUNTED || + MapblockMeshGenerator gen(&mesh_make_data, &collector, + client->getSceneManager()->getMeshManipulator()); + + if (n.getParam2()) { + // keep it + } else if (f.param_type_2 == CPT2_WALLMOUNTED || f.param_type_2 == CPT2_COLORED_WALLMOUNTED) { - if (f.drawtype == NDT_TORCHLIKE) - param2 = 1; - else if (f.drawtype == NDT_SIGNLIKE || + if (f.drawtype == NDT_TORCHLIKE || + f.drawtype == NDT_SIGNLIKE || f.drawtype == NDT_NODEBOX || - f.drawtype == NDT_MESH) - param2 = 4; + f.drawtype == NDT_MESH) { + n.setParam2(4); + } + } else if (f.drawtype == NDT_SIGNLIKE || f.drawtype == NDT_TORCHLIKE) { + n.setParam2(1); } - gen.renderSingle(id, param2); + gen.renderSingle(n.getContent(), n.getParam2()); colors->clear(); scene::SMesh *mesh = new scene::SMesh(); @@ -392,7 +396,6 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client, bool che case NDT_TORCHLIKE: case NDT_RAILLIKE: case NDT_PLANTLIKE: - case NDT_PLANTLIKE_ROOTED: case NDT_FLOWINGLIQUID: { v3f wscale = def.wield_scale; if (f.drawtype == NDT_FLOWINGLIQUID) @@ -408,14 +411,26 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client, bool che 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: setCube(f, def.wield_scale); break; - default: + default: { // Render non-trivial drawtypes like the actual node - mesh = createSpecialNodeMesh(client, id, &m_colors, f); + MapNode n(id); + n.setParam2(def.place_param2); + + mesh = createSpecialNodeMesh(client, n, &m_colors, f); changeToMesh(mesh); mesh->drop(); m_meshnode->setScale( @@ -423,6 +438,7 @@ void WieldMeshSceneNode::setItem(const ItemStack &item, Client *client, bool che / (BS * f.visual_scale)); break; } + } u32 material_count = m_meshnode->getMaterialCount(); for (u32 i = 0; i < material_count; ++i) { @@ -523,7 +539,7 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result) 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 @@ -585,12 +601,16 @@ void getItemMesh(Client *client, const ItemStack &item, ItemMesh *result) result->buffer_colors.emplace_back(l0.has_color, l0.color); break; } - default: + default: { // Render non-trivial drawtypes like the actual node - mesh = createSpecialNodeMesh(client, id, &result->buffer_colors, f); + MapNode n(id); + n.setParam2(def.place_param2); + + mesh = createSpecialNodeMesh(client, n, &result->buffer_colors, f); scaleMesh(mesh, v3f(0.12, 0.12, 0.12)); break; } + } u32 mc = mesh->getMeshBufferCount(); for (u32 i = 0; i < mc; ++i) { diff --git a/src/clientiface.cpp b/src/clientiface.cpp index 01852c5d1..f35dcd0eb 100644 --- a/src/clientiface.cpp +++ b/src/clientiface.cpp @@ -452,9 +452,6 @@ void RemoteClient::notifyEvent(ClientStateEvent 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; @@ -674,7 +671,6 @@ void ClientInterface::UpdatePlayerList() std::vector<session_t> clients = getClientIDs(); m_clients_names.clear(); - if (!clients.empty()) infostream<<"Players:"<<std::endl; diff --git a/src/clientiface.h b/src/clientiface.h index eabffb0b6..dfd976741 100644 --- a/src/clientiface.h +++ b/src/clientiface.h @@ -25,11 +25,13 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "serialization.h" // for SER_FMT_VER_INVALID #include "network/networkpacket.h" #include "network/networkprotocol.h" +#include "network/address.h" #include "porting.h" #include <list> #include <vector> #include <set> +#include <memory> #include <mutex> class MapBlock; @@ -188,7 +190,6 @@ enum ClientStateEvent { CSE_Hello, CSE_AuthAccept, - CSE_InitLegacy, CSE_GotInit2, CSE_SetDenied, CSE_SetDefinitionsSent, @@ -338,17 +339,24 @@ public: u8 getMajor() const { return m_version_major; } u8 getMinor() const { return m_version_minor; } u8 getPatch() const { return m_version_patch; } - const std::string &getFull() const { return m_full_version; } + const std::string &getFullVer() const { return m_full_version; } void setLangCode(const std::string &code) { m_lang_code = code; } const std::string &getLangCode() const { return m_lang_code; } + + void setCachedAddress(const Address &addr) { m_addr = addr; } + const Address &getAddress() const { return m_addr; } + 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; - + + // Cached here so retrieval doesn't have to go to connection API + Address m_addr; + // Client sent language code std::string m_lang_code; @@ -412,7 +420,7 @@ private: /* client information - */ + */ u8 m_version_major = 0; u8 m_version_minor = 0; u8 m_version_patch = 0; diff --git a/src/constants.h b/src/constants.h index c17f3b6af..3cc3af094 100644 --- a/src/constants.h +++ b/src/constants.h @@ -89,7 +89,7 @@ with this program; if not, write to the Free Software Foundation, Inc., // Size of player's main inventory #define PLAYER_INVENTORY_SIZE (8 * 4) -// Default maximum hit points of a player +// Default maximum health points of a player #define PLAYER_MAX_HP_DEFAULT 20 // Default maximal breath of a player diff --git a/src/content/mods.cpp b/src/content/mods.cpp index 95ab0290a..f791fa797 100644 --- a/src/content/mods.cpp +++ b/src/content/mods.cpp @@ -28,6 +28,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "settings.h" #include "porting.h" #include "convert_json.h" +#include "script/common/c_internal.h" bool parseDependsString(std::string &dep, std::unordered_set<char> &symbols) { @@ -44,20 +45,25 @@ bool parseDependsString(std::string &dep, std::unordered_set<char> &symbols) return !dep.empty(); } +static void log_mod_deprecation(const ModSpec &spec, const std::string &warning) +{ + auto handling_mode = get_deprecated_handling_mode(); + if (handling_mode != DeprecatedHandlingMode::Ignore) { + std::ostringstream os; + os << warning << " (" << spec.name << " at " << spec.path << ")" + << std::endl; + + if (handling_mode == DeprecatedHandlingMode::Error) { + throw ModError(os.str()); + } else { + warningstream << os.str(); + } + } +} + 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(); @@ -78,6 +84,21 @@ void parseModContents(ModSpec &spec) spec.modpack_content = getModsInPath(spec.path, true); } else { + Settings info; + info.readConfigFile((spec.path + DIR_DELIM + "mod.conf").c_str()); + + if (info.exists("name")) + spec.name = info.get("name"); + else + log_mod_deprecation(spec, "Mods not having a mod.conf file with " + "the name is deprecated."); + + if (info.exists("author")) + spec.author = info.get("author"); + + if (info.exists("release")) + spec.release = info.getS32("release"); + // Attempt to load dependencies from mod.conf bool mod_conf_has_depends = false; if (info.exists("depends")) { @@ -109,6 +130,11 @@ void parseModContents(ModSpec &spec) std::vector<std::string> dependencies; std::ifstream is((spec.path + DIR_DELIM + "depends.txt").c_str()); + + if (is.good()) + log_mod_deprecation(spec, "depends.txt is deprecated, " + "please use mod.conf instead."); + while (is.good()) { std::string dep; std::getline(is, dep); @@ -127,14 +153,12 @@ void parseModContents(ModSpec &spec) } } - if (info.exists("description")) { + 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>()); - } + else if (fs::ReadFile(spec.path + DIR_DELIM + "description.txt", + spec.desc)) + log_mod_deprecation(spec, "description.txt is deprecated, please " + "use mod.conf instead."); } } diff --git a/src/content/subgames.cpp b/src/content/subgames.cpp index c6350f2dd..e9dc609b0 100644 --- a/src/content/subgames.cpp +++ b/src/content/subgames.cpp @@ -329,18 +329,16 @@ void loadGameConfAndInitWorld(const std::string &path, const std::string &name, } } - // 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); - game_defaults.removeSecureSettings(); + Settings *game_settings = Settings::getLayer(SL_GAME); + const bool new_game_settings = (game_settings == nullptr); + if (new_game_settings) { + // Called by main-menu without a Server instance running + // -> create and free manually + game_settings = Settings::createLayer(SL_GAME); + } - g_settings->overrideDefaults(&game_defaults); + getGameMinetestConfig(gamespec.path, *game_settings); + game_settings->removeSecureSettings(); infostream << "Initializing world at " << final_path << std::endl; @@ -381,4 +379,8 @@ void loadGameConfAndInitWorld(const std::string &path, const std::string &name, fs::safeWriteToFile(map_meta_path, oss.str()); } + + // The Settings object is no longer needed for created worlds + if (new_game_settings) + delete game_settings; } diff --git a/src/convert_json.cpp b/src/convert_json.cpp index c774aa002..686113fa8 100644 --- a/src/convert_json.cpp +++ b/src/convert_json.cpp @@ -17,63 +17,23 @@ 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 <memory> #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) +void fastWriteJson(const Json::Value &value, std::ostream &to) { - 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; + Json::StreamWriterBuilder builder; + builder["indentation"] = ""; + std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter()); + writer->write(value, &to); } 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); + fastWriteJson(value, oss); return oss.str(); } diff --git a/src/convert_json.h b/src/convert_json.h index d8825acdc..d1d487e77 100644 --- a/src/convert_json.h +++ b/src/convert_json.h @@ -20,8 +20,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once #include <json/json.h> +#include <ostream> -Json::Value fetchJsonValue(const std::string &url, - std::vector<std::string> *extra_headers); +void fastWriteJson(const Json::Value &value, std::ostream &to); std::string fastWriteJson(const Json::Value &value); diff --git a/src/database/database-files.cpp b/src/database/database-files.cpp index d2b0b1543..d9d113b4e 100644 --- a/src/database/database-files.cpp +++ b/src/database/database-files.cpp @@ -19,6 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <cassert> #include <json/json.h> +#include "convert_json.h" #include "database-files.h" #include "remoteplayer.h" #include "settings.h" @@ -36,29 +37,116 @@ PlayerDatabaseFiles::PlayerDatabaseFiles(const std::string &savedir) : m_savedir fs::CreateDir(m_savedir); } -void PlayerDatabaseFiles::serialize(std::ostringstream &os, RemotePlayer *player) +void PlayerDatabaseFiles::deSerialize(RemotePlayer *p, std::istream &is, + const std::string &playername, PlayerSAO *sao) +{ + Settings args("PlayerArgsEnd"); + + if (!args.parseConfigLines(is)) { + throw SerializationError("PlayerArgsEnd of player " + playername + " not found!"); + } + + p->m_dirty = true; + //args.getS32("version"); // Version field value not used + const std::string &name = args.get("name"); + strlcpy(p->m_name, name.c_str(), PLAYERNAME_SIZE); + + if (sao) { + try { + sao->setHPRaw(args.getU16("hp")); + } catch(SettingNotFoundException &e) { + sao->setHPRaw(PLAYER_MAX_HP_DEFAULT); + } + + try { + sao->setBasePosition(args.getV3F("position")); + } catch (SettingNotFoundException &e) {} + + try { + sao->setLookPitch(args.getFloat("pitch")); + } catch (SettingNotFoundException &e) {} + try { + sao->setPlayerYaw(args.getFloat("yaw")); + } catch (SettingNotFoundException &e) {} + + try { + sao->setBreath(args.getU16("breath"), false); + } catch (SettingNotFoundException &e) {} + + try { + const std::string &extended_attributes = args.get("extended_attributes"); + std::istringstream iss(extended_attributes); + Json::CharReaderBuilder builder; + builder.settings_["collectComments"] = false; + std::string errs; + + Json::Value attr_root; + Json::parseFromStream(builder, iss, &attr_root, &errs); + + const Json::Value::Members attr_list = attr_root.getMemberNames(); + for (const auto &it : attr_list) { + Json::Value attr_value = attr_root[it]; + sao->getMeta().setString(it, attr_value.asString()); + } + sao->getMeta().setModified(false); + } catch (SettingNotFoundException &e) {} + } + + try { + p->inventory.deSerialize(is); + } catch (SerializationError &e) { + errorstream << "Failed to deserialize player inventory. player_name=" + << name << " " << e.what() << std::endl; + } + + if (!p->inventory.getList("craftpreview") && p->inventory.getList("craftresult")) { + // Convert players without craftpreview + p->inventory.addList("craftpreview", 1); + + bool craftresult_is_preview = true; + if(args.exists("craftresult_is_preview")) + craftresult_is_preview = args.getBool("craftresult_is_preview"); + if(craftresult_is_preview) + { + // Clear craftresult + p->inventory.getList("craftresult")->changeItem(0, ItemStack()); + } + } +} + +void PlayerDatabaseFiles::serialize(RemotePlayer *p, std::ostream &os) { // Utilize a Settings object for storing values - Settings args; + Settings args("PlayerArgsEnd"); args.setS32("version", 1); - args.set("name", player->getName()); + args.set("name", p->m_name); - 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()); + PlayerSAO *sao = p->getPlayerSAO(); + // This should not happen + sanity_check(sao); + args.setU16("hp", sao->getHP()); + args.setV3F("position", sao->getBasePosition()); + args.setFloat("pitch", sao->getLookPitch()); + args.setFloat("yaw", sao->getRotation().Y); + args.setU16("breath", sao->getBreath()); std::string extended_attrs; - player->serializeExtraAttributes(extended_attrs); + { + // serializeExtraAttributes + Json::Value json_root; + + const StringMap &attrs = sao->getMeta().getStrings(); + for (const auto &attr : attrs) { + json_root[attr.first] = attr.second; + } + + extended_attrs = fastWriteJson(json_root); + } args.set("extended_attributes", extended_attrs); args.writeLines(os); - os << "PlayerArgsEnd\n"; - - player->inventory.serialize(os); + p->inventory.serialize(os); } void PlayerDatabaseFiles::savePlayer(RemotePlayer *player) @@ -83,7 +171,7 @@ void PlayerDatabaseFiles::savePlayer(RemotePlayer *player) return; } - testplayer.deSerialize(is, path, NULL); + deSerialize(&testplayer, is, path, NULL); is.close(); if (strcmp(testplayer.getName(), player->getName()) == 0) { path_found = true; @@ -101,7 +189,7 @@ void PlayerDatabaseFiles::savePlayer(RemotePlayer *player) // Open and serialize file std::ostringstream ss(std::ios_base::binary); - serialize(ss, player); + serialize(player, ss); if (!fs::safeWriteToFile(path, ss.str())) { infostream << "Failed to write " << path << std::endl; } @@ -121,7 +209,7 @@ bool PlayerDatabaseFiles::removePlayer(const std::string &name) if (!is.good()) continue; - temp_player.deSerialize(is, path, NULL); + deSerialize(&temp_player, is, path, NULL); is.close(); if (temp_player.getName() == name) { @@ -147,7 +235,7 @@ bool PlayerDatabaseFiles::loadPlayer(RemotePlayer *player, PlayerSAO *sao) if (!is.good()) continue; - player->deSerialize(is, path, sao); + deSerialize(player, is, path, sao); is.close(); if (player->getName() == player_to_load) @@ -180,7 +268,7 @@ void PlayerDatabaseFiles::listPlayers(std::vector<std::string> &res) // Null env & dummy peer_id PlayerSAO playerSAO(NULL, &player, 15789, false); - player.deSerialize(is, "", &playerSAO); + deSerialize(&player, is, "", &playerSAO); is.close(); res.emplace_back(player.getName()); diff --git a/src/database/database-files.h b/src/database/database-files.h index cb830a3ed..e647a2e24 100644 --- a/src/database/database-files.h +++ b/src/database/database-files.h @@ -38,7 +38,14 @@ public: void listPlayers(std::vector<std::string> &res); private: - void serialize(std::ostringstream &os, RemotePlayer *player); + void deSerialize(RemotePlayer *p, std::istream &is, const std::string &playername, + PlayerSAO *sao); + /* + serialize() writes a bunch of text that can contain + any characters except a '\0', and such an ending that + deSerialize stops reading exactly at the right point. + */ + void serialize(RemotePlayer *p, std::ostream &os); std::string m_savedir; }; diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index 23e06ab05..e16f15512 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -27,8 +27,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapgen/mapgen.h" // Mapgen::setDefaultSettings #include "util/string.h" -void set_default_settings(Settings *settings) +void set_default_settings() { + Settings *settings = Settings::createLayer(SL_DEFAULTS); + // Client and server settings->setDefault("language", ""); settings->setDefault("name", ""); @@ -54,7 +56,7 @@ void set_default_settings(Settings *settings) settings->setDefault("client_unload_unused_data_timeout", "600"); settings->setDefault("client_mapblock_limit", "7500"); settings->setDefault("enable_build_where_you_stand", "true"); - settings->setDefault("curl_timeout", "5000"); + settings->setDefault("curl_timeout", "20000"); settings->setDefault("curl_parallel_limit", "8"); settings->setDefault("curl_file_download_timeout", "300000"); settings->setDefault("curl_verify_cert", "true"); @@ -75,7 +77,7 @@ void set_default_settings(Settings *settings) settings->setDefault("cheat_menu_selected_font_color", "(255, 255, 255)"); settings->setDefault("cheat_menu_selected_font_color_alpha", "235"); settings->setDefault("cheat_menu_head_height", "50"); - settings->setDefault("cheat_menu_entry_height", "40"); + settings->setDefault("cheat_menu_entry_height", "35"); settings->setDefault("cheat_menu_entry_width", "200"); // Cheats @@ -137,7 +139,7 @@ void set_default_settings(Settings *settings) settings->setDefault("keymap_zoom", "KEY_KEY_Z"); settings->setDefault("keymap_inventory", "KEY_KEY_I"); settings->setDefault("keymap_enderchest", "KEY_KEY_O"); - settings->setDefault("keymap_special1", "KEY_KEY_E"); + settings->setDefault("keymap_aux1", "KEY_KEY_E"); settings->setDefault("keymap_chat", "KEY_KEY_T"); settings->setDefault("keymap_cmd", "/"); settings->setDefault("keymap_cmd_local", "."); @@ -154,6 +156,7 @@ void set_default_settings(Settings *settings) settings->setDefault("keymap_increase_volume", ""); settings->setDefault("keymap_decrease_volume", ""); settings->setDefault("keymap_cinematic", ""); + settings->setDefault("keymap_toggle_block_bounds", ""); settings->setDefault("keymap_toggle_hud", "KEY_F1"); settings->setDefault("keymap_toggle_chat", "KEY_F2"); settings->setDefault("keymap_toggle_fog", "KEY_F3"); @@ -306,6 +309,7 @@ void set_default_settings(Settings *settings) #endif settings->setDefault("enable_particles", "true"); settings->setDefault("arm_inertia", "true"); + settings->setDefault("show_nametag_backgrounds", "true"); settings->setDefault("enable_minimap", "true"); settings->setDefault("minimap_shape_round", "false"); @@ -351,7 +355,7 @@ void set_default_settings(Settings *settings) // Main menu settings->setDefault("main_menu_path", ""); - settings->setDefault("serverlist_file", "favoriteservers.txt"); + settings->setDefault("serverlist_file", "favoriteservers.json"); #if USE_FREETYPE settings->setDefault("freetype", "true"); @@ -369,12 +373,7 @@ void set_default_settings(Settings *settings) settings->setDefault("mono_font_path_bold_italic", porting::getDataPath("fonts" DIR_DELIM "Cousine-BoldItalic.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")); @@ -415,7 +414,7 @@ void set_default_settings(Settings *settings) settings->setDefault("max_simultaneous_block_sends_per_client", "40"); settings->setDefault("time_send_interval", "5"); - settings->setDefault("default_game", "mineclone2"); + settings->setDefault("default_game", "MineClone2"); settings->setDefault("motd", ""); settings->setDefault("max_users", "15"); settings->setDefault("creative_mode", "false"); @@ -527,10 +526,9 @@ void set_default_settings(Settings *settings) settings->setDefault("screen_h", "0"); settings->setDefault("fullscreen", "true"); settings->setDefault("touchtarget", "true"); - settings->setDefault("TMPFolder", porting::path_cache); settings->setDefault("touchscreen_threshold","20"); settings->setDefault("fixed_virtual_joystick", "false"); - settings->setDefault("virtual_joystick_triggers_aux", "false"); + settings->setDefault("virtual_joystick_triggers_aux1", "false"); settings->setDefault("smooth_lighting", "false"); settings->setDefault("max_simultaneous_block_sends_per_client", "10"); settings->setDefault("emergequeue_limit_diskonly", "16"); diff --git a/src/defaultsettings.h b/src/defaultsettings.h index c81e88502..c239b3c12 100644 --- a/src/defaultsettings.h +++ b/src/defaultsettings.h @@ -25,11 +25,4 @@ 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); +void set_default_settings(); diff --git a/src/emerge.cpp b/src/emerge.cpp index 12e407797..32e7d9f24 100644 --- a/src/emerge.cpp +++ b/src/emerge.cpp @@ -113,13 +113,15 @@ EmergeParams::~EmergeParams() { infostream << "EmergeParams: destroying " << this << std::endl; // Delete everything that was cloned on creation of EmergeParams + delete biomegen; delete biomemgr; delete oremgr; delete decomgr; delete schemmgr; } -EmergeParams::EmergeParams(EmergeManager *parent, const BiomeManager *biomemgr, +EmergeParams::EmergeParams(EmergeManager *parent, const BiomeGen *biomegen, + const BiomeManager *biomemgr, const OreManager *oremgr, const DecorationManager *decomgr, const SchematicManager *schemmgr) : ndef(parent->ndef), @@ -129,6 +131,7 @@ EmergeParams::EmergeParams(EmergeManager *parent, const BiomeManager *biomemgr, biomemgr(biomemgr->clone()), oremgr(oremgr->clone()), decomgr(decomgr->clone()), schemmgr(schemmgr->clone()) { + this->biomegen = biomegen->clone(this->biomemgr); } //// @@ -143,6 +146,10 @@ EmergeManager::EmergeManager(Server *server) this->decomgr = new DecorationManager(server); this->schemmgr = new SchematicManager(server); + // initialized later + this->mgparams = nullptr; + this->biomegen = nullptr; + // Note that accesses to this variable are not synchronized. // This is because the *only* thread ever starting or stopping // EmergeThreads should be the ServerThread. @@ -240,9 +247,12 @@ void EmergeManager::initMapgens(MapgenParams *params) mgparams = params; + v3s16 csize = v3s16(1, 1, 1) * (params->chunksize * MAP_BLOCKSIZE); + biomegen = biomemgr->createBiomeGen(BIOMEGEN_ORIGINAL, params->bparams, csize); + for (u32 i = 0; i != m_threads.size(); i++) { - EmergeParams *p = new EmergeParams( - this, biomemgr, oremgr, decomgr, schemmgr); + EmergeParams *p = new EmergeParams(this, biomegen, + biomemgr, oremgr, decomgr, schemmgr); infostream << "EmergeManager: Created params " << p << " for thread " << i << std::endl; m_mapgens.push_back(Mapgen::createMapgen(params->mgtype, params, p)); @@ -396,14 +406,7 @@ int EmergeManager::getGroundLevelAtPoint(v2s16 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. + // Use a simple heuristic return blockpos.Y * (MAP_BLOCKSIZE + 1) <= mgparams->water_level; } diff --git a/src/emerge.h b/src/emerge.h index da845e243..aac3e7dd3 100644 --- a/src/emerge.h +++ b/src/emerge.h @@ -99,13 +99,15 @@ public: u32 gen_notify_on; const std::set<u32> *gen_notify_on_deco_ids; // shared + BiomeGen *biomegen; BiomeManager *biomemgr; OreManager *oremgr; DecorationManager *decomgr; SchematicManager *schemmgr; private: - EmergeParams(EmergeManager *parent, const BiomeManager *biomemgr, + EmergeParams(EmergeManager *parent, const BiomeGen *biomegen, + const BiomeManager *biomemgr, const OreManager *oremgr, const DecorationManager *decomgr, const SchematicManager *schemmgr); }; @@ -140,6 +142,8 @@ public: ~EmergeManager(); DISABLE_CLASS_COPY(EmergeManager); + const BiomeGen *getBiomeGen() const { return biomegen; } + // no usage restrictions const BiomeManager *getBiomeManager() const { return biomemgr; } const OreManager *getOreManager() const { return oremgr; } @@ -196,6 +200,7 @@ private: // Managers of various map generation-related components // Note that each Mapgen gets a copy(!) of these to work with + BiomeGen *biomegen; BiomeManager *biomemgr; OreManager *oremgr; DecorationManager *decomgr; diff --git a/src/exceptions.h b/src/exceptions.h index c54307653..a558adc5d 100644 --- a/src/exceptions.h +++ b/src/exceptions.h @@ -72,11 +72,6 @@ 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) {} diff --git a/src/filesys.cpp b/src/filesys.cpp index 28a33f4d0..99b030624 100644 --- a/src/filesys.cpp +++ b/src/filesys.cpp @@ -27,9 +27,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "log.h" #include "config.h" #include "porting.h" -#ifdef __ANDROID__ -#include "settings.h" // For g_settings -#endif namespace fs { @@ -359,8 +356,9 @@ std::string TempPath() compatible with lua's os.tmpname which under the default configuration hardcodes mkstemp("/tmp/lua_XXXXXX"). */ + #ifdef __ANDROID__ - return g_settings->get("TMPFolder"); + return porting::path_cache; #else return DIR_DELIM "tmp"; #endif @@ -401,21 +399,6 @@ void GetRecursiveSubPaths(const std::string &path, } } -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; @@ -744,6 +727,70 @@ bool safeWriteToFile(const std::string &path, const std::string &content) return true; } +bool extractZipFile(io::IFileSystem *fs, const char *filename, const std::string &destination) +{ + if (!fs->addFileArchive(filename, false, false, io::EFAT_ZIP)) { + return false; + } + + sanity_check(fs->getFileArchiveCount() > 0); + + /**********************************************************************/ + /* WARNING this is not threadsafe!! */ + /**********************************************************************/ + io::IFileArchive* opened_zip = fs->getFileArchive(fs->getFileArchiveCount() - 1); + + const io::IFileList* files_in_zip = opened_zip->getFileList(); + + unsigned int number_of_files = files_in_zip->getFileCount(); + + for (unsigned int i=0; i < number_of_files; i++) { + std::string fullpath = destination; + fullpath += DIR_DELIM; + fullpath += files_in_zip->getFullFileName(i).c_str(); + std::string fullpath_dir = fs::RemoveLastPathComponent(fullpath); + + if (!files_in_zip->isDirectory(i)) { + if (!fs::PathExists(fullpath_dir) && !fs::CreateAllDirs(fullpath_dir)) { + fs->removeFileArchive(fs->getFileArchiveCount()-1); + return false; + } + + io::IReadFile* toread = opened_zip->createAndOpenFile(i); + + FILE *targetfile = fopen(fullpath.c_str(),"wb"); + + if (targetfile == NULL) { + fs->removeFileArchive(fs->getFileArchiveCount()-1); + return false; + } + + char read_buffer[1024]; + long total_read = 0; + + while (total_read < toread->getSize()) { + + unsigned int bytes_read = + toread->read(read_buffer,sizeof(read_buffer)); + if ((bytes_read == 0 ) || + (fwrite(read_buffer, 1, bytes_read, targetfile) != bytes_read)) + { + fclose(targetfile); + fs->removeFileArchive(fs->getFileArchiveCount() - 1); + return false; + } + total_read += bytes_read; + } + + fclose(targetfile); + } + + } + + fs->removeFileArchive(fs->getFileArchiveCount() - 1); + return true; +} + bool ReadFile(const std::string &path, std::string &out) { std::ifstream is(path, std::ios::binary | std::ios::ate); diff --git a/src/filesys.h b/src/filesys.h index b2c800c55..a9584b036 100644 --- a/src/filesys.h +++ b/src/filesys.h @@ -36,6 +36,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #define PATH_DELIM ":" #endif +namespace irr { namespace io { +class IFileSystem; +}} + namespace fs { @@ -85,9 +89,6 @@ void GetRecursiveSubPaths(const std::string &path, 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); @@ -128,6 +129,8 @@ const char *GetFilenameFromPath(const char *path); bool safeWriteToFile(const std::string &path, const std::string &content); +bool extractZipFile(irr::io::IFileSystem *fs, const char *filename, const std::string &destination); + bool ReadFile(const std::string &path, std::string &out); bool Rename(const std::string &from, const std::string &to); diff --git a/src/gui/CMakeLists.txt b/src/gui/CMakeLists.txt index f93b85aff..ea6e44ab7 100644 --- a/src/gui/CMakeLists.txt +++ b/src/gui/CMakeLists.txt @@ -24,7 +24,6 @@ set(gui_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/guiTable.cpp ${CMAKE_CURRENT_SOURCE_DIR}/guiHyperText.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 diff --git a/src/gui/StyleSpec.h b/src/gui/StyleSpec.h index f2844ce28..fc92a861b 100644 --- a/src/gui/StyleSpec.h +++ b/src/gui/StyleSpec.h @@ -55,6 +55,8 @@ public: BORDERCOLORS, BORDERWIDTHS, SOUND, + SPACING, + SIZE, NUM_PROPERTIES, NONE }; @@ -119,6 +121,10 @@ public: return BORDERWIDTHS; } else if (name == "sound") { return SOUND; + } else if (name == "spacing") { + return SPACING; + } else if (name == "size") { + return SIZE; } else { return NONE; } @@ -259,27 +265,40 @@ public: return rect; } - irr::core::vector2d<s32> getVector2i(Property prop, irr::core::vector2d<s32> def) const + v2f32 getVector2f(Property prop, v2f32 def) const { const auto &val = properties[prop]; if (val.empty()) return def; - irr::core::vector2d<s32> vec; - if (!parseVector2i(val, &vec)) + v2f32 vec; + if (!parseVector2f(val, &vec)) return def; return vec; } - irr::core::vector2d<s32> getVector2i(Property prop) const + v2s32 getVector2i(Property prop, v2s32 def) const + { + const auto &val = properties[prop]; + if (val.empty()) + return def; + + v2f32 vec; + if (!parseVector2f(val, &vec)) + return def; + + return v2s32(vec.X, vec.Y); + } + + v2s32 getVector2i(Property prop) const { const auto &val = properties[prop]; FATAL_ERROR_IF(val.empty(), "Unexpected missing property"); - irr::core::vector2d<s32> vec; - parseVector2i(val, &vec); - return vec; + v2f32 vec; + parseVector2f(val, &vec); + return v2s32(vec.X, vec.Y); } gui::IGUIFont *getFont() const @@ -432,22 +451,20 @@ private: return true; } - bool parseVector2i(const std::string &value, irr::core::vector2d<s32> *parsed_vec) const + bool parseVector2f(const std::string &value, v2f32 *parsed_vec) const { - irr::core::vector2d<s32> vec; + v2f32 vec; std::vector<std::string> v_vector = split(value, ','); if (v_vector.size() == 1) { - s32 x = stoi(v_vector[0]); + f32 x = stof(v_vector[0]); vec.X = x; vec.Y = x; } else if (v_vector.size() == 2) { - s32 x = stoi(v_vector[0]); - s32 y = stoi(v_vector[1]); - vec.X = x; - vec.Y = y; + vec.X = stof(v_vector[0]); + vec.Y = stof(v_vector[1]); } else { - warningstream << "Invalid vector2d string format: \"" << value + warningstream << "Invalid 2d vector string format: \"" << value << "\"" << std::endl; return false; } diff --git a/src/gui/cheatMenu.cpp b/src/gui/cheatMenu.cpp index 7687f10d9..31acfb780 100644 --- a/src/gui/cheatMenu.cpp +++ b/src/gui/cheatMenu.cpp @@ -30,7 +30,7 @@ FontMode CheatMenu::fontStringToEnum(std::string str) else if (str == "FM_Mono") return FM_Mono; else if (str == "FM_Fallback") - return FM_Fallback; + return _FM_Fallback; else if (str == "FM_Simple") return FM_Simple; else if (str == "FM_SimpleMono") diff --git a/src/gui/guiButton.cpp b/src/gui/guiButton.cpp index b98e5de82..d6dbddf54 100644 --- a/src/gui/guiButton.cpp +++ b/src/gui/guiButton.cpp @@ -506,6 +506,13 @@ video::SColor GUIButton::getOverrideColor() const return OverrideColor;
}
+#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8
+video::SColor GUIButton::getActiveColor() const
+{
+ return video::SColor(0,0,0,0); // unused?
+}
+#endif
+
void GUIButton::enableOverrideColor(bool enable)
{
OverrideColorEnabled = enable;
diff --git a/src/gui/guiButton.h b/src/gui/guiButton.h index 4e1b04aac..834405f51 100644 --- a/src/gui/guiButton.h +++ b/src/gui/guiButton.h @@ -69,6 +69,12 @@ using namespace irr; class ISimpleTextureSource;
+#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8)
+#define OVERRIDE_19
+#else
+#define OVERRIDE_19 override
+#endif
+
class GUIButton : public gui::IGUIButton
{
public:
@@ -97,22 +103,27 @@ public: virtual gui::IGUIFont* getActiveFont() const override;
//! Sets another color for the button text.
- virtual void setOverrideColor(video::SColor color);
+ virtual void setOverrideColor(video::SColor color) OVERRIDE_19;
//! Gets the override color
- virtual video::SColor getOverrideColor(void) const;
+ virtual video::SColor getOverrideColor(void) const OVERRIDE_19;
+
+ #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8
+ //! Gets the currently used text color
+ virtual video::SColor getActiveColor() const override;
+ #endif
//! Sets if the button text should use the override color or the color in the gui skin.
- virtual void enableOverrideColor(bool enable);
+ virtual void enableOverrideColor(bool enable) OVERRIDE_19;
//! Checks if an override color is enabled
- virtual bool isOverrideColorEnabled(void) const;
+ virtual bool isOverrideColorEnabled(void) const OVERRIDE_19;
// PATCH
//! Sets an image which should be displayed on the button when it is in the given state.
virtual void setImage(gui::EGUI_BUTTON_IMAGE_STATE state,
video::ITexture* image=nullptr,
- const core::rect<s32>& sourceRect=core::rect<s32>(0,0,0,0));
+ const core::rect<s32>& sourceRect=core::rect<s32>(0,0,0,0)) OVERRIDE_19;
//! Sets an image which should be displayed on the button when it is in normal state.
virtual void setImage(video::ITexture* image=nullptr) override;
@@ -141,7 +152,7 @@ public: */
virtual void setSprite(gui::EGUI_BUTTON_STATE state, s32 index,
video::SColor color=video::SColor(255,255,255,255),
- bool loop=false, bool scale=false);
+ bool loop=false, bool scale=false) OVERRIDE_19;
#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 8)
void setSprite(gui::EGUI_BUTTON_STATE state, s32 index, video::SColor color, bool loop) override {
@@ -150,16 +161,16 @@ public: #endif
//! Get the sprite-index for the given state or -1 when no sprite is set
- virtual s32 getSpriteIndex(gui::EGUI_BUTTON_STATE state) const;
+ virtual s32 getSpriteIndex(gui::EGUI_BUTTON_STATE state) const OVERRIDE_19;
//! Get the sprite color for the given state. Color is only used when a sprite is set.
- virtual video::SColor getSpriteColor(gui::EGUI_BUTTON_STATE state) const;
+ virtual video::SColor getSpriteColor(gui::EGUI_BUTTON_STATE state) const OVERRIDE_19;
//! Returns if the sprite in the given state does loop
- virtual bool getSpriteLoop(gui::EGUI_BUTTON_STATE state) const;
+ virtual bool getSpriteLoop(gui::EGUI_BUTTON_STATE state) const OVERRIDE_19;
//! Returns if the sprite in the given state is scaled
- virtual bool getSpriteScale(gui::EGUI_BUTTON_STATE state) const;
+ virtual bool getSpriteScale(gui::EGUI_BUTTON_STATE state) const OVERRIDE_19;
//! Sets if the button should behave like a push button. Which means it
//! can be in two states: Normal or Pressed. With a click on the button,
@@ -199,13 +210,13 @@ public: virtual bool isScalingImage() const override;
//! Get if the shift key was pressed in last EGET_BUTTON_CLICKED event
- virtual bool getClickShiftState() const
+ virtual bool getClickShiftState() const OVERRIDE_19
{
return ClickShiftState;
}
//! Get if the control key was pressed in last EGET_BUTTON_CLICKED event
- virtual bool getClickControlState() const
+ virtual bool getClickControlState() const OVERRIDE_19
{
return ClickControlState;
}
diff --git a/src/gui/guiButtonItemImage.cpp b/src/gui/guiButtonItemImage.cpp index d8b9042ac..d9ab4b935 100644 --- a/src/gui/guiButtonItemImage.cpp +++ b/src/gui/guiButtonItemImage.cpp @@ -30,7 +30,7 @@ using namespace gui; GUIButtonItemImage::GUIButtonItemImage(gui::IGUIEnvironment *environment, gui::IGUIElement *parent, s32 id, core::rect<s32> rectangle, - ISimpleTextureSource *tsrc, std::string item, Client *client, + ISimpleTextureSource *tsrc, const std::string &item, Client *client, bool noclip) : GUIButton (environment, parent, id, rectangle, tsrc, noclip) { @@ -39,13 +39,12 @@ GUIButtonItemImage::GUIButtonItemImage(gui::IGUIEnvironment *environment, item, getActiveFont(), client); sendToBack(m_image); - m_item_name = item; m_client = client; } GUIButtonItemImage *GUIButtonItemImage::addButton(IGUIEnvironment *environment, const core::rect<s32> &rectangle, ISimpleTextureSource *tsrc, - IGUIElement *parent, s32 id, const wchar_t *text, std::string item, + IGUIElement *parent, s32 id, const wchar_t *text, const std::string &item, Client *client) { GUIButtonItemImage *button = new GUIButtonItemImage(environment, diff --git a/src/gui/guiButtonItemImage.h b/src/gui/guiButtonItemImage.h index aad923bda..205e957a7 100644 --- a/src/gui/guiButtonItemImage.h +++ b/src/gui/guiButtonItemImage.h @@ -33,16 +33,15 @@ public: //! constructor GUIButtonItemImage(gui::IGUIEnvironment *environment, gui::IGUIElement *parent, s32 id, core::rect<s32> rectangle, ISimpleTextureSource *tsrc, - std::string item, Client *client, bool noclip = false); + const std::string &item, Client *client, bool noclip = false); //! Do not drop returned handle static GUIButtonItemImage *addButton(gui::IGUIEnvironment *environment, const core::rect<s32> &rectangle, ISimpleTextureSource *tsrc, - IGUIElement *parent, s32 id, const wchar_t *text, std::string item, - Client *client); + IGUIElement *parent, s32 id, const wchar_t *text, + const std::string &item, Client *client); private: - std::string m_item_name; Client *m_client; GUIItemImage *m_image; }; diff --git a/src/gui/guiChatConsole.cpp b/src/gui/guiChatConsole.cpp index ef471106d..baaaea5e8 100644 --- a/src/gui/guiChatConsole.cpp +++ b/src/gui/guiChatConsole.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ +#include "IrrCompileConfig.h" #include "guiChatConsole.h" #include "chat.h" #include "client/client.h" @@ -326,7 +327,6 @@ void GUIChatConsole::drawText() tmp->draw( fragment.text, destrect, - video::SColor(255, 255, 255, 255), false, false, &AbsoluteClippingRect); @@ -607,13 +607,7 @@ bool GUIChatConsole::OnEvent(const SEvent& event) 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 + prompt.input(event.KeyInput.Char); return true; } } @@ -625,6 +619,13 @@ bool GUIChatConsole::OnEvent(const SEvent& event) m_chat_backend->scroll(rows); } } +#if (IRRLICHT_VERSION_MT_REVISION >= 2) + else if(event.EventType == EET_STRING_INPUT_EVENT) + { + prompt.input(std::wstring(event.StringInput.Str->c_str())); + return true; + } +#endif return Parent ? Parent->OnEvent(event) : false; } diff --git a/src/gui/guiChatConsole.h b/src/gui/guiChatConsole.h index 204f9f9cc..1152f2b2d 100644 --- a/src/gui/guiChatConsole.h +++ b/src/gui/guiChatConsole.h @@ -68,12 +68,12 @@ public: // Irrlicht draw method virtual void draw(); - bool canTakeFocus(gui::IGUIElement* element) { return false; } - virtual bool OnEvent(const SEvent& event); virtual void setVisible(bool visible); + virtual bool acceptsIME() { return true; } + private: void reformatConsole(); void recalculateConsolePosition(); diff --git a/src/gui/guiConfirmRegistration.cpp b/src/gui/guiConfirmRegistration.cpp index 020a2796a..4ca9a64ed 100644 --- a/src/gui/guiConfirmRegistration.cpp +++ b/src/gui/guiConfirmRegistration.cpp @@ -25,7 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <IGUIButton.h> #include <IGUIStaticText.h> #include <IGUIFont.h> -#include "intlGUIEditBox.h" +#include "guiEditBoxWithScrollbar.h" #include "porting.h" #include "gettext.h" @@ -109,10 +109,9 @@ void GUIConfirmRegistration::regenerateGui(v2u32 screensize) 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_intotext, rect2, false, true); - delete[] info_text_buf_wide; + std::wstring info_text_w = utf8_to_wide(info_text_buf); + gui::IGUIEditBox *e = new GUIEditBoxWithScrollBar(info_text_w.c_str(), + true, Environment, this, ID_intotext, rect2, false, true); e->drop(); e->setMultiLine(true); e->setWordWrap(true); @@ -192,8 +191,7 @@ void GUIConfirmRegistration::acceptInput() bool GUIConfirmRegistration::processInput() { - std::wstring m_password_ws = narrow_to_wide(m_password); - if (m_password_ws != m_pass_confirm) { + if (utf8_to_wide(m_password) != m_pass_confirm) { gui::IGUIElement *e = getElementFromId(ID_message); if (e) e->setVisible(true); diff --git a/src/gui/guiEditBox.cpp b/src/gui/guiEditBox.cpp index 11d080be9..ba548aa2d 100644 --- a/src/gui/guiEditBox.cpp +++ b/src/gui/guiEditBox.cpp @@ -19,6 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "guiEditBox.h" +#include "IrrCompileConfig.h" #include "IGUISkin.h" #include "IGUIEnvironment.h" #include "IGUIFont.h" @@ -208,35 +209,19 @@ bool GUIEditBox::OnEvent(const SEvent &event) } } break; - case EET_KEY_INPUT_EVENT: { -#if (defined(__linux__) || defined(__FreeBSD__)) || defined(__DragonFly__) - // ################################################################ - // ValkaTR: - // This part is the difference from the original intlGUIEditBox - // It converts UTF-8 character into a UCS-2 (wchar_t) - wchar_t wc = L'_'; - mbtowc(&wc, (char *)&event.KeyInput.Char, - sizeof(event.KeyInput.Char)); - - // printf( "char: %lc (%u) \r\n", wc, wc ); - - SEvent irrevent(event); - irrevent.KeyInput.Char = wc; - // ################################################################ - - if (processKey(irrevent)) - return true; -#else + case EET_KEY_INPUT_EVENT: if (processKey(event)) return true; -#endif // defined(linux) - break; - } case EET_MOUSE_INPUT_EVENT: if (processMouse(event)) return true; break; +#if (IRRLICHT_VERSION_MT_REVISION >= 2) + case EET_STRING_INPUT_EVENT: + inputString(*event.StringInput.Str); + return true; +#endif default: break; } @@ -689,6 +674,51 @@ bool GUIEditBox::onKeyDelete(const SEvent &event, s32 &mark_begin, s32 &mark_end return true; } +void GUIEditBox::inputChar(wchar_t c) +{ + if (c == 0) + return; + core::stringw s(&c, 1); + inputString(s); +} + +void GUIEditBox::inputString(const core::stringw &str) +{ + if (!isEnabled() || !m_writable) + return; + + u32 len = str.size(); + if (Text.size()+len <= m_max || m_max == 0) { + core::stringw s; + if (m_mark_begin != m_mark_end) { + // replace marked text + s32 real_begin = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end; + s32 real_end = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin; + + s = Text.subString(0, real_begin); + s.append(str); + s.append(Text.subString(real_end, Text.size() - real_end)); + Text = s; + m_cursor_pos = real_begin + len; + } else { + // append string + s = Text.subString(0, m_cursor_pos); + s.append(str); + s.append(Text.subString(m_cursor_pos, + Text.size() - m_cursor_pos)); + Text = s; + m_cursor_pos += len; + } + + m_blink_start_time = porting::getTimeMs(); + setTextMarkers(0, 0); + } + + breakText(); + sendGuiEvent(EGET_EDITBOX_CHANGED); + calculateScrollPos(); +} + bool GUIEditBox::processMouse(const SEvent &event) { switch (event.MouseInput.Event) { @@ -747,6 +777,7 @@ bool GUIEditBox::processMouse(const SEvent &event) s32 pos = m_vscrollbar->getPos(); s32 step = m_vscrollbar->getSmallStep(); m_vscrollbar->setPos(pos - event.MouseInput.Wheel * step); + return true; } break; default: @@ -817,3 +848,54 @@ void GUIEditBox::updateVScrollBar() } } } + +void GUIEditBox::deserializeAttributes( + io::IAttributes *in, io::SAttributeReadWriteOptions *options = 0) +{ + IGUIEditBox::deserializeAttributes(in, options); + + 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.empty()) + setPasswordBox(in->getAttributeAsBool("PasswordBox")); + else + setPasswordBox(in->getAttributeAsBool("PasswordBox"), ch[0]); + + setTextAlignment((EGUI_ALIGNMENT)in->getAttributeAsEnumeration( + "HTextAlign", GUIAlignmentNames), + (EGUI_ALIGNMENT)in->getAttributeAsEnumeration( + "VTextAlign", GUIAlignmentNames)); + + setWritable(in->getAttributeAsBool("Writable")); + // setOverrideFont(in->getAttributeAsFont("OverrideFont")); +} + +//! Writes attributes of the element. +void GUIEditBox::serializeAttributes( + io::IAttributes *out, io::SAttributeReadWriteOptions *options = 0) const +{ + // IGUIEditBox::serializeAttributes(out,options); + + out->addBool("OverrideColorEnabled", m_override_color_enabled); + out->addColor("OverrideColor", m_override_color); + // out->addFont("OverrideFont",m_override_font); + 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); +} diff --git a/src/gui/guiEditBox.h b/src/gui/guiEditBox.h index 3e41c7e51..2a5c911bc 100644 --- a/src/gui/guiEditBox.h +++ b/src/gui/guiEditBox.h @@ -19,6 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once +#include "irrlichttypes.h" #include "IGUIEditBox.h" #include "IOSOperator.h" #include "guiScrollBar.h" @@ -129,6 +130,16 @@ public: //! called if an event happened. virtual bool OnEvent(const SEvent &event); + //! 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 acceptsIME() { return isEnabled() && m_writable; }; + protected: virtual void breakText() = 0; @@ -147,7 +158,8 @@ protected: virtual s32 getCursorPos(s32 x, s32 y) = 0; bool processKey(const SEvent &event); - virtual void inputChar(wchar_t c) = 0; + virtual void inputString(const core::stringw &str); + virtual void inputChar(wchar_t c); //! returns the line number that the cursor is on s32 getLineFromPos(s32 pos); diff --git a/src/gui/guiEditBoxWithScrollbar.cpp b/src/gui/guiEditBoxWithScrollbar.cpp index 707dbb7db..c72070787 100644 --- a/src/gui/guiEditBoxWithScrollbar.cpp +++ b/src/gui/guiEditBoxWithScrollbar.cpp @@ -481,44 +481,6 @@ void GUIEditBoxWithScrollBar::setTextRect(s32 line) m_current_text_rect += m_frame_rect.UpperLeftCorner; } - -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() { @@ -682,54 +644,21 @@ void GUIEditBoxWithScrollBar::setBackgroundColor(const video::SColor &bg_color) //! 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); + + GUIEditBox::serializeAttributes(out, options); } //! Reads attributes of the element void GUIEditBoxWithScrollBar::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options = 0) { - IGUIEditBox::deserializeAttributes(in, options); + GUIEditBox::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; } diff --git a/src/gui/guiEditBoxWithScrollbar.h b/src/gui/guiEditBoxWithScrollbar.h index b863ee614..3f7450dcb 100644 --- a/src/gui/guiEditBoxWithScrollbar.h +++ b/src/gui/guiEditBoxWithScrollbar.h @@ -49,8 +49,6 @@ protected: virtual void breakText(); //! sets the area of the given line virtual void setTextRect(s32 line); - //! adds a letter to the edit box - virtual void inputChar(wchar_t c); //! calculates the current scroll position void calculateScrollPos(); //! calculated the FrameRect diff --git a/src/gui/guiEngine.cpp b/src/gui/guiEngine.cpp index c5ad5c323..694baf482 100644 --- a/src/gui/guiEngine.cpp +++ b/src/gui/guiEngine.cpp @@ -75,8 +75,6 @@ video::ITexture *MenuTextureSource::getTexture(const std::string &name, u32 *id) if (name.empty()) return NULL; - m_to_delete.insert(name); - #if ENABLE_GLES video::ITexture *retval = m_driver->findTexture(name.c_str()); if (retval) @@ -88,6 +86,7 @@ video::ITexture *MenuTextureSource::getTexture(const std::string &name, u32 *id) image = Align2Npot2(image, m_driver); retval = m_driver->addTexture(name.c_str(), image); + m_to_delete.insert(name); image->drop(); return retval; #else @@ -122,12 +121,14 @@ void MenuMusicFetcher::fetchSounds(const std::string &name, /******************************************************************************/ GUIEngine::GUIEngine(JoystickController *joystick, gui::IGUIElement *parent, + RenderingEngine *rendering_engine, IMenuManager *menumgr, MainMenuData *data, bool &kill) : + m_rendering_engine(rendering_engine), m_parent(parent), m_menumanager(menumgr), - m_smgr(RenderingEngine::get_scene_manager()), + m_smgr(rendering_engine->get_scene_manager()), m_data(data), m_kill(kill) { @@ -139,7 +140,7 @@ GUIEngine::GUIEngine(JoystickController *joystick, m_buttonhandler = new TextDestGuiEngine(this); //create texture source - m_texture_source = new MenuTextureSource(RenderingEngine::get_video_driver()); + m_texture_source = new MenuTextureSource(rendering_engine->get_video_driver()); //create soundmanager MenuMusicFetcher soundfetcher; @@ -157,7 +158,7 @@ GUIEngine::GUIEngine(JoystickController *joystick, g_fontengine->getTextHeight()); rect += v2s32(4, 0); - m_irr_toplefttext = gui::StaticText::add(RenderingEngine::get_gui_env(), + m_irr_toplefttext = gui::StaticText::add(rendering_engine->get_gui_env(), m_toplefttext, rect, false, true, 0, -1); //create formspecsource @@ -169,6 +170,7 @@ GUIEngine::GUIEngine(JoystickController *joystick, -1, m_menumanager, NULL /* &client */, + m_rendering_engine->get_gui_env(), m_texture_source, m_sound_manager, m_formspecgui, @@ -233,7 +235,7 @@ 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(); + video::IVideoDriver *driver = m_rendering_engine->get_video_driver(); cloudInit(); @@ -260,10 +262,10 @@ void GUIEngine::run() fog_pixelfog, fog_rangefog); } - while (RenderingEngine::run() && (!m_startgame) && (!m_kill)) { + while (m_rendering_engine->run() && (!m_startgame) && (!m_kill)) { const irr::core::dimension2d<u32> ¤t_screen_size = - RenderingEngine::get_video_driver()->getScreenSize(); + m_rendering_engine->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 @@ -294,11 +296,11 @@ void GUIEngine::run() drawHeader(driver); drawFooter(driver); - RenderingEngine::get_gui_env()->drawAll(); + m_rendering_engine->get_gui_env()->drawAll(); driver->endScene(); - IrrlichtDevice *device = RenderingEngine::get_raw_device(); + IrrlichtDevice *device = m_rendering_engine->get_raw_device(); u32 frametime_min = 1000 / (device->isWindowFocused() ? g_settings->getFloat("fps_max") : g_settings->getFloat("fps_max_unfocused")); @@ -331,7 +333,7 @@ GUIEngine::~GUIEngine() //clean up texture pointers for (image_definition &texture : m_textures) { if (texture.texture) - RenderingEngine::get_video_driver()->removeTexture(texture.texture); + m_rendering_engine->get_video_driver()->removeTexture(texture.texture); } delete m_texture_source; @@ -351,13 +353,13 @@ void GUIEngine::cloudInit() v3f(0,0,0), v3f(0, 60, 100)); m_cloud.camera->setFarValue(10000); - m_cloud.lasttime = RenderingEngine::get_timer_time(); + m_cloud.lasttime = m_rendering_engine->get_timer_time(); } /******************************************************************************/ void GUIEngine::cloudPreProcess() { - u32 time = RenderingEngine::get_timer_time(); + u32 time = m_rendering_engine->get_timer_time(); if(time > m_cloud.lasttime) m_cloud.dtime = (time - m_cloud.lasttime) / 1000.0; @@ -378,7 +380,7 @@ void GUIEngine::cloudPostProcess(u32 frametime_min, IrrlichtDevice *device) u32 busytime_u32; // not using getRealTime is necessary for wine - u32 time = RenderingEngine::get_timer_time(); + u32 time = m_rendering_engine->get_timer_time(); if(time > m_cloud.lasttime) busytime_u32 = time - m_cloud.lasttime; else @@ -486,8 +488,6 @@ void GUIEngine::drawHeader(video::IVideoDriver *driver) 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())), @@ -531,7 +531,7 @@ void GUIEngine::drawFooter(video::IVideoDriver *driver) bool GUIEngine::setTexture(texture_layer layer, const std::string &texturepath, bool tile_image, unsigned int minsize) { - video::IVideoDriver *driver = RenderingEngine::get_video_driver(); + video::IVideoDriver *driver = m_rendering_engine->get_video_driver(); if (m_textures[layer].texture) { driver->removeTexture(m_textures[layer].texture); @@ -598,7 +598,7 @@ void GUIEngine::updateTopLeftTextSize() rect += v2s32(4, 0); m_irr_toplefttext->remove(); - m_irr_toplefttext = gui::StaticText::add(RenderingEngine::get_gui_env(), + m_irr_toplefttext = gui::StaticText::add(m_rendering_engine->get_gui_env(), m_toplefttext, rect, false, true, 0, -1); } diff --git a/src/gui/guiEngine.h b/src/gui/guiEngine.h index eef1ad8aa..70abce181 100644 --- a/src/gui/guiEngine.h +++ b/src/gui/guiEngine.h @@ -50,6 +50,7 @@ struct image_definition { /* forward declarations */ /******************************************************************************/ class GUIEngine; +class RenderingEngine; class MainMenuScripting; class Clouds; struct MainMenuData; @@ -150,6 +151,7 @@ public: */ GUIEngine(JoystickController *joystick, gui::IGUIElement *parent, + RenderingEngine *rendering_engine, IMenuManager *menumgr, MainMenuData *data, bool &kill); @@ -188,6 +190,7 @@ private: /** update size of topleftext element */ void updateTopLeftTextSize(); + RenderingEngine *m_rendering_engine = nullptr; /** parent gui element */ gui::IGUIElement *m_parent = nullptr; /** manager to add menus to */ diff --git a/src/gui/guiFormSpecMenu.cpp b/src/gui/guiFormSpecMenu.cpp index 973fc60a8..c6435804f 100644 --- a/src/gui/guiFormSpecMenu.cpp +++ b/src/gui/guiFormSpecMenu.cpp @@ -19,6 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <cstdlib> +#include <cmath> #include <algorithm> #include <iterator> #include <limits> @@ -64,7 +65,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "guiInventoryList.h" #include "guiItemImage.h" #include "guiScrollContainer.h" -#include "intlGUIEditBox.h" #include "guiHyperText.h" #include "guiScene.h" @@ -96,10 +96,10 @@ inline u32 clamp_u8(s32 value) GUIFormSpecMenu::GUIFormSpecMenu(JoystickController *joystick, gui::IGUIElement *parent, s32 id, IMenuManager *menumgr, - Client *client, ISimpleTextureSource *tsrc, ISoundManager *sound_manager, - IFormSource *fsrc, TextDest *tdst, + Client *client, gui::IGUIEnvironment *guienv, ISimpleTextureSource *tsrc, + ISoundManager *sound_manager, IFormSource *fsrc, TextDest *tdst, const std::string &formspecPrepend, bool remap_dbl_click): - GUIModalMenu(RenderingEngine::get_gui_env(), parent, id, menumgr, remap_dbl_click), + GUIModalMenu(guienv, parent, id, menumgr, remap_dbl_click), m_invmgr(client), m_tsrc(tsrc), m_sound_manager(sound_manager), @@ -145,12 +145,12 @@ GUIFormSpecMenu::~GUIFormSpecMenu() } void GUIFormSpecMenu::create(GUIFormSpecMenu *&cur_formspec, Client *client, - JoystickController *joystick, IFormSource *fs_src, TextDest *txt_dest, - const std::string &formspecPrepend, ISoundManager *sound_manager) + gui::IGUIEnvironment *guienv, JoystickController *joystick, IFormSource *fs_src, + TextDest *txt_dest, const std::string &formspecPrepend, ISoundManager *sound_manager) { if (cur_formspec == nullptr) { cur_formspec = new GUIFormSpecMenu(joystick, guiroot, -1, &g_menumgr, - client, client->getTextureSource(), sound_manager, fs_src, + client, guienv, client->getTextureSource(), sound_manager, fs_src, txt_dest, formspecPrepend); cur_formspec->doPause = false; @@ -497,19 +497,39 @@ void GUIFormSpecMenu::parseList(parserData *data, const std::string &element) 3 ); - v2f32 slot_spacing = data->real_coordinates ? - v2f32(imgsize.X * 1.25f, imgsize.Y * 1.25f) : spacing; + auto style = getDefaultStyleForElement("list", spec.fname); - v2s32 pos = data->real_coordinates ? getRealCoordinateBasePos(v_pos) - : getElementBasePos(&v_pos); + v2f32 slot_scale = style.getVector2f(StyleSpec::SIZE, v2f32(0, 0)); + v2f32 slot_size( + slot_scale.X <= 0 ? imgsize.X : std::max<f32>(slot_scale.X * imgsize.X, 1), + slot_scale.Y <= 0 ? imgsize.Y : std::max<f32>(slot_scale.Y * imgsize.Y, 1) + ); + + v2f32 slot_spacing = style.getVector2f(StyleSpec::SPACING, v2f32(-1, -1)); + v2f32 default_spacing = data->real_coordinates ? + v2f32(imgsize.X * 0.25f, imgsize.Y * 0.25f) : + v2f32(spacing.X - imgsize.X, spacing.Y - imgsize.Y); + + slot_spacing.X = slot_spacing.X < 0 ? default_spacing.X : + imgsize.X * slot_spacing.X; + slot_spacing.Y = slot_spacing.Y < 0 ? default_spacing.Y : + imgsize.Y * slot_spacing.Y; + + slot_spacing += slot_size; + + v2s32 pos = data->real_coordinates ? getRealCoordinateBasePos(v_pos) : + getElementBasePos(&v_pos); core::rect<s32> rect = core::rect<s32>(pos.X, pos.Y, - pos.X + (geom.X - 1) * slot_spacing.X + imgsize.X, - pos.Y + (geom.Y - 1) * slot_spacing.Y + imgsize.Y); + pos.X + (geom.X - 1) * slot_spacing.X + slot_size.X, + pos.Y + (geom.Y - 1) * slot_spacing.Y + slot_size.Y); GUIInventoryList *e = new GUIInventoryList(Environment, data->current_parent, - spec.fid, rect, m_invmgr, loc, listname, geom, start_i, imgsize, - slot_spacing, this, data->inventorylist_options, m_font); + spec.fid, rect, m_invmgr, loc, listname, geom, start_i, + v2s32(slot_size.X, slot_size.Y), slot_spacing, this, + data->inventorylist_options, m_font); + + e->setNotClipped(style.getBool(StyleSpec::NOCLIP, false)); m_inventorylists.push_back(e); m_fields.push_back(spec); @@ -907,7 +927,7 @@ void GUIFormSpecMenu::parseAnimatedImage(parserData *data, const std::string &el core::rect<s32> rect = core::rect<s32>(pos, pos + geom); - GUIAnimatedImage *e = new GUIAnimatedImage(Environment, this, spec.fid, + GUIAnimatedImage *e = new GUIAnimatedImage(Environment, data->current_parent, spec.fid, rect, texture_name, frame_count, frame_duration, m_tsrc); if (parts.size() >= 7) @@ -1526,21 +1546,13 @@ void GUIFormSpecMenu::createTextField(parserData *data, FieldSpec &spec, } gui::IGUIEditBox *e = nullptr; - static constexpr bool use_intl_edit_box = USE_FREETYPE && - IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 9; - - if (use_intl_edit_box && g_settings->getBool("freetype")) { - e = new gui::intlGUIEditBox(spec.fdefault.c_str(), true, Environment, - data->current_parent, spec.fid, rect, is_editable, is_multiline); - } else { - if (is_multiline) { - e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true, Environment, - data->current_parent, spec.fid, rect, is_editable, true); - } else if (is_editable) { - e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, - data->current_parent, spec.fid); - e->grab(); - } + if (is_multiline) { + e = new GUIEditBoxWithScrollBar(spec.fdefault.c_str(), true, Environment, + data->current_parent, spec.fid, rect, is_editable, true); + } else if (is_editable) { + e = Environment->addEditBox(spec.fdefault.c_str(), rect, true, + data->current_parent, spec.fid); + e->grab(); } auto style = getDefaultStyleForElement(is_multiline ? "textarea" : "field", spec.fname); @@ -2725,7 +2737,7 @@ void GUIFormSpecMenu::parseModel(parserData *data, const std::string &element) { std::vector<std::string> parts = split(element, ';'); - if (parts.size() < 5 || (parts.size() > 9 && + if (parts.size() < 5 || (parts.size() > 10 && m_formspec_version <= FORMSPEC_API_VERSION)) { errorstream << "Invalid model element (" << parts.size() << "): '" << element << "'" << std::endl; @@ -2733,8 +2745,8 @@ void GUIFormSpecMenu::parseModel(parserData *data, const std::string &element) } // Avoid length checks by resizing - if (parts.size() < 9) - parts.resize(9); + if (parts.size() < 10) + parts.resize(10); std::vector<std::string> v_pos = split(parts[0], ','); std::vector<std::string> v_geom = split(parts[1], ','); @@ -2745,6 +2757,7 @@ void GUIFormSpecMenu::parseModel(parserData *data, const std::string &element) bool inf_rotation = is_yes(parts[6]); bool mousectrl = is_yes(parts[7]) || parts[7].empty(); // default true std::vector<std::string> frame_loop = split(parts[8], ','); + std::string speed = unescape_string(parts[9]); MY_CHECKPOS("model", 0); MY_CHECKGEOM("model", 1); @@ -2781,7 +2794,7 @@ void GUIFormSpecMenu::parseModel(parserData *data, const std::string &element) core::rect<s32> rect(pos, pos + geom); - GUIScene *e = new GUIScene(Environment, RenderingEngine::get_scene_manager(), + GUIScene *e = new GUIScene(Environment, m_client->getSceneManager(), data->current_parent, rect, spec.fid); auto meshnode = e->setMesh(mesh); @@ -2804,6 +2817,7 @@ void GUIFormSpecMenu::parseModel(parserData *data, const std::string &element) } e->setFrameLoop(frame_loop_begin, frame_loop_end); + e->setAnimationSpeed(stof(speed)); auto style = getStyleForElement("model", spec.fname); e->setStyles(style); @@ -3505,8 +3519,6 @@ bool GUIFormSpecMenu::getAndroidUIInput() GUIInventoryList::ItemSpec GUIFormSpecMenu::getItemAtPos(v2s32 p) const { - core::rect<s32> imgrect(0, 0, imgsize.X, imgsize.Y); - for (const GUIInventoryList *e : m_inventorylists) { s32 item_index = e->getItemIndexAtPos(p); if (item_index != -1) @@ -3837,7 +3849,7 @@ ItemStack GUIFormSpecMenu::verifySelectedItem() return ItemStack(); } -void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode=quit_mode_no) +void GUIFormSpecMenu::acceptInput(FormspecQuitMode quitmode) { if(m_text_dst) { diff --git a/src/gui/guiFormSpecMenu.h b/src/gui/guiFormSpecMenu.h index 37106cb65..926de66d5 100644 --- a/src/gui/guiFormSpecMenu.h +++ b/src/gui/guiFormSpecMenu.h @@ -152,6 +152,7 @@ public: gui::IGUIElement* parent, s32 id, IMenuManager *menumgr, Client *client, + gui::IGUIEnvironment *guienv, ISimpleTextureSource *tsrc, ISoundManager *sound_manager, IFormSource* fs_src, @@ -162,8 +163,9 @@ public: ~GUIFormSpecMenu(); static void create(GUIFormSpecMenu *&cur_formspec, Client *client, - JoystickController *joystick, IFormSource *fs_src, TextDest *txt_dest, - const std::string &formspecPrepend, ISoundManager *sound_manager); + gui::IGUIEnvironment *guienv, JoystickController *joystick, IFormSource *fs_src, + TextDest *txt_dest, const std::string &formspecPrepend, + ISoundManager *sound_manager); void setFormSpec(const std::string &formspec_string, const InventoryLocation ¤t_inventory_location) @@ -253,7 +255,7 @@ public: void updateSelectedItem(); ItemStack verifySelectedItem(); - void acceptInput(FormspecQuitMode quitmode); + void acceptInput(FormspecQuitMode quitmode=quit_mode_no); bool preprocessEvent(const SEvent& event); bool OnEvent(const SEvent& event); bool doPause; diff --git a/src/gui/guiHyperText.cpp b/src/gui/guiHyperText.cpp index 88931cdf9..ccfdcb81d 100644 --- a/src/gui/guiHyperText.cpp +++ b/src/gui/guiHyperText.cpp @@ -1088,7 +1088,7 @@ bool GUIHyperText::OnEvent(const SEvent &event) if (event.MouseInput.Event == EMIE_MOUSE_MOVED) checkHover(event.MouseInput.X, event.MouseInput.Y); - if (event.MouseInput.Event == EMIE_MOUSE_WHEEL) { + if (event.MouseInput.Event == EMIE_MOUSE_WHEEL && m_vscrollbar->isVisible()) { m_vscrollbar->setPos(m_vscrollbar->getPos() - event.MouseInput.Wheel * m_vscrollbar->getSmallStep()); m_text_scrollpos.Y = -m_vscrollbar->getPos(); diff --git a/src/gui/guiInventoryList.cpp b/src/gui/guiInventoryList.cpp index 58d7ae771..290ae40e7 100644 --- a/src/gui/guiInventoryList.cpp +++ b/src/gui/guiInventoryList.cpp @@ -101,8 +101,6 @@ void GUIInventoryList::draw() && m_invmgr->getInventory(selected_item->inventoryloc) == inv && selected_item->listname == m_listname && selected_item->i == item_i; - core::rect<s32> clipped_rect(rect); - clipped_rect.clipAgainst(AbsoluteClippingRect); bool hovering = m_hovered_i == item_i; ItemRotationKind rotation_kind = selected ? IT_ROT_SELECTED : (hovering ? IT_ROT_HOVERED : IT_ROT_NONE); diff --git a/src/gui/guiKeyChangeMenu.cpp b/src/gui/guiKeyChangeMenu.cpp index a7270da06..719a4101a 100644 --- a/src/gui/guiKeyChangeMenu.cpp +++ b/src/gui/guiKeyChangeMenu.cpp @@ -46,7 +46,7 @@ enum GUI_ID_KEY_BACKWARD_BUTTON, GUI_ID_KEY_LEFT_BUTTON, GUI_ID_KEY_RIGHT_BUTTON, - GUI_ID_KEY_USE_BUTTON, + GUI_ID_KEY_AUX1_BUTTON, GUI_ID_KEY_FLY_BUTTON, GUI_ID_KEY_FAST_BUTTON, GUI_ID_KEY_JUMP_BUTTON, @@ -71,6 +71,7 @@ enum GUI_ID_KEY_MINIMAP_BUTTON, GUI_ID_KEY_SCREENSHOT_BUTTON, GUI_ID_KEY_CHATLOG_BUTTON, + GUI_ID_KEY_BLOCK_BOUNDS_BUTTON, GUI_ID_KEY_HUD_BUTTON, GUI_ID_KEY_FOG_BUTTON, GUI_ID_KEY_CHEAT_MENU_BUTTON, @@ -187,7 +188,7 @@ void GUIKeyChangeMenu::regenerateGui(v2u32 screensize) { core::rect<s32> rect(0, 0, option_w, 30 * s); rect += topleft + v2s32(option_x, option_y); - const wchar_t *text = wgettext("\"Special\" = climb down"); + const wchar_t *text = wgettext("\"Aux1\" = climb down"); Environment->addCheckBox(g_settings->getBool("aux1_descends"), rect, this, GUI_ID_CB_AUX1_DESCENDS, text); delete[] text; @@ -258,7 +259,7 @@ bool GUIKeyChangeMenu::acceptInput() { for (key_setting *k : key_settings) { std::string default_key; - g_settings->getDefaultNoEx(k->setting_name, default_key); + Settings::getLayer(SL_DEFAULTS)->getNoEx(k->setting_name, default_key); if (k->key.sym() != default_key) g_settings->set(k->setting_name, k->key.sym()); @@ -422,47 +423,48 @@ void GUIKeyChangeMenu::add_key(int id, const wchar_t *button_name, const std::st void GUIKeyChangeMenu::init_keys() { - this->add_key(GUI_ID_KEY_FORWARD_BUTTON, wgettext("Forward"), "keymap_forward"); - this->add_key(GUI_ID_KEY_BACKWARD_BUTTON, wgettext("Backward"), "keymap_backward"); - this->add_key(GUI_ID_KEY_LEFT_BUTTON, wgettext("Left"), "keymap_left"); - this->add_key(GUI_ID_KEY_RIGHT_BUTTON, wgettext("Right"), "keymap_right"); - this->add_key(GUI_ID_KEY_USE_BUTTON, wgettext("Special"), "keymap_special1"); - this->add_key(GUI_ID_KEY_JUMP_BUTTON, wgettext("Jump"), "keymap_jump"); - this->add_key(GUI_ID_KEY_SNEAK_BUTTON, wgettext("Sneak"), "keymap_sneak"); - this->add_key(GUI_ID_KEY_DROP_BUTTON, wgettext("Drop"), "keymap_drop"); - this->add_key(GUI_ID_KEY_INVENTORY_BUTTON, wgettext("Inventory"), "keymap_inventory"); - this->add_key(GUI_ID_KEY_ENDERCHEST_BUTTON,wgettext("Enderchest"), "keymap_enderchest"); - this->add_key(GUI_ID_KEY_HOTBAR_PREV_BUTTON,wgettext("Prev. item"), "keymap_hotbar_previous"); - this->add_key(GUI_ID_KEY_HOTBAR_NEXT_BUTTON,wgettext("Next item"), "keymap_hotbar_next"); - this->add_key(GUI_ID_KEY_ZOOM_BUTTON, wgettext("Zoom"), "keymap_zoom"); - this->add_key(GUI_ID_KEY_CAMERA_BUTTON, wgettext("Change camera"), "keymap_camera_mode"); - this->add_key(GUI_ID_KEY_MINIMAP_BUTTON, wgettext("Toggle minimap"), "keymap_minimap"); - this->add_key(GUI_ID_KEY_FLY_BUTTON, wgettext("Toggle fly"), "keymap_freemove"); - this->add_key(GUI_ID_KEY_PITCH_MOVE, wgettext("Toggle pitchmove"), "keymap_pitchmove"); - this->add_key(GUI_ID_KEY_FAST_BUTTON, wgettext("Toggle fast"), "keymap_fastmove"); - this->add_key(GUI_ID_KEY_NOCLIP_BUTTON, wgettext("Toggle noclip"), "keymap_noclip"); - this->add_key(GUI_ID_KEY_MUTE_BUTTON, wgettext("Mute"), "keymap_mute"); - this->add_key(GUI_ID_KEY_DEC_VOLUME_BUTTON,wgettext("Dec. volume"), "keymap_decrease_volume"); - this->add_key(GUI_ID_KEY_INC_VOLUME_BUTTON,wgettext("Inc. volume"), "keymap_increase_volume"); - this->add_key(GUI_ID_KEY_AUTOFWD_BUTTON, wgettext("Autoforward"), "keymap_autoforward"); - this->add_key(GUI_ID_KEY_CHAT_BUTTON, wgettext("Chat"), "keymap_chat"); - this->add_key(GUI_ID_KEY_SCREENSHOT_BUTTON,wgettext("Screenshot"), "keymap_screenshot"); - this->add_key(GUI_ID_KEY_RANGE_BUTTON, wgettext("Range select"), "keymap_rangeselect"); - this->add_key(GUI_ID_KEY_DEC_RANGE_BUTTON, wgettext("Dec. range"), "keymap_decrease_viewing_range_min"); - this->add_key(GUI_ID_KEY_INC_RANGE_BUTTON, wgettext("Inc. range"), "keymap_increase_viewing_range_min"); - this->add_key(GUI_ID_KEY_CONSOLE_BUTTON, wgettext("Console"), "keymap_console"); - this->add_key(GUI_ID_KEY_CMD_BUTTON, wgettext("Command"), "keymap_cmd"); - this->add_key(GUI_ID_KEY_CMD_LOCAL_BUTTON, wgettext("Local command"), "keymap_cmd_local"); - this->add_key(GUI_ID_KEY_HUD_BUTTON, wgettext("Toggle HUD"), "keymap_toggle_hud"); - this->add_key(GUI_ID_KEY_CHATLOG_BUTTON, wgettext("Toggle chat log"), "keymap_toggle_chat"); - this->add_key(GUI_ID_KEY_FOG_BUTTON, wgettext("Toggle fog"), "keymap_toggle_fog"); - this->add_key(GUI_ID_KEY_CHEAT_MENU_BUTTON,wgettext("Toggle C. Menu"),"keymap_toggle_cheat_menu"); - this->add_key(GUI_ID_KEY_KILLAURA_BUTTON, wgettext("Killaura"), "keymap_toggle_killaura"); - this->add_key(GUI_ID_KEY_FREECAM_BUTTON, wgettext("Freecam"), "keymap_toggle_freecam"); - this->add_key(GUI_ID_KEY_SCAFFOLD_BUTTON, wgettext("Scaffold"), "keymap_toggle_scaffold"); - this->add_key(GUI_ID_KEY_SELECT_UP_BUTTON, wgettext("C. Menu Up"), "keymap_select_up"); - this->add_key(GUI_ID_KEY_SELECT_DOWN_BUTTON,wgettext("C. Menu Down"), "keymap_select_down"); - this->add_key(GUI_ID_KEY_SELECT_LEFT_BUTTON,wgettext("C. Menu Left"), "keymap_select_left"); - this->add_key(GUI_ID_KEY_SELECT_RIGHT_BUTTON,wgettext("C. Menu Right"),"keymap_select_right"); - this->add_key(GUI_ID_KEY_SELECT_CONFIRM_BUTTON,wgettext("C. Menu Enter"),"keymap_select_confirm"); + this->add_key(GUI_ID_KEY_FORWARD_BUTTON, wgettext("Forward"), "keymap_forward"); + this->add_key(GUI_ID_KEY_BACKWARD_BUTTON, wgettext("Backward"), "keymap_backward"); + this->add_key(GUI_ID_KEY_LEFT_BUTTON, wgettext("Left"), "keymap_left"); + this->add_key(GUI_ID_KEY_RIGHT_BUTTON, wgettext("Right"), "keymap_right"); + this->add_key(GUI_ID_KEY_AUX1_BUTTON, wgettext("Aux1"), "keymap_aux1"); + this->add_key(GUI_ID_KEY_JUMP_BUTTON, wgettext("Jump"), "keymap_jump"); + this->add_key(GUI_ID_KEY_SNEAK_BUTTON, wgettext("Sneak"), "keymap_sneak"); + this->add_key(GUI_ID_KEY_DROP_BUTTON, wgettext("Drop"), "keymap_drop"); + this->add_key(GUI_ID_KEY_INVENTORY_BUTTON, wgettext("Inventory"), "keymap_inventory"); + this->add_key(GUI_ID_KEY_ENDERCHEST_BUTTON, wgettext("Enderchest"), "keymap_enderchest"); + this->add_key(GUI_ID_KEY_HOTBAR_PREV_BUTTON, wgettext("Prev. item"), "keymap_hotbar_previous"); + this->add_key(GUI_ID_KEY_HOTBAR_NEXT_BUTTON, wgettext("Next item"), "keymap_hotbar_next"); + this->add_key(GUI_ID_KEY_ZOOM_BUTTON, wgettext("Zoom"), "keymap_zoom"); + this->add_key(GUI_ID_KEY_CAMERA_BUTTON, wgettext("Change camera"), "keymap_camera_mode"); + this->add_key(GUI_ID_KEY_MINIMAP_BUTTON, wgettext("Toggle minimap"), "keymap_minimap"); + this->add_key(GUI_ID_KEY_FLY_BUTTON, wgettext("Toggle fly"), "keymap_freemove"); + this->add_key(GUI_ID_KEY_PITCH_MOVE, wgettext("Toggle pitchmove"), "keymap_pitchmove"); + this->add_key(GUI_ID_KEY_FAST_BUTTON, wgettext("Toggle fast"), "keymap_fastmove"); + this->add_key(GUI_ID_KEY_NOCLIP_BUTTON, wgettext("Toggle noclip"), "keymap_noclip"); + this->add_key(GUI_ID_KEY_MUTE_BUTTON, wgettext("Mute"), "keymap_mute"); + this->add_key(GUI_ID_KEY_DEC_VOLUME_BUTTON, wgettext("Dec. volume"), "keymap_decrease_volume"); + this->add_key(GUI_ID_KEY_INC_VOLUME_BUTTON, wgettext("Inc. volume"), "keymap_increase_volume"); + this->add_key(GUI_ID_KEY_AUTOFWD_BUTTON, wgettext("Autoforward"), "keymap_autoforward"); + this->add_key(GUI_ID_KEY_CHAT_BUTTON, wgettext("Chat"), "keymap_chat"); + this->add_key(GUI_ID_KEY_SCREENSHOT_BUTTON, wgettext("Screenshot"), "keymap_screenshot"); + this->add_key(GUI_ID_KEY_RANGE_BUTTON, wgettext("Range select"), "keymap_rangeselect"); + this->add_key(GUI_ID_KEY_DEC_RANGE_BUTTON, wgettext("Dec. range"), "keymap_decrease_viewing_range_min"); + this->add_key(GUI_ID_KEY_INC_RANGE_BUTTON, wgettext("Inc. range"), "keymap_increase_viewing_range_min"); + this->add_key(GUI_ID_KEY_CONSOLE_BUTTON, wgettext("Console"), "keymap_console"); + this->add_key(GUI_ID_KEY_CMD_BUTTON, wgettext("Command"), "keymap_cmd"); + this->add_key(GUI_ID_KEY_CMD_LOCAL_BUTTON, wgettext("Local command"), "keymap_cmd_local"); + this->add_key(GUI_ID_KEY_BLOCK_BOUNDS_BUTTON, wgettext("Block bounds"), "keymap_toggle_block_bounds"); + this->add_key(GUI_ID_KEY_HUD_BUTTON, wgettext("Toggle HUD"), "keymap_toggle_hud"); + this->add_key(GUI_ID_KEY_CHATLOG_BUTTON, wgettext("Toggle chat log"), "keymap_toggle_chat"); + this->add_key(GUI_ID_KEY_FOG_BUTTON, wgettext("Toggle fog"), "keymap_toggle_fog"); + this->add_key(GUI_ID_KEY_CHEAT_MENU_BUTTON, wgettext("Toggle C. Menu"), "keymap_toggle_cheat_menu"); + this->add_key(GUI_ID_KEY_KILLAURA_BUTTON, wgettext("Killaura"), "keymap_toggle_killaura"); + this->add_key(GUI_ID_KEY_FREECAM_BUTTON, wgettext("Freecam"), "keymap_toggle_freecam"); + this->add_key(GUI_ID_KEY_SCAFFOLD_BUTTON, wgettext("Scaffold"), "keymap_toggle_scaffold"); + this->add_key(GUI_ID_KEY_SELECT_UP_BUTTON, wgettext("C. Menu Up"), "keymap_select_up"); + this->add_key(GUI_ID_KEY_SELECT_DOWN_BUTTON, wgettext("C. Menu Down"), "keymap_select_down"); + this->add_key(GUI_ID_KEY_SELECT_LEFT_BUTTON, wgettext("C. Menu Left"), "keymap_select_left"); + this->add_key(GUI_ID_KEY_SELECT_RIGHT_BUTTON, wgettext("C. Menu Right"), "keymap_select_right"); + this->add_key(GUI_ID_KEY_SELECT_CONFIRM_BUTTON, wgettext("C. Menu Enter"), "keymap_select_confirm"); } diff --git a/src/gui/guiScene.cpp b/src/gui/guiScene.cpp index 5f4c50b91..f0cfbec5e 100644 --- a/src/gui/guiScene.cpp +++ b/src/gui/guiScene.cpp @@ -34,9 +34,6 @@ GUIScene::GUIScene(gui::IGUIEnvironment *env, scene::ISceneManager *smgr, m_cam = m_smgr->addCameraSceneNode(0, v3f(0.f, 0.f, -100.f), v3f(0.f)); m_cam->setFOV(30.f * core::DEGTORAD); - scene::ILightSceneNode *light = m_smgr->addLightSceneNode(m_cam); - light->setRadius(1000.f); - m_smgr->getParameters()->setAttribute(scene::ALLOW_ZWRITE_ON_TRANSPARENT, true); } @@ -60,6 +57,7 @@ scene::IAnimatedMeshSceneNode *GUIScene::setMesh(scene::IAnimatedMesh *mesh) m_mesh = m_smgr->addAnimatedMeshSceneNode(mesh); m_mesh->setPosition(-m_mesh->getBoundingBox().getCenter()); m_mesh->animateJoints(); + return m_mesh; } @@ -73,10 +71,13 @@ void GUIScene::setTexture(u32 idx, video::ITexture *texture) material.setFlag(video::EMF_FOG_ENABLE, true); material.setFlag(video::EMF_BILINEAR_FILTER, false); material.setFlag(video::EMF_BACK_FACE_CULLING, false); + material.setFlag(video::EMF_ZWRITE_ENABLE, true); } void GUIScene::draw() { + m_driver->clearBuffers(video::ECBF_DEPTH); + // Control rotation speed based on time u64 new_time = porting::getTimeMs(); u64 dtime_ms = 0; @@ -161,6 +162,14 @@ void GUIScene::setFrameLoop(s32 begin, s32 end) m_mesh->setFrameLoop(begin, end); } +/** + * Sets the animation speed (FPS) for the mesh + */ +void GUIScene::setAnimationSpeed(f32 speed) +{ + m_mesh->setAnimationSpeed(speed); +} + /* Camera control functions */ inline void GUIScene::calcOptimalDistance() diff --git a/src/gui/guiScene.h b/src/gui/guiScene.h index 08eb7f350..0f5f3a891 100644 --- a/src/gui/guiScene.h +++ b/src/gui/guiScene.h @@ -37,6 +37,7 @@ public: void setTexture(u32 idx, video::ITexture *texture); void setBackgroundColor(const video::SColor &color) noexcept { m_bgcolor = color; }; void setFrameLoop(s32 begin, s32 end); + void setAnimationSpeed(f32 speed); void enableMouseControl(bool enable) noexcept { m_mouse_ctrl = enable; }; void setRotation(v2f rot) noexcept { m_custom_rot = rot; }; void enableContinuousRotation(bool enable) noexcept { m_inf_rot = enable; }; diff --git a/src/gui/intlGUIEditBox.cpp b/src/gui/intlGUIEditBox.cpp deleted file mode 100644 index a61619148..000000000 --- a/src/gui/intlGUIEditBox.cpp +++ /dev/null @@ -1,723 +0,0 @@ -// 11.11.2011 11:11 ValkaTR -// -// This is a copy of intlGUIEditBox from the irrlicht, but with a -// fix in the OnEvent function, which doesn't allowed input of -// other keyboard layouts than latin-1 -// -// Characters like: ä ö ü õ ы й ю я ъ № € ° ... -// -// This fix is only needed for linux, because of a bug -// in the CIrrDeviceLinux.cpp:1014-1015 of the irrlicht -// -// Also locale in the programm should not be changed to -// a "C", "POSIX" or whatever, it should be set to "", -// or XLookupString will return nothing for the international -// characters. -// -// From the "man setlocale": -// -// On startup of the main program, the portable "C" locale -// is selected as default. A program may be made -// portable to all locales by calling: -// -// setlocale(LC_ALL, ""); -// -// after program initialization.... -// - -// Copyright (C) 2002-2013 Nikolaus Gebhardt -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in irrlicht.h - -#include <util/numeric.h> -#include "intlGUIEditBox.h" - -#include "IGUISkin.h" -#include "IGUIEnvironment.h" -#include "IGUIFont.h" -#include "IVideoDriver.h" -//#include "irrlicht/os.cpp" -#include "porting.h" -//#include "Keycodes.h" -#include "log.h" - -/* - todo: - optional scrollbars - 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 -*/ - -namespace irr -{ -namespace gui -{ - -//! constructor -intlGUIEditBox::intlGUIEditBox(const wchar_t* text, bool border, - IGUIEnvironment* environment, IGUIElement* parent, s32 id, - const core::rect<s32>& rectangle, bool writable, bool has_vscrollbar) - : GUIEditBox(environment, parent, id, rectangle, border, writable) -{ - #ifdef _DEBUG - setDebugName("intlintlGUIEditBox"); - #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); - - 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; - } - - if (skin && has_vscrollbar) { - m_scrollbar_width = skin->getSize(gui::EGDS_SCROLLBAR_SIZE); - - if (m_scrollbar_width > 0) { - createVScrollBar(); - } - } - - breakText(); - - calculateScrollPos(); - setWritable(writable); -} - -//! Sets whether to draw the background -void intlGUIEditBox::setDrawBackground(bool draw) -{ -} - -void intlGUIEditBox::updateAbsolutePosition() -{ - core::rect<s32> oldAbsoluteRect(AbsoluteRect); - IGUIElement::updateAbsolutePosition(); - if ( oldAbsoluteRect != AbsoluteRect ) - { - breakText(); - } -} - - -//! draws the element and its children -void intlGUIEditBox::draw() -{ - if (!IsVisible) - return; - - const bool focus = Environment->hasFocus(this); - - IGUISkin* skin = Environment->getSkin(); - if (!skin) - return; - - m_frame_rect = AbsoluteRect; - - // draw the border - - if (m_border) - { - if (m_writable) { - skin->draw3DSunkenPane(this, skin->getColor(EGDC_WINDOW), - false, true, m_frame_rect, &AbsoluteClippingRect); - } - - 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(); - core::rect<s32> localClipRect = m_frame_rect; - localClipRect.clipAgainst(AbsoluteClippingRect); - - // draw the text - - IGUIFont* font = m_override_font; - if (!m_override_font) - font = skin->getFont(); - - s32 cursorLine = 0; - s32 charcursorpos = 0; - - if (font) - { - if (m_last_break_font != font) - { - breakText(); - } - - // calculate cursor pos - - core::stringw *txtLine = &Text; - s32 startPos = 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 hlineStart = ml ? getLineFromPos(realmbgn) : 0; - const s32 hlineCount = ml ? getLineFromPos(realmend) - hlineStart + 1 : 1; - const s32 lineCount = 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.empty()) { - if (!IsEnabled && !m_override_color_enabled) - { - m_override_color_enabled = true; - m_override_color = skin->getColor(EGDC_GRAY_TEXT); - } - - for (s32 i=0; i < lineCount; ++i) - { - setTextRect(i); - - // clipping test - don't draw anything outside the visible area - core::rect<s32> c = localClipRect; - 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; - } - } - txtLine = &m_broken_text[0]; - startPos = 0; - } - else - { - txtLine = ml ? &m_broken_text[i] : &Text; - startPos = ml ? m_broken_text_positions[i] : 0; - } - - - // draw normal text - font->draw(txtLine->c_str(), m_current_text_rect, - m_override_color_enabled ? m_override_color : skin->getColor(EGDC_BUTTON_TEXT), - false, true, &localClipRect); - - // draw mark and marked text - if (focus && m_mark_begin != m_mark_end && i >= hlineStart && i < hlineStart + hlineCount) - { - - s32 mbegin = 0, mend = 0; - s32 lineStartPos = 0, lineEndPos = txtLine->size(); - - if (i == hlineStart) - { - // highlight start is on this line - s = txtLine->subString(0, realmbgn - startPos); - mbegin = font->getDimension(s.c_str()).Width; - - // deal with kerning - mbegin += font->getKerningWidth( - &((*txtLine)[realmbgn - startPos]), - realmbgn - startPos > 0 ? &((*txtLine)[realmbgn - startPos - 1]) : 0); - - lineStartPos = realmbgn - startPos; - } - if (i == hlineStart + hlineCount - 1) - { - // highlight end is on this line - s2 = txtLine->subString(0, realmend - startPos); - mend = font->getDimension(s2.c_str()).Width; - lineEndPos = (s32)s2.size(); - } - else - mend = font->getDimension(txtLine->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, &localClipRect); - - // draw marked text - s = txtLine->subString(lineStartPos, lineEndPos - lineStartPos); - - if (!s.empty()) - font->draw(s.c_str(), m_current_text_rect, - m_override_color_enabled ? m_override_color : skin->getColor(EGDC_HIGH_LIGHT_TEXT), - false, true, &localClipRect); - - } - } - - // Return the override color information to its previous settings. - m_override_color_enabled = prevOver; - m_override_color = prevColor; - } - - // draw cursor - - if (m_word_wrap || m_multiline) - { - cursorLine = getLineFromPos(m_cursor_pos); - txtLine = &m_broken_text[cursorLine]; - startPos = m_broken_text_positions[cursorLine]; - } - s = txtLine->subString(0,m_cursor_pos-startPos); - charcursorpos = font->getDimension(s.c_str()).Width + - font->getKerningWidth(L"_", m_cursor_pos-startPos > 0 ? &((*txtLine)[m_cursor_pos-startPos-1]) : 0); - - if (m_writable) { - if (focus && (porting::getTimeMs() - m_blink_start_time) % 700 < 350) { - setTextRect(cursorLine); - 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, &localClipRect); - } - } - } - - // draw children - IGUIElement::draw(); -} - - -s32 intlGUIEditBox::getCursorPos(s32 x, s32 y) -{ - IGUIFont* font = m_override_font; - IGUISkin* skin = Environment->getSkin(); - if (!m_override_font) - font = skin->getFont(); - - const u32 lineCount = (m_word_wrap || m_multiline) ? m_broken_text.size() : 1; - - core::stringw *txtLine = NULL; - s32 startPos = 0; - u32 curr_line_idx = 0; - x += 3; - - for (; curr_line_idx < lineCount; ++curr_line_idx) { - setTextRect(curr_line_idx); - if (curr_line_idx == 0 && y < m_current_text_rect.UpperLeftCorner.Y) - y = m_current_text_rect.UpperLeftCorner.Y; - if (curr_line_idx == lineCount - 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 - txtLine = (m_word_wrap || m_multiline) ? &m_broken_text[curr_line_idx] : &Text; - startPos = (m_word_wrap || m_multiline) ? m_broken_text_positions[curr_line_idx] : 0; - break; - } - } - - if (x < m_current_text_rect.UpperLeftCorner.X) - x = m_current_text_rect.UpperLeftCorner.X; - else if (x > m_current_text_rect.LowerRightCorner.X) - x = m_current_text_rect.LowerRightCorner.X; - - s32 idx = font->getCharacterFromPos(txtLine->c_str(), x - m_current_text_rect.UpperLeftCorner.X); - // Special handling for last line, if we are on limits, add 1 extra shift because idx - // will be the last char, not null char of the wstring - if (curr_line_idx == lineCount - 1 && x == m_current_text_rect.LowerRightCorner.X) - idx++; - - return rangelim(idx + startPos, 0, S32_MAX); -} - - -//! Breaks the single text line. -void intlGUIEditBox::breakText() -{ - IGUISkin* skin = Environment->getSkin(); - - if ((!m_word_wrap && !m_multiline) || !skin) - return; - - m_broken_text.clear(); // need to reallocate :/ - m_broken_text_positions.clear(); - - IGUIFont* font = m_override_font; - if (!m_override_font) - font = skin->getFont(); - - if (!font) - return; - - m_last_break_font = font; - - core::stringw line; - core::stringw word; - core::stringw whitespace; - s32 lastLineStart = 0; - s32 size = Text.size(); - s32 length = 0; - s32 elWidth = RelativeRect.getWidth() - m_scrollbar_width - 10; - wchar_t c; - - for (s32 i=0; i<size; ++i) - { - c = Text[i]; - bool lineBreak = false; - - if (c == L'\r') // Mac or Windows breaks - { - lineBreak = true; - c = ' '; - if (Text[i+1] == L'\n') // Windows breaks - { - Text.erase(i+1); - --size; - } - } - else if (c == L'\n') // Unix breaks - { - lineBreak = true; - c = ' '; - } - - // don't break if we're not a multi-line edit box - if (!m_multiline) - lineBreak = false; - - if (c == L' ' || c == 0 || i == (size-1)) - { - if (!word.empty()) { - // here comes the next whitespace, look if - // we can break the last word to the next line. - s32 whitelgth = font->getDimension(whitespace.c_str()).Width; - s32 worldlgth = font->getDimension(word.c_str()).Width; - - if (m_word_wrap && length + worldlgth + whitelgth > elWidth) - { - // break to next line - length = worldlgth; - m_broken_text.push_back(line); - m_broken_text_positions.push_back(lastLineStart); - lastLineStart = i - (s32)word.size(); - line = word; - } - else - { - // add word to line - line += whitespace; - line += word; - length += whitelgth + worldlgth; - } - - word = L""; - whitespace = L""; - } - - whitespace += c; - - // compute line break - if (lineBreak) - { - line += whitespace; - line += word; - m_broken_text.push_back(line); - m_broken_text_positions.push_back(lastLineStart); - lastLineStart = 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(lastLineStart); -} - - -void intlGUIEditBox::setTextRect(s32 line) -{ - core::dimension2du d; - - IGUISkin* skin = Environment->getSkin(); - if (!skin) - return; - - IGUIFont* font = m_override_font ? m_override_font : skin->getFont(); - - if (!font) - return; - - // get text dimension - const u32 lineCount = (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) - (lineCount*d.Height)/2 + d.Height*line; - break; - case EGUIA_LOWERRIGHT: - // align to bottom edge - m_current_text_rect.UpperLeftCorner.Y = - m_frame_rect.getHeight() - lineCount*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; - -} - -void intlGUIEditBox::inputChar(wchar_t c) -{ - if (!isEnabled() || !m_writable) - 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(); - sendGuiEvent(EGET_EDITBOX_CHANGED); - calculateScrollPos(); -} - - -void intlGUIEditBox::calculateScrollPos() -{ - if (!m_autoscroll) - return; - - // calculate horizontal scroll position - s32 cursLine = getLineFromPos(m_cursor_pos); - setTextRect(cursLine); - - // don't do horizontal scrolling when wordwrap is enabled. - if (!m_word_wrap) - { - // get cursor position - IGUISkin* skin = Environment->getSkin(); - if (!skin) - return; - IGUIFont* font = m_override_font ? m_override_font : skin->getFont(); - if (!font) - return; - - core::stringw *txtLine = m_multiline ? &m_broken_text[cursLine] : &Text; - s32 cPos = m_multiline ? m_cursor_pos - m_broken_text_positions[cursLine] : m_cursor_pos; - - s32 cStart = m_current_text_rect.UpperLeftCorner.X + m_hscroll_pos + - font->getDimension(txtLine->subString(0, cPos).c_str()).Width; - - s32 cEnd = cStart + font->getDimension(L"_ ").Width; - - if (m_frame_rect.LowerRightCorner.X < cEnd) - m_hscroll_pos = cEnd - m_frame_rect.LowerRightCorner.X; - else if (m_frame_rect.UpperLeftCorner.X > cStart) - m_hscroll_pos = cStart - m_frame_rect.UpperLeftCorner.X; - else - m_hscroll_pos = 0; - - // todo: adjust scrollbar - } - - if (!m_word_wrap && !m_multiline) - return; - - // vertical scroll position - if (m_frame_rect.LowerRightCorner.Y < m_current_text_rect.LowerRightCorner.Y) - m_vscroll_pos += m_current_text_rect.LowerRightCorner.Y - m_frame_rect.LowerRightCorner.Y; // scrolling downwards - else if (m_frame_rect.UpperLeftCorner.Y > m_current_text_rect.UpperLeftCorner.Y) - m_vscroll_pos += m_current_text_rect.UpperLeftCorner.Y - m_frame_rect.UpperLeftCorner.Y; // scrolling upwards - - // todo: adjust scrollbar - if (m_vscrollbar) - m_vscrollbar->setPos(m_vscroll_pos); -} - - -//! Create a vertical scrollbar -void intlGUIEditBox::createVScrollBar() -{ - s32 fontHeight = 1; - - if (m_override_font) { - fontHeight = m_override_font->getDimension(L"").Height; - } else { - if (IGUISkin* skin = Environment->getSkin()) { - if (IGUIFont* font = skin->getFont()) { - fontHeight = font->getDimension(L"").Height; - } - } - } - - irr::core::rect<s32> scrollbarrect = m_frame_rect; - scrollbarrect.UpperLeftCorner.X += m_frame_rect.getWidth() - m_scrollbar_width; - m_vscrollbar = new GUIScrollBar(Environment, getParent(), -1, - scrollbarrect, false, true); - - m_vscrollbar->setVisible(false); - m_vscrollbar->setSmallStep(3 * fontHeight); - m_vscrollbar->setLargeStep(10 * fontHeight); -} - - -//! Writes attributes of the element. -void intlGUIEditBox::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const -{ - // IGUIEditBox::serializeAttributes(out,options); - - out->addBool ("OverrideColorEnabled", m_override_color_enabled ); - out->addColor ("OverrideColor", m_override_color); - // out->addFont("OverrideFont",m_override_font); - 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 intlGUIEditBox::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0) -{ - IGUIEditBox::deserializeAttributes(in,options); - - 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.empty()) - setPasswordBox(in->getAttributeAsBool("PasswordBox")); - else - setPasswordBox(in->getAttributeAsBool("PasswordBox"), ch[0]); - - setTextAlignment( (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("HTextAlign", GUIAlignmentNames), - (EGUI_ALIGNMENT) in->getAttributeAsEnumeration("VTextAlign", GUIAlignmentNames)); - - setWritable(in->getAttributeAsBool("Writable")); - // setOverrideFont(in->getAttributeAsFont("OverrideFont")); -} - - -} // end namespace gui -} // end namespace irr diff --git a/src/gui/intlGUIEditBox.h b/src/gui/intlGUIEditBox.h deleted file mode 100644 index 2abc12d1a..000000000 --- a/src/gui/intlGUIEditBox.h +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (C) 2002-2013 Nikolaus Gebhardt -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in irrlicht.h - -#pragma once - -#include "IrrCompileConfig.h" -//#ifdef _IRR_COMPILE_WITH_GUI_ - -#include "guiEditBox.h" -#include "irrArray.h" -#include "IOSOperator.h" - -namespace irr -{ -namespace gui -{ - class intlGUIEditBox : public GUIEditBox - { - public: - - //! constructor - intlGUIEditBox(const wchar_t* text, bool border, IGUIEnvironment* environment, - IGUIElement* parent, s32 id, const core::rect<s32>& rectangle, - bool writable = true, bool has_vscrollbar = false); - - //! destructor - virtual ~intlGUIEditBox() {} - - //! Sets whether to draw the background - virtual void setDrawBackground(bool draw); - - virtual bool isDrawBackgroundEnabled() const { return true; } - - //! draws the element and its children - virtual void draw(); - - //! Updates the absolute position, splits text if required - virtual void updateAbsolutePosition(); - - //! 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 void setCursorChar(const wchar_t cursorChar) {} - - virtual wchar_t getCursorChar() const { return L'|'; } - - virtual void setCursorBlinkTime(u32 timeMs) {} - - virtual u32 getCursorBlinkTime() const { return 500; } - - protected: - //! Breaks the single text line. - virtual void breakText(); - //! sets the area of the given line - virtual void setTextRect(s32 line); - //! adds a letter to the edit box - virtual void inputChar(wchar_t c); - //! calculates the current scroll position - void calculateScrollPos(); - - s32 getCursorPos(s32 x, s32 y); - - //! Create a vertical scrollbar - void createVScrollBar(); - }; - - -} // end namespace gui -} // end namespace irr - -//#endif // _IRR_COMPILE_WITH_GUI_ diff --git a/src/gui/modalMenu.cpp b/src/gui/modalMenu.cpp index 9b1e6dd9c..0d3fb55f0 100644 --- a/src/gui/modalMenu.cpp +++ b/src/gui/modalMenu.cpp @@ -183,6 +183,64 @@ static bool isChild(gui::IGUIElement *tocheck, gui::IGUIElement *parent) return false; } +#ifdef __ANDROID__ + +bool GUIModalMenu::simulateMouseEvent( + gui::IGUIElement *target, ETOUCH_INPUT_EVENT touch_event) +{ + SEvent mouse_event{}; // value-initialized, not unitialized + mouse_event.EventType = EET_MOUSE_INPUT_EVENT; + mouse_event.MouseInput.X = m_pointer.X; + mouse_event.MouseInput.Y = m_pointer.Y; + switch (touch_event) { + case ETIE_PRESSED_DOWN: + mouse_event.MouseInput.Event = EMIE_LMOUSE_PRESSED_DOWN; + mouse_event.MouseInput.ButtonStates = EMBSM_LEFT; + break; + case ETIE_MOVED: + mouse_event.MouseInput.Event = EMIE_MOUSE_MOVED; + mouse_event.MouseInput.ButtonStates = EMBSM_LEFT; + break; + case ETIE_LEFT_UP: + mouse_event.MouseInput.Event = EMIE_LMOUSE_LEFT_UP; + mouse_event.MouseInput.ButtonStates = 0; + break; + default: + return false; + } + if (preprocessEvent(mouse_event)) + return true; + if (!target) + return false; + return target->OnEvent(mouse_event); +} + +void GUIModalMenu::enter(gui::IGUIElement *hovered) +{ + sanity_check(!m_hovered); + m_hovered.grab(hovered); + SEvent gui_event{}; + gui_event.EventType = EET_GUI_EVENT; + gui_event.GUIEvent.Caller = m_hovered.get(); + gui_event.GUIEvent.EventType = EGET_ELEMENT_HOVERED; + gui_event.GUIEvent.Element = gui_event.GUIEvent.Caller; + m_hovered->OnEvent(gui_event); +} + +void GUIModalMenu::leave() +{ + if (!m_hovered) + return; + SEvent gui_event{}; + gui_event.EventType = EET_GUI_EVENT; + gui_event.GUIEvent.Caller = m_hovered.get(); + gui_event.GUIEvent.EventType = EGET_ELEMENT_LEFT; + m_hovered->OnEvent(gui_event); + m_hovered.reset(); +} + +#endif + bool GUIModalMenu::preprocessEvent(const SEvent &event) { #ifdef __ANDROID__ @@ -230,89 +288,50 @@ bool GUIModalMenu::preprocessEvent(const SEvent &event) } if (event.EventType == EET_TOUCH_INPUT_EVENT) { - SEvent translated; - memset(&translated, 0, sizeof(SEvent)); - translated.EventType = EET_MOUSE_INPUT_EVENT; - gui::IGUIElement *root = Environment->getRootGUIElement(); - - if (!root) { - errorstream << "GUIModalMenu::preprocessEvent" - << " unable to get root element" << std::endl; - return false; - } - gui::IGUIElement *hovered = - root->getElementFromPoint(core::position2d<s32>( - event.TouchInput.X, event.TouchInput.Y)); - - translated.MouseInput.X = event.TouchInput.X; - translated.MouseInput.Y = event.TouchInput.Y; - translated.MouseInput.Control = false; + irr_ptr<GUIModalMenu> holder; + holder.grab(this); // keep this alive until return (it might be dropped downstream [?]) - if (event.TouchInput.touchedCount == 1) { - switch (event.TouchInput.Event) { - case ETIE_PRESSED_DOWN: + switch ((int)event.TouchInput.touchedCount) { + case 1: { + if (event.TouchInput.Event == ETIE_PRESSED_DOWN || event.TouchInput.Event == ETIE_MOVED) m_pointer = v2s32(event.TouchInput.X, event.TouchInput.Y); - translated.MouseInput.Event = EMIE_LMOUSE_PRESSED_DOWN; - translated.MouseInput.ButtonStates = EMBSM_LEFT; + if (event.TouchInput.Event == ETIE_PRESSED_DOWN) m_down_pos = m_pointer; - break; - case ETIE_MOVED: - m_pointer = v2s32(event.TouchInput.X, event.TouchInput.Y); - translated.MouseInput.Event = EMIE_MOUSE_MOVED; - translated.MouseInput.ButtonStates = EMBSM_LEFT; - break; - case ETIE_LEFT_UP: - translated.MouseInput.Event = EMIE_LMOUSE_LEFT_UP; - translated.MouseInput.ButtonStates = 0; - hovered = root->getElementFromPoint(m_down_pos); - // we don't have a valid pointer element use last - // known pointer pos - translated.MouseInput.X = m_pointer.X; - translated.MouseInput.Y = m_pointer.Y; - - // reset down pos - m_down_pos = v2s32(0, 0); - break; - default: - break; + gui::IGUIElement *hovered = Environment->getRootGUIElement()->getElementFromPoint(core::position2d<s32>(m_pointer)); + if (event.TouchInput.Event == ETIE_PRESSED_DOWN) + Environment->setFocus(hovered); + if (m_hovered != hovered) { + leave(); + enter(hovered); } - } else if ((event.TouchInput.touchedCount == 2) && - (event.TouchInput.Event == ETIE_PRESSED_DOWN)) { - hovered = root->getElementFromPoint(m_down_pos); - - translated.MouseInput.Event = EMIE_RMOUSE_PRESSED_DOWN; - translated.MouseInput.ButtonStates = EMBSM_LEFT | EMBSM_RIGHT; - translated.MouseInput.X = m_pointer.X; - translated.MouseInput.Y = m_pointer.Y; - if (hovered) - hovered->OnEvent(translated); - - translated.MouseInput.Event = EMIE_RMOUSE_LEFT_UP; - translated.MouseInput.ButtonStates = EMBSM_LEFT; - - if (hovered) - hovered->OnEvent(translated); - - return true; - } else { - // ignore unhandled 2 touch events (accidental moving for example) + gui::IGUIElement *focused = Environment->getFocus(); + bool ret = simulateMouseEvent(focused, event.TouchInput.Event); + if (!ret && m_hovered != focused) + ret = simulateMouseEvent(m_hovered.get(), event.TouchInput.Event); + if (event.TouchInput.Event == ETIE_LEFT_UP) + leave(); + return ret; + } + case 2: { + if (event.TouchInput.Event != ETIE_PRESSED_DOWN) + return true; // ignore + auto focused = Environment->getFocus(); + if (!focused) + return true; + SEvent rclick_event{}; + rclick_event.EventType = EET_MOUSE_INPUT_EVENT; + rclick_event.MouseInput.Event = EMIE_RMOUSE_PRESSED_DOWN; + rclick_event.MouseInput.ButtonStates = EMBSM_LEFT | EMBSM_RIGHT; + rclick_event.MouseInput.X = m_pointer.X; + rclick_event.MouseInput.Y = m_pointer.Y; + focused->OnEvent(rclick_event); + rclick_event.MouseInput.Event = EMIE_RMOUSE_LEFT_UP; + rclick_event.MouseInput.ButtonStates = EMBSM_LEFT; + focused->OnEvent(rclick_event); return true; } - - // check if translated event needs to be preprocessed again - if (preprocessEvent(translated)) + default: // ignored return true; - - if (hovered) { - grab(); - bool retval = hovered->OnEvent(translated); - - if (event.TouchInput.Event == ETIE_LEFT_UP) - // reset pointer - m_pointer = v2s32(0, 0); - - drop(); - return retval; } } #endif diff --git a/src/gui/modalMenu.h b/src/gui/modalMenu.h index 1cb687f82..ed0da3205 100644 --- a/src/gui/modalMenu.h +++ b/src/gui/modalMenu.h @@ -20,6 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once #include "irrlichttypes_extrabloated.h" +#include "irr_ptr.h" #include "util/string.h" class GUIModalMenu; @@ -100,4 +101,12 @@ private: // This might be necessary to expose to the implementation if it // wants to launch other menus bool m_allow_focus_removal = false; + +#ifdef __ANDROID__ + irr_ptr<gui::IGUIElement> m_hovered; + + bool simulateMouseEvent(gui::IGUIElement *target, ETOUCH_INPUT_EVENT touch_event); + void enter(gui::IGUIElement *element); + void leave(); +#endif }; diff --git a/src/gui/touchscreengui.cpp b/src/gui/touchscreengui.cpp index e1a971462..78b18c2d9 100644 --- a/src/gui/touchscreengui.cpp +++ b/src/gui/touchscreengui.cpp @@ -40,7 +40,7 @@ const char **button_imagenames = (const char *[]) { "jump_btn.png", "down.png", "zoom.png", - "aux_btn.png" + "aux1_btn.png" }; const char **joystick_imagenames = (const char *[]) { @@ -80,8 +80,8 @@ static irr::EKEY_CODE id2keycode(touch_gui_button_id id) case zoom_id: key = "zoom"; break; - case special1_id: - key = "special1"; + case aux1_id: + key = "aux1"; break; case fly_id: key = "freemove"; @@ -425,7 +425,7 @@ TouchScreenGUI::TouchScreenGUI(IrrlichtDevice *device, IEventReceiver *receiver) m_touchscreen_threshold = g_settings->getU16("touchscreen_threshold"); m_fixed_joystick = g_settings->getBool("fixed_virtual_joystick"); - m_joystick_triggers_special1 = g_settings->getBool("virtual_joystick_triggers_aux"); + m_joystick_triggers_aux1 = g_settings->getBool("virtual_joystick_triggers_aux1"); m_screensize = m_device->getVideoDriver()->getScreenSize(); button_size = MYMIN(m_screensize.Y / 4.5f, porting::getDisplayDensity() * @@ -521,9 +521,9 @@ void TouchScreenGUI::init(ISimpleTextureSource *tsrc) m_screensize.Y - (3 * button_size)), L"z", false); - // init special1/aux button - if (!m_joystick_triggers_special1) - initButton(special1_id, + // init aux1 button + if (!m_joystick_triggers_aux1) + initButton(aux1_id, rect<s32>(m_screensize.X - (1.25 * button_size), m_screensize.Y - (2.5 * button_size), m_screensize.X - (0.25 * button_size), @@ -923,7 +923,7 @@ void TouchScreenGUI::translateEvent(const SEvent &event) } if (distance > button_size) { - m_joystick_status[j_special1] = true; + m_joystick_status[j_aux1] = true; // move joystick "button" s32 ndx = button_size * dx / distance - button_size / 2.0f; s32 ndy = button_size * dy / distance - button_size / 2.0f; @@ -1039,7 +1039,7 @@ bool TouchScreenGUI::doubleTapDetection() void TouchScreenGUI::applyJoystickStatus() { for (unsigned int i = 0; i < 5; i++) { - if (i == 4 && !m_joystick_triggers_special1) + if (i == 4 && !m_joystick_triggers_aux1) continue; SEvent translated{}; diff --git a/src/gui/touchscreengui.h b/src/gui/touchscreengui.h index 761d33207..ad5abae87 100644 --- a/src/gui/touchscreengui.h +++ b/src/gui/touchscreengui.h @@ -18,6 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once +#include "irrlichttypes.h" #include <IEventReceiver.h> #include <IGUIButton.h> #include <IGUIEnvironment.h> @@ -38,7 +39,7 @@ typedef enum jump_id = 0, crunch_id, zoom_id, - special1_id, + aux1_id, after_last_element_id, settings_starter_id, rare_controls_starter_id, @@ -68,7 +69,7 @@ typedef enum j_backward, j_left, j_right, - j_special1 + j_aux1 } touch_gui_joystick_move_id; typedef enum @@ -216,7 +217,7 @@ private: // forward, backward, left, right touch_gui_button_id m_joystick_names[5] = { - forward_id, backward_id, left_id, right_id, special1_id}; + forward_id, backward_id, left_id, right_id, aux1_id}; bool m_joystick_status[5] = {false, false, false, false, false}; /* @@ -236,7 +237,7 @@ private: int m_joystick_id = -1; bool m_joystick_has_really_moved = false; bool m_fixed_joystick = false; - bool m_joystick_triggers_special1 = false; + bool m_joystick_triggers_aux1 = false; button_info *m_joystick_btn_off = nullptr; button_info *m_joystick_btn_bg = nullptr; button_info *m_joystick_btn_center = nullptr; diff --git a/src/httpfetch.cpp b/src/httpfetch.cpp index 65202ce3e..6137782ff 100644 --- a/src/httpfetch.cpp +++ b/src/httpfetch.cpp @@ -22,7 +22,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <iostream> #include <sstream> #include <list> -#include <map> +#include <unordered_map> #include <cerrno> #include <mutex> #include "network/socket.h" // for select() @@ -37,13 +37,14 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "settings.h" #include "noise.h" -std::mutex g_httpfetch_mutex; -std::map<unsigned long, std::queue<HTTPFetchResult> > g_httpfetch_results; -PcgRandom g_callerid_randomness; +static std::mutex g_httpfetch_mutex; +static std::unordered_map<unsigned long, std::queue<HTTPFetchResult>> + g_httpfetch_results; +static PcgRandom g_callerid_randomness; HTTPFetchRequest::HTTPFetchRequest() : timeout(g_settings->getS32("curl_timeout")), - connect_timeout(timeout), + connect_timeout(10 * 1000), useragent(std::string(PROJECT_NAME_C "/") + g_version_hash + " (" + porting::get_sysinfo() + ")") { } @@ -54,7 +55,7 @@ static void httpfetch_deliver_result(const HTTPFetchResult &fetch_result) unsigned long caller = fetch_result.caller; if (caller != HTTPFETCH_DISCARD) { MutexAutoLock lock(g_httpfetch_mutex); - g_httpfetch_results[caller].push(fetch_result); + g_httpfetch_results[caller].emplace(fetch_result); } } @@ -67,8 +68,7 @@ unsigned long httpfetch_caller_alloc() // Check each caller ID except HTTPFETCH_DISCARD const unsigned long discard = HTTPFETCH_DISCARD; for (unsigned long caller = discard + 1; caller != discard; ++caller) { - std::map<unsigned long, std::queue<HTTPFetchResult> >::iterator - it = g_httpfetch_results.find(caller); + auto it = g_httpfetch_results.find(caller); if (it == g_httpfetch_results.end()) { verbosestream << "httpfetch_caller_alloc: allocating " << caller << std::endl; @@ -127,8 +127,7 @@ bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetch_result) MutexAutoLock lock(g_httpfetch_mutex); // Check that caller exists - std::map<unsigned long, std::queue<HTTPFetchResult> >::iterator - it = g_httpfetch_results.find(caller); + auto it = g_httpfetch_results.find(caller); if (it == g_httpfetch_results.end()) return false; @@ -138,7 +137,7 @@ bool httpfetch_async_get(unsigned long caller, HTTPFetchResult &fetch_result) return false; // Pop first result - fetch_result = caller_results.front(); + fetch_result = std::move(caller_results.front()); caller_results.pop(); return true; } diff --git a/src/inventory.cpp b/src/inventory.cpp index 1ef9b13cd..fc1aaf371 100644 --- a/src/inventory.cpp +++ b/src/inventory.cpp @@ -965,13 +965,14 @@ InventoryList * Inventory::getList(const std::string &name) { s32 i = getListIndex(name); if(i == -1) - return NULL; + return nullptr; return m_lists[i]; } std::vector<const InventoryList*> Inventory::getLists() { std::vector<const InventoryList*> lists; + lists.reserve(m_lists.size()); for (auto list : m_lists) { lists.push_back(list); } @@ -990,11 +991,11 @@ bool Inventory::deleteList(const std::string &name) return true; } -const InventoryList * Inventory::getList(const std::string &name) const +const InventoryList *Inventory::getList(const std::string &name) const { s32 i = getListIndex(name); if(i == -1) - return NULL; + return nullptr; return m_lists[i]; } diff --git a/src/inventorymanager.cpp b/src/inventorymanager.cpp index 635bd2e4b..1e81c1dbc 100644 --- a/src/inventorymanager.cpp +++ b/src/inventorymanager.cpp @@ -301,6 +301,7 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame if (!list_to->getItem(dest_i).empty()) { to_i = dest_i; apply(mgr, player, gamedef); + assert(move_count <= count); count -= move_count; } } @@ -339,7 +340,7 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame */ ItemStack src_item = list_from->getItem(from_i); - if (count > 0) + if (count > 0 && count < src_item.count) src_item.count = count; if (src_item.empty()) return; @@ -352,10 +353,12 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame bool allow_swap = !list_to->itemFits(to_i, src_item, &restitem) && restitem.count == src_item.count && !caused_by_move_somewhere; + move_count = src_item.count - restitem.count; // Shift-click: Cannot fill this stack, proceed with next slot - if (caused_by_move_somewhere && restitem.count == src_item.count) + if (caused_by_move_somewhere && move_count == 0) { return; + } if (allow_swap) { // Swap will affect the entire stack if it can performed. @@ -384,9 +387,16 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame src_can_take_count = dst_can_put_count = 0; } else { // Take from one inventory, put into another + int src_item_count = src_item.count; + if (caused_by_move_somewhere) + // When moving somewhere: temporarily use the actual movable stack + // size to ensure correct callback execution. + src_item.count = move_count; dst_can_put_count = allowPut(src_item, player); src_can_take_count = allowTake(src_item, player); - + if (caused_by_move_somewhere) + // Reset source item count + src_item.count = src_item_count; bool swap_expected = allow_swap; allow_swap = allow_swap && (src_can_take_count == -1 || src_can_take_count >= src_item.count) @@ -416,12 +426,17 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame count = src_can_take_count; if (dst_can_put_count != -1 && count > dst_can_put_count) count = dst_can_put_count; + /* Limit according to source item count */ if (count > list_from->getItem(from_i).count) count = list_from->getItem(from_i).count; /* If no items will be moved, don't go further */ if (count == 0) { + if (caused_by_move_somewhere) + // Set move count to zero, as no items have been moved + move_count = 0; + // Undo client prediction. See 'clientApply' if (from_inv.type == InventoryLocation::PLAYER) list_from->setModified(); @@ -438,6 +453,7 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame <<" list=\""<<to_list<<"\"" <<" i="<<to_i <<std::endl; + return; } @@ -455,6 +471,8 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame bool did_swap = false; move_count = list_from->moveItem(from_i, list_to, to_i, count, allow_swap, &did_swap); + if (caused_by_move_somewhere) + count = old_count; assert(allow_swap == did_swap); // If source is infinite, reset it's stack @@ -503,8 +521,7 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame << std::endl; // If we are inside the move somewhere loop, we don't need to report - // anything if nothing happened (perhaps we don't need to report - // anything for caused_by_move_somewhere == true, but this way its safer) + // anything if nothing happened if (caused_by_move_somewhere && move_count == 0) return; @@ -558,7 +575,15 @@ void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGame } mgr->setInventoryModified(from_inv); } else { + int src_item_count = src_item.count; + if (caused_by_move_somewhere) + // When moving somewhere: temporarily use the actual movable stack + // size to ensure correct callback execution. + src_item.count = move_count; onPutAndOnTake(src_item, player); + if (caused_by_move_somewhere) + // Reset source item count + src_item.count = src_item_count; if (did_swap) { // Item is now placed in source list src_item = list_from->getItem(from_i); diff --git a/src/irr_ptr.h b/src/irr_ptr.h index 5022adb9d..42b409676 100644 --- a/src/irr_ptr.h +++ b/src/irr_ptr.h @@ -27,9 +27,14 @@ with this program; if not, write to the Free Software Foundation, Inc., * It should only be used for user-managed objects, i.e. those created with * the @c new operator or @c create* functions, like: * `irr_ptr<scene::IMeshBuffer> buf{new scene::SMeshBuffer()};` + * The reference counting is *not* balanced as new objects have reference + * count set to one, and the @c irr_ptr constructor (and @c reset) assumes + * ownership of that reference. * - * It should *never* be used for engine-managed objects, including - * those created with @c addTexture and similar methods. + * It shouldn’t be used for engine-managed objects, including those created + * with @c addTexture and similar methods. Constructing @c irr_ptr directly + * from such object is a bug and may lead to a crash. Indirect construction + * is possible though; see the @c grab free function for details and use cases. */ template <class ReferenceCounted, class = typename std::enable_if<std::is_base_of<IReferenceCounted, @@ -38,16 +43,6 @@ class irr_ptr { ReferenceCounted *value = nullptr; - /** Drops stored pointer replacing it with the given one. - * @note Copy semantics: reference counter *is* increased. - */ - void grab(ReferenceCounted *object) - { - if (object) - object->grab(); - reset(object); - } - public: irr_ptr() {} @@ -71,8 +66,10 @@ public: reset(b.release()); } - /** Constructs a shared pointer out of a plain one + /** Constructs a shared pointer out of a plain one to control object lifetime. + * @param object The object, usually returned by some @c create* function. * @note Move semantics: reference counter is *not* increased. + * @warning Never wrap any @c add* function with this! */ explicit irr_ptr(ReferenceCounted *object) noexcept { reset(object); } @@ -134,4 +131,70 @@ public: value->drop(); value = object; } + + /** Drops stored pointer replacing it with the given one. + * @note Copy semantics: reference counter *is* increased. + */ + void grab(ReferenceCounted *object) noexcept + { + if (object) + object->grab(); + reset(object); + } }; + +// clang-format off +// ^ dislikes long lines + +/** Constructs a shared pointer as a *secondary* reference to an object + * + * This function is intended to make a temporary reference to an object which + * is owned elsewhere so that it is not destroyed too early. To acheive that + * it does balanced reference counting, i.e. reference count is increased + * in this function and decreased when the returned pointer is destroyed. + */ +template <class ReferenceCounted> +irr_ptr<ReferenceCounted> grab(ReferenceCounted *object) noexcept +{ + irr_ptr<ReferenceCounted> ptr; + ptr.grab(object); + return ptr; +} + +template <typename ReferenceCounted> +bool operator==(const irr_ptr<ReferenceCounted> &a, const irr_ptr<ReferenceCounted> &b) noexcept +{ + return a.get() == b.get(); +} + +template <typename ReferenceCounted> +bool operator==(const irr_ptr<ReferenceCounted> &a, const ReferenceCounted *b) noexcept +{ + return a.get() == b; +} + +template <typename ReferenceCounted> +bool operator==(const ReferenceCounted *a, const irr_ptr<ReferenceCounted> &b) noexcept +{ + return a == b.get(); +} + +template <typename ReferenceCounted> +bool operator!=(const irr_ptr<ReferenceCounted> &a, const irr_ptr<ReferenceCounted> &b) noexcept +{ + return a.get() != b.get(); +} + +template <typename ReferenceCounted> +bool operator!=(const irr_ptr<ReferenceCounted> &a, const ReferenceCounted *b) noexcept +{ + return a.get() != b; +} + +template <typename ReferenceCounted> +bool operator!=(const ReferenceCounted *a, const irr_ptr<ReferenceCounted> &b) noexcept +{ + return a != b.get(); +} + +// clang-format on diff --git a/src/irrlicht_changes/CGUITTFont.cpp b/src/irrlicht_changes/CGUITTFont.cpp index bd4e700de..e785ea837 100644 --- a/src/irrlicht_changes/CGUITTFont.cpp +++ b/src/irrlicht_changes/CGUITTFont.cpp @@ -103,7 +103,7 @@ video::IImage* SGUITTGlyph::createGlyphImage(const FT_Bitmap& bits, video::IVide // Load the monochrome data in. const u32 image_pitch = image->getPitch() / sizeof(u16); - u16* image_data = (u16*)image->lock(); + u16* image_data = (u16*)image->getData(); u8* glyph_data = bits.buffer; for (s32 y = 0; y < (s32)bits.rows; ++y) @@ -119,7 +119,6 @@ video::IImage* SGUITTGlyph::createGlyphImage(const FT_Bitmap& bits, video::IVide } image_data += image_pitch; } - image->unlock(); break; } @@ -133,7 +132,7 @@ video::IImage* SGUITTGlyph::createGlyphImage(const FT_Bitmap& bits, video::IVide // Load the grayscale data in. const float gray_count = static_cast<float>(bits.num_grays); const u32 image_pitch = image->getPitch() / sizeof(u32); - u32* image_data = (u32*)image->lock(); + u32* image_data = (u32*)image->getData(); u8* glyph_data = bits.buffer; for (s32 y = 0; y < (s32)bits.rows; ++y) { @@ -145,7 +144,6 @@ video::IImage* SGUITTGlyph::createGlyphImage(const FT_Bitmap& bits, video::IVide } glyph_data += bits.pitch; } - image->unlock(); break; } default: @@ -277,7 +275,8 @@ CGUITTFont* CGUITTFont::create(IrrlichtDevice *device, const io::path& filename, //! Constructor. CGUITTFont::CGUITTFont(IGUIEnvironment *env) : use_monochrome(false), use_transparency(true), use_hinting(true), use_auto_hinting(true), -batch_load_size(1), Device(0), Environment(env), Driver(0), GlobalKerningWidth(0), GlobalKerningHeight(0) +batch_load_size(1), Device(0), Environment(env), Driver(0), GlobalKerningWidth(0), GlobalKerningHeight(0), +shadow_offset(0), shadow_alpha(0), fallback(0) { #ifdef _DEBUG setDebugName("CGUITTFont"); @@ -548,12 +547,12 @@ void CGUITTFont::setFontHinting(const bool enable, const bool enable_auto_hintin void CGUITTFont::draw(const core::stringw& text, const core::rect<s32>& position, video::SColor color, bool hcenter, bool vcenter, const core::rect<s32>* clip) { - draw(EnrichedString(std::wstring(text.c_str()), color), position, color, hcenter, vcenter, clip); + draw(EnrichedString(std::wstring(text.c_str()), color), position, hcenter, vcenter, clip); } -void CGUITTFont::draw(const EnrichedString &text, const core::rect<s32>& position, video::SColor color, bool hcenter, bool vcenter, const core::rect<s32>* clip) +void CGUITTFont::draw(const EnrichedString &text, const core::rect<s32>& position, bool hcenter, bool vcenter, const core::rect<s32>* clip) { - std::vector<video::SColor> colors = text.getColors(); + const std::vector<video::SColor> &colors = text.getColors(); if (!Driver) return; @@ -563,6 +562,7 @@ void CGUITTFont::draw(const EnrichedString &text, const core::rect<s32>& positio { Glyph_Pages[i]->render_positions.clear(); Glyph_Pages[i]->render_source_rects.clear(); + Glyph_Pages[i]->render_colors.clear(); } // Set up some variables. @@ -591,7 +591,6 @@ void CGUITTFont::draw(const EnrichedString &text, const core::rect<s32>& positio u32 n; uchar32_t previousChar = 0; core::ustring::const_iterator iter(utext); - std::vector<video::SColor> applied_colors; while (!iter.atEnd()) { uchar32_t currentChar = *iter; @@ -637,12 +636,36 @@ void CGUITTFont::draw(const EnrichedString &text, const core::rect<s32>& positio CGUITTGlyphPage* const page = Glyph_Pages[glyph.glyph_page]; page->render_positions.push_back(core::position2di(offset.X + offx, offset.Y + offy)); page->render_source_rects.push_back(glyph.source_rect); + if (iter.getPos() < colors.size()) + page->render_colors.push_back(colors[iter.getPos()]); + else + page->render_colors.push_back(video::SColor(255,255,255,255)); Render_Map.set(glyph.glyph_page, page); - u32 current_color = iter.getPos(); - if (current_color < colors.size()) - applied_colors.push_back(colors[current_color]); } - offset.X += getWidthFromCharacter(currentChar); + if (n > 0) + { + offset.X += getWidthFromCharacter(currentChar); + } + else if (fallback != 0) + { + // Let the fallback font draw it, this isn't super efficient but hopefully that doesn't matter + wchar_t l1[] = { (wchar_t) currentChar, 0 }, l2 = (wchar_t) previousChar; + + if (visible) + { + // Apply kerning. + offset.X += fallback->getKerningWidth(l1, &l2); + offset.Y += fallback->getKerningHeight(); + + u32 current_color = iter.getPos(); + fallback->draw(core::stringw(l1), + core::rect<s32>({offset.X-1, offset.Y-1}, position.LowerRightCorner), // ??? + current_color < colors.size() ? colors[current_color] : video::SColor(255, 255, 255, 255), + false, false, clip); + } + + offset.X += fallback->getDimension(l1).Width; + } previousChar = currentChar; ++iter; @@ -666,16 +689,24 @@ void CGUITTFont::draw(const EnrichedString &text, const core::rect<s32>& positio for (size_t i = 0; i < page->render_positions.size(); ++i) page->render_positions[i] -= core::vector2di(shadow_offset, shadow_offset); } + // render runs of matching color in batch + size_t ibegin; + video::SColor colprev; for (size_t i = 0; i < page->render_positions.size(); ++i) { - irr::video::SColor col; - if (!applied_colors.empty()) { - col = applied_colors[i < applied_colors.size() ? i : 0]; - } else { - col = irr::video::SColor(255, 255, 255, 255); - } + ibegin = i; + colprev = page->render_colors[i]; + do + ++i; + while (i < page->render_positions.size() && page->render_colors[i] == colprev); + core::array<core::vector2di> tmp_positions; + core::array<core::recti> tmp_source_rects; + tmp_positions.set_pointer(&page->render_positions[ibegin], i - ibegin, false, false); // no copy + tmp_source_rects.set_pointer(&page->render_source_rects[ibegin], i - ibegin, false, false); + --i; + if (!use_transparency) - col.color |= 0xff000000; - Driver->draw2DImage(page->texture, page->render_positions[i], page->render_source_rects[i], clip, col, true); + colprev.color |= 0xff000000; + Driver->draw2DImageBatch(page->texture, tmp_positions, tmp_source_rects, clip, colprev, true); } } } @@ -768,6 +799,12 @@ inline u32 CGUITTFont::getWidthFromCharacter(uchar32_t c) const int w = Glyphs[n-1].advance.x / 64; return w; } + if (fallback != 0) + { + wchar_t s[] = { (wchar_t) c, 0 }; + return fallback->getDimension(s).Width; + } + if (c >= 0x2000) return (font_metrics.ascender / 64); else return (font_metrics.ascender / 64) / 2; @@ -791,6 +828,12 @@ inline u32 CGUITTFont::getHeightFromCharacter(uchar32_t c) const s32 height = (font_metrics.ascender / 64) - Glyphs[n-1].offset.Y + Glyphs[n-1].source_rect.getHeight(); return height; } + if (fallback != 0) + { + wchar_t s[] = { (wchar_t) c, 0 }; + return fallback->getDimension(s).Height; + } + if (c >= 0x2000) return (font_metrics.ascender / 64); else return (font_metrics.ascender / 64) / 2; @@ -806,9 +849,9 @@ u32 CGUITTFont::getGlyphIndexByChar(uchar32_t c) const // Get the glyph. u32 glyph = FT_Get_Char_Index(tt_face, c); - // Check for a valid glyph. If it is invalid, attempt to use the replacement character. + // Check for a valid glyph. if (glyph == 0) - glyph = FT_Get_Char_Index(tt_face, core::unicode::UTF_REPLACEMENT_CHARACTER); + return 0; // If our glyph is already loaded, don't bother doing any batch loading code. if (glyph != 0 && Glyphs[glyph - 1].isLoaded) @@ -924,13 +967,26 @@ core::vector2di CGUITTFont::getKerning(const uchar32_t thisLetter, const uchar32 core::vector2di ret(GlobalKerningWidth, GlobalKerningHeight); + u32 n = getGlyphIndexByChar(thisLetter); + + // If we don't have this glyph, ask fallback font + if (n == 0) + { + if (fallback != 0) { + wchar_t l1 = (wchar_t) thisLetter, l2 = (wchar_t) previousLetter; + ret.X = fallback->getKerningWidth(&l1, &l2); + ret.Y = fallback->getKerningHeight(); + } + return ret; + } + // If we don't have kerning, no point in continuing. if (!FT_HAS_KERNING(tt_face)) return ret; // Get the kerning information. FT_Vector v; - FT_Get_Kerning(tt_face, getGlyphIndexByChar(previousLetter), getGlyphIndexByChar(thisLetter), FT_KERNING_DEFAULT, &v); + FT_Get_Kerning(tt_face, getGlyphIndexByChar(previousLetter), n, FT_KERNING_DEFAULT, &v); // If we have a scalable font, the return value will be in font points. if (FT_IS_SCALABLE(tt_face)) @@ -962,6 +1018,9 @@ void CGUITTFont::setInvisibleCharacters(const core::ustring& s) video::IImage* CGUITTFont::createTextureFromChar(const uchar32_t& ch) { u32 n = getGlyphIndexByChar(ch); + if (n == 0) + n = getGlyphIndexByChar((uchar32_t) core::unicode::UTF_REPLACEMENT_CHARACTER); + const SGUITTGlyph& glyph = Glyphs[n-1]; CGUITTGlyphPage* page = Glyph_Pages[glyph.glyph_page]; @@ -971,11 +1030,7 @@ video::IImage* CGUITTFont::createTextureFromChar(const uchar32_t& ch) video::ITexture* tex = page->texture; // Acquire a read-only lock of the corresponding page texture. - #if IRRLICHT_VERSION_MAJOR==1 && IRRLICHT_VERSION_MINOR>=8 void* ptr = tex->lock(video::ETLM_READ_ONLY); - #else - void* ptr = tex->lock(true); - #endif video::ECOLOR_FORMAT format = tex->getColorFormat(); core::dimension2du tex_size = tex->getOriginalSize(); @@ -1132,11 +1187,7 @@ core::array<scene::ISceneNode*> CGUITTFont::addTextSceneNode(const wchar_t* text // Now we copy planes corresponding to the letter size. IMeshManipulator* mani = smgr->getMeshManipulator(); IMesh* meshcopy = mani->createMeshCopy(shared_plane_ptr_); - #if IRRLICHT_VERSION_MAJOR==1 && IRRLICHT_VERSION_MINOR>=8 mani->scale(meshcopy, vector3df((f32)letter_size.Width, (f32)letter_size.Height, 1)); - #else - mani->scaleMesh(meshcopy, vector3df((f32)letter_size.Width, (f32)letter_size.Height, 1)); - #endif ISceneNode* current_node = smgr->addMeshSceneNode(meshcopy, parent, -1, current_pos); meshcopy->drop(); @@ -1149,6 +1200,8 @@ core::array<scene::ISceneNode*> CGUITTFont::addTextSceneNode(const wchar_t* text container.push_back(current_node); } offset.X += getWidthFromCharacter(current_char); + // Note that fallback font handling is missing here (Minetest never uses this) + previous_char = current_char; ++text; } diff --git a/src/irrlicht_changes/CGUITTFont.h b/src/irrlicht_changes/CGUITTFont.h index 310f74f67..7b04ae828 100644 --- a/src/irrlicht_changes/CGUITTFont.h +++ b/src/irrlicht_changes/CGUITTFont.h @@ -34,7 +34,7 @@ #include <irrlicht.h> #include <ft2build.h> #include <vector> -#include "irrUString.h" +#include <irrUString.h> #include "util/enriched_string.h" #include FT_FREETYPE_H @@ -199,6 +199,7 @@ namespace gui core::array<core::vector2di> render_positions; core::array<core::recti> render_source_rects; + core::array<video::SColor> render_colors; private: core::array<const SGUITTGlyph*> glyph_to_be_paged; @@ -269,8 +270,8 @@ namespace gui video::SColor color, bool hcenter=false, bool vcenter=false, const core::rect<s32>* clip=0); - virtual void draw(const EnrichedString& text, const core::rect<s32>& position, - video::SColor color, bool hcenter=false, bool vcenter=false, + void draw(const EnrichedString& text, const core::rect<s32>& position, + bool hcenter=false, bool vcenter=false, const core::rect<s32>* clip=0); //! Returns the dimension of a character produced by this font. @@ -313,6 +314,9 @@ namespace gui //! Get the last glyph page's index. u32 getLastGlyphPageIndex() const { return Glyph_Pages.size() - 1; } + //! Set font that should be used for glyphs not present in ours + void setFallback(gui::IGUIFont* font) { fallback = font; } + //! Create corresponding character's software image copy from the font, //! so you can use this data just like any ordinary video::IImage. //! \param ch The character you need @@ -387,6 +391,8 @@ namespace gui core::ustring Invisible; u32 shadow_offset; u32 shadow_alpha; + + gui::IGUIFont* fallback; }; } // end namespace gui diff --git a/src/irrlicht_changes/CMakeLists.txt b/src/irrlicht_changes/CMakeLists.txt index d2f66ab77..87c88f7e8 100644 --- a/src/irrlicht_changes/CMakeLists.txt +++ b/src/irrlicht_changes/CMakeLists.txt @@ -3,7 +3,7 @@ if (BUILD_CLIENT) ${CMAKE_CURRENT_SOURCE_DIR}/static_text.cpp ) - if (ENABLE_FREETYPE) + if (USE_FREETYPE) set(client_irrlicht_changes_SRCS ${client_irrlicht_changes_SRCS} ${CMAKE_CURRENT_SOURCE_DIR}/CGUITTFont.cpp ) diff --git a/src/irrlicht_changes/irrUString.h b/src/irrlicht_changes/irrUString.h deleted file mode 100644 index 09172ee6d..000000000 --- a/src/irrlicht_changes/irrUString.h +++ /dev/null @@ -1,3891 +0,0 @@ -/* - Basic Unicode string class for Irrlicht. - Copyright (c) 2009-2011 John Norman - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any - damages arising from the use of this software. - - Permission is granted to anyone to use this software for any - purpose, including commercial applications, and to alter it and - redistribute it freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you - must not claim that you wrote the original software. If you use - this software in a product, an acknowledgment in the product - documentation would be appreciated but is not required. - - 2. Altered source versions must be plainly marked as such, and - must not be misrepresented as being the original software. - - 3. This notice may not be removed or altered from any source - distribution. - - The original version of this class can be located at: - http://irrlicht.suckerfreegames.com/ - - John Norman - john@suckerfreegames.com -*/ - -#pragma once - -#if (__cplusplus > 199711L) || (_MSC_VER >= 1600) || defined(__GXX_EXPERIMENTAL_CXX0X__) -# define USTRING_CPP0X -# if defined(__GXX_EXPERIMENTAL_CXX0X__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5))) -# define USTRING_CPP0X_NEWLITERALS -# endif -#endif - -#include <stdio.h> -#include <string.h> -#include <stdlib.h> -#include <cstddef> - -#ifdef _WIN32 -#define __BYTE_ORDER 0 -#define __LITTLE_ENDIAN 0 -#define __BIG_ENDIAN 1 -#elif defined(__MACH__) && defined(__APPLE__) -#include <machine/endian.h> -#elif defined(__FreeBSD__) || defined(__DragonFly__) -#include <sys/endian.h> -#else -#include <endian.h> -#endif - -#ifdef USTRING_CPP0X -# include <utility> -#endif - -#ifndef USTRING_NO_STL -# include <string> -# include <iterator> -# include <ostream> -#endif - -#include "irrTypes.h" -#include "irrAllocator.h" -#include "irrArray.h" -#include "irrMath.h" -#include "irrString.h" -#include "path.h" - -//! UTF-16 surrogate start values. -static const irr::u16 UTF16_HI_SURROGATE = 0xD800; -static const irr::u16 UTF16_LO_SURROGATE = 0xDC00; - -//! Is a UTF-16 code point a surrogate? -#define UTF16_IS_SURROGATE(c) (((c) & 0xF800) == 0xD800) -#define UTF16_IS_SURROGATE_HI(c) (((c) & 0xFC00) == 0xD800) -#define UTF16_IS_SURROGATE_LO(c) (((c) & 0xFC00) == 0xDC00) - - -namespace irr -{ - - // Define our character types. -#ifdef USTRING_CPP0X_NEWLITERALS // C++0x - typedef char32_t uchar32_t; - typedef char16_t uchar16_t; - typedef char uchar8_t; -#else - typedef u32 uchar32_t; - typedef u16 uchar16_t; - typedef u8 uchar8_t; -#endif - -namespace core -{ - -namespace unicode -{ - -//! The unicode replacement character. Used to replace invalid characters. -const irr::u16 UTF_REPLACEMENT_CHARACTER = 0xFFFD; - -//! Convert a UTF-16 surrogate pair into a UTF-32 character. -//! \param high The high value of the pair. -//! \param low The low value of the pair. -//! \return The UTF-32 character expressed by the surrogate pair. -inline uchar32_t toUTF32(uchar16_t high, uchar16_t low) -{ - // Convert the surrogate pair into a single UTF-32 character. - uchar32_t x = ((high & ((1 << 6) -1)) << 10) | (low & ((1 << 10) -1)); - uchar32_t wu = ((high >> 6) & ((1 << 5) - 1)) + 1; - return (wu << 16) | x; -} - -//! Swaps the endianness of a 16-bit value. -//! \return The new value. -inline uchar16_t swapEndian16(const uchar16_t& c) -{ - return ((c >> 8) & 0x00FF) | ((c << 8) & 0xFF00); -} - -//! Swaps the endianness of a 32-bit value. -//! \return The new value. -inline uchar32_t swapEndian32(const uchar32_t& c) -{ - return ((c >> 24) & 0x000000FF) | - ((c >> 8) & 0x0000FF00) | - ((c << 8) & 0x00FF0000) | - ((c << 24) & 0xFF000000); -} - -//! The Unicode byte order mark. -const u16 BOM = 0xFEFF; - -//! The size of the Unicode byte order mark in terms of the Unicode character size. -const u8 BOM_UTF8_LEN = 3; -const u8 BOM_UTF16_LEN = 1; -const u8 BOM_UTF32_LEN = 1; - -//! Unicode byte order marks for file operations. -const u8 BOM_ENCODE_UTF8[3] = { 0xEF, 0xBB, 0xBF }; -const u8 BOM_ENCODE_UTF16_BE[2] = { 0xFE, 0xFF }; -const u8 BOM_ENCODE_UTF16_LE[2] = { 0xFF, 0xFE }; -const u8 BOM_ENCODE_UTF32_BE[4] = { 0x00, 0x00, 0xFE, 0xFF }; -const u8 BOM_ENCODE_UTF32_LE[4] = { 0xFF, 0xFE, 0x00, 0x00 }; - -//! The size in bytes of the Unicode byte marks for file operations. -const u8 BOM_ENCODE_UTF8_LEN = 3; -const u8 BOM_ENCODE_UTF16_LEN = 2; -const u8 BOM_ENCODE_UTF32_LEN = 4; - -//! Unicode encoding type. -enum EUTF_ENCODE -{ - EUTFE_NONE = 0, - EUTFE_UTF8, - EUTFE_UTF16, - EUTFE_UTF16_LE, - EUTFE_UTF16_BE, - EUTFE_UTF32, - EUTFE_UTF32_LE, - EUTFE_UTF32_BE -}; - -//! Unicode endianness. -enum EUTF_ENDIAN -{ - EUTFEE_NATIVE = 0, - EUTFEE_LITTLE, - EUTFEE_BIG -}; - -//! Returns the specified unicode byte order mark in a byte array. -//! The byte order mark is the first few bytes in a text file that signifies its encoding. -/** \param mode The Unicode encoding method that we want to get the byte order mark for. - If EUTFE_UTF16 or EUTFE_UTF32 is passed, it uses the native system endianness. **/ -//! \return An array that contains a byte order mark. -inline core::array<u8> getUnicodeBOM(EUTF_ENCODE mode) -{ -#define COPY_ARRAY(source, size) \ - memcpy(ret.pointer(), source, size); \ - ret.set_used(size) - - core::array<u8> ret(4); - switch (mode) - { - case EUTFE_UTF8: - COPY_ARRAY(BOM_ENCODE_UTF8, BOM_ENCODE_UTF8_LEN); - break; - case EUTFE_UTF16: - #ifdef __BIG_ENDIAN__ - COPY_ARRAY(BOM_ENCODE_UTF16_BE, BOM_ENCODE_UTF16_LEN); - #else - COPY_ARRAY(BOM_ENCODE_UTF16_LE, BOM_ENCODE_UTF16_LEN); - #endif - break; - case EUTFE_UTF16_BE: - COPY_ARRAY(BOM_ENCODE_UTF16_BE, BOM_ENCODE_UTF16_LEN); - break; - case EUTFE_UTF16_LE: - COPY_ARRAY(BOM_ENCODE_UTF16_LE, BOM_ENCODE_UTF16_LEN); - break; - case EUTFE_UTF32: - #ifdef __BIG_ENDIAN__ - COPY_ARRAY(BOM_ENCODE_UTF32_BE, BOM_ENCODE_UTF32_LEN); - #else - COPY_ARRAY(BOM_ENCODE_UTF32_LE, BOM_ENCODE_UTF32_LEN); - #endif - break; - case EUTFE_UTF32_BE: - COPY_ARRAY(BOM_ENCODE_UTF32_BE, BOM_ENCODE_UTF32_LEN); - break; - case EUTFE_UTF32_LE: - COPY_ARRAY(BOM_ENCODE_UTF32_LE, BOM_ENCODE_UTF32_LEN); - break; - case EUTFE_NONE: - // TODO sapier: fixed warning only, - // don't know if something needs to be done here - break; - } - return ret; - -#undef COPY_ARRAY -} - -//! Detects if the given data stream starts with a unicode BOM. -//! \param data The data stream to check. -//! \return The unicode BOM associated with the data stream, or EUTFE_NONE if none was found. -inline EUTF_ENCODE determineUnicodeBOM(const char* data) -{ - if (memcmp(data, BOM_ENCODE_UTF8, 3) == 0) return EUTFE_UTF8; - if (memcmp(data, BOM_ENCODE_UTF16_BE, 2) == 0) return EUTFE_UTF16_BE; - if (memcmp(data, BOM_ENCODE_UTF16_LE, 2) == 0) return EUTFE_UTF16_LE; - if (memcmp(data, BOM_ENCODE_UTF32_BE, 4) == 0) return EUTFE_UTF32_BE; - if (memcmp(data, BOM_ENCODE_UTF32_LE, 4) == 0) return EUTFE_UTF32_LE; - return EUTFE_NONE; -} - -} // end namespace unicode - - -//! UTF-16 string class. -template <typename TAlloc = irrAllocator<uchar16_t> > -class ustring16 -{ -public: - - ///------------------/// - /// iterator classes /// - ///------------------/// - - //! Access an element in a unicode string, allowing one to change it. - class _ustring16_iterator_access - { - public: - _ustring16_iterator_access(const ustring16<TAlloc>* s, u32 p) : ref(s), pos(p) {} - - //! Allow the class to be interpreted as a single UTF-32 character. - operator uchar32_t() const - { - return _get(); - } - - //! Allow one to change the character in the unicode string. - //! \param c The new character to use. - //! \return Myself. - _ustring16_iterator_access& operator=(const uchar32_t c) - { - _set(c); - return *this; - } - - //! Increments the value by 1. - //! \return Myself. - _ustring16_iterator_access& operator++() - { - _set(_get() + 1); - return *this; - } - - //! Increments the value by 1, returning the old value. - //! \return A unicode character. - uchar32_t operator++(int) - { - uchar32_t old = _get(); - _set(old + 1); - return old; - } - - //! Decrements the value by 1. - //! \return Myself. - _ustring16_iterator_access& operator--() - { - _set(_get() - 1); - return *this; - } - - //! Decrements the value by 1, returning the old value. - //! \return A unicode character. - uchar32_t operator--(int) - { - uchar32_t old = _get(); - _set(old - 1); - return old; - } - - //! Adds to the value by a specified amount. - //! \param val The amount to add to this character. - //! \return Myself. - _ustring16_iterator_access& operator+=(int val) - { - _set(_get() + val); - return *this; - } - - //! Subtracts from the value by a specified amount. - //! \param val The amount to subtract from this character. - //! \return Myself. - _ustring16_iterator_access& operator-=(int val) - { - _set(_get() - val); - return *this; - } - - //! Multiples the value by a specified amount. - //! \param val The amount to multiply this character by. - //! \return Myself. - _ustring16_iterator_access& operator*=(int val) - { - _set(_get() * val); - return *this; - } - - //! Divides the value by a specified amount. - //! \param val The amount to divide this character by. - //! \return Myself. - _ustring16_iterator_access& operator/=(int val) - { - _set(_get() / val); - return *this; - } - - //! Modulos the value by a specified amount. - //! \param val The amount to modulo this character by. - //! \return Myself. - _ustring16_iterator_access& operator%=(int val) - { - _set(_get() % val); - return *this; - } - - //! Adds to the value by a specified amount. - //! \param val The amount to add to this character. - //! \return A unicode character. - uchar32_t operator+(int val) const - { - return _get() + val; - } - - //! Subtracts from the value by a specified amount. - //! \param val The amount to subtract from this character. - //! \return A unicode character. - uchar32_t operator-(int val) const - { - return _get() - val; - } - - //! Multiplies the value by a specified amount. - //! \param val The amount to multiply this character by. - //! \return A unicode character. - uchar32_t operator*(int val) const - { - return _get() * val; - } - - //! Divides the value by a specified amount. - //! \param val The amount to divide this character by. - //! \return A unicode character. - uchar32_t operator/(int val) const - { - return _get() / val; - } - - //! Modulos the value by a specified amount. - //! \param val The amount to modulo this character by. - //! \return A unicode character. - uchar32_t operator%(int val) const - { - return _get() % val; - } - - private: - //! Gets a uchar32_t from our current position. - uchar32_t _get() const - { - const uchar16_t* a = ref->c_str(); - if (!UTF16_IS_SURROGATE(a[pos])) - return static_cast<uchar32_t>(a[pos]); - else - { - if (pos + 1 >= ref->size_raw()) - return 0; - - return unicode::toUTF32(a[pos], a[pos + 1]); - } - } - - //! Sets a uchar32_t at our current position. - void _set(uchar32_t c) - { - ustring16<TAlloc>* ref2 = const_cast<ustring16<TAlloc>*>(ref); - const uchar16_t* a = ref2->c_str(); - if (c > 0xFFFF) - { - // c will be multibyte, so split it up into the high and low surrogate pairs. - uchar16_t x = static_cast<uchar16_t>(c); - uchar16_t vh = UTF16_HI_SURROGATE | ((((c >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); - uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); - - // If the previous position was a surrogate pair, just replace them. Else, insert the low pair. - if (UTF16_IS_SURROGATE_HI(a[pos]) && pos + 1 != ref2->size_raw()) - ref2->replace_raw(vl, static_cast<u32>(pos) + 1); - else ref2->insert_raw(vl, static_cast<u32>(pos) + 1); - - ref2->replace_raw(vh, static_cast<u32>(pos)); - } - else - { - // c will be a single byte. - uchar16_t vh = static_cast<uchar16_t>(c); - - // If the previous position was a surrogate pair, remove the extra byte. - if (UTF16_IS_SURROGATE_HI(a[pos])) - ref2->erase_raw(static_cast<u32>(pos) + 1); - - ref2->replace_raw(vh, static_cast<u32>(pos)); - } - } - - const ustring16<TAlloc>* ref; - u32 pos; - }; - typedef typename ustring16<TAlloc>::_ustring16_iterator_access access; - - - //! Iterator to iterate through a UTF-16 string. -#ifndef USTRING_NO_STL - class _ustring16_const_iterator : public std::iterator< - std::bidirectional_iterator_tag, // iterator_category - access, // value_type - ptrdiff_t, // difference_type - const access, // pointer - const access // reference - > -#else - class _ustring16_const_iterator -#endif - { - public: - typedef _ustring16_const_iterator _Iter; - typedef std::iterator<std::bidirectional_iterator_tag, access, ptrdiff_t, const access, const access> _Base; - typedef const access const_pointer; - typedef const access const_reference; - -#ifndef USTRING_NO_STL - typedef typename _Base::value_type value_type; - typedef typename _Base::difference_type difference_type; - typedef typename _Base::difference_type distance_type; - typedef typename _Base::pointer pointer; - typedef const_reference reference; -#else - typedef access value_type; - typedef u32 difference_type; - typedef u32 distance_type; - typedef const_pointer pointer; - typedef const_reference reference; -#endif - - //! Constructors. - _ustring16_const_iterator(const _Iter& i) : ref(i.ref), pos(i.pos) {} - _ustring16_const_iterator(const ustring16<TAlloc>& s) : ref(&s), pos(0) {} - _ustring16_const_iterator(const ustring16<TAlloc>& s, const u32 p) : ref(&s), pos(0) - { - if (ref->size_raw() == 0 || p == 0) - return; - - // Go to the appropriate position. - u32 i = p; - u32 sr = ref->size_raw(); - const uchar16_t* a = ref->c_str(); - while (i != 0 && pos < sr) - { - if (UTF16_IS_SURROGATE_HI(a[pos])) - pos += 2; - else ++pos; - --i; - } - } - - //! Test for equalness. - bool operator==(const _Iter& iter) const - { - if (ref == iter.ref && pos == iter.pos) - return true; - return false; - } - - //! Test for unequalness. - bool operator!=(const _Iter& iter) const - { - if (ref != iter.ref || pos != iter.pos) - return true; - return false; - } - - //! Switch to the next full character in the string. - _Iter& operator++() - { // ++iterator - if (pos == ref->size_raw()) return *this; - const uchar16_t* a = ref->c_str(); - if (UTF16_IS_SURROGATE_HI(a[pos])) - pos += 2; // TODO: check for valid low surrogate? - else ++pos; - if (pos > ref->size_raw()) pos = ref->size_raw(); - return *this; - } - - //! Switch to the next full character in the string, returning the previous position. - _Iter operator++(int) - { // iterator++ - _Iter _tmp(*this); - ++*this; - return _tmp; - } - - //! Switch to the previous full character in the string. - _Iter& operator--() - { // --iterator - if (pos == 0) return *this; - const uchar16_t* a = ref->c_str(); - --pos; - if (UTF16_IS_SURROGATE_LO(a[pos]) && pos != 0) // low surrogate, go back one more. - --pos; - return *this; - } - - //! Switch to the previous full character in the string, returning the previous position. - _Iter operator--(int) - { // iterator-- - _Iter _tmp(*this); - --*this; - return _tmp; - } - - //! Advance a specified number of full characters in the string. - //! \return Myself. - _Iter& operator+=(const difference_type v) - { - if (v == 0) return *this; - if (v < 0) return operator-=(v * -1); - - if (pos >= ref->size_raw()) - return *this; - - // Go to the appropriate position. - // TODO: Don't force u32 on an x64 OS. Make it agnostic. - u32 i = (u32)v; - u32 sr = ref->size_raw(); - const uchar16_t* a = ref->c_str(); - while (i != 0 && pos < sr) - { - if (UTF16_IS_SURROGATE_HI(a[pos])) - pos += 2; - else ++pos; - --i; - } - if (pos > sr) - pos = sr; - - return *this; - } - - //! Go back a specified number of full characters in the string. - //! \return Myself. - _Iter& operator-=(const difference_type v) - { - if (v == 0) return *this; - if (v > 0) return operator+=(v * -1); - - if (pos == 0) - return *this; - - // Go to the appropriate position. - // TODO: Don't force u32 on an x64 OS. Make it agnostic. - u32 i = (u32)v; - const uchar16_t* a = ref->c_str(); - while (i != 0 && pos != 0) - { - --pos; - if (UTF16_IS_SURROGATE_LO(a[pos]) != 0 && pos != 0) - --pos; - --i; - } - - return *this; - } - - //! Return a new iterator that is a variable number of full characters forward from the current position. - _Iter operator+(const difference_type v) const - { - _Iter ret(*this); - ret += v; - return ret; - } - - //! Return a new iterator that is a variable number of full characters backward from the current position. - _Iter operator-(const difference_type v) const - { - _Iter ret(*this); - ret -= v; - return ret; - } - - //! Returns the distance between two iterators. - difference_type operator-(const _Iter& iter) const - { - // Make sure we reference the same object! - if (ref != iter.ref) - return difference_type(); - - _Iter i = iter; - difference_type ret; - - // Walk up. - if (pos > i.pos) - { - while (pos > i.pos) - { - ++i; - ++ret; - } - return ret; - } - - // Walk down. - while (pos < i.pos) - { - --i; - --ret; - } - return ret; - } - - //! Accesses the full character at the iterator's position. - const_reference operator*() const - { - if (pos >= ref->size_raw()) - { - const uchar16_t* a = ref->c_str(); - u32 p = ref->size_raw(); - if (UTF16_IS_SURROGATE_LO(a[p])) - --p; - reference ret(ref, p); - return ret; - } - const_reference ret(ref, pos); - return ret; - } - - //! Accesses the full character at the iterator's position. - reference operator*() - { - if (pos >= ref->size_raw()) - { - const uchar16_t* a = ref->c_str(); - u32 p = ref->size_raw(); - if (UTF16_IS_SURROGATE_LO(a[p])) - --p; - reference ret(ref, p); - return ret; - } - reference ret(ref, pos); - return ret; - } - - //! Accesses the full character at the iterator's position. - const_pointer operator->() const - { - return operator*(); - } - - //! Accesses the full character at the iterator's position. - pointer operator->() - { - return operator*(); - } - - //! Is the iterator at the start of the string? - bool atStart() const - { - return pos == 0; - } - - //! Is the iterator at the end of the string? - bool atEnd() const - { - const uchar16_t* a = ref->c_str(); - if (UTF16_IS_SURROGATE(a[pos])) - return (pos + 1) >= ref->size_raw(); - else return pos >= ref->size_raw(); - } - - //! Moves the iterator to the start of the string. - void toStart() - { - pos = 0; - } - - //! Moves the iterator to the end of the string. - void toEnd() - { - pos = ref->size_raw(); - } - - //! Returns the iterator's position. - //! \return The iterator's position. - u32 getPos() const - { - return pos; - } - - protected: - const ustring16<TAlloc>* ref; - u32 pos; - }; - - //! Iterator to iterate through a UTF-16 string. - class _ustring16_iterator : public _ustring16_const_iterator - { - public: - typedef _ustring16_iterator _Iter; - typedef _ustring16_const_iterator _Base; - typedef typename _Base::const_pointer const_pointer; - typedef typename _Base::const_reference const_reference; - - - typedef typename _Base::value_type value_type; - typedef typename _Base::difference_type difference_type; - typedef typename _Base::distance_type distance_type; - typedef access pointer; - typedef access reference; - - using _Base::pos; - using _Base::ref; - - //! Constructors. - _ustring16_iterator(const _Iter& i) : _ustring16_const_iterator(i) {} - _ustring16_iterator(const ustring16<TAlloc>& s) : _ustring16_const_iterator(s) {} - _ustring16_iterator(const ustring16<TAlloc>& s, const u32 p) : _ustring16_const_iterator(s, p) {} - - //! Accesses the full character at the iterator's position. - reference operator*() const - { - if (pos >= ref->size_raw()) - { - const uchar16_t* a = ref->c_str(); - u32 p = ref->size_raw(); - if (UTF16_IS_SURROGATE_LO(a[p])) - --p; - reference ret(ref, p); - return ret; - } - reference ret(ref, pos); - return ret; - } - - //! Accesses the full character at the iterator's position. - reference operator*() - { - if (pos >= ref->size_raw()) - { - const uchar16_t* a = ref->c_str(); - u32 p = ref->size_raw(); - if (UTF16_IS_SURROGATE_LO(a[p])) - --p; - reference ret(ref, p); - return ret; - } - reference ret(ref, pos); - return ret; - } - - //! Accesses the full character at the iterator's position. - pointer operator->() const - { - return operator*(); - } - - //! Accesses the full character at the iterator's position. - pointer operator->() - { - return operator*(); - } - }; - - typedef typename ustring16<TAlloc>::_ustring16_iterator iterator; - typedef typename ustring16<TAlloc>::_ustring16_const_iterator const_iterator; - - ///----------------------/// - /// end iterator classes /// - ///----------------------/// - - //! Default constructor - ustring16() - : array(0), allocated(1), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - array = allocator.allocate(1); // new u16[1]; - array[0] = 0x0; - } - - - //! Constructor - ustring16(const ustring16<TAlloc>& other) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - *this = other; - } - - - //! Constructor from other string types - template <class B, class A> - ustring16(const string<B, A>& other) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - *this = other; - } - - -#ifndef USTRING_NO_STL - //! Constructor from std::string - template <class B, class A, typename Alloc> - ustring16(const std::basic_string<B, A, Alloc>& other) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - *this = other.c_str(); - } - - - //! Constructor from iterator. - template <typename Itr> - ustring16(Itr first, Itr last) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - reserve(std::distance(first, last)); - array[used] = 0; - - for (; first != last; ++first) - append((uchar32_t)*first); - } -#endif - - -#ifndef USTRING_CPP0X_NEWLITERALS - //! Constructor for copying a character string from a pointer. - ustring16(const char* const c) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - - loadDataStream(c, strlen(c)); - //append((uchar8_t*)c); - } - - - //! Constructor for copying a character string from a pointer with a given length. - ustring16(const char* const c, u32 length) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - - loadDataStream(c, length); - } -#endif - - - //! Constructor for copying a UTF-8 string from a pointer. - ustring16(const uchar8_t* const c) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - - append(c); - } - - - //! Constructor for copying a UTF-8 string from a single char. - ustring16(const char c) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - - append((uchar32_t)c); - } - - - //! Constructor for copying a UTF-8 string from a pointer with a given length. - ustring16(const uchar8_t* const c, u32 length) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - - append(c, length); - } - - - //! Constructor for copying a UTF-16 string from a pointer. - ustring16(const uchar16_t* const c) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - - append(c); - } - - - //! Constructor for copying a UTF-16 string from a pointer with a given length - ustring16(const uchar16_t* const c, u32 length) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - - append(c, length); - } - - - //! Constructor for copying a UTF-32 string from a pointer. - ustring16(const uchar32_t* const c) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - - append(c); - } - - - //! Constructor for copying a UTF-32 from a pointer with a given length. - ustring16(const uchar32_t* const c, u32 length) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - - append(c, length); - } - - - //! Constructor for copying a wchar_t string from a pointer. - ustring16(const wchar_t* const c) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - - if (sizeof(wchar_t) == 4) - append(reinterpret_cast<const uchar32_t* const>(c)); - else if (sizeof(wchar_t) == 2) - append(reinterpret_cast<const uchar16_t* const>(c)); - else if (sizeof(wchar_t) == 1) - append(reinterpret_cast<const uchar8_t* const>(c)); - } - - - //! Constructor for copying a wchar_t string from a pointer with a given length. - ustring16(const wchar_t* const c, u32 length) - : array(0), allocated(0), used(0) - { -#if __BYTE_ORDER == __BIG_ENDIAN - encoding = unicode::EUTFE_UTF16_BE; -#else - encoding = unicode::EUTFE_UTF16_LE; -#endif - - if (sizeof(wchar_t) == 4) - append(reinterpret_cast<const uchar32_t* const>(c), length); - else if (sizeof(wchar_t) == 2) - append(reinterpret_cast<const uchar16_t* const>(c), length); - else if (sizeof(wchar_t) == 1) - append(reinterpret_cast<const uchar8_t* const>(c), length); - } - - -#ifdef USTRING_CPP0X - //! Constructor for moving a ustring16 - ustring16(ustring16<TAlloc>&& other) - : array(other.array), encoding(other.encoding), allocated(other.allocated), used(other.used) - { - //std::cout << "MOVE constructor" << std::endl; - other.array = 0; - other.allocated = 0; - other.used = 0; - } -#endif - - - //! Destructor - ~ustring16() - { - allocator.deallocate(array); // delete [] array; - } - - - //! Assignment operator - ustring16& operator=(const ustring16<TAlloc>& other) - { - if (this == &other) - return *this; - - used = other.size_raw(); - if (used >= allocated) - { - allocator.deallocate(array); // delete [] array; - allocated = used + 1; - array = allocator.allocate(used + 1); //new u16[used]; - } - - const uchar16_t* p = other.c_str(); - for (u32 i=0; i<=used; ++i, ++p) - array[i] = *p; - - array[used] = 0; - - // Validate our new UTF-16 string. - validate(); - - return *this; - } - - -#ifdef USTRING_CPP0X - //! Move assignment operator - ustring16& operator=(ustring16<TAlloc>&& other) - { - if (this != &other) - { - //std::cout << "MOVE operator=" << std::endl; - allocator.deallocate(array); - - array = other.array; - allocated = other.allocated; - encoding = other.encoding; - used = other.used; - other.array = 0; - other.used = 0; - } - return *this; - } -#endif - - - //! Assignment operator for other string types - template <class B, class A> - ustring16<TAlloc>& operator=(const string<B, A>& other) - { - *this = other.c_str(); - return *this; - } - - - //! Assignment operator for UTF-8 strings - ustring16<TAlloc>& operator=(const uchar8_t* const c) - { - if (!array) - { - array = allocator.allocate(1); //new u16[1]; - allocated = 1; - } - used = 0; - array[used] = 0x0; - if (!c) return *this; - - //! Append our string now. - append(c); - return *this; - } - - - //! Assignment operator for UTF-16 strings - ustring16<TAlloc>& operator=(const uchar16_t* const c) - { - if (!array) - { - array = allocator.allocate(1); //new u16[1]; - allocated = 1; - } - used = 0; - array[used] = 0x0; - if (!c) return *this; - - //! Append our string now. - append(c); - return *this; - } - - - //! Assignment operator for UTF-32 strings - ustring16<TAlloc>& operator=(const uchar32_t* const c) - { - if (!array) - { - array = allocator.allocate(1); //new u16[1]; - allocated = 1; - } - used = 0; - array[used] = 0x0; - if (!c) return *this; - - //! Append our string now. - append(c); - return *this; - } - - - //! Assignment operator for wchar_t strings. - /** Note that this assumes that a correct unicode string is stored in the wchar_t string. - Since wchar_t changes depending on its platform, it could either be a UTF-8, -16, or -32 string. - This function assumes you are storing the correct unicode encoding inside the wchar_t string. **/ - ustring16<TAlloc>& operator=(const wchar_t* const c) - { - if (sizeof(wchar_t) == 4) - *this = reinterpret_cast<const uchar32_t* const>(c); - else if (sizeof(wchar_t) == 2) - *this = reinterpret_cast<const uchar16_t* const>(c); - else if (sizeof(wchar_t) == 1) - *this = reinterpret_cast<const uchar8_t* const>(c); - - return *this; - } - - - //! Assignment operator for other strings. - /** Note that this assumes that a correct unicode string is stored in the string. **/ - template <class B> - ustring16<TAlloc>& operator=(const B* const c) - { - if (sizeof(B) == 4) - *this = reinterpret_cast<const uchar32_t* const>(c); - else if (sizeof(B) == 2) - *this = reinterpret_cast<const uchar16_t* const>(c); - else if (sizeof(B) == 1) - *this = reinterpret_cast<const uchar8_t* const>(c); - - return *this; - } - - - //! Direct access operator - access operator [](const u32 index) - { - _IRR_DEBUG_BREAK_IF(index>=size()) // bad index - iterator iter(*this, index); - return iter.operator*(); - } - - - //! Direct access operator - const access operator [](const u32 index) const - { - _IRR_DEBUG_BREAK_IF(index>=size()) // bad index - const_iterator iter(*this, index); - return iter.operator*(); - } - - - //! Equality operator - bool operator ==(const uchar16_t* const str) const - { - if (!str) - return false; - - u32 i; - for(i=0; array[i] && str[i]; ++i) - if (array[i] != str[i]) - return false; - - return !array[i] && !str[i]; - } - - - //! Equality operator - bool operator ==(const ustring16<TAlloc>& other) const - { - for(u32 i=0; array[i] && other.array[i]; ++i) - if (array[i] != other.array[i]) - return false; - - return used == other.used; - } - - - //! Is smaller comparator - bool operator <(const ustring16<TAlloc>& other) const - { - for(u32 i=0; array[i] && other.array[i]; ++i) - { - s32 diff = array[i] - other.array[i]; - if ( diff ) - return diff < 0; - } - - return used < other.used; - } - - - //! Inequality operator - bool operator !=(const uchar16_t* const str) const - { - return !(*this == str); - } - - - //! Inequality operator - bool operator !=(const ustring16<TAlloc>& other) const - { - return !(*this == other); - } - - - //! Returns the length of a ustring16 in full characters. - //! \return Length of a ustring16 in full characters. - u32 size() const - { - const_iterator i(*this, 0); - u32 pos = 0; - while (!i.atEnd()) - { - ++i; - ++pos; - } - return pos; - } - - - //! Informs if the ustring is empty or not. - //! \return True if the ustring is empty, false if not. - bool empty() const - { - return (size_raw() == 0); - } - - - //! Returns a pointer to the raw UTF-16 string data. - //! \return pointer to C-style NUL terminated array of UTF-16 code points. - const uchar16_t* c_str() const - { - return array; - } - - - //! Compares the first n characters of this string with another. - //! \param other Other string to compare to. - //! \param n Number of characters to compare. - //! \return True if the n first characters of both strings are equal. - bool equalsn(const ustring16<TAlloc>& other, u32 n) const - { - u32 i; - const uchar16_t* oa = other.c_str(); - for(i=0; i < n && array[i] && oa[i]; ++i) - if (array[i] != oa[i]) - return false; - - // if one (or both) of the strings was smaller then they - // are only equal if they have the same length - return (i == n) || (used == other.used); - } - - - //! Compares the first n characters of this string with another. - //! \param str Other string to compare to. - //! \param n Number of characters to compare. - //! \return True if the n first characters of both strings are equal. - bool equalsn(const uchar16_t* const str, u32 n) const - { - if (!str) - return false; - u32 i; - for(i=0; i < n && array[i] && str[i]; ++i) - if (array[i] != str[i]) - return false; - - // if one (or both) of the strings was smaller then they - // are only equal if they have the same length - return (i == n) || (array[i] == 0 && str[i] == 0); - } - - - //! Appends a character to this ustring16 - //! \param character The character to append. - //! \return A reference to our current string. - ustring16<TAlloc>& append(uchar32_t character) - { - if (used + 2 >= allocated) - reallocate(used + 2); - - if (character > 0xFFFF) - { - used += 2; - - // character will be multibyte, so split it up into a surrogate pair. - uchar16_t x = static_cast<uchar16_t>(character); - uchar16_t vh = UTF16_HI_SURROGATE | ((((character >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); - uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); - array[used-2] = vh; - array[used-1] = vl; - } - else - { - ++used; - array[used-1] = character; - } - array[used] = 0; - - return *this; - } - - - //! Appends a UTF-8 string to this ustring16 - //! \param other The UTF-8 string to append. - //! \param length The length of the string to append. - //! \return A reference to our current string. - ustring16<TAlloc>& append(const uchar8_t* const other, u32 length=0xffffffff) - { - if (!other) - return *this; - - // Determine if the string is long enough for a BOM. - u32 len = 0; - const uchar8_t* p = other; - do - { - ++len; - } while (*p++ && len < unicode::BOM_ENCODE_UTF8_LEN); - - // Check for BOM. - unicode::EUTF_ENCODE c_bom = unicode::EUTFE_NONE; - if (len == unicode::BOM_ENCODE_UTF8_LEN) - { - if (memcmp(other, unicode::BOM_ENCODE_UTF8, unicode::BOM_ENCODE_UTF8_LEN) == 0) - c_bom = unicode::EUTFE_UTF8; - } - - // If a BOM was found, don't include it in the string. - const uchar8_t* c2 = other; - if (c_bom != unicode::EUTFE_NONE) - { - c2 = other + unicode::BOM_UTF8_LEN; - length -= unicode::BOM_UTF8_LEN; - } - - // Calculate the size of the string to read in. - len = 0; - p = c2; - do - { - ++len; - } while(*p++ && len < length); - if (len > length) - len = length; - - // If we need to grow the array, do it now. - if (used + len >= allocated) - reallocate(used + (len * 2)); - u32 start = used; - - // Convert UTF-8 to UTF-16. - u32 pos = start; - for (u32 l = 0; l<len;) - { - ++used; - if (((c2[l] >> 6) & 0x03) == 0x02) - { // Invalid continuation byte. - array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; - ++l; - } - else if (c2[l] == 0xC0 || c2[l] == 0xC1) - { // Invalid byte - overlong encoding. - array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; - ++l; - } - else if ((c2[l] & 0xF8) == 0xF0) - { // 4 bytes UTF-8, 2 bytes UTF-16. - // Check for a full string. - if ((l + 3) >= len) - { - array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; - l += 3; - break; - } - - // Validate. - bool valid = true; - u8 l2 = 0; - if (valid && (((c2[l+1] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; - if (valid && (((c2[l+2] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; - if (valid && (((c2[l+3] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; - if (!valid) - { - array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; - l += l2; - continue; - } - - // Decode. - uchar8_t b1 = ((c2[l] & 0x7) << 2) | ((c2[l+1] >> 4) & 0x3); - uchar8_t b2 = ((c2[l+1] & 0xF) << 4) | ((c2[l+2] >> 2) & 0xF); - uchar8_t b3 = ((c2[l+2] & 0x3) << 6) | (c2[l+3] & 0x3F); - uchar32_t v = b3 | ((uchar32_t)b2 << 8) | ((uchar32_t)b1 << 16); - - // Split v up into a surrogate pair. - uchar16_t x = static_cast<uchar16_t>(v); - uchar16_t vh = UTF16_HI_SURROGATE | ((((v >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); - uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); - - array[pos++] = vh; - array[pos++] = vl; - l += 4; - ++used; // Using two shorts this time, so increase used by 1. - } - else if ((c2[l] & 0xF0) == 0xE0) - { // 3 bytes UTF-8, 1 byte UTF-16. - // Check for a full string. - if ((l + 2) >= len) - { - array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; - l += 2; - break; - } - - // Validate. - bool valid = true; - u8 l2 = 0; - if (valid && (((c2[l+1] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; - if (valid && (((c2[l+2] >> 6) & 0x03) == 0x02)) ++l2; else valid = false; - if (!valid) - { - array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; - l += l2; - continue; - } - - // Decode. - uchar8_t b1 = ((c2[l] & 0xF) << 4) | ((c2[l+1] >> 2) & 0xF); - uchar8_t b2 = ((c2[l+1] & 0x3) << 6) | (c2[l+2] & 0x3F); - uchar16_t ch = b2 | ((uchar16_t)b1 << 8); - array[pos++] = ch; - l += 3; - } - else if ((c2[l] & 0xE0) == 0xC0) - { // 2 bytes UTF-8, 1 byte UTF-16. - // Check for a full string. - if ((l + 1) >= len) - { - array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; - l += 1; - break; - } - - // Validate. - if (((c2[l+1] >> 6) & 0x03) != 0x02) - { - array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; - ++l; - continue; - } - - // Decode. - uchar8_t b1 = (c2[l] >> 2) & 0x7; - uchar8_t b2 = ((c2[l] & 0x3) << 6) | (c2[l+1] & 0x3F); - uchar16_t ch = b2 | ((uchar16_t)b1 << 8); - array[pos++] = ch; - l += 2; - } - else - { // 1 byte UTF-8, 1 byte UTF-16. - // Validate. - if (c2[l] > 0x7F) - { // Values above 0xF4 are restricted and aren't used. By now, anything above 0x7F is invalid. - array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; - } - else array[pos++] = static_cast<uchar16_t>(c2[l]); - ++l; - } - } - array[used] = 0; - - // Validate our new UTF-16 string. - validate(); - - return *this; - } - - - //! Appends a UTF-16 string to this ustring16 - //! \param other The UTF-16 string to append. - //! \param length The length of the string to append. - //! \return A reference to our current string. - ustring16<TAlloc>& append(const uchar16_t* const other, u32 length=0xffffffff) - { - if (!other) - return *this; - - // Determine if the string is long enough for a BOM. - u32 len = 0; - const uchar16_t* p = other; - do - { - ++len; - } while (*p++ && len < unicode::BOM_ENCODE_UTF16_LEN); - - // Check for the BOM to determine the string's endianness. - unicode::EUTF_ENDIAN c_end = unicode::EUTFEE_NATIVE; - if (memcmp(other, unicode::BOM_ENCODE_UTF16_LE, unicode::BOM_ENCODE_UTF16_LEN) == 0) - c_end = unicode::EUTFEE_LITTLE; - else if (memcmp(other, unicode::BOM_ENCODE_UTF16_BE, unicode::BOM_ENCODE_UTF16_LEN) == 0) - c_end = unicode::EUTFEE_BIG; - - // If a BOM was found, don't include it in the string. - const uchar16_t* c2 = other; - if (c_end != unicode::EUTFEE_NATIVE) - { - c2 = other + unicode::BOM_UTF16_LEN; - length -= unicode::BOM_UTF16_LEN; - } - - // Calculate the size of the string to read in. - len = 0; - p = c2; - do - { - ++len; - } while(*p++ && len < length); - if (len > length) - len = length; - - // If we need to grow the size of the array, do it now. - if (used + len >= allocated) - reallocate(used + (len * 2)); - u32 start = used; - used += len; - - // Copy the string now. - unicode::EUTF_ENDIAN m_end = getEndianness(); - for (u32 l = start; l < start + len; ++l) - { - array[l] = (uchar16_t)c2[l]; - if (c_end != unicode::EUTFEE_NATIVE && c_end != m_end) - array[l] = unicode::swapEndian16(array[l]); - } - - array[used] = 0; - - // Validate our new UTF-16 string. - validate(); - return *this; - } - - - //! Appends a UTF-32 string to this ustring16 - //! \param other The UTF-32 string to append. - //! \param length The length of the string to append. - //! \return A reference to our current string. - ustring16<TAlloc>& append(const uchar32_t* const other, u32 length=0xffffffff) - { - if (!other) - return *this; - - // Check for the BOM to determine the string's endianness. - unicode::EUTF_ENDIAN c_end = unicode::EUTFEE_NATIVE; - if (memcmp(other, unicode::BOM_ENCODE_UTF32_LE, unicode::BOM_ENCODE_UTF32_LEN) == 0) - c_end = unicode::EUTFEE_LITTLE; - else if (memcmp(other, unicode::BOM_ENCODE_UTF32_BE, unicode::BOM_ENCODE_UTF32_LEN) == 0) - c_end = unicode::EUTFEE_BIG; - - // If a BOM was found, don't include it in the string. - const uchar32_t* c2 = other; - if (c_end != unicode::EUTFEE_NATIVE) - { - c2 = other + unicode::BOM_UTF32_LEN; - length -= unicode::BOM_UTF32_LEN; - } - - // Calculate the size of the string to read in. - u32 len = 0; - const uchar32_t* p = c2; - do - { - ++len; - } while(*p++ && len < length); - if (len > length) - len = length; - - // If we need to grow the size of the array, do it now. - // In case all of the UTF-32 string is split into surrogate pairs, do len * 2. - if (used + (len * 2) >= allocated) - reallocate(used + ((len * 2) * 2)); - u32 start = used; - - // Convert UTF-32 to UTF-16. - unicode::EUTF_ENDIAN m_end = getEndianness(); - u32 pos = start; - for (u32 l = 0; l<len; ++l) - { - ++used; - - uchar32_t ch = c2[l]; - if (c_end != unicode::EUTFEE_NATIVE && c_end != m_end) - ch = unicode::swapEndian32(ch); - - if (ch > 0xFFFF) - { - // Split ch up into a surrogate pair as it is over 16 bits long. - uchar16_t x = static_cast<uchar16_t>(ch); - uchar16_t vh = UTF16_HI_SURROGATE | ((((ch >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); - uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); - array[pos++] = vh; - array[pos++] = vl; - ++used; // Using two shorts, so increased used again. - } - else if (ch >= 0xD800 && ch <= 0xDFFF) - { - // Between possible UTF-16 surrogates (invalid!) - array[pos++] = unicode::UTF_REPLACEMENT_CHARACTER; - } - else array[pos++] = static_cast<uchar16_t>(ch); - } - array[used] = 0; - - // Validate our new UTF-16 string. - validate(); - - return *this; - } - - - //! Appends a ustring16 to this ustring16 - //! \param other The string to append to this one. - //! \return A reference to our current string. - ustring16<TAlloc>& append(const ustring16<TAlloc>& other) - { - const uchar16_t* oa = other.c_str(); - - u32 len = other.size_raw(); - - if (used + len >= allocated) - reallocate(used + len); - - for (u32 l=0; l<len; ++l) - array[used+l] = oa[l]; - - used += len; - array[used] = 0; - - return *this; - } - - - //! Appends a certain amount of characters of a ustring16 to this ustring16. - //! \param other The string to append to this one. - //! \param length How many characters of the other string to add to this one. - //! \return A reference to our current string. - ustring16<TAlloc>& append(const ustring16<TAlloc>& other, u32 length) - { - if (other.size() == 0) - return *this; - - if (other.size() < length) - { - append(other); - return *this; - } - - if (used + length * 2 >= allocated) - reallocate(used + length * 2); - - const_iterator iter(other, 0); - u32 l = length; - while (!iter.atEnd() && l) - { - uchar32_t c = *iter; - append(c); - ++iter; - --l; - } - - return *this; - } - - - //! Reserves some memory. - //! \param count The amount of characters to reserve. - void reserve(u32 count) - { - if (count < allocated) - return; - - reallocate(count); - } - - - //! Finds first occurrence of character. - //! \param c The character to search for. - //! \return Position where the character has been found, or -1 if not found. - s32 findFirst(uchar32_t c) const - { - const_iterator i(*this, 0); - - s32 pos = 0; - while (!i.atEnd()) - { - uchar32_t t = *i; - if (c == t) - return pos; - ++pos; - ++i; - } - - return -1; - } - - //! Finds first occurrence of a character of a list. - //! \param c A list of characters to find. For example if the method should find the first occurrence of 'a' or 'b', this parameter should be "ab". - //! \param count The amount of characters in the list. Usually, this should be strlen(c). - //! \return Position where one of the characters has been found, or -1 if not found. - s32 findFirstChar(const uchar32_t* const c, u32 count=1) const - { - if (!c || !count) - return -1; - - const_iterator i(*this, 0); - - s32 pos = 0; - while (!i.atEnd()) - { - uchar32_t t = *i; - for (u32 j=0; j<count; ++j) - if (t == c[j]) - return pos; - ++pos; - ++i; - } - - return -1; - } - - - //! Finds first position of a character not in a given list. - //! \param c A list of characters to NOT find. For example if the method should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab". - //! \param count The amount of characters in the list. Usually, this should be strlen(c). - //! \return Position where the character has been found, or -1 if not found. - s32 findFirstCharNotInList(const uchar32_t* const c, u32 count=1) const - { - if (!c || !count) - return -1; - - const_iterator i(*this, 0); - - s32 pos = 0; - while (!i.atEnd()) - { - uchar32_t t = *i; - u32 j; - for (j=0; j<count; ++j) - if (t == c[j]) - break; - - if (j==count) - return pos; - ++pos; - ++i; - } - - return -1; - } - - //! Finds last position of a character not in a given list. - //! \param c A list of characters to NOT find. For example if the method should find the first occurrence of a character not 'a' or 'b', this parameter should be "ab". - //! \param count The amount of characters in the list. Usually, this should be strlen(c). - //! \return Position where the character has been found, or -1 if not found. - s32 findLastCharNotInList(const uchar32_t* const c, u32 count=1) const - { - if (!c || !count) - return -1; - - const_iterator i(end()); - --i; - - s32 pos = size() - 1; - while (!i.atStart()) - { - uchar32_t t = *i; - u32 j; - for (j=0; j<count; ++j) - if (t == c[j]) - break; - - if (j==count) - return pos; - --pos; - --i; - } - - return -1; - } - - //! Finds next occurrence of character. - //! \param c The character to search for. - //! \param startPos The position in the string to start searching. - //! \return Position where the character has been found, or -1 if not found. - s32 findNext(uchar32_t c, u32 startPos) const - { - const_iterator i(*this, startPos); - - s32 pos = startPos; - while (!i.atEnd()) - { - uchar32_t t = *i; - if (t == c) - return pos; - ++pos; - ++i; - } - - return -1; - } - - - //! Finds last occurrence of character. - //! \param c The character to search for. - //! \param start The start position of the reverse search ( default = -1, on end ). - //! \return Position where the character has been found, or -1 if not found. - s32 findLast(uchar32_t c, s32 start = -1) const - { - u32 s = size(); - start = core::clamp ( start < 0 ? (s32)s : start, 0, (s32)s ) - 1; - - const_iterator i(*this, start); - u32 pos = start; - while (!i.atStart()) - { - uchar32_t t = *i; - if (t == c) - return pos; - --pos; - --i; - } - - return -1; - } - - //! Finds last occurrence of a character in a list. - //! \param c A list of strings to find. For example if the method should find the last occurrence of 'a' or 'b', this parameter should be "ab". - //! \param count The amount of characters in the list. Usually, this should be strlen(c). - //! \return Position where one of the characters has been found, or -1 if not found. - s32 findLastChar(const uchar32_t* const c, u32 count=1) const - { - if (!c || !count) - return -1; - - const_iterator i(end()); - --i; - - s32 pos = size(); - while (!i.atStart()) - { - uchar32_t t = *i; - for (u32 j=0; j<count; ++j) - if (t == c[j]) - return pos; - --pos; - --i; - } - - return -1; - } - - - //! Finds another ustring16 in this ustring16. - //! \param str The string to find. - //! \param start The start position of the search. - //! \return Positions where the ustring16 has been found, or -1 if not found. - s32 find(const ustring16<TAlloc>& str, const u32 start = 0) const - { - u32 my_size = size(); - u32 their_size = str.size(); - - if (their_size == 0 || my_size - start < their_size) - return -1; - - const_iterator i(*this, start); - - s32 pos = start; - while (!i.atEnd()) - { - const_iterator i2(i); - const_iterator j(str, 0); - uchar32_t t1 = (uchar32_t)*i2; - uchar32_t t2 = (uchar32_t)*j; - while (t1 == t2) - { - ++i2; - ++j; - if (j.atEnd()) - return pos; - t1 = (uchar32_t)*i2; - t2 = (uchar32_t)*j; - } - ++i; - ++pos; - } - - return -1; - } - - - //! Finds another ustring16 in this ustring16. - //! \param str The string to find. - //! \param start The start position of the search. - //! \return Positions where the string has been found, or -1 if not found. - s32 find_raw(const ustring16<TAlloc>& str, const u32 start = 0) const - { - const uchar16_t* data = str.c_str(); - if (data && *data) - { - u32 len = 0; - - while (data[len]) - ++len; - - if (len > used) - return -1; - - for (u32 i=start; i<=used-len; ++i) - { - u32 j=0; - - while(data[j] && array[i+j] == data[j]) - ++j; - - if (!data[j]) - return i; - } - } - - return -1; - } - - - //! Returns a substring. - //! \param begin: Start of substring. - //! \param length: Length of substring. - //! \return A reference to our current string. - ustring16<TAlloc> subString(u32 begin, s32 length) const - { - u32 len = size(); - // if start after ustring16 - // or no proper substring length - if ((length <= 0) || (begin>=len)) - return ustring16<TAlloc>(""); - // clamp length to maximal value - if ((length+begin) > len) - length = len-begin; - - ustring16<TAlloc> o; - o.reserve((length+1) * 2); - - const_iterator i(*this, begin); - while (!i.atEnd() && length) - { - o.append(*i); - ++i; - --length; - } - - return o; - } - - - //! Appends a character to this ustring16. - //! \param c Character to append. - //! \return A reference to our current string. - ustring16<TAlloc>& operator += (char c) - { - append((uchar32_t)c); - return *this; - } - - - //! Appends a character to this ustring16. - //! \param c Character to append. - //! \return A reference to our current string. - ustring16<TAlloc>& operator += (uchar32_t c) - { - append(c); - return *this; - } - - - //! Appends a number to this ustring16. - //! \param c Number to append. - //! \return A reference to our current string. - ustring16<TAlloc>& operator += (short c) - { - append(core::stringc(c)); - return *this; - } - - - //! Appends a number to this ustring16. - //! \param c Number to append. - //! \return A reference to our current string. - ustring16<TAlloc>& operator += (unsigned short c) - { - append(core::stringc(c)); - return *this; - } - - -#ifdef USTRING_CPP0X_NEWLITERALS - //! Appends a number to this ustring16. - //! \param c Number to append. - //! \return A reference to our current string. - ustring16<TAlloc>& operator += (int c) - { - append(core::stringc(c)); - return *this; - } - - - //! Appends a number to this ustring16. - //! \param c Number to append. - //! \return A reference to our current string. - ustring16<TAlloc>& operator += (unsigned int c) - { - append(core::stringc(c)); - return *this; - } -#endif - - - //! Appends a number to this ustring16. - //! \param c Number to append. - //! \return A reference to our current string. - ustring16<TAlloc>& operator += (long c) - { - append(core::stringc(c)); - return *this; - } - - - //! Appends a number to this ustring16. - //! \param c Number to append. - //! \return A reference to our current string. - ustring16<TAlloc>& operator += (unsigned long c) - { - append(core::stringc(c)); - return *this; - } - - - //! Appends a number to this ustring16. - //! \param c Number to append. - //! \return A reference to our current string. - ustring16<TAlloc>& operator += (double c) - { - append(core::stringc(c)); - return *this; - } - - - //! Appends a char ustring16 to this ustring16. - //! \param c Char ustring16 to append. - //! \return A reference to our current string. - ustring16<TAlloc>& operator += (const uchar16_t* const c) - { - append(c); - return *this; - } - - - //! Appends a ustring16 to this ustring16. - //! \param other ustring16 to append. - //! \return A reference to our current string. - ustring16<TAlloc>& operator += (const ustring16<TAlloc>& other) - { - append(other); - return *this; - } - - - //! Replaces all characters of a given type with another one. - //! \param toReplace Character to replace. - //! \param replaceWith Character replacing the old one. - //! \return A reference to our current string. - ustring16<TAlloc>& replace(uchar32_t toReplace, uchar32_t replaceWith) - { - iterator i(*this, 0); - while (!i.atEnd()) - { - typename ustring16<TAlloc>::access a = *i; - if ((uchar32_t)a == toReplace) - a = replaceWith; - ++i; - } - return *this; - } - - - //! Replaces all instances of a string with another one. - //! \param toReplace The string to replace. - //! \param replaceWith The string replacing the old one. - //! \return A reference to our current string. - ustring16<TAlloc>& replace(const ustring16<TAlloc>& toReplace, const ustring16<TAlloc>& replaceWith) - { - if (toReplace.size() == 0) - return *this; - - const uchar16_t* other = toReplace.c_str(); - const uchar16_t* replace = replaceWith.c_str(); - const u32 other_size = toReplace.size_raw(); - const u32 replace_size = replaceWith.size_raw(); - - // Determine the delta. The algorithm will change depending on the delta. - s32 delta = replace_size - other_size; - - // A character for character replace. The string will not shrink or grow. - if (delta == 0) - { - s32 pos = 0; - while ((pos = find_raw(other, pos)) != -1) - { - for (u32 i = 0; i < replace_size; ++i) - array[pos + i] = replace[i]; - ++pos; - } - return *this; - } - - // We are going to be removing some characters. The string will shrink. - if (delta < 0) - { - u32 i = 0; - for (u32 pos = 0; pos <= used; ++i, ++pos) - { - // Is this potentially a match? - if (array[pos] == *other) - { - // Check to see if we have a match. - u32 j; - for (j = 0; j < other_size; ++j) - { - if (array[pos + j] != other[j]) - break; - } - - // If we have a match, replace characters. - if (j == other_size) - { - for (j = 0; j < replace_size; ++j) - array[i + j] = replace[j]; - i += replace_size - 1; - pos += other_size - 1; - continue; - } - } - - // No match found, just copy characters. - array[i - 1] = array[pos]; - } - array[i] = 0; - used = i; - - return *this; - } - - // We are going to be adding characters, so the string size will increase. - // Count the number of times toReplace exists in the string so we can allocate the new size. - u32 find_count = 0; - s32 pos = 0; - while ((pos = find_raw(other, pos)) != -1) - { - ++find_count; - ++pos; - } - - // Re-allocate the string now, if needed. - u32 len = delta * find_count; - if (used + len >= allocated) - reallocate(used + len); - - // Start replacing. - pos = 0; - while ((pos = find_raw(other, pos)) != -1) - { - uchar16_t* start = array + pos + other_size - 1; - uchar16_t* ptr = array + used; - uchar16_t* end = array + used + delta; - - // Shift characters to make room for the string. - while (ptr != start) - { - *end = *ptr; - --ptr; - --end; - } - - // Add the new string now. - for (u32 i = 0; i < replace_size; ++i) - array[pos + i] = replace[i]; - - pos += replace_size; - used += delta; - } - - // Terminate the string and return ourself. - array[used] = 0; - return *this; - } - - - //! Removes characters from a ustring16.. - //! \param c The character to remove. - //! \return A reference to our current string. - ustring16<TAlloc>& remove(uchar32_t c) - { - u32 pos = 0; - u32 found = 0; - u32 len = (c > 0xFFFF ? 2 : 1); // Remove characters equal to the size of c as a UTF-16 character. - for (u32 i=0; i<=used; ++i) - { - uchar32_t uc32 = 0; - if (!UTF16_IS_SURROGATE_HI(array[i])) - uc32 |= array[i]; - else if (i + 1 <= used) - { - // Convert the surrogate pair into a single UTF-32 character. - uc32 = unicode::toUTF32(array[i], array[i + 1]); - } - u32 len2 = (uc32 > 0xFFFF ? 2 : 1); - - if (uc32 == c) - { - found += len; - continue; - } - - array[pos++] = array[i]; - if (len2 == 2) - array[pos++] = array[++i]; - } - used -= found; - array[used] = 0; - return *this; - } - - - //! Removes a ustring16 from the ustring16. - //! \param toRemove The string to remove. - //! \return A reference to our current string. - ustring16<TAlloc>& remove(const ustring16<TAlloc>& toRemove) - { - u32 size = toRemove.size_raw(); - if (size == 0) return *this; - - const uchar16_t* tra = toRemove.c_str(); - u32 pos = 0; - u32 found = 0; - for (u32 i=0; i<=used; ++i) - { - u32 j = 0; - while (j < size) - { - if (array[i + j] != tra[j]) - break; - ++j; - } - if (j == size) - { - found += size; - i += size - 1; - continue; - } - - array[pos++] = array[i]; - } - used -= found; - array[used] = 0; - return *this; - } - - - //! Removes characters from the ustring16. - //! \param characters The characters to remove. - //! \return A reference to our current string. - ustring16<TAlloc>& removeChars(const ustring16<TAlloc>& characters) - { - if (characters.size_raw() == 0) - return *this; - - u32 pos = 0; - u32 found = 0; - const_iterator iter(characters); - for (u32 i=0; i<=used; ++i) - { - uchar32_t uc32 = 0; - if (!UTF16_IS_SURROGATE_HI(array[i])) - uc32 |= array[i]; - else if (i + 1 <= used) - { - // Convert the surrogate pair into a single UTF-32 character. - uc32 = unicode::toUTF32(array[i], array[i+1]); - } - u32 len2 = (uc32 > 0xFFFF ? 2 : 1); - - bool cont = false; - iter.toStart(); - while (!iter.atEnd()) - { - uchar32_t c = *iter; - if (uc32 == c) - { - found += (c > 0xFFFF ? 2 : 1); // Remove characters equal to the size of c as a UTF-16 character. - ++i; - cont = true; - break; - } - ++iter; - } - if (cont) continue; - - array[pos++] = array[i]; - if (len2 == 2) - array[pos++] = array[++i]; - } - used -= found; - array[used] = 0; - return *this; - } - - - //! Trims the ustring16. - //! Removes the specified characters (by default, Latin-1 whitespace) from the begining and the end of the ustring16. - //! \param whitespace The characters that are to be considered as whitespace. - //! \return A reference to our current string. - ustring16<TAlloc>& trim(const ustring16<TAlloc>& whitespace = " \t\n\r") - { - core::array<uchar32_t> utf32white = whitespace.toUTF32(); - - // find start and end of the substring without the specified characters - const s32 begin = findFirstCharNotInList(utf32white.const_pointer(), whitespace.used + 1); - if (begin == -1) - return (*this=""); - - const s32 end = findLastCharNotInList(utf32white.const_pointer(), whitespace.used + 1); - - return (*this = subString(begin, (end +1) - begin)); - } - - - //! Erases a character from the ustring16. - //! May be slow, because all elements following after the erased element have to be copied. - //! \param index Index of element to be erased. - //! \return A reference to our current string. - ustring16<TAlloc>& erase(u32 index) - { - _IRR_DEBUG_BREAK_IF(index>used) // access violation - - iterator i(*this, index); - - uchar32_t t = *i; - u32 len = (t > 0xFFFF ? 2 : 1); - - for (u32 j = static_cast<u32>(i.getPos()) + len; j <= used; ++j) - array[j - len] = array[j]; - - used -= len; - array[used] = 0; - - return *this; - } - - - //! Validate the existing ustring16, checking for valid surrogate pairs and checking for proper termination. - //! \return A reference to our current string. - ustring16<TAlloc>& validate() - { - // Validate all unicode characters. - for (u32 i=0; i<allocated; ++i) - { - // Terminate on existing null. - if (array[i] == 0) - { - used = i; - return *this; - } - if (UTF16_IS_SURROGATE(array[i])) - { - if (((i+1) >= allocated) || UTF16_IS_SURROGATE_LO(array[i])) - array[i] = unicode::UTF_REPLACEMENT_CHARACTER; - else if (UTF16_IS_SURROGATE_HI(array[i]) && !UTF16_IS_SURROGATE_LO(array[i+1])) - array[i] = unicode::UTF_REPLACEMENT_CHARACTER; - ++i; - } - if (array[i] >= 0xFDD0 && array[i] <= 0xFDEF) - array[i] = unicode::UTF_REPLACEMENT_CHARACTER; - } - - // terminate - used = 0; - if (allocated > 0) - { - used = allocated - 1; - array[used] = 0; - } - return *this; - } - - - //! Gets the last char of the ustring16, or 0. - //! \return The last char of the ustring16, or 0. - uchar32_t lastChar() const - { - if (used < 1) - return 0; - - if (UTF16_IS_SURROGATE_LO(array[used-1])) - { - // Make sure we have a paired surrogate. - if (used < 2) - return 0; - - // Check for an invalid surrogate. - if (!UTF16_IS_SURROGATE_HI(array[used-2])) - return 0; - - // Convert the surrogate pair into a single UTF-32 character. - return unicode::toUTF32(array[used-2], array[used-1]); - } - else - { - return array[used-1]; - } - } - - - //! Split the ustring16 into parts. - /** This method will split a ustring16 at certain delimiter characters - into the container passed in as reference. The type of the container - has to be given as template parameter. It must provide a push_back and - a size method. - \param ret The result container - \param c C-style ustring16 of delimiter characters - \param count Number of delimiter characters - \param ignoreEmptyTokens Flag to avoid empty substrings in the result - container. If two delimiters occur without a character in between, an - empty substring would be placed in the result. If this flag is set, - only non-empty strings are stored. - \param keepSeparators Flag which allows to add the separator to the - result ustring16. If this flag is true, the concatenation of the - substrings results in the original ustring16. Otherwise, only the - characters between the delimiters are returned. - \return The number of resulting substrings - */ - template<class container> - u32 split(container& ret, const uchar32_t* const c, u32 count=1, bool ignoreEmptyTokens=true, bool keepSeparators=false) const - { - if (!c) - return 0; - - const_iterator i(*this); - const u32 oldSize=ret.size(); - u32 pos = 0; - u32 lastpos = 0; - u32 lastpospos = 0; - bool lastWasSeparator = false; - while (!i.atEnd()) - { - uchar32_t ch = *i; - bool foundSeparator = false; - for (u32 j=0; j<count; ++j) - { - if (ch == c[j]) - { - if ((!ignoreEmptyTokens || pos - lastpos != 0) && - !lastWasSeparator) - ret.push_back(ustring16<TAlloc>(&array[lastpospos], pos - lastpos)); - foundSeparator = true; - lastpos = (keepSeparators ? pos : pos + 1); - lastpospos = (keepSeparators ? i.getPos() : i.getPos() + 1); - break; - } - } - lastWasSeparator = foundSeparator; - ++pos; - ++i; - } - u32 s = size() + 1; - if (s > lastpos) - ret.push_back(ustring16<TAlloc>(&array[lastpospos], s - lastpos)); - return ret.size()-oldSize; - } - - - //! Split the ustring16 into parts. - /** This method will split a ustring16 at certain delimiter characters - into the container passed in as reference. The type of the container - has to be given as template parameter. It must provide a push_back and - a size method. - \param ret The result container - \param c A unicode string of delimiter characters - \param ignoreEmptyTokens Flag to avoid empty substrings in the result - container. If two delimiters occur without a character in between, an - empty substring would be placed in the result. If this flag is set, - only non-empty strings are stored. - \param keepSeparators Flag which allows to add the separator to the - result ustring16. If this flag is true, the concatenation of the - substrings results in the original ustring16. Otherwise, only the - characters between the delimiters are returned. - \return The number of resulting substrings - */ - template<class container> - u32 split(container& ret, const ustring16<TAlloc>& c, bool ignoreEmptyTokens=true, bool keepSeparators=false) const - { - core::array<uchar32_t> v = c.toUTF32(); - return split(ret, v.pointer(), v.size(), ignoreEmptyTokens, keepSeparators); - } - - - //! Gets the size of the allocated memory buffer for the string. - //! \return The size of the allocated memory buffer. - u32 capacity() const - { - return allocated; - } - - - //! Returns the raw number of UTF-16 code points in the string which includes the individual surrogates. - //! \return The raw number of UTF-16 code points, excluding the trialing NUL. - u32 size_raw() const - { - return used; - } - - - //! Inserts a character into the string. - //! \param c The character to insert. - //! \param pos The position to insert the character. - //! \return A reference to our current string. - ustring16<TAlloc>& insert(uchar32_t c, u32 pos) - { - u8 len = (c > 0xFFFF ? 2 : 1); - - if (used + len >= allocated) - reallocate(used + len); - - used += len; - - iterator iter(*this, pos); - for (u32 i = used - 2; i > iter.getPos(); --i) - array[i] = array[i - len]; - - if (c > 0xFFFF) - { - // c will be multibyte, so split it up into a surrogate pair. - uchar16_t x = static_cast<uchar16_t>(c); - uchar16_t vh = UTF16_HI_SURROGATE | ((((c >> 16) & ((1 << 5) - 1)) - 1) << 6) | (x >> 10); - uchar16_t vl = UTF16_LO_SURROGATE | (x & ((1 << 10) - 1)); - array[iter.getPos()] = vh; - array[iter.getPos()+1] = vl; - } - else - { - array[iter.getPos()] = static_cast<uchar16_t>(c); - } - array[used] = 0; - return *this; - } - - - //! Inserts a string into the string. - //! \param c The string to insert. - //! \param pos The position to insert the string. - //! \return A reference to our current string. - ustring16<TAlloc>& insert(const ustring16<TAlloc>& c, u32 pos) - { - u32 len = c.size_raw(); - if (len == 0) return *this; - - if (used + len >= allocated) - reallocate(used + len); - - used += len; - - iterator iter(*this, pos); - for (u32 i = used - 2; i > iter.getPos() + len; --i) - array[i] = array[i - len]; - - const uchar16_t* s = c.c_str(); - for (u32 i = 0; i < len; ++i) - { - array[pos++] = *s; - ++s; - } - - array[used] = 0; - return *this; - } - - - //! Inserts a character into the string. - //! \param c The character to insert. - //! \param pos The position to insert the character. - //! \return A reference to our current string. - ustring16<TAlloc>& insert_raw(uchar16_t c, u32 pos) - { - if (used + 1 >= allocated) - reallocate(used + 1); - - ++used; - - for (u32 i = used - 1; i > pos; --i) - array[i] = array[i - 1]; - - array[pos] = c; - array[used] = 0; - return *this; - } - - - //! Removes a character from string. - //! \param pos Position of the character to remove. - //! \return A reference to our current string. - ustring16<TAlloc>& erase_raw(u32 pos) - { - for (u32 i=pos; i<=used; ++i) - { - array[i] = array[i + 1]; - } - --used; - array[used] = 0; - return *this; - } - - - //! Replaces a character in the string. - //! \param c The new character. - //! \param pos The position of the character to replace. - //! \return A reference to our current string. - ustring16<TAlloc>& replace_raw(uchar16_t c, u32 pos) - { - array[pos] = c; - return *this; - } - - - //! Returns an iterator to the beginning of the string. - //! \return An iterator to the beginning of the string. - iterator begin() - { - iterator i(*this, 0); - return i; - } - - - //! Returns an iterator to the beginning of the string. - //! \return An iterator to the beginning of the string. - const_iterator begin() const - { - const_iterator i(*this, 0); - return i; - } - - - //! Returns an iterator to the beginning of the string. - //! \return An iterator to the beginning of the string. - const_iterator cbegin() const - { - const_iterator i(*this, 0); - return i; - } - - - //! Returns an iterator to the end of the string. - //! \return An iterator to the end of the string. - iterator end() - { - iterator i(*this, 0); - i.toEnd(); - return i; - } - - - //! Returns an iterator to the end of the string. - //! \return An iterator to the end of the string. - const_iterator end() const - { - const_iterator i(*this, 0); - i.toEnd(); - return i; - } - - - //! Returns an iterator to the end of the string. - //! \return An iterator to the end of the string. - const_iterator cend() const - { - const_iterator i(*this, 0); - i.toEnd(); - return i; - } - - - //! Converts the string to a UTF-8 encoded string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. - //! \return A string containing the UTF-8 encoded string. - core::string<uchar8_t> toUTF8_s(const bool addBOM = false) const - { - core::string<uchar8_t> ret; - ret.reserve(used * 4 + (addBOM ? unicode::BOM_UTF8_LEN : 0) + 1); - const_iterator iter(*this, 0); - - // Add the byte order mark if the user wants it. - if (addBOM) - { - ret.append(unicode::BOM_ENCODE_UTF8[0]); - ret.append(unicode::BOM_ENCODE_UTF8[1]); - ret.append(unicode::BOM_ENCODE_UTF8[2]); - } - - while (!iter.atEnd()) - { - uchar32_t c = *iter; - if (c > 0xFFFF) - { // 4 bytes - uchar8_t b1 = (0x1E << 3) | ((c >> 18) & 0x7); - uchar8_t b2 = (0x2 << 6) | ((c >> 12) & 0x3F); - uchar8_t b3 = (0x2 << 6) | ((c >> 6) & 0x3F); - uchar8_t b4 = (0x2 << 6) | (c & 0x3F); - ret.append(b1); - ret.append(b2); - ret.append(b3); - ret.append(b4); - } - else if (c > 0x7FF) - { // 3 bytes - uchar8_t b1 = (0xE << 4) | ((c >> 12) & 0xF); - uchar8_t b2 = (0x2 << 6) | ((c >> 6) & 0x3F); - uchar8_t b3 = (0x2 << 6) | (c & 0x3F); - ret.append(b1); - ret.append(b2); - ret.append(b3); - } - else if (c > 0x7F) - { // 2 bytes - uchar8_t b1 = (0x6 << 5) | ((c >> 6) & 0x1F); - uchar8_t b2 = (0x2 << 6) | (c & 0x3F); - ret.append(b1); - ret.append(b2); - } - else - { // 1 byte - ret.append(static_cast<uchar8_t>(c)); - } - ++iter; - } - return ret; - } - - - //! Converts the string to a UTF-8 encoded string array. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. - //! \return An array containing the UTF-8 encoded string. - core::array<uchar8_t> toUTF8(const bool addBOM = false) const - { - core::array<uchar8_t> ret(used * 4 + (addBOM ? unicode::BOM_UTF8_LEN : 0) + 1); - const_iterator iter(*this, 0); - - // Add the byte order mark if the user wants it. - if (addBOM) - { - ret.push_back(unicode::BOM_ENCODE_UTF8[0]); - ret.push_back(unicode::BOM_ENCODE_UTF8[1]); - ret.push_back(unicode::BOM_ENCODE_UTF8[2]); - } - - while (!iter.atEnd()) - { - uchar32_t c = *iter; - if (c > 0xFFFF) - { // 4 bytes - uchar8_t b1 = (0x1E << 3) | ((c >> 18) & 0x7); - uchar8_t b2 = (0x2 << 6) | ((c >> 12) & 0x3F); - uchar8_t b3 = (0x2 << 6) | ((c >> 6) & 0x3F); - uchar8_t b4 = (0x2 << 6) | (c & 0x3F); - ret.push_back(b1); - ret.push_back(b2); - ret.push_back(b3); - ret.push_back(b4); - } - else if (c > 0x7FF) - { // 3 bytes - uchar8_t b1 = (0xE << 4) | ((c >> 12) & 0xF); - uchar8_t b2 = (0x2 << 6) | ((c >> 6) & 0x3F); - uchar8_t b3 = (0x2 << 6) | (c & 0x3F); - ret.push_back(b1); - ret.push_back(b2); - ret.push_back(b3); - } - else if (c > 0x7F) - { // 2 bytes - uchar8_t b1 = (0x6 << 5) | ((c >> 6) & 0x1F); - uchar8_t b2 = (0x2 << 6) | (c & 0x3F); - ret.push_back(b1); - ret.push_back(b2); - } - else - { // 1 byte - ret.push_back(static_cast<uchar8_t>(c)); - } - ++iter; - } - ret.push_back(0); - return ret; - } - - -#ifdef USTRING_CPP0X_NEWLITERALS // C++0x - //! Converts the string to a UTF-16 encoded string. - //! \param endian The desired endianness of the string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. - //! \return A string containing the UTF-16 encoded string. - core::string<char16_t> toUTF16_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const - { - core::string<char16_t> ret; - ret.reserve(used + (addBOM ? unicode::BOM_UTF16_LEN : 0) + 1); - - // Add the BOM if specified. - if (addBOM) - { - if (endian == unicode::EUTFEE_NATIVE) - ret[0] = unicode::BOM; - else if (endian == unicode::EUTFEE_LITTLE) - { - uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(&ret[0]); - *ptr8++ = unicode::BOM_ENCODE_UTF16_LE[0]; - *ptr8 = unicode::BOM_ENCODE_UTF16_LE[1]; - } - else - { - uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(&ret[0]); - *ptr8++ = unicode::BOM_ENCODE_UTF16_BE[0]; - *ptr8 = unicode::BOM_ENCODE_UTF16_BE[1]; - } - } - - ret.append(array); - if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) - { - char16_t* ptr = ret.c_str(); - for (u32 i = 0; i < ret.size(); ++i) - *ptr++ = unicode::swapEndian16(*ptr); - } - return ret; - } -#endif - - - //! Converts the string to a UTF-16 encoded string array. - //! Unfortunately, no toUTF16_s() version exists due to limitations with Irrlicht's string class. - //! \param endian The desired endianness of the string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. - //! \return An array containing the UTF-16 encoded string. - core::array<uchar16_t> toUTF16(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const - { - core::array<uchar16_t> ret(used + (addBOM ? unicode::BOM_UTF16_LEN : 0) + 1); - uchar16_t* ptr = ret.pointer(); - - // Add the BOM if specified. - if (addBOM) - { - if (endian == unicode::EUTFEE_NATIVE) - *ptr = unicode::BOM; - else if (endian == unicode::EUTFEE_LITTLE) - { - uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ptr); - *ptr8++ = unicode::BOM_ENCODE_UTF16_LE[0]; - *ptr8 = unicode::BOM_ENCODE_UTF16_LE[1]; - } - else - { - uchar8_t* ptr8 = reinterpret_cast<uchar8_t*>(ptr); - *ptr8++ = unicode::BOM_ENCODE_UTF16_BE[0]; - *ptr8 = unicode::BOM_ENCODE_UTF16_BE[1]; - } - ++ptr; - } - - memcpy((void*)ptr, (void*)array, used * sizeof(uchar16_t)); - if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) - { - for (u32 i = 0; i <= used; ++i) - ptr[i] = unicode::swapEndian16(ptr[i]); - } - ret.set_used(used + (addBOM ? unicode::BOM_UTF16_LEN : 0)); - ret.push_back(0); - return ret; - } - - -#ifdef USTRING_CPP0X_NEWLITERALS // C++0x - //! Converts the string to a UTF-32 encoded string. - //! \param endian The desired endianness of the string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. - //! \return A string containing the UTF-32 encoded string. - core::string<char32_t> toUTF32_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const - { - core::string<char32_t> ret; - ret.reserve(size() + 1 + (addBOM ? unicode::BOM_UTF32_LEN : 0)); - const_iterator iter(*this, 0); - - // Add the BOM if specified. - if (addBOM) - { - if (endian == unicode::EUTFEE_NATIVE) - ret.append(unicode::BOM); - else - { - union - { - uchar32_t full; - u8 chunk[4]; - } t; - - if (endian == unicode::EUTFEE_LITTLE) - { - t.chunk[0] = unicode::BOM_ENCODE_UTF32_LE[0]; - t.chunk[1] = unicode::BOM_ENCODE_UTF32_LE[1]; - t.chunk[2] = unicode::BOM_ENCODE_UTF32_LE[2]; - t.chunk[3] = unicode::BOM_ENCODE_UTF32_LE[3]; - } - else - { - t.chunk[0] = unicode::BOM_ENCODE_UTF32_BE[0]; - t.chunk[1] = unicode::BOM_ENCODE_UTF32_BE[1]; - t.chunk[2] = unicode::BOM_ENCODE_UTF32_BE[2]; - t.chunk[3] = unicode::BOM_ENCODE_UTF32_BE[3]; - } - ret.append(t.full); - } - } - - while (!iter.atEnd()) - { - uchar32_t c = *iter; - if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) - c = unicode::swapEndian32(c); - ret.append(c); - ++iter; - } - return ret; - } -#endif - - - //! Converts the string to a UTF-32 encoded string array. - //! Unfortunately, no toUTF32_s() version exists due to limitations with Irrlicht's string class. - //! \param endian The desired endianness of the string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. - //! \return An array containing the UTF-32 encoded string. - core::array<uchar32_t> toUTF32(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const - { - core::array<uchar32_t> ret(size() + (addBOM ? unicode::BOM_UTF32_LEN : 0) + 1); - const_iterator iter(*this, 0); - - // Add the BOM if specified. - if (addBOM) - { - if (endian == unicode::EUTFEE_NATIVE) - ret.push_back(unicode::BOM); - else - { - union - { - uchar32_t full; - u8 chunk[4]; - } t; - - if (endian == unicode::EUTFEE_LITTLE) - { - t.chunk[0] = unicode::BOM_ENCODE_UTF32_LE[0]; - t.chunk[1] = unicode::BOM_ENCODE_UTF32_LE[1]; - t.chunk[2] = unicode::BOM_ENCODE_UTF32_LE[2]; - t.chunk[3] = unicode::BOM_ENCODE_UTF32_LE[3]; - } - else - { - t.chunk[0] = unicode::BOM_ENCODE_UTF32_BE[0]; - t.chunk[1] = unicode::BOM_ENCODE_UTF32_BE[1]; - t.chunk[2] = unicode::BOM_ENCODE_UTF32_BE[2]; - t.chunk[3] = unicode::BOM_ENCODE_UTF32_BE[3]; - } - ret.push_back(t.full); - } - } - ret.push_back(0); - - while (!iter.atEnd()) - { - uchar32_t c = *iter; - if (endian != unicode::EUTFEE_NATIVE && getEndianness() != endian) - c = unicode::swapEndian32(c); - ret.push_back(c); - ++iter; - } - return ret; - } - - - //! Converts the string to a wchar_t encoded string. - /** The size of a wchar_t changes depending on the platform. This function will store a - correct UTF-8, -16, or -32 encoded string depending on the size of a wchar_t. **/ - //! \param endian The desired endianness of the string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. - //! \return A string containing the wchar_t encoded string. - core::string<wchar_t> toWCHAR_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const - { - if (sizeof(wchar_t) == 4) - { - core::array<uchar32_t> a(toUTF32(endian, addBOM)); - core::stringw ret(a.pointer()); - return ret; - } - else if (sizeof(wchar_t) == 2) - { - if (endian == unicode::EUTFEE_NATIVE && addBOM == false) - { - core::stringw ret(array); - return ret; - } - else - { - core::array<uchar16_t> a(toUTF16(endian, addBOM)); - core::stringw ret(a.pointer()); - return ret; - } - } - else if (sizeof(wchar_t) == 1) - { - core::array<uchar8_t> a(toUTF8(addBOM)); - core::stringw ret(a.pointer()); - return ret; - } - - // Shouldn't happen. - return core::stringw(); - } - - - //! Converts the string to a wchar_t encoded string array. - /** The size of a wchar_t changes depending on the platform. This function will store a - correct UTF-8, -16, or -32 encoded string depending on the size of a wchar_t. **/ - //! \param endian The desired endianness of the string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. - //! \return An array containing the wchar_t encoded string. - core::array<wchar_t> toWCHAR(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const - { - if (sizeof(wchar_t) == 4) - { - core::array<uchar32_t> a(toUTF32(endian, addBOM)); - core::array<wchar_t> ret(a.size()); - ret.set_used(a.size()); - memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar32_t)); - return ret; - } - if (sizeof(wchar_t) == 2) - { - if (endian == unicode::EUTFEE_NATIVE && addBOM == false) - { - core::array<wchar_t> ret(used); - ret.set_used(used); - memcpy((void*)ret.pointer(), (void*)array, used * sizeof(uchar16_t)); - return ret; - } - else - { - core::array<uchar16_t> a(toUTF16(endian, addBOM)); - core::array<wchar_t> ret(a.size()); - ret.set_used(a.size()); - memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar16_t)); - return ret; - } - } - if (sizeof(wchar_t) == 1) - { - core::array<uchar8_t> a(toUTF8(addBOM)); - core::array<wchar_t> ret(a.size()); - ret.set_used(a.size()); - memcpy((void*)ret.pointer(), (void*)a.pointer(), a.size() * sizeof(uchar8_t)); - return ret; - } - - // Shouldn't happen. - return core::array<wchar_t>(); - } - - //! Converts the string to a properly encoded io::path string. - //! \param endian The desired endianness of the string. - //! \param addBOM If true, the proper unicode byte-order mark will be prefixed to the string. - //! \return An io::path string containing the properly encoded string. - io::path toPATH_s(const unicode::EUTF_ENDIAN endian = unicode::EUTFEE_NATIVE, const bool addBOM = false) const - { -#if defined(_IRR_WCHAR_FILESYSTEM) - return toWCHAR_s(endian, addBOM); -#else - return toUTF8_s(addBOM); -#endif - } - - //! Loads an unknown stream of data. - //! Will attempt to determine if the stream is unicode data. Useful for loading from files. - //! \param data The data stream to load from. - //! \param data_size The length of the data string. - //! \return A reference to our current string. - ustring16<TAlloc>& loadDataStream(const char* data, size_t data_size) - { - // Clear our string. - *this = ""; - if (!data) - return *this; - - unicode::EUTF_ENCODE e = unicode::determineUnicodeBOM(data); - switch (e) - { - default: - case unicode::EUTFE_UTF8: - append((uchar8_t*)data, data_size); - break; - - case unicode::EUTFE_UTF16: - case unicode::EUTFE_UTF16_BE: - case unicode::EUTFE_UTF16_LE: - append((uchar16_t*)data, data_size / 2); - break; - - case unicode::EUTFE_UTF32: - case unicode::EUTFE_UTF32_BE: - case unicode::EUTFE_UTF32_LE: - append((uchar32_t*)data, data_size / 4); - break; - } - - return *this; - } - - //! Gets the encoding of the Unicode string this class contains. - //! \return An enum describing the current encoding of this string. - const unicode::EUTF_ENCODE getEncoding() const - { - return encoding; - } - - //! Gets the endianness of the Unicode string this class contains. - //! \return An enum describing the endianness of this string. - const unicode::EUTF_ENDIAN getEndianness() const - { - if (encoding == unicode::EUTFE_UTF16_LE || - encoding == unicode::EUTFE_UTF32_LE) - return unicode::EUTFEE_LITTLE; - else return unicode::EUTFEE_BIG; - } - -private: - - //! Reallocate the string, making it bigger or smaller. - //! \param new_size The new size of the string. - void reallocate(u32 new_size) - { - uchar16_t* old_array = array; - - array = allocator.allocate(new_size + 1); //new u16[new_size]; - allocated = new_size + 1; - if (old_array == 0) return; - - u32 amount = used < new_size ? used : new_size; - for (u32 i=0; i<=amount; ++i) - array[i] = old_array[i]; - - if (allocated <= used) - used = allocated - 1; - - array[used] = 0; - - allocator.deallocate(old_array); // delete [] old_array; - } - - //--- member variables - - uchar16_t* array; - unicode::EUTF_ENCODE encoding; - u32 allocated; - u32 used; - TAlloc allocator; - //irrAllocator<uchar16_t> allocator; -}; - -typedef ustring16<irrAllocator<uchar16_t> > ustring; - - -//! Appends two ustring16s. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const ustring16<TAlloc>& right) -{ - ustring16<TAlloc> ret(left); - ret += right; - return ret; -} - - -//! Appends a ustring16 and a null-terminated unicode string. -template <typename TAlloc, class B> -inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const B* const right) -{ - ustring16<TAlloc> ret(left); - ret += right; - return ret; -} - - -//! Appends a ustring16 and a null-terminated unicode string. -template <class B, typename TAlloc> -inline ustring16<TAlloc> operator+(const B* const left, const ustring16<TAlloc>& right) -{ - ustring16<TAlloc> ret(left); - ret += right; - return ret; -} - - -//! Appends a ustring16 and an Irrlicht string. -template <typename TAlloc, typename B, typename BAlloc> -inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const string<B, BAlloc>& right) -{ - ustring16<TAlloc> ret(left); - ret += right; - return ret; -} - - -//! Appends a ustring16 and an Irrlicht string. -template <typename TAlloc, typename B, typename BAlloc> -inline ustring16<TAlloc> operator+(const string<B, BAlloc>& left, const ustring16<TAlloc>& right) -{ - ustring16<TAlloc> ret(left); - ret += right; - return ret; -} - - -//! Appends a ustring16 and a std::basic_string. -template <typename TAlloc, typename B, typename A, typename BAlloc> -inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const std::basic_string<B, A, BAlloc>& right) -{ - ustring16<TAlloc> ret(left); - ret += right; - return ret; -} - - -//! Appends a ustring16 and a std::basic_string. -template <typename TAlloc, typename B, typename A, typename BAlloc> -inline ustring16<TAlloc> operator+(const std::basic_string<B, A, BAlloc>& left, const ustring16<TAlloc>& right) -{ - ustring16<TAlloc> ret(left); - ret += right; - return ret; -} - - -//! Appends a ustring16 and a char. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const char right) -{ - ustring16<TAlloc> ret(left); - ret += right; - return ret; -} - - -//! Appends a ustring16 and a char. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const char left, const ustring16<TAlloc>& right) -{ - ustring16<TAlloc> ret(left); - ret += right; - return ret; -} - - -#ifdef USTRING_CPP0X_NEWLITERALS -//! Appends a ustring16 and a uchar32_t. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const uchar32_t right) -{ - ustring16<TAlloc> ret(left); - ret += right; - return ret; -} - - -//! Appends a ustring16 and a uchar32_t. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const uchar32_t left, const ustring16<TAlloc>& right) -{ - ustring16<TAlloc> ret(left); - ret += right; - return ret; -} -#endif - - -//! Appends a ustring16 and a short. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const short right) -{ - ustring16<TAlloc> ret(left); - ret += core::stringc(right); - return ret; -} - - -//! Appends a ustring16 and a short. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const short left, const ustring16<TAlloc>& right) -{ - ustring16<TAlloc> ret((core::stringc(left))); - ret += right; - return ret; -} - - -//! Appends a ustring16 and an unsigned short. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned short right) -{ - ustring16<TAlloc> ret(left); - ret += core::stringc(right); - return ret; -} - - -//! Appends a ustring16 and an unsigned short. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const unsigned short left, const ustring16<TAlloc>& right) -{ - ustring16<TAlloc> ret((core::stringc(left))); - ret += right; - return ret; -} - - -//! Appends a ustring16 and an int. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const int right) -{ - ustring16<TAlloc> ret(left); - ret += core::stringc(right); - return ret; -} - - -//! Appends a ustring16 and an int. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const int left, const ustring16<TAlloc>& right) -{ - ustring16<TAlloc> ret((core::stringc(left))); - ret += right; - return ret; -} - - -//! Appends a ustring16 and an unsigned int. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned int right) -{ - ustring16<TAlloc> ret(left); - ret += core::stringc(right); - return ret; -} - - -//! Appends a ustring16 and an unsigned int. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const unsigned int left, const ustring16<TAlloc>& right) -{ - ustring16<TAlloc> ret((core::stringc(left))); - ret += right; - return ret; -} - - -//! Appends a ustring16 and a long. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const long right) -{ - ustring16<TAlloc> ret(left); - ret += core::stringc(right); - return ret; -} - - -//! Appends a ustring16 and a long. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const long left, const ustring16<TAlloc>& right) -{ - ustring16<TAlloc> ret((core::stringc(left))); - ret += right; - return ret; -} - - -//! Appends a ustring16 and an unsigned long. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const unsigned long right) -{ - ustring16<TAlloc> ret(left); - ret += core::stringc(right); - return ret; -} - - -//! Appends a ustring16 and an unsigned long. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const unsigned long left, const ustring16<TAlloc>& right) -{ - ustring16<TAlloc> ret((core::stringc(left))); - ret += right; - return ret; -} - - -//! Appends a ustring16 and a float. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const float right) -{ - ustring16<TAlloc> ret(left); - ret += core::stringc(right); - return ret; -} - - -//! Appends a ustring16 and a float. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const float left, const ustring16<TAlloc>& right) -{ - ustring16<TAlloc> ret((core::stringc(left))); - ret += right; - return ret; -} - - -//! Appends a ustring16 and a double. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const ustring16<TAlloc>& left, const double right) -{ - ustring16<TAlloc> ret(left); - ret += core::stringc(right); - return ret; -} - - -//! Appends a ustring16 and a double. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const double left, const ustring16<TAlloc>& right) -{ - ustring16<TAlloc> ret((core::stringc(left))); - ret += right; - return ret; -} - - -#ifdef USTRING_CPP0X -//! Appends two ustring16s. -template <typename TAlloc> -inline ustring16<TAlloc>&& operator+(const ustring16<TAlloc>& left, ustring16<TAlloc>&& right) -{ - //std::cout << "MOVE operator+(&, &&)" << std::endl; - right.insert(left, 0); - return std::move(right); -} - - -//! Appends two ustring16s. -template <typename TAlloc> -inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const ustring16<TAlloc>& right) -{ - //std::cout << "MOVE operator+(&&, &)" << std::endl; - left.append(right); - return std::move(left); -} - - -//! Appends two ustring16s. -template <typename TAlloc> -inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, ustring16<TAlloc>&& right) -{ - //std::cout << "MOVE operator+(&&, &&)" << std::endl; - if ((right.size_raw() <= left.capacity() - left.size_raw()) || - (right.capacity() - right.size_raw() < left.size_raw())) - { - left.append(right); - return std::move(left); - } - else - { - right.insert(left, 0); - return std::move(right); - } -} - - -//! Appends a ustring16 and a null-terminated unicode string. -template <typename TAlloc, class B> -inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const B* const right) -{ - //std::cout << "MOVE operator+(&&, B*)" << std::endl; - left.append(right); - return std::move(left); -} - - -//! Appends a ustring16 and a null-terminated unicode string. -template <class B, typename TAlloc> -inline ustring16<TAlloc>&& operator+(const B* const left, ustring16<TAlloc>&& right) -{ - //std::cout << "MOVE operator+(B*, &&)" << std::endl; - right.insert(left, 0); - return std::move(right); -} - - -//! Appends a ustring16 and an Irrlicht string. -template <typename TAlloc, typename B, typename BAlloc> -inline ustring16<TAlloc>&& operator+(const string<B, BAlloc>& left, ustring16<TAlloc>&& right) -{ - //std::cout << "MOVE operator+(&, &&)" << std::endl; - right.insert(left, 0); - return std::move(right); -} - - -//! Appends a ustring16 and an Irrlicht string. -template <typename TAlloc, typename B, typename BAlloc> -inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const string<B, BAlloc>& right) -{ - //std::cout << "MOVE operator+(&&, &)" << std::endl; - left.append(right); - return std::move(left); -} - - -//! Appends a ustring16 and a std::basic_string. -template <typename TAlloc, typename B, typename A, typename BAlloc> -inline ustring16<TAlloc>&& operator+(const std::basic_string<B, A, BAlloc>& left, ustring16<TAlloc>&& right) -{ - //std::cout << "MOVE operator+(&, &&)" << std::endl; - right.insert(core::ustring16<TAlloc>(left), 0); - return std::move(right); -} - - -//! Appends a ustring16 and a std::basic_string. -template <typename TAlloc, typename B, typename A, typename BAlloc> -inline ustring16<TAlloc>&& operator+(ustring16<TAlloc>&& left, const std::basic_string<B, A, BAlloc>& right) -{ - //std::cout << "MOVE operator+(&&, &)" << std::endl; - left.append(right); - return std::move(left); -} - - -//! Appends a ustring16 and a char. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const char right) -{ - left.append((uchar32_t)right); - return std::move(left); -} - - -//! Appends a ustring16 and a char. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const char left, ustring16<TAlloc>&& right) -{ - right.insert((uchar32_t)left, 0); - return std::move(right); -} - - -#ifdef USTRING_CPP0X_NEWLITERALS -//! Appends a ustring16 and a uchar32_t. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const uchar32_t right) -{ - left.append(right); - return std::move(left); -} - - -//! Appends a ustring16 and a uchar32_t. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const uchar32_t left, ustring16<TAlloc>&& right) -{ - right.insert(left, 0); - return std::move(right); -} -#endif - - -//! Appends a ustring16 and a short. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const short right) -{ - left.append(core::stringc(right)); - return std::move(left); -} - - -//! Appends a ustring16 and a short. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const short left, ustring16<TAlloc>&& right) -{ - right.insert(core::stringc(left), 0); - return std::move(right); -} - - -//! Appends a ustring16 and an unsigned short. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const unsigned short right) -{ - left.append(core::stringc(right)); - return std::move(left); -} - - -//! Appends a ustring16 and an unsigned short. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const unsigned short left, ustring16<TAlloc>&& right) -{ - right.insert(core::stringc(left), 0); - return std::move(right); -} - - -//! Appends a ustring16 and an int. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const int right) -{ - left.append(core::stringc(right)); - return std::move(left); -} - - -//! Appends a ustring16 and an int. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const int left, ustring16<TAlloc>&& right) -{ - right.insert(core::stringc(left), 0); - return std::move(right); -} - - -//! Appends a ustring16 and an unsigned int. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const unsigned int right) -{ - left.append(core::stringc(right)); - return std::move(left); -} - - -//! Appends a ustring16 and an unsigned int. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const unsigned int left, ustring16<TAlloc>&& right) -{ - right.insert(core::stringc(left), 0); - return std::move(right); -} - - -//! Appends a ustring16 and a long. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const long right) -{ - left.append(core::stringc(right)); - return std::move(left); -} - - -//! Appends a ustring16 and a long. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const long left, ustring16<TAlloc>&& right) -{ - right.insert(core::stringc(left), 0); - return std::move(right); -} - - -//! Appends a ustring16 and an unsigned long. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const unsigned long right) -{ - left.append(core::stringc(right)); - return std::move(left); -} - - -//! Appends a ustring16 and an unsigned long. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const unsigned long left, ustring16<TAlloc>&& right) -{ - right.insert(core::stringc(left), 0); - return std::move(right); -} - - -//! Appends a ustring16 and a float. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const float right) -{ - left.append(core::stringc(right)); - return std::move(left); -} - - -//! Appends a ustring16 and a float. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const float left, ustring16<TAlloc>&& right) -{ - right.insert(core::stringc(left), 0); - return std::move(right); -} - - -//! Appends a ustring16 and a double. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(ustring16<TAlloc>&& left, const double right) -{ - left.append(core::stringc(right)); - return std::move(left); -} - - -//! Appends a ustring16 and a double. -template <typename TAlloc> -inline ustring16<TAlloc> operator+(const double left, ustring16<TAlloc>&& right) -{ - right.insert(core::stringc(left), 0); - return std::move(right); -} -#endif - - -#ifndef USTRING_NO_STL -//! Writes a ustring16 to an ostream. -template <typename TAlloc> -inline std::ostream& operator<<(std::ostream& out, const ustring16<TAlloc>& in) -{ - out << in.toUTF8_s().c_str(); - return out; -} - -//! Writes a ustring16 to a wostream. -template <typename TAlloc> -inline std::wostream& operator<<(std::wostream& out, const ustring16<TAlloc>& in) -{ - out << in.toWCHAR_s().c_str(); - return out; -} -#endif - - -#ifndef USTRING_NO_STL - -namespace unicode -{ - -//! Hashing algorithm for hashing a ustring. Used for things like unordered_maps. -//! Algorithm taken from std::hash<std::string>. -class hash : public std::unary_function<core::ustring, size_t> -{ - public: - size_t operator()(const core::ustring& s) const - { - size_t ret = 2166136261U; - size_t index = 0; - size_t stride = 1 + s.size_raw() / 10; - - core::ustring::const_iterator i = s.begin(); - while (i != s.end()) - { - // TODO: Don't force u32 on an x64 OS. Make it agnostic. - ret = 16777619U * ret ^ (size_t)s[(u32)index]; - index += stride; - i += stride; - } - return (ret); - } -}; - -} // end namespace unicode - -#endif - -} // end namespace core -} // end namespace irr diff --git a/src/irrlicht_changes/static_text.cpp b/src/irrlicht_changes/static_text.cpp index bf61cd64e..8908a91f7 100644 --- a/src/irrlicht_changes/static_text.cpp +++ b/src/irrlicht_changes/static_text.cpp @@ -108,16 +108,11 @@ void StaticText::draw() font->getDimension(str.c_str()).Width; } - //str = colorizeText(BrokenText[i].c_str(), colors, previous_color); - //if (!colors.empty()) - // previous_color = colors[colors.size() - 1]; - #if USE_FREETYPE if (font->getType() == irr::gui::EGFT_CUSTOM) { irr::gui::CGUITTFont *tmp = static_cast<irr::gui::CGUITTFont*>(font); tmp->draw(str, - r, previous_color, // FIXME - HAlign == EGUIA_CENTER, VAlign == EGUIA_CENTER, + r, HAlign == EGUIA_CENTER, VAlign == EGUIA_CENTER, (RestrainTextInside ? &AbsoluteClippingRect : NULL)); } else #endif @@ -246,15 +241,17 @@ void StaticText::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vert } -#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7 -const video::SColor& StaticText::getOverrideColor() const -#else video::SColor StaticText::getOverrideColor() const -#endif { return ColoredText.getDefaultColor(); } +#if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8 +video::SColor StaticText::getActiveColor() const +{ + return getOverrideColor(); +} +#endif //! Sets if the static text should use the overide color or the //! color in the gui skin. diff --git a/src/irrlicht_changes/static_text.h b/src/irrlicht_changes/static_text.h index 1f111ea56..83bbf4c3d 100644 --- a/src/irrlicht_changes/static_text.h +++ b/src/irrlicht_changes/static_text.h @@ -134,10 +134,11 @@ namespace gui virtual void setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical); //! Gets the override color - #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR <= 7 - virtual const video::SColor& getOverrideColor() const; - #else virtual video::SColor getOverrideColor() const; + + #if IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR > 8 + //! Gets the currently used text color + virtual video::SColor getActiveColor() const; #endif //! Sets if the static text should use the overide color or the diff --git a/src/irrlichttypes.h b/src/irrlichttypes.h index 794776b26..93c2d105b 100644 --- a/src/irrlichttypes.h +++ b/src/irrlichttypes.h @@ -19,16 +19,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once -/* Ensure that <stdint.h> is included before <irrTypes.h>, unless building on - * MSVC, to address an irrlicht issue: https://sourceforge.net/p/irrlicht/bugs/433/ - * - * TODO: Decide whether or not we support non-compliant C++ compilers like old - * versions of MSCV. If we do not then <stdint.h> can always be included - * regardless of the compiler. +/* + * IrrlichtMt already includes stdint.h in irrTypes.h. This works everywhere + * we need it to (including recent MSVC), so should be fine here too. */ -#ifndef _MSC_VER -# include <cstdint> -#endif +#include <cstdint> #include <irrTypes.h> @@ -36,19 +31,6 @@ using namespace irr; namespace irr { -// Irrlicht 1.8+ defines 64bit unsigned symbol in irrTypes.h -#if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR < 8) -#ifdef _MSC_VER - // Windows - typedef long long s64; - typedef unsigned long long u64; -#else - // Posix - typedef int64_t s64; - typedef uint64_t u64; -#endif -#endif - #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 9) namespace core { template <typename T> diff --git a/src/itemdef.cpp b/src/itemdef.cpp index 5fb1e4c47..d79d6b263 100644 --- a/src/itemdef.cpp +++ b/src/itemdef.cpp @@ -71,13 +71,11 @@ ItemDefinition& ItemDefinition::operator=(const ItemDefinition &def) stack_max = def.stack_max; usable = def.usable; liquids_pointable = def.liquids_pointable; - if(def.tool_capabilities) - { - tool_capabilities = new ToolCapabilities( - *def.tool_capabilities); - } + if (def.tool_capabilities) + tool_capabilities = new ToolCapabilities(*def.tool_capabilities); groups = def.groups; node_placement_prediction = def.node_placement_prediction; + place_param2 = def.place_param2; sound_place = def.sound_place; sound_place_failed = def.sound_place_failed; range = def.range; @@ -120,8 +118,8 @@ void ItemDefinition::reset() sound_place = SimpleSoundSpec(); sound_place_failed = SimpleSoundSpec(); range = -1; - node_placement_prediction = ""; + place_param2 = 0; } void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const @@ -166,6 +164,8 @@ void ItemDefinition::serialize(std::ostream &os, u16 protocol_version) const os << serializeString16(wield_overlay); os << serializeString16(short_description); + + os << place_param2; } void ItemDefinition::deSerialize(std::istream &is) @@ -219,6 +219,8 @@ void ItemDefinition::deSerialize(std::istream &is) // block to not need to increase the version. try { short_description = deSerializeString16(is); + + place_param2 = readU8(is); // 0 if missing } catch(SerializationError &e) {}; } diff --git a/src/itemdef.h b/src/itemdef.h index ebf0d3527..3e302840f 100644 --- a/src/itemdef.h +++ b/src/itemdef.h @@ -86,6 +86,7 @@ struct ItemDefinition // Server will update the precise end result a moment later. // "" = no prediction std::string node_placement_prediction; + u8 place_param2; /* Some helpful methods diff --git a/src/itemstackmetadata.cpp b/src/itemstackmetadata.cpp index 4aa1a0903..7a26fbb0e 100644 --- a/src/itemstackmetadata.cpp +++ b/src/itemstackmetadata.cpp @@ -21,6 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "itemstackmetadata.h" #include "util/serialize.h" #include "util/strfnd.h" +#include <algorithm> #define DESERIALIZE_START '\x01' #define DESERIALIZE_KV_DELIM '\x02' @@ -37,10 +38,22 @@ void ItemStackMetadata::clear() updateToolCapabilities(); } +static void sanitize_string(std::string &str) +{ + str.erase(std::remove(str.begin(), str.end(), DESERIALIZE_START), str.end()); + str.erase(std::remove(str.begin(), str.end(), DESERIALIZE_KV_DELIM), str.end()); + str.erase(std::remove(str.begin(), str.end(), DESERIALIZE_PAIR_DELIM), str.end()); +} + bool ItemStackMetadata::setString(const std::string &name, const std::string &var) { - bool result = Metadata::setString(name, var); - if (name == TOOLCAP_KEY) + std::string clean_name = name; + std::string clean_var = var; + sanitize_string(clean_name); + sanitize_string(clean_var); + + bool result = Metadata::setString(clean_name, clean_var); + if (clean_name == TOOLCAP_KEY) updateToolCapabilities(); return result; } diff --git a/src/main.cpp b/src/main.cpp index af6d307dc..7f96836b5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -47,11 +47,19 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "gui/guiEngine.h" #include "gui/mainmenumanager.h" #endif - #ifdef HAVE_TOUCHSCREENGUI #include "gui/touchscreengui.h" #endif +// for version information only +extern "C" { +#if USE_LUAJIT + #include <luajit.h> +#else + #include <lua.h> +#endif +} + #if !defined(SERVER) && \ (IRRLICHT_VERSION_MAJOR == 1) && \ (IRRLICHT_VERSION_MINOR == 8) && \ @@ -217,8 +225,7 @@ int main(int argc, char *argv[]) return run_dedicated_server(game_params, cmd_args) ? 0 : 1; #ifndef SERVER - ClientLauncher launcher; - retval = launcher.run(game_params, cmd_args) ? 0 : 1; + retval = ClientLauncher().run(game_params, cmd_args) ? 0 : 1; #else retval = 0; #endif @@ -351,6 +358,11 @@ static void print_version() #ifndef SERVER std::cout << "Using Irrlicht " IRRLICHT_SDK_VERSION << std::endl; #endif +#if USE_LUAJIT + std::cout << "Using " << LUAJIT_VERSION << std::endl; +#else + std::cout << "Using " << LUA_RELEASE << std::endl; +#endif std::cout << g_build_info << std::endl; } @@ -474,12 +486,15 @@ static bool create_userdata_path() static bool init_common(const Settings &cmd_args, int argc, char *argv[]) { startup_message(); - set_default_settings(g_settings); + set_default_settings(); // Initialize sockets sockets_init(); atexit(sockets_cleanup); + // Initialize g_settings + Settings::createLayer(SL_GLOBAL); + if (!read_config_file(cmd_args)) return false; diff --git a/src/map.cpp b/src/map.cpp index a80e7ff92..eeaf5c140 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -545,23 +545,6 @@ void Map::transformLiquids(std::map<v3s16, MapBlock*> &modified_blocks, u32 liquid_loop_max = g_settings->getS32("liquid_loop_max"); u32 loop_max = liquid_loop_max; -#if 0 - - /* If liquid_loop_max is not keeping up with the queue size increase - * loop_max up to a maximum of liquid_loop_max * dedicated_server_step. - */ - if (m_transforming_liquid.size() > loop_max * 2) { - // "Burst" mode - float server_step = g_settings->getFloat("dedicated_server_step"); - if (m_transforming_liquid_loop_count_multiplier - 1.0 < server_step) - m_transforming_liquid_loop_count_multiplier *= 1.0 + server_step / 10; - } else { - m_transforming_liquid_loop_count_multiplier = 1.0; - } - - loop_max *= m_transforming_liquid_loop_count_multiplier; -#endif - while (m_transforming_liquid.size() != 0) { // This should be done here so that it is done when continue is used @@ -1216,7 +1199,7 @@ bool Map::isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes) ServerMap::ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManager *emerge, MetricsBackend *mb): Map(gamedef), - settings_mgr(g_settings, savedir + DIR_DELIM + "map_meta.txt"), + settings_mgr(savedir + DIR_DELIM + "map_meta.txt"), m_emerge(emerge) { verbosestream<<FUNCTION_NAME<<std::endl; @@ -1317,18 +1300,6 @@ ServerMap::~ServerMap() */ delete dbase; delete dbase_ro; - -#if 0 - /* - Free all MapChunks - */ - core::map<v2s16, MapChunk*>::Iterator i = m_chunks.getIterator(); - for(; i.atEnd() == false; i++) - { - MapChunk *chunk = i.getNode()->getValue(); - delete chunk; - } -#endif } MapgenParams *ServerMap::getMapgenParams() @@ -1417,25 +1388,6 @@ bool ServerMap::initBlockMake(v3s16 blockpos, BlockMakeData *data) data->vmanip = new MMVManip(this); data->vmanip->initialEmerge(full_bpmin, full_bpmax); - // Note: we may need this again at some point. -#if 0 - // Ensure none of the blocks to be generated were marked as - // containing CONTENT_IGNORE - for (s16 z = blockpos_min.Z; z <= blockpos_max.Z; z++) { - for (s16 y = blockpos_min.Y; y <= blockpos_max.Y; y++) { - for (s16 x = blockpos_min.X; x <= blockpos_max.X; x++) { - core::map<v3s16, u8>::Node *n; - n = data->vmanip->m_loaded_blocks.find(v3s16(x, y, z)); - if (n == NULL) - continue; - u8 flags = n->getValue(); - flags &= ~VMANIP_BLOCK_CONTAINS_CIGNORE; - n->setValue(flags); - } - } - } -#endif - // Data is ready now. return true; } @@ -1446,8 +1398,6 @@ void ServerMap::finishBlockMake(BlockMakeData *data, v3s16 bpmin = data->blockpos_min; v3s16 bpmax = data->blockpos_max; - v3s16 extra_borders(1, 1, 1); - bool enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info; EMERGE_DBG_OUT("finishBlockMake(): " PP(bpmin) " - " PP(bpmax)); @@ -1540,116 +1490,6 @@ MapSector *ServerMap::createSector(v2s16 p2d) return sector; } -#if 0 -/* - This is a quick-hand function for calling makeBlock(). -*/ -MapBlock * ServerMap::generateBlock( - v3s16 p, - std::map<v3s16, MapBlock*> &modified_blocks -) -{ - bool enable_mapgen_debug_info = g_settings->getBool("enable_mapgen_debug_info"); - - TimeTaker timer("generateBlock"); - - //MapBlock *block = original_dummy; - - v2s16 p2d(p.X, p.Z); - v2s16 p2d_nodes = p2d * MAP_BLOCKSIZE; - - /* - Do not generate over-limit - */ - if(blockpos_over_limit(p)) - { - infostream<<FUNCTION_NAME<<": Block position over limit"<<std::endl; - throw InvalidPositionException("generateBlock(): pos. over limit"); - } - - /* - Create block make data - */ - BlockMakeData data; - initBlockMake(&data, p); - - /* - Generate block - */ - { - TimeTaker t("mapgen::make_block()"); - mapgen->makeChunk(&data); - //mapgen::make_block(&data); - - if(enable_mapgen_debug_info == false) - t.stop(true); // Hide output - } - - /* - Blit data back on map, update lighting, add mobs and whatever this does - */ - finishBlockMake(&data, modified_blocks); - - /* - Get central block - */ - MapBlock *block = getBlockNoCreateNoEx(p); - -#if 0 - /* - Check result - */ - if(block) - { - bool erroneus_content = false; - for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++) - for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++) - for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++) - { - v3s16 p(x0,y0,z0); - MapNode n = block->getNode(p); - if(n.getContent() == CONTENT_IGNORE) - { - infostream<<"CONTENT_IGNORE at " - <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")" - <<std::endl; - erroneus_content = true; - assert(0); - } - } - if(erroneus_content) - { - assert(0); - } - } -#endif - -#if 0 - /* - Generate a completely empty block - */ - if(block) - { - for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++) - for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++) - { - for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++) - { - MapNode n; - n.setContent(CONTENT_AIR); - block->setNode(v3s16(x0,y0,z0), n); - } - } - } -#endif - - if(enable_mapgen_debug_info == false) - timer.stop(true); // Hide output - - return block; -} -#endif - MapBlock * ServerMap::createBlock(v3s16 p) { /* @@ -418,13 +418,7 @@ private: bool m_map_saving_enabled; int m_map_compression_level; -#if 0 - // Chunk size in MapSectors - // If 0, chunks are disabled. - s16 m_chunksize; - // Chunks - core::map<v2s16, MapChunk*> m_chunks; -#endif + std::set<v3s16> m_chunks_in_progress; /* diff --git a/src/map_settings_manager.cpp b/src/map_settings_manager.cpp index 9c447b3d0..99e3cb0e6 100644 --- a/src/map_settings_manager.cpp +++ b/src/map_settings_manager.cpp @@ -25,17 +25,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "map_settings_manager.h" -MapSettingsManager::MapSettingsManager(Settings *user_settings, - const std::string &map_meta_path): - m_map_meta_path(map_meta_path), - m_map_settings(new Settings()), - m_user_settings(user_settings) +MapSettingsManager::MapSettingsManager(const std::string &map_meta_path): + m_map_meta_path(map_meta_path) { - assert(m_user_settings != NULL); - - Mapgen::setDefaultSettings(m_map_settings); - // This inherits the combined defaults provided by loadGameConfAndInitWorld. - m_map_settings->overrideDefaults(user_settings); + m_map_settings = Settings::createLayer(SL_MAP, "[end_of_params]"); + Mapgen::setDefaultSettings(Settings::getLayer(SL_DEFAULTS)); } @@ -49,22 +43,23 @@ MapSettingsManager::~MapSettingsManager() bool MapSettingsManager::getMapSetting( const std::string &name, std::string *value_out) { + // Get from map_meta.txt, then try from all other sources if (m_map_settings->getNoEx(name, *value_out)) return true; // Compatibility kludge - if (m_user_settings == g_settings && name == "seed") - return m_user_settings->getNoEx("fixed_map_seed", *value_out); + if (name == "seed") + return Settings::getLayer(SL_GLOBAL)->getNoEx("fixed_map_seed", *value_out); - return m_user_settings->getNoEx(name, *value_out); + return false; } bool MapSettingsManager::getMapSettingNoiseParams( const std::string &name, NoiseParams *value_out) { - return m_map_settings->getNoiseParams(name, *value_out) || - m_user_settings->getNoiseParams(name, *value_out); + // TODO: Rename to "getNoiseParams" + return m_map_settings->getNoiseParams(name, *value_out); } @@ -77,7 +72,7 @@ bool MapSettingsManager::setMapSetting( if (override_meta) m_map_settings->set(name, value); else - m_map_settings->setDefault(name, value); + Settings::getLayer(SL_GLOBAL)->set(name, value); return true; } @@ -89,7 +84,11 @@ bool MapSettingsManager::setMapSettingNoiseParams( if (mapgen_params) return false; - m_map_settings->setNoiseParams(name, *value, !override_meta); + if (override_meta) + m_map_settings->setNoiseParams(name, *value); + else + Settings::getLayer(SL_GLOBAL)->setNoiseParams(name, *value); + return true; } @@ -104,8 +103,8 @@ bool MapSettingsManager::loadMapMeta() return false; } - if (!m_map_settings->parseConfigLines(is, "[end_of_params]")) { - errorstream << "loadMapMeta: [end_of_params] not found!" << std::endl; + if (!m_map_settings->parseConfigLines(is)) { + errorstream << "loadMapMeta: Format error. '[end_of_params]' missing?" << std::endl; return false; } @@ -116,28 +115,23 @@ bool MapSettingsManager::loadMapMeta() bool MapSettingsManager::saveMapMeta() { // If mapgen params haven't been created yet; abort - if (!mapgen_params) + if (!mapgen_params) { + infostream << "saveMapMeta: mapgen_params not present! " + << "Server startup was probably interrupted." << std::endl; return false; + } + // Paths set up by subgames.cpp, but not in unittests if (!fs::CreateAllDirs(fs::RemoveLastPathComponent(m_map_meta_path))) { errorstream << "saveMapMeta: could not create dirs to " << m_map_meta_path; return false; } - std::ostringstream oss(std::ios_base::binary); - Settings conf; + mapgen_params->MapgenParams::writeParams(m_map_settings); + mapgen_params->writeParams(m_map_settings); - mapgen_params->MapgenParams::writeParams(&conf); - mapgen_params->writeParams(&conf); - conf.writeLines(oss); - - // NOTE: If there are ever types of map settings other than - // those relating to map generation, save them here - - oss << "[end_of_params]\n"; - - if (!fs::safeWriteToFile(m_map_meta_path, oss.str())) { + if (!m_map_settings->updateConfigFile(m_map_meta_path.c_str())) { errorstream << "saveMapMeta: could not write " << m_map_meta_path << std::endl; return false; @@ -152,23 +146,21 @@ MapgenParams *MapSettingsManager::makeMapgenParams() if (mapgen_params) return mapgen_params; - assert(m_user_settings != NULL); assert(m_map_settings != NULL); // At this point, we have (in order of precedence): - // 1). m_mapgen_settings->m_settings containing map_meta.txt settings or + // 1). SL_MAP containing map_meta.txt settings or // explicit overrides from scripts - // 2). m_mapgen_settings->m_defaults containing script-set mgparams without - // overrides - // 3). g_settings->m_settings containing all user-specified config file + // 2). SL_GLOBAL containing all user-specified config file // settings - // 4). g_settings->m_defaults containing any low-priority settings from + // 3). SL_DEFAULTS containing any low-priority settings from // scripts, e.g. mods using Lua as an enhanced config file) // Now, get the mapgen type so we can create the appropriate MapgenParams std::string mg_name; MapgenType mgtype = getMapSetting("mg_name", &mg_name) ? Mapgen::getMapgenType(mg_name) : MAPGEN_DEFAULT; + if (mgtype == MAPGEN_INVALID) { errorstream << "EmergeManager: mapgen '" << mg_name << "' not valid; falling back to " << diff --git a/src/map_settings_manager.h b/src/map_settings_manager.h index 5baa38455..9258d3032 100644 --- a/src/map_settings_manager.h +++ b/src/map_settings_manager.h @@ -44,8 +44,7 @@ struct MapgenParams; */ class MapSettingsManager { public: - MapSettingsManager(Settings *user_settings, - const std::string &map_meta_path); + MapSettingsManager(const std::string &map_meta_path); ~MapSettingsManager(); // Finalized map generation parameters @@ -71,6 +70,6 @@ public: private: std::string m_map_meta_path; + // TODO: Rename to "m_settings" Settings *m_map_settings; - Settings *m_user_settings; }; diff --git a/src/mapblock.h b/src/mapblock.h index 641a1b69b..7b82301e9 100644 --- a/src/mapblock.h +++ b/src/mapblock.h @@ -340,15 +340,6 @@ public: // is not valid on this MapBlock. bool isValidPositionParent(v3s16 p); MapNode getNodeParent(v3s16 p, bool *is_valid_position = NULL); - void setNodeParent(v3s16 p, MapNode & n); - - inline void drawbox(s16 x0, s16 y0, s16 z0, s16 w, s16 h, s16 d, MapNode node) - { - for (u16 z = 0; z < d; z++) - for (u16 y = 0; y < h; y++) - for (u16 x = 0; x < w; x++) - setNode(x0 + x, y0 + y, z0 + z, node); - } // Copies data to VoxelManipulator to getPosRelative() void copyTo(VoxelManipulator &dst); diff --git a/src/mapgen/mapgen.cpp b/src/mapgen/mapgen.cpp index e0dfd2d71..7984ff609 100644 --- a/src/mapgen/mapgen.cpp +++ b/src/mapgen/mapgen.cpp @@ -595,7 +595,8 @@ MapgenBasic::MapgenBasic(int mapgenid, MapgenParams *params, EmergeParams *emerg this->heightmap = new s16[csize.X * csize.Z]; //// Initialize biome generator - biomegen = m_bmgr->createBiomeGen(BIOMEGEN_ORIGINAL, params->bparams, csize); + biomegen = emerge->biomegen; + biomegen->assertChunkSize(csize); biomemap = biomegen->biomemap; //// Look up some commonly used content @@ -621,7 +622,6 @@ MapgenBasic::MapgenBasic(int mapgenid, MapgenParams *params, EmergeParams *emerg MapgenBasic::~MapgenBasic() { - delete biomegen; delete []heightmap; delete m_emerge; // destroying EmergeParams is our responsibility diff --git a/src/mapgen/mapgen.h b/src/mapgen/mapgen.h index 1487731e2..61db4f3b9 100644 --- a/src/mapgen/mapgen.h +++ b/src/mapgen/mapgen.h @@ -30,10 +30,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #define MAPGEN_DEFAULT_NAME "v7" /////////////////// Mapgen flags -#define MG_TREES 0x01 // Obsolete. Moved into mgv6 flags #define MG_CAVES 0x02 #define MG_DUNGEONS 0x04 -#define MG_FLAT 0x08 // Obsolete. Moved into mgv6 flags #define MG_LIGHT 0x10 #define MG_DECORATIONS 0x20 #define MG_BIOMES 0x40 diff --git a/src/mapgen/mapgen_v6.cpp b/src/mapgen/mapgen_v6.cpp index e04180f96..bce9cee81 100644 --- a/src/mapgen/mapgen_v6.cpp +++ b/src/mapgen/mapgen_v6.cpp @@ -792,7 +792,7 @@ void MapgenV6::flowMud(s16 &mudflow_minpos, s16 &mudflow_maxpos) v3s16(0, 0, -1), // Front v3s16(-1, 0, 0), // Left }; - + // Iterate twice for (s16 k = 0; k < 2; k++) { for (s16 z = mudflow_minpos; z <= mudflow_maxpos; z++) @@ -1055,7 +1055,6 @@ void MapgenV6::growGrass() // Add surface nodes MapNode n_dirt_with_grass(c_dirt_with_grass); MapNode n_dirt_with_snow(c_dirt_with_snow); MapNode n_snowblock(c_snowblock); - MapNode n_snow(c_snow); const v3s16 &em = vm->m_area.getExtent(); u32 index = 0; diff --git a/src/mapgen/mapgen_valleys.cpp b/src/mapgen/mapgen_valleys.cpp index c4234857e..80a99b1f0 100644 --- a/src/mapgen/mapgen_valleys.cpp +++ b/src/mapgen/mapgen_valleys.cpp @@ -57,7 +57,8 @@ FlagDesc flagdesc_mapgen_valleys[] = { MapgenValleys::MapgenValleys(MapgenValleysParams *params, EmergeParams *emerge) : MapgenBasic(MAPGEN_VALLEYS, params, emerge) { - // NOTE: MapgenValleys has a hard dependency on BiomeGenOriginal + FATAL_ERROR_IF(biomegen->getType() != BIOMEGEN_ORIGINAL, + "MapgenValleys has a hard dependency on BiomeGenOriginal"); m_bgen = (BiomeGenOriginal *)biomegen; spflags = params->spflags; diff --git a/src/mapgen/mg_biome.cpp b/src/mapgen/mg_biome.cpp index 610c38594..f08cc190f 100644 --- a/src/mapgen/mg_biome.cpp +++ b/src/mapgen/mg_biome.cpp @@ -101,71 +101,6 @@ BiomeManager *BiomeManager::clone() const return mgr; } - -// For BiomeGen type 'BiomeGenOriginal' -float BiomeManager::getHeatAtPosOriginal(v3s16 pos, NoiseParams &np_heat, - NoiseParams &np_heat_blend, u64 seed) const -{ - return - NoisePerlin2D(&np_heat, pos.X, pos.Z, seed) + - NoisePerlin2D(&np_heat_blend, pos.X, pos.Z, seed); -} - - -// For BiomeGen type 'BiomeGenOriginal' -float BiomeManager::getHumidityAtPosOriginal(v3s16 pos, NoiseParams &np_humidity, - NoiseParams &np_humidity_blend, u64 seed) const -{ - return - NoisePerlin2D(&np_humidity, pos.X, pos.Z, seed) + - NoisePerlin2D(&np_humidity_blend, pos.X, pos.Z, seed); -} - - -// For BiomeGen type 'BiomeGenOriginal' -const Biome *BiomeManager::getBiomeFromNoiseOriginal(float heat, - float humidity, v3s16 pos) const -{ - Biome *biome_closest = nullptr; - Biome *biome_closest_blend = nullptr; - float dist_min = FLT_MAX; - float dist_min_blend = FLT_MAX; - - for (size_t i = 1; i < getNumObjects(); i++) { - Biome *b = (Biome *)getRaw(i); - if (!b || - pos.Y < b->min_pos.Y || pos.Y > b->max_pos.Y + b->vertical_blend || - pos.X < b->min_pos.X || pos.X > b->max_pos.X || - pos.Z < b->min_pos.Z || pos.Z > b->max_pos.Z) - continue; - - float d_heat = heat - b->heat_point; - float d_humidity = humidity - b->humidity_point; - float dist = (d_heat * d_heat) + (d_humidity * d_humidity); - - if (pos.Y <= b->max_pos.Y) { // Within y limits of biome b - if (dist < dist_min) { - dist_min = dist; - biome_closest = b; - } - } else if (dist < dist_min_blend) { // Blend area above biome b - dist_min_blend = dist; - biome_closest_blend = b; - } - } - - const u64 seed = pos.Y + (heat + humidity) * 0.9f; - PcgRandom rng(seed); - - if (biome_closest_blend && dist_min_blend <= dist_min && - rng.range(0, biome_closest_blend->vertical_blend) >= - pos.Y - biome_closest_blend->max_pos.Y) - return biome_closest_blend; - - return (biome_closest) ? biome_closest : (Biome *)getRaw(BIOME_NONE); -} - - //////////////////////////////////////////////////////////////////////////////// void BiomeParamsOriginal::readParams(const Settings *settings) @@ -189,7 +124,7 @@ void BiomeParamsOriginal::writeParams(Settings *settings) const //////////////////////////////////////////////////////////////////////////////// BiomeGenOriginal::BiomeGenOriginal(BiomeManager *biomemgr, - BiomeParamsOriginal *params, v3s16 chunksize) + const BiomeParamsOriginal *params, v3s16 chunksize) { m_bmgr = biomemgr; m_params = params; @@ -224,17 +159,26 @@ BiomeGenOriginal::~BiomeGenOriginal() delete noise_humidity_blend; } -// Only usable in a mapgen thread -Biome *BiomeGenOriginal::calcBiomeAtPoint(v3s16 pos) const +BiomeGen *BiomeGenOriginal::clone(BiomeManager *biomemgr) const +{ + return new BiomeGenOriginal(biomemgr, m_params, m_csize); +} + +float BiomeGenOriginal::calcHeatAtPoint(v3s16 pos) const { - float heat = - NoisePerlin2D(&m_params->np_heat, pos.X, pos.Z, m_params->seed) + + return NoisePerlin2D(&m_params->np_heat, pos.X, pos.Z, m_params->seed) + NoisePerlin2D(&m_params->np_heat_blend, pos.X, pos.Z, m_params->seed); - float humidity = - NoisePerlin2D(&m_params->np_humidity, pos.X, pos.Z, m_params->seed) + +} + +float BiomeGenOriginal::calcHumidityAtPoint(v3s16 pos) const +{ + return NoisePerlin2D(&m_params->np_humidity, pos.X, pos.Z, m_params->seed) + NoisePerlin2D(&m_params->np_humidity_blend, pos.X, pos.Z, m_params->seed); +} - return calcBiomeFromNoise(heat, humidity, pos); +Biome *BiomeGenOriginal::calcBiomeAtPoint(v3s16 pos) const +{ + return calcBiomeFromNoise(calcHeatAtPoint(pos), calcHumidityAtPoint(pos), pos); } diff --git a/src/mapgen/mg_biome.h b/src/mapgen/mg_biome.h index be4cfea4d..c85afc3a0 100644 --- a/src/mapgen/mg_biome.h +++ b/src/mapgen/mg_biome.h @@ -97,6 +97,15 @@ public: virtual BiomeGenType getType() const = 0; + // Clone this BiomeGen and set a the new BiomeManager to be used by the copy + virtual BiomeGen *clone(BiomeManager *biomemgr) const = 0; + + // Check that the internal chunk size is what the mapgen expects, just to be sure. + inline void assertChunkSize(v3s16 expect) const + { + FATAL_ERROR_IF(m_csize != expect, "Chunk size mismatches"); + } + // Calculates the biome at the exact position provided. This function can // be called at any time, but may be less efficient than the latter methods, // depending on implementation. @@ -158,12 +167,18 @@ struct BiomeParamsOriginal : public BiomeParams { class BiomeGenOriginal : public BiomeGen { public: BiomeGenOriginal(BiomeManager *biomemgr, - BiomeParamsOriginal *params, v3s16 chunksize); + const BiomeParamsOriginal *params, v3s16 chunksize); virtual ~BiomeGenOriginal(); BiomeGenType getType() const { return BIOMEGEN_ORIGINAL; } + BiomeGen *clone(BiomeManager *biomemgr) const; + + // Slower, meant for Script API use + float calcHeatAtPoint(v3s16 pos) const; + float calcHumidityAtPoint(v3s16 pos) const; Biome *calcBiomeAtPoint(v3s16 pos) const; + void calcBiomeNoise(v3s16 pmin); biome_t *getBiomes(s16 *heightmap, v3s16 pmin); @@ -176,7 +191,7 @@ public: float *humidmap; private: - BiomeParamsOriginal *m_params; + const BiomeParamsOriginal *m_params; Noise *noise_heat; Noise *noise_humidity; @@ -229,14 +244,6 @@ public: virtual void clear(); - // For BiomeGen type 'BiomeGenOriginal' - float getHeatAtPosOriginal(v3s16 pos, NoiseParams &np_heat, - NoiseParams &np_heat_blend, u64 seed) const; - float getHumidityAtPosOriginal(v3s16 pos, NoiseParams &np_humidity, - NoiseParams &np_humidity_blend, u64 seed) const; - const Biome *getBiomeFromNoiseOriginal(float heat, float humidity, - v3s16 pos) const; - private: BiomeManager() {}; diff --git a/src/mapgen/mg_ore.h b/src/mapgen/mg_ore.h index 76420fab4..a757fa6d0 100644 --- a/src/mapgen/mg_ore.h +++ b/src/mapgen/mg_ore.h @@ -52,7 +52,7 @@ extern FlagDesc flagdesc_ore[]; class Ore : public ObjDef, public NodeResolver { public: - static const bool NEEDS_NOISE = false; + const bool needs_noise; content_t c_ore; // the node to place std::vector<content_t> c_wherein; // the nodes to be placed in @@ -68,7 +68,7 @@ public: Noise *noise = nullptr; std::unordered_set<biome_t> biomes; - Ore() = default;; + explicit Ore(bool needs_noise): needs_noise(needs_noise) {} virtual ~Ore(); virtual void resolveNodeNames(); @@ -83,88 +83,81 @@ protected: class OreScatter : public Ore { public: - static const bool NEEDS_NOISE = false; + OreScatter() : Ore(false) {} - ObjDef *clone() const; + ObjDef *clone() const override; - virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, - v3s16 nmin, v3s16 nmax, biome_t *biomemap); + void generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap) override; }; class OreSheet : public Ore { public: - static const bool NEEDS_NOISE = true; + OreSheet() : Ore(true) {} - ObjDef *clone() const; + ObjDef *clone() const override; u16 column_height_min; u16 column_height_max; float column_midpoint_factor; - virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, - v3s16 nmin, v3s16 nmax, biome_t *biomemap); + void generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap) override; }; class OrePuff : public Ore { public: - static const bool NEEDS_NOISE = true; - - ObjDef *clone() const; + ObjDef *clone() const override; NoiseParams np_puff_top; NoiseParams np_puff_bottom; Noise *noise_puff_top = nullptr; Noise *noise_puff_bottom = nullptr; - OrePuff() = default; + OrePuff() : Ore(true) {} virtual ~OrePuff(); - virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, - v3s16 nmin, v3s16 nmax, biome_t *biomemap); + void generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap) override; }; class OreBlob : public Ore { public: - static const bool NEEDS_NOISE = true; - - ObjDef *clone() const; + ObjDef *clone() const override; - virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, - v3s16 nmin, v3s16 nmax, biome_t *biomemap); + OreBlob() : Ore(true) {} + void generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap) override; }; class OreVein : public Ore { public: - static const bool NEEDS_NOISE = true; - - ObjDef *clone() const; + ObjDef *clone() const override; float random_factor; Noise *noise2 = nullptr; int sizey_prev = 0; - OreVein() = default; + OreVein() : Ore(true) {} virtual ~OreVein(); - virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, - v3s16 nmin, v3s16 nmax, biome_t *biomemap); + void generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap) override; }; class OreStratum : public Ore { public: - static const bool NEEDS_NOISE = false; - - ObjDef *clone() const; + ObjDef *clone() const override; NoiseParams np_stratum_thickness; Noise *noise_stratum_thickness = nullptr; u16 stratum_thickness; - OreStratum() = default; + OreStratum() : Ore(false) {} virtual ~OreStratum(); - virtual void generate(MMVManip *vm, int mapseed, u32 blockseed, - v3s16 nmin, v3s16 nmax, biome_t *biomemap); + void generate(MMVManip *vm, int mapseed, u32 blockseed, + v3s16 nmin, v3s16 nmax, biome_t *biomemap) override; }; class OreManager : public ObjDefManager { diff --git a/src/mapgen/mg_schematic.cpp b/src/mapgen/mg_schematic.cpp index e70e97e48..653bad4fe 100644 --- a/src/mapgen/mg_schematic.cpp +++ b/src/mapgen/mg_schematic.cpp @@ -76,10 +76,6 @@ void SchematicManager::clear() /////////////////////////////////////////////////////////////////////////////// -Schematic::Schematic() -= default; - - Schematic::~Schematic() { delete []schemdata; @@ -108,13 +104,19 @@ ObjDef *Schematic::clone() const void Schematic::resolveNodeNames() { + c_nodes.clear(); getIdsFromNrBacklog(&c_nodes, true, CONTENT_AIR); size_t bufsize = size.X * size.Y * size.Z; for (size_t i = 0; i != bufsize; i++) { content_t c_original = schemdata[i].getContent(); - content_t c_new = c_nodes[c_original]; - schemdata[i].setContent(c_new); + if (c_original >= c_nodes.size()) { + errorstream << "Corrupt schematic. name=\"" << name + << "\" at index " << i << std::endl; + c_original = 0; + } + // Unfold condensed ID layout to content_t + schemdata[i].setContent(c_nodes[c_original]); } } @@ -279,8 +281,7 @@ void Schematic::placeOnMap(ServerMap *map, v3s16 p, u32 flags, } -bool Schematic::deserializeFromMts(std::istream *is, - std::vector<std::string> *names) +bool Schematic::deserializeFromMts(std::istream *is) { std::istream &ss = *is; content_t cignore = CONTENT_IGNORE; @@ -312,6 +313,8 @@ bool Schematic::deserializeFromMts(std::istream *is, slice_probs[y] = (version >= 3) ? readU8(ss) : MTSCHEM_PROB_ALWAYS_OLD; //// Read node names + NodeResolver::reset(); + u16 nidmapcount = readU16(ss); for (int i = 0; i != nidmapcount; i++) { std::string name = deSerializeString16(ss); @@ -324,9 +327,12 @@ bool Schematic::deserializeFromMts(std::istream *is, have_cignore = true; } - names->push_back(name); + m_nodenames.push_back(name); } + // Prepare for node resolver + m_nnlistsizes.push_back(m_nodenames.size()); + //// Read node data size_t nodecount = size.X * size.Y * size.Z; @@ -358,9 +364,11 @@ bool Schematic::deserializeFromMts(std::istream *is, } -bool Schematic::serializeToMts(std::ostream *os, - const std::vector<std::string> &names) const +bool Schematic::serializeToMts(std::ostream *os) const { + // Nodes must not be resolved (-> condensed) + // checking here is not possible because "schemdata" might be temporary. + std::ostream &ss = *os; writeU32(ss, MTSCHEM_FILE_SIGNATURE); // signature @@ -370,9 +378,10 @@ bool Schematic::serializeToMts(std::ostream *os, for (int y = 0; y != size.Y; y++) // Y slice probabilities writeU8(ss, slice_probs[y]); - writeU16(ss, names.size()); // name count - for (size_t i = 0; i != names.size(); i++) - ss << serializeString16(names[i]); // node names + writeU16(ss, m_nodenames.size()); // name count + for (size_t i = 0; i != m_nodenames.size(); i++) { + ss << serializeString16(m_nodenames[i]); // node names + } // compressed bulk node data MapNode::serializeBulk(ss, SER_FMT_VER_HIGHEST_WRITE, @@ -382,8 +391,7 @@ bool Schematic::serializeToMts(std::ostream *os, } -bool Schematic::serializeToLua(std::ostream *os, - const std::vector<std::string> &names, bool use_comments, +bool Schematic::serializeToLua(std::ostream *os, bool use_comments, u32 indent_spaces) const { std::ostream &ss = *os; @@ -392,6 +400,9 @@ bool Schematic::serializeToLua(std::ostream *os, if (indent_spaces > 0) indent.assign(indent_spaces, ' '); + bool resolve_done = isResolveDone(); + FATAL_ERROR_IF(resolve_done && !m_ndef, "serializeToLua: NodeDefManager is required"); + //// Write header { ss << "schematic = {" << std::endl; @@ -436,9 +447,22 @@ bool Schematic::serializeToLua(std::ostream *os, u8 probability = schemdata[i].param1 & MTSCHEM_PROB_MASK; bool force_place = schemdata[i].param1 & MTSCHEM_FORCE_PLACE; - ss << indent << indent << "{" - << "name=\"" << names[schemdata[i].getContent()] - << "\", prob=" << (u16)probability * 2 + // After node resolving: real content_t, lookup using NodeDefManager + // Prior node resolving: condensed ID, lookup using m_nodenames + content_t c = schemdata[i].getContent(); + + ss << indent << indent << "{" << "name=\""; + + if (!resolve_done) { + // Prior node resolving (eg. direct schematic load) + FATAL_ERROR_IF(c >= m_nodenames.size(), "Invalid node list"); + ss << m_nodenames[c]; + } else { + // After node resolving (eg. biome decoration) + ss << m_ndef->get(c).name; + } + + ss << "\", prob=" << (u16)probability * 2 << ", param2=" << (u16)schemdata[i].param2; if (force_place) @@ -467,25 +491,24 @@ bool Schematic::loadSchematicFromFile(const std::string &filename, return false; } - size_t origsize = m_nodenames.size(); - if (!deserializeFromMts(&is, &m_nodenames)) - return false; + if (!m_ndef) + m_ndef = ndef; - m_nnlistsizes.push_back(m_nodenames.size() - origsize); + if (!deserializeFromMts(&is)) + return false; name = filename; if (replace_names) { - for (size_t i = origsize; i < m_nodenames.size(); i++) { - std::string &node_name = m_nodenames[i]; + for (std::string &node_name : m_nodenames) { StringMap::iterator it = replace_names->find(node_name); if (it != replace_names->end()) node_name = it->second; } } - if (ndef) - ndef->pendNodeResolve(this); + if (m_ndef) + m_ndef->pendNodeResolve(this); return true; } @@ -494,33 +517,26 @@ bool Schematic::loadSchematicFromFile(const std::string &filename, bool Schematic::saveSchematicToFile(const std::string &filename, const NodeDefManager *ndef) { - MapNode *orig_schemdata = schemdata; - std::vector<std::string> ndef_nodenames; - std::vector<std::string> *names; + Schematic *schem = this; - if (m_resolve_done && ndef == NULL) - ndef = m_ndef; + bool needs_condense = isResolveDone(); - if (ndef) { - names = &ndef_nodenames; + if (!m_ndef) + m_ndef = ndef; - u32 volume = size.X * size.Y * size.Z; - schemdata = new MapNode[volume]; - for (u32 i = 0; i != volume; i++) - schemdata[i] = orig_schemdata[i]; + if (needs_condense) { + if (!m_ndef) + return false; - generate_nodelist_and_update_ids(schemdata, volume, names, ndef); - } else { // otherwise, use the names we have on hand in the list - names = &m_nodenames; + schem = (Schematic *)this->clone(); + schem->condenseContentIds(); } std::ostringstream os(std::ios_base::binary); - bool status = serializeToMts(&os, *names); + bool status = schem->serializeToMts(&os); - if (ndef) { - delete []schemdata; - schemdata = orig_schemdata; - } + if (needs_condense) + delete schem; if (!status) return false; @@ -556,6 +572,10 @@ bool Schematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2) } delete vm; + + // Reset and mark as complete + NodeResolver::reset(true); + return true; } @@ -584,26 +604,29 @@ void Schematic::applyProbabilities(v3s16 p0, } -void generate_nodelist_and_update_ids(MapNode *nodes, size_t nodecount, - std::vector<std::string> *usednodes, const NodeDefManager *ndef) +void Schematic::condenseContentIds() { std::unordered_map<content_t, content_t> nodeidmap; content_t numids = 0; + // Reset node resolve fields + NodeResolver::reset(); + + size_t nodecount = size.X * size.Y * size.Z; for (size_t i = 0; i != nodecount; i++) { content_t id; - content_t c = nodes[i].getContent(); + content_t c = schemdata[i].getContent(); - std::unordered_map<content_t, content_t>::const_iterator it = nodeidmap.find(c); + auto it = nodeidmap.find(c); if (it == nodeidmap.end()) { id = numids; numids++; - usednodes->push_back(ndef->get(c).name); - nodeidmap.insert(std::make_pair(c, id)); + m_nodenames.push_back(m_ndef->get(c).name); + nodeidmap.emplace(std::make_pair(c, id)); } else { id = it->second; } - nodes[i].setContent(id); + schemdata[i].setContent(id); } } diff --git a/src/mapgen/mg_schematic.h b/src/mapgen/mg_schematic.h index 6b31251b6..5f64ea280 100644 --- a/src/mapgen/mg_schematic.h +++ b/src/mapgen/mg_schematic.h @@ -92,7 +92,7 @@ enum SchematicFormatType { class Schematic : public ObjDef, public NodeResolver { public: - Schematic(); + Schematic() = default; virtual ~Schematic(); ObjDef *clone() const; @@ -105,11 +105,9 @@ public: const NodeDefManager *ndef); bool getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2); - bool deserializeFromMts(std::istream *is, std::vector<std::string> *names); - bool serializeToMts(std::ostream *os, - const std::vector<std::string> &names) const; - bool serializeToLua(std::ostream *os, const std::vector<std::string> &names, - bool use_comments, u32 indent_spaces) const; + bool deserializeFromMts(std::istream *is); + bool serializeToMts(std::ostream *os) const; + bool serializeToLua(std::ostream *os, bool use_comments, u32 indent_spaces) const; void blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_place); bool placeOnVManip(MMVManip *vm, v3s16 p, u32 flags, Rotation rot, bool force_place); @@ -124,6 +122,10 @@ public: v3s16 size; MapNode *schemdata = nullptr; u8 *slice_probs = nullptr; + +private: + // Counterpart to the node resolver: Condense content_t to a sequential "m_nodenames" list + void condenseContentIds(); }; class SchematicManager : public ObjDefManager { @@ -151,5 +153,3 @@ private: Server *m_server; }; -void generate_nodelist_and_update_ids(MapNode *nodes, size_t nodecount, - std::vector<std::string> *usednodes, const NodeDefManager *ndef); diff --git a/src/mapnode.cpp b/src/mapnode.cpp index 0551f3b6f..c885bfe1d 100644 --- a/src/mapnode.cpp +++ b/src/mapnode.cpp @@ -159,8 +159,11 @@ u8 MapNode::getWallMounted(const NodeDefManager *nodemgr) const { const ContentFeatures &f = nodemgr->get(*this); if (f.param_type_2 == CPT2_WALLMOUNTED || - f.param_type_2 == CPT2_COLORED_WALLMOUNTED) + f.param_type_2 == CPT2_COLORED_WALLMOUNTED) { return getParam2() & 0x07; + } else if (f.drawtype == NDT_SIGNLIKE || f.drawtype == NDT_TORCHLIKE) { + return 1; + } return 0; } @@ -177,6 +180,16 @@ v3s16 MapNode::getWallMountedDir(const NodeDefManager *nodemgr) const } } +u8 MapNode::getDegRotate(const NodeDefManager *nodemgr) const +{ + const ContentFeatures &f = nodemgr->get(*this); + if (f.param_type_2 == CPT2_DEGROTATE) + return getParam2() % 240; + if (f.param_type_2 == CPT2_COLORED_DEGROTATE) + return 10 * ((getParam2() & 0x1F) % 24); + return 0; +} + void MapNode::rotateAlongYAxis(const NodeDefManager *nodemgr, Rotation rot) { ContentParamType2 cpt2 = nodemgr->get(*this).param_type_2; @@ -230,6 +243,17 @@ void MapNode::rotateAlongYAxis(const NodeDefManager *nodemgr, Rotation rot) Rotation oldrot = wallmounted_to_rot[wmountface - 2]; param2 &= ~7; param2 |= rot_to_wallmounted[(oldrot - rot) & 3]; + } else if (cpt2 == CPT2_DEGROTATE) { + int angle = param2; // in 1.5° + angle += 60 * rot; // don’t do that on u8 + angle %= 240; + param2 = angle; + } else if (cpt2 == CPT2_COLORED_DEGROTATE) { + int angle = param2 & 0x1F; // in 15° + int color = param2 & 0xE0; + angle += 6 * rot; + angle %= 24; + param2 = color | angle; } } diff --git a/src/mapnode.h b/src/mapnode.h index a9ae63ba3..28ff9e43d 100644 --- a/src/mapnode.h +++ b/src/mapnode.h @@ -240,6 +240,9 @@ struct MapNode u8 getWallMounted(const NodeDefManager *nodemgr) const; v3s16 getWallMountedDir(const NodeDefManager *nodemgr) const; + /// @returns Rotation in range 0–239 (in 1.5° steps) + u8 getDegRotate(const NodeDefManager *nodemgr) const; + void rotateAlongYAxis(const NodeDefManager *nodemgr, Rotation rot); /*! diff --git a/src/network/clientpackethandler.cpp b/src/network/clientpackethandler.cpp index 55f85571d..2fea03fbf 100644 --- a/src/network/clientpackethandler.cpp +++ b/src/network/clientpackethandler.cpp @@ -450,10 +450,10 @@ void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt) string initialization data } */ - + LocalPlayer *player = m_env.getLocalPlayer(); - bool try_reattach = player && player->isWaitingForReattach(); - + bool try_reattach = player && player->isWaitingForReattach(); + try { u8 type; u16 removed_count, added_count, id; @@ -596,13 +596,13 @@ void Client::handleCommand_Breath(NetworkPacket* pkt) } void Client::handleCommand_MovePlayer(NetworkPacket* pkt) -{ +{ LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); if ((player->getCAO() && player->getCAO()->getParentId()) || player->isWaitingForReattach()) return; - + v3f pos; f32 pitch, yaw; @@ -622,10 +622,10 @@ void Client::handleCommand_MovePlayer(NetworkPacket* pkt) it would just force the pitch and yaw values to whatever the camera points to. */ - + if (g_settings->getBool("no_force_rotate")) return; - + ClientEvent *event = new ClientEvent(); event->type = CE_PLAYER_FORCE_MOVE; event->player_force_move.pitch = pitch; @@ -833,12 +833,12 @@ void Client::handleCommand_PlaySound(NetworkPacket* pkt) *pkt >> pitch; *pkt >> ephemeral; } catch (PacketError &e) {}; - + SimpleSoundSpec sound_spec(name, gain, fade, pitch); - + if (m_mods_loaded && m_script->on_play_sound(sound_spec)) return; - + // Start playing int client_id = -1; switch(type) { @@ -987,10 +987,10 @@ void Client::handleCommand_SpawnParticle(NetworkPacket* pkt) ClientEvent *event = new ClientEvent(); event->type = CE_SPAWN_PARTICLE; event->spawn_particle = new ParticleParameters(p); - + if (m_mods_loaded && m_script->on_spawn_particle(*event->spawn_particle)) return; - + m_client_event_queue.push(event); } @@ -1063,9 +1063,6 @@ void Client::handleCommand_DeleteParticleSpawner(NetworkPacket* pkt) void Client::handleCommand_HudAdd(NetworkPacket* pkt) { - std::string datastring(pkt->getString(0), pkt->getSize()); - std::istringstream is(datastring, std::ios_base::binary); - u32 server_id; u8 type; v2f pos; @@ -1092,22 +1089,23 @@ void Client::handleCommand_HudAdd(NetworkPacket* pkt) } catch(PacketError &e) {}; ClientEvent *event = new ClientEvent(); - event->type = CE_HUDADD; - event->hudadd.server_id = server_id; - event->hudadd.type = type; - event->hudadd.pos = new v2f(pos); - event->hudadd.name = new std::string(name); - event->hudadd.scale = new v2f(scale); - event->hudadd.text = new std::string(text); - event->hudadd.number = number; - event->hudadd.item = item; - event->hudadd.dir = dir; - event->hudadd.align = new v2f(align); - event->hudadd.offset = new v2f(offset); - event->hudadd.world_pos = new v3f(world_pos); - event->hudadd.size = new v2s32(size); - event->hudadd.z_index = z_index; - event->hudadd.text2 = new std::string(text2); + event->type = CE_HUDADD; + event->hudadd = new ClientEventHudAdd(); + event->hudadd->server_id = server_id; + event->hudadd->type = type; + event->hudadd->pos = pos; + event->hudadd->name = name; + event->hudadd->scale = scale; + event->hudadd->text = text; + event->hudadd->number = number; + event->hudadd->item = item; + event->hudadd->dir = dir; + event->hudadd->align = align; + event->hudadd->offset = offset; + event->hudadd->world_pos = world_pos; + event->hudadd->size = size; + event->hudadd->z_index = z_index; + event->hudadd->text2 = text2; m_client_event_queue.push(event); } @@ -1117,16 +1115,10 @@ void Client::handleCommand_HudRemove(NetworkPacket* pkt) *pkt >> server_id; - auto i = m_hud_server_to_client.find(server_id); - if (i != m_hud_server_to_client.end()) { - int client_id = i->second; - m_hud_server_to_client.erase(i); - - ClientEvent *event = new ClientEvent(); - event->type = CE_HUDRM; - event->hudrm.id = client_id; - m_client_event_queue.push(event); - } + ClientEvent *event = new ClientEvent(); + event->type = CE_HUDRM; + event->hudrm.id = server_id; + m_client_event_queue.push(event); } void Client::handleCommand_HudChange(NetworkPacket* pkt) @@ -1153,19 +1145,17 @@ void Client::handleCommand_HudChange(NetworkPacket* pkt) else *pkt >> intdata; - std::unordered_map<u32, u32>::const_iterator i = m_hud_server_to_client.find(server_id); - if (i != m_hud_server_to_client.end()) { - ClientEvent *event = new ClientEvent(); - event->type = CE_HUDCHANGE; - event->hudchange.id = i->second; - event->hudchange.stat = (HudElementStat)stat; - event->hudchange.v2fdata = new v2f(v2fdata); - event->hudchange.v3fdata = new v3f(v3fdata); - event->hudchange.sdata = new std::string(sdata); - event->hudchange.data = intdata; - event->hudchange.v2s32data = new v2s32(v2s32data); - m_client_event_queue.push(event); - } + ClientEvent *event = new ClientEvent(); + event->type = CE_HUDCHANGE; + event->hudchange = new ClientEventHudChange(); + event->hudchange->id = server_id; + event->hudchange->stat = static_cast<HudElementStat>(stat); + event->hudchange->v2fdata = v2fdata; + event->hudchange->v3fdata = v3fdata; + event->hudchange->sdata = sdata; + event->hudchange->data = intdata; + event->hudchange->v2s32data = v2s32data; + m_client_event_queue.push(event); } void Client::handleCommand_HudSetFlags(NetworkPacket* pkt) diff --git a/src/network/networkexceptions.h b/src/network/networkexceptions.h index f4913928c..58a3bb490 100644 --- a/src/network/networkexceptions.h +++ b/src/network/networkexceptions.h @@ -56,12 +56,6 @@ public: InvalidIncomingDataException(const char *s) : BaseException(s) {} }; -class InvalidOutgoingDataException : public BaseException -{ -public: - InvalidOutgoingDataException(const char *s) : BaseException(s) {} -}; - class NoIncomingDataException : public BaseException { public: @@ -103,4 +97,4 @@ class SendFailedException : public BaseException { public: SendFailedException(const std::string &s) : BaseException(s) {} -};
\ No newline at end of file +}; diff --git a/src/network/networkpacket.cpp b/src/network/networkpacket.cpp index 6d0abb12c..a71e26572 100644 --- a/src/network/networkpacket.cpp +++ b/src/network/networkpacket.cpp @@ -50,7 +50,7 @@ void NetworkPacket::checkReadOffset(u32 from_offset, u32 field_size) } } -void NetworkPacket::putRawPacket(u8 *data, u32 datasize, session_t peer_id) +void NetworkPacket::putRawPacket(const u8 *data, u32 datasize, session_t peer_id) { // If a m_command is already set, we are rewriting on same packet // This is not permitted @@ -145,6 +145,8 @@ void NetworkPacket::putLongString(const std::string &src) putRawString(src.c_str(), msgsize); } +static constexpr bool NEED_SURROGATE_CODING = sizeof(wchar_t) > 2; + NetworkPacket& NetworkPacket::operator>>(std::wstring& dst) { checkReadOffset(m_read_offset, 2); @@ -160,9 +162,16 @@ NetworkPacket& NetworkPacket::operator>>(std::wstring& dst) checkReadOffset(m_read_offset, strLen * 2); dst.reserve(strLen); - for(u16 i=0; i<strLen; i++) { - wchar_t c16 = readU16(&m_data[m_read_offset]); - dst.append(&c16, 1); + for (u16 i = 0; i < strLen; i++) { + wchar_t c = readU16(&m_data[m_read_offset]); + if (NEED_SURROGATE_CODING && c >= 0xD800 && c < 0xDC00 && i+1 < strLen) { + i++; + m_read_offset += sizeof(u16); + + wchar_t c2 = readU16(&m_data[m_read_offset]); + c = 0x10000 + ( ((c & 0x3ff) << 10) | (c2 & 0x3ff) ); + } + dst.push_back(c); m_read_offset += sizeof(u16); } @@ -175,15 +184,37 @@ NetworkPacket& NetworkPacket::operator<<(const std::wstring &src) throw PacketError("String too long"); } - u16 msgsize = src.size(); + if (!NEED_SURROGATE_CODING || src.size() == 0) { + *this << static_cast<u16>(src.size()); + for (u16 i = 0; i < src.size(); i++) + *this << static_cast<u16>(src[i]); - *this << msgsize; + return *this; + } - // Write string - for (u16 i=0; i<msgsize; i++) { - *this << (u16) src[i]; + // write dummy value, to be overwritten later + const u32 len_offset = m_read_offset; + u32 written = 0; + *this << static_cast<u16>(0xfff0); + + for (u16 i = 0; i < src.size(); i++) { + wchar_t c = src[i]; + if (c > 0xffff) { + // Encode high code-points as surrogate pairs + u32 n = c - 0x10000; + *this << static_cast<u16>(0xD800 | (n >> 10)) + << static_cast<u16>(0xDC00 | (n & 0x3ff)); + written += 2; + } else { + *this << static_cast<u16>(c); + written++; + } } + if (written > WIDE_STRING_MAX_LEN) + throw PacketError("String too long"); + writeU16(&m_data[len_offset], written); + return *this; } diff --git a/src/network/networkpacket.h b/src/network/networkpacket.h index e77bfb744..c7ff03b8e 100644 --- a/src/network/networkpacket.h +++ b/src/network/networkpacket.h @@ -34,7 +34,7 @@ public: ~NetworkPacket(); - void putRawPacket(u8 *data, u32 datasize, session_t peer_id); + void putRawPacket(const u8 *data, u32 datasize, session_t peer_id); void clear(); // Getters diff --git a/src/network/serverpackethandler.cpp b/src/network/serverpackethandler.cpp index c636d01e1..708ddbf20 100644 --- a/src/network/serverpackethandler.cpp +++ b/src/network/serverpackethandler.cpp @@ -56,12 +56,12 @@ void Server::handleCommand_Init(NetworkPacket* pkt) session_t peer_id = pkt->getPeerId(); RemoteClient *client = getClient(peer_id, CS_Created); + Address addr; std::string addr_s; try { - Address address = getPeerAddress(peer_id); - addr_s = address.serializeString(); - } - catch (con::PeerNotFoundException &e) { + addr = m_con->GetPeerAddress(peer_id); + addr_s = addr.serializeString(); + } catch (con::PeerNotFoundException &e) { /* * no peer for this packet found * most common reason is peer timeout, e.g. peer didn't @@ -73,13 +73,14 @@ void Server::handleCommand_Init(NetworkPacket* pkt) return; } - // If net_proto_version is set, this client has already been handled if (client->getState() > CS_Created) { verbosestream << "Server: Ignoring multiple TOSERVER_INITs from " << addr_s << " (peer_id=" << peer_id << ")" << std::endl; return; } + client->setCachedAddress(addr); + verbosestream << "Server: Got TOSERVER_INIT from " << addr_s << " (peer_id=" << peer_id << ")" << std::endl; @@ -173,6 +174,16 @@ void Server::handleCommand_Init(NetworkPacket* pkt) return; } + RemotePlayer *player = m_env->getPlayer(playername); + + // If player is already connected, cancel + if (player && player->getPeerId() != PEER_ID_INEXISTENT) { + actionstream << "Server: Player with name \"" << playername << + "\" tried to connect, but player with same name is already connected" << std::endl; + DenyAccess(peer_id, SERVER_ACCESSDENIED_ALREADY_CONNECTED); + return; + } + m_clients.setPlayerName(peer_id, playername); //TODO (later) case insensitivity @@ -437,18 +448,20 @@ void Server::handleCommand_GotBlocks(NetworkPacket* pkt) u8 count; *pkt >> count; - RemoteClient *client = getClient(pkt->getPeerId()); - if ((s16)pkt->getSize() < 1 + (int)count * 6) { throw con::InvalidIncomingDataException ("GOTBLOCKS length is too short"); } + m_clients.lock(); + RemoteClient *client = m_clients.lockedGetClientNoEx(pkt->getPeerId()); + for (u16 i = 0; i < count; i++) { v3s16 p; *pkt >> p; client->GotBlock(p); } + m_clients.unlock(); } void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao, @@ -485,8 +498,12 @@ void Server::process_PlayerPos(RemotePlayer *player, PlayerSAO *playersao, pitch = modulo360f(pitch); yaw = wrapDegrees_0_360(yaw); - playersao->setBasePosition(position); - player->setSpeed(speed); + if (!playersao->isAttached()) { + // Only update player positions when moving freely + // to not interfere with attachment handling + playersao->setBasePosition(position); + player->setSpeed(speed); + } playersao->setLookPitch(pitch); playersao->setPlayerYaw(yaw); playersao->setFov(fov); @@ -619,21 +636,36 @@ void Server::handleCommand_InventoryAction(NetworkPacket* pkt) const bool player_has_interact = checkPriv(player->getName(), "interact"); - auto check_inv_access = [player, player_has_interact] ( + auto check_inv_access = [player, player_has_interact, this] ( const InventoryLocation &loc) -> bool { - if (loc.type == InventoryLocation::CURRENT_PLAYER) - return false; // Only used internally on the client, never sent - if (loc.type == InventoryLocation::PLAYER) { - // Allow access to own inventory in all cases - return loc.name == player->getName(); - } - if (!player_has_interact) { + // Players without interact may modify their own inventory + if (!player_has_interact && loc.type != InventoryLocation::PLAYER) { infostream << "Cannot modify foreign inventory: " << "No interact privilege" << std::endl; return false; } - return true; + + switch (loc.type) { + case InventoryLocation::CURRENT_PLAYER: + // Only used internally on the client, never sent + return false; + case InventoryLocation::PLAYER: + // Allow access to own inventory in all cases + return loc.name == player->getName(); + case InventoryLocation::NODEMETA: + { + // Check for out-of-range interaction + v3f node_pos = intToFloat(loc.p, BS); + v3f player_pos = player->getPlayerSAO()->getEyePosition(); + f32 d = player_pos.getDistanceFrom(node_pos); + return checkInteractDistance(player, d, "inventory"); + } + case InventoryLocation::DETACHED: + return getInventoryMgr()->checkDetachedInventoryAccess(loc, player->getName()); + default: + return false; + } }; /* @@ -653,18 +685,6 @@ void Server::handleCommand_InventoryAction(NetworkPacket* pkt) !check_inv_access(ma->to_inv)) return; - InventoryLocation *remote = ma->from_inv.type == InventoryLocation::PLAYER ? - &ma->to_inv : &ma->from_inv; - - // Check for out-of-range interaction - if (remote->type == InventoryLocation::NODEMETA) { - v3f node_pos = intToFloat(remote->p, BS); - v3f player_pos = player->getPlayerSAO()->getEyePosition(); - f32 d = player_pos.getDistanceFrom(node_pos); - if (!checkInteractDistance(player, d, "inventory")) - return; - } - /* Disable moving items out of craftpreview */ @@ -749,21 +769,8 @@ void Server::handleCommand_InventoryAction(NetworkPacket* pkt) void Server::handleCommand_ChatMessage(NetworkPacket* pkt) { - /* - u16 command - u16 length - wstring message - */ - u16 len; - *pkt >> len; - std::wstring message; - for (u16 i = 0; i < len; i++) { - u16 tmp_wchar; - *pkt >> tmp_wchar; - - message += (wchar_t)tmp_wchar; - } + *pkt >> message; session_t peer_id = pkt->getPeerId(); RemotePlayer *player = m_env->getPlayer(peer_id); @@ -775,15 +782,13 @@ void Server::handleCommand_ChatMessage(NetworkPacket* pkt) return; } - // Get player name of this client std::string name = player->getName(); - std::wstring wname = narrow_to_wide(name); - std::wstring answer_to_sender = handleChat(name, wname, message, true, player); + std::wstring answer_to_sender = handleChat(name, message, true, player); if (!answer_to_sender.empty()) { // Send the answer to sender - SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_NORMAL, - answer_to_sender, wname)); + SendChatMessage(peer_id, ChatMessage(CHATMESSAGE_TYPE_SYSTEM, + answer_to_sender)); } } @@ -1046,6 +1051,12 @@ void Server::handleCommand_Interact(NetworkPacket *pkt) if (pointed.type == POINTEDTHING_NODE) { target_pos = intToFloat(pointed.node_undersurface, BS); } else if (pointed.type == POINTEDTHING_OBJECT) { + if (playersao->getId() == pointed_object->getId()) { + actionstream << "Server: " << player->getName() + << " attempted to interact with themselves" << std::endl; + m_script->on_cheat(playersao, "interacted_with_self"); + return; + } target_pos = pointed_object->getBasePosition(); } float d = playersao->getEyePosition().getDistanceFrom(target_pos); diff --git a/src/nodedef.cpp b/src/nodedef.cpp index bc00d5637..f27a8154b 100644 --- a/src/nodedef.cpp +++ b/src/nodedef.cpp @@ -360,7 +360,7 @@ void ContentFeatures::reset() i = TileDef(); for (auto &j : tiledef_special) j = TileDef(); - alpha = 255; + alpha = ALPHAMODE_OPAQUE; post_effect_color = video::SColor(0, 0, 0, 0); param_type = CPT_NONE; param_type_2 = CPT2_NONE; @@ -405,6 +405,31 @@ void ContentFeatures::reset() node_dig_prediction = "air"; } +void ContentFeatures::setAlphaFromLegacy(u8 legacy_alpha) +{ + // No special handling for nodebox/mesh here as it doesn't make sense to + // throw warnings when the server is too old to support the "correct" way + switch (drawtype) { + case NDT_NORMAL: + alpha = legacy_alpha == 255 ? ALPHAMODE_OPAQUE : ALPHAMODE_CLIP; + break; + case NDT_LIQUID: + case NDT_FLOWINGLIQUID: + alpha = legacy_alpha == 255 ? ALPHAMODE_OPAQUE : ALPHAMODE_BLEND; + break; + default: + alpha = legacy_alpha == 255 ? ALPHAMODE_CLIP : ALPHAMODE_BLEND; + break; + } +} + +u8 ContentFeatures::getAlphaForLegacy() const +{ + // This is so simple only because 255 and 0 mean wildly different things + // depending on drawtype... + return alpha == ALPHAMODE_OPAQUE ? 255 : 0; +} + void ContentFeatures::serialize(std::ostream &os, u16 protocol_version) const { const u8 version = CONTENTFEATURES_VERSION; @@ -433,7 +458,7 @@ void ContentFeatures::serialize(std::ostream &os, u16 protocol_version) const for (const TileDef &td : tiledef_special) { td.serialize(os, protocol_version); } - writeU8(os, alpha); + writeU8(os, getAlphaForLegacy()); writeU8(os, color.getRed()); writeU8(os, color.getGreen()); writeU8(os, color.getBlue()); @@ -489,21 +514,7 @@ void ContentFeatures::serialize(std::ostream &os, u16 protocol_version) const os << serializeString16(node_dig_prediction); writeU8(os, leveled_max); -} - -void ContentFeatures::correctAlpha(TileDef *tiles, int length) -{ - // alpha == 0 means that the node is using texture alpha - if (alpha == 0 || alpha == 255) - return; - - for (int i = 0; i < length; i++) { - if (tiles[i].name.empty()) - continue; - std::stringstream s; - s << tiles[i].name << "^[noalpha^[opacity:" << ((int)alpha); - tiles[i].name = s.str(); - } + writeU8(os, alpha); } void ContentFeatures::deSerialize(std::istream &is) @@ -539,7 +550,7 @@ void ContentFeatures::deSerialize(std::istream &is) throw SerializationError("unsupported CF_SPECIAL_COUNT"); for (TileDef &td : tiledef_special) td.deSerialize(is, version, drawtype); - alpha = readU8(is); + setAlphaFromLegacy(readU8(is)); color.setRed(readU8(is)); color.setGreen(readU8(is)); color.setBlue(readU8(is)); @@ -597,10 +608,16 @@ void ContentFeatures::deSerialize(std::istream &is) try { node_dig_prediction = deSerializeString16(is); - u8 tmp_leveled_max = readU8(is); + + u8 tmp = readU8(is); if (is.eof()) /* readU8 doesn't throw exceptions so we have to do this */ throw SerializationError(""); - leveled_max = tmp_leveled_max; + leveled_max = tmp; + + tmp = readU8(is); + if (is.eof()) + throw SerializationError(""); + alpha = static_cast<enum AlphaMode>(tmp); } catch(SerializationError &e) {}; } @@ -692,6 +709,7 @@ bool ContentFeatures::textureAlphaCheck(ITextureSource *tsrc, const TileDef *til video::IVideoDriver *driver = RenderingEngine::get_video_driver(); static thread_local bool long_warning_printed = false; std::set<std::string> seen; + for (int i = 0; i < length; i++) { if (seen.find(tiles[i].name) != seen.end()) continue; @@ -716,20 +734,21 @@ bool ContentFeatures::textureAlphaCheck(ITextureSource *tsrc, const TileDef *til break_loop: image->drop(); - if (!ok) { - warningstream << "Texture \"" << tiles[i].name << "\" of " - << name << " has transparent pixels, assuming " - "use_texture_alpha = true." << std::endl; - if (!long_warning_printed) { - warningstream << " This warning can be a false-positive if " - "unused pixels in the texture are transparent. However if " - "it is meant to be transparent, you *MUST* update the " - "nodedef and set use_texture_alpha = true! This compatibility " - "code will be removed in a few releases." << std::endl; - long_warning_printed = true; - } - return true; + if (ok) + continue; + warningstream << "Texture \"" << tiles[i].name << "\" of " + << name << " has transparency, assuming " + "use_texture_alpha = \"clip\"." << std::endl; + if (!long_warning_printed) { + warningstream << " This warning can be a false-positive if " + "unused pixels in the texture are transparent. However if " + "it is meant to be transparent, you *MUST* update the " + "nodedef and set use_texture_alpha = \"clip\"! This " + "compatibility code will be removed in a few releases." + << std::endl; + long_warning_printed = true; } + return true; } return false; } @@ -774,31 +793,33 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc bool is_liquid = false; - MaterialType material_type = (alpha == 255) ? - TILE_MATERIAL_BASIC : TILE_MATERIAL_ALPHA; + if (alpha == ALPHAMODE_LEGACY_COMPAT) { + // Before working with the alpha mode, resolve any legacy kludges + alpha = textureAlphaCheck(tsrc, tdef, 6) ? ALPHAMODE_CLIP : ALPHAMODE_OPAQUE; + } + + MaterialType material_type = alpha == ALPHAMODE_OPAQUE ? + TILE_MATERIAL_OPAQUE : (alpha == ALPHAMODE_CLIP ? TILE_MATERIAL_BASIC : + TILE_MATERIAL_ALPHA); switch (drawtype) { default: case NDT_NORMAL: - material_type = (alpha == 255) ? - TILE_MATERIAL_OPAQUE : TILE_MATERIAL_ALPHA; solidness = 2; break; case NDT_AIRLIKE: solidness = 0; break; case NDT_LIQUID: - assert(liquid_type == LIQUID_SOURCE); if (tsettings.opaque_water) - alpha = 255; + alpha = ALPHAMODE_OPAQUE; solidness = 1; is_liquid = true; break; case NDT_FLOWINGLIQUID: - assert(liquid_type == LIQUID_FLOWING); solidness = 0; if (tsettings.opaque_water) - alpha = 255; + alpha = ALPHAMODE_OPAQUE; is_liquid = true; break; case NDT_GLASSLIKE: @@ -850,19 +871,16 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc break; case NDT_MESH: case NDT_NODEBOX: - if (alpha == 255 && textureAlphaCheck(tsrc, tdef, 6)) - alpha = 0; - solidness = 0; - if (waving == 1) + if (waving == 1) { material_type = TILE_MATERIAL_WAVING_PLANTS; - else if (waving == 2) + } else if (waving == 2) { material_type = TILE_MATERIAL_WAVING_LEAVES; - else if (waving == 3) - material_type = (alpha == 255) ? TILE_MATERIAL_WAVING_LIQUID_OPAQUE : - TILE_MATERIAL_WAVING_LIQUID_BASIC; - else if (alpha == 255) - material_type = TILE_MATERIAL_OPAQUE; + } else if (waving == 3) { + material_type = alpha == ALPHAMODE_OPAQUE ? + TILE_MATERIAL_WAVING_LIQUID_OPAQUE : (alpha == ALPHAMODE_CLIP ? + TILE_MATERIAL_WAVING_LIQUID_BASIC : TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT); + } break; case NDT_TORCHLIKE: case NDT_SIGNLIKE: @@ -876,16 +894,12 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc } if (is_liquid) { - // Vertex alpha is no longer supported, correct if necessary. - correctAlpha(tdef, 6); - correctAlpha(tdef_overlay, 6); - correctAlpha(tdef_spec, CF_SPECIAL_COUNT); - if (waving == 3) { - material_type = (alpha == 255) ? TILE_MATERIAL_WAVING_LIQUID_OPAQUE : - TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT; + material_type = alpha == ALPHAMODE_OPAQUE ? + TILE_MATERIAL_WAVING_LIQUID_OPAQUE : (alpha == ALPHAMODE_CLIP ? + TILE_MATERIAL_WAVING_LIQUID_BASIC : TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT); } else { - material_type = (alpha == 255) ? TILE_MATERIAL_LIQUID_OPAQUE : + material_type = alpha == ALPHAMODE_OPAQUE ? TILE_MATERIAL_LIQUID_OPAQUE : TILE_MATERIAL_LIQUID_TRANSPARENT; } } @@ -930,7 +944,8 @@ void ContentFeatures::updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc if (param_type_2 == CPT2_COLOR || param_type_2 == CPT2_COLORED_FACEDIR || - param_type_2 == CPT2_COLORED_WALLMOUNTED) + param_type_2 == CPT2_COLORED_WALLMOUNTED || + param_type_2 == CPT2_COLORED_DEGROTATE) palette = tsrc->getPalette(palette_name); if (drawtype == NDT_MESH && !mesh.empty()) { @@ -1436,9 +1451,7 @@ void NodeDefManager::applyTextureOverrides(const std::vector<TextureOverride> &o } } -void NodeDefManager::updateTextures(IGameDef *gamedef, - void (*progress_callback)(void *progress_args, u32 progress, u32 max_progress), - void *progress_callback_args) +void NodeDefManager::updateTextures(IGameDef *gamedef, void *progress_callback_args) { #ifndef SERVER infostream << "NodeDefManager::updateTextures(): Updating " @@ -1447,8 +1460,8 @@ void NodeDefManager::updateTextures(IGameDef *gamedef, Client *client = (Client *)gamedef; ITextureSource *tsrc = client->tsrc(); IShaderSource *shdsrc = client->getShaderSource(); - scene::IMeshManipulator *meshmanip = - RenderingEngine::get_scene_manager()->getMeshManipulator(); + auto smgr = client->getSceneManager(); + scene::IMeshManipulator *meshmanip = smgr->getMeshManipulator(); TextureSettings tsettings; tsettings.readSettings(); @@ -1457,7 +1470,7 @@ void NodeDefManager::updateTextures(IGameDef *gamedef, for (u32 i = 0; i < size; i++) { ContentFeatures *f = &(m_content_features[i]); f->updateTextures(tsrc, shdsrc, meshmanip, client, tsettings); - progress_callback(progress_callback_args, i, size); + client->showUpdateProgressTexture(progress_callback_args, i, size); } #endif } @@ -1545,10 +1558,10 @@ void NodeDefManager::deSerialize(std::istream &is) } -void NodeDefManager::addNameIdMapping(content_t i, std::string name) +void NodeDefManager::addNameIdMapping(content_t i, const std::string &name) { m_name_id_mapping.set(i, name); - m_name_id_mapping_with_aliases.insert(std::make_pair(name, i)); + m_name_id_mapping_with_aliases.emplace(name, i); } @@ -1612,7 +1625,7 @@ static void removeDupes(std::vector<content_t> &list) void NodeDefManager::resolveCrossrefs() { for (ContentFeatures &f : m_content_features) { - if (f.liquid_type != LIQUID_NONE) { + if (f.liquid_type != LIQUID_NONE || f.drawtype == NDT_LIQUID || f.drawtype == NDT_FLOWINGLIQUID) { f.liquid_alternative_flowing_id = getId(f.liquid_alternative_flowing); f.liquid_alternative_source_id = getId(f.liquid_alternative_source); continue; @@ -1677,8 +1690,7 @@ bool NodeDefManager::nodeboxConnects(MapNode from, MapNode to, NodeResolver::NodeResolver() { - m_nodenames.reserve(16); - m_nnlistsizes.reserve(4); + reset(); } @@ -1781,3 +1793,16 @@ bool NodeResolver::getIdsFromNrBacklog(std::vector<content_t> *result_out, return success; } + +void NodeResolver::reset(bool resolve_done) +{ + m_nodenames.clear(); + m_nodenames_idx = 0; + m_nnlistsizes.clear(); + m_nnlistsizes_idx = 0; + + m_resolve_done = resolve_done; + + m_nodenames.reserve(16); + m_nnlistsizes.reserve(4); +} diff --git a/src/nodedef.h b/src/nodedef.h index 66c21cc07..8a6d88071 100644 --- a/src/nodedef.h +++ b/src/nodedef.h @@ -44,6 +44,9 @@ class ITextureSource; class IShaderSource; class IGameDef; class NodeResolver; +#if BUILD_UNITTESTS +class TestSchematic; +#endif enum ContentParamType { @@ -64,7 +67,7 @@ enum ContentParamType2 CPT2_WALLMOUNTED, // Block level like FLOWINGLIQUID CPT2_LEVELED, - // 2D rotation for things like plants + // 2D rotation CPT2_DEGROTATE, // Mesh options for plants CPT2_MESHOPTIONS, @@ -76,6 +79,8 @@ enum ContentParamType2 CPT2_COLORED_WALLMOUNTED, // Glasslike framed drawtype internal liquid level, param2 values 0 to 63 CPT2_GLASSLIKE_LIQUID_LEVEL, + // 3 bits of palette index, then degrotate + CPT2_COLORED_DEGROTATE, }; enum LiquidType @@ -231,6 +236,14 @@ enum AlignStyle : u8 { ALIGN_STYLE_USER_DEFINED, }; +enum AlphaMode : u8 { + ALPHAMODE_BLEND, + ALPHAMODE_CLIP, + ALPHAMODE_OPAQUE, + ALPHAMODE_LEGACY_COMPAT, /* means either opaque or clip */ +}; + + /* Stand-alone definition of a TileSpec (basically a server-side TileSpec) */ @@ -315,9 +328,7 @@ struct ContentFeatures // These will be drawn over the base tiles. TileDef tiledef_overlay[6]; TileDef tiledef_special[CF_SPECIAL_COUNT]; // eg. flowing liquid - // If 255, the node is opaque. - // Otherwise it uses texture alpha. - u8 alpha; + AlphaMode alpha; // The color of the node. video::SColor color; std::string palette_name; @@ -418,29 +429,27 @@ struct ContentFeatures void serialize(std::ostream &os, u16 protocol_version) const; void deSerialize(std::istream &is); - /*! - * Since vertex alpha is no longer supported, this method - * adds opacity directly to the texture pixels. - * - * \param tiles array of the tile definitions. - * \param length length of tiles - */ - void correctAlpha(TileDef *tiles, int length); - -#ifndef SERVER - /* - * Checks if any tile texture has any transparent pixels. - * Prints a warning and returns true if that is the case, false otherwise. - * This is supposed to be used for use_texture_alpha backwards compatibility. - */ - bool textureAlphaCheck(ITextureSource *tsrc, const TileDef *tiles, - int length); -#endif - - /* Some handy methods */ + void setDefaultAlphaMode() + { + switch (drawtype) { + case NDT_NORMAL: + case NDT_LIQUID: + case NDT_FLOWINGLIQUID: + alpha = ALPHAMODE_OPAQUE; + break; + case NDT_NODEBOX: + case NDT_MESH: + alpha = ALPHAMODE_LEGACY_COMPAT; // this should eventually be OPAQUE + break; + default: + alpha = ALPHAMODE_CLIP; + break; + } + } + bool needsBackfaceCulling() const { switch (drawtype) { @@ -474,6 +483,21 @@ struct ContentFeatures void updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc, scene::IMeshManipulator *meshmanip, Client *client, const TextureSettings &tsettings); #endif + +private: +#ifndef SERVER + /* + * Checks if any tile texture has any transparent pixels. + * Prints a warning and returns true if that is the case, false otherwise. + * This is supposed to be used for use_texture_alpha backwards compatibility. + */ + bool textureAlphaCheck(ITextureSource *tsrc, const TileDef *tiles, + int length); +#endif + + void setAlphaFromLegacy(u8 legacy_alpha); + + u8 getAlphaForLegacy() const; }; /*! @@ -636,9 +660,7 @@ public: * total ContentFeatures. * @param progress_cbk_args passed to the callback function */ - void updateTextures(IGameDef *gamedef, - void (*progress_cbk)(void *progress_args, u32 progress, u32 max_progress), - void *progress_cbk_args); + void updateTextures(IGameDef *gamedef, void *progress_cbk_args); /*! * Writes the content of this manager to the given output stream. @@ -701,7 +723,7 @@ private: * @param i a content ID * @param name a node name */ - void addNameIdMapping(content_t i, std::string name); + void addNameIdMapping(content_t i, const std::string &name); /*! * Removes a content ID from all groups. @@ -770,10 +792,13 @@ private: NodeDefManager *createNodeDefManager(); +// NodeResolver: Queue for node names which are then translated +// to content_t after the NodeDefManager was initialized class NodeResolver { public: NodeResolver(); virtual ~NodeResolver(); + // Callback which is run as soon NodeDefManager is ready virtual void resolveNodeNames() = 0; // required because this class is used as mixin for ObjDef @@ -785,12 +810,31 @@ public: bool getIdsFromNrBacklog(std::vector<content_t> *result_out, bool all_required = false, content_t c_fallback = CONTENT_IGNORE); - void nodeResolveInternal(); + inline bool isResolveDone() const { return m_resolve_done; } + void reset(bool resolve_done = false); - u32 m_nodenames_idx = 0; - u32 m_nnlistsizes_idx = 0; + // Vector containing all node names in the resolve "queue" std::vector<std::string> m_nodenames; + // Specifies the "set size" of node names which are to be processed + // this is used for getIdsFromNrBacklog + // TODO: replace or remove std::vector<size_t> m_nnlistsizes; + +protected: + friend class NodeDefManager; // m_ndef + const NodeDefManager *m_ndef = nullptr; + // Index of the next "m_nodenames" entry to resolve + u32 m_nodenames_idx = 0; + +private: +#if BUILD_UNITTESTS + // Unittest requires access to m_resolve_done + friend class TestSchematic; +#endif + void nodeResolveInternal(); + + // Index of the next "m_nnlistsizes" entry to process + u32 m_nnlistsizes_idx = 0; bool m_resolve_done = false; }; diff --git a/src/nodemetadata.cpp b/src/nodemetadata.cpp index 6447c8785..f98732385 100644 --- a/src/nodemetadata.cpp +++ b/src/nodemetadata.cpp @@ -206,10 +206,9 @@ NodeMetadataList::~NodeMetadataList() std::vector<v3s16> NodeMetadataList::getAllKeys() { std::vector<v3s16> keys; - - NodeMetadataMap::const_iterator it; - for (it = m_data.begin(); it != m_data.end(); ++it) - keys.push_back(it->first); + keys.reserve(m_data.size()); + for (const auto &it : m_data) + keys.push_back(it.first); return keys; } @@ -218,7 +217,7 @@ NodeMetadata *NodeMetadataList::get(v3s16 p) { NodeMetadataMap::const_iterator n = m_data.find(p); if (n == m_data.end()) - return NULL; + return nullptr; return n->second; } @@ -235,7 +234,7 @@ void NodeMetadataList::remove(v3s16 p) void NodeMetadataList::set(v3s16 p, NodeMetadata *d) { remove(p); - m_data.insert(std::make_pair(p, d)); + m_data.emplace(p, d); } void NodeMetadataList::clear() @@ -251,9 +250,8 @@ void NodeMetadataList::clear() int NodeMetadataList::countNonEmpty() const { int n = 0; - NodeMetadataMap::const_iterator it; - for (it = m_data.begin(); it != m_data.end(); ++it) { - if (!it->second->empty()) + for (const auto &it : m_data) { + if (!it.second->empty()) n++; } return n; diff --git a/src/noise.cpp b/src/noise.cpp index e16564b05..a10efa3c4 100644 --- a/src/noise.cpp +++ b/src/noise.cpp @@ -369,7 +369,7 @@ float contour(float v) ///////////////////////// [ New noise ] //////////////////////////// -float NoisePerlin2D(NoiseParams *np, float x, float y, s32 seed) +float NoisePerlin2D(const NoiseParams *np, float x, float y, s32 seed) { float a = 0; float f = 1.0; @@ -395,7 +395,7 @@ float NoisePerlin2D(NoiseParams *np, float x, float y, s32 seed) } -float NoisePerlin3D(NoiseParams *np, float x, float y, float z, s32 seed) +float NoisePerlin3D(const NoiseParams *np, float x, float y, float z, s32 seed) { float a = 0; float f = 1.0; @@ -422,7 +422,7 @@ float NoisePerlin3D(NoiseParams *np, float x, float y, float z, s32 seed) } -Noise::Noise(NoiseParams *np_, s32 seed, u32 sx, u32 sy, u32 sz) +Noise::Noise(const NoiseParams *np_, s32 seed, u32 sx, u32 sy, u32 sz) { np = *np_; this->seed = seed; diff --git a/src/noise.h b/src/noise.h index 613879890..854781731 100644 --- a/src/noise.h +++ b/src/noise.h @@ -146,7 +146,7 @@ public: float *persist_buf = nullptr; float *result = nullptr; - Noise(NoiseParams *np, s32 seed, u32 sx, u32 sy, u32 sz=1); + Noise(const NoiseParams *np, s32 seed, u32 sx, u32 sy, u32 sz=1); ~Noise(); void setSize(u32 sx, u32 sy, u32 sz=1); @@ -192,8 +192,8 @@ private: }; -float NoisePerlin2D(NoiseParams *np, float x, float y, s32 seed); -float NoisePerlin3D(NoiseParams *np, float x, float y, float z, s32 seed); +float NoisePerlin2D(const NoiseParams *np, float x, float y, s32 seed); +float NoisePerlin3D(const NoiseParams *np, float x, float y, float z, s32 seed); inline float NoisePerlin2D_PO(NoiseParams *np, float x, float xoff, float y, float yoff, s32 seed) diff --git a/src/object_properties.cpp b/src/object_properties.cpp index f31773060..2eebc27d6 100644 --- a/src/object_properties.cpp +++ b/src/object_properties.cpp @@ -24,6 +24,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/basic_macros.h" #include <sstream> +static const video::SColor NULL_BGCOLOR{0, 1, 1, 1}; + ObjectProperties::ObjectProperties() { textures.emplace_back("unknown_object.png"); @@ -62,6 +64,13 @@ std::string ObjectProperties::dump() os << ", nametag=" << nametag; os << ", nametag_color=" << "\"" << nametag_color.getAlpha() << "," << nametag_color.getRed() << "," << nametag_color.getGreen() << "," << nametag_color.getBlue() << "\" "; + + if (nametag_bgcolor) + os << ", nametag_bgcolor=" << "\"" << nametag_color.getAlpha() << "," << nametag_color.getRed() + << "," << nametag_color.getGreen() << "," << nametag_color.getBlue() << "\" "; + else + os << ", nametag_bgcolor=null "; + os << ", selectionbox=" << PP(selectionbox.MinEdge) << "," << PP(selectionbox.MaxEdge); os << ", pointable=" << pointable; os << ", static_save=" << static_save; @@ -121,6 +130,13 @@ void ObjectProperties::serialize(std::ostream &os) const writeU8(os, shaded); writeU8(os, show_on_minimap); + if (!nametag_bgcolor) + writeARGB8(os, NULL_BGCOLOR); + else if (nametag_bgcolor.value().getAlpha() == 0) + writeARGB8(os, video::SColor(0, 0, 0, 0)); + else + writeARGB8(os, nametag_bgcolor.value()); + // Add stuff only at the bottom. // Never remove anything, because we don't want new versions of this } @@ -182,5 +198,11 @@ void ObjectProperties::deSerialize(std::istream &is) if (is.eof()) return; show_on_minimap = tmp; + + auto bgcolor = readARGB8(is); + if (bgcolor != NULL_BGCOLOR) + nametag_bgcolor = bgcolor; + else + nametag_bgcolor = nullopt; } catch (SerializationError &e) {} } diff --git a/src/object_properties.h b/src/object_properties.h index adb483527..db28eebfd 100644 --- a/src/object_properties.h +++ b/src/object_properties.h @@ -24,6 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <iostream> #include <map> #include <vector> +#include "util/Optional.h" struct ObjectProperties { @@ -53,6 +54,7 @@ struct ObjectProperties s8 glow = 0; std::string nametag = ""; video::SColor nametag_color = video::SColor(255, 255, 255, 255); + Optional<video::SColor> nametag_bgcolor = nullopt; f32 automatic_face_movement_max_rotation_per_sec = -1.0f; std::string infotext; //! For dropped items, this contains item information. diff --git a/src/pathfinder.cpp b/src/pathfinder.cpp index 3f0b98c10..c45ce9158 100644 --- a/src/pathfinder.cpp +++ b/src/pathfinder.cpp @@ -157,9 +157,8 @@ public: ArrayGridNodeContainer(Pathfinder *pathf, v3s16 dimensions); virtual PathGridnode &access(v3s16 p); -private: - v3s16 m_dimensions; +private: int m_x_stride; int m_y_stride; std::vector<PathGridnode> m_nodes_array; @@ -306,8 +305,6 @@ private: int m_max_index_y = 0; /**< max index of search area in y direction */ int m_max_index_z = 0; /**< max index of search area in z direction */ - - int m_searchdistance = 0; /**< max distance to search in each direction */ int m_maxdrop = 0; /**< maximum number of blocks a path may drop */ int m_maxjump = 0; /**< maximum number of blocks a path may jump */ int m_min_target_distance = 0; /**< current smalest path to target */ @@ -619,7 +616,6 @@ std::vector<v3s16> Pathfinder::getPath(v3s16 source, std::vector<v3s16> retval; //initialization - m_searchdistance = searchdistance; m_maxjump = max_jump; m_maxdrop = max_drop; m_start = source; @@ -1432,7 +1428,7 @@ std::string Pathfinder::dirToName(PathDirections dir) } /******************************************************************************/ -void Pathfinder::printPath(std::vector<v3s16> path) +void Pathfinder::printPath(const std::vector<v3s16> &path) { unsigned int current = 0; for (std::vector<v3s16>::iterator i = path.begin(); diff --git a/src/porting.h b/src/porting.h index e4ebe36fd..93932e1d9 100644 --- a/src/porting.h +++ b/src/porting.h @@ -234,21 +234,21 @@ inline u64 getTimeMs() { struct timespec ts; os_get_clock(&ts); - return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; + return ((u64) ts.tv_sec) * 1000LL + ((u64) ts.tv_nsec) / 1000000LL; } inline u64 getTimeUs() { struct timespec ts; os_get_clock(&ts); - return ts.tv_sec * 1000000 + ts.tv_nsec / 1000; + return ((u64) ts.tv_sec) * 1000000LL + ((u64) ts.tv_nsec) / 1000LL; } inline u64 getTimeNs() { struct timespec ts; os_get_clock(&ts); - return ts.tv_sec * 1000000000 + ts.tv_nsec; + return ((u64) ts.tv_sec) * 1000000000LL + ((u64) ts.tv_nsec); } #endif diff --git a/src/remoteplayer.cpp b/src/remoteplayer.cpp index bef60c792..925ad001b 100644 --- a/src/remoteplayer.cpp +++ b/src/remoteplayer.cpp @@ -83,122 +83,6 @@ RemotePlayer::RemotePlayer(const char *name, IItemDefManager *idef): m_star_params = sky_defaults.getStarDefaults(); } -void RemotePlayer::serializeExtraAttributes(std::string &output) -{ - assert(m_sao); - Json::Value json_root; - - const StringMap &attrs = m_sao->getMeta().getStrings(); - for (const auto &attr : attrs) { - json_root[attr.first] = attr.second; - } - - output = fastWriteJson(json_root); -} - - -void RemotePlayer::deSerialize(std::istream &is, const std::string &playername, - PlayerSAO *sao) -{ - Settings args; - - if (!args.parseConfigLines(is, "PlayerArgsEnd")) { - throw SerializationError("PlayerArgsEnd of player " + playername + " not found!"); - } - - m_dirty = true; - //args.getS32("version"); // Version field value not used - const std::string &name = args.get("name"); - strlcpy(m_name, name.c_str(), PLAYERNAME_SIZE); - - if (sao) { - try { - sao->setHPRaw(args.getU16("hp")); - } catch(SettingNotFoundException &e) { - sao->setHPRaw(PLAYER_MAX_HP_DEFAULT); - } - - try { - sao->setBasePosition(args.getV3F("position")); - } catch (SettingNotFoundException &e) {} - - try { - sao->setLookPitch(args.getFloat("pitch")); - } catch (SettingNotFoundException &e) {} - try { - sao->setPlayerYaw(args.getFloat("yaw")); - } catch (SettingNotFoundException &e) {} - - try { - sao->setBreath(args.getU16("breath"), false); - } catch (SettingNotFoundException &e) {} - - try { - const std::string &extended_attributes = args.get("extended_attributes"); - std::istringstream iss(extended_attributes); - Json::CharReaderBuilder builder; - builder.settings_["collectComments"] = false; - std::string errs; - - Json::Value attr_root; - Json::parseFromStream(builder, iss, &attr_root, &errs); - - const Json::Value::Members attr_list = attr_root.getMemberNames(); - for (const auto &it : attr_list) { - Json::Value attr_value = attr_root[it]; - sao->getMeta().setString(it, attr_value.asString()); - } - sao->getMeta().setModified(false); - } catch (SettingNotFoundException &e) {} - } - - try { - inventory.deSerialize(is); - } catch (SerializationError &e) { - errorstream << "Failed to deserialize player inventory. player_name=" - << name << " " << e.what() << std::endl; - } - - if (!inventory.getList("craftpreview") && inventory.getList("craftresult")) { - // Convert players without craftpreview - inventory.addList("craftpreview", 1); - - bool craftresult_is_preview = true; - if(args.exists("craftresult_is_preview")) - craftresult_is_preview = args.getBool("craftresult_is_preview"); - if(craftresult_is_preview) - { - // Clear craftresult - inventory.getList("craftresult")->changeItem(0, ItemStack()); - } - } -} - -void RemotePlayer::serialize(std::ostream &os) -{ - // Utilize a Settings object for storing values - Settings args; - args.setS32("version", 1); - args.set("name", m_name); - - // This should not happen - assert(m_sao); - args.setU16("hp", m_sao->getHP()); - args.setV3F("position", m_sao->getBasePosition()); - args.setFloat("pitch", m_sao->getLookPitch()); - args.setFloat("yaw", m_sao->getRotation().Y); - args.setU16("breath", m_sao->getBreath()); - - std::string extended_attrs; - serializeExtraAttributes(extended_attrs); - args.set("extended_attributes", extended_attrs); - - args.writeLines(os); - - os<<"PlayerArgsEnd\n"; - - inventory.serialize(os); -} const RemotePlayerChatResult RemotePlayer::canSendChatMessage() { diff --git a/src/remoteplayer.h b/src/remoteplayer.h index e4209c54f..8d086fc5a 100644 --- a/src/remoteplayer.h +++ b/src/remoteplayer.h @@ -44,8 +44,6 @@ public: RemotePlayer(const char *name, IItemDefManager *idef); virtual ~RemotePlayer() = default; - void deSerialize(std::istream &is, const std::string &playername, PlayerSAO *sao); - PlayerSAO *getPlayerSAO() { return m_sao; } void setPlayerSAO(PlayerSAO *sao) { m_sao = sao; } @@ -142,14 +140,6 @@ public: void onSuccessfulSave(); private: - /* - serialize() writes a bunch of text that can contain - any characters except a '\0', and such an ending that - deSerialize stops reading exactly at the right point. - */ - void serialize(std::ostream &os); - void serializeExtraAttributes(std::string &output); - PlayerSAO *m_sao = nullptr; bool m_dirty = false; diff --git a/src/script/common/c_content.cpp b/src/script/common/c_content.cpp index 72361bdb5..897ca2862 100644 --- a/src/script/common/c_content.cpp +++ b/src/script/common/c_content.cpp @@ -84,9 +84,6 @@ void read_item_definition(lua_State* L, int index, getboolfield(L, index, "liquids_pointable", def.liquids_pointable); - warn_if_field_exists(L, index, "tool_digging_properties", - "Obsolete; use tool_capabilities"); - lua_getfield(L, index, "tool_capabilities"); if(lua_istable(L, -1)){ def.tool_capabilities = new ToolCapabilities( @@ -123,6 +120,8 @@ void read_item_definition(lua_State* L, int index, // "" = no prediction getstringfield(L, index, "node_placement_prediction", def.node_placement_prediction); + + getintfield(L, index, "place_param2", def.place_param2); } /******************************************************************************/ @@ -144,8 +143,10 @@ void push_item_definition_full(lua_State *L, const ItemDefinition &i) lua_setfield(L, -2, "name"); lua_pushstring(L, i.description.c_str()); lua_setfield(L, -2, "description"); - lua_pushstring(L, i.short_description.c_str()); - lua_setfield(L, -2, "short_description"); + if (!i.short_description.empty()) { + lua_pushstring(L, i.short_description.c_str()); + lua_setfield(L, -2, "short_description"); + } lua_pushstring(L, type.c_str()); lua_setfield(L, -2, "type"); lua_pushstring(L, i.inventory_image.c_str()); @@ -199,7 +200,7 @@ void read_object_properties(lua_State *L, int index, if (getintfield(L, -1, "hp_max", hp_max)) { prop->hp_max = (u16)rangelim(hp_max, 0, U16_MAX); - if (prop->hp_max < sao->getHP()) { + if (sao && prop->hp_max < sao->getHP()) { PlayerHPChangeReason reason(PlayerHPChangeReason::SET_HP); sao->setHP(prop->hp_max, reason); if (sao->getType() == ACTIVEOBJECT_TYPE_PLAYER) @@ -208,7 +209,7 @@ void read_object_properties(lua_State *L, int index, } if (getintfield(L, -1, "breath_max", prop->breath_max)) { - if (sao->getType() == ACTIVEOBJECT_TYPE_PLAYER) { + if (sao && sao->getType() == ACTIVEOBJECT_TYPE_PLAYER) { PlayerSAO *player = (PlayerSAO *)sao; if (prop->breath_max < player->getBreath()) player->setBreath(prop->breath_max); @@ -316,6 +317,17 @@ void read_object_properties(lua_State *L, int index, prop->nametag_color = color; } lua_pop(L, 1); + lua_getfield(L, -1, "nametag_bgcolor"); + if (!lua_isnil(L, -1)) { + if (lua_toboolean(L, -1)) { + video::SColor color; + if (read_color(L, -1, &color)) + prop->nametag_bgcolor = color; + } else { + prop->nametag_bgcolor = nullopt; + } + } + lua_pop(L, 1); lua_getfield(L, -1, "automatic_face_movement_max_rotation_per_sec"); if (lua_isnumber(L, -1)) { @@ -407,6 +419,13 @@ void push_object_properties(lua_State *L, ObjectProperties *prop) lua_setfield(L, -2, "nametag"); push_ARGB8(L, prop->nametag_color); lua_setfield(L, -2, "nametag_color"); + if (prop->nametag_bgcolor) { + push_ARGB8(L, prop->nametag_bgcolor.value()); + lua_setfield(L, -2, "nametag_bgcolor"); + } else { + lua_pushboolean(L, false); + lua_setfield(L, -2, "nametag_bgcolor"); + } lua_pushnumber(L, prop->automatic_face_movement_max_rotation_per_sec); lua_setfield(L, -2, "automatic_face_movement_max_rotation_per_sec"); lua_pushlstring(L, prop->infotext.c_str(), prop->infotext.size()); @@ -497,6 +516,35 @@ TileDef read_tiledef(lua_State *L, int index, u8 drawtype) } /******************************************************************************/ +void push_tiledef(lua_State *L, TileDef tiledef) +{ + lua_newtable(L); + setstringfield(L, -1, "name", tiledef.name); + setboolfield(L, -1, "backface_culling", tiledef.backface_culling); + setboolfield(L, -1, "tileable_horizontal", tiledef.tileable_horizontal); + setboolfield(L, -1, "tileable_vertical", tiledef.tileable_vertical); + std::string align_style; + switch (tiledef.align_style) { + case ALIGN_STYLE_USER_DEFINED: + align_style = "user"; + break; + case ALIGN_STYLE_WORLD: + align_style = "world"; + break; + default: + align_style = "node"; + } + setstringfield(L, -1, "align_style", align_style); + setintfield(L, -1, "scale", tiledef.scale); + if (tiledef.has_color) { + push_ARGB8(L, tiledef.color); + lua_setfield(L, -2, "color"); + } + push_animation_definition(L, tiledef.animation); + lua_setfield(L, -2, "animation"); +} + +/******************************************************************************/ void read_content_features(lua_State *L, ContentFeatures &f, int index) { if(index < 0) @@ -624,22 +672,39 @@ void read_content_features(lua_State *L, ContentFeatures &f, int index) } lua_pop(L, 1); - f.alpha = getintfield_default(L, index, "alpha", 255); + /* alpha & use_texture_alpha */ + // This is a bit complicated due to compatibility + + f.setDefaultAlphaMode(); + + warn_if_field_exists(L, index, "alpha", + "Obsolete, only limited compatibility provided; " + "replaced by \"use_texture_alpha\""); + if (getintfield_default(L, index, "alpha", 255) != 255) + f.alpha = ALPHAMODE_BLEND; + + lua_getfield(L, index, "use_texture_alpha"); + if (lua_isboolean(L, -1)) { + warn_if_field_exists(L, index, "use_texture_alpha", + "Boolean values are deprecated; use the new choices"); + if (lua_toboolean(L, -1)) + f.alpha = (f.drawtype == NDT_NORMAL) ? ALPHAMODE_CLIP : ALPHAMODE_BLEND; + } else if (check_field_or_nil(L, -1, LUA_TSTRING, "use_texture_alpha")) { + int result = f.alpha; + string_to_enum(ScriptApiNode::es_TextureAlphaMode, result, + std::string(lua_tostring(L, -1))); + f.alpha = static_cast<enum AlphaMode>(result); + } + lua_pop(L, 1); - bool usealpha = getboolfield_default(L, index, - "use_texture_alpha", false); - if (usealpha) - f.alpha = 0; + /* Other stuff */ - // Read node color. lua_getfield(L, index, "color"); read_color(L, -1, &f.color); lua_pop(L, 1); getstringfield(L, index, "palette", f.palette_name); - /* Other stuff */ - lua_getfield(L, index, "post_effect_color"); read_color(L, -1, &f.post_effect_color); lua_pop(L, 1); @@ -652,24 +717,11 @@ void read_content_features(lua_State *L, ContentFeatures &f, int index) if (!f.palette_name.empty() && !(f.param_type_2 == CPT2_COLOR || f.param_type_2 == CPT2_COLORED_FACEDIR || - f.param_type_2 == CPT2_COLORED_WALLMOUNTED)) + f.param_type_2 == CPT2_COLORED_WALLMOUNTED || + f.param_type_2 == CPT2_COLORED_DEGROTATE)) warningstream << "Node " << f.name.c_str() << " has a palette, but not a suitable paramtype2." << std::endl; - // Warn about some obsolete fields - warn_if_field_exists(L, index, "wall_mounted", - "Obsolete; use paramtype2 = 'wallmounted'"); - warn_if_field_exists(L, index, "light_propagates", - "Obsolete; determined from paramtype"); - warn_if_field_exists(L, index, "dug_item", - "Obsolete; use 'drop' field"); - warn_if_field_exists(L, index, "extra_dug_item", - "Obsolete; use 'drop' field"); - warn_if_field_exists(L, index, "extra_dug_item_rarity", - "Obsolete; use 'drop' field"); - warn_if_field_exists(L, index, "metadata_name", - "Obsolete; use on_add and metadata callbacks"); - // True for all ground-like things like stone and mud, false for eg. trees getboolfield(L, index, "is_ground_content", f.is_ground_content); f.light_propagates = (f.param_type == CPT_LIGHT); @@ -813,9 +865,32 @@ void push_content_features(lua_State *L, const ContentFeatures &c) std::string drawtype(ScriptApiNode::es_DrawType[(int)c.drawtype].str); std::string liquid_type(ScriptApiNode::es_LiquidType[(int)c.liquid_type].str); - /* Missing "tiles" because I don't see a usecase (at least not yet). */ + lua_newtable(L); + + // tiles + lua_newtable(L); + for (int i = 0; i < 6; i++) { + push_tiledef(L, c.tiledef[i]); + lua_rawseti(L, -2, i + 1); + } + lua_setfield(L, -2, "tiles"); + + // overlay_tiles + lua_newtable(L); + for (int i = 0; i < 6; i++) { + push_tiledef(L, c.tiledef_overlay[i]); + lua_rawseti(L, -2, i + 1); + } + lua_setfield(L, -2, "overlay_tiles"); + // special_tiles lua_newtable(L); + for (int i = 0; i < CF_SPECIAL_COUNT; i++) { + push_tiledef(L, c.tiledef_special[i]); + lua_rawseti(L, -2, i + 1); + } + lua_setfield(L, -2, "special_tiles"); + lua_pushboolean(L, c.has_on_construct); lua_setfield(L, -2, "has_on_construct"); lua_pushboolean(L, c.has_on_destruct); @@ -1313,6 +1388,8 @@ void push_tool_capabilities(lua_State *L, /******************************************************************************/ void push_inventory(lua_State *L, Inventory *inventory) { + if (! inventory) + throw SerializationError("Attempt to push nonexistant inventory"); std::vector<const InventoryList*> lists = inventory->getLists(); std::vector<const InventoryList*>::iterator iter = lists.begin(); lua_createtable(L, 0, lists.size()); @@ -1862,14 +1939,7 @@ void push_pointed_thing(lua_State *L, const PointedThing &pointed, bool csm, } else if (pointed.type == POINTEDTHING_OBJECT) { lua_pushstring(L, "object"); lua_setfield(L, -2, "type"); - if (csm) { -#ifndef SERVER - ClientObjectRef::create(L, pointed.object_id); -#endif - } else { - push_objectRef(L, pointed.object_id); - } - + push_objectRef(L, pointed.object_id); lua_setfield(L, -2, "ref"); } else { lua_pushstring(L, "nothing"); @@ -2129,7 +2199,7 @@ void push_collision_move_result(lua_State *L, const collisionMoveResult &res) void push_physics_override(lua_State *L, float speed, float jump, float gravity, bool sneak, bool sneak_glitch, bool new_move) { lua_createtable(L, 0, 6); - + lua_pushnumber(L, speed); lua_setfield(L, -2, "speed"); diff --git a/src/script/common/c_content.h b/src/script/common/c_content.h index 10b77a116..dc8f19ef3 100644 --- a/src/script/common/c_content.h +++ b/src/script/common/c_content.h @@ -39,7 +39,9 @@ extern "C" { #include "itemgroup.h" #include "itemdef.h" #include "c_types.h" -#include "hud.h" +// We do a explicit path include because by default c_content.h include src/client/hud.h +// prior to the src/hud.h, which is not good on server only build +#include "../../hud.h" namespace Json { class Value; } diff --git a/src/script/common/helper.cpp b/src/script/common/helper.cpp index 488144790..fbf24e1b7 100644 --- a/src/script/common/helper.cpp +++ b/src/script/common/helper.cpp @@ -50,22 +50,26 @@ bool LuaHelper::isNaN(lua_State *L, int idx) /* * Read template functions */ -template <> bool LuaHelper::readParam(lua_State *L, int index) +template <> +bool LuaHelper::readParam(lua_State *L, int index) { return lua_toboolean(L, index) != 0; } -template <> s16 LuaHelper::readParam(lua_State *L, int index) +template <> +s16 LuaHelper::readParam(lua_State *L, int index) { return lua_tonumber(L, index); } -template <> int LuaHelper::readParam(lua_State *L, int index) +template <> +int LuaHelper::readParam(lua_State *L, int index) { return luaL_checkint(L, index); } -template <> float LuaHelper::readParam(lua_State *L, int index) +template <> +float LuaHelper::readParam(lua_State *L, int index) { if (isNaN(L, index)) throw LuaError("NaN value is not allowed."); @@ -73,7 +77,8 @@ template <> float LuaHelper::readParam(lua_State *L, int index) return (float)luaL_checknumber(L, index); } -template <> v2s16 LuaHelper::readParam(lua_State *L, int index) +template <> +v2s16 LuaHelper::readParam(lua_State *L, int index) { v2s16 p; CHECK_POS_TAB(index); @@ -88,7 +93,8 @@ template <> v2s16 LuaHelper::readParam(lua_State *L, int index) return p; } -template <> v2f LuaHelper::readParam(lua_State *L, int index) +template <> +v2f LuaHelper::readParam(lua_State *L, int index) { v2f p; CHECK_POS_TAB(index); @@ -103,7 +109,8 @@ template <> v2f LuaHelper::readParam(lua_State *L, int index) return p; } -template <> v3f LuaHelper::readParam(lua_State *L, int index) +template <> +v3f LuaHelper::readParam(lua_State *L, int index) { v3f p; CHECK_POS_TAB(index); @@ -122,7 +129,8 @@ template <> v3f LuaHelper::readParam(lua_State *L, int index) return p; } -template <> std::string LuaHelper::readParam(lua_State *L, int index) +template <> +std::string LuaHelper::readParam(lua_State *L, int index) { size_t length; std::string result; diff --git a/src/script/common/helper.h b/src/script/common/helper.h index 7a794dc9b..6491e73cf 100644 --- a/src/script/common/helper.h +++ b/src/script/common/helper.h @@ -38,7 +38,8 @@ protected: * @param index Lua Index to read * @return read value from Lua */ - template <typename T> static T readParam(lua_State *L, int index); + template <typename T> + static T readParam(lua_State *L, int index); /** * Read a value using a template type T from Lua State L and index diff --git a/src/script/cpp_api/s_async.cpp b/src/script/cpp_api/s_async.cpp index 5f1f9297e..0619b32c0 100644 --- a/src/script/cpp_api/s_async.cpp +++ b/src/script/cpp_api/s_async.cpp @@ -158,35 +158,6 @@ void AsyncEngine::step(lua_State *L) } /******************************************************************************/ -void AsyncEngine::pushFinishedJobs(lua_State* L) { - // Result Table - MutexAutoLock l(resultQueueMutex); - - unsigned int index = 1; - lua_createtable(L, resultQueue.size(), 0); - int top = lua_gettop(L); - - while (!resultQueue.empty()) { - LuaJobInfo jobDone = resultQueue.front(); - resultQueue.pop_front(); - - lua_createtable(L, 0, 2); // Pre-allocate space for two map fields - int top_lvl2 = lua_gettop(L); - - lua_pushstring(L, "jobid"); - lua_pushnumber(L, jobDone.id); - lua_settable(L, top_lvl2); - - lua_pushstring(L, "retval"); - lua_pushlstring(L, jobDone.serializedResult.data(), - jobDone.serializedResult.size()); - lua_settable(L, top_lvl2); - - lua_rawseti(L, top, index++); - } -} - -/******************************************************************************/ void AsyncEngine::prepareEnvironment(lua_State* L, int top) { for (StateInitializer &stateInitializer : stateInitializers) { diff --git a/src/script/cpp_api/s_async.h b/src/script/cpp_api/s_async.h index b1f4bf45f..99a4f891c 100644 --- a/src/script/cpp_api/s_async.h +++ b/src/script/cpp_api/s_async.h @@ -98,12 +98,6 @@ public: */ void step(lua_State *L); - /** - * Push a list of finished jobs onto the stack - * @param L The Lua stack - */ - void pushFinishedJobs(lua_State *L); - protected: /** * Get a Job from queue to be processed diff --git a/src/script/cpp_api/s_base.cpp b/src/script/cpp_api/s_base.cpp index 1d62d8b65..5711ccbfd 100644 --- a/src/script/cpp_api/s_base.cpp +++ b/src/script/cpp_api/s_base.cpp @@ -21,6 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "cpp_api/s_internal.h" #include "cpp_api/s_security.h" #include "lua_api/l_object.h" +#include "lua_api/l_clientobject.h" #include "common/c_converter.h" #include "server/player_sao.h" #include "filesys.h" @@ -354,13 +355,18 @@ void ScriptApiBase::setOriginFromTableRaw(int index, const char *fxn) * since we lose control over the ref and the contained pointer. */ -void ScriptApiBase::addObjectReference(ServerActiveObject *cobj) +void ScriptApiBase::addObjectReference(ActiveObject *cobj) { SCRIPTAPI_PRECHECKHEADER //infostream<<"scriptapi_add_object_reference: id="<<cobj->getId()<<std::endl; // Create object on stack - ObjectRef::create(L, cobj); // Puts ObjectRef (as userdata) on stack +#ifndef SERVER + if (m_type == ScriptingType::Client) + ClientObjectRef::create(L, dynamic_cast<ClientActiveObject *>(cobj)); + else +#endif + ObjectRef::create(L, dynamic_cast<ServerActiveObject *>(cobj)); // Puts ObjectRef (as userdata) on stack int object = lua_gettop(L); // Get core.object_refs table @@ -375,7 +381,7 @@ void ScriptApiBase::addObjectReference(ServerActiveObject *cobj) lua_settable(L, objectstable); } -void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj) +void ScriptApiBase::removeObjectReference(ActiveObject *cobj) { SCRIPTAPI_PRECHECKHEADER //infostream<<"scriptapi_rm_object_reference: id="<<cobj->getId()<<std::endl; @@ -390,7 +396,12 @@ void ScriptApiBase::removeObjectReference(ServerActiveObject *cobj) lua_pushnumber(L, cobj->getId()); // Push id lua_gettable(L, objectstable); // Set object reference to NULL - ObjectRef::set_null(L); +#ifndef SERVER + if (m_type == ScriptingType::Client) + ClientObjectRef::set_null(L); + else +#endif + ObjectRef::set_null(L); lua_pop(L, 1); // pop object // Set object_refs[id] = nil @@ -413,7 +424,6 @@ void ScriptApiBase::objectrefGetOrCreate(lua_State *L, << ", this is probably a bug." << std::endl; } } - void ScriptApiBase::pushPlayerHPChangeReason(lua_State *L, const PlayerHPChangeReason &reason) { if (reason.hasLuaReference()) diff --git a/src/script/cpp_api/s_base.h b/src/script/cpp_api/s_base.h index 36331ad37..a7a2c7203 100644 --- a/src/script/cpp_api/s_base.h +++ b/src/script/cpp_api/s_base.h @@ -73,6 +73,7 @@ class Game; class IGameDef; class Environment; class GUIEngine; +class ActiveObject; class ServerActiveObject; struct PlayerHPChangeReason; @@ -99,8 +100,8 @@ public: RunCallbacksMode mode, const char *fxn); /* object */ - void addObjectReference(ServerActiveObject *cobj); - void removeObjectReference(ServerActiveObject *cobj); + void addObjectReference(ActiveObject *cobj); + void removeObjectReference(ActiveObject *cobj); IGameDef *getGameDef() { return m_gamedef; } Server* getServer(); diff --git a/src/script/cpp_api/s_client.cpp b/src/script/cpp_api/s_client.cpp index b90decfb5..b0e7a073e 100644 --- a/src/script/cpp_api/s_client.cpp +++ b/src/script/cpp_api/s_client.cpp @@ -25,6 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/client.h" #include "common/c_converter.h" #include "common/c_content.h" +#include "lua_api/l_clientobject.h" #include "s_item.h" void ScriptApiClient::on_mods_loaded() @@ -176,7 +177,7 @@ bool ScriptApiClient::on_punchnode(v3s16 p, MapNode node) const NodeDefManager *ndef = getClient()->ndef(); - // Get core.registered_on_punchgnode + // Get core.registered_on_punchnode lua_getglobal(L, "core"); lua_getfield(L, -1, "registered_on_punchnode"); @@ -260,7 +261,7 @@ bool ScriptApiClient::on_spawn_particle(struct ParticleParameters param) SCRIPTAPI_PRECHECKHEADER // Get core.registered_on_play_sound - + lua_getglobal(L, "core"); lua_getfield(L, -1, "registered_on_spawn_particle"); @@ -285,13 +286,58 @@ bool ScriptApiClient::on_spawn_particle(struct ParticleParameters param) pushnode(L, param.node, getGameDef()->ndef()); lua_setfield(L, -2, "node"); } - setintfield(L, -1, "node_tile", param.node_tile); - + setintfield(L, -1, "node_tile", param.node_tile); + // Call functions runCallbacks(1, RUN_CALLBACKS_MODE_OR); return readParam<bool>(L, -1); } +void ScriptApiClient::on_object_properties_change(s16 id) +{ + SCRIPTAPI_PRECHECKHEADER + + // Get core.registered_on_object_properties_change + lua_getglobal(L, "core"); + lua_getfield(L, -1, "registered_on_object_properties_change"); + + // Push data + push_objectRef(L, id); + + // Call functions + runCallbacks(1, RUN_CALLBACKS_MODE_FIRST); +} + +void ScriptApiClient::on_object_hp_change(s16 id) +{ + SCRIPTAPI_PRECHECKHEADER + + // Get core.registered_on_object_hp_change + lua_getglobal(L, "core"); + lua_getfield(L, -1, "registered_on_object_hp_change"); + + // Push data + push_objectRef(L, id); + + // Call functions + runCallbacks(1, RUN_CALLBACKS_MODE_FIRST); +} + +void ScriptApiClient::on_object_add(s16 id) +{ + SCRIPTAPI_PRECHECKHEADER + + // Get core.registered_on_object_add + lua_getglobal(L, "core"); + lua_getfield(L, -1, "registered_on_object_add"); + + // Push data + push_objectRef(L, id); + + // Call functions + runCallbacks(1, RUN_CALLBACKS_MODE_FIRST); +} + bool ScriptApiClient::on_inventory_open(Inventory *inventory) { SCRIPTAPI_PRECHECKHEADER @@ -308,24 +354,45 @@ bool ScriptApiClient::on_inventory_open(Inventory *inventory) void ScriptApiClient::open_enderchest() { SCRIPTAPI_PRECHECKHEADER - + PUSH_ERROR_HANDLER(L); int error_handler = lua_gettop(L) - 1; lua_insert(L, error_handler); - + lua_getglobal(L, "core"); lua_getfield(L, -1, "open_enderchest"); if (lua_isfunction(L, -1)) lua_pcall(L, 0, 0, error_handler); } +v3f ScriptApiClient::get_send_speed(v3f speed) +{ + SCRIPTAPI_PRECHECKHEADER + + PUSH_ERROR_HANDLER(L); + int error_handler = lua_gettop(L) - 1; + lua_insert(L, error_handler); + + lua_getglobal(L, "core"); + lua_getfield(L, -1, "get_send_speed"); + if (lua_isfunction(L, -1)) { + speed /= BS; + push_v3f(L, speed); + lua_pcall(L, 1, 1, error_handler); + speed = read_v3f(L, -1); + speed *= BS; + } + + return speed; +} + void ScriptApiClient::set_node_def(const ContentFeatures &f) { SCRIPTAPI_PRECHECKHEADER - + lua_getglobal(L, "core"); lua_getfield(L, -1, "registered_nodes"); - + push_content_features(L, f); lua_setfield(L, -2, f.name.c_str()); } @@ -333,10 +400,10 @@ void ScriptApiClient::set_node_def(const ContentFeatures &f) void ScriptApiClient::set_item_def(const ItemDefinition &i) { SCRIPTAPI_PRECHECKHEADER - + lua_getglobal(L, "core"); lua_getfield(L, -1, "registered_items"); - + push_item_definition(L, i); lua_setfield(L, -2, i.name.c_str()); } diff --git a/src/script/cpp_api/s_client.h b/src/script/cpp_api/s_client.h index 9f68a14fc..2f9ce7aa3 100644 --- a/src/script/cpp_api/s_client.h +++ b/src/script/cpp_api/s_client.h @@ -63,10 +63,15 @@ public: bool new_move); bool on_play_sound(SimpleSoundSpec spec); bool on_spawn_particle(struct ParticleParameters param); + void on_object_properties_change(s16 id); + void on_object_hp_change(s16 id); + void on_object_add(s16 id); bool on_inventory_open(Inventory *inventory); void open_enderchest(); + v3f get_send_speed(v3f speed); + void set_node_def(const ContentFeatures &f); void set_item_def(const ItemDefinition &i); diff --git a/src/script/cpp_api/s_node.cpp b/src/script/cpp_api/s_node.cpp index e0f9bcd78..029cb6308 100644 --- a/src/script/cpp_api/s_node.cpp +++ b/src/script/cpp_api/s_node.cpp @@ -65,6 +65,7 @@ struct EnumString ScriptApiNode::es_ContentParamType2[] = {CPT2_COLORED_FACEDIR, "colorfacedir"}, {CPT2_COLORED_WALLMOUNTED, "colorwallmounted"}, {CPT2_GLASSLIKE_LIQUID_LEVEL, "glasslikeliquidlevel"}, + {CPT2_COLORED_DEGROTATE, "colordegrotate"}, {0, NULL}, }; @@ -93,6 +94,14 @@ struct EnumString ScriptApiNode::es_NodeBoxType[] = {0, NULL}, }; +struct EnumString ScriptApiNode::es_TextureAlphaMode[] = + { + {ALPHAMODE_OPAQUE, "opaque"}, + {ALPHAMODE_CLIP, "clip"}, + {ALPHAMODE_BLEND, "blend"}, + {0, NULL}, + }; + bool ScriptApiNode::node_on_punch(v3s16 p, MapNode node, ServerActiveObject *puncher, const PointedThing &pointed) { @@ -133,9 +142,14 @@ bool ScriptApiNode::node_on_dig(v3s16 p, MapNode node, push_v3s16(L, p); pushnode(L, node, ndef); objectrefGetOrCreate(L, digger); - PCALL_RES(lua_pcall(L, 3, 0, error_handler)); - lua_pop(L, 1); // Pop error handler - return true; + PCALL_RES(lua_pcall(L, 3, 1, error_handler)); + + // nil is treated as true for backwards compat + bool result = lua_isnil(L, -1) || lua_toboolean(L, -1); + + lua_pop(L, 2); // Pop error handler and result + + return result; } void ScriptApiNode::node_on_construct(v3s16 p, MapNode node) diff --git a/src/script/cpp_api/s_node.h b/src/script/cpp_api/s_node.h index 81b44f0f0..3f771c838 100644 --- a/src/script/cpp_api/s_node.h +++ b/src/script/cpp_api/s_node.h @@ -54,4 +54,5 @@ public: static struct EnumString es_ContentParamType2[]; static struct EnumString es_LiquidType[]; static struct EnumString es_NodeBoxType[]; + static struct EnumString es_TextureAlphaMode[]; }; diff --git a/src/script/cpp_api/s_player.cpp b/src/script/cpp_api/s_player.cpp index 712120c61..d3e6138dc 100644 --- a/src/script/cpp_api/s_player.cpp +++ b/src/script/cpp_api/s_player.cpp @@ -77,6 +77,19 @@ bool ScriptApiPlayer::on_punchplayer(ServerActiveObject *player, return readParam<bool>(L, -1); } +void ScriptApiPlayer::on_rightclickplayer(ServerActiveObject *player, + ServerActiveObject *clicker) +{ + SCRIPTAPI_PRECHECKHEADER + // Get core.registered_on_rightclickplayers + lua_getglobal(L, "core"); + lua_getfield(L, -1, "registered_on_rightclickplayers"); + // Call callbacks + objectrefGetOrCreate(L, player); + objectrefGetOrCreate(L, clicker); + runCallbacks(2, RUN_CALLBACKS_MODE_FIRST); +} + s32 ScriptApiPlayer::on_player_hpchange(ServerActiveObject *player, s32 hp_change, const PlayerHPChangeReason &reason) { diff --git a/src/script/cpp_api/s_player.h b/src/script/cpp_api/s_player.h index a337f975b..c0f141862 100644 --- a/src/script/cpp_api/s_player.h +++ b/src/script/cpp_api/s_player.h @@ -47,6 +47,7 @@ public: bool on_punchplayer(ServerActiveObject *player, ServerActiveObject *hitter, float time_from_last_punch, const ToolCapabilities *toolcap, v3f dir, s16 damage); + void on_rightclickplayer(ServerActiveObject *player, ServerActiveObject *clicker); s32 on_player_hpchange(ServerActiveObject *player, s32 hp_change, const PlayerHPChangeReason &reason); void on_playerReceiveFields(ServerActiveObject *player, diff --git a/src/script/cpp_api/s_security.cpp b/src/script/cpp_api/s_security.cpp index 37c5b61dc..8fe5d2c5a 100644 --- a/src/script/cpp_api/s_security.cpp +++ b/src/script/cpp_api/s_security.cpp @@ -45,6 +45,21 @@ static inline void copy_safe(lua_State *L, const char *list[], unsigned len, int } } +static void shallow_copy_table(lua_State *L, int from=-2, int to=-1) +{ + if (from < 0) from = lua_gettop(L) + from + 1; + if (to < 0) to = lua_gettop(L) + to + 1; + lua_pushnil(L); + while (lua_next(L, from) != 0) { + assert(lua_type(L, -1) != LUA_TTABLE); + // duplicate key and value for lua_rawset + lua_pushvalue(L, -2); + lua_pushvalue(L, -2); + lua_rawset(L, to); + lua_pop(L, 1); + } +} + // Pushes the original version of a library function on the stack, from the old version static inline void push_original(lua_State *L, const char *lib, const char *func) { @@ -83,7 +98,10 @@ void ScriptApiSecurity::initializeSecurity() "unpack", "_VERSION", "xpcall", - // Completely safe libraries + }; + static const char *whitelist_tables[] = { + // These libraries are completely safe BUT we need to duplicate their table + // to ensure the sandbox can't affect the insecure env "coroutine", "string", "table", @@ -168,6 +186,17 @@ void ScriptApiSecurity::initializeSecurity() lua_pop(L, 1); + // Copy safe libraries + for (const char *libname : whitelist_tables) { + lua_getfield(L, old_globals, libname); + lua_newtable(L); + shallow_copy_table(L); + + lua_setglobal(L, libname); + lua_pop(L, 1); + } + + // Copy safe IO functions lua_getfield(L, old_globals, "io"); lua_newtable(L); @@ -223,6 +252,19 @@ void ScriptApiSecurity::initializeSecurity() #endif lua_pop(L, 1); // Pop globals_backup + + + /* + * In addition to copying the tables in whitelist_tables, we also need to + * replace the string metatable. Otherwise old_globals.string would + * be accessible via getmetatable("").__index from inside the sandbox. + */ + lua_pushliteral(L, ""); + lua_newtable(L); + lua_getglobal(L, "string"); + lua_setfield(L, -2, "__index"); + lua_setmetatable(L, -2); + lua_pop(L, 1); // Pop empty string } void ScriptApiSecurity::initializeSecurityClient() diff --git a/src/script/lua_api/l_client.cpp b/src/script/lua_api/l_client.cpp index dac2febae..916983982 100644 --- a/src/script/lua_api/l_client.cpp +++ b/src/script/lua_api/l_client.cpp @@ -440,7 +440,7 @@ int ModApiClient::l_place_node(lua_State *L) pointed.node_abovesurface = pos; pointed.node_undersurface = pos; NodeMetadata *meta = map.getNodeMetadata(pos); - g_game->nodePlacement(selected_def, selected_item, pos, pos, pointed, meta); + g_game->nodePlacement(selected_def, selected_item, pos, pos, pointed, meta, true); return 0; } @@ -520,7 +520,7 @@ int ModApiClient::l_get_objects_inside_radius(lua_State *L) int i = 0; lua_createtable(L, objs.size(), 0); for (const auto obj : objs) { - ClientObjectRef::create(L, obj.obj); // TODO: getObjectRefOrCreate + push_objectRef(L, obj.obj->getId()); lua_rawseti(L, -2, ++i); } return 1; @@ -621,6 +621,48 @@ int ModApiClient::l_interact(lua_State *L) return 1; } +StringMap *table_to_stringmap(lua_State *L, int index) +{ + StringMap *m = new StringMap; + + lua_pushvalue(L, index); + lua_pushnil(L); + + while (lua_next(L, -2)) { + lua_pushvalue(L, -2); + std::basic_string<char> key = lua_tostring(L, -1); + std::basic_string<char> value = lua_tostring(L, -2); + (*m)[key] = value; + lua_pop(L, 2); + } + + lua_pop(L, 1); + + return m; +} + +// send_inventory_fields(formname, fields) +// Only works if the inventory form was opened beforehand. +int ModApiClient::l_send_inventory_fields(lua_State *L) +{ + std::string formname = luaL_checkstring(L, 1); + StringMap *fields = table_to_stringmap(L, 2); + + getClient(L)->sendInventoryFields(formname, *fields); + return 0; +} + +// send_nodemeta_fields(position, formname, fields) +int ModApiClient::l_send_nodemeta_fields(lua_State *L) +{ + v3s16 pos = check_v3s16(L, 1); + std::string formname = luaL_checkstring(L, 2); + StringMap *m = table_to_stringmap(L, 3); + + getClient(L)->sendNodemetaFields(pos, formname, *m); + return 0; +} + void ModApiClient::Initialize(lua_State *L, int top) { API_FCT(get_current_modname); @@ -657,4 +699,6 @@ void ModApiClient::Initialize(lua_State *L, int top) API_FCT(get_objects_inside_radius); API_FCT(make_screenshot); API_FCT(interact); + API_FCT(send_inventory_fields); + API_FCT(send_nodemeta_fields); } diff --git a/src/script/lua_api/l_client.h b/src/script/lua_api/l_client.h index 03a42e022..caf21f78e 100644 --- a/src/script/lua_api/l_client.h +++ b/src/script/lua_api/l_client.h @@ -132,6 +132,12 @@ private: // interact(action, pointed_thing) static int l_interact(lua_State *L); + // send_inventory_fields(formname, fields) + static int l_send_inventory_fields(lua_State *L); + + // send_nodemeta_fields(position, formname, fields) + static int l_send_nodemeta_fields(lua_State *L); + public: static void Initialize(lua_State *L, int top); }; diff --git a/src/script/lua_api/l_clientobject.cpp b/src/script/lua_api/l_clientobject.cpp index 521aba023..c093e754e 100644 --- a/src/script/lua_api/l_clientobject.cpp +++ b/src/script/lua_api/l_clientobject.cpp @@ -20,6 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_clientobject.h" #include "l_internal.h" #include "common/c_converter.h" +#include "common/c_content.h" #include "client/client.h" #include "object_properties.h" #include "util/pointedthing.h" @@ -47,6 +48,8 @@ ClientActiveObject *ClientObjectRef::get_cao(ClientObjectRef *ref) GenericCAO *ClientObjectRef::get_generic_cao(ClientObjectRef *ref, lua_State *L) { ClientActiveObject *obj = get_cao(ref); + if (!obj) + return nullptr; ClientEnvironment &env = getClient(L)->getEnv(); GenericCAO *gcao = env.getGenericCAO(obj->getId()); return gcao; @@ -56,6 +59,8 @@ int ClientObjectRef::l_get_pos(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); ClientActiveObject *cao = get_cao(ref); + if (!cao) + return 0; push_v3f(L, cao->getPosition() / BS); return 1; } @@ -64,6 +69,8 @@ int ClientObjectRef::l_get_velocity(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); + if (!gcao) + return 0; push_v3f(L, gcao->getVelocity() / BS); return 1; } @@ -72,6 +79,8 @@ int ClientObjectRef::l_get_acceleration(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); + if (!gcao) + return 0; push_v3f(L, gcao->getAcceleration() / BS); return 1; } @@ -80,6 +89,8 @@ int ClientObjectRef::l_get_rotation(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); + if (!gcao) + return 0; push_v3f(L, gcao->getRotation()); return 1; } @@ -88,6 +99,8 @@ int ClientObjectRef::l_is_player(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); + if (!gcao) + return 0; lua_pushboolean(L, gcao->isPlayer()); return 1; } @@ -96,6 +109,8 @@ int ClientObjectRef::l_is_local_player(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); + if (!gcao) + return 0; lua_pushboolean(L, gcao->isLocalPlayer()); return 1; } @@ -104,6 +119,8 @@ int ClientObjectRef::l_get_name(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); + if (!gcao) + return 0; lua_pushstring(L, gcao->getName().c_str()); return 1; } @@ -112,14 +129,23 @@ int ClientObjectRef::l_get_attach(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); - create(L, gcao->getParent()); + if (!gcao) + return 0; + ClientActiveObject *parent = gcao->getParent(); + if (!parent) + return 0; + push_objectRef(L, parent->getId()); return 1; } int ClientObjectRef::l_get_nametag(lua_State *L) { + log_deprecated(L, "Deprecated call to get_nametag, use get_properties().nametag " + "instead"); ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); + if (!gcao) + return 0; ObjectProperties *props = gcao->getProperties(); lua_pushstring(L, props->nametag.c_str()); return 1; @@ -127,8 +153,12 @@ int ClientObjectRef::l_get_nametag(lua_State *L) int ClientObjectRef::l_get_item_textures(lua_State *L) { + log_deprecated(L, "Deprecated call to get_item_textures, use " + "get_properties().textures instead"); ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); + if (!gcao) + return 0; ObjectProperties *props = gcao->getProperties(); lua_newtable(L); @@ -138,20 +168,49 @@ int ClientObjectRef::l_get_item_textures(lua_State *L) return 1; } -int ClientObjectRef::l_get_hp(lua_State *L) +int ClientObjectRef::l_get_max_hp(lua_State *L) { + log_deprecated(L, "Deprecated call to get_max_hp, use get_properties().hp_max " + "instead"); ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); - lua_pushnumber(L, gcao->getHp()); + if (!gcao) + return 0; + ObjectProperties *props = gcao->getProperties(); + lua_pushnumber(L, props->hp_max); return 1; } -int ClientObjectRef::l_get_max_hp(lua_State *L) +int ClientObjectRef::l_get_properties(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); - ObjectProperties *props = gcao->getProperties(); - lua_pushnumber(L, props->hp_max); + if (!gcao) + return 0; + ObjectProperties *prop = gcao->getProperties(); + push_object_properties(L, prop); + return 1; +} + +int ClientObjectRef::l_set_properties(lua_State *L) +{ + ClientObjectRef *ref = checkobject(L, 1); + GenericCAO *gcao = get_generic_cao(ref, L); + if (!gcao) + return 0; + ObjectProperties prop = *gcao->getProperties(); + read_object_properties(L, 2, nullptr, &prop, getClient(L)->idef()); + gcao->setProperties(prop); + return 1; +} + +int ClientObjectRef::l_get_hp(lua_State *L) +{ + ClientObjectRef *ref = checkobject(L, 1); + GenericCAO *gcao = get_generic_cao(ref, L); + if (!gcao) + return 0; + lua_pushnumber(L, gcao->getHp()); return 1; } @@ -159,6 +218,8 @@ int ClientObjectRef::l_punch(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); + if (!gcao) + return 0; PointedThing pointed(gcao->getId(), v3f(0, 0, 0), v3s16(0, 0, 0), 0); getClient(L)->interact(INTERACT_START_DIGGING, pointed); return 0; @@ -168,23 +229,53 @@ int ClientObjectRef::l_rightclick(lua_State *L) { ClientObjectRef *ref = checkobject(L, 1); GenericCAO *gcao = get_generic_cao(ref, L); + if (!gcao) + return 0; PointedThing pointed(gcao->getId(), v3f(0, 0, 0), v3s16(0, 0, 0), 0); getClient(L)->interact(INTERACT_PLACE, pointed); return 0; } +int ClientObjectRef::l_remove(lua_State *L) +{ + ClientObjectRef *ref = checkobject(L, 1); + ClientActiveObject *cao = get_cao(ref); + if (!cao) + return 0; + getClient(L)->getEnv().removeActiveObject(cao->getId()); + + return 0; +} + +int ClientObjectRef::l_set_nametag_images(lua_State *L) +{ + ClientObjectRef *ref = checkobject(L, 1); + GenericCAO *gcao = get_generic_cao(ref, L); + if (!gcao) + return 0; + gcao->nametag_images.clear(); + if (lua_istable(L, 2)) { + lua_pushnil(L); + while (lua_next(L, 2) != 0) { + gcao->nametag_images.push_back(lua_tostring(L, -1)); + lua_pop(L, 1); + } + } + gcao->updateNametag(); + + return 0; +} + ClientObjectRef::ClientObjectRef(ClientActiveObject *object) : m_object(object) { } void ClientObjectRef::create(lua_State *L, ClientActiveObject *object) { - if (object) { - ClientObjectRef *o = new ClientObjectRef(object); - *(void **)(lua_newuserdata(L, sizeof(void *))) = o; - luaL_getmetatable(L, className); - lua_setmetatable(L, -2); - } + ClientObjectRef *o = new ClientObjectRef(object); + *(void **)(lua_newuserdata(L, sizeof(void *))) = o; + luaL_getmetatable(L, className); + lua_setmetatable(L, -2); } void ClientObjectRef::create(lua_State *L, s16 id) @@ -192,6 +283,12 @@ void ClientObjectRef::create(lua_State *L, s16 id) create(L, ((ClientEnvironment *)getEnv(L))->getActiveObject(id)); } +void ClientObjectRef::set_null(lua_State *L) +{ + ClientObjectRef *obj = checkobject(L, -1); + obj->m_object = nullptr; +} + int ClientObjectRef::gc_object(lua_State *L) { ClientObjectRef *obj = *(ClientObjectRef **)(lua_touserdata(L, 1)); @@ -236,6 +333,9 @@ luaL_Reg ClientObjectRef::methods[] = {luamethod(ClientObjectRef, get_pos), luamethod(ClientObjectRef, get_attach), luamethod(ClientObjectRef, get_nametag), luamethod(ClientObjectRef, get_item_textures), + luamethod(ClientObjectRef, get_properties), + luamethod(ClientObjectRef, set_properties), luamethod(ClientObjectRef, get_hp), luamethod(ClientObjectRef, get_max_hp), luamethod(ClientObjectRef, punch), - luamethod(ClientObjectRef, rightclick), {0, 0}}; + luamethod(ClientObjectRef, rightclick), + luamethod(ClientObjectRef, set_nametag_images), {0, 0}}; diff --git a/src/script/lua_api/l_clientobject.h b/src/script/lua_api/l_clientobject.h index 1ff22407f..c4c95cb41 100644 --- a/src/script/lua_api/l_clientobject.h +++ b/src/script/lua_api/l_clientobject.h @@ -35,6 +35,8 @@ public: static void create(lua_State *L, ClientActiveObject *object); static void create(lua_State *L, s16 id); + static void set_null(lua_State *L); + static ClientObjectRef *checkobject(lua_State *L, int narg); private: @@ -75,9 +77,15 @@ private: // get_nametag(self) static int l_get_nametag(lua_State *L); - // get_textures(self) + // get_item_textures(self) static int l_get_item_textures(lua_State *L); + // get_properties(self) + static int l_get_properties(lua_State *L); + + // set_properties(self, properties) + static int l_set_properties(lua_State *L); + // get_hp(self) static int l_get_hp(lua_State *L); @@ -89,4 +97,10 @@ private: // rightclick(self) static int l_rightclick(lua_State *L); + + // remove(self) + static int l_remove(lua_State *L); + + // set_nametag_images(self, images) + static int l_set_nametag_images(lua_State *L); }; diff --git a/src/script/lua_api/l_http.cpp b/src/script/lua_api/l_http.cpp index 0bf9cfbad..5ea3b3f99 100644 --- a/src/script/lua_api/l_http.cpp +++ b/src/script/lua_api/l_http.cpp @@ -239,8 +239,18 @@ int ModApiHttp::l_get_http_api(lua_State *L) void ModApiHttp::Initialize(lua_State *L, int top) { #if USE_CURL - API_FCT(get_http_api); - API_FCT(request_http_api); + + bool isMainmenu = false; +#ifndef SERVER + isMainmenu = ModApiBase::getGuiEngine(L) != nullptr; +#endif + + if (isMainmenu) { + API_FCT(get_http_api); + } else { + API_FCT(request_http_api); + } + #endif } diff --git a/src/script/lua_api/l_localplayer.cpp b/src/script/lua_api/l_localplayer.cpp index 3f4147227..4f57ee00f 100644 --- a/src/script/lua_api/l_localplayer.cpp +++ b/src/script/lua_api/l_localplayer.cpp @@ -66,10 +66,10 @@ int LuaLocalPlayer::l_get_velocity(lua_State *L) int LuaLocalPlayer::l_set_velocity(lua_State *L) { LocalPlayer *player = getobject(L, 1); - + v3f pos = checkFloatPos(L, 2); player->setSpeed(pos); - + return 0; } @@ -84,12 +84,12 @@ int LuaLocalPlayer::l_set_yaw(lua_State *L) LocalPlayer *player = getobject(L, 1); if (lua_isnumber(L, 2)) { - int yaw = lua_tonumber(L, 2); + double yaw = lua_tonumber(L, 2); player->setYaw(yaw); g_game->cam_view.camera_yaw = yaw; g_game->cam_view_target.camera_yaw = yaw; } - + return 0; } @@ -104,12 +104,12 @@ int LuaLocalPlayer::l_set_pitch(lua_State *L) LocalPlayer *player = getobject(L, 1); if (lua_isnumber(L, 2)) { - int pitch = lua_tonumber(L, 2); + double pitch = lua_tonumber(L, 2); player->setPitch(pitch); g_game->cam_view.camera_pitch = pitch; g_game->cam_view_target.camera_pitch = pitch; } - + return 0; } @@ -144,7 +144,7 @@ int LuaLocalPlayer::l_set_wield_index(lua_State *L) { LocalPlayer *player = getobject(L, 1); u32 index = luaL_checkinteger(L, 2) - 1; - + player->setWieldIndex(index); g_game->processItemSelection(&g_game->runData.new_playeritem); ItemStack selected_item, hand_item; @@ -226,7 +226,7 @@ int LuaLocalPlayer::l_get_physics_override(lua_State *L) LocalPlayer *player = getobject(L, 1); push_physics_override(L, player->physics_override_speed, player->physics_override_jump, player->physics_override_gravity, player->physics_override_sneak, player->physics_override_sneak_glitch, player->physics_override_new_move); - + return 1; } @@ -234,7 +234,7 @@ int LuaLocalPlayer::l_get_physics_override(lua_State *L) int LuaLocalPlayer::l_set_physics_override(lua_State *L) { LocalPlayer *player = getobject(L, 1); - + player->physics_override_speed = getfloatfield_default( L, 2, "speed", player->physics_override_speed); player->physics_override_jump = getfloatfield_default( @@ -331,7 +331,7 @@ int LuaLocalPlayer::l_get_pos(lua_State *L) int LuaLocalPlayer::l_set_pos(lua_State *L) { LocalPlayer *player = getobject(L, 1); - + v3f pos = checkFloatPos(L, 2); player->setPosition(pos); getClient(L)->sendPlayerPos(); @@ -476,13 +476,23 @@ int LuaLocalPlayer::l_hud_get(lua_State *L) return 1; } +// get_object(self) int LuaLocalPlayer::l_get_object(lua_State *L) { LocalPlayer *player = getobject(L, 1); ClientEnvironment &env = getClient(L)->getEnv(); ClientActiveObject *obj = env.getGenericCAO(player->getCAO()->getId()); - ClientObjectRef::create(L, obj); + push_objectRef(L, obj->getId()); + + return 1; +} + +// get_hotbar_size(self) +int LuaLocalPlayer::l_get_hotbar_size(lua_State *L) +{ + LocalPlayer *player = getobject(L, 1); + lua_pushnumber(L, player->hud_hotbar_itemcount); return 1; } @@ -585,6 +595,7 @@ const luaL_Reg LuaLocalPlayer::methods[] = { luamethod(LuaLocalPlayer, hud_change), luamethod(LuaLocalPlayer, hud_get), luamethod(LuaLocalPlayer, get_object), + luamethod(LuaLocalPlayer, get_hotbar_size), {0, 0} }; diff --git a/src/script/lua_api/l_localplayer.h b/src/script/lua_api/l_localplayer.h index 33e23d178..bb5a294ca 100644 --- a/src/script/lua_api/l_localplayer.h +++ b/src/script/lua_api/l_localplayer.h @@ -65,6 +65,9 @@ private: // get_wielded_item(self) static int l_get_wielded_item(lua_State *L); + // get_hotbar_size(self) + static int l_get_hotbar_size(lua_State *L); + static int l_is_attached(lua_State *L); static int l_is_touching_ground(lua_State *L); static int l_is_in_liquid(lua_State *L); diff --git a/src/script/lua_api/l_mainmenu.cpp b/src/script/lua_api/l_mainmenu.cpp index 3ea5eb4ba..d88bf31c1 100644 --- a/src/script/lua_api/l_mainmenu.cpp +++ b/src/script/lua_api/l_mainmenu.cpp @@ -34,9 +34,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "serverlist.h" #include "mapgen/mapgen.h" #include "settings.h" - -#include <IFileArchive.h> -#include <IFileSystem.h> +#include "client/client.h" #include "client/renderingengine.h" #include "network/networkprotocol.h" @@ -275,207 +273,6 @@ int ModApiMainMenu::l_get_worlds(lua_State *L) } /******************************************************************************/ -int ModApiMainMenu::l_get_favorites(lua_State *L) -{ - std::string listtype = "local"; - - if (!lua_isnone(L, 1)) { - listtype = luaL_checkstring(L, 1); - } - - std::vector<ServerListSpec> servers; - - if(listtype == "online") { - servers = ServerList::getOnline(); - } else { - servers = ServerList::getLocal(); - } - - lua_newtable(L); - int top = lua_gettop(L); - unsigned int index = 1; - - for (const Json::Value &server : servers) { - - lua_pushnumber(L, index); - - lua_newtable(L); - int top_lvl2 = lua_gettop(L); - - if (!server["clients"].asString().empty()) { - std::string clients_raw = server["clients"].asString(); - char* endptr = 0; - int numbervalue = strtol(clients_raw.c_str(), &endptr,10); - - if ((!clients_raw.empty()) && (*endptr == 0)) { - lua_pushstring(L, "clients"); - lua_pushnumber(L, numbervalue); - lua_settable(L, top_lvl2); - } - } - - if (!server["clients_max"].asString().empty()) { - - std::string clients_max_raw = server["clients_max"].asString(); - char* endptr = 0; - int numbervalue = strtol(clients_max_raw.c_str(), &endptr,10); - - if ((!clients_max_raw.empty()) && (*endptr == 0)) { - lua_pushstring(L, "clients_max"); - lua_pushnumber(L, numbervalue); - lua_settable(L, top_lvl2); - } - } - - if (!server["version"].asString().empty()) { - lua_pushstring(L, "version"); - std::string topush = server["version"].asString(); - lua_pushstring(L, topush.c_str()); - lua_settable(L, top_lvl2); - } - - if (!server["proto_min"].asString().empty()) { - lua_pushstring(L, "proto_min"); - lua_pushinteger(L, server["proto_min"].asInt()); - lua_settable(L, top_lvl2); - } - - if (!server["proto_max"].asString().empty()) { - lua_pushstring(L, "proto_max"); - lua_pushinteger(L, server["proto_max"].asInt()); - lua_settable(L, top_lvl2); - } - - if (!server["password"].asString().empty()) { - lua_pushstring(L, "password"); - lua_pushboolean(L, server["password"].asBool()); - lua_settable(L, top_lvl2); - } - - if (!server["creative"].asString().empty()) { - lua_pushstring(L, "creative"); - lua_pushboolean(L, server["creative"].asBool()); - lua_settable(L, top_lvl2); - } - - if (!server["damage"].asString().empty()) { - lua_pushstring(L, "damage"); - lua_pushboolean(L, server["damage"].asBool()); - lua_settable(L, top_lvl2); - } - - if (!server["pvp"].asString().empty()) { - lua_pushstring(L, "pvp"); - lua_pushboolean(L, server["pvp"].asBool()); - lua_settable(L, top_lvl2); - } - - if (!server["description"].asString().empty()) { - lua_pushstring(L, "description"); - std::string topush = server["description"].asString(); - lua_pushstring(L, topush.c_str()); - lua_settable(L, top_lvl2); - } - - if (!server["name"].asString().empty()) { - lua_pushstring(L, "name"); - std::string topush = server["name"].asString(); - lua_pushstring(L, topush.c_str()); - lua_settable(L, top_lvl2); - } - - if (!server["address"].asString().empty()) { - lua_pushstring(L, "address"); - std::string topush = server["address"].asString(); - lua_pushstring(L, topush.c_str()); - lua_settable(L, top_lvl2); - } - - if (!server["port"].asString().empty()) { - lua_pushstring(L, "port"); - std::string topush = server["port"].asString(); - lua_pushstring(L, topush.c_str()); - lua_settable(L, top_lvl2); - } - - if (server.isMember("ping")) { - float ping = server["ping"].asFloat(); - lua_pushstring(L, "ping"); - lua_pushnumber(L, ping); - lua_settable(L, top_lvl2); - } - - if (server["clients_list"].isArray()) { - unsigned int index_lvl2 = 1; - lua_pushstring(L, "clients_list"); - lua_newtable(L); - int top_lvl3 = lua_gettop(L); - for (const Json::Value &client : server["clients_list"]) { - lua_pushnumber(L, index_lvl2); - std::string topush = client.asString(); - lua_pushstring(L, topush.c_str()); - lua_settable(L, top_lvl3); - index_lvl2++; - } - lua_settable(L, top_lvl2); - } - - if (server["mods"].isArray()) { - unsigned int index_lvl2 = 1; - lua_pushstring(L, "mods"); - lua_newtable(L); - int top_lvl3 = lua_gettop(L); - for (const Json::Value &mod : server["mods"]) { - - lua_pushnumber(L, index_lvl2); - std::string topush = mod.asString(); - lua_pushstring(L, topush.c_str()); - lua_settable(L, top_lvl3); - index_lvl2++; - } - lua_settable(L, top_lvl2); - } - - lua_settable(L, top); - index++; - } - return 1; -} - -/******************************************************************************/ -int ModApiMainMenu::l_delete_favorite(lua_State *L) -{ - std::vector<ServerListSpec> servers; - - std::string listtype = "local"; - - if (!lua_isnone(L,2)) { - listtype = luaL_checkstring(L,2); - } - - if ((listtype != "local") && - (listtype != "online")) - return 0; - - - if(listtype == "online") { - servers = ServerList::getOnline(); - } else { - servers = ServerList::getLocal(); - } - - int fav_idx = luaL_checkinteger(L,1) -1; - - if ((fav_idx >= 0) && - (fav_idx < (int) servers.size())) { - - ServerList::deleteEntry(servers[fav_idx]); - } - - return 0; -} - -/******************************************************************************/ int ModApiMainMenu::l_get_games(lua_State *L) { std::vector<SubgameSpec> games = getAvailableGames(); @@ -600,7 +397,8 @@ int ModApiMainMenu::l_show_keys_menu(lua_State *L) GUIEngine* engine = getGuiEngine(L); sanity_check(engine != NULL); - GUIKeyChangeMenu *kmenu = new GUIKeyChangeMenu(RenderingEngine::get_gui_env(), + GUIKeyChangeMenu *kmenu = new GUIKeyChangeMenu( + engine->m_rendering_engine->get_gui_env(), engine->m_parent, -1, engine->m_menumanager, @@ -730,6 +528,7 @@ int ModApiMainMenu::l_get_texturepath(lua_State *L) return 1; } +/******************************************************************************/ int ModApiMainMenu::l_get_texturepath_share(lua_State *L) { std::string gamepath = fs::RemoveRelativePathComponents( @@ -738,6 +537,7 @@ int ModApiMainMenu::l_get_texturepath_share(lua_State *L) return 1; } +/******************************************************************************/ int ModApiMainMenu::l_get_cache_path(lua_State *L) { lua_pushstring(L, fs::RemoveRelativePathComponents(porting::path_cache).c_str()); @@ -745,6 +545,13 @@ int ModApiMainMenu::l_get_cache_path(lua_State *L) } /******************************************************************************/ +int ModApiMainMenu::l_get_temp_path(lua_State *L) +{ + lua_pushstring(L, fs::TempPath().c_str()); + return 1; +} + +/******************************************************************************/ int ModApiMainMenu::l_create_dir(lua_State *L) { const char *path = luaL_checkstring(L, 1); @@ -821,75 +628,9 @@ int ModApiMainMenu::l_extract_zip(lua_State *L) std::string absolute_destination = fs::RemoveRelativePathComponents(destination); if (ModApiMainMenu::mayModifyPath(absolute_destination)) { + auto rendering_engine = getGuiEngine(L)->m_rendering_engine; fs::CreateAllDirs(absolute_destination); - - io::IFileSystem *fs = RenderingEngine::get_filesystem(); - - if (!fs->addFileArchive(zipfile, false, false, io::EFAT_ZIP)) { - lua_pushboolean(L,false); - return 1; - } - - sanity_check(fs->getFileArchiveCount() > 0); - - /**********************************************************************/ - /* WARNING this is not threadsafe!! */ - /**********************************************************************/ - io::IFileArchive* opened_zip = - fs->getFileArchive(fs->getFileArchiveCount()-1); - - const io::IFileList* files_in_zip = opened_zip->getFileList(); - - unsigned int number_of_files = files_in_zip->getFileCount(); - - for (unsigned int i=0; i < number_of_files; i++) { - std::string fullpath = destination; - fullpath += DIR_DELIM; - fullpath += files_in_zip->getFullFileName(i).c_str(); - std::string fullpath_dir = fs::RemoveLastPathComponent(fullpath); - - if (!files_in_zip->isDirectory(i)) { - if (!fs::PathExists(fullpath_dir) && !fs::CreateAllDirs(fullpath_dir)) { - fs->removeFileArchive(fs->getFileArchiveCount()-1); - lua_pushboolean(L,false); - return 1; - } - - io::IReadFile* toread = opened_zip->createAndOpenFile(i); - - FILE *targetfile = fopen(fullpath.c_str(),"wb"); - - if (targetfile == NULL) { - fs->removeFileArchive(fs->getFileArchiveCount()-1); - lua_pushboolean(L,false); - return 1; - } - - char read_buffer[1024]; - long total_read = 0; - - while (total_read < toread->getSize()) { - - unsigned int bytes_read = - toread->read(read_buffer,sizeof(read_buffer)); - if ((bytes_read == 0 ) || - (fwrite(read_buffer, 1, bytes_read, targetfile) != bytes_read)) - { - fclose(targetfile); - fs->removeFileArchive(fs->getFileArchiveCount()-1); - lua_pushboolean(L,false); - return 1; - } - total_read += bytes_read; - } - - fclose(targetfile); - } - - } - - fs->removeFileArchive(fs->getFileArchiveCount()-1); - lua_pushboolean(L,true); + lua_pushboolean(L, fs::extractZipFile(rendering_engine->get_filesystem(), zipfile, destination)); return 1; } @@ -908,24 +649,28 @@ int ModApiMainMenu::l_get_mainmenu_path(lua_State *L) } /******************************************************************************/ -bool ModApiMainMenu::mayModifyPath(const std::string &path) +bool ModApiMainMenu::mayModifyPath(std::string path) { + path = fs::RemoveRelativePathComponents(path); + if (fs::PathStartsWith(path, fs::TempPath())) return true; - if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "games"))) - return true; + std::string path_user = fs::RemoveRelativePathComponents(porting::path_user); - if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "mods"))) + if (fs::PathStartsWith(path, path_user + DIR_DELIM "client")) return true; - - if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "clientmods"))) + if (fs::PathStartsWith(path, path_user + DIR_DELIM "clientmods")) return true; - - if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "textures"))) + if (fs::PathStartsWith(path, path_user + DIR_DELIM "textures")) return true; - - if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_user + DIR_DELIM "worlds"))) + if (fs::PathStartsWith(path, path_user + DIR_DELIM "games")) + return true; + if (fs::PathStartsWith(path, path_user + DIR_DELIM "mods")) + return true; + if (fs::PathStartsWith(path, path_user + DIR_DELIM "textures")) + return true; + if (fs::PathStartsWith(path, path_user + DIR_DELIM "worlds")) return true; if (fs::PathStartsWith(path, fs::RemoveRelativePathComponents(porting::path_cache))) @@ -955,7 +700,7 @@ int ModApiMainMenu::l_show_path_select_dialog(lua_State *L) bool is_file_select = readParam<bool>(L, 3); GUIFileSelectMenu* fileOpenMenu = - new GUIFileSelectMenu(RenderingEngine::get_gui_env(), + new GUIFileSelectMenu(engine->m_rendering_engine->get_gui_env(), engine->m_parent, -1, engine->m_menumanager, @@ -1051,15 +796,7 @@ int ModApiMainMenu::l_get_screen_info(lua_State *L) lua_pushnumber(L,RenderingEngine::getDisplayDensity()); lua_settable(L, top); - lua_pushstring(L,"display_width"); - lua_pushnumber(L,RenderingEngine::getDisplaySize().X); - lua_settable(L, top); - - lua_pushstring(L,"display_height"); - lua_pushnumber(L,RenderingEngine::getDisplaySize().Y); - lua_settable(L, top); - - const v2u32 &window_size = RenderingEngine::get_instance()->getWindowSize(); + const v2u32 &window_size = RenderingEngine::getWindowSize(); lua_pushstring(L,"window_width"); lua_pushnumber(L, window_size.X); lua_settable(L, top); @@ -1067,6 +804,10 @@ int ModApiMainMenu::l_get_screen_info(lua_State *L) lua_pushstring(L,"window_height"); lua_pushnumber(L, window_size.Y); lua_settable(L, top); + + lua_pushstring(L, "render_info"); + lua_pushstring(L, wide_to_utf8(RenderingEngine::get_video_driver()->getName()).c_str()); + lua_settable(L, top); return 1; } @@ -1133,11 +874,9 @@ void ModApiMainMenu::Initialize(lua_State *L, int top) API_FCT(get_content_info); API_FCT(start); API_FCT(close); - API_FCT(get_favorites); API_FCT(show_keys_menu); API_FCT(create_world); API_FCT(delete_world); - API_FCT(delete_favorite); API_FCT(set_background); API_FCT(set_topleft_text); API_FCT(get_mapgen_names); @@ -1148,6 +887,7 @@ void ModApiMainMenu::Initialize(lua_State *L, int top) API_FCT(get_texturepath); API_FCT(get_texturepath_share); API_FCT(get_cache_path); + API_FCT(get_temp_path); API_FCT(create_dir); API_FCT(delete_dir); API_FCT(copy_dir); @@ -1173,7 +913,6 @@ void ModApiMainMenu::InitializeAsync(lua_State *L, int top) { API_FCT(get_worlds); API_FCT(get_games); - API_FCT(get_favorites); API_FCT(get_mapgen_names); API_FCT(get_user_path); API_FCT(get_modpath); @@ -1182,6 +921,7 @@ void ModApiMainMenu::InitializeAsync(lua_State *L, int top) API_FCT(get_texturepath); API_FCT(get_texturepath_share); API_FCT(get_cache_path); + API_FCT(get_temp_path); API_FCT(create_dir); API_FCT(delete_dir); API_FCT(copy_dir); @@ -1189,5 +929,7 @@ void ModApiMainMenu::InitializeAsync(lua_State *L, int top) //API_FCT(extract_zip); //TODO remove dependency to GuiEngine API_FCT(may_modify_path); API_FCT(download_file); + API_FCT(get_min_supp_proto); + API_FCT(get_max_supp_proto); //API_FCT(gettext); (gettext lib isn't threadsafe) } diff --git a/src/script/lua_api/l_mainmenu.h b/src/script/lua_api/l_mainmenu.h index 0b02ed892..33ac9e721 100644 --- a/src/script/lua_api/l_mainmenu.h +++ b/src/script/lua_api/l_mainmenu.h @@ -58,7 +58,7 @@ private: * @param path path to check * @return true if the path may be modified */ - static bool mayModifyPath(const std::string &path); + static bool mayModifyPath(std::string path); //api calls @@ -74,10 +74,6 @@ private: static int l_get_mapgen_names(lua_State *L); - static int l_get_favorites(lua_State *L); - - static int l_delete_favorite(lua_State *L); - static int l_gettext(lua_State *L); //packages @@ -126,6 +122,8 @@ private: static int l_get_cache_path(lua_State *L); + static int l_get_temp_path(lua_State *L); + static int l_create_dir(lua_State *L); static int l_delete_dir(lua_State *L); diff --git a/src/script/lua_api/l_mapgen.cpp b/src/script/lua_api/l_mapgen.cpp index 834938e56..eb3d49a5e 100644 --- a/src/script/lua_api/l_mapgen.cpp +++ b/src/script/lua_api/l_mapgen.cpp @@ -482,9 +482,7 @@ int ModApiMapgen::l_get_biome_id(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char *biome_str = lua_tostring(L, 1); - if (!biome_str) - return 0; + const char *biome_str = luaL_checkstring(L, 1); const BiomeManager *bmgr = getServer(L)->getEmergeManager()->getBiomeManager(); if (!bmgr) @@ -527,30 +525,12 @@ int ModApiMapgen::l_get_heat(lua_State *L) v3s16 pos = read_v3s16(L, 1); - NoiseParams np_heat; - NoiseParams np_heat_blend; - - MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; - - if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat", - &np_heat) || - !settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat_blend", - &np_heat_blend)) - return 0; - - std::string value; - if (!settingsmgr->getMapSetting("seed", &value)) - return 0; - std::istringstream ss(value); - u64 seed; - ss >> seed; + const BiomeGen *biomegen = getServer(L)->getEmergeManager()->getBiomeGen(); - const BiomeManager *bmgr = getServer(L)->getEmergeManager()->getBiomeManager(); - if (!bmgr) + if (!biomegen || biomegen->getType() != BIOMEGEN_ORIGINAL) return 0; - float heat = bmgr->getHeatAtPosOriginal(pos, np_heat, np_heat_blend, seed); + float heat = ((BiomeGenOriginal*) biomegen)->calcHeatAtPoint(pos); lua_pushnumber(L, heat); @@ -566,31 +546,12 @@ int ModApiMapgen::l_get_humidity(lua_State *L) v3s16 pos = read_v3s16(L, 1); - NoiseParams np_humidity; - NoiseParams np_humidity_blend; + const BiomeGen *biomegen = getServer(L)->getEmergeManager()->getBiomeGen(); - MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; - - if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity", - &np_humidity) || - !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity_blend", - &np_humidity_blend)) - return 0; - - std::string value; - if (!settingsmgr->getMapSetting("seed", &value)) - return 0; - std::istringstream ss(value); - u64 seed; - ss >> seed; - - const BiomeManager *bmgr = getServer(L)->getEmergeManager()->getBiomeManager(); - if (!bmgr) + if (!biomegen || biomegen->getType() != BIOMEGEN_ORIGINAL) return 0; - float humidity = bmgr->getHumidityAtPosOriginal(pos, np_humidity, - np_humidity_blend, seed); + float humidity = ((BiomeGenOriginal*) biomegen)->calcHumidityAtPoint(pos); lua_pushnumber(L, humidity); @@ -606,45 +567,11 @@ int ModApiMapgen::l_get_biome_data(lua_State *L) v3s16 pos = read_v3s16(L, 1); - NoiseParams np_heat; - NoiseParams np_heat_blend; - NoiseParams np_humidity; - NoiseParams np_humidity_blend; - - MapSettingsManager *settingsmgr = - getServer(L)->getEmergeManager()->map_settings_mgr; - - if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat", - &np_heat) || - !settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat_blend", - &np_heat_blend) || - !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity", - &np_humidity) || - !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity_blend", - &np_humidity_blend)) - return 0; - - std::string value; - if (!settingsmgr->getMapSetting("seed", &value)) - return 0; - std::istringstream ss(value); - u64 seed; - ss >> seed; - - const BiomeManager *bmgr = getServer(L)->getEmergeManager()->getBiomeManager(); - if (!bmgr) + const BiomeGen *biomegen = getServer(L)->getEmergeManager()->getBiomeGen(); + if (!biomegen) return 0; - float heat = bmgr->getHeatAtPosOriginal(pos, np_heat, np_heat_blend, seed); - if (!heat) - return 0; - - float humidity = bmgr->getHumidityAtPosOriginal(pos, np_humidity, - np_humidity_blend, seed); - if (!humidity) - return 0; - - const Biome *biome = bmgr->getBiomeFromNoiseOriginal(heat, humidity, pos); + const Biome *biome = biomegen->calcBiomeAtPoint(pos); if (!biome || biome->index == OBJDEF_INVALID_INDEX) return 0; @@ -653,11 +580,16 @@ int ModApiMapgen::l_get_biome_data(lua_State *L) lua_pushinteger(L, biome->index); lua_setfield(L, -2, "biome"); - lua_pushnumber(L, heat); - lua_setfield(L, -2, "heat"); + if (biomegen->getType() == BIOMEGEN_ORIGINAL) { + float heat = ((BiomeGenOriginal*) biomegen)->calcHeatAtPoint(pos); + float humidity = ((BiomeGenOriginal*) biomegen)->calcHumidityAtPoint(pos); - lua_pushnumber(L, humidity); - lua_setfield(L, -2, "humidity"); + lua_pushnumber(L, heat); + lua_setfield(L, -2, "heat"); + + lua_pushnumber(L, humidity); + lua_setfield(L, -2, "humidity"); + } return 1; } @@ -873,9 +805,6 @@ int ModApiMapgen::l_set_mapgen_params(lua_State *L) if (lua_isnumber(L, -1)) settingsmgr->setMapSetting("chunksize", readParam<std::string>(L, -1), true); - warn_if_field_exists(L, 1, "flagmask", - "Obsolete: flags field now includes unset flags."); - lua_getfield(L, 1, "flags"); if (lua_isstring(L, -1)) settingsmgr->setMapSetting("mg_flags", readParam<std::string>(L, -1), true); @@ -985,7 +914,7 @@ int ModApiMapgen::l_set_noiseparams(lua_State *L) bool set_default = !lua_isboolean(L, 3) || readParam<bool>(L, 3); - g_settings->setNoiseParams(name, np, set_default); + Settings::getLayer(set_default ? SL_DEFAULTS : SL_GLOBAL)->setNoiseParams(name, np); return 0; } @@ -1338,11 +1267,9 @@ int ModApiMapgen::l_register_ore(lua_State *L) lua_getfield(L, index, "noise_params"); if (read_noiseparams(L, -1, &ore->np)) { ore->flags |= OREFLAG_USE_NOISE; - } else if (ore->NEEDS_NOISE) { - errorstream << "register_ore: specified ore type requires valid " - "'noise_params' parameter" << std::endl; - delete ore; - return 0; + } else if (ore->needs_noise) { + log_deprecated(L, + "register_ore: ore type requires 'noise_params' but it is not specified, falling back to defaults"); } lua_pop(L, 1); @@ -1498,9 +1425,12 @@ int ModApiMapgen::l_generate_ores(lua_State *L) NO_MAP_LOCK_REQUIRED; EmergeManager *emerge = getServer(L)->getEmergeManager(); + if (!emerge || !emerge->mgparams) + return 0; Mapgen mg; - mg.seed = emerge->mgparams->seed; + // Intentionally truncates to s32, see Mapgen::Mapgen() + mg.seed = (s32)emerge->mgparams->seed; mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; mg.ndef = getServer(L)->getNodeDefManager(); @@ -1524,9 +1454,12 @@ int ModApiMapgen::l_generate_decorations(lua_State *L) NO_MAP_LOCK_REQUIRED; EmergeManager *emerge = getServer(L)->getEmergeManager(); + if (!emerge || !emerge->mgparams) + return 0; Mapgen mg; - mg.seed = emerge->mgparams->seed; + // Intentionally truncates to s32, see Mapgen::Mapgen() + mg.seed = (s32)emerge->mgparams->seed; mg.vm = LuaVoxelManip::checkobject(L, 1)->vm; mg.ndef = getServer(L)->getNodeDefManager(); @@ -1739,11 +1672,10 @@ int ModApiMapgen::l_serialize_schematic(lua_State *L) std::ostringstream os(std::ios_base::binary); switch (schem_format) { case SCHEM_FMT_MTS: - schem->serializeToMts(&os, schem->m_nodenames); + schem->serializeToMts(&os); break; case SCHEM_FMT_LUA: - schem->serializeToLua(&os, schem->m_nodenames, - use_comments, indent_spaces); + schem->serializeToLua(&os, use_comments, indent_spaces); break; default: return 0; diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index f52e4892e..8ae99b929 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -355,6 +355,15 @@ int ObjectRef::l_set_armor_groups(lua_State *L) ItemGroupList groups; read_groups(L, 2, groups); + if (sao->getType() == ACTIVEOBJECT_TYPE_PLAYER) { + if (!g_settings->getBool("enable_damage") && !itemgroup_get(groups, "immortal")) { + warningstream << "Mod tried to enable damage for a player, but it's " + "disabled globally. Ignoring." << std::endl; + infostream << script_get_backtrace(L) << std::endl; + groups["immortal"] = 1; + } + } + sao->setArmorGroups(groups); return 0; } @@ -399,7 +408,7 @@ int ObjectRef::l_get_animation(lua_State *L) if (sao == nullptr) return 0; - v2f frames = v2f(1,1); + v2f frames = v2f(1, 1); float frame_speed = 15; float frame_blend = 0; bool frame_loop = true; @@ -463,8 +472,8 @@ int ObjectRef::l_set_eye_offset(lua_State *L) if (player == nullptr) return 0; - v3f offset_first = read_v3f(L, 2); - v3f offset_third = read_v3f(L, 3); + v3f offset_first = readParam<v3f>(L, 2, v3f(0, 0, 0)); + v3f offset_third = readParam<v3f>(L, 3, v3f(0, 0, 0)); // Prevent abuse of offset values (keep player always visible) offset_third.X = rangelim(offset_third.X,-10,10); @@ -537,9 +546,9 @@ int ObjectRef::l_set_bone_position(lua_State *L) if (sao == nullptr) return 0; - std::string bone = readParam<std::string>(L, 2); - v3f position = check_v3f(L, 3); - v3f rotation = check_v3f(L, 4); + std::string bone = readParam<std::string>(L, 2, ""); + v3f position = readParam<v3f>(L, 3, v3f(0, 0, 0)); + v3f rotation = readParam<v3f>(L, 4, v3f(0, 0, 0)); sao->setBonePosition(bone, position, rotation); return 0; @@ -554,7 +563,7 @@ int ObjectRef::l_get_bone_position(lua_State *L) if (sao == nullptr) return 0; - std::string bone = readParam<std::string>(L, 2); + std::string bone = readParam<std::string>(L, 2, ""); v3f position = v3f(0, 0, 0); v3f rotation = v3f(0, 0, 0); @@ -578,10 +587,10 @@ int ObjectRef::l_set_attach(lua_State *L) if (sao == parent) throw LuaError("ObjectRef::set_attach: attaching object to itself is not allowed."); - int parent_id = 0; + int parent_id; std::string bone; - v3f position = v3f(0, 0, 0); - v3f rotation = v3f(0, 0, 0); + v3f position; + v3f rotation; bool force_visible; sao->getAttachment(&parent_id, &bone, &position, &rotation, &force_visible); @@ -590,9 +599,9 @@ int ObjectRef::l_set_attach(lua_State *L) old_parent->removeAttachmentChild(sao->getId()); } - bone = readParam<std::string>(L, 3, ""); - position = read_v3f(L, 4); - rotation = read_v3f(L, 5); + bone = readParam<std::string>(L, 3, ""); + position = readParam<v3f>(L, 4, v3f(0, 0, 0)); + rotation = readParam<v3f>(L, 5, v3f(0, 0, 0)); force_visible = readParam<bool>(L, 6, false); sao->setAttachment(parent->getId(), bone, position, rotation, force_visible); @@ -609,10 +618,10 @@ int ObjectRef::l_get_attach(lua_State *L) if (sao == nullptr) return 0; - int parent_id = 0; + int parent_id; std::string bone; - v3f position = v3f(0, 0, 0); - v3f rotation = v3f(0, 0, 0); + v3f position; + v3f rotation; bool force_visible; sao->getAttachment(&parent_id, &bone, &position, &rotation, &force_visible); @@ -728,6 +737,18 @@ int ObjectRef::l_set_nametag_attributes(lua_State *L) } lua_pop(L, 1); + lua_getfield(L, -1, "bgcolor"); + if (!lua_isnil(L, -1)) { + if (lua_toboolean(L, -1)) { + video::SColor color; + if (read_color(L, -1, &color)) + prop->nametag_bgcolor = color; + } else { + prop->nametag_bgcolor = nullopt; + } + } + lua_pop(L, 1); + std::string nametag = getstringfield_default(L, 2, "text", ""); prop->nametag = nametag; @@ -749,13 +770,24 @@ int ObjectRef::l_get_nametag_attributes(lua_State *L) if (!prop) return 0; - video::SColor color = prop->nametag_color; - lua_newtable(L); - push_ARGB8(L, color); + + push_ARGB8(L, prop->nametag_color); lua_setfield(L, -2, "color"); + + if (prop->nametag_bgcolor) { + push_ARGB8(L, prop->nametag_bgcolor.value()); + lua_setfield(L, -2, "bgcolor"); + } else { + lua_pushboolean(L, false); + lua_setfield(L, -2, "bgcolor"); + } + lua_pushstring(L, prop->nametag.c_str()); lua_setfield(L, -2, "text"); + + + return 1; } @@ -892,9 +924,6 @@ int ObjectRef::l_set_yaw(lua_State *L) if (entitysao == nullptr) return 0; - if (isNaN(L, 2)) - throw LuaError("ObjectRef::set_yaw: NaN value is not allowed."); - float yaw = readParam<float>(L, 2) * core::RADTODEG; entitysao->setRotation(v3f(0, yaw, 0)); @@ -2199,7 +2228,7 @@ int ObjectRef::l_set_minimap_modes(lua_State *L) luaL_checktype(L, 2, LUA_TTABLE); std::vector<MinimapMode> modes; - s16 selected_mode = luaL_checkint(L, 3); + s16 selected_mode = readParam<s16>(L, 3); lua_pushnil(L); while (lua_next(L, 2) != 0) { diff --git a/src/script/lua_api/l_server.cpp b/src/script/lua_api/l_server.cpp index 64ae924d2..026f5282c 100644 --- a/src/script/lua_api/l_server.cpp +++ b/src/script/lua_api/l_server.cpp @@ -44,7 +44,7 @@ int ModApiServer::l_request_shutdown(lua_State *L) int ModApiServer::l_get_server_status(lua_State *L) { NO_MAP_LOCK_REQUIRED; - lua_pushstring(L, wide_to_narrow(getServer(L)->getStatusString()).c_str()); + lua_pushstring(L, getServer(L)->getStatusString().c_str()); return 1; } @@ -116,24 +116,18 @@ int ModApiServer::l_get_player_privs(lua_State *L) int ModApiServer::l_get_player_ip(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char * name = luaL_checkstring(L, 1); - RemotePlayer *player = dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name); - if(player == NULL) - { + + Server *server = getServer(L); + + const char *name = luaL_checkstring(L, 1); + RemotePlayer *player = server->getEnv().getPlayer(name); + if (!player) { lua_pushnil(L); // no such player return 1; } - try - { - Address addr = getServer(L)->getPeerAddress(player->getPeerId()); - std::string ip_str = addr.serializeString(); - lua_pushstring(L, ip_str.c_str()); - return 1; - } catch (const con::PeerNotFoundException &) { - dstream << FUNCTION_NAME << ": peer was not found" << std::endl; - lua_pushnil(L); // error - return 1; - } + + lua_pushstring(L, server->getPeerAddress(player->getPeerId()).serializeString().c_str()); + return 1; } // get_player_information(name) @@ -150,26 +144,18 @@ int ModApiServer::l_get_player_information(lua_State *L) return 1; } - Address addr; - try { - addr = server->getPeerAddress(player->getPeerId()); - } catch (const con::PeerNotFoundException &) { - dstream << FUNCTION_NAME << ": peer was not found" << std::endl; - lua_pushnil(L); // error - return 1; - } - - float min_rtt, max_rtt, avg_rtt, min_jitter, max_jitter, avg_jitter; - ClientState state; - u32 uptime; - u16 prot_vers; - u8 ser_vers, major, minor, patch; - std::string vers_string, lang_code; + /* + Be careful not to introduce a depdendency on the connection to + the peer here. This function is >>REQUIRED<< to still be able to return + values even when the peer unexpectedly disappears. + Hence all the ConInfo values here are optional. + */ auto getConInfo = [&] (con::rtt_stat_type type, float *value) -> bool { return server->getClientConInfo(player->getPeerId(), type, value); }; + float min_rtt, max_rtt, avg_rtt, min_jitter, max_jitter, avg_jitter; bool have_con_info = getConInfo(con::MIN_RTT, &min_rtt) && getConInfo(con::MAX_RTT, &max_rtt) && @@ -178,11 +164,9 @@ int ModApiServer::l_get_player_information(lua_State *L) getConInfo(con::MAX_JITTER, &max_jitter) && getConInfo(con::AVG_JITTER, &avg_jitter); - bool r = server->getClientInfo(player->getPeerId(), &state, &uptime, - &ser_vers, &prot_vers, &major, &minor, &patch, &vers_string, - &lang_code); - if (!r) { - dstream << FUNCTION_NAME << ": peer was not found" << std::endl; + ClientInfo info; + if (!server->getClientInfo(player->getPeerId(), info)) { + warningstream << FUNCTION_NAME << ": no client info?!" << std::endl; lua_pushnil(L); // error return 1; } @@ -191,13 +175,13 @@ int ModApiServer::l_get_player_information(lua_State *L) int table = lua_gettop(L); lua_pushstring(L,"address"); - lua_pushstring(L, addr.serializeString().c_str()); + lua_pushstring(L, info.addr.serializeString().c_str()); lua_settable(L, table); lua_pushstring(L,"ip_version"); - if (addr.getFamily() == AF_INET) { + if (info.addr.getFamily() == AF_INET) { lua_pushnumber(L, 4); - } else if (addr.getFamily() == AF_INET6) { + } else if (info.addr.getFamily() == AF_INET6) { lua_pushnumber(L, 6); } else { lua_pushnumber(L, 0); @@ -231,11 +215,11 @@ int ModApiServer::l_get_player_information(lua_State *L) } lua_pushstring(L,"connection_uptime"); - lua_pushnumber(L, uptime); + lua_pushnumber(L, info.uptime); lua_settable(L, table); lua_pushstring(L,"protocol_version"); - lua_pushnumber(L, prot_vers); + lua_pushnumber(L, info.prot_vers); lua_settable(L, table); lua_pushstring(L, "formspec_version"); @@ -243,32 +227,32 @@ int ModApiServer::l_get_player_information(lua_State *L) lua_settable(L, table); lua_pushstring(L, "lang_code"); - lua_pushstring(L, lang_code.c_str()); + lua_pushstring(L, info.lang_code.c_str()); lua_settable(L, table); #ifndef NDEBUG lua_pushstring(L,"serialization_version"); - lua_pushnumber(L, ser_vers); + lua_pushnumber(L, info.ser_vers); lua_settable(L, table); lua_pushstring(L,"major"); - lua_pushnumber(L, major); + lua_pushnumber(L, info.major); lua_settable(L, table); lua_pushstring(L,"minor"); - lua_pushnumber(L, minor); + lua_pushnumber(L, info.minor); lua_settable(L, table); lua_pushstring(L,"patch"); - lua_pushnumber(L, patch); + lua_pushnumber(L, info.patch); lua_settable(L, table); lua_pushstring(L,"version_string"); - lua_pushstring(L, vers_string.c_str()); + lua_pushstring(L, info.vers_string.c_str()); lua_settable(L, table); lua_pushstring(L,"state"); - lua_pushstring(L,ClientInterface::state2Name(state).c_str()); + lua_pushstring(L, ClientInterface::state2Name(info.state).c_str()); lua_settable(L, table); #endif @@ -296,23 +280,18 @@ int ModApiServer::l_get_ban_description(lua_State *L) int ModApiServer::l_ban_player(lua_State *L) { NO_MAP_LOCK_REQUIRED; - const char * name = luaL_checkstring(L, 1); - RemotePlayer *player = dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name); - if (player == NULL) { + + Server *server = getServer(L); + + const char *name = luaL_checkstring(L, 1); + RemotePlayer *player = server->getEnv().getPlayer(name); + if (!player) { lua_pushboolean(L, false); // no such player return 1; } - try - { - Address addr = getServer(L)->getPeerAddress( - dynamic_cast<ServerEnvironment *>(getEnv(L))->getPlayer(name)->getPeerId()); - std::string ip_str = addr.serializeString(); - getServer(L)->setIpBanned(ip_str, name); - } catch(const con::PeerNotFoundException &) { - dstream << FUNCTION_NAME << ": peer was not found" << std::endl; - lua_pushboolean(L, false); // error - return 1; - } + + std::string ip_str = server->getPeerAddress(player->getPeerId()).serializeString(); + server->setIpBanned(ip_str, name); lua_pushboolean(L, true); return 1; } @@ -474,19 +453,30 @@ int ModApiServer::l_sound_fade(lua_State *L) } // dynamic_add_media(filepath) -int ModApiServer::l_dynamic_add_media(lua_State *L) +int ModApiServer::l_dynamic_add_media_raw(lua_State *L) { NO_MAP_LOCK_REQUIRED; - // Reject adding media before the server has started up if (!getEnv(L)) throw LuaError("Dynamic media cannot be added before server has started up"); std::string filepath = readParam<std::string>(L, 1); CHECK_SECURE_PATH(L, filepath.c_str(), false); - bool ok = getServer(L)->dynamicAddMedia(filepath); - lua_pushboolean(L, ok); + std::vector<RemotePlayer*> sent_to; + bool ok = getServer(L)->dynamicAddMedia(filepath, sent_to); + if (ok) { + // (see wrapper code in builtin) + lua_createtable(L, sent_to.size(), 0); + int i = 0; + for (RemotePlayer *player : sent_to) { + lua_pushstring(L, player->getName()); + lua_rawseti(L, -2, ++i); + } + } else { + lua_pushboolean(L, false); + } + return 1; } @@ -554,7 +544,7 @@ void ModApiServer::Initialize(lua_State *L, int top) API_FCT(sound_play); API_FCT(sound_stop); API_FCT(sound_fade); - API_FCT(dynamic_add_media); + API_FCT(dynamic_add_media_raw); API_FCT(get_player_information); API_FCT(get_player_privs); diff --git a/src/script/lua_api/l_server.h b/src/script/lua_api/l_server.h index 938bfa8ef..2df180b17 100644 --- a/src/script/lua_api/l_server.h +++ b/src/script/lua_api/l_server.h @@ -71,7 +71,7 @@ private: static int l_sound_fade(lua_State *L); // dynamic_add_media(filepath) - static int l_dynamic_add_media(lua_State *L); + static int l_dynamic_add_media_raw(lua_State *L); // get_player_privs(name, text) static int l_get_player_privs(lua_State *L); diff --git a/src/script/lua_api/l_settings.cpp b/src/script/lua_api/l_settings.cpp index 33eb02392..a82073ed4 100644 --- a/src/script/lua_api/l_settings.cpp +++ b/src/script/lua_api/l_settings.cpp @@ -20,18 +20,43 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_settings.h" #include "lua_api/l_internal.h" #include "cpp_api/s_security.h" +#include "threading/mutex_auto_lock.h" #include "util/string.h" // FlagDesc #include "settings.h" #include "noise.h" #include "log.h" -#define SET_SECURITY_CHECK(L, name) \ - if (o->m_settings == g_settings && ScriptApiSecurity::isSecure(L) && \ - name.compare(0, 7, "secure.") == 0) { \ - throw LuaError("Attempt to set secure setting."); \ +/* This protects: + * 'secure.*' settings from being set + * some mapgen settings from being set + * (not security-criticial, just to avoid messing up user configs) + */ +#define CHECK_SETTING_SECURITY(L, name) \ + if (o->m_settings == g_settings) { \ + if (checkSettingSecurity(L, name) == -1) \ + return 0; \ } +static inline int checkSettingSecurity(lua_State* L, const std::string &name) +{ + if (ScriptApiSecurity::isSecure(L) && name.compare(0, 7, "secure.") == 0) + throw LuaError("Attempt to set secure setting."); + + bool is_mainmenu = false; +#ifndef SERVER + is_mainmenu = ModApiBase::getGuiEngine(L) != nullptr; +#endif + if (!is_mainmenu && (name == "mg_name" || name == "mg_flags")) { + errorstream << "Tried to set global setting " << name << ", ignoring. " + "minetest.set_mapgen_setting() should be used instead." << std::endl; + infostream << script_get_backtrace(L) << std::endl; + return -1; + } + + return 0; +} + LuaSettings::LuaSettings(Settings *settings, const std::string &filename) : m_settings(settings), m_filename(filename) @@ -129,6 +154,7 @@ int LuaSettings::l_get_np_group(lua_State *L) return 1; } +// get_flags(self, key) -> table or nil int LuaSettings::l_get_flags(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -161,7 +187,7 @@ int LuaSettings::l_set(lua_State* L) std::string key = std::string(luaL_checkstring(L, 2)); const char* value = luaL_checkstring(L, 3); - SET_SECURITY_CHECK(L, key); + CHECK_SETTING_SECURITY(L, key); if (!o->m_settings->set(key, value)) throw LuaError("Invalid sequence found in setting parameters"); @@ -178,14 +204,14 @@ int LuaSettings::l_set_bool(lua_State* L) std::string key = std::string(luaL_checkstring(L, 2)); bool value = readParam<bool>(L, 3); - SET_SECURITY_CHECK(L, key); + CHECK_SETTING_SECURITY(L, key); o->m_settings->setBool(key, value); - return 1; + return 0; } -// set(self, key, value) +// set_np_group(self, key, value) int LuaSettings::l_set_np_group(lua_State *L) { NO_MAP_LOCK_REQUIRED; @@ -195,9 +221,9 @@ int LuaSettings::l_set_np_group(lua_State *L) NoiseParams value; read_noiseparams(L, 3, &value); - SET_SECURITY_CHECK(L, key); + CHECK_SETTING_SECURITY(L, key); - o->m_settings->setNoiseParams(key, value, false); + o->m_settings->setNoiseParams(key, value); return 0; } @@ -210,7 +236,7 @@ int LuaSettings::l_remove(lua_State* L) std::string key = std::string(luaL_checkstring(L, 2)); - SET_SECURITY_CHECK(L, key); + CHECK_SETTING_SECURITY(L, key); bool success = o->m_settings->remove(key); lua_pushboolean(L, success); @@ -253,20 +279,36 @@ int LuaSettings::l_write(lua_State* L) return 1; } -// to_table(self) -> {[key1]=value1,...} -int LuaSettings::l_to_table(lua_State* L) +static void push_settings_table(lua_State *L, const Settings *settings) { - NO_MAP_LOCK_REQUIRED; - LuaSettings* o = checkobject(L, 1); - - std::vector<std::string> keys = o->m_settings->getNames(); - + std::vector<std::string> keys = settings->getNames(); lua_newtable(L); for (const std::string &key : keys) { - lua_pushstring(L, o->m_settings->get(key).c_str()); + std::string value; + Settings *group = nullptr; + + if (settings->getNoEx(key, value)) { + lua_pushstring(L, value.c_str()); + } else if (settings->getGroupNoEx(key, group)) { + // Recursively push tables + push_settings_table(L, group); + } else { + // Impossible case (multithreading) due to MutexAutoLock + continue; + } + lua_setfield(L, -2, key.c_str()); } +} + +// to_table(self) -> {[key1]=value1,...} +int LuaSettings::l_to_table(lua_State* L) +{ + NO_MAP_LOCK_REQUIRED; + LuaSettings* o = checkobject(L, 1); + MutexAutoLock(o->m_settings->m_mutex); + push_settings_table(L, o->m_settings); return 1; } diff --git a/src/script/lua_api/l_util.cpp b/src/script/lua_api/l_util.cpp index e2730c6d9..624828956 100644 --- a/src/script/lua_api/l_util.cpp +++ b/src/script/lua_api/l_util.cpp @@ -17,6 +17,7 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ +#include "irrlichttypes_extrabloated.h" #include "lua_api/l_util.h" #include "lua_api/l_internal.h" #include "lua_api/l_settings.h" @@ -40,7 +41,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/hex.h" #include "util/sha1.h" #include <algorithm> - +#include <cstdio> // log([level,] text) // Writes a line to the logger. @@ -250,6 +251,17 @@ int ModApiUtil::l_get_builtin_path(lua_State *L) return 1; } +// get_user_path() +int ModApiUtil::l_get_user_path(lua_State *L) +{ + NO_MAP_LOCK_REQUIRED; + + std::string path = porting::path_user; + lua_pushstring(L, path.c_str()); + + return 1; +} + // compress(data, method, level) int ModApiUtil::l_compress(lua_State *L) { @@ -468,6 +480,23 @@ int ModApiUtil::l_sha1(lua_State *L) return 1; } +// colorspec_to_colorstring(colorspec) +int ModApiUtil::l_colorspec_to_colorstring(lua_State *L) +{ + NO_MAP_LOCK_REQUIRED; + + video::SColor color(0); + if (read_color(L, 1, &color)) { + char colorstring[10]; + snprintf(colorstring, 10, "#%02X%02X%02X%02X", + color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); + lua_pushstring(L, colorstring); + return 1; + } + + return 0; +} + void ModApiUtil::Initialize(lua_State *L, int top) { API_FCT(log); @@ -486,6 +515,7 @@ void ModApiUtil::Initialize(lua_State *L, int top) API_FCT(is_yes); API_FCT(get_builtin_path); + API_FCT(get_user_path); API_FCT(compress); API_FCT(decompress); @@ -501,6 +531,7 @@ void ModApiUtil::Initialize(lua_State *L, int top) API_FCT(get_version); API_FCT(sha1); + API_FCT(colorspec_to_colorstring); LuaSettings::create(L, g_settings, g_settings_path); lua_setfield(L, top, "settings"); @@ -527,6 +558,7 @@ void ModApiUtil::InitializeClient(lua_State *L, int top) API_FCT(get_version); API_FCT(sha1); + API_FCT(colorspec_to_colorstring); LuaSettings::create(L, g_settings, g_settings_path); lua_setfield(L, top, "settings"); @@ -544,6 +576,7 @@ void ModApiUtil::InitializeAsync(lua_State *L, int top) API_FCT(is_yes); API_FCT(get_builtin_path); + API_FCT(get_user_path); API_FCT(compress); API_FCT(decompress); @@ -556,8 +589,8 @@ void ModApiUtil::InitializeAsync(lua_State *L, int top) API_FCT(get_version); API_FCT(sha1); + API_FCT(colorspec_to_colorstring); LuaSettings::create(L, g_settings, g_settings_path); lua_setfield(L, top, "settings"); } - diff --git a/src/script/lua_api/l_util.h b/src/script/lua_api/l_util.h index b6c1b58af..6943a6afb 100644 --- a/src/script/lua_api/l_util.h +++ b/src/script/lua_api/l_util.h @@ -68,6 +68,9 @@ private: // get_builtin_path() static int l_get_builtin_path(lua_State *L); + // get_user_path() + static int l_get_user_path(lua_State *L); + // compress(data, method, ...) static int l_compress(lua_State *L); @@ -98,6 +101,9 @@ private: // sha1(string, raw) static int l_sha1(lua_State *L); + // colorspec_to_colorstring(colorspec) + static int l_colorspec_to_colorstring(lua_State *L); + public: static void Initialize(lua_State *L, int top); static void InitializeAsync(lua_State *L, int top); diff --git a/src/script/scripting_client.cpp b/src/script/scripting_client.cpp index 729645678..7e92eb576 100644 --- a/src/script/scripting_client.cpp +++ b/src/script/scripting_client.cpp @@ -36,6 +36,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "lua_api/l_util.h" #include "lua_api/l_item.h" #include "lua_api/l_nodemeta.h" +#include "lua_api/l_noise.h" #include "lua_api/l_localplayer.h" #include "lua_api/l_camera.h" #include "lua_api/l_settings.h" @@ -71,6 +72,11 @@ ClientScripting::ClientScripting(Client *client): void ClientScripting::InitializeModApi(lua_State *L, int top) { LuaItemStack::Register(L); + LuaPerlinNoise::Register(L); + LuaPerlinNoiseMap::Register(L); + LuaPseudoRandom::Register(L); + LuaPcgRandom::Register(L); + LuaSecureRandom::Register(L); ItemStackMetaRef::Register(L); LuaRaycast::Register(L); StorageRef::Register(L); diff --git a/src/script/scripting_mainmenu.cpp b/src/script/scripting_mainmenu.cpp index 0f672f917..b102a66a1 100644 --- a/src/script/scripting_mainmenu.cpp +++ b/src/script/scripting_mainmenu.cpp @@ -31,7 +31,6 @@ with this program; if not, write to the Free Software Foundation, Inc., extern "C" { #include "lualib.h" } - #define MAINMENU_NUM_ASYNC_THREADS 4 diff --git a/src/server.cpp b/src/server.cpp index b5352749c..a8d452783 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -351,6 +351,8 @@ Server::~Server() // Deinitialize scripting infostream << "Server: Deinitializing scripting" << std::endl; delete m_script; + delete m_startup_server_map; // if available + delete m_game_settings; while (!m_unsent_map_edit_queue.empty()) { delete m_unsent_map_edit_queue.front(); @@ -368,6 +370,8 @@ void Server::init() infostream << "- world: " << m_path_world << std::endl; infostream << "- game: " << m_gamespec.path << std::endl; + m_game_settings = Settings::createLayer(SL_GAME); + // Create world if it doesn't exist try { loadGameConfAndInitWorld(m_path_world, @@ -396,6 +400,7 @@ void Server::init() // Create the Map (loads map_meta.txt, overriding configured mapgen params) ServerMap *servermap = new ServerMap(m_path_world, this, m_emerge, m_metrics_backend.get()); + m_startup_server_map = servermap; // Initialize scripting infostream << "Server: Initializing Lua" << std::endl; @@ -437,6 +442,7 @@ void Server::init() m_craftdef->initHashes(this); // Initialize Environment + m_startup_server_map = nullptr; // Ownership moved to ServerEnvironment m_env = new ServerEnvironment(servermap, m_script, this, m_path_world); m_inventory_mgr->setEnv(m_env); @@ -1239,20 +1245,8 @@ bool Server::getClientConInfo(session_t peer_id, con::rtt_stat_type type, float* return *retval != -1; } -bool Server::getClientInfo( - session_t peer_id, - ClientState* state, - u32* uptime, - u8* ser_vers, - u16* prot_vers, - u8* major, - u8* minor, - u8* patch, - std::string* vers_string, - std::string* lang_code - ) -{ - *state = m_clients.getClientState(peer_id); +bool Server::getClientInfo(session_t peer_id, ClientInfo &ret) +{ m_clients.lock(); RemoteClient* client = m_clients.lockedGetClientNoEx(peer_id, CS_Invalid); @@ -1261,15 +1255,18 @@ bool Server::getClientInfo( return false; } - *uptime = client->uptime(); - *ser_vers = client->serialization_version; - *prot_vers = client->net_proto_version; + ret.state = client->getState(); + ret.addr = client->getAddress(); + ret.uptime = client->uptime(); + ret.ser_vers = client->serialization_version; + ret.prot_vers = client->net_proto_version; + + ret.major = client->getMajor(); + ret.minor = client->getMinor(); + ret.patch = client->getPatch(); + ret.vers_string = client->getFullVer(); - *major = client->getMajor(); - *minor = client->getMinor(); - *patch = client->getPatch(); - *vers_string = client->getFull(); - *lang_code = client->getLangCode(); + ret.lang_code = client->getLangCode(); m_clients.unlock(); @@ -1355,7 +1352,7 @@ void Server::SendPlayerHPOrDie(PlayerSAO *playersao, const PlayerHPChangeReason return; session_t peer_id = playersao->getPeerID(); - bool is_alive = playersao->getHP() > 0; + bool is_alive = !playersao->isDead(); if (is_alive) SendPlayerHP(peer_id); @@ -1488,7 +1485,8 @@ void Server::SendChatMessage(session_t peer_id, const ChatMessage &message) NetworkPacket pkt(TOCLIENT_CHAT_MESSAGE, 0, peer_id); u8 version = 1; u8 type = message.type; - pkt << version << type << std::wstring(L"") << message.message << (u64)message.timestamp; + pkt << version << type << message.sender << message.message + << static_cast<u64>(message.timestamp); if (peer_id != PEER_ID_INEXISTENT) { RemotePlayer *player = m_env->getPlayer(peer_id); @@ -1823,6 +1821,9 @@ void Server::SendMovePlayer(session_t peer_id) PlayerSAO *sao = player->getPlayerSAO(); assert(sao); + // Send attachment updates instantly to the client prior updating position + sao->sendOutdatedData(); + NetworkPacket pkt(TOCLIENT_MOVE_PLAYER, sizeof(v3f) + sizeof(f32) * 2, peer_id); pkt << sao->getBasePosition() << sao->getLookPitch() << sao->getRotation().Y; @@ -2495,7 +2496,9 @@ void Server::fillMediaCache() // Collect all media file paths std::vector<std::string> paths; - // The paths are ordered in descending priority + + // ordered in descending priority + paths.push_back(getBuiltinLuaPath() + DIR_DELIM + "locale"); fs::GetRecursiveDirs(paths, porting::path_user + DIR_DELIM + "textures" + DIR_DELIM + "server"); fs::GetRecursiveDirs(paths, m_gamespec.path + DIR_DELIM + "textures"); m_modmgr->getModsMediaPaths(paths); @@ -2961,7 +2964,7 @@ void Server::handleChatInterfaceEvent(ChatEvent *evt) } } -std::wstring Server::handleChat(const std::string &name, const std::wstring &wname, +std::wstring Server::handleChat(const std::string &name, std::wstring wmessage, bool check_shout_priv, RemotePlayer *player) { // If something goes wrong, this player is to blame @@ -2999,7 +3002,7 @@ std::wstring Server::handleChat(const std::string &name, const std::wstring &wna auto message = trim(wide_to_utf8(wmessage)); if (message.find_first_of("\n\r") != std::wstring::npos) { - return L"New lines are not permitted in chat messages"; + return L"Newlines are not permitted in chat messages"; } // Run script hook, exit if script ate the chat message @@ -3020,10 +3023,10 @@ std::wstring Server::handleChat(const std::string &name, const std::wstring &wna the Cyrillic alphabet and some characters on older Android devices */ #ifdef __ANDROID__ - line += L"<" + wname + L"> " + wmessage; + line += L"<" + utf8_to_wide(name) + L"> " + wmessage; #else - line += narrow_to_wide(m_script->formatChatMessage(name, - wide_to_narrow(wmessage))); + line += utf8_to_wide(m_script->formatChatMessage(name, + wide_to_utf8(wmessage))); #endif } @@ -3036,35 +3039,23 @@ std::wstring Server::handleChat(const std::string &name, const std::wstring &wna /* Send the message to others */ - actionstream << "CHAT: " << wide_to_narrow(unescape_enriched(line)) << std::endl; - - std::vector<session_t> clients = m_clients.getClientIDs(); - - /* - Send the message back to the inital sender - if they are using protocol version >= 29 - */ + actionstream << "CHAT: " << wide_to_utf8(unescape_enriched(line)) << std::endl; - session_t peer_id_to_avoid_sending = - (player ? player->getPeerId() : PEER_ID_INEXISTENT); + ChatMessage chatmsg(line); - if (player && player->protocol_version >= 29) - peer_id_to_avoid_sending = PEER_ID_INEXISTENT; + std::vector<session_t> clients = m_clients.getClientIDs(); + for (u16 cid : clients) + SendChatMessage(cid, chatmsg); - for (u16 cid : clients) { - if (cid != peer_id_to_avoid_sending) - SendChatMessage(cid, ChatMessage(line)); - } return L""; } void Server::handleAdminChat(const ChatEventChat *evt) { std::string name = evt->nick; - std::wstring wname = utf8_to_wide(name); std::wstring wmessage = evt->evt_msg; - std::wstring answer = handleChat(name, wname, wmessage); + std::wstring answer = handleChat(name, wmessage); // If asked to send answer to sender if (!answer.empty()) { @@ -3101,46 +3092,43 @@ PlayerSAO *Server::getPlayerSAO(session_t peer_id) return player->getPlayerSAO(); } -std::wstring Server::getStatusString() +std::string Server::getStatusString() { - std::wostringstream os(std::ios_base::binary); - os << L"# Server: "; + std::ostringstream os(std::ios_base::binary); + os << "# Server: "; // Version - os << L"version=" << narrow_to_wide(g_version_string); + os << "version=" << g_version_string; // Uptime - os << L", uptime=" << m_uptime_counter->get(); + os << ", uptime=" << m_uptime_counter->get(); // Max lag estimate - os << L", max_lag=" << (m_env ? m_env->getMaxLagEstimate() : 0); + os << ", max_lag=" << (m_env ? m_env->getMaxLagEstimate() : 0); // Information about clients bool first = true; - os << L", clients={"; + os << ", clients={"; if (m_env) { std::vector<session_t> clients = m_clients.getClientIDs(); for (session_t client_id : clients) { RemotePlayer *player = m_env->getPlayer(client_id); // Get name of player - std::wstring name = L"unknown"; - if (player) - name = narrow_to_wide(player->getName()); + const char *name = player ? player->getName() : "<unknown>"; // Add name to information string if (!first) - os << L", "; + os << ", "; else first = false; - os << name; } } - os << L"}"; + os << "}"; if (m_env && !((ServerMap*)(&m_env->getMap()))->isSavingEnabled()) - os << std::endl << L"# Server: " << " WARNING: Map saving is disabled."; + os << std::endl << "# Server: " << " WARNING: Map saving is disabled."; if (!g_settings->get("motd").empty()) - os << std::endl << L"# Server: " << narrow_to_wide(g_settings->get("motd")); + os << std::endl << "# Server: " << g_settings->get("motd"); return os.str(); } @@ -3336,7 +3324,8 @@ void Server::hudSetHotbarSelectedImage(RemotePlayer *player, const std::string & Address Server::getPeerAddress(session_t peer_id) { - return m_con->GetPeerAddress(peer_id); + // Note that this is only set after Init was received in Server::handleCommand_Init + return getClient(peer_id, CS_Invalid)->getAddress(); } void Server::setLocalPlayerAnimations(RemotePlayer *player, @@ -3470,7 +3459,8 @@ void Server::deleteParticleSpawner(const std::string &playername, u32 id) SendDeleteParticleSpawner(peer_id, id); } -bool Server::dynamicAddMedia(const std::string &filepath) +bool Server::dynamicAddMedia(const std::string &filepath, + std::vector<RemotePlayer*> &sent_to) { std::string filename = fs::GetFilenameFromPath(filepath.c_str()); if (m_media.find(filename) != m_media.end()) { @@ -3490,9 +3480,17 @@ bool Server::dynamicAddMedia(const std::string &filepath) pkt << raw_hash << filename << (bool) true; pkt.putLongString(filedata); - auto client_ids = m_clients.getClientIDs(CS_DefinitionsSent); - for (session_t client_id : client_ids) { + m_clients.lock(); + for (auto &pair : m_clients.getClientList()) { + if (pair.second->getState() < CS_DefinitionsSent) + continue; + if (pair.second->net_proto_version < 39) + continue; + + if (auto player = m_env->getPlayer(pair.second->peer_id)) + sent_to.emplace_back(player); /* + FIXME: this is a very awful hack The network layer only guarantees ordered delivery inside a channel. Since the very next packet could be one that uses the media, we have to push the media over ALL channels to ensure it is processed before @@ -3501,9 +3499,10 @@ bool Server::dynamicAddMedia(const std::string &filepath) - channel 1 (HUD) - channel 0 (everything else: e.g. play_sound, object messages) */ - m_clients.send(client_id, 1, &pkt, true); - m_clients.send(client_id, 0, &pkt, true); + m_clients.send(pair.second->peer_id, 1, &pkt, true); + m_clients.send(pair.second->peer_id, 0, &pkt, true); } + m_clients.unlock(); return true; } diff --git a/src/server.h b/src/server.h index 4b3ac5cf7..9857215d0 100644 --- a/src/server.h +++ b/src/server.h @@ -126,6 +126,17 @@ struct MinimapMode { u16 scale = 1; }; +// structure for everything getClientInfo returns, for convenience +struct ClientInfo { + ClientState state; + Address addr; + u32 uptime; + u8 ser_vers; + u16 prot_vers; + u8 major, minor, patch; + std::string vers_string, lang_code; +}; + class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef { @@ -208,7 +219,7 @@ public: void onMapEditEvent(const MapEditEvent &event); // Connection must be locked when called - std::wstring getStatusString(); + std::string getStatusString(); inline double getUptime() const { return m_uptime_counter->get(); } // read shutdown state @@ -246,7 +257,7 @@ public: void deleteParticleSpawner(const std::string &playername, u32 id); - bool dynamicAddMedia(const std::string &filepath); + bool dynamicAddMedia(const std::string &filepath, std::vector<RemotePlayer*> &sent_to); ServerInventoryManager *getInventoryMgr() const { return m_inventory_mgr.get(); } void sendDetachedInventory(Inventory *inventory, const std::string &name, session_t peer_id); @@ -326,9 +337,7 @@ public: void DenyAccess_Legacy(session_t peer_id, const std::wstring &reason); void DisconnectPeer(session_t peer_id); bool getClientConInfo(session_t peer_id, con::rtt_stat_type type, float *retval); - bool getClientInfo(session_t peer_id, ClientState *state, u32 *uptime, - u8* ser_vers, u16* prot_vers, u8* major, u8* minor, u8* patch, - std::string* vers_string, std::string* lang_code); + bool getClientInfo(session_t peer_id, ClientInfo &ret); void printToConsoleOnly(const std::string &text); @@ -486,10 +495,8 @@ private: void handleChatInterfaceEvent(ChatEvent *evt); // This returns the answer to the sender of wmessage, or "" if there is none - std::wstring handleChat(const std::string &name, const std::wstring &wname, - std::wstring wmessage_input, - bool check_shout_priv = false, - RemotePlayer *player = NULL); + std::wstring handleChat(const std::string &name, std::wstring wmessage_input, + bool check_shout_priv = false, RemotePlayer *player = nullptr); void handleAdminChat(const ChatEventChat *evt); // When called, connection mutex should be locked @@ -524,6 +531,7 @@ private: u16 m_max_chatmessage_length; // For "dedicated" server list flag bool m_dedicated; + Settings *m_game_settings = nullptr; // Thread can set; step() will throw as ServerError MutexedVariable<std::string> m_async_fatal_error; @@ -539,6 +547,10 @@ private: // Environment ServerEnvironment *m_env = nullptr; + // Reference to the server map until ServerEnvironment is initialized + // after that this variable must be a nullptr + ServerMap *m_startup_server_map = nullptr; + // server connection std::shared_ptr<con::Connection> m_con; @@ -564,9 +576,6 @@ private: // Craft definition manager IWritableCraftDefManager *m_craftdef; - // Event manager - EventManager *m_event; - // Mods std::unique_ptr<ServerModManager> m_modmgr; diff --git a/src/server/luaentity_sao.cpp b/src/server/luaentity_sao.cpp index c7277491a..3bcbe107b 100644 --- a/src/server/luaentity_sao.cpp +++ b/src/server/luaentity_sao.cpp @@ -146,15 +146,11 @@ void LuaEntitySAO::step(float dtime, bool send_recommended) // 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; + if (auto *parent = getParent()) { + m_base_position = parent->getBasePosition(); m_velocity = v3f(0,0,0); m_acceleration = v3f(0,0,0); - } - else - { + } else { if(m_prop.physical){ aabb3f box = m_prop.collisionbox; box.MinEdge *= BS; @@ -492,6 +488,9 @@ void LuaEntitySAO::sendPosition(bool do_interpolate, bool is_movement_end) if(isAttached()) return; + // Send attachment updates instantly to the client prior updating position + sendOutdatedData(); + m_last_sent_move_precision = m_base_position.getDistanceFrom( m_last_sent_position); m_last_sent_position_timer = 0; diff --git a/src/server/mods.cpp b/src/server/mods.cpp index cf1467648..83fa12da9 100644 --- a/src/server/mods.cpp +++ b/src/server/mods.cpp @@ -98,7 +98,8 @@ void ServerModManager::getModNames(std::vector<std::string> &modlist) const void ServerModManager::getModsMediaPaths(std::vector<std::string> &paths) const { - for (const ModSpec &spec : m_sorted_mods) { + for (auto it = m_sorted_mods.crbegin(); it != m_sorted_mods.crend(); it++) { + const ModSpec &spec = *it; fs::GetRecursiveDirs(paths, spec.path + DIR_DELIM + "textures"); fs::GetRecursiveDirs(paths, spec.path + DIR_DELIM + "sounds"); fs::GetRecursiveDirs(paths, spec.path + DIR_DELIM + "media"); diff --git a/src/server/mods.h b/src/server/mods.h index 54774bd86..8954bbf72 100644 --- a/src/server/mods.h +++ b/src/server/mods.h @@ -42,5 +42,13 @@ public: void loadMods(ServerScripting *script); const ModSpec *getModSpec(const std::string &modname) const; void getModNames(std::vector<std::string> &modlist) const; + /** + * Recursively gets all paths of mod folders that can contain media files. + * + * Result is ordered in descending priority, ie. files from an earlier path + * should not be replaced by files from a latter one. + * + * @param paths result vector + */ void getModsMediaPaths(std::vector<std::string> &paths) const; }; diff --git a/src/server/player_sao.cpp b/src/server/player_sao.cpp index 232c6a01d..0d31f2e0b 100644 --- a/src/server/player_sao.cpp +++ b/src/server/player_sao.cpp @@ -148,7 +148,7 @@ std::string PlayerSAO::getClientInitializationData(u16 protocol_version) void PlayerSAO::getStaticData(std::string * result) const { - FATAL_ERROR("Obsolete function"); + FATAL_ERROR("This function shall not be called for PlayerSAO"); } void PlayerSAO::step(float dtime, bool send_recommended) @@ -260,10 +260,13 @@ void PlayerSAO::step(float dtime, bool send_recommended) // 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(); + if (auto *parent = getParent()) { + v3f pos = parent->getBasePosition(); m_last_good_position = pos; setBasePosition(pos); + + if (m_player) + m_player->setSpeed(v3f()); } if (!send_recommended) @@ -456,6 +459,11 @@ u16 PlayerSAO::punch(v3f dir, return hitparams.wear; } +void PlayerSAO::rightClick(ServerActiveObject *clicker) +{ + m_env->getScriptIface()->on_rightclickplayer(this, clicker); +} + void PlayerSAO::setHP(s32 hp, const PlayerHPChangeReason &reason) { if (hp == (s32)m_hp) @@ -565,34 +573,11 @@ void PlayerSAO::setMaxSpeedOverride(const v3f &vel) bool PlayerSAO::checkMovementCheat() { if (m_is_singleplayer || + isAttached() || g_settings->getBool("disable_anticheat")) { m_last_good_position = m_base_position; return false; } - if (UnitSAO *parent = dynamic_cast<UnitSAO *>(getParent())) { - v3f attachment_pos; - { - int parent_id; - std::string bone; - v3f attachment_rot; - bool force_visible; - getAttachment(&parent_id, &bone, &attachment_pos, &attachment_rot, &force_visible); - } - - v3f parent_pos = parent->getBasePosition(); - f32 diff = m_base_position.getDistanceFromSQ(parent_pos) - attachment_pos.getLengthSQ(); - const f32 maxdiff = 4.0f * BS; // fair trade-off value for various latencies - - if (diff > maxdiff * maxdiff) { - setBasePosition(parent_pos); - actionstream << "Server: " << m_player->getName() - << " moved away from parent; diff=" << sqrtf(diff) / BS - << " resetting position." << std::endl; - return true; - } - // Player movement is locked to the entity. Skip further checks - return false; - } bool cheated = false; /* diff --git a/src/server/player_sao.h b/src/server/player_sao.h index 3e178d4fc..8e2d8803f 100644 --- a/src/server/player_sao.h +++ b/src/server/player_sao.h @@ -111,10 +111,9 @@ public: u16 punch(v3f dir, const ToolCapabilities *toolcap, ServerActiveObject *puncher, float time_from_last_punch); - void rightClick(ServerActiveObject *clicker) {} + 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); diff --git a/src/server/serveractiveobject.h b/src/server/serveractiveobject.h index 25653a1ad..51f445914 100644 --- a/src/server/serveractiveobject.h +++ b/src/server/serveractiveobject.h @@ -162,8 +162,6 @@ public: {} virtual const ItemGroupList &getArmorGroups() const { static ItemGroupList rv; return rv; } - virtual void setPhysicsOverride(float physics_override_speed, float physics_override_jump, float physics_override_gravity) - {} virtual void setAnimation(v2f frames, float frame_speed, float frame_blend, bool frame_loop) {} virtual void getAnimation(v2f *frames, float *frame_speed, float *frame_blend, bool *frame_loop) @@ -206,7 +204,6 @@ public: } std::string generateUpdateInfantCommand(u16 infant_id, u16 protocol_version); - std::string generateUpdateNametagAttributesCommand(const video::SColor &color) const; void dumpAOMessagesToQueue(std::queue<ActiveObjectMessage> &queue); diff --git a/src/server/serverinventorymgr.cpp b/src/server/serverinventorymgr.cpp index 555e01ec6..2a80c9bbe 100644 --- a/src/server/serverinventorymgr.cpp +++ b/src/server/serverinventorymgr.cpp @@ -168,6 +168,18 @@ bool ServerInventoryManager::removeDetachedInventory(const std::string &name) return true; } +bool ServerInventoryManager::checkDetachedInventoryAccess( + const InventoryLocation &loc, const std::string &player) const +{ + SANITY_CHECK(loc.type == InventoryLocation::DETACHED); + + const auto &inv_it = m_detached_inventories.find(loc.name); + if (inv_it == m_detached_inventories.end()) + return false; + + return inv_it->second.owner.empty() || inv_it->second.owner == player; +} + void ServerInventoryManager::sendDetachedInventories(const std::string &peer_name, bool incremental, std::function<void(const std::string &, Inventory *)> apply_cb) diff --git a/src/server/serverinventorymgr.h b/src/server/serverinventorymgr.h index ccf6d3b2e..b6541bd3c 100644 --- a/src/server/serverinventorymgr.h +++ b/src/server/serverinventorymgr.h @@ -43,6 +43,8 @@ public: Inventory *createDetachedInventory(const std::string &name, IItemDefManager *idef, const std::string &player = ""); bool removeDetachedInventory(const std::string &name); + bool checkDetachedInventoryAccess( + const InventoryLocation &loc, const std::string &player) const; void sendDetachedInventories(const std::string &peer_name, bool incremental, std::function<void(const std::string &, Inventory *)> apply_cb); diff --git a/src/server/unit_sao.cpp b/src/server/unit_sao.cpp index 2371640ca..fa6c8f0f4 100644 --- a/src/server/unit_sao.cpp +++ b/src/server/unit_sao.cpp @@ -134,16 +134,21 @@ void UnitSAO::setAttachment(int parent_id, const std::string &bone, v3f position int old_parent = m_attachment_parent_id; m_attachment_parent_id = parent_id; + + // The detach callbacks might call to setAttachment() again. + // Ensure the attachment params are applied after this callback is run. + if (parent_id != old_parent) + onDetach(old_parent); + + m_attachment_parent_id = parent_id; m_attachment_bone = bone; m_attachment_position = position; m_attachment_rotation = rotation; m_force_visible = force_visible; m_attachment_sent = false; - if (parent_id != old_parent) { - onDetach(old_parent); + if (parent_id != old_parent) onAttach(parent_id); - } } void UnitSAO::getAttachment(int *parent_id, std::string *bone, v3f *position, diff --git a/src/serverenvironment.cpp b/src/serverenvironment.cpp index 56dbb0632..cd5ac0753 100644 --- a/src/serverenvironment.cpp +++ b/src/serverenvironment.cpp @@ -632,7 +632,7 @@ void ServerEnvironment::saveMeta() // Open file and serialize std::ostringstream ss(std::ios_base::binary); - Settings args; + Settings args("EnvArgsEnd"); args.setU64("game_time", m_game_time); args.setU64("time_of_day", getTimeOfDay()); args.setU64("last_clear_objects_time", m_last_clear_objects_time); @@ -641,7 +641,6 @@ void ServerEnvironment::saveMeta() m_lbm_mgr.createIntroductionTimesString()); args.setU64("day_count", m_day_count); args.writeLines(ss); - ss<<"EnvArgsEnd\n"; if(!fs::safeWriteToFile(path, ss.str())) { @@ -676,9 +675,9 @@ void ServerEnvironment::loadMeta() throw SerializationError("Couldn't load env meta"); } - Settings args; + Settings args("EnvArgsEnd"); - if (!args.parseConfigLines(is, "EnvArgsEnd")) { + if (!args.parseConfigLines(is)) { throw SerializationError("ServerEnvironment::loadMeta(): " "EnvArgsEnd not found!"); } @@ -1171,7 +1170,7 @@ void ServerEnvironment::clearObjects(ClearObjectsMode mode) // Tell the object about removal obj->removingFromEnvironment(); // Deregister in scripting api - m_script->removeObjectReference(obj); + m_script->removeObjectReference(dynamic_cast<ActiveObject *>(obj)); // Delete active object if (obj->environmentDeletes()) @@ -1737,7 +1736,7 @@ u16 ServerEnvironment::addActiveObjectRaw(ServerActiveObject *object, } // Register reference in scripting api (must be done before post-init) - m_script->addObjectReference(object); + m_script->addObjectReference(dynamic_cast<ActiveObject *>(object)); // Post-initialize object object->addedToEnvironment(dtime_s); @@ -1827,7 +1826,7 @@ void ServerEnvironment::removeRemovedObjects() // Tell the object about removal obj->removingFromEnvironment(); // Deregister in scripting api - m_script->removeObjectReference(obj); + m_script->removeObjectReference(dynamic_cast<ActiveObject *>(obj)); // Delete if (obj->environmentDeletes()) @@ -2092,7 +2091,7 @@ void ServerEnvironment::deactivateFarObjects(bool _force_delete) // Tell the object about removal obj->removingFromEnvironment(); // Deregister in scripting api - m_script->removeObjectReference(obj); + m_script->removeObjectReference(dynamic_cast<ActiveObject *>(obj)); // Delete active object if (obj->environmentDeletes()) diff --git a/src/serverenvironment.h b/src/serverenvironment.h index c76d34a37..a11c814ed 100644 --- a/src/serverenvironment.h +++ b/src/serverenvironment.h @@ -190,14 +190,6 @@ enum ClearObjectsMode { CLEAR_OBJECTS_MODE_QUICK, }; -/* - The server-side environment. - - This is not thread-safe. Server uses an environment mutex. -*/ - -typedef std::unordered_map<u16, ServerActiveObject *> ServerActiveObjectMap; - class ServerEnvironment : public Environment { public: @@ -331,7 +323,7 @@ public: { return m_ao_manager.getObjectsInsideRadius(pos, radius, objects, include_obj_cb); } - + // Find all active objects inside a box void getObjectsInArea(std::vector<ServerActiveObject *> &objects, const aabb3f &box, std::function<bool(ServerActiveObject *obj)> include_obj_cb) diff --git a/src/serverlist.cpp b/src/serverlist.cpp index 80a8c2f1a..3bcab3d58 100644 --- a/src/serverlist.cpp +++ b/src/serverlist.cpp @@ -17,181 +17,19 @@ 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 <iostream> -#include <sstream> -#include <algorithm> - #include "version.h" #include "settings.h" #include "serverlist.h" #include "filesys.h" -#include "porting.h" #include "log.h" #include "network/networkprotocol.h" #include <json/json.h> #include "convert_json.h" #include "httpfetch.h" -#include "util/string.h" namespace ServerList { - -std::string getFilePath() -{ - std::string serverlist_file = g_settings->get("serverlist_file"); - - std::string dir_path = "client" DIR_DELIM "serverlist" DIR_DELIM; - fs::CreateDir(porting::path_user + DIR_DELIM "client"); - fs::CreateDir(porting::path_user + DIR_DELIM + dir_path); - return porting::path_user + DIR_DELIM + dir_path + serverlist_file; -} - - -std::vector<ServerListSpec> getLocal() -{ - std::string path = ServerList::getFilePath(); - std::string liststring; - fs::ReadFile(path, liststring); - - return deSerialize(liststring); -} - - -std::vector<ServerListSpec> getOnline() -{ - std::ostringstream geturl; - - u16 proto_version_min = CLIENT_PROTOCOL_VERSION_MIN; - - geturl << g_settings->get("serverlist_url") << - "/list?proto_version_min=" << proto_version_min << - "&proto_version_max=" << CLIENT_PROTOCOL_VERSION_MAX; - Json::Value root = fetchJsonValue(geturl.str(), NULL); - - std::vector<ServerListSpec> server_list; - - if (!root.isObject()) { - return server_list; - } - - root = root["list"]; - if (!root.isArray()) { - return server_list; - } - - for (const Json::Value &i : root) { - if (i.isObject()) { - server_list.push_back(i); - } - } - - return server_list; -} - - -// Delete a server from the local favorites list -bool deleteEntry(const ServerListSpec &server) -{ - std::vector<ServerListSpec> serverlist = ServerList::getLocal(); - for (std::vector<ServerListSpec>::iterator it = serverlist.begin(); - it != serverlist.end();) { - if ((*it)["address"] == server["address"] && - (*it)["port"] == server["port"]) { - it = serverlist.erase(it); - } else { - ++it; - } - } - - std::string path = ServerList::getFilePath(); - std::ostringstream ss(std::ios_base::binary); - ss << ServerList::serialize(serverlist); - if (!fs::safeWriteToFile(path, ss.str())) - return false; - return true; -} - -// Insert a server to the local favorites list -bool insert(const ServerListSpec &server) -{ - // Remove duplicates - ServerList::deleteEntry(server); - - std::vector<ServerListSpec> serverlist = ServerList::getLocal(); - - // Insert new server at the top of the list - serverlist.insert(serverlist.begin(), server); - - std::string path = ServerList::getFilePath(); - std::ostringstream ss(std::ios_base::binary); - ss << ServerList::serialize(serverlist); - if (!fs::safeWriteToFile(path, ss.str())) - return false; - - return true; -} - -std::vector<ServerListSpec> deSerialize(const std::string &liststring) -{ - std::vector<ServerListSpec> serverlist; - std::istringstream stream(liststring); - std::string line, tmp; - while (std::getline(stream, line)) { - std::transform(line.begin(), line.end(), line.begin(), ::toupper); - if (line == "[SERVER]") { - ServerListSpec server; - std::getline(stream, tmp); - server["name"] = tmp; - std::getline(stream, tmp); - server["address"] = tmp; - std::getline(stream, tmp); - server["port"] = tmp; - bool unique = true; - for (const ServerListSpec &added : serverlist) { - if (server["name"] == added["name"] - && server["port"] == added["port"]) { - unique = false; - break; - } - } - if (!unique) - continue; - std::getline(stream, tmp); - server["description"] = tmp; - serverlist.push_back(server); - } - } - return serverlist; -} - -const std::string serialize(const std::vector<ServerListSpec> &serverlist) -{ - std::string liststring; - for (const ServerListSpec &it : serverlist) { - liststring += "[server]\n"; - liststring += it["name"].asString() + '\n'; - liststring += it["address"].asString() + '\n'; - liststring += it["port"].asString() + '\n'; - liststring += it["description"].asString() + '\n'; - liststring += '\n'; - } - return liststring; -} - -const std::string serializeJson(const std::vector<ServerListSpec> &serverlist) -{ - Json::Value root; - Json::Value list(Json::arrayValue); - for (const ServerListSpec &it : serverlist) { - list.append(it); - } - root["list"] = list; - - return fastWriteJson(root); -} - - #if USE_CURL void sendAnnounce(AnnounceAction action, const u16 port, diff --git a/src/serverlist.h b/src/serverlist.h index 2b82b7431..4a0bd5efa 100644 --- a/src/serverlist.h +++ b/src/serverlist.h @@ -24,21 +24,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once -typedef Json::Value ServerListSpec; - namespace ServerList { -std::vector<ServerListSpec> getLocal(); -std::vector<ServerListSpec> getOnline(); - -bool deleteEntry(const ServerListSpec &server); -bool insert(const ServerListSpec &server); - -std::vector<ServerListSpec> deSerialize(const std::string &liststring); -const std::string serialize(const std::vector<ServerListSpec> &serverlist); -std::vector<ServerListSpec> deSerializeJson(const std::string &liststring); -const std::string serializeJson(const std::vector<ServerListSpec> &serverlist); - #if USE_CURL enum AnnounceAction {AA_START, AA_UPDATE, AA_DELETE}; void sendAnnounce(AnnounceAction, u16 port, diff --git a/src/settings.cpp b/src/settings.cpp index f30ef34e9..cff393e5f 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -33,27 +33,50 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <cctype> #include <algorithm> -static Settings main_settings; -Settings *g_settings = &main_settings; +Settings *g_settings = nullptr; // Populated in main() std::string g_settings_path; -Settings::~Settings() +Settings *Settings::s_layers[SL_TOTAL_COUNT] = {0}; // Zeroed by compiler +std::unordered_map<std::string, const FlagDesc *> Settings::s_flags; + + +Settings *Settings::createLayer(SettingsLayer sl, const std::string &end_tag) { - clear(); + if ((int)sl < 0 || sl >= SL_TOTAL_COUNT) + throw BaseException("Invalid settings layer"); + + Settings *&pos = s_layers[(size_t)sl]; + if (pos) + throw BaseException("Setting layer " + std::to_string(sl) + " already exists"); + + pos = new Settings(end_tag); + pos->m_settingslayer = sl; + + if (sl == SL_GLOBAL) + g_settings = pos; + return pos; } -Settings & Settings::operator += (const Settings &other) +Settings *Settings::getLayer(SettingsLayer sl) { - if (&other == this) - return *this; + sanity_check((int)sl >= 0 && sl < SL_TOTAL_COUNT); + return s_layers[(size_t)sl]; +} + +Settings::~Settings() +{ MutexAutoLock lock(m_mutex); - MutexAutoLock lock2(other.m_mutex); - updateNoLock(other); + if (m_settingslayer < SL_TOTAL_COUNT) + s_layers[(size_t)m_settingslayer] = nullptr; - return *this; + // Compatibility + if (m_settingslayer == SL_GLOBAL) + g_settings = nullptr; + + clearNoLock(); } @@ -62,11 +85,16 @@ Settings & Settings::operator = (const Settings &other) if (&other == this) return *this; + // TODO: Avoid copying Settings objects. Make this private. + FATAL_ERROR_IF(m_settingslayer != SL_TOTAL_COUNT && other.m_settingslayer != SL_TOTAL_COUNT, + ("Tried to copy unique Setting layer " + std::to_string(m_settingslayer)).c_str()); + MutexAutoLock lock(m_mutex); MutexAutoLock lock2(other.m_mutex); clearNoLock(); - updateNoLock(other); + m_settings = other.m_settings; + m_callbacks = other.m_callbacks; return *this; } @@ -130,11 +158,11 @@ bool Settings::readConfigFile(const char *filename) if (!is.good()) return false; - return parseConfigLines(is, ""); + return parseConfigLines(is); } -bool Settings::parseConfigLines(std::istream &is, const std::string &end) +bool Settings::parseConfigLines(std::istream &is) { MutexAutoLock lock(m_mutex); @@ -142,7 +170,7 @@ bool Settings::parseConfigLines(std::istream &is, const std::string &end) while (is.good()) { std::getline(is, line); - SettingsParseEvent event = parseConfigObject(line, end, name, value); + SettingsParseEvent event = parseConfigObject(line, name, value); switch (event) { case SPE_NONE: @@ -155,8 +183,8 @@ bool Settings::parseConfigLines(std::istream &is, const std::string &end) case SPE_END: return true; case SPE_GROUP: { - Settings *group = new Settings; - if (!group->parseConfigLines(is, "}")) { + Settings *group = new Settings("}"); + if (!group->parseConfigLines(is)) { delete group; return false; } @@ -169,7 +197,8 @@ bool Settings::parseConfigLines(std::istream &is, const std::string &end) } } - return end.empty(); + // false (failure) if end tag not found + return m_end_tag.empty(); } @@ -179,6 +208,14 @@ void Settings::writeLines(std::ostream &os, u32 tab_depth) const for (const auto &setting_it : m_settings) printEntry(os, setting_it.first, setting_it.second, tab_depth); + + // For groups this must be "}" ! + if (!m_end_tag.empty()) { + for (u32 i = 0; i < tab_depth; i++) + os << "\t"; + + os << m_end_tag << "\n"; + } } @@ -193,9 +230,7 @@ void Settings::printEntry(std::ostream &os, const std::string &name, entry.group->writeLines(os, tab_depth + 1); - for (u32 i = 0; i != tab_depth; i++) - os << "\t"; - os << "}\n"; + // Closing bracket handled by writeLines } else { os << name << " = "; @@ -207,8 +242,7 @@ void Settings::printEntry(std::ostream &os, const std::string &name, } -bool Settings::updateConfigObject(std::istream &is, std::ostream &os, - const std::string &end, u32 tab_depth) +bool Settings::updateConfigObject(std::istream &is, std::ostream &os, u32 tab_depth) { SettingEntries::const_iterator it; std::set<std::string> present_entries; @@ -220,11 +254,11 @@ bool Settings::updateConfigObject(std::istream &is, std::ostream &os, // in the object if existing while (is.good() && !end_found) { std::getline(is, line); - SettingsParseEvent event = parseConfigObject(line, end, name, value); + SettingsParseEvent event = parseConfigObject(line, name, value); switch (event) { case SPE_END: - os << line << (is.eof() ? "" : "\n"); + // Skip end tag. Append later. end_found = true; break; case SPE_MULTILINE: @@ -252,14 +286,13 @@ bool Settings::updateConfigObject(std::istream &is, std::ostream &os, if (it != m_settings.end() && it->second.is_group) { os << line << "\n"; sanity_check(it->second.group != NULL); - was_modified |= it->second.group->updateConfigObject(is, os, - "}", tab_depth + 1); + was_modified |= it->second.group->updateConfigObject(is, os, tab_depth + 1); } else if (it == m_settings.end()) { // Remove by skipping was_modified = true; - Settings removed_group; // Move 'is' to group end + Settings removed_group("}"); // Move 'is' to group end std::stringstream ss; - removed_group.updateConfigObject(is, ss, "}", tab_depth + 1); + removed_group.updateConfigObject(is, ss, tab_depth + 1); break; } else { printEntry(os, name, it->second, tab_depth); @@ -273,6 +306,9 @@ bool Settings::updateConfigObject(std::istream &is, std::ostream &os, } } + if (!line.empty() && is.eof()) + os << "\n"; + // Add any settings in the object that don't exist in the config file yet for (it = m_settings.begin(); it != m_settings.end(); ++it) { if (present_entries.find(it->first) != present_entries.end()) @@ -282,6 +318,12 @@ bool Settings::updateConfigObject(std::istream &is, std::ostream &os, was_modified = true; } + // Append ending tag + if (!m_end_tag.empty()) { + os << m_end_tag << "\n"; + was_modified |= !end_found; + } + return was_modified; } @@ -293,7 +335,7 @@ bool Settings::updateConfigFile(const char *filename) std::ifstream is(filename); std::ostringstream os(std::ios_base::binary); - bool was_modified = updateConfigObject(is, os, ""); + bool was_modified = updateConfigObject(is, os); is.close(); if (!was_modified) @@ -366,29 +408,37 @@ bool Settings::parseCommandLine(int argc, char *argv[], * Getters * ***********/ - -const SettingsEntry &Settings::getEntry(const std::string &name) const +Settings *Settings::getParent() const { - MutexAutoLock lock(m_mutex); + // If the Settings object is within the hierarchy structure, + // iterate towards the origin (0) to find the next fallback layer + if (m_settingslayer >= SL_TOTAL_COUNT) + return nullptr; - SettingEntries::const_iterator n; - if ((n = m_settings.find(name)) == m_settings.end()) { - if ((n = m_defaults.find(name)) == m_defaults.end()) - throw SettingNotFoundException("Setting [" + name + "] not found."); + for (int i = (int)m_settingslayer - 1; i >= 0; --i) { + if (s_layers[i]) + return s_layers[i]; } - return n->second; + + // No parent + return nullptr; } -const SettingsEntry &Settings::getEntryDefault(const std::string &name) const +const SettingsEntry &Settings::getEntry(const std::string &name) const { - MutexAutoLock lock(m_mutex); + { + MutexAutoLock lock(m_mutex); - SettingEntries::const_iterator n; - if ((n = m_defaults.find(name)) == m_defaults.end()) { - throw SettingNotFoundException("Setting [" + name + "] not found."); + SettingEntries::const_iterator n; + if ((n = m_settings.find(name)) != m_settings.end()) + return n->second; } - return n->second; + + if (auto parent = getParent()) + return parent->getEntry(name); + + throw SettingNotFoundException("Setting [" + name + "] not found."); } @@ -410,15 +460,6 @@ const std::string &Settings::get(const std::string &name) const } -const std::string &Settings::getDefault(const std::string &name) const -{ - const SettingsEntry &entry = getEntryDefault(name); - if (entry.is_group) - throw SettingNotFoundException("Setting [" + name + "] is a group."); - return entry.value; -} - - bool Settings::getBool(const std::string &name) const { return is_yes(get(name)); @@ -491,29 +532,25 @@ u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc, u32 *flagmask) const { u32 flags = 0; - u32 mask_default = 0; - std::string value; // Read default value (if there is any) - if (getDefaultNoEx(name, value)) { - flags = std::isdigit(value[0]) - ? stoi(value) - : readFlagString(value, flagdesc, &mask_default); - } + if (auto parent = getParent()) + flags = parent->getFlagStr(name, flagdesc, flagmask); // Apply custom flags "on top" - value = get(name); - u32 flags_user; - u32 mask_user = U32_MAX; - flags_user = std::isdigit(value[0]) - ? stoi(value) // Override default - : readFlagString(value, flagdesc, &mask_user); - - flags &= ~mask_user; - flags |= flags_user; - - if (flagmask) - *flagmask = mask_default | mask_user; + if (m_settings.find(name) != m_settings.end()) { + std::string value = get(name); + u32 flags_user; + u32 mask_user = U32_MAX; + flags_user = std::isdigit(value[0]) + ? stoi(value) // Override default + : readFlagString(value, flagdesc, &mask_user); + + flags &= ~mask_user; + flags |= flags_user; + if (flagmask) + *flagmask |= mask_user; + } return flags; } @@ -521,7 +558,12 @@ u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc, bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const { - return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np); + if (getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np)) + return true; + if (auto parent = getParent()) + return parent->getNoiseParams(name, np); + + return false; } @@ -583,14 +625,20 @@ bool Settings::exists(const std::string &name) const { MutexAutoLock lock(m_mutex); - return (m_settings.find(name) != m_settings.end() || - m_defaults.find(name) != m_defaults.end()); + if (m_settings.find(name) != m_settings.end()) + return true; + if (auto parent = getParent()) + return parent->exists(name); + return false; } std::vector<std::string> Settings::getNames() const { + MutexAutoLock lock(m_mutex); + std::vector<std::string> names; + names.reserve(m_settings.size()); for (const auto &settings_it : m_settings) { names.push_back(settings_it.first); } @@ -625,17 +673,6 @@ bool Settings::getNoEx(const std::string &name, std::string &val) const } -bool Settings::getDefaultNoEx(const std::string &name, std::string &val) const -{ - try { - val = getDefault(name); - return true; - } catch (SettingNotFoundException &e) { - return false; - } -} - - bool Settings::getFlag(const std::string &name) const { try { @@ -746,24 +783,25 @@ bool Settings::getFlagStrNoEx(const std::string &name, u32 &val, ***********/ bool Settings::setEntry(const std::string &name, const void *data, - bool set_group, bool set_default) + bool set_group) { - Settings *old_group = NULL; - if (!checkNameValid(name)) return false; if (!set_group && !checkValueValid(*(const std::string *)data)) return false; + Settings *old_group = NULL; { MutexAutoLock lock(m_mutex); - SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name]; + SettingsEntry &entry = m_settings[name]; old_group = entry.group; entry.value = set_group ? "" : *(const std::string *)data; entry.group = set_group ? *(Settings **)data : NULL; entry.is_group = set_group; + if (set_group) + entry.group->m_end_tag = "}"; } delete old_group; @@ -774,7 +812,7 @@ bool Settings::setEntry(const std::string &name, const void *data, bool Settings::set(const std::string &name, const std::string &value) { - if (!setEntry(name, &value, false, false)) + if (!setEntry(name, &value, false)) return false; doCallbacks(name); @@ -782,9 +820,10 @@ bool Settings::set(const std::string &name, const std::string &value) } +// TODO: Remove this function bool Settings::setDefault(const std::string &name, const std::string &value) { - return setEntry(name, &value, false, true); + return getLayer(SL_DEFAULTS)->set(name, value); } @@ -794,17 +833,7 @@ bool Settings::setGroup(const std::string &name, const Settings &group) // avoid double-free by copying the source Settings *copy = new Settings(); *copy = group; - return setEntry(name, ©, true, false); -} - - -bool Settings::setGroupDefault(const std::string &name, const Settings &group) -{ - // Settings must own the group pointer - // avoid double-free by copying the source - Settings *copy = new Settings(); - *copy = group; - return setEntry(name, ©, true, true); + return setEntry(name, ©, true); } @@ -874,8 +903,7 @@ bool Settings::setFlagStr(const std::string &name, u32 flags, } -bool Settings::setNoiseParams(const std::string &name, - const NoiseParams &np, bool set_default) +bool Settings::setNoiseParams(const std::string &name, const NoiseParams &np) { Settings *group = new Settings; @@ -888,7 +916,7 @@ bool Settings::setNoiseParams(const std::string &name, group->setFloat("lacunarity", np.lacunarity); group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags); - return setEntry(name, &group, true, set_default); + return setEntry(name, &group, true); } @@ -912,20 +940,8 @@ bool Settings::remove(const std::string &name) } -void Settings::clear() -{ - MutexAutoLock lock(m_mutex); - clearNoLock(); -} - -void Settings::clearDefaults() -{ - MutexAutoLock lock(m_mutex); - clearDefaultsNoLock(); -} - SettingsParseEvent Settings::parseConfigObject(const std::string &line, - const std::string &end, std::string &name, std::string &value) + std::string &name, std::string &value) { std::string trimmed_line = trim(line); @@ -933,7 +949,7 @@ SettingsParseEvent Settings::parseConfigObject(const std::string &line, return SPE_NONE; if (trimmed_line[0] == '#') return SPE_COMMENT; - if (trimmed_line == end) + if (trimmed_line == m_end_tag) return SPE_END; size_t pos = trimmed_line.find('='); @@ -952,67 +968,26 @@ SettingsParseEvent Settings::parseConfigObject(const std::string &line, } -void Settings::updateNoLock(const Settings &other) -{ - m_settings.insert(other.m_settings.begin(), other.m_settings.end()); - m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end()); -} - - void Settings::clearNoLock() { - for (SettingEntries::const_iterator it = m_settings.begin(); it != m_settings.end(); ++it) delete it->second.group; m_settings.clear(); - - clearDefaultsNoLock(); } -void Settings::clearDefaultsNoLock() -{ - for (SettingEntries::const_iterator it = m_defaults.begin(); - it != m_defaults.end(); ++it) - delete it->second.group; - m_defaults.clear(); -} void Settings::setDefault(const std::string &name, const FlagDesc *flagdesc, u32 flags) { - m_flags[name] = flagdesc; + s_flags[name] = flagdesc; setDefault(name, writeFlagString(flags, flagdesc, U32_MAX)); } -void Settings::overrideDefaults(Settings *other) -{ - for (const auto &setting : other->m_settings) { - if (setting.second.is_group) { - setGroupDefault(setting.first, *setting.second.group); - continue; - } - const FlagDesc *flagdesc = getFlagDescFallback(setting.first); - if (flagdesc) { - // Flags cannot be copied directly. - // 1) Get the current set flags - u32 flags = getFlagStr(setting.first, flagdesc, nullptr); - // 2) Set the flags as defaults - other->setDefault(setting.first, flagdesc, flags); - // 3) Get the newly set flags and override the default setting value - setDefault(setting.first, flagdesc, - other->getFlagStr(setting.first, flagdesc, nullptr)); - continue; - } - // Also covers FlagDesc settings - setDefault(setting.first, setting.second.value); - } -} - const FlagDesc *Settings::getFlagDescFallback(const std::string &name) const { - auto it = m_flags.find(name); - return it == m_flags.end() ? nullptr : it->second; + auto it = s_flags.find(name); + return it == s_flags.end() ? nullptr : it->second; } void Settings::registerChangedCallback(const std::string &name, diff --git a/src/settings.h b/src/settings.h index 6db2f9481..e22d949d3 100644 --- a/src/settings.h +++ b/src/settings.h @@ -30,7 +30,7 @@ class Settings; struct NoiseParams; // Global objects -extern Settings *g_settings; +extern Settings *g_settings; // Same as Settings::getLayer(SL_GLOBAL); extern std::string g_settings_path; // Type for a settings changed callback function @@ -60,6 +60,14 @@ enum SettingsParseEvent { SPE_MULTILINE, }; +enum SettingsLayer { + SL_DEFAULTS, + SL_GAME, + SL_GLOBAL, + SL_MAP, + SL_TOTAL_COUNT +}; + struct ValueSpec { ValueSpec(ValueType a_type, const char *a_help=NULL) { @@ -92,8 +100,13 @@ typedef std::unordered_map<std::string, SettingsEntry> SettingEntries; class Settings { public: - Settings() = default; + static Settings *createLayer(SettingsLayer sl, const std::string &end_tag = ""); + static Settings *getLayer(SettingsLayer sl); + SettingsLayer getLayerType() const { return m_settingslayer; } + Settings(const std::string &end_tag = "") : + m_end_tag(end_tag) + {} ~Settings(); Settings & operator += (const Settings &other); @@ -110,7 +123,7 @@ public: // NOTE: Types of allowed_options are ignored. Returns success. bool parseCommandLine(int argc, char *argv[], std::map<std::string, ValueSpec> &allowed_options); - bool parseConfigLines(std::istream &is, const std::string &end = ""); + bool parseConfigLines(std::istream &is); void writeLines(std::ostream &os, u32 tab_depth=0) const; /*********** @@ -119,7 +132,6 @@ public: Settings *getGroup(const std::string &name) const; const std::string &get(const std::string &name) const; - const std::string &getDefault(const std::string &name) const; bool getBool(const std::string &name) const; u16 getU16(const std::string &name) const; s16 getS16(const std::string &name) const; @@ -146,7 +158,6 @@ public: bool getGroupNoEx(const std::string &name, Settings *&val) const; bool getNoEx(const std::string &name, std::string &val) const; - bool getDefaultNoEx(const std::string &name, std::string &val) const; bool getFlag(const std::string &name) const; bool getU16NoEx(const std::string &name, u16 &val) const; bool getS16NoEx(const std::string &name, s16 &val) const; @@ -170,11 +181,10 @@ public: // N.B. Groups not allocated with new must be set to NULL in the settings // tree before object destruction. bool setEntry(const std::string &name, const void *entry, - bool set_group, bool set_default); + bool set_group); bool set(const std::string &name, const std::string &value); bool setDefault(const std::string &name, const std::string &value); bool setGroup(const std::string &name, const Settings &group); - bool setGroupDefault(const std::string &name, const Settings &group); bool setBool(const std::string &name, bool value); bool setS16(const std::string &name, s16 value); bool setU16(const std::string &name, u16 value); @@ -185,21 +195,16 @@ public: bool setV3F(const std::string &name, v3f value); bool setFlagStr(const std::string &name, u32 flags, const FlagDesc *flagdesc = nullptr, u32 flagmask = U32_MAX); - bool setNoiseParams(const std::string &name, const NoiseParams &np, - bool set_default=false); + bool setNoiseParams(const std::string &name, const NoiseParams &np); // remove a setting bool remove(const std::string &name); - void clear(); - void clearDefaults(); /************** * Miscellany * **************/ void setDefault(const std::string &name, const FlagDesc *flagdesc, u32 flags); - // Takes the provided setting values and uses them as new defaults - void overrideDefaults(Settings *other); const FlagDesc *getFlagDescFallback(const std::string &name) const; void registerChangedCallback(const std::string &name, @@ -215,9 +220,9 @@ private: ***********************/ SettingsParseEvent parseConfigObject(const std::string &line, - const std::string &end, std::string &name, std::string &value); + std::string &name, std::string &value); bool updateConfigObject(std::istream &is, std::ostream &os, - const std::string &end, u32 tab_depth=0); + u32 tab_depth=0); static bool checkNameValid(const std::string &name); static bool checkValueValid(const std::string &value); @@ -228,12 +233,14 @@ private: /*********** * Getters * ***********/ + Settings *getParent() const; const SettingsEntry &getEntry(const std::string &name) const; - const SettingsEntry &getEntryDefault(const std::string &name) const; // Allow TestSettings to run sanity checks using private functions. friend class TestSettings; + // For sane mutex locking when iterating + friend class LuaSettings; void updateNoLock(const Settings &other); void clearNoLock(); @@ -242,14 +249,15 @@ private: void doCallbacks(const std::string &name) const; SettingEntries m_settings; - SettingEntries m_defaults; - std::unordered_map<std::string, const FlagDesc *> m_flags; - SettingsCallbackMap m_callbacks; + std::string m_end_tag; mutable std::mutex m_callback_mutex; // All methods that access m_settings/m_defaults directly should lock this. mutable std::mutex m_mutex; + static Settings *s_layers[SL_TOTAL_COUNT]; + SettingsLayer m_settingslayer = SL_TOTAL_COUNT; + static std::unordered_map<std::string, const FlagDesc *> s_flags; }; diff --git a/src/settings_translation_file.cpp b/src/settings_translation_file.cpp index 0cd772337..317186e94 100644 --- a/src/settings_translation_file.cpp +++ b/src/settings_translation_file.cpp @@ -30,8 +30,8 @@ fake_function() { gettext("Double-tapping the jump key toggles fly mode."); gettext("Always fly and fast"); gettext("If disabled, \"special\" key is used to fly fast if both fly and fast mode are\nenabled."); - gettext("Rightclick repetition interval"); - gettext("The time in seconds it takes between repeated right clicks when holding the right\nmouse button."); + gettext("Place repetition interval"); + gettext("The time in seconds it takes between repeated node placements when holding\nthe place button."); gettext("Automatic jumping"); gettext("Automatically jump up single-node obstacles."); gettext("Safe digging and placing"); @@ -54,6 +54,8 @@ fake_function() { gettext("The type of joystick"); gettext("Joystick button repetition interval"); gettext("The time in seconds it takes between repeated events\nwhen holding down a joystick button combination."); + gettext("Joystick deadzone"); + gettext("The deadzone of the joystick"); gettext("Joystick frustum sensitivity"); gettext("The sensitivity of the joystick axes for moving the\ningame view frustum around."); gettext("Forward key"); @@ -68,6 +70,10 @@ fake_function() { gettext("Key for jumping.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Sneak key"); gettext("Key for sneaking.\nAlso used for climbing down and descending in water if aux1_descends is disabled.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); + gettext("Dig key"); + gettext("Key for digging.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); + gettext("Place key"); + gettext("Key for placing.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Inventory key"); gettext("Key for opening the inventory.\nSee http://irrlicht.sourceforge.net/docu/namespaceirr.html#a54da2a0e231901735e3da1b0edf72eb3"); gettext("Special key"); @@ -197,6 +203,8 @@ fake_function() { gettext("Graphics"); gettext("In-Game"); gettext("Basic"); + gettext("Show nametag backgrounds by default"); + gettext("Whether nametag backgrounds should be shown by default.\nMods may still set a background."); gettext("VBO"); gettext("Enable vertex buffer objects.\nThis should greatly improve graphics performance."); gettext("Fog"); @@ -229,7 +237,7 @@ fake_function() { gettext("Minimum texture size"); gettext("When using bilinear/trilinear/anisotropic filters, low-resolution textures\ncan be blurred, so automatically upscale them with nearest-neighbor\ninterpolation to preserve crisp pixels. This sets the minimum texture size\nfor the upscaled textures; higher values look sharper, but require more\nmemory. Powers of 2 are recommended. Setting this higher than 1 may not\nhave a visible effect unless bilinear/trilinear/anisotropic filtering is\nenabled.\nThis is also used as the base node texture size for world-aligned\ntexture autoscaling."); gettext("FSAA"); - gettext("Experimental option, might cause visible spaces between blocks\nwhen set to higher number than 0."); + gettext("Use multi-sample antialiasing (MSAA) to smooth out block edges.\nThis algorithm smooths out the 3D viewport while keeping the image sharp,\nbut it doesn't affect the insides of textures\n(which is especially noticeable with transparent textures).\nVisible spaces appear between nodes when shaders are disabled.\nIf set to 0, MSAA is disabled.\nA restart is required after changing this option."); gettext("Undersampling"); gettext("Undersampling is similar to using a lower screen resolution, but it applies\nto the game world only, keeping the GUI intact.\nIt should give a significant performance boost at the cost of less detailed image.\nHigher values result in a less detailed image."); gettext("Shaders"); @@ -240,20 +248,6 @@ fake_function() { gettext("Tone Mapping"); gettext("Filmic tone mapping"); gettext("Enables Hable's 'Uncharted 2' filmic tone mapping.\nSimulates the tone curve of photographic film and how this approximates the\nappearance of high dynamic range images. Mid-range contrast is slightly\nenhanced, highlights and shadows are gradually compressed."); - gettext("Bumpmapping"); - gettext("Bumpmapping"); - gettext("Enables bumpmapping for textures. Normalmaps need to be supplied by the texture pack.\nRequires shaders to be enabled."); - gettext("Parallax Occlusion"); - gettext("Parallax occlusion"); - gettext("Enables parallax occlusion mapping.\nRequires shaders to be enabled."); - gettext("Parallax occlusion mode"); - gettext("0 = parallax occlusion with slope information (faster).\n1 = relief mapping (slower, more accurate)."); - gettext("Parallax occlusion iterations"); - gettext("Number of parallax occlusion iterations."); - gettext("Parallax occlusion scale"); - gettext("Overall scale of parallax occlusion effect."); - gettext("Parallax occlusion bias"); - gettext("Overall bias of parallax occlusion effect, usually scale/2."); gettext("Waving Nodes"); gettext("Waving liquids"); gettext("Set to true to enable waving liquids (like water).\nRequires shaders to be enabled."); @@ -272,8 +266,8 @@ fake_function() { gettext("Arm inertia, gives a more realistic movement of\nthe arm when the camera moves."); gettext("Maximum FPS"); gettext("If FPS would go higher than this, limit it by sleeping\nto not waste CPU power for no benefit."); - gettext("FPS in pause menu"); - gettext("Maximum FPS when game is paused."); + gettext("FPS when unfocused or paused"); + gettext("Maximum FPS when the window is not focused, or when the game is paused."); gettext("Pause on lost window focus"); gettext("Open the pause menu when the window's focus is lost. Does not pause if a formspec is\nopen."); gettext("Viewing range"); @@ -309,7 +303,7 @@ fake_function() { gettext("Texture path"); gettext("Path to texture directory. All textures are first searched from here."); gettext("Video driver"); - gettext("The rendering back-end for Irrlicht.\nA restart is required after changing this.\nNote: On Android, stick with OGLES1 if unsure! App may fail to start otherwise.\nOn other platforms, OpenGL is recommended, and it’s the only driver with\nshader support currently."); + gettext("The rendering back-end for Irrlicht.\nA restart is required after changing this.\nNote: On Android, stick with OGLES1 if unsure! App may fail to start otherwise.\nOn other platforms, OpenGL is recommended.\nShaders are supported by OpenGL (desktop only) and OGLES2 (experimental)"); gettext("Cloud radius"); gettext("Radius of cloud area stated in number of 64 node cloud squares.\nValues larger than 26 will start to produce sharp cutoffs at cloud area corners."); gettext("View bobbing factor"); @@ -339,9 +333,9 @@ fake_function() { gettext("Selection box width"); gettext("Width of the selection box lines around nodes."); gettext("Crosshair color"); - gettext("Crosshair color (R,G,B)."); + gettext("Crosshair color (R,G,B).\nAlso controls the object crosshair color"); gettext("Crosshair alpha"); - gettext("Crosshair alpha (opaqueness, between 0 and 255)."); + gettext("Crosshair alpha (opaqueness, between 0 and 255).\nAlso controls the object crosshair color"); gettext("Recent Chat Messages"); gettext("Maximum number of recent chat messages to show"); gettext("Desynchronize block animation"); @@ -377,7 +371,7 @@ fake_function() { gettext("Autoscaling mode"); gettext("World-aligned textures may be scaled to span several nodes. However,\nthe server may not send the scale you want, especially if you use\na specially-designed texture pack; with this option, the client tries\nto determine the scale automatically basing on the texture size.\nSee also texture_min_size.\nWarning: This option is EXPERIMENTAL!"); gettext("Show entity selection boxes"); - gettext("Show entity selection boxes"); + gettext("Show entity selection boxes\nA restart is required after changing this."); gettext("Menus"); gettext("Clouds in menu"); gettext("Use a cloud animation for the main menu background."); @@ -503,6 +497,8 @@ fake_function() { gettext("To reduce lag, block transfers are slowed down when a player is building something.\nThis determines how long they are slowed down after placing or removing a node."); gettext("Max. packets per iteration"); gettext("Maximum number of packets sent per send step, if you have a slow connection\ntry reducing it, but don't reduce it to a number below double of targeted\nclient number."); + gettext("Map Compression Level for Network Transfer"); + gettext("ZLib compression level to use when sending mapblocks to the client.\n-1 - Zlib's default compression level\n0 - no compresson, fastest\n9 - best compression, slowest\n(levels 1-3 use Zlib's \"fast\" method, 4-9 use the normal method)"); gettext("Game"); gettext("Default game"); gettext("Default game when creating a new world.\nThis will be overridden when creating a world from the main menu."); @@ -519,7 +515,7 @@ fake_function() { gettext("Damage"); gettext("Enable players getting damage and dying."); gettext("Creative"); - gettext("Enable creative mode for new created maps."); + gettext("Enable creative mode for all players"); gettext("Fixed map seed"); gettext("A chosen map seed for a new map, leave empty for random.\nWill be overridden when creating a new world in the main menu."); gettext("Default password"); @@ -601,7 +597,7 @@ fake_function() { gettext("Acceleration of gravity, in nodes per second per second."); gettext("Advanced"); gettext("Deprecated Lua API handling"); - gettext("Handling for deprecated Lua API calls:\n- legacy: (try to) mimic old behaviour (default for release).\n- log: mimic and log backtrace of deprecated call (default for debug).\n- error: abort on usage of deprecated call (suggested for mod developers)."); + gettext("Handling for deprecated Lua API calls:\n- none: Do not log deprecated calls\n- log: mimic and log backtrace of deprecated call (default).\n- error: abort on usage of deprecated call (suggested for mod developers)."); gettext("Max. clearobjects extra blocks"); gettext("Number of extra blocks that can be loaded by /clearobjects at once.\nThis is a trade-off between sqlite transaction overhead and\nmemory consumption (4096=100MB, as a rule of thumb)."); gettext("Unload unused server data"); @@ -610,12 +606,16 @@ fake_function() { gettext("Maximum number of statically stored objects in a block."); gettext("Synchronous SQLite"); gettext("See https://www.sqlite.org/pragma.html#pragma_synchronous"); + gettext("Map Compression Level for Disk Storage"); + gettext("ZLib compression level to use when saving mapblocks to disk.\n-1 - Zlib's default compression level\n0 - no compresson, fastest\n9 - best compression, slowest\n(levels 1-3 use Zlib's \"fast\" method, 4-9 use the normal method)"); gettext("Dedicated server step"); gettext("Length of a server tick and the interval at which objects are generally updated over\nnetwork."); gettext("Active block management interval"); gettext("Length of time between active block management cycles"); gettext("ABM interval"); gettext("Length of time between Active Block Modifier (ABM) execution cycles"); + gettext("ABM time budget"); + gettext("The time budget allowed for ABMs to execute on each step\n(as a fraction of the ABM Interval)"); gettext("NodeTimer interval"); gettext("Length of time between NodeTimer execution cycles"); gettext("Ignore world errors"); @@ -687,8 +687,6 @@ fake_function() { gettext("Maximum time in ms a file download (e.g. a mod download) may take."); gettext("High-precision FPU"); gettext("Makes DirectX work with LuaJIT. Disable if it causes troubles."); - gettext("Main menu style"); - gettext("Changes the main menu UI:\n- Full: Multiple singleplayer worlds, game choice, texture pack chooser, etc.\n- Simple: One singleplayer world, no game or texture pack choosers. May be\nnecessary for smaller screens."); gettext("Main menu script"); gettext("Replaces the default main menu with a custom one."); gettext("Engine profiling data print interval"); @@ -958,6 +956,12 @@ fake_function() { gettext("Terrain noise threshold for hills.\nControls proportion of world area covered by hills.\nAdjust towards 0.0 for a larger proportion."); gettext("Hill steepness"); gettext("Controls steepness/height of hills."); + gettext("Cavern limit"); + gettext("Y-level of cavern upper limit."); + gettext("Cavern taper"); + gettext("Y-distance over which caverns expand to full size."); + gettext("Cavern threshold"); + gettext("Defines full size of caverns, smaller values create larger caverns."); gettext("Dungeon minimum Y"); gettext("Lower Y limit of dungeons."); gettext("Dungeon maximum Y"); @@ -971,6 +975,8 @@ fake_function() { gettext("First of two 3D noises that together define tunnels."); gettext("Cave2 noise"); gettext("Second of two 3D noises that together define tunnels."); + gettext("Cavern noise"); + gettext("3D noise defining giant caverns."); gettext("Dungeon noise"); gettext("3D noise that determines number of dungeons per mapchunk."); gettext("Mapgen Fractal"); @@ -1097,4 +1103,6 @@ fake_function() { gettext("The URL for the content repository"); gettext("ContentDB Flag Blacklist"); gettext("Comma-separated list of flags to hide in the content repository.\n\"nonfree\" can be used to hide packages which do not qualify as 'free software',\nas defined by the Free Software Foundation.\nYou can also specify content ratings.\nThese flags are independent from Minetest versions,\nso see a full list at https://content.minetest.net/help/content_flags/"); + gettext("ContentDB Max Concurrent Downloads"); + gettext("Maximum number of concurrent downloads. Downloads exceeding this limit will be queued.\nThis should be lower than curl_parallel_limit."); } diff --git a/src/tool.cpp b/src/tool.cpp index 90f4f9c12..3f639a69e 100644 --- a/src/tool.cpp +++ b/src/tool.cpp @@ -23,6 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "log.h" #include "inventory.h" #include "exceptions.h" +#include "convert_json.h" #include "util/serialize.h" #include "util/numeric.h" @@ -142,7 +143,7 @@ void ToolCapabilities::serializeJson(std::ostream &os) const } root["damage_groups"] = damage_groups_object; - os << root; + fastWriteJson(root, os); } void ToolCapabilities::deserializeJson(std::istream &is) diff --git a/src/translation.cpp b/src/translation.cpp index 82e813a5d..55c958fa2 100644 --- a/src/translation.cpp +++ b/src/translation.cpp @@ -144,14 +144,13 @@ void Translations::loadTranslation(const std::string &data) } std::wstring oword1 = word1.str(), oword2 = word2.str(); - if (oword2.empty()) { - oword2 = oword1; - errorstream << "Ignoring empty translation for \"" - << wide_to_utf8(oword1) << "\"" << std::endl; + if (!oword2.empty()) { + std::wstring translation_index = textdomain + L"|"; + translation_index.append(oword1); + m_translations[translation_index] = oword2; + } else { + infostream << "Ignoring empty translation for \"" + << wide_to_utf8(oword1) << "\"" << std::endl; } - - std::wstring translation_index = textdomain + L"|"; - translation_index.append(oword1); - m_translations[translation_index] = oword2; } } diff --git a/src/unittest/test.cpp b/src/unittest/test.cpp index 0f6b36649..d4841d559 100644 --- a/src/unittest/test.cpp +++ b/src/unittest/test.cpp @@ -182,7 +182,7 @@ void TestGameDef::defineSomeNodes() "{default_water.png"; f = ContentFeatures(); f.name = itemdef.name; - f.alpha = 128; + f.alpha = ALPHAMODE_BLEND; f.liquid_type = LIQUID_SOURCE; f.liquid_viscosity = 4; f.is_ground_content = true; @@ -203,7 +203,7 @@ void TestGameDef::defineSomeNodes() "{default_lava.png"; f = ContentFeatures(); f.name = itemdef.name; - f.alpha = 128; + f.alpha = ALPHAMODE_OPAQUE; f.liquid_type = LIQUID_SOURCE; f.liquid_viscosity = 7; f.light_source = LIGHT_MAX-1; diff --git a/src/unittest/test_clientactiveobjectmgr.cpp b/src/unittest/test_clientactiveobjectmgr.cpp index 4d2846c8d..2d508cf32 100644 --- a/src/unittest/test_clientactiveobjectmgr.cpp +++ b/src/unittest/test_clientactiveobjectmgr.cpp @@ -29,6 +29,7 @@ public: TestClientActiveObject() : ClientActiveObject(0, nullptr, nullptr) {} ~TestClientActiveObject() = default; ActiveObjectType getType() const { return ACTIVEOBJECT_TYPE_TEST; } + virtual void addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr) {} }; class TestClientActiveObjectMgr : public TestBase diff --git a/src/unittest/test_connection.cpp b/src/unittest/test_connection.cpp index c5e4085e1..c3aacc536 100644 --- a/src/unittest/test_connection.cpp +++ b/src/unittest/test_connection.cpp @@ -39,6 +39,7 @@ public: void runTests(IGameDef *gamedef); + void testNetworkPacketSerialize(); void testHelpers(); void testConnectSendReceive(); }; @@ -47,6 +48,7 @@ static TestConnection g_test_instance; void TestConnection::runTests(IGameDef *gamedef) { + TEST(testNetworkPacketSerialize); TEST(testHelpers); TEST(testConnectSendReceive); } @@ -78,6 +80,39 @@ struct Handler : public con::PeerHandler const char *name; }; +void TestConnection::testNetworkPacketSerialize() +{ + const static u8 expected[] = { + 0x00, 0x7b, + 0x00, 0x02, 0xd8, 0x42, 0xdf, 0x9a + }; + + if (sizeof(wchar_t) == 2) + warningstream << __func__ << " may fail on this platform." << std::endl; + + { + NetworkPacket pkt(123, 0); + + // serializing wide strings should do surrogate encoding, we test that here + pkt << std::wstring(L"\U00020b9a"); + + SharedBuffer<u8> buf = pkt.oldForgePacket(); + UASSERTEQ(int, buf.getSize(), sizeof(expected)); + UASSERT(!memcmp(expected, &buf[0], buf.getSize())); + } + + { + NetworkPacket pkt; + pkt.putRawPacket(expected, sizeof(expected), 0); + + // same for decoding + std::wstring pkt_s; + pkt >> pkt_s; + + UASSERT(pkt_s == L"\U00020b9a"); + } +} + void TestConnection::testHelpers() { // Some constants for testing diff --git a/src/unittest/test_map_settings_manager.cpp b/src/unittest/test_map_settings_manager.cpp index 3d642a9b4..81ca68705 100644 --- a/src/unittest/test_map_settings_manager.cpp +++ b/src/unittest/test_map_settings_manager.cpp @@ -30,7 +30,7 @@ public: TestMapSettingsManager() { TestManager::registerTestModule(this); } const char *getName() { return "TestMapSettingsManager"; } - void makeUserConfig(Settings *conf); + void makeUserConfig(); std::string makeMetaFile(bool make_corrupt); void runTests(IGameDef *gamedef); @@ -65,8 +65,11 @@ void check_noise_params(const NoiseParams *np1, const NoiseParams *np2) } -void TestMapSettingsManager::makeUserConfig(Settings *conf) +void TestMapSettingsManager::makeUserConfig() { + delete Settings::getLayer(SL_GLOBAL); + Settings *conf = Settings::createLayer(SL_GLOBAL); + conf->set("mg_name", "v7"); conf->set("seed", "5678"); conf->set("water_level", "20"); @@ -103,12 +106,11 @@ std::string TestMapSettingsManager::makeMetaFile(bool make_corrupt) void TestMapSettingsManager::testMapSettingsManager() { - Settings user_settings; - makeUserConfig(&user_settings); + makeUserConfig(); std::string test_mapmeta_path = makeMetaFile(false); - MapSettingsManager mgr(&user_settings, test_mapmeta_path); + MapSettingsManager mgr(test_mapmeta_path); std::string value; UASSERT(mgr.getMapSetting("mg_name", &value)); @@ -140,6 +142,12 @@ void TestMapSettingsManager::testMapSettingsManager() mgr.setMapSettingNoiseParams("mgv5_np_height", &script_np_height); mgr.setMapSettingNoiseParams("mgv5_np_factor", &script_np_factor); + { + NoiseParams dummy; + mgr.getMapSettingNoiseParams("mgv5_np_factor", &dummy); + check_noise_params(&dummy, &script_np_factor); + } + // Now make our Params and see if the values are correctly sourced MapgenParams *params = mgr.makeMapgenParams(); UASSERT(params->mgtype == MAPGEN_V5); @@ -188,50 +196,66 @@ void TestMapSettingsManager::testMapSettingsManager() void TestMapSettingsManager::testMapMetaSaveLoad() { - Settings conf; std::string path = getTestTempDirectory() + DIR_DELIM + "foobar" + DIR_DELIM + "map_meta.txt"; + makeUserConfig(); + Settings &conf = *Settings::getLayer(SL_GLOBAL); + + // There cannot be two MapSettingsManager + // copy the mapgen params to compare them + MapgenParams params1, params2; // Create a set of mapgen params and save them to map meta - conf.set("seed", "12345"); - conf.set("water_level", "5"); - MapSettingsManager mgr1(&conf, path); - MapgenParams *params1 = mgr1.makeMapgenParams(); - UASSERT(params1); - UASSERT(mgr1.saveMapMeta()); + { + conf.set("seed", "12345"); + conf.set("water_level", "5"); + MapSettingsManager mgr(path); + MapgenParams *params = mgr.makeMapgenParams(); + UASSERT(params); + params1 = *params; + params1.bparams = nullptr; // No double-free + UASSERT(mgr.saveMapMeta()); + } // Now try loading the map meta to mapgen params - conf.set("seed", "67890"); - conf.set("water_level", "32"); - MapSettingsManager mgr2(&conf, path); - UASSERT(mgr2.loadMapMeta()); - MapgenParams *params2 = mgr2.makeMapgenParams(); - UASSERT(params2); + { + conf.set("seed", "67890"); + conf.set("water_level", "32"); + MapSettingsManager mgr(path); + UASSERT(mgr.loadMapMeta()); + MapgenParams *params = mgr.makeMapgenParams(); + UASSERT(params); + params2 = *params; + params2.bparams = nullptr; // No double-free + } // Check that both results are correct - UASSERTEQ(u64, params1->seed, 12345); - UASSERTEQ(s16, params1->water_level, 5); - UASSERTEQ(u64, params2->seed, 12345); - UASSERTEQ(s16, params2->water_level, 5); + UASSERTEQ(u64, params1.seed, 12345); + UASSERTEQ(s16, params1.water_level, 5); + UASSERTEQ(u64, params2.seed, 12345); + UASSERTEQ(s16, params2.water_level, 5); } void TestMapSettingsManager::testMapMetaFailures() { std::string test_mapmeta_path; - Settings conf; // Check to see if it'll fail on a non-existent map meta file - test_mapmeta_path = "woobawooba/fgdfg/map_meta.txt"; - UASSERT(!fs::PathExists(test_mapmeta_path)); + { + test_mapmeta_path = "woobawooba/fgdfg/map_meta.txt"; + UASSERT(!fs::PathExists(test_mapmeta_path)); - MapSettingsManager mgr1(&conf, test_mapmeta_path); - UASSERT(!mgr1.loadMapMeta()); + MapSettingsManager mgr1(test_mapmeta_path); + UASSERT(!mgr1.loadMapMeta()); + } // Check to see if it'll fail on a corrupt map meta file - test_mapmeta_path = makeMetaFile(true); - UASSERT(fs::PathExists(test_mapmeta_path)); + { + test_mapmeta_path = makeMetaFile(true); + UASSERT(fs::PathExists(test_mapmeta_path)); - MapSettingsManager mgr2(&conf, test_mapmeta_path); - UASSERT(!mgr2.loadMapMeta()); + MapSettingsManager mgr2(test_mapmeta_path); + UASSERT(!mgr2.loadMapMeta()); + } } diff --git a/src/unittest/test_noderesolver.cpp b/src/unittest/test_noderesolver.cpp index 28da43620..ed66093a9 100644 --- a/src/unittest/test_noderesolver.cpp +++ b/src/unittest/test_noderesolver.cpp @@ -56,6 +56,8 @@ void TestNodeResolver::runTests(IGameDef *gamedef) class Foobar : public NodeResolver { public: + friend class TestNodeResolver; // m_ndef + void resolveNodeNames(); content_t test_nr_node1; diff --git a/src/unittest/test_schematic.cpp b/src/unittest/test_schematic.cpp index da4ce50d2..d2f027eb4 100644 --- a/src/unittest/test_schematic.cpp +++ b/src/unittest/test_schematic.cpp @@ -66,13 +66,14 @@ void TestSchematic::testMtsSerializeDeserialize(const NodeDefManager *ndef) std::stringstream ss(std::ios_base::binary | std::ios_base::in | std::ios_base::out); - std::vector<std::string> names; - names.emplace_back("foo"); - names.emplace_back("bar"); - names.emplace_back("baz"); - names.emplace_back("qux"); - - Schematic schem, schem2; + Schematic schem; + { + std::vector<std::string> &names = schem.m_nodenames; + names.emplace_back("foo"); + names.emplace_back("bar"); + names.emplace_back("baz"); + names.emplace_back("qux"); + } schem.flags = 0; schem.size = size; @@ -83,18 +84,21 @@ void TestSchematic::testMtsSerializeDeserialize(const NodeDefManager *ndef) for (s16 y = 0; y != size.Y; y++) schem.slice_probs[y] = MTSCHEM_PROB_ALWAYS; - UASSERT(schem.serializeToMts(&ss, names)); + UASSERT(schem.serializeToMts(&ss)); ss.seekg(0); - names.clear(); - UASSERT(schem2.deserializeFromMts(&ss, &names)); + Schematic schem2; + UASSERT(schem2.deserializeFromMts(&ss)); - UASSERTEQ(size_t, names.size(), 4); - UASSERTEQ(std::string, names[0], "foo"); - UASSERTEQ(std::string, names[1], "bar"); - UASSERTEQ(std::string, names[2], "baz"); - UASSERTEQ(std::string, names[3], "qux"); + { + std::vector<std::string> &names = schem2.m_nodenames; + UASSERTEQ(size_t, names.size(), 4); + UASSERTEQ(std::string, names[0], "foo"); + UASSERTEQ(std::string, names[1], "bar"); + UASSERTEQ(std::string, names[2], "baz"); + UASSERTEQ(std::string, names[3], "qux"); + } UASSERT(schem2.size == size); for (size_t i = 0; i != volume; i++) @@ -120,14 +124,14 @@ void TestSchematic::testLuaTableSerialize(const NodeDefManager *ndef) for (s16 y = 0; y != size.Y; y++) schem.slice_probs[y] = MTSCHEM_PROB_ALWAYS; - std::vector<std::string> names; + std::vector<std::string> &names = schem.m_nodenames; names.emplace_back("air"); names.emplace_back("default:lava_source"); names.emplace_back("default:glass"); std::ostringstream ss(std::ios_base::binary); - UASSERT(schem.serializeToLua(&ss, names, false, 0)); + UASSERT(schem.serializeToLua(&ss, false, 0)); UASSERTEQ(std::string, ss.str(), expected_lua_output); } @@ -159,6 +163,8 @@ void TestSchematic::testFileSerializeDeserialize(const NodeDefManager *ndef) schem1.slice_probs[0] = 80; schem1.slice_probs[1] = 160; schem1.slice_probs[2] = 240; + // Node resolving happened manually. + schem1.m_resolve_done = true; for (size_t i = 0; i != volume; i++) { content_t c = content_map[test_schem2_data[i]]; diff --git a/src/unittest/test_settings.cpp b/src/unittest/test_settings.cpp index f91ba5b67..6b493c9e4 100644 --- a/src/unittest/test_settings.cpp +++ b/src/unittest/test_settings.cpp @@ -21,6 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <cmath> #include "settings.h" +#include "defaultsettings.h" #include "noise.h" class TestSettings : public TestBase { @@ -31,6 +32,7 @@ public: void runTests(IGameDef *gamedef); void testAllSettings(); + void testDefaults(); void testFlagDesc(); static const char *config_text_before; @@ -42,6 +44,7 @@ static TestSettings g_test_instance; void TestSettings::runTests(IGameDef *gamedef) { TEST(testAllSettings); + TEST(testDefaults); TEST(testFlagDesc); } @@ -70,7 +73,8 @@ const char *TestSettings::config_text_before = " with leading whitespace!\n" "\"\"\"\n" "np_terrain = 5, 40, (250, 250, 250), 12341, 5, 0.7, 2.4\n" - "zoop = true"; + "zoop = true\n" + "[dummy_eof_end_tag]\n"; const std::string TestSettings::config_text_after = "leet = 1337\n" @@ -111,12 +115,34 @@ const std::string TestSettings::config_text_after = " animals = cute\n" " num_apples = 4\n" " num_oranges = 53\n" - "}\n"; + "}\n" + "[dummy_eof_end_tag]"; + +void compare_settings(const std::string &name, Settings *a, Settings *b) +{ + auto keys = a->getNames(); + Settings *group1, *group2; + std::string value1, value2; + for (auto &key : keys) { + if (a->getGroupNoEx(key, group1)) { + UASSERT(b->getGroupNoEx(key, group2)); + + compare_settings(name + "->" + key, group1, group2); + continue; + } + + UASSERT(b->getNoEx(key, value1)); + // For identification + value1 = name + "->" + key + "=" + value1; + value2 = name + "->" + key + "=" + a->get(key); + UASSERTCMP(std::string, ==, value2, value1); + } +} void TestSettings::testAllSettings() { try { - Settings s; + Settings s("[dummy_eof_end_tag]"); // Test reading of settings std::istringstream is(config_text_before); @@ -197,21 +223,44 @@ void TestSettings::testAllSettings() is.clear(); is.seekg(0); - UASSERT(s.updateConfigObject(is, os, "", 0) == true); - //printf(">>>> expected config:\n%s\n", TEST_CONFIG_TEXT_AFTER); - //printf(">>>> actual config:\n%s\n", os.str().c_str()); -#if __cplusplus < 201103L - // This test only works in older C++ versions than C++11 because we use unordered_map - UASSERT(os.str() == config_text_after); -#endif + UASSERT(s.updateConfigObject(is, os, 0) == true); + + { + // Confirm settings + Settings s2("[dummy_eof_end_tag]"); + std::istringstream is(config_text_after, std::ios_base::binary); + UASSERT(s2.parseConfigLines(is) == true); + + compare_settings("(main)", &s, &s2); + } + } catch (SettingNotFoundException &e) { UASSERT(!"Setting not found!"); } } +void TestSettings::testDefaults() +{ + Settings *game = Settings::createLayer(SL_GAME); + Settings *def = Settings::getLayer(SL_DEFAULTS); + + def->set("name", "FooBar"); + UASSERT(def->get("name") == "FooBar"); + UASSERT(game->get("name") == "FooBar"); + + game->set("name", "Baz"); + UASSERT(game->get("name") == "Baz"); + + delete game; + + // Restore default settings + delete Settings::getLayer(SL_DEFAULTS); + set_default_settings(); +} + void TestSettings::testFlagDesc() { - Settings s; + Settings &s = *Settings::createLayer(SL_GAME); FlagDesc flagdesc[] = { { "biomes", 0x01 }, { "trees", 0x02 }, @@ -242,4 +291,6 @@ void TestSettings::testFlagDesc() // Enabled: tables s.set("test_flags", "16"); UASSERT(s.getFlagStr("test_flags", flagdesc, nullptr) == 0x10); + + delete &s; } diff --git a/src/unittest/test_utilities.cpp b/src/unittest/test_utilities.cpp index 447b591e1..93ba3f844 100644 --- a/src/unittest/test_utilities.cpp +++ b/src/unittest/test_utilities.cpp @@ -247,8 +247,8 @@ void TestUtilities::testStartsWith() void TestUtilities::testStrEqual() { - UASSERT(str_equal(narrow_to_wide("abc"), narrow_to_wide("abc"))); - UASSERT(str_equal(narrow_to_wide("ABC"), narrow_to_wide("abc"), true)); + UASSERT(str_equal(utf8_to_wide("abc"), utf8_to_wide("abc"))); + UASSERT(str_equal(utf8_to_wide("ABC"), utf8_to_wide("abc"), true)); } @@ -302,9 +302,18 @@ void TestUtilities::testAsciiPrintableHelper() void TestUtilities::testUTF8() { - UASSERT(wide_to_utf8(utf8_to_wide("")) == ""); - UASSERT(wide_to_utf8(utf8_to_wide("the shovel dug a crumbly node!")) - == "the shovel dug a crumbly node!"); + UASSERT(utf8_to_wide("¤") == L"¤"); + + UASSERT(wide_to_utf8(L"¤") == "¤"); + + UASSERTEQ(std::string, wide_to_utf8(utf8_to_wide("")), ""); + UASSERTEQ(std::string, wide_to_utf8(utf8_to_wide("the shovel dug a crumbly node!")), + "the shovel dug a crumbly node!"); + UASSERTEQ(std::string, wide_to_utf8(utf8_to_wide("-ä-")), + "-ä-"); + UASSERTEQ(std::string, wide_to_utf8(utf8_to_wide("-\xF0\xA0\x80\x8B-")), + "-\xF0\xA0\x80\x8B-"); + } void TestUtilities::testRemoveEscapes() diff --git a/src/util/Optional.h b/src/util/Optional.h new file mode 100644 index 000000000..9c2842b43 --- /dev/null +++ b/src/util/Optional.h @@ -0,0 +1,77 @@ +/* +Minetest +Copyright (C) 2021 rubenwardy + +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 "debug.h" + +struct nullopt_t +{ +}; +constexpr nullopt_t nullopt{}; + +/** + * An implementation of optional for C++11, which aims to be + * compatible with a subset of std::optional features. + * + * Unfortunately, Minetest doesn't use C++17 yet. + * + * @tparam T The type to be stored + */ +template <typename T> +class Optional +{ + bool m_has_value = false; + T m_value; + +public: + Optional() noexcept {} + Optional(nullopt_t) noexcept {} + Optional(const T &value) noexcept : m_has_value(true), m_value(value) {} + Optional(const Optional<T> &other) noexcept : + m_has_value(other.m_has_value), m_value(other.m_value) + { + } + + void operator=(nullopt_t) noexcept { m_has_value = false; } + + void operator=(const Optional<T> &other) noexcept + { + m_has_value = other.m_has_value; + m_value = other.m_value; + } + + T &value() + { + FATAL_ERROR_IF(!m_has_value, "optional doesn't have value"); + return m_value; + } + + const T &value() const + { + FATAL_ERROR_IF(!m_has_value, "optional doesn't have value"); + return m_value; + } + + const T &value_or(const T &def) const { return m_has_value ? m_value : def; } + + bool has_value() const noexcept { return m_has_value; } + + explicit operator bool() const { return m_has_value; } +}; diff --git a/src/util/areastore.cpp b/src/util/areastore.cpp index cea526336..67bfef0c0 100644 --- a/src/util/areastore.cpp +++ b/src/util/areastore.cpp @@ -96,16 +96,15 @@ void AreaStore::deserialize(std::istream &is) u16 num_areas = readU16(is); std::vector<Area> areas; + areas.reserve(num_areas); for (u32 i = 0; i < num_areas; ++i) { Area a(U32_MAX); a.minedge = readV3S16(is); a.maxedge = readV3S16(is); u16 data_len = readU16(is); - char *data = new char[data_len]; - is.read(data, data_len); - a.data = std::string(data, data_len); - areas.emplace_back(a); - delete [] data; + a.data = std::string(data_len, '\0'); + is.read(&a.data[0], data_len); + areas.emplace_back(std::move(a)); } bool read_ids = is.good(); // EOF for old formats diff --git a/src/util/container.h b/src/util/container.h index 2ad2bbfc7..1c4a219f0 100644 --- a/src/util/container.h +++ b/src/util/container.h @@ -90,8 +90,7 @@ public: bool get(const Key &name, Value *result) const { MutexAutoLock lock(m_mutex); - typename std::map<Key, Value>::const_iterator n = - m_values.find(name); + auto n = m_values.find(name); if (n == m_values.end()) return false; if (result) @@ -103,11 +102,9 @@ public: { MutexAutoLock lock(m_mutex); std::vector<Value> result; - for (typename std::map<Key, Value>::const_iterator - it = m_values.begin(); - it != m_values.end(); ++it){ + result.reserve(m_values.size()); + for (auto it = m_values.begin(); it != m_values.end(); ++it) result.push_back(it->second); - } return result; } @@ -136,7 +133,7 @@ public: return m_queue.empty(); } - void push_back(T t) + void push_back(const T &t) { MutexAutoLock lock(m_mutex); m_queue.push_back(t); @@ -151,7 +148,7 @@ public: if (m_signal.wait(wait_time_max_ms)) { MutexAutoLock lock(m_mutex); - T t = m_queue.front(); + T t = std::move(m_queue.front()); m_queue.pop_front(); return t; } @@ -164,7 +161,7 @@ public: if (m_signal.wait(wait_time_max_ms)) { MutexAutoLock lock(m_mutex); - T t = m_queue.front(); + T t = std::move(m_queue.front()); m_queue.pop_front(); return t; } @@ -178,7 +175,7 @@ public: MutexAutoLock lock(m_mutex); - T t = m_queue.front(); + T t = std::move(m_queue.front()); m_queue.pop_front(); return t; } @@ -188,7 +185,7 @@ public: if (m_signal.wait(wait_time_max_ms)) { MutexAutoLock lock(m_mutex); - T t = m_queue.back(); + T t = std::move(m_queue.back()); m_queue.pop_back(); return t; } @@ -204,7 +201,7 @@ public: if (m_signal.wait(wait_time_max_ms)) { MutexAutoLock lock(m_mutex); - T t = m_queue.back(); + T t = std::move(m_queue.back()); m_queue.pop_back(); return t; } @@ -218,7 +215,7 @@ public: MutexAutoLock lock(m_mutex); - T t = m_queue.back(); + T t = std::move(m_queue.back()); m_queue.pop_back(); return t; } diff --git a/src/util/enriched_string.cpp b/src/util/enriched_string.cpp index 762d094eb..b1f95215e 100644 --- a/src/util/enriched_string.cpp +++ b/src/util/enriched_string.cpp @@ -65,12 +65,14 @@ void EnrichedString::operator=(const wchar_t *str) addAtEnd(translate_string(std::wstring(str)), m_default_color); } -void EnrichedString::addAtEnd(const std::wstring &s, const SColor &initial_color) +void EnrichedString::addAtEnd(const std::wstring &s, SColor initial_color) { SColor color(initial_color); bool use_default = (m_default_length == m_string.size() && color == m_default_color); + m_colors.reserve(m_colors.size() + s.size()); + size_t i = 0; while (i < s.length()) { if (s[i] != L'\x1b') { @@ -200,12 +202,6 @@ const std::wstring &EnrichedString::getString() const return m_string; } -void EnrichedString::setDefaultColor(const irr::video::SColor &color) -{ - m_default_color = color; - updateDefaultColor(); -} - void EnrichedString::updateDefaultColor() { sanity_check(m_default_length <= m_colors.size()); diff --git a/src/util/enriched_string.h b/src/util/enriched_string.h index c8a095887..16a0eef74 100644 --- a/src/util/enriched_string.h +++ b/src/util/enriched_string.h @@ -23,18 +23,22 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <vector> #include <SColor.h> +using namespace irr; + class EnrichedString { public: EnrichedString(); EnrichedString(const std::wstring &s, - const irr::video::SColor &color = irr::video::SColor(255, 255, 255, 255)); + const video::SColor &color = video::SColor(255, 255, 255, 255)); EnrichedString(const wchar_t *str, - const irr::video::SColor &color = irr::video::SColor(255, 255, 255, 255)); + const video::SColor &color = video::SColor(255, 255, 255, 255)); EnrichedString(const std::wstring &string, - const std::vector<irr::video::SColor> &colors); - void clear(); + const std::vector<video::SColor> &colors); void operator=(const wchar_t *str); - void addAtEnd(const std::wstring &s, const irr::video::SColor &color); + + void clear(); + + void addAtEnd(const std::wstring &s, video::SColor color); // Adds the character source[i] at the end. // An EnrichedString should always be able to be copied @@ -49,12 +53,16 @@ public: EnrichedString operator+(const EnrichedString &other) const; void operator+=(const EnrichedString &other); const wchar_t *c_str() const; - const std::vector<irr::video::SColor> &getColors() const; + const std::vector<video::SColor> &getColors() const; const std::wstring &getString() const; - void setDefaultColor(const irr::video::SColor &color); + inline void setDefaultColor(video::SColor color) + { + m_default_color = color; + updateDefaultColor(); + } void updateDefaultColor(); - inline const irr::video::SColor &getDefaultColor() const + inline const video::SColor &getDefaultColor() const { return m_default_color; } @@ -80,11 +88,11 @@ public: { return m_has_background; } - inline irr::video::SColor getBackground() const + inline video::SColor getBackground() const { return m_background; } - inline void setBackground(const irr::video::SColor &color) + inline void setBackground(video::SColor color) { m_background = color; m_has_background = true; @@ -92,10 +100,10 @@ public: private: std::wstring m_string; - std::vector<irr::video::SColor> m_colors; + std::vector<video::SColor> m_colors; bool m_has_background; - irr::video::SColor m_default_color; - irr::video::SColor m_background; + video::SColor m_default_color; + video::SColor m_background; // This variable defines the length of the default-colored text. // Change this to a std::vector if an "end coloring" tag is wanted. size_t m_default_length = 0; diff --git a/src/util/numeric.cpp b/src/util/numeric.cpp index 1af3f66be..99e4cfb5c 100644 --- a/src/util/numeric.cpp +++ b/src/util/numeric.cpp @@ -106,10 +106,6 @@ u64 murmur_hash_64_ua(const void *key, int len, unsigned int seed) bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir, f32 camera_fov, f32 range, f32 *distance_ptr) { - // Maximum radius of a block. The magic number is - // sqrt(3.0) / 2.0 in literal form. - static constexpr const f32 block_max_radius = 0.866025403784f * MAP_BLOCKSIZE * BS; - v3s16 blockpos_nodes = blockpos_b * MAP_BLOCKSIZE; // Block center position @@ -123,7 +119,7 @@ bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir, v3f blockpos_relative = blockpos - camera_pos; // Total distance - f32 d = MYMAX(0, blockpos_relative.getLength() - block_max_radius); + f32 d = MYMAX(0, blockpos_relative.getLength() - BLOCK_MAX_RADIUS); if (distance_ptr) *distance_ptr = d; @@ -141,7 +137,7 @@ bool isBlockInSight(v3s16 blockpos_b, v3f camera_pos, v3f camera_dir, // such that a block that has any portion visible with the // current camera position will have the center visible at the // adjusted postion - f32 adjdist = block_max_radius / cos((M_PI - camera_fov) / 2); + f32 adjdist = BLOCK_MAX_RADIUS / cos((M_PI - camera_fov) / 2); // Block position relative to adjusted camera v3f blockpos_adj = blockpos - (camera_pos - camera_dir * adjdist); diff --git a/src/util/numeric.h b/src/util/numeric.h index 864ab7543..32a6f4312 100644 --- a/src/util/numeric.h +++ b/src/util/numeric.h @@ -20,6 +20,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once #include "basic_macros.h" +#include "constants.h" #include "irrlichttypes.h" #include "irr_v2d.h" #include "irr_v3d.h" @@ -36,6 +37,9 @@ with this program; if not, write to the Free Software Foundation, Inc., y = temp; \ } while (0) +// Maximum radius of a block. The magic number is +// sqrt(3.0) / 2.0 in literal form. +static constexpr const f32 BLOCK_MAX_RADIUS = 0.866025403784f * MAP_BLOCKSIZE * BS; inline s16 getContainerPos(s16 p, s16 d) { diff --git a/src/util/serialize.h b/src/util/serialize.h index b3ec28eab..15bdd050d 100644 --- a/src/util/serialize.h +++ b/src/util/serialize.h @@ -290,7 +290,7 @@ inline void writeS8(u8 *data, s8 i) inline void writeS16(u8 *data, s16 i) { - writeU16(data, (u16)i); + writeU16(data, (u16)i); } inline void writeS32(u8 *data, s32 i) diff --git a/src/util/string.cpp b/src/util/string.cpp index 3ac3b8cf0..eec5ab4cd 100644 --- a/src/util/string.cpp +++ b/src/util/string.cpp @@ -30,7 +30,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <array> #include <sstream> #include <iomanip> -#include <map> +#include <unordered_map> #ifndef _WIN32 #include <iconv.h> @@ -44,14 +44,10 @@ with this program; if not, write to the Free Software Foundation, Inc., #define BSD_ICONV_USED #endif -static bool parseHexColorString(const std::string &value, video::SColor &color, - unsigned char default_alpha = 0xff); -static bool parseNamedColorString(const std::string &value, video::SColor &color); - #ifndef _WIN32 -bool convert(const char *to, const char *from, char *outbuf, - size_t outbuf_size, char *inbuf, size_t inbuf_size) +static bool convert(const char *to, const char *from, char *outbuf, + size_t *outbuf_size, char *inbuf, size_t inbuf_size) { iconv_t cd = iconv_open(to, from); @@ -60,15 +56,14 @@ bool convert(const char *to, const char *from, char *outbuf, #else char *inbuf_ptr = inbuf; #endif - char *outbuf_ptr = outbuf; size_t *inbuf_left_ptr = &inbuf_size; - size_t *outbuf_left_ptr = &outbuf_size; + const size_t old_outbuf_size = *outbuf_size; size_t old_size = inbuf_size; while (inbuf_size > 0) { - iconv(cd, &inbuf_ptr, inbuf_left_ptr, &outbuf_ptr, outbuf_left_ptr); + iconv(cd, &inbuf_ptr, inbuf_left_ptr, &outbuf_ptr, outbuf_size); if (inbuf_size == old_size) { iconv_close(cd); return false; @@ -77,11 +72,12 @@ bool convert(const char *to, const char *from, char *outbuf, } iconv_close(cd); + *outbuf_size = old_outbuf_size - *outbuf_size; return true; } #ifdef __ANDROID__ -// Android need manual caring to support the full character set possible with wchar_t +// On Android iconv disagrees how big a wchar_t is for whatever reason const char *DEFAULT_ENCODING = "UTF-32LE"; #else const char *DEFAULT_ENCODING = "WCHAR_T"; @@ -89,58 +85,52 @@ const char *DEFAULT_ENCODING = "WCHAR_T"; std::wstring utf8_to_wide(const std::string &input) { - size_t inbuf_size = input.length() + 1; + const size_t inbuf_size = input.length(); // maximum possible size, every character is sizeof(wchar_t) bytes - size_t outbuf_size = (input.length() + 1) * sizeof(wchar_t); + size_t outbuf_size = input.length() * sizeof(wchar_t); - char *inbuf = new char[inbuf_size]; + char *inbuf = new char[inbuf_size]; // intentionally NOT null-terminated memcpy(inbuf, input.c_str(), inbuf_size); - char *outbuf = new char[outbuf_size]; - memset(outbuf, 0, outbuf_size); + std::wstring out; + out.resize(outbuf_size / sizeof(wchar_t)); #ifdef __ANDROID__ - // Android need manual caring to support the full character set possible with wchar_t SANITY_CHECK(sizeof(wchar_t) == 4); #endif - if (!convert(DEFAULT_ENCODING, "UTF-8", outbuf, outbuf_size, inbuf, inbuf_size)) { + char *outbuf = reinterpret_cast<char*>(&out[0]); + if (!convert(DEFAULT_ENCODING, "UTF-8", outbuf, &outbuf_size, inbuf, inbuf_size)) { infostream << "Couldn't convert UTF-8 string 0x" << hex_encode(input) << " into wstring" << std::endl; delete[] inbuf; - delete[] outbuf; return L"<invalid UTF-8 string>"; } - std::wstring out((wchar_t *)outbuf); - delete[] inbuf; - delete[] outbuf; + out.resize(outbuf_size / sizeof(wchar_t)); return out; } std::string wide_to_utf8(const std::wstring &input) { - size_t inbuf_size = (input.length() + 1) * sizeof(wchar_t); - // maximum possible size: utf-8 encodes codepoints using 1 up to 6 bytes - size_t outbuf_size = (input.length() + 1) * 6; + const size_t inbuf_size = input.length() * sizeof(wchar_t); + // maximum possible size: utf-8 encodes codepoints using 1 up to 4 bytes + size_t outbuf_size = input.length() * 4; - char *inbuf = new char[inbuf_size]; + char *inbuf = new char[inbuf_size]; // intentionally NOT null-terminated memcpy(inbuf, input.c_str(), inbuf_size); - char *outbuf = new char[outbuf_size]; - memset(outbuf, 0, outbuf_size); + std::string out; + out.resize(outbuf_size); - if (!convert("UTF-8", DEFAULT_ENCODING, outbuf, outbuf_size, inbuf, inbuf_size)) { + if (!convert("UTF-8", DEFAULT_ENCODING, &out[0], &outbuf_size, inbuf, inbuf_size)) { infostream << "Couldn't convert wstring 0x" << hex_encode(inbuf, inbuf_size) << " into UTF-8 string" << std::endl; delete[] inbuf; - delete[] outbuf; - return "<invalid wstring>"; + return "<invalid wide string>"; } - std::string out(outbuf); - delete[] inbuf; - delete[] outbuf; + out.resize(outbuf_size); return out; } @@ -172,74 +162,15 @@ std::string wide_to_utf8(const std::wstring &input) #endif // _WIN32 -// You must free the returned string! -// The returned string is allocated using new wchar_t *utf8_to_wide_c(const char *str) { std::wstring ret = utf8_to_wide(std::string(str)); size_t len = ret.length(); wchar_t *ret_c = new wchar_t[len + 1]; - memset(ret_c, 0, (len + 1) * sizeof(wchar_t)); - memcpy(ret_c, ret.c_str(), len * sizeof(wchar_t)); + memcpy(ret_c, ret.c_str(), (len + 1) * sizeof(wchar_t)); return ret_c; } -// You must free the returned string! -// The returned string is allocated using new -wchar_t *narrow_to_wide_c(const char *str) -{ - wchar_t *nstr = nullptr; -#if defined(_WIN32) - int nResult = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR) str, -1, 0, 0); - if (nResult == 0) { - errorstream<<"gettext: MultiByteToWideChar returned null"<<std::endl; - } else { - nstr = new wchar_t[nResult]; - MultiByteToWideChar(CP_UTF8, 0, (LPCSTR) str, -1, (WCHAR *) nstr, nResult); - } -#else - size_t len = strlen(str); - nstr = new wchar_t[len + 1]; - - std::wstring intermediate = narrow_to_wide(str); - memset(nstr, 0, (len + 1) * sizeof(wchar_t)); - memcpy(nstr, intermediate.c_str(), len * sizeof(wchar_t)); -#endif - - return nstr; -} - -std::wstring narrow_to_wide(const std::string &mbs) { -#ifdef __ANDROID__ - return utf8_to_wide(mbs); -#else - size_t wcl = mbs.size(); - Buffer<wchar_t> wcs(wcl + 1); - size_t len = mbstowcs(*wcs, mbs.c_str(), wcl); - if (len == (size_t)(-1)) - return L"<invalid multibyte string>"; - wcs[len] = 0; - return *wcs; -#endif -} - - -std::string wide_to_narrow(const std::wstring &wcs) -{ -#ifdef __ANDROID__ - return wide_to_utf8(wcs); -#else - size_t mbl = wcs.size() * 4; - SharedBuffer<char> mbs(mbl+1); - size_t len = wcstombs(*mbs, wcs.c_str(), mbl); - if (len == (size_t)(-1)) - return "Character conversion failed!"; - - mbs[len] = 0; - return *mbs; -#endif -} - std::string urlencode(const std::string &str) { @@ -389,29 +320,10 @@ u64 read_seed(const char *str) return num; } -bool parseColorString(const std::string &value, video::SColor &color, bool quiet, - unsigned char default_alpha) -{ - bool success; - - if (value[0] == '#') - success = parseHexColorString(value, color, default_alpha); - else - success = parseNamedColorString(value, color); - - if (!success && !quiet) - errorstream << "Invalid color: \"" << value << "\"" << std::endl; - - return success; -} - static bool parseHexColorString(const std::string &value, video::SColor &color, unsigned char default_alpha) { - unsigned char components[] = { 0x00, 0x00, 0x00, default_alpha }; // R,G,B,A - - if (value[0] != '#') - return false; + u8 components[] = {0x00, 0x00, 0x00, default_alpha}; // R,G,B,A size_t len = value.size(); bool short_form; @@ -423,198 +335,182 @@ static bool parseHexColorString(const std::string &value, video::SColor &color, else return false; - bool success = true; - for (size_t pos = 1, cc = 0; pos < len; pos++, cc++) { - assert(cc < sizeof components / sizeof components[0]); if (short_form) { - unsigned char d; - if (!hex_digit_decode(value[pos], d)) { - success = false; - break; - } + u8 d; + if (!hex_digit_decode(value[pos], d)) + return false; + components[cc] = (d & 0xf) << 4 | (d & 0xf); } else { - unsigned char d1, d2; + u8 d1, d2; if (!hex_digit_decode(value[pos], d1) || - !hex_digit_decode(value[pos+1], d2)) { - success = false; - break; - } + !hex_digit_decode(value[pos+1], d2)) + return false; + components[cc] = (d1 & 0xf) << 4 | (d2 & 0xf); - pos++; // skip the second digit -- it's already used + pos++; // skip the second digit -- it's already used } } - if (success) { - color.setRed(components[0]); - color.setGreen(components[1]); - color.setBlue(components[2]); - color.setAlpha(components[3]); - } + color.setRed(components[0]); + color.setGreen(components[1]); + color.setBlue(components[2]); + color.setAlpha(components[3]); - return success; + return true; } -struct ColorContainer { - ColorContainer(); - std::map<const std::string, u32> colors; +const static std::unordered_map<std::string, u32> s_named_colors = { + {"aliceblue", 0xf0f8ff}, + {"antiquewhite", 0xfaebd7}, + {"aqua", 0x00ffff}, + {"aquamarine", 0x7fffd4}, + {"azure", 0xf0ffff}, + {"beige", 0xf5f5dc}, + {"bisque", 0xffe4c4}, + {"black", 00000000}, + {"blanchedalmond", 0xffebcd}, + {"blue", 0x0000ff}, + {"blueviolet", 0x8a2be2}, + {"brown", 0xa52a2a}, + {"burlywood", 0xdeb887}, + {"cadetblue", 0x5f9ea0}, + {"chartreuse", 0x7fff00}, + {"chocolate", 0xd2691e}, + {"coral", 0xff7f50}, + {"cornflowerblue", 0x6495ed}, + {"cornsilk", 0xfff8dc}, + {"crimson", 0xdc143c}, + {"cyan", 0x00ffff}, + {"darkblue", 0x00008b}, + {"darkcyan", 0x008b8b}, + {"darkgoldenrod", 0xb8860b}, + {"darkgray", 0xa9a9a9}, + {"darkgreen", 0x006400}, + {"darkgrey", 0xa9a9a9}, + {"darkkhaki", 0xbdb76b}, + {"darkmagenta", 0x8b008b}, + {"darkolivegreen", 0x556b2f}, + {"darkorange", 0xff8c00}, + {"darkorchid", 0x9932cc}, + {"darkred", 0x8b0000}, + {"darksalmon", 0xe9967a}, + {"darkseagreen", 0x8fbc8f}, + {"darkslateblue", 0x483d8b}, + {"darkslategray", 0x2f4f4f}, + {"darkslategrey", 0x2f4f4f}, + {"darkturquoise", 0x00ced1}, + {"darkviolet", 0x9400d3}, + {"deeppink", 0xff1493}, + {"deepskyblue", 0x00bfff}, + {"dimgray", 0x696969}, + {"dimgrey", 0x696969}, + {"dodgerblue", 0x1e90ff}, + {"firebrick", 0xb22222}, + {"floralwhite", 0xfffaf0}, + {"forestgreen", 0x228b22}, + {"fuchsia", 0xff00ff}, + {"gainsboro", 0xdcdcdc}, + {"ghostwhite", 0xf8f8ff}, + {"gold", 0xffd700}, + {"goldenrod", 0xdaa520}, + {"gray", 0x808080}, + {"green", 0x008000}, + {"greenyellow", 0xadff2f}, + {"grey", 0x808080}, + {"honeydew", 0xf0fff0}, + {"hotpink", 0xff69b4}, + {"indianred", 0xcd5c5c}, + {"indigo", 0x4b0082}, + {"ivory", 0xfffff0}, + {"khaki", 0xf0e68c}, + {"lavender", 0xe6e6fa}, + {"lavenderblush", 0xfff0f5}, + {"lawngreen", 0x7cfc00}, + {"lemonchiffon", 0xfffacd}, + {"lightblue", 0xadd8e6}, + {"lightcoral", 0xf08080}, + {"lightcyan", 0xe0ffff}, + {"lightgoldenrodyellow", 0xfafad2}, + {"lightgray", 0xd3d3d3}, + {"lightgreen", 0x90ee90}, + {"lightgrey", 0xd3d3d3}, + {"lightpink", 0xffb6c1}, + {"lightsalmon", 0xffa07a}, + {"lightseagreen", 0x20b2aa}, + {"lightskyblue", 0x87cefa}, + {"lightslategray", 0x778899}, + {"lightslategrey", 0x778899}, + {"lightsteelblue", 0xb0c4de}, + {"lightyellow", 0xffffe0}, + {"lime", 0x00ff00}, + {"limegreen", 0x32cd32}, + {"linen", 0xfaf0e6}, + {"magenta", 0xff00ff}, + {"maroon", 0x800000}, + {"mediumaquamarine", 0x66cdaa}, + {"mediumblue", 0x0000cd}, + {"mediumorchid", 0xba55d3}, + {"mediumpurple", 0x9370db}, + {"mediumseagreen", 0x3cb371}, + {"mediumslateblue", 0x7b68ee}, + {"mediumspringgreen", 0x00fa9a}, + {"mediumturquoise", 0x48d1cc}, + {"mediumvioletred", 0xc71585}, + {"midnightblue", 0x191970}, + {"mintcream", 0xf5fffa}, + {"mistyrose", 0xffe4e1}, + {"moccasin", 0xffe4b5}, + {"navajowhite", 0xffdead}, + {"navy", 0x000080}, + {"oldlace", 0xfdf5e6}, + {"olive", 0x808000}, + {"olivedrab", 0x6b8e23}, + {"orange", 0xffa500}, + {"orangered", 0xff4500}, + {"orchid", 0xda70d6}, + {"palegoldenrod", 0xeee8aa}, + {"palegreen", 0x98fb98}, + {"paleturquoise", 0xafeeee}, + {"palevioletred", 0xdb7093}, + {"papayawhip", 0xffefd5}, + {"peachpuff", 0xffdab9}, + {"peru", 0xcd853f}, + {"pink", 0xffc0cb}, + {"plum", 0xdda0dd}, + {"powderblue", 0xb0e0e6}, + {"purple", 0x800080}, + {"red", 0xff0000}, + {"rosybrown", 0xbc8f8f}, + {"royalblue", 0x4169e1}, + {"saddlebrown", 0x8b4513}, + {"salmon", 0xfa8072}, + {"sandybrown", 0xf4a460}, + {"seagreen", 0x2e8b57}, + {"seashell", 0xfff5ee}, + {"sienna", 0xa0522d}, + {"silver", 0xc0c0c0}, + {"skyblue", 0x87ceeb}, + {"slateblue", 0x6a5acd}, + {"slategray", 0x708090}, + {"slategrey", 0x708090}, + {"snow", 0xfffafa}, + {"springgreen", 0x00ff7f}, + {"steelblue", 0x4682b4}, + {"tan", 0xd2b48c}, + {"teal", 0x008080}, + {"thistle", 0xd8bfd8}, + {"tomato", 0xff6347}, + {"turquoise", 0x40e0d0}, + {"violet", 0xee82ee}, + {"wheat", 0xf5deb3}, + {"white", 0xffffff}, + {"whitesmoke", 0xf5f5f5}, + {"yellow", 0xffff00}, + {"yellowgreen", 0x9acd32} }; -ColorContainer::ColorContainer() -{ - colors["aliceblue"] = 0xf0f8ff; - colors["antiquewhite"] = 0xfaebd7; - colors["aqua"] = 0x00ffff; - colors["aquamarine"] = 0x7fffd4; - colors["azure"] = 0xf0ffff; - colors["beige"] = 0xf5f5dc; - colors["bisque"] = 0xffe4c4; - colors["black"] = 00000000; - colors["blanchedalmond"] = 0xffebcd; - colors["blue"] = 0x0000ff; - colors["blueviolet"] = 0x8a2be2; - colors["brown"] = 0xa52a2a; - colors["burlywood"] = 0xdeb887; - colors["cadetblue"] = 0x5f9ea0; - colors["chartreuse"] = 0x7fff00; - colors["chocolate"] = 0xd2691e; - colors["coral"] = 0xff7f50; - colors["cornflowerblue"] = 0x6495ed; - colors["cornsilk"] = 0xfff8dc; - colors["crimson"] = 0xdc143c; - colors["cyan"] = 0x00ffff; - colors["darkblue"] = 0x00008b; - colors["darkcyan"] = 0x008b8b; - colors["darkgoldenrod"] = 0xb8860b; - colors["darkgray"] = 0xa9a9a9; - colors["darkgreen"] = 0x006400; - colors["darkgrey"] = 0xa9a9a9; - colors["darkkhaki"] = 0xbdb76b; - colors["darkmagenta"] = 0x8b008b; - colors["darkolivegreen"] = 0x556b2f; - colors["darkorange"] = 0xff8c00; - colors["darkorchid"] = 0x9932cc; - colors["darkred"] = 0x8b0000; - colors["darksalmon"] = 0xe9967a; - colors["darkseagreen"] = 0x8fbc8f; - colors["darkslateblue"] = 0x483d8b; - colors["darkslategray"] = 0x2f4f4f; - colors["darkslategrey"] = 0x2f4f4f; - colors["darkturquoise"] = 0x00ced1; - colors["darkviolet"] = 0x9400d3; - colors["deeppink"] = 0xff1493; - colors["deepskyblue"] = 0x00bfff; - colors["dimgray"] = 0x696969; - colors["dimgrey"] = 0x696969; - colors["dodgerblue"] = 0x1e90ff; - colors["firebrick"] = 0xb22222; - colors["floralwhite"] = 0xfffaf0; - colors["forestgreen"] = 0x228b22; - colors["fuchsia"] = 0xff00ff; - colors["gainsboro"] = 0xdcdcdc; - colors["ghostwhite"] = 0xf8f8ff; - colors["gold"] = 0xffd700; - colors["goldenrod"] = 0xdaa520; - colors["gray"] = 0x808080; - colors["green"] = 0x008000; - colors["greenyellow"] = 0xadff2f; - colors["grey"] = 0x808080; - colors["honeydew"] = 0xf0fff0; - colors["hotpink"] = 0xff69b4; - colors["indianred"] = 0xcd5c5c; - colors["indigo"] = 0x4b0082; - colors["ivory"] = 0xfffff0; - colors["khaki"] = 0xf0e68c; - colors["lavender"] = 0xe6e6fa; - colors["lavenderblush"] = 0xfff0f5; - colors["lawngreen"] = 0x7cfc00; - colors["lemonchiffon"] = 0xfffacd; - colors["lightblue"] = 0xadd8e6; - colors["lightcoral"] = 0xf08080; - colors["lightcyan"] = 0xe0ffff; - colors["lightgoldenrodyellow"] = 0xfafad2; - colors["lightgray"] = 0xd3d3d3; - colors["lightgreen"] = 0x90ee90; - colors["lightgrey"] = 0xd3d3d3; - colors["lightpink"] = 0xffb6c1; - colors["lightsalmon"] = 0xffa07a; - colors["lightseagreen"] = 0x20b2aa; - colors["lightskyblue"] = 0x87cefa; - colors["lightslategray"] = 0x778899; - colors["lightslategrey"] = 0x778899; - colors["lightsteelblue"] = 0xb0c4de; - colors["lightyellow"] = 0xffffe0; - colors["lime"] = 0x00ff00; - colors["limegreen"] = 0x32cd32; - colors["linen"] = 0xfaf0e6; - colors["magenta"] = 0xff00ff; - colors["maroon"] = 0x800000; - colors["mediumaquamarine"] = 0x66cdaa; - colors["mediumblue"] = 0x0000cd; - colors["mediumorchid"] = 0xba55d3; - colors["mediumpurple"] = 0x9370db; - colors["mediumseagreen"] = 0x3cb371; - colors["mediumslateblue"] = 0x7b68ee; - colors["mediumspringgreen"] = 0x00fa9a; - colors["mediumturquoise"] = 0x48d1cc; - colors["mediumvioletred"] = 0xc71585; - colors["midnightblue"] = 0x191970; - colors["mintcream"] = 0xf5fffa; - colors["mistyrose"] = 0xffe4e1; - colors["moccasin"] = 0xffe4b5; - colors["navajowhite"] = 0xffdead; - colors["navy"] = 0x000080; - colors["oldlace"] = 0xfdf5e6; - colors["olive"] = 0x808000; - colors["olivedrab"] = 0x6b8e23; - colors["orange"] = 0xffa500; - colors["orangered"] = 0xff4500; - colors["orchid"] = 0xda70d6; - colors["palegoldenrod"] = 0xeee8aa; - colors["palegreen"] = 0x98fb98; - colors["paleturquoise"] = 0xafeeee; - colors["palevioletred"] = 0xdb7093; - colors["papayawhip"] = 0xffefd5; - colors["peachpuff"] = 0xffdab9; - colors["peru"] = 0xcd853f; - colors["pink"] = 0xffc0cb; - colors["plum"] = 0xdda0dd; - colors["powderblue"] = 0xb0e0e6; - colors["purple"] = 0x800080; - colors["red"] = 0xff0000; - colors["rosybrown"] = 0xbc8f8f; - colors["royalblue"] = 0x4169e1; - colors["saddlebrown"] = 0x8b4513; - colors["salmon"] = 0xfa8072; - colors["sandybrown"] = 0xf4a460; - colors["seagreen"] = 0x2e8b57; - colors["seashell"] = 0xfff5ee; - colors["sienna"] = 0xa0522d; - colors["silver"] = 0xc0c0c0; - colors["skyblue"] = 0x87ceeb; - colors["slateblue"] = 0x6a5acd; - colors["slategray"] = 0x708090; - colors["slategrey"] = 0x708090; - colors["snow"] = 0xfffafa; - colors["springgreen"] = 0x00ff7f; - colors["steelblue"] = 0x4682b4; - colors["tan"] = 0xd2b48c; - colors["teal"] = 0x008080; - colors["thistle"] = 0xd8bfd8; - colors["tomato"] = 0xff6347; - colors["turquoise"] = 0x40e0d0; - colors["violet"] = 0xee82ee; - colors["wheat"] = 0xf5deb3; - colors["white"] = 0xffffff; - colors["whitesmoke"] = 0xf5f5f5; - colors["yellow"] = 0xffff00; - colors["yellowgreen"] = 0x9acd32; - -} - -static const ColorContainer named_colors; - static bool parseNamedColorString(const std::string &value, video::SColor &color) { std::string color_name; @@ -635,9 +531,8 @@ static bool parseNamedColorString(const std::string &value, video::SColor &color color_name = lowercase(color_name); - std::map<const std::string, unsigned>::const_iterator it; - it = named_colors.colors.find(color_name); - if (it == named_colors.colors.end()) + auto it = s_named_colors.find(color_name); + if (it == s_named_colors.end()) return false; u32 color_temp = it->second; @@ -645,21 +540,26 @@ static bool parseNamedColorString(const std::string &value, video::SColor &color /* An empty string for alpha is ok (none of the color table entries * have an alpha value either). Color strings without an alpha specified * are interpreted as fully opaque - * - * For named colors the supplied alpha string (representing a hex value) - * must be exactly two digits. For example: colorname#08 */ if (!alpha_string.empty()) { - if (alpha_string.length() != 2) - return false; - - unsigned char d1, d2; - if (!hex_digit_decode(alpha_string.at(0), d1) - || !hex_digit_decode(alpha_string.at(1), d2)) + if (alpha_string.size() == 1) { + u8 d; + if (!hex_digit_decode(alpha_string[0], d)) + return false; + + color_temp |= ((d & 0xf) << 4 | (d & 0xf)) << 24; + } else if (alpha_string.size() == 2) { + u8 d1, d2; + if (!hex_digit_decode(alpha_string[0], d1) + || !hex_digit_decode(alpha_string[1], d2)) + return false; + + color_temp |= ((d1 & 0xf) << 4 | (d2 & 0xf)) << 24; + } else { return false; - color_temp |= ((d1 & 0xf) << 4 | (d2 & 0xf)) << 24; + } } else { - color_temp |= 0xff << 24; // Fully opaque + color_temp |= 0xff << 24; // Fully opaque } color = video::SColor(color_temp); @@ -667,6 +567,22 @@ static bool parseNamedColorString(const std::string &value, video::SColor &color return true; } +bool parseColorString(const std::string &value, video::SColor &color, bool quiet, + unsigned char default_alpha) +{ + bool success; + + if (value[0] == '#') + success = parseHexColorString(value, color, default_alpha); + else + success = parseNamedColorString(value, color); + + if (!success && !quiet) + errorstream << "Invalid color: \"" << value << "\"" << std::endl; + + return success; +} + void str_replace(std::string &str, char from, char to) { std::replace(str.begin(), str.end(), from, to); @@ -766,7 +682,8 @@ void translate_string(const std::wstring &s, Translations *translations, } else { // This is an escape sequence *inside* the template string to translate itself. // This should not happen, show an error message. - errorstream << "Ignoring escape sequence '" << wide_to_narrow(escape_sequence) << "' in translation" << std::endl; + errorstream << "Ignoring escape sequence '" + << wide_to_utf8(escape_sequence) << "' in translation" << std::endl; } } diff --git a/src/util/string.h b/src/util/string.h index 6fd11fadc..21f1d6877 100644 --- a/src/util/string.h +++ b/src/util/string.h @@ -64,22 +64,14 @@ struct FlagDesc { u32 flag; }; -// try not to convert between wide/utf8 encodings; this can result in data loss -// try to only convert between them when you need to input/output stuff via Irrlicht +// Try to avoid converting between wide and UTF-8 unless you need to +// input/output stuff via Irrlicht std::wstring utf8_to_wide(const std::string &input); std::string wide_to_utf8(const std::wstring &input); -wchar_t *utf8_to_wide_c(const char *str); - -// NEVER use those two functions unless you have a VERY GOOD reason to -// they just convert between wide and multibyte encoding -// multibyte encoding depends on current locale, this is no good, especially on Windows - // You must free the returned string! -// The returned string is allocated using new -wchar_t *narrow_to_wide_c(const char *str); -std::wstring narrow_to_wide(const std::string &mbs); -std::string wide_to_narrow(const std::wstring &wcs); +// The returned string is allocated using new[] +wchar_t *utf8_to_wide_c(const char *str); std::string urlencode(const std::string &str); std::string urldecode(const std::string &str); @@ -353,11 +345,6 @@ inline s32 mystoi(const std::string &str, s32 min, s32 max) return i; } - -// MSVC2010 includes it's own versions of these -//#if !defined(_MSC_VER) || _MSC_VER < 1600 - - /** * Returns a 32-bit value reprensented by the string \p str (decimal). * @see atoi(3) for further limitations @@ -367,17 +354,6 @@ inline s32 mystoi(const std::string &str) return atoi(str.c_str()); } - -/** - * Returns s 32-bit value represented by the wide string \p str (decimal). - * @see atoi(3) for further limitations - */ -inline s32 mystoi(const std::wstring &str) -{ - return mystoi(wide_to_narrow(str)); -} - - /** * Returns a float reprensented by the string \p str (decimal). * @see atof(3) @@ -387,8 +363,6 @@ inline float mystof(const std::string &str) return atof(str.c_str()); } -//#endif - #define stoi mystoi #define stof mystof @@ -696,15 +670,19 @@ inline const std::string duration_to_string(int sec) std::stringstream ss; if (hour > 0) { - ss << hour << "h "; + ss << hour << "h"; + if (min > 0 || sec > 0) + ss << " "; } if (min > 0) { - ss << min << "m "; + ss << min << "min"; + if (sec > 0) + ss << " "; } if (sec > 0) { - ss << sec << "s "; + ss << sec << "s"; } return ss.str(); diff --git a/src/version.cpp b/src/version.cpp index 241228a6a..c555f30af 100644 --- a/src/version.cpp +++ b/src/version.cpp @@ -33,11 +33,12 @@ const char *g_version_hash = VERSION_GITHASH; const char *g_build_info = "BUILD_TYPE=" BUILD_TYPE "\n" "RUN_IN_PLACE=" STR(RUN_IN_PLACE) "\n" + "USE_CURL=" STR(USE_CURL) "\n" +#ifndef SERVER "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" +#endif "STATIC_SHAREDIR=" STR(STATIC_SHAREDIR) #if USE_GETTEXT && defined(STATIC_LOCALEDIR) "\n" "STATIC_LOCALEDIR=" STR(STATIC_LOCALEDIR) diff --git a/src/voxelalgorithms.cpp b/src/voxelalgorithms.cpp index 62fd68890..ffb70aa71 100644 --- a/src/voxelalgorithms.cpp +++ b/src/voxelalgorithms.cpp @@ -65,7 +65,7 @@ struct ChangingLight { ChangingLight() = default; - ChangingLight(const relative_v3 &rel_pos, const mapblock_v3 &block_pos, + ChangingLight(relative_v3 rel_pos, mapblock_v3 block_pos, MapBlock *b, direction source_dir) : rel_position(rel_pos), block_position(block_pos), @@ -125,8 +125,8 @@ struct LightQueue { * The parameters are the same as in ChangingLight's constructor. * \param light light level of the ChangingLight */ - inline void push(u8 light, const relative_v3 &rel_pos, - const mapblock_v3 &block_pos, MapBlock *block, + inline void push(u8 light, relative_v3 rel_pos, + mapblock_v3 block_pos, MapBlock *block, direction source_dir) { assert(light <= LIGHT_SUN); @@ -467,7 +467,7 @@ bool is_sunlight_above(Map *map, v3s16 pos, const NodeDefManager *ndef) static const LightBank banks[] = { LIGHTBANK_DAY, LIGHTBANK_NIGHT }; void update_lighting_nodes(Map *map, - std::vector<std::pair<v3s16, MapNode> > &oldnodes, + const std::vector<std::pair<v3s16, MapNode>> &oldnodes, std::map<v3s16, MapBlock*> &modified_blocks) { const NodeDefManager *ndef = map->getNodeDefManager(); @@ -482,8 +482,7 @@ void update_lighting_nodes(Map *map, // won't change, since they didn't get their light from a // modified node. u8 min_safe_light = 0; - for (std::vector<std::pair<v3s16, MapNode> >::iterator it = - oldnodes.begin(); it < oldnodes.end(); ++it) { + for (auto it = oldnodes.cbegin(); it < oldnodes.cend(); ++it) { u8 old_light = it->second.getLight(bank, ndef); if (old_light > min_safe_light) { min_safe_light = old_light; @@ -495,8 +494,7 @@ void update_lighting_nodes(Map *map, min_safe_light++; } // For each changed node process sunlight and initialize - for (std::vector<std::pair<v3s16, MapNode> >::iterator it = - oldnodes.begin(); it < oldnodes.end(); ++it) { + for (auto it = oldnodes.cbegin(); it < oldnodes.cend(); ++it) { // Get position and block of the changed node v3s16 p = it->first; relative_v3 rel_pos; diff --git a/src/voxelalgorithms.h b/src/voxelalgorithms.h index 1452f30f4..bcbd3b586 100644 --- a/src/voxelalgorithms.h +++ b/src/voxelalgorithms.h @@ -45,7 +45,7 @@ namespace voxalgo */ void update_lighting_nodes( Map *map, - std::vector<std::pair<v3s16, MapNode> > &oldnodes, + const std::vector<std::pair<v3s16, MapNode>> &oldnodes, std::map<v3s16, MapBlock*> &modified_blocks); /*! |