《OGRE 3D 渲染引擎原理与架构》10.3 资源流式加载

10.3 讲 Paging 组件的页面流式加载。Page::load 按 synchronous 分流:同步在调用线程 handleRequest→handleResponse,异步把请求放后台、响应放主线程队列;handleResponse 在 mInUnload 时放弃加载;loadPage 对已存在页面只 touch。lab 复现分流、主线程泵出与 isHeld 5 帧容差,16 项断言。

10.3 资源流式加载

大地图场景无法把全部内容一次性装进内存。Paging 组件把世界切成「页面」(Page),按玩家位置流式加载/卸载:接近某页就触发加载,离开就卸载。关键设计是每个页面的加载都能在同步与异步之间选择,Page::load(bool synchronous) 是唯一的入口;而 PageManager 每帧驱动整个页面系统。本节看加载的同步/异步分流、handleRequest/handleResponse 的主线程/后台分工,以及「已存在即 touch」和「5 帧容差」这两个保持页面驻留的机制。

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

10.1 的资源组加载是一次性全量;本节的 Paging 是按需、增量、可卸载的流式。二者都建立在 10.2 的 WorkQueue 之上。lab 复现 Page 的分流、PagedWorldSection 的页面管理,以及 isHeld 的环绕安全容差。

Page::load:synchronous 决定谁做 handleRequest

Page::load 先检查 mDeferredProcessInProgress——加载已在途时直接忽略重复调用。然后清空内容集合、置位进行中标志、清除 mInUnload。真正的分流在这里:synchronous 时在当前调用线程依次 handleRequest(后台工作)+ handleResponse(收尾);否则把 handleRequest 提交到后台队列,再把 handleResponse 排进主线程队列,保证收尾动作一定发生在主线程:

// Components/Paging/src/OgrePage.cpp:Page::load(v14.6.3 源码摘录,已删减)
    void Page::load(bool synchronous)
    {
        if (!mDeferredProcessInProgress)
        {
            destroyAllContentCollections();
            mDeferredProcessInProgress = true;
            mInUnload = false;

            if(synchronous)
            {
                auto res = handleRequest(NULL, NULL);
                handleResponse(res, NULL);
                delete res;
            }
            else
            {
                Root::getSingleton().getWorkQueue()->addTask([this]() {
                    auto res = handleRequest(NULL, NULL);
                    Root::getSingleton().getWorkQueue()->addMainThreadTask([this, res]() {
                        handleResponse(res, NULL);
                        delete res;
                    });
                });
            }

        }

    }

