《OGRE 3D 渲染引擎原理与架构》7.1 地形组件

Terrain 组件:Terrain 是 SceneManager::Listener 子类,一块一块的方形地形;TerrainGroup 以 (0,0) 为中心格子组织多块地形,packIndex 把格子坐标打包成 uint32 key,convertTerrainSlotToWorldPosition 换算世界坐标;TerrainGlobalOptions 是全局限定单例。lab 复现网格与坐标换算。

7.1 地形组件

从粒子特效(第六章)切换到地面场景:OGRE 的 Terrain 组件(Components/Terrain)提供无限滚动地形的能力。它不是把一张巨大高度图整块渲染,而是切成一块块方形 Terrain,由 TerrainGroup 以网格形式管理;具体哪块加载、哪块卸载交给第八章的 Paging 组件。这一节讲三个骨架:单块地形 Terrain、网格组织 TerrainGroup、全局默认 TerrainGlobalOptions。

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

helio 四卷没有地形组件;cg 三卷讲过高度图采样公式。这里解析真实 OGRE 的 Terrain 组件:网格坐标如何打包成整数 key、格子坐标怎么换算成世界坐标、全局默认值存在哪里。

Terrain:一块方形地形

Terrain 继承 SceneManager::Listener,一个实例就是一块以高度图为底的方形地面:

