《OGRE 3D 渲染引擎原理与架构》8.2 分页策略

分页策略决定「哪页该加载」:Grid2DPageStrategy 把世界坐标折成网格、按 cellSize 定位所在格、用 packIndex 生成 PageID;notifyCamera 以相机格为圆心扫出 load 内圈与 hold 外圈,内圈 loadPage、外圈 holdPage、之外卸载。lab 复现定位与环形判定。

8.2 分页策略

8.1 的分区只提供了一个 PageMap 容器,真正决定「相机在哪、哪些页该加载」的是 PageStrategy。默认策略是 Grid2DPageStrategy:把世界切成二维格子,页 ID 就是格子坐标打包成的整数,相机每帧扫一圈「加载环」和「保持环」。

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

helio 四卷没有分页策略;webarch 卷讲过环形缓存思路。这里解析真实 OGRE 的 Grid2DPageStrategyData:世界→网格折换、格子定位、页 ID 打包,以及 notifyCamera 的 load/hold 双环扫描。

世界坐标 → 网格坐标

世界是三维的,网格是二维的。Grid2DPageStrategyData 用 mMode 决定哪两个世界轴映射成网格轴,默认 G2D_X_Z——注意 z 轴取负,因为世界 z 与网格 y 方向相反:

// Components/Paging/src/OgreGrid2DPageStrategy.cpp:Grid2DPageStrategyData::convertWorldToGridSpace(v14.6.3 源码摘录)
    void Grid2DPageStrategyData::convertWorldToGridSpace(const Vector3& world, Vector2& grid)
    {
        switch(mMode)
        {
        case G2D_X_Z:
            grid.x = world.x;
            grid.y = -world.z;
            break;
        case G2D_X_Y:
            grid.x = world.x;
            grid.y = world.y;
            break;
        case G2D_Y_Z:
            grid.x = -world.z;
            grid.y = world.y;
            break;
        }
    }

网格坐标 → 格子位置

determineGridLocation 把连续网格坐标折算成格子整数坐标。关键在 offset = cellSize * 0.5:格子以 mOrigin 为中心对齐,所以先平移到格子中心系再除 cellSize 向下取整:

// Components/Paging/src/OgreGrid2DPageStrategy.cpp:Grid2DPageStrategyData::determineGridLocation(v14.6.3 源码摘录)
    void Grid2DPageStrategyData::determineGridLocation(const Vector2& gridpos, int32 *x, int32 *y)
    {
        Vector2 relPos = gridpos - mOrigin;
        Real offset = mCellSize * 0.5f;
        relPos.x += offset;
        relPos.y += offset;

        *x = static_cast<int32>(std::floor(relPos.x / mCellSize));
        *y = static_cast<int32>(std::floor(relPos.y / mCellSize));

    }

默认尺寸参数(构造函数,v14.6.3 实测):

参数默认值
mCellSize1000
mLoadRadius2000(→ 2 格)
mHoldRadius3000(→ 3 格)

updateDerivedMetrics 把世界单位半径折算成格子数:mLoadRadiusInCells = mLoadRadius / mCellSize。修改 setCellSize/setLoadRadius/setHoldRadius 都会重算。

calculatePageID:格子坐标 → 页 ID

页 ID 的打包与 7.1 的 TerrainGroup::packIndex 完全一致——int16 符号位、uint16 移位合并、高 16 位存 x:

