Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
MaterialStore.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
7#include "./MaterialStore.hpp"
8
10#include "../rhi/GfxDevice.hpp"
11#include "../rhi/GfxEnums.hpp"
12#include "../rhi/Texture.hpp"
15#include "../rhi/Shader.hpp"
16#include "../../core/Log.hpp"
18
19#include <cstdlib>
20
21namespace esengine {
22
24 clear();
25 if (resources_) resources_->clearShaderRetiredCallback(this);
26}
27
29 if (resources_ == resources) return;
30 if (resources_) { clear(); resources_->clearShaderRetiredCallback(this); }
31 resources_ = resources;
32 if (resources_) resources_->setShaderRetiredCallback(this, [](void* owner, resource::ShaderHandle shader) {
33 static_cast<MaterialStore*>(owner)->forgetShader(shader);
34 });
35}
36
38 forgetLookups();
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);
48}
49
50void MaterialStore::undefine(u32 materialId) {
51 auto it = materials_.find(materialId);
52 if (it == materials_.end()) return;
53 if (it->second.ubo != BufferHandle::Invalid && device_) device_->deleteBuffer(it->second.ubo);
54 forgetLookups();
55 materials_.erase(it);
56}
57
59 if (device_) {
60 for (auto& [id, rec] : materials_) {
61 if (rec.ubo != BufferHandle::Invalid) device_->deleteBuffer(rec.ubo);
62 }
63 }
64 if (device_) for (const auto& [ubo, bytes] : through_ubos_) if (ubo != BufferHandle::Invalid) device_->deleteBuffer(ubo);
65 through_ubos_.clear();
66 forgetLookups();
67 materials_.clear();
68 layouts_.clear();
69 sources_.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);
74}
75
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);
81 }
82}
83
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;
89 };
90 mix(vertex);
91 mix(fragment);
92 return h;
93}
94
95namespace {
96// A material that moves where its maps are read (the Model shader's Tiling, Offset and Rotation) has its cut-out read
97// there too, by the depth programs that reproduce its coverage — or a tiled fence casts the shadow of an untiled one.
98bool declaresUvTransform(const resource::ParsedShader& material) {
99 for (const auto& p : material.properties) if (p.name == "u_uvTiling") return true;
100 return false;
101}
102} // namespace
103
105 bool withNormals, bool skinned, bool envMapped,
106 bool lightmapped, bool gbuffer, bool tangents, bool tipPass, bool opaque) const {
107 // Only for a shader that has something to write: one that never mentions the feature would
108 // compile the same program twice and then be declared to write an output it does not have.
109 bool albedo = false;
110 bool direct = false;
111 if (gbuffer || lighting_direct_ || opaque) {
112 const MaterialRecord* rec = find(materialId);
113 const auto src = rec && rec->shaderRef.isValid() ? sources_.find(rec->shaderRef.id()) : sources_.end();
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;
117 // An unblended draw writes its alpha straight into the frame, where the sky reads it as coverage: a shader that
118 // says what an opaque surface's alpha is gets a program for it, and one that does not keeps sharing the blended one.
119 opaque = opaque && src != sources_.end() && src->second.mentionsOpaque;
120 }
121 // Keyed by shader AND vertex shape: a layout may not declare an attribute its
122 // shader ignores, so geometry with normals — or posed by bones — needs its own.
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);
132 // A program already made for this shader and vertex shape is the answer, and almost every draw of a frame asks for one: it is looked up before
133 // the feature list is built, since building it (nine strings and the vector that holds them) was most of what a cached answer cost.
134 if (const MaterialRecord* rec = find(materialId); rec && rec->shaderRef.isValid()) {
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()) {
137 const Shader* shader = resources.getShader(hit->second);
138 const u32 cached = shader ? shader->getProgramId() : 0;
139 if (gbuffer && cached != 0) markGBufferProgram(cached, albedo);
140 return cached;
141 }
142 }
143 }
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");
149 // Resident geometry carries the frame's shadow map on its own slot 2 and the
150 // reflection on slot 3; the batch variant of the same material must not, which
151 // is why these ride the mesh path.
152 features.push_back("ES_RECEIVE_SHADOW");
153 if (envMapped) features.push_back("ES_ENV_MAP");
154 // As above: this vertex source gives the fragment a real world position, so a
155 // positional light is read from where it is rather than from the plane.
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");
162 if (gbuffer && program != 0) markGBufferProgram(program, albedo);
163 return program;
164}
165
167 bool withNormals, bool skinned, bool tangents) const {
168 const MaterialRecord* rec = find(materialId);
169 if (!rec || !rec->shaderRef.isValid()) return 0;
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()) {
175 const Shader* shader = resources.getShader(cached->second);
176 return shader ? shader->getProgramId() : 0;
177 }
178 auto src = sources_.find(rec->shaderRef.id());
179 if (src == sources_.end()) {
180 variants[shape] = {};
181 return 0;
182 }
183
184 // The engine's mesh depth shader, handed the material's hook and the block it reads. The
185 // material's own fragment is not used: a shadow map wants depth, not colour.
186 const resource::ParsedShader material = resource::ShaderParser::parse(src->second.source);
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] = {};
192 return 0;
193 }
194 depth.properties = material.properties;
195 depth.materialBlockSize = material.materialBlockSize;
196 depth.vertexHook = material.vertexHook;
197 depth.wgslVertexHook = material.wgslVertexHook;
198
199 std::vector<std::string> features;
200 if (withNormals) features.emplace_back("MESH_NORMALS");
201 // A depth pass has no use for a tangent frame, and the vertex stage of SHADOW_DEPTH does not write the varying the fragment prelude would then read.
202 // The variant is still keyed by `tangents` so a mesh with and without them keeps its own program.
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");
208 const auto target = resources.preferredShaderTarget();
209 const std::string vert = resource::ShaderParser::assembleStage(depth, resource::ShaderStage::Vertex, "", features, target);
210 const std::string frag = resource::ShaderParser::assembleStage(depth, resource::ShaderStage::Fragment, "", features, target);
211 if (vert.empty() || frag.empty()) {
212 ES_LOG_WARN("MaterialStore: no shadow program for material {} (stage assembly failed)", materialId);
213 variants[shape] = {};
214 return 0;
215 }
216 // Deferred: the program is waited for by the first draw that uses it, so the programs a frame asks for together compile together.
217 resource::ShaderHandle handle = resources.createShaderWithBindings(vert, frag, {}, resources.preferredShaderLanguage(), /*deferLink=*/true);
218 Shader* shader = resources.getShader(handle);
219 if (!shader || !shader->isValid()) {
220 resources.releaseShader(handle);
221 variants[shape] = {};
222 return 0;
223 }
224 // The samplers the hook reads (the terrain's height pages) sit on the units the material declares them on; a program left unseeded reads unit 0.
225 seedSamplers(*shader, material);
226 const u32 program = shader->getProgramId();
227 variants[shape] = handle;
228 return program;
229}
230
232 bool withNormals, bool skinned, bool tangents) const {
233 const MaterialRecord* rec = find(materialId);
234 if (!rec || !rec->shaderRef.isValid()) return 0;
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()) {
240 const Shader* shader = resources.getShader(cached->second);
241 return shader ? shader->getProgramId() : 0;
242 }
243 auto src = sources_.find(rec->shaderRef.id());
244 if (src == sources_.end()) {
245 variants[shape] = {};
246 return 0;
247 }
248 const resource::ParsedShader material = resource::ShaderParser::parse(src->second.source);
250 // The Model shader's coverage is what the depth fragment reproduces, and a hook would move vertices the colour pass moves its own way.
251 if (!material.valid || !depth.valid || material.name != "Model" || material.coverageParam != "u_alphaCutoff" || !material.vertexHook.empty()) {
252 variants[shape] = {};
253 return 0;
254 }
255 depth.properties = material.properties;
256 depth.materialBlockSize = material.materialBlockSize;
257
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");
264 const auto target = resources.preferredShaderTarget();
265 const std::string vert = resource::ShaderParser::assembleStage(depth, resource::ShaderStage::Vertex, "", features, target);
266 const std::string frag = resource::ShaderParser::assembleStage(depth, resource::ShaderStage::Fragment, "", features, target);
267 if (vert.empty() || frag.empty()) {
268 ES_LOG_WARN("MaterialStore: no prepass program for material {} (stage assembly failed)", materialId);
269 variants[shape] = {};
270 return 0;
271 }
272 resource::ShaderHandle handle = resources.createShaderWithBindings(vert, frag, {}, resources.preferredShaderLanguage(), /*deferLink=*/true);
273 Shader* shader = resources.getShader(handle);
274 if (!shader || !shader->isValid()) {
275 resources.releaseShader(handle);
276 variants[shape] = {};
277 return 0;
278 }
279 const u32 program = shader->getProgramId();
280 variants[shape] = handle;
281 return program;
282}
283
285 return variantProgram(materialId, resources, 1ull << 35, { "PARTICLE" }, "particles");
286}
287
288u32 MaterialStore::variantProgram(u32 materialId, resource::ResourceManager& resources,
289 u64 shape, std::vector<std::string> extraFeatures,
290 const char* what) const {
291 const MaterialRecord* rec = find(materialId);
292 if (!rec || !rec->shaderRef.isValid()) return 0;
293 auto& variants = mesh_programs_[rec->shaderRef.id()];
294 auto cached = variants.find(shape);
295 if (cached != variants.end()) {
296 const Shader* shader = resources.getShader(cached->second);
297 return shader ? shader->getProgramId() : 0;
298 }
299
300 auto src = sources_.find(rec->shaderRef.id());
301 if (src == sources_.end()) {
302 variants[shape] = {};
303 return 0;
304 }
305
306 // The SAME source and features plus this vertex source's: the author's
307 // fragment is untouched and only the engine's vertex stage changes, which is
308 // what makes this one material rather than two that must be kept in step.
309 resource::ParsedShader parsed = resource::ShaderParser::parse(src->second.source);
310 std::vector<std::string> features = resource::ShaderParser::splitFeatures(src->second.features);
311 // A particle shader that declares PARTICLE_WORLD is lit as a thing in the world: its particle variant carries a world position and
312 // a normal (the way to the eye), which is what the lit path of a fragment stage reads under MESH_NORMALS. One that does not is the
313 // flat quad a 2D scene lights by its layer, as it always was.
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");
318 }
319 for (auto& f : extraFeatures) features.push_back(std::move(f));
320 const auto target = resources.preferredShaderTarget();
321 features = resource::ShaderParser::featuresRead(parsed, features, target);
322 const std::string vert = resource::ShaderParser::assembleStage(
323 parsed, resource::ShaderStage::Vertex, "", features, target);
324 const std::string frag = resource::ShaderParser::assembleStage(
325 parsed, resource::ShaderStage::Fragment, "", features, target);
326 // Only a shader whose vertex stage is the ENGINE's can be retargeted: one that
327 // writes its own decides how a vertex reaches clip space, and adding MESH to it
328 // would compile a program that still ignores the per-object transform.
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] = {};
333 return 0;
334 }
335 // A full WGSL vertex twin is a translation of the BATCH vertex stage, frozen
336 // into the file: compiled for this source it reads attributes the layout does
337 // not have, and the device rejects the pipeline.
338 const auto fullVertex = parsed.wgslStageFull.find(resource::ShaderStage::Vertex);
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] = {};
344 return 0;
345 }
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] = {};
350 return 0;
351 }
352
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()) {
356 if (const Shader* shader = resources.getShader(twin->second)) {
357 variants[shape] = twin->second;
358 return shader->getProgramId();
359 }
360 }
361 resource::ShaderHandle handle = resources.createShader(vert, frag, /*rewriteLoose=*/false,
362 resources.preferredShaderLanguage(), /*deferLink=*/true);
363 Shader* shader = resources.getShader(handle);
364 if (!shader || !shader->isValid()) {
365 resources.releaseShader(handle);
366 variants[shape] = {};
367 return 0;
368 }
369 seedSamplers(*shader, parsed);
370 const u32 program = shader->getProgramId();
371 variants[shape] = handle;
372 same[text] = handle;
373 return program;
374}
375
376namespace {
377
379u32 paramArity(resource::ShaderPropertyType t) {
381 switch (t) {
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;
386 default: return 0;
387 }
388}
389
390} // namespace
391
394 layout.blockSize = parsed.materialBlockSize;
395 layout.coverageParam = parsed.coverageParam;
396 layout.tipParam = parsed.tipParam;
397 layout.hairShadowParam = parsed.hairShadowParam;
398 layout.usesGBuffer = parsed.usesGBuffer;
399 layout.usesLights = parsed.usesLights;
400 layout.highPrecision = parsed.highPrecision;
401 layout.name = parsed.name;
402 layout.vertexBounds = parsed.vertexBounds;
403 layout.vertexHook = !parsed.vertexHook.empty();
404 for (const auto& p : parsed.properties) {
405 if (!p.fromParam) continue;
407 if (p.textureUnit >= 0) {
408 // Resolve the param's `default(<name>)` to a built-in default texture, bound when
409 // a material leaves the param unset.
410 layout.textures.push_back({ p.name, static_cast<u32>(p.textureUnit),
411 materialDefaultByName(p.defaultValue), p.layered });
412 }
413 } else if (p.std140Offset >= 0) {
414 MaterialParamSlot slot{ p.name, static_cast<u32>(p.std140Offset), paramArity(p.type) };
415 slot.worldUnits = p.worldUnits;
416 // default(a,b,c,d) csv -> the slot's initial block value.
417 // A trailing comma ends the list, as a stream's getline would: no empty last field.
418 usize at = 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);
423 at = comma + 1;
424 }
425 layout.params.push_back(slot);
426 }
427 }
428 if (const auto* input = layout.findTexture(parsed.depthInput)) {
429 layout.depthInputUnit = static_cast<i32>(input->unit);
430 }
431 return layout;
432}
433
434
436 if (shader.language() != GfxShaderLanguage::GLSL_ES300) return;
437 std::vector<std::pair<std::string, i32>> seeds;
438 for (const auto& p : parsed.properties) {
439 if (p.fromParam && p.type == resource::ShaderPropertyType::Texture && p.textureUnit >= 0) {
440 seeds.emplace_back(p.name, static_cast<i32>(p.textureUnit));
441 }
442 }
443 // After the program links, which for one made with deferLink is when something first needs it. Every variant gets the material's
444 // whole list, and one that does not read a texture (a depth program, most of all) has had it optimized out: that is not a typo.
445 shader.whenLinked([seeds = std::move(seeds)](Shader& s) {
446 s.bind();
447 for (const auto& [name, unit] : seeds) {
448 if (s.hasUniform(name)) s.setUniform(name, unit);
449 }
450 s.unbind();
451 });
452}
453
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;
459 // Blocks filled before the project said its unit hold the old defaults. No record says which params a material set, so one is
460 // taken to be unset where it still holds exactly what the default was.
461 for (auto& [id, rec] : materials_) {
462 auto lit = layouts_.find(rec.shaderRef.id());
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));
471 rec.uboDirty = true;
472 rec.revision = revise();
473 }
474 }
475}
476
477void MaterialStore::bindForDraw(u32 materialId, u32 samplerUnits) {
478 if (!device_) return;
479 auto it = materials_.find(materialId);
480 if (it == materials_.end()) return;
481 MaterialRecord& rec = it->second;
482
483 auto lit = layouts_.find(rec.shaderRef.id());
484 if (lit != layouts_.end()) ensureDefaults(rec, lit->second);
485
486 // Per-material constants UBO (binding 1) — present only when the shader declares params.
487 if (!rec.uboBytes.empty()) {
488 const u32 byteSize = static_cast<u32>(rec.uboBytes.size());
489 if (rec.ubo == BufferHandle::Invalid) {
490 rec.ubo = device_->createBuffer({GfxBufferUsage::Uniform, byteSize, /*dynamic=*/true},
491 GfxContent::retained(), rec.uboBytes.data());
492 rec.uboDirty = false;
493 } else if (rec.uboDirty) {
494 // Full re-spec (not a sub-update): orphans the old store so a draw still
495 // reading it does not stall the upload.
496 device_->resizeBuffer(rec.ubo, byteSize, rec.uboBytes.data());
497 rec.uboDirty = false;
498 }
499 device_->setUniformBuffer(MATERIAL_CONSTANTS_BINDING, rec.ubo);
500 }
501
502 // Texture params — bound to their sampler units: MATERIAL_TEXTURE_UNIT_BASE upward, then any
503 // unit below it the shader never reads from the draw (ShaderParser::materialOverflowUnits), which
504 // is why the draw binds its own units first. Iterate the shader's layout (not just the material's explicit bindings)
505 // so an unset param binds its declared default (white/black/flatnormal) instead of sampling
506 // whatever stale texture is at the unit.
507 if (lit != layouts_.end()) {
508 for (const auto& slot : lit->second.textures) {
509 if (slot.unit < 32 && !((samplerUnits >> slot.unit) & 1u)) continue;
510 TextureHandle gpu = builtinDefault(slot);
511 // What stood behind this draw, where the frame took a copy of it; a material that named a texture there keeps its own.
512 if (sceneColor_ != TextureHandle::Invalid && slot.name == "u_sceneColor") gpu = sceneColor_;
513 if (sceneDepth_ != TextureHandle::Invalid && slot.name == "u_sceneDepthMap") gpu = sceneDepth_;
514 if (screenColor_ != TextureHandle::Invalid && slot.name == "u_screenColor") gpu = screenColor_;
515 for (const auto& b : rec.textures) {
516 if (b.unit != slot.unit) continue;
517 // Resolved HERE rather than cached at set time. A pool lookup is
518 // an array index next to the GL call it precedes, and it is what
519 // lets a texture re-uploaded behind its handle reach the material.
520 if (resources_) {
521 if (Texture* texture = resources_->getTexture(b.texture)) {
522 gpu = texture->handle();
523 }
524 }
525 break;
526 }
527 if (gpu != TextureHandle::Invalid) device_->bindTexture(slot.unit, gpu);
528 }
529 }
530}
531
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;
538 MaterialRecord& rec = it->second;
539 const MaterialUniformLayout* own = nullptr;
540 if (auto lit = layouts_.find(rec.shaderRef.id()); lit != layouts_.end()) {
541 ensureDefaults(rec, lit->second);
542 own = &lit->second;
543 }
544 const MaterialUniformLayout& layout = through->second;
545 if (layout.blockSize > 0) {
546 std::vector<u8> bytes(layout.blockSize, 0);
547 for (const auto& p : layout.params) {
548 f32 value[4];
549 defaultInUnits(p, world_unit_scale_, value);
550 std::memcpy(bytes.data() + p.offset, value, p.arity * sizeof(f32));
551 const MaterialParamSlot* mine = own ? own->find(p.name) : nullptr;
552 if (mine && mine->arity == p.arity && mine->offset + p.arity * sizeof(f32) <= rec.uboBytes.size()) {
553 std::memcpy(bytes.data() + p.offset, rec.uboBytes.data() + mine->offset, p.arity * sizeof(f32));
554 }
555 }
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));
558 }
559 if (through_ubos_.size() <= scratch) through_ubos_.resize(scratch + 1, {BufferHandle::Invalid, 0});
560 auto& [ubo, size] = through_ubos_[scratch];
561 if (ubo == BufferHandle::Invalid || size != layout.blockSize) {
562 if (ubo != BufferHandle::Invalid) device_->deleteBuffer(ubo);
563 ubo = device_->createBuffer({GfxBufferUsage::Uniform, layout.blockSize, /*dynamic=*/true}, GfxContent::transient(), bytes.data());
564 size = layout.blockSize;
565 } else {
566 device_->resizeBuffer(ubo, layout.blockSize, bytes.data());
567 }
568 if (ubo == BufferHandle::Invalid) return false;
569 device_->setUniformBuffer(MATERIAL_CONSTANTS_BINDING, ubo);
570 }
571 for (const auto& slot : layout.textures) {
572 TextureHandle gpu = builtinDefault(slot);
573 const MaterialTextureSlot* mine = own ? own->findTexture(slot.name) : nullptr;
574 if (mine) {
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();
578 break;
579 }
580 }
581 if (gpu != TextureHandle::Invalid) device_->bindTexture(slot.unit, gpu);
582 }
583 return true;
584}
585
587 switch (which) {
588 case MaterialDefaultTexture::Black: return defaultBlack_;
589 case MaterialDefaultTexture::FlatNormal: return defaultFlatNormal_;
590 case MaterialDefaultTexture::Ripples: return defaultRipples_;
592 }
593 return defaultWhite_;
594}
595
596} // namespace esengine
Abstract graphics device interface.
Backend-agnostic graphics enumerations.
Logging utilities for ESEngine.
#define ES_LOG_WARN(...)
Logs a warning message.
Definition Log.hpp:294
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.
Definition Shader.hpp:86
u32 getProgramId() const
Gets the program handle's raw value, for command payloads and sort keys.
Definition Shader.hpp:257
void bind() const
Binds the shader for rendering.
Definition Shader.cpp:151
GfxShaderLanguage language() const
The source language this program was compiled from.
Definition Shader.hpp:126
void whenLinked(std::function< void(Shader &)> fn)
Runs fn on this shader once it has linked: at once for one that has.
Definition Shader.cpp:164
void setUniform(const std::string &name, i32 value) const
Sets an integer uniform.
Definition Shader.cpp:422
bool isValid() const
Checks if the shader compiled and linked successfully.
Definition Shader.hpp:251
bool hasUniform(const std::string &name) const
True if the linked program declares this uniform.
Definition Shader.cpp:364
void unbind() const
Unbinds the shader.
Definition Shader.cpp:173
2D texture for GPU rendering
Definition Texture.hpp:116
bool isValid() const
Checks if the handle references a valid resource.
Definition Handle.hpp:82
IdType id() const
Gets the packed identifier (index + generation).
Definition Handle.hpp:85
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)
Handle< esengine::Shader > ShaderHandle
Handle to a shader resource.
Definition Handle.hpp:214
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
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.
Definition Types.hpp:45
float f32
32-bit floating point
Definition Types.hpp:59
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....
A shader's layout: std140 block (scalar/vector params) + texture sampler slots.
const MaterialParamSlot * find(const std::string &name) const
bool highPrecision
The shader writes a measurement and wants a float target (ParsedShader::highPrecision).
std::vector< MaterialTextureSlot > textures
std::vector< MaterialParamSlot > params
std::string tipParam
The float param that turns the shader's blended tip pass on (see ParsedShader::tipParam).
std::string hairShadowParam
The float param that makes the shader's meshes hair for shadows (see ParsedShader::hairShadowParam).
i32 depthInputUnit
The tracked sampler of a deterministic vertex hook.
const MaterialTextureSlot * findTexture(const std::string &name) const
bool usesLights
The shader reads the frame's light block and shadow atlas (ParsedShader::usesLights).
bool usesGBuffer
The shader reads the scene's surface record (ParsedShader::usesGBuffer).
std::string name
The shader's own name (#pragma shader "<name>"), for what a profiler calls a draw by.
Result of parsing an .esshader file.
bool valid
True if parsing succeeded.
std::string name
Shader name.
std::vector< ShaderProperty > properties
Exposed material params (pragma param / properties block).