// Components/Terrain/include/OgreTerrain.h:Terrain 类(v14.6.3 源码摘录,已删减)
    class _OgreTerrainExport Terrain : public SceneManager::Listener
    {
    public:
        friend class TerrainLodManager;

        /** Constructor.
        @param sm The SceneManager to use.
        */
        Terrain(SceneManager* sm);
        virtual ~Terrain();

        static const uint32 TERRAIN_CHUNK_ID;
        static const uint16 TERRAIN_CHUNK_VERSION;
        static const uint16 TERRAIN_MAX_BATCH_SIZE;

        static const uint32 TERRAINLAYERDECLARATION_CHUNK_ID;
        static const uint16 TERRAINLAYERDECLARATION_CHUNK_VERSION;
        static const uint32 TERRAINLAYERSAMPLER_CHUNK_ID;
        static const uint16 TERRAINLAYERSAMPLER_CHUNK_VERSION;
        static const uint32 TERRAINLAYERSAMPLERELEMENT_CHUNK_ID;
        static const uint16 TERRAINLAYERSAMPLERELEMENT_CHUNK_VERSION;
        static const uint32 TERRAINLAYERINSTANCE_CHUNK_ID;
        static const uint16 TERRAINLAYERINSTANCE_CHUNK_VERSION;
        static const uint32 TERRAINDERIVEDDATA_CHUNK_ID;
        static const uint16 TERRAINDERIVEDDATA_CHUNK_VERSION;
        static const uint32 TERRAINGENERALINFO_CHUNK_ID;
        static const uint16 TERRAINGENERALINFO_CHUNK_VERSION;

        static const uint32 LOD_MORPH_CUSTOM_PARAM;

        typedef std::vector<Real> RealVector;

几个要点:

  • 监听 SceneManager:地形需要知道相机的移动(触发 LOD 更新)、渲染顺序等场景事件。
  • 一大串 TERRAIN*_CHUNK_* 常量:地形序列化用「分块」格式,每块有自己的 ID/版本,方便增量升级。
  • TERRAIN_MAX_BATCH_SIZE 与 RealVector:顶点批处理上限和高度数据存储,7.2 会用到。

TerrainGroup:以 (0,0) 为中心格子

单块地形只是一块板。TerrainGroup 把它组织成格子阵列,并且中心格子是 (0,0),支持负坐标:

// Components/Terrain/include/OgreTerrainGroup.h:TerrainGroup 文档(v14.6.3 源码摘录,已删减)
        the grid cells are indexed from 0 as a 'centre' slot, supporting both 
        positive and negative values. so (0,0) is the centre slot, (1,0) is the
        slot to the right of the centre, (1,0) is the slot above the centre, (-2,1) 
        is the slot two to the left of the centre and one up, etc. The maximum
        extent of each axis is -32768 to +32767, so in other words enough for
        over 4 billion entries. That should be enough for anyone!

格子坐标限制在 -32768..32767(int16),因此两个格子坐标能打包进一个 uint32。构造函数带四个参数:

// Components/Terrain/include/OgreTerrainGroup.h:TerrainGroup 构造函数(v14.6.3 源码摘录,已删减)
        TerrainGroup(SceneManager* sm, Terrain::Alignment align, uint16 terrainSize, 
            Real terrainWorldSize);
  • align:地形对齐轴(默认 ALIGN_X_Z,地形 X 轴对应世界 X、地形 Y 轴对应世界 Z)。
  • terrainSize:每块地形一条边的顶点数(2^n+1)。
  • terrainWorldSize:每块地形的世界尺寸(米)。

packIndex:格子坐标打包成 uint32

packIndex 用「int16 → uint16 → 移位合并」把 (x, y) 打包成 key,x 占高 16 位、y 占低 16 位:

// Components/Terrain/src/OgreTerrainGroup.cpp:TerrainGroup::packIndex/unpackIndex(v14.6.3 源码摘录)
    uint32 TerrainGroup::packIndex(long x, long y) const
    {
        // Convert to signed 16-bit so sign bit is in bit 15
        int16 xs16 = static_cast<int16>(x);
        int16 ys16 = static_cast<int16>(y);

        // convert to unsigned because we do not want to propagate sign bit to 32-bits
        uint16 x16 = static_cast<uint16>(xs16);
        uint16 y16 = static_cast<uint16>(ys16);

        uint32 key = 0;
        key = (x16 << 16) | y16;

        return key;
    }
    //---------------------------------------------------------------------
    void TerrainGroup::unpackIndex(uint32 key, long *x, long *y)
    {
        // inverse of packIndex
        // unsigned versions
        uint16 y16 = static_cast<uint16>(key & 0xFFFF);
        uint16 x16 = static_cast<uint16>((key >> 16) & 0xFFFF);

注释点明两个技巧:

  1. 先转 int16(把符号放到 bit 15),再转 uint16——避免 x << 16 时符号位扩散到 32 位。
  2. 解包时先取无符号 16 位,再转回 int16 还原符号。

TerrainGroup 内部用 std::map<uint32, TerrainSlot*> 存格子,getTerrainSlot 先 packIndex(x, y) 查表。

格子坐标 → 世界坐标

convertTerrainSlotToWorldPosition 把格子坐标换算成世界坐标:先按 mTerrainWorldSize 缩放得到地形轴位置,再做对齐轴转换,最后平移 mOrigin:

// Components/Terrain/src/OgreTerrainGroup.cpp:TerrainGroup::convertTerrainSlotToWorldPosition(v14.6.3 源码摘录)
    void TerrainGroup::convertTerrainSlotToWorldPosition(long x, long y, Vector3* pos) const
    {
        Vector3 terrainPos(x * mTerrainWorldSize, y * mTerrainWorldSize, 0);

        Terrain::convertTerrainToWorldAxes(mAlignment, terrainPos, pos);
        *pos += mOrigin;


    }

ALIGN_X_Z 下「地形 X → 世界 X、地形 Y → 世界 Z、高度 → 世界 Y」,所以 slot (x, y) 的中心在世界 (x·size, 0, y·size) + mOrigin。getTerrainSlotPosition(x, y) 就是它的封装。

TerrainGlobalOptions:全局默认值的单例

很多地形参数(裙边尺寸、阴影光照方向、合成图距离)都有默认值,且逐块设置太繁琐。OGRE 用全局限定单例集中管理——注意它不是独立文件,而是直接写在 OgreTerrain.h 里:

// Components/Terrain/include/OgreTerrain.h:TerrainGlobalOptions(v14.6.3 源码摘录,已删减)
    class _OgreTerrainExport TerrainGlobalOptions : public TerrainAlloc, public Singleton<TerrainGlobalOptions>
    {
    protected:

        Real mSkirtSize;
        Vector3 mLightMapDir;
        bool mCastsShadows;
        Real mMaxPixelError;
        uint8 mRenderQueueGroup;
        uint32 mVisibilityFlags;
        uint32 mQueryFlags;
        bool mUseRayBoxDistanceCalculation;
        TerrainMaterialGeneratorPtr mDefaultMaterialGenerator;
        uint16 mLayerBlendMapSize;
        Real mDefaultLayerTextureWorldSize;
        uint16 mDefaultGlobalColourMapSize;
        uint16 mLightmapSize;
        uint16 mCompositeMapSize;
        ColourValue mCompositeMapAmbient;
        ColourValue mCompositeMapDiffuse;
        Real mCompositeMapDistance;
        String mResourceGroup;
        bool mUseVertexCompressionWhenAvailable;

构造函数的默认值(v14.6.3 实测):

字段默认值
mSkirtSize30(隐藏地形裂缝的「裙边」宽度)
mLightMapDirVector3(1,-1,0).normalisedCopy()
mCastsShadowsfalse
mMaxPixelError3.0
mLayerBlendMapSize1024
mCompositeMapDistance4000
mCompositeMapAmbient/DiffuseColourValue::White

文档明确要求「每应用只构造一个实例,且早于任何其他地形类的工作」。这也是 7.3 材质生成器 TerrainMaterialGeneratorA 的挂靠点。

源码定位

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

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

下面用纯 C++ 复现地形网格与坐标换算。它与 src/07-1-terrain-component.cpp 逐字节一致:

// file: src/07-1-terrain-component.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/07-1-terrain-component.cpp -o bin/07-1-terrain-component && ./bin/07-1-terrain-component
//
// 复现 Terrain 组件与 TerrainGroup 网格(对应 OgreTerrain.h 262- 的 Terrain 类、
//   OgreTerrain.h 1835- 的 TerrainGlobalOptions、OgreTerrainGroup.h 的 TerrainGroup、
//   OgreTerrainGroup.cpp 798- 的 packIndex/unpackIndex、680- 的 convertTerrainSlotToWorldPosition):
//   Terrain 是 SceneManager::Listener 子类,一个实例代表一块方形地形;
//   TerrainGroup 以 (0,0) 为中心格子管理多块地形,格子坐标经 int16->uint16->(x16<<16)|y16
//     打包成 uint32 key,unpackIndex 逆向解包(含符号恢复);
//   convertTerrainSlotToWorldPosition 把格子坐标换算成世界坐标:ALIGN_X_Z 下格子 x 映射世界 x、
//     格子 y 映射世界 z,再平移 mOrigin;
//   getTerrainPosition 把世界坐标折算成 [0,1] 地形空间;
//   TerrainGlobalOptions 是全局限定单例,携带 skirt/光照方向等默认值。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <cmath>
#include <cstdint>

namespace ogre_repro {

struct Vec3 {
  float x, y, z;
  float length() const { return std::sqrt(x * x + y * y + z * z); }
};

using Real = float;  // OGRE 的 Real 别名

// 对应 TerrainGroup::packIndex(OgreTerrainGroup.cpp 798-)
uint32_t packIndex(long x, long y) {
  int16_t xs16 = static_cast<int16_t>(x);
  int16_t ys16 = static_cast<int16_t>(y);
  uint16_t x16 = static_cast<uint16_t>(xs16);
  uint16_t y16 = static_cast<uint16_t>(ys16);
  return (static_cast<uint32_t>(x16) << 16) | y16;
}

// 对应 TerrainGroup::unpackIndex(OgreTerrainGroup.cpp 814-)
void unpackIndex(uint32_t key, long* x, long* y) {
  uint16_t y16 = static_cast<uint16_t>(key & 0xFFFF);
  uint16_t x16 = static_cast<uint16_t>((key >> 16) & 0xFFFF);
  *x = static_cast<int16_t>(x16);  // 还原符号位
  *y = static_cast<int16_t>(y16);
}

// 对应 TerrainGlobalOptions(OgreTerrain.h 1835-,全局单例默认值)
class TerrainGlobalOptions {
 public:
  static TerrainGlobalOptions& get() {
    static TerrainGlobalOptions g;
    return g;
  }
  float getSkirtSize() const { return mSkirtSize; }
  Vec3 getLightMapDirection() const { return mLightMapDir; }
  void setLightMapDirection(const Vec3& v) { mLightMapDir = v; }
  uint16_t getLayerBlendMapSize() const { return mLayerBlendMapSize; }
  Real getCompositeMapDistance() const { return mCompositeMapDistance; }

 private:
  TerrainGlobalOptions()
      : mSkirtSize(30),
        mLightMapDir(Vec3{1 / std::sqrt(2.0f), -1 / std::sqrt(2.0f), 0}),  // (1,-1,0) 归一化
        mLayerBlendMapSize(1024),
        mCompositeMapDistance(4000) {}
  float mSkirtSize;
  Vec3 mLightMapDir;
  uint16_t mLayerBlendMapSize;
  Real mCompositeMapDistance;
};

// 对应 TerrainGroup(OgreTerrainGroup.h 66-):以 (0,0) 为中心格子的地形网格
class TerrainGroup {
 public:
  TerrainGroup(float worldSize, const Vec3& origin)
      : mTerrainWorldSize(worldSize), mOrigin(origin) {}

  uint32_t pack(long x, long y) const { return ogre_repro::packIndex(x, y); }

  // 对应 convertTerrainSlotToWorldPosition(680-),ALIGN_X_Z:格子 y -> 世界 z
  Vec3 slotPosition(long x, long y) const {
    Vec3 terrainPos{x * mTerrainWorldSize, y * mTerrainWorldSize, 0};
    return Vec3{terrainPos.x + mOrigin.x, terrainPos.z + mOrigin.y,
                terrainPos.y + mOrigin.z};
  }

  // 对应 getTerrainPosition(OgreTerrain.h 912-):世界坐标 -> [0,1] 地形空间
  void terrainPosition(const Vec3& world, Vec3* out) const {
    out->x = (world.x - mOrigin.x) / mTerrainWorldSize;
    out->y = (world.z - mOrigin.z) / mTerrainWorldSize;
    out->z = world.y;  // 绝对高度
  }

  float mTerrainWorldSize;
  Vec3 mOrigin;
};

}  // namespace ogre_repro

int main() {
  using namespace ogre_repro;

  // packIndex:int16 网格坐标 -> uint32 key(x 高 16 位,y 低 16 位)
  CHECK_EQ(packIndex(0, 0), 0u);
  CHECK_EQ(packIndex(0, 1), 1u);
  CHECK_EQ(packIndex(1, 0), 0x10000u);
  CHECK_EQ(packIndex(-1, 0), 0xFFFF0000u);   // 符号位留在高 16 位

  // unpackIndex 往返,符号正确还原
  long x = 0, y = 0;
  unpackIndex(packIndex(3, -2), &x, &y);
  CHECK_EQ(x, 3l);
  CHECK_EQ(y, -2l);
  unpackIndex(packIndex(-5, 7), &x, &y);
  CHECK_EQ(x, -5l);
  CHECK_EQ(y, 7l);

  // 格子坐标 -> 世界坐标:slot (x,y) 中心在 (x*size, 0, y*size)
  TerrainGroup grid(100.0f, Vec3{0, 0, 0});
  Vec3 p = grid.slotPosition(2, 3);
  CHECK_EQ(p.x, 200.0f);
  CHECK_EQ(p.z, 300.0f);
  CHECK_EQ(p.y, 0.0f);

  TerrainGroup grid2(100.0f, Vec3{10, 20, 0});  // origin 是世界坐标,y 分量是高度
  p = grid2.slotPosition(1, -1);
  CHECK_EQ(p.x, 110.0f);    // 1*100 + 10
  CHECK_EQ(p.y, 20.0f);     // 高度取 mOrigin.y
  CHECK_EQ(p.z, -100.0f);   // -1*100 + 0

  // 世界坐标 -> [0,1] 地形空间
  Vec3 ts;
  grid.terrainPosition(Vec3{25, 0, 75}, &ts);
  CHECK_EQ(ts.x, 0.25f);
  CHECK_EQ(ts.y, 0.75f);
  grid2.terrainPosition(Vec3{110, 0, -80}, &ts);
  CHECK_EQ(ts.x, 1.0f);
  CHECK_EQ(ts.y, -0.8f);    // (-80 - 0)/100

  // TerrainGlobalOptions 默认值
  TerrainGlobalOptions& opt = TerrainGlobalOptions::get();
  CHECK_EQ(opt.getSkirtSize(), 30.0f);
  CHECK_EQ(opt.getLayerBlendMapSize(), 1024u);
  CHECK_EQ(opt.getCompositeMapDistance(), 4000.0f);
  Vec3 dir = opt.getLightMapDirection();
  CHECK(std::fabs(dir.length() - 1.0f) < 1e-4f);  // (1,-1,0) 已归一化

  // 全局单例可修改并影响后续查询
  opt.setLightMapDirection(Vec3{0, 1, 0});
  CHECK_EQ(TerrainGlobalOptions::get().getLightMapDirection().y, 1.0f);

  return lab::report("07-1 地形组件");
}

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

小结

  • Terrain 继承 SceneManager::Listener,一个实例一块方形地形,用 TERRAIN*_CHUNK_* 分块序列化。
  • TerrainGroup 以 (0,0) 为中心格子管理多块地形,格子坐标限 -32768..32767。
  • packIndex 用 int16 → uint16 → (x16<<16)|y16 打包成 uint32 key,unpackIndex 逆向还原符号。
  • convertTerrainSlotToWorldPosition 把格子坐标换算成世界坐标(缩放 + 对齐轴转换 + 平移 origin)。
  • TerrainGlobalOptions 是全局限定单例,集中管理裙边尺寸、光照方向等默认值。

阅读导航:上一节:6.3 影响器 · 下一节:7.2 高度图与 LOD 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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