Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
openfbx_loader.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
17#include "momentum/common/log.h"
26#include "momentum/math/mesh.h"
28
29#include <nlohmann/json.hpp>
30#include <ofbx.h>
31#include <gsl/span_ext>
32
33#include <cmath>
34#include <exception>
35#include <fstream>
36#include <functional>
37#include <numeric>
38#include <set>
39#include <unordered_map>
40#include <variant>
41
42namespace momentum {
43
44namespace {
45
46Eigen::Vector3d toEigen(const ofbx::DVec3& v) {
47 return {v.x, v.y, v.z};
48}
49
50Eigen::Affine3d toEigen(const ofbx::DMatrix& mat) {
51 return Eigen::Affine3d(Eigen::Matrix4d(mat.m));
52}
53
54Eigen::Vector3i getRotationOrder(ofbx::RotationOrder order) {
55 switch (order) {
56 case ofbx::RotationOrder::EULER_XYZ:
57 default:
58 return {0, 1, 2};
59 case ofbx::RotationOrder::EULER_XZY:
60 return {0, 2, 1};
61 case ofbx::RotationOrder::EULER_YZX:
62 return {1, 2, 0};
63 case ofbx::RotationOrder::EULER_YXZ:
64 return {1, 0, 2};
65 case ofbx::RotationOrder::EULER_ZXY:
66 return {2, 0, 1};
67 case ofbx::RotationOrder::EULER_ZYX:
68 return {2, 1, 0};
69 }
70}
71
72const char* rotationOrderStr(ofbx::RotationOrder order) {
73 switch (order) {
74 case ofbx::RotationOrder::EULER_XYZ:
75 return "EULER_XYZ";
76 case ofbx::RotationOrder::EULER_XZY:
77 return "EULER_XZY";
78 case ofbx::RotationOrder::EULER_YZX:
79 return "EULER_YZX";
80 case ofbx::RotationOrder::EULER_YXZ:
81 return "EULER_YXZ";
82 case ofbx::RotationOrder::EULER_ZXY:
83 return "EULER_ZXY";
84 case ofbx::RotationOrder::EULER_ZYX:
85 return "EULER_ZYX";
86 case ofbx::RotationOrder::SPHERIC_XYZ:
87 return "SPHERIC_XYZ";
88 default:
89 return "Unknown";
90 }
91}
92
93const char* propertyTypeStr(ofbx::IElementProperty::Type type) {
94 switch (type) {
95 case ofbx::IElementProperty::LONG:
96 return "LONG";
97 case ofbx::IElementProperty::INTEGER:
98 return "INTEGER";
99 case ofbx::IElementProperty::STRING:
100 return "STRING";
101 case ofbx::IElementProperty::FLOAT:
102 return "FLOAT";
103 case ofbx::IElementProperty::DOUBLE:
104 return "DOUBLE";
105 case ofbx::IElementProperty::ARRAY_DOUBLE:
106 return "ARRAY_DOUBLE";
107 case ofbx::IElementProperty::ARRAY_INT:
108 return "ARRAY_INT";
109 case ofbx::IElementProperty::ARRAY_LONG:
110 return "ARRAY_LONG";
111 case ofbx::IElementProperty::ARRAY_FLOAT:
112 return "ARRAY_FLOAT";
113 default:
114 return "Unknown";
115 }
116}
117
118ofbx::IElement* resolveProperty(const ofbx::Object& object, const char* name);
119std::string resolveStringProperty(const ofbx::Object& object, const char* name);
120
121PhysicalProperties loadPhysicalPropertiesFromNodes(
122 const Skeleton& skeleton,
123 const std::vector<const ofbx::Object*>& jointFbxNodes) {
124 PhysicalProperties result;
125
126 for (size_t jointIndex = 0; jointIndex < jointFbxNodes.size(); ++jointIndex) {
127 const ofbx::Object* jointNode = jointFbxNodes.at(jointIndex);
128 if (jointNode == nullptr) {
129 continue;
130 }
131
132 // Reading the FBX property itself can throw: resolveProperty/resolveStringProperty use MT_THROW
133 // (std::runtime_error) when a node carries a malformed "physicalProperties" property, and
134 // jointPhysicalPropertiesFromJsonString additionally skips entries whose JSON content is
135 // malformed or invalid. Catch broadly so a single bad joint is skipped rather than aborting the
136 // whole character load.
137 try {
138 if (resolveProperty(*jointNode, "physicalProperties") == nullptr) {
139 continue;
140 }
141
142 if (auto jointProperties = jointPhysicalPropertiesFromJsonString(
143 resolveStringProperty(*jointNode, "physicalProperties"),
144 skeleton.joints.at(jointIndex).name,
145 jointIndex)) {
146 result.push_back(std::move(*jointProperties));
147 }
148 } catch (const std::exception& e) {
149 MT_LOGW(
150 "Skipping physical properties for FBX joint '{}': {}",
151 skeleton.joints.at(jointIndex).name,
152 e.what());
153 }
154 }
155
156 return result;
157}
158
159template <typename T>
160Eigen::Quaternion<T> computeEulerRotation(
161 const Eigen::Vector3<T>& angles,
162 ofbx::RotationOrder order) {
163 using VecType = Eigen::Vector3<T>;
164 using QuaternionType = Eigen::Quaternion<T>;
165
166 if (order == ofbx::RotationOrder::SPHERIC_XYZ) {
167 // in the case of a ball-joint the 3 parameters are simply the xyz parameters of a quaternion
168 return QuaternionType(
169 std::sqrt(std::max(T(1) - angles.squaredNorm(), T(0))), angles.x(), angles.y(), angles.z());
170 } else {
171 const Eigen::Vector3i rotOrder = getRotationOrder(order);
172 QuaternionType result = QuaternionType::Identity();
173 for (uint32_t index = 0; index < 3; ++index) {
174 const auto& rIndex = rotOrder(index);
175 result = QuaternionType(Eigen::AngleAxis<T>(angles(rIndex), VecType::Unit(rIndex))) * result;
176 }
177 return result;
178 }
179}
180
181Eigen::Quaterniond fbxEulerRotationToQuat(
182 const ofbx::DVec3& eulerAngles,
183 const ofbx::RotationOrder rotOrder) {
184 const Eigen::Vector3d rotDegrees = toEigen(eulerAngles).head<3>();
185 const Eigen::Vector3d rotRadians = toRad<double>() * rotDegrees;
186 return computeEulerRotation<double>(rotRadians, rotOrder);
187}
188
189const ofbx::IElement* findChild(const ofbx::IElement& element, const char* id) {
190 auto* curChild = element.getFirstChild();
191 while (curChild) {
192 if (curChild->getID() == id) {
193 return curChild;
194 }
195 curChild = curChild->getSibling();
196 }
197 return nullptr;
198}
199
200bool equalsCaseInsensitive(const ofbx::DataView& data, const char* rhs) {
201 const char* c = rhs;
202 const char* c2 = (const char*)data.begin;
203 while (*c && c2 != (const char*)data.end) {
204 if (tolower(*c) != tolower(*c2)) {
205 return false;
206 }
207 ++c;
208 ++c2;
209 }
210 return c2 == (const char*)data.end && *c == '\0';
211}
212
213bool equalsCaseInsensitive(const std::string& lhs, const char* rhs) {
214 const char* c = rhs;
215 auto it = lhs.begin();
216 while (*c && it != lhs.end()) {
217 if (tolower(static_cast<unsigned char>(*c)) != tolower(static_cast<unsigned char>(*it))) {
218 return false;
219 }
220 ++c;
221 ++it;
222 }
223 return it == lhs.end() && *c == '\0';
224}
225
226// This function is more or less copied from the OpenFBX SDK.
227ofbx::IElement* resolveProperty(const ofbx::Object& object, const char* name) {
228 // This is black magic, but for some reason all the user properties are stored in an
229 // element named Properties70.
230 const ofbx::IElement* props = findChild(object.element, "Properties70");
231 if (!props) {
232 return nullptr;
233 }
234
235 ofbx::IElement* prop = props->getFirstChild();
236 while (prop) {
237 auto* firstProp = prop->getFirstProperty();
239 firstProp->getType() != ofbx::IElementProperty::STRING,
240 "Expected string for first property value but got {}.",
241 propertyTypeStr(firstProp->getType()));
242
243 // The Autodesk SDK appears to be case-insensitive wrt names, so we'll mirror that
244 // behavior here.
245 if (firstProp != nullptr && equalsCaseInsensitive(firstProp->getValue(), name)) {
246 return prop;
247 }
248 prop = prop->getSibling();
249 }
250 return nullptr;
251}
252
253// Get the nth property, needed because elements store properties in the order [name, ?, ?, ?,
254// value].
255const ofbx::IElementProperty* getElementProperty(const ofbx::IElement* element, size_t iProp) {
256 auto* prop = element->getFirstProperty();
257 for (size_t j = 0; j < iProp; ++j) {
258 if (prop == nullptr) {
259 return nullptr;
260 }
261 prop = prop->getNext();
262 }
263
264 return prop;
265}
266
267double resolveDoubleProperty(const ofbx::Object& object, const char* name) {
268 const ofbx::IElement* element = resolveProperty(object, name);
269 MT_THROW_IF(element == nullptr, "Unable to find property element in {}", object.name);
270 const ofbx::IElementProperty* x = getElementProperty(element, 4);
271 MT_THROW_IF(x == nullptr, "Unable to find property {} in {}", name, object.name);
272 if (x->getType() == ofbx::IElementProperty::DOUBLE) {
273 return x->getValue().toDouble();
274 } else if (x->getType() == ofbx::IElementProperty::FLOAT) {
275 return x->getValue().toFloat();
276 } else {
277 MT_THROW(
278 "For property {}, expected float/double but got {}.", name, propertyTypeStr(x->getType()));
279 }
280}
281
282std::string resolveStringProperty(const ofbx::Object& object, const char* name) {
283 const ofbx::IElement* element = resolveProperty(object, name);
284 MT_THROW_IF(element == nullptr, "Unable to find property element in {}", object.name);
285 const ofbx::IElementProperty* x = getElementProperty(element, 4);
286 MT_THROW_IF(x == nullptr, "Unable to find property {} in {}", name, object.name);
287 if (x->getType() == ofbx::IElementProperty::STRING) {
288 const auto& val = x->getValue();
289 const size_t len = val.end - val.begin;
290 std::string result(reinterpret_cast<const char*>(val.begin), len);
291 return result;
292 } else {
293 MT_THROW("For property {}, expected string but got {}.", name, propertyTypeStr(x->getType()));
294 }
295}
296
297template <typename VecArray, typename EltType>
298VecArray extractPropertyArrayImp(const ofbx::IElementProperty* prop, const char* what) {
299 using VecType = typename VecArray::value_type;
300 using Scalar = typename VecType::Scalar;
301
302 const auto nScalar = prop->getCount();
303 if (nScalar == 0) {
304 return VecArray();
305 }
306
307 const auto vecLength = VecType::RowsAtCompileTime;
308 const auto nVec = nScalar / vecLength;
309
311 nVec * vecLength != nScalar,
312 "For {}; expected to be divisible by {} but got {} as count",
313 what,
314 int(vecLength),
315 nScalar);
316
317 std::vector<EltType> vals(nScalar);
318 prop->getValues(vals.data(), (int)(sizeof(EltType) * vals.size()));
319
320 VecArray result;
321 result.reserve(nVec);
322 for (int iVec = 0; iVec < nVec; ++iVec) {
323 VecType v;
324 for (Eigen::DenseIndex k = 0; k < vecLength; ++k) {
325 v[k] = (Scalar)vals[iVec * static_cast<size_t>(vecLength) + k];
326 }
327 result.push_back(v);
328 }
329
330 return result;
331}
332
333template <typename VecArray>
334VecArray extractPropertyVecArray(const ofbx::IElement* element, const char* what) {
335 const auto* prop = element->getFirstProperty();
336 MT_THROW_IF(prop == nullptr, "For element {} found no property.", what);
337 if (prop->getType() == ofbx::IElementProperty::ARRAY_DOUBLE) {
338 return extractPropertyArrayImp<VecArray, double>(prop, what);
339 } else if (prop->getType() == ofbx::IElementProperty::ARRAY_FLOAT) {
340 return extractPropertyArrayImp<VecArray, float>(prop, what);
341 } else {
342 MT_THROW(
343 "For property {} expected float/double array but got {}.",
344 what,
345 propertyTypeStr(prop->getType()));
346 }
347}
348
349template <typename T>
350ofbx::IElementProperty::Type propertyArrayType();
351template <>
352ofbx::IElementProperty::Type propertyArrayType<double>() {
353 return ofbx::IElementProperty::ARRAY_DOUBLE;
354}
355template <>
356ofbx::IElementProperty::Type propertyArrayType<float>() {
357 return ofbx::IElementProperty::ARRAY_FLOAT;
358}
359template <>
360ofbx::IElementProperty::Type propertyArrayType<int>() {
361 return ofbx::IElementProperty::ARRAY_INT;
362}
363
364template <typename T>
365std::vector<T> extractPropertyArray(const ofbx::IElement* element, const char* what) {
366 const auto* prop = element->getFirstProperty();
367 MT_THROW_IF(prop == nullptr, "For element {} found no property.", what);
368 if (prop->getType() == propertyArrayType<T>()) {
369 std::vector<T> vals(prop->getCount());
370 prop->getValues(&vals[0], (int)(sizeof(T) * vals.size()));
371 return vals;
372 } else {
373 MT_THROW(
374 "For property {}, expected {} but got {}.",
375 what,
376 propertyTypeStr(propertyArrayType<T>()),
377 propertyTypeStr(prop->getType()));
378 }
379}
380
381std::vector<double> extractPropertyFloatArray(const ofbx::IElement* element, const char* what) {
382 const auto* prop = element->getFirstProperty();
383 MT_THROW_IF(prop == nullptr, "For element {}, found no property.", what);
384 if (prop->getType() == ofbx::IElementProperty::ARRAY_DOUBLE) {
385 return extractPropertyArray<double>(element, what);
386 } else if (prop->getType() == ofbx::IElementProperty::ARRAY_FLOAT) {
387 auto res = extractPropertyArray<float>(element, what);
388 std::vector<double> result(res.begin(), res.end());
389 return result;
390 } else {
391 MT_THROW(
392 "For property {}, expected float array but got {}.",
393 what,
394 propertyTypeStr(prop->getType()));
395 }
396}
397
398void stripNamespace(const ofbx::Object* obj) {
399 const char* lastColon = std::strrchr(obj->name, ':');
400 if (lastColon) {
401 const char* newName = lastColon + 1;
402 std::memmove(const_cast<char*>(obj->name), newName, std::strlen(newName) + 1);
403 }
404}
405
406void extractCollisionCapsule(const ofbx::Object* node, size_t parent, CollisionGeometry& capsules) {
407 const double length = resolveDoubleProperty(*node, "length");
408 const double rad_a = resolveDoubleProperty(*node, "rad_a");
409 const double rad_b = resolveDoubleProperty(*node, "rad_b");
410
411 const auto xf = node->getLocalTransform();
412
413 TaperedCapsule capsule;
414 capsule.parent = parent;
415 capsule.length = length;
416 capsule.radius = {rad_a, rad_b};
417 capsule.transformation = toEigen(xf).cast<float>();
418 capsules.emplace_back(capsule);
419}
420
421void extractCollisionEllipsoid(
422 const ofbx::Object* node,
423 size_t parent,
424 CollisionGeometry& collisionGeometry) {
425 const double radiusX = resolveDoubleProperty(*node, "radii_x");
426 const double radiusY = resolveDoubleProperty(*node, "radii_y");
427 const double radiusZ = resolveDoubleProperty(*node, "radii_z");
428
429 const auto xf = node->getLocalTransform();
430
431 CollisionEllipsoid ellipsoid;
432 ellipsoid.parent = parent;
433 ellipsoid.radii = Eigen::Vector3f(
434 static_cast<float>(radiusX), static_cast<float>(radiusY), static_cast<float>(radiusZ));
435 ellipsoid.transformation = toEigen(xf).cast<float>();
436 collisionGeometry.emplace_back(ellipsoid);
437}
438
439void extractCollisionBox(
440 const ofbx::Object* node,
441 size_t parent,
442 CollisionGeometry& collisionGeometry) {
443 const double halfExtentsX = resolveDoubleProperty(*node, "half_extents_x");
444 const double halfExtentsY = resolveDoubleProperty(*node, "half_extents_y");
445 const double halfExtentsZ = resolveDoubleProperty(*node, "half_extents_z");
446
447 const auto xf = node->getLocalTransform();
448
449 CollisionBox box;
450 box.parent = parent;
451 box.halfExtents = Eigen::Vector3f(
452 static_cast<float>(halfExtentsX),
453 static_cast<float>(halfExtentsY),
454 static_cast<float>(halfExtentsZ));
455 box.transformation = toEigen(xf).cast<float>();
456 collisionGeometry.emplace_back(box);
457}
458
459void extractCollisionPrimitive(
460 const ofbx::Object* node,
461 size_t parent,
462 CollisionGeometry& collisionGeometry) {
463 auto* shapeProperty = resolveProperty(*node, "col_shape");
464 if (shapeProperty != nullptr) {
465 const std::string shape = resolveStringProperty(*node, "col_shape");
466 if (equalsCaseInsensitive(shape, "ellipsoid") ||
467 equalsCaseInsensitive(shape, "collision_ellipsoid")) {
468 extractCollisionEllipsoid(node, parent, collisionGeometry);
469 return;
470 }
471 if (equalsCaseInsensitive(shape, "box") || equalsCaseInsensitive(shape, "collision_box")) {
472 extractCollisionBox(node, parent, collisionGeometry);
473 return;
474 }
475 if (equalsCaseInsensitive(shape, "tapered_capsule") ||
476 equalsCaseInsensitive(shape, "capsule") ||
477 equalsCaseInsensitive(shape, "collision_capsule")) {
478 extractCollisionCapsule(node, parent, collisionGeometry);
479 return;
480 }
481
482 MT_LOGW(
483 "Unknown FBX collision shape '{}' on node '{}'; falling back to tapered capsule.",
484 shape,
485 node->name);
486 }
487
488 extractCollisionCapsule(node, parent, collisionGeometry);
489}
490
491void extractLocator(const ofbx::Object* node, size_t parent, LocatorList& locators) {
492 Locator locator;
493 locator.name = node->name;
494 const auto translationOffset = node->getLocalTranslation();
495 locator.offset = toEigen(translationOffset).cast<float>();
496 locator.parent = parent;
497 locators.push_back(locator);
498}
499
500void validateAndLogRotation(
501 const ofbx::Object* node,
502 const std::string& jointName,
503 Permissive permissive) {
504 auto order = node->getRotationOrder();
505 if (order != ofbx::RotationOrder::EULER_XYZ) {
506 if (permissive == Permissive::Yes) {
507 MT_LOGW(
508 "momentum supports only XYZ rotation; joint {} has {} rotation order.",
509 jointName,
510 rotationOrderStr(order));
511 } else {
512 MT_THROW(
513 "momentum supports only XYZ rotation; joint {} has {} rotation order.",
514 jointName,
515 rotationOrderStr(order));
516 }
517 }
518}
519
520Eigen::Quaterniond computeLocalRotation(
521 const ofbx::Object* node,
522 const std::string& jointName,
523 Permissive permissive) {
524 auto order = node->getRotationOrder();
525 auto localRot = fbxEulerRotationToQuat(node->getLocalRotation(), order);
526 if (Eigen::AngleAxisd(localRot).angle() > 1e-2) {
527 if (permissive == Permissive::Yes) {
528 MT_LOGW(
529 "{}: Node {} has nonzero rest rotation ({}, {}, {}), which will be baked into the skeleton.",
530 __func__,
531 jointName,
532 node->getLocalRotation().x,
533 node->getLocalRotation().y,
534 node->getLocalRotation().z);
535 } else {
536 MT_LOGE(
537 "{}: Node {} has nonzero rest rotation ({}, {}, {}) and it will be ignored",
538 __func__,
539 jointName,
540 node->getLocalRotation().x,
541 node->getLocalRotation().y,
542 node->getLocalRotation().z);
543 localRot = Eigen::Quaterniond::Identity();
544 }
545 }
546 return localRot;
547}
548
549void parseSkeleton(
550 const ofbx::Object* curSkelNode,
551 const size_t parent,
552 Skeleton& skeleton,
553 std::vector<const ofbx::Object*>& fbxObjects,
554 CollisionGeometry& capsules,
555 LocatorList& locators,
556 Permissive permissive) {
557 MT_CHECK(curSkelNode, "Skeleton node for parent '{}' is null", parent);
558
559 if (!curSkelNode->isNode()) {
560 return;
561 }
562
563 const auto type = curSkelNode->getType();
564 const std::string jointName = curSkelNode->name;
565
566 if (type == ofbx::Object::Type::NULL_NODE) {
567 auto* res = resolveProperty(*curSkelNode, "col_type");
568 if (res != nullptr) {
569 extractCollisionPrimitive(curSkelNode, parent, capsules);
570 } else if (parent != kInvalidIndex) {
571 extractLocator(curSkelNode, parent, locators);
572 } else {
573 int i = 0;
574 while (ofbx::Object* child = curSkelNode->resolveObjectLink(i++)) {
575 parseSkeleton(child, kInvalidIndex, skeleton, fbxObjects, capsules, locators, permissive);
576 }
577 }
578 return;
579 }
580
581 if (type != ofbx::Object::Type::LIMB_NODE) {
582 return;
583 }
584
585 validateAndLogRotation(curSkelNode, jointName, permissive);
586 const Eigen::Quaterniond localRot = computeLocalRotation(curSkelNode, jointName, permissive);
587
588 const auto preRotEuler = curSkelNode->getPreRotation();
589 const Eigen::Quaterniond preRotation =
590 fbxEulerRotationToQuat(preRotEuler, ofbx::RotationOrder::EULER_XYZ) * localRot;
591
593 toEigen(curSkelNode->getPostRotation()).head<3>().norm() > 1e-8,
594 "{}: Node {} has nonzero post-rotation; it will be ignored.",
595 __func__,
596 jointName);
597
598 const auto translationOffset = curSkelNode->getLocalTranslation();
599
600 Joint joint;
601 joint.name = jointName;
602 joint.parent = parent;
603 joint.preRotation = preRotation.cast<float>();
604 joint.translationOffset = toEigen(translationOffset).cast<float>();
605 const size_t jointIndex = skeleton.joints.size();
606 skeleton.joints.push_back(joint);
607 fbxObjects.push_back(curSkelNode);
608
609 int i = 0;
610 while (ofbx::Object* child = curSkelNode->resolveObjectLink(i++)) {
611 parseSkeleton(child, jointIndex, skeleton, fbxObjects, capsules, locators, permissive);
612 }
613}
614
615std::tuple<Skeleton, std::vector<const ofbx::Object*>, LocatorList, CollisionGeometry>
616parseSkeleton(const ofbx::Object* sceneRoot, const std::string& skelRoot, Permissive permissive) {
617 MT_CHECK(sceneRoot, "Scene root with skel root '{}' is null", skelRoot);
618
619 Skeleton skeleton;
620 LocatorList locators;
621 CollisionGeometry collision;
622 std::vector<const ofbx::Object*>
623 jointFbxNodes; // Contains the mapping between FbxNode* and indices in the FbxSkeleton
624
625 int i = 0;
626 while (ofbx::Object* child = sceneRoot->resolveObjectLink(i)) {
627 i++;
628 if (!skelRoot.empty() && child->name != skelRoot) {
629 continue;
630 }
631 parseSkeleton(child, kInvalidIndex, skeleton, jointFbxNodes, collision, locators, permissive);
632 }
633
634 return {skeleton, jointFbxNodes, locators, collision};
635}
636
637// Note: we intentionally omit reserve() here. This function is called once per sub-mesh in a loop,
638// and reserve(size() + batchSize) defeats std::vector's geometric growth, causing O(K*N) copies
639// instead of O(N) amortized. Letting the default 2x growth strategy handle it is more efficient.
640void populatePolyFaceData(
641 Mesh& mesh,
642 const PolygonData& vertices,
643 size_t vertexOffset,
644 size_t textureCoordOffset) {
645 for (const auto& idx : vertices.indices) {
646 mesh.polyFaces.push_back(idx + static_cast<uint32_t>(vertexOffset));
647 }
648 for (size_t i = 0; i + 1 < vertices.offsets.size(); ++i) {
649 mesh.polyFaceSizes.push_back(vertices.offsets[i + 1] - vertices.offsets[i]);
650 }
651 if (!vertices.textureIndices.empty()) {
652 for (const auto& idx : vertices.textureIndices) {
653 mesh.polyTexcoordFaces.push_back(idx + static_cast<uint32_t>(textureCoordOffset));
654 }
655 }
656}
657
658enum EMapping {
659 MappingUnknown,
660 MappingByPolyVertex,
661 MappingByVertex,
662};
663
664enum EReference {
665 RefUnknown,
666 RefIndexToDirect,
667 RefDirect,
668};
669
670std::vector<Eigen::Vector2f>
671parseUVMapping(const ofbx::IElement& geomElement, PolygonData& vertices, size_t nVerts) {
672 std::vector<Eigen::Vector2f> textureCoords;
673 const auto* layer_uv_element = findChild(geomElement, "LayerElementUV");
674 if (layer_uv_element == nullptr) {
675 return textureCoords;
676 }
677
678 const auto* uvs_element = findChild(*layer_uv_element, "UV");
679 if (uvs_element == nullptr || !uvs_element->getFirstProperty()) {
680 MT_LOGE("No UVs found in mesh element.");
681 return textureCoords;
682 }
683
684 EMapping mapping = MappingUnknown;
685 const auto* mapping_element = findChild(*layer_uv_element, "MappingInformationType");
686 if (mapping_element != nullptr && mapping_element->getFirstProperty() != nullptr) {
687 const ofbx::DataView& view = mapping_element->getFirstProperty()->getValue();
688 if (view == "ByPolygonVertex") {
689 mapping = MappingByPolyVertex;
690 } else if (view == "ByVertex" || view == "ByVertice") {
691 mapping = MappingByVertex;
692 }
693 }
695 mapping == MappingUnknown,
696 "Don't currently know how to deal with mapping type that is not 'ByPolygonVertex' or 'ByVertex'.");
697
698 EReference reference = RefUnknown;
699 const auto* reference_element = findChild(*layer_uv_element, "ReferenceInformationType");
700 if (reference_element != nullptr && reference_element->getFirstProperty() != nullptr) {
701 const ofbx::DataView& view = reference_element->getFirstProperty()->getValue();
702 if (view == "IndexToDirect") {
703 reference = RefIndexToDirect;
704 } else if (view == "Direct") {
705 reference = RefDirect;
706 }
707 }
709 reference == RefUnknown,
710 "Don't currently know how to deal with reference type that is not 'IndexToDirect' or 'Direct'.");
711
712 textureCoords = extractPropertyVecArray<std::vector<Eigen::Vector2f>>(uvs_element, "UV");
713
714 if (reference == RefIndexToDirect) {
715 const auto* indices_element = findChild(*layer_uv_element, "UVIndex");
716 MT_THROW_IF(indices_element == nullptr, "Missing indices element.");
717 const auto textureIndices = extractPropertyArray<int>(indices_element, "PolygonVertexIndex");
718
720 textureIndices.size() != vertices.indices.size(),
721 "Mismatch between texture indices size {} and vertex indices size {}.",
722 textureIndices.size(),
723 vertices.indices.size());
724 std::copy(
725 textureIndices.begin(), textureIndices.end(), std::back_inserter(vertices.textureIndices));
726 } else if (reference == RefDirect) {
727 if (mapping == MappingByPolyVertex) {
729 textureCoords.size() != vertices.indices.size(),
730 "Mismatch between 'Direct' texture coord array size {} and vertex indices size {}.",
731 textureCoords.size(),
732 vertices.indices.size());
733 vertices.textureIndices.resize(vertices.indices.size());
734 } else if (mapping == MappingByVertex) {
736 textureCoords.size() != nVerts,
737 "Mismatch between 'Direct' texture coord array size {} and vertex count {}.",
738 textureCoords.size(),
739 nVerts);
740 }
741 std::iota(vertices.textureIndices.begin(), vertices.textureIndices.end(), 0);
742 } else {
743 MT_THROW("UV reading code failed to handle a valid reference type. This is a bug.");
744 }
745
746 for (auto& tc : textureCoords) {
747 tc.y() = 1.0f - tc.y();
748 }
749
750 return textureCoords;
751}
752
753void parseBlendShapes(
754 const ofbx::BlendShape* blendshapes,
755 const std::vector<Eigen::Vector3f>& vertexPositions,
756 size_t vertexOffset,
757 BlendShape_p& blendShape,
758 const Mesh& mesh) {
759 if (!blendShape) {
760 blendShape = std::make_shared<BlendShape>();
761 }
762
763 int newShapes = 0;
764 int numChannels = blendshapes->getBlendShapeChannelCount();
765 for (int c = 0; c < numChannels; ++c) {
766 const auto* channel = blendshapes->getBlendShapeChannel(c);
767 newShapes += channel->getShapeCount();
768 }
769
770 std::vector<std::string> shapeNames = blendShape->getShapeNames();
771 MatrixXf shapes = blendShape->getShapeVectors();
772 const int currentShapes = static_cast<int>(shapes.cols());
773 shapes.conservativeResize(shapes.rows() + vertexPositions.size() * 3, shapes.cols() + newShapes);
774 shapes.bottomRows(vertexPositions.size() * 3) =
775 MatrixXf::Zero(vertexPositions.size() * 3, shapes.cols());
776 shapes.rightCols(newShapes) = MatrixXf::Zero(shapes.rows(), newShapes);
777 shapeNames.resize(shapeNames.size() + newShapes, "");
778
779 int shapeIndex = 0;
780 for (int c = 0; c < numChannels; ++c) {
781 const auto* const channel = blendshapes->getBlendShapeChannel(c);
782 int numShapes = channel->getShapeCount();
783 for (int s = 0; s < numShapes; ++s) {
784 const auto* const shape = channel->getShape(s);
785 int numVertices = shape->getVertexCount();
786 const auto* const shapeV = shape->getVertices();
787 int numIndices = shape->getIndexCount();
788 const auto* const indexV = shape->getIndices();
789 MT_CHECK(numIndices == numVertices);
790 for (int v = 0; v < numVertices; ++v) {
791 MT_THROW_IF(v >= numIndices, "Vertex index {} exceeds numIndices {}", v, numIndices);
792 shapes(vertexOffset * 3 + indexV[v] * 3 + 0, currentShapes + shapeIndex) = shapeV[v].x;
793 shapes(vertexOffset * 3 + indexV[v] * 3 + 1, currentShapes + shapeIndex) = shapeV[v].y;
794 shapes(vertexOffset * 3 + indexV[v] * 3 + 2, currentShapes + shapeIndex) = shapeV[v].z;
795 }
796 MT_CHECK(
797 static_cast<size_t>(currentShapes + shapeIndex) < shapeNames.size(),
798 "Shape index {} out of bounds (shapeNames size: {})",
799 currentShapes + shapeIndex,
800 shapeNames.size());
801 shapeNames[currentShapes + shapeIndex] = shape->name;
802 shapeIndex++;
803 }
804 }
805
806 blendShape->setShapeVectors(shapes, shapeNames);
807 blendShape->setBaseShape(mesh.vertices);
808}
809
810using VertexBoneWithWeight = std::tuple<size_t, size_t, double>;
811
812void collectClusterWeights(
813 const ofbx::Skin* fbxskin,
814 const std::unordered_map<const ofbx::Object*, size_t>& boneMap,
815 TransformationList& inverseBindPoseTransforms,
816 std::vector<VertexBoneWithWeight>& weights,
817 size_t nVerts,
818 const char* meshName) {
819 int clusterCount = fbxskin->getClusterCount();
820 for (int clusterIndex = 0; clusterIndex < clusterCount; clusterIndex++) {
821 const auto* cluster = fbxskin->getCluster(clusterIndex);
822 MT_CHECK(cluster != nullptr);
823
824 const auto* bone = cluster->getLink();
825 const auto fbxJointItr = boneMap.find(bone);
827 fbxJointItr == boneMap.end(),
828 "Cluster {} references invalid bone: {}",
829 cluster->name,
830 bone->name);
831
832 const size_t boneIndex = fbxJointItr->second;
833 if (boneIndex < inverseBindPoseTransforms.size()) {
834 inverseBindPoseTransforms[boneIndex] =
835 toEigen(cluster->getTransformLinkMatrix()).inverse().cast<float>();
836 }
837
838 const auto* skinning_indices_element = findChild(cluster->element, "Indexes");
839 if (skinning_indices_element == nullptr || !skinning_indices_element->getFirstProperty()) {
840 MT_LOGT(
841 "Skipping as no skinning indices found in cluster element {} (mesh is {}).",
842 cluster->name,
843 meshName);
844 continue;
845 }
846
847 const auto skinningIndices = extractPropertyArray<int>(skinning_indices_element, "Indexes");
848
849 const auto* skinning_weights_element = findChild(cluster->element, "Weights");
851 skinning_weights_element == nullptr || !skinning_weights_element->getFirstProperty(),
852 "No skinning weights found in cluster element {} (mesh is {}).",
853 cluster->name,
854 meshName);
855 const auto skinningWeights = extractPropertyFloatArray(skinning_weights_element, "Weights");
856
858 skinningIndices.size() != skinningWeights.size(),
859 "Mismatch between indices count ({}) and weight count ({}) in cluster {}",
860 skinningIndices.size(),
861 skinningWeights.size(),
862 cluster->name);
863
864 const auto numBoneVertexIndices = skinningIndices.size();
865 for (size_t boneVIndex = 0; boneVIndex < numBoneVertexIndices; boneVIndex++) {
866 const int boneVertexIndex = skinningIndices[boneVIndex];
868 boneVertexIndex < 0 || static_cast<size_t>(boneVertexIndex) >= nVerts,
869 "Invalid vertex index ({}) in cluster {}",
870 boneVertexIndex,
871 cluster->name);
872 const auto boneWeight = skinningWeights[boneVIndex];
873 if (boneWeight <= 0) {
874 continue;
875 }
877 boneWeight > 1.01,
878 "{}: Bone weight of {} found; expected value between 0 and 1.",
879 __func__,
880 boneWeight);
881 weights.emplace_back(boneVertexIndex, boneIndex, boneWeight);
882 }
883 }
884}
885
886void assignSkinWeights(
887 std::vector<VertexBoneWithWeight>& weights,
888 std::unique_ptr<SkinWeights>& skinWeights,
889 size_t vertexOffset,
890 size_t nVerts,
891 const char* meshName) {
892 if (!skinWeights) {
893 skinWeights = std::make_unique<SkinWeights>();
894 }
895 skinWeights->index.conservativeResize(vertexOffset + nVerts, Eigen::NoChange);
896 skinWeights->weight.conservativeResize(vertexOffset + nVerts, Eigen::NoChange);
897 skinWeights->index.bottomRows(nVerts).setZero();
898 skinWeights->weight.bottomRows(nVerts).setZero();
899
900 std::stable_sort(
901 weights.begin(),
902 weights.end(),
903 [](const VertexBoneWithWeight& b1, const VertexBoneWithWeight& b2) {
904 return std::get<0>(b1) < std::get<0>(b2);
905 });
906 auto weightItr = weights.begin();
907
908 using BoneWeight = std::pair<size_t, double>;
909 std::vector<BoneWeight> curBoneWeights;
910
911 for (size_t iVertex = 0; iVertex < nVerts; ++iVertex) {
912 curBoneWeights.clear();
914 weightItr == weights.end() || std::get<0>(*weightItr) != iVertex,
915 "No weights found for vertex {} in mesh {}",
916 iVertex,
917 meshName);
918
919 auto vertWeightsBegin = weightItr;
920 while (weightItr != weights.end() && std::get<0>(*weightItr) == iVertex) {
921 ++weightItr;
922 }
923 auto vertWeightsEnd = weightItr;
924
925 for (auto itr = vertWeightsBegin; itr != vertWeightsEnd; ++itr) {
926 const auto boneIndex = std::get<1>(*itr);
927 const auto boneWeight = std::clamp(std::get<2>(*itr), 0.0, 1.0);
928 curBoneWeights.emplace_back(boneIndex, boneWeight);
929 }
930
931 std::stable_sort(
932 curBoneWeights.begin(),
933 curBoneWeights.end(),
934 [](const BoneWeight& b1, const BoneWeight& b2) { return b1.second > b2.second; });
935 curBoneWeights.resize(std::min<size_t>(curBoneWeights.size(), kMaxSkinJoints));
936
937 double weightSum = 0;
938 for (const auto& [idx, weight] : curBoneWeights) {
939 weightSum += weight;
940 }
941
943 weightSum <= 0, "Empty weight sum found for vertex {} in mesh {}", iVertex, meshName);
944
945 for (int iPr = 0; iPr < curBoneWeights.size() && iPr < kMaxSkinJoints; ++iPr) {
946 // NOLINTNEXTLINE(facebook-hte-LocalUncheckedArrayBounds)
947 const auto [boneIdx, weight] = curBoneWeights[iPr];
948 skinWeights->index(vertexOffset + iVertex, iPr) = static_cast<uint32_t>(boneIdx);
949 skinWeights->weight(vertexOffset + iVertex, iPr) = weight / weightSum;
950 }
951 }
952}
953
954void parseSkinnedModel(
955 const ofbx::Mesh* meshRoot,
956 const std::vector<const ofbx::Object*>& boneFbxNodes,
957 Mesh& mesh,
958 std::unique_ptr<SkinWeights>& skinWeights,
959 TransformationList& inverseBindPoseTransforms,
960 BlendShape_p& blendShape,
961 Permissive permissive,
962 LoadBlendShapes loadBlendShapes) {
963 const auto* geometry = meshRoot->getGeometry();
964 const auto& geomElement = geometry->element;
965
966 const auto* vertices_element = findChild(geomElement, "Vertices");
968 vertices_element == nullptr || !vertices_element->getFirstProperty(),
969 "No vertices found in mesh element.");
970 const auto vertexPositions =
971 extractPropertyVecArray<std::vector<Eigen::Vector3f>>(vertices_element, "Vertices");
972 const auto nVerts = vertexPositions.size();
973
974 const auto* polys_element = findChild(geomElement, "PolygonVertexIndex");
976 polys_element == nullptr || !polys_element->getFirstProperty(),
977 "No polygons found in mesh element.");
978 const auto indices = extractPropertyArray<int>(polys_element, "PolygonVertexIndex");
979
980 PolygonData vertices;
981 vertices.indices.reserve(indices.size());
982 for (const auto& i : indices) {
983 if (i < 0) {
984 vertices.indices.push_back(-(i + 1));
985 vertices.offsets.push_back((uint32_t)vertices.indices.size());
986 } else {
987 vertices.indices.push_back(i);
988 }
989 }
990
991 std::vector<Eigen::Vector2f> textureCoords = parseUVMapping(geomElement, vertices, nVerts);
992
993 auto errMsg = vertices.errorMessage(nVerts);
994 MT_THROW_IF(!errMsg.empty(), "Error reading polygons from FBX file: {}", errMsg);
995 errMsg = vertices.warnMessage(textureCoords.size());
996 MT_LOGW_IF(!errMsg.empty(), "Error reading polygon data from FBX file: {}", errMsg);
997
998 const size_t vertexOffset = mesh.vertices.size();
999 std::copy(
1000 std::begin(vertexPositions), std::end(vertexPositions), std::back_inserter(mesh.vertices));
1001 for (const auto& t : triangulate(vertices.indices, vertices.offsets)) {
1002 mesh.faces.emplace_back(t + Eigen::Vector3i::Constant(static_cast<int>(vertexOffset)));
1003 }
1004
1005 mesh.normals.resize(vertexOffset + nVerts, Vector3f::Zero());
1006 mesh.colors.resize(vertexOffset + nVerts, Vector3b::Constant(255));
1007 mesh.confidence.resize(vertexOffset + nVerts, 1);
1008
1009 const size_t textureCoordOffset = mesh.texcoords.size();
1010 std::copy(std::begin(textureCoords), std::end(textureCoords), std::back_inserter(mesh.texcoords));
1011 for (const auto& t : triangulate(vertices.textureIndices, vertices.offsets)) {
1012 mesh.texcoord_faces.emplace_back(
1013 t + Eigen::Vector3i::Constant(static_cast<int>(textureCoordOffset)));
1014 }
1015
1016 // Populate polygon face data (preserves original topology)
1017 populatePolyFaceData(mesh, vertices, vertexOffset, textureCoordOffset);
1018
1019 const auto* blendshapes = geometry->getBlendShape();
1020 if (loadBlendShapes == LoadBlendShapes::Yes && blendshapes) {
1021 parseBlendShapes(blendshapes, vertexPositions, vertexOffset, blendShape, mesh);
1022 }
1023
1024 const auto* fbxskin = geometry->getSkin();
1025 if (!fbxskin) {
1027 permissive == Permissive::No,
1028 "No skin found for geometry. Enable permissive mode to allow saving as a mesh-only character.");
1029 return;
1030 }
1031
1032 std::unordered_map<const ofbx::Object*, size_t> boneMap;
1033 for (size_t i = 0; i < boneFbxNodes.size(); ++i) {
1034 boneMap.insert(std::make_pair(boneFbxNodes[i], i));
1035 }
1036
1037 std::vector<VertexBoneWithWeight> weights;
1038 weights.reserve(2 * nVerts);
1039 collectClusterWeights(
1040 fbxskin, boneMap, inverseBindPoseTransforms, weights, nVerts, meshRoot->name);
1041 assignSkinWeights(weights, skinWeights, vertexOffset, nVerts, meshRoot->name);
1042}
1043
1044double getMaxSeconds(const std::vector<const ofbx::AnimationCurveNode*>& curves) {
1045 ofbx::i64 fbxTime = 0;
1046 for (const ofbx::AnimationCurveNode* node : curves) {
1047 for (int iChannel = 0; iChannel < 3; ++iChannel) {
1048 const ofbx::AnimationCurve* channel = node->getCurve(iChannel);
1049 if (channel == nullptr) {
1050 continue;
1051 }
1052 const int count = channel->getKeyCount();
1053 if (count <= 0) {
1054 continue;
1055 }
1056 const ofbx::i64* time = channel->getKeyTime();
1057 if (time[count - 1] > fbxTime) {
1058 fbxTime = time[count - 1];
1059 }
1060 }
1061 }
1062 return ofbx::fbxTimeToSeconds(fbxTime);
1063}
1064
1065size_t findJointIndex(
1066 const ofbx::Object* queryObj,
1067 const std::vector<const ofbx::Object*>& fbxNodes) {
1068 size_t result = kInvalidIndex;
1069 for (size_t iNode = 0; iNode < fbxNodes.size(); ++iNode) {
1070 if (queryObj == fbxNodes[iNode]) {
1071 result = iNode;
1072 break;
1073 }
1074 }
1075
1076 return result;
1077}
1078
1079MatrixXf parseAnimation(
1080 const ofbx::AnimationStack* animStack,
1081 const std::vector<const ofbx::Object*>& boneFbxNodes,
1082 const Skeleton& skeleton,
1083 const float fps,
1084 Permissive permissive) {
1085 // Return motion in numJointParameters X numFrames
1086 MatrixXf motion;
1087 std::vector<const ofbx::AnimationCurveNode*> skeletonAnimCurves;
1088
1089 // Collect animation curves only for skeleton joints (not markers)
1090 int iLayer = 0;
1091 while (const ofbx::AnimationLayer* animLayer = animStack->getLayer(iLayer++)) {
1092 int iCurve = 0;
1093 while (const ofbx::AnimationCurveNode* curve = animLayer->getCurveNode(iCurve++)) {
1094 // Only collect curves that belong to skeleton joints
1095 const ofbx::Object* bone = curve->getBone();
1096 if (!bone) {
1097 continue;
1098 }
1099
1100 for (const ofbx::Object* jointNode : boneFbxNodes) {
1101 if (bone == jointNode) {
1102 skeletonAnimCurves.push_back(curve);
1103 break;
1104 }
1105 }
1106 }
1107 }
1108 if (skeletonAnimCurves.empty()) {
1109 return {};
1110 }
1111
1112 const double totalSeconds = getMaxSeconds(skeletonAnimCurves);
1113 const size_t numFrames = ceil(totalSeconds * fps) + 1;
1114 motion.setZero(skeleton.joints.size() * kParametersPerJoint, numFrames);
1115
1117 boneFbxNodes.size() < skeleton.joints.size(),
1118 "boneFbxNodes size {} is less than skeleton joints size {}",
1119 boneFbxNodes.size(),
1120 skeleton.joints.size());
1121 for (size_t i = 0; i < skeleton.joints.size(); ++i) {
1122 // Load the rest pose into the animation; for channels that aren't animated, Maya
1123 // won't export a curve node and so this is the only way to get the rest pose set
1124 // up correctly.
1125 // Note that the rest translation is already baked into the translationOffset in
1126 // the skeleton so we don't want to set it here.
1127 if (permissive == Permissive::No) {
1128 // Local rotation is Euler angles:
1129 const auto localRot = boneFbxNodes[i]->getLocalRotation();
1130 motion.row(i * kParametersPerJoint + 3).setConstant(toRad(localRot.x));
1131 motion.row(i * kParametersPerJoint + 4).setConstant(toRad(localRot.y));
1132 motion.row(i * kParametersPerJoint + 5).setConstant(toRad(localRot.z));
1133 }
1134 motion.row(i * kParametersPerJoint + 6)
1135 .setConstant(std::log2(boneFbxNodes[i]->getLocalScaling().x));
1136 }
1137
1138 std::vector<bool> writtenJoints(skeleton.joints.size() * kParametersPerJoint, false);
1139
1140 // Curves on the same node will be added together.
1141 for (const ofbx::AnimationCurveNode* curveNode : skeletonAnimCurves) {
1142 // Find the skeleton joint
1143 const size_t jointIndex = findJointIndex(curveNode->getBone(), boneFbxNodes);
1144 if (jointIndex == kInvalidIndex) {
1145 continue;
1146 }
1147 // Find out which channels
1148 const auto& property = curveNode->getBoneLinkProperty();
1149 int mode = -1;
1150 if (property == "Lcl Translation") {
1151 mode = 0;
1152 } else if (property == "Lcl Rotation") {
1153 mode = 1;
1154 } else if (property == "Lcl Scaling") {
1155 mode = 2;
1156 } else {
1157 continue;
1158 }
1159 // Find the indices to write to
1160 const size_t startIndex = jointIndex * kParametersPerJoint + mode * 3;
1161 const size_t endIndex = startIndex + ((mode == 2) ? 1 : 3);
1162 for (size_t i = startIndex; i < endIndex; ++i) {
1163 if (writtenJoints.at(i)) {
1164 // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays)
1165 char propertyName[128];
1166 property.toString(propertyName);
1167 MT_LOGW(
1168 "Multiple curves affecting the same parameter {} in {}",
1169 propertyName,
1170 curveNode->getBone()->name);
1171 }
1172
1173 writtenJoints.at(i) = true;
1174 }
1175
1176 // Linear interpolation of the curve on timeline
1177 for (size_t iFrame = 0; iFrame < numFrames; ++iFrame) {
1178 const ofbx::DVec3 values =
1179 curveNode->getNodeLocalTransform(static_cast<double>(iFrame) / fps);
1180
1181 // Aggregate the motion
1182 if (mode == 0) {
1183 // FBX unit is default to centimeter - the same as Momentum unit
1184 if (jointIndex < skeleton.joints.size()) {
1185 motion.col(iFrame).template segment<3>(startIndex).noalias() =
1186 toEigen(values).cast<float>() - skeleton.joints[jointIndex].translationOffset;
1187 }
1188 } else if (mode == 1) {
1189 // assume the correct rotation order
1190 motion.col(iFrame).template segment<3>(startIndex).noalias() =
1191 toRad() * toEigen(values).cast<float>();
1192 } else if (mode == 2) {
1193 float scale = 1.0;
1194 // Warn and average if non-uniform scale
1195 const float kMaxScaleDiff = 1e-4;
1196 if (std::abs(values.x - values.y) > kMaxScaleDiff ||
1197 std::abs(values.x - values.z) > kMaxScaleDiff) {
1198 MT_LOGW(
1199 "Animation has non-uniform scale, which is not supported: ({}, {}, {})",
1200 values.x,
1201 values.y,
1202 values.z);
1203 scale = (values.x + values.y + values.z) / 3.0;
1204 } else {
1205 scale = values.x;
1206 }
1207 // XXX not sure how to handle layers of scaling; we don't assume to support this case for
1208 // now.
1209 motion.col(iFrame)[startIndex] = std::log2(scale);
1210 }
1211 }
1212 }
1213 return motion;
1214}
1215
1216std::vector<ofbx::u8> readFileToBuffer(const filesystem::path& path) {
1217 // The FBX SDK returns a confusing error if the file doesn't actually
1218 // exist, so we should trap that case and return a more helpful error instead.
1219 std::ifstream ifs(path.string(), std::ios::binary | std::ios::ate);
1220 MT_THROW_IF(!ifs.good(), "Error reading FBX file from {}", path.string());
1221
1222 auto length = ifs.tellg();
1223 ifs.seekg(0, std::ifstream::beg);
1224
1225 MT_THROW_IF(length > INT32_MAX, "File too large for OpenFBX.");
1226
1227 std::vector<ofbx::u8> buffer(length);
1228 ifs.read(reinterpret_cast<char*>(buffer.data()), length);
1229 MT_THROW_IF(!ifs.good(), "Error reading the entire FBX file from {}", path.string());
1230
1231 return buffer;
1232}
1233
1234// Parse marker sequence from FBX animation data
1236parseMarkerSequence(const ofbx::IScene* scene, const ofbx::Object* root, const float fps) {
1237 MarkerSequence result;
1238 result.fps = fps;
1239
1240 if (!scene || scene->getAnimationStackCount() == 0) {
1241 return result;
1242 }
1243
1244 // Find the "Markers" node in the scene hierarchy
1245 const ofbx::Object* markersRoot = nullptr;
1246 std::function<const ofbx::Object*(const ofbx::Object*)> findMarkersRoot =
1247 [&](const ofbx::Object* node) -> const ofbx::Object* {
1248 if (!node) {
1249 return nullptr;
1250 }
1251
1252 if (std::string(node->name) == "Markers") {
1253 // Check if this is a Momentum markers root by looking for the custom property
1254 auto* markerRootProp = resolveProperty(*node, kMomentumMarkersRootProperty);
1255 if (markerRootProp) {
1256 return node;
1257 }
1258 }
1259
1260 int childIndex = 0;
1261 while (const ofbx::Object* child = node->resolveObjectLink(childIndex++)) {
1262 if (const auto* found = findMarkersRoot(child)) {
1263 return found;
1264 }
1265 }
1266 return nullptr;
1267 };
1268
1269 markersRoot = findMarkersRoot(root);
1270 if (!markersRoot) {
1271 // Return empty sequence with no frames
1272 return result;
1273 }
1274
1275 // Collect marker nodes (children of Markers root)
1276 // Only include nodes with the Momentum_Marker custom property
1277 std::vector<const ofbx::Object*> markerNodes;
1278 std::vector<std::string> markerNames;
1279 int childIndex = 0;
1280 while (const ofbx::Object* child = markersRoot->resolveObjectLink(childIndex++)) {
1281 // Check if this is a Momentum marker by looking for the custom property
1282 auto* markerProp = resolveProperty(*child, kMomentumMarkerProperty);
1283 if (markerProp) {
1284 markerNodes.push_back(child);
1285 markerNames.emplace_back(child->name);
1286 }
1287 }
1288
1289 if (markerNodes.empty()) {
1290 // Return empty sequence with no frames
1291 return result;
1292 }
1293
1294 // Get animation data for all marker nodes
1295 const ofbx::AnimationStack* animStack = scene->getAnimationStack(0);
1296 if (!animStack) {
1297 // Return empty sequence with no frames
1298 return result;
1299 }
1300
1301 // Collect animation curves only for marker nodes
1302 std::vector<const ofbx::AnimationCurveNode*> markerAnimCurves;
1303 int iLayer = 0;
1304 while (const ofbx::AnimationLayer* animLayer = animStack->getLayer(iLayer++)) {
1305 int iCurve = 0;
1306 while (const ofbx::AnimationCurveNode* curve = animLayer->getCurveNode(iCurve++)) {
1307 // Only collect curves that belong to marker nodes
1308 const ofbx::Object* bone = curve->getBone();
1309 if (bone) {
1310 for (const ofbx::Object* markerNode : markerNodes) {
1311 if (bone == markerNode) {
1312 markerAnimCurves.push_back(curve);
1313 break;
1314 }
1315 }
1316 }
1317 }
1318 }
1319
1320 if (markerAnimCurves.empty()) {
1321 // Return empty sequence with no frames
1322 return result;
1323 }
1324
1325 // Determine the total number of frames based on marker animation only
1326 const double totalSeconds = getMaxSeconds(markerAnimCurves);
1327 const size_t numFrames = std::ceil(totalSeconds * fps) + 1;
1328 result.frames.resize(numFrames);
1329
1330 // Parse animation curves for each marker
1331 for (size_t markerIndex = 0; markerIndex < markerNodes.size(); ++markerIndex) {
1332 const ofbx::Object* markerNode = markerNodes.at(markerIndex);
1333 const std::string& markerName = markerNames.at(markerIndex);
1334
1335 // Find animation curves for this marker's translation
1336 const ofbx::AnimationCurveNode* translationCurve = nullptr;
1337 for (const ofbx::AnimationCurveNode* curveNode : markerAnimCurves) {
1338 if (curveNode->getBone() == markerNode) {
1339 const auto& property = curveNode->getBoneLinkProperty();
1340 if (property == "Lcl Translation") {
1341 translationCurve = curveNode;
1342 break;
1343 }
1344 }
1345 }
1346
1347 if (translationCurve) {
1348 // Get the individual animation curves for X, Y, Z components
1349 const ofbx::AnimationCurve* curveX = translationCurve->getCurve(0);
1350 const ofbx::AnimationCurve* curveY = translationCurve->getCurve(1);
1351 const ofbx::AnimationCurve* curveZ = translationCurve->getCurve(2);
1352
1353 // Collect all unique keyframe times from all three curves
1354 std::set<ofbx::i64> keyframeTimes;
1355 if (curveX) {
1356 const int keyCount = curveX->getKeyCount();
1357 const ofbx::i64* times = curveX->getKeyTime();
1358 for (int i = 0; i < keyCount; ++i) {
1359 keyframeTimes.insert(times[i]);
1360 }
1361 }
1362 if (curveY) {
1363 const int keyCount = curveY->getKeyCount();
1364 const ofbx::i64* times = curveY->getKeyTime();
1365 for (int i = 0; i < keyCount; ++i) {
1366 keyframeTimes.insert(times[i]);
1367 }
1368 }
1369 if (curveZ) {
1370 const int keyCount = curveZ->getKeyCount();
1371 const ofbx::i64* times = curveZ->getKeyTime();
1372 for (int i = 0; i < keyCount; ++i) {
1373 keyframeTimes.insert(times[i]);
1374 }
1375 }
1376
1377 // Add markers only at frames where keyframes exist
1378 for (const ofbx::i64 fbxTime : keyframeTimes) {
1379 const double timeInSeconds = ofbx::fbxTimeToSeconds(fbxTime);
1380 const size_t frameIndex = std::round(timeInSeconds * fps);
1381
1382 // Skip if frame index is out of bounds
1383 if (frameIndex >= numFrames) {
1384 continue;
1385 }
1386
1387 // Evaluate position at this keyframe time
1388 const ofbx::DVec3 position = translationCurve->getNodeLocalTransform(timeInSeconds);
1389
1390 Marker marker;
1391 marker.name = markerName;
1392 marker.pos = toEigen(position);
1393 marker.occluded = false;
1394
1395 result.frames[frameIndex].push_back(marker);
1396 }
1397 }
1398 }
1399
1400 return result;
1401}
1402
1403std::tuple<Character, std::vector<MatrixXf>, float> loadOpenFbx(
1404 const std::span<const std::byte> inputData,
1405 KeepLocators keepLocators,
1406 bool loadAnim,
1407 Permissive permissive,
1408 LoadBlendShapes loadBlendShapes,
1409 bool stripNamespaces) {
1410 auto fbxCharDataRaw = cast_span<const unsigned char>(inputData);
1411 const size_t length = fbxCharDataRaw.size();
1412 MT_THROW_IF(length > INT32_MAX, "File too large for OpenFBX.");
1413
1414 auto ofbx_deleter = [](ofbx::IScene* s) { s->destroy(); };
1415 // We don't currently use blend shapes for anything and they can be very
1416 // expensive to load. Ignore stuff in the scene that we don't support.
1417 auto loadFlags = ofbx::LoadFlags::IGNORE_CAMERAS | ofbx::LoadFlags::IGNORE_LIGHTS |
1418 ofbx::LoadFlags::IGNORE_VIDEOS | ofbx::LoadFlags::IGNORE_MATERIALS;
1419 if (loadBlendShapes == LoadBlendShapes::No) {
1420 loadFlags |= ofbx::LoadFlags::IGNORE_BLEND_SHAPES;
1421 }
1422 if (!loadAnim) {
1423 loadFlags |= ofbx::LoadFlags::IGNORE_ANIMATIONS;
1424 }
1425 std::unique_ptr<ofbx::IScene, decltype(ofbx_deleter)> scene(
1426 ofbx::load(fbxCharDataRaw.data(), static_cast<int32_t>(length), (ofbx::u16)loadFlags),
1427 ofbx_deleter);
1428 MT_THROW_IF(!scene, "Error reading FBX scene data. Error: {}", ofbx::getError());
1429 MT_THROW_IF(!scene->getRoot(), "FBX scene has no root node. Error: {}", ofbx::getError());
1430
1431 if (stripNamespaces) {
1432 // Strip all namespaces from all node names in the scene
1433 for (int i = 0; i < scene->getAllObjectCount(); ++i) {
1434 const ofbx::Object* obj = scene->getAllObjects()[i];
1435 if (obj && obj->name[0] != '\0') {
1436 stripNamespace(obj);
1437 }
1438 }
1439 }
1440
1441 const auto [skeleton, jointFbxNodes, locators, collision] =
1442 parseSkeleton(scene->getRoot(), {}, permissive);
1443
1444 std::string name;
1445 std::string metadata = "{}"; // empty json string
1446 if (!jointFbxNodes.empty()) {
1447 auto* resName = resolveProperty(*jointFbxNodes[0], "name");
1448 if (resName != nullptr) {
1449 name = resolveStringProperty(*jointFbxNodes[0], "name");
1450 }
1451 auto* resMeta = resolveProperty(*jointFbxNodes[0], "metadata");
1452 if (resMeta != nullptr) {
1453 metadata = resolveStringProperty(*jointFbxNodes[0], "metadata");
1454 }
1455 }
1456 // ensure metadata is valid JSON
1457 try {
1458 auto json = nlohmann::json::parse(metadata);
1459 } catch (const nlohmann::json::parse_error& e) {
1460 MT_LOGW("Failed to parse metadata: {}", e.what());
1461 }
1462
1463 TransformationList inverseBindPoseTransforms;
1464 for (const auto& j : jointFbxNodes) {
1465 Eigen::Affine3d mat = Eigen::Affine3d::Identity();
1466 if (j) {
1467 mat = toEigen(j->getGlobalTransform());
1468 }
1469 inverseBindPoseTransforms.push_back(mat.inverse().cast<float>());
1470 }
1471
1472 Mesh mesh;
1473 std::unique_ptr<SkinWeights> skinWeights;
1474 BlendShape_p blendShape;
1475
1476 for (int iMesh = 0; iMesh < scene->getMeshCount(); ++iMesh) {
1477 parseSkinnedModel(
1478 scene->getMesh(iMesh),
1479 jointFbxNodes,
1480 mesh,
1481 skinWeights,
1482 inverseBindPoseTransforms,
1483 blendShape,
1484 permissive,
1485 loadBlendShapes);
1486 }
1487 mesh.updateNormals();
1488
1489 std::vector<MatrixXf> jointParamMotions;
1490 if (loadAnim) {
1491 for (int iAnim = 0; iAnim < scene->getAnimationStackCount(); ++iAnim) {
1492 const ofbx::AnimationStack* stack = scene->getAnimationStack(iAnim);
1493 if (stack != nullptr) {
1494 jointParamMotions.emplace_back(
1495 parseAnimation(stack, jointFbxNodes, skeleton, scene->getSceneFrameRate(), permissive));
1496 }
1497 }
1498 }
1499
1500 Character result(
1501 skeleton,
1502 ParameterTransform::empty(skeleton.joints.size() * kParametersPerJoint),
1504 keepLocators == KeepLocators::Yes ? locators : LocatorList(),
1505 &mesh,
1506 skinWeights.get(),
1507 collision.empty() ? nullptr : &collision,
1508 nullptr,
1509 blendShape,
1510 {}, // faceExpressionBlendShapes
1511 name, // nameIn
1512 {}, // inverseBindPose
1513 {}, // skinnedLocators
1514 metadata);
1515 result.resetJointMap();
1516 result.inverseBindPose = inverseBindPoseTransforms;
1517 result.physicalProperties = loadPhysicalPropertiesFromNodes(result.skeleton, jointFbxNodes);
1518
1519 return {result, jointParamMotions, scene->getSceneFrameRate()};
1520}
1521
1522} // namespace
1523
1525 const std::span<const std::byte> inputData,
1526 KeepLocators keepLocators,
1527 Permissive permissive,
1528 LoadBlendShapes loadBlendShapes,
1529 bool stripNamespaces) {
1530 auto [character, motion, fps] =
1531 loadOpenFbx(inputData, keepLocators, false, permissive, loadBlendShapes, stripNamespaces);
1532 return character;
1533}
1534
1536 const filesystem::path& path,
1537 KeepLocators keepLocators,
1538 Permissive permissive,
1539 LoadBlendShapes loadBlendShapes,
1540 bool stripNamespaces) {
1541 auto buffer = readFileToBuffer(path);
1542 return loadOpenFbxCharacter(
1543 gsl::as_bytes(gsl::make_span(buffer)),
1544 keepLocators,
1545 permissive,
1546 loadBlendShapes,
1547 stripNamespaces);
1548}
1549
1550std::tuple<Character, std::vector<MatrixXf>, float> loadOpenFbxCharacterWithMotion(
1551 std::span<const std::byte> inputData,
1552 KeepLocators keepLocators,
1553 Permissive permissive,
1554 LoadBlendShapes loadBlendShapes,
1555 bool stripNamespaces) {
1556 return loadOpenFbx(inputData, keepLocators, true, permissive, loadBlendShapes, stripNamespaces);
1557}
1558
1559std::tuple<Character, std::vector<MatrixXf>, float> loadOpenFbxCharacterWithMotion(
1560 const filesystem::path& inputPath,
1561 KeepLocators keepLocators,
1562 Permissive permissive,
1563 LoadBlendShapes loadBlendShapes,
1564 bool stripNamespaces) {
1565 auto buffer = readFileToBuffer(inputPath);
1567 gsl::as_bytes(gsl::make_span(buffer)),
1568 keepLocators,
1569 permissive,
1570 loadBlendShapes,
1571 stripNamespaces);
1572}
1573
1575 std::span<const std::byte> inputData,
1576 bool stripNamespaces) {
1577 auto fbxCharDataRaw = cast_span<const unsigned char>(inputData);
1578 const size_t length = fbxCharDataRaw.size();
1579 MT_THROW_IF(length > INT32_MAX, "File too large for OpenFBX.");
1580
1581 auto ofbx_deleter = [](ofbx::IScene* s) { s->destroy(); };
1582 // We don't currently use blend shapes for anything and they can be very
1583 // expensive to load. Ignore stuff in the scene that we don't support.
1584 auto loadFlags = ofbx::LoadFlags::IGNORE_CAMERAS | ofbx::LoadFlags::IGNORE_LIGHTS |
1585 ofbx::LoadFlags::IGNORE_VIDEOS | ofbx::LoadFlags::IGNORE_MATERIALS |
1586 ofbx::LoadFlags::IGNORE_BLEND_SHAPES;
1587
1588 std::unique_ptr<ofbx::IScene, decltype(ofbx_deleter)> scene(
1589 ofbx::load(fbxCharDataRaw.data(), static_cast<int32_t>(length), (ofbx::u16)loadFlags),
1590 ofbx_deleter);
1591 MT_THROW_IF(!scene, "Error reading FBX scene data. Error: {}", ofbx::getError());
1592 MT_THROW_IF(!scene->getRoot(), "FBX scene has no root node. Error: {}", ofbx::getError());
1593
1594 if (stripNamespaces) {
1595 // Strip all namespaces from all node names in the scene
1596 for (int i = 0; i < scene->getAllObjectCount(); ++i) {
1597 const ofbx::Object* obj = scene->getAllObjects()[i];
1598 if (obj && obj->name[0] != '\0') {
1599 stripNamespace(obj);
1600 }
1601 }
1602 }
1603
1604 return parseMarkerSequence(scene.get(), scene->getRoot(), scene->getSceneFrameRate());
1605}
1606
1607MarkerSequence loadOpenFbxMarkerSequence(const filesystem::path& filename, bool stripNamespaces) {
1608 auto buffer = readFileToBuffer(filename);
1609 return loadOpenFbxMarkerSequence(gsl::as_bytes(gsl::make_span(buffer)), stripNamespaces);
1610}
1611
1612} // 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
#define MT_LOGE_IF(condition,...)
Definition log.h:187
#define MT_LOGW(...)
Definition log.h:180
#define MT_LOGE(...)
Definition log.h:181
#define MT_LOGT(...)
Definition log.h:177
#define MT_LOGW_IF(condition,...)
Definition log.h:186
std::span< T > cast_span(std::span< std::byte > bs)
Casts a span of bytes to a span of a different type.
Definition gsl_utils.h:26
CollisionGeometryT< float > CollisionGeometry
SkeletonT< float > Skeleton
Definition fwd.h:263
CollisionEllipsoidT< float > CollisionEllipsoid
Definition fwd.h:168
constexpr const char * kMomentumMarkersRootProperty
std::vector< Affine3f > TransformationList
One affine transform per joint, indexed by joint id.
Definition types.h:410
std::vector< ParameterLimit > ParameterLimits
MeshT< float > Mesh
Definition fwd.h:20
std::tuple< Character, std::vector< MatrixXf >, float > loadOpenFbxCharacterWithMotion(std::span< const std::byte > inputData, KeepLocators keepLocators, Permissive permissive, LoadBlendShapes loadBlendShapes, bool stripNamespaces)
::std::shared_ptr< BlendShape > BlendShape_p
Definition fwd.h:20
MarkerSequence loadOpenFbxMarkerSequence(std::span< const std::byte > inputData, bool stripNamespaces)
Load a MarkerSequence from an in-memory FBX byte buffer.
Character loadOpenFbxCharacter(const std::span< const std::byte > inputData, KeepLocators keepLocators, Permissive permissive, LoadBlendShapes loadBlendShapes, bool stripNamespaces)
constexpr T toRad(T x=T(1)) noexcept
Converts the given angle x (in degrees) to radians.
Definition constants.h:68
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.
std::vector< JointPhysicalProperties > PhysicalProperties
Optional physical mass properties for a character.
Definition joint.h:114
CollisionBoxT< float > CollisionBox
Definition fwd.h:187
std::vector< Eigen::Vector3i > triangulate(std::span< const uint32_t > indices, std::span< const uint32_t > offsets)
constexpr size_t kParametersPerJoint
Definition types.h:21
JointT< float > Joint
Definition fwd.h:206
LoadBlendShapes
Definition fbx_io.h:26
KeepLocators
Definition fbx_io.h:23
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
constexpr const char * kMomentumMarkerProperty
TaperedCapsuleT< float > TaperedCapsule
Definition fwd.h:320
constexpr uint32_t kMaxSkinJoints
Maximum number of joints that can influence a single vertex.
MatrixX< float > MatrixXf
Definition types.h:82
std::vector< Locator > LocatorList
A collection of locators attached to a skeleton.
Definition locator.h:79
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
Represents a point attached to a joint in a skeleton.
Definition locator.h:19
std::string name
Definition locator.h:20
All frames from a single motion capture sequence for one subject (actor).
Definition marker.h:37
float fps
Frame rate of the capture, in frames per second.
Definition marker.h:45
A single motion capture marker observation (position, occlusion, confidence).
Definition marker.h:18
std::string name
The name of the marker.
Definition marker.h:20
static ParameterTransformT< float > empty(size_t nJointParameters)
std::vector< uint32_t > indices