// Components/Paging/src/OgreGrid2DPageStrategy.cpp:Grid2DPageStrategyData::calculatePageID(v14.6.3 源码摘录)
    PageID Grid2DPageStrategyData::calculatePageID(int32 x, int32 y)
    {
        // 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;

这样 PageID 支持 -32768..32767 的格子坐标,正负格子都能唯一编码。

notifyCamera:load 内圈 + hold 外圈

notifyCamera 每帧被调用:先把相机位置折算成格子,再以相机格为中心扫矩形环——内圈 loadRadius 请求加载,外圈 holdRadius 只保持不主动加载,环外的页「由推断被标记卸载」:

// Components/Paging/src/OgreGrid2DPageStrategy.cpp:Grid2DPageStrategy::notifyCamera(v14.6.3 源码摘录,已删减)
    void Grid2DPageStrategy::notifyCamera(Camera* cam, PagedWorldSection* section)
    {
        Grid2DPageStrategyData* stratData = static_cast<Grid2DPageStrategyData*>(section->getStrategyData());

        const Vector3& pos = cam->getDerivedPosition();
        Vector2 gridpos;
        stratData->convertWorldToGridSpace(pos, gridpos);
        int32 x, y;
        stratData->determineGridLocation(gridpos, &x, &y);

        Real loadRadius = stratData->getLoadRadiusInCells();
        Real holdRadius = stratData->getHoldRadiusInCells();
        // scan the whole Hold range
        Real fxmin = (Real)x - holdRadius;
        Real fxmax = (Real)x + holdRadius;
        Real fymin = (Real)y - holdRadius;
        Real fymax = (Real)y + holdRadius;

        int32 xmin = stratData->getCellRangeMinX();
        int32 xmax = stratData->getCellRangeMaxX();
        int32 ymin = stratData->getCellRangeMinY();
        int32 ymax = stratData->getCellRangeMaxY();

        // Round UP max, round DOWN min
        xmin = fxmin < xmin ? xmin : (int32)floor(fxmin);
        xmax = fxmax > xmax ? xmax : (int32)ceil(fxmax);
        ymin = fymin < ymin ? ymin : (int32)floor(fymin);
        ymax = fymax > ymax ? ymax : (int32)ceil(fymax);
        // the inner, active load range
        fxmin = (Real)x - loadRadius;
        fxmax = (Real)x + loadRadius;
        fymin = (Real)y - loadRadius;
        fymax = (Real)y + loadRadius;
        // Round UP max, round DOWN min
        int32 loadxmin = fxmin < xmin ? xmin : (int32)floor(fxmin);
        int32 loadxmax = fxmax > xmax ? xmax : (int32)ceil(fxmax);
        int32 loadymin = fymin < ymin ? ymin : (int32)floor(fymin);
        int32 loadymax = fymax > ymax ? ymax : (int32)ceil(fymax);

        for (int32 cy = ymin; cy <= ymax; ++cy)
        {
            for (int32 cx = xmin; cx <= xmax; ++cx)
            {
                PageID pageID = stratData->calculatePageID(cx, cy);
                if (cx >= loadxmin && cx <= loadxmax && cy >= loadymin && cy <= loadymax)
                {
                    // in the 'load' range, request it
                    section->loadPage(pageID);
                }
                else
                {
                    // in the outer 'hold' range, keep it but don't actively load
                    section->holdPage(pageID);
                }
                // other pages will by inference be marked for unloading
            }

三个关键设计:

  1. 双环:load 内圈主动加载,hold 外圈只保持——这样玩家快速回头时外圈的页还在,避免反复加载。
  2. ceil/floor 取整:环边界是实数,扫描范围向下/向上取整,保证覆盖完整格子。
  3. 卸载靠推断:不在任何环内的页,loadPage/holdPage 都没被调用,它们的 frameLastHeld 老化后自然成为卸载候选(8.1 讲过)。

进入加载圈和停留在保留圈

策略根据相机坐标映射页号,并用加载与保留范围区分新页和已有页。相机在两个阈值之间移动时,保留区域能减少页的反复开关。页内容交接见卷四 10.3。

按连续位置记录页号、load、hold 和卸载结果。原生 Paging 探针验证通用 Page 的提交分支,地形专用节流和实际相机页格轨迹要分别观察。

加载圈与保留圈的状态

flowchart TD
  A["相机映射到分页网格"] --> B{"页处于加载范围?"}
  B -->|"是"| C["请求加载或刷新已有页"]
  B -->|"否"| D{"页已加载且仍在保留范围?"}
  D -->|"是"| E["holdPage 刷新存活标记"]
  D -->|"否"| F["该相机不刷新此页"]
  F --> G{"页已超出持有期限?"}
  G -->|"是"| H["在帧末回收"]
  G -->|"否"| I["等待后续帧"]

分页探针 用通用 Page 验证准备与提交条件。相机移动触发的页号与保留圈,应按本节网格策略单独记录。

源码定位

  • Components/Paging/include/OgreGrid2DPageStrategy.h :G2D_X_Z(50)、Grid2DPageStrategyData(100)、mOrigin(124)、mCellSize(126)、mLoadRadius(128)、mHoldRadius(130)、convertWorldToGridSpace(199)、determineGridLocation(213)、calculatePageID(215)、notifyCamera(235)
  • Components/Paging/src/OgreGrid2DPageStrategy.cpp :构造函数默认值(50-55)、convertWorldToGridSpace(112)、updateDerivedMetrics(153)、determineGridLocation(157)、calculatePageID(200)、notifyCamera(295)

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

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

下面用纯 C++ 复现网格定位与双环判定。它与 src/08-2-page-strategy.cpp 逐字节一致:

// file: src/08-2-page-strategy.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/08-2-page-strategy.cpp -o bin/08-2-page-strategy && ./bin/08-2-page-strategy
//
// 复现 Grid2DPageStrategy 的网格定位与 notifyCamera(对应 OgreGrid2DPageStrategy.cpp
//   112- convertWorldToGridSpace、157- determineGridLocation、200- calculatePageID、
//   295- notifyCamera):
//   convertWorldToGridSpace 在 G2D_X_Z 模式下把世界 (x,y,z) 折成网格 (x, -z);
//   determineGridLocation 把网格坐标相对 mOrigin 平移 cellSize/2 后按 cellSize 取整;
//   calculatePageID 与 TerrainGroup::packIndex 相同的 int16->uint16->(x16<<16)|y16 打包;
//   notifyCamera 以相机所在格为圆心,内圈 loadRadius 请求 loadPage,外圈 holdRadius
//     只 holdPage,之外的页由推断标记卸载。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <cstdint>
#include <cmath>

namespace ogre_repro {

using int32 = std::int32_t;

enum GridMode { G2D_X_Z, G2D_X_Y, G2D_Y_Z };

// 对应 Grid2DPageStrategyData(OgreGrid2DPageStrategy.cpp 108-)
class Grid2DPageStrategyData {
 public:
  Grid2DPageStrategyData() {
    mMode = G2D_X_Z;
    mOriginX = 0.0f;
    mOriginY = 0.0f;
    mCellSize = 1000.0f;
    mLoadRadius = 2000.0f;
    mHoldRadius = 3000.0f;
    updateDerivedMetrics();
  }

  // 对应 convertWorldToGridSpace(112-)
  void convertWorldToGridSpace(float wx, float wy, float wz, float* gx, float* gy) const {
    switch (mMode) {
      case G2D_X_Z:
        *gx = wx;
        *gy = -wz;
        break;
      case G2D_X_Y:
        *gx = wx;
        *gy = wy;
        break;
      default:  // G2D_Y_Z
        *gx = -wz;
        *gy = wy;
        break;
    }
  }

  // 对应 determineGridLocation(157-)
  void determineGridLocation(float gx, float gy, int32* x, int32* y) const {
    float rx = gx - mOriginX;
    float ry = gy - mOriginY;
    float offset = mCellSize * 0.5f;
    rx += offset;
    ry += offset;
    *x = static_cast<int32>(std::floor(rx / mCellSize));
    *y = static_cast<int32>(std::floor(ry / mCellSize));
  }

  // 对应 calculatePageID(200-)
  uint32_t calculatePageID(int32 x, int32 y) const {
    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;
  }

  // 对应 updateDerivedMetrics(153-)
  void updateDerivedMetrics() {
    mLoadRadiusInCells = mLoadRadius / mCellSize;
    mHoldRadiusInCells = mHoldRadius / mCellSize;
  }
  void setCellSize(float sz) {
    mCellSize = sz;
    updateDerivedMetrics();
  }
  void setLoadRadius(float sz) {
    mLoadRadius = sz;
    updateDerivedMetrics();
  }
  void setHoldRadius(float sz) {
    mHoldRadius = sz;
    updateDerivedMetrics();
  }
  float getLoadRadiusInCells() const { return mLoadRadiusInCells; }
  float getHoldRadiusInCells() const { return mHoldRadiusInCells; }

 private:
  GridMode mMode;
  float mOriginX, mOriginY;
  float mCellSize;
  float mLoadRadius, mHoldRadius;
  float mLoadRadiusInCells, mHoldRadiusInCells;
};

// notifyCamera 的判定:LOAD / HOLD / NONE(295- 的扫描环逻辑)
enum Action { LOAD, HOLD, NONE };
Action classifyCell(int32 cx, int32 cy, int32 camX, int32 camY,
                    float loadCells, float holdCells) {
  // 外圈 hold 范围
  float fxmin = float(camX) - holdCells, fxmax = float(camX) + holdCells;
  float fymin = float(camY) - holdCells, fymax = float(camY) + holdCells;
  int32 xmin = static_cast<int32>(std::floor(fxmin));
  int32 xmax = static_cast<int32>(std::ceil(fxmax));
  int32 ymin = static_cast<int32>(std::floor(fymin));
  int32 ymax = static_cast<int32>(std::ceil(fymax));
  if (cx < xmin || cx > xmax || cy < ymin || cy > ymax) return NONE;

  // 内圈 load 范围
  float lxmin = float(camX) - loadCells, lxmax = float(camX) + loadCells;
  float lymin = float(camY) - loadCells, lymax = float(camY) + loadCells;
  int32 loadxmin = static_cast<int32>(std::floor(lxmin));
  int32 loadxmax = static_cast<int32>(std::ceil(lxmax));
  int32 loadymin = static_cast<int32>(std::floor(lymin));
  int32 loadymax = static_cast<int32>(std::ceil(lymax));
  if (cx >= loadxmin && cx <= loadxmax && cy >= loadymin && cy <= loadymax)
    return LOAD;
  return HOLD;
}

}  // namespace ogre_repro

int main() {
  using namespace ogre_repro;

  Grid2DPageStrategyData data;

  // G2D_X_Z:世界 (x, y, z) -> 网格 (x, -z)
  float gx = 0, gy = 0;
  data.convertWorldToGridSpace(10.0f, 5.0f, -20.0f, &gx, &gy);
  CHECK_EQ(gx, 10.0f);
  CHECK_EQ(gy, 20.0f);
  data.convertWorldToGridSpace(10.0f, 5.0f, 20.0f, &gx, &gy);
  CHECK_EQ(gy, -20.0f);

  // determineGridLocation:cellSize=1000、origin=(0,0)
  int32 x = 0, y = 0;
  data.determineGridLocation(10.0f, 20.0f, &x, &y);      // +500 -> (0,0)
  CHECK_EQ(x, 0);
  CHECK_EQ(y, 0);
  data.determineGridLocation(1500.0f, 1300.0f, &x, &y);  // +500 -> (2,1)
  CHECK_EQ(x, 2);
  CHECK_EQ(y, 1);
  data.determineGridLocation(-2000.0f, -2000.0f, &x, &y);  // (-1500,-1500) -> (-2,-2)
  CHECK_EQ(x, -2);
  CHECK_EQ(y, -2);

  // calculatePageID:与 packIndex 相同
  CHECK_EQ(data.calculatePageID(0, 0), 0u);
  CHECK_EQ(data.calculatePageID(2, -1), 0x2FFFFu);  // (2<<16)|0xFFFF

  // updateDerivedMetrics:半径按格子折算
  CHECK_EQ(data.getLoadRadiusInCells(), 2.0f);   // 2000/1000
  CHECK_EQ(data.getHoldRadiusInCells(), 3.0f);   // 3000/1000

  // notifyCamera 判定:相机在格 (2,1),load=2 格、hold=3 格
  CHECK_EQ(classifyCell(0, 0, 2, 1, 2.0f, 3.0f), LOAD);
  CHECK_EQ(classifyCell(4, 3, 2, 1, 2.0f, 3.0f), LOAD);
  CHECK_EQ(classifyCell(-1, -2, 2, 1, 2.0f, 3.0f), HOLD);  // 外圈角落
  CHECK_EQ(classifyCell(5, 4, 2, 1, 2.0f, 3.0f), HOLD);    // 外圈角落
  CHECK_EQ(classifyCell(6, 4, 2, 1, 2.0f, 3.0f), NONE);    // 超出 hold 环
  CHECK_EQ(classifyCell(-3, -3, 2, 1, 2.0f, 3.0f), NONE);  // 超出 hold 环

  // 加载半径变小时,原 LOAD 格退回 HOLD
  CHECK_EQ(classifyCell(4, 3, 2, 1, 1.0f, 3.0f), HOLD);  // load=1 -> (4,3) 出内圈

  return lab::report("08-2 分页策略");
}

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

小结

  • convertWorldToGridSpace 把世界坐标折成网格坐标,G2D_X_Z 下 grid.y = -world.z。
  • determineGridLocation 用 cellSize/2 偏移把网格坐标折算成格子整数坐标。
  • calculatePageID 用与 TerrainGroup::packIndex 相同的打包,页 ID 覆盖正负格子。
  • notifyCamera 以相机格为圆心扫双环:内圈 loadPage、外圈 holdPage、环外靠 frameLastHeld 老化卸载。
  • 默认 cellSize=1000、load=2000、hold=3000(即 2 格 / 3 格)。

阅读导航:上一节:8.1 分页概述 · 下一节:8.3 地形分页 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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