《OGRE 3D 渲染引擎原理与架构》7.3 GLSL 着色器

GLSL 侧的三件事:GLUniformCache 对 uniform location 做值哈希缓存避免重复上传,GLSLProgramCommon 用 attributeIndex 表把语义映射成固定属性位置(position=0、normal=2、texcoord=8+index),GLSLProgramManager 给 uniform block 绑定 index+2 的 binding。lab 复现 uniform 缓存、固定属性索引与 block 绑定。

7.3 GLSL 着色器

前面两节处理的是「给 GPU 什么数据」,这一节处理「GPU 怎么读它」——GLSL 程序、uniform 与顶点属性的绑定。OGRE 在 GL 侧有三个关键组件:GLUniformCache 缓存 uniform 值避免重复上传,GLSLProgramCommon 用固定属性索引表映射顶点语义,GLSLProgramManager 从程序里抽取 uniforms 并给 uniform block 分配 binding 槽。

GLUniformCache:值哈希避免重复上传

每次 glUniform* 上传都带着驱动开销。OGRE 用 GLUniformCache 记录每个 location 的值哈希,值没变就跳过上传:

// RenderSystems/GLSupport/src/OgreGLUniformCache.cpp:GLUniformCache::updateUniform(v14.6.3 源码摘录,已删减)
bool GLUniformCache::updateUniform(int location, const void *value, int length)
{
#ifdef OGRE_ENABLE_STATE_CACHE
    uint32 current = mUniformValueMap[location];
    uint32 hash = Ogre::FastHash((const char *)value, length);
    // First check if the uniform name is in the map. If not, this is new so insert it into the map.
    if (!current || (current != hash))
    {
        // Haven't cached this state yet or the value has changed
        mUniformValueMap[location] = hash;
        return true;
    }

    return false;
#else
    return true;
#endif
}

要点:mUniformValueMap[location] 默认值是 0,!current 时视为「首次上传必 true」;OGRE_ENABLE_STATE_CACHE 关闭时直接无条件返回 true(每次都传)。注意哈希碰撞的工程取舍——极小概率误判「值没变」,靠调用方定期 clearCache() 规避。lab 里我们验证「首传 true / 同值 false / 改值 true」与不同 location 的独立缓存。

getFixedAttributeIndex:语义 → 固定属性位置

GLSL 的 layout(location=...) 是 GL 3.3+ 的主流做法。OGRE 在 GLSupport 里维护一张静态索引表,把顶点语义映射成固定的 location:

// RenderSystems/GLSupport/src/GLSL/OgreGLSLProgramCommon.cpp:attributeIndex 表(v14.6.3 源码摘录,已删减)
static int32 attributeIndex[VES_COUNT + 1] = {
        -1,// n/a
        0, // VES_POSITION
        1, // VES_BLEND_WEIGHTS
        7, // VES_BLEND_INDICES
        2, // VES_NORMAL
        3, // VES_DIFFUSE
        4, // VES_SPECULAR
        8, // VES_TEXTURE_COORDINATES
        15,// VES_BINORMAL
        14 // VES_TANGENT
};
语义location说明
VES_POSITION0与固定管线 gl_Vertex 对齐
VES_NORMAL2与固定管线 gl_Normal 对齐
VES_DIFFUSE3与固定管线 gl_Color 对齐
VES_TEXTURE_COORDINATES8+indexuv0=8、uv1=9……

查表函数把多 UV 语义特殊处理——VES_TEXTURE_COORDINATES 返回 8 + index:

// RenderSystems/GLSupport/src/GLSL/OgreGLSLProgramCommon.cpp:GLSLProgramCommon::getFixedAttributeIndex(v14.6.3 源码摘录,已删减)
int32 GLSLProgramCommon::getFixedAttributeIndex(VertexElementSemantic semantic, uint index)
{
    OgreAssertDbg(semantic > 0 && semantic <= VES_COUNT, "Missing attribute!");

    if(semantic == VES_TEXTURE_COORDINATES)
        return attributeIndex[semantic] + index;

    return attributeIndex[semantic];
}

这套索引与 7.2 的 VAO needsUpdate 里 getFixedAttributeIndex(sem, elemIndex) 是同一处调用——固定 location 让 CPU 侧不用每帧重新查询 uniform/attribute 位置。

extractUniformsFromProgram:uniform block 的 binding 分配

GLSLProgramManager::extractUniformsFromProgram 在程序链好后扫描 active uniforms 和 uniform blocks。block 的关键策略是「0 和 1 两个 binding 槽预留给默认缓冲」:

// RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLProgramManager.cpp:GLSLProgramManager::extractUniformsFromProgram(v14.6.3 源码摘录,已删减)
        // Now deal with uniform blocks
        GLint blockCount = 0;
        OGRE_CHECK_GL_ERROR(glGetProgramiv(programObject, GL_ACTIVE_UNIFORM_BLOCKS, &blockCount));

        for (int index = 0; index < blockCount; index++)
        {
            OGRE_CHECK_GL_ERROR(glGetActiveUniformBlockName(programObject, index, uniformLength, NULL, uniformName));
            // slots 0 & 1 are reserved for defaultbuffer
            auto binding = index + 2;
            bufferInfoMap[uniformName] = {binding, GL_UNIFORM_BLOCK};
            OGRE_CHECK_GL_ERROR(glUniformBlockBinding(programObject, index, binding));
        }

第 0 个 block 拿到 binding 2,第 1 个拿到 binding 3,依此类推——OGRE 自己的 default buffer 占住 0/1。配合 GL 3.3 的 UBO 机制,材质脚本里的 shared_params 就通过 binding 与 GLSL 的 layout(std140, binding = 2) uniform BlurParams 对上。lab 里我们验证两个 block 得到 2 和 3。

