《OGRE 3D 渲染引擎原理与架构》2.1 自定义可移动对象

自定义场景内容第一步是继承 MovableObject:它同时提供挂节点、渲染距离、可见性、类型名与包围盒等基础设施,派生类必须实现 getMovableType/getBoundingBox/getBoundingRadius/_updateRenderQueue 四个契约。lab 复现一个最小 MovableObject 子类的生命周期。

2.1 自定义可移动对象

第 1 章解决「插件怎么装」,这一章解决「装进去之后你写的东西长什么样」。OGRE 里一切能挂到场景节点、能参与剔除与渲染的「东西」——实体、灯光、相机、粒子系统——都继承 MovableObject。要往引擎里加一种全新的场景内容,第一步就是写一个 MovableObject 子类。这一节看 OgreMovableObject.h 给派生类准备了什么,以及必须实现哪些纯虚方法。

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

卷三 1.x 从 Entity 这个具体对象讲了场景内容如何渲染;这里从抽象层讲 MovableObject 契约本身——它是卷三那些对象的共同基类,也是写自定义场景内容的第一步。第 2.2 讲 Renderable(MovableObject 往渲染队列里塞的东西),2.3 讲 MovableObjectFactory(谁负责造它)。

基类给了什么

MovableObject 同时继承三个基类——ShadowCaster(能投影)、AnimableObject(能动画)、MovableAlloc(自定义分配):

