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.

34.0 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file    MaterialStore.hpp
 * @brief   Engine-side material registry — the resolved "how to draw" for a material handle.
 * @details A material is a first-class engine object: the SDK pushes its resolved render
 *          state here (defineMaterial) when the material is created or edited, and the
 *          render path looks it up by the handle a component carries (e.g. Sprite::material).
 *          This replaces the dead pull-callback + cache, where C++ called back into JS per
 *          material and the resolved data never reached a draw.
 *
 *          Per-material shader parameters live in a std140 MaterialConstants UBO (binding 1):
 *          a shader authored with `#pragma param` registers its layout here, and setUniform
 *          packs named values into the material's byte buffer by reflected offset. The render
 *          path uploads (when dirty) and binds that UBO per draw via bindForDraw.
 *
 * @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 "../../core/Revision.hpp"
#include "../../resource/Handle.hpp"
#include "../draw/BlendMode.hpp"
#include "../rhi/GfxEnums.hpp"

#include <glm/vec4.hpp>

#include <algorithm>
#include <cstring>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>

namespace esengine {
namespace resource { struct ParsedShader; }

namespace resource { class ResourceManager; }


class GfxDevice;

/** @brief Triangle culling mode baked into a material's pipeline. */
enum class CullMode : u8 {
    None = 0,
    Back = 1,
    Front = 2,
};

/** @brief One scalar/vector param's slot in a shader's std140 MaterialConstants block. */
struct MaterialParamSlot {
    std::string name;
    u32 offset = 0;  ///< std140 byte offset within the block.
    u32 arity = 1;   ///< Float component count (1..4); textures are not slots.
    f32 defaults[4] = {0, 0, 0, 0};  ///< Shader-declared default(...); the block's initial value.
    i8 worldUnits = 0;  ///< 1 a length, -1 a rate per length: the default is at 100 units a metre (ShaderProperty::worldUnits).
};

/** @brief Which built-in texture a param falls back to when a material leaves it unset. */
enum class MaterialDefaultTexture : u8 { White, Black, FlatNormal, Ripples };

/** @brief Maps a shader's declared `default(<name>)` to the built-in it names. */
inline MaterialDefaultTexture materialDefaultByName(const std::string& name) {
    if (name == "black") return MaterialDefaultTexture::Black;
    if (name == "flatnormal" || name == "normal") return MaterialDefaultTexture::FlatNormal;
    if (name == "ripples") return MaterialDefaultTexture::Ripples;
    return MaterialDefaultTexture::White;  // "white" / empty / unknown
}

/** @brief A texture param's sampler unit (>= MATERIAL_TEXTURE_UNIT_BASE, above the batch's 0..7). */
struct MaterialTextureSlot {
    std::string name;
    u32 unit = 0;
    /// The shader's declared `default(white|black|flatnormal)`, kept as the CHOICE
    /// rather than the resolved id: the built-ins are re-created when the device
    /// is, and an id resolved at registration would outlive the texture it names.
    MaterialDefaultTexture defaultTexture = MaterialDefaultTexture::White;
    /// Declared `textureArray` (a `sampler2DArray`): left unset, it binds layers of its default's colour (setBuiltinDefaultArrays),
    /// as a 2D default under an array sampler reads black on WebGL.
    bool layered = false;
};

/** @brief A material's bound texture at a sampler unit. */
struct MaterialTextureBinding {
    u32 unit = 0;
    /// The resource handle, NOT a resolved GPU id. Resolving at bind time is what
    /// lets the texture behind it be re-uploaded — by a hot update, or by a device
    /// loss — without every material that references it having to be re-bound.
    resource::TextureHandle texture;
};

/** @brief A shader's layout: std140 block (scalar/vector params) + texture sampler slots. */
struct MaterialUniformLayout {
    u32 blockSize = 0;
    /// The param whose value above zero makes output alpha coverage (see
    /// ParsedShader::coverageParam); empty when the shader declares none.
    std::string coverageParam;
    /// The float param that turns the shader's blended tip pass on (see ParsedShader::tipParam).
    std::string tipParam;
    /// The float param that makes the shader's meshes hair for shadows (see ParsedShader::hairShadowParam).
    std::string hairShadowParam;
    /// The shader reads the scene's surface record (ParsedShader::usesGBuffer).
    bool usesGBuffer = false;
    /// The shader reads the frame's light block and shadow atlas (ParsedShader::usesLights).
    bool usesLights = false;
    /// The shader writes a measurement and wants a float target (ParsedShader::highPrecision).
    bool highPrecision = false;
    /// The shader's own name (`#pragma shader "<name>"`), for what a profiler calls a draw by.
    std::string name;
    /// What the shader's vertex hook can move a vertex by (ParsedShader::vertexBounds), and whether it
    /// has a hook at all — culling grows a mesh's box by the first, and the shadow pass builds a
    /// program of its own for the second.
    float vertexBounds = 0.0f;
    bool vertexHook = false;
    std::vector<MaterialParamSlot> params;
    std::vector<MaterialTextureSlot> textures;

