Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
gltf_skeleton_io.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
16#include <algorithm>
17#include <limits>
18
19namespace momentum {
20
21namespace {
22
23constexpr auto kInvalidNodeId = std::numeric_limits<uint32_t>::max();
24
25bool hasMomentumExtension(const fx::gltf::Document& model) {
26 bool hasExtension = model.extensionsAndExtras.count("extensions") != 0 &&
27 model.extensionsAndExtras["extensions"].count("FB_momentum") != 0;
28 return hasExtension;
29}
30
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"];
35 } else {
36 return nlohmann::json::object();
37 }
38}
39
40[[nodiscard]] std::vector<uint32_t> getAncestorsIncludingSelf(
41 uint32_t nodeId,
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];
48 }
49 std::reverse(ancestors.begin(), ancestors.end());
50 return ancestors;
51}
52
53[[nodiscard]] uint32_t findClosestCommonAncestor(
54 const uint32_t node1,
55 const uint32_t node2,
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];
64 } else {
65 break;
66 }
67 }
68 return commonAncestor;
69}
70
71// DFS the hierarchy graph to reconstruct it.
72// Along the way, save the joints, collision geometry and the locators, as well as a
73// nodeToObjectMap for query. nodeToObjectMap stores mapping from node index to joint index,
74// if the node is a joint. If it's a collision capsule or locator,
75// stores the index in the collision volume array or locator array.
76// If no extension is present in the glb file, right now we will load every not-skinned node as a
77// joint. #TODO: correctly load hierarchy from the skinning information if no momentum extension is
78// in the file.
79void loadHierarchyRecursive(
80 const fx::gltf::Document& model,
81 const int nodeId,
82 size_t parentJointId,
83 JointList& joints,
84 CollisionGeometry_u& collision,
85 LocatorList& locators,
86 PhysicalProperties& physicalProperties,
87 std::vector<size_t>& nodeToObjectMap,
88 bool useExtension) {
90 (nodeId < 0) || (nodeId >= model.nodes.size()),
91 "Invalid node id found in the gltf hierarchy: {}",
92 nodeId);
93 const auto& node = model.nodes[nodeId];
94 if (!isHierarchyNode(node)) {
95 return;
96 }
97
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());
101 MT_CHECK(
102 nodeToObjectMap.size() == model.nodes.size(),
103 "NodeMap: {}, nodes: {}",
104 nodeToObjectMap.size(),
105 model.nodes.size());
106 auto newParentJointId = parentJointId;
107 if (type == "collision_capsule") {
108 // Found collision geometry, should be the end node
110 parentJointId == kInvalidIndex,
111 "Invalid collision capsule without a parent joint: {}",
112 node.name);
113 auto capsule = createCollisionCapsule(node, extension);
114 capsule.parent = parentJointId;
115 collision->push_back(capsule);
116 nodeToObjectMap[nodeId] = collision->size() - 1;
117 } else if (type == "collision_ellipsoid") {
118 // Found collision geometry, should be the end node
120 parentJointId == kInvalidIndex,
121 "Invalid collision ellipsoid without a parent joint: {}",
122 node.name);
123 auto ellipsoid = createCollisionEllipsoid(node, extension);
124 ellipsoid.parent = parentJointId;
125 collision->push_back(ellipsoid);
126 nodeToObjectMap[nodeId] = collision->size() - 1;
127 } else if (type == "collision_box") {
128 // Found collision geometry, should be the end node
130 parentJointId == kInvalidIndex,
131 "Invalid collision box without a parent joint: {}",
132 node.name);
133 auto box = createCollisionBox(node, extension);
134 box.parent = parentJointId;
135 collision->push_back(box);
136 nodeToObjectMap[nodeId] = collision->size() - 1;
137 } else if (type == "locator") {
138 // Found locator, should be the end node
140 parentJointId == kInvalidIndex, "Invalid locator without a parent joint: {}", node.name);
141 Locator loc = createLocator(node, extension);
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") {
146 Joint joint = createJoint(node);
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")) {
152 physicalProperties.push_back(jointPhysicalPropertiesFromJson(
153 extension.at("physicalProperties"), joint.name, newParentJointId));
154 }
155 }
156 // #TODO: log skipped nodes
157
158 MT_CHECK(!model.nodes.empty());
159 for (auto childId : model.nodes[nodeId].children) {
161 (childId < 0) || (childId >= model.nodes.size()),
162 "Invalid node id found in the gltf hierarchy: {}",
163 childId);
164
165 loadHierarchyRecursive(
166 model,
167 childId,
168 newParentJointId,
169 joints,
170 collision,
171 locators,
172 physicalProperties,
173 nodeToObjectMap,
174 useExtension);
175 }
176}
177
178} // namespace
179
180TaperedCapsule createCollisionCapsule(const fx::gltf::Node& node, const nlohmann::json& extension) {
185 tc.transformation.translation = toMomentumVec3f(node.translation);
186
187 try {
188 tc.length = extension["length"];
189 tc.radius = fromJson<Vector2f>(extension["radius"]);
190 } catch (const std::exception&) {
191 MT_THROW(
192 "Fail to parse json {} for collision capsule {} when loading character.",
193 node.name,
194 extension.dump());
195 }
196 return tc;
197}
198
200 const fx::gltf::Node& node,
201 const nlohmann::json& extension) {
202 CollisionEllipsoid ellipsoid;
203 ellipsoid.parent = kInvalidIndex;
204 ellipsoid.transformation = Transform();
205 ellipsoid.transformation.rotation = toMomentumQuaternionf(node.rotation);
206 ellipsoid.transformation.translation = toMomentumVec3f(node.translation);
207
208 try {
209 ellipsoid.radii = fromJson<Vector3f>(extension["radii"]);
210 } catch (const std::exception&) {
211 MT_THROW(
212 "Fail to parse json {} for collision ellipsoid {} when loading character.",
213 extension.dump(),
214 node.name);
215 }
216 return ellipsoid;
217}
218
219CollisionBox createCollisionBox(const fx::gltf::Node& node, const nlohmann::json& extension) {
220 CollisionBox box;
221 box.parent = kInvalidIndex;
223 box.transformation.rotation = toMomentumQuaternionf(node.rotation);
224 box.transformation.translation = toMomentumVec3f(node.translation);
225
226 try {
227 box.halfExtents = fromJson<Vector3f>(extension["halfExtents"]);
228 } catch (const std::exception&) {
229 MT_THROW(
230 "Fail to parse json {} for collision box {} when loading character.",
231 extension.dump(),
232 node.name);
233 }
234 return box;
235}
236
237Locator createLocator(const fx::gltf::Node& node, const nlohmann::json& extension) {
238 Locator loc;
239 loc.parent = kInvalidIndex;
240 loc.name = node.name;
241 loc.offset = toMomentumVec3f(node.translation);
242
243 try {
244 loc.weight = extension["weight"];
245 if (extension.contains("limitOrigin")) {
246 loc.limitOrigin = fromJson<Vector3f>(extension["limitOrigin"]);
247 } else {
248 loc.limitOrigin = loc.offset;
249 }
250 loc.limitWeight = fromJson<Vector3f>(extension["limitWeight"]);
251 loc.locked = fromJson<Vector3i>(extension["locked"]);
252 if (extension.contains("attachedToSkin")) {
253 loc.attachedToSkin = extension["attachedToSkin"];
254 }
255 if (extension.contains("skinOffset")) {
256 loc.skinOffset = extension["skinOffset"];
257 }
258 } catch (const std::exception&) {
259 MT_THROW(
260 "Fail to parse json {} for locator {} when loading character.",
261 extension.dump(),
262 node.name);
263 }
264 return loc;
265}
266
267Joint createJoint(const fx::gltf::Node& node) {
268 Joint joint;
269 joint.name = node.name;
270 joint.parent = kInvalidIndex;
271 joint.preRotation = toMomentumQuaternionf(node.rotation);
272 joint.translationOffset = toMomentumVec3f(node.translation);
273 return joint;
274}
275
276bool isHierarchyNode(const fx::gltf::Node& node) {
277 return (node.skin < 0) && (node.camera < 0);
278}
279
280std::vector<std::vector<uint32_t>> gatherSkeletonRoots(const fx::gltf::Document& model) {
281 MT_CHECK(model.scene < model.scenes.size(), "{}: {}", model.scene, model.scenes.size());
282 // If no skinned mesh is present, consider the scene root nodes as skeleton roots.
283 if (model.meshes.empty() || model.skins.empty()) {
284 std::vector<uint32_t> roots = model.scenes[model.scene].nodes;
285 return {roots};
286 }
287
288 // Build a parent map for ancestor query
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) {
294 // NOLINTNEXTLINE(facebook-hte-ParameterUncheckedArrayBounds)
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;
300 }
301 }
302 nodeStack.swap(nextStack);
303 }
304
305 // Assumption: all the joints in the skin are directly connected (i.e. no non-joint node in
306 // between two joints) Merge skeleton within the same skin. If they are in the same hierarchy,
307 // they can be merged under their closest common ancestor.
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) {
314 // NOLINTNEXTLINE(facebook-hte-LocalUncheckedArrayBounds)
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;
323 foundSibling = true;
324 break;
325 }
326 }
327 if (!foundSibling) {
328 skinSkeletonRoots[skinId].push_back(jointId);
329 }
330 }
331 }
332 }
333
334 auto result = std::vector<std::vector<uint32_t>>(model.skins.size());
335 // Merge skeleton between different skins. If the skeleton root of one is an ancestor of another,
336 // the other one can be merged to the same root.
337 for (auto skinId = 0; skinId < model.skins.size(); skinId++) {
338 MT_CHECK(
339 !skinSkeletonRoots[skinId].empty(),
340 "id: {}, size: {}",
341 skinId,
342 skinSkeletonRoots[skinId].size());
343 if (skinSkeletonRoots[skinId].size() > 1) {
344 // NOLINTNEXTLINE(facebook-hte-LocalUncheckedArrayBounds)
345 auto& roots = result[skinId];
346 roots = skinSkeletonRoots[skinId];
347 } else {
348 auto ancestors = getAncestorsIncludingSelf(skinSkeletonRoots[skinId][0], parentMap);
349 bool isIndependent = true;
350 for (auto checkId = 0; checkId < model.skins.size(); checkId++) {
351 MT_CHECK(
352 !skinSkeletonRoots[checkId].empty(),
353 "id: {}, size: {}",
354 checkId,
355 skinSkeletonRoots[checkId].size());
356 if ((checkId == skinId) || skinSkeletonRoots[checkId].size() > 1) {
357 continue;
358 }
359 if (std::find(ancestors.begin(), ancestors.end(), skinSkeletonRoots[checkId][0]) !=
360 ancestors.end()) {
361 isIndependent = false;
362 break;
363 }
364 }
365 if (isIndependent) {
366 // NOLINTNEXTLINE(facebook-hte-LocalUncheckedArrayBounds)
367 auto& roots = result[skinId];
368 roots.push_back(skinSkeletonRoots[skinId][0]);
369 }
370 }
371 }
372 // Remove the empty skeletons that were skipped
373 result.erase(
374 std::remove_if(
375 result.begin(),
376 result.end(),
377 [](const std::vector<uint32_t>& roots) { return roots.empty(); }),
378 result.end());
379 return result;
380}
381
382std::tuple<
383 std::string,
384 JointList,
385 CollisionGeometry_u,
388 std::vector<size_t>>
389loadHierarchy(const fx::gltf::Document& model) {
390 JointList joints;
391 auto collision = std::make_unique<CollisionGeometry>();
392 LocatorList locators;
393 PhysicalProperties physicalProperties;
394 auto nodeToObjectMap = std::vector<size_t>(model.nodes.size(), kInvalidIndex);
395 const bool useExtension = hasMomentumExtension(model);
396
397 // Currently only the first found skeleton is used
398 // #TODO: support multiple characters in the file, and use the skin information stored in
399 // CharacterInfo.
400 auto skeletonRoots = gatherSkeletonRoots(model);
401 MT_CHECK(skeletonRoots.size() == 1, "{}", skeletonRoots.size());
402 for (const auto& rootNode : skeletonRoots[0]) {
403 loadHierarchyRecursive(
404 model,
405 rootNode,
407 joints,
408 collision,
409 locators,
410 physicalProperties,
411 nodeToObjectMap,
412 useExtension);
413 if (!joints.empty()) {
414 break;
415 }
416 }
417 MT_THROW_IF(model.nodes.empty(), "No valid node found in the gltf file.");
418 std::string name = model.nodes.at(0).name;
419
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;
425 }
426 return static_cast<int>(c1.type) < static_cast<int>(c2.type);
427 });
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;
432 });
433 // remove the collision geometry if it was empty to begin with
434 if (collision->empty()) {
435 collision.reset();
436 }
437 return std::make_tuple(
438 name, joints, std::move(collision), locators, physicalProperties, nodeToObjectMap);
439}
440
442 JointList joints;
443 joints.push_back(Joint());
444 MT_CHECK(joints.size() == 1, "{}", joints.size());
445 joints[0].name = "root";
446 return joints;
447}
448
449} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
#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
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
Definition fwd.h:77
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
Definition joint.h:81
CollisionEllipsoidT< float > CollisionEllipsoid
Definition fwd.h:168
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)
Definition json_utils.h:45
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.
Definition joint.h:114
CollisionBoxT< float > CollisionBox
Definition fwd.h:187
std::vector< std::vector< uint32_t > > gatherSkeletonRoots(const fx::gltf::Document &model)
Gather skeleton roots from the glTF model.
JointT< float > Joint
Definition fwd.h:206
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
TaperedCapsuleT< float > TaperedCapsule
Definition fwd.h:320
std::vector< Locator > LocatorList
A collection of locators attached to a skeleton.
Definition locator.h:79
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.
Definition joint.h:24
Quaternion< T > preRotation
Pre-rotation from the parent joint's axes to this joint's local axes.
Definition joint.h:32
Vector3< T > translationOffset
Constant translation offset from the parent joint's origin to this joint's origin,...
Definition joint.h:36
std::string name
Definition joint.h:21
Represents a point attached to a joint in a skeleton.
Definition locator.h:19
float weight
Influence weight when used as a constraint in error functions.
Definition locator.h:32
size_t parent
Index of the parent joint in the skeleton.
Definition locator.h:23
std::string name
Definition locator.h:20
float skinOffset
Offset from the skin surface, used when solving for body shape using locators.
Definition locator.h:46
Vector3f limitWeight
Per-axis strength pulling the locator back toward limitOrigin.
Definition locator.h:39
Vector3i locked
Per-axis lock flags (x, y, z): 1 = locked, 0 = free.
Definition locator.h:29
bool attachedToSkin
True if the locator is attached to the skin of a person (e.g.
Definition locator.h:43
Vector3f offset
Position in the parent joint's local coordinate frame.
Definition locator.h:26
Vector3f limitOrigin
Reference position for limit constraints; typically equals offset when loaded.
Definition locator.h:35
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.
Vector3< T > translation
Definition transform.h:40
Quaternion< T > rotation
Unit quaternion encoding the rotation.
Definition transform.h:39