// OgreMain/include/OgreMovableObject.h:MovableObject 类声明(v14.6.3 源码摘录,已删减)
    class _OgreExport MovableObject : public ShadowCaster, public AnimableObject, public MovableAlloc
    {
    ...
    protected:
        /// Name of this object
        String mName;
        /// Creator of this object (if created by a factory)
        MovableObjectFactory* mCreator;
        /// SceneManager holding this object (if applicable)
        SceneManager* mManager;
        /// 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;
        ...
        /// The render queue to use when rendering this object
        uint8 mRenderQueueID;
        /// The render queue group to use when rendering this object
        ushort mRenderQueuePriority;
        /// Upper distance to still render
        Real mUpperDistance;
        Real mSquaredUpperDistance;
        /// Minimum pixel size to still render
        Real mMinPixelSize;
        ...
        /// 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;
        ...
    public:
        MovableObject();
        MovableObject(const String& name);
        virtual ~MovableObject();
        ...
        /** Returns the name of this object. */
        const String& getName(void) const { return mName; }

        /** Returns the type name of this object. */
        virtual const String& getMovableType(void) const = 0;

派生类免费获得一整箱基础设施:名字、创建者/管理者/父节点指针、可见性位域(mVisible/mDebugDisplay/mBeyondFarDistance/mCastShadows)、渲染队列编号与优先级、渲染距离、最小像素、世界 AABB 与包围球缓存、光源列表、查询/可见性标志。这些成员让一个最小的子类也能被场景管理器、渲染队列和视锥剔除正常对待。

必须实现的契约

基类里四个方法是纯虚的,任何 MovableObject 子类都得给出实现:

// OgreMain/include/OgreMovableObject.h:纯虚契约(v14.6.3 源码摘录,已删减)
        /** Returns the type name of this object. */
        virtual const String& getMovableType(void) const = 0;
        ...
        /** Retrieves the local axis-aligned bounding box for this object.

            This bounding box is in local coordinates.
        */
        virtual const AxisAlignedBox& getBoundingBox(void) const = 0;

        /** Retrieves the radius of the origin-centered bounding sphere 
             for this object.
        */
        virtual Real getBoundingRadius(void) const = 0;
        ...
        /** Internal method by which the movable object must add Renderable subclass instances to the rendering queue.

            The engine will call this method when this object is to be rendered. The object must then create one or more
            Renderable subclass instances which it places on the passed in Queue for rendering.
        */
        virtual void _updateRenderQueue(RenderQueue* queue) = 0;
纯虚方法职责
getMovableType()返回类型名(如 "Entity"、"MyCustom"),SceneManager::createMovableObject 靠它找工厂
getBoundingBox()局部坐标 AABB,视锥剔除用它
getBoundingRadius()包围球半径,距离/球剔除用
_updateRenderQueue(RenderQueue*)渲染时把 0 个或多个 Renderable 塞进队列

_updateRenderQueue 是「场景对象」与「渲染」之间的桥:引擎判定此对象可见后调用它,它负责把真正可渲染的东西(Renderable 子类,下一节讲)放进渲染队列。一个对象可以不渲染任何东西(比如灯光),那时 _updateRenderQueue 留空即可。

可见性与渲染距离

可见性不是简单一个开关:setVisible 只设 mVisible 位,isVisible() 会再叠加上渲染距离与最小像素的判断:

// OgreMain/include/OgreMovableObject.h:setVisible / getVisible / isVisible / setRenderingDistance(v14.6.3 源码摘录,已删减)
        void setVisible(bool visible) { mVisible = visible; }

        /** Gets this object whether to be visible or not, if it has a renderable component. 

            Returns the value set by MovableObject::setVisible only.
        */
        bool getVisible(void) const { return mVisible; }

        /** Returns whether or not this object is supposed to be visible or not. 

            Takes into account both upper rendering distance and visible flag.
        */
        virtual bool isVisible(void) const;

        /** Sets the distance at which the object is no longer rendered.
        @note Camera::setUseRenderingDistance() needs to be called for this parameter to be used.
        @param dist Distance beyond which the object will not be rendered 
            (the default is 0, which means objects are always rendered).
        */
        void setRenderingDistance(Real dist) {
            mUpperDistance = dist; 
            mSquaredUpperDistance = mUpperDistance * mUpperDistance;
        }

setRenderingDistance 顺带预算了 mSquaredUpperDistance——用平方距离比较省一次开方,是批量剔除的经典优化。isVisible() 的实现(OgreMovableObject.cpp)会综合 mVisible、mBeyondFarDistance 与渲染距离判断。注释还提醒:频繁的小改动用 setVisible,长时间隐藏则直接 detach 节点更省——那是结构级移除,省下每帧的可见性检测开销。

源码定位

  • OgreMain/include/OgreMovableObject.h :MovableObject 类(56)、受保护成员(104-160)、getName(198)、getMovableType(201)、_notifyCurrentCamera(247)、getBoundingBox(253)、getBoundingRadius(258)、_updateRenderQueue(272)、setVisible(288)、getVisible(294)、isVisible(300)、setRenderingDistance(307)

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

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

下面用纯 C++ 复现 MovableObject 子类的最小契约:四个纯虚方法、可见性标志、渲染距离与节点挂接。它与 src/02-1-custom-movable-object.cpp 逐字节一致:

// file: src/02-1-custom-movable-object.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/02-1-custom-movable-object.cpp -o bin/02-1-custom-movable-object && ./bin/02-1-custom-movable-object
//
// 复现 MovableObject 子类契约(对应 OgreMain/include/OgreMovableObject.h 56- 的类声明、
//   201/253/258/272 的 getMovableType/getBoundingBox/getBoundingRadius/_updateRenderQueue、
//   288-313 的 setVisible/getVisible/setRenderingDistance):
//   子类必须实现四个纯虚方法;可见性由 mVisible 叠加渲染距离共同决定;
//   对象可挂到节点并记录父节点。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <cstdint>
#include <string>

namespace ogre_repro {

// 对应 OgreAxisAlignedBox:极简 AABB
struct AABB {
  float minX = 0, minY = 0, minZ = 0;
  float maxX = 0, maxY = 0, maxZ = 0;
};

// 对应 Node:极简场景节点
struct Node {
  std::string name;
};

// 对应 OgreMovableObject.h 56-:抽象可移动对象
class MovableObjectBase {
 public:
  virtual ~MovableObjectBase() {}
  virtual const std::string& getMovableType() const = 0;
  virtual const AABB& getBoundingBox() const = 0;
  virtual float getBoundingRadius() const = 0;
  virtual void _updateRenderQueue() = 0;  // 简化:不接队列,记录次数
  virtual void _notifyCurrentCamera(int) {}

  void setVisible(bool v) { mVisible = v; }
  bool getVisible() const { return mVisible; }
  // 对应 isVisible:叠加 mVisible 与渲染距离(简化:距离由外部判 far)
  virtual bool isVisible(bool beyondFar) const { return mVisible && !beyondFar; }
  void setRenderingDistance(float d) { mUpperDistance = d; }
  float getRenderingDistance() const { return mUpperDistance; }

  void attachTo(Node* n) { mParentNode = n; }
  Node* getParentNode() const { return mParentNode; }

 protected:
  bool mVisible = true;
  float mUpperDistance = 0.f;
  Node* mParentNode = nullptr;
};

// 自定义可移动对象:实现四个纯虚契约
class MyMovable : public MovableObjectBase {
 public:
  const std::string& getMovableType() const override { return sType; }
  const AABB& getBoundingBox() const override { return mBox; }
  float getBoundingRadius() const override { return mRadius; }
  void _updateRenderQueue() override { mQueueCalls++; }

  static const std::string sType;
  AABB mBox = {-1, -1, -1, 1, 1, 1};
  float mRadius = 1.732f;
  int mQueueCalls = 0;
};

const std::string MyMovable::sType = "MyMovable";

}  // namespace ogre_repro

int main() {
  using namespace ogre_repro;

  MyMovable m;
  // 默认可见、无父节点、渲染距离 0(不限制)
  CHECK(m.getVisible());
  CHECK(m.getParentNode() == nullptr);
  CHECK_EQ(m.getRenderingDistance(), 0.f);

  // 四个纯虚契约
  CHECK_EQ(m.getMovableType(), "MyMovable");
  CHECK_EQ(m.getBoundingBox().maxX, 1.f);
  CHECK_EQ(m.getBoundingRadius(), 1.732f);
  CHECK_EQ(m.mQueueCalls, 0);

  // _updateRenderQueue 在可见判定后触发
  m._updateRenderQueue();
  m._updateRenderQueue();
  CHECK_EQ(m.mQueueCalls, 2);

  // 可见性:mVisible + 距离共同决定(far 则不可见)
  CHECK(m.isVisible(false));
  m.setVisible(false);
  CHECK(!m.getVisible());
  CHECK(!m.isVisible(false));
  m.setVisible(true);
  CHECK(m.isVisible(false));
  CHECK(!m.isVisible(true));  // beyond far distance

  // 渲染距离:设定后读取一致
  m.setRenderingDistance(100.f);
  CHECK_EQ(m.getRenderingDistance(), 100.f);

  // 节点挂接
  Node sceneRoot;
  sceneRoot.name = "Root";
  m.attachTo(&sceneRoot);
  CHECK(m.getParentNode() == &sceneRoot);

  // _notifyCurrentCamera 可覆写:默认不崩溃
  m._notifyCurrentCamera(1);

  return lab::report("2.1 自定义可移动对象");
}

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

小结

  • MovableObject : ShadowCaster, AnimableObject, MovableAlloc 是场景内容共同基类,免费提供名字/可见性/渲染距离/包围盒缓存/光源列表等设施。
  • 派生类必须实现四个纯虚方法:getMovableType/getBoundingBox/getBoundingRadius/_updateRenderQueue。
  • setVisible 只设位,isVisible() 叠加渲染距离综合判断。
  • setRenderingDistance 预存平方距离,避免每帧开方。
  • 对象可挂到 Node,频繁可见性改动用 setVisible,长期隐藏用 detach。

阅读导航:上一节:1.3 自定义插件骨架 · 下一节:2.2 自定义可渲染对象 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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