15#include <nlohmann/json.hpp>
26nlohmann::json vector3ToJson(
const Vector3f& value) {
27 return nlohmann::json::array({value.x(), value.y(), value.z()});
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",
35 Vector3f result(value.at(0).get<
float>(), value.at(1).get<
float>(), value.at(2).get<
float>());
38 "Physical properties field '{}' must contain only finite values",
43nlohmann::json quaternionToJson(
const Quaternionf& value) {
44 return nlohmann::json::array({value.w(), value.x(), value.y(), value.z()});
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]",
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",
62 result.norm() <= 0.0f,
63 "Physical properties field '{}' must be a non-zero quaternion",
65 return result.normalized();
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);
79Matrix3f inertiaFromJson(
const nlohmann::json& value) {
80 MT_THROW_IF(!value.is_object(),
"Physical properties field 'inertia' must be an object");
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 '{}'",
87 const float result = value.at(fieldName).get<
float>();
89 !std::isfinite(result),
90 "Physical properties field 'inertia.{}' must contain a finite value",
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");
102 result << ixx, ixy, ixz, ixy, iyy, iyz, ixz, iyz, izz;
109 j = nlohmann::json::object();
111 j[set.first] = nlohmann::json::array();
113 if (set.second.test(i)) {
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 =
130 set.set(parameterIndex);
139 j = nlohmann::json::object();
141 for (
const auto& pc : csts.second.parameterIdValue) {
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 =
159 const float value = constraintPair.value();
161 pose.parameterIdValue.emplace_back(parameterIndex, value);
172 for (
size_t jt = 0; jt < character.
skeleton.
joints.size(); jt++) {
192 auto bs = nlohmann::json::array();
193 for (
int i = 0; i < blendShapeParameters.size(); i++) {
194 bs.push_back(blendShapeParameters[i]);
196 auto fe = nlohmann::json::array();
197 for (
int i = 0; i < faceExpressionParameters.size(); i++) {
198 fe.push_back(faceExpressionParameters[i]);
200 j[
"blendShapeParameters"] = bs;
201 j[
"faceExpressionParameters"] = fe;
212 auto parameterItr = j.find(
"parameters");
213 MT_THROW_IF(parameterItr == j.end(),
"No 'parameters' found in parameter transform.");
215 for (
const auto& p : *parameterItr) {
216 pt.
name.push_back(p.get<std::string>());
220 std::vector<Eigen::Triplet<float>> triplets;
222 auto jointItr = j.find(
"joints");
223 MT_THROW_IF(jointItr == j.end(),
"No 'joints' found in parameter transform.");
225 for (
const auto& joint : jointItr->items()) {
226 const std::string& jointName = joint.key();
232 for (
const auto& jointParameter : joint.value().items()) {
233 const std::string& jointParameterName = jointParameter.key();
247 "Unknown channel name in expression : {}",
254 for (
const auto& parameter : jointParameter.value().items()) {
256 const float weight = parameter.value();
257 const std::string& parameterName = parameter.key();
263 "Unknown parameter name in expression : {}",
267 triplets.emplace_back(
269 static_cast<int>(parameterIndex),
278 static_cast<int>(pt.
name.size()));
281 pt.
transform.setFromTriplets(triplets.begin(), triplets.end());
288 auto blendShapeParameters = j.find(
"blendShapeParameters");
289 if (blendShapeParameters != j.end()) {
291 for (
int i = 0; i < blendShapeParameters->size(); i++) {
297 auto faceExpressionParameters = j.find(
"faceExpressionParameters");
298 if (faceExpressionParameters != j.end()) {
300 for (
int i = 0; i < faceExpressionParameters->size(); i++) {
314 !std::isfinite(jointProperties.
mass) || jointProperties.
mass <= 0.0f,
315 "Physical properties entry for '{}' must have positive finite mass",
319 "Physical properties entry for '{}' must have finite center-of-mass offset",
322 !jointProperties.
inertia.allFinite(),
323 "Physical properties entry for '{}' must have finite inertia",
328 "Physical properties entry for '{}' must have finite non-zero inertia rotation",
331 j = nlohmann::json::object();
332 j[
"mass"] = jointProperties.
mass;
334 j[
"inertia"] = inertiaToJson(jointProperties.
inertia);
335 j[
"inertiaRotation"] = quaternionToJson(jointProperties.
inertiaRotation.normalized());
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'",
348 !j.contains(
"centerOfMass"),
349 "Physical properties entry for '{}' must contain field 'centerOfMass'",
352 !j.contains(
"inertia"),
353 "Physical properties entry for '{}' must contain field 'inertia'",
356 !j.contains(
"inertiaRotation"),
357 "Physical properties entry for '{}' must contain field 'inertiaRotation'",
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",
369 jointProperties.
centerOfMassOffset = vector3FromJson(j.at(
"centerOfMass"),
"centerOfMass");
370 jointProperties.
inertia = inertiaFromJson(j.at(
"inertia"));
371 jointProperties.
inertiaRotation = quaternionFromJson(j.at(
"inertiaRotation"),
"inertiaRotation");
373 return jointProperties;
383 const std::string& json,
384 const std::string& jointName,
385 const size_t jointIndex) {
392 }
catch (
const std::exception& e) {
393 MT_LOGW(
"Skipping malformed physical properties for joint '{}': {}", jointName, e.what());
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;
412void minMaxJointToJson(
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;
423 li[
"limits"] = lim.data.minMaxJoint.limits;
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;
447 if (lim.data.linear.rangeMax != std::numeric_limits<float>::max()) {
448 li[
"rangeMax"] = lim.data.linear.rangeMax;
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;
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;
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;
469 if (lim.data.linearJoint.rangeMax != std::numeric_limits<float>::max()) {
470 li[
"rangeMax"] = lim.data.linearJoint.rangeMax;
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;
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;
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;
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"]);
510size_t parseJointParameterIndex(
const std::string& attribute) {
521 l.data.minMax.parameterIndex =
522 character.parameterTransform.getParameterIdByName(element.value(
"parameter",
""));
526void minMaxJointFromJson(
528 const nlohmann::json& element,
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);
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());
551void linearJointFromJson(
553 const nlohmann::json& element,
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());
568void halfPlaneFromJson(
570 const nlohmann::json& element,
573 l.data.halfPlane.param1 =
574 character.parameterTransform.getParameterIdByName(element.value(
"param1",
""));
575 l.data.halfPlane.param2 =
576 character.parameterTransform.getParameterIdByName(element.value(
"param2",
""));
578 l.data.halfPlane.offset = element[
"offset"];
581void ellipsoidFromJson(
583 const nlohmann::json& element,
585 const std::string& parentKey,
586 const std::string& ellipsoidKey) {
588 l.data.ellipsoid.parent = character.skeleton.getJointIdByName(element.value(
"parent",
""));
589 l.data.ellipsoid.ellipsoidParent =
590 character.skeleton.getJointIdByName(element.value(parentKey,
""));
592 l.data.ellipsoid.offset /=
toM();
594 l.data.ellipsoid.ellipsoid.translation() /=
toM();
595 l.data.ellipsoid.ellipsoidInv = l.data.ellipsoid.ellipsoid.inverse();
601 j = nlohmann::json::array();
603 j.push_back(nlohmann::json::object());
605 li[
"weight"] = lim.weight;
609 minMaxToJson(character, lim, li);
612 minMaxJointToJson(character, lim, li,
"minmax_joint");
615 minMaxJointToJson(character, lim, li,
"minmax_joint_passive");
618 linearToJson(character, lim, li);
621 linearJointToJson(character, lim, li);
624 halfPlaneToJson(character, lim, li);
627 ellipsoidToJson(character, lim, li);
632 "Unknown parameter limit type '{}' from character name '{}'",
643 for (
const auto& element : j) {
644 const std::string type = element.value(
"type",
"");
646 l.
weight = element.value(
"weight", 0.0f);
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") {
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") {
665 "Deprecated parameter limit type: {} (typo). Please use 'ellipsoid' instead.", type);
666 ellipsoidFromJson(character, element, l,
"elipsoidParent",
"elipsoid");
668 MT_THROW(
"Unknown parameter limit type '{}' from character name '{}'.", type, character.
name);
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
#define MT_LOGW_ONCE(...)
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.
Matrix3< float > Matrix3f
Quaternion< float > Quaternionf
std::unordered_map< std::string, ParameterSet > ParameterSets
T fromJson(const nlohmann::json &j)
std::vector< ParameterLimit > ParameterLimits
void toJson(const Eigen::MatrixBase< Derived > &mat, nlohmann::json &j)
constexpr std::array< const char *, kParametersPerJoint > kJointParameterNames
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
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.
void parameterSetsToJson(const Character &character, nlohmann::json &j)
void poseConstraintsToJson(const Character &character, nlohmann::json &j)
constexpr size_t kParametersPerJoint
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.
ParameterSets parameterSetsFromJson(const Character &character, const nlohmann::json &j)
std::unordered_map< std::string, PoseConstraint > PoseConstraints
Vector3< float > Vector3f
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.
ParameterLimits parameterLimits
Constraints on model parameters.
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
std::string name
Character identifier.
ParameterTransform parameterTransform
Maps model parameters to joint parameters.
Physical mass properties attached to one skeleton joint.
Vector3f centerOfMassOffset
Local center-of-mass offset from the joint frame, in centimeters.
size_t jointIndex
Cached joint index.
Matrix3f inertia
Inertia tensor about the body's center of mass, expressed in the local inertia frame,...
Quaternionf inertiaRotation
Rotation from the inertia frame to the joint frame.
std::string jointName
Skeleton joint that owns this physical body.
float mass
Body mass in kilograms.
size_t getJointIdByName(std::string_view name) const
Returns the index of a joint with the given name, or kInvalidIndex if not found.
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
std::vector< std::string > getJointNames() const