《OGRE 3D 渲染引擎原理与架构》12.2 内容导入集成

12.2 讲 DotScene 内容导入。load 先校验 formatVersion,缺失即报错;processNode 创建节点(空名自动命名,否则加前缀),先递归子 node 再处理 entity;processEntity 按 instanced 分流。lab 复现版本校验、命名与分流,14 项断言。

12.2 内容导入集成

.scene 文件是 OGRE 生态里的场景描述格式:一棵 XML 树,包含环境、节点、实体、灯光、相机与地形。DotSceneLoader 把它转成运行时场景图。整个导入可以拆成「校验 → 场景级处理 → 节点递归 → 实体处理」四个层次。最容易踩坑的两处是命名与instanced 分流:节点名可空(此时让 OGRE 自动命名)或加 mItemPrefix 前缀;实体若带 instanced 属性,走 createInstancedEntity 的实例化路径,否则 createEntity 创建普通实体。

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

11.3 从外部文件导入网格资源;本节的 DotScene 把整个场景布局(节点层级、实体摆放、灯光相机)装进场景图。lab 复现版本校验、节点命名规则、递归顺序与实体分流。

load:先校验 formatVersion

load 有两个前置门:XML 解析失败直接返回;然后取 <scene> 根节点,缺失 formatVersion 属性就记错误并返回——这是对「无效 .scene 文件」的显式拦截。校验通过后才把根节点设为挂载点并进入 processScene。mItemPrefix 来自场景节点上的 _DotSceneLoaderOptions(namePrefix 可选项):

// PlugIns/DotScene/src/DotSceneLoader.cpp:DotSceneLoader::load(v14.6.3 源码摘录,已删减)
    auto result = XMLDoc.load_buffer(stream->getAsString().c_str(), stream->size());
    if (!result)
    {
        LogManager::getSingleton().logError("DotSceneLoader - " + String(result.description()));
        return;
    }

    // Grab the scene node
    auto XMLRoot = XMLDoc.child("scene");

    // Validate the File
    if (!XMLRoot.attribute("formatVersion"))
    {
        LogManager::getSingleton().logError("DotSceneLoader - Invalid .scene File. Missing <scene formatVersion='x.y' >");
        return;
    }

    // figure out where to attach any nodes we create
    mAttachNode = rootNode;

    // Process the scene
    processScene(XMLRoot);

processScene 读 formatVersion 打日志,然后按 environment/nodes/externals/userData/light/camera 等子节点分流处理:

// PlugIns/DotScene/src/DotSceneLoader.cpp:DotSceneLoader::processScene(v14.6.3 源码摘录,已删减)
    // Process the scene parameters
    String version = getAttrib(XMLRoot, "formatVersion", "unknown");

    String message = "[DotSceneLoader] Parsing dotScene file with version " + version;
    if (XMLRoot.attribute("sceneManager"))
        message += ", scene manager " + String(XMLRoot.attribute("sceneManager").value());
    if (XMLRoot.attribute("minOgreVersion"))
        message += ", min. Ogre version " + String(XMLRoot.attribute("minOgreVersion").value());
    if (XMLRoot.attribute("author"))
        message += ", author " + String(XMLRoot.attribute("author").value());

    LogManager::getSingleton().logMessage(message);

    // Process environment (?)
    if (auto pElement = XMLRoot.child("environment"))
        processEnvironment(pElement);

    // Process nodes (?)
    if (auto pElement = XMLRoot.child("nodes"))
        processNodes(pElement);

processNode:空名自动命名,否则加前缀

processNode 的命名逻辑是本节重点。name 为空时让 OGRE 取名(createChildSceneNode() 无参版),否则用 mItemPrefix + name 构造唯一名——前缀机制正是为了多个 .scene 合并时避免节点名冲突。节点创建后处理 position/rotation/scale/lookTarget/trackTarget 属性,然后先递归子 node、再处理 entity,保证父节点先存在、子内容可挂靠:

