《OGRE 3D 渲染引擎原理与架构》13.3 对象数据布局

OGRE 的对象数据布局把局部变换、派生缓存、脏标志分层存放:OgreNode.h 用 mPosition/mOrientation/mScale 存局部数据,mDerived* 与 mCachedTransform 存派生缓存,位域标志决定惰性重算;updateFromParentImpl 按继承标志合并父子变换。lab 复现 2D 节点布局与惰性更新。

13.3 对象数据布局

前两节看了「怎么分配、怎么共享」,这一节看「对象内部的数据怎么摆」。OGRE 的场景对象是典型的缓存密集型数据布局:每个 Node 同时持有局部变换、派生变换缓存和一组脏标志。设计核心是惰性更新——只要节点没动过,每帧渲染查询的是上一次缓存的派生值;只有被 setPosition/setOrientation 等标记为脏的节点,才会在 _updateFromParent 时重算。这就是规模化场景下「一万个节点每帧零额外计算」的底层保障。

本章与站内既有内容的分工

《游戏引擎实现原理》(helio 四卷)实现场景图时把「变换同步」放在每帧统一遍历里;这里解析真实 OGRE Node 的数据布局:局部数据、派生缓存、脏标志如何分区存放,位域怎么把 8 个布尔压进 1 个字节,以及 updateFromParentImpl 按什么规则合并父子变换。15.2 的 lab 还会从「双引擎对照」的角度再看一次变换同步,本篇聚焦字段与标志本身。

Node 的三区数据布局

OgreNode.h 把 Node 的数据分成三个区:指针区、标志区、变换区。标志区尤其值得细看——8 个布尔被声明为位域,编译器会尽力把它们压进同一字节:

// OgreMain/include/OgreNode.h:Node 数据成员(v14.6.3 源码摘录,已删减)
    protected:
        /// Pointer to parent node
        Node* mParent;
        /// Collection of pointers to direct children
        ChildNodeMap mChildren;

        typedef std::vector<Node*> ChildUpdateSet;
        /// List of children which need updating, used if self is not out of date but children are
        ChildUpdateSet mChildrenToUpdate;
        /// Friendly name of this node
        String mName;

        /// Flag to indicate own transform from parent is out of date
        mutable bool mNeedParentUpdate : 1;
        /// Flag indicating that all children need to be updated
        bool mNeedChildUpdate : 1;
        /// Flag indicating that parent has been notified about update request
        bool mParentNotified : 1;
        /// Flag indicating that the node has been queued for update
        bool mQueuedForUpdate : 1;
        /// Stores whether this node inherits orientation from it's parent
        bool mInheritOrientation : 1;
        /// Stores whether this node inherits scale from it's parent
        bool mInheritScale : 1;
        mutable bool mCachedTransformOutOfDate : 1;

        /// Stores the orientation of the node relative to it's parent.
        Quaternion mOrientation;
        /// Stores the position/translation of the node relative to its parent.
        Vector3 mPosition;
        /// Stores the scaling factor applied to this node
        Vector3 mScale;

        /// Cached derived transform as a 4x4 matrix
        mutable Affine3 mCachedTransform;
        ...
        mutable Quaternion mDerivedOrientation;
        ...
        mutable Vector3 mDerivedPosition;
        ...
        mutable Vector3 mDerivedScale;
        ...
        void _updateFromParent(void) const;

三个区各司其职:

区字段用途
指针/拓扑mParent、mChildren、mChildrenToUpdate场景图结构本身
标志(位域)mNeedParentUpdate、mNeedChildUpdate、mCachedTransformOutOfDate…谁脏、谁继承、谁排队
变换数据mOrientation/mPosition/mScale局部变换(相对父)
派生缓存mDerivedOrientation/mDerivedPosition/mDerivedScale、mCachedTransform合并后的世界变换(相对根)

关键在「缓存」二字:mDerivedPosition 的注释写着「This is updated when _updateFromParent is called」——派生值不是每帧算的,只在需要时由更新流程触发。mNeedParentUpdate 从 setPosition 等 API 置位,在 updateFromParentImpl 末尾清位,形成一个完整的脏标记闭环。

派生变换的合并规则

OgreNode.cpp 的 updateFromParentImpl 是布局的使用者:它消费局部数据、按继承标志写入派生缓存:

