18#include <Eigen/Geometry>
33enum class BvhChannel { Xposition, Yposition, Zposition, Xrotation, Yrotation, Zrotation };
38 size_t parentIndex{0};
40 std::vector<BvhChannel> channels;
41 size_t channelOffset{0};
45std::string
trim(
const std::string& s) {
46 const auto start = s.find_first_not_of(
" \t\r\n");
47 if (start == std::string::npos) {
50 const auto end = s.find_last_not_of(
" \t\r\n");
51 return s.substr(start, end - start + 1);
55BvhChannel parseChannelType(
const std::string& token) {
56 if (token ==
"Xposition") {
57 return BvhChannel::Xposition;
58 }
else if (token ==
"Yposition") {
59 return BvhChannel::Yposition;
60 }
else if (token ==
"Zposition") {
61 return BvhChannel::Zposition;
62 }
else if (token ==
"Xrotation") {
63 return BvhChannel::Xrotation;
64 }
else if (token ==
"Yrotation") {
65 return BvhChannel::Yrotation;
66 }
else if (token ==
"Zrotation") {
67 return BvhChannel::Zrotation;
69 MT_THROW(
"Unknown BVH channel type: {}", token);
74const char* channelTypeName(BvhChannel ch) {
76 case BvhChannel::Xposition:
78 case BvhChannel::Yposition:
80 case BvhChannel::Zposition:
82 case BvhChannel::Xrotation:
84 case BvhChannel::Yrotation:
86 case BvhChannel::Zrotation:
89 MT_THROW(
"Invalid BVH channel: {}",
static_cast<int>(ch));
93int rotationAxisIndex(BvhChannel ch) {
95 case BvhChannel::Xrotation:
97 case BvhChannel::Yrotation:
99 case BvhChannel::Zrotation:
101 case BvhChannel::Xposition:
102 case BvhChannel::Yposition:
103 case BvhChannel::Zposition:
106 MT_THROW(
"Invalid BVH channel: {}",
static_cast<int>(ch));
110int positionParameterIndex(BvhChannel ch) {
112 case BvhChannel::Xposition:
114 case BvhChannel::Yposition:
116 case BvhChannel::Zposition:
118 case BvhChannel::Xrotation:
119 case BvhChannel::Yrotation:
120 case BvhChannel::Zrotation:
123 MT_THROW(
"Invalid BVH channel: {}",
static_cast<int>(ch));
126bool isRotationChannel(BvhChannel ch) {
127 return ch == BvhChannel::Xrotation || ch == BvhChannel::Yrotation || ch == BvhChannel::Zrotation;
130bool isPositionChannel(BvhChannel ch) {
131 return ch == BvhChannel::Xposition || ch == BvhChannel::Yposition || ch == BvhChannel::Zposition;
134struct BvhParseResult {
135 std::vector<BvhJointData> joints;
136 size_t totalChannels{0};
137 std::vector<VectorXf> frames;
146void parseJointDefinition(
147 std::istringstream& iss,
148 std::stack<size_t>& jointStack,
149 BvhParseResult& result) {
150 std::string jointName;
152 MT_THROW_IF(jointName.empty(),
"BVH joint name is empty");
155 joint.name = jointName;
156 joint.parentIndex = jointStack.empty() ?
kInvalidIndex : jointStack.top();
157 joint.offset = Vector3f::Zero();
158 joint.channelOffset = result.totalChannels;
160 const size_t jointIndex = result.joints.size();
161 result.joints.push_back(joint);
162 jointStack.push(jointIndex);
166void parseOffset(std::istringstream& iss, std::stack<size_t>& jointStack, BvhParseResult& result) {
172 if (jointStack.empty() || jointStack.top() ==
kInvalidIndex) {
175 const auto topIdx = jointStack.top();
176 if (topIdx < result.joints.size()) {
177 result.joints[topIdx].offset =
Vector3f(x, y, z);
183 std::istringstream& iss,
184 std::stack<size_t>& jointStack,
185 BvhParseResult& result) {
190 jointStack.top() >= result.joints.size(),
191 "CHANNELS found outside of a joint definition");
192 const auto topIdx = jointStack.top();
193 MT_THROW_IF(topIdx >= result.joints.size(),
"Joint index out of range");
194 auto& joint = result.joints[topIdx];
195 for (
int i = 0; i < numChannels; ++i) {
196 std::string channelName;
198 joint.channels.push_back(parseChannelType(channelName));
199 result.totalChannels++;
204void parseBvhHierarchy(std::istream& stream, BvhParseResult& result) {
206 std::stack<size_t> jointStack;
210 const std::string trimmedLine =
trim(line);
211 if (trimmedLine.empty()) {
215 std::istringstream iss(trimmedLine);
219 if (keyword ==
"ROOT" || keyword ==
"JOINT") {
220 parseJointDefinition(iss, jointStack, result);
221 }
else if (keyword ==
"End") {
224 }
else if (keyword ==
"OFFSET") {
225 parseOffset(iss, jointStack, result);
226 }
else if (keyword ==
"CHANNELS") {
227 parseChannels(iss, jointStack, result);
228 }
else if (keyword ==
"{") {
230 }
else if (keyword ==
"}") {
231 MT_THROW_IF(jointStack.empty(),
"Unexpected closing brace in BVH hierarchy");
233 }
else if (keyword ==
"MOTION") {
241void parseBvhMotion(std::istream& stream, BvhParseResult& result) {
246 const std::string trimmedLine =
trim(line);
247 if (trimmedLine.empty()) {
251 std::istringstream iss(trimmedLine);
255 if (keyword ==
"Frames:") {
256 size_t numFrames = 0;
258 result.frames.reserve(numFrames);
259 }
else if (keyword ==
"Frame") {
261 std::string timeKeyword;
262 float frameTime = 0.0f;
263 iss >> timeKeyword >> frameTime;
264 if (frameTime > 0.0f) {
265 result.fps = 1.0f / frameTime;
269 std::istringstream dataIss(trimmedLine);
270 VectorXf frameData(result.totalChannels);
271 for (
size_t i = 0; i < result.totalChannels; ++i) {
272 MT_THROW_IF(!dataIss,
"Unexpected end of motion data line");
273 dataIss >> frameData[i];
275 result.frames.push_back(frameData);
281BvhParseResult parseBvhStream(std::istream& stream) {
282 BvhParseResult result;
288 const std::string trimmedLine =
trim(line);
289 if (trimmedLine ==
"HIERARCHY") {
294 parseBvhHierarchy(stream, result);
295 parseBvhMotion(stream, result);
297 MT_THROW_IF(result.joints.empty(),
"No joints found in BVH file");
308 const BvhJointData& bvhJoint,
311 for (
size_t chIdx = 0; chIdx < bvhJoint.channels.size(); ++chIdx) {
312 const auto ch = bvhJoint.channels[chIdx];
313 if (!isRotationChannel(ch)) {
316 const auto dataIdx =
static_cast<Eigen::Index
>(bvhJoint.channelOffset + chIdx);
317 const float angleRad = frameData[dataIdx] *
pi<float>() / 180.0f;
318 q = q *
Quaternionf(Eigen::AngleAxisf(angleRad, Vector3f::Unit(rotationAxisIndex(ch))));
324void mapBvhJointToModelParams(
325 const BvhJointData& bvhJoint,
327 Eigen::Index jointParamBase,
328 Eigen::Index frameIdx,
331 for (
size_t chIdx = 0; chIdx < bvhJoint.channels.size(); ++chIdx) {
332 const auto ch = bvhJoint.channels[chIdx];
333 if (!isPositionChannel(ch)) {
336 const auto dataIdx =
static_cast<Eigen::Index
>(bvhJoint.channelOffset + chIdx);
337 motion(jointParamBase + positionParameterIndex(ch), frameIdx) = frameData[dataIdx];
341 const Quaternionf q = convertBvhRotationToQuaternion(bvhJoint, frameData);
342 if (!q.isApprox(Quaternionf::Identity())) {
346 motion(jointParamBase +
RX, frameIdx) = eulerAngles[0];
347 motion(jointParamBase +
RY, frameIdx) = eulerAngles[1];
348 motion(jointParamBase +
RZ, frameIdx) = eulerAngles[2];
353Character buildCharacterFromBvh(
const std::vector<BvhJointData>& bvhJoints) {
355 skeleton.joints.reserve(bvhJoints.size());
357 std::vector<std::string> jointNames;
358 jointNames.reserve(bvhJoints.size());
360 for (
const auto& bvhJoint : bvhJoints) {
362 joint.name = bvhJoint.name;
363 joint.parent = bvhJoint.parentIndex;
364 joint.preRotation = Quaternionf::Identity();
365 joint.translationOffset = bvhJoint.offset;
366 skeleton.joints.push_back(joint);
367 jointNames.push_back(bvhJoint.name);
372 return {skeleton, parameterTransform};
378 const std::vector<BvhJointData>& bvhJoints,
379 const std::vector<VectorXf>& frames,
382 const auto numFrames =
static_cast<Eigen::Index
>(frames.size());
384 MatrixXf motion = MatrixXf::Zero(numModelParams, numFrames);
386 for (Eigen::Index frameIdx = 0; frameIdx < numFrames; ++frameIdx) {
387 for (
size_t jointIdx = 0; jointIdx < bvhJoints.size(); ++jointIdx) {
389 mapBvhJointToModelParams(
390 bvhJoints[jointIdx], frames[frameIdx], jointParamBase, frameIdx, motion);
397std::tuple<Character, MotionParameters, float> loadBvhFromStream(std::istream& stream) {
398 auto parseResult = parseBvhStream(stream);
400 Character character = buildCharacterFromBvh(parseResult.joints);
402 MatrixXf motion = mapBvhMotion(parseResult.joints, parseResult.frames, parseResult.joints.size());
404 MotionParameters motionParams = std::make_tuple(character.parameterTransform.name, motion);
406 return std::make_tuple(std::move(character), std::move(motionParams), parseResult.fps);
416std::vector<BvhJointData> buildBvhJointsFromCharacter(
const Character& character) {
417 const auto& skeleton = character.skeleton;
418 std::vector<BvhJointData> bvhJoints;
419 bvhJoints.reserve(skeleton.joints.size());
421 size_t channelOffset = 0;
422 for (
const auto& joint : skeleton.joints) {
423 BvhJointData bvhJoint;
424 bvhJoint.name = joint.name;
425 bvhJoint.parentIndex = joint.parent;
426 bvhJoint.offset = joint.translationOffset;
427 bvhJoint.channelOffset = channelOffset;
431 bvhJoint.channels = {
432 BvhChannel::Xposition,
433 BvhChannel::Yposition,
434 BvhChannel::Zposition,
435 BvhChannel::Zrotation,
436 BvhChannel::Xrotation,
437 BvhChannel::Yrotation};
441 bvhJoint.channels = {BvhChannel::Zrotation, BvhChannel::Xrotation, BvhChannel::Yrotation};
445 bvhJoints.push_back(std::move(bvhJoint));
452std::vector<std::vector<size_t>> buildChildMap(
const Skeleton& skeleton) {
453 const auto numJoints = skeleton.joints.size();
454 std::vector<std::vector<size_t>> children(numJoints);
455 for (
size_t i = 0; i < numJoints; ++i) {
456 const auto parent = skeleton.joints[i].parent;
458 children[parent].push_back(i);
466 std::ostream& stream,
468 const std::vector<BvhJointData>& bvhJoints,
469 const std::vector<std::vector<size_t>>& children,
472 MT_THROW_IF(jointIdx >= skeleton.joints.size(),
"Joint index out of range");
473 const auto depthSz =
static_cast<std::string::size_type
>(depth);
474 const auto indent = std::string(depthSz * 2,
' ');
475 const auto innerIndent = std::string((depthSz + 1) * 2,
' ');
479 stream <<
"ROOT " << skeleton.joints[jointIdx].name <<
"\n";
481 stream << indent <<
"JOINT " << skeleton.joints[jointIdx].name <<
"\n";
483 stream << indent <<
"{\n";
486 const auto& offset = bvhJoints[jointIdx].offset;
487 stream << innerIndent <<
"OFFSET " << std::fixed << std::setprecision(4) << offset[0] <<
" "
488 << offset[1] <<
" " << offset[2] <<
"\n";
491 const auto& channels = bvhJoints[jointIdx].channels;
492 stream << innerIndent <<
"CHANNELS " << channels.size();
493 for (
const auto& ch : channels) {
494 stream <<
" " << channelTypeName(ch);
498 if (children[jointIdx].empty()) {
500 stream << innerIndent <<
"End Site\n";
501 stream << innerIndent <<
"{\n";
502 stream << std::string((depthSz + 2) * 2,
' ') <<
"OFFSET 0.0000 0.0000 0.0000\n";
503 stream << innerIndent <<
"}\n";
506 for (
const auto childIdx : children[jointIdx]) {
507 writeBvhJoint(stream, skeleton, bvhJoints, children, childIdx, depth + 1);
511 stream << indent <<
"}\n";
515void writeBvhHierarchy(
516 std::ostream& stream,
518 const std::vector<BvhJointData>& bvhJoints) {
519 const auto& skeleton = character.skeleton;
520 stream <<
"HIERARCHY\n";
522 const auto children = buildChildMap(skeleton);
525 for (
size_t i = 0; i < skeleton.joints.size(); ++i) {
527 writeBvhJoint(stream, skeleton, bvhJoints, children, i, 0);
533VectorXf convertModelParamsToBvhFrame(
534 const std::vector<BvhJointData>& bvhJoints,
536 Eigen::Index frameIdx) {
538 size_t totalChannels = 0;
539 for (
const auto& joint : bvhJoints) {
540 totalChannels += joint.channels.size();
543 VectorXf frameData = VectorXf::Zero(totalChannels);
545 for (
size_t jointIdx = 0; jointIdx < bvhJoints.size(); ++jointIdx) {
546 const auto& bvhJoint = bvhJoints[jointIdx];
550 const float rx = motion(jointParamBase +
RX, frameIdx);
551 const float ry = motion(jointParamBase +
RY, frameIdx);
552 const float rz = motion(jointParamBase +
RZ, frameIdx);
556 Quaternionf(Eigen::AngleAxisf(ry, Vector3f::UnitY())) *
557 Quaternionf(Eigen::AngleAxisf(rx, Vector3f::UnitX()));
560 std::vector<int> rotAxes;
561 std::vector<size_t> rotChannelIndices;
562 for (
size_t chIdx = 0; chIdx < bvhJoint.channels.size(); ++chIdx) {
563 const auto ch = bvhJoint.channels[chIdx];
564 if (isRotationChannel(ch)) {
565 rotAxes.push_back(rotationAxisIndex(ch));
566 rotChannelIndices.push_back(bvhJoint.channelOffset + chIdx);
567 }
else if (isPositionChannel(ch)) {
568 const auto dataIdx =
static_cast<Eigen::Index
>(bvhJoint.channelOffset + chIdx);
569 frameData[dataIdx] = motion(jointParamBase + positionParameterIndex(ch), frameIdx);
573 if (rotAxes.size() == 3 && rotChannelIndices.size() == 3) {
578 const float rad2deg = 180.0f /
pi<float>();
579 for (
size_t k = 0; k < 3; ++k) {
580 frameData[rotChannelIndices[k]] = angles[k] * rad2deg;
590 std::ostream& stream,
591 const std::vector<BvhJointData>& bvhJoints,
594 MT_THROW_IF(fps <= 0.0f,
"fps must be positive for BVH export");
596 const auto numFrames = motion.cols();
598 stream <<
"MOTION\n";
599 stream <<
"Frames: " << numFrames <<
"\n";
600 stream <<
"Frame Time: " << std::fixed << std::setprecision(6) << (1.0f / fps) <<
"\n";
602 for (Eigen::Index frameIdx = 0; frameIdx < numFrames; ++frameIdx) {
603 const VectorXf frameData = convertModelParamsToBvhFrame(bvhJoints, motion, frameIdx);
605 for (Eigen::Index i = 0; i < frameData.size(); ++i) {
609 stream << std::fixed << std::setprecision(4) << frameData[i];
617 std::ostream& stream,
621 const auto bvhJoints = buildBvhJointsFromCharacter(character);
623 writeBvhHierarchy(stream, character, bvhJoints);
624 writeBvhMotion(stream, bvhJoints, motion, fps);
630 std::ifstream stream(filepath);
631 MT_THROW_IF(!stream.is_open(),
"Failed to open BVH file: {}", filepath.string());
632 auto [character, motionParams, fps] = loadBvhFromStream(stream);
638 auto [character, motionParams, fps] = loadBvhFromStream(stream);
643 const filesystem::path& filepath) {
644 std::ifstream stream(filepath);
645 MT_THROW_IF(!stream.is_open(),
"Failed to open BVH file: {}", filepath.string());
646 return loadBvhFromStream(stream);
650 std::span<const std::byte> bytes) {
652 return loadBvhFromStream(stream);
656 std::ofstream stream(filepath);
657 MT_THROW_IF(!stream.is_open(),
"Failed to open BVH file for writing: {}", filepath.string());
660 const auto numParams =
662 MatrixXf motion = MatrixXf::Zero(numParams, 1);
663 saveBvhToStream(stream, character, motion, 30.0f);
667 const filesystem::path& filepath,
671 std::ofstream stream(filepath);
672 MT_THROW_IF(!stream.is_open(),
"Failed to open BVH file for writing: {}", filepath.string());
674 const auto& [paramNames, motion] = motionParams;
675 saveBvhToStream(stream, character, motion, fps);
682 const auto& [paramNames, motion] = motionParams;
684 std::ostringstream oss;
685 saveBvhToStream(oss, character, motion, fps);
687 const std::string str = oss.str();
688 std::vector<std::byte> bytes(str.size());
689 std::memcpy(bytes.data(), str.data(), str.size());
#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.
void saveBvhCharacter(const filesystem::path &filepath, const Character &character)
Saves a character to a BVH file with a single rest-pose frame.
SkeletonT< float > Skeleton
Vector3< T > rotationMatrixToEuler(const Matrix3< T > &m, int axis0, int axis1, int axis2, EulerConvention convention)
Converts rotation matrix to Euler angles.
StringType trim(const StringType &text, const char *whiteChars)
Returns a copy of the string with leading and trailing characters in whiteChars removed.
Quaternion< float > Quaternionf
Vector3< T > rotationMatrixToEulerXYZ(const Matrix3< T > &m, EulerConvention convention)
An optimized version of rotationMatrixToEuler(m, 0, 1, 2, convention) or rotationMatrixToEuler(m,...
Character loadBvhCharacter(const filesystem::path &filepath)
Loads a character from a BVH (BioVision Hierarchy) file.
std::tuple< std::vector< std::string >, Eigen::MatrixXf > MotionParameters
A tuple of model parameter names and a matrix of poses across a sequence of frames.
@ Extrinsic
The extrinsic convention.
@ Intrinsic
The intrinsic convention.
std::istream & GetLineCrossPlatform(std::istream &is, std::string &line)
Reads a line from the input stream, handling line endings for different platforms.
constexpr size_t kParametersPerJoint
void saveBvhCharacterWithMotion(const filesystem::path &filepath, const Character &character, const MotionParameters &motionParams, float fps)
Saves a character with motion data to a BVH file.
std::tuple< Character, MotionParameters, float > loadBvhCharacterWithMotion(const filesystem::path &filepath)
Loads a character with motion data from a BVH (BioVision Hierarchy) file.
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Vector3< float > Vector3f
VectorX< float > VectorXf
constexpr T pi() noexcept
Returns the mathematical constant pi.
MatrixX< float > MatrixXf
A character model with skeletal structure, mesh, and optional components.
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
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.