48nlohmann::json getMomentumExtension(
const nlohmann::json& extensionsAndExtras) {
49 if (extensionsAndExtras.count(
"extensions") != 0 &&
50 extensionsAndExtras[
"extensions"].count(
"FB_momentum") != 0) {
51 return extensionsAndExtras[
"extensions"][
"FB_momentum"];
53 return nlohmann::json::object();
57void loadGlobalExtensions(
const fx::gltf::Document& model,
Character& character) {
60 const auto& def = getMomentumExtension(model.extensionsAndExtras);
62 if (def.count(
"transform") > 0) {
68 if (def.count(
"parameterSet") > 0) {
72 if (def.count(
"poseConstraints") > 0) {
76 if (def.count(
"parameterLimits") > 0) {
79 if (def.count(
"metadata") > 0) {
80 character.
metadata = def.value<std::string>(
"metadata", {});
83 auto json = nlohmann::json::parse(character.
metadata);
84 }
catch (
const nlohmann::json::parse_error& e) {
85 MT_LOGW(
"Failed to parse metadata: {}", e.what());
88 }
catch (std::runtime_error& err) {
89 MT_THROW(
"Unable to load gltf : {}", err.what());
94 const fx::gltf::Document& model,
95 std::vector<size_t>& nodeToObjectMap) {
110 nodeToObjectMap.size() == model.nodes.size(),
111 "nodeMap: {}, nodes: {}",
112 nodeToObjectMap.size(),
118 std::vector<size_t> remainingNodes;
119 remainingNodes.reserve(model.nodes.size());
120 for (
auto nodeId = 0; nodeId < nodeToObjectMap.size(); nodeId++) {
122 remainingNodes.push_back(nodeId);
131 if (loadedBlendShape !=
nullptr) {
132 result.
blendShape = std::move(loadedBlendShape);
140 for (
auto& locator : result.
locators) {
146 loadGlobalExtensions(model, result);
155fx::gltf::Document loadModel(
156 const std::variant<filesystem::path, std::span<const std::byte>>& input) {
157 fx::gltf::Document model;
158 constexpr uint32_t kMax = std::numeric_limits<uint32_t>::max();
159 constexpr fx::gltf::ReadQuotas kQuotas = {8, kMax, kMax};
163 using T = std::decay_t<
decltype(arg)>;
164 if constexpr (std::is_same_v<T, filesystem::path>) {
168 std::ifstream infile(arg);
169 MT_THROW_IF(!infile.is_open(),
"Unable to open: {}", arg.string());
170 std::copy_n(std::istreambuf_iterator<char>(infile.rdbuf()), 4, std::back_inserter(magic));
171 if (magic ==
"glTF") {
172 model = fx::gltf::LoadFromBinary(arg.string(), kQuotas);
174 model = fx::gltf::LoadFromText(arg.string(), kQuotas);
176 }
else if constexpr (std::is_same_v<T, std::span<const std::byte>>) {
178 model = fx::gltf::LoadFromBinary(inputStream,
"", kQuotas);
187 const std::variant<filesystem::path, std::span<const std::byte>>& input) {
192 fx::gltf::Document model = loadModel(input);
194 }
catch (std::runtime_error& err) {
195 MT_THROW(
"Unable to load gltf : {}", err.what());
204 std::span<const SkeletonState> skeletonStates,
205 std::span<
const std::vector<Marker>> markerSequence,
211 const auto kCharacterIsEmpty = character.
skeleton.
joints.empty() && character.
mesh ==
nullptr;
212 if (!kCharacterIsEmpty) {
213 fileBuilder.
addCharacter(character, Vector3f::Zero(), Quaternionf::Identity(), options);
217 if (!skeletonStates.empty()) {
220 if (!markerSequence.empty()) {
222 !skeletonStates.empty() && (skeletonStates.size() != markerSequence.size()),
223 "Size of skeleton states vector {} does not correspond to size of marker sequence vector {}",
224 skeletonStates.size(),
225 markerSequence.size());
241 const fx::gltf::Document& model,
242 std::vector<size_t>& nodeToObjectMap) {
248 result = populateCharacterFromModel(model, nodeToObjectMap);
249 }
catch (std::runtime_error& err) {
250 MT_THROW(
"Unable to load gltf : {}", err.what());
257 std::vector<size_t> nodeToObjectMap;
262 return loadModelAndCharacter(gltfFilename);
266 return loadModelAndCharacter(byteSpan);
269std::tuple<MotionParameters, IdentityParameters, float>
loadMotion(
270 const filesystem::path& gltfFilename) {
275 fx::gltf::Document model = loadModel(gltfFilename);
277 }
catch (std::runtime_error& err) {
278 MT_THROW(
"Unable to load gltf from file '{}'. Error: {}", gltfFilename.string(), err.what());
284 fx::gltf::Document model = loadModel(gltfFilename);
285 const auto& def = getMomentumExtension(model.extensionsAndExtras);
288 if (def.count(
"motion") == 0) {
289 MT_LOGW(
"No motion data found in gltf file when loading timestamps");
293 const auto& motion = def[
"motion"];
294 if (!motion.contains(
"timestamps")) {
295 MT_LOGW(
"No timestamps found in gltf file");
300 return motion[
"timestamps"].get<std::vector<int64_t>>();
301 }
catch (
const std::exception& err) {
303 "Unable to load timestamps from gltf file '{}'. Error: {}",
304 gltfFilename.string(),
310 const filesystem::path& gltfFilename) {
315 std::span<const std::byte> byteSpan) {
320 const filesystem::path& gltfFilename) {
322 std::ifstream file(gltfFilename, std::ios::binary | std::ios::ate);
323 MT_THROW_IF(!file.is_open(),
"Unable to open file: {}", gltfFilename.string());
325 const std::streamsize size = file.tellg();
326 file.seekg(0, std::ios::beg);
328 std::vector<std::byte> buffer(size);
329 if (!file.read(
reinterpret_cast<char*
>(buffer.data()), size)) {
330 MT_THROW(
"Unable to read file: {}", gltfFilename.string());
338 std::span<const std::byte> byteSpan) {
342 "Mismatch between character and motion; character has {} model parameters while motion has {}.",
348 return {character, motion, modelIdentity, fps};
351std::tuple<Character, std::vector<SkeletonState>, std::vector<float>>
356std::tuple<Character, std::vector<SkeletonState>, std::vector<float>>
362 const filesystem::path& gltfFilename,
368 const std::span<const std::byte> byteSpan,
378 std::span<
const std::vector<Marker>> markerSequence,
381 std::span<const int64_t> timestamps) {
384 const auto kCharacterIsEmpty = character.
skeleton.
joints.empty() && character.
mesh ==
nullptr;
385 if (!kCharacterIsEmpty) {
386 fileBuilder.
addCharacter(character, Vector3f::Zero(), Quaternionf::Identity(), options);
390 if ((!std::get<0>(motion).empty()) || (!std::get<0>(offsets).empty())) {
392 character, fps, motion, offsets, options.
extensions,
"default", timestamps);
394 if (!markerSequence.empty()) {
406MarkerSequence loadMarkerSequenceFromModel(fx::gltf::Document model) {
409 if (model.animations.empty()) {
413 const auto& def = getMomentumExtension(model.extensionsAndExtras);
414 const float fps = def.value(
"fps", 120.0f);
418 const auto& animation = model.animations.front();
420 for (
const auto& channel : animation.channels) {
422 if (channel.target.path !=
"translation") {
427 if (channel.target.node < 0 ||
static_cast<size_t>(channel.target.node) >= model.nodes.size()) {
430 const auto& node = model.nodes.at(channel.target.node);
433 if (node.skin >= 0 || node.camera >= 0) {
437 const auto& extension = getMomentumExtension(node.extensionsAndExtras);
438 const std::string type = extension.value(
"type",
"");
439 if (type ==
"marker") {
441 const auto& sampler = animation.samplers[channel.sampler];
447 if (positions.empty()) {
451 timestamps.size() == positions.size(),
452 "timestamps: {}, positions: {}",
457 const size_t length =
static_cast<size_t>(std::lround(timestamps.back() * fps)) + 1;
458 if (length > result.
frames.size()) {
459 result.
frames.resize(length);
463 const auto& confArray =
464 extension.count(
"confidence") != 0 ? extension[
"confidence"] : nlohmann::json();
465 for (
size_t i = 0; i < positions.size(); i++) {
466 const auto index =
static_cast<size_t>(std::lround(timestamps[i] * fps));
467 result.
frames[index].emplace_back();
468 auto& marker = result.
frames[index].back();
470 marker.name = node.name;
471 marker.occluded =
false;
472 marker.pos = positions[i].cast<
double>();
473 if (confArray.is_array() && i < confArray.size()) {
474 marker.confidence = confArray[i].get<
float>();
486 return loadMarkerSequenceFromModel(loadModel(filename));
490 return loadMarkerSequenceFromModel(loadModel(byteSpan));
494 const filesystem::path& filename,
499 std::span<
const std::vector<Marker>> markerSequence,
501 std::span<const int64_t> timestamps) {
502 constexpr auto kEmbedResources =
false;
504 character, fps, motion, offsets, markerSequence, kEmbedResources, options, timestamps);
510 const filesystem::path& filename,
513 std::span<const SkeletonState> skeletonStates,
514 std::span<
const std::vector<Marker>> markerSequence,
516 constexpr auto kEmbedResources =
false;
518 character, fps, skeletonStates, markerSequence, kEmbedResources, options);
528 std::span<
const std::vector<Marker>> markerSequence,
530 std::span<const int64_t> timestamps) {
531 constexpr auto kEmbedResources =
false;
533 character, fps, motion, offsets, markerSequence, kEmbedResources, options, timestamps);
535 std::ostringstream output(std::ios::binary | std::ios::out);
536 fx::gltf::Save(model, output, {},
true);
537 const auto view = output.str();
538 const auto n = view.size();
539 std::vector<std::byte> result(n);
540 for (
size_t i = 0; i < n; ++i) {
541 result[i] =
static_cast<std::byte
>(view[i]);
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Helper class to build a glb scene.
void setAnimationInterpolation(GltfAnimationInterpolation interpolation)
Set how the joint and blend shape animation samplers added afterwards interpolate between their keys ...
const fx::gltf::Document & getDocument()
Allow copy the document, but do not allow modify the file outside of the builder to keep metadata con...
void addMotion(const Character &character, float fps=120.0f, const MotionParameters &motion={}, const IdentityParameters &offsets={}, bool addExtensions=true, const std::string &customName="default", std::span< const int64_t > timestamps={})
Add a motion to the provided character.
void addMarkerSequence(float fps, std::span< const std::vector< momentum::Marker > > markerSequence, MarkerMesh markerMesh=MarkerMesh::UnitCube, const std::string &animName="default")
Add marker data to the file.
void addCharacter(const Character &character, const Vector3f &positionOffset=Vector3f::Zero(), const Quaternionf &rotationOffset=Quaternionf::Identity(), const FileSaveOptions &options=FileSaveOptions())
Add a character to the scene.
void save(const filesystem::path &filename, GltfFileFormat fileFormat=GltfFileFormat::Auto, bool embedResources=false)
void addSkeletonStates(const Character &character, float fps, std::span< const SkeletonState > skeletonStates, const std::string &customName="default")
Add a skeleton states to the provided character.
void forceEmbedResources()
Set all existing buffers to embed resources.
#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.
ParameterLimits parameterLimitsFromJson(const Character &character, const nlohmann::json &j)
std::tuple< MotionParameters, IdentityParameters, float > loadMotion(const filesystem::path &gltfFilename)
Load motion data from a glTF file.
::std::unique_ptr< BlendShape > BlendShape_u
std::tuple< std::vector< std::string >, JointParameters > IdentityParameters
A tuple of skeleton joint names and identity parameters.
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.
std::tuple< Character, std::vector< SkeletonState >, std::vector< float > > loadCharacterWithSkeletonStates(std::span< const std::byte > byteSpan)
Load a glTF character with motion in the form of skeleton states.
ModelParameters applyModelParameterScales(const ParameterTransform ¶meterTransform, MatrixXf &motion, const JointParameters &jointIdentity)
Apply model parameter scale conversion to motion data.
void saveGltfCharacter(const filesystem::path &filename, const Character &character, const float fps, const MotionParameters &motion, const IdentityParameters &offsets, std::span< const std::vector< Marker > > markerSequence, const FileSaveOptions &options, std::span< const int64_t > timestamps)
Save a character with motion to a glTF file.
SkinWeights_u bindMeshToJoint(const Mesh_u &mesh, size_t jointId)
Bind a mesh to a single joint.
std::tuple< MatrixXf, JointParameters, float > loadMotionOnCharacterCommon(const std::variant< filesystem::path, std::span< const std::byte > > &input, const Character &character)
Load motion onto a character (common implementation).
std::vector< std::byte > saveCharacterToBytes(const Character &character, float fps, const MotionParameters &motion, const IdentityParameters &offsets, std::span< const std::vector< Marker > > markerSequence, const FileSaveOptions &options, std::span< const int64_t > timestamps)
Save a character with motion to a byte buffer.
std::tuple< std::vector< std::string >, Eigen::MatrixXf > MotionParameters
A tuple of model parameter names and a matrix of poses across a sequence of frames.
Character loadGltfCharacterInternal(const fx::gltf::Document &model, std::vector< size_t > &nodeToObjectMap)
Internal function to load a character from a glTF model with node-to-object mapping.
JointList createSkeletonWithOnlyRoot()
Create a skeleton with only a root joint.
Vector3f toMomentumVec3f(const std::array< float, 3 > &vec) noexcept
fx::gltf::Document makeCharacterDocument(const Character &character, const float fps, const MotionParameters &motion, const IdentityParameters &offsets, std::span< const std::vector< Marker > > markerSequence, bool embedResource, const FileSaveOptions &options, std::span< const int64_t > timestamps)
Create a glTF document from a character.
std::tuple< Character, MatrixXf, ModelParameters, float > loadCharacterWithMotionModelParameterScales(const filesystem::path &gltfFilename)
Load a glTF character with motion and apply scale parameters to the motion.
std::vector< T > copyAccessorBuffer(const fx::gltf::Document &model, int32_t id)
std::tuple< Character, std::vector< SkeletonState >, std::vector< float > > loadCharacterWithSkeletonStatesCommon(const std::variant< filesystem::path, std::span< const std::byte > > &input)
Load character with skeleton states from input (common implementation).
std::tuple< Character, MatrixXf, JointParameters, float > loadCharacterWithMotionCommon(const std::variant< filesystem::path, std::span< const std::byte > > &input, bool mapParameters)
Load character with motion from input (common implementation).
constexpr size_t kParametersPerJoint
ParameterTransform parameterTransformFromJson(const Character &character, const nlohmann::json &j)
MarkerSequence loadMarkerSequence(const filesystem::path &filename)
Load a marker sequence from a glTF file.
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
ParameterSets parameterSetsFromJson(const Character &character, const nlohmann::json &j)
Character loadGltfCharacter(const fx::gltf::Document &model)
Load a glTF character from a document.
std::tuple< Mesh_u, SkinWeights_u, BlendShape_u > loadSkinnedMesh(const fx::gltf::Document &model, const std::vector< size_t > &meshNodes, const std::vector< size_t > &nodeToObjectMap)
Load skinned mesh, skin weights, and blend shapes from the model.
std::tuple< MatrixXf, JointParameters, float > loadMotionOnCharacter(const filesystem::path &gltfFilename, const Character &character)
Load motion from a glTF file and map it to a character.
std::tuple< MotionParameters, IdentityParameters, float > loadMotionFromModel(fx::gltf::Document &model)
Load motion data from a glTF model.
PoseConstraints poseConstraintsFromJson(const Character &character, const nlohmann::json &j)
std::tuple< Character, MatrixXf, JointParameters, float > loadCharacterWithMotion(const filesystem::path &gltfFilename)
Load a glTF character with motion from a file path.
std::vector< int64_t > loadMotionTimestamps(const filesystem::path &gltfFilename)
Load per-frame timestamps from a glTF file.
A character model with skeletal structure, mesh, and optional components.
LocatorList locators
Points of interest attached to joints.
SkinWeights_u skinWeights
Defines how mesh vertices are influenced by joints.
void initInverseBindPose()
Initializes the inverse bind pose transformations.
void resetJointMap()
Resets the joint map to identity (each joint maps to itself).
PhysicalProperties physicalProperties
Joint-level physical mass and inertia data loaded from model assets.
ParameterLimits parameterLimits
Constraints on model parameters.
Mesh_u mesh
3D mesh representing the character's surface
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
std::string name
Character identifier.
ParameterTransform parameterTransform
Maps model parameters to joint parameters.
BlendShape_const_p blendShape
Shape variations that can be blended.
std::string metadata
Metadata (as a JSON-serialized string).
CollisionGeometry_u collision
Collision volumes for the character.
Unified options for saving files in both FBX and GLTF formats.
bool extensions
Enable GLTF extensions (default: true) Only used for GLTF output.
GltfAnimationInterpolation gltfAnimationInterpolation
Interpolation of the joint and blend shape animation samplers (default: Step) Marker animation always...
GltfFileFormat gltfFileFormat
GLTF file format selection (default: Auto) Only used for GLTF output.
All frames from a single motion capture sequence for one subject (actor).
float fps
Frame rate of the capture, in frames per second.
std::vector< std::vector< Marker > > frames
All marker observations across the sequence. Layout: [numFrames][numMarkers].
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
istream that takes a span of const bytes as input.