Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
gltf_animation_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#include "momentum/common/log.h"
22
23#include <algorithm>
24#include <fstream>
25#include <limits>
26
27namespace momentum {
28
29namespace {
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
40fx::gltf::Document loadModel(
41 const std::variant<filesystem::path, std::span<const std::byte>>& input) {
42 fx::gltf::Document model;
43 constexpr uint32_t kMax = std::numeric_limits<uint32_t>::max();
44 constexpr fx::gltf::ReadQuotas kQuotas = {8, kMax, kMax};
45
46 std::visit(
47 [&](auto&& arg) {
48 using T = std::decay_t<decltype(arg)>;
49 if constexpr (std::is_same_v<T, filesystem::path>) {
50 // Read first 4 chars for file sensing (https://docs.fileformat.com/3d/glb/)
51 // It is ASCII string "glTF", and can be used to identify data as Binary glTF
52 std::string magic;
53 std::ifstream infile(arg);
54 MT_THROW_IF(!infile.is_open(), "Unable to open: {}", arg.string());
55 std::copy_n(std::istreambuf_iterator<char>(infile.rdbuf()), 4, std::back_inserter(magic));
56 if (magic == "glTF") {
57 model = fx::gltf::LoadFromBinary(arg.string(), kQuotas);
58 } else {
59 model = fx::gltf::LoadFromText(arg.string(), kQuotas);
60 }
61 } else if constexpr (std::is_same_v<T, std::span<const std::byte>>) {
62 ispanstream inputStream(arg);
63 model = fx::gltf::LoadFromBinary(inputStream, "", kQuotas);
64 }
65 },
66 input);
67
68 return model;
69}
70
71} // namespace
72
73std::tuple<MotionParameters, IdentityParameters> getMotionFromModel(fx::gltf::Document& model) {
74 const auto& def = getMomentumExtension(model.extensionsAndExtras);
75 const auto motion = def.value("motion", nlohmann::json::object());
76
77 const size_t nframes = motion.value("nframes", 0);
78 const int32_t poseBuffer = motion.value("poses", int32_t(-1));
79 const int32_t offsetBuffer = motion.value("offsets", int32_t(-1));
80
81 if (nframes == 0 || (poseBuffer < 0 && offsetBuffer < 0)) {
82 return {};
83 }
84
85 // get values from gltf binary buffers
86 MatrixXf storedMotion;
87 VectorXf storedIdentity;
88 std::vector<std::string> parameterNames;
89 std::vector<std::string> jointNames;
90 if (poseBuffer >= 0) {
91 const auto poseValues = copyAccessorBuffer<float>(model, poseBuffer);
92 parameterNames = motion.value("parameterNames", std::vector<std::string>());
93
94 if (poseValues.size() != parameterNames.size() * nframes) {
95 return {};
96 }
97
98 storedMotion = Map<const MatrixXf>(poseValues.data(), parameterNames.size(), nframes);
99 }
100 if (offsetBuffer >= 0) {
101 const auto offsetValues = copyAccessorBuffer<float>(model, offsetBuffer);
102 jointNames = motion.value("jointNames", std::vector<std::string>());
103
104 if (offsetValues.size() != jointNames.size() * kParametersPerJoint) {
105 return {};
106 }
107
108 storedIdentity =
109 Map<const VectorXf>(offsetValues.data(), jointNames.size() * kParametersPerJoint);
110 }
111
112 return {{parameterNames, storedMotion}, {jointNames, storedIdentity}};
113}
114
115float calculateFpsFromAnimationData(const fx::gltf::Document& model) {
116 if (model.animations.empty()) {
117 return 0.0f;
118 }
119
120 // Collect FPS values from each sampler
121 std::vector<float> fpsValues;
122 fpsValues.reserve(32);
123
124 // Iterate through all animations and their samplers
125 for (const auto& animation : model.animations) {
126 for (const auto& sampler : animation.samplers) {
127 const int32_t inputAccessorIndex = sampler.input;
128 if (inputAccessorIndex < 0 ||
129 inputAccessorIndex >= static_cast<int32_t>(model.accessors.size())) {
130 continue;
131 }
132
133 const auto& accessor = model.accessors[inputAccessorIndex];
134 if (accessor.count < 2) {
135 continue;
136 }
137
138 // Get time range from accessor min/max
139 if (accessor.min.empty() || accessor.max.empty()) {
140 continue;
141 }
142
143 const float minTime = accessor.min[0];
144 const float maxTime = accessor.max[0];
145 const float duration = maxTime - minTime;
146
147 if (duration <= 0.0f) {
148 continue;
149 }
150
151 // Calculate FPS for this sampler: (keyframes - 1) / duration
152 const float fps = static_cast<float>(accessor.count - 1) / duration;
153 fpsValues.push_back(fps);
154 }
155 }
156
157 if (fpsValues.empty()) {
158 return 0.0f;
159 }
160
161 // Use median FPS to be robust against outliers
162 std::sort(fpsValues.begin(), fpsValues.end());
163 const float medianFps = fpsValues[fpsValues.size() / 2];
164 return medianFps;
165}
166
167std::tuple<MotionParameters, IdentityParameters, float> loadMotionFromModel(
168 fx::gltf::Document& model) {
169 // parse motion data
170 try {
171 // load motion
172 const auto& def = getMomentumExtension(model.extensionsAndExtras);
173 float fps = def.value("fps", 0.0f);
174
175 // If FPS is not found in momentum metadata, try to calculate from animation data
176 if (fps == 0.0f) {
178 if (fps > 0.0f) {
179 MT_LOGD("FPS not found in momentum metadata, calculated from animation data: {}", fps);
180 } else {
181 // Fall back to default if calculation fails
182 fps = 120.0f;
183 MT_LOGW("FPS not found in momentum metadata or animation data, using default: {}", fps);
184 }
185 }
186
187 const auto& [motion, identity] = getMotionFromModel(model);
188 return {motion, identity, fps};
189 } catch (std::runtime_error& err) {
190 MT_THROW("Unable to parse motion data : {}", err.what());
191 }
192}
193
194std::tuple<Character, MatrixXf, JointParameters, float> loadCharacterWithMotionCommon(
195 const std::variant<filesystem::path, std::span<const std::byte>>& input,
196 bool mapParameters) {
197 // ---------------------------------------------
198 // load Skeleton and Mesh
199 // ---------------------------------------------
200 try {
201 // Set maximum filesize to 4 gigabyte (glb hard limit due to uint32).
202 // Need to fork gltf load to support dynamic loading at some point if files get too big
203 fx::gltf::Document model = loadModel(input);
204 Character character = loadGltfCharacter(model);
205
206 // load motion
207 auto [motion, identity, fps] = loadMotionFromModel(model);
208
209 // check that there is actual motion data within the glb / gltf
210 MT_LOGW_IF(std::get<1>(motion).cols() == 0, "No motion data found in gltf file");
211 return {
212 character,
213 mapParameters ? mapMotionToCharacter(motion, character) : std::get<1>(motion),
214 mapParameters ? mapIdentityToCharacter(identity, character) : std::get<1>(identity),
215 fps};
216 } catch (std::runtime_error& err) {
217 MT_THROW("Unable to load gltf : {}", err.what());
218 }
219}
220
221std::tuple<MatrixXf, JointParameters, float> loadMotionOnCharacterCommon(
222 const std::variant<filesystem::path, std::span<const std::byte>>& input,
223 const Character& character) {
224 const auto [loadedChar, motion, identity, fps] = loadCharacterWithMotionCommon(input);
225 // glTF files that store motion without per-joint identity offsets surface as an empty `identity`
226 // vector. Skip mapIdentityToCharacter in that case to preserve the "no identity present" signal
227 // and to avoid violating its size precondition (joint names paired with an empty values vector).
228 const JointParameters mappedIdentity = identity.size() != 0
229 ? mapIdentityToCharacter({loadedChar.skeleton.getJointNames(), identity}, character)
230 : identity;
231 return {
232 mapMotionToCharacter({loadedChar.parameterTransform.name, motion}, character),
233 mappedIdentity,
234 fps};
235}
236
237namespace {
238
239// Validates a channel's target node and resolves it to a bone index.
240// Returns kInvalidIndex if the channel should be skipped.
241// Throws on bone index out of range or name mismatch.
242size_t validateAndResolveChannel(
243 const fx::gltf::Animation::Channel& channel,
244 const fx::gltf::Document& model,
245 const std::vector<size_t>& nodeToObjectMap,
246 const Skeleton& skeleton) {
247 if (channel.target.node >= nodeToObjectMap.size() ||
248 nodeToObjectMap.at(channel.target.node) == kInvalidIndex) {
249 return kInvalidIndex;
250 }
251
252 // Bounds already validated above
253 const auto boneIdx = nodeToObjectMap.at(channel.target.node);
255 boneIdx >= skeleton.joints.size(),
256 "Bone index {} is larger than the number of joints in the skeleton ({})",
257 boneIdx,
258 skeleton.joints.size());
259
260 const auto& node = model.nodes.at(channel.target.node);
262 node.name != skeleton.joints.at(boneIdx).name,
263 "Bone mismatch between gltf and character; GLTF: {}, Character: {}",
264 node.name,
265 skeleton.joints[boneIdx].name);
266
267 return boneIdx;
268}
269
270// Reads translation/rotation/scale data from a channel sampler and applies it to skeleton states.
271// Returns false if the channel's target path is unrecognized and should be skipped.
272bool applyChannelDataToStates(
273 const fx::gltf::Document& model,
274 const fx::gltf::Animation::Sampler& sampler,
275 const std::string& targetPath,
276 size_t boneIdx,
277 const Character& character,
278 std::vector<SkeletonState>& states,
279 std::vector<float>& timestamps) {
280 // Read the appropriate transform component from the sampler output
281 std::vector<Vector3f> translations_m;
282 std::vector<Quaternionf> rotations;
283 std::vector<Vector3f> scales;
284 if (targetPath == "translation") {
285 translations_m = copyAccessorBuffer<Vector3f>(model, sampler.output);
286 } else if (targetPath == "rotation") {
287 rotations = copyAccessorBuffer<Quaternionf>(model, sampler.output);
288 } else if (targetPath == "scale") {
289 scales = copyAccessorBuffer<Vector3f>(model, sampler.output);
290 } else {
291 return false;
292 }
293
294 // Validate and store timestamps
295 auto timestampsCur = copyAccessorBuffer<float>(model, sampler.input);
296 if (timestamps.empty()) {
297 timestamps = timestampsCur;
298 } else {
300 timestamps.size() != timestampsCur.size(),
301 "Timestamps do not match between channels, got {} and {}",
302 timestamps.size(),
303 timestampsCur.size());
304 }
305
306 // Lazily initialize states on first channel
307 if (states.empty()) {
308 states.resize(
309 timestamps.size(),
311 JointParameters::Zero(character.parameterTransform.numJointParameters()),
312 character.skeleton));
313 }
314
315 MT_THROW_IF(states.size() != timestamps.size(), "States and timestamps do not match in size");
316
317 // Apply the transform component to each frame
318 if (translations_m.size() == states.size()) {
319 for (size_t i = 0; i < states.size(); ++i) {
321 boneIdx >= states[i].jointState.size(),
322 "Bone index {} exceeds jointState size {}",
323 boneIdx,
324 states[i].jointState.size());
325 states[i].jointState[boneIdx].localTransform.translation = toCm() * translations_m[i];
326 }
327 }
328 if (rotations.size() == states.size()) {
329 for (size_t i = 0; i < states.size(); ++i) {
331 boneIdx >= states[i].jointState.size(),
332 "Bone index {} exceeds jointState size {}",
333 boneIdx,
334 states[i].jointState.size());
335 states[i].jointState[boneIdx].localTransform.rotation = rotations[i];
336 }
337 }
338 if (scales.size() == states.size()) {
339 for (size_t i = 0; i < states.size(); ++i) {
341 boneIdx >= states[i].jointState.size(),
342 "Bone index {} exceeds jointState size {}",
343 boneIdx,
344 states[i].jointState.size());
345 states[i].jointState[boneIdx].localTransform.scale = scales[i].x();
346 }
347 }
348
349 return true;
350}
351
352// Computes global transforms from local transforms by walking the joint hierarchy.
353void computeGlobalTransforms(const Skeleton& skeleton, std::vector<SkeletonState>& states) {
354 for (auto& s : states) {
355 for (size_t iJoint = 0; iJoint < skeleton.joints.size(); ++iJoint) {
356 Transform parentTransform;
357 const auto parentJoint = skeleton.joints[iJoint].parent;
358 if (parentJoint != kInvalidIndex) {
359 parentTransform = s.jointState[parentJoint].transform;
360 }
361 s.jointState[iJoint].transform = parentTransform * s.jointState[iJoint].localTransform;
362 }
363 }
364}
365
366} // namespace
367
368std::tuple<Character, std::vector<SkeletonState>, std::vector<float>>
370 const std::variant<filesystem::path, std::span<const std::byte>>& input) {
371 const fx::gltf::Document model = loadModel(input);
372 std::vector<size_t> nodeToObjectMap;
373 Character character = loadGltfCharacterInternal(model, nodeToObjectMap);
374
375 if (model.animations.empty()) {
376 MT_LOGW("No animation found in gltf file");
377 return {character, {}, {}};
378 }
379 if (model.animations.size() > 1) {
380 MT_LOGW("Multiple animations found in gltf file. Only the first one will be used.");
381 }
382
383 const auto& animation = model.animations.front();
384 std::vector<float> timestamps;
385 std::vector<SkeletonState> states;
386
387 for (const auto& channel : animation.channels) {
388 const auto boneIdx =
389 validateAndResolveChannel(channel, model, nodeToObjectMap, character.skeleton);
390 if (boneIdx == kInvalidIndex) {
391 continue;
392 }
393
394 const auto& sampler = animation.samplers[channel.sampler];
395 if (!applyChannelDataToStates(
396 model, sampler, channel.target.path, boneIdx, character, states, timestamps)) {
397 continue;
398 }
399 }
400
401 computeGlobalTransforms(character.skeleton, states);
402
403 return {character, states, timestamps};
404}
405
406} // namespace momentum
#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_LOGW(...)
Definition log.h:180
#define MT_LOGD(...)
Definition log.h:178
#define MT_LOGW_IF(condition,...)
Definition log.h:186
TransformT< float > Transform
Definition fwd.h:77
SkeletonT< float > Skeleton
Definition fwd.h:263
JointParameters mapIdentityToCharacter(const IdentityParameters &inputIdentity, const Character &targetCharacter)
Maps the input JointParameter vector to a target character by matching joint names.
std::tuple< MotionParameters, IdentityParameters > getMotionFromModel(fx::gltf::Document &model)
Get motion parameters from a glTF model.
float calculateFpsFromAnimationData(const fx::gltf::Document &model)
Calculate FPS from glTF animation data.
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).
MatrixXf mapMotionToCharacter(const MotionParameters &inputMotion, const Character &targetCharacter)
Maps the input ModelParameter motion to a target character by matching model parameter names.
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.
Definition gltf_io.cpp:240
constexpr T toCm(T x=T(1)) noexcept
Converts the given length x (in meters) to centimeters.
Definition constants.h:96
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).
SkeletonStateT< float > SkeletonState
Definition fwd.h:282
JointParametersT< float > JointParameters
Definition types.h:135
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
Definition types.h:21
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
Character loadGltfCharacter(const fx::gltf::Document &model)
Load a glTF character from a document.
Definition gltf_io.cpp:256
Eigen::VectorX< T > mapParameters(const ModelParametersT< T > &in, const std::vector< size_t > &mp)
VectorX< float > VectorXf
Definition types.h:209
std::tuple< MotionParameters, IdentityParameters, float > loadMotionFromModel(fx::gltf::Document &model)
Load motion data from a glTF model.
Eigen::Map< T > Map
Definition types.h:40
MatrixX< float > MatrixXf
Definition types.h:82
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
Definition character.h:36
static EIGEN_DEVICE_FUNC Derived< Scalar > Zero(::Eigen::Index size)
Definition types.h:92
istream that takes a span of const bytes as input.