// PlugIns/DotScene/src/DotSceneLoader.cpp:DotSceneLoader::processNode(v14.6.3 源码摘录,已删减)
    // Construct the node's name
    String name = getAttrib(XMLNode, "name");

    // Create the scene node
    SceneNode* pNode;
    if (name.empty())
    {
        // Let Ogre choose the name
        if (pParent)
            pNode = pParent->createChildSceneNode();
        else
            pNode = mAttachNode->createChildSceneNode();
    }
    else
    {
        // Provide the name
        if (pParent)
            pNode = pParent->createChildSceneNode(mItemPrefix + name);
        else
            pNode = mAttachNode->createChildSceneNode(mItemPrefix + name);
    }

    // Process other attributes

    // Process position (?)
    if (auto pElement = XMLNode.child("position"))
    {
        pNode->setPosition(parseVector3(pElement));
    }

    // Process node (*)
    for (auto pElement : XMLNode.children("node"))
    {
        processNode(pElement, pNode);
    }

    // Process entity (*)
    for (auto pElement : XMLNode.children("entity"))
    {
        processEntity(pElement, pNode);
    }

processEntity:instanced 属性分流

processEntity 读取 name/meshFile/static/instanced/material/castShadows/visible 等属性。instanced 属性非空时走实例化路径:先加载网格取第一个子网格材质名,再 createInstancedEntity(material, instancedManager) 并挂到父节点;否则走普通路径 createEntity(mItemPrefix + name, meshFile, group),设置阴影与可见性,可选设置材质。staticGeometry 非空时实体不挂节点(属于静态几何组,留待 processStaticGeometry):

