8.3 材质脚本与状态合并
材质写代码里费事,写脚本里才高效。OGRE 的 .material 脚本用声明式语法描述 8.1 的三层结构,ScriptCompiler 把它编译成资源对象。这一节讲脚本解析,以及编译阶段的「状态合并」。
本章与站内既有内容的分工
helio 卷二的脚本/资产导入讲编辑器侧;本系列 8.3 讲 OGRE 引擎内脚本编译器的机制与编译期状态处理。
MaterialManager:脚本材质是"unloaded"的
OgreMaterialManager.h 的类注释有个重要设计——脚本加载的材质不立刻加载纹理:
// OgreMain/include/OgreMaterialManager.h:MaterialManager 类注释(v14.6.3 源码摘录,已删减)
When loaded from a script, a Material is in an 'unloaded' state and only stores the settings
required. It does not at that stage load any textures. This is because the material settings may be
loaded 'en masse' from bulk material script files, but only a subset will actually be required.
Because this is a subclass of ResourceManager, any files loaded will be searched for in any path or
archive added to the resource paths/archives. See ResourceManager for details.
...
Ogre comes configured with a set of defaults for newly created
materials. If you wish to have a different set of defaults,
simply call getDefaultSettings() and change the returned Material's
settings. All materials created from then on will be configured
with the new defaults you have specified.
要点:一个 100 个材质的大脚本可能只用到其中 10 个,所以脚本材质只存设置(ambient/diffuse/technique 结构),真正用到的那个才在加载时解析纹理。getDefaultSettings() 返回一个模板材质,改它就能改变后续所有新建材质的默认值。
ScriptCompiler:脚本 → 资源
OgreScriptCompiler.h 的 ScriptCompiler 是编译主体。入口是把脚本字符串编译成资源:
// OgreMain/include/OgreScriptCompiler.h:ScriptCompiler::compile(v14.6.3 源码摘录,已删减)
/// Takes in a string of script code and compiles it into resources
/**
* @param str The script code
* @param source The source of the script code (e.g. a script file)
* @param group The resource group to place the compiled resources into
*/
bool compile(const String &str, const String &source, const String &group);
流程是经典三段式:ScriptLexer 把文本切成 token → ScriptParser 把 token 构造成抽象节点树(AbstractNode)→ 编译器遍历节点树实例化资源。任何错误记入错误列表,用内建错误码标识:
// OgreMain/include/OgreScriptCompiler.h:脚本错误码(v14.6.3 源码摘录,已删减)
enum{
CE_STRINGEXPECTED,
CE_NUMBEREXPECTED,
CE_FEWERPARAMETERSEXPECTED,
CE_VARIABLEEXPECTED,
CE_UNDEFINEDVARIABLE,
CE_OBJECTNAMEEXPECTED,
CE_OBJECTALLOCATIONERROR,
CE_INVALIDPARAMETERS,
CE_DUPLICATEOVERRIDE,
CE_UNEXPECTEDTOKEN,
CE_OBJECTBASENOTFOUND,
CE_REFERENCETOANONEXISTINGOBJECT,
CE_DEPRECATEDSYMBOL
};
.material 脚本本身是嵌套块语法——material { technique { pass { texture_unit { texture ... } } } },一层层对应到 8.1 的三层结构。脚本里的 texture 只记录纹理名,真正解析纹理对象要等材质被 load(配合上面的 unloaded 设计)。
compile:状态合并与硬件适配
脚本编译出的是「逻辑材质」,真正交给渲染系统前要过 compile 阶段。Material::compile(bool autoManageTextureUnits) 与 Technique::_compile 做三件事:
// OgreMain/include/OgreTechnique.h:Technique::_compile(v14.6.3 源码摘录,已删减)
/** Internal compilation method; see Material::compile.
@return Any information explaining problems with the compile.
*/
String _compile(bool autoManageTextureUnits);
/// Internal method for checking hardware support
bool checkHardwareSupport(bool autoManageTextureUnits, StringStream& compileErrors);
- 硬件支持检查(
checkHardwareSupport):当前渲染系统能否跑这个 Technique 的 Pass,不能就跑降级 Technique; - 固定管线 Pass 拆分:固定功能 Pass 若同时用太多纹理单元(旧卡多纹理限制),
autoManageTextureUnits自动拆成多个 Pass; - 状态排序:8.1 提过的
Pass::HashFunc在编译期算出 Pass 哈希,渲染队列按哈希排序,把状态相同的 Pass 排在一起,减少状态切换。
这套「逻辑材质 → 编译 → 渲染状态」的分离,让脚本只管描述、引擎负责适配硬件与优化切换。这也是全引擎少有的「脚本层」典型:卷四的 .program/.overlay 脚本复用同一套 ScriptCompiler。
源码定位
OgreMain/include/OgreMaterialManager.h:MaterialManager(unloaded 语义、getDefaultSettings)OgreMain/include/OgreScriptCompiler.h:ScriptCompiler::compile、内建错误码(CE_*)OgreMain/include/OgreMaterial.h:Material::compileOgreMain/include/OgreTechnique.h:Technique::_compile/checkHardwareSupport
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
下面复现 .material 脚本的块解析、颜色/纹理提取与脚本错误码。它与 src/08-3-material-script-state.cpp 逐字节一致:
// file: src/08-3-material-script-state.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/08-3-material-script-state.cpp -o bin/08-3-material-script-state && ./bin/08-3-material-script-state
//
// 复现 OgreScriptCompiler 编译 .material 脚本为材质结构的流程:
// 按块解析 material/technique/pass/texture_unit,提取颜色与纹理名;
// 与 ScriptCompiler 错误码(CE_*)对应的非法输入报错。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <cctype>
#include <sstream>
#include <string>
#include <vector>
namespace ogre_repro {
// 对应 ScriptCompiler 的错误码(局部复制关键项)
enum {
CE_STRINGEXPECTED = 0,
CE_NUMBEREXPECTED,
CE_OBJECTNAMEEXPECTED,
CE_UNEXPECTEDTOKEN,
CE_REFERENCETOANONEXISTINGOBJECT
};
struct Colour { float r = 0, g = 0, b = 0; };
// 编译产物:一个 material 的结构(对应编译后的 ConcreteNode 树产物)
struct CompiledMaterial {
std::string name;
std::vector<std::string> techniques; // technique 名(通常无名)
std::vector<std::string> passes; // pass 名
Colour ambient, diffuse;
std::vector<std::string> textureUnits; // texture_unit 的纹理名
};
// 对应 ScriptCompiler:compile(str, source, group),按行块解析
class ScriptCompiler {
public:
std::vector<uint32_t> errors; // 错误码列表
// 简化编译器:只识别 material/technique/pass/texture_unit 块与颜色指令
bool compile(const std::string& script, CompiledMaterial& out) {
errors.clear();
std::istringstream in(script);
std::string line;
std::string section; // 当前块:material/technique/pass/texture_unit
std::string materialName;
std::string textureName;
bool inTextureUnit = false;
int openBlocks = 0;
while (std::getline(in, line)) {
// 去注释与空白
size_t hash = line.find("//");
if (hash != std::string::npos) line = line.substr(0, hash);
trim(line);
if (line.empty()) continue;
std::istringstream ls(line);
std::string kw;
ls >> kw;
if (kw == "{") { openBlocks++; continue; }
if (kw == "}") {
openBlocks--;
if (inTextureUnit && openBlocks < 3) inTextureUnit = false;
continue;
}
if (kw == "material") {
if (!(ls >> materialName)) {
errors.push_back(CE_OBJECTNAMEEXPECTED); // 对应缺名字
return false;
}
section = "material";
} else if (kw == "technique") {
section = "technique";
out.techniques.push_back("default");
} else if (kw == "pass") {
section = "pass";
out.passes.push_back("default");
} else if (kw == "texture_unit") {
inTextureUnit = true;
out.textureUnits.push_back("");
} else if (kw == "texture") {
if (!inTextureUnit) { errors.push_back(CE_UNEXPECTEDTOKEN); return false; }
std::string file;
if (!(ls >> file)) { errors.push_back(CE_STRINGEXPECTED); return false; }
out.textureUnits.back() = file;
} else if (kw == "ambient") {
if (!readColour(ls, out.ambient)) { errors.push_back(CE_NUMBEREXPECTED); return false; }
} else if (kw == "diffuse") {
if (!readColour(ls, out.diffuse)) { errors.push_back(CE_NUMBEREXPECTED); return false; }
} else {
errors.push_back(CE_UNEXPECTEDTOKEN);
return false;
}
}
if (openBlocks != 0) { errors.push_back(CE_UNEXPECTEDTOKEN); return false; }
out.name = materialName;
return errors.empty();
}
private:
static void trim(std::string& s) {
size_t b = 0, e = s.size();
while (b < e && std::isspace(static_cast<unsigned char>(s[b]))) b++;
while (e > b && std::isspace(static_cast<unsigned char>(s[e - 1]))) e--;
s = s.substr(b, e - b);
}
static bool readColour(std::istringstream& ls, Colour& c) {
if (!(ls >> c.r >> c.g >> c.b)) return false;
return true;
}
};
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
const std::string grass = R"(
material Grass
{
technique
{
pass
{
ambient 0.5 0.5 0.5
diffuse 0.8 0.8 0.8
texture_unit
{
texture grass.jpg
}
}
}
}
)";
ScriptCompiler compiler;
CompiledMaterial m;
CHECK(compiler.compile(grass, m));
CHECK(m.name == "Grass");
CHECK_EQ(m.techniques.size(), 1u);
CHECK_EQ(m.passes.size(), 1u);
CHECK_EQ(m.textureUnits.size(), 1u);
CHECK(m.textureUnits[0] == "grass.jpg");
CHECK(m.ambient.r == 0.5f);
CHECK(m.diffuse.r == 0.8f);
CHECK(m.diffuse.g == 0.8f);
// 缺 material 名 → CE_OBJECTNAMEEXPECTED(对应脚本错误码)
CompiledMaterial bad;
CHECK(!compiler.compile("material\n{\n}\n", bad));
CHECK(compiler.errors[0] == CE_OBJECTNAMEEXPECTED);
// texture 出现在 texture_unit 外 → CE_UNEXPECTEDTOKEN
CompiledMaterial bad2;
std::string badScript = "material M { texture a.png }";
// 本实现按行:花括号在同一行会被当作关键字块处理,改用换行构造
badScript = "material M\n{\ntexture a.png\n}\n";
CHECK(!compiler.compile(badScript, bad2));
bool sawUnexpected = false;
for (auto e : compiler.errors)
if (e == CE_UNEXPECTEDTOKEN) sawUnexpected = true;
CHECK(sawUnexpected);
return lab::report("08-3 材质:材质脚本与状态合并");
}
本机实测(Apple clang 16,clang++ -std=c++20):编译通过,断言 13/13 通过。
小结
- 脚本加载的材质是 unloaded 的,只存设置不预载纹理,用到才解析。
ScriptCompiler::compile三段式:词法 → 语法树 → 实例化资源,错误用 CE_* 码标识。.material脚本是嵌套块语法,逐层对应 Material/Technique/Pass/TUS。Material::compile做状态合并:硬件支持检查、固定管线 Pass 拆分、Pass 哈希排序。
阅读导航:上一节:8.2 TextureUnitState 与纹理单元 · 下一节:9.1 Skeleton 与 Bone 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。