// OgreMain/src/OgreNode.cpp:Node::updateFromParentImpl(v14.6.3 源码摘录,已删减)
    void Node::updateFromParentImpl(void) const
    {
        mCachedTransformOutOfDate = true;

        if (mParent)
        {
#if OGRE_NODE_INHERIT_TRANSFORM
            ...
#else
            // Update orientation
            const Quaternion& parentOrientation = mParent->_getDerivedOrientation();
            if (mInheritOrientation)
            {
                // Combine orientation with that of parent
                mDerivedOrientation = parentOrientation * mOrientation;
            }
            else
            {
                // No inheritance
                mDerivedOrientation = mOrientation;
            }

            // Update scale
            const Vector3& parentScale = mParent->_getDerivedScale();
            if (mInheritScale)
            {
                // Scale own position by parent scale, NB just combine
                // as equivalent axes, no shearing
                mDerivedScale = parentScale * mScale;
            }
            else
            {
                // No inheritance
                mDerivedScale = mScale;
            }

            // Change position vector based on parent's orientation & scale
            mDerivedPosition = parentOrientation * (parentScale * mPosition);

            // Add altered position vector to parents
            mDerivedPosition += mParent->_getDerivedPosition();
#endif
        }
        else
        {
            // Root node, no parent
            mDerivedOrientation = mOrientation;
            mDerivedPosition = mPosition;
            mDerivedScale = mScale;
        }

        mNeedParentUpdate = false;
    }

这段代码编码了三个继承语义:

  1. 旋转继承:mInheritOrientation 为真时 derived = parent * local(先父后子),为假时只取本地——这解释了为什么「某些节点不希望被父节点旋转带走」(比如 UI 上的固定朝向标记)。
  2. 缩放继承:mInheritScale 为真时 derived = parentScale * localScale(分量相乘),为假时只取本地。
  3. 位置合成:无论继承开关,位置都经过父的旋转与缩放后再加父位置——derivedPos = parentOrient * (parentScale * localPos) + parentPos,这正是「挂到移动平台上跟着走」的数学形式。

注意 mNeedParentUpdate = false 放在末尾:派生缓存一旦写回,脏标志即被清掉,下一帧直接命中缓存。

MovableObject:另一种紧凑布局

Node 之外,MovableObject(挂到节点上的可渲染对象)也用同样的思路压缩数据——位域 + 缓存:

// OgreMain/include/OgreMovableObject.h:MovableObject 数据成员(v14.6.3 源码摘录,已删减)
        /// node to which this object is attached
        Node* mParentNode;
        /// MovableObject listener - only one allowed (no list) for size & performance reasons. */
        Listener* mListener;
        bool mParentIsTagPoint : 1;
        /// Is this object visible?
        bool mVisible : 1;
        /// Is debug display enabled?
        bool mDebugDisplay : 1;
        /// Hidden because of distance?
        bool mBeyondFarDistance : 1;
        /// Does this object cast shadows?
        bool mCastShadows : 1;
        /// Flags whether the RenderQueue's default should be used.
        bool mRenderQueueIDSet : 1;
        /// Flags whether the RenderQueue's default should be used.
        bool mRenderQueuePrioritySet : 1;
        /// Does rendering this object disabled by listener?
        bool mRenderingDisabled : 1;
        /// The render queue to use when rendering this object
        uint8 mRenderQueueID;
        /// The render queue group to use when rendering this object
        ushort mRenderQueuePriority;
        ...
        /// Cached world AABB of this object
        mutable AxisAlignedBox mWorldAABB;
        // Cached world bounding sphere
        mutable Sphere mWorldBoundingSphere;
        /// List of lights for this object
        mutable LightList mLightList;
        /// The last frame that this light list was updated in
        mutable ulong mLightListUpdated;

9 个布尔位域挤在一起,渲染队列 ID 用 1 字节、优先级用 2 字节,注释直接说明「one allowed (no list) for size & performance reasons」——为尺寸与性能牺牲多监听器支持。世界 AABB、包围球、光照列表都是 mutable 缓存,与 Node 的派生缓存同一套「用脏标志换速度」哲学:查询时若缓存新鲜就直接返回。

用工作负载解释缓存收益

结构体布局、对齐、指针间接访问与数据拷贝都会影响局部性。对齐与分配类别影响可用地址和管理方式,命中率取决于实际的遍历顺序与数据量。

