3.2 参数缓冲 GpuProgramParameters
着色器跑起来要喂常量:世界矩阵、光源颜色、时间、用户自定义 uniform。OGRE 把这些常量全部塞进一块字节缓冲,对外提供两套写入接口——低层汇编程序按「float4 逻辑索引」写,高层程序按「参数名」写。这一节拆开这块缓冲,看两套接口如何落到同一块内存。
本章与站内既有内容的分工
helio 四卷在实现渲染器时把 uniform 缓存简化为「数组 + 索引」;卷一 8.x 提到过 GpuProgramParameters 的存在。这里看 OGRE 的生产级设计:物理缓冲 + 逻辑到物理映射 + 名称到定义映射三层结构,以及为什么低层和高层语言走的是两条不同的解析链。
常量是什么形状:GpuConstantType 与 GpuConstantDefinition
常量类型由两段枚举描述。BaseConstantType 划大类(float/int/double/uint/bool/sampler),GpuConstantType 在各类上叠尺寸:
// OgreMain/include/OgreGpuProgramParams.h:BaseConstantType/GpuConstantType(v14.6.3 源码摘录,已删减)
enum BaseConstantType
{
BCT_FLOAT = 0,
BCT_INT = 0x10,
BCT_DOUBLE = 0x20,
BCT_UINT = 0x30,
BCT_BOOL = 0x40,
BCT_SAMPLER = 0x50,
BCT_SPECIALIZATION = 0x60, //!< shader specialisation constant
BCT_UNKNOWN = 0x70
};
enum GpuConstantType
{
GCT_FLOAT1 = BCT_FLOAT + 1,
GCT_FLOAT2 = BCT_FLOAT + 2,
GCT_FLOAT3 = BCT_FLOAT + 3,
GCT_FLOAT4 = BCT_FLOAT + 4,
GCT_SAMPLER1D = BCT_SAMPLER + 1,
...
GCT_MATRIX_4X4 = BCT_FLOAT + 13,
注意这个编码技巧:BCT_FLOAT = 0,于是 GCT_FLOAT1..4 就是 1..4,而 GCT_MATRIX_4X4 = 13。要判断一个常量是否 float 家族,只要看 ctype / 0x10 * 0x10(取高位)——isFloat() 就是这样做的。大类用高 4 位,尺寸用低 4 位,一个整数同时表达「是什么」和「多大」。
每个具名常量的元信息存在 GpuConstantDefinition:
// OgreMain/include/OgreGpuProgramParams.h:GpuConstantDefinition(v14.6.3 源码摘录,已删减)
struct _OgreExport GpuConstantDefinition
{
/// Physical byte offset in buffer
size_t physicalIndex;
/// Logical index - used to communicate this constant to the rendersystem
size_t logicalIndex;
/** Number of typed slots per element
(some programs pack each array element to float4, some do not) */
uint32 elementSize;
/// Length of array
uint32 arraySize;
/// Data type
GpuConstantType constType;
/// How this parameter varies (bitwise combination of GpuProgramVariability)
mutable uint16 variability;
字段含义:
| 字段 | 含义 |
|---|---|
physicalIndex | 在常量缓冲里的物理字节偏移 |
logicalIndex | 给渲染系统通信用的逻辑索引(低层程序用) |
elementSize | 每个数组元素的槽位数(可能打包成 float4,也可能不打包) |
arraySize | 数组长度 |
constType | 数据类型(float4 / mat4x4 / sampler…) |
variability | 可变性掩码(per-object / per-light / 全局),3.3 会用到 |
缓冲本身:ConstantList
常量真正存储的地方是 ConstantList——一个朴素的字节向量:
// OgreMain/include/OgreGpuProgramParams.h:ConstantList(v14.6.3 源码摘录,已删减)
/** Definition of container that holds the current constants.
@note Not necessarily in direct index order to constant indexes, logical
to physical index map is derived from GpuProgram
*/
typedef std::vector<uchar> ConstantList;
成员 mConstants 就是它:
// OgreMain/include/OgreGpuProgramParams.h:GpuProgramParameters 成员(v14.6.3 源码摘录,已删减)
/// Packed list of constants (physical indexing)
ConstantList mConstants;
既然是字节缓冲,读写都要走类型转换。_writeRawConstants 直接 memcpy:
// OgreMain/include/OgreGpuProgramParams.h:_writeRawConstants(v14.6.3 源码摘录,已删减)
template<typename T>
void _writeRawConstants(size_t physicalIndex, const T* val, size_t count)
{
assert(physicalIndex + sizeof(T) * count <= mConstants.size());
memcpy(&mConstants[physicalIndex], val, sizeof(T) * count);
}
physicalIndex 就是字节偏移,count 是元素个数。这个模板让 float、int、Matrix4 都能复用同一条拷贝路径。
低层入口:setConstant 走逻辑→物理映射
低层汇编程序只有「寄存器号」概念——常量是 float4 数组的索引。setConstant(index, val, count) 里 index 是 float4 逻辑索引:
// OgreMain/src/OgreGpuProgramParams.cpp:setConstant(v14.6.3 源码摘录,已删减)
void GpuProgramParameters::setConstant(size_t index, const float *val, size_t count)
{
// Raw buffer size is 4x count
size_t rawCount = count * 4;
// get physical index
assert(mLogicalToPhysical && "GpuProgram hasn't set up the logical -> physical map!");
size_t physicalIndex = _getConstantPhysicalIndex(index, rawCount, GPV_GLOBAL, BCT_FLOAT);
// Copy
_writeRawConstants(physicalIndex, val, rawCount);
}
count 是 float4 个数,所以原始 float 数是 4*count。为什么要逻辑→物理映射而不是直接用逻辑索引?OGRE 只在程序实际设置过的常量上分配空间,逻辑索引间可能有空洞;把逻辑索引折叠到紧凑的物理偏移,缓冲就小很多。映射在 _setLogicalIndexes 里装好,同时按需扩容:
// OgreMain/src/OgreGpuProgramParams.cpp:_setLogicalIndexes(v14.6.3 源码摘录,已删减)
void GpuProgramParameters::_setLogicalIndexes(const GpuLogicalBufferStructPtr& indexMap)
{
mLogicalToPhysical = indexMap;
// resize the internal buffers
// Note that these will only contain something after the first parameter
// set has set some parameters
// Size and reset buffer (fill with zero to make comparison later ok)
if (indexMap && indexMap->bufferSize*4 > mConstants.size())
{
mConstants.insert(mConstants.end(), indexMap->bufferSize * 4 - mConstants.size(), 0);
}
}
高层入口:setNamedConstant 查名称直写
GLSL/HLSL 用 uniform 名,不关心寄存器。setNamedConstant 先在 mNamedConstants(一张 String → GpuConstantDefinition 的 map)里查名字,拿到 physicalIndex 后直写:
// OgreMain/src/OgreGpuProgramParams.cpp:_setNamedConstant(v14.6.3 源码摘录,已删减)
template <typename T> void GpuProgramParameters::_setNamedConstant(const String& name, const T* val, size_t count)
{
// look up, and throw an exception if we're not ignoring missing
const GpuConstantDefinition* def = _findNamedConstantDefinition(name, !mIgnoreMissingParams);
if (!def)
return;
if (count > def->arraySize * def->elementSize)
{
// The shader compiler may trim the array if the trailing elements
// are unused or their usage can be optimized away. Therefore,
// a count exceeding the array size not not an error.
count = def->arraySize * def->elementSize;
}
_writeRawConstants(withArrayOffset(def, name), val, count);
}
两个细节值得记:
- 缺失名称:默认
!mIgnoreMissingParams为真,找不到就抛异常;设为忽略则静默返回。 - 数组超界:编译器可能裁剪未用的数组尾元素,所以
count > arraySize*elementSize不是错误,截断到定义尺寸继续写——防止越界写坏缓冲。
withArrayOffset 处理 light[3] 这类带下标的名字:把下标乘上 elementSize 加到 physicalIndex,再配合 arraySize 检查。
lab 把两块缓冲放到同一个 GpuProgramParameters 里验证:逻辑映射写 float4、名称映射写 Matrix4、数组超界截断、缺失名称忽略。
源码定位
OgreMain/include/OgreGpuProgramParams.h:BaseConstantType/GpuConstantType(52-121)、GpuConstantDefinition(146-161)、ConstantList(387)、mConstants(1088)、_writeRawConstants(1267-1272)OgreMain/src/OgreGpuProgramParams.cpp:setConstant(891-903)、_setLogicalIndexes(817-830)、_setNamedConstant(2304-2321)
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
下面复现字节缓冲、双路径写入与数组截断。它与 src/03-2-gpu-program-params.cpp 逐字节一致:
// file: src/03-2-gpu-program-params.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/03-2-gpu-program-params.cpp -o bin/03-2-gpu-program-params && ./bin/03-2-gpu-program-params
//
// 复现 GpuProgramParameters 常量缓冲(对应 OgreGpuProgramParams.h 387/1088、OgreGpuProgramParams.cpp 891-903、2304-2321):
// ConstantList 是 std::vector<uchar> 字节缓冲,physicalIndex 是物理字节偏移;
// setConstant 以 float4 逻辑索引进入,经 logical->physical 映射解析字节偏移后 memcpy;
// setNamedConstant 查名称->GpuConstantDefinition.physicalIndex 直接写物理偏移;数组写入超界时截断。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <cstdint>
#include <cstring>
#include <map>
#include <string>
#include <vector>
namespace ogre_repro {
enum BaseConstantType : uint8_t { BCT_FLOAT = 0 };
enum GpuConstantType : uint8_t {
GCT_FLOAT1 = BCT_FLOAT + 1,
GCT_FLOAT4 = BCT_FLOAT + 4,
GCT_MATRIX_4X4 = BCT_FLOAT + 13
};
// 对应 GpuConstantDefinition:物理字节偏移 + 逻辑索引 + 元素/数组尺寸 + 类型
struct GpuConstantDefinition {
size_t physicalIndex = 0;
size_t logicalIndex = 0;
uint32_t elementSize = 0; // 每个元素的 float 数
uint32_t arraySize = 1; // 数组长度
GpuConstantType constType = GCT_FLOAT4;
};
// 对应 ConstantList:底层常量字节缓冲
using ConstantList = std::vector<uint8_t>;
class GpuProgramParameters {
public:
// 对应 _setLogicalIndexes:记录 logical->physical 字节偏移映射并分配缓冲
void _setLogicalIndexes(const std::map<size_t, size_t>& logicalToPhysical, size_t byteSize) {
mLogicalToPhysical = logicalToPhysical;
mConstants.assign(byteSize, 0);
}
// 对应 _setNamedConstants:注册 名称->定义 映射
void setNamedConstants(const std::map<std::string, GpuConstantDefinition>& named) {
mNamedConstants = named;
}
// 对应 setConstant(index, float*, count):count 为 float4 个数,rawCount=4*count
void setConstant(size_t index, const float* val, size_t count) {
size_t rawCount = count * 4;
size_t physicalIndex = _getConstantPhysicalIndex(index);
_writeRawConstants(physicalIndex, val, rawCount);
}
// 对应 setNamedConstant(name, float*, count):查 def->physicalIndex 直写
void setNamedConstant(const std::string& name, const float* val, size_t count) {
auto it = mNamedConstants.find(name);
if (it == mNamedConstants.end()) return; // mIgnoreMissingParams 为 true 时忽略缺失
const GpuConstantDefinition& def = it->second;
size_t maxCount = def.arraySize * def.elementSize;
if (count > maxCount) count = maxCount; // 编译器可能裁剪数组尾部,超界截断
_writeRawConstants(def.physicalIndex, val, count);
}
float readFloat(size_t byteOffset) const {
float f = 0.0f;
std::memcpy(&f, &mConstants[byteOffset], sizeof(float));
return f;
}
size_t size() const { return mConstants.size(); }
private:
size_t _getConstantPhysicalIndex(size_t logicalIndex) const {
auto it = mLogicalToPhysical.find(logicalIndex);
return it == mLogicalToPhysical.end() ? 0 : it->second;
}
void _writeRawConstants(size_t physicalIndex, const float* val, size_t count) {
std::memcpy(&mConstants[physicalIndex], val, count * sizeof(float));
}
ConstantList mConstants;
std::map<size_t, size_t> mLogicalToPhysical;
std::map<std::string, GpuConstantDefinition> mNamedConstants;
};
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
// ---- 低层程序:逻辑索引 -> 物理字节偏移 ----
GpuProgramParameters low;
std::map<size_t, size_t> l2p;
l2p[0] = 0;
l2p[1] = 16; // 第二个 float4 从字节 16 开始
l2p[2] = 32;
l2p[3] = 48;
low._setLogicalIndexes(l2p, 64);
CHECK(low.size() == 64); // 4 个 float4 = 64 字节
const float v4[4] = {1.0f, 2.0f, 3.0f, 4.0f};
low.setConstant(1, v4, 1); // 写逻辑索引 1(物理 16)
CHECK(low.readFloat(16) == 1.0f);
CHECK(low.readFloat(20) == 2.0f);
CHECK(low.readFloat(24) == 3.0f);
CHECK(low.readFloat(28) == 4.0f);
CHECK(low.readFloat(0) == 0.0f); // 逻辑索引 0 未写保持 0
// 一次写 2 个 float4(连续逻辑索引 2-3 -> 物理 32-63)
const float v8[8] = {10, 11, 12, 13, 14, 15, 16, 17};
low.setConstant(2, v8, 2);
CHECK(low.readFloat(32) == 10.0f);
CHECK(low.readFloat(44) == 13.0f); // 第 4 个 float 落于字节 44
CHECK(low.readFloat(48) == 14.0f);
CHECK(low.readFloat(60) == 17.0f);
// ---- 高级程序:名称 -> 定义 -> 物理偏移 ----
GpuProgramParameters hi;
std::map<std::string, GpuConstantDefinition> defs;
defs["world"] = GpuConstantDefinition{0, 0, 16, 1, GCT_MATRIX_4X4}; // Matrix4=16 floats
defs["light[0]"] = GpuConstantDefinition{64, 4, 4, 3, GCT_FLOAT4}; // 3 个 float4 数组
hi.setNamedConstants(defs);
hi._setLogicalIndexes(l2p, 80);
const float m16[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
hi.setNamedConstant("world", m16, 16);
CHECK(hi.readFloat(0) == 1.0f);
CHECK(hi.readFloat(12) == 4.0f);
CHECK(hi.readFloat(60) == 16.0f);
// 数组超界截断:light[0] 最多 3*4=12 个 float,写 16 个只落 12 个
const float arr[16] = {21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36};
hi.setNamedConstant("light[0]", arr, 16);
CHECK(hi.readFloat(64 + 0) == 21.0f);
CHECK(hi.readFloat(64 + 44) == 32.0f); // 第 12 个 float 被写入
CHECK(hi.readFloat(64 + 48) == 0.0f); // 第 13 个 float 被截断,未越界
// 缺失名称被忽略(不抛异常),已写常量不受影响
const float g[4] = {5, 6, 7, 8};
hi.setNamedConstant("nonexistent", g, 4);
CHECK(hi.readFloat(0) == 1.0f); // world 的值未被改动
return lab::report("03-2 参数缓冲 GpuProgramParameters");
}
本机实测(Apple clang 16,clang++ -std=c++20):编译通过(-Wall 零警告),断言 17/17 通过。
小结
- 常量存在
ConstantList(std::vector<uchar>)里,physicalIndex是字节偏移,读写靠memcpy。 GpuConstantType用「高 4 位大类 + 低 4 位尺寸」编码,isFloat()只看高 4 位。- 低层程序
setConstant以 float4 逻辑索引进入,经mLogicalToPhysical映射到物理偏移。 - 高层程序
setNamedConstant查String → GpuConstantDefinition直写physicalIndex。 - 数组写入超界按
arraySize*elementSize截断;缺失名称在mIgnoreMissingParams下被静默忽略。
阅读导航:上一节:3.1 GPU 程序抽象 · 下一节:3.3 自动参数绑定 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。