    /// What the per-draw questions ask of a layout by name, answered once when it is registered (MaterialStore::registerLayout):
    /// an index into params or textures, -1 for none. Asked by name, each was a string search per mesh per view per frame.
    struct Named {
        i32 sceneColor = -1, sceneDepth = -1;              // textures
        i32 transmission = -1, blendDistance = -1;          // params
        i32 coverage = -1, tip = -1, hairShadow = -1;       // params
        bool coverageIsCutoff = false;
    } named;

    /** Resolves {@link named} from the names; called whenever params, textures or the special names change. */
    void resolveNamed() {
        const auto param = [this](const std::string& n) -> i32 {
            if (n.empty()) return -1;
            for (usize i = 0; i < params.size(); ++i) if (params[i].name == n) return static_cast<i32>(i);
            return -1;
        };
        const auto texture = [this](const char* n) -> i32 {
            for (usize i = 0; i < textures.size(); ++i) if (textures[i].name == n) return static_cast<i32>(i);
            return -1;
        };
        named.sceneColor = texture("u_sceneColor");
        named.sceneDepth = texture("u_sceneDepthMap");
        named.transmission = param("u_transmission");
        named.blendDistance = param("u_blendDistance");
        named.coverage = param(coverageParam);
        named.tip = param(tipParam);
        named.hairShadow = param(hairShadowParam);
        named.coverageIsCutoff = coverageParam == "u_alphaCutoff";
    }

    const MaterialParamSlot* find(const std::string& name) const {
        for (const auto& p : params) {
            if (p.name == name) return &p;
        }
        return nullptr;
    }
    const MaterialTextureSlot* findTexture(const std::string& name) const {
        for (const auto& t : textures) {
            if (t.name == name) return &t;
        }
        return nullptr;
    }
};

/**
 * @brief A material's resolved render state (P0) plus its packed std140 constants (P1).
 */
struct MaterialRecord {
    /// The identity: what the layout is filed under, and what survives the
    /// program being rebuilt. `shader` below caches what it currently resolves
    /// to, because the collect path reads that per entity.
    resource::ShaderHandle shaderRef;
    u32 shader = 0;  ///< Program id; 0 means "use the path's default batch shader".
    BlendMode blend = BlendMode::Normal;
    bool depthTest = false;
    bool depthWrite = true;
    CullMode cull = CullMode::None;
    /// Depth-buffer units toward the eye — what a surface laid ON another one
    /// says so it wins. @see PipelineDesc::depthBias.
    i16 depthBias = 0;

    /// Packed std140 MaterialConstants payload (sized to the shader's blockSize), the GPU
    /// UBO it uploads to (lazy), and whether the bytes changed since the last upload.
    std::vector<u8> uboBytes;
    BufferHandle ubo = BufferHandle::Invalid;
    bool uboDirty = false;

