AMFP Enhanced
C++ reference: the code this unofficial fork added
Loading...
Searching...
No Matches
FbxDecompose.h
Go to the documentation of this file.
1/*
2 * AMFP-2026: split a bone matrix into translation, rotation and scale the way the Autodesk
3 * FBX SDK did (KFbxXMatrix GetT / GetR / GetS), so the ufbx loader reproduces the original
4 * loader's rest poses and keys. A mirrored matrix (negative determinant) can be split in two
5 * valid ways; the SDK made all three scales negative and kept a proper rotation, whereas
6 * ufbx flips one axis, and the two differ by a 180-degree turn on mirrored bones.
7 * Pure (column vectors, translation in column 3), unit tested in tests/cpp/test_fbx_decompose.cpp.
8 */
9#ifndef HPL_FBX_DECOMPOSE_H
10#define HPL_FBX_DECOMPOSE_H
11
12#include <cmath>
13
14namespace hpl {
15
16struct FbxTrs
17{
18 double t[3];
19 double r[3][3]; // proper rotation (determinant +1)
20 double s[3];
21};
22
23inline FbxTrs FbxDecomposeSdk(const double m[3][4])
24{
25 FbxTrs out;
26 for(int i = 0; i < 3; ++i) out.t[i] = m[i][3];
27
28 double det = m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
29 + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
30 double sign = det < 0 ? -1.0 : 1.0;
31
32 for(int c = 0; c < 3; ++c)
33 {
34 double len = std::sqrt(m[0][c] * m[0][c] + m[1][c] * m[1][c] + m[2][c] * m[2][c]);
35 out.s[c] = sign * len;
36 for(int r = 0; r < 3; ++r) out.r[r][c] = out.s[c] != 0 ? m[r][c] / out.s[c] : (r == c ? 1.0 : 0.0);
37 }
38 return out;
39}
40
41/** Rotation matrix -> quaternion (w, x, y, z). */
42inline void FbxRotationToQuat(const double r[3][3], double q[4])
43{
44 double trace = r[0][0] + r[1][1] + r[2][2];
45 if(trace > 0)
46 {
47 double s = std::sqrt(trace + 1.0) * 2.0;
48 q[0] = 0.25 * s;
49 q[1] = (r[2][1] - r[1][2]) / s;
50 q[2] = (r[0][2] - r[2][0]) / s;
51 q[3] = (r[1][0] - r[0][1]) / s;
52 }
53 else if(r[0][0] > r[1][1] && r[0][0] > r[2][2])
54 {
55 double s = std::sqrt(1.0 + r[0][0] - r[1][1] - r[2][2]) * 2.0;
56 q[0] = (r[2][1] - r[1][2]) / s;
57 q[1] = 0.25 * s;
58 q[2] = (r[0][1] + r[1][0]) / s;
59 q[3] = (r[0][2] + r[2][0]) / s;
60 }
61 else if(r[1][1] > r[2][2])
62 {
63 double s = std::sqrt(1.0 + r[1][1] - r[0][0] - r[2][2]) * 2.0;
64 q[0] = (r[0][2] - r[2][0]) / s;
65 q[1] = (r[0][1] + r[1][0]) / s;
66 q[2] = 0.25 * s;
67 q[3] = (r[1][2] + r[2][1]) / s;
68 }
69 else
70 {
71 double s = std::sqrt(1.0 + r[2][2] - r[0][0] - r[1][1]) * 2.0;
72 q[0] = (r[1][0] - r[0][1]) / s;
73 q[1] = (r[0][2] + r[2][0]) / s;
74 q[2] = (r[1][2] + r[2][1]) / s;
75 q[3] = 0.25 * s;
76 }
77}
78
79}
80
81#endif
FbxTrs FbxDecomposeSdk(const double m[3][4])
void FbxRotationToQuat(const double r[3][3], double q[4])
Rotation matrix -> quaternion (w, x, y, z).
double r[3][3]
double s[3]
double t[3]