handleRequest 是后台线程(注释 “Background thread (maybe)"):它调 prepareImpl 填充 PageData,并把结果包成 WorkQueue::Response;handleResponse 是主线程(注释 “Main thread”):拿到成功响应且未在卸载时,才 loadImpl() 完成加载,随后复位 mDeferredProcessInProgress。注意卸载中(mInUnload)即使响应成功也放弃加载——页面已经被拆了,不能把内容装回去:

// Components/Paging/src/OgrePage.cpp:Page::handleResponse(v14.6.3 源码摘录,已删减)
    void Page::handleResponse(const WorkQueue::Response* res, const WorkQueue* srcQ)
    {
        // Main thread
        PageResponse pres = any_cast<PageResponse>(res->getData());

        // final loading behaviour
        if (res->succeeded() && !mInUnload)
        {
            if(!pres.pageData->collectionsToAdd.empty())
                std::swap(mContentCollections, pres.pageData->collectionsToAdd);

            loadImpl();
        }

        OGRE_DELETE pres.pageData;

        mDeferredProcessInProgress = false;

    }

PagedWorldSection::loadPage:不存在才加载,已存在只 touch

PagedWorldSection 管理页面的生命周期。loadPage(pageID, sync) 先查 mPages 地图:页面不存在就 new 一个 Page 插入(插入失败且键对应别的对象时删除旧对象),并调 page->load(sync);已存在则只调 i->second->touch()——更新「最后一次被使用」的帧号,让页面保持驻留,不重复加载:

// Components/Paging/src/OgrePagedWorldSection.cpp:PagedWorldSection::loadPage(v14.6.3 源码摘录,已删减)
    void PagedWorldSection::loadPage(PageID pageID, bool sync)
    {
        if (!mParent->getManager()->getPagingOperationsEnabled())
            return;

        PageMap::iterator i = mPages.find(pageID);
        if (i == mPages.end())
        {
            Page* page = OGRE_NEW Page(pageID, this);
            // try to insert
            std::pair<PageMap::iterator, bool> ret = mPages.emplace(page->getID(), page);

            if (!ret.second)
            {
                // page with this ID already in map
                if (ret.first->second != page)
                {
                    // replacing a page, delete the old one
                    OGRE_DELETE ret.first->second;
                    ret.first->second = page;
                }
            }
            page->load(sync);
        }
        else
            i->second->touch();
    }

isHeld:5 帧容差与帧号环绕

页面是否该保留由 isHeld() 决定:touch() 把 mFrameLastHeld 记为当前帧号,isHeld() 计算当前帧与上次持有的距离,距离不超过 5 帧就算持有。计算用「帧号小则补上环绕」的方式处理 32 位/64 位帧计数回绕,保证无限游戏时长下判断始终正确:

// Components/Paging/src/OgrePage.cpp:Page::isHeld(v14.6.3 源码摘录,已删减)
    bool Page::isHeld() const
    {
        unsigned long nextFrame = Root::getSingleton().getNextFrameNumber();
        unsigned long dist;
        if (nextFrame < mFrameLastHeld)
        {
            // we must have wrapped around
            dist = nextFrame + (std::numeric_limits<unsigned long>::max() - mFrameLastHeld);
        }
        else
            dist = nextFrame - mFrameLastHeld;

        // 5-frame tolerance
        return dist <= 5;
    }

PageManager::EventRouter 作为帧监听器把整个系统驱动起来:frameStarted 遍历所有世界调 frameStart(timeSinceLastFrame)(推进页面生命周期),再通知所有被监视的相机:

// Components/Paging/src/OgrePageManager.cpp:PageManager::EventRouter::frameStarted(v14.6.3 源码摘录,已删减)
    bool PageManager::EventRouter::frameStarted(const FrameEvent& evt)
    {
        if(pWorldMap->empty())
            return true;

        for(auto & i : *pWorldMap)
        {
            i.second->frameStart(evt.timeSinceLastFrame);
            // Notify of all active cameras
            // Previously we did this in cameraPreRenderScene, but that had the effect
            // of causing unnecessary unloading of pages if a camera was rendered
            // intermittently, so we assume that all cameras we're told to watch are 'active'
            for (auto & c : *pCameraList)
            {
                i.second->notifyCamera(c);
            }
        }

        return true;
    }

Paging 准备与主线程提交

flowchart TD
  subgraph Main["主线程"]
    A["相机通知 PageStrategy"] --> B["分区按 page ID 查找"]
    B -->|"已登记"| T["touch 保持页面"]
    B -->|"未登记且启用分页"| C["创建 Page,调用 load"]
    C --> X{"已有处理在途?"}
    X -->|"是"| Y["本次调用返回"]
    X -->|"否"| Z["销毁旧内容集合并设处理中"]
    Z --> D{"请求同步加载?"}
    D -->|"是"| E["直接调用 handleRequest / prepareImpl"]
    E --> H["handleResponse"]
    H --> I{"准备成功且未卸载?"}
    I -->|"是"| J["接收内容集合并调用 loadImpl"]
    I -->|"否"| K["跳过最终加载"]
    J --> R["清除处理中标记"]
    K --> R
    M["frameEnded 所在路径泵送主线程任务"] --> H
    L["分区 frameEnd"] --> N{"isHeld?"}
    N -->|"否"| O["卸载未持有页"]
    N -->|"是"| P["调用页面 frameEnd"]
  end
  subgraph Worker["WorkQueue 工作线程"]
    F["handleRequest / prepareImpl"] --> G["封装结果并投递主线程回调"]
  end
  D -->|"否,投递队列任务"| F
  G --> M

页数据交接与卸载边界

通用 Page 的异步调用有两个交接点。worker 的 handleRequest 生成临时 PageData 和 Response。主线程 handleResponse 检查准备结果及 mInUnload,成功且页仍需要时才接管内容并 loadImpl。无论是否接管,回调正常返回时都会清理临时 PageData 并清除在途标记。地形页还有 TerrainPagedWorldSection 自己的定义、加载和节流路径。 Page 源码 · 地形分页源码

flowchart LR
  S["PagedWorldSection 按页号登记"] --> P["Page"]
  P -->|"派发 prepare"| W["WorkQueue worker"]
  W -->|"交接 PageData 与 Response"| M["主线程回调"]
  S -->|"卸载请求设置标记"| P
  M --> C{"准备成功且页未卸载?"}
  C -->|"是"| L["页接管内容并 loadImpl"]
  C -->|"否"| R["跳过提交"]
  L --> F["释放临时数据,清除在途标记"]
  R --> F

mInUnload 检查的是提交条件。两段 lambda 捕获 Page 的 this,因此分析退出或自定义扩展时,还必须单独检查页实例能否活到回调结束。以持有期间的正常完成、卸载标记期间的回调、最终销毁三个时点描述交接。原生探针保持 Page 活到主线程响应之后,分别跑过正常提交、只设置卸载标记和准备失败三条路径。页实际删除发生在响应结束之后。 分页探针 通用页卸载 。

源码定位

  • Components/Paging/src/OgrePage.cpp:Page::load(169-196 行)
  • Components/Paging/src/OgrePage.cpp:Page::handleRequest/handleResponse(204-243 行)
  • Components/Paging/src/OgrePage.cpp:Page::touch/isHeld(90-109 行)
  • Components/Paging/src/OgrePagedWorldSection.cpp:PagedWorldSection::loadPage(198-224 行)
  • Components/Paging/src/OgrePageManager.cpp:PageManager::EventRouter::frameStarted(519-538 行)

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

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

PageRepro 复现 handleRequest/handleResponse 的 mInUnload 放弃加载与 isHeld 的 5 帧容差(含环绕);PagedWorldSectionRepro 复现 loadPage 的「不存在加载、已存在 touch」、异步时主线程队列泵出,以及 frameStart 逐页 touch。它与 src/10-3-resource-streaming.cpp 逐字节一致:

// file: src/10-3-resource-streaming.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/10-3-resource-streaming.cpp -o bin/10-3-resource-streaming && ./bin/10-3-resource-streaming
//
// 复现 Paging 组件的页面流式加载(Components/Paging/src/OgrePage.cpp 169-242
//   的 Page::load/handleRequest/handleResponse 与 OgrePagedWorldSection.cpp
//   198-224 的 loadPage):同步加载在调用线程 handleRequest→handleResponse;
//   异步加载把 handleRequest 放后台、handleResponse 放主线程队列;页面已存在
//   时 loadPage 只 touch();handleResponse 在 mInUnload 时放弃加载。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <cstdint>
#include <deque>
#include <limits>
#include <map>
#include <utility>

namespace ogre_repro {

using PageID = uint32_t;

// 对应 OgrePage.cpp 50-109 的 Page(isHeld 用 5 帧容差)
struct PageRepro {
    PageID id = 0;
    bool inUnload = false;
    bool deferredInProgress = false;
    bool prepared = false;
    bool loaded = false;
    uint32_t contentCollections = 0;
    uint64_t frameLastHeld = 0;

    // 对应 Page::touch
    void touch(uint64_t frame) { frameLastHeld = frame; }

    // 对应 Page::isHeld:帧号环绕安全的 5 帧容差
    bool isHeld(uint64_t frame) const {
        uint64_t dist;
        if (frame < frameLastHeld) {
            dist = frame + (std::numeric_limits<uint64_t>::max() - frameLastHeld);
        } else {
            dist = frame - frameLastHeld;
        }
        return dist <= 5;
    }

    // 对应 Page::handleRequest:后台线程,prepare 内容集合
    void handleRequest() { prepared = true; }

    // 对应 Page::handleResponse:主线程,mInUnload 时放弃加载
    void handleResponse() {
        if (!inUnload) {
            contentCollections = 3;  // 模拟 loadImpl 加载 3 个 content collection
            loaded = true;
        }
        deferredInProgress = false;
    }

    // 对应 Page::unload
    void unload() {
        inUnload = true;
        contentCollections = 0;
        loaded = false;
    }
};

// 对应 PagedWorldSection::loadPage + WorkQueue 主线程队列(单线程模拟)
class PagedWorldSectionRepro {
public:
    explicit PagedWorldSectionRepro(uint64_t frame) : mFrame(frame) {}

    PageRepro* loadPage(PageID pageID, bool sync) {
        auto it = mPages.find(pageID);
        if (it == mPages.end()) {
            auto* page = new PageRepro();
            page->id = pageID;
            mPages.emplace(pageID, page);
            // 对应 OgrePage.cpp 169-196 的 Page::load 同步/异步分流
            if (sync) {
                page->handleRequest();
                page->handleResponse();
            } else {
                page->deferredInProgress = true;
                page->handleRequest();      // 后台阶段:prepare
                mMainTasks.push_back(page);  // 主线程队列:handleResponse
            }
            return page;
        }
        it->second->touch(mFrame);  // 已存在:只 touch()
        return it->second;
    }

    void processMainThreadTasks() {
        while (!mMainTasks.empty()) {
            PageRepro* p = mMainTasks.front();
            mMainTasks.pop_front();
            p->handleResponse();
        }
    }

    void unloadPage(PageID pageID) {
        auto it = mPages.find(pageID);
        if (it != mPages.end()) {
            it->second->unload();
            mPages.erase(it);
        }
    }

    // 对应 PageManager::EventRouter::frameStarted:逐世界逐 section 驱动
    void frameStart() {
        for (auto& [id, p] : mPages) {
            (void)id;
            p->touch(mFrame);
        }
    }

    size_t pageCount() const { return mPages.size(); }
    PageRepro* getPage(PageID pageID) const {
        auto it = mPages.find(pageID);
        return it == mPages.end() ? nullptr : it->second;
    }

private:
    std::map<PageID, PageRepro*> mPages;
    std::deque<PageRepro*> mMainTasks;
    uint64_t mFrame;
};

}  // namespace ogre_repro

int main() {
    using namespace ogre_repro;

    PagedWorldSectionRepro section(0);
    CHECK(section.getPage(1) == nullptr && section.pageCount() == 0u);

    // 同步加载:调用线程直接 handleRequest + handleResponse
    PageRepro* p1 = section.loadPage(1, true);
    CHECK(p1->prepared && p1->loaded && !p1->deferredInProgress);
    CHECK_EQ(p1->contentCollections, 3u);
    CHECK_EQ(section.pageCount(), 1u);

    // 页面已存在:loadPage 只 touch,不重复加载
    PageRepro* p1b = section.loadPage(1, true);
    CHECK(p1 == p1b && p1->loaded);  // 状态未被重置
    CHECK_EQ(p1->contentCollections, 3u);

    // 异步加载:后台 prepare 完成,handleResponse 留在主线程队列
    PageRepro* p2 = section.loadPage(2, false);
    CHECK(p2->prepared && !p2->loaded && p2->deferredInProgress);
    section.processMainThreadTasks();
    CHECK(p2->loaded && !p2->deferredInProgress);
    CHECK_EQ(p2->contentCollections, 3u);

    // 异步加载中 unload:handleResponse 因 mInUnload 放弃加载
    PageRepro* p3 = section.loadPage(3, false);
    CHECK(p3->deferredInProgress && !p3->loaded);
    p3->unload();
    section.processMainThreadTasks();
    CHECK(!p3->loaded && !p3->deferredInProgress);
    CHECK_EQ(p3->contentCollections, 0u);

    // isHeld:5 帧容差
    PageRepro held;
    held.touch(100);
    CHECK(held.isHeld(105) && held.isHeld(103) && !held.isHeld(106));
    // 帧号环绕
    PageRepro wrap;
    wrap.touch(std::numeric_limits<uint64_t>::max() - 1);
    CHECK(wrap.isHeld(2) && !wrap.isHeld(100));  // dist = 2 + 1 = 3

    // frameStart 遍历所有页面并 touch
    PagedWorldSectionRepro s2(500);
    s2.loadPage(10, true);
    s2.loadPage(11, true);
    s2.frameStart();
    CHECK(s2.getPage(10)->frameLastHeld == 500 && s2.getPage(11)->frameLastHeld == 500);

    // unloadPage:unload + 从地图移除
    s2.unloadPage(10);
    CHECK(s2.getPage(10) == nullptr && s2.pageCount() == 1u);

    return lab::report("10.3 资源流式加载");
}

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

小结

  • Page::load(synchronous) 是唯一加载入口:同步在调用线程完成,异步把 handleRequest 放后台、handleResponse 排主线程。
  • handleResponse 只有「成功且未在卸载」才 loadImpl(),mInUnload 时响应到达即放弃。
  • loadPage 对已存在页面只 touch(),不重复加载;touch 更新 mFrameLastHeld。
  • isHeld() 用帧号距离(含环绕补正)判断,5 帧容差决定页面驻留资格。
  • PageManager::EventRouter::frameStarted 每帧遍历世界推进生命周期,并通知被监视相机。

阅读导航:上一节:10.2 工作队列 · 下一节:11.1 网格升级工具 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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