    /// Texture params bound to sampler units, by handle (see MaterialTextureBinding).
    std::vector<MaterialTextureBinding> textures;

    /// Changes whenever anything above does, or its shader's layout: see core/Revision.hpp and MaterialStore::revisionOf.
    u64 revision = 0;
};

/**
 * @brief Maps a material handle to its resolved record. Owned by RenderContext so it is
 *        reachable from both the SDK binding (push) and the render collect path (read).
 */
class MaterialStore {
public:
    MaterialStore() = default;
    ~MaterialStore();
    MaterialStore(const MaterialStore&) = delete;
    MaterialStore& operator=(const MaterialStore&) = delete;
    /// The render path uses this device to create/upload/delete per-material UBOs.
    void setDevice(GfxDevice* device) { device_ = device; }

    /// Resolves texture handles at bind time; without one, texture params bind nothing.
    void setResourceManager(resource::ResourceManager* resources);
    void forgetShader(resource::ShaderHandle shader);

    /// The context's built-in fallbacks.
    void setBuiltinDefaults(TextureHandle white, TextureHandle black, TextureHandle flatNormal, TextureHandle ripples) {
        defaultWhite_ = white;
        defaultBlack_ = black;
        defaultFlatNormal_ = flatNormal;
        defaultRipples_ = ripples;
    }

    /// The context's current fallback for a declared `default(...)`. One authority,
    /// so the post-process pipeline's params fall back to the same textures.
    TextureHandle builtinDefault(MaterialDefaultTexture which) const;
    /// The context's layers of white, black and a flat normal: what an unset `textureArray` param binds.
    void setBuiltinDefaultArrays(TextureHandle white, TextureHandle black, TextureHandle flatNormal) {
        defaultWhiteArray_ = white;
        defaultBlackArray_ = black;
        defaultFlatNormalArray_ = flatNormal;
    }
    /// What an unset param of `slot` binds: its declared default, as layers for an array (ripples are white there).
    TextureHandle builtinDefault(const MaterialTextureSlot& slot) const {
        if (!slot.layered) return builtinDefault(slot.defaultTexture);
        if (slot.defaultTexture == MaterialDefaultTexture::Black) return defaultBlackArray_;
        if (slot.defaultTexture == MaterialDefaultTexture::FlatNormal) return defaultFlatNormalArray_;
        return defaultWhiteArray_;
    }

    /**
     * @brief Point each of @p shader's texture params at its unit.
     *
     * @details GLSL ES 300 has no `layout(binding=)`, so a program carries this
     *          as uniform state.
     */
    static void seedSamplers(Shader& shader, const resource::ParsedShader& parsed);

    /// The layout a parsed shader's `#pragma param` reflection describes: the std140 block for the scalar and vector params (declared order
    /// is offset order) and a sampler slot for each texture param, at the unit the parser gave it. Material shaders and the chain's own
    /// last pass read their parameters through the same one.
    static MaterialUniformLayout layoutOf(const resource::ParsedShader& parsed);

    /// Keeps a material shader's SOURCE beside its handle, so the same material can
    /// be compiled for another vertex source later. Without it the store holds only
    /// the assembled program and a variant would need the author's file again.
    void rememberSource(resource::ShaderHandle shader, std::string source, std::string features) {
        if (shader.isValid()) {
            const bool mentionsGbuffer = source.find("ES_GBUFFER") != std::string::npos;
            const bool writesAlbedo = mentionsGbuffer && source.find("fragAlbedo") != std::string::npos;
            const bool takesLight = source.find("applyLighting") != std::string::npos;
            const bool mentionsOpaque = source.find("ES_OPAQUE") != std::string::npos;
            sources_[shader.id()] = { std::move(source), std::move(features), mentionsGbuffer, writesAlbedo, takesLight, mentionsOpaque };
        }
    }

