18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-02 15:26:53 +01:00
Files
maszyna/model/skinning.cpp
T
maj00r 2e7c1abdac feat(model): skinned parts of EU07M models move with their joints, skinned on the CPU (#539)
* feat(model): skinned parts of EU07M models move with their joints, skinned on the CPU

Stage 4 of the EU07M model format. A primitive with a skin (SKIN, SKJT, weights in VSKN or VSKW) was drawn in its bind
pose. Now it follows the joints of its skin, in both renderers.

- The joints are nodes of the model, so they're posed as before: animation events, the .mmd, SetRotate / SetTranslate
  from the vehicle code. The matrix of a joint is world(joint) * inverse bind(joint), world being the transform of the
  joint from the root of the model with the animations of the instance drawn (TSubModel::posed_transform()); the
  vertices lie in the bind pose in the space of the model, the transform of the node of the mesh left out, as in glTF.
- The loader keeps the bind pose and the weights of a skinned primitive (skinning::skinned_geometry on the submodel) and
  the skins of the model (TModel3d::skins()).
- The first pass of a frame to draw a skinned submodel of an instance works out the palette and, when it changed, moves
  the vertices on the CPU: positions by the blended matrix, normals and tangents by its rotation (model/skinning.cpp,
  gfx::skin_cache in rendering/common/skincache.cpp). The geometry of the instance is made or replaced before the passes
  of the next frame (flush() in the frame setup of both renderers), as nothing the passes draw may change while they draw
  (gfx::walk_sync): the vertices follow the joints a frame late. In the bind pose the shared geometry of the model is
  drawn; an instance not drawn for 600 frames lets go of its own.
- Fix: a node with range_max_sq 0, which the spec gives as no limit, was never drawn (a model made anew rather than
  converted from E3D); it keeps the default range of a submodel now.
- The editor self-test gets "animate <node> <submodel> <x> <y> <z>", which turns a submodel of an instance as an
  animation event does, since the editor doesn't run the events.

Not in this commit: the skinning in a compute shader, bounds of the posed submodel, motion vectors and ray tracing of the
moved vertices.

Checked: a tube of two joints in two instances, one turned by 60 degrees at its middle, bends smoothly while the other
stays straight, in Vulkan and GL 4.6, with gfx.gpucull 0 and 1 (time let run in the editor for the test only). Unit
tests 1194/1194, 5 new ones for the weights, the bind pose, the blending and the file. Not built with GCC here.

* 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.

* fix(model): a mirroring joint turns the handedness of the tangent frame too, so the bitangent mirrors with the surface

* feat(model): .r3a and .r3p in what this branch adds, as below it

The model files are .r3a and the family store .r3p, selected with modelformat r3a (2fe1064f9 on feat/e4d-compact).

* feat(model): .ng3d and .ng3p in what this branch adds, as below it

The model files are .ng3d and the family store .ng3p, selected with modelformat ng3d (8637101d9 on feat/e4d-compact).
2026-12-01 18:12:08 +01:00

159 lines
5.0 KiB
C++

/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "model/skinning.h"
#include <algorithm>
#include <cmath>
#include <limits>
namespace skinning
{
template <typename Weight> vertex_weights unpack(std::array<std::uint16_t, 4> const &Joints, std::array<Weight, 4> const &Weights)
{
vertex_weights result;
result.joints = Joints;
auto total{0.f};
for (std::size_t idx = 0; idx < 4; ++idx)
{
result.weights[idx] = static_cast<float>(Weights[idx]) / static_cast<float>(std::numeric_limits<Weight>::max());
total += result.weights[idx];
}
if (total <= 0.f)
{
result.joints = {};
result.weights = {1.f, 0.f, 0.f, 0.f};
return result;
}
// the weights of the file add up to the largest value of the type; the rounding of the division is made up for here
for (auto &weight : result.weights)
{
weight /= total;
}
return result;
}
template vertex_weights unpack<std::uint8_t>(std::array<std::uint16_t, 4> const &, std::array<std::uint8_t, 4> const &);
template vertex_weights unpack<std::uint16_t>(std::array<std::uint16_t, 4> const &, std::array<std::uint16_t, 4> const &);
std::vector<glm::mat4> palette(glm::mat4 const &Mesh, std::span<glm::mat4 const> const Joints, std::span<glm::mat4 const> const InverseBind)
{
auto const tomesh{glm::inverse(Mesh)};
std::vector<glm::mat4> result;
result.reserve(Joints.size());
for (std::size_t idx = 0; idx < Joints.size(); ++idx)
{
auto const inversebind{idx < InverseBind.size() ? InverseBind[idx] : glm::mat4{1.f}};
result.emplace_back(tomesh * Joints[idx] * inversebind);
}
return result;
}
bool rest_pose(std::span<glm::mat4 const> const Palette, float const Tolerance, float const Scale)
{
glm::mat4 const identity{1.f};
// 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]) > limit)
{
return false;
}
}
}
return true;
});
}
float palette_scale(glm::mat4 const &Mesh, std::span<glm::mat4 const> 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
{
glm::mat4 blended(vertex_weights const &Weights, std::span<glm::mat4 const> const Palette)
{
glm::mat4 result{0.f};
for (std::size_t idx = 0; idx < 4; ++idx)
{
auto const weight{Weights.weights[idx]};
if (weight <= 0.f)
{
continue;
}
auto const joint{static_cast<std::size_t>(Weights.joints[idx])};
result += weight * (joint < Palette.size() ? Palette[joint] : glm::mat4{1.f});
}
return result;
}
glm::vec3 direction(glm::mat3 const &Rotation, glm::vec3 const &Vector)
{
auto const moved{Rotation * Vector};
auto const length{glm::length(moved)};
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, bool const Mirrors)
{
glm::mat3 const cofactors{glm::cross(Rotation[1], Rotation[2]), glm::cross(Rotation[2], Rotation[0]), glm::cross(Rotation[0], Rotation[1])};
return Mirrors ? -cofactors : cofactors;
}
// the rotation turns the space inside out (a negative determinant): the normals take the sign, and so does the handedness of
// the tangent frame, or the bitangent rebuilt from the normal and the tangent points the other way
bool mirrors(glm::mat3 const &Rotation)
{
return glm::dot(Rotation[0], glm::cross(Rotation[1], Rotation[2])) < 0.f;
}
} // namespace
void skin_vertices(std::span<gfx::basic_vertex const> const Rest, std::span<vertex_weights const> const Weights, std::span<glm::mat4 const> const Palette, std::span<gfx::basic_vertex> const Out)
{
auto const count{std::min(Rest.size(), Out.size())};
for (std::size_t idx = 0; idx < count; ++idx)
{
auto const &rest{Rest[idx]};
auto &out{Out[idx]};
out = rest;
if (idx >= Weights.size())
{
continue;
}
auto const matrix{blended(Weights[idx], Palette)};
glm::mat3 const rotation{matrix};
out.position = glm::vec3{matrix * glm::vec4{rest.position, 1.f}};
auto const mirrored{mirrors(rotation)};
out.normal = direction(normal_matrix(rotation, mirrored), rest.normal);
out.tangent = glm::vec4{direction(rotation, glm::vec3{rest.tangent}), mirrored ? -rest.tangent.w : rest.tangent.w};
}
}
} // namespace skinning