Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(rhi): loose uniforms ride a std140 DrawParams UBO — WebGPU gap 1

yhh4c53852919b3
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 671973c2f..9c9afc199 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -45,6 +45,7 @@ set(ESENGINE_SOURCES
src/esengine/resource/ShaderParser.cpp
src/esengine/renderer/RenderContext.cpp
src/esengine/renderer/Shader.cpp
+ src/esengine/renderer/DrawParams.cpp
src/esengine/renderer/Buffer.cpp
src/esengine/renderer/Texture.cpp
src/esengine/renderer/Framebuffer.cpp
diff --git a/sdk/src/camera/editorGridRenderer.ts b/sdk/src/camera/editorGridRenderer.ts
index 39b7c61d7..2c5a1fead 100644
--- a/sdk/src/camera/editorGridRenderer.ts
+++ b/sdk/src/camera/editorGridRenderer.ts
@@ -29,11 +29,14 @@ import { registerPreSceneDrawCallback } from '../customDraw';
import { EditorView } from './EditorView';
import { EditorGrid, DEFAULT_EDITOR_GRID } from './EditorGrid';
-const GRID_VERT = `
-attribute vec2 a_position;
+// GLSL ES 3.0, so the engine lifts the loose uniforms into its std140
+// DrawParams block — this draw's parameters ride the UBO seam, not per-program
+// uniform uploads.
+const GRID_VERT = `#version 300 es
+in vec2 a_position;
uniform mat4 u_projection;
uniform mat4 u_model;
-varying vec2 v_world;
+out vec2 v_world;
void main() {
vec4 wp = u_model * vec4(a_position, 0.0, 1.0);
v_world = wp.xy;
@@ -41,9 +44,9 @@ void main() {
}
`;
-const GRID_FRAG = `
+const GRID_FRAG = `#version 300 es
precision highp float;
-varying vec2 v_world;
+in vec2 v_world;
uniform float u_param0; // minor spacing (world units)
uniform float u_param1; // major every Nth line
uniform float u_param2; // worldPerPixel
@@ -51,6 +54,7 @@ uniform vec4 u_color; // minor line color
uniform vec4 u_vec0; // major line color
uniform vec4 u_vec1; // X axis (world y=0) color
uniform vec4 u_vec2; // Y axis (world x=0) color
+out vec4 fragColor;
float lineCov(float coord, float sp, float lw, float aa) {
float d = abs(mod(coord + sp * 0.5, sp) - sp * 0.5);
@@ -83,7 +87,7 @@ void main() {
c = over(vec4(u_vec1.rgb, u_vec1.a * axisXC), c);
c = over(vec4(u_vec2.rgb, u_vec2.a * axisYC), c);
if (c.a <= 0.0) discard;
- gl_FragColor = c;
+ fragColor = c;
}
`;
diff --git a/src/esengine/bindings/GeometryBindings.cpp b/src/esengine/bindings/GeometryBindings.cpp
index d009501e1..9ac161ee1 100644
--- a/src/esengine/bindings/GeometryBindings.cpp
+++ b/src/esengine/bindings/GeometryBindings.cpp
@@ -145,6 +145,7 @@ void draw_mesh(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr) {
applyMeshPipeline(*g_device, *shader, *geom);
shader->setUniform("u_projection", g_currentViewProjection);
shader->setUniform("u_model", transform);
+ shader->commitParams();
geom->bind(ctx().require<GfxDevice>());
@@ -233,6 +234,10 @@ void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t trans
}
}
+ // Lifted uniforms (everything above except the sampler slots) live in the
+ // shader's DrawParams block; flush + bind them for this draw.
+ shader->commitParams();
+
geom->bind(ctx().require<GfxDevice>());
if (geom->hasIndices()) {
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index f321341a5..db1af655e 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -148,7 +148,9 @@ u32 compileEsshader(const std::string& source, const std::string& featuresCsv) {
}
const std::string vert = resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "", features);
const std::string frag = resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment, "", features);
- resource::ShaderHandle handle = rm->createShader(vert, frag);
+ // No DrawParams rewrite: assembled material sources already carry their
+ // params in MaterialConstants; only sampler uniforms remain loose.
+ resource::ShaderHandle handle = rm->createShader(vert, frag, /*rewriteLoose=*/false);
if (!handle.isValid()) return 0;
if (auto* rc = g_renderContext) {
if (Shader* s = rm->getShader(handle)) {
diff --git a/src/esengine/renderer/DrawParams.cpp b/src/esengine/renderer/DrawParams.cpp
new file mode 100644
index 000000000..aa5ff7573
--- /dev/null
+++ b/src/esengine/renderer/DrawParams.cpp
@@ -0,0 +1,219 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file DrawParams.cpp
+ * @brief Loose-uniform → std140 DrawParams block rewriter.
+ */
+
+#include "DrawParams.hpp"
+
+#include <cctype>
+
+namespace esengine {
+
+const DrawParamSlot* DrawParamsLayout::find(const std::string& name) const {
+ for (const auto& s : slots) {
+ if (s.name == name) return &s;
+ }
+ return nullptr;
+}
+
+void drawParamSizeAlign(DrawParamType t, u32& size, u32& align) {
+ switch (t) {
+ case DrawParamType::Float:
+ case DrawParamType::Int: size = 4; align = 4; break;
+ case DrawParamType::Vec2: size = 8; align = 8; break;
+ case DrawParamType::Vec3: size = 12; align = 16; break;
+ case DrawParamType::Vec4: size = 16; align = 16; break;
+ // std140 matrices are column arrays with vec4 stride.
+ case DrawParamType::Mat3: size = 48; align = 16; break;
+ case DrawParamType::Mat4: size = 64; align = 16; break;
+ }
+}
+
+namespace {
+
+struct LooseDecl {
+ std::string name;
+ std::string member; ///< Block-member text, e.g. "highp vec2 u_resolution;"
+ DrawParamType type = DrawParamType::Float;
+ usize begin = 0; ///< Byte range of the declaration line (excl. trailing newline).
+ usize end = 0;
+};
+
+bool typeFromToken(const std::string& tok, DrawParamType& out) {
+ if (tok == "float") { out = DrawParamType::Float; return true; }
+ if (tok == "int") { out = DrawParamType::Int; return true; }
+ if (tok == "vec2") { out = DrawParamType::Vec2; return true; }
+ if (tok == "vec3") { out = DrawParamType::Vec3; return true; }
+ if (tok == "vec4") { out = DrawParamType::Vec4; return true; }
+ if (tok == "mat3") { out = DrawParamType::Mat3; return true; }
+ if (tok == "mat4") { out = DrawParamType::Mat4; return true; }
+ return false;
+}
+
+bool isIdentChar(char c) {
+ return std::isalnum(static_cast<unsigned char>(c)) || c == '_';
+}
+
+/** Splits a line into whitespace-separated tokens, treating ';' as its own token. */
+std::vector<std::string> tokenize(const std::string& line) {
+ std::vector<std::string> tokens;
+ std::string cur;
+ for (char c : line) {
+ if (std::isspace(static_cast<unsigned char>(c))) {
+ if (!cur.empty()) { tokens.push_back(cur); cur.clear(); }
+ } else if (c == ';') {
+ if (!cur.empty()) { tokens.push_back(cur); cur.clear(); }
+ tokens.push_back(";");
+ } else {
+ cur += c;
+ }
+ }
+ if (!cur.empty()) tokens.push_back(cur);
+ return tokens;
+}
+
+/**
+ * Collects liftable loose uniform declarations. Line-based: a declaration must
+ * be `uniform [precision] <type> <name>;` on one line (matches how every
+ * in-tree and SDK-authored shader writes them). Lines inside block comments and
+ * text after `//` are ignored; anything the grammar doesn't cover is left
+ * loose (safe: GL keeps handling loose uniforms).
+ */
+std::vector<LooseDecl> collectLooseDecls(const std::string& src) {
+ std::vector<LooseDecl> out;
+ bool inBlockComment = false;
+
+ usize lineStart = 0;
+ while (lineStart < src.size()) {
+ usize lineEnd = src.find('\n', lineStart);
+ if (lineEnd == std::string::npos) lineEnd = src.size();
+ std::string line = src.substr(lineStart, lineEnd - lineStart);
+
+ // Resolve comment state: drop /*...*/ segments (line-local or spanning).
+ std::string code;
+ code.reserve(line.size());
+ for (usize i = 0; i < line.size();) {
+ if (inBlockComment) {
+ usize close = line.find("*/", i);
+ if (close == std::string::npos) { i = line.size(); break; }
+ inBlockComment = false;
+ i = close + 2;
+ } else if (line.compare(i, 2, "/*") == 0) {
+ inBlockComment = true;
+ i += 2;
+ } else if (line.compare(i, 2, "//") == 0) {
+ break;
+ } else {
+ code += line[i++];
+ }
+ }
+
+ const auto tokens = tokenize(code);
+ // uniform [precision] type name ;
+ if (tokens.size() >= 4 && tokens[0] == "uniform" && tokens.back() == ";") {
+ usize t = 1;
+ std::string precision;
+ if (tokens[t] == "highp" || tokens[t] == "mediump" || tokens[t] == "lowp") {
+ precision = tokens[t];
+ ++t;
+ }
+ DrawParamType type;
+ // Exactly: type name ; — anything longer (initializer, extra
+ // declarator) or shorter is not a liftable declaration.
+ if (tokens.size() == t + 3 && typeFromToken(tokens[t], type)) {
+ const std::string& name = tokens[t + 1];
+ bool identOk = !name.empty() && !std::isdigit(static_cast<unsigned char>(name[0]));
+ for (char c : name) identOk = identOk && isIdentChar(c);
+ if (identOk) {
+ LooseDecl d;
+ d.name = name;
+ d.type = type;
+ d.member = (precision.empty() ? "" : precision + " ") + tokens[t] + " " + name + ";";
+ d.begin = lineStart;
+ d.end = lineEnd;
+ out.push_back(std::move(d));
+ }
+ }
+ }
+
+ lineStart = lineEnd + 1;
+ }
+ return out;
+}
+
+/** Replaces each decl's line with `replacementForFirst` (first) or nothing (rest). */
+std::string applyRewrite(const std::string& src, const std::vector<LooseDecl>& decls,
+ const std::string& blockText) {
+ std::string out = src;
+ // Back to front so byte ranges stay valid.
+ for (usize i = decls.size(); i-- > 0;) {
+ const auto& d = decls[i];
+ out.replace(d.begin, d.end - d.begin, i == 0 ? blockText : "");
+ }
+ return out;
+}
+
+} // namespace
+
+DrawParamsRewrite rewriteLooseUniforms(const std::string& vertexSrc, const std::string& fragmentSrc) {
+ DrawParamsRewrite result{vertexSrc, fragmentSrc, {}};
+
+ // Uniform blocks need GLSL ES 3.0 — a 1.00 source (no #version 300
+ // directive; attribute/varying style) keeps its loose uniforms, which GL
+ // handles as before.
+ if (vertexSrc.find("#version 300") == std::string::npos ||
+ fragmentSrc.find("#version 300") == std::string::npos) {
+ return result;
+ }
+
+ // A source that already mentions the block name authored its own layout —
+ // do not stack a second definition on top.
+ if (vertexSrc.find(DRAW_PARAMS_BLOCK) != std::string::npos ||
+ fragmentSrc.find(DRAW_PARAMS_BLOCK) != std::string::npos) {
+ return result;
+ }
+
+ const auto vsDecls = collectLooseDecls(vertexSrc);
+ const auto fsDecls = collectLooseDecls(fragmentSrc);
+ if (vsDecls.empty() && fsDecls.empty()) return result;
+
+ // Union of both stages in first-appearance order; both stages must agree on
+ // a shared name's type (else the program is broken regardless — leave the
+ // sources for the linker to report).
+ std::vector<const LooseDecl*> unionDecls;
+ for (const auto* decls : {&vsDecls, &fsDecls}) {
+ for (const auto& d : *decls) {
+ const LooseDecl* seen = nullptr;
+ for (const auto* u : unionDecls) {
+ if (u->name == d.name) { seen = u; break; }
+ }
+ if (seen == nullptr) {
+ unionDecls.push_back(&d);
+ } else if (seen->type != d.type) {
+ return result;
+ }
+ }
+ }
+
+ auto alignUp = [](u32 v, u32 a) -> u32 { return (v + a - 1) & ~(a - 1); };
+ u32 offset = 0;
+ std::string blockText = std::string("layout(std140) uniform ") + DRAW_PARAMS_BLOCK + " {\n";
+ for (const auto* d : unionDecls) {
+ u32 size = 0, align = 0;
+ drawParamSizeAlign(d->type, size, align);
+ offset = alignUp(offset, align);
+ result.layout.slots.push_back({d->name, d->type, offset});
+ offset += size;
+ blockText += " " + d->member + "\n";
+ }
+ blockText += "};";
+ result.layout.blockSize = alignUp(offset, 16);
+
+ if (!vsDecls.empty()) result.vertexSrc = applyRewrite(vertexSrc, vsDecls, blockText);
+ if (!fsDecls.empty()) result.fragmentSrc = applyRewrite(fragmentSrc, fsDecls, blockText);
+ return result;
+}
+
+} // namespace esengine
diff --git a/src/esengine/renderer/DrawParams.hpp b/src/esengine/renderer/DrawParams.hpp
new file mode 100644
index 000000000..85bd24fa6
--- /dev/null
+++ b/src/esengine/renderer/DrawParams.hpp
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file DrawParams.hpp
+ * @brief Per-draw shader parameter block — the UBO home for what used to be
+ * loose uniforms.
+ * @details Shaders created through ResourceManager::createShader (user draw
+ * shaders, post-process effects) may declare loose non-sampler
+ * uniforms; rewriteLooseUniforms() lifts those declarations into one
+ * `layout(std140) uniform DrawParams { ... }` block and reports the
+ * member layout. Shader keeps a CPU shadow of the block: setUniform
+ * writes land in the shadow by std140 offset and commitParams()
+ * uploads + binds the shader's UBO at DRAW_PARAMS_BINDING before the
+ * draw. Samplers stay loose uniforms (GL sampler units; bind-group
+ * entries on future backends). The setUniform authoring surface is
+ * unchanged while all uniform DATA flows through the buffer seam a
+ * WebGPU backend requires.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+#include "../core/Types.hpp"
+
+#include <string>
+#include <vector>
+
+namespace esengine {
+
+/** @brief Indexed UBO binding point for the per-draw DrawParams block.
+ * (0 = FrameConstants, 1 = MaterialConstants, 2 = LightConstants, 3 = TimeConstants.) */
+inline constexpr u32 DRAW_PARAMS_BINDING = 4;
+
+/** @brief GLSL block name; must match the rewriter's generated block + Shader::compile lookup. */
+inline constexpr const char* DRAW_PARAMS_BLOCK = "DrawParams";
+
+/**
+ * @brief Size of the zeroed fallback UBO RenderContext binds at DRAW_PARAMS_BINDING
+ * each frame.
+ * @details A draw path that never calls commitParams (e.g. a raw material shader
+ * drawn by the batch path) still needs SOME buffer bound that covers its
+ * block, or WebGL rejects the draw; the fallback makes unset members read
+ * zero — exactly what their loose-uniform ancestors read. Adoption warns
+ * if a shader's block ever exceeds this.
+ */
+inline constexpr u32 DRAW_PARAMS_FALLBACK_SIZE = 4096;
+
+/** @brief GLSL type of one lifted uniform (the subset the rewriter supports). */
+enum class DrawParamType : u8 { Float, Int, Vec2, Vec3, Vec4, Mat3, Mat4 };
+
+/** @brief One lifted uniform's slot in a shader's std140 DrawParams block. */
+struct DrawParamSlot {
+ std::string name;
+ DrawParamType type = DrawParamType::Float;
+ u32 offset = 0; ///< std140 byte offset within the block.
+};
+
+/** @brief A shader's DrawParams layout: lifted members + 16-aligned block size. */
+struct DrawParamsLayout {
+ std::vector<DrawParamSlot> slots;
+ u32 blockSize = 0; ///< 0 ⇒ the shader has no DrawParams block.
+
+ bool empty() const { return blockSize == 0; }
+ const DrawParamSlot* find(const std::string& name) const;
+};
+
+/** @brief std140 size/base-alignment of a supported param type. */
+void drawParamSizeAlign(DrawParamType t, u32& size, u32& align);
+
+/** @brief Result of rewriteLooseUniforms; layout.empty() ⇒ sources unchanged. */
+struct DrawParamsRewrite {
+ std::string vertexSrc;
+ std::string fragmentSrc;
+ DrawParamsLayout layout;
+};
+
+/**
+ * @brief Lifts loose non-sampler uniform declarations out of both stages into
+ * one shared std140 DrawParams block.
+ * @details Handles single-declarator float/int/vec2/vec3/vec4/mat3/mat4
+ * declarations (optional precision qualifier); arrays, initializers,
+ * multi-declarator lines, samplers and struct types stay loose and
+ * untouched. Both stages share ONE block definition (GLSL requires
+ * identical redeclarations), inserted where each stage's first lifted
+ * declaration was. Returns the inputs unchanged when nothing lifts,
+ * when the same name is declared with two types, or when the source
+ * already mentions the DrawParams block name.
+ */
+DrawParamsRewrite rewriteLooseUniforms(const std::string& vertexSrc, const std::string& fragmentSrc);
+
+} // namespace esengine
diff --git a/src/esengine/renderer/PostProcessPipeline.cpp b/src/esengine/renderer/PostProcessPipeline.cpp
index cd2653264..55c1fd6dd 100644
--- a/src/esengine/renderer/PostProcessPipeline.cpp
+++ b/src/esengine/renderer/PostProcessPipeline.cpp
@@ -375,6 +375,10 @@ void PostProcessPipeline::renderPass(const PostProcessPass& pass, TextureHandle
if (shader->hasUniform(name)) shader->setUniform(name, value);
}
+ // Effect parameters live in the shader's DrawParams block (lifted at
+ // creation); flush + bind them for this draw.
+ shader->commitParams();
+
drawScreenQuad();
}
@@ -408,6 +412,7 @@ void PostProcessPipeline::blitToOutput(TextureHandle texture) {
applyPassPipeline(*shader);
shader->setUniform("u_texture", 0);
+ shader->commitParams();
drawScreenQuad();
}
diff --git a/src/esengine/renderer/RenderContext.cpp b/src/esengine/renderer/RenderContext.cpp
index fc454e48f..d00b3fc0f 100644
--- a/src/esengine/renderer/RenderContext.cpp
+++ b/src/esengine/renderer/RenderContext.cpp
@@ -14,8 +14,11 @@
#include "RenderContext.hpp"
#include "GfxDevice.hpp"
#include "FrameConstants.hpp"
+#include "DrawParams.hpp"
#include "../core/Log.hpp"
+#include <vector>
+
#include <glm/gtc/type_ptr.hpp>
namespace esengine {
@@ -114,12 +117,26 @@ void RenderContext::initFrameUbo() {
{GfxBufferUsage::Uniform, static_cast<u32>(sizeof(TimeConstants)), /*dynamic=*/true}, &time);
device_.setUniformBuffer(TIME_CONSTANTS_BINDING, timeUbo_);
+ // Zeroed fallback for the shared per-draw params slot: a shader whose loose
+ // uniforms were lifted into a DrawParams block but whose draw path never
+ // commits (e.g. a raw material shader drawn by the batch path) must still
+ // find a buffer covering its block there — members then read zero, exactly
+ // what their loose-uniform ancestors read.
+ const std::vector<u8> zeros(DRAW_PARAMS_FALLBACK_SIZE, 0);
+ drawParamsFallback_ = device_.createBuffer(
+ {GfxBufferUsage::Uniform, DRAW_PARAMS_FALLBACK_SIZE, /*dynamic=*/false}, zeros.data());
+ device_.setUniformBuffer(DRAW_PARAMS_BINDING, drawParamsFallback_);
+
ES_LOG_DEBUG("FrameConstants UBO created (handle: {})", static_cast<u32>(frameUbo_));
}
void RenderContext::updateFrameConstants(const glm::mat4& viewProjection) {
viewProjection_ = viewProjection;
device_.updateBuffer(frameUbo_, 0, glm::value_ptr(viewProjection), sizeof(glm::mat4));
+ // Re-arm the params fallback for this pass: a post-process or custom-draw
+ // commit from the previous pass left its own (differently sized) buffer on
+ // the shared slot.
+ device_.setUniformBuffer(DRAW_PARAMS_BINDING, drawParamsFallback_);
}
void RenderContext::setFrameTime(f32 elapsedSec, u32 viewportW, u32 viewportH) {
diff --git a/src/esengine/renderer/RenderContext.hpp b/src/esengine/renderer/RenderContext.hpp
index 8ae67fb7c..e35b8ac5e 100644
--- a/src/esengine/renderer/RenderContext.hpp
+++ b/src/esengine/renderer/RenderContext.hpp
@@ -191,6 +191,7 @@ private:
TextureHandle flatNormalTexture_ = TextureHandle::Invalid;
BufferHandle frameUbo_ = BufferHandle::Invalid;
BufferHandle timeUbo_ = BufferHandle::Invalid;
+ BufferHandle drawParamsFallback_ = BufferHandle::Invalid;
f32 lastElapsed_ = 0.0f;
MaterialStore materials_;
LightStore lights_;
diff --git a/src/esengine/renderer/Shader.cpp b/src/esengine/renderer/Shader.cpp
index 49a31a261..d24c36b81 100644
--- a/src/esengine/renderer/Shader.cpp
+++ b/src/esengine/renderer/Shader.cpp
@@ -21,15 +21,22 @@
#include "LightConstants.hpp"
#include "../core/Log.hpp"
+#include <cstring>
#include <fstream>
#include <vector>
namespace esengine {
Shader::~Shader() {
- if (program_ != ShaderHandle::Invalid && device_) {
- device_->deleteProgram(program_);
- program_ = ShaderHandle::Invalid;
+ if (device_) {
+ if (program_ != ShaderHandle::Invalid) {
+ device_->deleteProgram(program_);
+ program_ = ShaderHandle::Invalid;
+ }
+ if (paramsUbo_ != BufferHandle::Invalid) {
+ device_->deleteBuffer(paramsUbo_);
+ paramsUbo_ = BufferHandle::Invalid;
+ }
}
}
@@ -38,21 +45,32 @@ Shader::Shader(Shader&& other) noexcept
, program_(other.program_)
, uniformCache_(std::move(other.uniformCache_))
, attribCache_(std::move(other.attribCache_))
- , activeUniforms_(std::move(other.activeUniforms_)) {
+ , activeUniforms_(std::move(other.activeUniforms_))
+ , drawParams_(std::move(other.drawParams_))
+ , paramsShadow_(std::move(other.paramsShadow_))
+ , paramsDirty_(other.paramsDirty_)
+ , paramsUbo_(other.paramsUbo_) {
other.program_ = ShaderHandle::Invalid;
+ other.paramsUbo_ = BufferHandle::Invalid;
}
Shader& Shader::operator=(Shader&& other) noexcept {
if (this != &other) {
- if (program_ != ShaderHandle::Invalid && device_) {
- device_->deleteProgram(program_);
+ if (device_) {
+ if (program_ != ShaderHandle::Invalid) device_->deleteProgram(program_);
+ if (paramsUbo_ != BufferHandle::Invalid) device_->deleteBuffer(paramsUbo_);
}
device_ = other.device_;
program_ = other.program_;
uniformCache_ = std::move(other.uniformCache_);
attribCache_ = std::move(other.attribCache_);
activeUniforms_ = std::move(other.activeUniforms_);
+ drawParams_ = std::move(other.drawParams_);
+ paramsShadow_ = std::move(other.paramsShadow_);
+ paramsDirty_ = other.paramsDirty_;
+ paramsUbo_ = other.paramsUbo_;
other.program_ = ShaderHandle::Invalid;
+ other.paramsUbo_ = BufferHandle::Invalid;
}
return *this;
}
@@ -185,6 +203,13 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSr
device_->uniformBlockBinding(program_, timeBlock, TIME_CONSTANTS_BINDING);
}
+ // Same for the per-draw params block (rewriteLooseUniforms generates it for
+ // shaders whose loose uniforms were lifted); commitParams binds the UBO.
+ u32 drawParamsBlock = device_->getUniformBlockIndex(program_, DRAW_PARAMS_BLOCK);
+ if (drawParamsBlock != GFX_INVALID_UNIFORM_BLOCK) {
+ device_->uniformBlockBinding(program_, drawParamsBlock, DRAW_PARAMS_BINDING);
+ }
+
ES_LOG_DEBUG("Shader compiled successfully (program handle: {}, active uniforms: {})",
static_cast<u32>(program_), activeUniforms_.size());
return true;
@@ -225,34 +250,94 @@ i32 Shader::getUniformLocation(const std::string& name) const {
}
bool Shader::hasUniform(const std::string& name) const {
+ // A lifted uniform is a block member: it has no location, but callers that
+ // guard with hasUniform (e.g. the post-process pass loop) must still see it.
+ if (drawParams_.find(name) != nullptr) return true;
return cacheUniformLocation(name, /*warnOnMiss=*/false) >= 0;
}
+void Shader::adoptDrawParams(DrawParamsLayout layout) {
+ drawParams_ = std::move(layout);
+ paramsShadow_.assign(drawParams_.blockSize, 0);
+ paramsDirty_ = false; // commitParams creates the UBO from the zeroed shadow
+ if (drawParams_.blockSize > DRAW_PARAMS_FALLBACK_SIZE) {
+ ES_LOG_WARN("Shader {}: DrawParams block ({} bytes) exceeds the frame fallback ({}); "
+ "draws that skip commitParams may be rejected",
+ static_cast<u32>(program_), drawParams_.blockSize, DRAW_PARAMS_FALLBACK_SIZE);
+ }
+}
+
+void Shader::commitParams() {
+ if (drawParams_.empty() || !device_) return;
+ if (paramsUbo_ == BufferHandle::Invalid) {
+ paramsUbo_ = device_->createBuffer(
+ {GfxBufferUsage::Uniform, drawParams_.blockSize, /*dynamic=*/true}, paramsShadow_.data());
+ paramsDirty_ = false;
+ } else if (paramsDirty_) {
+ device_->updateBuffer(paramsUbo_, 0, paramsShadow_.data(), drawParams_.blockSize);
+ paramsDirty_ = false;
+ }
+ // Rebind even when clean: the slot is shared, another shader's commit (or
+ // the frame fallback) owns it otherwise.
+ device_->setUniformBuffer(DRAW_PARAMS_BINDING, paramsUbo_);
+}
+
+bool Shader::writeParam(const std::string& name, DrawParamType type, const void* src) const {
+ const DrawParamSlot* slot = drawParams_.find(name);
+ if (slot == nullptr) return false;
+ if (slot->type != type) {
+ ES_LOG_WARN("Shader {}: setUniform('{}') type mismatch with its DrawParams slot",
+ static_cast<u32>(program_), name);
+ return true; // consumed: the name has no loose location to fall back to
+ }
+ u8* dst = paramsShadow_.data() + slot->offset;
+ if (type == DrawParamType::Mat3) {
+ // std140 mat3 columns have vec4 stride; glm::mat3 is 3 packed vec3s.
+ const f32* m = static_cast<const f32*>(src);
+ for (u32 col = 0; col < 3; ++col) {
+ std::memcpy(dst + col * 16, m + col * 3, 3 * sizeof(f32));
+ }
+ } else {
+ u32 size = 0, align = 0;
+ drawParamSizeAlign(type, size, align);
+ std::memcpy(dst, src, size);
+ }
+ paramsDirty_ = true;
+ return true;
+}
+
void Shader::setUniform(const std::string& name, i32 value) const {
+ if (writeParam(name, DrawParamType::Int, &value)) return;
device_->setUniform1i(getUniformLocation(name), value);
}
void Shader::setUniform(const std::string& name, f32 value) const {
+ if (writeParam(name, DrawParamType::Float, &value)) return;
device_->setUniform1f(getUniformLocation(name), value);
}
void Shader::setUniform(const std::string& name, const glm::vec2& value) const {
+ if (writeParam(name, DrawParamType::Vec2, glm::value_ptr(value))) return;
device_->setUniform2f(getUniformLocation(name), value.x, value.y);
}
void Shader::setUniform(const std::string& name, const glm::vec3& value) const {
+ if (writeParam(name, DrawParamType::Vec3, glm::value_ptr(value))) return;
device_->setUniform3f(getUniformLocation(name), value.x, value.y, value.z);
}
void Shader::setUniform(const std::string& name, const glm::vec4& value) const {
+ if (writeParam(name, DrawParamType::Vec4, glm::value_ptr(value))) return;
device_->setUniform4f(getUniformLocation(name), value.x, value.y, value.z, value.w);
}
void Shader::setUniform(const std::string& name, const glm::mat3& value) const {
+ if (writeParam(name, DrawParamType::Mat3, glm::value_ptr(value))) return;
device_->setUniformMat3(getUniformLocation(name), glm::value_ptr(value));
}
void Shader::setUniform(const std::string& name, const glm::mat4& value) const {
+ if (writeParam(name, DrawParamType::Mat4, glm::value_ptr(value))) return;
device_->setUniformMat4(getUniformLocation(name), glm::value_ptr(value));
}
diff --git a/src/esengine/renderer/Shader.hpp b/src/esengine/renderer/Shader.hpp
index d7897a9f9..cac7d5c50 100644
--- a/src/esengine/renderer/Shader.hpp
+++ b/src/esengine/renderer/Shader.hpp
@@ -21,6 +21,7 @@
// Project includes
#include "../core/Types.hpp"
#include "../math/Math.hpp"
+#include "DrawParams.hpp"
#include "GfxEnums.hpp"
// Standard library
@@ -198,6 +199,31 @@ public:
/** @brief Returns reflected metadata for every active uniform, populated at link time */
const std::vector<GfxUniformInfo>& getActiveUniforms() const { return activeUniforms_; }
+ // =========================================================================
+ // DrawParams (per-draw parameter block)
+ // =========================================================================
+
+ /**
+ * @brief Adopts the layout rewriteLooseUniforms produced for this program.
+ * @details Allocates the zeroed CPU shadow, so unset members read 0 — the
+ * same value their loose-uniform ancestors read. From here on the
+ * name-based setUniform overloads write into the shadow instead of
+ * issuing loose uniform uploads; commitParams() flushes it.
+ */
+ void adoptDrawParams(DrawParamsLayout layout);
+
+ /** @brief True when this program carries a DrawParams block. */
+ bool hasDrawParams() const { return !drawParams_.empty(); }
+
+ /**
+ * @brief Uploads the shadow (when dirty) and binds this shader's params UBO
+ * at DRAW_PARAMS_BINDING.
+ * @details Call before any draw with this shader — the binding slot is
+ * shared, so the previous committer's buffer is bound otherwise.
+ * No-op for shaders without a DrawParams block.
+ */
+ void commitParams();
+
// =========================================================================
// State
// =========================================================================
@@ -231,6 +257,10 @@ private:
/** @brief Resolve + cache a uniform location; warns on miss only when asked. */
i32 cacheUniformLocation(const std::string& name, bool warnOnMiss) const;
+ /** @brief Writes a param into the shadow if `name` is a DrawParams member.
+ * @return True when consumed (caller must not fall through to a loose upload). */
+ bool writeParam(const std::string& name, DrawParamType type, const void* src) const;
+
GfxDevice* device_ = nullptr; ///< Set by the create* factories; all GL goes through it.
ShaderHandle program_ = ShaderHandle::Invalid;
@@ -238,6 +268,13 @@ private:
mutable std::unordered_map<std::string, i32> uniformCache_;
mutable std::unordered_map<std::string, i32> attribCache_;
std::vector<GfxUniformInfo> activeUniforms_;
+
+ DrawParamsLayout drawParams_;
+ /// CPU shadow of the DrawParams block (mutable: the const name-based
+ /// setUniform overloads write here, mirroring the mutable location cache).
+ mutable std::vector<u8> paramsShadow_;
+ mutable bool paramsDirty_ = false;
+ BufferHandle paramsUbo_ = BufferHandle::Invalid;
};
} // namespace esengine
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index 0baabd1f0..1e99f45a2 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -64,8 +64,30 @@ void ResourceManager::update() {
// Shader Resources
// =============================================================================
-ShaderHandle ResourceManager::createShader(const std::string& vertSrc, const std::string& fragSrc) {
+ShaderHandle ResourceManager::createShader(const std::string& vertSrc, const std::string& fragSrc,
+ bool rewriteLoose) {
if (!device_) return {};
+
+ // Lift loose non-sampler uniforms into a std140 DrawParams block, so this
+ // shader's parameters flow through the UBO seam (setUniform writes the CPU
+ // shadow; commitParams uploads + binds). ShaderParser-assembled material
+ // sources pass rewriteLoose=false: their params already live in
+ // MaterialConstants and only sampler uniforms remain loose.
+ if (rewriteLoose) {
+ DrawParamsRewrite rw = rewriteLooseUniforms(vertSrc, fragSrc);
+ if (!rw.layout.empty()) {
+ auto shader = Shader::create(*device_, rw.vertexSrc, rw.fragmentSrc);
+ if (shader) {
+ shader->adoptDrawParams(std::move(rw.layout));
+ return shaders_.add(std::move(shader));
+ }
+ // The unmodified source is the author's ground truth — if the lifted
+ // form fails to compile (a rewriter blind spot), fall back to it
+ // loudly rather than failing a shader that used to work.
+ ES_LOG_WARN("DrawParams rewrite failed to compile; retrying shader with loose uniforms");
+ }
+ }
+
auto shader = Shader::create(*device_, vertSrc, fragSrc);
if (!shader) {
ES_LOG_ERROR("Failed to create shader from source");
diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hpp
index 602b57849..0b8439266 100644
--- a/src/esengine/resource/ResourceManager.hpp
+++ b/src/esengine/resource/ResourceManager.hpp
@@ -131,9 +131,14 @@ public:
* @brief Creates a shader from source strings
* @param vertSrc Vertex shader GLSL source
* @param fragSrc Fragment shader GLSL source
+ * @param rewriteLoose Lift loose non-sampler uniforms into a std140
+ * DrawParams block (see renderer/DrawParams.hpp). Pass false for
+ * sources whose uniform blocks are already assembled (ShaderParser
+ * material output).
* @return Handle to the shader, or invalid handle on failure
*/
- ShaderHandle createShader(const std::string& vertSrc, const std::string& fragSrc);
+ ShaderHandle createShader(const std::string& vertSrc, const std::string& fragSrc,
+ bool rewriteLoose = true);
ShaderHandle createShaderWithBindings(const std::string& vertSrc, const std::string& fragSrc,
std::initializer_list<AttribBinding> bindings);
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index c90c5e66c..fd8eaaf10 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -51,6 +51,7 @@ add_test(NAME test_resource_pool COMMAND test_resource_pool)
add_executable(test_shader_device
renderer/test_shader_device.cpp
${CMAKE_SOURCE_DIR}/src/esengine/renderer/Shader.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/DrawParams.cpp
${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp
)
target_include_directories(test_shader_device PRIVATE
@@ -59,6 +60,21 @@ target_include_directories(test_shader_device PRIVATE
)
add_test(NAME test_shader_device COMMAND test_shader_device)
+# DrawParams: the loose-uniform → std140 block rewriter + the Shader facade that
+# routes setUniform writes into the params UBO seam (MockGfxDevice asserts no
+# loose uploads for lifted members).
+add_executable(test_draw_params
+ renderer/test_draw_params.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/Shader.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/renderer/DrawParams.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp
+)
+target_include_directories(test_draw_params PRIVATE
+ ${CMAKE_SOURCE_DIR}/src
+ ${CMAKE_SOURCE_DIR}/third_party/glm
+)
+add_test(NAME test_draw_params COMMAND test_draw_params)
+
# Shader variant (feature-permutation) system (RC7-6). Compiles ShaderParser.cpp
# directly — no GL/engine link — and checks #pragma feature parsing + #define injection.
add_executable(test_shader_variant
diff --git a/tests/renderer/MockGfxDevice.hpp b/tests/renderer/MockGfxDevice.hpp
index 03c07104f..c83e9ae07 100644
--- a/tests/renderer/MockGfxDevice.hpp
+++ b/tests/renderer/MockGfxDevice.hpp
@@ -20,6 +20,7 @@ struct MockGfxDevice final : GfxDevice {
int createProgramCalls = 0;
int deleteProgramCalls = 0;
int setUniform1iCalls = 0;
+ int setUniform1fCalls = 0;
int setUniform4fCalls = 0;
int getActiveUniformsCalls = 0;
int createTextureCalls = 0;
@@ -58,6 +59,9 @@ struct MockGfxDevice final : GfxDevice {
BufferHandle lastIbo = BufferHandle::Invalid;
RenderPassDesc lastPassDesc{};
i32 lastUniform1iLoc = -999, lastUniform1iVal = 0;
+ u32 lastUniformBufferSlot = 0xFFFFFFFFu;
+ BufferHandle lastUniformBuffer = BufferHandle::Invalid;
+ std::vector<u8> lastUpdateData;
BufferDesc lastBufferDesc{};
bool lastCreateBufferHadData = false;
TextureDesc lastTextureDesc{};
@@ -85,9 +89,16 @@ struct MockGfxDevice final : GfxDevice {
return BufferHandle{nextBufferId++};
}
void deleteBuffer(BufferHandle) override { ++deleteBufferCalls; }
- void updateBuffer(BufferHandle, u32, const void*, u32) override { ++updateBufferCalls; }
+ void updateBuffer(BufferHandle, u32, const void* data, u32 sizeBytes) override {
+ ++updateBufferCalls;
+ lastUpdateData.assign(static_cast<const u8*>(data), static_cast<const u8*>(data) + sizeBytes);
+ }
void resizeBuffer(BufferHandle, u32, const void*) override { ++resizeBufferCalls; }
- void setUniformBuffer(u32, BufferHandle) override { ++setUniformBufferCalls; }
+ void setUniformBuffer(u32 slot, BufferHandle buffer) override {
+ ++setUniformBufferCalls;
+ lastUniformBufferSlot = slot;
+ lastUniformBuffer = buffer;
+ }
VertexLayoutHandle createVertexLayout(const VertexLayoutDesc& desc) override {
++createVertexLayoutCalls;
@@ -137,7 +148,7 @@ struct MockGfxDevice final : GfxDevice {
i32 getUniformLocation(ShaderHandle, const char*) override { return 0; }
i32 getAttribLocation(ShaderHandle, const char*) override { return 0; }
void setUniform1i(i32 loc, i32 v) override { ++setUniform1iCalls; lastUniform1iLoc = loc; lastUniform1iVal = v; }
- void setUniform1f(i32, f32) override {}
+ void setUniform1f(i32, f32) override { ++setUniform1fCalls; }
void setUniform2f(i32, f32, f32) override {}
void setUniform3f(i32, f32, f32, f32) override {}
void setUniform4f(i32, f32, f32, f32, f32) override { ++setUniform4fCalls; }
diff --git a/tests/renderer/test_draw_params.cpp b/tests/renderer/test_draw_params.cpp
new file mode 100644
index 000000000..fa336501d
--- /dev/null
+++ b/tests/renderer/test_draw_params.cpp
@@ -0,0 +1,202 @@
+// DrawParams harness: the loose-uniform → std140 DrawParams rewriter, and the
+// Shader facade that routes name-based setUniform writes into the CPU shadow +
+// commitParams into the UBO seam (no loose uniform uploads for lifted members).
+
+#include "MockGfxDevice.hpp"
+#include "esengine/renderer/DrawParams.hpp"
+#include "esengine/renderer/Shader.hpp"
+
+#include <cstdio>
+#include <cstring>
+
+using namespace esengine;
+
+static int g_failures = 0;
+#define CHECK(cond, msg) \
+ do { \
+ if (!(cond)) { std::printf("FAIL: %s\n", msg); ++g_failures; } \
+ else { std::printf("ok: %s\n", msg); } \
+ } while (0)
+
+static const char* FS_POSTPROCESS =
+ "#version 300 es\n"
+ "precision highp float;\n"
+ "in vec2 v_texCoord;\n"
+ "uniform sampler2D u_texture;\n"
+ "uniform vec2 u_resolution;\n"
+ "uniform float u_intensity;\n"
+ "out vec4 fragColor;\n"
+ "void main() { fragColor = vec4(u_resolution, u_intensity, 1.0); }\n";
+
+static const char* VS_PLAIN =
+ "#version 300 es\n"
+ "in vec2 a_pos;\n"
+ "void main() { gl_Position = vec4(a_pos, 0.0, 1.0); }\n";
+
+int main() {
+ // ── Rewriter: lifts non-sampler uniforms, leaves samplers loose ──
+ {
+ auto rw = rewriteLooseUniforms(VS_PLAIN, FS_POSTPROCESS);
+ CHECK(!rw.layout.empty(), "postprocess fragment lifts a block");
+ CHECK(rw.layout.slots.size() == 2, "two members lifted (sampler stays)");
+ CHECK(rw.fragmentSrc.find("uniform vec2 u_resolution;") == std::string::npos,
+ "loose u_resolution declaration removed");
+ CHECK(rw.fragmentSrc.find("uniform sampler2D u_texture;") != std::string::npos,
+ "sampler declaration untouched");
+ CHECK(rw.fragmentSrc.find("layout(std140) uniform DrawParams {") != std::string::npos,
+ "block declaration inserted");
+ CHECK(rw.vertexSrc == VS_PLAIN, "stage without loose uniforms unchanged");
+
+ const DrawParamSlot* res = rw.layout.find("u_resolution");
+ const DrawParamSlot* inten = rw.layout.find("u_intensity");
+ CHECK(res && res->offset == 0, "vec2 at std140 offset 0");
+ CHECK(inten && inten->offset == 8, "float packs after vec2 at offset 8");
+ CHECK(rw.layout.blockSize == 16, "block size rounds to 16");
+ }
+
+ // ── Rewriter: std140 alignment (vec3 aligns to 16, mat4 = 64) ──
+ {
+ std::string fs =
+ "#version 300 es\nprecision highp float;\n"
+ "uniform float u_a;\n"
+ "uniform vec3 u_b;\n"
+ "uniform mat4 u_m;\n"
+ "out vec4 o;\nvoid main() { o = u_m * vec4(u_b, u_a); }\n";
+ auto rw = rewriteLooseUniforms(VS_PLAIN, fs);
+ CHECK(rw.layout.find("u_a")->offset == 0, "float at 0");
+ CHECK(rw.layout.find("u_b")->offset == 16, "vec3 aligns to 16");
+ CHECK(rw.layout.find("u_m")->offset == 32, "mat4 aligns after vec3's 12 bytes");
+ CHECK(rw.layout.blockSize == 96, "total 96 (32 + 64)");
+ }
+
+ // ── Rewriter: both stages share ONE identical block ──
+ {
+ std::string vs =
+ "#version 300 es\nin vec2 a_pos;\n"
+ "uniform mat4 u_projection;\n"
+ "uniform mat4 u_model;\n"
+ "void main() { gl_Position = u_projection * u_model * vec4(a_pos, 0.0, 1.0); }\n";
+ std::string fs =
+ "#version 300 es\nprecision highp float;\n"
+ "uniform vec4 u_color;\n"
+ "out vec4 o;\nvoid main() { o = u_color; }\n";
+ auto rw = rewriteLooseUniforms(vs, fs);
+ CHECK(rw.layout.slots.size() == 3, "union of both stages lifted");
+ const std::string block = "layout(std140) uniform DrawParams {\n"
+ " mat4 u_projection;\n"
+ " mat4 u_model;\n"
+ " vec4 u_color;\n"
+ "};";
+ CHECK(rw.vertexSrc.find(block) != std::string::npos, "vertex carries the full union block");
+ CHECK(rw.fragmentSrc.find(block) != std::string::npos, "fragment carries the SAME block");
+ CHECK(rw.layout.find("u_color")->offset == 128, "member offsets span the union");
+ }
+
+ // ── Rewriter: leaves what it can't lift ──
+ {
+ std::string fs =
+ "#version 300 es\nprecision highp float;\n"
+ "uniform float u_arr[4];\n" // array → stays loose
+ "uniform float u_a, u_b;\n" // multi-declarator → stays loose
+ "// uniform float u_commented;\n" // comment → ignored
+ "/* uniform float u_blocked; */\n" // comment → ignored
+ "uniform float u_real;\n"
+ "out vec4 o;\nvoid main() { o = vec4(u_real); }\n";
+ auto rw = rewriteLooseUniforms(VS_PLAIN, fs);
+ CHECK(rw.layout.slots.size() == 1, "only the plain declaration lifts");
+ CHECK(rw.layout.find("u_real") != nullptr, "the plain declaration is u_real");
+ CHECK(rw.fragmentSrc.find("uniform float u_arr[4];") != std::string::npos,
+ "array declaration untouched");
+ CHECK(rw.fragmentSrc.find("uniform float u_a, u_b;") != std::string::npos,
+ "multi-declarator untouched");
+ }
+
+ // ── Rewriter: bails on an authored DrawParams block and on type conflicts ──
+ {
+ std::string fs = "#version 300 es\nuniform float u_x;\n"
+ "layout(std140) uniform DrawParams { float y; };\n";
+ auto rw = rewriteLooseUniforms(VS_PLAIN, fs);
+ CHECK(rw.layout.empty() && rw.fragmentSrc == fs, "authored DrawParams name bails");
+
+ std::string vs2 = "#version 300 es\nuniform float u_x;\n";
+ std::string fs2 = "#version 300 es\nuniform vec2 u_x;\n";
+ auto rw2 = rewriteLooseUniforms(vs2, fs2);
+ CHECK(rw2.layout.empty(), "cross-stage type conflict bails");
+ }
+
+ // ── Rewriter: GLSL ES 1.00 sources (no #version 300) keep loose uniforms ──
+ {
+ std::string vs = "attribute vec2 a_position;\nuniform mat4 u_projection;\n"
+ "void main() { gl_Position = u_projection * vec4(a_position, 0.0, 1.0); }\n";
+ std::string fs = "precision highp float;\nuniform vec4 u_color;\n"
+ "void main() { gl_FragColor = u_color; }\n";
+ auto rw = rewriteLooseUniforms(vs, fs);
+ CHECK(rw.layout.empty(), "ES 1.00 program is not lifted");
+ CHECK(rw.vertexSrc == vs && rw.fragmentSrc == fs, "ES 1.00 sources unchanged");
+ }
+
+ // ── Shader facade: lifted writes land in the shadow, not loose uploads ──
+ {
+ MockGfxDevice d;
+ auto shader = Shader::create(d, "vs", "fs");
+ auto rw = rewriteLooseUniforms(VS_PLAIN, FS_POSTPROCESS);
+ shader->adoptDrawParams(rw.layout);
+
+ CHECK(shader->hasDrawParams(), "layout adopted");
+ CHECK(shader->hasUniform("u_intensity"), "hasUniform sees a block member");
+
+ shader->setUniform("u_intensity", 0.5f);
+ CHECK(d.setUniform1fCalls == 0, "lifted float write issues no loose upload");
+
+ shader->setUniform("u_texture", 3);
+ CHECK(d.setUniform1iCalls == 1, "sampler still goes through the loose path");
+
+ // First commit creates the UBO from the shadow and binds slot 4.
+ shader->commitParams();
+ CHECK(d.createBufferCalls == 1, "commit creates the params UBO once");
+ CHECK(d.lastBufferDesc.usage == GfxBufferUsage::Uniform, "params UBO is a uniform buffer");
+ CHECK(d.lastBufferDesc.size == rw.layout.blockSize, "params UBO sized to the block");
+ CHECK(d.lastUniformBufferSlot == DRAW_PARAMS_BINDING, "commit binds DRAW_PARAMS_BINDING");
+
+ // Clean commit re-binds but does not re-upload.
+ const int updatesBefore = d.updateBufferCalls;
+ shader->commitParams();
+ CHECK(d.updateBufferCalls == updatesBefore, "clean commit skips the upload");
+ CHECK(d.setUniformBufferCalls == 2, "clean commit still re-binds the shared slot");
+
+ // Dirty commit uploads the shadow — with the written value at its offset.
+ shader->setUniform("u_resolution", glm::vec2(640.0f, 480.0f));
+ shader->commitParams();
+ CHECK(d.updateBufferCalls == updatesBefore + 1, "dirty commit uploads");
+ f32 packed[2] = {0.0f, 0.0f};
+ std::memcpy(packed, d.lastUpdateData.data() + rw.layout.find("u_resolution")->offset,
+ sizeof(packed));
+ CHECK(packed[0] == 640.0f && packed[1] == 480.0f, "value lands at its std140 offset");
+ }
+
+ // ── Shader facade: mat3 expands to vec4-strided columns ──
+ {
+ MockGfxDevice d;
+ auto shader = Shader::create(d, "vs", "fs");
+ std::string fs = "#version 300 es\nuniform mat3 u_m;\n";
+ auto rw = rewriteLooseUniforms(VS_PLAIN, fs);
+ shader->adoptDrawParams(rw.layout);
+ shader->commitParams(); // create the UBO so the next commit takes the update path
+
+ glm::mat3 m(0.0f);
+ m[1][0] = 7.0f; // column 1, row 0
+ shader->setUniform("u_m", m);
+ shader->commitParams();
+ f32 col1x = 0.0f;
+ std::memcpy(&col1x, d.lastUpdateData.data() + 16, sizeof(f32));
+ CHECK(d.lastUpdateData.size() == 48, "std140 mat3 occupies 48 bytes");
+ CHECK(col1x == 7.0f, "mat3 column 1 lands at stride 16");
+ }
+
+ if (g_failures) {
+ std::printf("%d failure(s)\n", g_failures);
+ return 1;
+ }
+ std::printf("all draw-params checks passed\n");
+ return 0;
+}