9.3 动画状态机
9.2 的 Animation 是静态数据,谁都能读。但同一段动画可以同时被几十个角色播放,各自播到一半、各自要不要循环——把「播放进度」从「动画数据」里拆出来,就是 AnimationState 存在的意义。这一节讲它的字段、时间推进(addTime 的回绕/夹止)以及一组状态的管理者 AnimationStateSet,最后落到多动画按权重混合。
本章与站内既有内容的分工
helio 四卷没有独立的动画状态层,播放进度与数据揉在一起;cg 三卷只讲插值数学。这里解析真实 OGRE 的 AnimationState/AnimationStateSet:timePos/length/weight/enabled/loop 五个字段各自管什么、addTime 的两种末端行为、以及骨架怎么拿多个状态算出一个加权结果。
AnimationState:正在播的那段动画
AnimationState 的构造参数把状态和数据的关系说得很清楚——它按动画名字引用一段数据,同时自己持有播放位置:
// OgreMain/include/OgreAnimationState.h:AnimationState 类(v14.6.3 源码摘录,已删减)
class _OgreExport AnimationState : public AnimationAlloc
{
public:
/** Normal constructor with all params supplied
@param
animName The name of this state.
@param
timePos The position, in seconds, where this state will begin.
@param
length The length, in seconds, of this animation state.
@param
weight Weight to apply the animation state with.
@param
enabled Whether the animation state is enabled.
*/
AnimationState(const String& animName, AnimationStateSet *parent,
Real timePos, Real length, Real weight = 1.0, bool enabled = false);
注意 length 的注释:「may be shorter than whole animation」——状态可以把一段动画截短来播,不必整段播完。字段访问器成对出现:
// OgreMain/include/OgreAnimationState.h:AnimationState 访问器(v14.6.3 源码摘录,已删减)
/// Gets the time position for this animation
Real getTimePosition(void) const;
/// Sets the time position for this animation
void setTimePosition(Real timePos);
/// Gets the total length of this animation (may be shorter than whole animation)
Real getLength() const;
/// Gets the weight (influence) of this animation
Real getWeight(void) const;
/// Sets the weight (influence) of this animation
void setWeight(Real weight);
/** Modifies the time position, adjusting for animation length
@param offset The amount of time, in seconds, to extend the animation.
This method loops at the edges if animation looping is enabled.
*/
void addTime(Real offset);
/// Returns true if the animation has reached the end and is not looping
bool hasEnded(void) const;
/// Returns true if this animation is currently enabled
bool getEnabled(void) const;
/// Sets whether this animation is enabled
void setEnabled(bool enabled);
addTime 是每帧驱动的入口:把 timePos 推进 offset 秒,如果 loop 开启就在 [0, length) 内回绕,否则超出后夹到 length 并让 hasEnded() 返回 true。weight 表示这条动画的影响力(1.0 全量,小于 1 与其它动画混合)。状态还支持按骨 blend mask(setBlendMaskEntry)做逐骨权重——不过那是骨骼混合的进阶话题,基础层只用单值 weight。
AnimationStateSet:状态的容器
一个实体往往同时维护多段动画(走、跑、攻击),AnimationStateSet 按名字持有它们:
// OgreMain/include/OgreAnimationState.h:AnimationStateSet(v14.6.3 源码摘录,已删减)
class _OgreExport AnimationStateSet : public AnimationAlloc
{
public:
/** Create a new AnimationState instance.
@param animName The name of the animation
@param timePos Starting time position
@param length Length of the animation to play
@param weight Weight to apply the animation with
@param enabled Whether the animation is enabled
*/
AnimationState* createAnimationState(const String& animName,
Real timePos, Real length, Real weight = 1.0, bool enabled = false);
/// Get an animation state by the name of the animation
AnimationState* getAnimationState(const String& name) const;
/// Tests if state for the named animation is present
bool hasAnimationState(const String& name) const;
底层是一张名字到状态的 map:
// OgreMain/include/OgreAnimationState.h:AnimationStateSet 私有成员(v14.6.3 源码摘录,已删减)
private:
unsigned long mDirtyFrameNumber;
AnimationStateMap mAnimationStates;
EnabledAnimationStateList mEnabledAnimationStates;
mEnabledAnimationStates 是只含启用状态的列表,让每帧更新只需遍历启用项;createAnimationState 把新状态同时登记进 map 与启用列表。
多状态按权重混合
当多个状态同时启用(例如走路 0.5、跑步 1.0),骨架每帧要产出一个「混合姿势」。最朴素的混合是加权平均——每个启用状态按 weight 加权:
blended = Σ(timePos × weight) / Σ weight
lab 里的 weightedBlend 只统计启用状态,禁用状态自动排除;这也对应 AnimationStateSet::getEnabledAnimationStates() 的语义。真实 OGRE 的骨架混合更复杂(逐骨 blend mask、分层混合),但「权重决定影响力」这个核心不变量是一样的。
骨骼状态混合数据流
flowchart LR
R["Skeleton 与 Animation 资源"] --> T["骨骼轨迹与关键帧"]
A["已启用的 AnimationState"] --> S["按播放时间采样"]
T --> S
S --> B["按权重合成实例骨骼变换"]
B --> M["骨骼矩阵"]
M --> V["硬件或软件蒙皮"]
从播放状态到某根骨骼的结果
启用的 AnimationState 给出时间和权重,轨迹找到该时间附近的关键帧并插值,将结果累积到实例骨骼。实例骨骼矩阵用于后续软硬件蒙皮。
选一根有两个关键帧的骨骼,手算两个时间点的插值,再加入另一播放状态观察权重。比较骨骼矩阵,再比较顶点结果。
一次骨骼求值与蒙皮分流
sequenceDiagram
participant A as AnimationStateSet
participant T as AnimationTrack
participant I as SkeletonInstance
participant E as Entity
A->>T: 提供已启用状态的时间和权重
T->>T: 找到关键帧并插值
T->>I: 累积实例骨骼变换
I-->>E: 当前骨骼矩阵
alt 硬件蒙皮路径
E->>E: 保留顶点输入并提供矩阵参数
else 软件蒙皮路径
E->>E: CPU 更新绘制所需顶点
end
源码定位
OgreMain/include/OgreAnimationState.h:AnimationState(58)、构造(79)、getTimePosition(87)、setTimePosition(89)、getLength(91)、getWeight(95)、setWeight(97)、addTime(103)、hasEnded(106)、getEnabled(109)、setEnabled(111)、setLoop(121)、AnimationStateSet(200)、createAnimationState(219)、getAnimationStates(245)、mAnimationStates(277)
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
下面用纯 C++ 复现 AnimationState 的字段、时间回绕与多状态权重混合。它与 src/09-3-animation-state.cpp 逐字节一致:
// file: src/09-3-animation-state.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/09-3-animation-state.cpp -o bin/09-3-animation-state && ./bin/09-3-animation-state
//
// 复现 AnimationState/AnimationStateSet(对应 OgreAnimationState.h 58/87/97/103/111/200/219/245):
// AnimationState 持有 animName/timePos/length/weight/enabled/loop;
// addTime 推进时间,loop 开启时在 [0, length) 回绕;
// AnimationStateSet 按名持有状态表,getAnimationStates 返回全部状态;
// 多动画按权重混合:各启用状态的时间位置 × 权重累加再归一化。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <cstdint>
#include <map>
#include <string>
namespace ogre_repro {
// 对应 OgreAnimationState.h 58:AnimationState
class AnimationState {
public:
AnimationState(const std::string& animName, float timePos, float length, float weight,
bool enabled)
: mAnimationName(animName),
mTimePos(timePos),
mLength(length),
mWeight(weight),
mEnabled(enabled),
mLoop(true) {}
// 对应 OgreAnimationState.h 85:getAnimationName
const std::string& getAnimationName() const { return mAnimationName; }
// 对应 OgreAnimationState.h 87:getTimePosition
float getTimePosition() const { return mTimePos; }
// 对应 OgreAnimationState.h 89:setTimePosition
void setTimePosition(float timePos) { mTimePos = timePos; }
// 对应 OgreAnimationState.h 91:getLength
float getLength() const { return mLength; }
// 对应 OgreAnimationState.h 95:getWeight
float getWeight() const { return mWeight; }
// 对应 OgreAnimationState.h 97:setWeight
void setWeight(float weight) { mWeight = weight; }
// 对应 OgreAnimationState.h 109:getEnabled
bool getEnabled() const { return mEnabled; }
// 对应 OgreAnimationState.h 111:setEnabled
void setEnabled(bool enabled) { mEnabled = enabled; }
void setLoop(bool loop) { mLoop = loop; }
bool getLoop() const { return mLoop; }
// 对应 OgreAnimationState.h 103:addTime,loop 时回绕
void addTime(float offset) {
mTimePos += offset;
if (mLoop) {
while (mTimePos >= mLength) mTimePos -= mLength;
while (mTimePos < 0.f) mTimePos += mLength;
} else if (mTimePos >= mLength) {
mTimePos = mLength;
}
}
bool hasEnded() const { return !mLoop && mTimePos >= mLength; }
private:
std::string mAnimationName;
float mTimePos;
float mLength;
float mWeight;
bool mEnabled;
bool mLoop;
};
// 对应 OgreAnimationState.h 200:AnimationStateSet
class AnimationStateSet {
public:
// 对应 OgreAnimationState.h 219:createAnimationState
AnimationState* createAnimationState(const std::string& animName, float timePos, float length,
float weight, bool enabled) {
AnimationState* state = new AnimationState(animName, timePos, length, weight, enabled);
mAnimationStates[animName] = state;
return state;
}
AnimationState* getAnimationState(const std::string& name) const {
auto it = mAnimationStates.find(name);
return it == mAnimationStates.end() ? nullptr : it->second;
}
bool hasAnimationState(const std::string& name) const {
return mAnimationStates.find(name) != mAnimationStates.end();
}
// 对应 OgreAnimationState.h 245:getAnimationStates
const std::map<std::string, AnimationState*>& getAnimationStates() const {
return mAnimationStates;
}
private:
// 对应 OgreAnimationState.h 277:mAnimationStates
std::map<std::string, AnimationState*> mAnimationStates;
};
// 按权重的混合:只统计启用状态,weightedBlend = Σ(time*w) / Σw
float weightedBlend(AnimationStateSet& set) {
float acc = 0.f;
float totalW = 0.f;
for (auto& kv : set.getAnimationStates()) {
AnimationState* state = kv.second;
if (!state->getEnabled()) continue;
acc += state->getTimePosition() * state->getWeight();
totalW += state->getWeight();
}
return totalW > 0.f ? acc / totalW : 0.f;
}
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
// 构造状态:名称 / 时间位置 / 长度 / 权重 / 启用
AnimationStateSet set;
AnimationState* walk = set.createAnimationState("walk", 0.2f, 1.0f, 0.5f, true);
CHECK_EQ(walk->getTimePosition(), 0.2f);
CHECK_EQ(walk->getLength(), 1.0f);
CHECK_EQ(walk->getWeight(), 0.5f);
CHECK(walk->getEnabled());
CHECK(set.hasAnimationState("walk"));
CHECK_EQ(set.getAnimationState("walk"), walk);
// addTime 推进时间
walk->addTime(0.3f);
CHECK_EQ(walk->getTimePosition(), 0.5f);
// loop 回绕:长度 1.0,0.75 + 0.5 → 1.25 − 1.0 = 0.25
walk->setTimePosition(0.75f);
walk->addTime(0.5f);
CHECK_EQ(walk->getTimePosition(), 0.25f);
// 非 loop:超出夹到 length 并 hasEnded
walk->setLoop(false);
walk->setTimePosition(0.8f);
walk->addTime(0.5f);
CHECK_EQ(walk->getTimePosition(), 1.0f);
CHECK(walk->hasEnded());
// 多状态按权重混合:walk(w=0.5, t=0.2) + run(w=1.0, t=0.8)
walk->setEnabled(true);
walk->setTimePosition(0.2f);
walk->setWeight(0.5f);
walk->setLoop(true);
AnimationState* run = set.createAnimationState("run", 0.8f, 1.0f, 1.0f, true);
float blended = weightedBlend(set);
CHECK_EQ(blended, (0.2f * 0.5f + 0.8f * 1.0f) / 1.5f);
// 禁用状态不参与混合:run disabled → 只剩 walk
run->setEnabled(false);
float blended2 = weightedBlend(set);
CHECK_EQ(blended2, 0.2f);
return lab::report("09-3 动画状态机");
}
本机实测(Apple clang 16,clang++ -std=c++20 -Wall):编译通过(零警告),断言 12/12 通过。
小结
AnimationState按动画名字引用数据,自己持有timePos/length/weight/enabled/loop五个运行期字段。addTime是每帧推进入口:loop 开启在[0, length)回绕,关闭则夹到length并触发hasEnded()。length可以比原动画短——状态支持截短播放。AnimationStateSet用 map 按名持有全部状态,另维护启用状态列表供每帧快速遍历。- 多状态按权重混合:
Σ(timePos × weight) / Σ weight,禁用状态不参与。
阅读导航:上一节:9.2 动画与轨迹 · 下一节:10.1 顶点变形动画 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。