38 const auto w = skinWeights.weight(vertexIndex, k);
40 const auto joint = skinWeights.index(vertexIndex, k);
41 if (minSkinnedJoint ==
kInvalidIndex || joint < minSkinnedJoint) {
42 minSkinnedJoint = joint;
51 return skeleton.commonAncestor(minSkinnedJoint, sdfParent);
61 character_(character),
62 sdfCollider_(sdfCollider) {
63 MT_CHECK_NOTNULL(character_.mesh,
"Character must have a mesh for vertex SDF constraints");
65 character_.skinWeights,
"Character must have skin weights for vertex SDF constraints");
66 MT_CHECK(sdfCollider_.isValid(),
"SDF collider must be valid");
73 constraint.
vertexIndex <
static_cast<int>(character_.mesh->vertices.size()),
74 "Invalid vertex index: {} (mesh has {} vertices)",
76 character_.mesh->vertices.size());
77 constraints_.push_back(constraint);
92 return constraints_.size();
96TransformT<T> VertexSDFErrorFunctionT<T>::computeWorldToSDFTransform(
100 const size_t parentJoint = sdfCollider_.parent;
101 MT_CHECK(parentJoint < state.
jointState.size(),
"Invalid parent joint index: {}", parentJoint);
102 parentTransform = state.
jointState[parentJoint].transform;
105 auto sdfWorldTransform = parentTransform * sdfCollider_.transformation.
cast<T>();
106 return sdfWorldTransform.inverse();
110T VertexSDFErrorFunctionT<T>::sampleSDFDistanceWithTransform(
111 const Eigen::Vector3<T>& worldPos,
113 const Vector3<T> sdfLocalPos = worldToSdfTransform * worldPos;
114 const float distance = sdfCollider_.sdf->sample(sdfLocalPos);
115 return static_cast<T
>(distance);
119std::pair<T, Eigen::Vector3<T>>
120VertexSDFErrorFunctionT<T>::sampleSDFDistanceAndGradientWithTransform(
121 const Eigen::Vector3<T>& worldPos,
124 const Vector3<T> sdfLocalPos = worldToSdfTransform * worldPos;
125 const auto [localDistance, localGradient] = sdfCollider_.sdf->sampleWithGradient(sdfLocalPos);
127 const T distance =
static_cast<T
>(localDistance);
129 const Eigen::Vector3<T> worldGradient =
130 sdfToWorldTransform.rotation * localGradient.template
cast<T>();
132 return std::make_pair(distance, worldGradient);
136void VertexSDFErrorFunctionT<T>::accumulateJointGradient(
139 const Eigen::Vector3<T>& posd,
140 const Eigen::Vector3<T>& direction,
141 Eigen::Ref<Eigen::VectorX<T>> gradient)
const {
142 for (
size_t d = 0; d < 3; d++) {
143 if (this->activeJointParams_[paramIndex + d]) {
145 direction.dot(jointState.getTranslationDerivative(d)),
147 this->parameterTransform_,
150 if (this->activeJointParams_[paramIndex + 3 + d]) {
152 direction.dot(jointState.getRotationDerivative(d, posd)),
154 this->parameterTransform_,
158 if (this->activeJointParams_[paramIndex + 6]) {
160 direction.dot(jointState.getScaleDerivative(posd)),
162 this->parameterTransform_,
168void VertexSDFErrorFunctionT<T>::accumulateJointJacobian(
171 const Eigen::Vector3<T>& posd,
172 const Eigen::Vector3<T>& direction,
173 Eigen::Ref<Eigen::MatrixX<T>> jacobianRow)
const {
174 for (
size_t d = 0; d < 3; d++) {
175 if (this->activeJointParams_[paramIndex + d]) {
177 direction.dot(jointState.getTranslationDerivative(d)),
179 this->parameterTransform_,
182 if (this->activeJointParams_[paramIndex + 3 + d]) {
184 direction.dot(jointState.getRotationDerivative(d, posd)),
186 this->parameterTransform_,
190 if (this->activeJointParams_[paramIndex + 6]) {
192 direction.dot(jointState.getScaleDerivative(posd)),
194 this->parameterTransform_,
200void VertexSDFErrorFunctionT<T>::accumulateColliderHierarchyGradient(
202 size_t colliderParent,
203 size_t commonAncestor,
204 const Eigen::Vector3<T>& sdfSurfacePoint,
205 const Eigen::Vector3<T>& direction,
206 Eigen::Ref<Eigen::VectorX<T>> gradient)
const {
207 size_t jointIndex = colliderParent;
208 while (jointIndex !=
kInvalidIndex && jointIndex != commonAncestor) {
209 const auto& jointState = state.jointState[jointIndex];
211 const Eigen::Vector3<T> posd = sdfSurfacePoint - jointState.translation();
215 jointIndex = this->skeleton_.joints[jointIndex].parent;
220void VertexSDFErrorFunctionT<T>::accumulateColliderHierarchyJacobian(
222 size_t colliderParent,
223 size_t commonAncestor,
224 const Eigen::Vector3<T>& sdfSurfacePoint,
225 const Eigen::Vector3<T>& direction,
226 Eigen::Ref<Eigen::MatrixX<T>> jacobianRow)
const {
227 size_t jointIndex = colliderParent;
228 while (jointIndex !=
kInvalidIndex && jointIndex != commonAncestor) {
229 const auto& jointState = state.jointState[jointIndex];
231 const Eigen::Vector3<T> posd = sdfSurfacePoint - jointState.translation();
235 jointIndex = this->skeleton_.joints[jointIndex].parent;
248 double totalError = 0.0;
250 if (constraints_.empty()) {
254 const auto worldToSdfTransform = computeWorldToSDFTransform(state);
256 for (
const auto& constraint : constraints_) {
257 const auto& worldPos = meshState.
posedMesh_->vertices[constraint.vertexIndex];
258 const T distance = sampleSDFDistanceWithTransform(worldPos, worldToSdfTransform);
259 const T distErr = distance - constraint.targetDistance;
261 totalError +=
static_cast<double>(
273 Eigen::Ref<Eigen::VectorX<T>> gradient) {
279 double totalError = 0.0;
281 if (constraints_.empty()) {
285 const auto worldToSdfTransform = computeWorldToSDFTransform(state);
286 const auto sdfToWorldTransform = worldToSdfTransform.inverse();
288 for (
const auto& constraint : constraints_) {
289 const auto& worldPos = meshState.
posedMesh_->vertices[constraint.vertexIndex];
290 const auto [distance, sdfGradient] = sampleSDFDistanceAndGradientWithTransform(
291 worldPos, worldToSdfTransform, sdfToWorldTransform);
293 const T distErr = distance - constraint.targetDistance;
295 totalError +=
static_cast<double>(
301 const Eigen::Vector3<T> diff = distErr * sdfGradient;
304 const Eigen::Vector3<T> sdfSurfacePoint = worldPos - distErr * sdfGradient;
306 const size_t commonAncestor = findCommonAncestorForVertex(
307 *character_.skinWeights, this->skeleton_, constraint.vertexIndex, sdfCollider_.parent);
311 character_, *meshState.
restMesh_, state, constraint.vertexIndex);
313 const auto [jointIndex, boneWeight, transformedVertex] = skinningIter.
next();
315 if (jointIndex == commonAncestor) {
319 if (std::abs(boneWeight) < std::numeric_limits<T>::epsilon()) {
325 const auto& jointState = state.
jointState[jointIndex];
327 const Eigen::Vector3<T> posd = transformedVertex - jointState.translation();
329 accumulateJointGradient(jointState, paramIndex, posd, boneWeight * wgt * diff, gradient);
334 accumulateColliderHierarchyGradient(
335 state, sdfCollider_.parent, commonAncestor, sdfSurfacePoint, -wgt * diff, gradient);
347 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
348 Eigen::Ref<Eigen::VectorX<T>> residual,
353 jacobian.cols() ==
static_cast<Eigen::Index
>(this->parameterTransform_.transform.cols()),
354 "Jacobian column count mismatch");
359 double totalError = 0.0;
362 if (constraints_.empty()) {
367 const auto worldToSdfTransform = computeWorldToSDFTransform(state);
368 const auto sdfToWorldTransform = worldToSdfTransform.inverse();
370 for (
const auto& constraint : constraints_) {
371 const auto& worldPos = meshState.
posedMesh_->vertices[constraint.vertexIndex];
372 const auto [distance, sdfGradient] = sampleSDFDistanceAndGradientWithTransform(
373 worldPos, worldToSdfTransform, sdfToWorldTransform);
375 const T distErr = distance - constraint.targetDistance;
378 currentRow < jacobian.rows() && currentRow < residual.rows(),
379 "Insufficient Jacobian/residual rows: need {}, have jacobian: {}, residual: {}",
384 const T wgt = std::sqrt(constraint.weight *
kVertexSDFWeight * this->weight_);
385 residual[currentRow] = wgt * distErr;
387 totalError +=
static_cast<double>(
390 jacobian.row(currentRow).setZero();
393 const Eigen::Vector3<T> worldJacobianContribution = wgt * sdfGradient;
396 const Eigen::Vector3<T> sdfSurfacePoint = worldPos - distErr * sdfGradient;
398 const size_t commonAncestor = findCommonAncestorForVertex(
399 *character_.skinWeights, this->skeleton_, constraint.vertexIndex, sdfCollider_.parent);
403 character_, *meshState.
restMesh_, state, constraint.vertexIndex);
405 const auto [jointIndex, boneWeight, transformedVertex] = skinningIter.
next();
407 if (jointIndex == commonAncestor) {
411 if (std::abs(boneWeight) < std::numeric_limits<T>::epsilon()) {
417 const auto& jointState = state.
jointState[jointIndex];
419 const Eigen::Vector3<T> posd = transformedVertex - jointState.translation();
421 accumulateJointJacobian(
425 boneWeight * worldJacobianContribution,
426 jacobian.middleRows(currentRow, 1));
431 accumulateColliderHierarchyJacobian(
436 -worldJacobianContribution,
437 jacobian.middleRows(currentRow, 1));
443 usedRows = currentRow;
449 return constraints_.size();
#define MT_CHECK_NOTNULL(ptr,...)
Asserts that ptr is not null; on failure, throws std::runtime_error with the optional fmt-style messa...
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
const Skeleton & skeleton_
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
std::tuple< size_t, T, Eigen::Vector3< T > > next()
Error function that penalizes deviation of mesh vertex SDF distance from a target value.
static constexpr T kVertexSDFWeight
Weight constant for vertex SDF penalties.
VertexSDFErrorFunctionT(const Character &character, const SDFColliderT< float > &sdfCollider)
Constructor.
size_t getJacobianSize() const override
Returns the maximum number of Jacobian rows needed.
void clearConstraints()
Clear all constraints.
size_t getNumConstraints() const
Returns the number of constraints.
void addConstraint(const VertexSDFConstraintT< T > &constraint)
Add a constraint specifying a target distance for a vertex.
double getError(const ModelParametersT< T > ¶ms, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) override
Computes the error for the given model parameters and skeleton state.
double getGradient(const ModelParametersT< T > ¶ms, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::VectorX< T > > gradient) override
Computes the error and its gradient.
double getJacobian(const ModelParametersT< T > ¶ms, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::MatrixX< T > > jacobian, Eigen::Ref< Eigen::VectorX< T > > residual, int &usedRows) override
Computes the Jacobian and residual.
const std::vector< VertexSDFConstraintT< T > > & getConstraints() const
Returns the current constraints.
void accumulateJointJacobian(const JointStateT< T > &jointState, size_t paramIndex, const Eigen::Vector3< T > &posd, const Eigen::Vector3< T > &direction, const VectorX< bool > &activeJointParams, const ParameterTransform ¶meterTransform, Eigen::Ref< Eigen::MatrixX< T > > jacobianRow)
Accumulates the Jacobian contribution of a single joint onto one residual row.
void accumulateJointGradient(const JointStateT< T > &jointState, size_t paramIndex, const Eigen::Vector3< T > &posd, const Eigen::Vector3< T > &direction, const VectorX< bool > &activeJointParams, const ParameterTransform ¶meterTransform, Eigen::Ref< Eigen::VectorX< T > > gradient)
Accumulates the gradient contribution of a single joint onto the model-parameter gradient.
size_t findCommonAncestorForVertex(const SkinWeights &skinWeights, const Skeleton &skeleton, size_t vertexIndex, size_t sdfParent)
Shared, stateless helpers for SDF-collision error functions.
SkeletonT< float > Skeleton
void jacobian_jointParams_to_modelParams(const Eigen::Ref< const Eigen::VectorX< T > > &jacobian_jointParams, const Eigen::Index iJointParam, const ParameterTransform ¶meterTransform, Eigen::Ref< Eigen::MatrixX< T > > jacobian)
void gradient_jointParams_to_modelParams(const T &grad_jointParams, const Eigen::Index iJointParam, const ParameterTransform ¶meterTransform, Eigen::Ref< Eigen::VectorX< T > > gradient)
constexpr size_t kParametersPerJoint
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
constexpr uint32_t kMaxSkinJoints
Maximum number of joints that can influence a single vertex.
decltype(auto) cast(const ContainerType< ObjectType > &originalContainer)
Casts the scalar type of objects in a container that support the cast<>() method.
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_FUNCTION()
A character model with skeletal structure, mesh, and optional components.
Represents the state of a joint with local and global transformations.
Represents the complete state of a model's mesh.
std::unique_ptr< MeshT< T > > posedMesh_
Posed mesh after the skeleton transforms have been applied.
std::unique_ptr< MeshT< T > > restMesh_
Rest positions of the mesh after the shape basis (and potentially facial expression basis) has been a...
A vector of size numModelParams holding the values of all model parameters for a character.
SDF collision geometry for character collision detection.
Represents the complete state of a skeleton.
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.
Linear blend skinning weights for a character mesh: per-vertex joint indices and influence weights.
Constraint specifying that a vertex should be at a target signed distance from the SDF.
int vertexIndex
Mesh vertex index.