    /// The program that draws @p materialId on resident geometry of this shape, compiled
    /// once and cached; 0 when the source was never kept or the variant fails, so the
    /// caller falls back rather than drawing it wrong.
    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 setLightingDirect(bool on) { lighting_direct_ = on; }
    bool lightingDirect() const { return lighting_direct_; }

    /// Whether @p programId is a variant that writes the surface record's second output — set when
    /// it was compiled for a pass that has one AND the material's shader has something to write
    /// (it mentions ES_GBUFFER). The draw list asks per command, so a pipeline says what its shader does.
    bool programWritesGBuffer(u32 programId) const {
        return gbuffer_programs_.count(programId) != 0;
    }
    /// Of those, the ones that also write the surface's diffuse colour (location 2, `fragAlbedo`).
    bool programWritesAlbedo(u32 programId) const {
        return albedo_programs_.count(programId) != 0;
    }
    /// A program that is not a material's — the engine's own mesh shader — says it writes the record.
    void markGBufferProgram(u32 programId, bool albedo) const {
        gbuffer_programs_.insert(programId);
        if (albedo) albedo_programs_.insert(programId);
    }

    /// The name of the shader @p materialId draws with, or "default" for the path's own batch shader.
    const std::string& shaderLabel(u32 materialId) const {
        static const std::string fallback = "default";
        const MaterialRecord* m = find(materialId);
        const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;
        return layout && !layout->name.empty() ? layout->name : fallback;
    }

    /// How far @p materialId's vertex hook can move a vertex from the mesh's own bounds, in the
    /// mesh's local units; 0 for a material without one.
    float vertexBounds(u32 materialId) const {
        const MaterialRecord* m = find(materialId);
        const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;
        return layout ? layout->vertexBounds : 0.0f;
    }

    /// Whether @p materialId bends its vertices (so its shadow has to bend too).
    bool hasVertexHook(u32 materialId) const {
        const MaterialRecord* m = find(materialId);
        const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;
        return layout && layout->vertexHook;
    }

    /// Whether @p materialId's caster has to be cut out by its alpha: its alpha is coverage now and the
    /// coverage param is the one the depth shader reads.
    bool castsCutoutShadow(u32 materialId) const {
        const MaterialRecord* m = find(materialId);
        const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;
        return layout && layout->named.coverageIsCutoff && alphaIsCoverage(materialId);
    }

    /// The program that draws @p materialId's CASTER into a shadow map: the engine's depth shader for
    /// resident meshes with the material's vertex hook and params grafted on, so a bent mesh casts the
    /// shadow of the bent shape. 0 when the source was never kept or the variant fails — the caller
    /// then casts the unbent shape, which is the old behaviour.
    u32 shadowProgram(u32 materialId, resource::ResourceManager& resources,
                      bool withNormals, bool skinned, bool tangents = false) const;

    /// The program that draws @p materialId's depth for the scene's prepass when its alpha is coverage: the engine's depth shader writing the coverage
    /// the material's own fragment writes, so under alpha-to-coverage the two pass draw the same samples. Only for the engine's Model shader, whose
    /// coverage it reproduces; 0 for anything else, for a bent vertex, and when the variant fails — the draw then takes no part in a prepass.
    u32 prepassCoverageProgram(u32 materialId, resource::ResourceManager& resources,
                               bool withNormals, bool skinned, bool tangents = false) const;

    /// The program that draws @p materialId on PARTICLE geometry — the instanced
    /// quad an emitter streams. Same source, same author's fragment, a different
    /// engine vertex stage; 0 on the same terms as {@link meshProgram}.
    u32 particleProgram(u32 materialId, resource::ResourceManager& resources) const;

    /// Registers (or replaces) a shader's MaterialConstants layout — called when a shader
    /// authored with #pragma param is compiled, so materials on it can pack their uniforms.
    /// Filed under the HANDLE, not the program id: rebuilding the program (a
    /// device loss, a shader reload) changes the id, and a layout filed under the
    /// old one would be unreachable from the material that still names it.
    void registerLayout(resource::ShaderHandle shader, MaterialUniformLayout layout) {
        if (!shader.isValid()) return;
        layout.resolveNamed();
        layouts_[shader.id()] = std::move(layout);
        // Every material on it now reads its params through another layout.
        reviseMaterialsOf(shader);
    }

