Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
vertex_sdf_error_function.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
9
19#include "momentum/math/mesh.h"
21
22namespace momentum {
23
24namespace {
25
27inline size_t findCommonAncestorForVertex(
28 const SkinWeights& skinWeights,
29 const Skeleton& skeleton,
30 size_t vertexIndex,
31 size_t sdfParent) {
32 if (sdfParent == kInvalidIndex) {
33 return kInvalidIndex;
34 }
35
36 size_t minSkinnedJoint = kInvalidIndex;
37 for (uint32_t k = 0; k < kMaxSkinJoints; ++k) {
38 const auto w = skinWeights.weight(vertexIndex, k);
39 if (w > 0) {
40 const auto joint = skinWeights.index(vertexIndex, k);
41 if (minSkinnedJoint == kInvalidIndex || joint < minSkinnedJoint) {
42 minSkinnedJoint = joint;
43 }
44 }
45 }
46
47 if (minSkinnedJoint == kInvalidIndex) {
48 return kInvalidIndex;
49 }
50
51 return skeleton.commonAncestor(minSkinnedJoint, sdfParent);
52}
53
54} // namespace
55
56template <typename T>
58 const Character& character,
59 const SDFColliderT<float>& sdfCollider)
60 : SkeletonErrorFunctionT<T>(character.skeleton, character.parameterTransform),
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");
67}
68
69template <typename T>
72 constraint.vertexIndex >= 0 &&
73 constraint.vertexIndex < static_cast<int>(character_.mesh->vertices.size()),
74 "Invalid vertex index: {} (mesh has {} vertices)",
75 constraint.vertexIndex,
76 character_.mesh->vertices.size());
77 constraints_.push_back(constraint);
78}
79
80template <typename T>
82 constraints_.clear();
83}
84
85template <typename T>
86const std::vector<VertexSDFConstraintT<T>>& VertexSDFErrorFunctionT<T>::getConstraints() const {
87 return constraints_;
88}
89
90template <typename T>
92 return constraints_.size();
93}
94
95template <typename T>
96TransformT<T> VertexSDFErrorFunctionT<T>::computeWorldToSDFTransform(
97 const SkeletonStateT<T>& state) const {
98 TransformT<T> parentTransform;
99 if (sdfCollider_.parent != kInvalidIndex) {
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;
103 }
104
105 auto sdfWorldTransform = parentTransform * sdfCollider_.transformation.cast<T>();
106 return sdfWorldTransform.inverse();
107}
108
109template <typename T>
110T VertexSDFErrorFunctionT<T>::sampleSDFDistanceWithTransform(
111 const Eigen::Vector3<T>& worldPos,
112 const TransformT<T>& worldToSdfTransform) const {
113 const Vector3<T> sdfLocalPos = worldToSdfTransform * worldPos;
114 const float distance = sdfCollider_.sdf->sample(sdfLocalPos);
115 return static_cast<T>(distance);
116}
117
118template <typename T>
119std::pair<T, Eigen::Vector3<T>>
120VertexSDFErrorFunctionT<T>::sampleSDFDistanceAndGradientWithTransform(
121 const Eigen::Vector3<T>& worldPos,
122 const TransformT<T>& worldToSdfTransform,
123 const TransformT<T>& sdfToWorldTransform) const {
124 const Vector3<T> sdfLocalPos = worldToSdfTransform * worldPos;
125 const auto [localDistance, localGradient] = sdfCollider_.sdf->sampleWithGradient(sdfLocalPos);
126
127 const T distance = static_cast<T>(localDistance);
128
129 const Eigen::Vector3<T> worldGradient =
130 sdfToWorldTransform.rotation * localGradient.template cast<T>();
131
132 return std::make_pair(distance, worldGradient);
133}
134
135template <typename T>
136void VertexSDFErrorFunctionT<T>::accumulateJointGradient(
137 const JointStateT<T>& jointState,
138 size_t paramIndex,
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)),
146 paramIndex + d,
147 this->parameterTransform_,
148 gradient);
149 }
150 if (this->activeJointParams_[paramIndex + 3 + d]) {
152 direction.dot(jointState.getRotationDerivative(d, posd)),
153 paramIndex + 3 + d,
154 this->parameterTransform_,
155 gradient);
156 }
157 }
158 if (this->activeJointParams_[paramIndex + 6]) {
160 direction.dot(jointState.getScaleDerivative(posd)),
161 paramIndex + 6,
162 this->parameterTransform_,
163 gradient);
164 }
165}
166
167template <typename T>
168void VertexSDFErrorFunctionT<T>::accumulateJointJacobian(
169 const JointStateT<T>& jointState,
170 size_t paramIndex,
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)),
178 paramIndex + d,
179 this->parameterTransform_,
180 jacobianRow);
181 }
182 if (this->activeJointParams_[paramIndex + 3 + d]) {
184 direction.dot(jointState.getRotationDerivative(d, posd)),
185 paramIndex + 3 + d,
186 this->parameterTransform_,
187 jacobianRow);
188 }
189 }
190 if (this->activeJointParams_[paramIndex + 6]) {
192 direction.dot(jointState.getScaleDerivative(posd)),
193 paramIndex + 6,
194 this->parameterTransform_,
195 jacobianRow);
196 }
197}
198
199template <typename T>
200void VertexSDFErrorFunctionT<T>::accumulateColliderHierarchyGradient(
201 const SkeletonStateT<T>& state,
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];
210 const size_t paramIndex = jointIndex * kParametersPerJoint;
211 const Eigen::Vector3<T> posd = sdfSurfacePoint - jointState.translation();
212
213 accumulateJointGradient(jointState, paramIndex, posd, direction, gradient);
214
215 jointIndex = this->skeleton_.joints[jointIndex].parent;
216 }
217}
218
219template <typename T>
220void VertexSDFErrorFunctionT<T>::accumulateColliderHierarchyJacobian(
221 const SkeletonStateT<T>& state,
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];
230 const size_t paramIndex = jointIndex * kParametersPerJoint;
231 const Eigen::Vector3<T> posd = sdfSurfacePoint - jointState.translation();
232
233 accumulateJointJacobian(jointState, paramIndex, posd, direction, jacobianRow);
234
235 jointIndex = this->skeleton_.joints[jointIndex].parent;
236 }
237}
238
239template <typename T>
241 const ModelParametersT<T>& /* params */,
242 const SkeletonStateT<T>& state,
243 const MeshStateT<T>& meshState) {
245
246 MT_CHECK_NOTNULL(meshState.posedMesh_);
247
248 double totalError = 0.0;
249
250 if (constraints_.empty()) {
251 return totalError;
252 }
253
254 const auto worldToSdfTransform = computeWorldToSDFTransform(state);
255
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;
260
261 totalError += static_cast<double>(
262 constraint.weight * distErr * distErr * kVertexSDFWeight * this->weight_);
263 }
264
265 return totalError;
266}
267
268template <typename T>
270 const ModelParametersT<T>& /* params */,
271 const SkeletonStateT<T>& state,
272 const MeshStateT<T>& meshState,
273 Eigen::Ref<Eigen::VectorX<T>> gradient) {
275
276 MT_CHECK_NOTNULL(meshState.posedMesh_);
277 MT_CHECK_NOTNULL(meshState.restMesh_);
278
279 double totalError = 0.0;
280
281 if (constraints_.empty()) {
282 return totalError;
283 }
284
285 const auto worldToSdfTransform = computeWorldToSDFTransform(state);
286 const auto sdfToWorldTransform = worldToSdfTransform.inverse();
287
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);
292
293 const T distErr = distance - constraint.targetDistance;
294
295 totalError += static_cast<double>(
296 constraint.weight * distErr * distErr * kVertexSDFWeight * this->weight_);
297
298 // de/d(distance) = 2 * constraintWeight * kVertexSDFWeight * weight_ * distErr
299 // de/d(worldPos) = de/d(distance) * sdfGradient
300 const T wgt = constraint.weight * 2.0f * kVertexSDFWeight * this->weight_;
301 const Eigen::Vector3<T> diff = distErr * sdfGradient;
302
303 // Compute the closest point on the target isosurface (lever arm for collider side)
304 const Eigen::Vector3<T> sdfSurfacePoint = worldPos - distErr * sdfGradient;
305
306 const size_t commonAncestor = findCommonAncestorForVertex(
307 *character_.skinWeights, this->skeleton_, constraint.vertexIndex, sdfCollider_.parent);
308
309 // Process mesh vertex (skinning weights)
310 SkinningWeightIteratorT<T> skinningIter(
311 character_, *meshState.restMesh_, state, constraint.vertexIndex);
312 while (!skinningIter.finished()) {
313 const auto [jointIndex, boneWeight, transformedVertex] = skinningIter.next();
314
315 if (jointIndex == commonAncestor) {
316 break;
317 }
318
319 if (std::abs(boneWeight) < std::numeric_limits<T>::epsilon()) {
320 continue;
321 }
322
323 MT_CHECK(jointIndex < this->skeleton_.joints.size());
324
325 const auto& jointState = state.jointState[jointIndex];
326 const size_t paramIndex = jointIndex * kParametersPerJoint;
327 const Eigen::Vector3<T> posd = transformedVertex - jointState.translation();
328
329 accumulateJointGradient(jointState, paramIndex, posd, boneWeight * wgt * diff, gradient);
330 }
331
332 // Process collider hierarchy (walk up from collider parent)
333 if (sdfCollider_.parent != kInvalidIndex) {
334 accumulateColliderHierarchyGradient(
335 state, sdfCollider_.parent, commonAncestor, sdfSurfacePoint, -wgt * diff, gradient);
336 }
337 }
338
339 return totalError;
340}
341
342template <typename T>
344 const ModelParametersT<T>& /* params */,
345 const SkeletonStateT<T>& state,
346 const MeshStateT<T>& meshState,
347 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
348 Eigen::Ref<Eigen::VectorX<T>> residual,
349 int& usedRows) {
351
352 MT_CHECK(
353 jacobian.cols() == static_cast<Eigen::Index>(this->parameterTransform_.transform.cols()),
354 "Jacobian column count mismatch");
355
356 MT_CHECK_NOTNULL(meshState.posedMesh_);
357 MT_CHECK_NOTNULL(meshState.restMesh_);
358
359 double totalError = 0.0;
360 int currentRow = 0;
361
362 if (constraints_.empty()) {
363 usedRows = 0;
364 return totalError;
365 }
366
367 const auto worldToSdfTransform = computeWorldToSDFTransform(state);
368 const auto sdfToWorldTransform = worldToSdfTransform.inverse();
369
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);
374
375 const T distErr = distance - constraint.targetDistance;
376
377 MT_CHECK(
378 currentRow < jacobian.rows() && currentRow < residual.rows(),
379 "Insufficient Jacobian/residual rows: need {}, have jacobian: {}, residual: {}",
380 currentRow + 1,
381 jacobian.rows(),
382 residual.rows());
383
384 const T wgt = std::sqrt(constraint.weight * kVertexSDFWeight * this->weight_);
385 residual[currentRow] = wgt * distErr;
386
387 totalError += static_cast<double>(
388 constraint.weight * distErr * distErr * kVertexSDFWeight * this->weight_);
389
390 jacobian.row(currentRow).setZero();
391
392 // dr/d(worldPos) = wgt * sdfGradient
393 const Eigen::Vector3<T> worldJacobianContribution = wgt * sdfGradient;
394
395 // Compute the closest point on the target isosurface (lever arm for collider side)
396 const Eigen::Vector3<T> sdfSurfacePoint = worldPos - distErr * sdfGradient;
397
398 const size_t commonAncestor = findCommonAncestorForVertex(
399 *character_.skinWeights, this->skeleton_, constraint.vertexIndex, sdfCollider_.parent);
400
401 // Process mesh vertex (skinning weights)
402 SkinningWeightIteratorT<T> skinningIter(
403 character_, *meshState.restMesh_, state, constraint.vertexIndex);
404 while (!skinningIter.finished()) {
405 const auto [jointIndex, boneWeight, transformedVertex] = skinningIter.next();
406
407 if (jointIndex == commonAncestor) {
408 break;
409 }
410
411 if (std::abs(boneWeight) < std::numeric_limits<T>::epsilon()) {
412 continue;
413 }
414
415 MT_CHECK(jointIndex < this->skeleton_.joints.size());
416
417 const auto& jointState = state.jointState[jointIndex];
418 const size_t paramIndex = jointIndex * kParametersPerJoint;
419 const Eigen::Vector3<T> posd = transformedVertex - jointState.translation();
420
421 accumulateJointJacobian(
422 jointState,
423 paramIndex,
424 posd,
425 boneWeight * worldJacobianContribution,
426 jacobian.middleRows(currentRow, 1));
427 }
428
429 // Process collider hierarchy (walk up from collider parent)
430 if (sdfCollider_.parent != kInvalidIndex) {
431 accumulateColliderHierarchyJacobian(
432 state,
433 sdfCollider_.parent,
434 commonAncestor,
435 sdfSurfacePoint,
436 -worldJacobianContribution,
437 jacobian.middleRows(currentRow, 1));
438 }
439
440 currentRow++;
441 }
442
443 usedRows = currentRow;
444 return totalError;
445}
446
447template <typename T>
449 return constraints_.size();
450}
451
452// Explicit template instantiations
453template class VertexSDFErrorFunctionT<float>;
455
456} // namespace momentum
#define MT_CHECK_NOTNULL(ptr,...)
Asserts that ptr is not null; on failure, throws std::runtime_error with the optional fmt-style messa...
Definition checks.h:45
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
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 > &params, 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 > &params, 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 > &params, 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 &parameterTransform, 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 &parameterTransform, 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
Definition fwd.h:263
void jacobian_jointParams_to_modelParams(const Eigen::Ref< const Eigen::VectorX< T > > &jacobian_jointParams, const Eigen::Index iJointParam, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::MatrixX< T > > jacobian)
void gradient_jointParams_to_modelParams(const T &grad_jointParams, const Eigen::Index iJointParam, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::VectorX< T > > gradient)
constexpr size_t kParametersPerJoint
Definition types.h:21
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
Vector< T, 3 > Vector3
Definition types.h:236
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.
Definition types.h:466
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
Represents the state of a joint with local and global transformations.
Definition joint_state.h:50
Represents the complete state of a model's mesh.
Definition mesh_state.h:24
std::unique_ptr< MeshT< T > > posedMesh_
Posed mesh after the skeleton transforms have been applied.
Definition mesh_state.h:32
std::unique_ptr< MeshT< T > > restMesh_
Rest positions of the mesh after the shape basis (and potentially facial expression basis) has been a...
Definition mesh_state.h:30
A vector of size numModelParams holding the values of all model parameters for a character.
Definition types.h:99
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.
Lightweight transform with separate rotation, translation, and uniform scaling.
Definition transform.h:36
TransformT< T2 > cast() const
Definition transform.h:206
Constraint specifying that a vertex should be at a target signed distance from the SDF.