Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
collision_error_function_stateless.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
18
19namespace momentum {
20
21template <typename T>
29
30template <typename T>
33 character.skeleton,
34 character.parameterTransform,
35 character.collision
36 ? *character.collision
37 : throw std::invalid_argument(
38 "Attempting to create collision error function with a character that has no collision geometries")) {
39 // Do nothing
40}
41
42template <typename T>
44 validPairs_.clear();
45
46 const SkeletonStateT<T> state(
47 this->parameterTransform_.zero().template cast<T>(), this->skeleton_);
48 collisionState.update(state, collisionGeometry);
49
50 const auto n = collisionGeometry.size();
51
52 aabbs_.resize(n);
53 for (size_t i = 0; i < n; ++i) {
54 aabbs_[i].id = gsl::narrow_cast<axel::Index>(i);
56 }
57
58 if (n == 0) {
59 return;
60 }
61
62 for (size_t i = 0; i < n; ++i) {
63 for (size_t j = i + 1; j < n; ++j) {
65 const size_t lca = this->skeleton_.commonAncestor(
66 collisionGeometry[i].parent, collisionGeometry[j].parent);
67 validPairs_.push_back({i, j, lca});
68 }
69 }
70 }
71}
72
73template <typename T>
75 {
76 MT_PROFILE_EVENT("Collision: updateState");
77 collisionState.update(state, collisionGeometry);
78 }
79
80 for (size_t i = 0; i < aabbs_.size(); ++i) {
82 }
83}
84
85template <typename T>
87 const CollisionGeometryStateT<T>& colState,
88 size_t indexA,
89 size_t indexB,
90 CollisionOverlapResultT<T>& result) const {
91 if (!aabbs_[indexA].intersects(aabbs_[indexB])) {
92 return false;
93 }
94 return overlaps(colState, collisionGeometry, indexA, indexB, result);
95}
96
97template <typename T>
99 const SkeletonStateT<T>& state,
100 const Vector3<T>& position,
101 const Vector3<T>& direction,
102 T weight,
103 size_t startJoint,
104 size_t stopJoint,
105 Ref<VectorX<T>> gradient,
106 T scaleCorrection) const {
108 state,
109 this->skeleton_,
110 this->activeJointParams_,
111 position,
112 direction,
113 weight,
114 startJoint,
115 stopJoint,
116 scaleCorrection,
117 [&](T value, size_t jointParamIndex) {
119 value, jointParamIndex, this->parameterTransform_, gradient);
120 });
121}
122
123template <typename T>
125 const SkeletonStateT<T>& state,
126 const Vector3<T>& position,
127 const Vector3<T>& direction,
128 T factor,
129 size_t startJoint,
130 size_t stopJoint,
131 Ref<MatrixX<T>> jacobian,
132 int row,
133 T scaleCorrection) const {
135 state,
136 this->skeleton_,
137 this->activeJointParams_,
138 position,
139 direction,
140 factor,
141 startJoint,
142 stopJoint,
143 scaleCorrection,
144 [&](T value, size_t jointParamIndex) {
146 value, jointParamIndex, row, this->parameterTransform_, jacobian);
147 });
148}
149
150template <typename T>
152 std::vector<Vector2i> collidingPairs;
153 for (const auto& pair : validPairs_) {
155 if (checkCollision(collisionState, pair.indexA, pair.indexB, result)) {
156 collidingPairs.emplace_back(pair.indexA, pair.indexB);
157 }
158 }
159 return collidingPairs;
160}
161
162template <typename T>
164 const ModelParametersT<T>& /* params */,
165 const SkeletonStateT<T>& state,
166 const MeshStateT<T>& /* meshState */) {
167 if (state.jointState.empty()) {
168 return 0.0;
169 }
170
171 MT_CHECK(
172 state.jointParameters.size() ==
173 gsl::narrow<Eigen::Index>(this->skeleton_.joints.size() * kParametersPerJoint));
174
175 computeBroadPhase(state);
176
177 double error = 0;
178 for (const auto& pair : validPairs_) {
180 if (!checkCollision(collisionState, pair.indexA, pair.indexB, result)) {
181 continue;
182 }
183 error += sqr(result.overlap) * kCollisionWeight * this->weight_;
184 }
185
186 return error;
187}
188
189template <typename T>
191 const ModelParametersT<T>& /* params */,
192 const SkeletonStateT<T>& state,
193 const MeshStateT<T>& /* meshState */,
194 Ref<VectorX<T>> gradient) {
195 if (state.jointState.empty()) {
196 return 0.0;
197 }
198
199 MT_CHECK(
200 state.jointParameters.size() ==
201 gsl::narrow<Eigen::Index>(this->skeleton_.joints.size() * kParametersPerJoint));
202
203 computeBroadPhase(state);
204
205 double error = 0;
206 for (const auto& pair : validPairs_) {
208 if (!checkCollision(collisionState, pair.indexA, pair.indexB, result)) {
209 continue;
210 }
211
212 error += sqr(result.overlap) * kCollisionWeight * this->weight_;
213
214 const Vector3<T> direction = result.positionA - result.positionB;
215 const T wgt = -T(2) * kCollisionWeight * this->weight_ * (result.overlap / result.distance);
216
218 state,
219 result.positionA,
220 direction,
221 wgt,
222 collisionGeometry[pair.indexA].parent,
223 pair.commonAncestor,
224 gradient,
225 -result.distance * result.radiusA * ln2<T>());
227 state,
228 result.positionB,
229 direction,
230 -wgt,
231 collisionGeometry[pair.indexB].parent,
232 pair.commonAncestor,
233 gradient,
234 result.distance * result.radiusB * ln2<T>());
235
236 // Scale derivatives above the common ancestor
237 {
238 const T netScaleVal =
239 (direction.squaredNorm() - result.distance * (result.radiusA + result.radiusB)) *
240 ln2<T>() * wgt;
241 size_t ancestorIndex = pair.commonAncestor;
242 while (ancestorIndex != kInvalidIndex) {
243 const size_t paramIndex = ancestorIndex * kParametersPerJoint;
244 if (this->activeJointParams_[paramIndex + 6]) {
246 netScaleVal, paramIndex + 6, this->parameterTransform_, gradient);
247 }
248 ancestorIndex = this->skeleton_.joints[ancestorIndex].parent;
249 }
250 }
251 }
252
253 return error;
254}
255
256template <typename T>
258 const ModelParametersT<T>& /* params */,
259 const SkeletonStateT<T>& state,
260 const MeshStateT<T>& /* meshState */,
261 Ref<MatrixX<T>> jacobian,
262 Ref<VectorX<T>> residual,
263 int& usedRows) {
265 MT_CHECK(
266 jacobian.rows() >= gsl::narrow<Eigen::Index>(getJacobianSize()),
267 "Jacobian rows mismatch: Actual {}, Expected {}",
268 jacobian.rows(),
269 gsl::narrow<Eigen::Index>(getJacobianSize()));
270 MT_CHECK(
271 residual.rows() >= gsl::narrow<Eigen::Index>(getJacobianSize()),
272 "Residual rows mismatch: Actual {}, Expected {}",
273 residual.rows(),
274 gsl::narrow<Eigen::Index>(getJacobianSize()));
275
276 if (state.jointState.empty()) {
277 return 0.0;
278 }
279
280 MT_CHECK(
281 state.jointParameters.size() ==
282 gsl::narrow<Eigen::Index>(this->skeleton_.joints.size() * kParametersPerJoint));
283
284 computeBroadPhase(state);
285
286 const T wgt = std::sqrt(kCollisionWeight * this->weight_);
287 int pos = 0;
288 double error = 0;
289
290 for (const auto& pair : validPairs_) {
292 if (!checkCollision(collisionState, pair.indexA, pair.indexB, result)) {
293 continue;
294 }
295
296 error += sqr(result.overlap) * kCollisionWeight * this->weight_;
297
298 const Vector3<T> direction = result.positionA - result.positionB;
299 const T fac = wgt / result.distance;
300 const int row = pos++;
301
303 state,
304 result.positionA,
305 direction,
306 -fac,
307 collisionGeometry[pair.indexA].parent,
308 pair.commonAncestor,
309 jacobian,
310 row,
311 -result.distance * result.radiusA * ln2<T>());
313 state,
314 result.positionB,
315 direction,
316 fac,
317 collisionGeometry[pair.indexB].parent,
318 pair.commonAncestor,
319 jacobian,
320 row,
321 result.distance * result.radiusB * ln2<T>());
322
323 // Scale derivatives above the common ancestor
324 {
325 const T netScaleVal = -fac * ln2<T>() * direction.squaredNorm() +
326 wgt * (result.radiusA + result.radiusB) * ln2<T>();
327 size_t ancestorIndex = pair.commonAncestor;
328 while (ancestorIndex != kInvalidIndex) {
329 const size_t paramIndex = ancestorIndex * kParametersPerJoint;
330 if (this->activeJointParams_[paramIndex + 6]) {
332 netScaleVal, paramIndex + 6, row, this->parameterTransform_, jacobian);
333 }
334 ancestorIndex = this->skeleton_.joints[ancestorIndex].parent;
335 }
336 }
337
338 residual(row) = result.overlap * wgt;
339 }
340
341 usedRows = pos;
342 return error;
343}
344
345template <typename T>
349
352
353} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
NOTE: This is a resurrected version of the CollisionErrorFunction (previously updated by D50818775).
void computeBroadPhase(const SkeletonStateT< T > &state)
Update collisionState and aabbs_ given the new skeleton state.
std::vector< CollisionPairInfo > validPairs_
Pre-filtered list of valid collision pairs.
std::vector< axel::BoundingBox< T > > aabbs_
Per-capsule AABBs, updated each frame for broadphase culling.
double getGradient(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< VectorX< T > > gradient) override
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.
double getError(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) final
double getJacobian(const ModelParametersT< T > &, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< MatrixX< T > > jacobian, Ref< VectorX< T > > residual, int &usedRows) override
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.
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.
CollisionErrorFunctionStatelessT(const Skeleton &skel, const ParameterTransform &pt, const CollisionGeometry &cg)
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
const ParameterTransform & parameterTransform_
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.