6.2 着色器参数绑定
着色器写好了还不够,还得把 CPU 侧的数据灌进去:世界矩阵、时间、光位置。GpuProgramParameters 就是这张「CPU 数据 → GPU 常量缓冲」的映射表。它有两条路:命名常量(按 uniform 名字写)与自动常量(登记一个 ACT_* 类型,每帧由引擎自动刷新)。这一节看这两条路各自的机制。
本章与站内既有内容的分工
卷二 3.2/3.3 已经讲过 GpuProgramParameters 的常量缓冲与自动参数数据源(AutoParamDataSource)。这一节把重点放在绑定语义:名字如何解析到物理偏移、数组下标怎么换算、自动常量以什么结构被登记,以及 _updateAutoParams 如何按类型刷新。不再重复卷二讲过的矩阵源细节。
命名常量:名字到物理偏移
参数对象持有一份名字到定义的映射。GpuConstantDefinition 记录了这个 uniform 在缓冲里的家:
// 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;
...
bool isFloat() const { return isFloat(constType); }
static bool isFloat(GpuConstantType c) { return getBaseType(c) == BCT_FLOAT; }
| 字段 | 含义 |
|---|---|
physicalIndex | 常量缓冲里的物理字节偏移,_writeRawConstant 的目标 |
logicalIndex | 逻辑索引,低层程序通过它跟渲染系统通信 |
elementSize | 每个数组元素占的槽数(GLSL 不补 4、SM1/D3D 补到 float4) |
arraySize | 数组长度 |
setNamedConstant 的浮点重载最直观地展示这条链:查定义 → 断言类型 → 换算数组偏移 → 写缓冲:
// OgreMain/src/OgreGpuProgramParams.cpp:GpuProgramParameters::setNamedConstant(v14.6.3 源码摘录,已删减)
void GpuProgramParameters::setNamedConstant(const String& name, float val)
{
// look up, and throw an exception if we're not ignoring missing
const GpuConstantDefinition* def =
_findNamedConstantDefinition(name, !mIgnoreMissingParams);
if (!def)
return;
OgreAssert(def->isFloat(), "Constant type mismatch");
_writeRawConstant(withArrayOffset(def, name), val);
}
名字查表本身有一处关键细节——剥数组下标。bones[2] 这种带下标的写法,表里的键是裸名 bones:
// OgreMain/src/OgreGpuProgramParams.cpp:GpuProgramParameters::_findNamedConstantDefinition(v14.6.3 源码摘录,已删减)
const GpuConstantDefinition*
GpuProgramParameters::_findNamedConstantDefinition(const String& name,
bool throwExceptionIfNotFound) const
{
if (!mNamedConstants)
{
if (throwExceptionIfNotFound)
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Named constants have not been initialised, perhaps a compile error");
return 0;
}
// strip array extension
size_t arrStart = name.back() == ']' ? name.find('[') : String::npos;
auto i = mNamedConstants->map.find(arrStart == String::npos ? name : name.substr(0, arrStart));
if (i == mNamedConstants->map.end() || (i->second.arraySize == 1 && arrStart != String::npos))
{
if (throwExceptionIfNotFound)
{
OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
"Parameter called " + name + " does not exist. " + knownNames,
"GpuProgramParameters::_findNamedConstantDefinition");
}
return 0;
}
else
{
return &(i->second);
}
}
注意第二重检查:即使找到了定义,若 arraySize == 1(非数组)却带了 [n] 下标,同样判失败。这样 nope[3] 不会悄悄写进未知位置。withArrayOffset 随后算出 def->physicalIndex + offset * def->elementSize。
自动常量:登记而不写死
世界矩阵、时间这类值每帧都在变,手写 setNamedConstant 太啰嗦。自动常量把「类型 + 目标索引 + 额外信息」登记成一条 AutoConstantEntry,值由引擎在合适的时机替你填:
// OgreMain/include/OgreGpuProgramParams.h:AutoConstantType / AutoConstantEntry(v14.6.3 源码摘录,已删减)
enum AutoConstantType
{
/// The current world matrix
ACT_WORLD_MATRIX,
/// The current world matrix, inverted
ACT_INVERSE_WORLD_MATRIX,
/** Provides transpose of world matrix.
*/
ACT_TRANSPOSE_WORLD_MATRIX,
/// The current world matrix, inverted & transposed
ACT_INVERSE_TRANSPOSE_WORLD_MATRIX,
...
/** Structure recording the use of an automatic parameter. */
class AutoConstantEntry
{
public:
/// The target (physical) constant index
size_t physicalIndex;
/// The type of parameter
AutoConstantType paramType;
/// Additional information to go with the parameter
union{
uint32 data;
float fData;
};
/// The variability of this parameter (see GpuParamVariability)
uint16 variability;
/** The number of elements per individual entry in this constant
Used in case people used packed elements smaller than 4 (e.g. GLSL)
and bind an auto which is 4-element packed to it */
uint8 elementCount;
AutoConstantEntry(AutoConstantType theType, size_t theIndex, uint32 theData,
uint16 theVariability, uint8 theElemCount = 4)
: physicalIndex(theIndex), paramType(theType),
data(theData), variability(theVariability), elementCount(theElemCount) {}
| 字段 | 含义 |
|---|---|
physicalIndex | 自动常量写入的物理位置 |
paramType | ACT_WORLD_MATRIX、ACT_VIEW_MATRIX、ACT_TIME 等 |
data/fData | 额外信息共用同一块内存:光索引用 uint32、时间因子用 float |
variability | 该参数的变化频率(GPV_PER_GAME_OBJECT、GPV_PER_FRAME…) |
elementCount | GLSL 里元素不满 4 槽时的实际元素数 |
setAutoConstant(index, type, extraInfo) 先按类型取 AutoConstantDefinition 定尺寸(不够 4 的向上补到 4),再记录 entry;setNamedAutoConstant(name, type, extraInfo) 则多一步:先按名字查定义拿到 physicalIndex,再记录。到了 _updateAutoParams(source, variabilityMask),引擎遍历 mAutoConstants,只刷新 variability 与掩码匹配的条目,从 AutoParamDataSource 读当前值写进缓冲。类型列表极长:ACT_WORLD_MATRIX、ACT_VIEWPROJ_MATRIX、ACT_BONE_MATRIX_ARRAY_3x4、ACT_LIGHT_POSITION、ACT_TIME、ACT_FROXEL_*……一份枚举就把「可自动化的渲染状态」都列全了。
源码定位
OgreMain/include/OgreGpuProgramParams.h:GpuConstantDefinition(146-)、AutoConstantType(476-)、AutoConstantEntry(1050-1079)、setAutoConstant(1408-)、setNamedAutoConstant(1482-)、setNamedConstant(1532-1582)OgreMain/src/OgreGpuProgramParams.cpp:_findNamedConstantDefinition(1350-1386)、setAutoConstant(1388-)、setNamedConstant(float)(2208-2217)、withArrayOffset(2190-2206)
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
下面复现命名常量与自动常量的绑定语义:名字→定义→物理偏移、数组下标换算、setNamedConstant 写缓冲、setAutoConstant/setNamedAutoConstant 登记 entry、updateAutoParams 按类型刷新。它与 src/ogre-ext-06-2-shader-parameters.cpp 逐字节一致:
// file: src/ogre-ext-06-2-shader-parameters.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/ogre-ext-06-2-shader-parameters.cpp -o bin/ogre-ext-06-2-shader-parameters && ./bin/ogre-ext-06-2-shader-parameters
//
// 复现 GpuProgramParameters 的命名常量与自动常量绑定
// (对应 OgreGpuProgramParams.h 146-、1050-1081、1408-1488,OgreGpuProgramParams.cpp 1343-1420、2208-2217):
// setNamedConstant 按名字查 GpuConstantDefinition,经 withArrayOffset 换算 physicalIndex 后写缓冲;
// setAutoConstant/setNamedAutoConstant 记录 AutoConstantEntry(physicalIndex + paramType + data),
// _updateAutoParams 遍历列表按类型刷新物理缓冲。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <cstdint>
#include <map>
#include <string>
#include <vector>
namespace ogre_repro {
// 对应 GpuConstantDefinition(OgreGpuProgramParams.h 146-)
struct GpuConstantDefinition {
uint32_t physicalIndex = 0; // 物理字节偏移
uint32_t elementSize = 4; // 每个数组元素的槽数
uint32_t arraySize = 1; // 数组长度
bool isFloat = true;
};
// 对应 GpuProgramParameters::AutoConstantType(OgreGpuProgramParams.h 476-)
enum AutoConstantType : uint8_t {
ACT_WORLD_MATRIX = 0,
ACT_VIEW_MATRIX,
ACT_PROJECTION_MATRIX,
ACT_TIME
};
// 对应 AutoConstantEntry(OgreGpuProgramParams.h 1050-1079)
struct AutoConstantEntry {
uint32_t physicalIndex;
AutoConstantType paramType;
uint32_t data; // union { uint32 data; float fData; } 的整数一侧
uint16_t variability;
uint8_t elementCount;
AutoConstantEntry(AutoConstantType t, uint32_t idx, uint32_t d,
uint16_t v, uint8_t elems = 4)
: physicalIndex(idx), paramType(t), data(d),
variability(v), elementCount(elems) {}
};
// 对应 GpuProgramParameters(OgreGpuProgramParams.h 467-)
class GpuProgramParameters {
public:
using NamedConstantMap = std::map<std::string, GpuConstantDefinition>;
void setNamedConstants(const NamedConstantMap& map) { mNamedConstants = map; }
// _findNamedConstantDefinition(OgreGpuProgramParams.cpp 1350-1386):
// 剥掉数组下标再查表,找不到返回空
const GpuConstantDefinition* findNamedConstantDefinition(
const std::string& name) const {
std::string base = name;
if (!name.empty() && name.back() == ']') {
size_t arrStart = name.find('[');
if (arrStart != std::string::npos) base = name.substr(0, arrStart);
}
auto it = mNamedConstants.find(base);
if (it == mNamedConstants.end()) return nullptr;
return &it->second;
}
// setNamedConstant(OgreGpuProgramParams.cpp 2208-2217):查定义 -> 数组偏移 -> 写缓冲
void setNamedConstant(const std::string& name, float val) {
const GpuConstantDefinition* def = findNamedConstantDefinition(name);
if (!def) return;
writeRawConstant(withArrayOffset(*def, name), val);
}
// withArrayOffset(OgreGpuProgramParams.cpp 2190-2206)
uint32_t withArrayOffset(const GpuConstantDefinition& def,
const std::string& name) const {
uint32_t offset = 0;
size_t start = name.find('[');
if (start != std::string::npos) {
offset = static_cast<uint32_t>(std::stoul(name.substr(start + 1)));
}
return def.physicalIndex + offset * def.elementSize;
}
void writeRawConstant(uint32_t physicalIndex, float val) {
if (physicalIndex + 1 > mConstants.size())
mConstants.resize(physicalIndex + 1, 0.0f);
mConstants[physicalIndex] = val;
}
float readRawConstant(uint32_t physicalIndex) const {
return physicalIndex < mConstants.size() ? mConstants[physicalIndex] : 0.0f;
}
// setAutoConstant(OgreGpuProgramParams.cpp 1388-):按逻辑索引记录自动常量
void setAutoConstant(uint32_t index, AutoConstantType acType, uint32_t extraInfo = 0) {
mAutoConstants.emplace_back(acType, index, extraInfo, deriveVariability(acType));
}
// setNamedAutoConstant(OgreGpuProgramParams.h 1482-)
void setNamedAutoConstant(const std::string& name, AutoConstantType acType,
uint32_t extraInfo = 0) {
const GpuConstantDefinition* def = findNamedConstantDefinition(name);
if (!def) return;
mAutoConstants.emplace_back(acType, def->physicalIndex, extraInfo,
deriveVariability(acType));
}
const std::vector<AutoConstantEntry>& getAutoConstants() const { return mAutoConstants; }
size_t getAutoConstantCount() const { return mAutoConstants.size(); }
bool hasAutoConstants() const { return !mAutoConstants.empty(); }
// _updateAutoParams(OgreGpuProgramParams.cpp 1533-):
// 遍历自动常量,按类型写入物理缓冲;ACT_TIME 用传入的当前时间
void updateAutoParams(float time) {
for (const auto& entry : mAutoConstants) {
switch (entry.paramType) {
case ACT_TIME:
writeRawConstant(entry.physicalIndex, time);
break;
default:
break;
}
}
}
private:
static uint16_t deriveVariability(AutoConstantType t) {
return t == ACT_TIME ? 1u : 2u; // 简化:时间逐帧变化,矩阵逐对象变化
}
NamedConstantMap mNamedConstants;
std::vector<float> mConstants; // 对应 ConstantList mConstants
std::vector<AutoConstantEntry> mAutoConstants; // 对应 AutoConstantList mAutoConstants
};
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
// 命名常量表:world_matrix 从 0 起、view_matrix 从 4 起、bones[3] 数组从 16 起
GpuProgramParameters::NamedConstantMap defs;
defs["world_matrix"] = {0u, 4u, 1u, true};
defs["view_matrix"] = {4u, 4u, 1u, true};
defs["bones"] = {16u, 4u, 3u, true};
GpuProgramParameters params;
params.setNamedConstants(defs);
// 不存在的名字被忽略(mIgnoreMissingParams 语义)
params.setNamedConstant("nope", 1.0f);
CHECK(params.findNamedConstantDefinition("nope") == nullptr);
// 命名常量写入物理缓冲
params.setNamedConstant("world_matrix", 0.5f);
CHECK(params.readRawConstant(0u) == 0.5f);
// 数组下标换算物理偏移:bones[2] -> 16 + 2*4 = 24
params.setNamedConstant("bones[0]", 1.0f);
params.setNamedConstant("bones[2]", 3.0f);
CHECK(params.readRawConstant(16u) == 1.0f);
CHECK(params.readRawConstant(24u) == 3.0f);
CHECK(params.readRawConstant(20u) == 0.0f); // bones[1] 未写
// 自动常量按逻辑索引注册
params.setAutoConstant(0u, ACT_WORLD_MATRIX);
CHECK(params.hasAutoConstants());
CHECK(params.getAutoConstantCount() == 1);
CHECK(params.getAutoConstants()[0].physicalIndex == 0u);
CHECK(params.getAutoConstants()[0].paramType == ACT_WORLD_MATRIX);
// 按名字注册自动常量:定位到 view_matrix 的物理偏移 4
params.setNamedAutoConstant("view_matrix", ACT_VIEW_MATRIX);
CHECK(params.getAutoConstantCount() == 2);
CHECK(params.getAutoConstants()[1].physicalIndex == 4u);
// 额外信息(如光索引)存在 data 里
params.setAutoConstant(8u, ACT_TIME, 0u);
CHECK(params.getAutoConstants()[2].data == 0u);
params.setAutoConstant(9u, ACT_TIME, 3u);
CHECK(params.getAutoConstants()[3].data == 3u);
// _updateAutoParams 只刷新 TIME 类型,矩阵类留给 AutoParamDataSource
params.updateAutoParams(12.5f);
CHECK(params.readRawConstant(8u) == 12.5f);
CHECK(params.readRawConstant(9u) == 12.5f);
CHECK(params.readRawConstant(0u) == 0.5f); // world_matrix 未被自动常量覆盖
// 全部自动常量:world + view + 两个 time
CHECK(params.getAutoConstantCount() == 4);
return lab::report("06-2 着色器参数绑定");
}
本机实测(Apple clang,clang++ -std=c++20 -Wall):编译通过(零警告),断言 17/17 通过。
小结
- 命名常量:名字 →
GpuConstantDefinition→physicalIndex,setNamedConstant查表后写缓冲。 _findNamedConstantDefinition先剥数组下标再查表,且拒绝给非数组名加下标。withArrayOffset按physicalIndex + offset * elementSize换算数组元素位置。- 自动常量以
AutoConstantEntry登记(physicalIndex+paramType+data/fData),_updateAutoParams按 variability 掩码刷新。 setNamedAutoConstant比setAutoConstant多一步名字解析,把名字翻译成物理索引。
阅读导航:上一节:6.1 高级着色器程序 · 下一节:6.3 着色器变体 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。