Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
locator_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"
17
18#include <nlohmann/json.hpp>
19#include <gsl/gsl>
20
21#include <fstream>
22#include <unordered_set>
23
24namespace momentum {
25
26namespace {
27
28std::string firstDuplicate(const LocatorList& locators) {
29 std::unordered_set<std::string> locatorNames;
30 for (const auto& l : locators) {
31 auto itr = locatorNames.find(l.name);
32 if (itr != locatorNames.end()) {
33 return l.name;
34 }
35 locatorNames.insert(itr, l.name);
36 }
37 return "";
38}
39
40// Convert byte index to line and column numbers
41std::pair<size_t, size_t> byteIndexToLineColumn(std::string_view input, size_t byteIndex) {
42 size_t line = 1;
43 size_t column = 1;
44
45 for (size_t i = 0; i < byteIndex && i < input.size(); ++i) {
46 if (input[i] == '\n') {
47 ++line;
48 column = 1;
49 } else {
50 ++column;
51 }
52 }
53
54 return {line, column};
55}
56
57} // namespace
58
60 const filesystem::path& filename,
61 const Skeleton& skeleton,
62 const ParameterTransform& parameterTransform) {
63 std::ifstream instream(filename, std::ios::binary);
64 MT_THROW_IF(!instream.is_open(), "Cannot find file {}", filename.string());
65 instream.seekg(0, std::ios::end);
66 auto length = instream.tellg();
67 instream.seekg(0, std::ios::beg);
68
69 std::vector<char> buffer(length);
70 instream.read(buffer.data(), length);
71
73 std::span<const std::byte>(reinterpret_cast<const std::byte*>(buffer.data()), length),
74 skeleton,
75 parameterTransform);
76}
77
79 std::span<const std::byte> rawData,
80 const Skeleton& skeleton,
81 const ParameterTransform& parameterTransform) {
82 const std::string_view input(reinterpret_cast<const char*>(rawData.data()), rawData.size());
83
84 LocatorList res;
85
86 try {
87 const nlohmann::json j = nlohmann::json::parse(input);
88
89 if (!j.contains("locators") || !j["locators"].is_array()) {
90 return res;
91 }
92
93 const SkeletonState state(parameterTransform.bindPose(), skeleton);
94
95 for (const auto& locatorJson : j["locators"]) {
96 Locator l;
97
98 // Read lock fields
99 l.locked.x() = locatorJson.value("lockX", 0);
100 l.locked.y() = locatorJson.value("lockY", 0);
101 l.locked.z() = locatorJson.value("lockZ", 0);
102
103 // Read name
104 l.name = locatorJson.value("name", std::string());
105
106 // Read parent index or parent name
107 l.parent = locatorJson.value("parent", kInvalidIndex);
108 if (locatorJson.contains("parentName")) {
109 const std::string parentName = locatorJson["parentName"].get<std::string>();
110 for (size_t k = 0; k < skeleton.joints.size(); k++) {
111 if (skeleton.joints[k].name == parentName) {
112 l.parent = static_cast<int>(k);
113 break;
114 }
115 }
116 if (l.parent == kInvalidIndex) {
117 MT_LOGW("Invalid parent name: {}", parentName);
118 }
119 }
120
121 // Skip locator if it has no parent
122 if (l.parent == kInvalidIndex) {
123 MT_LOGW(
124 "Skipping locator '{}' because it has no valid parent",
125 l.name.empty() ? "(unnamed)" : l.name);
126 continue;
127 }
128
129 // Read weight
130 l.weight = locatorJson.value("weight", 1.0f);
131
132 // Read offset
133 const bool hasOffsetX = locatorJson.contains("offsetX");
134 const bool hasOffsetY = locatorJson.contains("offsetY");
135 const bool hasOffsetZ = locatorJson.contains("offsetZ");
136 l.offset.x() = locatorJson.value("offsetX", 0.0f);
137 l.offset.y() = locatorJson.value("offsetY", 0.0f);
138 l.offset.z() = locatorJson.value("offsetZ", 0.0f);
139
140 // Check for partial offset specification
141 const bool hasAnyOffset = hasOffsetX || hasOffsetY || hasOffsetZ;
142 const bool hasAllOffset = hasOffsetX && hasOffsetY && hasOffsetZ;
143 if (hasAnyOffset && !hasAllOffset) {
144 MT_LOGW(
145 "Locator '{}' has partial offset specification (offsetX: {}, offsetY: {}, offsetZ: {}). "
146 "If any offset component is specified, all three should be provided.",
147 l.name.empty() ? "(unnamed)" : l.name,
148 hasOffsetX,
149 hasOffsetY,
150 hasOffsetZ);
151 }
152
153 // Read global coordinates and convert to local offset if present
154 const bool hasGlobalX = locatorJson.contains("globalX");
155 const bool hasGlobalY = locatorJson.contains("globalY");
156 const bool hasGlobalZ = locatorJson.contains("globalZ");
157 const bool hasAnyGlobal = hasGlobalX || hasGlobalY || hasGlobalZ;
158 const bool hasAllGlobal = hasGlobalX && hasGlobalY && hasGlobalZ;
159
160 // Check for partial global specification
161 if (hasAnyGlobal && !hasAllGlobal) {
162 MT_LOGW(
163 "Locator '{}' has partial global specification (globalX: {}, globalY: {}, globalZ: {}). "
164 "If any global component is specified, all three should be provided.",
165 l.name.empty() ? "(unnamed)" : l.name,
166 hasGlobalX,
167 hasGlobalY,
168 hasGlobalZ);
169 }
170
171 // Check for both global and local offset specification
172 if (hasAnyGlobal && hasAnyOffset) {
173 MT_LOGW(
174 "Locator '{}' has both global (globalX/Y/Z) and local (offsetX/Y/Z) offset specification. "
175 "Only one type of offset should be specified. Global offset will take precedence.",
176 l.name.empty() ? "(unnamed)" : l.name);
177 }
178
179 if (hasAnyGlobal) {
180 Vector3f global;
181 global.x() = locatorJson.value("globalX", 0.0f);
182 global.y() = locatorJson.value("globalY", 0.0f);
183 global.z() = locatorJson.value("globalZ", 0.0f);
184 l.offset = state.jointState[l.parent].transform.inverse() * global;
185 }
186
187 // Read limit weights
188 l.limitWeight[0] = locatorJson.value("limitWeightX", 0.0f);
189 l.limitWeight[1] = locatorJson.value("limitWeightY", 0.0f);
190 l.limitWeight[2] = locatorJson.value("limitWeightZ", 0.0f);
191
192 // Read skin attachment fields
193 l.attachedToSkin = (locatorJson.value("attachedToSkin", 0) != 0);
194 l.skinOffset = locatorJson.value("skinOffset", 0.0f);
195
196 l.limitOrigin = l.offset;
197 res.push_back(l);
198 }
199 } catch (const nlohmann::json::parse_error& e) {
200 const auto [line, column] = byteIndexToLineColumn(input, e.byte);
201 MT_THROW("Failed to parse locators JSON at line {}, column {}: {}", line, column, e.what());
202 }
203
204 std::string dup = firstDuplicate(res);
205 MT_THROW_IF(!dup.empty(), "Duplicated locator {} found", dup);
206
207 return res;
208}
209
211 const filesystem::path& filename,
212 const LocatorList& locators,
213 const Skeleton& skeleton,
214 const LocatorSpace space) {
215 const SkeletonState state(VectorXf::Zero(skeleton.joints.size() * kParametersPerJoint), skeleton);
216 const LocatorState lstate(state, locators);
217
218 nlohmann::json j;
219 j["locators"] = nlohmann::json::array();
220
221 for (size_t i = 0; i < locators.size(); i++) {
222 nlohmann::json locatorJson;
223
224 locatorJson["name"] = locators[i].name;
225
226 if (space == LocatorSpace::Global) {
227 locatorJson["globalX"] = lstate.position[i].x();
228 locatorJson["globalY"] = lstate.position[i].y();
229 locatorJson["globalZ"] = lstate.position[i].z();
230 } else if (space == LocatorSpace::Local) {
231 locatorJson["offsetX"] = locators[i].offset.x();
232 locatorJson["offsetY"] = locators[i].offset.y();
233 locatorJson["offsetZ"] = locators[i].offset.z();
234 }
235
236 locatorJson["lockX"] = locators[i].locked.x();
237 locatorJson["lockY"] = locators[i].locked.y();
238 locatorJson["lockZ"] = locators[i].locked.z();
239 locatorJson["weight"] = locators[i].weight;
240
241 if (locators[i].limitWeight[0] != 0.0f) {
242 locatorJson["limitWeightX"] = locators[i].limitWeight.x();
243 }
244 if (locators[i].limitWeight[1] != 0.0f) {
245 locatorJson["limitWeightY"] = locators[i].limitWeight.y();
246 }
247 if (locators[i].limitWeight[2] != 0.0f) {
248 locatorJson["limitWeightZ"] = locators[i].limitWeight.z();
249 }
250
251 if (locators[i].attachedToSkin) {
252 locatorJson["attachedToSkin"] = 1;
253 }
254 if (locators[i].skinOffset != 0.0f) {
255 locatorJson["skinOffset"] = locators[i].skinOffset;
256 }
257
258 MT_CHECK(
259 0 <= locators[i].parent && locators[i].parent < skeleton.joints.size(),
260 "Invalid joint index");
261 if (!skeleton.joints.empty() && locators[i].parent < skeleton.joints.size()) {
262 locatorJson["parentName"] = skeleton.joints[locators[i].parent].name;
263 }
264
265 j["locators"].push_back(locatorJson);
266 }
267
268 std::ofstream o(filename);
269 o << j.dump(1, '\t') << '\n';
270}
271
272} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
#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
SkeletonT< float > Skeleton
Definition fwd.h:263
void saveLocators(const filesystem::path &filename, const LocatorList &locators, const Skeleton &skeleton, const LocatorSpace space)
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
SkeletonStateT< float > SkeletonState
Definition fwd.h:282
constexpr size_t kParametersPerJoint
Definition types.h:21
LocatorList loadLocators(const filesystem::path &filename, const Skeleton &skeleton, const ParameterTransform &parameterTransform)
LocatorList loadLocatorsFromBuffer(std::span< const std::byte > rawData, const Skeleton &skeleton, const ParameterTransform &parameterTransform)
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
Vector3< float > Vector3f
Definition types.h:251
std::vector< Locator > LocatorList
A collection of locators attached to a skeleton.
Definition locator.h:79
Tracks the current world positions of locators in a skeleton.
std::vector< Vector3f > position
World-space positions of all locators, updated when the skeleton moves.
Represents a point attached to a joint in a skeleton.
Definition locator.h:19
float weight
Influence weight when used as a constraint in error functions.
Definition locator.h:32
size_t parent
Index of the parent joint in the skeleton.
Definition locator.h:23
std::string name
Definition locator.h:20
float skinOffset
Offset from the skin surface, used when solving for body shape using locators.
Definition locator.h:46
Vector3f limitWeight
Per-axis strength pulling the locator back toward limitOrigin.
Definition locator.h:39
Vector3i locked
Per-axis lock flags (x, y, z): 1 = locked, 0 = free.
Definition locator.h:29
bool attachedToSkin
True if the locator is attached to the skin of a person (e.g.
Definition locator.h:43
Vector3f offset
Position in the parent joint's local coordinate frame.
Definition locator.h:26
Vector3f limitOrigin
Reference position for limit constraints; typically equals offset when loaded.
Definition locator.h:35
JointParametersT< T > bindPose() const
Return bind pose joint parameters (same as the rest pose here).
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
Definition skeleton.h:25