23constexpr auto kInvalidNodeId = std::numeric_limits<uint32_t>::max();
25bool hasMomentumExtension(
const fx::gltf::Document& model) {
26 bool hasExtension = model.extensionsAndExtras.count(
"extensions") != 0 &&
27 model.extensionsAndExtras[
"extensions"].count(
"FB_momentum") != 0;
31nlohmann::json getMomentumExtension(
const nlohmann::json& extensionsAndExtras) {
32 if (extensionsAndExtras.count(
"extensions") != 0 &&
33 extensionsAndExtras[
"extensions"].count(
"FB_momentum") != 0) {
34 return extensionsAndExtras[
"extensions"][
"FB_momentum"];
36 return nlohmann::json::object();
40[[nodiscard]] std::vector<uint32_t> getAncestorsIncludingSelf(
42 const std::vector<uint32_t>& parents) {
43 auto ancestors = std::vector<uint32_t>();
44 auto curNode = nodeId;
45 while (curNode != kInvalidNodeId) {
46 ancestors.push_back(curNode);
47 curNode = parents[curNode];
49 std::reverse(ancestors.begin(), ancestors.end());
53[[nodiscard]] uint32_t findClosestCommonAncestor(
56 const std::vector<uint32_t>& parents) {
57 const auto ancestors1 = getAncestorsIncludingSelf(node1, parents);
58 const auto ancestors2 = getAncestorsIncludingSelf(node2, parents);
59 const auto maxNumIter = std::min(ancestors1.size(), ancestors2.size());
60 auto commonAncestor = kInvalidNodeId;
61 for (
auto i = 0; i < maxNumIter; i++) {
62 if (ancestors1[i] == ancestors2[i]) {
63 commonAncestor = ancestors1[i];
68 return commonAncestor;
79void loadHierarchyRecursive(
80 const fx::gltf::Document& model,
84 CollisionGeometry_u& collision,
87 std::vector<size_t>& nodeToObjectMap,
90 (nodeId < 0) || (nodeId >= model.nodes.size()),
91 "Invalid node id found in the gltf hierarchy: {}",
93 const auto& node = model.nodes[nodeId];
98 const auto& extension = getMomentumExtension(node.extensionsAndExtras);
99 const std::string type = extension.value(
"type",
"");
100 MT_CHECK(nodeId < nodeToObjectMap.size(),
"id: {}, size: {}", nodeId, nodeToObjectMap.size());
102 nodeToObjectMap.size() == model.nodes.size(),
103 "NodeMap: {}, nodes: {}",
104 nodeToObjectMap.size(),
106 auto newParentJointId = parentJointId;
107 if (type ==
"collision_capsule") {
111 "Invalid collision capsule without a parent joint: {}",
114 capsule.parent = parentJointId;
115 collision->push_back(capsule);
116 nodeToObjectMap[nodeId] = collision->size() - 1;
117 }
else if (type ==
"collision_ellipsoid") {
121 "Invalid collision ellipsoid without a parent joint: {}",
124 ellipsoid.parent = parentJointId;
125 collision->push_back(ellipsoid);
126 nodeToObjectMap[nodeId] = collision->size() - 1;
127 }
else if (type ==
"collision_box") {
131 "Invalid collision box without a parent joint: {}",
134 box.parent = parentJointId;
135 collision->push_back(box);
136 nodeToObjectMap[nodeId] = collision->size() - 1;
137 }
else if (type ==
"locator") {
140 parentJointId ==
kInvalidIndex,
"Invalid locator without a parent joint: {}", node.name);
142 loc.parent = parentJointId;
143 locators.push_back(loc);
144 nodeToObjectMap[nodeId] = locators.size() - 1;
145 }
else if ((!useExtension && (node.mesh < 0)) || type ==
"skeleton_joint") {
147 joint.parent = parentJointId;
148 joints.push_back(joint);
149 nodeToObjectMap[nodeId] = joints.size() - 1;
150 newParentJointId = joints.size() - 1;
151 if (extension.contains(
"physicalProperties")) {
153 extension.at(
"physicalProperties"), joint.name, newParentJointId));
159 for (
auto childId : model.nodes[nodeId].children) {
161 (childId < 0) || (childId >= model.nodes.size()),
162 "Invalid node id found in the gltf hierarchy: {}",
165 loadHierarchyRecursive(
188 tc.
length = extension[
"length"];
190 }
catch (
const std::exception&) {
192 "Fail to parse json {} for collision capsule {} when loading character.",
200 const fx::gltf::Node& node,
201 const nlohmann::json& extension) {
210 }
catch (
const std::exception&) {
212 "Fail to parse json {} for collision ellipsoid {} when loading character.",
228 }
catch (
const std::exception&) {
230 "Fail to parse json {} for collision box {} when loading character.",
240 loc.
name = node.name;
244 loc.
weight = extension[
"weight"];
245 if (extension.contains(
"limitOrigin")) {
252 if (extension.contains(
"attachedToSkin")) {
255 if (extension.contains(
"skinOffset")) {
258 }
catch (
const std::exception&) {
260 "Fail to parse json {} for locator {} when loading character.",
269 joint.
name = node.name;
277 return (node.skin < 0) && (node.camera < 0);
281 MT_CHECK(model.scene < model.scenes.size(),
"{}: {}", model.scene, model.scenes.size());
283 if (model.meshes.empty() || model.skins.empty()) {
284 std::vector<uint32_t> roots = model.scenes[model.scene].nodes;
289 auto parentMap = std::vector<uint32_t>(model.nodes.size(), kInvalidNodeId);
290 auto nodeStack = model.scenes[model.scene].nodes;
291 while (!nodeStack.empty()) {
292 std::vector<uint32_t> nextStack;
293 for (
const auto& nodeId : nodeStack) {
295 const auto& node = model.nodes[nodeId];
296 nextStack.reserve(nextStack.size() + node.children.size());
297 nextStack.insert(nextStack.end(), node.children.begin(), node.children.end());
298 for (
auto child : model.nodes[nodeId].children) {
299 parentMap[child] = nodeId;
302 nodeStack.swap(nextStack);
308 auto skinSkeletonRoots =
309 std::vector<std::vector<uint32_t>>(model.skins.size(), std::vector<uint32_t>());
310 for (
auto skinId = 0; skinId < model.skins.size(); skinId++) {
311 const auto& skin = model.skins[skinId];
312 auto& roots = skinSkeletonRoots[skinId];
313 for (
const auto jointId : skin.joints) {
315 const auto parentId = parentMap[jointId];
316 auto parentIter = std::find(skin.joints.begin(), skin.joints.end(), parentId);
317 if (parentIter == skin.joints.end()) {
318 bool foundSibling =
false;
319 for (
auto& root : roots) {
320 auto commonAncestor = findClosestCommonAncestor(jointId, root, parentMap);
321 if (commonAncestor != kInvalidNodeId) {
322 root = commonAncestor;
328 skinSkeletonRoots[skinId].push_back(jointId);
334 auto result = std::vector<std::vector<uint32_t>>(model.skins.size());
337 for (
auto skinId = 0; skinId < model.skins.size(); skinId++) {
339 !skinSkeletonRoots[skinId].empty(),
342 skinSkeletonRoots[skinId].size());
343 if (skinSkeletonRoots[skinId].size() > 1) {
345 auto& roots = result[skinId];
346 roots = skinSkeletonRoots[skinId];
348 auto ancestors = getAncestorsIncludingSelf(skinSkeletonRoots[skinId][0], parentMap);
349 bool isIndependent =
true;
350 for (
auto checkId = 0; checkId < model.skins.size(); checkId++) {
352 !skinSkeletonRoots[checkId].empty(),
355 skinSkeletonRoots[checkId].size());
356 if ((checkId == skinId) || skinSkeletonRoots[checkId].size() > 1) {
359 if (std::find(ancestors.begin(), ancestors.end(), skinSkeletonRoots[checkId][0]) !=
361 isIndependent =
false;
367 auto& roots = result[skinId];
368 roots.push_back(skinSkeletonRoots[skinId][0]);
377 [](
const std::vector<uint32_t>& roots) { return roots.empty(); }),
391 auto collision = std::make_unique<CollisionGeometry>();
394 auto nodeToObjectMap = std::vector<size_t>(model.nodes.size(),
kInvalidIndex);
395 const bool useExtension = hasMomentumExtension(model);
401 MT_CHECK(skeletonRoots.size() == 1,
"{}", skeletonRoots.size());
402 for (
const auto& rootNode : skeletonRoots[0]) {
403 loadHierarchyRecursive(
413 if (!joints.empty()) {
417 MT_THROW_IF(model.nodes.empty(),
"No valid node found in the gltf file.");
418 std::string name = model.nodes.at(0).name;
420 std::sort(collision->begin(), collision->end(), [](
const auto& c1,
const auto& c2) {
421 int c1Parent = c1.parent == kInvalidIndex ? -1 : static_cast<int>(c1.parent);
422 int c2Parent = c2.parent == kInvalidIndex ? -1 : static_cast<int>(c2.parent);
423 if (c1Parent != c2Parent) {
424 return c1Parent < c2Parent;
426 return static_cast<int>(c1.type) <
static_cast<int>(c2.type);
428 std::sort(locators.begin(), locators.end(), [](
const Locator& l1,
const Locator& l2) {
429 int l1Parent = l1.parent == kInvalidIndex ? -1 : static_cast<int>(l1.parent);
430 int l2Parent = l2.parent == kInvalidIndex ? -1 : static_cast<int>(l2.parent);
431 return l1Parent < l2Parent;
434 if (collision->empty()) {
437 return std::make_tuple(
438 name, joints, std::move(collision), locators, physicalProperties, nodeToObjectMap);
443 joints.push_back(
Joint());
444 MT_CHECK(joints.size() == 1,
"{}", joints.size());
445 joints[0].name =
"root";
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
#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.
bool isHierarchyNode(const fx::gltf::Node &node)
Check if a node is allowed in the skeleton hierarchy.
Quaternionf toMomentumQuaternionf(const std::array< float, 4 > &gltfQuat) noexcept
TransformT< float > Transform
std::tuple< std::string, JointList, CollisionGeometry_u, LocatorList, PhysicalProperties, std::vector< size_t > > loadHierarchy(const fx::gltf::Document &model)
Load the hierarchy from the model.
Joint createJoint(const fx::gltf::Node &node)
Create a joint from a glTF node.
JointListT< float > JointList
CollisionEllipsoidT< float > CollisionEllipsoid
CollisionBox createCollisionBox(const fx::gltf::Node &node, const nlohmann::json &extension)
Create a collision box from a glTF node.
T fromJson(const nlohmann::json &j)
JointList createSkeletonWithOnlyRoot()
Create a skeleton with only a root joint.
Locator createLocator(const fx::gltf::Node &node, const nlohmann::json &extension)
Create a locator from a glTF node.
CollisionEllipsoid createCollisionEllipsoid(const fx::gltf::Node &node, const nlohmann::json &extension)
Create a collision ellipsoid from a glTF node.
Vector3f toMomentumVec3f(const std::array< float, 3 > &vec) noexcept
JointPhysicalProperties jointPhysicalPropertiesFromJson(const nlohmann::json &j, const std::string &jointName, const size_t jointIndex)
Parses one joint's physical mass properties from JSON.
TaperedCapsule createCollisionCapsule(const fx::gltf::Node &node, const nlohmann::json &extension)
Create a collision capsule from a glTF node.
std::vector< JointPhysicalProperties > PhysicalProperties
Optional physical mass properties for a character.
CollisionBoxT< float > CollisionBox
std::vector< std::vector< uint32_t > > gatherSkeletonRoots(const fx::gltf::Document &model)
Gather skeleton roots from the glTF model.
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
TaperedCapsuleT< float > TaperedCapsule
std::vector< Locator > LocatorList
A collection of locators attached to a skeleton.
Vector3< S > halfExtents
Half extents along the local x, y, and z axes.
TransformT< S > transformation
Transformation defining the box center and orientation relative to the parent.
size_t parent
Parent joint to which the geometry is attached.
Vector3< S > radii
Radii along the local x, y, and z axes.
size_t parent
Parent joint to which the geometry is attached.
TransformT< S > transformation
Transformation defining the ellipsoid center and orientation relative to the parent.
size_t parent
Index of the parent joint in the skeleton hierarchy, or kInvalidIndex for the root.
Quaternion< T > preRotation
Pre-rotation from the parent joint's axes to this joint's local axes.
Vector3< T > translationOffset
Constant translation offset from the parent joint's origin to this joint's origin,...
Represents a point attached to a joint in a skeleton.
float weight
Influence weight when used as a constraint in error functions.
size_t parent
Index of the parent joint in the skeleton.
float skinOffset
Offset from the skin surface, used when solving for body shape using locators.
Vector3f limitWeight
Per-axis strength pulling the locator back toward limitOrigin.
Vector3i locked
Per-axis lock flags (x, y, z): 1 = locked, 0 = free.
bool attachedToSkin
True if the locator is attached to the skin of a person (e.g.
Vector3f offset
Position in the parent joint's local coordinate frame.
Vector3f limitOrigin
Reference position for limit constraints; typically equals offset when loaded.
size_t parent
Parent joint to which the geometry is attached.
S length
Length of the collision geometry along the x-axis.
TransformT< S > transformation
Transformation defining the orientation and starting point relative to the parent coordinate system.
Vector2< S > radius
Radii at the two endpoints of the capsule.