《OGRE 3D 渲染引擎原理与架构》5.1 实例管理器

实例管理器解决大量重复网格的高效渲染:InstancingTechnique 四档决定每实例数据走常数还是顶点缓冲,InstanceBatch 预分配编号实体池,createInstancedEntity 从空闲池尾取、满批自动建新批,isBatchFull/isBatchUnused 是池判据。lab 复现池管理与自动建批。

5.1 实例管理器

一棵森林有几千棵树,每棵都用同一网格、同一材质,但位置各不相同。如果每棵树都当作独立 Entity 提交渲染,顶点着色器的负担是几千倍的浪费。OGRE 的答案是实例化(instancing):一份顶点数据提交一次,每实例只带极小的变化数据(通常是 4x3 变换矩阵)。InstanceManager 就是管理「实例」的入口——它按材质把实例分成一批批 InstanceBatch,负责创建、回收、自动扩容。

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

卷二讲过 Entity/SubEntity 的单体渲染路径(一份几何 + 一个变换);本节介绍的是「大量重复几何」的批量路径。第 5 章三节构成一条完整链路:5.1 讲管理器的池与批次划分,5.2 讲批次内部怎么组织顶点数据(HW 克隆 vs Shader 共享),5.3 讲静态几何——一种「连每帧更新都省掉」的更静态方案。

InstancingTechnique:四种实例化路线

InstanceManager 构造时就要选定一种 InstancingTechnique,它决定实例数据怎么送到 GPU:

// OgreMain/include/OgreInstanceManager.h:InstancingTechnique(v14.6.3 源码摘录,已删减)
        enum InstancingTechnique
        {
            ShaderBased,            ///< %Any SM 2.0+ @ref InstanceBatchShader
            TextureVTF,             ///< Needs Vertex Texture Fetch & SM 3.0+ @ref InstanceBatchVTF
            HWInstancingBasic,      ///< Needs SM 3.0+ and HW instancing support @ref InstanceBatchHW
            HWInstancingVTF,        ///< Needs SM 3.0+, HW instancing support & VTF @ref InstanceBatchHW_VTF
            InstancingTechniquesCount
        };

四种技术的硬件门槛和策略各不相同:

技术硬件要求实例数据怎么传
ShaderBasedSM 2.0+走着色器常数寄存器,兼容面最广
TextureVTFSM 3.0+ 且支持顶点纹理读取把实例矩阵存进纹理,顶点着色器采样
HWInstancingBasicSM 3.0+ 且支持硬件实例化克隆顶点缓冲,每实例 3 个 TEXCOORD 装矩阵
HWInstancingVTFSM 3.0+ 硬件实例化 + VTF结合两者

技术选择影响的是 5.2 节要讲的 InstanceBatch 子类——ShaderBased 对应 InstanceBatchShader,HWInstancingBasic 对应 InstanceBatchHW。管理器构造时按技术类型创建对应子类。

内部结构:按材质组织批次

InstanceManager 的内部容器和注释把核心策略讲得很清楚:

// OgreMain/include/OgreInstanceManager.h:内部容器(v14.6.3 源码摘录,已删减)
        typedef std::vector<InstanceBatch*>        InstanceBatchVec;   //vec[batchN] = Batch
        typedef std::map<String, InstanceBatchVec> InstanceBatchMap;   //map[materialName] = Vec

        typedef std::map<String, BatchSettings>    BatchSettingsMap;

        const String            mName;                  //Not the name of the mesh
        MeshPtr                 mMeshReference;
        InstanceBatchMap        mInstanceBatches;
        size_t                  mIdCount;

        InstanceBatchVec        mDirtyBatches;

        RenderOperation         mSharedRenderOperation;

        size_t                  mInstancesPerBatch;
        InstancingTechnique     mInstancingTechnique;

两层容器:mInstanceBatches 是 map<材质名, 批次数组>——批次是按材质划分的,因为同一批内所有实例共享纹理与材质。每个 InstanceBatch 有自己的 mInstancesPerBatch(该批最大实例数)。mSharedRenderOperation 是共享的渲染操作——buildNewBatch 第一次构建后,后续批次复用它的渲染装配,避免重复构建顶点/索引缓冲。

批次划分逻辑在两个私有方法里,注释把语义讲透:

// OgreMain/include/OgreInstanceManager.h:getFreeBatch / buildNewBatch(v14.6.3 源码摘录,已删减)
        /** Finds a batch with at least one free instanced entity we can use.
            If none found, creates one.
        */
        inline InstanceBatch* getFreeBatch( const String &materialName );

        /** Called when batches are fully exhausted (can't return more instances) so a new batch
            is created.
            For the first time use, it can take big build time.
            It takes care of getting the render operation which will be shared by further batches,
            which decreases their build time, and prevents GPU RAM from skyrocketing.
        @param materialName The material name, to know where to put this batch in the map
        @param firstTime True if this is the first time it is called
        @return The created InstancedManager for convenience
        */
        InstanceBatch* buildNewBatch( const String &materialName, bool firstTime );