源码定位

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

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

下面用纯 C++ 复现 GLSL 侧的 uniform 缓存、固定属性索引与 block 绑定分配。它与 src/07-3-gl-shader.cpp 逐字节一致:

// file: src/07-3-gl-shader.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/07-3-gl-shader.cpp -o bin/07-3-gl-shader && ./bin/07-3-gl-shader
//
// 复现 GLSL 着色器与 uniform 定位(对应 OgreGLUniformCache.cpp 41-58、
// OgreGLSLProgramCommon.cpp 48-79、115-123、OgreGLSLProgramManager.cpp 123-168):
//   GLUniformCache::updateUniform 对 location 缓存值哈希,仅哈希变化才返回 true;
//   getFixedAttributeIndex 用 attributeIndex 表把语义映射成固定属性位置
//   (position=0、normal=2、diffuse=3、texcoord=8+index);
//   extractUniformsFromProgram 给每个 uniform block 绑定 index+2 的 binding。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <cstdint>
#include <string>
#include <unordered_map>
#include <vector>

namespace ogre_repro {

uint32_t fastHash(const char* data, int length) {
  uint32_t hash = 2166136261u;  // FNV-1a 简化
  for (int i = 0; i < length; ++i) {
    hash ^= static_cast<uint8_t>(data[i]);
    hash *= 16777619u;
  }
  return hash;
}

class GLUniformCache {
 public:
  // 对应 updateUniform:缓存 location 的值哈希,未变返回 false
  bool updateUniform(int location, const void* value, int length) {
    uint32_t current = mUniformValueMap[location];
    uint32_t hash = fastHash(static_cast<const char*>(value), length);
    if (!current || current != hash) {
      mUniformValueMap[location] = hash;
      return true;
    }
    return false;
  }
  void clearCache() { mUniformValueMap.clear(); }
  std::unordered_map<int, uint32_t> mUniformValueMap;
};

enum VertexElementSemantic : uint8_t {
  VES_POSITION = 1,
  VES_BLEND_WEIGHTS,
  VES_BLEND_INDICES,
  VES_NORMAL,
  VES_DIFFUSE,
  VES_SPECULAR,
  VES_TEXTURE_COORDINATES,
  VES_BINORMAL,
  VES_TANGENT
};

constexpr int32_t attributeIndex[VES_TANGENT + 1] = {
    -1,  // n/a
    0,   // VES_POSITION
    1,   // VES_BLEND_WEIGHTS
    7,   // VES_BLEND_INDICES
    2,   // VES_NORMAL
    3,   // VES_DIFFUSE
    4,   // VES_SPECULAR
    8,   // VES_TEXTURE_COORDINATES
    15,  // VES_BINORMAL
    14   // VES_TANGENT
};

int32_t getFixedAttributeIndex(VertexElementSemantic semantic, uint32_t index) {
  if (semantic == VES_TEXTURE_COORDINATES)
    return attributeIndex[semantic] + static_cast<int32_t>(index);
  return attributeIndex[semantic];
}

}  // namespace ogre_repro

int main() {
  using namespace ogre_repro;

  // uniform 缓存:首次必 true,相同值 false,改变后 true
  GLUniformCache cache;
  float v1 = 1.0f, v2 = 2.0f;
  CHECK(cache.updateUniform(0, &v1, sizeof(float)));
  CHECK(!cache.updateUniform(0, &v1, sizeof(float)));
  CHECK(cache.updateUniform(0, &v2, sizeof(float)));
  CHECK(cache.updateUniform(3, &v1, sizeof(float)));  // 不同 location 独立缓存

  // 固定属性索引
  CHECK_EQ(getFixedAttributeIndex(VES_POSITION, 0), int32_t(0));
  CHECK_EQ(getFixedAttributeIndex(VES_NORMAL, 0), int32_t(2));
  CHECK_EQ(getFixedAttributeIndex(VES_DIFFUSE, 0), int32_t(3));
  CHECK_EQ(getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 0), int32_t(8));
  CHECK_EQ(getFixedAttributeIndex(VES_TEXTURE_COORDINATES, 3), int32_t(11));  // 8+3
  CHECK_EQ(getFixedAttributeIndex(VES_TANGENT, 0), int32_t(14));
  CHECK_EQ(getFixedAttributeIndex(VES_BINORMAL, 0), int32_t(15));

  // uniform block binding = index + 2(slots 0/1 保留给 default buffer)
  std::vector<std::string> blocks = {"BlurParams", "CameraBlock"};
  std::unordered_map<std::string, int> bindings;
  for (size_t i = 0; i < blocks.size(); ++i)
    bindings[blocks[i]] = static_cast<int>(i) + 2;
  CHECK_EQ(bindings["BlurParams"], 2);
  CHECK_EQ(bindings["CameraBlock"], 3);

  return lab::report("07-3 GLSL 着色器");
}

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

小结

  • GLUniformCache::updateUniform 以「location → 值哈希」缓存跳过重复上传,OGRE_ENABLE_STATE_CACHE 关闭时退化为每次都传。
  • attributeIndex 表把顶点语义映射成固定 location:position=0、normal=2、diffuse=3、texcoord=8+index。
  • extractUniformsFromProgram 给每个 uniform block 分配 index+2 的 binding,0/1 预留给 default buffer。
  • 固定属性索引同时服务于 VAO 缓存与材质管线,是 GL 后端「免查询」策略的核心。

阅读导航:上一节:7.2 GL 硬件缓冲与顶点数组 · 下一节:8.1 Vulkan 渲染系统 。

继续阅读

探索更多技术文章

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

全部文章 返回首页

「books」更多文章

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