31nlohmann::json getMomentumExtension(
const nlohmann::json& extensionsAndExtras) {
32 if (extensionsAndExtras.count(
"extensions") != 0 &&
33 extensionsAndExtras[
"extensions"].count(
"FB_momentum") != 0) {
34 return extensionsAndExtras[
"extensions"][
"FB_momentum"];
36 return nlohmann::json::object();
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};
48 using T = std::decay_t<
decltype(arg)>;
49 if constexpr (std::is_same_v<T, filesystem::path>) {
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);
59 model = fx::gltf::LoadFromText(arg.string(), kQuotas);
61 }
else if constexpr (std::is_same_v<T, std::span<const std::byte>>) {
63 model = fx::gltf::LoadFromBinary(inputStream,
"", kQuotas);
74 const auto& def = getMomentumExtension(model.extensionsAndExtras);
75 const auto motion = def.value(
"motion", nlohmann::json::object());
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));
81 if (nframes == 0 || (poseBuffer < 0 && offsetBuffer < 0)) {
88 std::vector<std::string> parameterNames;
89 std::vector<std::string> jointNames;
90 if (poseBuffer >= 0) {
92 parameterNames = motion.value(
"parameterNames", std::vector<std::string>());
94 if (poseValues.size() != parameterNames.size() * nframes) {
100 if (offsetBuffer >= 0) {
102 jointNames = motion.value(
"jointNames", std::vector<std::string>());
112 return {{parameterNames, storedMotion}, {jointNames, storedIdentity}};
116 if (model.animations.empty()) {
121 std::vector<float> fpsValues;
122 fpsValues.reserve(32);
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())) {
133 const auto& accessor = model.accessors[inputAccessorIndex];
134 if (accessor.count < 2) {
139 if (accessor.min.empty() || accessor.max.empty()) {
143 const float minTime = accessor.min[0];
144 const float maxTime = accessor.max[0];
145 const float duration = maxTime - minTime;
147 if (duration <= 0.0f) {
152 const float fps =
static_cast<float>(accessor.count - 1) / duration;
153 fpsValues.push_back(fps);
157 if (fpsValues.empty()) {
162 std::sort(fpsValues.begin(), fpsValues.end());
163 const float medianFps = fpsValues[fpsValues.size() / 2];
168 fx::gltf::Document& model) {
172 const auto& def = getMomentumExtension(model.extensionsAndExtras);
173 float fps = def.value(
"fps", 0.0f);
179 MT_LOGD(
"FPS not found in momentum metadata, calculated from animation data: {}", fps);
183 MT_LOGW(
"FPS not found in momentum metadata or animation data, using default: {}", fps);
188 return {motion, identity, fps};
189 }
catch (std::runtime_error& err) {
190 MT_THROW(
"Unable to parse motion data : {}", err.what());
195 const std::variant<filesystem::path, std::span<const std::byte>>& input,
203 fx::gltf::Document model = loadModel(input);
210 MT_LOGW_IF(std::get<1>(motion).cols() == 0,
"No motion data found in gltf file");
216 }
catch (std::runtime_error& err) {
217 MT_THROW(
"Unable to load gltf : {}", err.what());
222 const std::variant<filesystem::path, std::span<const std::byte>>& input,
242size_t validateAndResolveChannel(
243 const fx::gltf::Animation::Channel& channel,
244 const fx::gltf::Document& model,
245 const std::vector<size_t>& nodeToObjectMap,
247 if (channel.target.node >= nodeToObjectMap.size() ||
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 ({})",
258 skeleton.joints.size());
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: {}",
265 skeleton.joints[boneIdx].name);
272bool applyChannelDataToStates(
273 const fx::gltf::Document& model,
274 const fx::gltf::Animation::Sampler& sampler,
275 const std::string& targetPath,
278 std::vector<SkeletonState>& states,
279 std::vector<float>& timestamps) {
281 std::vector<Vector3f> translations_m;
282 std::vector<Quaternionf> rotations;
283 std::vector<Vector3f> scales;
284 if (targetPath ==
"translation") {
286 }
else if (targetPath ==
"rotation") {
288 }
else if (targetPath ==
"scale") {
296 if (timestamps.empty()) {
297 timestamps = timestampsCur;
300 timestamps.size() != timestampsCur.size(),
301 "Timestamps do not match between channels, got {} and {}",
303 timestampsCur.size());
307 if (states.empty()) {
312 character.skeleton));
315 MT_THROW_IF(states.size() != timestamps.size(),
"States and timestamps do not match in size");
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 {}",
324 states[i].jointState.size());
325 states[i].jointState[boneIdx].localTransform.translation =
toCm() * translations_m[i];
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 {}",
334 states[i].jointState.size());
335 states[i].jointState[boneIdx].localTransform.rotation = rotations[i];
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 {}",
344 states[i].jointState.size());
345 states[i].jointState[boneIdx].localTransform.scale = scales[i].x();
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) {
357 const auto parentJoint = skeleton.joints[iJoint].parent;
359 parentTransform = s.jointState[parentJoint].transform;
361 s.jointState[iJoint].transform = parentTransform * s.jointState[iJoint].localTransform;
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;
375 if (model.animations.empty()) {
376 MT_LOGW(
"No animation found in gltf file");
377 return {character, {}, {}};
379 if (model.animations.size() > 1) {
380 MT_LOGW(
"Multiple animations found in gltf file. Only the first one will be used.");
383 const auto& animation = model.animations.front();
384 std::vector<float> timestamps;
385 std::vector<SkeletonState> states;
387 for (
const auto& channel : animation.channels) {
389 validateAndResolveChannel(channel, model, nodeToObjectMap, character.
skeleton);
394 const auto& sampler = animation.samplers[channel.sampler];
395 if (!applyChannelDataToStates(
396 model, sampler, channel.target.path, boneIdx, character, states, timestamps)) {
401 computeGlobalTransforms(character.
skeleton, states);
403 return {character, states, timestamps};
#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.
#define MT_LOGW_IF(condition,...)
TransformT< float > Transform
SkeletonT< float > Skeleton
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.
constexpr T toCm(T x=T(1)) noexcept
Converts the given length x (in meters) to centimeters.
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
JointParametersT< float > JointParameters
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
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Character loadGltfCharacter(const fx::gltf::Document &model)
Load a glTF character from a document.
Eigen::VectorX< T > mapParameters(const ModelParametersT< T > &in, const std::vector< size_t > &mp)
VectorX< float > VectorXf
std::tuple< MotionParameters, IdentityParameters, float > loadMotionFromModel(fx::gltf::Document &model)
Load motion data from a glTF model.
MatrixX< float > MatrixXf
A character model with skeletal structure, mesh, and optional components.
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
static EIGEN_DEVICE_FUNC Derived< Scalar > Zero(::Eigen::Index size)
istream that takes a span of const bytes as input.