    /**
     * @brief What @p materialId is, as a number that changes whenever it does: its state, a param, a texture, its shader's layout.
     * @return 0 for no material. A reader that derived something from a material keeps this beside it (see core/Revision.hpp).
     */
    u64 revisionOf(u32 materialId) const {
        const MaterialRecord* m = find(materialId);
        return m ? m->revision : 0;
    }

    /**
     * @brief Changes whenever any material does (revisionOf), or one is added or removed.
     * @details A reader that kept what it derived from many materials, or a pointer to a record, asks this once rather than
     *          revisionOf each: while it holds, every record kept is the one it was.
     */
    u64 revision() const { return store_revision_; }

    /// Pushes a material's resolved render state. Preserves any already-packed constants
    /// (an edit such as setBlendMode re-pushes state without clobbering uniforms); a shader
    /// change invalidates the old constants since the layout differs.
    void define(u32 materialId, const MaterialRecord& record) {
        if (materialId == 0) return;
        auto it = materials_.find(materialId);
        if (it == materials_.end()) {
            MaterialRecord& added = materials_[materialId];
            added = record;
            added.revision = revise();
            return;
        }
        MaterialRecord& rec = it->second;
        const bool shaderChanged = rec.shaderRef != record.shaderRef;
        const BufferHandle ubo = rec.ubo;
        std::vector<u8> bytes = std::move(rec.uboBytes);
        std::vector<MaterialTextureBinding> texs = std::move(rec.textures);
        rec = record;        // render state
        rec.ubo = ubo;       // keep the GPU buffer
        if (shaderChanged) {
            rec.uboBytes.clear();   // old layout invalid; re-packed on next set
            rec.textures.clear();
        } else {
            rec.uboBytes = std::move(bytes);
            rec.textures = std::move(texs);
        }
        rec.uboDirty = true; // re-upload on next bind
        rec.revision = revise();
    }

    /// Writes a named param's float components into the material's std140 buffer at the
    /// offset its shader's layout reflects. No-op if the material/layout/param is unknown.
    void setUniform(u32 materialId, const std::string& name, const f32* values, u32 arity) {
        auto it = materials_.find(materialId);
        if (it == materials_.end()) return;
        MaterialRecord& rec = it->second;
        auto lit = layouts_.find(rec.shaderRef.id());
        if (lit == layouts_.end()) return;
        const MaterialParamSlot* slot = lit->second.find(name);
        if (!slot) return;
        ensureDefaults(rec, lit->second);
        const u32 n = std::min(arity, slot->arity);
        std::memcpy(rec.uboBytes.data() + slot->offset, values, n * sizeof(f32));
        rec.uboDirty = true;
        rec.revision = revise();
    }

    /// Binds a texture to a named texture param's sampler unit. No-op if the material,
    /// its layout, or the texture param is unknown. Render path resolves it in bindForDraw.
    void setTexture(u32 materialId, const std::string& name, resource::TextureHandle texture) {
        auto it = materials_.find(materialId);
        if (it == materials_.end()) return;
        auto lit = layouts_.find(it->second.shaderRef.id());
        if (lit == layouts_.end()) return;
        const MaterialTextureSlot* slot = lit->second.findTexture(name);
        if (!slot) return;
        it->second.revision = revise();
        for (auto& b : it->second.textures) {
            if (b.unit == slot->unit) { b.texture = texture; return; }
        }
        it->second.textures.push_back({ slot->unit, texture });
    }

    void undefine(u32 materialId);

