37 device_->deleteProgram(program_);
41 device_->deleteBuffer(paramsUbo_);
48 : device_(other.device_)
49 , program_(other.program_)
50 , uniformCache_(std::move(other.uniformCache_))
51 , attribCache_(std::move(other.attribCache_))
52 , activeUniforms_(std::move(other.activeUniforms_))
53 , drawParams_(std::move(other.drawParams_))
54 , paramsShadow_(std::move(other.paramsShadow_))
55 , paramsDirty_(other.paramsDirty_)
56 , paramsUbo_(other.paramsUbo_) {
57 linked_ = other.linked_;
58 afterLink_ = std::move(other.afterLink_);
62 if (!linked_ && device_) device_->onProgramLinked(program_, [
this] { finishLink(); });
71 device_ = other.device_;
72 program_ = other.program_;
73 uniformCache_ = std::move(other.uniformCache_);
74 attribCache_ = std::move(other.attribCache_);
75 activeUniforms_ = std::move(other.activeUniforms_);
76 drawParams_ = std::move(other.drawParams_);
77 paramsShadow_ = std::move(other.paramsShadow_);
78 paramsDirty_ = other.paramsDirty_;
79 paramsUbo_ = other.paramsUbo_;
80 linked_ = other.linked_;
81 afterLink_ = std::move(other.afterLink_);
85 if (!linked_ && device_) device_->onProgramLinked(program_, [
this] { finishLink(); });
93 shader->device_ = &device;
94 if (!shader->compile(vertexSrc, fragmentSrc, {},
nullptr,
nullptr,
language)) {
101 const std::string& vertexSrc,
const std::string& fragmentSrc,
102 std::initializer_list<AttribBinding> bindings,
105 shader->device_ = &device;
106 if (!shader->compile(vertexSrc, fragmentSrc, bindings,
nullptr,
nullptr,
language, deferLink)) {
113 const std::string& vertexPath,
const std::string& fragmentPath) {
114 auto readFile = [](
const std::string& filepath) -> std::string {
115 std::FILE* file = std::fopen(filepath.c_str(),
"rb");
117 ES_LOG_ERROR(
"Failed to open shader file: {}", filepath);
124 while ((n = std::fread(chunk, 1,
sizeof chunk, file)) > 0) content.append(chunk, n);
125 const bool failed = std::ferror(file) != 0;
129 ES_LOG_ERROR(
"Failed to read shader file: {}", filepath);
132 if (content.empty()) {
140 std::string vertexSrc = readFile(vertexPath);
141 std::string fragmentSrc = readFile(fragmentPath);
143 if (vertexSrc.empty() || fragmentSrc.empty()) {
144 ES_LOG_ERROR(
"Failed to load shader files: vertex={}, fragment={}", vertexPath, fragmentPath);
148 return create(device, vertexSrc, fragmentSrc);
155 if (device_) device_->useProgram(program_);
158void Shader::ensureLinked()
const {
159 if (linked_ || !device_)
return;
170 afterLink_.push_back(std::move(fn));
177bool Shader::compile(
const std::string& vertexSrc,
const std::string& fragmentSrc,
178 const std::vector<AttribBinding>& bindings,
189 if (outLog) *outLog =
"backend does not support the shader source language";
191 ES_LOG_ERROR(
"Shader::compile: backend does not support the requested shader language");
195 std::vector<GfxAttribBinding> binds;
196 binds.reserve(bindings.size());
197 for (
const auto& b : bindings) {
198 binds.push_back(GfxAttribBinding{b.index, b.name});
202 GfxShaderSource source{
language, vertexSrc.c_str(), fragmentSrc.c_str()};
203 source.deferLink = deferLink && device_->supportsDeferredLink();
204 program_ = device_->createProgram(source,
205 binds.data(),
static_cast<u32>(binds.size()),
208 if (outFailedStage) {
222 if (source.deferLink) {
224 device_->onProgramLinked(program_, [
this] { finishLink(); });
231void Shader::finishLink() {
233 reflectActiveUniforms();
299 struct PinnedSampler {
const char* name;
u32 unit; };
300 static const PinnedSampler kPinned[] = {
312 for (
const PinnedSampler& p : kPinned) {
314 if (!pinned) {
bind(); pinned =
true; }
319 ES_LOG_DEBUG(
"Shader compiled successfully (program handle: {}, active uniforms: {})",
320 static_cast<u32>(program_), activeUniforms_.size());
321 auto after = std::move(afterLink_);
323 for (
auto& fn : after) fn(*
this);
327 const std::string& vertexSrc,
328 const std::string& fragmentSrc,
329 std::initializer_list<AttribBinding> bindings,
334 shader->device_ = &device;
335 if (!shader->compile(vertexSrc, fragmentSrc, bindings, &outcome.
log, &outcome.
failedStage,
339 outcome.
shader = std::move(shader);
343void Shader::reflectActiveUniforms() {
347i32 Shader::cacheUniformLocation(
const std::string& name,
bool warnOnMiss)
const {
349 auto [it, inserted] = uniformCache_.emplace(name, -1);
352 if (it->second < 0 && warnOnMiss) {
353 ES_LOG_WARN(
"Shader {}: uniform '{}' not found (typo or optimized out)",
354 static_cast<u32>(program_), name);
361 return cacheUniformLocation(name,
true);
367 if (drawParams_.find(name) !=
nullptr)
return true;
368 return cacheUniformLocation(name,
false) >= 0;
372 drawParams_ = std::move(layout);
373 paramsShadow_.assign(drawParams_.blockSize, 0);
374 paramsDirty_ =
false;
376 ES_LOG_WARN(
"Shader {}: DrawParams block ({} bytes) exceeds the frame fallback ({}); "
377 "draws that skip commitParams may be rejected",
383 if (drawParams_.empty() || !device_)
return;
385 paramsUbo_ = device_->createBuffer(
387 paramsShadow_.data());
388 paramsDirty_ =
false;
389 }
else if (paramsDirty_) {
390 device_->updateBuffer(paramsUbo_, 0, paramsShadow_.data(), drawParams_.blockSize);
391 paramsDirty_ =
false;
398bool Shader::writeParam(
const std::string& name,
DrawParamType type,
const void* src)
const {
400 if (slot ==
nullptr)
return false;
401 if (slot->
type != type) {
402 ES_LOG_WARN(
"Shader {}: setUniform('{}') type mismatch with its DrawParams slot",
403 static_cast<u32>(program_), name);
406 u8* dst = paramsShadow_.data() + slot->
offset;
409 const f32* m =
static_cast<const f32*
>(src);
410 for (
u32 col = 0; col < 3; ++col) {
411 std::memcpy(dst + col * 16, m + col * 3, 3 *
sizeof(
f32));
414 u32 size = 0, align = 0;
416 std::memcpy(dst, src, size);
458 device_->setUniform1i(location, value);
462 device_->setUniform1f(location, value);
466 device_->setUniform2f(location, value.x, value.y);
470 device_->setUniform3f(location, value.x, value.y, value.z);
474 device_->setUniform4f(location, value.x, value.y, value.z, value.w);
478 device_->setUniformMat3(location, glm::value_ptr(value));
482 device_->setUniformMat4(location, glm::value_ptr(value));
487 auto [it, inserted] = attribCache_.emplace(name, -1);
489 it->second = device_->getAttribLocation(program_, name.c_str());
Per-frame shader constants shared via a single Uniform Buffer Object.
Abstract graphics device interface.
WHERE one draw's entry is in the frame's per-object record texture, and what an entry says.
Per-frame 2D lighting constants — the third tier of the engine's constant-buffer layering (after per-...
Logging utilities for ESEngine.
#define ES_LOG_WARN(...)
Logs a warning message.
#define ES_LOG_ERROR(...)
Logs an error message.
#define ES_LOG_DEBUG(...)
Binding points for per-material shader constants — the second tier of the engine's constant-buffer la...
The indirect light where ONE draw stands, when a grid was baked for it.
GPU shader program abstraction.
The pose one skinned draw is deformed by: a bone matrix per joint.
static constexpr GfxContent retained()
Abstract graphics device interface.
bool finishProgram(ShaderHandle program)
Waits for program to link if it has not yet. False when it failed to.
i32 getUniformLocation(ShaderHandle program, const char *name)
Gets a uniform location by name, -1 when the linked program has none.
virtual bool supportsShaderLanguage(GfxShaderLanguage language) const =0
Whether this backend compiles language (GL: GLSL ES 300; WebGPU: WGSL).
std::vector< GfxUniformInfo > getActiveUniforms(ShaderHandle program)
Enumerates all active uniforms of a linked shader program.
static ShaderCompileOutcome createEx(GfxDevice &device, const std::string &vertexSrc, const std::string &fragmentSrc, std::initializer_list< AttribBinding > bindings={}, GfxShaderLanguage language=GfxShaderLanguage::GLSL_ES300, bool deferLink=false)
Creates a shader and exposes the driver log on failure.
static Unique< Shader > create(GfxDevice &device, const std::string &vertexSrc, const std::string &fragmentSrc, GfxShaderLanguage language=GfxShaderLanguage::GLSL_ES300)
Creates a shader from source code strings.
static Unique< Shader > createFromFile(GfxDevice &device, const std::string &vertexPath, const std::string &fragmentPath)
Creates a shader from file paths.
void bind() const
Binds the shader for rendering.
void commitParams()
Uploads the shadow (when dirty) and binds this shader's params UBO at DRAW_PARAMS_BINDING.
GfxShaderLanguage language() const
The source language this program was compiled from.
void adoptDrawParams(DrawParamsLayout layout)
Adopts the layout rewriteLooseUniforms produced for this program.
void whenLinked(std::function< void(Shader &)> fn)
Runs fn on this shader once it has linked: at once for one that has.
void setUniform(const std::string &name, i32 value) const
Sets an integer uniform.
Shader & operator=(const Shader &)=delete
i32 getAttribLocation(const std::string &name) const
Gets the location of a vertex attribute.
bool hasUniform(const std::string &name) const
True if the linked program declares this uniform.
i32 getUniformLocation(const std::string &name) const
void unbind() const
Unbinds the shader.
static Unique< Shader > createWithBindings(GfxDevice &device, const std::string &vertexSrc, const std::string &fragmentSrc, std::initializer_list< AttribBinding > bindings, GfxShaderLanguage language=GfxShaderLanguage::GLSL_ES300, bool deferLink=false)
Creates a shader with explicit attribute bindings applied before linking.
DrawParamType
GLSL type of one lifted uniform (the subset the rewriter supports).
constexpr const char * SKIN_CONSTANTS_BLOCK
GLSL block name; must match the shader's declaration + Shader::compile lookup.
constexpr const char * MATERIAL_CONSTANTS_BLOCK
GLSL block name; must match ShaderParser's generated block + Shader::compile lookup.
static constexpr u32 GFX_INVALID_UNIFORM_BLOCK
Sentinel returned by getUniformBlockIndex when a program has no such block (GL_INVALID_INDEX).
constexpr Unique< T > makeUnique(Args &&... args)
Creates a Unique pointer with the given arguments.
std::int32_t i32
Signed 32-bit integer.
constexpr u32 FRAME_CONSTANTS_BINDING
Indexed uniform binding point the FrameConstants block is bound to.
constexpr const char * FRAME_CONSTANTS_BLOCK
GLSL block name; must match the shader declarations and Shader::compile lookup.
constexpr const char * LIGHTMAP_SAMPLER
The baked-light atlas, and the unit a lightmapped mesh samples it from.
constexpr const char * MORPH_DELTA_SAMPLER
The sampler a mesh's morph deltas arrive through, and the unit it is pinned to.
constexpr u32 SHADOW_2D_TEXTURE_UNIT
constexpr const char * PROBE_GRID_SAMPLER
The frame's probe atlas, read per pixel, on the bake's unit.
constexpr u32 LIGHTMAP_TEXTURE_UNIT
std::size_t usize
Size type for indexing and sizes.
constexpr u32 SHADOW_MAP_TEXTURE_UNIT
constexpr u32 WATER_SUN_TEXTURE_UNIT
GfxShaderLanguage
Shader source language a backend consumes.
constexpr u32 SKIN_CONSTANTS_BINDING
Indexed UBO binding point for the per-draw SkinConstants block.
constexpr u32 PROBE_CONSTANTS_BINDING
Indexed UBO binding point for the per-draw ProbeConstants block.
constexpr u32 MORPH_DELTA_TEXTURE_UNIT
GfxShaderStage
Which pipeline stage rejected a program during createProgram().
constexpr const char * PROBE_CONSTANTS_BLOCK
GLSL block name; must match the injected Lit header + Shader::compile lookup.
constexpr const char * INSTANCE_DATA_SAMPLER
GLSL name of the record texture; pinned to its unit by Shader::compile.
constexpr u32 LIGHT_CONSTANTS_BINDING
Indexed UBO binding point for the per-frame LightConstants block.
constexpr const char * WATER_SUN_SAMPLER
constexpr u32 DRAW_PARAMS_FALLBACK_SIZE
Size of the zeroed fallback UBO RenderContext binds at DRAW_PARAMS_BINDING each frame.
constexpr u32 TIME_CONSTANTS_BINDING
std::unique_ptr< T > Unique
Unique ownership smart pointer.
constexpr const char * SHADOW_MAP_SAMPLER
The injected shadow-map sampler, and the texture unit Shader::compile pins it to.
constexpr u32 MATERIAL_CONSTANTS_BINDING
Indexed UBO binding point for the per-material MaterialConstants block.
constexpr const char * SHADOW_2D_SAMPLER
The 2D shadow mask, and the texture unit every Lit shader samples it from.
constexpr const char * ENV_MAP_SAMPLER
The injected reflection sampler, one unit past the shadow map's.
std::uint32_t u32
Unsigned 32-bit integer.
static constexpr u32 MESH_INSTANCE_TEXTURE_UNIT
std::uint8_t u8
Unsigned 8-bit integer.
constexpr const char * DRAW_PARAMS_BLOCK
GLSL block name; must match the rewriter's generated block + Shader::compile lookup.
constexpr u32 SHAPE_2D_TEXTURE_UNIT
constexpr u32 DRAW_PARAMS_BINDING
Indexed UBO binding point for the per-draw DrawParams block. (0 = FrameConstants, 1 = MaterialConstan...
constexpr const char * LIGHT_CONSTANTS_BLOCK
GLSL block name; must match ShaderParser's injected block + Shader::compile lookup.
ShaderStageFailure
Which pipeline stage rejected a shader during compile/link.
constexpr u32 ENV_MAP_TEXTURE_UNIT
constexpr const char * TIME_CONSTANTS_BLOCK
constexpr const char * INSTANCE_CONSTANTS_BLOCK
GLSL block name; must match the injected mesh header + Shader::compile lookup.
constexpr u32 PLANAR_CONSTANTS_BINDING
constexpr const char * PLANAR_CONSTANTS_BLOCK
void drawParamSizeAlign(DrawParamType t, u32 &size, u32 &align)
std140 size/base-alignment of a supported param type.
constexpr const char * SHAPE_2D_SAMPLER
The 2D light-shape mask, and the unit below the shadow mask's.
constexpr u32 INSTANCE_CONSTANTS_BINDING
Indexed UBO binding point for the per-draw InstanceConstants block. Nine and not four: slot 4 is DRAW...
float f32
32-bit floating point
One lifted uniform's slot in a shader's std140 DrawParams block.
u32 offset
std140 byte offset within the block.
A shader's DrawParams layout: lifted members + 16-aligned block size.
const DrawParamSlot * find(const std::string &name) const
Result returned by Shader::createEx when you need the raw driver log.
ShaderStageFailure failedStage