From 3b9d8b2fa3ba88f91e6aa8aa752f410ded38c263 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:12:50 +0100 Subject: [PATCH 1/3] fix(render): EU07M review of #537: no whole vertices kept for the bounds, the compact variant checked by CI and given up when it fails - The bounding radius, offset() and MaxY() read the positions of a chunk alone (Positions(), geometry_bank::positions()): on Vulkan the compact streams are no longer decoded into basic_vertex and kept for the life of the bank as every model loads, so the host memory of EU07M models stays below that of E3D. What still needs whole vertices (the editor, the picking, the export) decodes them on first use as before. - A COMPACT_VERTEX variant which doesn't compile is told once in the log and the banks of EU07M models go back to basic_vertex (compact_layout_failed()), those built already when they are drawn next, instead of the models being left out for the session. - The shader validator compiles the vk14 shaders which have COMPACT_VERTEX with it, alone and with MODEL_DRAWS, as the renderer makes the variants. --- ci_shadervalidator/main.cpp | 11 +++++++++ model/Model3d.cpp | 32 ++++++++++++++++++------- rendering/geometrybank.cpp | 24 +++++++++++++++++++ rendering/geometrybank.h | 4 ++++ rendering/renderer.h | 9 +++++++ rendering/vulkan14/vulkan14geometry.cpp | 22 +++++++++++++++-- rendering/vulkan14/vulkan14geometry.h | 7 ++++++ rendering/vulkan14/vulkan14indirect.cpp | 5 ++++ rendering/vulkan14/vulkan14renderer.h | 1 + rendering/vulkan14/vulkan14scene.cpp | 5 ++++ 10 files changed, 109 insertions(+), 11 deletions(-) diff --git a/ci_shadervalidator/main.cpp b/ci_shadervalidator/main.cpp index 96af5c0ed..1bb1bbafb 100644 --- a/ci_shadervalidator/main.cpp +++ b/ci_shadervalidator/main.cpp @@ -226,6 +226,17 @@ bool check_vk14(std::string const &Name) if (!check_text(gfx::preprocess_shader(gfx::shader_api::vulkan14, Name, "#define NO_MOTION_OUTPUT 1\n", {}, false, vk14_dir), "-V --target-env " + vulkan_env)) suc = false; } + // the compact vertex layout of EU07M models (vk14::vertex_kind::scene_compact), alone and with the multi draws, as the + // renderer puts the definitions before the sources (compact_kind and multidraw_kind of vulkan14indirect.cpp) + if (source.text.find("COMPACT_VERTEX") != std::string::npos) + { + std::cout << "done, compact vertices..." << std::flush; + for (std::string_view const defines : {"#define COMPACT_VERTEX\n", "#define MODEL_DRAWS\n#define COMPACT_VERTEX\n"}) + { + if (!check_text(gfx::preprocess_shader(gfx::shader_api::vulkan14, Name, std::string{defines}, {}, false, vk14_dir), "-V --target-env " + vulkan_env)) + suc = false; + } + } // the ray traced reflections (gfx.raytracing): the renderer puts the extensions and REFLECTION_RAYS before the sources // (vk14::binding_preamble()), the shaders which shade with light_common.glsl trace the rays if (source.text.find("REFLECTION_RAYS_ACTIVE") != std::string::npos) diff --git a/model/Model3d.cpp b/model/Model3d.cpp index c526c8ff9..485bb7054 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -1486,9 +1486,10 @@ void TSubModel::create_geometry(std::size_t &Indexoffset, std::size_t &Vertexoff // since we're comparing squared radii, we need to square it back for correct results m_boundingradius *= m_boundingradius; auto const submodeloffset{offset(std::numeric_limits::max())}; - for (auto const &vertex : GfxRenderer->Vertices(m_geometry.handle)) + // the positions alone: the vertices of an EU07M model on Vulkan would be made and kept whole for it + for (auto const &position : GfxRenderer->Positions(m_geometry.handle)) { - squaredradius = glm::length2(submodeloffset + vertex.position); + squaredradius = glm::length2(submodeloffset + position); if (squaredradius > m_boundingradius) { m_boundingradius = squaredradius; @@ -1612,9 +1613,9 @@ float TSubModel::MaxY(float4x4 const &m) if (m_geometry.handle != null_handle) { - for (auto const &vertex : GfxRenderer->Vertices(m_geometry.handle)) + for (auto const &position : GfxRenderer->Positions(m_geometry.handle)) { - maxy = std::max(maxy, m[0][1] * vertex.position.x + m[1][1] * vertex.position.y + m[2][1] * vertex.position.z + m[3][1]); + maxy = std::max(maxy, m[0][1] * position.x + m[1][1] * position.y + m[2][1] * position.z + m[3][1]); } } else if (false == Vertices.empty()) @@ -1756,17 +1757,30 @@ glm::vec3 TSubModel::offset(float const Geometrytestoffsetthreshold) const // offset of zero generally means the submodel has optimized identity matrix // for such cases we resort to an estimate from submodel geometry // TODO: do proper bounding area calculation for submodel when loading mesh and grab the centre point from it here - auto const &vertices{(m_geometry.handle != null_handle ? GfxRenderer->Vertices(m_geometry.handle) : Vertices)}; - if (false == vertices.empty()) + // the positions alone: the vertices of an EU07M model on Vulkan would be made and kept whole for them + gfx::position_array positions; + if (m_geometry.handle != null_handle) + { + positions = GfxRenderer->Positions(m_geometry.handle); + } + else + { + positions.reserve(Vertices.size()); + for (auto const &vertex : Vertices) + { + positions.push_back(vertex.position); + } + } + if (false == positions.empty()) { // transformation matrix for the submodel can still contain rotation and/or scaling, // so we pass the vertex positions through it rather than just grab them directly offset = glm::vec3(); - auto const vertexfactor{1.f / vertices.size()}; + auto const vertexfactor{1.f / positions.size()}; auto const transformationmatrix{glm::make_mat4(parentmatrix.readArray())}; - for (auto const &vertex : vertices) + for (auto const &position : positions) { - offset += glm::vec3{transformationmatrix * glm::vec4{vertex.position, 1}} * vertexfactor; + offset += glm::vec3{transformationmatrix * glm::vec4{position, 1}} * vertexfactor; } } } diff --git a/rendering/geometrybank.cpp b/rendering/geometrybank.cpp index 7e82cce68..ce84c9be1 100644 --- a/rendering/geometrybank.cpp +++ b/rendering/geometrybank.cpp @@ -496,6 +496,24 @@ geometry_bank::indices( gfx::geometry_handle const &Geometry ) const { return geometry_bank::chunk( Geometry ).indices; } +// the positions of the vertices of specified chunk: of a chunk of the compact layout its stream as it is, without making the +// basic_vertex of it which vertices() keeps for good +position_array +geometry_bank::positions( gfx::geometry_handle const &Geometry ) const { + + auto const &chunk { geometry_bank::chunk( Geometry ) }; + std::scoped_lock lock { m_decodemutex }; + if( chunk.compact() ) { + return chunk.positions; + } + position_array positions; + positions.reserve( chunk.vertices.size() ); + for( auto const &vertex : chunk.vertices ) { + positions.push_back( vertex.position ); + } + return positions; +} + // provides direct access to vertex data of specfied chunk vertex_array const & geometry_bank::vertices( gfx::geometry_handle const &Geometry ) const { @@ -751,6 +769,12 @@ geometrybank_manager::indices( gfx::geometry_handle const &Geometry ) const { } // provides direct access to vertex data of specfied chunk +gfx::position_array +geometrybank_manager::positions( gfx::geometry_handle const &Geometry ) const { + + return bank( Geometry ).first->positions( Geometry ); +} + gfx::vertex_array const & geometrybank_manager::vertices( gfx::geometry_handle const &Geometry ) const { diff --git a/rendering/geometrybank.h b/rendering/geometrybank.h index 8f1b20370..b44ee7f4b 100644 --- a/rendering/geometrybank.h +++ b/rendering/geometrybank.h @@ -181,6 +181,8 @@ public: void release(); // provides direct access to index data of specfied chunk auto indices( gfx::geometry_handle const &Geometry ) const -> gfx::index_array const &; + // the positions of the vertices of specified chunk, without the basic_vertex of a chunk of the compact layout being made + auto positions( gfx::geometry_handle const &Geometry ) const -> gfx::position_array; // provides direct access to vertex data of specfied chunk auto vertices( gfx::geometry_handle const &Geometry ) const -> gfx::vertex_array const &; // provides direct access to vertex user data of specfied chunk @@ -324,6 +326,8 @@ public: ++First; } } // provides direct access to index data of specfied chunk auto indices( gfx::geometry_handle const &Geometry ) const -> gfx::index_array const &; + // the positions of the vertices of specified chunk (geometry_bank::positions()) + auto positions( gfx::geometry_handle const &Geometry ) const -> gfx::position_array; // provides direct access to vertex data of specfied chunk auto vertices( gfx::geometry_handle const &Geometry ) const -> gfx::vertex_array const &; // what the banks keep in the process, for the debug panel: banks, chunks with their vertex bytes, index bytes and user data bytes diff --git a/rendering/renderer.h b/rendering/renderer.h index 17ba4db31..5021e9992 100644 --- a/rendering/renderer.h +++ b/rendering/renderer.h @@ -123,6 +123,15 @@ public: virtual auto Indices( gfx::geometry_handle const &Geometry ) const->gfx::index_array const & = 0; // provides direct access to vertex data of specfied chunk virtual auto Vertices( gfx::geometry_handle const &Geometry ) const ->gfx::vertex_array const & = 0; + // the positions of the vertices of specified chunk, for what needs no more of them (the bounds of a model as it loads): a renderer + // keeping the compact streams of an EU07M model gives them without making and keeping the basic_vertex Vertices() would + virtual auto Positions( gfx::geometry_handle const &Geometry ) const -> gfx::position_array { + auto const &vertices { Vertices( Geometry ) }; + gfx::position_array positions; + positions.reserve( vertices.size() ); + for( auto const &vertex : vertices ) { + positions.push_back( vertex.position ); } + return positions; } // provides direct access to vertex user data of specfied chunk virtual auto UserData( gfx::geometry_handle const &Geometry ) const ->gfx::userdata_array const & = 0; // kind of geometry of specified chunk, -1 when the renderer doesn't tell diff --git a/rendering/vulkan14/vulkan14geometry.cpp b/rendering/vulkan14/vulkan14geometry.cpp index 1cf0c35a7..b1f9f59b8 100644 --- a/rendering/vulkan14/vulkan14geometry.cpp +++ b/rendering/vulkan14/vulkan14geometry.cpp @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/vulkan14/vulkan14texture.h" #include +#include namespace vk14 { @@ -25,8 +26,24 @@ gfx::vertex_userdata const no_userdata{glm::vec4{0.f, 0.f, 0.f, 1.f}}; // the numbers the data of the banks get, unique across the banks (a bank made where another one was gets a new one) std::atomic g_generation{0}; +// set when a variant of a program for the compact layout didn't compile (compact_layout_failed()) +std::atomic g_compactfailed{false}; + } // namespace +void compact_layout_failed(std::string_view const Program) +{ + if (false == g_compactfailed.exchange(true)) + { + log_error(std::format("the compact vertex variant of \"{}\" didn't compile; EU07M models are drawn from basic_vertex from now on", Program)); + } +} + +bool compact_layout_usable() +{ + return false == g_compactfailed.load(); +} + VkPrimitiveTopology topology_of(unsigned int const Type) { switch (Type) @@ -150,7 +167,7 @@ bool vulkan14_geometrybank::build() release_(); // the compact layout when every chunk of the bank is of it (an EU07M model); otherwise its chunks go as basic_vertex - m_compact = (false == m_chunks.empty()) && std::ranges::all_of(m_chunks, [](geometry_chunk const &Chunk) { return Chunk.compact(); }); + m_compact = compact_layout_usable() && (false == m_chunks.empty()) && std::ranges::all_of(m_chunks, [](geometry_chunk const &Chunk) { return Chunk.compact(); }); if (false == m_compact) { for (auto &chunk : m_chunks) @@ -297,7 +314,8 @@ bool vulkan14_geometrybank::source(gfx::geometry_handle const &Geometry, chunk_s return false; } std::lock_guard lock(m_mutex); - if (m_layoutdirty) + // a bank of the compact layout whose programs can't be had is made anew of basic_vertex + if (m_layoutdirty || (m_compact && (false == compact_layout_usable()))) { build(); } diff --git a/rendering/vulkan14/vulkan14geometry.h b/rendering/vulkan14/vulkan14geometry.h index daed8db8d..7ad767074 100644 --- a/rendering/vulkan14/vulkan14geometry.h +++ b/rendering/vulkan14/vulkan14geometry.h @@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include namespace vk14 { @@ -56,6 +57,12 @@ struct chunk_source // the vulkan primitive of a primitive of opengl (GL_TRIANGLES ...) VkPrimitiveTopology topology_of(unsigned int Type); +// a variant of a scene program for the compact layout didn't compile: the banks of EU07M models are made of basic_vertex +// from then on, those made already when they are drawn next, so the models stay in sight. told once in the log +void compact_layout_failed(std::string_view Program); +// false once compact_layout_failed() was called +bool compact_layout_usable(); + class vulkan14_geometrybank : public gfx::geometry_bank { public: diff --git a/rendering/vulkan14/vulkan14indirect.cpp b/rendering/vulkan14/vulkan14indirect.cpp index 611f139fb..48f5d5d5d 100644 --- a/rendering/vulkan14/vulkan14indirect.cpp +++ b/rendering/vulkan14/vulkan14indirect.cpp @@ -320,6 +320,11 @@ std::shared_ptr make_variant(vk14::shader_library &Shaders, catch (gfx::shader_exception const &Exception) { vk14::log_error(Exception.what()); + if (Kind.compact) + { + // without the variant the chunks of the compact layout would be left out for good: their banks go back to basic_vertex + vk14::compact_layout_failed(Name); + } } return nullptr; } diff --git a/rendering/vulkan14/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index de445152e..23e017f67 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -88,6 +88,7 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk void Erase(gfx::geometry_handle const &Geometry) override; gfx::index_array const &Indices(gfx::geometry_handle const &Geometry) const override; gfx::vertex_array const &Vertices(gfx::geometry_handle const &Geometry) const override; + gfx::position_array Positions(gfx::geometry_handle const &Geometry) const override; gfx::userdata_array const &UserData(gfx::geometry_handle const &Geometry) const override; int Primitive(gfx::geometry_handle const &Geometry) const override; // the sleepers and timbers are drawn by the walk of the scene (gfx::scene_walk), as in the opengl renderer diff --git a/rendering/vulkan14/vulkan14scene.cpp b/rendering/vulkan14/vulkan14scene.cpp index 4ad5f432b..1fb38ec6f 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -1352,6 +1352,11 @@ gfx::vertex_array const &vulkan14_renderer::Vertices(gfx::geometry_handle const return m_geometry.vertices(Geometry); } +gfx::position_array vulkan14_renderer::Positions(gfx::geometry_handle const &Geometry) const +{ + return m_geometry.positions(Geometry); +} + gfx::userdata_array const &vulkan14_renderer::UserData(gfx::geometry_handle const &Geometry) const { return m_geometry.userdata(Geometry); From 99bc0b125c5f75ecef4da01ddec8690247d86fec Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:14:35 +0100 Subject: [PATCH 2/3] fix(render): EU07M review of #538: an instance with light colours of its own drawn alone, the light records locked only when stale - An instance with lightcolors of its own isn't instanced: the colours go onto the shared submodels as the instance is prepared, which the instances of a bucket don't each get, so they all showed the colours of one of them. - The walk takes the exclusive lock for the light records of a bucket only when they are stale in this frame (Refresh_Light_Records() checks again under it): the later passes of the frame no longer stop the other walkers. - instance_cull.comp (both renderers) puts the word of the light parts into [0][3] after the product with the view, so a view with a translation can't stretch the first column of a lit instance. - The spec: ls_Dark / ls_Home switch without the fade too, and the instances with light colours of their own. --- docs/eu07m-format.md | 5 ++++- model/AnimModel.cpp | 5 +++++ rendering/common/scenewalk.cpp | 5 +++-- shaders/ogl46/instance_cull.comp | 6 +++++- shaders/vk14/instance_cull.comp | 6 +++++- 5 files changed, 22 insertions(+), 5 deletions(-) diff --git a/docs/eu07m-format.md b/docs/eu07m-format.md index 8723fd89e..514a08cfb 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -257,7 +257,10 @@ egzemplarz osobno. Dotyczy to modeli EU07M i E3D tak samo. w shaderze macierz zerową (`instance_hides_part()` w `common.glsl`). - Egzemplarz pokazuje całą część zapaloną albo całą zgaszoną. Przy miganiu i przy przełączaniu (`ls_On` / `ls_Off` / `ls_Blink`) zamiana następuje w połowie przejścia (krycie 0,5), a nie płynnym przenikaniem jak bez instancjonowania. - Stany stałe wyglądają tak samo jak bez instancjonowania. + Stany stałe wyglądają tak samo jak bez instancjonowania. Tak samo bez płynnego przejścia (`fVisible`) zmieniają się + `ls_Dark` i `ls_Home`. +- Egzemplarz z własnymi kolorami świateł (`lightcolors` węzła) jest rysowany osobno: kolory są nadawane wspólnym + submodelom przy przygotowaniu egzemplarza, którego egzemplarze kubełka nie dostają każdy z osobna. - Pomiar (Vulkan, 200 głowic `s4ipcpb_dd`): z `gfx.gpucull 0` klatka 9,2 ms → 1,5–2,5 ms i 2400 → 16 drawcalli, z `gfx.gpucull 1` 9,1 ms → 3,0 ms i 2410 → 26 drawcalli. diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 91cf164d1..8c347163b 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "model/AnimModel.h" +#include + #include "rendering/renderer.h" #include "model/MdlMngr.h" #include "simulation/simulation.h" @@ -569,6 +571,9 @@ void TAnimModel::update_instanceable_flag() { // gfx.instancedlights: the lights go with the matrix of each instance (instance_light_bits()), and the instanced walk // animates each instance (RaAnimate) and prepares the model with all the parts of the lights shown (RaPrepareInstanced) if( ( iNumLights != 0 ) && ( false == Global.gfx_instancedlights ) ) { ++s_rejected_lights; return; } + // light colours of its own (lightcolors of the node) go onto the shared submodels as the instance is prepared (RaPrepare), + // which the instances of a bucket don't each get: such an instance is drawn on its own + if( std::ranges::any_of( m_lightcolors, []( glm::vec3 const &Colour ) { return Colour.r >= 0.f; } ) ) { ++s_rejected_lights; return; } if( !m_animlist.empty() ) { ++s_rejected_animlist; return; } if( submodel_tree_blocks_instancing( pModel->Root ) ) { ++s_rejected_animated_submodel; return; } m_instanceable = true; diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index 1b348c25d..0e69fad1b 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -1034,8 +1034,9 @@ void scene_walk::Queue_Instances( scene::basic_cell const *Cell ) } } if( m_instancecullpass && bucket_has_lights( instancebucket ) ) { - // the culling of the gpu takes the light states of the instances from their records - gfx::walk_sync::change change; + // the culling of the gpu takes the light states of the instances from their records. only the first pass of the frame has + // them to refresh (Refresh_Light_Records() checks again under the lock), so the others don't stop the walkers for it + gfx::walk_sync::change change { instancebucket.lightsframe != m_framestamp }; Refresh_Light_Records( instancebucket ); } if( buckettests && Bucket_Culled( instancebucket ) ) { diff --git a/shaders/ogl46/instance_cull.comp b/shaders/ogl46/instance_cull.comp index 5a6fd6ca4..c874d880e 100644 --- a/shaders/ogl46/instance_cull.comp +++ b/shaders/ogl46/instance_cull.comp @@ -226,7 +226,11 @@ void write(uint entry, instance_record record, vec3 location, instance_cull_job modelviews[slot] = originview * mat4(record.rotationscale[0], record.rotationscale[1], record.rotationscale[2], vec4(record.position, 1.0)); return; } - modelviews[slot] = view * mat4(record.rotationscale[0], record.rotationscale[1], record.rotationscale[2], vec4(location, 1.0)); + // the word of the light parts (w of the first column, instance_light_bits()) is put back after the product, so a view with a + // translation can't add to the first column with it + mat4 modelview = view * mat4(vec4(record.rotationscale[0].xyz, 0.0), record.rotationscale[1], record.rotationscale[2], vec4(location, 1.0)); + modelview[0][3] = record.rotationscale[0].w; + modelviews[slot] = modelview; } void main() diff --git a/shaders/vk14/instance_cull.comp b/shaders/vk14/instance_cull.comp index c6b8e0983..b07a59b48 100644 --- a/shaders/vk14/instance_cull.comp +++ b/shaders/vk14/instance_cull.comp @@ -234,7 +234,11 @@ void write(uint entry, instance_record record, vec3 location, instance_cull_job modelviews[slot] = originview * mat4(record.rotationscale[0], record.rotationscale[1], record.rotationscale[2], vec4(record.position, 1.0)); return; } - modelviews[slot] = view * mat4(record.rotationscale[0], record.rotationscale[1], record.rotationscale[2], vec4(location, 1.0)); + // the word of the light parts (w of the first column, instance_light_bits()) is put back after the product, so a view with a + // translation can't add to the first column with it + mat4 modelview = view * mat4(vec4(record.rotationscale[0].xyz, 0.0), record.rotationscale[1], record.rotationscale[2], vec4(location, 1.0)); + modelview[0][3] = record.rotationscale[0].w; + modelviews[slot] = modelview; } void main() From 115c13b2747da7defe22a1db390a9a4df1565b1b Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:16:19 +0100 Subject: [PATCH 3/3] fix(model): EU07M review of #539: a model made anew keeps its transforms, normals of scaled joints, the rest pose far from the origin - A node of a model made anew (legacy_flags 0) with a transform gets 0x8000, as a converted one has it: the walk and posed_transform() left such nodes out, so a skin was drawn off its place in the bind pose (the tube: the upper half 2 m off) and jumped when an animation set 0x4000 on the joint. - Normals are skinned by the cofactors of the blended rotation (the direction of its inverse transpose), with the sign of its determinant, not by the rotation: a joint scaled unevenly tilted the normals of its part. - rest_pose() takes the translation within the tolerance times the distance from the origin of the mesh and the joints (palette_scale()): the float chain rounds in proportion to it, and a model a few kilometres out counted as posed in the bind pose, with a geometry copy and a skinning pass of its own. Tests: the rest pose far from the origin, the normals of a stretched and of a mirroring joint. --- model/eu07m/eu07m_load.cpp | 4 ++++ model/skinning.cpp | 31 +++++++++++++++++++++++++++---- model/skinning.h | 8 ++++++-- rendering/common/skincache.cpp | 5 +++-- tests/unit/test_skinning.cpp | 21 +++++++++++++++++++++ 5 files changed, 61 insertions(+), 8 deletions(-) diff --git a/model/eu07m/eu07m_load.cpp b/model/eu07m/eu07m_load.cpp index 987f25191..509afcd15 100644 --- a/model/eu07m/eu07m_load.cpp +++ b/model/eu07m/eu07m_load.cpp @@ -148,6 +148,10 @@ void submodel_builder::build(std::uint32_t const Index, TSubModel &Submodel) { // 0 is no limit (a model made anew); a converted one carries the range of its E3D submodel. the submodel keeps its default Submodel.fSquareMaxDist = node.range_max_sq > 0.f ? node.range_max_sq : Submodel.fSquareMaxDist; transform(Index, Submodel); + // a model made anew has no E3D flags (legacy_flags 0): a node of it with a transform keeps it as one converted from E3D does + // (0x8000), or the walk and posed_transform() would leave it out, and with it the joints of the skins + if ((node.legacy_flags == 0) && (Submodel.iMatrix >= 0) && (m_transforms[Index] != glm::mat4{1.f})) + Submodel.iFlags |= 0x8000; auto const parts{parts_of(m_model, node)}; Submodel.b_Anim = parts.animation; Submodel.eType = TP_ROTATOR; diff --git a/model/skinning.cpp b/model/skinning.cpp index f20bdf3e3..4e346b8f4 100644 --- a/model/skinning.cpp +++ b/model/skinning.cpp @@ -58,15 +58,18 @@ std::vector palette(glm::mat4 const &Mesh, std::span return result; } -bool rest_pose(std::span const Palette, float const Tolerance) +bool rest_pose(std::span const Palette, float const Tolerance, float const Scale) { glm::mat4 const identity{1.f}; - return std::ranges::all_of(Palette, [&](glm::mat4 const &Matrix) { + // the translation is rounded in proportion to the distances the palette was made of + auto const translation{Tolerance * std::max(1.f, Scale)}; + return std::ranges::all_of(Palette, [&identity, Tolerance, translation](glm::mat4 const &Matrix) { for (int column = 0; column < 4; ++column) { + auto const limit{column == 3 ? translation : Tolerance}; for (int row = 0; row < 4; ++row) { - if (std::abs(Matrix[column][row] - identity[column][row]) > Tolerance) + if (std::abs(Matrix[column][row] - identity[column][row]) > limit) { return false; } @@ -76,6 +79,17 @@ bool rest_pose(std::span const Palette, float const Tolerance) }); } +float palette_scale(glm::mat4 const &Mesh, std::span const Joints) +{ + auto const reach{[](glm::mat4 const &Matrix) { return std::max({std::abs(Matrix[3][0]), std::abs(Matrix[3][1]), std::abs(Matrix[3][2])}); }}; + auto scale{reach(Mesh)}; + for (auto const &joint : Joints) + { + scale = std::max(scale, reach(joint)); + } + return scale; +} + namespace { @@ -102,6 +116,15 @@ glm::vec3 direction(glm::mat3 const &Rotation, glm::vec3 const &Vector) return length > 0.f ? moved / length : Vector; } +// what moves the normals: the inverse transpose of the rotation, here as its cofactors (the same direction, without the +// division), with the sign of the determinant so a mirroring matrix keeps the normals facing out. the rotation itself would +// tilt the normals of a part squashed by a scale +glm::mat3 normal_matrix(glm::mat3 const &Rotation) +{ + glm::mat3 const cofactors{glm::cross(Rotation[1], Rotation[2]), glm::cross(Rotation[2], Rotation[0]), glm::cross(Rotation[0], Rotation[1])}; + return glm::dot(Rotation[0], cofactors[0]) < 0.f ? -cofactors : cofactors; +} + } // namespace void skin_vertices(std::span const Rest, std::span const Weights, std::span const Palette, std::span const Out) @@ -119,7 +142,7 @@ void skin_vertices(std::span const Rest, std::span vertex_weights unpack(std::array co // Mesh and Joint posed from the root of the model, so the placement of the instance cancels out std::vector palette(glm::mat4 const &Mesh, std::span Joints, std::span InverseBind); -// true when every matrix of the palette leaves the vertices where they are (within Tolerance): the rest pose -bool rest_pose(std::span Palette, float Tolerance = 1e-5f); +// true when every matrix of the palette leaves the vertices where they are: the rest pose. the rotation within Tolerance, the +// translation within Tolerance times Scale (at least 1), the distance from the origin of what the palette was made of +// (palette_scale()), as the float chain rounds in proportion to it +bool rest_pose(std::span Palette, float Tolerance = 1e-5f, float Scale = 1.f); +// the largest distance from the origin along an axis of the mesh and the joints a palette is made of +float palette_scale(glm::mat4 const &Mesh, std::span Joints); // the vertices moved by the palette: positions by the blended matrix, normals and tangents by its rotation, renormalised. a joint out // of the palette counts as the identity. Out has as many vertices as Rest diff --git a/rendering/common/skincache.cpp b/rendering/common/skincache.cpp index 9a23ce500..68398ed23 100644 --- a/rendering/common/skincache.cpp +++ b/rendering/common/skincache.cpp @@ -64,8 +64,9 @@ geometry_handle skin_cache::geometry(TSubModel &Submodel, TModel3d const &Model, { joints.emplace_back(joint != nullptr ? joint->posed_transform() : glm::mat4{1.f}); } - auto palette{skinning::palette(Submodel.posed_transform(), joints, skin.inverse_bind)}; - cached.posed = (false == skinning::rest_pose(palette)); + auto const mesh{Submodel.posed_transform()}; + auto palette{skinning::palette(mesh, joints, skin.inverse_bind)}; + cached.posed = (false == skinning::rest_pose(palette, 1e-5f, skinning::palette_scale(mesh, joints))); if (cached.posed && (palette != cached.palette)) { cached.vertices.resize(source->rest.size()); diff --git a/tests/unit/test_skinning.cpp b/tests/unit/test_skinning.cpp index 39f4970ec..bd0c2a5d8 100644 --- a/tests/unit/test_skinning.cpp +++ b/tests/unit/test_skinning.cpp @@ -139,8 +139,29 @@ TEST_CASE("skinning: the bind pose leaves the vertices where they are") { auto const placed{glm::translate(glm::rotate(glm::mat4{1.f}, 0.7f, glm::vec3{0.f, 1.f, 0.f}), glm::vec3{10.f, 5.f, -3.f})}; std::vector const placedjoints{placed, placed * tipbind}; CHECK(skinning::rest_pose(skinning::palette(placed, placedjoints, inversebind), 1e-4f)); + // the default tolerance, scaled by the distances the palette was made of: a model far from the origin is at rest as well + auto const distant{glm::translate(glm::mat4{1.f}, glm::vec3{1500.f, 40.f, -2300.f})}; + std::vector const distantjoints{distant, distant * tipbind}; + CHECK(skinning::rest_pose(skinning::palette(distant, distantjoints, inversebind), 1e-5f, skinning::palette_scale(distant, distantjoints))); std::vector const moved{glm::translate(glm::mat4{1.f}, glm::vec3{0.f, 0.1f, 0.f})}; CHECK_FALSE(skinning::rest_pose(moved)); + CHECK_FALSE(skinning::rest_pose(moved, 1e-5f, skinning::palette_scale(distant, distantjoints))); +} + +TEST_CASE("skinning: the normals of a part scaled unevenly stay square to its surface") { + // a joint stretched twice along x: a surface at 45 degrees leans towards y, its normal towards x less + std::vector const palette{glm::scale(glm::mat4{1.f}, glm::vec3{2.f, 1.f, 1.f})}; + auto vertex{vertex_at({0.f, 0.f, 0.f})}; + vertex.normal = glm::normalize(glm::vec3{1.f, 1.f, 0.f}); + std::vector const rest{vertex}; + std::vector const weights{{{0, 0, 0, 0}, {1.f, 0.f, 0.f, 0.f}}}; + std::vector out(1); + skinning::skin_vertices(rest, weights, palette, out); + CHECK(close_to(out[0].normal, glm::normalize(glm::vec3{0.5f, 1.f, 0.f}))); + // a mirroring joint keeps the normal facing out + std::vector const mirror{glm::scale(glm::mat4{1.f}, glm::vec3{-1.f, 1.f, 1.f})}; + skinning::skin_vertices(rest, weights, mirror, out); + CHECK(close_to(out[0].normal, glm::normalize(glm::vec3{-1.f, 1.f, 0.f}))); } TEST_CASE("skinning: a joint turned moves its vertices, blended by the weights") {