《OGRE 3D 渲染引擎原理与架构》2.1 Root 单例与构造顺序

Root 是 OGRE 的引擎单例,继承 Singleton<Root>,全进程只有一个实例。构造顺序有讲究:日志管理器最先,之后是动态库、归档、资源组,再到材质、网格、骨架管理器,最后加载插件。第二次构造会被断言拦截。lab 用 C++ 复现 Singleton 模板与创建顺序日志。

2.1 Root 单例与构造顺序

Root 是 OGRE 的引擎入口,全进程只有一个实例。OgreRoot.h 里它的继承关系写得明明白白:

// OgreMain/include/OgreRoot.h:Root 类声明(v14.6.3 源码摘录)
        created before any other Ogre operations are called. Once an
        instance has been created, the same instance is accessible
        throughout the life of that object by using Root::getSingleton
        (as a reference) or Root::getSingletonPtr (as a pointer).
    */
    class _OgreExport Root : public Singleton<Root>, public RootAlloc

Root : public Singleton<Root>——单例模板参数化,而不是写死一个全局 instance() 方法。构造签名带三个默认参数:

// OgreMain/include/OgreRoot.h:Root 构造(v14.6.3 源码摘录)
        Root(const String& pluginFileName = "plugins.cfg",
            const String& configFileName = "ogre.cfg",
            const String& logFileName = "Ogre.log");
        ~Root();

分别是插件列表文件、配置文件和日志文件名。Singleton<T> 模板在 OgreSingleton.h,实现很简短但语义明确:

// OgreMain/include/OgreSingleton.h:Singleton<T>(v14.6.3 源码摘录,已删减)
template <typename T> class Singleton
{
private:
    Singleton(const Singleton<T>&);
    Singleton& operator=(const Singleton<T>&);
protected:
    static T* msSingleton;
public:
    Singleton(void)
    {
        OgreAssert(!msSingleton, "There can be only one singleton");
        msSingleton = static_cast<T*>(this);
    }
    ~Singleton(void)
    {
        assert(msSingleton);
        msSingleton = 0;
    }
    static T& getSingleton(void)
    {
        assert(msSingleton);
        return (*msSingleton);
    }
    static T* getSingletonPtr(void) { return msSingleton; }
};

要点:静态成员 msSingleton 记录实例;构造时断言「只能有一个单例」,否则 OgreAssert 触发;getSingleton() 返回引用,getSingletonPtr() 返回指针。复制构造与赋值被私有禁掉。整个 OGRE 的单例家族——LogManager、MaterialManager、MeshManager——都用这套模板。

构造顺序:日志先行

OgreRoot.cpp 的构造函数是一份精密的初始化清单。顺序本身就是架构:日志最先建,因为后面每一步都要写日志;动态库管理器接着建,因为加载插件靠它;归档与资源组随后,为资源加载铺路;最后才到各内容管理器与插件。截取开头与中段:

// OgreMain/src/OgreRoot.cpp:Root 构造(v14.6.3 源码摘录,已删减)
        // Create log manager and default log file if there is no log manager yet
        if(!LogManager::getSingletonPtr())
        {
            mLogManager = std::make_unique<LogManager>();
            mLogManager->createLog(logFileName, true, true);
        }

        mDynLibManager = std::make_unique<DynLibManager>();
        mArchiveManager = std::make_unique<ArchiveManager>();
        mResourceGroupManager = std::make_unique<ResourceGroupManager>();

        // WorkQueue (note: users can replace this if they want)
        DefaultWorkQueue* defaultQ = OGRE_NEW DefaultWorkQueue("Root");
        // match threads to hardware
        int threadCount = OGRE_THREAD_HARDWARE_CONCURRENCY;
        // but clamp it at 2 by default - we dont scale much beyond that currently
        threadCount = Math::Clamp(threadCount, 1, 2);
        defaultQ->setWorkerThreadCount(threadCount);
        mWorkQueue.reset(defaultQ);

注意 OGRE_NEW 与 std::make_unique 混用:前者走自定义分配器,后者走标准库。线程数「匹配硬件但默认钳到 2」的注释直白点出移动端省电的考虑。继续往下,内容管理器按依赖先后进场:

// OgreMain/src/OgreRoot.cpp:Root 构造续(v14.6.3 源码摘录,已删减)
        mMaterialManager = std::make_unique<MaterialManager>();
        mMeshManager = std::make_unique<MeshManager>();
        mSkeletonManager = std::make_unique<SkeletonManager>();
        mParticleManager = std::make_unique<ParticleSystemManager>();
        mTimer = std::make_unique<Timer>();
        mLodStrategyManager = std::make_unique<LodStrategyManager>();

        // instantiate and register base movable factories
        mEntityFactory = std::make_unique<EntityFactory>();
        addMovableObjectFactory(mEntityFactory.get());
        mLightFactory = std::make_unique<LightFactory>();
        addMovableObjectFactory(mLightFactory.get());
        ...

        // Load plugins
        if (!pluginFileName.empty())
            loadPlugins(pluginFileName);

        LogManager::getSingleton().logMessage("*-*-* OGRE Initialising");
        LogManager::getSingleton().logMessage("*-*-* Version " + mVersion);

