33 const std::vector<bool>& activeJoints) {
34 for (
size_t jointIndex = 0; jointIndex < activeJoints.size(); ++jointIndex) {
35 if (!activeJoints[jointIndex]) {
44 return parameterTransform;
47struct SimplifiedJointPlacement {
50 Vector3f translationOffset = Vector3f::Zero();
53SimplifiedJointPlacement getSimplifiedJointPlacement(
56 const std::vector<size_t>& lastJoint,
57 const size_t jointIndex) {
58 const Joint& joint = skeleton.joints.at(jointIndex);
63 size_t retainedAncestor = jointIndex;
66 retainedAncestor = skeleton.joints.at(retainedAncestor).parent;
68 simplifiedParent = lastJoint.at(retainedAncestor);
73 ? referenceState.jointState.at(retainedAncestor).transform.inverse() *
74 referenceState.jointState.at(jointIndex).translation()
75 : referenceState.jointState.at(jointIndex).translation();
76 return {simplifiedParent, retainedAncestor, offset};
79Joint makeSimplifiedJoint(
81 const size_t jointIndex,
82 const SimplifiedJointPlacement& placement) {
83 Joint result = skeleton.joints.at(jointIndex);
84 result.parent = placement.parent;
85 result.translationOffset = placement.translationOffset;
87 size_t parent = skeleton.joints.at(jointIndex).parent;
88 while (parent != placement.retainedAncestor && parent !=
kInvalidIndex) {
89 result.preRotation = skeleton.joints.at(parent).preRotation * result.preRotation;
90 parent = skeleton.joints.at(parent).parent;
96size_t findSimplifiedAncestor(
98 const std::vector<size_t>& intermediateJointMap,
99 const size_t jointIndex) {
100 size_t ancestor = jointIndex;
102 ancestor = skeleton.joints.at(ancestor).parent;
107 "During skeleton simplification, inactive joint '{}' has no valid parent joint. "
108 "Every joint in the simplified skeleton must have at least one parent joint that is not disabled.",
109 skeleton.joints.at(jointIndex).name);
110 return intermediateJointMap.at(ancestor);
114 const Matrix3f inertiaRotation = properties.inertiaRotation.toRotationMatrix();
115 return inertiaRotation * properties.inertia * inertiaRotation.transpose();
118void addParallelAxisShift(
Matrix3f& inertia,
const float mass,
const Vector3f& offset) {
119 const float dx = offset.x();
120 const float dy = offset.y();
121 const float dz = offset.z();
122 inertia(0, 0) += mass * (dy * dy + dz * dz);
123 inertia(1, 1) += mass * (dx * dx + dz * dz);
124 inertia(2, 2) += mass * (dx * dx + dy * dy);
126 const float xy = -mass * dx * dy;
127 const float xz = -mass * dx * dz;
128 const float yz = -mass * dy * dz;
139 const Vector3f& centerOfMassOffset) {
140 Matrix3f result = inertiaInJointFrame(properties);
141 const Vector3f offset = properties.centerOfMassOffset - centerOfMassOffset;
142 addParallelAxisShift(result, properties.mass, offset);
146void symmetrizeInPlace(
Matrix3f& inertia) {
147 const float xy = 0.5f * (inertia(0, 1) + inertia(1, 0));
148 const float xz = 0.5f * (inertia(0, 2) + inertia(2, 0));
149 const float yz = 0.5f * (inertia(1, 2) + inertia(2, 1));
158void mergePhysicalProperties(
161 const float mergedMass = target.mass + source.mass;
162 const Vector3f mergedCenterOfMassOffset = mergedMass > 0.0f
163 ? (target.mass * target.centerOfMassOffset + source.mass * source.centerOfMassOffset) /
165 : target.centerOfMassOffset;
166 Matrix3f mergedInertia = inertiaShiftedToCenter(target, mergedCenterOfMassOffset) +
167 inertiaShiftedToCenter(source, mergedCenterOfMassOffset);
168 symmetrizeInPlace(mergedInertia);
170 target.mass = mergedMass;
171 target.centerOfMassOffset = mergedCenterOfMassOffset;
172 target.inertia = mergedInertia;
173 target.inertiaRotation = Quaternionf::Identity();
180 const std::vector<size_t>& jointMap,
184 result.reserve(physicalProperties.size());
185 std::vector<size_t> resultIndexByJoint(targetSkeleton.joints.size(),
kInvalidIndex);
187 for (
const auto& jointProperties : physicalProperties) {
188 const size_t oldJointIndex =
190 if (oldJointIndex ==
kInvalidIndex || oldJointIndex >= jointMap.size()) {
194 const size_t newJointIndex = jointMap[oldJointIndex];
195 if (newJointIndex ==
kInvalidIndex || newJointIndex >= targetSkeleton.joints.size()) {
201 mappedProperties.jointName = targetSkeleton.joints.at(newJointIndex).name;
203 const auto oldToNewLocal = targetBindState.jointState.at(newJointIndex).transform.inverse() *
204 sourceBindState.jointState.at(oldJointIndex).transform;
205 mappedProperties.centerOfMassOffset = oldToNewLocal * jointProperties.centerOfMassOffset;
206 mappedProperties.inertiaRotation =
207 (oldToNewLocal.rotation * jointProperties.inertiaRotation).normalized();
211 size_t& resultIndex = resultIndexByJoint.at(newJointIndex);
213 resultIndex = result.size();
214 result.push_back(std::move(mappedProperties));
216 mergePhysicalProperties(result.at(resultIndex), mappedProperties);
223std::unique_ptr<CollisionGeometry> remapCollisionGeometry(
225 const std::vector<size_t>& jointMap,
228 if (collision ==
nullptr) {
232 auto result = std::make_unique<CollisionGeometry>(*collision);
233 for (
auto& collisionGeometry : *result) {
234 const auto oldParent = collisionGeometry.parent;
235 collisionGeometry.parent = jointMap.at(collisionGeometry.parent);
238 collisionGeometry.transformation =
239 targetBindState.jointState.at(collisionGeometry.parent).transform.inverse() *
240 sourceBindState.jointState.at(oldParent).transform * collisionGeometry.transformation;
259 const std::string& nameIn,
262 std::string_view metadataIn,
276 mesh = std::make_unique<Mesh>(*m);
284 poseShapes = std::make_unique<PoseShape>(*bs);
288 initInverseBindPose();
293 collision = std::make_unique<CollisionGeometry>(*cg);
313 mesh = std::make_unique<Mesh>(*c.mesh);
316 skinWeights = std::make_unique<SkinWeights>(*c.skinWeights);
321 poseShapes = std::make_unique<PoseShape>(*c.poseShapes);
325 collision = std::make_unique<CollisionGeometry>(*c.collision);
329Character::Character(Character&& c)
noexcept =
default;
331Character::Character() =
default;
333Character::~Character() =
default;
362 const auto nJoints =
skeleton.joints.size();
363 std::vector<bool> result(nJoints,
false);
368 const auto& row = it.row();
369 const auto& col = it.col();
371 if (!parameterSet.test(col)) {
376 MT_CHECK(jointIndex < nJoints,
"{} vs {}", jointIndex, nJoints);
377 result[jointIndex] =
true;
386 activeJoints.size() ==
skeleton.joints.size(),
395 const auto globalParam = it.row();
396 const auto kParam = it.col();
404 if (activeJoints[jointIndex] != 0) {
405 result.set(kParam,
true);
415 activeJoints.size() ==
skeleton.joints.size(),
420 std::find(activeJoints.begin(), activeJoints.end(),
true) == activeJoints.end(),
421 "In simplifySkeleton, no joints are enabled; resulting skeleton must have at least one valid joint.");
450 for (
size_t aIndex = 0; aIndex <
skeleton.joints.size(); aIndex++) {
453 const auto placement = getSimplifiedJointPlacement(
skeleton, referenceState, lastJoint, aIndex);
455 if (activeJoints[aIndex]) {
456 simplifiedSkeleton.
joints.push_back(makeSimplifiedJoint(
skeleton, aIndex, placement));
457 const size_t newJointIndex = simplifiedSkeleton.
joints.size() - 1;
458 intermediateJointMap.at(aIndex) = newJointIndex;
459 lastJoint.at(aIndex) = newJointIndex;
460 simplifiedJointMap.at(aIndex) = newJointIndex;
465 simplifiedJointMap.at(aIndex) =
466 findSimplifiedAncestor(
skeleton, intermediateJointMap, aIndex);
470 simplifiedSkeleton.
joints.empty(),
471 "During skeleton simplification, resulting skeleton was empty. Simplified skeleton must have at least one valid joint.");
476 Character result(simplifiedSkeleton, simplifiedTransform);
480 result.
jointMap = simplifiedJointMap;
514 result.
mesh = std::make_unique<Mesh>(*
mesh);
523 remapCollisionGeometry(
collision.get(), result.
jointMap, sourceBindState, targetBindState);
530 parameterSet.count() > 0,
"No active parameters in the input to simplifyParameterTransform.");
532 auto [subsetParamTransform, subsetParamLimits] =
537 subsetParamTransform,
559 if (!activeJoints.empty()) {
560 activeJoints[0] =
true;
568 const Character& originalCharacter)
const {
583 for (
int v = 0; v < result.
index.rows(); v++) {
592 const auto& joint = result.
index(v, i);
593 for (
int j = i + 1; j < gsl::narrow_cast<int>(
kMaxSkinJoints); j++) {
594 if (result.
index(v, j) == joint) {
596 result.
weight(v, j) = 0.0f;
604 for (
int j = i + 1; j < gsl::narrow_cast<int>(
kMaxSkinJoints); j++) {
607 std::swap(result.
index(v, i), result.
index(v, j));
618 const Character& originalCharacter)
const {
639 for (
auto&& limit : result) {
642 auto& data = limit.data.minMaxJoint;
643 data.jointIndex =
jointMap[data.jointIndex];
646 auto& data = limit.data.ellipsoid;
647 const auto sourceParent = data.parent;
648 const auto targetParent =
jointMap[sourceParent];
650 targetParent < targetBindState.
jointState.size(),
654 data.parent = targetParent;
656 const auto targetTransformationInverse =
657 targetBindState.
jointState[targetParent].transform.inverse();
658 const auto sourceTransformation = sourceBindState.
jointState[sourceParent].transform;
659 data.offset = targetTransformationInverse * sourceTransformation * data.offset;
661 const auto sourceEllipsoidParent = data.ellipsoidParent;
662 data.ellipsoidParent =
jointMap[data.ellipsoidParent];
663 const auto targetEllipsoidInverse =
664 targetBindState.
jointState[data.ellipsoidParent].transform.inverse();
665 const auto sourceEllipsoid = sourceBindState.
jointState[sourceEllipsoidParent].transform;
666 data.ellipsoid = targetEllipsoidInverse * sourceEllipsoid * data.ellipsoid;
667 data.ellipsoidInv = data.ellipsoid.inverse();
676 const Character& originalCharacter)
const {
698 for (
auto& sl : result) {
701 sl.parents(i) =
static_cast<uint32_t
>(
jointMap[sl.parents(i)]);
707 const auto& joint = sl.parents(i);
708 for (
int j = i + 1; j < gsl::narrow_cast<int>(
kMaxSkinJoints); j++) {
709 if (sl.parents(j) == joint) {
710 sl.skinWeights(i) += sl.skinWeights(j);
711 sl.skinWeights(j) = 0.0f;
719 for (
int j = i + 1; j < gsl::narrow_cast<int>(
kMaxSkinJoints); j++) {
720 if (sl.skinWeights(i) < sl.skinWeights(j)) {
721 std::swap(sl.skinWeights(i), sl.skinWeights(j));
722 std::swap(sl.parents(i), sl.parents(j));
753 for (
const auto& sourceLocator : locs) {
754 result.emplace_back(sourceLocator);
755 auto& loc = result.back();
758 loc.offset = targetBindState.
jointState[loc.parent].transform.inverse() *
759 sourceBindState.
jointState[sourceLocator.parent].transform * sourceLocator.offset;
798 auto parameterSplit = parameters;
799 auto offsetSplit = parameters;
800 for (
int j = 0; j < offsetSplit.pose.size(); j++) {
801 if (parameterSet.test(j)) {
802 parameterSplit.pose[j] = 0.0f;
804 offsetSplit.pose[j] = 0.0f;
808 return parameterSplit;
813 Eigen::Index maxBlendShapes)
const {
821 Eigen::Index maxBlendShapes) {
823 if (!blendShape_in) {
833 blendShape_in->modelSize() == this->mesh->vertices.size(),
835 blendShape_in->modelSize(),
836 this->mesh->vertices.size());
847 Eigen::Index maxBlendShapes)
const {
855 Eigen::Index maxBlendShapes) {
858 if (!blendShape_in) {
866 blendShape_in->modelSize() ==
mesh->vertices.size(),
868 blendShape_in->modelSize(),
869 mesh->vertices.size());
873 auto nBlendShapes = blendShape_in->shapeSize();
874 if (maxBlendShapes > 0) {
875 nBlendShapes = std::min(maxBlendShapes, nBlendShapes);
887 result.
mesh->vertices = this->
blendShape->template computeShape<float>(blendWeights);
888 result.
mesh->updateNormals();
892 this->parameterTransform,
894 ~this->parameterTransform.getBlendShapeParameters());
912 result.
mesh->vertices = this->
blendShape->template computeShape<float>(blendWeights);
927 result.
mesh->updateNormals();
931 if (bakeBlendShapes) {
This file provides functions for applying blend shape deformations and skeletal transformations to ch...
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Functions for linear blend skinning (Skeletal Subspace Deformation).
Matrix3< float > Matrix3f
CollisionGeometryT< float > CollisionGeometry
SkeletonT< float > Skeleton
::std::shared_ptr< const BlendShapeBase > BlendShapeBase_const_p
std::tuple< ParameterTransformT< T >, ParameterLimits > subsetParameterTransform(const ParameterTransformT< T > ¶mTransformOld, const ParameterLimits ¶mLimitsOld, const ParameterSet ¶mSet)
Return a parameter mapping that only includes the listed parameters.
std::vector< Affine3f > TransformationList
One affine transform per joint, indexed by joint id.
std::vector< ParameterLimit > ParameterLimits
BlendWeightsT< float > BlendWeights
ParameterTransformT< float > ParameterTransform
std::tuple< ParameterTransform, ParameterLimits > addBlendShapeParameters(ParameterTransform paramTransform, ParameterLimits paramLimits, Eigen::Index nBlendShapes)
std::vector< JointPhysicalProperties > PhysicalProperties
Optional physical mass properties for a character.
SkeletonStateT< float > SkeletonState
std::vector< SkinnedLocator > SkinnedLocatorList
A collection of locators attached to a skeleton.
CharacterParametersT< float > CharacterParameters
constexpr size_t kParametersPerJoint
ModelParametersT< float > ModelParameters
std::vector< Vector3< T > > applySSD(const SkinWeights &skin, typename DeduceSpanType< const Vector3< T > >::type points, typename DeduceSpanType< const Eigen::Matrix4< T > >::type skinningTransforms)
Applies forward SSD (linear blend skinning) to points using precomputed skinning transforms.
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
size_t resolvePhysicalPropertiesJointIndex(const JointPhysicalProperties &properties, const Skeleton &skeleton)
Resolves physical mass properties to a skeleton joint.
Vector3< float > Vector3f
::std::shared_ptr< const BlendShape > BlendShape_const_p
constexpr uint32_t kMaxSkinJoints
Maximum number of joints that can influence a single vertex.
std::bitset< kMaxModelParams > ParameterSet
Bitset for model parameter enablement.
BlendWeightsT< T > extractBlendWeights(const ParameterTransform ¶mTransform, const ModelParametersT< T > &modelParams)
Extracts blend shape weights from model parameters.
std::tuple< ParameterTransform, ParameterLimits > addFaceExpressionParameters(ParameterTransform paramTransform, ParameterLimits paramLimits, Eigen::Index nFaceExpressionBlendShapes)
ParameterTransformT< T > mapParameterTransformJoints(const ParameterTransformT< T > ¶meterTransform, size_t numTargetJoints, const std::vector< size_t > &jointMapping)
Construct a new parameter transform where the joints have been mapped to a new skeleton.
std::vector< Locator > LocatorList
A collection of locators attached to a skeleton.
JointParametersT< T > offsets
The joint parameter vector representing the unique bone lengths of the character, defining the charac...
ModelParametersT< T > pose
The model parameter vector representing the pose of the character.
A character model with skeletal structure, mesh, and optional components.
void addFaceExpressionBlendShape(const BlendShapeBase_const_p &blendShape_in, Eigen::Index maxBlendShapes=-1)
Adds face expression blend shapes to this character.
ParameterLimits remapParameterLimits(const ParameterLimits &limits, const Character &originalCharacter) const
Remaps parameter limits from original character to simplified version.
SkinWeights remapSkinWeights(const SkinWeights &skinWeights, const Character &originalCharacter) const
Remaps skin weights from original character to simplified version.
std::vector< bool > parametersToActiveJoints(const ParameterSet ¶meterSet) const
Determines which joints are affected by the specified parameters.
TransformationList inverseBindPose
Inverse of the bind pose transformations for each joint.
Character bake(const ModelParameters &modelParams, bool bakeBlendShapes=true, bool bakeScales=true) const
Generic "bake-out" for turning a character into self-contained geometry.
LocatorList locators
Points of interest attached to joints.
SkinWeights_u skinWeights
Defines how mesh vertices are influenced by joints.
CharacterParameters bindPose() const
Returns parameters representing the character's bind pose.
void initInverseBindPose()
Initializes the inverse bind pose transformations.
static CharacterParameters splitParameters(const Character &character, const CharacterParameters ¶meters, const ParameterSet ¶meterSet)
Splits character parameters into active and inactive components.
void resetJointMap()
Resets the joint map to identity (each joint maps to itself).
PhysicalProperties physicalProperties
Joint-level physical mass and inertia data loaded from model assets.
Character simplifyParameterTransform(const ParameterSet ¶meterSet) const
Creates a simplified character with only the specified parameters.
BlendShapeBase_const_p faceExpressionBlendShape
Facial expression blend shapes.
ParameterLimits parameterLimits
Constraints on model parameters.
Mesh_u mesh
3D mesh representing the character's surface
PoseShape_u poseShapes
Pose-dependent shape corrections.
Character simplifySkeleton(const std::vector< bool > &activeJoints) const
Creates a simplified character with only the specified joints.
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
void addBlendShape(const BlendShape_const_p &blendShape_in, Eigen::Index maxBlendShapes)
Adds blend shapes to this character.
SkinnedLocatorList remapSkinnedLocators(const SkinnedLocatorList &locs, const Character &originalCharacter) const
std::string name
Character identifier.
Character withFaceExpressionBlendShape(const BlendShapeBase_const_p &blendShape_in, Eigen::Index maxBlendShapes=-1) const
Creates a new character with the specified face expression blend shapes.
Character & operator=(const Character &rhs)
Character withBlendShape(const BlendShape_const_p &blendShape_in, Eigen::Index maxBlendShapes) const
Creates a new character with the specified blend shapes.
SkinnedLocatorList skinnedLocators
Points of interest attached to joints, with skinning weights.
Character simplify(const ParameterSet &activeParams=ParameterSet().flip()) const
Creates a simplified character with only joints affected by the specified parameters.
ParameterTransform parameterTransform
Maps model parameters to joint parameters.
ParameterSet activeJointsToParameters(const std::vector< bool > &activeJoints) const
Determines which parameters affect the specified joints.
BlendShape_const_p blendShape
Shape variations that can be blended.
Character bakeBlendShape(const ModelParameters &modelParams) const
Creates a new character with blend shapes baked into the mesh.
std::vector< size_t > jointMap
Maps from original joint indices to simplified joint indices.
void initParameterTransform()
Initializes the parameter transform with the correct dimensions for this character.
LocatorList remapLocators(const LocatorList &locs, const Character &originalCharacter) const
Remaps locators from original character to simplified version.
std::string metadata
Metadata (as a JSON-serialized string).
CollisionGeometry_u collision
Collision volumes for the character.
static EIGEN_DEVICE_FUNC Derived< Scalar > Zero(::Eigen::Index size)
Physical mass properties attached to one skeleton joint.
size_t jointIndex
Cached joint index.
Computes shape deformations based on joint rotations.
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
Linear blend skinning weights for a character mesh: per-vertex joint indices and influence weights.
WeightMatrix weight
Joint influence weights per vertex.
IndexMatrix index
Joint indices influencing each vertex.