getFreeBatch 回答「这个材质有没有不满的批」,没有就调 buildNewBatch 新建。buildNewBatch 的注释特别强调首次调用的成本:第一次构建要搭完整的 RenderOperation,耗时较长,但后续批次共享这份装配,既省构建时间又防止 GPU 显存暴涨。

InstanceBatch:预分配实体池

批次内部怎么管理实例?InstanceBatch 的类文档先交代了共享约束:

// OgreMain/include/OgreInstanceBatch.h:类文档(v14.6.3 源码摘录,已删减)
        <b>As it happens with instancing in general, all instanced entities from the same batch will share
        the same textures and materials</b>
    @par
        Each InstanceBatch preallocates a fixed amount of mInstancesPerBatch instances once it's been
        built (@ref build, @ref buildFrom).
        @ref createInstancedEntity and @ref removeInstancedEntity on how to retrieve those instances
        remove them from scene.

两句关键约束:同一批的实例共享纹理和材质(所以批次按材质划分);批次在 build 时一次性预分配 mInstancesPerBatch 个实例。池的具体实现是两条 vector:

// OgreMain/include/OgreInstanceBatch.h:mInstancedEntities / mUnusedEntities(v14.6.3 源码摘录,已删减)
        //InstancedEntities are all allocated at build time and kept as "unused"
        //when they're requested, they're removed from there when requested,
        //and put back again when they're no longer needed
        //Note each InstancedEntity has a unique ID ranging from [0; mInstancesPerBatch)
        InstancedEntityVec  mInstancedEntities;
        InstancedEntityVec  mUnusedEntities;

注释给出池设计的三条规则:实体在 build 时全部分配并标记为「unused」;被请求时从 mUnusedEntities 移除;不再需要时放回。关键细节在最后一句——每个 InstancedEntity 的 ID 范围是 [0; mInstancesPerBatch),即批内的 ID 是固定的,复用只是「槽位回归空闲」。

池满没满用两个内联查询:

// OgreMain/include/OgreInstanceBatch.h:isBatchFull / isBatchUnused(v14.6.3 源码摘录,已删减)
        /** @return true if it can not create more InstancedEntities
            (Num InstancedEntities == mInstancesPerBatch)
        */
        bool isBatchFull(void) const { return mUnusedEntities.empty(); }

        /** Returns true if it no instanced entity has been requested or all of them have been removed
        */
        bool isBatchUnused(void) const { return mUnusedEntities.size() == mInstancedEntities.size(); }

isBatchFull 看空闲池是否空(所有名额都被占用);isBatchUnused 看空闲池是否等于总数(没有任何在用实例)。这两个判据是 InstanceManager 决定「复用旧批」还是「新建批」的基础。

池的初始化与 LIFO 弹出

实体池在批次构建时填充。createAllInstancedEntities 用连续编号生成全部实体:

// OgreMain/src/OgreInstanceBatch.cpp:createAllInstancedEntities(v14.6.3 源码摘录,已删减)
    void InstanceBatch::createAllInstancedEntities()
    {
        mInstancedEntities.reserve( mInstancesPerBatch );
        mUnusedEntities.reserve( mInstancesPerBatch );

        for( size_t i=0; i<mInstancesPerBatch; ++i )
        {
            InstancedEntity *instance = generateInstancedEntity(i);
            mInstancedEntities.push_back( instance );
            mUnusedEntities.push_back( instance );
        }
    }
    //-----------------------------------------------------------------------
    InstancedEntity* InstanceBatch::generateInstancedEntity(size_t num)
    {
        return OGRE_NEW InstancedEntity(this, static_cast<uint32>(num));
    }

每个实体的 mId 就是循环变量 i(0 到 mInstancesPerBatch-1)。mInstancedEntities 和 mUnusedEntities 以相同顺序装同一批指针——池是「预分配全集」+「空闲子集」的经典双向量布局。

createInstancedEntity 从空闲池尾部弹出:

// OgreMain/src/OgreInstanceBatch.cpp:createInstancedEntity(v14.6.3 源码摘录,已删减)
    InstancedEntity* InstanceBatch::createInstancedEntity()
    {
        InstancedEntity *retVal = 0;

        if( !mUnusedEntities.empty() )
        {
            retVal = mUnusedEntities.back();
            mUnusedEntities.pop_back();

            retVal->setInUse(true);
        }

        return retVal;
    }

