25 if (resources_) resources_->clearShaderRetiredCallback(
this);
29 if (resources_ == resources)
return;
30 if (resources_) {
clear(); resources_->clearShaderRetiredCallback(
this); }
31 resources_ = resources;
39 reviseMaterialsOf(shader);
40 layouts_.erase(shader.
id());
41 sources_.erase(shader.
id());
42 auto found = mesh_programs_.find(shader.
id());
43 if (found == mesh_programs_.end())
return;
44 auto variants = std::move(found->second);
45 mesh_programs_.erase(found);
46 variant_sources_.erase(shader.
id());
47 releaseVariants(variants);
51 auto it = materials_.find(materialId);
52 if (it == materials_.end())
return;
60 for (
auto& [
id, rec] : materials_) {
64 if (device_)
for (
const auto& [ubo, bytes] : through_ubos_)
if (ubo !=
BufferHandle::Invalid) device_->deleteBuffer(ubo);
65 through_ubos_.clear();
70 auto variants = std::move(mesh_programs_);
71 mesh_programs_.clear();
72 variant_sources_.clear();
73 for (
const auto& [source, programs] : variants) releaseVariants(programs);
76void MaterialStore::releaseVariants(
const std::unordered_map<u64, resource::ShaderHandle>& variants) {
77 if (!resources_)
return;
78 std::unordered_set<u32> released;
79 for (
const auto& [shape, handle] : variants) {
80 if (released.insert(handle.id()).second) resources_->
releaseShader(handle);
84u64 MaterialStore::sourceDigest(
const std::string& vertex,
const std::string& fragment) {
85 u64 h = 1469598103934665603ull;
86 const auto mix = [&h](
const std::string& text) {
87 for (
const char c : text) { h ^=
static_cast<unsigned char>(c); h *= 1099511628211ull; }
88 h ^= 0xFFull; h *= 1099511628211ull;
99 for (
const auto& p : material.properties)
if (p.name ==
"u_uvTiling")
return true;
105 bool withNormals,
bool skinned,
bool envMapped,
106 bool lightmapped,
bool gbuffer,
bool tangents,
bool tipPass,
bool opaque)
const {
111 if (gbuffer || lighting_direct_ || opaque) {
114 gbuffer = gbuffer && src != sources_.end() && src->second.mentionsGbuffer;
115 albedo = gbuffer && src->second.writesAlbedo;
116 direct = lighting_direct_ && src != sources_.end() && src->second.takesLight;
119 opaque = opaque && src != sources_.end() && src->second.mentionsOpaque;
123 const u64 shape = (withNormals ? (1ull << 32) : 0ull)
124 | (skinned ? (1ull << 33) : 0ull)
125 | (envMapped ? (1ull << 34) : 0ull)
126 | (lightmapped ? (1ull << 36) : 0ull)
127 | (gbuffer ? (1ull << 38) : 0ull)
128 | (tangents && withNormals ? (1ull << 39) : 0ull)
129 | (tipPass ? (1ull << 40) : 0ull)
130 | (direct ? (1ull << 42) : 0ull)
131 | (opaque ? (1ull << 43) : 0ull);
135 if (
const auto bucket = mesh_programs_.find(rec->shaderRef.id()); bucket != mesh_programs_.end()) {
136 if (
const auto hit = bucket->second.find(shape); hit != bucket->second.end()) {
144 std::vector<std::string> features{
"MESH" };
145 if (withNormals) features.push_back(
"MESH_NORMALS");
146 if (skinned) features.push_back(
"SKINNED");
147 if (lightmapped) features.push_back(
"MESH_LIGHTMAP");
148 if (tangents && withNormals) features.push_back(
"MESH_TANGENTS");
152 features.push_back(
"ES_RECEIVE_SHADOW");
153 if (envMapped) features.push_back(
"ES_ENV_MAP");
156 features.push_back(
"ES_SURFACE_3D");
157 if (gbuffer) features.push_back(
"ES_GBUFFER");
158 if (tipPass) features.push_back(
"ES_TIP_PASS");
159 if (direct) features.push_back(
"ES_LIGHT_DIRECT");
160 if (opaque) features.push_back(
"ES_OPAQUE");
161 const u32 program = variantProgram(materialId, resources, shape, features,
"resident geometry");
167 bool withNormals,
bool skinned,
bool tangents)
const {
170 const u64 shape = (1ull << 37) | (withNormals ? (1ull << 32) : 0ull) | (skinned ? (1ull << 33) : 0ull)
171 | (tangents && withNormals ? (1ull << 39) : 0ull);
172 auto& variants = mesh_programs_[rec->
shaderRef.
id()];
173 auto cached = variants.find(shape);
174 if (cached != variants.end()) {
179 if (src == sources_.end()) {
180 variants[shape] = {};
188 const bool hooked = !material.
vertexHook.empty();
189 const bool cutout = material.
coverageParam ==
"u_alphaCutoff";
190 if (!material.
valid || !depth.
valid || (!hooked && !cutout)) {
191 variants[shape] = {};
199 std::vector<std::string> features;
200 if (withNormals) features.emplace_back(
"MESH_NORMALS");
203 if (skinned) features.emplace_back(
"SKINNED");
204 features.emplace_back(
"SHADOW_DEPTH");
205 if (hooked) features.emplace_back(
"ES_MATERIAL_VERTEX");
206 if (cutout) features.emplace_back(
"SHADOW_ALPHA");
207 if (cutout && declaresUvTransform(material)) features.emplace_back(
"ES_UV_TRANSFORM");
211 if (vert.empty() || frag.empty()) {
212 ES_LOG_WARN(
"MaterialStore: no shadow program for material {} (stage assembly failed)", materialId);
213 variants[shape] = {};
219 if (!shader || !shader->
isValid()) {
221 variants[shape] = {};
227 variants[shape] = handle;
232 bool withNormals,
bool skinned,
bool tangents)
const {
235 const u64 shape = (1ull << 41) | (withNormals ? (1ull << 32) : 0ull) | (skinned ? (1ull << 33) : 0ull)
236 | (tangents && withNormals ? (1ull << 39) : 0ull);
237 auto& variants = mesh_programs_[rec->
shaderRef.
id()];
238 auto cached = variants.find(shape);
239 if (cached != variants.end()) {
244 if (src == sources_.end()) {
245 variants[shape] = {};
252 variants[shape] = {};
258 std::vector<std::string> features;
259 if (withNormals) features.emplace_back(
"MESH_NORMALS");
260 if (skinned) features.emplace_back(
"SKINNED");
261 features.emplace_back(
"SHADOW_DEPTH");
262 features.emplace_back(
"PREPASS_COVERAGE");
263 if (declaresUvTransform(material)) features.emplace_back(
"ES_UV_TRANSFORM");
267 if (vert.empty() || frag.empty()) {
268 ES_LOG_WARN(
"MaterialStore: no prepass program for material {} (stage assembly failed)", materialId);
269 variants[shape] = {};
274 if (!shader || !shader->
isValid()) {
276 variants[shape] = {};
280 variants[shape] = handle;
285 return variantProgram(materialId, resources, 1ull << 35, {
"PARTICLE" },
"particles");
289 u64 shape, std::vector<std::string> extraFeatures,
290 const char* what)
const {
293 auto& variants = mesh_programs_[rec->
shaderRef.
id()];
294 auto cached = variants.find(shape);
295 if (cached != variants.end()) {
301 if (src == sources_.end()) {
302 variants[shape] = {};
314 const bool particle = std::find(extraFeatures.begin(), extraFeatures.end(),
"PARTICLE") != extraFeatures.end();
315 if (particle && std::find(parsed.features.begin(), parsed.features.end(),
"PARTICLE_WORLD") != parsed.features.end()
316 && std::find(features.begin(), features.end(),
"MESH_NORMALS") == features.end()) {
317 features.push_back(
"MESH_NORMALS");
319 for (
auto& f : extraFeatures) features.push_back(std::move(f));
329 if (!parsed.vertexIsCanonical) {
330 ES_LOG_WARN(
"MaterialStore: material {} writes its own vertex stage, so it cannot draw "
331 "{} (only a shader on the engine's vertex stage can)", materialId, what);
332 variants[shape] = {};
340 && fullVertex != parsed.wgslStageFull.end() && fullVertex->second) {
341 ES_LOG_WARN(
"MaterialStore: material {} carries a generated WGSL vertex stage, so it "
342 "cannot draw {} — regenerate its twin", materialId, what);
343 variants[shape] = {};
346 if (!parsed.valid || vert.empty() || frag.empty()) {
347 ES_LOG_WARN(
"MaterialStore: no {} variant for material {} ({})",
348 what, materialId, parsed.valid ?
"stage assembly failed" : parsed.errorMessage);
349 variants[shape] = {};
353 const u64 text = sourceDigest(vert, frag);
354 auto& same = variant_sources_[rec->
shaderRef.
id()];
355 if (
const auto twin = same.find(text); twin != same.end()) {
357 variants[shape] = twin->second;
364 if (!shader || !shader->isValid()) {
366 variants[shape] = {};
370 const u32 program = shader->getProgramId();
371 variants[shape] = handle;
382 case PT::Float:
case PT::Int:
return 1;
383 case PT::Vec2:
return 2;
384 case PT::Vec3:
return 3;
385 case PT::Vec4:
case PT::Color:
return 4;
405 if (!p.fromParam)
continue;
407 if (p.textureUnit >= 0) {
410 layout.
textures.push_back({ p.name,
static_cast<u32>(p.textureUnit),
413 }
else if (p.std140Offset >= 0) {
419 for (
u32 i = 0; i < slot.
arity && at < p.defaultValue.size(); ++i) {
420 usize comma = p.defaultValue.find(
',', at);
421 if (comma == std::string::npos) comma = p.defaultValue.size();
422 slot.
defaults[i] = std::strtof(p.defaultValue.substr(at, comma - at).c_str(),
nullptr);
425 layout.
params.push_back(slot);
437 std::vector<std::pair<std::string, i32>> seeds;
440 seeds.emplace_back(p.name,
static_cast<i32>(p.textureUnit));
447 for (
const auto& [name, unit] : seeds) {
455 const f32 scale = (unitsPerMeter > 0.0f ? unitsPerMeter : 100.0f) / 100.0f;
456 if (scale == world_unit_scale_)
return;
457 const f32 was = world_unit_scale_;
458 world_unit_scale_ = scale;
461 for (
auto& [
id, rec] : materials_) {
463 if (lit == layouts_.end() || rec.
uboBytes.size() < lit->second.blockSize)
continue;
464 for (
const auto& p : lit->second.params) {
465 if (p.worldUnits == 0)
continue;
466 f32 before[4], now[4];
467 defaultInUnits(p, was, before);
468 if (std::memcmp(rec.
uboBytes.data() + p.offset, before, p.arity *
sizeof(
f32)) != 0)
continue;
469 defaultInUnits(p, scale, now);
470 std::memcpy(rec.
uboBytes.data() + p.offset, now, p.arity *
sizeof(
f32));
478 if (!device_)
return;
479 auto it = materials_.find(materialId);
480 if (it == materials_.end())
return;
484 if (lit != layouts_.end()) ensureDefaults(rec, lit->second);
496 device_->resizeBuffer(rec.
ubo, byteSize, rec.
uboBytes.data());
507 if (lit != layouts_.end()) {
508 for (
const auto& slot : lit->second.textures) {
509 if (slot.unit < 32 && !((samplerUnits >> slot.unit) & 1u))
continue;
515 for (
const auto& b : rec.
textures) {
516 if (b.unit != slot.unit)
continue;
521 if (
Texture* texture = resources_->getTexture(b.texture)) {
522 gpu = texture->handle();
533 const std::vector<std::pair<std::string, glm::vec4>>& overrides,
u32 scratch) {
534 if (!device_)
return false;
535 auto it = materials_.find(materialId);
536 auto through = layouts_.find(shader.
id());
537 if (it == materials_.end() || through == layouts_.end())
return false;
540 if (
auto lit = layouts_.find(rec.
shaderRef.
id()); lit != layouts_.end()) {
541 ensureDefaults(rec, lit->second);
546 std::vector<u8> bytes(layout.
blockSize, 0);
547 for (
const auto& p : layout.
params) {
549 defaultInUnits(p, world_unit_scale_, value);
550 std::memcpy(bytes.data() + p.offset, value, p.arity *
sizeof(
f32));
553 std::memcpy(bytes.data() + p.offset, rec.
uboBytes.data() + mine->
offset, p.arity *
sizeof(
f32));
556 for (
const auto& [name, v] : overrides) {
557 if (
const MaterialParamSlot* p = layout.
find(name)) std::memcpy(bytes.data() + p->offset, &v.x, std::min(p->arity, 4u) *
sizeof(
f32));
560 auto& [ubo, size] = through_ubos_[scratch];
566 device_->resizeBuffer(ubo, layout.
blockSize, bytes.data());
571 for (
const auto& slot : layout.
textures) {
575 for (
const auto& b : rec.
textures) {
576 if (b.unit != mine->
unit)
continue;
577 if (resources_)
if (
Texture* texture = resources_->getTexture(b.texture)) gpu = texture->handle();
593 return defaultWhite_;
Abstract graphics device interface.
Backend-agnostic graphics enumerations.
Logging utilities for ESEngine.
#define ES_LOG_WARN(...)
Logs a warning message.
Binding points for per-material shader constants — the second tier of the engine's constant-buffer la...
Engine-side material registry — the resolved "how to draw" for a material handle.
Central resource management system.
Parser for unified .esshader file format.
GPU shader program abstraction.
GPU texture abstraction for 2D images.
static constexpr GfxContent transient()
static constexpr GfxContent retained()
void markGBufferProgram(u32 programId, bool albedo) const
A program that is not a material's — the engine's own mesh shader — says it writes the record.
void bindForDraw(u32 materialId, u32 samplerUnits=0xFFFFFFFFu)
bool bindThrough(u32 materialId, resource::ShaderHandle shader, const std::vector< std::pair< std::string, glm::vec4 > > &overrides, u32 scratch)
Binds a material's values for a draw through another shader (a bake into a texture,...
const MaterialRecord * find(u32 materialId) const
The record for materialId, or nullptr if the handle is 0 / unregistered.
u32 meshProgram(u32 materialId, resource::ResourceManager &resources, bool withNormals=false, bool skinned=false, bool envMapped=false, bool lightmapped=false, bool gbuffer=false, bool tangents=false, bool tipPass=false, bool opaque=false) const
void setWorldUnitsPerMeter(f32 unitsPerMeter)
void forgetShader(resource::ShaderHandle shader)
TextureHandle builtinDefault(MaterialDefaultTexture which) const
u32 shadowProgram(u32 materialId, resource::ResourceManager &resources, bool withNormals, bool skinned, bool tangents=false) const
u32 prepassCoverageProgram(u32 materialId, resource::ResourceManager &resources, bool withNormals, bool skinned, bool tangents=false) const
void undefine(u32 materialId)
u32 particleProgram(u32 materialId, resource::ResourceManager &resources) const
static MaterialUniformLayout layoutOf(const resource::ParsedShader &parsed)
static void seedSamplers(Shader &shader, const resource::ParsedShader &parsed)
Point each of shader's texture params at its unit.
void setResourceManager(resource::ResourceManager *resources)
Resolves texture handles at bind time; without one, texture params bind nothing.
GPU shader program for rendering.
u32 getProgramId() const
Gets the program handle's raw value, for command payloads and sort keys.
void bind() const
Binds the shader for rendering.
GfxShaderLanguage language() const
The source language this program was compiled from.
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.
bool isValid() const
Checks if the shader compiled and linked successfully.
bool hasUniform(const std::string &name) const
True if the linked program declares this uniform.
void unbind() const
Unbinds the shader.
2D texture for GPU rendering
bool isValid() const
Checks if the handle references a valid resource.
IdType id() const
Gets the packed identifier (index + generation).
Central manager for GPU resources.
ShaderTargetLanguage preferredShaderTarget() const
preferredShaderLanguage() as a ShaderParser assembly target.
ShaderHandle createShaderWithBindings(const std::string &vertSrc, const std::string &fragSrc, std::initializer_list< AttribBinding > bindings, GfxShaderLanguage language=GfxShaderLanguage::GLSL_ES300, bool deferLink=false)
GfxShaderLanguage preferredShaderLanguage() const
The language embedded pipelines must author their sources in.
void releaseShader(ShaderHandle handle)
Releases a shader (decrements ref count).
Shader * getShader(ShaderHandle handle)
Gets a shader by handle.
ShaderHandle createShader(const std::string &vertSrc, const std::string &fragSrc, bool rewriteLoose=true, GfxShaderLanguage language=GfxShaderLanguage::GLSL_ES300, bool deferLink=false)
void setShaderRetiredCallback(void *owner, ShaderRetiredCallback callback)
static std::vector< std::string > splitFeatures(const std::string &csv)
Split a comma-separated feature/switch list into trimmed, non-empty entries — the form the boundary c...
static ParsedShader parse(const std::string &source)
Parses shader source into structured format (no include support).
static std::string assembleStage(const ParsedShader &parsed, ShaderStage stage, const std::string &platform="", const std::vector< std::string > &features={}, ShaderTargetLanguage target=ShaderTargetLanguage::GLSL_ES300)
Assembles final GLSL source for a specific stage.
static std::vector< std::string > featuresRead(const ParsedShader &parsed, const std::vector< std::string > &features, ShaderTargetLanguage target=ShaderTargetLanguage::GLSL_ES300)
constexpr const char * MESH
Handle< esengine::Shader > ShaderHandle
Handle to a shader resource.
std::int32_t i32
Signed 32-bit integer.
std::uint64_t u64
Unsigned 64-bit integer.
std::size_t usize
Size type for indexing and sizes.
MaterialDefaultTexture
Which built-in texture a param falls back to when a material leaves it unset.
constexpr u32 MATERIAL_CONSTANTS_BINDING
Indexed UBO binding point for the per-material MaterialConstants block.
MaterialDefaultTexture materialDefaultByName(const std::string &name)
Maps a shader's declared default(<name>) to the built-in it names.
std::uint32_t u32
Unsigned 32-bit integer.
float f32
32-bit floating point
One scalar/vector param's slot in a shader's std140 MaterialConstants block.
i8 worldUnits
1 a length, -1 a rate per length: the default is at 100 units a metre (ShaderProperty::worldUnits).
u32 arity
Float component count (1..4); textures are not slots.
u32 offset
std140 byte offset within the block.
f32 defaults[4]
Shader-declared default(...); the block's initial value.
A material's resolved render state (P0) plus its packed std140 constants (P1).
resource::ShaderHandle shaderRef
std::vector< MaterialTextureBinding > textures
Texture params bound to sampler units, by handle (see MaterialTextureBinding).
u64 revision
Changes whenever anything above does, or its shader's layout: see core/Revision.hpp and MaterialStore...
std::vector< u8 > uboBytes
A texture param's sampler unit (>= MATERIAL_TEXTURE_UNIT_BASE, above the batch's 0....
Result of parsing an .esshader file.
bool valid
True if parsing succeeded.
std::string hairShadowParam
std::string coverageParam
std::string name
Shader name.
std::string wgslVertexHook
std::vector< ShaderProperty > properties
Exposed material params (pragma param / properties block).