15#include <ezc3d/ezc3d_all.h>
19#include <unordered_map>
29std::string findSubjectName(
const std::string& markerLabelIn) {
30 constexpr auto kNamespaceSep =
':';
31 auto sepPos = markerLabelIn.find(kNamespaceSep);
32 if (sepPos == std::string::npos) {
33 constexpr auto kUnderscoreSep =
"_";
34 sepPos = markerLabelIn.find_last_of(kUnderscoreSep);
35 if (sepPos != std::string::npos) {
37 auto candidateName = markerLabelIn.substr(0, sepPos);
38 std::transform(candidateName.begin(), candidateName.end(), candidateName.begin(), ::tolower);
39 const std::set<std::string> kSideStrSet = {
"l",
"r",
"left",
"right"};
40 if (kSideStrSet.find(candidateName) != kSideStrSet.end()) {
48 return markerLabelIn.substr(0, sepPos);
51bool isMarkerValid(
const std::string_view label, std::span<const std::string> validMarkerNames) {
56 if ((label.size() >= 2 && label[label.size() - 2] ==
'-') ||
57 (label.size() >= 3 && label[label.size() - 3] ==
'-')) {
62 if (!validMarkerNames.empty()) {
63 if (std::find(validMarkerNames.begin(), validMarkerNames.end(), label) ==
64 validMarkerNames.end()) {
77std::optional<std::string> getValidatedUnit(
const ezc3d::ParametersNS::GroupNS::Group& pointGroup) {
78 constexpr auto kUnitStr =
"UNITS";
79 const auto& unit = pointGroup.parameter(kUnitStr).valuesAsString();
80 if (unit.size() != 1) {
81 MT_LOGE(
"{}: Invalid c3d file: no unit information found!", __func__);
84 const auto& unitStr = unit[0];
85 if (unitStr !=
"mm" && unitStr !=
"m" && unitStr !=
"cm" && unitStr !=
"dm") {
86 MT_LOGE(
"{}: Unknown unit string '{}' found in the file.", __func__, unitStr);
91 "{}: Unit '{}' is not mm. Translating a C3D file that contains 3D point data stored in any units other than millimeters is extremely complex and any mistakes will render the file invalid.",
100std::vector<std::string> loadPointLabels(
101 const ezc3d::ParametersNS::GroupNS::Group& pointGroup,
102 size_t kPointsPerFrame) {
103 constexpr auto kLabelStr =
"LABELS";
104 constexpr auto kNumLabelsPerSection = 255;
105 constexpr size_t kAdditionSectionStartIndex = 2;
107 auto pointLabels = pointGroup.parameter(kLabelStr).valuesAsString();
108 const size_t numOfExtraSections = kPointsPerFrame / kNumLabelsPerSection;
109 pointLabels.reserve(kPointsPerFrame);
110 for (
size_t sectionId = kAdditionSectionStartIndex;
111 sectionId < kAdditionSectionStartIndex + numOfExtraSections;
113 const auto labelStr = kLabelStr + std::to_string(sectionId);
114 const auto& additionalPointLabels = pointGroup.parameter(labelStr).valuesAsString();
116 pointLabels.end(), additionalPointLabels.begin(), additionalPointLabels.end());
118 if (pointLabels.size() < kPointsPerFrame) {
119 MT_LOGE(
"{}: Number of point labels loaded isn't consistent with the header! ", __func__);
122 pointLabels.resize(kPointsPerFrame);
128std::unordered_map<std::string, std::vector<size_t>> groupPointsBySubject(
129 std::span<const std::string> pointLabels) {
130 std::unordered_map<std::string, std::vector<size_t>> subjectNameMap;
131 subjectNameMap.reserve(pointLabels.size());
132 for (
size_t iLabel = 0; iLabel < pointLabels.size(); ++iLabel) {
133 subjectNameMap[findSubjectName(pointLabels[iLabel])].push_back(iLabel);
135 return subjectNameMap;
141std::vector<std::pair<int, int>> buildSubjectStructures(
142 const std::unordered_map<std::string, std::vector<size_t>>& subjectNameMap,
143 std::span<const std::string> pointLabels,
144 std::span<const std::string> validMarkerNames,
146 std::vector<MarkerSequence>& resultAnim,
147 std::vector<std::vector<Marker>>& templateActors) {
148 resultAnim.assign(subjectNameMap.size(), {});
149 templateActors.assign(subjectNameMap.size(), {});
150 std::vector<std::pair<int, int>> markerMap(pointLabels.size(), {-1, -1});
152 for (
const auto& [subjectName, pointIndices] : subjectNameMap) {
157 auto& actorSequence = resultAnim.at(actorId);
158 actorSequence.fps = fps;
159 actorSequence.name = subjectName;
160 auto& templateActor = templateActors.at(actorId);
161 for (
const auto kPointIdx : pointIndices) {
162 if (kPointIdx >= pointLabels.size()) {
165 auto pointLabel = pointLabels[kPointIdx];
166 if (!subjectName.empty()) {
167 pointLabel = pointLabel.substr(subjectName.size() + 1);
169 if (!isMarkerValid(pointLabel, validMarkerNames)) {
174 markerMap.at(kPointIdx) = {
static_cast<int>(actorId), markerCount};
176 marker.
name = pointLabel;
177 marker.occluded =
true;
178 templateActor.push_back(marker);
188bool updateFrameMarkers(
189 const ezc3d::DataNS::Frame& frameData,
190 std::span<
const std::pair<int, int>> markerMap,
192 const std::string& unitStr,
193 std::vector<std::vector<Marker>>& templateActors) {
194 for (
auto& templateActor : templateActors) {
195 for (
auto& marker : templateActor) {
196 marker.occluded =
true;
200 bool hasVisible =
false;
201 const auto& framePoints = frameData.points().points();
202 for (
size_t pointId = 0; pointId < markerMap.size(); ++pointId) {
203 const auto [kActorId, kMarkerId] = markerMap[pointId];
204 if (kActorId == -1 || kMarkerId == -1) {
207 const auto& pointData = framePoints[pointId];
208 Vector3d pos{pointData.x(), pointData.y(), pointData.z()};
209 if (std::isnan(pos[0]) || std::isnan(pos[1]) || std::isnan(pos[2])) {
212 if (pos == Eigen::Vector3d::Zero()) {
217 if (pointData.residual() < 0) {
224 if (
static_cast<size_t>(kActorId) >= templateActors.size() ||
225 static_cast<size_t>(kMarkerId) >= templateActors.at(kActorId).size()) {
228 auto& marker = templateActors.at(kActorId).at(kMarkerId);
229 marker.occluded =
false;
237std::vector<MarkerSequence>
238loadC3dFromObject(ezc3d::c3d& c3dFile,
UpVector up, std::span<const std::string> validMarkerNames) {
240 const auto& header = c3dFile.header();
241 const size_t kPointsPerFrame = header.nb3dPoints();
242 const auto kFrameCount = header.nbFrames();
243 const float fps = header.frameRate();
244 MT_LOGD(
"{}: Found {} frames", __func__, kFrameCount);
245 MT_LOGD(
"{}: Frame rate {}", __func__, fps);
247 constexpr auto kPointGroupStr =
"POINT";
248 const auto& pointGroup = c3dFile.parameters().group(kPointGroupStr);
250 const auto unitStr = getValidatedUnit(pointGroup);
251 if (!unitStr.has_value()) {
255 const auto pointLabels = loadPointLabels(pointGroup, kPointsPerFrame);
256 if (pointLabels.empty()) {
260 const auto subjectNameMap = groupPointsBySubject(pointLabels);
261 const size_t kNumOfSubjects = subjectNameMap.size();
262 std::vector<MarkerSequence> resultAnim(kNumOfSubjects);
263 std::vector<std::vector<Marker>> templateActors(kNumOfSubjects);
264 const auto markerMap = buildSubjectStructures(
265 subjectNameMap, pointLabels, validMarkerNames, fps, resultAnim, templateActors);
267 bool hasAnim =
false;
268 const auto& frames = c3dFile.data().frames();
269 for (
int frameId = 0; frameId < kFrameCount; ++frameId) {
270 hasAnim |= updateFrameMarkers(frames[frameId], markerMap, up, *unitStr, templateActors);
271 for (
size_t actorId = 0; actorId < templateActors.size(); ++actorId) {
272 resultAnim[actorId].frames.push_back(templateActors[actorId]);
280 }
catch (std::exception& e) {
281 MT_LOGE(
"{}: Exception: {}", __func__, e.what());
284 MT_LOGE(
"{}: Unknown c3d reading error", __func__);
291std::vector<MarkerSequence>
292loadC3d(
const std::string& filename,
UpVector up, std::span<const std::string> validMarkerNames) {
294 ezc3d::c3d c3dFile(filename);
295 return loadC3dFromObject(c3dFile, up, validMarkerNames);
296 }
catch (
const std::exception& e) {
297 MT_LOGE(
"{}: failed to open {}: {}", __func__, filename, e.what());
302#ifdef MOMENTUM_WITH_EZC3D_ISTREAM
303std::vector<MarkerSequence>
loadC3d(
304 std::span<const std::byte> bytes,
306 std::span<const std::string> validMarkerNames) {
308 ispanstream stream(bytes);
309 ezc3d::c3d c3dFile(
static_cast<std::istream&
>(stream));
310 return loadC3dFromObject(c3dFile, up, validMarkerNames);
311 }
catch (
const std::exception& e) {
312 MT_LOGE(
"{}: failed to read c3d from buffer ({} bytes): {}", __func__, bytes.size(), e.what());
#define MT_LOGW_IF(condition,...)
Vector3< double > Vector3d
std::vector< MarkerSequence > loadC3d(const std::string &filename, UpVector up, std::span< const std::string > validMarkerNames)
Loads all the subjects from a C3D file into a vector of MarkerSequences.
UpVector
This enumeration is used to define the primary up vector directions for various coordinate systems an...
Vector3< T > toMomentumVector3(const Vector3< T > &vec, UpVector up, Unit unit)
This function converts a 3D vector in the mocap marker coordinate system to the Momentum coordinate s...
A single motion capture marker observation (position, occlusion, confidence).
std::string name
The name of the marker.