Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
json_utils.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
11#include "momentum/common/log.h"
14
15#include <nlohmann/json.hpp>
16
17#include <cmath>
18#include <exception>
19#include <optional>
20#include <utility>
21
22namespace momentum {
23
24namespace {
25
26nlohmann::json vector3ToJson(const Vector3f& value) {
27 return nlohmann::json::array({value.x(), value.y(), value.z()});
28}
29
30Vector3f vector3FromJson(const nlohmann::json& value, const std::string& fieldName) {
32 !value.is_array() || value.size() != 3,
33 "Physical properties field '{}' must be a 3-element vector",
34 fieldName);
35 Vector3f result(value.at(0).get<float>(), value.at(1).get<float>(), value.at(2).get<float>());
37 !result.allFinite(),
38 "Physical properties field '{}' must contain only finite values",
39 fieldName);
40 return result;
41}
42
43nlohmann::json quaternionToJson(const Quaternionf& value) {
44 return nlohmann::json::array({value.w(), value.x(), value.y(), value.z()});
45}
46
47Quaternionf quaternionFromJson(const nlohmann::json& value, const std::string& fieldName) {
49 !value.is_array() || value.size() != 4,
50 "Physical properties field '{}' must be a 4-element quaternion [w, x, y, z]",
51 fieldName);
52 Quaternionf result(
53 value.at(0).get<float>(),
54 value.at(1).get<float>(),
55 value.at(2).get<float>(),
56 value.at(3).get<float>());
58 !result.coeffs().allFinite(),
59 "Physical properties field '{}' must contain only finite values",
60 fieldName);
62 result.norm() <= 0.0f,
63 "Physical properties field '{}' must be a non-zero quaternion",
64 fieldName);
65 return result.normalized();
66}
67
68nlohmann::json inertiaToJson(const Matrix3f& value) {
69 nlohmann::json result;
70 result["ixx"] = value(0, 0);
71 result["ixy"] = value(0, 1);
72 result["ixz"] = value(0, 2);
73 result["iyy"] = value(1, 1);
74 result["iyz"] = value(1, 2);
75 result["izz"] = value(2, 2);
76 return result;
77}
78
79Matrix3f inertiaFromJson(const nlohmann::json& value) {
80 MT_THROW_IF(!value.is_object(), "Physical properties field 'inertia' must be an object");
81
82 const auto getComponent = [&](const char* fieldName) {
84 !value.contains(fieldName) || !value.at(fieldName).is_number(),
85 "Physical properties field 'inertia' must contain numeric field '{}'",
86 fieldName);
87 const float result = value.at(fieldName).get<float>();
89 !std::isfinite(result),
90 "Physical properties field 'inertia.{}' must contain a finite value",
91 fieldName);
92 return result;
93 };
94
95 const float ixx = getComponent("ixx");
96 const float ixy = getComponent("ixy");
97 const float ixz = getComponent("ixz");
98 const float iyy = getComponent("iyy");
99 const float iyz = getComponent("iyz");
100 const float izz = getComponent("izz");
101 Matrix3f result;
102 result << ixx, ixy, ixz, ixy, iyy, iyz, ixz, iyz, izz;
103 return result;
104}
105
106} // namespace
107
108void parameterSetsToJson(const Character& character, nlohmann::json& j) {
109 j = nlohmann::json::object();
110 for (const auto& set : character.parameterTransform.parameterSets) {
111 j[set.first] = nlohmann::json::array();
112 for (size_t i = 0; i < character.parameterTransform.name.size(); i++) {
113 if (set.second.test(i)) {
114 j[set.first].push_back(character.parameterTransform.name[i]);
115 }
116 }
117 }
118}
119
120ParameterSets parameterSetsFromJson(const Character& character, const nlohmann::json& j) {
121 ParameterSets result;
122
123 for (const auto& parameterSet : j.items()) {
124 auto& set = result[parameterSet.key()];
125 for (const auto& parameter : parameterSet.value().items()) {
126 const auto parameterIndex =
127 character.parameterTransform.getParameterIdByName(parameter.value());
128
129 if (parameterIndex != kInvalidIndex) {
130 set.set(parameterIndex);
131 }
132 }
133 }
134
135 return result;
136}
137
138void poseConstraintsToJson(const Character& character, nlohmann::json& j) {
139 j = nlohmann::json::object();
140 for (const auto& csts : character.parameterTransform.poseConstraints) {
141 for (const auto& pc : csts.second.parameterIdValue) {
142 if (!character.parameterTransform.name.empty() &&
143 pc.first < character.parameterTransform.name.size()) {
144 j[csts.first][character.parameterTransform.name[pc.first]] = pc.second;
145 }
146 }
147 }
148}
149
150PoseConstraints poseConstraintsFromJson(const Character& character, const nlohmann::json& j) {
151 PoseConstraints result;
152
153 for (const auto& constraint : j.items()) {
154 auto& pose = result[constraint.key()];
155 for (const auto& constraintPair : constraint.value().items()) {
156 const auto parameterIndex =
157 character.parameterTransform.getParameterIdByName(constraintPair.key());
158
159 const float value = constraintPair.value();
160 if (parameterIndex != kInvalidIndex) {
161 pose.parameterIdValue.emplace_back(parameterIndex, value);
162 }
163 }
164 }
165
166 return result;
167}
168
169void parameterTransformToJson(const Character& character, nlohmann::json& j) {
170 j["parameters"] = character.parameterTransform.name;
171
172 for (size_t jt = 0; jt < character.skeleton.joints.size(); jt++) {
173 const auto& jointName = character.skeleton.joints[jt].name;
174 const size_t paramIndex = jt * kParametersPerJoint;
175 for (size_t d = 0; d < kParametersPerJoint; d++) {
176 for (auto index = character.parameterTransform.transform.outerIndexPtr()[paramIndex + d];
177 index < character.parameterTransform.transform.outerIndexPtr()[paramIndex + d + 1];
178 ++index) {
179 const auto& parameterIndex = character.parameterTransform.transform.innerIndexPtr()[index];
180 const auto& parameterValue = character.parameterTransform.transform.valuePtr()[index];
181
182 if (parameterIndex < character.parameterTransform.name.size()) {
183 j["joints"][jointName][kJointParameterNames[d]]
184 [character.parameterTransform.name[parameterIndex]] = parameterValue;
185 }
186 }
187 }
188 }
189 // write blendshape parameters
190 const auto& blendShapeParameters = character.parameterTransform.blendShapeParameters;
191 const auto& faceExpressionParameters = character.parameterTransform.faceExpressionParameters;
192 auto bs = nlohmann::json::array();
193 for (int i = 0; i < blendShapeParameters.size(); i++) {
194 bs.push_back(blendShapeParameters[i]);
195 }
196 auto fe = nlohmann::json::array();
197 for (int i = 0; i < faceExpressionParameters.size(); i++) {
198 fe.push_back(faceExpressionParameters[i]);
199 }
200 j["blendShapeParameters"] = bs;
201 j["faceExpressionParameters"] = fe;
202}
203
204ParameterTransform parameterTransformFromJson(const Character& character, const nlohmann::json& j) {
206 try {
209 pt.offsets = VectorXf::Zero(character.skeleton.joints.size() * kParametersPerJoint);
210
211 // load all the parameter names
212 auto parameterItr = j.find("parameters");
213 MT_THROW_IF(parameterItr == j.end(), "No 'parameters' found in parameter transform.");
214
215 for (const auto& p : *parameterItr) {
216 pt.name.push_back(p.get<std::string>());
217 }
218
219 // triplet list
220 std::vector<Eigen::Triplet<float>> triplets;
221
222 auto jointItr = j.find("joints");
223 MT_THROW_IF(jointItr == j.end(), "No 'joints' found in parameter transform.");
224
225 for (const auto& joint : jointItr->items()) {
226 const std::string& jointName = joint.key();
227
228 // get the right joint to modify
229 const size_t jointIndex = character.skeleton.getJointIdByName(jointName);
230 MT_THROW_IF(jointIndex == kInvalidIndex, "Unknown joint name in expression : {}", jointName);
231
232 for (const auto& jointParameter : joint.value().items()) {
233 const std::string& jointParameterName = jointParameter.key();
234
235 // the first pToken is the name of the joint and it's attribute type
236 size_t attributeIndex = kInvalidIndex;
237 for (size_t jt = 0; jt < kParametersPerJoint; jt++) {
238 if (jointParameterName == kJointParameterNames[jt]) {
239 attributeIndex = jt;
240 break;
241 }
242 }
243
244 // if we didn't find a right name exit with an error
246 attributeIndex == kInvalidIndex,
247 "Unknown channel name in expression : {}",
248 jointParameterName);
249
250 // enable the attribute in the skeleton if we have a parameter controlling it
251 pt.activeJointParams[jointIndex * kParametersPerJoint + attributeIndex] = true;
252
253 // split the parameter names
254 for (const auto& parameter : jointParameter.value().items()) {
255 // get weight and name
256 const float weight = parameter.value();
257 const std::string& parameterName = parameter.key();
258
259 auto parameterIndex = pt.getParameterIdByName(parameterName);
260
262 parameterIndex == kInvalidIndex,
263 "Unknown parameter name in expression : {}",
264 parameterName);
265
266 // add triplet
267 triplets.emplace_back(
268 static_cast<int>(jointIndex * kParametersPerJoint + attributeIndex),
269 static_cast<int>(parameterIndex),
270 weight);
271 }
272 }
273 }
274
275 // resize the Transform matrix to the correct size
276 pt.transform.resize(
277 static_cast<int>(character.skeleton.joints.size()) * kParametersPerJoint,
278 static_cast<int>(pt.name.size()));
279
280 // finish parameter setup by creating sparse matrix
281 pt.transform.setFromTriplets(triplets.begin(), triplets.end());
282 } catch (...) {
283 // create an identity parameter transform
285 }
286
287 // read blendshape parameters
288 auto blendShapeParameters = j.find("blendShapeParameters");
289 if (blendShapeParameters != j.end()) {
290 pt.blendShapeParameters.resize(blendShapeParameters->size());
291 for (int i = 0; i < blendShapeParameters->size(); i++) {
292 pt.blendShapeParameters[i] = (*blendShapeParameters)[i].get<int>();
293 }
294 } else {
295 pt.blendShapeParameters.resize(0);
296 }
297 auto faceExpressionParameters = j.find("faceExpressionParameters");
298 if (faceExpressionParameters != j.end()) {
299 pt.faceExpressionParameters.resize(faceExpressionParameters->size());
300 for (int i = 0; i < faceExpressionParameters->size(); i++) {
301 pt.faceExpressionParameters[i] = (*faceExpressionParameters)[i].get<int>();
302 }
303 } else {
304 pt.faceExpressionParameters.resize(0);
305 }
306
307 return pt;
308}
309
311 const JointPhysicalProperties& jointProperties,
312 nlohmann::json& j) {
314 !std::isfinite(jointProperties.mass) || jointProperties.mass <= 0.0f,
315 "Physical properties entry for '{}' must have positive finite mass",
316 jointProperties.jointName);
318 !jointProperties.centerOfMassOffset.allFinite(),
319 "Physical properties entry for '{}' must have finite center-of-mass offset",
320 jointProperties.jointName);
322 !jointProperties.inertia.allFinite(),
323 "Physical properties entry for '{}' must have finite inertia",
324 jointProperties.jointName);
326 !jointProperties.inertiaRotation.coeffs().allFinite() ||
327 jointProperties.inertiaRotation.norm() <= 0.0f,
328 "Physical properties entry for '{}' must have finite non-zero inertia rotation",
329 jointProperties.jointName);
330
331 j = nlohmann::json::object();
332 j["mass"] = jointProperties.mass;
333 j["centerOfMass"] = vector3ToJson(jointProperties.centerOfMassOffset);
334 j["inertia"] = inertiaToJson(jointProperties.inertia);
335 j["inertiaRotation"] = quaternionToJson(jointProperties.inertiaRotation.normalized());
336}
337
339 const nlohmann::json& j,
340 const std::string& jointName,
341 const size_t jointIndex) {
342 MT_THROW_IF(!j.is_object(), "Physical properties entry for '{}' must be an object", jointName);
344 !j.contains("mass") || !j.at("mass").is_number(),
345 "Physical properties entry for '{}' must contain numeric field 'mass'",
346 jointName);
348 !j.contains("centerOfMass"),
349 "Physical properties entry for '{}' must contain field 'centerOfMass'",
350 jointName);
352 !j.contains("inertia"),
353 "Physical properties entry for '{}' must contain field 'inertia'",
354 jointName);
356 !j.contains("inertiaRotation"),
357 "Physical properties entry for '{}' must contain field 'inertiaRotation'",
358 jointName);
359
360 JointPhysicalProperties jointProperties;
361 jointProperties.jointName = jointName;
362 jointProperties.jointIndex = jointIndex;
363 jointProperties.mass = j.at("mass").get<float>();
365 !std::isfinite(jointProperties.mass) || jointProperties.mass <= 0.0f,
366 "Physical properties entry for '{}' must have positive finite mass",
367 jointProperties.jointName);
368
369 jointProperties.centerOfMassOffset = vector3FromJson(j.at("centerOfMass"), "centerOfMass");
370 jointProperties.inertia = inertiaFromJson(j.at("inertia"));
371 jointProperties.inertiaRotation = quaternionFromJson(j.at("inertiaRotation"), "inertiaRotation");
372
373 return jointProperties;
374}
375
377 nlohmann::json j;
378 jointPhysicalPropertiesToJson(jointProperties, j);
379 return j.dump();
380}
381
382std::optional<JointPhysicalProperties> jointPhysicalPropertiesFromJsonString(
383 const std::string& json,
384 const std::string& jointName,
385 const size_t jointIndex) {
386 // Catch std::exception (not just nlohmann::json::exception): a well-formed JSON string can still
387 // fail jointPhysicalPropertiesFromJson's semantic validation (e.g. missing field, non-positive
388 // mass), which throws std::runtime_error via MT_THROW. Both classes of failure must skip the
389 // single bad entry rather than abort loading the whole character.
390 try {
391 return jointPhysicalPropertiesFromJson(nlohmann::json::parse(json), jointName, jointIndex);
392 } catch (const std::exception& e) {
393 MT_LOGW("Skipping malformed physical properties for joint '{}': {}", jointName, e.what());
394 return std::nullopt;
395 }
396}
397
398namespace {
399
400void minMaxToJson(const Character& character, const ParameterLimit& lim, nlohmann::json& li) {
401 li["type"] = "minmax";
403 character.parameterTransform.name.empty() ||
404 lim.data.minMax.parameterIndex >= character.parameterTransform.name.size(),
405 "MinMax parameter index {} is out of bounds (name size: {})",
406 lim.data.minMax.parameterIndex,
407 character.parameterTransform.name.size());
408 li["parameter"] = character.parameterTransform.name[lim.data.minMax.parameterIndex];
409 li["limits"] = lim.data.minMax.limits;
410}
411
412void minMaxJointToJson(
413 const Character& character,
414 const ParameterLimit& lim,
415 nlohmann::json& li,
416 const char* typeName) {
417 li["type"] = typeName;
418 if (!character.skeleton.joints.empty() &&
419 lim.data.minMaxJoint.jointIndex < character.skeleton.joints.size()) {
420 li["jointIndex"] = character.skeleton.joints[lim.data.minMaxJoint.jointIndex].name;
421 }
422 li["jointParameter"] = kJointParameterNames[lim.data.minMaxJoint.jointParameter];
423 li["limits"] = lim.data.minMaxJoint.limits;
424}
425
426void linearToJson(const Character& character, const ParameterLimit& lim, nlohmann::json& li) {
427 li["type"] = "linear";
429 character.parameterTransform.name.empty() ||
430 lim.data.linear.referenceIndex >= character.parameterTransform.name.size(),
431 "Linear referenceIndex {} is out of bounds (name size: {})",
432 lim.data.linear.referenceIndex,
433 character.parameterTransform.name.size());
434 li["referenceParameter"] = character.parameterTransform.name[lim.data.linear.referenceIndex];
436 character.parameterTransform.name.empty() ||
437 lim.data.linear.targetIndex >= character.parameterTransform.name.size(),
438 "Linear targetIndex {} is out of bounds (name size: {})",
439 lim.data.linear.targetIndex,
440 character.parameterTransform.name.size());
441 li["targetParameter"] = character.parameterTransform.name[lim.data.linear.targetIndex];
442 li["scale"] = lim.data.linear.scale;
443 li["offset"] = lim.data.linear.offset;
444 if (lim.data.linear.rangeMin != -std::numeric_limits<float>::max()) {
445 li["rangeMin"] = lim.data.linear.rangeMin;
446 }
447 if (lim.data.linear.rangeMax != std::numeric_limits<float>::max()) {
448 li["rangeMax"] = lim.data.linear.rangeMax;
449 }
450}
451
452void linearJointToJson(const Character& character, const ParameterLimit& lim, nlohmann::json& li) {
453 li["type"] = "linear_joint";
454 if (!character.skeleton.joints.empty() &&
455 lim.data.linearJoint.referenceJointIndex < character.skeleton.joints.size()) {
456 li["referenceJoint"] = character.skeleton.joints[lim.data.linearJoint.referenceJointIndex].name;
457 }
458 li["referenceJointParameter"] = lim.data.linearJoint.referenceJointParameter;
459 if (!character.skeleton.joints.empty() &&
460 lim.data.linearJoint.targetJointIndex < character.skeleton.joints.size()) {
461 li["targetJoint"] = character.skeleton.joints[lim.data.linearJoint.targetJointIndex].name;
462 }
463 li["targetJointParameter"] = lim.data.linearJoint.targetJointParameter;
464 li["scale"] = lim.data.linearJoint.scale;
465 li["offset"] = lim.data.linearJoint.offset;
466 if (lim.data.linearJoint.rangeMin != -std::numeric_limits<float>::max()) {
467 li["rangeMin"] = lim.data.linearJoint.rangeMin;
468 }
469 if (lim.data.linearJoint.rangeMax != std::numeric_limits<float>::max()) {
470 li["rangeMax"] = lim.data.linearJoint.rangeMax;
471 }
472}
473
474void halfPlaneToJson(const Character& character, const ParameterLimit& lim, nlohmann::json& li) {
475 li["type"] = "half_plane";
477 character.parameterTransform.name.empty() ||
478 lim.data.halfPlane.param1 >= character.parameterTransform.name.size(),
479 "HalfPlane param1 index {} is out of bounds (name size: {})",
480 lim.data.halfPlane.param1,
481 character.parameterTransform.name.size());
482 li["param1"] = character.parameterTransform.name[lim.data.halfPlane.param1];
484 character.parameterTransform.name.empty() ||
485 lim.data.halfPlane.param2 >= character.parameterTransform.name.size(),
486 "HalfPlane param2 index {} is out of bounds (name size: {})",
487 lim.data.halfPlane.param2,
488 character.parameterTransform.name.size());
489 li["param2"] = character.parameterTransform.name[lim.data.halfPlane.param2];
490 li["normal"] = lim.data.halfPlane.normal;
491 li["offset"] = lim.data.halfPlane.offset;
492}
493
494void ellipsoidToJson(const Character& character, const ParameterLimit& lim, nlohmann::json& li) {
495 li["type"] = "ellipsoid";
496 if (!character.skeleton.joints.empty() &&
497 lim.data.ellipsoid.parent < character.skeleton.joints.size()) {
498 li["parent"] = character.skeleton.joints[lim.data.ellipsoid.parent].name;
499 }
500 if (!character.skeleton.joints.empty() &&
501 lim.data.ellipsoid.ellipsoidParent < character.skeleton.joints.size()) {
502 li["ellipsoidParent"] = character.skeleton.joints[lim.data.ellipsoid.ellipsoidParent].name;
503 }
504 li["offset"] = lim.data.ellipsoid.offset * toM();
505 auto eli = lim.data.ellipsoid.ellipsoid;
506 eli.translation() *= toM();
507 toJson(eli.matrix(), li["ellipsoid"]);
508}
509
510size_t parseJointParameterIndex(const std::string& attribute) {
511 for (size_t t = 0; t < kParametersPerJoint; t++) {
512 if (attribute == kJointParameterNames[t]) {
513 return t;
514 }
515 }
516 return kInvalidIndex;
517}
518
519void minMaxFromJson(const Character& character, const nlohmann::json& element, ParameterLimit& l) {
520 l.type = MinMax;
521 l.data.minMax.parameterIndex =
522 character.parameterTransform.getParameterIdByName(element.value("parameter", ""));
523 l.data.minMax.limits = fromJson<Vector2f>(element["limits"]);
524}
525
526void minMaxJointFromJson(
527 const Character& character,
528 const nlohmann::json& element,
530 LimitType limitType) {
531 l.type = limitType;
532 l.data.minMaxJoint.jointIndex =
533 character.skeleton.getJointIdByName(element.value("jointIndex", ""));
534 const std::string attribute = element.value("jointParameter", "");
535 l.data.minMaxJoint.jointParameter = parseJointParameterIndex(attribute);
536 l.data.minMaxJoint.limits = fromJson<Vector2f>(element["limits"]);
537}
538
539void linearFromJson(const Character& character, const nlohmann::json& element, ParameterLimit& l) {
540 l.type = Linear;
541 l.data.linear.referenceIndex =
542 character.parameterTransform.getParameterIdByName(element.value("referenceParameter", ""));
543 l.data.linear.targetIndex =
544 character.parameterTransform.getParameterIdByName(element.value("targetParameter", ""));
545 l.data.linear.scale = element["scale"];
546 l.data.linear.offset = element["offset"];
547 l.data.linear.rangeMin = element.value("rangeMin", -std::numeric_limits<float>::max());
548 l.data.linear.rangeMax = element.value("rangeMax", std::numeric_limits<float>::max());
549}
550
551void linearJointFromJson(
552 const Character& character,
553 const nlohmann::json& element,
554 ParameterLimit& l) {
555 l.type = LinearJoint;
556 l.data.linearJoint.referenceJointIndex =
557 character.skeleton.getJointIdByName(element.value("referenceJoint", ""));
558 l.data.linearJoint.targetJointIndex =
559 character.skeleton.getJointIdByName(element.value("targetJoint", ""));
560 l.data.linearJoint.referenceJointParameter = element["referenceJointParameter"].get<size_t>();
561 l.data.linearJoint.targetJointParameter = element["targetJointParameter"].get<size_t>();
562 l.data.linearJoint.scale = element["scale"];
563 l.data.linearJoint.offset = element["offset"];
564 l.data.linearJoint.rangeMin = element.value("rangeMin", -std::numeric_limits<float>::max());
565 l.data.linearJoint.rangeMax = element.value("rangeMax", std::numeric_limits<float>::max());
566}
567
568void halfPlaneFromJson(
569 const Character& character,
570 const nlohmann::json& element,
571 ParameterLimit& l) {
572 l.type = HalfPlane;
573 l.data.halfPlane.param1 =
574 character.parameterTransform.getParameterIdByName(element.value("param1", ""));
575 l.data.halfPlane.param2 =
576 character.parameterTransform.getParameterIdByName(element.value("param2", ""));
577 l.data.halfPlane.normal = fromJson<Vector2f>(element["normal"]);
578 l.data.halfPlane.offset = element["offset"];
579}
580
581void ellipsoidFromJson(
582 const Character& character,
583 const nlohmann::json& element,
585 const std::string& parentKey,
586 const std::string& ellipsoidKey) {
587 l.type = Ellipsoid;
588 l.data.ellipsoid.parent = character.skeleton.getJointIdByName(element.value("parent", ""));
589 l.data.ellipsoid.ellipsoidParent =
590 character.skeleton.getJointIdByName(element.value(parentKey, ""));
591 l.data.ellipsoid.offset = fromJson<Vector3f>(element["offset"]);
592 l.data.ellipsoid.offset /= toM();
593 l.data.ellipsoid.ellipsoid.matrix() = fromJson<Matrix4f>(element[ellipsoidKey]);
594 l.data.ellipsoid.ellipsoid.translation() /= toM();
595 l.data.ellipsoid.ellipsoidInv = l.data.ellipsoid.ellipsoid.inverse();
596}
597
598} // namespace
599
600void parameterLimitsToJson(const Character& character, nlohmann::json& j) {
601 j = nlohmann::json::array();
602 for (const auto& lim : character.parameterLimits) {
603 j.push_back(nlohmann::json::object());
604 auto& li = j.back();
605 li["weight"] = lim.weight;
606
607 switch (lim.type) {
608 case MinMax:
609 minMaxToJson(character, lim, li);
610 break;
611 case MinMaxJoint:
612 minMaxJointToJson(character, lim, li, "minmax_joint");
613 break;
615 minMaxJointToJson(character, lim, li, "minmax_joint_passive");
616 break;
617 case Linear:
618 linearToJson(character, lim, li);
619 break;
620 case LinearJoint:
621 linearJointToJson(character, lim, li);
622 break;
623 case HalfPlane:
624 halfPlaneToJson(character, lim, li);
625 break;
626 case Ellipsoid:
627 ellipsoidToJson(character, lim, li);
628 break;
629 case LimitTypeCount:
630 default:
631 MT_LOGE(
632 "Unknown parameter limit type '{}' from character name '{}'",
633 toString(lim.type),
634 character.name);
635 break;
636 }
637 }
638}
639
640ParameterLimits parameterLimitsFromJson(const Character& character, const nlohmann::json& j) {
641 ParameterLimits result;
642
643 for (const auto& element : j) {
644 const std::string type = element.value("type", "");
646 l.weight = element.value("weight", 0.0f);
647
648 if (type == "minmax") {
649 minMaxFromJson(character, element, l);
650 } else if (type == "minmax_joint") {
651 minMaxJointFromJson(character, element, l, MinMaxJoint);
652 } else if (type == "minmax_joint_passive") {
653 minMaxJointFromJson(character, element, l, MinMaxJointPassive);
654 } else if (type == "linear") {
655 linearFromJson(character, element, l);
656 } else if (type == "linear_joint") {
657 linearJointFromJson(character, element, l);
658 } else if (type == "half_plane") {
659 halfPlaneFromJson(character, element, l);
660 } else if (type == "ellipsoid") {
661 ellipsoidFromJson(character, element, l, "ellipsoidParent", "ellipsoid");
662 } else if (type == "elipsoid") {
663 // TODO: Remove once all the model files are migrated to ellipsoid
665 "Deprecated parameter limit type: {} (typo). Please use 'ellipsoid' instead.", type);
666 ellipsoidFromJson(character, element, l, "elipsoidParent", "elipsoid");
667 } else {
668 MT_THROW("Unknown parameter limit type '{}' from character name '{}'.", type, character.name);
669 }
670 result.push_back(l);
671 }
672
673 return result;
674}
675
676} // namespace momentum
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
Definition exception.h:31
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Definition exception.h:55
#define MT_LOGW(...)
Definition log.h:180
#define MT_LOGW_ONCE(...)
Definition log.h:192
#define MT_LOGE(...)
Definition log.h:181
ParameterLimits parameterLimitsFromJson(const Character &character, const nlohmann::json &j)
constexpr T toM(T x=T(1)) noexcept
Converts the given length x (in centimeters) to meters.
Definition constants.h:87
Matrix3< float > Matrix3f
Definition types.h:107
Quaternion< float > Quaternionf
Definition types.h:386
std::unordered_map< std::string, ParameterSet > ParameterSets
T fromJson(const nlohmann::json &j)
Definition json_utils.h:45
std::vector< ParameterLimit > ParameterLimits
void toJson(const Eigen::MatrixBase< Derived > &mat, nlohmann::json &j)
Definition json_utils.h:30
constexpr std::array< const char *, kParametersPerJoint > kJointParameterNames
Definition types.h:24
void jointPhysicalPropertiesToJson(const JointPhysicalProperties &jointProperties, nlohmann::json &j)
Serializes one joint's physical mass properties.
JointPhysicalProperties jointPhysicalPropertiesFromJson(const nlohmann::json &j, const std::string &jointName, const size_t jointIndex)
Parses one joint's physical mass properties from JSON.
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
std::optional< JointPhysicalProperties > jointPhysicalPropertiesFromJsonString(const std::string &json, const std::string &jointName, const size_t jointIndex)
Parses one joint's physical mass properties from its canonical on-disk JSON string.
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
Definition types.h:207
void parameterSetsToJson(const Character &character, nlohmann::json &j)
void poseConstraintsToJson(const Character &character, nlohmann::json &j)
constexpr size_t kParametersPerJoint
Definition types.h:21
ParameterTransform parameterTransformFromJson(const Character &character, const nlohmann::json &j)
std::string jointPhysicalPropertiesToJsonString(const JointPhysicalProperties &jointProperties)
Serializes one joint's physical mass properties to its canonical on-disk JSON string.
void parameterTransformToJson(const Character &character, nlohmann::json &j)
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
ParameterSets parameterSetsFromJson(const Character &character, const nlohmann::json &j)
std::unordered_map< std::string, PoseConstraint > PoseConstraints
Vector3< float > Vector3f
Definition types.h:251
std::string_view toString(const LimitType type)
void parameterLimitsToJson(const Character &character, nlohmann::json &j)
PoseConstraints poseConstraintsFromJson(const Character &character, const nlohmann::json &j)
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
ParameterLimits parameterLimits
Constraints on model parameters.
Definition character.h:46
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
Definition character.h:36
std::string name
Character identifier.
Definition character.h:82
ParameterTransform parameterTransform
Maps model parameters to joint parameters.
Definition character.h:39
Physical mass properties attached to one skeleton joint.
Definition joint.h:88
Vector3f centerOfMassOffset
Local center-of-mass offset from the joint frame, in centimeters.
Definition joint.h:103
size_t jointIndex
Cached joint index.
Definition joint.h:97
Matrix3f inertia
Inertia tensor about the body's center of mass, expressed in the local inertia frame,...
Definition joint.h:107
Quaternionf inertiaRotation
Rotation from the inertia frame to the joint frame.
Definition joint.h:110
std::string jointName
Skeleton joint that owns this physical body.
Definition joint.h:93
float mass
Body mass in kilograms.
Definition joint.h:100
VectorX< bool > activeJointParams
The list of joint parameters that are actually active and influenced from the transform.
VectorXi faceExpressionParameters
The indices of the parameters that influence face expressions; faceExpressionParameters(0) is the par...
PoseConstraints poseConstraints
A set of predefined poses.
std::vector< std::string > name
The list of model parameter names.
VectorXi blendShapeParameters
The indices of the parameters that influence blend shapes; blendShapeParameters(0) is the parameter t...
ParameterSets parameterSets
Convenience grouping of model parameters.
size_t getParameterIdByName(const std::string &nm) const
Return the index of a model parameter from its name.
SparseRowMatrix< T > transform
The sparse mapping matrix that maps model parameters to joint parameters.
static ParameterTransformT< float > identity(momentum::span< const std::string > jointNames)
size_t getJointIdByName(std::string_view name) const
Returns the index of a joint with the given name, or kInvalidIndex if not found.
Definition skeleton.cpp:25
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
Definition skeleton.h:25
std::vector< std::string > getJointNames() const
Definition skeleton.cpp:35