9.2 Animation 与关键帧
Animation 是一段有时间长度的动画序列。它自己不保存变换,而是由若干轨道(track)组成:节点轨道(NodeAnimationTrack)驱动骨骼节点,顶点轨道驱动网格顶点,数值轨道驱动任意可动画值。这一节讲轨道的登记、关键帧的存储,以及关键帧之间如何插值。
本章与站内既有内容的分工
9.1 讲了 Skeleton 与 Bone 的数据组织;本节的轨道用 handle 定位骨骼(handle 就是 9.1 里骨头的数字身份)。helio 卷三的动画状态机讲播放调度,本节只讲 OGRE 里关键帧数据的定义与插值计算。
Animation:时间序列的容器
OgreAnimation.h 里 Animation 有两个插值模式枚举,控制轨道如何补间:
// OgreMain/include/OgreAnimation.h:Animation 插值枚举(v14.6.3 源码摘录,已删减)
/** The types of animation interpolation available. */
enum InterpolationMode : uint8
{
/** Values are interpolated along straight lines. */
IM_LINEAR,
/** Values are interpolated along a spline, resulting in smoother changes in direction. */
IM_SPLINE
};
/** The types of rotational interpolation available. */
enum RotationInterpolationMode : uint8
{
/** Values are interpolated linearly. This is faster but does not
necessarily give a completely accurate result.
*/
RIM_LINEAR,
/** Values are interpolated spherically. This is more accurate but
has a higher cost.
*/
RIM_SPHERICAL
};
三个要点:
- 位置/缩放插值由
InterpolationMode控制:IM_LINEAR沿直线补间(快),IM_SPLINE沿样条补间(平滑但贵); - 旋转插值单独由
RotationInterpolationMode控制:RIM_LINEAR用归一化线性插值(nlerp,快但不精确),RIM_SPHERICAL用球面插值(Slerp,精确但更贵); - 两者分开,因为旋转不能用普通线性插值(四元数直接 lerp 结果不保证是单位四元数,角度也不均匀)。
轨道按 handle 登记进 Animation 的 NodeTrackList(std::map<unsigned short, NodeAnimationTrack*>):
// OgreMain/include/OgreAnimation.h:createNodeTrack(v14.6.3 源码摘录,已删减)
/** Creates a NodeAnimationTrack for animating a Node.
@param handle Handle to give the track, used for accessing the track later.
Must be unique within this Animation.
*/
NodeAnimationTrack* createNodeTrack(unsigned short handle);
一个 Animation 可以有多个轨道,每个轨道针对一根骨骼(handle 匹配骨骼)。动画总长度与关键帧时间共同决定采样点。
TransformKeyFrame:一个变换快照
OgreKeyFrame.h 的 TransformKeyFrame 是节点轨道的关键帧,保存平移、缩放、旋转三个量:
// OgreMain/include/OgreKeyFrame.h:TransformKeyFrame(v14.6.3 源码摘录,已删减)
/** Specialised KeyFrame which stores a full transform. */
class _OgreExport TransformKeyFrame : public KeyFrame
{
public:
virtual void setTranslate(const Vector3& trans);
const Vector3& getTranslate(void) const;
virtual void setScale(const Vector3& scale);
virtual const Vector3& getScale(void) const;
virtual void setRotation(const Quaternion& rot);
virtual const Quaternion& getRotation(void) const;
private:
Vector3 mTranslate;
Vector3 mScale;
Quaternion mRotate;
};
关键帧只有时间与快照,不含「如何过渡」。多个关键帧由轨道持有、按时间排序,过渡规则由轨道 + Animation 的插值模式决定。
getKeyFramesAtTime:定位前后关键帧
动画采样时,任意时间点有 1 或 2 个「活动」关键帧:恰好在关键帧上是 1 个,否则是它前后的 2 个。AnimationTrack::getKeyFramesAtTime 做这件事并返回参数 t:
// OgreMain/src/OgreAnimationTrack.cpp:AnimationTrack::getKeyFramesAtTime(v14.6.3 源码摘录,已删减)
float AnimationTrack::getKeyFramesAtTime(const TimeIndex& timeIndex, KeyFrame** keyFrame1, KeyFrame** keyFrame2,
unsigned short* firstKeyIndex) const
{
Real t1, t2;
Real timePos = timeIndex.getTimePos();
KeyFrameList::const_iterator i;
...
// Wrap time
Real totalAnimationLength = mParent->getLength();
if( timePos > totalAnimationLength && totalAnimationLength > 0.0f )
timePos = std::fmod( timePos, totalAnimationLength );
KeyFrame timeKey(NULL, timePos);
i = std::lower_bound(mKeyFrames.begin(), mKeyFrames.end() - 1, &timeKey, KeyFrameTimeLess());
...
*keyFrame2 = *i;
t2 = (*keyFrame2)->getTime();
// Find last keyframe before or on current time
if (i != mKeyFrames.begin() && timePos < (*i)->getTime())
{
--i;
}
*keyFrame1 = *i;
t1 = (*keyFrame1)->getTime();
if (t1 == t2)
{
return 0.0f;
}
else
{
return Math::inverseLerp(t1, t2, timePos);
}
}
三个关键语义:
- 超长回绕:
timePos超过动画长度时按std::fmod取模(循环采样); - 二分定位:
std::lower_bound在[begin, end()-1)区间找第一个>= timePos的关键帧作keyFrame2,最后一个关键帧保底作上界;若非首帧且时间在其之前,回退一格得keyFrame1; - 参数 t:
Math::inverseLerp(t1, t2, timePos) = (timePos - t1)/(t2 - t1),范围0.0 <= t < 1.0;恰落在关键帧上(t1 == t2)返回 0。
插值:IM_LINEAR 的完整分支
NodeAnimationTrack::getInterpolatedKeyFrame 拿到 t 后做实际补间:
// OgreMain/src/OgreAnimationTrack.cpp:NodeAnimationTrack::getInterpolatedKeyFrame(v14.6.3 源码摘录,已删减)
if (t == 0.0)
{
kret->setRotation(k1->getRotation());
kret->setTranslate(k1->getTranslate());
kret->setScale(k1->getScale());
}
else
{
Animation::InterpolationMode im = mParent->getInterpolationMode();
Animation::RotationInterpolationMode rim =
mParent->getRotationInterpolationMode();
switch(im)
{
case Animation::IM_LINEAR:
if (rim == Animation::RIM_LINEAR)
{
kret->setRotation( Quaternion::nlerp(t, k1->getRotation(),
k2->getRotation(), mUseShortestRotationPath) );
}
else //if (rim == Animation::RIM_SPHERICAL)
{
kret->setRotation( Quaternion::Slerp(t, k1->getRotation(),
k2->getRotation(), mUseShortestRotationPath) );
}
base = k1->getTranslate();
kret->setTranslate(Math::lerp(base, k2->getTranslate(), t));
base = k1->getScale();
kret->setScale(Math::lerp(base, k2->getScale(), t));
break;
case Animation::IM_SPLINE:
...
}
}
机制表:
| 分量 | IM_LINEAR 下的插值 | 公式 |
|---|---|---|
| 平移 | Math::lerp | p0 + (p1 - p0)·t |
| 缩放 | Math::lerp | s0 + (s1 - s0)·t |
| 旋转(RIM_LINEAR) | Quaternion::nlerp | 线性插值后归一化 |
| 旋转(RIM_SPHERICAL) | Quaternion::Slerp | 球面(弧线)插值 |
mUseShortestRotationPath 让旋转走「最短路径」:当两个四元数点积为负(夹角 > 90°)时先翻转目标四元数再插值,避免绕远路。
源码定位
OgreMain/include/OgreAnimation.h:Animation(InterpolationMode/RotationInterpolationMode、createNodeTrack、mNodeTrackList)OgreMain/include/OgreAnimationTrack.h:AnimationTrack/NodeAnimationTrack(getKeyFramesAtTime、createNodeKeyFrame)OgreMain/include/OgreKeyFrame.h:TransformKeyFrame(mTranslate/mScale/mRotate)OgreMain/src/OgreAnimationTrack.cpp:getKeyFramesAtTime实现、NodeAnimationTrack::getInterpolatedKeyFrame线性分支
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
下面复现轨道登记、关键帧排序插入、getKeyFramesAtTime 定位与两种旋转插值。它与 src/09-2-animation-keyframe.cpp 逐字节一致:
// file: src/09-2-animation-keyframe.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/09-2-animation-keyframe.cpp -o bin/09-2-animation-keyframe && ./bin/09-2-animation-keyframe
//
// 复现 OgreAnimation / OgreAnimationTrack / OgreKeyFrame:
// 轨道按 handle 登记;关键帧按时间排序插入;
// getKeyFramesAtTime 定位前后关键帧并返回参数 t;
// IM_LINEAR 下平移/缩放 lerp,旋转按 RIM_LINEAR(nlerp)/RIM_SPHERICAL(slerp)。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <algorithm>
#include <cmath>
#include <map>
#include <string>
#include <vector>
namespace ogre_repro {
const double kPi = 3.141592653589793;
static bool approx(double a, double b, double eps = 1e-6) {
return std::abs(a - b) <= eps;
}
struct Vec3 {
double x = 0, y = 0, z = 0;
Vec3() = default;
Vec3(double x_, double y_, double z_) : x(x_), y(y_), z(z_) {}
friend Vec3 operator*(const Vec3& v, double s) { return {v.x * s, v.y * s, v.z * s}; }
friend Vec3 operator+(const Vec3& a, const Vec3& b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
friend Vec3 operator-(const Vec3& a, const Vec3& b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
bool closeTo(const Vec3& o, double eps) const {
return approx(x, o.x, eps) && approx(y, o.y, eps) && approx(z, o.z, eps);
}
};
// 简化 Quaternion(对应 OgreQuaternion,仅覆盖插值所需)
struct Quat {
double w = 1, x = 0, y = 0, z = 0;
Quat() = default;
Quat(double w_, double x_, double y_, double z_) : w(w_), x(x_), y(y_), z(z_) {}
static Quat fromAxisAngle(const Vec3& axis, double angleRad) {
double half = angleRad / 2;
double s = std::sin(half);
return Quat(std::cos(half), axis.x * s, axis.y * s, axis.z * s);
}
Quat normalized() const {
double n = std::sqrt(w * w + x * x + y * y + z * z);
return Quat(w / n, x / n, y / n, z / n);
}
Quat operator-() const { return Quat(-w, -x, -y, -z); }
friend Quat operator*(const Quat& q, double s) { return Quat(q.w * s, q.x * s, q.y * s, q.z * s); }
friend Quat operator+(const Quat& a, const Quat& b) {
return Quat(a.w + b.w, a.x + b.x, a.y + b.y, a.z + b.z);
}
double dot(const Quat& o) const { return w * o.w + x * o.x + y * o.y + z * o.z; }
bool closeTo(const Quat& o, double eps) const {
return approx(w, o.w, eps) && approx(x, o.x, eps) && approx(y, o.y, eps) && approx(z, o.z, eps);
}
};
static Vec3 lerp(const Vec3& v0, const Vec3& v1, double t) { return v0 + (v1 - v0) * t; }
// 对应 Quaternion::nlerp:归一化线性插值(RIM_LINEAR 用)
static Quat nlerp(double t, const Quat& q1, const Quat& q2, bool shortest) {
Quat q2s = q2;
if (shortest && q1.dot(q2) < 0) q2s = -q2;
return (q1 * (1.0 - t) + q2s * t).normalized();
}
// 对应 Quaternion::Slerp:球面插值(RIM_SPHERICAL 用)
static Quat slerp(double t, const Quat& q1, const Quat& q2, bool shortest) {
Quat q2s = q2;
double dot = q1.dot(q2);
if (shortest && dot < 0) {
q2s = -q2;
dot = -dot;
}
const double kEps = 1e-3;
if (dot > 1.0 - kEps) return nlerp(t, q1, q2s, false);
double theta = std::acos(std::clamp(dot, -1.0, 1.0));
double sinTheta = std::sin(theta);
double wa = std::sin((1.0 - t) * theta) / sinTheta;
double wb = std::sin(t * theta) / sinTheta;
return (q1 * wa + q2s * wb).normalized();
}
class Animation;
// 对应 TransformKeyFrame(OgreKeyFrame.h)
class TransformKeyFrame {
public:
double mTime;
Vec3 mTranslate{0, 0, 0};
Vec3 mScale{1, 1, 1};
Quat mRotate;
explicit TransformKeyFrame(double time) : mTime(time) {}
double getTime() const { return mTime; }
void setTranslate(const Vec3& v) { mTranslate = v; }
const Vec3& getTranslate() const { return mTranslate; }
void setScale(const Vec3& s) { mScale = s; }
const Vec3& getScale() const { return mScale; }
void setRotation(const Quat& q) { mRotate = q; }
const Quat& getRotation() const { return mRotate; }
};
// 对应 NodeAnimationTrack(OgreAnimationTrack.h),方法在 Animation 之后定义
class NodeAnimationTrack {
public:
std::vector<TransformKeyFrame*> mKeyFrames;
Animation* mParent;
unsigned short mHandle;
NodeAnimationTrack(Animation* parent, unsigned short handle)
: mParent(parent), mHandle(handle) {}
~NodeAnimationTrack() {
for (auto k : mKeyFrames) delete k;
}
unsigned short getHandle() const { return mHandle; }
size_t getNumKeyFrames() const { return mKeyFrames.size(); }
TransformKeyFrame* getKeyFrame(size_t i) const { return mKeyFrames.at(i); }
TransformKeyFrame* createKeyFrame(double timePos);
double getKeyFramesAtTime(double timePos, TransformKeyFrame** kf1,
TransformKeyFrame** kf2) const;
TransformKeyFrame getInterpolatedKeyFrame(double timePos) const;
};
// 对应 Animation(OgreAnimation.h)
class Animation {
public:
enum InterpolationMode : uint8_t { IM_LINEAR, IM_SPLINE };
enum RotationInterpolationMode : uint8_t { RIM_LINEAR, RIM_SPHERICAL };
std::string mName;
double mLength;
std::map<unsigned short, NodeAnimationTrack*> mNodeTracks;
InterpolationMode mInterpolationMode = IM_LINEAR;
RotationInterpolationMode mRotationInterpolationMode = RIM_LINEAR;
Animation(const std::string& name, double length) : mName(name), mLength(length) {}
~Animation() {
for (auto& kv : mNodeTracks) delete kv.second;
}
double getLength() const { return mLength; }
// 对应 Animation::createNodeTrack(handle)
NodeAnimationTrack* createNodeTrack(unsigned short handle) {
NodeAnimationTrack* t = new NodeAnimationTrack(this, handle);
mNodeTracks[handle] = t;
return t;
}
NodeAnimationTrack* getNodeTrack(unsigned short handle) const {
auto it = mNodeTracks.find(handle);
return it != mNodeTracks.end() ? it->second : nullptr;
}
unsigned short getNumNodeTracks() const {
return static_cast<unsigned short>(mNodeTracks.size());
}
InterpolationMode getInterpolationMode() const { return mInterpolationMode; }
void setInterpolationMode(InterpolationMode im) { mInterpolationMode = im; }
RotationInterpolationMode getRotationInterpolationMode() const {
return mRotationInterpolationMode;
}
void setRotationInterpolationMode(RotationInterpolationMode rim) {
mRotationInterpolationMode = rim;
}
};
// createKeyFrame:按时间排序插入(对应 AnimationTrack::createKeyFrame 的 upper_bound 插入)
TransformKeyFrame* NodeAnimationTrack::createKeyFrame(double timePos) {
TransformKeyFrame* kf = new TransformKeyFrame(timePos);
auto it = std::upper_bound(mKeyFrames.begin(), mKeyFrames.end(), kf,
[](const TransformKeyFrame* a, const TransformKeyFrame* b) {
return a->getTime() < b->getTime();
});
mKeyFrames.insert(it, kf);
return kf;
}
// 对应 AnimationTrack::getKeyFramesAtTime:
// 1) 超过动画长度时取模回绕;2) lower_bound 找首个 >= timePos 的关键帧;
// 3) 回退一格得前一关键帧;4) inverseLerp 返回参数 t(0.0 <= t < 1.0)。
double NodeAnimationTrack::getKeyFramesAtTime(double timePos,
TransformKeyFrame** kf1,
TransformKeyFrame** kf2) const {
double totalLength = mParent->getLength();
if (timePos > totalLength && totalLength > 0.0)
timePos = std::fmod(timePos, totalLength);
// OGRE 的搜索区间是 [begin, end()-1):最后一个关键帧保底作 keyFrame2
TransformKeyFrame timeKey(timePos);
auto i = std::lower_bound(mKeyFrames.begin(), mKeyFrames.end() - 1, &timeKey,
[](const TransformKeyFrame* kf, const TransformKeyFrame* tk) {
return kf->getTime() < tk->getTime();
});
*kf2 = *i;
double t2 = (*kf2)->getTime();
if (i != mKeyFrames.begin() && timePos < (*i)->getTime()) --i;
*kf1 = *i;
double t1 = (*kf1)->getTime();
if (t1 == t2) return 0.0;
return (timePos - t1) / (t2 - t1); // inverseLerp
}
// 对应 NodeAnimationTrack::getInterpolatedKeyFrame(IM_LINEAR 分支):
// t==0 直接取 k1;平移/缩放 lerp;旋转按 RIM 选 nlerp 或 slerp。
TransformKeyFrame NodeAnimationTrack::getInterpolatedKeyFrame(double timePos) const {
TransformKeyFrame kret(0.0);
TransformKeyFrame* k1 = nullptr;
TransformKeyFrame* k2 = nullptr;
double t = getKeyFramesAtTime(timePos, &k1, &k2);
if (t == 0.0) {
kret.setRotation(k1->getRotation());
kret.setTranslate(k1->getTranslate());
kret.setScale(k1->getScale());
return kret;
}
bool shortest = true;
if (mParent->getRotationInterpolationMode() == Animation::RIM_LINEAR) {
kret.setRotation(nlerp(t, k1->getRotation(), k2->getRotation(), shortest));
} else {
kret.setRotation(slerp(t, k1->getRotation(), k2->getRotation(), shortest));
}
kret.setTranslate(lerp(k1->getTranslate(), k2->getTranslate(), t));
kret.setScale(lerp(k1->getScale(), k2->getScale(), t));
return kret;
}
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
// Animation:name + length,默认 IM_LINEAR / RIM_LINEAR
Animation anim("Walk", 2.0);
CHECK(anim.getLength() == 2.0);
CHECK(anim.getInterpolationMode() == Animation::IM_LINEAR);
CHECK(anim.getRotationInterpolationMode() == Animation::RIM_LINEAR);
// createNodeTrack:按 handle 登记,getNodeTrack 按 handle 取回
NodeAnimationTrack* track = anim.createNodeTrack(0);
CHECK(anim.getNumNodeTracks() == 1);
CHECK(anim.getNodeTrack(0) == track);
CHECK(track->getHandle() == 0);
// 关键帧:乱序插入,createKeyFrame 按时间排序
TransformKeyFrame* k0 = track->createKeyFrame(0.0);
k0->setTranslate(Vec3{0, 0, 0});
k0->setScale(Vec3{1, 1, 1});
k0->setRotation(Quat{1, 0, 0, 0});
TransformKeyFrame* k2 = track->createKeyFrame(1.0);
k2->setTranslate(Vec3{10, 0, 0});
k2->setScale(Vec3{1, 2, 1});
k2->setRotation(Quat::fromAxisAngle(Vec3{0, 0, 1}, kPi / 2));
track->createKeyFrame(2.0); // 最后一个关键帧是上界哨兵
TransformKeyFrame* k1 = track->createKeyFrame(0.5);
k1->setTranslate(Vec3{5, 0, 0});
k1->setScale(Vec3{1, 1.5, 1});
k1->setRotation(Quat::fromAxisAngle(Vec3{0, 0, 1}, kPi / 4));
CHECK(track->getNumKeyFrames() == 4);
CHECK(track->getKeyFrame(1)->getTime() == 0.5); // 乱序插入已排序
CHECK(track->getKeyFrame(3)->getTime() == 2.0); // 最后一个关键帧是上界哨兵
// getKeyFramesAtTime:中间点 → 前后关键帧 + 参数 t
TransformKeyFrame* f1 = nullptr;
TransformKeyFrame* f2 = nullptr;
double t = track->getKeyFramesAtTime(0.25, &f1, &f2);
CHECK(f1->getTime() == 0.0);
CHECK(f2->getTime() == 0.5);
CHECK(approx(t, 0.5));
// 精确落在关键帧上 → 参数 t == 0
t = track->getKeyFramesAtTime(0.5, &f1, &f2);
CHECK(f1 == f2);
CHECK(approx(t, 0.0));
// 最后两个关键帧之间(1.0 与 2.0)
t = track->getKeyFramesAtTime(1.5, &f1, &f2);
CHECK(f1->getTime() == 1.0);
CHECK(f2->getTime() == 2.0);
CHECK(approx(t, 0.5));
// 超过动画长度 → fmod 回绕:3.0 mod 2.0 == 1.0,落在关键帧 1.0 上
t = track->getKeyFramesAtTime(3.0, &f1, &f2);
CHECK(f1->getTime() == 1.0);
CHECK(approx(t, 0.0));
// getInterpolatedKeyFrame:t==0 直接取关键帧快照
TransformKeyFrame r = track->getInterpolatedKeyFrame(0.0);
CHECK(r.getTranslate().closeTo(Vec3{0, 0, 0}, 1e-6));
CHECK(approx(r.getRotation().w, 1.0));
// IM_LINEAR:平移/缩放 lerp(0→0.5 区间,t=0.5)
r = track->getInterpolatedKeyFrame(0.25);
CHECK(r.getTranslate().closeTo(Vec3{2.5, 0, 0}, 1e-6));
CHECK(r.getScale().closeTo(Vec3{1, 1.25, 1}, 1e-6));
// 旋转插值语义:RIM_LINEAR 走 nlerp、RIM_SPHERICAL 走 slerp
Quat qI{1, 0, 0, 0};
Quat q180 = Quat::fromAxisAngle(Vec3{0, 0, 1}, kPi); // (0,0,0,1)
Quat sn = nlerp(0.25, qI, q180, true);
Quat ss = slerp(0.25, qI, q180, true);
// slerp(0.25):I→rotZ180 的球面路径中点,即旋转 45°,四元数 w=cos(22.5°)
CHECK(approx(ss.w, 0.9238795));
CHECK(approx(ss.z, 0.3826834));
// nlerp 走弦上线性插值后归一化:角度略小于 45°,z 分量不同
CHECK(!approx(sn.z, 0.3826834, 1e-4));
// 轨道内 getInterpolatedKeyFrame 的 RIM 分支:分别等于 nlerp/slerp 输出
TransformKeyFrame rn = track->getInterpolatedKeyFrame(0.25);
CHECK(rn.getRotation().closeTo(
nlerp(0.5, k0->getRotation(), k1->getRotation(), true), 1e-6));
anim.setRotationInterpolationMode(Animation::RIM_SPHERICAL);
TransformKeyFrame rs = track->getInterpolatedKeyFrame(0.25);
CHECK(rs.getRotation().closeTo(
slerp(0.5, k0->getRotation(), k1->getRotation(), true), 1e-6));
anim.setRotationInterpolationMode(Animation::RIM_LINEAR);
return lab::report("09-2 骨架动画:Animation 与关键帧");
}
本机实测(Apple clang 16,clang++ -std=c++20):编译通过(-Wall 零警告),断言 28/28 通过。
小结
- Animation 是带长度的动画序列,由多条轨道组成,轨道按 handle 登记(handle 匹配骨骼)。
- TransformKeyFrame 是节点轨道的变换快照(平移/缩放/旋转),关键帧按时间排序存储。
getKeyFramesAtTime超长回绕 + 二分定位前后关键帧,返回参数 t(0.0 <= t < 1.0)。- IM_LINEAR 下平移/缩放走
Math::lerp,旋转按 RIM 选 nlerp(快)或 Slerp(精确),mUseShortestRotationPath避免绕远路。
阅读导航:上一节:9.1 Skeleton 与 Bone · 下一节:9.3 AnimationState 与动画播放 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。