构造的最后是 loadPlugins(pluginFileName) 与两行启动横幅。也就是说,横幅是构造的收尾,不是启动的起点——引擎在你调 Root 构造时就已经完成了大半初始化。Entity、Light、BillboardSet 这些基础可移动对象工厂在构造期就注册完毕。

为什么是这个顺序

这个顺序不是随意的,背后是依赖关系:

  1. 日志最先:没有它,后面任何一步的报错都无处可看;
  2. 动态库与归档:插件文件是 .so/.dll,靠 DynLibManager 打开;资源在文件系统/zip 里,靠 Archive 抽象;
  3. 资源组:资源加载的命名空间;
  4. 内容管理器:材质/网格/骨架管理器是资源管理器的特化,依赖上面的抽象;
  5. 工厂注册:Entity 等可移动对象需要工厂才能创建;
  6. 插件加载最后:插件可以注册新的渲染后端、新场景管理器,必须等基础设施齐备。

getSingletonPtr() 检查的使用也值得注意:if(!LogManager::getSingletonPtr()) 意味着如果你事先自己建了 LogManager,Root 不会重复建——单例可被外部预置。

源码定位

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

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

下面复现 Singleton<T> 模板与 Root 构造的创建顺序日志。它与 src/02-1-root-singleton.cpp 逐字节一致:

// file: src/02-1-root-singleton.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/02-1-root-singleton.cpp -o bin/02-1-root-singleton && ./bin/02-1-root-singleton
//
// 复现 OgreSingleton.h 的 Singleton<T> 模板与 Root 构造时的管理器创建顺序。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <stdexcept>
#include <string>
#include <vector>

namespace ogre_repro {

// 对应 OgreSingleton.h:getSingleton/getSingletonPtr,单例断言
template <typename T>
class Singleton {
 protected:
  static T* msSingleton;

 public:
  Singleton() {
    // 对应 OgreAssert(!msSingleton, "There can be only one singleton")
    if (msSingleton) throw std::runtime_error("There can be only one singleton");
    msSingleton = static_cast<T*>(this);
  }
  ~Singleton() { msSingleton = 0; }
  static T& getSingleton() {
    if (!msSingleton) throw std::runtime_error("singleton not created");
    return *msSingleton;
  }
  static T* getSingletonPtr() { return msSingleton; }
};

template <typename T>
T* Singleton<T>::msSingleton = 0;

// 对应 OgreRoot 构造时先创建的管理器;创建顺序记录在 log 里
class RootRepro : public Singleton<RootRepro> {
 public:
  std::vector<std::string> order;

  RootRepro() {
    order.push_back("LogManager");       // OgreRoot.cpp 最先创建日志
    order.push_back("DynLibManager");    // 动态库管理器
    order.push_back("ArchiveManager");   // 归档管理器
    order.push_back("ResourceGroupManager");
    order.push_back("SceneManagerEnumerator");
    order.push_back("MaterialManager");
    order.push_back("MeshManager");
    order.push_back("SkeletonManager");
  }
};

}  // namespace ogre_repro

int main() {
  using namespace ogre_repro;

  // 构造前 getSingletonPtr 为空
  CHECK(Singleton<RootRepro>::getSingletonPtr() == nullptr);

  RootRepro root;
  CHECK(RootRepro::getSingletonPtr() == &root);
  CHECK(&RootRepro::getSingleton() == &root);

  // 尝试第二次构造应抛「只能有一个单例」
  bool threw = false;
  try {
    RootRepro second;
  } catch (const std::runtime_error&) {
    threw = true;
  }
  CHECK(threw);

  // 构造顺序:LogManager 在最前
  CHECK(root.order[0] == "LogManager");
  CHECK(root.order.back() == "SkeletonManager");

  std::printf("构造顺序:");
  for (const auto& s : root.order) std::printf("%s ", s.c_str());
  std::printf("\n");

  return lab::report("02-1 Root 单例与构造顺序");
}

本机实测(Apple clang 16,clang++ -std=c++20):编译通过,断言 6/6 通过,打印八步构造顺序。

小结

  • Root 是继承 Singleton<Root> 的引擎单例,第二次构造会被断言拦截。
  • 构造顺序反映依赖:日志 → 动态库 → 归档/资源组 → 内容管理器 → 工厂 → 插件。
  • 单例可被外部预置:if(!LogManager::getSingletonPtr()) 检查避免重复创建。
  • 构造末尾的启动横幅标志初始化完成,真正的渲染要在 initialise 之后。

阅读导航:上一节:1.3 CMake 构建系统与版本宏 · 下一节:2.2 Root 启动:选后端、建场景、跑一帧 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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