Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
plane_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"
18
19#include <cmath>
20#include <stdexcept>
21
22namespace momentum {
23
24template <typename T>
26 const Skeleton& skel,
27 const ParameterTransform& pt,
28 const CollisionGeometry& cg,
29 const Vector3<T>& planeNormal,
30 T planeOffset)
31 : SkeletonErrorFunctionT<T>(skel, pt), collisionQuery_(cg, planeNormal, planeOffset) {
32 const SkeletonStateT<T> state(
33 this->parameterTransform_.zero().template cast<T>(), this->skeleton_);
34 collisionQuery_.update(state, T(0));
35}
36
37template <typename T>
39 const Character& character,
40 const Vector3<T>& planeNormal,
41 T planeOffset)
43 character.skeleton,
44 character.parameterTransform,
45 character.collision
46 ? *character.collision
47 : throw std::invalid_argument(
48 "Attempting to create plane collision error function with a character that "
49 "has no collision geometries"),
50 planeNormal,
51 planeOffset) {
52 // Do nothing
53}
54
55template <typename T>
57 const SkeletonStateT<T>& state,
58 const Vector3<T>& position,
59 const Vector3<T>& direction,
60 T weight,
61 size_t startJoint,
62 Ref<VectorX<T>> gradient,
63 T scaleCorrection) const {
65 state,
66 this->skeleton_,
68 position,
69 direction,
70 weight,
71 startJoint,
73 scaleCorrection,
74 [&](T value, size_t jointParamIndex) {
76 value, jointParamIndex, this->parameterTransform_, gradient);
77 });
78}
79
80template <typename T>
82 const SkeletonStateT<T>& state,
83 const Vector3<T>& position,
84 const Vector3<T>& direction,
85 T factor,
86 size_t startJoint,
87 Ref<MatrixX<T>> jacobian,
88 int row,
89 T scaleCorrection) const {
91 state,
92 this->skeleton_,
94 position,
95 direction,
96 factor,
97 startJoint,
99 scaleCorrection,
100 [&](T value, size_t jointParamIndex) {
102 value, jointParamIndex, row, this->parameterTransform_, jacobian);
103 });
104}
105
106template <typename T>
108 return collisionQuery_.getCollidingPrimitives();
109}
110
111template <typename T>
112std::vector<PlaneCollisionDebugEntryT<T>> PlaneCollisionErrorFunctionT<T>::getCollisionDebugInfo()
113 const {
114 return collisionQuery_.getCollisionDebugInfo();
115}
116
117template <typename T>
119 const std::span<const JointStateT<T>> states,
120 const T contactMargin) {
121 return collisionQuery_.getContactPoints(states, contactMargin);
122}
123
124template <typename T>
126 const std::span<const JointStateT<T>> states,
127 const T contactMargin) {
128 return collisionQuery_.getContactPointsByParent(states, contactMargin);
129}
130
131template <typename T>
132std::vector<PlaneCollisionContactPointT<T>>
134 const std::span<const JointStateT<T>> states,
135 const T contactMargin) {
136 return collisionQuery_.getContactPointsByParentWithDetails(states, contactMargin);
137}
138
139template <typename T>
141 const ModelParametersT<T>& /* params */,
142 const SkeletonStateT<T>& state,
143 const MeshStateT<T>& /* meshState */) {
144 if (state.jointState.empty()) {
145 return 0.0;
146 }
147
148 MT_CHECK(
149 state.jointParameters.size() ==
150 gsl::narrow<Eigen::Index>(this->skeleton_.joints.size() * kParametersPerJoint));
151
152 collisionQuery_.update(state, T(0));
153 collisionQuery_.updateActiveParentCollisions();
154
155 double error = 0;
156 for (const auto& collision : collisionQuery_.activeParentCollisions()) {
157 error += sqr(collision.overlap) * kCollisionWeight * this->weight_;
158 }
159
160 MT_LOGD(
161 "PlaneCollisionError: {} active parents / {} candidates / {} primitives, error={:.8f}, weight={:.4f}",
162 collisionQuery_.activeParentCollisions().size(),
163 collisionQuery_.candidatePrimitiveCount(),
164 collisionQuery_.primitiveCount(),
165 error,
166 this->weight_);
167
168 return error;
169}
170
171template <typename T>
173 const ModelParametersT<T>& /* params */,
174 const SkeletonStateT<T>& state,
175 const MeshStateT<T>& /* meshState */,
176 Ref<VectorX<T>> gradient) {
177 if (state.jointState.empty()) {
178 return 0.0;
179 }
180
181 MT_CHECK(
182 state.jointParameters.size() ==
183 gsl::narrow<Eigen::Index>(this->skeleton_.joints.size() * kParametersPerJoint));
184
185 collisionQuery_.update(state, T(0));
186 collisionQuery_.updateActiveParentCollisions();
187
188 double error = 0;
189 for (const auto& collision : collisionQuery_.activeParentCollisions()) {
190 error += sqr(collision.overlap) * kCollisionWeight * this->weight_;
191
192 const T wgt = -T(2) * kCollisionWeight * this->weight_ * collision.overlap;
194 state,
195 collision.position,
196 collisionQuery_.getPlaneNormal(),
197 wgt,
198 collision.parentJoint,
199 gradient,
200 /*scaleCorrection=*/T(0));
201 }
202
203 return error;
204}
205
206template <typename T>
208 const ModelParametersT<T>& /* params */,
209 const SkeletonStateT<T>& state,
210 const MeshStateT<T>& /* meshState */,
211 Ref<MatrixX<T>> jacobian,
212 Ref<VectorX<T>> residual,
213 int& usedRows) {
215 MT_CHECK(
216 jacobian.rows() >= gsl::narrow<Eigen::Index>(getJacobianSize()),
217 "Jacobian rows mismatch: Actual {}, Expected {}",
218 jacobian.rows(),
219 gsl::narrow<Eigen::Index>(getJacobianSize()));
220 MT_CHECK(
221 residual.rows() >= gsl::narrow<Eigen::Index>(getJacobianSize()),
222 "Residual rows mismatch: Actual {}, Expected {}",
223 residual.rows(),
224 gsl::narrow<Eigen::Index>(getJacobianSize()));
225
226 if (state.jointState.empty()) {
227 usedRows = 0;
228 return 0.0;
229 }
230
231 MT_CHECK(
232 state.jointParameters.size() ==
233 gsl::narrow<Eigen::Index>(this->skeleton_.joints.size() * kParametersPerJoint));
234
235 collisionQuery_.update(state, T(0));
236 collisionQuery_.updateActiveParentCollisions();
237
238 const T wgt = std::sqrt(kCollisionWeight * this->weight_);
239 int pos = 0;
240 double error = 0;
241
242 for (const auto& collision : collisionQuery_.activeParentCollisions()) {
243 error += sqr(collision.overlap) * kCollisionWeight * this->weight_;
244
245 const int row = pos++;
247 state,
248 collision.position,
249 collisionQuery_.getPlaneNormal(),
250 -wgt,
251 collision.parentJoint,
252 jacobian,
253 row,
254 /*scaleCorrection=*/T(0));
255 residual(row) = collision.overlap * wgt;
256 }
257
258 usedRows = pos;
259 return error;
260}
261
262template <typename T>
264 return collisionQuery_.primitiveCount();
265}
266
269
270} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Penalizes collision between character collision primitives and a fixed plane.
double getJacobian(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< MatrixX< T > > jacobian, Ref< VectorX< T > > residual, int &usedRows) override
PlaneCollisionErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt, const CollisionGeometry &cg, const Vector3< T > &planeNormal, T planeOffset)
void accumulateJacobianAlongChain(const SkeletonStateT< T > &state, const Vector3< T > &position, const Vector3< T > &direction, T factor, size_t startJoint, Ref< MatrixX< T > > jacobian, int row, T scaleCorrection=T(0)) const
Accumulate Jacobian contributions along a joint chain up to the root.
std::vector< PlaneCollisionDebugEntryT< T > > getCollisionDebugInfo() const
Query detailed collision state for all currently-colliding primitives.
std::vector< PlaneCollisionContactPointT< T > > getContactPointsByParentWithDetails(std::span< const JointStateT< T > > states, T contactMargin)
Return one detailed world-space primitive surface point per parent joint at or near the plane.
void accumulateGradientAlongChain(const SkeletonStateT< T > &state, const Vector3< T > &position, const Vector3< T > &direction, T weight, size_t startJoint, Ref< VectorX< T > > gradient, T scaleCorrection=T(0)) const
Accumulate gradient contributions along a joint chain up to the root.
std::vector< Vector3< T > > getContactPointsByParent(std::span< const JointStateT< T > > states, T contactMargin)
Return one world-space primitive surface point per parent joint at or near the plane.
double getGradient(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< VectorX< T > > gradient) override
double getError(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) final
std::vector< Vector3< T > > getContactPoints(std::span< const JointStateT< T > > states, T contactMargin)
Return world-space primitive surface points at or near the plane for an explicit state.
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 .
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
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
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
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.