12#ifdef MOMENTUM_WITH_FBX_SDK
18#include <unordered_map>
25 struct CharacterData {
26 SkeletonNodeResult skeletonResult;
27 MeshBlendShapeResult meshResult;
31 ::fbxsdk::FbxManager* manager =
nullptr;
32 ::fbxsdk::FbxScene* scene =
nullptr;
33 std::unordered_map<std::string, CharacterData> characters;
36 manager = ::fbxsdk::FbxManager::Create();
37 auto* ios = ::fbxsdk::FbxIOSettings::Create(manager, IOSROOT);
38 manager->SetIOSettings(ios);
39 scene = ::fbxsdk::FbxScene::Create(manager,
"momentum_scene");
43 if (scene !=
nullptr) {
47 if (manager !=
nullptr) {
53 Impl(
const Impl&) =
delete;
55 Impl(Impl&&) =
delete;
61FbxBuilder::~FbxBuilder() =
default;
63FbxBuilder::FbxBuilder(FbxBuilder&&) noexcept = default;
65FbxBuilder& FbxBuilder::operator=(FbxBuilder&&) noexcept = default;
67void FbxBuilder::addCharacter(const Character& character, const FileSaveOptions& options) {
68 MT_THROW_IF(!impl_,
"FbxBuilder has been moved from or already saved");
71 auto* root = impl_->scene->GetRootNode();
72 MT_THROW_IF(root ==
nullptr,
"Unable to get root node from FBX scene");
75 ::fbxsdk::FbxAxisSystem axis =
toFbx(options.coordSystemInfo);
76 axis.ConvertScene(impl_->scene);
83 if (options.locators) {
86 if (options.collisions) {
91 MeshBlendShapeResult meshResult;
92 if (options.mesh && character.mesh !=
nullptr) {
94 character, impl_->scene, root, skeletonResult.jointToNodeMap, options.permissive);
98 if (!skeletonResult.nodes.empty()) {
99 root->AddChild(skeletonResult.rootNode);
103 const std::string& name = character.name;
104 impl_->characters[name] = {std::move(skeletonResult), std::move(meshResult), name};
107void FbxBuilder::addRigidBody(
108 const Character& character,
109 const std::string& name,
111 const FileSaveOptions& options) {
112 MT_THROW_IF(!impl_,
"FbxBuilder has been moved from or already saved");
115 auto* root = impl_->scene->GetRootNode();
116 MT_THROW_IF(root ==
nullptr,
"Unable to get root node from FBX scene");
118 const std::string charName = name.empty() ? character.name : name;
128 for (
auto* node : skeletonResult.nodes) {
129 std::string prefixed = charName +
":" + node->GetName();
130 node->SetName(prefixed.c_str());
131 if (
auto* attr = node->GetNodeAttribute()) {
132 attr->SetName(prefixed.c_str());
139 parentJoint >= skeletonResult.nodes.size(),
140 "parentJoint index {} out of range for skeleton with {} joints",
142 skeletonResult.nodes.size());
143 ::fbxsdk::FbxNode* meshParentNode = skeletonResult.nodes[parentJoint];
146 MeshBlendShapeResult meshResult;
147 if (options.mesh && character.mesh !=
nullptr) {
150 const auto numVertices =
static_cast<int>(character.mesh->vertices.size());
151 ::fbxsdk::FbxNode* meshNode =
152 ::fbxsdk::FbxNode::Create(impl_->scene, (charName +
"_mesh").c_str());
153 ::fbxsdk::FbxMesh* lMesh = ::fbxsdk::FbxMesh::Create(impl_->scene,
"mesh");
154 lMesh->SetControlPointCount(numVertices);
155 lMesh->InitNormals(numVertices);
156 for (
int i = 0; i < numVertices; i++) {
158 character.mesh->vertices[i].x(),
159 character.mesh->vertices[i].y(),
160 character.mesh->vertices[i].z());
162 character.mesh->normals[i].x(),
163 character.mesh->normals[i].y(),
164 character.mesh->normals[i].z());
165 lMesh->SetControlPointAt(point, normal, i);
168 lMesh->BuildMeshEdgeArray();
169 meshNode->SetNodeAttribute(lMesh);
172 if (!character.mesh->texcoords.empty()) {
173 const fbxsdk::FbxLayerElement::EType uvType = fbxsdk::FbxLayerElement::eTextureDiffuse;
174 lMesh->InitTextureUV(0, uvType);
175 lMesh->InitTextureUVIndices(
176 ::fbxsdk::FbxLayerElement::EMappingMode::eByPolygonVertex, uvType);
177 for (
const auto& texcoords : character.mesh->texcoords) {
178 lMesh->AddTextureUV(::fbxsdk::FbxVector2(texcoords[0], 1.0f - texcoords[1]), uvType);
184 if (meshParentNode !=
nullptr) {
185 meshParentNode->AddChild(meshNode);
190 if (!skeletonResult.nodes.empty()) {
191 root->AddChild(skeletonResult.rootNode);
194 impl_->characters[character.name] = {std::move(skeletonResult), std::move(meshResult), charName};
197void FbxBuilder::addMotion(
198 const Character& character,
200 const MatrixXf& motion,
201 const VectorXf& offsets) {
202 MT_THROW_IF(!impl_,
"FbxBuilder has been moved from or already saved");
204 auto it = impl_->characters.find(character.name);
206 it == impl_->characters.end(),
207 "Character '{}' has not been added to the builder",
210 if (motion.cols() == 0) {
216 if (offsets.size() == character.parameterTransform.numJointParameters()) {
217 params.offsets = offsets;
219 params.offsets = character.parameterTransform.bindPose();
224 params.pose = motion.col(0);
225 state.set(params, character,
false,
false,
false);
227 jointValues.resize(state.skeletonState.jointParameters.v.size(), motion.cols());
228 jointValues.col(0) = state.skeletonState.jointParameters.v;
230 for (Eigen::Index f = 1; f < motion.cols(); f++) {
231 params.pose = motion.col(f);
232 state.set(params, character,
false,
false,
false);
233 jointValues.col(f) = state.skeletonState.jointParameters.v;
236 const auto& charData = it->second;
237 if (jointValues.rows() == character.parameterTransform.numJointParameters()) {
239 character, impl_->scene, charData.skeletonResult.nodes, jointValues, fps,
false);
244 if (blendShapeWeights.cols() > 0 && !charData.meshResult.blendShapeChannels.empty()) {
246 impl_->scene, charData.meshResult.blendShapeChannels, blendShapeWeights, fps);
249 if (faceExpressionWeights.cols() > 0 && !charData.meshResult.faceExprChannels.empty()) {
251 impl_->scene, charData.meshResult.faceExprChannels, faceExpressionWeights, fps);
255void FbxBuilder::addMotionWithJointParams(
256 const Character& character,
258 const MatrixXf& jointParams) {
259 MT_THROW_IF(!impl_,
"FbxBuilder has been moved from or already saved");
261 auto it = impl_->characters.find(character.name);
263 it == impl_->characters.end(),
264 "Character '{}' has not been added to the builder",
267 if (jointParams.cols() == 0) {
271 const auto& charData = it->second;
275 charData.skeletonResult.nodes,
286void writeUserProperties(::fbxsdk::FbxNode* node,
const FbxUserProperties& userProperties) {
287 for (
const auto& entry : userProperties) {
288 const std::string& propertyName = entry.first;
291 [&](
const auto& typedValue) {
292 using T = std::decay_t<
decltype(typedValue)>;
293 ::fbxsdk::FbxDataType dataType;
294 if constexpr (std::is_same_v<T, bool>) {
295 dataType = ::fbxsdk::FbxBoolDT;
296 }
else if constexpr (std::is_same_v<T, int>) {
297 dataType = ::fbxsdk::FbxIntDT;
298 }
else if constexpr (std::is_same_v<T, float>) {
299 dataType = ::fbxsdk::FbxFloatDT;
301 dataType = ::fbxsdk::FbxStringDT;
303 auto property = ::fbxsdk::FbxProperty::Create(node, dataType, propertyName.c_str());
304 property.ModifyFlag(::fbxsdk::FbxPropertyFlags::eUserDefined,
true);
305 if constexpr (std::is_same_v<T, std::string>) {
306 property.Set(::fbxsdk::FbxString(typedValue.c_str()));
308 property.Set(typedValue);
317void FbxBuilder::addAnimatedMesh(
318 const Character& character,
319 const std::string& name,
321 const MatrixXf& jointParams,
322 const FbxUserProperties& userProperties) {
323 MT_THROW_IF(character.mesh ==
nullptr,
"Character has no mesh");
329 character.skeleton.joints.empty() ? Vector3f::Zero()
330 : character.skeleton.joints[0].translationOffset,
334void FbxBuilder::addAnimatedMesh(
336 const std::string& name,
338 const MatrixXf& jointParams,
339 const Vector3f& translationOffset,
340 const FbxUserProperties& userProperties) {
341 MT_THROW_IF(!impl_,
"FbxBuilder has been moved from or already saved");
343 MT_THROW_IF(jointParams.cols() == 0,
"jointParams is empty");
345 auto* root = impl_->scene->GetRootNode();
346 MT_THROW_IF(root ==
nullptr,
"Unable to get root node from FBX scene");
349 const auto numVertices =
static_cast<int>(mesh.vertices.size());
350 ::fbxsdk::FbxNode* meshNode = ::fbxsdk::FbxNode::Create(impl_->scene, name.c_str());
351 ::fbxsdk::FbxMesh* lMesh = ::fbxsdk::FbxMesh::Create(impl_->scene, (name +
"_geo").c_str());
352 lMesh->SetControlPointCount(numVertices);
353 lMesh->InitNormals(numVertices);
354 for (
int i = 0; i < numVertices; i++) {
355 lMesh->SetControlPointAt(
356 FbxVector4(mesh.vertices[i].x(), mesh.vertices[i].y(), mesh.vertices[i].z()),
357 FbxVector4(mesh.normals[i].x(), mesh.normals[i].y(), mesh.normals[i].z()),
361 lMesh->BuildMeshEdgeArray();
362 meshNode->SetNodeAttribute(lMesh);
364 if (!mesh.texcoords.empty()) {
365 const fbxsdk::FbxLayerElement::EType uvType = fbxsdk::FbxLayerElement::eTextureDiffuse;
366 lMesh->InitTextureUV(0, uvType);
367 lMesh->InitTextureUVIndices(::fbxsdk::FbxLayerElement::EMappingMode::eByPolygonVertex, uvType);
368 for (
const auto& texcoords : mesh.texcoords) {
369 lMesh->AddTextureUV(::fbxsdk::FbxVector2(texcoords[0], 1.0f - texcoords[1]), uvType);
374 writeUserProperties(meshNode, userProperties);
376 root->AddChild(meshNode);
380 auto [animStack, animBaseLayer] =
388 const auto nFrames = jointParams.cols();
391 FbxDouble3 staticTrans(
395 meshNode->LclTranslation.Set(staticTrans);
396 FbxDouble3 staticRot(
400 meshNode->LclRotation.Set(staticRot);
401 const Eigen::Index scaleRow = std::min(
static_cast<Eigen::Index
>(6), jointParams.rows() - 1);
402 const float staticScale =
jointParamToFbx(jointParams(scaleRow, 0), 6, rootJoint);
403 meshNode->LclScaling.Set(FbxDouble3(staticScale, staticScale, staticScale));
407 const std::array<::fbxsdk::FbxProperty*, 3> properties = {
408 &meshNode->LclTranslation,
409 &meshNode->LclRotation,
410 &meshNode->LclScaling,
412 const std::array<const char*, 3> components = {
413 FBXSDK_CURVENODE_COMPONENT_X,
414 FBXSDK_CURVENODE_COMPONENT_Y,
415 FBXSDK_CURVENODE_COMPONENT_Z,
418 ::fbxsdk::FbxTime time;
419 for (
size_t c = 0; c < 9; c++) {
420 const auto paramRow =
static_cast<Eigen::Index
>(std::min(c,
size_t(6)));
421 if (paramRow >= jointParams.rows()) {
425 bool isConstant =
true;
426 const float firstVal = jointParams(paramRow, 0);
427 for (Eigen::Index f = 1; f < nFrames; f++) {
428 if (jointParams(paramRow, f) != firstVal) {
437 auto* prop = properties[c / 3];
438 prop->GetCurveNode(
true);
439 auto* curve = prop->GetCurve(animBaseLayer, components[c % 3],
true);
441 curve->KeyModifyBegin();
442 for (Eigen::Index f = 0; f < nFrames; f++) {
443 const float val =
jointParamToFbx(jointParams(paramRow, f), c, rootJoint);
444 time.SetSecondDouble(
static_cast<double>(f) / fps);
445 const auto keyIndex = curve->KeyAdd(time);
446 curve->KeySet(keyIndex, time, val);
448 curve->KeyModifyEnd();
452void FbxBuilder::addMarkerSequence(
float fps, std::span<
const std::vector<Marker>> markerSequence) {
453 MT_THROW_IF(!impl_,
"FbxBuilder has been moved from or already saved");
455 if (!markerSequence.empty()) {
460void FbxBuilder::save(
const filesystem::path& filename) {
461 MT_THROW_IF(!impl_,
"FbxBuilder has been moved from or already saved");
463 auto* lExporter = ::fbxsdk::FbxExporter::Create(impl_->manager,
"");
465 std::string sFilename = filename.string();
467 lExporter->Initialize(sFilename.c_str(), -1, impl_->manager->GetIOSettings());
471 "Unable to initialize fbx exporter: {}",
472 lExporter->GetStatus().GetErrorString());
474 lExporter->Export(impl_->scene);
475 lExporter->Destroy();
491 "FbxBuilder requires the Autodesk FBX SDK. FBX loading is available via OpenFBX, but building scenes requires the full SDK.");
501 MT_THROW(
"FbxBuilder requires the Autodesk FBX SDK.");
509 MT_THROW(
"FbxBuilder requires the Autodesk FBX SDK.");
513 MT_THROW(
"FbxBuilder requires the Autodesk FBX SDK.");
517 MT_THROW(
"FbxBuilder requires the Autodesk FBX SDK.");
526 MT_THROW(
"FbxBuilder requires the Autodesk FBX SDK.");
536 MT_THROW(
"FbxBuilder requires the Autodesk FBX SDK.");
540 MT_THROW(
"FbxBuilder requires the Autodesk FBX SDK.");
544 MT_THROW(
"FbxBuilder requires the Autodesk FBX SDK.");
Builder class for creating FBX files with multiple characters and animations.
void addMarkerSequence(float fps, std::span< const std::vector< Marker > > markerSequence)
Add a marker sequence to the scene.
void addMotionWithJointParams(const Character &character, float fps, const MatrixXf &jointParams)
Add joint-parameter animation for a previously added character.
void save(const filesystem::path &filename)
Save the FBX scene to a file.
void operator=(FbxBuilder const &)=delete
void addRigidBody(const Character &character, const std::string &name="", size_t parentJoint=0, const FileSaveOptions &options=FileSaveOptions())
Add a rigid body (skeleton + mesh parented to a joint, no skinning).
void addMotion(const Character &character, float fps, const MatrixXf &motion={}, const VectorXf &offsets={})
Add model-parameter animation for a previously added character.
void addCharacter(const Character &character, const FileSaveOptions &options=FileSaveOptions())
Add a skinned character (skeleton + mesh with skin weights) to the scene.
void addAnimatedMesh(const Character &character, const std::string &name, float fps, const MatrixXf &jointParams, const FbxUserProperties &userProperties={})
Add an animated mesh (mesh node with per-frame transform, no skeleton).
#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.
MatrixXf extractBlendShapeWeights(const Character &character, const MatrixXf &poses)
void addPhysicalProperties(const Character &character, const std::unordered_map< size_t, fbxsdk::FbxNode * > &jointToNodeMap)
std::pair<::fbxsdk::FbxAnimStack *, ::fbxsdk::FbxAnimLayer * > getOrCreateAnimStackAndLayer(::fbxsdk::FbxScene *scene, const char *stackName)
void createAnimationCurves(const Character &character, ::fbxsdk::FbxScene *scene, const std::vector<::fbxsdk::FbxNode * > &skeletonNodes, const MatrixXf &jointValues, const double framerate, const bool skipActiveJointParamCheck)
void setFrameRate(::fbxsdk::FbxScene *scene, const double framerate)
std::vector<::fbxsdk::FbxNode * > createMarkerNodes(::fbxsdk::FbxScene *scene, std::span< const std::vector< Marker > > markerSequence, const double framerate)
void writeTextureUVIndicesToFbxMesh(const Mesh &mesh, ::fbxsdk::FbxMesh *lMesh, fbxsdk::FbxLayerElement::EType uvType)
::fbxsdk::FbxAxisSystem::EUpVector toFbx(const FbxUpVector upVector)
void createBlendShapeAnimationCurves(::fbxsdk::FbxScene *scene, const std::vector<::fbxsdk::FbxBlendShapeChannel * > &channels, const MatrixXf &weights, const double framerate)
MatrixXf extractFaceExpressionWeights(const Character &character, const MatrixXf &poses)
void createLocatorNodes(const Character &character, ::fbxsdk::FbxScene *scene, const std::vector<::fbxsdk::FbxNode * > &skeletonNodes)
float jointParamToFbx(float value, size_t curveOffset, const Joint &joint)
Convert a raw momentum joint parameter to the FBX-native value.
void createCollisionGeometryNodes(const Character &character, ::fbxsdk::FbxScene *scene, const std::vector<::fbxsdk::FbxNode * > &skeletonNodes)
SkeletonNodeResult createSkeletonNodes(const Character &character, ::fbxsdk::FbxScene *scene)
MeshBlendShapeResult createMeshNode(const Character &character, ::fbxsdk::FbxScene *scene, ::fbxsdk::FbxNode *parentNode, const std::unordered_map< size_t, fbxsdk::FbxNode * > &jointToNodeMap, Permissive permissive, const std::string &meshName="body_mesh")
void writePolygonsToFbxMesh(const Mesh &mesh, ::fbxsdk::FbxMesh *lMesh)
void addMetaData(::fbxsdk::FbxNode *skeletonRootNode, const Character &character)
T normal(const T &mean, const T &sigma)
Normally distributed value via the global Random singleton.
CharacterStateT< float > CharacterState
std::variant< bool, int, float, std::string > FbxUserPropertyValue
Value of a user-defined FBX property.
std::map< std::string, FbxUserPropertyValue > FbxUserProperties
User-defined FBX properties, keyed by property name.
CharacterParametersT< float > CharacterParameters
Vector3< float > Vector3f
VectorX< float > VectorXf
MatrixX< float > MatrixXf
A character model with skeletal structure, mesh, and optional components.
Unified options for saving files in both FBX and GLTF formats.
Vector3< T > translationOffset
Constant translation offset from the parent joint's origin to this joint's origin,...