用相同对象数、访问轨迹和构建模式记录时间与分配数据。需要时将批处理后更少的 draw 与更高的实例数据更新成本一起呈现。

源码定位

  • OgreMain/include/OgreNode.h :Node* mParent(100)、mutable bool mNeedParentUpdate : 1(111)、bool mInheritOrientation : 1(119)、bool mInheritScale : 1(121)、Quaternion mOrientation(125)、Vector3 mPosition(127)、Vector3 mScale(129)、mutable Affine3 mCachedTransform(132)、mutable Quaternion mDerivedOrientation(144)、mutable Vector3 mDerivedPosition(153)、mutable Vector3 mDerivedScale(162)、void _updateFromParent(void) const;(170)
  • OgreMain/src/OgreNode.cpp :void Node::updateFromParentImpl(void) const(继承合并逻辑,mDerivedOrientation = parentOrientation * mOrientation、mDerivedScale = parentScale * mScale、mDerivedPosition = parentOrientation * (parentScale * mPosition)、mNeedParentUpdate = false)
  • OgreMain/include/OgreMovableObject.h :位域标志(115-129)、mutable AxisAlignedBox mWorldAABB(146)、mutable LightList mLightList(150)

上游引用固定到 OGRE v14.6.3 源码 。

可运行产物:C++ 最小验证

下面用纯 C++ 复现 Node 的「局部数据 + 派生缓存 + 位域脏标志」布局。它与 src/ogre-ext-13-3-object-data-layout.cpp 逐字节一致:

// file: src/ogre-ext-13-3-object-data-layout.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/ogre-ext-13-3-object-data-layout.cpp -o bin/ogre-ext-13-3-object-data-layout && ./bin/ogre-ext-13-3-object-data-layout
//
// 复现 OgreNode.h / OgreNode.cpp 的对象数据布局与惰性更新:
//   局部变换(mPosition/mScale/mOrientation)+ 派生缓存(mDerived*);
//   位域打包脏标志(对应 mNeedParentUpdate 等 :1 声明);
//   updateFromParentImpl 按 inheritOrientation/inheritScale 合并父子变换,
//   根节点(无父)直接复制局部值到派生缓存。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <cmath>
#include <cstdint>

namespace ogre_repro {

// 位域打包:bit0 = needParentUpdate, bit1 = inheritOrientation, bit2 = inheritScale
struct NodeData {
  // 局部变换
  float posX, posY;
  float scaleX, scaleY;
  float orient;  // 弧度
  // 派生缓存
  float derivedX, derivedY;
  float derivedScaleX, derivedScaleY;
  float derivedOrient;
  // 位域标志(对应源码 bool mNeedParentUpdate : 1 等)
  uint8_t flags;

  bool needParentUpdate() const { return (flags & 1u) != 0; }
  bool inheritOrientation() const { return (flags & 2u) != 0; }
  bool inheritScale() const { return (flags & 4u) != 0; }
  void setDirty() { flags |= 1u; }
};

// 对应 Node::updateFromParentImpl:parent 为 nullptr 时是根节点
void updateFromParent(NodeData& node, const NodeData* parent) {
  if (!parent) {
    // 根节点:无父,直接复制(对应源码 else 分支)
    node.derivedOrient = node.orient;
    node.derivedScaleX = node.scaleX;
    node.derivedScaleY = node.scaleY;
    node.derivedX = node.posX;
    node.derivedY = node.posY;
    node.flags &= ~1u;
    return;
  }

  if (node.inheritOrientation())
    node.derivedOrient = parent->derivedOrient + node.orient;
  else
    node.derivedOrient = node.orient;

  if (node.inheritScale()) {
    node.derivedScaleX = parent->derivedScaleX * node.scaleX;
    node.derivedScaleY = parent->derivedScaleY * node.scaleY;
  } else {
    node.derivedScaleX = node.scaleX;
    node.derivedScaleY = node.scaleY;
  }

  // mDerivedPosition = parentOrient * (parentScale * mPosition) + parentPos
  float ca = std::cos(parent->derivedOrient);
  float sa = std::sin(parent->derivedOrient);
  float lx = parent->derivedScaleX * node.posX;
  float ly = parent->derivedScaleY * node.posY;
  node.derivedX = parent->derivedX + (ca * lx - sa * ly);
  node.derivedY = parent->derivedY + (sa * lx + ca * ly);

  // 派生缓存写回后清脏
  node.flags &= ~1u;
}

}  // namespace ogre_repro