    /// The record for @p materialId, or nullptr if the handle is 0 / unregistered.
    const MaterialRecord* find(u32 materialId) const {
        if (materialId == 0) return nullptr;
        // Every question about a draw's material asks for it again: the last answer is kept, as layoutFor keeps its own.
        if (materialId == last_material_id_ && last_material_) return last_material_;
        auto it = materials_.find(materialId);
        last_material_id_ = materialId;
        last_material_ = it != materials_.end() ? &it->second : nullptr;
        return last_material_;
    }

    /** A float param of @p m by its layout index, or 0 when there is none or it is not packed. */
    static f32 paramValue(const MaterialRecord& m, const MaterialUniformLayout& layout, i32 index) {
        if (index < 0) return 0.0f;
        const MaterialParamSlot& slot = layout.params[static_cast<usize>(index)];
        if (slot.offset + sizeof(f32) > m.uboBytes.size()) return 0.0f;
        f32 value = 0.0f;
        std::memcpy(&value, m.uboBytes.data() + slot.offset, sizeof(f32));
        return value;
    }

    /// Whether @p materialId's shader reads the picture of what is behind it (declares `u_sceneColor`): refraction, a lens, anything
    /// that has to see the opaque scene as it stood before this draw. Such a draw is made after a copy of that picture is taken.
    bool usesSceneColor(u32 materialId) const {
        const MaterialRecord* m = find(materialId);
        const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;
        if (!layout || layout->named.sceneColor < 0) return false;
        // A shader that has a `u_transmission` (the Model shader, whose material is mostly opaque) asks for the copy only while
        // the material holds it above zero; one that has none always does.
        if (layout->named.transmission < 0) return true;
        return paramValue(*m, *layout, layout->named.transmission) > 0.0f;
    }
    /// The copy of the opaque scene the frame took for the draws above, or invalid when it took none. Bound to a material's
    /// `u_sceneColor` unit unless the material was given a texture of its own there.
    void setSceneColor(TextureHandle texture) { sceneColor_ = texture; }

    /// Whether @p materialId's shader reads how far the opaque scene behind it is (declares `u_sceneDepthMap`): water measuring its
    /// own depth, a fade where a surface meets what it lies on. Such a draw is also made after the scene's copy.
    bool usesSceneDepth(u32 materialId) const {
        const MaterialRecord* m = find(materialId);
        const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;
        return layout && layout->named.sceneDepth >= 0;
    }
    /// Whether @p materialId is nothing without that copy: it fades into what is behind it, where water only falls back to a plainer look.
    /// Seeing one is why a frame with no chain of its own takes one.
    bool needsScenePicture(u32 materialId) const {
        const MaterialRecord* m = find(materialId);
        const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;
        return layout && layout->named.blendDistance >= 0;
    }
    /// The copy of the opaque scene's distances the frame took, or invalid when it took none. Bound to a material's `u_sceneDepthMap` unit.
    void setSceneDepth(TextureHandle texture) { sceneDepth_ = texture; }

    /// Whether @p materialId's output alpha is coverage now: its shader names a
    /// coverage param and this material holds it above zero.
    bool alphaIsCoverage(u32 materialId) const {
        const MaterialRecord* m = find(materialId);
        const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;
        if (!layout) return false;
        return paramValue(*m, *layout, layout->named.coverage) > 0.0f;
    }

    /// Whether @p materialId draws a blended pass over its opaque one: its shader names a tip param and this
    /// material holds it above zero.
    bool hasTipPass(u32 materialId) const {
        const MaterialRecord* m = find(materialId);
        const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;
        if (!layout) return false;
        return paramValue(*m, *layout, layout->named.tip) > 0.0f;
    }

    /// The hair shadow density @p materialId holds (see ParsedShader::hairShadowParam), 0 when its shader has none or it is off.
    f32 hairShadowDensity(u32 materialId) const {
        const MaterialRecord* m = find(materialId);
        const MaterialUniformLayout* layout = m ? layoutFor(m->shaderRef) : nullptr;
        if (!layout) return 0.0f;
        const f32 value = paramValue(*m, *layout, layout->named.hairShadow);
        return value > 0.0f ? value : 0.0f;
    }

