Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
MaterialBindings.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
9#include "ActiveContext.hpp"
10
11#include "../core/Log.hpp"
18
19#include <algorithm>
20#include <cstdlib>
21
22namespace esengine {
23
24static EstellaContext& ctx() { return activeCtx(); }
25
26#define g_renderContext (ctx().tryGet<RenderContext>())
27#define g_resourceManager (ctx().tryGet<resource::ResourceManager>())
28
29u32 material_compileEsshader(const std::string& source, const std::string& featuresCsv) {
30 auto* rm = g_resourceManager;
31 if (!rm) return 0;
33 if (!parsed.valid) {
34 ES_LOG_ERROR("material_compileEsshader: parse failed: {}", parsed.errorMessage);
35 return 0;
36 }
37 const std::vector<std::string> features = resource::ShaderParser::splitFeatures(featuresCsv);
38 // Assemble both stages for the backend's language — a material .esshader
39 // carries its WGSL twin in-file, and a missing twin surfaces here as a
40 // descriptive assembly error rather than a backend compile failure.
41 const auto target = rm->preferredShaderTarget();
42 const std::string vert = resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "", features, target);
43 const std::string frag = resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment, "", features, target);
44 if (vert.empty() || frag.empty()) {
45 ES_LOG_ERROR("material_compileEsshader: stage assembly failed for '{}'", parsed.name);
46 return 0;
47 }
48 // No DrawParams rewrite: assembled material sources already carry their
49 // params in MaterialConstants; only sampler uniforms remain loose.
50 // A material shader the package ships, and a post-process effect: both known to compile, so with the async policy on they are queued
51 // and waited for by whoever draws with them, not one by one here.
52 resource::ShaderHandle handle = rm->createShader(vert, frag, /*rewriteLoose=*/false,
53 rm->preferredShaderLanguage(), rm->deferLinks());
54 if (!handle.isValid()) return 0;
55 if (auto* rc = g_renderContext) {
56 if (Shader* s = rm->getShader(handle)) {
57 rc->materials().registerLayout(handle, MaterialStore::layoutOf(parsed));
58 // Kept so the same material can be compiled for another vertex source
59 // (GPU-resident geometry) without the author's file being read again.
60 rc->materials().rememberSource(handle, source, featuresCsv);
61 // Through the store's own seeding, not a copy of it: a device
62 // recovery has to redo exactly this, and two spellings of "which
63 // unit does this sampler read" is how one of them stops being done.
65 }
66 }
67 return handle.id();
68}
69
70void material_define(u32 materialId, u32 shaderHandle, u32 blendMode, u32 flags,
71 i32 depthBias) {
72 auto* rc = g_renderContext;
73 if (!rc) return;
74 // The handle is the identity; the program id is a cache of what it currently
75 // resolves to, refreshed by refreshShaderPrograms when the device rebuilds it.
77 rec.shaderRef = resource::ShaderHandle(shaderHandle);
78 if (auto* rm = g_resourceManager) {
79 if (Shader* s = rm->getShader(rec.shaderRef)) rec.shader = s->getProgramId();
80 }
81 rec.blend = static_cast<BlendMode>(blendMode);
82 rec.depthTest = (flags & 0x1u) != 0;
83 rec.depthWrite = (flags & 0x2u) != 0;
84 rec.cull = static_cast<CullMode>((flags >> 2) & 0x3u);
85 // Its own parameter and not another flag bit: this is a VALUE, and packing
86 // one into a word of booleans is how two sides come to disagree about it.
87 rec.depthBias = static_cast<i16>(std::clamp(depthBias, -32768, 32767));
88 rc->materials().define(materialId, rec);
89}
90
91void material_setUniform(u32 materialId, const std::string& name, u32 arity,
92 f32 v0, f32 v1, f32 v2, f32 v3) {
93 auto* rc = g_renderContext;
94 if (!rc) return;
95 const f32 vals[4] = { v0, v1, v2, v3 };
96 rc->materials().setUniform(materialId, name, vals, arity);
97}
98
99void material_setTexture(u32 materialId, const std::string& name, u32 textureHandle) {
100 auto* rc = g_renderContext;
101 if (!rc) return;
102 // The handle is stored as-is. Resolving it here would freeze the material to
103 // the GPU object the texture happened to have at this moment, which is the
104 // one thing a re-upload behind that handle must not need to undo.
105 rc->materials().setTexture(materialId, name, resource::TextureHandle(textureHandle));
106}
107
108void material_undefine(u32 materialId) {
109 if (auto* rc = g_renderContext) rc->materials().undefine(materialId);
110}
111
112} // namespace esengine
#define g_renderContext
#define g_resourceManager
Logging utilities for ESEngine.
#define ES_LOG_ERROR(...)
Logs an error message.
Definition Log.hpp:296
Material + .esshader entry points, for whichever core is embedded.
Engine-side material registry — the resolved "how to draw" for a material handle.
Rendering context containing all renderer state.
Central resource management system.
Parser for unified .esshader file format.
GPU shader program abstraction.
GPU texture abstraction for 2D images.
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.
GPU shader program for rendering.
Definition Shader.hpp:86
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
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.
Handle< esengine::Shader > ShaderHandle
Handle to a shader resource.
Definition Handle.hpp:214
Handle< esengine::Texture > TextureHandle
Handle to a texture resource.
Definition Handle.hpp:217
void material_setUniform(u32 materialId, const std::string &name, u32 arity, f32 v0, f32 v1, f32 v2, f32 v3)
u32 material_compileEsshader(const std::string &source, const std::string &featuresCsv)
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
void material_setTexture(u32 materialId, const std::string &name, u32 textureHandle)
void material_define(u32 materialId, u32 shaderHandle, u32 blendMode, u32 flags, i32 depthBias)
std::int16_t i16
Signed 16-bit integer.
Definition Types.hpp:52
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
BlendMode
Predefined blend modes for rendering.
Definition BlendMode.hpp:22
void material_undefine(u32 materialId)
static EstellaContext & ctx()
EstellaContext & activeCtx()
The engine context every binding routes through — single source of truth.
CullMode
Triangle culling mode baked into a material's pipeline.
float f32
32-bit floating point
Definition Types.hpp:59
A material's resolved render state (P0) plus its packed std140 constants (P1).
resource::ShaderHandle shaderRef
u32 shader
Program id; 0 means "use the path's default batch shader".
Result of parsing an .esshader file.
std::string errorMessage
Parse error if any.
bool valid
True if parsing succeeded.
std::string name
Shader name.