From a27362de6a66692b191f8db0eea13f8d9302cef6 Mon Sep 17 00:00:00 2001 From: SmallJoker Date: Sat, 16 Oct 2021 19:21:53 +0200 Subject: Disable dynamic shadows for the 5.5.0 release The dynamic shadows are yet not in the desired state to justify the inclusion into version 5.5.0. A stable release is long overdue, hence this allows fixes to continue in 5.6.0-dev to finally release an acceptable version of the dynamic shadows feature. Reverting this commit is highly recommended to proceed in development. --- src/client/mapblock_mesh.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/client/mapblock_mesh.cpp') diff --git a/src/client/mapblock_mesh.cpp b/src/client/mapblock_mesh.cpp index 03522eca9..249a56087 100644 --- a/src/client/mapblock_mesh.cpp +++ b/src/client/mapblock_mesh.cpp @@ -861,7 +861,7 @@ static void updateFastFaceRow( g_settings->getBool("enable_waving_water"); static thread_local const bool force_not_tiling = - g_settings->getBool("enable_dynamic_shadows"); + false && g_settings->getBool("enable_dynamic_shadows"); v3s16 p = startpos; -- cgit v1.2.3 From c61998bd2000427b96fc506edffa9fa4e27a1a9b Mon Sep 17 00:00:00 2001 From: rubenwardy Date: Mon, 31 Jan 2022 21:48:14 +0000 Subject: Revert "Disable dynamic shadows for the 5.5.0 release" (#12032) --- builtin/mainmenu/tab_settings.lua | 14 +++++------ builtin/settingtypes.txt | 52 +++++++++++++++++++++++++++++++++++++++ src/client/mapblock_mesh.cpp | 2 +- src/client/render/core.cpp | 2 +- src/client/renderingengine.h | 4 +-- src/client/shader.cpp | 2 +- src/client/sky.cpp | 2 +- 7 files changed, 65 insertions(+), 13 deletions(-) (limited to 'src/client/mapblock_mesh.cpp') diff --git a/builtin/mainmenu/tab_settings.lua b/builtin/mainmenu/tab_settings.lua index 700b7390f..42f7f8daf 100644 --- a/builtin/mainmenu/tab_settings.lua +++ b/builtin/mainmenu/tab_settings.lua @@ -218,10 +218,10 @@ local function formspec(tabview, name, tabdata) "checkbox[8.25,1.5;cb_waving_leaves;" .. fgettext("Waving Leaves") .. ";" .. dump(core.settings:get_bool("enable_waving_leaves")) .. "]" .. "checkbox[8.25,2;cb_waving_plants;" .. fgettext("Waving Plants") .. ";" - .. dump(core.settings:get_bool("enable_waving_plants")) .. "]" - --"label[8.25,3.0;" .. fgettext("Dynamic shadows: ") .. "]" .. - --"dropdown[8.25,3.5;3.5;dd_shadows;" .. dd_options.shadow_levels[1] .. ";" - -- .. getSettingIndex.ShadowMapping() .. "]" + .. dump(core.settings:get_bool("enable_waving_plants")) .. "]".. + "label[8.25,3.0;" .. fgettext("Dynamic shadows: ") .. "]" .. + "dropdown[8.25,3.5;3.5;dd_shadows;" .. dd_options.shadow_levels[1] .. ";" + .. getSettingIndex.ShadowMapping() .. "]" else tab_string = tab_string .. "label[8.38,0.7;" .. core.colorize("#888888", @@ -231,9 +231,9 @@ local function formspec(tabview, name, tabdata) "label[8.38,1.7;" .. core.colorize("#888888", fgettext("Waving Leaves")) .. "]" .. "label[8.38,2.2;" .. core.colorize("#888888", - fgettext("Waving Plants")) .. "]" - --"label[8.38,2.7;" .. core.colorize("#888888", - -- fgettext("Dynamic shadows")) .. "]" + fgettext("Waving Plants")) .. "]".. + "label[8.38,2.7;" .. core.colorize("#888888", + fgettext("Dynamic shadows")) .. "]" end return tab_string diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index 42b45aa00..ef8b84cff 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -586,6 +586,58 @@ enable_waving_leaves (Waving leaves) bool false # Requires shaders to be enabled. enable_waving_plants (Waving plants) bool false +[***Dynamic shadows] + +# Set to true to enable Shadow Mapping. +# Requires shaders to be enabled. +enable_dynamic_shadows (Dynamic shadows) bool false + +# Set the shadow strength. +# Lower value means lighter shadows, higher value means darker shadows. +shadow_strength (Shadow strength) float 0.2 0.05 1.0 + +# Maximum distance to render shadows. +shadow_map_max_distance (Shadow map max distance in nodes to render shadows) float 120.0 10.0 1000.0 + +# Texture size to render the shadow map on. +# This must be a power of two. +# Bigger numbers create better shadows but it is also more expensive. +shadow_map_texture_size (Shadow map texture size) int 1024 128 8192 + +# Sets shadow texture quality to 32 bits. +# On false, 16 bits texture will be used. +# This can cause much more artifacts in the shadow. +shadow_map_texture_32bit (Shadow map texture in 32 bits) bool true + +# Enable Poisson disk filtering. +# On true uses Poisson disk to make "soft shadows". Otherwise uses PCF filtering. +shadow_poisson_filter (Poisson filtering) bool true + +# Define shadow filtering quality. +# This simulates the soft shadows effect by applying a PCF or Poisson disk +# but also uses more resources. +shadow_filters (Shadow filter quality) enum 1 0,1,2 + +# Enable colored shadows. +# On true translucent nodes cast colored shadows. This is expensive. +shadow_map_color (Colored shadows) bool false + +# Spread a complete update of shadow map over given amount of frames. +# Higher values might make shadows laggy, lower values +# will consume more resources. +# Minimum value: 1; maximum value: 16 +shadow_update_frames (Map shadows update frames) int 8 1 16 + +# Set the soft shadow radius size. +# Lower values mean sharper shadows, bigger values mean softer shadows. +# Minimum value: 1.0; maximum value: 10.0 +shadow_soft_radius (Soft shadow radius) float 1.0 1.0 10.0 + +# Set the tilt of Sun/Moon orbit in degrees. +# Value of 0 means no tilt / vertical orbit. +# Minimum value: 0.0; maximum value: 60.0 +shadow_sky_body_orbit_tilt (Sky Body Orbit Tilt) float 0.0 0.0 60.0 + [**Advanced] # Arm inertia, gives a more realistic movement of diff --git a/src/client/mapblock_mesh.cpp b/src/client/mapblock_mesh.cpp index 249a56087..03522eca9 100644 --- a/src/client/mapblock_mesh.cpp +++ b/src/client/mapblock_mesh.cpp @@ -861,7 +861,7 @@ static void updateFastFaceRow( g_settings->getBool("enable_waving_water"); static thread_local const bool force_not_tiling = - false && g_settings->getBool("enable_dynamic_shadows"); + g_settings->getBool("enable_dynamic_shadows"); v3s16 p = startpos; diff --git a/src/client/render/core.cpp b/src/client/render/core.cpp index 44ef1c98c..f151832f3 100644 --- a/src/client/render/core.cpp +++ b/src/client/render/core.cpp @@ -36,7 +36,7 @@ RenderingCore::RenderingCore(IrrlichtDevice *_device, Client *_client, Hud *_hud virtual_size = screensize; if (g_settings->getBool("enable_shaders") && - false && g_settings->getBool("enable_dynamic_shadows")) { + g_settings->getBool("enable_dynamic_shadows")) { shadow_renderer = new ShadowRenderer(device, client); } } diff --git a/src/client/renderingengine.h b/src/client/renderingengine.h index a0ddb0d9a..6f104bba9 100644 --- a/src/client/renderingengine.h +++ b/src/client/renderingengine.h @@ -123,8 +123,8 @@ public: // FIXME: this is still global when it shouldn't be static ShadowRenderer *get_shadow_renderer() { - //if (s_singleton && s_singleton->core) - // return s_singleton->core->get_shadow_renderer(); + if (s_singleton && s_singleton->core) + return s_singleton->core->get_shadow_renderer(); return nullptr; } static std::vector getSupportedVideoDrivers(); diff --git a/src/client/shader.cpp b/src/client/shader.cpp index c04a25862..dc9e9ae6d 100644 --- a/src/client/shader.cpp +++ b/src/client/shader.cpp @@ -733,7 +733,7 @@ ShaderInfo ShaderSource::generateShader(const std::string &name, shaders_header << "#define FOG_START " << core::clamp(g_settings->getFloat("fog_start"), 0.0f, 0.99f) << "\n"; - if (false && g_settings->getBool("enable_dynamic_shadows")) { + if (g_settings->getBool("enable_dynamic_shadows")) { shaders_header << "#define ENABLE_DYNAMIC_SHADOWS 1\n"; if (g_settings->getBool("shadow_map_color")) shaders_header << "#define COLORED_SHADOWS 1\n"; diff --git a/src/client/sky.cpp b/src/client/sky.cpp index 7fe90c6cd..0ab710eee 100644 --- a/src/client/sky.cpp +++ b/src/client/sky.cpp @@ -103,7 +103,7 @@ Sky::Sky(s32 id, RenderingEngine *rendering_engine, ITextureSource *tsrc, IShade m_directional_colored_fog = g_settings->getBool("directional_colored_fog"); - if (false && g_settings->getBool("enable_dynamic_shadows")) { + if (g_settings->getBool("enable_dynamic_shadows")) { float val = g_settings->getFloat("shadow_sky_body_orbit_tilt"); m_sky_body_orbit_tilt = rangelim(val, 0.0f, 60.0f); } -- cgit v1.2.3 From b0b9732359d43325c8bd820abeb8417353365a0c Mon Sep 17 00:00:00 2001 From: x2048 Date: Sat, 2 Apr 2022 10:42:27 +0200 Subject: Add depth sorting for node faces (#11696) Use BSP tree to order transparent triangles https://en.wikipedia.org/wiki/Binary_space_partitioning --- builtin/settingtypes.txt | 4 + src/client/clientmap.cpp | 244 ++++++++++++++++++++++++++------------ src/client/clientmap.h | 43 ++++--- src/client/content_mapblock.cpp | 57 ++++++++- src/client/mapblock_mesh.cpp | 257 +++++++++++++++++++++++++++++++++++++++- src/client/mapblock_mesh.h | 101 ++++++++++++++++ src/client/tile.h | 15 ++- src/defaultsettings.cpp | 1 + 8 files changed, 629 insertions(+), 93 deletions(-) (limited to 'src/client/mapblock_mesh.cpp') diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index 3dc165bd1..b4230735b 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -858,6 +858,10 @@ autoscale_mode (Autoscaling mode) enum disable disable,enable,force # A restart is required after changing this. show_entity_selectionbox (Show entity selection boxes) bool false +# Distance in nodes at which transparency depth sorting is enabled +# Use this to limit the performance impact of transparency depth sorting +transparency_sorting_distance (Transparency Sorting Distance) int 16 0 128 + [*Menus] # Use a cloud animation for the main menu background. diff --git a/src/client/clientmap.cpp b/src/client/clientmap.cpp index 1a024e464..f070a58bb 100644 --- a/src/client/clientmap.cpp +++ b/src/client/clientmap.cpp @@ -97,9 +97,32 @@ ClientMap::ClientMap( m_cache_trilinear_filter = g_settings->getBool("trilinear_filter"); m_cache_bilinear_filter = g_settings->getBool("bilinear_filter"); m_cache_anistropic_filter = g_settings->getBool("anisotropic_filter"); + m_cache_transparency_sorting_distance = g_settings->getU16("transparency_sorting_distance"); } +void ClientMap::updateCamera(v3f pos, v3f dir, f32 fov, v3s16 offset) +{ + v3s16 previous_node = floatToInt(m_camera_position, BS) + m_camera_offset; + v3s16 previous_block = getContainerPos(previous_node, MAP_BLOCKSIZE); + + m_camera_position = pos; + m_camera_direction = dir; + m_camera_fov = fov; + m_camera_offset = offset; + + v3s16 current_node = floatToInt(m_camera_position, BS) + m_camera_offset; + v3s16 current_block = getContainerPos(current_node, MAP_BLOCKSIZE); + + // reorder the blocks when camera crosses block boundary + if (previous_block != current_block) + m_needs_update_drawlist = true; + + // reorder transparent meshes when camera crosses node boundary + if (previous_node != current_node) + m_needs_update_transparent_meshes = true; +} + MapSector * ClientMap::emergeSector(v2s16 p2d) { // Check that it doesn't exist already @@ -323,22 +346,17 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) u32 mesh_animate_count = 0; //u32 mesh_animate_count_far = 0; + /* + Update transparent meshes + */ + if (is_transparent_pass) + updateTransparentMeshBuffers(); + /* Draw the selected MapBlocks */ MeshBufListList grouped_buffers; - - struct DrawDescriptor { - v3s16 m_pos; - scene::IMeshBuffer *m_buffer; - bool m_reuse_material; - - DrawDescriptor(const v3s16 &pos, scene::IMeshBuffer *buffer, bool reuse_material) : - m_pos(pos), m_buffer(buffer), m_reuse_material(reuse_material) - {} - }; - std::vector draw_order; video::SMaterial previous_material; @@ -375,7 +393,15 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) /* Get the meshbuffers of the block */ - { + if (is_transparent_pass) { + // In transparent pass, the mesh will give us + // the partial buffers in the correct order + for (auto &buffer : block->mesh->getTransparentBuffers()) + draw_order.emplace_back(block_pos, &buffer); + } + else { + // otherwise, group buffers across meshes + // using MeshBufListList MapBlockMesh *mapBlockMesh = block->mesh; assert(mapBlockMesh); @@ -389,35 +415,14 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) video::SMaterial& material = buf->getMaterial(); video::IMaterialRenderer* rnd = - driver->getMaterialRenderer(material.MaterialType); + driver->getMaterialRenderer(material.MaterialType); bool transparent = (rnd && rnd->isTransparent()); - if (transparent == is_transparent_pass) { + if (!transparent) { if (buf->getVertexCount() == 0) errorstream << "Block [" << analyze_block(block) - << "] contains an empty meshbuf" << std::endl; - - material.setFlag(video::EMF_TRILINEAR_FILTER, - m_cache_trilinear_filter); - material.setFlag(video::EMF_BILINEAR_FILTER, - m_cache_bilinear_filter); - material.setFlag(video::EMF_ANISOTROPIC_FILTER, - m_cache_anistropic_filter); - material.setFlag(video::EMF_WIREFRAME, - m_control.show_wireframe); - - if (is_transparent_pass) { - // Same comparison as in MeshBufListList - bool new_material = material.getTexture(0) != previous_material.getTexture(0) || - material != previous_material; - - draw_order.emplace_back(block_pos, buf, !new_material); - - if (new_material) - previous_material = material; - } - else { - grouped_buffers.add(buf, block_pos, layer); - } + << "] contains an empty meshbuf" << std::endl; + + grouped_buffers.add(buf, block_pos, layer); } } } @@ -442,8 +447,17 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) // Render all mesh buffers in order drawcall_count += draw_order.size(); + for (auto &descriptor : draw_order) { - scene::IMeshBuffer *buf = descriptor.m_buffer; + scene::IMeshBuffer *buf; + + if (descriptor.m_use_partial_buffer) { + descriptor.m_partial_buffer->beforeDraw(); + buf = descriptor.m_partial_buffer->getBuffer(); + } + else { + buf = descriptor.m_buffer; + } // Check and abort if the machine is swapping a lot if (draw.getTimerTime() > 2000) { @@ -454,6 +468,17 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) if (!descriptor.m_reuse_material) { auto &material = buf->getMaterial(); + + // Apply filter settings + material.setFlag(video::EMF_TRILINEAR_FILTER, + m_cache_trilinear_filter); + material.setFlag(video::EMF_BILINEAR_FILTER, + m_cache_bilinear_filter); + material.setFlag(video::EMF_ANISOTROPIC_FILTER, + m_cache_anistropic_filter); + material.setFlag(video::EMF_WIREFRAME, + m_control.show_wireframe); + // pass the shadow map texture to the buffer texture ShadowRenderer *shadow = m_rendering_engine->get_shadow_renderer(); if (shadow && shadow->is_active()) { @@ -475,7 +500,7 @@ void ClientMap::renderMap(video::IVideoDriver* driver, s32 pass) driver->setTransform(video::ETS_WORLD, m); driver->drawMeshBuffer(buf); - vertex_count += buf->getVertexCount(); + vertex_count += buf->getIndexCount(); } g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true)); @@ -698,7 +723,9 @@ void ClientMap::renderMapShadows(video::IVideoDriver *driver, u32 drawcall_count = 0; u32 vertex_count = 0; - MeshBufListList drawbufs; + MeshBufListList grouped_buffers; + std::vector draw_order; + int count = 0; int low_bound = is_transparent_pass ? 0 : m_drawlist_shadow.size() / total_frames * frame; @@ -727,7 +754,15 @@ void ClientMap::renderMapShadows(video::IVideoDriver *driver, /* Get the meshbuffers of the block */ - { + if (is_transparent_pass) { + // In transparent pass, the mesh will give us + // the partial buffers in the correct order + for (auto &buffer : block->mesh->getTransparentBuffers()) + draw_order.emplace_back(block_pos, &buffer); + } + else { + // otherwise, group buffers across meshes + // using MeshBufListList MapBlockMesh *mapBlockMesh = block->mesh; assert(mapBlockMesh); @@ -742,49 +777,74 @@ void ClientMap::renderMapShadows(video::IVideoDriver *driver, video::SMaterial &mat = buf->getMaterial(); auto rnd = driver->getMaterialRenderer(mat.MaterialType); bool transparent = rnd && rnd->isTransparent(); - if (transparent == is_transparent_pass) - drawbufs.add(buf, block_pos, layer); + if (!transparent) + grouped_buffers.add(buf, block_pos, layer); } } } } + u32 buffer_count = 0; + for (auto &lists : grouped_buffers.lists) + for (MeshBufList &list : lists) + buffer_count += list.bufs.size(); + + draw_order.reserve(draw_order.size() + buffer_count); + + // Capture draw order for all solid meshes + for (auto &lists : grouped_buffers.lists) { + for (MeshBufList &list : lists) { + // iterate in reverse to draw closest blocks first + for (auto it = list.bufs.rbegin(); it != list.bufs.rend(); ++it) + draw_order.emplace_back(it->first, it->second, it != list.bufs.rbegin()); + } + } + TimeTaker draw("Drawing shadow mesh buffers"); core::matrix4 m; // Model matrix v3f offset = intToFloat(m_camera_offset, BS); + u32 material_swaps = 0; - // Render all layers in order - for (auto &lists : drawbufs.lists) { - for (MeshBufList &list : lists) { - // Check and abort if the machine is swapping a lot - if (draw.getTimerTime() > 1000) { - infostream << "ClientMap::renderMapShadows(): Rendering " - "took >1s, returning." << std::endl; - break; - } - for (auto &pair : list.bufs) { - scene::IMeshBuffer *buf = pair.second; - - // override some material properties - video::SMaterial local_material = buf->getMaterial(); - local_material.MaterialType = material.MaterialType; - local_material.BackfaceCulling = material.BackfaceCulling; - local_material.FrontfaceCulling = material.FrontfaceCulling; - local_material.BlendOperation = material.BlendOperation; - local_material.Lighting = false; - driver->setMaterial(local_material); - - v3f block_wpos = intToFloat(pair.first * MAP_BLOCKSIZE, BS); - m.setTranslation(block_wpos - offset); - - driver->setTransform(video::ETS_WORLD, m); - driver->drawMeshBuffer(buf); - vertex_count += buf->getVertexCount(); - } + // Render all mesh buffers in order + drawcall_count += draw_order.size(); + + for (auto &descriptor : draw_order) { + scene::IMeshBuffer *buf; + + if (descriptor.m_use_partial_buffer) { + descriptor.m_partial_buffer->beforeDraw(); + buf = descriptor.m_partial_buffer->getBuffer(); + } + else { + buf = descriptor.m_buffer; + } - drawcall_count += list.bufs.size(); + // Check and abort if the machine is swapping a lot + if (draw.getTimerTime() > 1000) { + infostream << "ClientMap::renderMapShadows(): Rendering " + "took >1s, returning." << std::endl; + break; } + + if (!descriptor.m_reuse_material) { + // override some material properties + video::SMaterial local_material = buf->getMaterial(); + local_material.MaterialType = material.MaterialType; + local_material.BackfaceCulling = material.BackfaceCulling; + local_material.FrontfaceCulling = material.FrontfaceCulling; + local_material.BlendOperation = material.BlendOperation; + local_material.Lighting = false; + driver->setMaterial(local_material); + ++material_swaps; + } + + v3f block_wpos = intToFloat(descriptor.m_pos * MAP_BLOCKSIZE, BS); + m.setTranslation(block_wpos - offset); + + driver->setTransform(video::ETS_WORLD, m); + driver->drawMeshBuffer(buf); + vertex_count += buf->getIndexCount(); } // restore the driver material state @@ -796,6 +856,7 @@ void ClientMap::renderMapShadows(video::IVideoDriver *driver, g_profiler->avg(prefix + "draw meshes [ms]", draw.stop(true)); g_profiler->avg(prefix + "vertices drawn [#]", vertex_count); g_profiler->avg(prefix + "drawcalls [#]", drawcall_count); + g_profiler->avg(prefix + "material swaps [#]", material_swaps); } /* @@ -891,3 +952,40 @@ void ClientMap::updateDrawListShadow(const v3f &shadow_light_pos, const v3f &sha g_profiler->avg("SHADOW MapBlocks drawn [#]", m_drawlist_shadow.size()); g_profiler->avg("SHADOW MapBlocks loaded [#]", blocks_loaded); } + +void ClientMap::updateTransparentMeshBuffers() +{ + ScopeProfiler sp(g_profiler, "CM::updateTransparentMeshBuffers", SPT_AVG); + u32 sorted_blocks = 0; + u32 unsorted_blocks = 0; + f32 sorting_distance_sq = pow(m_cache_transparency_sorting_distance * BS, 2.0f); + + + // Update the order of transparent mesh buffers in each mesh + for (auto it = m_drawlist.begin(); it != m_drawlist.end(); it++) { + MapBlock* block = it->second; + if (!block->mesh) + continue; + + if (m_needs_update_transparent_meshes || + block->mesh->getTransparentBuffers().size() == 0) { + + v3s16 block_pos = block->getPos(); + v3f block_pos_f = intToFloat(block_pos * MAP_BLOCKSIZE + MAP_BLOCKSIZE / 2, BS); + f32 distance = m_camera_position.getDistanceFromSQ(block_pos_f); + if (distance <= sorting_distance_sq) { + block->mesh->updateTransparentBuffers(m_camera_position, block_pos); + ++sorted_blocks; + } + else { + block->mesh->consolidateTransparentBuffers(); + ++unsorted_blocks; + } + } + } + + g_profiler->avg("CM::Transparent Buffers - Sorted", sorted_blocks); + g_profiler->avg("CM::Transparent Buffers - Unsorted", unsorted_blocks); + m_needs_update_transparent_meshes = false; +} + diff --git a/src/client/clientmap.h b/src/client/clientmap.h index b4dc42395..d8554313d 100644 --- a/src/client/clientmap.h +++ b/src/client/clientmap.h @@ -56,6 +56,7 @@ struct MeshBufListList class Client; class ITextureSource; +class PartialMeshBuffer; /* ClientMap @@ -85,21 +86,7 @@ public: ISceneNode::drop(); } - void updateCamera(const v3f &pos, const v3f &dir, f32 fov, const v3s16 &offset) - { - v3s16 previous_block = getContainerPos(floatToInt(m_camera_position, BS) + m_camera_offset, MAP_BLOCKSIZE); - - m_camera_position = pos; - m_camera_direction = dir; - m_camera_fov = fov; - m_camera_offset = offset; - - v3s16 current_block = getContainerPos(floatToInt(m_camera_position, BS) + m_camera_offset, MAP_BLOCKSIZE); - - // reorder the blocks when camera crosses block boundary - if (previous_block != current_block) - m_needs_update_drawlist = true; - } + void updateCamera(v3f pos, v3f dir, f32 fov, v3s16 offset); /* Forcefully get a sector from somewhere @@ -150,6 +137,10 @@ public: f32 getCameraFov() const { return m_camera_fov; } private: + + // update the vertex order in transparent mesh buffers + void updateTransparentMeshBuffers(); + // Orders blocks by distance to the camera class MapBlockComparer { @@ -167,6 +158,26 @@ private: v3s16 m_camera_block; }; + + // reference to a mesh buffer used when rendering the map. + struct DrawDescriptor { + v3s16 m_pos; + union { + scene::IMeshBuffer *m_buffer; + const PartialMeshBuffer *m_partial_buffer; + }; + bool m_reuse_material:1; + bool m_use_partial_buffer:1; + + DrawDescriptor(v3s16 pos, scene::IMeshBuffer *buffer, bool reuse_material) : + m_pos(pos), m_buffer(buffer), m_reuse_material(reuse_material), m_use_partial_buffer(false) + {} + + DrawDescriptor(v3s16 pos, const PartialMeshBuffer *buffer) : + m_pos(pos), m_partial_buffer(buffer), m_reuse_material(false), m_use_partial_buffer(true) + {} + }; + Client *m_client; RenderingEngine *m_rendering_engine; @@ -179,6 +190,7 @@ private: v3f m_camera_direction = v3f(0,0,1); f32 m_camera_fov = M_PI; v3s16 m_camera_offset; + bool m_needs_update_transparent_meshes = true; std::map m_drawlist; std::map m_drawlist_shadow; @@ -190,4 +202,5 @@ private: bool m_cache_bilinear_filter; bool m_cache_anistropic_filter; bool m_added_to_shadow_renderer{false}; + u16 m_cache_transparency_sorting_distance; }; diff --git a/src/client/content_mapblock.cpp b/src/client/content_mapblock.cpp index bb2d6398f..947793ed0 100644 --- a/src/client/content_mapblock.cpp +++ b/src/client/content_mapblock.cpp @@ -381,12 +381,12 @@ void MapblockMeshGenerator::drawAutoLightedCuboid(aabb3f box, const f32 *txc, box.MinEdge *= f->visual_scale; box.MaxEdge *= f->visual_scale; } - box.MinEdge += origin; - box.MaxEdge += origin; if (!txc) { generateCuboidTextureCoords(box, texture_coord_buf); txc = texture_coord_buf; } + box.MinEdge += origin; + box.MaxEdge += origin; if (!tiles) { tiles = &tile; tile_count = 1; @@ -1377,6 +1377,59 @@ void MapblockMeshGenerator::drawNodeboxNode() std::vector boxes; n.getNodeBoxes(nodedef, &boxes, neighbors_set); + + bool isTransparent = false; + + for (const TileSpec &tile : tiles) { + if (tile.layers[0].isTransparent()) { + isTransparent = true; + break; + } + } + + if (isTransparent) { + std::vector sections; + // Preallocate 8 default splits + Min&Max for each nodebox + sections.reserve(8 + 2 * boxes.size()); + + for (int axis = 0; axis < 3; axis++) { + // identify sections + + if (axis == 0) { + // Default split at node bounds, up to 3 nodes in each direction + for (float s = -3.5f * BS; s < 4.0f * BS; s += 1.0f * BS) + sections.push_back(s); + } + else { + // Avoid readding the same 8 default splits for Y and Z + sections.resize(8); + } + + // Add edges of existing node boxes, rounded to 1E-3 + for (size_t i = 0; i < boxes.size(); i++) { + sections.push_back(std::floor(boxes[i].MinEdge[axis] * 1E3) * 1E-3); + sections.push_back(std::floor(boxes[i].MaxEdge[axis] * 1E3) * 1E-3); + } + + // split the boxes at recorded sections + // limit splits to avoid runaway crash if inner loop adds infinite splits + // due to e.g. precision problems. + // 100 is just an arbitrary, reasonably high number. + for (size_t i = 0; i < boxes.size() && i < 100; i++) { + aabb3f *box = &boxes[i]; + for (float section : sections) { + if (box->MinEdge[axis] < section && box->MaxEdge[axis] > section) { + aabb3f copy(*box); + copy.MinEdge[axis] = section; + box->MaxEdge[axis] = section; + boxes.push_back(copy); + box = &boxes[i]; // find new address of the box in case of reallocation + } + } + } + } + } + for (auto &box : boxes) drawAutoLightedCuboid(box, nullptr, tiles, 6); } diff --git a/src/client/mapblock_mesh.cpp b/src/client/mapblock_mesh.cpp index 03522eca9..8c7d66186 100644 --- a/src/client/mapblock_mesh.cpp +++ b/src/client/mapblock_mesh.cpp @@ -30,6 +30,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "client/meshgen/collector.h" #include "client/renderingengine.h" #include +#include /* MeshMakeData @@ -1003,6 +1004,173 @@ static void applyTileColor(PreMeshBuffer &pmb) } } +/* + MapBlockBspTree +*/ + +void MapBlockBspTree::buildTree(const std::vector *triangles) +{ + this->triangles = triangles; + + nodes.clear(); + + // assert that triangle index can fit into s32 + assert(triangles->size() <= 0x7FFFFFFFL); + std::vector indexes; + indexes.reserve(triangles->size()); + for (u32 i = 0; i < triangles->size(); i++) + indexes.push_back(i); + + root = buildTree(v3f(1, 0, 0), v3f(85, 85, 85), 40, indexes, 0); +} + +/** + * @brief Find a candidate plane to split a set of triangles in two + * + * The candidate plane is represented by one of the triangles from the set. + * + * @param list Vector of indexes of the triangles in the set + * @param triangles Vector of all triangles in the BSP tree + * @return Address of the triangle that represents the proposed split plane + */ +static const MeshTriangle *findSplitCandidate(const std::vector &list, const std::vector &triangles) +{ + // find the center of the cluster. + v3f center(0, 0, 0); + size_t n = list.size(); + for (s32 i : list) { + center += triangles[i].centroid / n; + } + + // find the triangle with the largest area and closest to the center + const MeshTriangle *candidate_triangle = &triangles[list[0]]; + const MeshTriangle *ith_triangle; + for (s32 i : list) { + ith_triangle = &triangles[i]; + if (ith_triangle->areaSQ > candidate_triangle->areaSQ || + (ith_triangle->areaSQ == candidate_triangle->areaSQ && + ith_triangle->centroid.getDistanceFromSQ(center) < candidate_triangle->centroid.getDistanceFromSQ(center))) { + candidate_triangle = ith_triangle; + } + } + return candidate_triangle; +} + +s32 MapBlockBspTree::buildTree(v3f normal, v3f origin, float delta, const std::vector &list, u32 depth) +{ + // if the list is empty, don't bother + if (list.empty()) + return -1; + + // if there is only one triangle, or the delta is insanely small, this is a leaf node + if (list.size() == 1 || delta < 0.01) { + nodes.emplace_back(normal, origin, list, -1, -1); + return nodes.size() - 1; + } + + std::vector front_list; + std::vector back_list; + std::vector node_list; + + // split the list + for (s32 i : list) { + const MeshTriangle &triangle = (*triangles)[i]; + float factor = normal.dotProduct(triangle.centroid - origin); + if (factor == 0) + node_list.push_back(i); + else if (factor > 0) + front_list.push_back(i); + else + back_list.push_back(i); + } + + // define the new split-plane + v3f candidate_normal(normal.Z, normal.X, normal.Y); + float candidate_delta = delta; + if (depth % 3 == 2) + candidate_delta /= 2; + + s32 front_index = -1; + s32 back_index = -1; + + if (!front_list.empty()) { + v3f next_normal = candidate_normal; + v3f next_origin = origin + delta * normal; + float next_delta = candidate_delta; + if (next_delta < 10) { + const MeshTriangle *candidate = findSplitCandidate(front_list, *triangles); + next_normal = candidate->getNormal(); + next_origin = candidate->centroid; + } + front_index = buildTree(next_normal, next_origin, next_delta, front_list, depth + 1); + + // if there are no other triangles, don't create a new node + if (back_list.empty() && node_list.empty()) + return front_index; + } + + if (!back_list.empty()) { + v3f next_normal = candidate_normal; + v3f next_origin = origin - delta * normal; + float next_delta = candidate_delta; + if (next_delta < 10) { + const MeshTriangle *candidate = findSplitCandidate(back_list, *triangles); + next_normal = candidate->getNormal(); + next_origin = candidate->centroid; + } + + back_index = buildTree(next_normal, next_origin, next_delta, back_list, depth + 1); + + // if there are no other triangles, don't create a new node + if (front_list.empty() && node_list.empty()) + return back_index; + } + + nodes.emplace_back(normal, origin, node_list, front_index, back_index); + + return nodes.size() - 1; +} + +void MapBlockBspTree::traverse(s32 node, v3f viewpoint, std::vector &output) const +{ + if (node < 0) return; // recursion break; + + const TreeNode &n = nodes[node]; + float factor = n.normal.dotProduct(viewpoint - n.origin); + + if (factor > 0) + traverse(n.back_ref, viewpoint, output); + else + traverse(n.front_ref, viewpoint, output); + + if (factor != 0) + for (s32 i : n.triangle_refs) + output.push_back(i); + + if (factor > 0) + traverse(n.front_ref, viewpoint, output); + else + traverse(n.back_ref, viewpoint, output); +} + + + +/* + PartialMeshBuffer +*/ + +void PartialMeshBuffer::beforeDraw() const +{ + // Patch the indexes in the mesh buffer before draw + + m_buffer->Indices.clear(); + if (!m_vertex_indexes.empty()) { + for (auto index : m_vertex_indexes) + m_buffer->Indices.push_back(index); + } + m_buffer->setDirty(scene::EBT_INDEX); +} + /* MapBlockMesh */ @@ -1173,8 +1341,31 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): scene::SMeshBuffer *buf = new scene::SMeshBuffer(); buf->Material = material; - buf->append(&p.vertices[0], p.vertices.size(), - &p.indices[0], p.indices.size()); + switch (p.layer.material_type) { + // list of transparent materials taken from tile.h + case TILE_MATERIAL_ALPHA: + case TILE_MATERIAL_LIQUID_TRANSPARENT: + case TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT: + { + buf->append(&p.vertices[0], p.vertices.size(), + &p.indices[0], 0); + + MeshTriangle t; + t.buffer = buf; + for (u32 i = 0; i < p.indices.size(); i += 3) { + t.p1 = p.indices[i]; + t.p2 = p.indices[i + 1]; + t.p3 = p.indices[i + 2]; + t.updateAttributes(); + m_transparent_triangles.push_back(t); + } + } + break; + default: + buf->append(&p.vertices[0], p.vertices.size(), + &p.indices[0], p.indices.size()); + break; + } mesh->addMeshBuffer(buf); buf->drop(); } @@ -1187,6 +1378,7 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): } //std::cout<<"added "< triangle_refs; + m_bsp_tree.traverse(rel_camera_pos, triangle_refs); + + // arrange index sequences into partial buffers + m_transparent_buffers.clear(); + + scene::SMeshBuffer *current_buffer = nullptr; + std::vector current_strain; + for (auto i : triangle_refs) { + const auto &t = m_transparent_triangles[i]; + if (current_buffer != t.buffer) { + if (current_buffer) { + m_transparent_buffers.emplace_back(current_buffer, current_strain); + current_strain.clear(); + } + current_buffer = t.buffer; + } + current_strain.push_back(t.p1); + current_strain.push_back(t.p2); + current_strain.push_back(t.p3); + } + + if (!current_strain.empty()) + m_transparent_buffers.emplace_back(current_buffer, current_strain); +} + +void MapBlockMesh::consolidateTransparentBuffers() +{ + m_transparent_buffers.clear(); + + scene::SMeshBuffer *current_buffer = nullptr; + std::vector current_strain; + + // use the fact that m_transparent_triangles is already arranged by buffer + for (const auto &t : m_transparent_triangles) { + if (current_buffer != t.buffer) { + if (current_buffer != nullptr) { + this->m_transparent_buffers.emplace_back(current_buffer, current_strain); + current_strain.clear(); + } + current_buffer = t.buffer; + } + current_strain.push_back(t.p1); + current_strain.push_back(t.p2); + current_strain.push_back(t.p3); + } + + if (!current_strain.empty()) { + this->m_transparent_buffers.emplace_back(current_buffer, current_strain); + } +} + video::SColor encode_light(u16 light, u8 emissive_light) { // Get components diff --git a/src/client/mapblock_mesh.h b/src/client/mapblock_mesh.h index 3b17c4af9..cfc39ade2 100644 --- a/src/client/mapblock_mesh.h +++ b/src/client/mapblock_mesh.h @@ -71,6 +71,91 @@ struct MeshMakeData void setSmoothLighting(bool smooth_lighting); }; +// represents a triangle as indexes into the vertex buffer in SMeshBuffer +class MeshTriangle +{ +public: + scene::SMeshBuffer *buffer; + u16 p1, p2, p3; + v3f centroid; + float areaSQ; + + void updateAttributes() + { + v3f v1 = buffer->getPosition(p1); + v3f v2 = buffer->getPosition(p2); + v3f v3 = buffer->getPosition(p3); + + centroid = (v1 + v2 + v3) / 3; + areaSQ = (v2-v1).crossProduct(v3-v1).getLengthSQ() / 4; + } + + v3f getNormal() const { + v3f v1 = buffer->getPosition(p1); + v3f v2 = buffer->getPosition(p2); + v3f v3 = buffer->getPosition(p3); + + return (v2-v1).crossProduct(v3-v1); + } +}; + +/** + * Implements a binary space partitioning tree + * See also: https://en.wikipedia.org/wiki/Binary_space_partitioning + */ +class MapBlockBspTree +{ +public: + MapBlockBspTree() {} + + void buildTree(const std::vector *triangles); + + void traverse(v3f viewpoint, std::vector &output) const + { + traverse(root, viewpoint, output); + } + +private: + // Tree node definition; + struct TreeNode + { + v3f normal; + v3f origin; + std::vector triangle_refs; + s32 front_ref; + s32 back_ref; + + TreeNode() = default; + TreeNode(v3f normal, v3f origin, const std::vector &triangle_refs, s32 front_ref, s32 back_ref) : + normal(normal), origin(origin), triangle_refs(triangle_refs), front_ref(front_ref), back_ref(back_ref) + {} + }; + + + s32 buildTree(v3f normal, v3f origin, float delta, const std::vector &list, u32 depth); + void traverse(s32 node, v3f viewpoint, std::vector &output) const; + + const std::vector *triangles = nullptr; // this reference is managed externally + std::vector nodes; // list of nodes + s32 root = -1; // index of the root node +}; + +class PartialMeshBuffer +{ +public: + PartialMeshBuffer(scene::SMeshBuffer *buffer, const std::vector &vertex_indexes) : + m_buffer(buffer), m_vertex_indexes(vertex_indexes) + {} + + scene::IMeshBuffer *getBuffer() const { return m_buffer; } + const std::vector &getVertexIndexes() const { return m_vertex_indexes; } + + void beforeDraw() const; +private: + scene::SMeshBuffer *m_buffer; + std::vector m_vertex_indexes; +}; + /* Holds a mesh for a mapblock. @@ -125,6 +210,15 @@ public: m_animation_force_timer--; } + /// update transparent buffers to render towards the camera + void updateTransparentBuffers(v3f camera_pos, v3s16 block_pos); + void consolidateTransparentBuffers(); + + /// get the list of transparent buffers + const std::vector &getTransparentBuffers() const + { + return this->m_transparent_buffers; + } private: scene::IMesh *m_mesh[MAX_TILE_LAYERS]; MinimapMapblock *m_minimap_mapblock; @@ -158,6 +252,13 @@ private: // of sunlit vertices // Keys are pairs of (mesh index, buffer index in the mesh) std::map, std::map > m_daynight_diffs; + + // list of all semitransparent triangles in the mapblock + std::vector m_transparent_triangles; + // Binary Space Partitioning tree for the block + MapBlockBspTree m_bsp_tree; + // Ordered list of references to parts of transparent buffers to draw + std::vector m_transparent_buffers; }; /*! diff --git a/src/client/tile.h b/src/client/tile.h index fe96cef58..88ff91f8e 100644 --- a/src/client/tile.h +++ b/src/client/tile.h @@ -260,6 +260,18 @@ struct TileLayer && (material_flags & MATERIAL_FLAG_TILEABLE_VERTICAL); } + bool isTransparent() const + { + switch (material_type) { + case TILE_MATERIAL_BASIC: + case TILE_MATERIAL_ALPHA: + case TILE_MATERIAL_LIQUID_TRANSPARENT: + case TILE_MATERIAL_WAVING_LIQUID_TRANSPARENT: + return true; + } + return false; + } + // Ordered for size, please do not reorder video::ITexture *texture = nullptr; @@ -308,7 +320,8 @@ struct TileSpec for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { if (layers[layer] != other.layers[layer]) return false; - if (!layers[layer].isTileable()) + // Only non-transparent tiles can be merged into fast faces + if (layers[layer].isTransparent() || !layers[layer].isTileable()) return false; } return rotation == 0 diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index 2e9a19199..b86287157 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -244,6 +244,7 @@ void set_default_settings() settings->setDefault("enable_particles", "true"); settings->setDefault("arm_inertia", "true"); settings->setDefault("show_nametag_backgrounds", "true"); + settings->setDefault("transparency_sorting_distance", "16"); settings->setDefault("enable_minimap", "true"); settings->setDefault("minimap_shape_round", "true"); -- cgit v1.2.3 From 7e18a1f1be2692bde078c1b77982da916c871497 Mon Sep 17 00:00:00 2001 From: paradust7 <102263465+paradust7@users.noreply.github.com> Date: Thu, 28 Apr 2022 09:52:19 -0700 Subject: Remove HW_buffer_counter after IrrlichtMt fix to remove HWBufferMap (#12232) Keep code and use version check instead, for backwards compatibility --- src/client/game.cpp | 5 +++++ src/client/mapblock_mesh.cpp | 2 ++ 2 files changed, 7 insertions(+) (limited to 'src/client/mapblock_mesh.cpp') diff --git a/src/client/game.cpp b/src/client/game.cpp index b877ba04a..1290534eb 100644 --- a/src/client/game.cpp +++ b/src/client/game.cpp @@ -907,7 +907,10 @@ private: bool m_does_lost_focus_pause_game = false; +#if IRRLICHT_VERSION_MT_REVISION < 5 int m_reset_HW_buffer_counter = 0; +#endif + #ifdef HAVE_TOUCHSCREENGUI bool m_cache_hold_aux1; #endif @@ -3990,6 +3993,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, /* ==================== End scene ==================== */ +#if IRRLICHT_VERSION_MT_REVISION < 5 if (++m_reset_HW_buffer_counter > 500) { /* Periodically remove all mesh HW buffers. @@ -4011,6 +4015,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, driver->removeAllHardwareBuffers(); m_reset_HW_buffer_counter = 0; } +#endif driver->endScene(); diff --git a/src/client/mapblock_mesh.cpp b/src/client/mapblock_mesh.cpp index 8c7d66186..2c5500fca 100644 --- a/src/client/mapblock_mesh.cpp +++ b/src/client/mapblock_mesh.cpp @@ -1390,12 +1390,14 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): MapBlockMesh::~MapBlockMesh() { for (scene::IMesh *m : m_mesh) { +#if IRRLICHT_VERSION_MT_REVISION < 5 if (m_enable_vbo) { for (u32 i = 0; i < m->getMeshBufferCount(); i++) { scene::IMeshBuffer *buf = m->getMeshBuffer(i); RenderingEngine::get_video_driver()->removeHardwareBuffer(buf); } } +#endif m->drop(); } delete m_minimap_mapblock; -- cgit v1.2.3 From a66e6d4dff0b1dad065297442981718d7f7aec55 Mon Sep 17 00:00:00 2001 From: sfan5 Date: Fri, 6 May 2022 09:54:04 +0200 Subject: Consolidate some data structures in MapBlockMesh --- src/client/mapblock_mesh.cpp | 69 ++++++++++++++++++++++---------------------- src/client/mapblock_mesh.h | 13 ++++++--- 2 files changed, 44 insertions(+), 38 deletions(-) (limited to 'src/client/mapblock_mesh.cpp') diff --git a/src/client/mapblock_mesh.cpp b/src/client/mapblock_mesh.cpp index 2c5500fca..868573bf0 100644 --- a/src/client/mapblock_mesh.cpp +++ b/src/client/mapblock_mesh.cpp @@ -1252,6 +1252,9 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): Convert MeshCollector to SMesh */ + const bool desync_animations = g_settings->getBool( + "desynchronize_mapblock_texture_animation"); + for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) { for(u32 i = 0; i < collector.prebuffers[layer].size(); i++) { @@ -1281,18 +1284,18 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): // - Texture animation if (p.layer.material_flags & MATERIAL_FLAG_ANIMATION) { // Add to MapBlockMesh in order to animate these tiles - m_animation_tiles[std::pair(layer, i)] = p.layer; - m_animation_frames[std::pair(layer, i)] = 0; - if (g_settings->getBool( - "desynchronize_mapblock_texture_animation")) { + auto &info = m_animation_info[{layer, i}]; + info.tile = p.layer; + info.frame = 0; + if (desync_animations) { // Get starting position from noise - m_animation_frame_offsets[std::pair(layer, i)] = + info.frame_offset = 100000 * (2.0 + noise3d( data->m_blockpos.X, data->m_blockpos.Y, data->m_blockpos.Z, 0)); } else { // Play all synchronized - m_animation_frame_offsets[std::pair(layer, i)] = 0; + info.frame_offset = 0; } // Replace tile texture with the first animation frame p.layer.texture = (*p.layer.frames)[0].texture; @@ -1303,19 +1306,23 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): // Dummy sunlight to handle non-sunlit areas video::SColorf sunlight; get_sunlight_color(&sunlight, 0); - u32 vertex_count = p.vertices.size(); + + std::map colors; + const u32 vertex_count = p.vertices.size(); for (u32 j = 0; j < vertex_count; j++) { video::SColor *vc = &p.vertices[j].Color; video::SColor copy = *vc; if (vc->getAlpha() == 0) // No sunlight - no need to animate final_color_blend(vc, copy, sunlight); // Finalize color else // Record color to animate - m_daynight_diffs[std::pair(layer, i)][j] = copy; + colors[j] = copy; // The sunlight ratio has been stored, // delete alpha (for the final rendering). vc->setAlpha(255); } + if (!colors.empty()) + m_daynight_diffs[{layer, i}] = std::move(colors); } // Create material @@ -1384,7 +1391,7 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): m_has_animation = !m_crack_materials.empty() || !m_daynight_diffs.empty() || - !m_animation_tiles.empty(); + !m_animation_info.empty(); } MapBlockMesh::~MapBlockMesh() @@ -1418,25 +1425,22 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, for (auto &crack_material : m_crack_materials) { scene::IMeshBuffer *buf = m_mesh[crack_material.first.first]-> getMeshBuffer(crack_material.first.second); - std::string basename = crack_material.second; // Create new texture name from original - std::ostringstream os; - os << basename << crack; + std::string s = crack_material.second + itos(crack); u32 new_texture_id = 0; video::ITexture *new_texture = - m_tsrc->getTextureForMesh(os.str(), &new_texture_id); + m_tsrc->getTextureForMesh(s, &new_texture_id); buf->getMaterial().setTexture(0, new_texture); - // If the current material is also animated, - // update animation info - auto anim_iter = m_animation_tiles.find(crack_material.first); - if (anim_iter != m_animation_tiles.end()) { - TileLayer &tile = anim_iter->second; + // If the current material is also animated, update animation info + auto anim_it = m_animation_info.find(crack_material.first); + if (anim_it != m_animation_info.end()) { + TileLayer &tile = anim_it->second.tile; tile.texture = new_texture; tile.texture_id = new_texture_id; // force animation update - m_animation_frames[crack_material.first] = -1; + anim_it->second.frame = -1; } } @@ -1444,28 +1448,25 @@ bool MapBlockMesh::animate(bool faraway, float time, int crack, } // Texture animation - for (auto &animation_tile : m_animation_tiles) { - const TileLayer &tile = animation_tile.second; + for (auto &it : m_animation_info) { + const TileLayer &tile = it.second.tile; // Figure out current frame - int frameoffset = m_animation_frame_offsets[animation_tile.first]; - int frame = (int)(time * 1000 / tile.animation_frame_length_ms - + frameoffset) % tile.animation_frame_count; + int frameno = (int)(time * 1000 / tile.animation_frame_length_ms + + it.second.frame_offset) % tile.animation_frame_count; // If frame doesn't change, skip - if (frame == m_animation_frames[animation_tile.first]) + if (frameno == it.second.frame) continue; - m_animation_frames[animation_tile.first] = frame; + it.second.frame = frameno; - scene::IMeshBuffer *buf = m_mesh[animation_tile.first.first]-> - getMeshBuffer(animation_tile.first.second); + scene::IMeshBuffer *buf = m_mesh[it.first.first]->getMeshBuffer(it.first.second); - const FrameSpec &animation_frame = (*tile.frames)[frame]; - buf->getMaterial().setTexture(0, animation_frame.texture); + const FrameSpec &frame = (*tile.frames)[frameno]; + buf->getMaterial().setTexture(0, frame.texture); if (m_enable_shaders) { - if (animation_frame.normal_texture) - buf->getMaterial().setTexture(1, - animation_frame.normal_texture); - buf->getMaterial().setTexture(2, animation_frame.flags_texture); + if (frame.normal_texture) + buf->getMaterial().setTexture(1, frame.normal_texture); + buf->getMaterial().setTexture(2, frame.flags_texture); } } diff --git a/src/client/mapblock_mesh.h b/src/client/mapblock_mesh.h index cfc39ade2..72d128038 100644 --- a/src/client/mapblock_mesh.h +++ b/src/client/mapblock_mesh.h @@ -219,7 +219,14 @@ public: { return this->m_transparent_buffers; } + private: + struct AnimationInfo { + int frame; // last animation frame + int frame_offset; + TileLayer tile; + }; + scene::IMesh *m_mesh[MAX_TILE_LAYERS]; MinimapMapblock *m_minimap_mapblock; ITextureSource *m_tsrc; @@ -238,12 +245,10 @@ private: // Maps mesh and mesh buffer (i.e. material) indices to base texture names std::map, std::string> m_crack_materials; - // Animation info: texture animationi + // Animation info: texture animation // Maps mesh and mesh buffer indices to TileSpecs // Keys are pairs of (mesh index, buffer index in the mesh) - std::map, TileLayer> m_animation_tiles; - std::map, int> m_animation_frames; // last animation frame - std::map, int> m_animation_frame_offsets; + std::map, AnimationInfo> m_animation_info; // Animation info: day/night transitions // Last daynight_ratio value passed to animate() -- cgit v1.2.3