30constexpr const char* kParameterTransformSection =
"ParameterTransform";
31constexpr const char* kParameterSetsSection =
"ParameterSets";
32constexpr const char* kPoseConstraintsSection =
"PoseConstraints";
33constexpr const char* kParameterLimitsSection =
"Limits";
35bool isKnownSection(
const std::string& sectionName) {
36 return sectionName == kParameterTransformSection || sectionName == kParameterSetsSection ||
37 sectionName == kPoseConstraintsSection || sectionName == kParameterLimitsSection;
40std::unordered_map<std::string, SectionContent> loadMomentumModelCommon(std::istream& input) {
42 MT_LOGW(
"Unable to read parameter transform data.");
46 std::unordered_map<std::string, SectionContent> result;
47 std::string sectionName;
48 std::string sectionContent;
49 size_t sectionStartLine = 0;
50 size_t linesNotInSectionCount = 0;
51 constexpr size_t kMaxLinesNotInSectionWarnings = 5;
54 size_t lineNumber = 0;
57 line =
trim(line.substr(0, line.find_first_of(
'#')));
63 if (line ==
"Momentum Model Definition V1.0") {
68 "Invalid model definition file; expected 'Momentum Model Definition V1.0', got {}", line);
74 line =
trim(line.substr(0, line.find_first_of(
'#')));
82 static const re2::RE2 reg(R
"(\[(\w+)\])");
83 std::string newSectionName;
84 if (re2::RE2::FullMatch(line, reg, &newSectionName)) {
86 if (!sectionName.empty() && !sectionContent.empty()) {
87 if (isKnownSection(sectionName)) {
88 result[sectionName].addSegment(sectionContent, sectionStartLine);
93 if (!isKnownSection(newSectionName)) {
94 MT_LOGW(
"Unexpected section found at line {}: [{}]", lineNumber, newSectionName);
98 sectionName = newSectionName;
99 sectionContent.clear();
100 sectionStartLine = lineNumber + 1;
101 }
else if (!sectionName.empty()) {
103 if (isKnownSection(sectionName)) {
104 sectionContent += line +
"\n";
108 if (linesNotInSectionCount < kMaxLinesNotInSectionWarnings) {
109 MT_LOGW(
"Line {} is not in a section and is not a comment: {}", lineNumber, line);
110 ++linesNotInSectionCount;
111 if (linesNotInSectionCount == kMaxLinesNotInSectionWarnings) {
112 MT_LOGW(
"Suppressing further warnings about lines not in sections");
119 if (!sectionName.empty() && !sectionContent.empty()) {
120 if (isKnownSection(sectionName)) {
121 result[sectionName].addSegment(sectionContent, sectionStartLine);
128std::tuple<ParameterTransform, ParameterLimits> loadModelDefinitionFromStream(
129 std::istream& instream,
131 MT_THROW_IF(!instream,
"Unable to read parameter transform data.");
133 const auto sections = loadMomentumModelCommon(instream);
135 std::tuple<ParameterTransform, ParameterLimits> res;
139 const auto ptIt = sections.find(kParameterTransformSection);
140 if (ptIt == sections.end()) {
146 const auto psIt = sections.find(kParameterSetsSection);
147 if (psIt != sections.end()) {
151 const auto pcIt = sections.find(kPoseConstraintsSection);
152 if (pcIt != sections.end()) {
156 const auto plIt = sections.find(kParameterLimitsSection);
157 if (plIt != sections.end()) {
165 std::vector<Eigen::Triplet<float>>& triplets,
167 const std::vector<std::string>& pTokens,
170 size_t attributeIndex,
171 const std::string& line) {
173 const auto dtokens =
tokenize(pTokens[1],
"+");
174 for (
const auto& dtoken : dtokens) {
176 const auto stokens =
tokenize(dtoken,
"*");
178 if (stokens.size() != 2) {
179 if (stokens.size() != 1) {
185 const float weight = gsl::narrow_cast<float>(std::stod(stokens[0]));
186 pt.offsets(pindex) = weight;
191 const float weight = gsl::narrow_cast<float>(std::stod(stokens[0]));
193 const std::string& parameterName =
trim(stokens[1]);
195 for (
size_t d = 0; d < pt.name.size(); d++) {
196 if (pt.name[d] == parameterName) {
197 parameterIndex =
static_cast<int>(d);
203 const size_t refJointIndex =
204 skeleton.getJointIdByName(parameterName.substr(0, parameterName.find_first_of(
'.')));
207 const std::string jpString = parameterName.substr(parameterName.find_first_of(
'.') + 1);
210 refJointParameter = l;
218 parameterIndex =
static_cast<int>(pt.name.size());
219 pt.name.push_back(parameterName);
222 triplets.emplace_back(
224 static_cast<int>(parameterIndex),
232 for (
size_t tr = 0; tr < triplets.size(); tr++) {
233 const auto& t = triplets[tr];
234 if (
static_cast<size_t>(t.row()) == refJointId) {
235 triplets.emplace_back(
237 static_cast<int>(t.col()),
243 triplets.emplace_back(
245 static_cast<int>(parameterIndex),
248 MT_THROW(
"Could not parse channel expression : {}", line);
255std::unordered_map<std::string, std::string>
loadMomentumModel(
const filesystem::path& filename) {
256 if (filename.empty()) {
260 std::ifstream infile(filename);
261 MT_THROW_IF(!infile.is_open(),
"Cannot find file {}", filename.string());
262 const auto sections = loadMomentumModelCommon(infile);
264 std::unordered_map<std::string, std::string> result;
265 for (
const auto& [sectionName, content] : sections) {
266 result[sectionName] = content.toString();
272 std::span<const std::byte> buffer) {
273 if (buffer.empty()) {
278 const auto sections = loadMomentumModelCommon(inputStream);
280 std::unordered_map<std::string, std::string> result;
281 for (
const auto& [sectionName, content] : sections) {
282 result[sectionName] = content.toString();
296 std::vector<Eigen::Triplet<float>> triplets;
298 auto iterator = content.
begin();
300 while (iterator.getline(line)) {
301 const size_t lineIndex = iterator.currentLine();
304 line = line.substr(0, line.find_first_of(
'#'));
307 if (
trim(line).empty()) {
314 const auto pTokens =
tokenize(line,
"=");
315 if (pTokens.size() != 2) {
317 "Ignoring invalid line under [ParameterTransform] section at line {}: {}",
324 const auto aTokens =
tokenize(pTokens[0],
".");
326 aTokens.size() != 2,
"Unknown joint name in expression at line {}: {}", lineIndex, line);
332 "Unknown joint name in expression at line {}: {}",
338 const auto trimName =
trim(aTokens[1]);
349 "Unknown channel name in expression at line {}: {}",
357 parseParameter(triplets, pt, pTokens, skeleton, jointIndex, attributeIndex, line);
363 static_cast<int>(pt.
name.size()));
368 std::begin(triplets),
370 [](
const Eigen::Triplet<float>& t) {
return t.value() == 0.0f; }),
373 pt.
transform.setFromTriplets(triplets.begin(), triplets.end());
392 auto iterator = content.
begin();
394 while (iterator.getline(line)) {
395 const size_t lineIndex = iterator.currentLine();
398 line = line.substr(0, line.find_first_of(
'#'));
401 if (
trim(line).empty()) {
406 if (line.find(
"parameterset") != 0) {
408 "Ignoring invalid line under [ParameterSets] section at line {}: {}", lineIndex, line);
413 const auto pTokens =
tokenize(line,
" \t\r\n");
416 "Could not parse parameterset line in parameter configuration at line {}: {}",
421 for (
size_t i = 2; i < pTokens.size(); i++) {
422 const std::string& parameterName =
trim(pTokens[i]);
424 for (
size_t d = 0; d < pt.
name.size(); d++) {
425 if (pt.
name[d] == parameterName) {
433 "Could not parse parameterset line in parameter configuration at line {}: {}. Found unknown parameter name {}.",
438 ps.set(parameterIndex,
true);
441 result[pTokens[1]] = ps;
461 auto iterator = content.
begin();
463 while (iterator.getline(line)) {
464 const size_t lineIndex = iterator.currentLine();
467 line = line.substr(0, line.find_first_of(
'#'));
470 if (
trim(line).empty()) {
475 if (line.find(
"poseconstraints") != 0) {
477 "Ignoring invalid line under [PoseConstraints] section at line {}: {}", lineIndex, line);
482 const auto pTokens =
tokenize(line,
" \t\r\n");
485 "Could not parse 'poseconstraints' line in parameter configuration at line {}: {}",
490 for (
size_t i = 2; i < pTokens.size(); i++) {
491 const std::string& item =
trim(pTokens[i]);
493 const auto cTokens =
tokenize(item,
"=");
494 if (cTokens.size() != 2) {
499 for (
size_t d = 0; d < pt.
name.size(); d++) {
500 if (pt.
name[d] == cTokens[0]) {
508 "Could not parse 'poseconstraints' line in parameter configuration at line {}: {}",
515 result[pTokens[1]] = ps;
532 const filesystem::path& filename,
534 std::ifstream infile(filename);
537 "Unable to open parameter transform file '{}' for reading.",
540 return loadModelDefinitionFromStream(infile, skeleton);
544 std::span<const std::byte> rawData,
546 if (rawData.empty()) {
552 MT_THROW_IF(!inputStream,
"Unable to read parameter transform data.");
554 return loadModelDefinitionFromStream(inputStream, skeleton);
560 std::ostringstream oss;
563 for (
size_t iJoint = 0; iJoint < skeleton.
joints.size(); ++iJoint) {
564 const auto& joint = skeleton.
joints[iJoint];
578 std::vector<std::pair<size_t, float>> influences;
579 for (Eigen::Index iModelParam = 0; iModelParam < parameterTransform.
transform.cols();
581 const float weight = parameterTransform.
transform.coeff(jointParamIndex, iModelParam);
582 if (weight != 0.0f) {
583 influences.emplace_back(iModelParam, weight);
588 const float offset = parameterTransform.
offsets[jointParamIndex];
589 bool needsPlus =
false;
591 if (!influences.empty()) {
592 bool firstTerm =
true;
593 for (
const auto& [modelParamIndex, weight] : influences) {
595 modelParamIndex >= parameterTransform.
name.size(),
596 "Model parameter index {} is out of bounds (name size: {})",
598 parameterTransform.
name.size());
602 oss << weight <<
"*" << parameterTransform.
name.at(modelParamIndex);
608 if (offset != 0.0f) {
623 std::ostringstream oss;
625 for (
const auto& [name, paramSet] : parameterSets) {
626 oss <<
"parameterset " << name;
629 for (
size_t i = 0; i < paramSet.size(); ++i) {
630 if (paramSet.test(i)) {
633 oss <<
" param_" << i;
643 std::ostringstream oss;
645 for (
const auto& [name, constraint] : poseConstraints) {
646 oss <<
"poseconstraints " << name;
649 for (
const auto& [paramIndex, value] : constraint.parameterIdValue) {
651 oss <<
" param_" << paramIndex <<
"=" << value;
663 std::ostringstream oss;
666 oss <<
"Momentum Model Definition V1.0\n\n";
669 if (!parameterTransform.
name.empty()) {
670 oss <<
"[ParameterTransform]\n";
677 oss <<
"[ParameterSets]\n";
678 for (
const auto& [name, paramSet] : parameterTransform.
parameterSets) {
679 oss <<
"parameterset " << name;
682 for (
size_t i = 0; i < paramSet.size() && i < parameterTransform.
name.size(); ++i) {
683 if (paramSet.test(i)) {
684 oss <<
" " << parameterTransform.
name[i];
694 oss <<
"[PoseConstraints]\n";
695 for (
const auto& [name, constraint] : parameterTransform.
poseConstraints) {
696 oss <<
"poseconstraints " << name;
699 for (
const auto& [paramIndex, value] : constraint.parameterIdValue) {
700 if (paramIndex < parameterTransform.
name.size()) {
701 oss <<
" " << parameterTransform.
name.at(paramIndex) <<
"=" << value;
710 if (!parameterLimits.empty()) {
711 oss <<
"[" << kParameterLimitsSection <<
"]\n";
Holds all segments of a section and provides line-aware iteration This is used internally to track li...
void addSegment(std::string_view content, size_t startLine)
LineIterator begin() const
Holds all segments of a section and provides line-aware iteration This is used internally to track li...
#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.
SkeletonT< float > Skeleton
StringType trim(const StringType &text, const char *whiteChars)
Returns a copy of the string with leading and trailing characters in whiteChars removed.
ParameterLimits parseParameterLimits(const io_detail::SectionContent &content, const Skeleton &skeleton, const ParameterTransform ¶meterTransform)
std::unordered_map< std::string, std::string > loadMomentumModel(const filesystem::path &filename)
std::unordered_map< std::string, ParameterSet > ParameterSets
std::string writeParameterTransform(const ParameterTransform ¶meterTransform, const Skeleton &skeleton)
std::unordered_map< std::string, std::string > loadMomentumModelFromBuffer(std::span< const std::byte > buffer)
std::vector< ParameterLimit > ParameterLimits
std::string writeParameterSets(const ParameterSets ¶meterSets)
constexpr std::array< const char *, kParametersPerJoint > kJointParameterNames
ParameterTransformT< float > ParameterTransform
std::string writePoseConstraints(const PoseConstraints &poseConstraints)
ParameterTransform parseParameterTransform(const SectionContent &content, const Skeleton &skeleton)
std::istream & GetLineCrossPlatform(std::istream &is, std::string &line)
Reads a line from the input stream, handling line endings for different platforms.
std::tuple< ParameterTransform, ParameterLimits > loadModelDefinition(const filesystem::path &filename, const Skeleton &skeleton)
constexpr size_t kParametersPerJoint
std::vector< std::string > tokenize(const std::string &inputString, const std::string &delimiters, const bool trim)
Tokenizes a string using the specified single-byte delimiter characters.
ParameterSets parseParameterSets(const SectionContent &content, const ParameterTransform &pt)
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
std::string writeParameterLimits(const ParameterLimits ¶meterLimits, const Skeleton &skeleton, const ParameterTransform ¶meterTransform)
std::unordered_map< std::string, PoseConstraint > PoseConstraints
PoseConstraints parsePoseConstraints(const SectionContent &content, const ParameterTransform &pt)
std::bitset< kMaxModelParams > ParameterSet
Bitset for model parameter enablement.
std::string writeModelDefinition(const Skeleton &skeleton, const ParameterTransform ¶meterTransform, const ParameterLimits ¶meterLimits)
Write complete model definition file.
std::vector< std::pair< size_t, float > > parameterIdValue
A vector of tuples of type: (model parameter index, parameter value).
size_t getJointIdByName(std::string_view name) const
Returns the index of a joint with the given name, or kInvalidIndex if not found.
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
istream that takes a span of const bytes as input.