注意 LIFO 语义:从 back() 弹出意味着先弹出编号最大的实体——第一次创建拿到 mInstancesPerBatch-1 号,最后一次创建才拿到 0 号。setInUse(true) 标记在用;removeInstancedEntity 对称地 setInUse(false) 后 push_back 回空闲池。加上 InstanceManager::createInstancedEntity(materialName) 入口,创建流程就是「getFreeBatch 找不满的批 → 批内弹出实体 → 全满则 buildNewBatch 新建批」。

源码定位

  • OgreMain/include/OgreInstanceManager.h :InstancingTechnique(69-76)、InstanceBatchMap(102-103)、getFreeBatch(127-130)、buildNewBatch(132-141)、createInstancedEntity(227-228)
  • OgreMain/include/OgreInstanceBatch.h :类文档(69-79)、mInstancedEntities/mUnusedEntities(102-107)、isBatchFull(242)、isBatchUnused(246)
  • OgreMain/src/OgreInstanceBatch.cpp :createAllInstancedEntities(174-185)、generateInstancedEntity(187-190)、createInstancedEntity(243-256)、removeInstancedEntity(258-272)

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

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

下面用纯 C++ 复现实例管理器:InstanceBatch 的预分配池、LIFO 弹出与回收、InstanceManager 按材质管理多批并自动建新批。它与 src/ogre-ext-05-1-instance-manager.cpp 逐字节一致:

// file: src/ogre-ext-05-1-instance-manager.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/ogre-ext-05-1-instance-manager.cpp -o bin/ogre-ext-05-1-instance-manager && ./bin/ogre-ext-05-1-instance-manager
//
// 复现实例管理器(对应 OgreMain/include/OgreInstanceManager.h 69-76 的
//   InstancingTechnique、127-141 的 getFreeBatch/buildNewBatch、228 的
//   createInstancedEntity,与 OgreInstanceBatch.h 88-115 的 mInstancedEntities/
//   mUnusedEntities 预分配池):每批预分配固定名额,createInstancedEntity 从
//   空闲池尾部取、满批自动建新批,移除后放回池。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <cstdint>
#include <map>
#include <string>
#include <vector>

namespace ogre_repro {

// 对应 OgreInstanceBatch.h 88/105-107 的 InstancedEntityVec 元素
class InstancedEntity {
 public:
  InstancedEntity(std::size_t id, const std::string& material)
      : mId(id), mMaterial(material) {}
  std::size_t mId;
  std::string mMaterial;
  bool mInUse = false;
};

// 对应 OgreInstanceBatch.h:一批实例,空闲池与在用池分离
class InstanceBatch {
 public:
  InstanceBatch(const std::string& material, std::size_t instancesPerBatch)
      : mMaterial(material), mInstancesPerBatch(instancesPerBatch) {
    for (std::size_t i = 0; i < instancesPerBatch; ++i) {
      InstancedEntity* e = new InstancedEntity(i, material);
      mInstancedEntities.push_back(e);
      mUnusedEntities.push_back(e);
    }
  }
  ~InstanceBatch() {
    for (auto e : mInstancedEntities) delete e;
  }

  // 对应 OgreInstanceBatch.h 305-313:从空闲池尾部取
  InstancedEntity* createInstancedEntity() {
    if (mUnusedEntities.empty()) return nullptr;
    InstancedEntity* e = mUnusedEntities.back();
    mUnusedEntities.pop_back();
    e->mInUse = true;
    return e;
  }

  void removeInstancedEntity(InstancedEntity* e) {
    e->mInUse = false;
    mUnusedEntities.push_back(e);
  }

  bool isBatchFull() const { return mUnusedEntities.empty(); }
  bool isBatchUnused() const {
    return mUnusedEntities.size() == mInstancedEntities.size();
  }

  std::vector<InstancedEntity*> mInstancedEntities;
  std::vector<InstancedEntity*> mUnusedEntities;
  std::string mMaterial;
  std::size_t mInstancesPerBatch;
};

// 对应 OgreInstanceManager.h:按材质管理多批,自动建新批
class InstanceManager {
 public:
  InstanceManager(const std::string& name, std::size_t instancesPerBatch)
      : mName(name), mInstancesPerBatch(instancesPerBatch) {}

  InstancedEntity* createInstancedEntity(const std::string& materialName) {
    // 对应 InstanceManager::getFreeBatch:优先复用未满的批
    InstanceBatch* batch = getFreeBatch(materialName);
    InstancedEntity* e = batch->createInstancedEntity();
    if (!e) {
      // 兜底:刚建好的批也应不满,此分支只在并发竞争下触发
      batch = buildNewBatch(materialName);
      e = batch->createInstancedEntity();
    }
    return e;
  }