    /// The registered #pragma-param layout for a shader program, or nullptr.
    /// The post-process pipeline reads it to pack pass params through the same
    /// reflected MaterialConstants block a material would use.
    const MaterialUniformLayout* layoutFor(resource::ShaderHandle shader) const {
        // Asked for the same shader by every mesh on it, several times each: the last answer is kept. Node-based, so an answer
        // stays where it is while others are added; only an erase moves it, and forgets it (forgetLookups).
        const u32 id = shader.id();
        if (id == last_layout_id_ && last_layout_) return last_layout_;
        auto it = layouts_.find(id);
        last_layout_id_ = id;
        last_layout_ = it != layouts_.end() ? &it->second : nullptr;
        return last_layout_;
    }

    /// Uploads (when dirty) and binds the material's MaterialConstants UBO at binding 1.
    /// No-op for materials whose shader declares no params (uboBytes stays empty).
    /** Binds the material's block and its textures; a texture only where @p samplerUnits says the bound program reads its unit. */
    void bindForDraw(u32 materialId, u32 samplerUnits = 0xFFFFFFFFu);

    /**
     * @brief Binds a material's values for a draw through another shader: what a pass that draws a material's surface somewhere else
     *        (a bake into a texture) reads, as Unreal draws a material to a render target.
     * @details Matched by NAME, so the two need not lay their params out alike: each param of @p shader takes the material's value of
     *          the param of the same name (else its own default), each texture the material's texture of the same name (else its
     *          default). @p overrides then replace vec4 params for this draw alone. The block goes into scratch buffer @p scratch, one
     *          per draw of a frame: on WebGPU a buffer rewritten between draws of one frame holds its last contents for all of them.
     * @return False when the material or the shader's layout is unknown.
     */
    bool bindThrough(u32 materialId, resource::ShaderHandle shader,
                     const std::vector<std::pair<std::string, glm::vec4>>& overrides, u32 scratch);

    /// Says what a world unit is (the project's units per metre). A param a material left at its default follows the change;
    /// one it set, to anything else, is the material's and stays.
    void setWorldUnitsPerMeter(f32 unitsPerMeter);

    /// Frees every per-material GPU UBO and clears all records/layouts. Call while the
    /// device is still valid (RenderContext::shutdown).
    void clear();

private:
    /// Fills an unpacked block with the shader's param defaults, so a material that never
    /// sets a param still draws with the declared default(...) values (not zeros).
    void ensureDefaults(MaterialRecord& rec, const MaterialUniformLayout& layout) const {
        if (layout.blockSize == 0 || rec.uboBytes.size() >= layout.blockSize) return;
        rec.uboBytes.resize(layout.blockSize, 0);
        for (const auto& p : layout.params) {
            f32 value[4];
            defaultInUnits(p, world_unit_scale_, value);
            std::memcpy(rec.uboBytes.data() + p.offset, value, p.arity * sizeof(f32));
        }
        rec.uboDirty = true;
    }

    /// A slot's default at @p scale units to the reference: a length times it, a rate per length over it, any other as declared.
    static void defaultInUnits(const MaterialParamSlot& p, f32 scale, f32* out) {
        const f32 k = p.worldUnits > 0 ? scale : p.worldUnits < 0 ? 1.0f / scale : 1.0f;
        for (u32 i = 0; i < 4; ++i) out[i] = p.defaults[i] * k;
    }

    /// The project's units per metre over the reference 100: what a world-unit default is scaled by.
    f32 world_unit_scale_ = 1.0f;