// PlugIns/DotScene/src/DotSceneLoader.cpp:DotSceneLoader::processEntity(v14.6.3 源码摘录,已删减)
    String name = getAttrib(XMLNode, "name");
    String meshFile = getAttrib(XMLNode, "meshFile");
    String staticGeometry = getAttrib(XMLNode, "static");
    String instancedManager = getAttrib(XMLNode, "instanced");
    String material = getAttrib(XMLNode, "material");
    bool castShadows = getAttribBool(XMLNode, "castShadows", true);
    bool visible = getAttribBool(XMLNode, "visible", true);

    // Create the entity
    MovableObject* pEntity = 0;

    try
    {
        // If the Entity is instanced then the creation path is different
        if (!instancedManager.empty())
        {
            // Load the Mesh to get the material name of the first submesh
            Ogre::MeshPtr mesh = MeshManager::getSingletonPtr()->load(meshFile, m_sGroupName);

            // Get the material name of the entity
            if (!material.empty())
                pEntity = mSceneMgr->createInstancedEntity(material, instancedManager);
            else
                pEntity = mSceneMgr->createInstancedEntity(mesh->getSubMesh(0)->getMaterialName(), instancedManager);

            pParent->attachObject(static_cast<InstancedEntity*>(pEntity));
        }
        else
        {
            pEntity = mSceneMgr->createEntity(mItemPrefix + name, meshFile, m_sGroupName);

            static_cast<Entity*>(pEntity)->setCastShadows(castShadows);
            static_cast<Entity*>(pEntity)->setVisible(visible);

            if (!material.empty())
                static_cast<Entity*>(pEntity)->setMaterialName(material);

            // If the Entity belongs to a Static Geometry group then it doesn't get attached to a node
            if (!staticGeometry.empty())

源码定位

  • PlugIns/DotScene/src/DotSceneLoader.cpp:DotSceneLoader::load(137-177 行)
  • PlugIns/DotScene/src/DotSceneLoader.cpp:DotSceneLoader::processScene(180-218 行)
  • PlugIns/DotScene/src/DotSceneLoader.cpp:DotSceneLoader::processNode(436-499 行)
  • PlugIns/DotScene/src/DotSceneLoader.cpp:DotSceneLoader::processEntity(615-659 行)

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

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

XmlNodeRepro 提供极简 XML 节点;DotSceneLoaderRepro::load 复现 formatVersion 校验,processNode 复现空名自动命名(NodeN)、mItemPrefix 前缀、先递归 node 再 entity,processEntity 复现 instanced 分流。它与 src/12-2-content-import.cpp 逐字节一致:

// file: src/12-2-content-import.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/12-2-content-import.cpp -o bin/12-2-content-import && ./bin/12-2-content-import
//
// 复现 DotScene 内容导入(PlugIns/DotScene/src/DotSceneLoader.cpp 137-177 的
//   load、180-218 的 processScene、436-499 的 processNode、615-659 的
//   processEntity):load 校验 <scene formatVersion='x.y'> 后进入场景处理;
//   processNode 创建场景节点(空名自动命名,否则加前缀),先递归子 node
//   再处理 entity;processEntity 按 instanced 属性分流到实例化/普通实体。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <cstdint>
#include <sstream>
#include <string>
#include <utility>
#include <vector>

namespace ogre_repro {

struct XmlNodeRepro {  // 极简 XML 节点:名字 + 属性 + 子节点
    std::string name;
    std::vector<std::pair<std::string, std::string>> attribs;
    std::vector<XmlNodeRepro> children;

    std::string attrib(const std::string& key, const std::string& def) const {
        for (auto& [k, v] : attribs)
            if (k == key)
                return v;
        return def;
    }
    bool hasAttrib(const std::string& key) const {
        for (auto& [k, v] : attribs)
            if (k == key)
                return true;
        return false;
    }
};

// 对应 Ogre::SceneNode 的最小状态
struct SceneNodeRepro {
    std::string name;
    float pos[3] = {0, 0, 0};
    std::vector<SceneNodeRepro*> children;
    std::vector<std::string> attachedEntities;
};

// 对应 DotSceneLoader(瘦身)
class DotSceneLoaderRepro {
public:
    explicit DotSceneLoaderRepro(std::string prefix) : mItemPrefix(std::move(prefix)) {}

    // 对应 load 137-177:校验 formatVersion 后处理场景
    bool load(const XmlNodeRepro& xmlRoot, SceneNodeRepro* rootNode) {
        if (!xmlRoot.hasAttrib("formatVersion")) {
            mLastError = "Missing <scene formatVersion='x.y' >";
            return false;
        }
        processScene(xmlRoot, rootNode);
        return true;
    }

    // 对应 processScene 180-201:版本 + nodes 子树
    void processScene(const XmlNodeRepro& xml, SceneNodeRepro* root) {
        mVersion = xml.attrib("formatVersion", "unknown");
        for (const XmlNodeRepro& c : xml.children)
            if (c.name == "nodes")
                for (const XmlNodeRepro& n : c.children)
                    if (n.name == "node")
                        processNode(n, root);
    }

    // 对应 processNode 436-499:建节点、位置、递归子节点、实体
    void processNode(const XmlNodeRepro& xml, SceneNodeRepro* parent) {
        auto* node = new SceneNodeRepro();
        const std::string name = xml.attrib("name", "");
        if (name.empty())
            node->name = autoName();  // 对应源码 445-452:让 Ogre 取名
        else
            node->name = mItemPrefix + name;
        if (const XmlNodeRepro* p = findChild(xml, "position")) {
            float* v = parseVec(p->attrib("x", "0") + " " + p->attrib("y", "0") + " " + p->attrib("z", "0"));
            node->pos[0] = v[0];
            node->pos[1] = v[1];
            node->pos[2] = v[2];
        }
        parent->children.push_back(node);

        for (const XmlNodeRepro& c : xml.children)  // 对应 491-494:先递归 node
            if (c.name == "node")
                processNode(c, node);
        for (const XmlNodeRepro& c : xml.children)  // 对应 497-500:再处理 entity
            if (c.name == "entity")
                processEntity(c, node);
    }

    // 对应 processEntity 615-659:instanced 属性分流
    void processEntity(const XmlNodeRepro& xml, SceneNodeRepro* parent) {
        const std::string name = xml.attrib("name", "");
        const std::string instanced = xml.attrib("instanced", "");
        const std::string meshFile = xml.attrib("meshFile", "");
        const bool castShadows = xml.attrib("castShadows", "true") == "true";
        const bool visible = xml.attrib("visible", "true") == "true";
        if (!instanced.empty())
            parent->attachedEntities.push_back("instanced:" + instanced + "/" + name);
        else
            parent->attachedEntities.push_back("entity:" + mItemPrefix + name + "@" + meshFile +
                                               " castShadows=" + (castShadows ? "1" : "0") +
                                               " visible=" + (visible ? "1" : "0"));
    }

    std::string mVersion;
    std::string mLastError;

private:
    static const XmlNodeRepro* findChild(const XmlNodeRepro& n, const std::string& name) {
        for (const XmlNodeRepro& c : n.children)
            if (c.name == name)
                return &c;
        return nullptr;
    }
    static float parseVec3Part(std::istringstream& is) {
        float v = 0;
        is >> v;
        return v;
    }
    static float* parseVec(const std::string& text) {
        static thread_local float out[3] = {0, 0, 0};
        std::istringstream is(text);
        out[0] = parseVec3Part(is);
        out[1] = parseVec3Part(is);
        out[2] = parseVec3Part(is);
        return out;
    }
    std::string autoName() {
        return "Node" + std::to_string(mAutoIndex++);
    }
    uint32_t mAutoIndex = 0;
    std::string mItemPrefix;
};

}  // namespace ogre_repro

int main() {
    using namespace ogre_repro;

    // 缺 formatVersion:load 失败
    XmlNodeRepro bad;
    bad.name = "scene";
    SceneNodeRepro root;
    DotSceneLoaderRepro ldr("L_");
    CHECK(!ldr.load(bad, &root));
    CHECK(!ldr.mLastError.empty());

    // 构造合法场景:nodes → Root(position 1 2 3) → 空名子节点 + 两个 entity
    XmlNodeRepro scene;
    scene.name = "scene";
    scene.attribs.push_back({"formatVersion", "1.0"});
    XmlNodeRepro nodes;
    nodes.name = "nodes";
    XmlNodeRepro rootNode;
    rootNode.name = "node";
    rootNode.attribs.push_back({"name", "Root"});
    XmlNodeRepro pos;
    pos.name = "position";
    pos.attribs.push_back({"x", "1"});
    pos.attribs.push_back({"y", "2"});
    pos.attribs.push_back({"z", "3"});
    rootNode.children.push_back(pos);
    XmlNodeRepro anonymous;  // 空名字 → 自动命名
    anonymous.name = "node";
    rootNode.children.push_back(anonymous);
    XmlNodeRepro dragon;
    dragon.name = "entity";
    dragon.attribs.push_back({"name", "Dragon"});
    dragon.attribs.push_back({"meshFile", "dragon.mesh"});
    dragon.attribs.push_back({"castShadows", "true"});
    rootNode.children.push_back(dragon);
    XmlNodeRepro inst;
    inst.name = "entity";
    inst.attribs.push_back({"name", "Tree"});
    inst.attribs.push_back({"meshFile", "tree.mesh"});
    inst.attribs.push_back({"instanced", "Forest"});
    rootNode.children.push_back(inst);
    nodes.children.push_back(rootNode);
    scene.children.push_back(nodes);

    DotSceneLoaderRepro loader("L_");
    CHECK(loader.load(scene, &root));
    CHECK(loader.mVersion == "1.0");

    // Root 节点:带前缀命名 + position 生效
    CHECK_EQ(root.children.size(), 1u);
    SceneNodeRepro* node = root.children[0];
    CHECK(node->name == "L_Root");
    CHECK_EQ(node->pos[0], 1.0f);
    CHECK_EQ(node->pos[1], 2.0f);
    CHECK_EQ(node->pos[2], 3.0f);

    // 空名字子节点:自动命名;挂在 Root 之下
    CHECK_EQ(node->children.size(), 1u);
    SceneNodeRepro* anonymousNode = node->children[0];
    CHECK(anonymousNode->name == "Node0");

    // entity 顺序:先普通实体(带属性),再 instanced 分流
    CHECK_EQ(node->attachedEntities.size(), 2u);
    CHECK(node->attachedEntities[0] ==
          "entity:L_Dragon@dragon.mesh castShadows=1 visible=1");
    CHECK(node->attachedEntities[1] == "instanced:Forest/Tree");

    return lab::report("12.2 内容导入集成");
}

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

小结

  • load 先校验 <scene formatVersion='x.y'>,缺失即报错返回;校验通过后以 mAttachNode 为挂载点进入 processScene。
  • processNode 命名两态:空名走 createChildSceneNode()(OGRE 自动取名),非空名加 mItemPrefix 前缀。
  • 处理顺序固定:先递归子 node、再 entity、再 light,保证父节点先建、内容可挂靠。
  • processEntity 按 instanced 属性分流:实例化实体 vs 普通实体(设置阴影/可见性/材质)。
  • staticGeometry 非空时实体不挂节点,交给静态几何组路径。

阅读导航:上一节:12.1 Bullet 物理集成 · 下一节:12.3 引擎混合使用 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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