  void removeInstancedEntity(const std::string& materialName, InstancedEntity* e) {
    // 简化:按材质找到所在批放回(真实实现按 mId 直接定位)
    for (auto b : mBatches[materialName])
      for (auto ent : b->mInstancedEntities)
        if (ent == e) {
          b->removeInstancedEntity(e);
          return;
        }
  }

  std::size_t totalInstances(const std::string& materialName) const {
    auto it = mBatches.find(materialName);
    if (it == mBatches.end()) return 0;
    std::size_t n = 0;
    for (auto b : it->second) n += b->mInstancedEntities.size();
    return n;
  }

  std::string mName;
  std::size_t mInstancesPerBatch;
  std::map<std::string, std::vector<InstanceBatch*>> mBatches;

 private:
  InstanceBatch* getFreeBatch(const std::string& materialName) {
    auto it = mBatches.find(materialName);
    if (it == mBatches.end() || it->second.empty())
      return buildNewBatch(materialName);
    for (auto b : it->second)
      if (!b->isBatchFull()) return b;
    return buildNewBatch(materialName);
  }
  InstanceBatch* buildNewBatch(const std::string& materialName) {
    InstanceBatch* b = new InstanceBatch(materialName, mInstancesPerBatch);
    mBatches[materialName].push_back(b);
    return b;
  }
};

}  // namespace ogre_repro

int main() {
  using namespace ogre_repro;

  InstanceManager mgr("Forest", 2);  // 每批 2 个实例

  // 创建第一批:编号 [0; mInstancesPerBatch),但空闲池是 LIFO,
  // 先弹出编号更大的(对应 OgreInstanceBatch.cpp 179-190 与 243-256)
  InstancedEntity* a = mgr.createInstancedEntity("Tree");
  CHECK(a != nullptr);
  CHECK_EQ(a->mId, size_t(1));
  CHECK(a->mInUse);
  CHECK_EQ(mgr.mBatches.size(), size_t(1));
  CHECK_EQ(mgr.mBatches["Tree"].size(), size_t(1));
  CHECK(!mgr.mBatches["Tree"][0]->isBatchFull());  // 只用 1 个名额

  InstancedEntity* b = mgr.createInstancedEntity("Tree");
  CHECK_EQ(b->mId, size_t(0));
  CHECK(mgr.mBatches["Tree"][0]->isBatchFull());  // 2/2 用满

  // 第三个实例:满批 → 自动建第二批(编号各自从 0 重新开始)
  InstancedEntity* c = mgr.createInstancedEntity("Tree");
  CHECK(c != nullptr);
  CHECK_EQ(c->mId, size_t(1));
  CHECK_EQ(mgr.mBatches["Tree"].size(), size_t(2));
  CHECK_EQ(mgr.totalInstances("Tree"), size_t(4));

  // 移除 b:回收到第一批的空闲池
  mgr.removeInstancedEntity("Tree", b);
  CHECK(!b->mInUse);
  CHECK(!mgr.mBatches["Tree"][0]->isBatchFull());

  // 再次创建:复用刚回收的槽位(b 放回空闲池尾部,被原样弹出)
  InstancedEntity* d = mgr.createInstancedEntity("Tree");
  CHECK(d == b);
  CHECK_EQ(d->mId, size_t(0));
  CHECK(mgr.mBatches["Tree"][0]->isBatchFull());

  // 全部移除 → isBatchUnused
  mgr.removeInstancedEntity("Tree", a);
  mgr.removeInstancedEntity("Tree", c);
  mgr.removeInstancedEntity("Tree", d);
  CHECK(mgr.mBatches["Tree"][0]->isBatchUnused());

  // 不同材质各自维护批次
  InstancedEntity* rock = mgr.createInstancedEntity("Rock");
  CHECK(rock != nullptr);
  CHECK_EQ(mgr.mBatches.size(), size_t(2));

  return lab::report("5.1 实例管理器");
}

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

小结

  • InstancingTechnique 四档决定实例数据走常数、纹理还是硬件实例化,对应不同 InstanceBatch 子类。
  • 批次按材质划分:InstanceBatchMap 是 map<材质名, 批次数组>,同一批实例共享纹理与材质。
  • 批次 build 时预分配 [0; mInstancesPerBatch) 编号的实体池,空闲池与在用池双向量。
  • createInstancedEntity 从空闲池尾弹出(LIFO),removeInstancedEntity 放回尾部。
  • isBatchFull/isBatchUnused 是管理器判据:满则 buildNewBatch,空则复用。

阅读导航:上一节:4.3 脚本词法与语法树 · 下一节:5.2 实例批 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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