Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
collision_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
15#include "momentum/common/log.h"
19
20namespace momentum {
21
22template <typename T>
24 const Skeleton& skel,
25 const ParameterTransform& pt,
26 const CollisionGeometry& cg,
27 bool filterRestPoseOverlaps)
28 : SkeletonErrorFunctionT<T>(skel, pt), collisionGeometry_(cg) {
29 updateCollisionPairs(filterRestPoseOverlaps);
30}
31
32template <typename T>
34 const Character& character,
35 bool filterRestPoseOverlaps)
37 character.skeleton,
38 character.parameterTransform,
39 character.collision
40 ? *character.collision
41 : throw std::invalid_argument(
42 "Attempting to create collision error function with a character that has no collision geometries"),
43 filterRestPoseOverlaps) {
44 // Do nothing
45}
46
47template <typename T>
48void CollisionErrorFunctionT<T>::updateCollisionPairs(bool filterRestPoseOverlaps) {
49 validPairs_.clear();
50
51 const SkeletonStateT<T> state(
52 this->parameterTransform_.zero().template cast<T>(), this->skeleton_);
54
55 const auto n = collisionGeometry_.size();
56
57 aabbs_.resize(n);
58 for (size_t i = 0; i < n; ++i) {
59 aabbs_[i].id = gsl::narrow_cast<axel::Index>(i);
61 }
62
63 if (n == 0) {
64 return;
65 }
66
67 for (size_t i = 0; i < n; ++i) {
68 for (size_t j = i + 1; j < n; ++j) {
70 collisionState_, collisionGeometry_, this->skeleton_, i, j, filterRestPoseOverlaps)) {
71 const size_t lca = this->skeleton_.commonAncestor(
72 collisionGeometry_[i].parent, collisionGeometry_[j].parent);
73 validPairs_.push_back({i, j, lca});
74 }
75 }
76 }
77}
78
79template <typename T>
81 {
82 MT_PROFILE_EVENT("Collision: updateState");
84 }
85
86 for (size_t i = 0; i < aabbs_.size(); ++i) {
88 }
89}
90
91template <typename T>
93 const CollisionGeometryStateT<T>& colState,
94 size_t indexA,
95 size_t indexB,
96 CollisionOverlapResultT<T>& result) const {
97 if (!aabbs_[indexA].intersects(aabbs_[indexB])) {
98 return false;
99 }
100 return overlaps(colState, collisionGeometry_, indexA, indexB, result);
101}
102
103template <typename T>
105 const SkeletonStateT<T>& state,
106 const Vector3<T>& position,
107 const Vector3<T>& direction,
108 T weight,
109 size_t startJoint,
110 size_t stopJoint,
111 Ref<VectorX<T>> gradient,
112 T scaleCorrection) const {
114 state,
115 this->skeleton_,
116 this->activeJointParams_,
117 position,
118 direction,
119 weight,
120 startJoint,
121 stopJoint,
122 scaleCorrection,
123 [&](T value, size_t jointParamIndex) {
125 value, jointParamIndex, this->parameterTransform_, gradient);
126 });
127}
128
129template <typename T>
131 const SkeletonStateT<T>& state,
132 const Vector3<T>& position,
133 const Vector3<T>& direction,
134 T factor,
135 size_t startJoint,
136 size_t stopJoint,
137 Ref<MatrixX<T>> jacobian,
138 int row,
139 T scaleCorrection) const {
141 state,
142 this->skeleton_,
143 this->activeJointParams_,
144 position,
145 direction,
146 factor,
147 startJoint,
148 stopJoint,
149 scaleCorrection,
150 [&](T value, size_t jointParamIndex) {
152 value, jointParamIndex, row, this->parameterTransform_, jacobian);
153 });
154}
155
156template <typename T>
158 std::vector<Vector2i> collidingPairs;
159 for (const auto& pair : validPairs_) {
161 if (checkCollision(collisionState_, pair.indexA, pair.indexB, result)) {
162 collidingPairs.emplace_back(static_cast<int>(pair.indexA), static_cast<int>(pair.indexB));
163 }
164 }
165 return collidingPairs;
166}
167
168template <typename T>
170 const ModelParametersT<T>& /* params */,
171 const SkeletonStateT<T>& state,
172 const MeshStateT<T>& /* meshState */) {
173 if (state.jointState.empty()) {
174 return 0.0;
175 }
176
177 MT_CHECK(
178 state.jointParameters.size() ==
179 gsl::narrow<Eigen::Index>(this->skeleton_.joints.size() * kParametersPerJoint));
180
181 computeBroadPhase(state);
182
183 double error = 0;
184 size_t collidingCount = 0;
185 for (const auto& pair : validPairs_) {
187 if (!checkCollision(collisionState_, pair.indexA, pair.indexB, result)) {
188 continue;
189 }
190 collidingCount++;
191 error += sqr(result.overlap) * kCollisionWeight * this->weight_;
192 }
193
194 MT_LOGD(
195 "CollisionError: {} colliding / {} valid pairs, error={:.8f}, weight={:.4f}",
196 collidingCount,
197 validPairs_.size(),
198 error,
199 this->weight_);
200
201 return error;
202}
203
204template <typename T>
206 const ModelParametersT<T>& /* params */,
207 const SkeletonStateT<T>& state,
208 const MeshStateT<T>& /* meshState */,
209 Ref<VectorX<T>> gradient) {
210 if (state.jointState.empty()) {
211 return 0.0;
212 }
213
214 MT_CHECK(
215 state.jointParameters.size() ==
216 gsl::narrow<Eigen::Index>(this->skeleton_.joints.size() * kParametersPerJoint));
217
218 computeBroadPhase(state);
219
220 double error = 0;
221 for (const auto& pair : validPairs_) {
223 if (!checkCollision(collisionState_, pair.indexA, pair.indexB, result)) {
224 continue;
225 }
226
227 error += sqr(result.overlap) * kCollisionWeight * this->weight_;
228
229 const Vector3<T> direction = result.positionA - result.positionB;
230 const T wgt = -T(2) * kCollisionWeight * this->weight_ * (result.overlap / result.distance);
231
233 state,
234 result.positionA,
235 direction,
236 wgt,
237 collisionGeometry_[pair.indexA].parent,
238 pair.commonAncestor,
239 gradient,
240 -result.distance * result.radiusA * ln2<T>());
242 state,
243 result.positionB,
244 direction,
245 -wgt,
246 collisionGeometry_[pair.indexB].parent,
247 pair.commonAncestor,
248 gradient,
249 result.distance * result.radiusB * ln2<T>());
250
251 // Scale derivatives above the common ancestor: translation and rotation derivatives cancel
252 // above the LCA (both capsule endpoints move identically), but scale derivatives do not
253 // because the two endpoints are at different distances from the scaled joint, and scaling
254 // also changes capsule radii.
255 {
256 const T netScaleVal =
257 (direction.squaredNorm() - result.distance * (result.radiusA + result.radiusB)) *
258 ln2<T>() * wgt;
259 size_t ancestorIndex = pair.commonAncestor;
260 while (ancestorIndex != kInvalidIndex) {
261 const size_t paramIndex = ancestorIndex * kParametersPerJoint;
262 if (this->activeJointParams_[paramIndex + 6]) {
264 netScaleVal, paramIndex + 6, this->parameterTransform_, gradient);
265 }
266 ancestorIndex = this->skeleton_.joints[ancestorIndex].parent;
267 }
268 }
269 }
270
271 return error;
272}
273
274template <typename T>
276 const ModelParametersT<T>& /* params */,
277 const SkeletonStateT<T>& state,
278 const MeshStateT<T>& /* meshState */,
279 Ref<MatrixX<T>> jacobian,
280 Ref<VectorX<T>> residual,
281 int& usedRows) {
283 MT_CHECK(
284 jacobian.rows() >= gsl::narrow<Eigen::Index>(getJacobianSize()),
285 "Jacobian rows mismatch: Actual {}, Expected {}",
286 jacobian.rows(),
287 gsl::narrow<Eigen::Index>(getJacobianSize()));
288 MT_CHECK(
289 residual.rows() >= gsl::narrow<Eigen::Index>(getJacobianSize()),
290 "Residual rows mismatch: Actual {}, Expected {}",
291 residual.rows(),
292 gsl::narrow<Eigen::Index>(getJacobianSize()));
293
294 if (state.jointState.empty()) {
295 return 0.0;
296 }
297
298 MT_CHECK(
299 state.jointParameters.size() ==
300 gsl::narrow<Eigen::Index>(this->skeleton_.joints.size() * kParametersPerJoint));
301
302 computeBroadPhase(state);
303
304 const T wgt = std::sqrt(kCollisionWeight * this->weight_);
305 int pos = 0;
306 double error = 0;
307
308 for (const auto& pair : validPairs_) {
310 if (!checkCollision(collisionState_, pair.indexA, pair.indexB, result)) {
311 continue;
312 }
313
314 error += sqr(result.overlap) * kCollisionWeight * this->weight_;
315
316 const Vector3<T> direction = result.positionA - result.positionB;
317 const T fac = wgt / result.distance;
318 const int row = pos++;
319
321 state,
322 result.positionA,
323 direction,
324 -fac,
325 collisionGeometry_[pair.indexA].parent,
326 pair.commonAncestor,
327 jacobian,
328 row,
329 -result.distance * result.radiusA * ln2<T>());
331 state,
332 result.positionB,
333 direction,
334 fac,
335 collisionGeometry_[pair.indexB].parent,
336 pair.commonAncestor,
337 jacobian,
338 row,
339 result.distance * result.radiusB * ln2<T>());
340
341 // Scale derivatives above the common ancestor
342 {
343 const T netScaleVal = -fac * ln2<T>() * direction.squaredNorm() +
344 wgt * (result.radiusA + result.radiusB) * ln2<T>();
345 size_t ancestorIndex = pair.commonAncestor;
346 while (ancestorIndex != kInvalidIndex) {
347 const size_t paramIndex = ancestorIndex * kParametersPerJoint;
348 if (this->activeJointParams_[paramIndex + 6]) {
350 netScaleVal, paramIndex + 6, row, this->parameterTransform_, jacobian);
351 }
352 ancestorIndex = this->skeleton_.joints[ancestorIndex].parent;
353 }
354 }
355
356 residual(row) = result.overlap * wgt;
357 }
358
359 usedRows = pos;
360 return error;
361}
362
363template <typename T>
364std::vector<CollisionDebugEntryT<T>> CollisionErrorFunctionT<T>::getCollisionDebugInfo() const {
365 std::vector<CollisionDebugEntryT<T>> entries;
366 for (const auto& pair : validPairs_) {
368 if (checkCollision(collisionState_, pair.indexA, pair.indexB, result)) {
369 entries.push_back(
370 {pair.indexA,
371 pair.indexB,
372 collisionGeometry_[pair.indexA].parent,
373 collisionGeometry_[pair.indexB].parent,
374 result.overlap,
375 result.distance});
376 }
377 }
378 return entries;
379}
380
381template <typename T>
383 return validPairs_.size();
384}
385
386template class CollisionErrorFunctionT<float>;
388
389} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
bool checkCollision(const CollisionGeometryStateT< T > &colState, size_t indexA, size_t indexB, CollisionOverlapResultT< T > &result) const
AABB broadphase pre-check followed by narrow-phase collision overlap test.
std::vector< CollisionDebugEntryT< T > > getCollisionDebugInfo() const
Query detailed collision state for all currently-colliding pairs.
void accumulateJacobianAlongChain(const SkeletonStateT< T > &state, const Vector3< T > &position, const Vector3< T > &direction, T factor, size_t startJoint, size_t stopJoint, Ref< MatrixX< T > > jacobian, int row, T scaleCorrection=T(0)) const
Accumulate Jacobian contributions along a joint chain from startJoint up to (but not including) stopJ...
std::vector< axel::BoundingBox< T > > aabbs_
Per-capsule AABBs, updated each frame for broadphase culling.
void updateCollisionPairs(bool filterRestPoseOverlaps=true)
CollisionErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt, const CollisionGeometry &cg, bool filterRestPoseOverlaps=true)
std::vector< Vector2i > getCollisionPairs() const
CollisionGeometryStateT< T > collisionState_
void accumulateGradientAlongChain(const SkeletonStateT< T > &state, const Vector3< T > &position, const Vector3< T > &direction, T weight, size_t startJoint, size_t stopJoint, Ref< VectorX< T > > gradient, T scaleCorrection=T(0)) const
Accumulate gradient contributions along a joint chain from startJoint up to (but not including) stopJ...
double getError(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) final
std::vector< CollisionPairInfo > validPairs_
Pre-filtered list of valid collision pairs (excludes rest-pose overlaps and adjacent joints).
double getGradient(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< VectorX< T > > gradient) override
void computeBroadPhase(const SkeletonStateT< T > &state)
Update collisionState_ and aabbs_ given the new skeleton state.
double getJacobian(const ModelParametersT< T > &, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< MatrixX< T > > jacobian, Ref< VectorX< T > > residual, int &usedRows) override
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
const ParameterTransform & parameterTransform_
#define MT_LOGD(...)
Definition log.h:178
CollisionGeometryT< float > CollisionGeometry
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)
Eigen::Ref< T > Ref
Definition types.h:43
void accumulateChainDerivatives(const SkeletonStateT< T > &state, const Skeleton &skeleton, const VectorX< bool > &activeJointParams, const Vector3< T > &position, const Vector3< T > &direction, T weight, size_t startJoint, size_t stopJoint, T scaleCorrection, const SinkFn &sink)
Accumulate the derivatives of direction .
constexpr T ln2() noexcept
Returns the natural logarithm of 2 (log_e 2).
Definition constants.h:40
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
Eigen::Matrix< T, Dynamic, Dynamic > MatrixX
Dynamic-size, column-major dense matrix.
Definition types.h:80
void gradient_jointParams_to_modelParams(const T &grad_jointParams, const Eigen::Index iJointParam, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::VectorX< T > > gradient)
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
Definition types.h:207
T sqr(const T &x)
Computes the square of a value.
Definition utility.h:47
void updateAabb(axel::BoundingBox< T > &aabb, const Vector3< T > &originA, const Vector3< T > &direction, const Vector2< T > &radii)
Updates an axis-aligned bounding box to encompass a tapered capsule.
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
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
bool overlaps(const Vector3< T > &originA, const Vector3< T > &directionA, const Vector2< T > &radiiA, T deltaA, const Vector3< T > &originB, const Vector3< T > &directionB, const Vector2< T > &radiiB, T deltaB, T &outDistance, Vector2< T > &outClosestPoints, T &outOverlap)
Determines if two tapered capsules overlap.
bool isValidCollisionPair(const CollisionGeometryStateT< T > &collisionState, const CollisionGeometry &collisionGeometry, const SkeletonT< S > &skeleton, size_t i, size_t j, bool filterRestPoseOverlaps=true)
Determines whether a pair of collision geometry primitives should be included as a valid collision pa...
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_EVENT(NAME)
Definition profile.h:112
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
Represents collision geometry states using a Structure of Arrays (SoA) format.
Narrow-phase collision information for a pair of primitives.
T overlap
Amount of overlap, positive when colliding.
T distance
Distance between the primitive center features used by the narrow phase.
T radiusA
Effective radius of the first primitive along the contact direction.
Vector3< T > positionB
Center feature position for the second primitive.
T radiusB
Effective radius of the second primitive along the contact direction.
Vector3< T > positionA
Center feature position for the first primitive.
Represents the complete state of a model's mesh.
Definition mesh_state.h:24
A vector of size numModelParams holding the values of all model parameters for a character.
Definition types.h:99
Represents the complete state of a skeleton.
JointParametersT< T > jointParameters
Joint parameters for all joints in the skeleton.
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.