    std::unordered_map<u32, MaterialRecord> materials_;
    std::unordered_map<u32, MaterialUniformLayout> layouts_;
    /// The blocks bindThrough writes, one per draw of a frame, and their sizes.
    std::vector<std::pair<BufferHandle, u32>> through_ubos_;
    /// The last material and layout asked for (find, layoutFor); forgotten whenever either map erases (forgetLookups).
    mutable u32 last_material_id_ = 0;
    mutable const MaterialRecord* last_material_ = nullptr;
    mutable u32 last_layout_id_ = 0;
    mutable const MaterialUniformLayout* last_layout_ = nullptr;
    void forgetLookups() {
        last_material_ = nullptr; last_material_id_ = 0; last_layout_ = nullptr; last_layout_id_ = 0;
        // A record went: a pointer anyone kept to one may be to it.
        store_revision_ = nextRevision();
    }
    /// The revision a changed material takes, which the store as a whole takes too.
    u64 revise() { return store_revision_ = nextRevision(); }
    u64 store_revision_ = nextRevision();
    /** Every material on @p shader takes a new revision: its layout changed or went. */
    void reviseMaterialsOf(resource::ShaderHandle shader) {
        for (auto& [id, rec] : materials_) if (rec.shaderRef == shader) rec.revision = revise();
    }

    /// A material shader's authored source + features, filed under its handle for
    /// the same reason the layout is: a rebuilt program changes the id.
    struct ShaderSource {
        std::string source;
        std::string features;
        /// Whether the source mentions ES_GBUFFER, found once when it is stored: the mesh path asks it for every draw, and the answer was a
        /// substring search through the whole text each time.
        bool mentionsGbuffer = false;
        /// Whether its gbuffer variant also writes `fragAlbedo` (location 2): a shader written before the
        /// attachment existed writes two outputs, and its pipeline must leave the third alone.
        bool writesAlbedo = false;
        bool takesLight = false;
        /// Whether the source has an ES_OPAQUE branch: only then is an unblended draw worth a program of its own.
        bool mentionsOpaque = false;
    };
    std::unordered_map<u32, ShaderSource> sources_;
    bool lighting_direct_ = false;
    /// (Handle, vertex source) → the program compiled for it (0 = tried and
    /// failed). Mutable because compiling it is memoization: the collect path
    /// asks a read-only store, and the answer is the same every time.
    // Indexed first by source shader: retirement touches only its own variants.
    // Handles resolve to the current device program, including after recovery.
    mutable std::unordered_map<u32, std::unordered_map<u64, resource::ShaderHandle>> mesh_programs_;
    /// Programs compiled with ES_GBUFFER (see programWritesGBuffer).
    mutable std::unordered_set<u32> gbuffer_programs_;
    /// Of those, the ones that write `fragAlbedo` too (see programWritesAlbedo).
    mutable std::unordered_set<u32> albedo_programs_;
    TextureHandle sceneColor_ = TextureHandle::Invalid;
    TextureHandle sceneDepth_ = TextureHandle::Invalid;

public:
    /** @brief How many material program variants have been built. A prewarm counts
     *         what it caused by the difference, rather than by asking again. */
    u32 builtVariantCount() const {
        u32 count = 0;
        for (const auto& [shader, variants] : mesh_programs_) count += static_cast<u32>(variants.size());
        return count;
    }

private:

    /// One material compiled for one vertex source: @p shape distinguishes the
    /// cache entries, @p extraFeatures the engine vertex stage, @p what the log.
    u32 variantProgram(u32 materialId, resource::ResourceManager& resources,
                       u64 shape, std::vector<std::string> extraFeatures,
                       const char* what) const;
    GfxDevice* device_ = nullptr;
    resource::ResourceManager* resources_ = nullptr;
    TextureHandle defaultWhite_ = TextureHandle::Invalid;
    TextureHandle defaultBlack_ = TextureHandle::Invalid;
    TextureHandle defaultFlatNormal_ = TextureHandle::Invalid;
    TextureHandle defaultRipples_ = TextureHandle::Invalid;
    TextureHandle defaultWhiteArray_ = TextureHandle::Invalid;
    TextureHandle defaultBlackArray_ = TextureHandle::Invalid;
    TextureHandle defaultFlatNormalArray_ = TextureHandle::Invalid;
};

}  // namespace esengine