Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
process_markers.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
14#include "momentum/common/log.h"
18
19#include <tuple>
20
21namespace momentum {
22
23namespace {
24
33std::span<const GloveFrameData> validateAndSliceGloveData(
34 std::span<const GloveFrameData> gloveData,
35 const Character& character,
36 size_t markerFrames,
37 size_t firstFrame,
38 size_t lastFrame,
39 const char* label) {
40 if (gloveData.empty()) {
41 return {};
42 }
44 gloveData.size() != markerFrames,
45 "{} glove data has {} frames but marker data has {} frames",
46 label,
47 gloveData.size(),
48 markerFrames);
49 // Validate only the [firstFrame, lastFrame) window that is actually consumed
50 // downstream; frames outside the range are sliced away and never used, so a
51 // bad observation in an excluded frame should not abort the solve.
52 for (size_t frameIndex = firstFrame; frameIndex < lastFrame; ++frameIndex) {
53 const auto& frame = gloveData[frameIndex];
54 for (size_t obsIndex = 0; obsIndex < frame.size(); ++obsIndex) {
55 const auto& obs = frame[obsIndex];
56 if (!obs.valid) {
57 continue;
58 }
60 obs.jointName.empty(),
61 "{} glove observation has empty joint name at frame {}, observation {}",
62 label,
63 frameIndex,
64 obsIndex);
66 character.skeleton.getJointIdByName(obs.jointName) == kInvalidIndex,
67 "{} glove observation uses unknown joint '{}' at frame {}, observation {}",
68 label,
69 obs.jointName,
70 frameIndex,
71 obsIndex);
73 !obs.position.allFinite(),
74 "{} glove observation '{}' has non-finite position at frame {}, observation {}",
75 label,
76 obs.jointName,
77 frameIndex,
78 obsIndex);
80 !obs.orientation.coeffs().allFinite(),
81 "{} glove observation '{}' has non-finite orientation at frame {}, observation {}",
82 label,
83 obs.jointName,
84 frameIndex,
85 obsIndex);
87 obs.orientation.norm() <= 1e-6f,
88 "{} glove observation '{}' has zero orientation at frame {}, observation {}",
89 label,
90 obs.jointName,
91 frameIndex,
92 obsIndex);
93 }
94 }
95 return gloveData.subspan(firstFrame, lastFrame - firstFrame);
96}
97
98bool hasAnyGloveData(
99 std::span<const GloveFrameData> leftGloveData,
100 std::span<const GloveFrameData> rightGloveData) {
101 return !leftGloveData.empty() || !rightGloveData.empty();
102}
103
107std::vector<CameraKeypointData> sliceCameraKeypointData(
108 std::span<const CameraKeypointData> data,
109 size_t firstFrame,
110 size_t lastFrame) {
111 std::vector<CameraKeypointData> result;
112 if (data.empty()) {
113 return result;
114 }
115 result.reserve(data.size());
116 for (const auto& camData : data) {
117 CameraKeypointData sliced;
118 sliced.camera = camData.camera;
119 if (camData.frameData.size() >= lastFrame) {
120 sliced.frameData.assign(
121 camData.frameData.begin() + firstFrame, camData.frameData.begin() + lastFrame);
122 } else if (camData.frameData.size() > firstFrame) {
123 sliced.frameData.assign(camData.frameData.begin() + firstFrame, camData.frameData.end());
124 }
125 result.push_back(std::move(sliced));
126 }
127 return result;
128}
129
130} // namespace
131
133 momentum::Character& character,
135 std::span<const std::vector<momentum::Marker>> markerData,
136 const CalibrationConfig& calibrationConfig,
137 size_t firstFrame,
138 size_t maxFrames,
139 std::span<const GloveFrameData> leftGloveData,
140 std::span<const GloveFrameData> rightGloveData,
141 const std::optional<GloveConfig>& gloveConfig,
142 std::span<const CameraKeypointData> cameraKeypointData,
143 std::vector<size_t>* selectedFrameIndices,
144 Eigen::MatrixXf* selectedFrameMotion) {
146 firstFrame > markerData.size(),
147 "First frame {} can't exceed total frames {}",
148 firstFrame,
149 markerData.size());
150 const size_t lastFrame =
151 maxFrames > 0 ? std::min(firstFrame + maxFrames, markerData.size()) : markerData.size();
152 const std::span<const std::vector<momentum::Marker>> inputData(
153 markerData.data() + firstFrame, lastFrame - firstFrame);
155 inputData.size() < 2,
156 "Calibration requires at least 2 frames, got {} (from {} total with firstFrame={}, maxFrames={}).",
157 inputData.size(),
158 markerData.size(),
159 firstFrame,
160 maxFrames);
161
162 // Check the glove_config precondition before validating observations, so the
163 // specific "glove_config must be provided" error fires instead of a vaguer
164 // "unknown joint" error when the missing config would have added the joints.
166 hasAnyGloveData(leftGloveData, rightGloveData) && !gloveConfig,
167 "glove_config must be provided when left_glove_data or right_glove_data is non-empty.");
168
169 const auto leftGloveSlice = validateAndSliceGloveData(
170 leftGloveData, character, markerData.size(), firstFrame, lastFrame, "Left");
171 const auto rightGloveSlice = validateAndSliceGloveData(
172 rightGloveData, character, markerData.size(), firstFrame, lastFrame, "Right");
173
174 MT_CHECK(
175 !(calibrationConfig.globalScaleOnly & calibrationConfig.locatorsOnly),
176 "globalScaleOnly and locatorsOnly are exclusive; they cannot both be true.");
177
178 const auto slicedKeypointData =
179 sliceCameraKeypointData(cameraKeypointData, firstFrame, lastFrame);
180
181 if (calibrationConfig.locatorsOnly) {
182 // The output locators will be written to character.
183 calibrateLocators(inputData, calibrationConfig, identity, character);
184 } else {
185 // The output locators will be written to character. The output identity will be saved in the
186 // identity variable.
188 inputData,
189 calibrationConfig,
190 character,
191 identity,
192 {0.0f, 0.0f, 0.0f},
193 leftGloveSlice,
194 rightGloveSlice,
195 gloveConfig,
196 slicedKeypointData,
197 selectedFrameIndices,
198 selectedFrameMotion);
199 }
200}
201
202Eigen::MatrixXf processMarkers(
203 momentum::Character& character,
205 const std::vector<std::vector<momentum::Marker>>& markerData,
206 const TrackingConfig& trackingConfig,
207 const CalibrationConfig& calibrationConfig,
208 bool calibrate,
209 size_t firstFrame,
210 size_t maxFrames,
211 std::span<const GloveFrameData> leftGloveData,
212 std::span<const GloveFrameData> rightGloveData,
213 const std::optional<GloveConfig>& gloveConfig,
214 std::span<const CameraKeypointData> cameraKeypointData) {
216 firstFrame > markerData.size(),
217 "First frame {} can't exceed total frames {}",
218 firstFrame,
219 markerData.size());
220 const size_t lastFrame =
221 maxFrames > 0 ? std::min(firstFrame + maxFrames, markerData.size()) : markerData.size();
222 const std::span<const std::vector<momentum::Marker>> inputData(
223 markerData.data() + firstFrame, lastFrame - firstFrame);
225 inputData.empty(),
226 "Input marker data is empty (firstFrame={}, maxFrames={}).",
227 firstFrame,
228 maxFrames);
229
230 // Check the glove_config precondition before validating observations, so the
231 // specific "glove_config must be provided" error fires instead of a vaguer
232 // "unknown joint" error when the missing config would have added the joints.
234 hasAnyGloveData(leftGloveData, rightGloveData) && !gloveConfig,
235 "glove_config must be provided when left_glove_data or right_glove_data is non-empty.");
236
237 const auto leftGloveSlice = validateAndSliceGloveData(
238 leftGloveData, character, markerData.size(), firstFrame, lastFrame, "Left");
239 const auto rightGloveSlice = validateAndSliceGloveData(
240 rightGloveData, character, markerData.size(), firstFrame, lastFrame, "Right");
241
242 const auto slicedKeypointData =
243 sliceCameraKeypointData(cameraKeypointData, firstFrame, lastFrame);
244
245 // calibrate model and locators
246 if (calibrate) {
247 MT_CHECK(
248 !(calibrationConfig.globalScaleOnly & calibrationConfig.locatorsOnly),
249 "globalScaleOnly and locatorsOnly are exclusive; they cannot both be true.");
250
251 if (calibrationConfig.locatorsOnly) {
252 // The output locators will be written to character.
253 calibrateLocators(inputData, calibrationConfig, identity, character);
254 } else {
255 // The output locators will be written to character. The output identity will be saved in the
256 // identity variable.
258 inputData,
259 calibrationConfig,
260 character,
261 identity,
262 {0.0f, 0.0f, 0.0f},
263 leftGloveSlice,
264 rightGloveSlice,
265 gloveConfig,
266 slicedKeypointData);
267 }
268 }
269
270 // track motion; identity parameters will be repeated for every frame in finalMotion.
271 // If glove data is provided and the character has glove bones (from calibration),
272 // the solver will attach constraints to them. If no glove bones exist yet,
273 // constraints fall back to the wrist joints directly.
274 Eigen::MatrixXf finalMotion = trackPosesPerframe(
275 inputData,
276 character,
277 identity,
278 trackingConfig,
279 1,
280 leftGloveSlice,
281 rightGloveSlice,
282 gloveConfig);
283
284 if (trackingConfig.debug) {
285 auto errors = getLocatorError(inputData, finalMotion, character);
286 MT_LOGI("Average marker error: {}", errors.first);
287 MT_LOGI("Max marker error: {}", errors.second);
288 }
289 return finalMotion;
290}
291
293 const std::string& inputMarkerFile,
294 const std::string& outputFile,
295 const TrackingConfig& trackingConfig,
296 const CalibrationConfig& calibrationConfig,
297 const ModelOptions& modelOptions,
298 bool calibrate,
299 size_t firstFrame,
300 size_t maxFrames) {
301 // validate output file extension and quit early
302 const auto outExtension = filesystem::path(outputFile).extension();
303 if (outExtension != ".fbx" && outExtension != ".gltf" && outExtension != ".glb") {
304 MT_LOGE(
305 "Invalid output file type {}; supported types are glb, gltf, and fbx",
306 outExtension.string());
307 return;
308 }
309
310 // read input character and optionally its identity parameters
311 auto [character, identity] = loadCharacterWithIdentity(modelOptions);
312
313 // read marker data
314 std::vector<std::string> validMarkerNames;
315 for (const auto& locator : character.locators) {
316 validMarkerNames.push_back(locator.name);
317 }
318 const auto actors = momentum::loadMarkers(inputMarkerFile, UpVector::Y, validMarkerNames);
319
320 // first try to see if we have an actor with the same name as the character
321 std::optional<MarkerSequence> actor;
322 for (const auto& a : actors) {
323 if (a.name == character.name) {
324 actor = a;
325 break;
326 }
327 }
328
329 // if not, get the main actor
330 if (!actor) {
331 const int index = findMainSubjectIndex(actors);
332 if (index >= 0) {
333 actor = actors[index];
334 }
335 }
336
337 // did we find an actor?
338 if (!actor) {
339 MT_LOGE("No marker sequence found in the marker file: {}", inputMarkerFile);
340 return;
341 }
342 try {
343 Eigen::MatrixXf finalMotion = processMarkers(
344 character,
345 identity,
346 actor->frames,
347 trackingConfig,
348 calibrationConfig,
349 calibrate,
350 firstFrame,
351 maxFrames);
352
353 // name the character after the actor name
354 character.name = actor->name;
355
356 // save results
357 const size_t lastFrame = maxFrames > 0 ? std::min(firstFrame + maxFrames, actor->frames.size())
358 : actor->frames.size();
360 outputFile,
361 character,
362 identity,
363 finalMotion,
364 std::span<const std::vector<momentum::Marker>>(
365 actor->frames.data() + firstFrame, actor->frames.data() + lastFrame),
366 actor->fps);
367 MT_LOGI("{} saved", outputFile);
368 } catch (std::exception& e) {
369 MT_LOGE("Failed to track the markers from file {}, exception: {}", inputMarkerFile, e.what());
370 }
371}
372
373} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
#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_LOGI(...)
Definition log.h:179
#define MT_LOGE(...)
Definition log.h:181
void processMarkerFile(const std::string &inputMarkerFile, const std::string &outputFile, const TrackingConfig &trackingConfig, const CalibrationConfig &calibrationConfig, const ModelOptions &modelOptions, bool calibrate, size_t firstFrame, size_t maxFrames)
Runs marker tracking on an input marker file (e.g.
std::pair< float, float > getLocatorError(std::span< const std::vector< momentum::Marker > > markerData, const MatrixXf &motion, momentum::Character &character)
Compute average and maximum marker tracking errors across all frames.
@ Y
Y-axis up vector.
void calibrateMarkers(momentum::Character &character, momentum::ModelParameters &identity, std::span< const std::vector< momentum::Marker > > markerData, const CalibrationConfig &calibrationConfig, size_t firstFrame, size_t maxFrames, std::span< const GloveFrameData > leftGloveData, std::span< const GloveFrameData > rightGloveData, const std::optional< GloveConfig > &gloveConfig, std::span< const CameraKeypointData > cameraKeypointData, std::vector< size_t > *selectedFrameIndices, Eigen::MatrixXf *selectedFrameMotion)
Calibrates a character model using marker data without running full tracking.
std::vector< MarkerSequence > loadMarkers(const std::string &filename, UpVector up, std::span< const std::string > validMarkerNames)
Loads all actor sequences from a marker file (c3d, trc, glb) and converts the positions to the target...
Definition marker_io.cpp:32
void saveMotion(const std::string &outFile, const momentum::Character &character, const momentum::ModelParameters &identity, Eigen::MatrixXf &finalMotion, std::span< const std::vector< momentum::Marker > > markerData, const double fps, const bool saveMarkerMesh, std::span< const int64_t > timestamps)
Save the given character and motion to a GLB or FBX file.
Eigen::MatrixXf processMarkers(momentum::Character &character, momentum::ModelParameters &identity, const std::vector< std::vector< momentum::Marker > > &markerData, const TrackingConfig &trackingConfig, const CalibrationConfig &calibrationConfig, bool calibrate, size_t firstFrame, size_t maxFrames, std::span< const GloveFrameData > leftGloveData, std::span< const GloveFrameData > rightGloveData, const std::optional< GloveConfig > &gloveConfig, std::span< const CameraKeypointData > cameraKeypointData)
Processes marker data for a character model.
Eigen::MatrixXf trackPosesPerframe(const std::span< const std::vector< Marker > > markerData, const Character &character, const ModelParameters &globalParams, const TrackingConfig &config, const size_t frameStride, std::span< const GloveFrameData > leftGloveData, std::span< const GloveFrameData > rightGloveData, const std::optional< GloveConfig > &gloveConfig)
Track poses independently per frame with fixed character identity.
int findMainSubjectIndex(std::span< const MarkerSequence > markerSequences)
Finds the "main subject" from a vector of MarkerSequences.
void calibrateLocators(const std::span< const std::vector< Marker > > markerData, const CalibrationConfig &config, const ModelParameters &identity, Character &character)
Calibrate only locator positions with fixed character identity parameters.
void calibrateModel(const std::span< const std::vector< Marker > > markerData, const CalibrationConfig &config, Character &character, ModelParameters &identity, const std::array< float, 3 > &regularizerWeights, std::span< const GloveFrameData > leftGloveData, std::span< const GloveFrameData > rightGloveData, const std::optional< GloveConfig > &gloveConfig, std::span< const CameraKeypointData > cameraKeypointData, std::vector< size_t > *selectedFrameIndices, Eigen::MatrixXf *selectedFrameMotion)
ModelParametersT< float > ModelParameters
Definition types.h:105
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
std::tuple< momentum::Character, momentum::ModelParameters > loadCharacterWithIdentity(const ModelOptions &modelFiles)
bool debug
True to print and save debug information.
Configuration for running body and/or locator calibration.
bool locatorsOnly
True to calibrate only the locators and not the body.
bool globalScaleOnly
True to only solve for a global body scale without changing individual bone length.
Per-camera 2D keypoint data for all frames.
Camera camera
Camera intrinsics and extrinsics (world-space).
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
Configuration for pose tracking given a calibrated body and locators.