int main() {
  using namespace ogre_repro;

  // 根节点:无父,派生 == 局部
  NodeData root{1.f, 2.f, 3.f, 4.f, 0.5f, 1.f, 2.f, 3.f, 4.f, 0.5f, 0u};
  updateFromParent(root, nullptr);
  CHECK(root.derivedX == 1.f && root.derivedY == 2.f);
  CHECK(root.derivedOrient == 0.5f);
  CHECK(root.derivedScaleX == 3.f && root.derivedScaleY == 4.f);

  // 子节点(继承旋转与缩放):pos 受父旋转+缩放+位置影响
  NodeData child{0.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0u};
  child.flags = 6u;  // inheritOrientation | inheritScale
  child.setDirty();
  CHECK(child.needParentUpdate());
  updateFromParent(child, &root);
  CHECK(!child.needParentUpdate());  // 更新后清脏
  // 父位置 (1,2) + 旋转 0.5 作用于局部 (0,0)
  CHECK_EQ(child.derivedX, 1.f);
  CHECK_EQ(child.derivedY, 2.f);
  CHECK_EQ(child.derivedScaleX, 3.f);
  CHECK_EQ(child.derivedScaleY, 4.f);
  CHECK_EQ(child.derivedOrient, 0.5f);

  // 局部位置非零:旋转真正生效
  child.posX = 1.f;  child.posY = 0.f;
  child.setDirty();
  updateFromParent(child, &root);
  float ca = std::cos(root.derivedOrient), sa = std::sin(root.derivedOrient);
  CHECK(std::fabs(child.derivedX - (1.f + 3.f * ca)) < 1e-5f);
  CHECK(std::fabs(child.derivedY - (2.f + 3.f * sa)) < 1e-5f);

  // 仅继承旋转:角度合并,缩放不继承
  NodeData nodeO{0.f, 0.f, 1.f, 1.f, 0.8f, 0.f, 0.f, 0.f, 0.f, 0.f, 2u};
  nodeO.setDirty();
  updateFromParent(nodeO, &root);
  CHECK(std::fabs(nodeO.derivedOrient - (root.derivedOrient + 0.8f)) < 1e-5f);
  CHECK_EQ(nodeO.derivedScaleX, 1.f);

  // 仅继承缩放:角度不继承,缩放相乘
  NodeData nodeS{0.f, 0.f, 5.f, 6.f, 0.1f, 0.f, 0.f, 0.f, 0.f, 0.f, 4u};
  nodeS.setDirty();
  updateFromParent(nodeS, &root);
  CHECK_EQ(nodeS.derivedOrient, 0.1f);
  CHECK_EQ(nodeS.derivedScaleX, 15.f);
  CHECK_EQ(nodeS.derivedScaleY, 24.f);

  // 位域读取:三个独立标志互不干扰
  CHECK(root.inheritOrientation() == false);
  CHECK(nodeO.inheritOrientation() == true && nodeO.inheritScale() == false);
  CHECK(nodeS.inheritScale() == true && nodeS.inheritOrientation() == false);

  return lab::report("13.3 对象数据布局");
}

本机实测(Apple clang,clang++ -std=c++20 -Wall):编译零警告,断言 20/20 通过。

小结

  • Node 的数据分三区:拓扑指针、位域标志、变换数据 + 派生缓存,派生值只在 _updateFromParent 时重算。
  • 8 个布尔用位域(:1)打包,单个标志的置位/清位成本极低,缓存查询直接命中。
  • updateFromParentImpl 编码继承语义:旋转/缩放可按 mInheritOrientation/mInheritScale 关闭,位置始终经过父旋转与缩放。
  • MovableObject 沿用同一哲学:位域打包可见性/阴影等开关,世界 AABB、光源列表做 mutable 缓存。
  • 末尾清脏(mNeedParentUpdate = false)让「脏标记-重算-清脏」形成闭环,规模化场景下未移动节点零计算。

阅读导航:上一节:13.2 共享指针 · 下一节:14.1 测试体系 。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「books」更多文章

  1. 《大规模分布式计算深入解析》15.3 落地:从 Neo4j 到自研图引擎
  2. 《大规模分布式计算深入解析·图计算与图数据库内核》 · 目录与学习路径(45 篇)
  3. 《大规模分布式计算深入解析》15.2 十一卷主线:从切分到图