Custom Material Nodes
How the material node graph is compiled, how to add a built-in node to the engine, and how to add a shader-language backend for code shaders. The catalogue of existing nodes is Material Nodes Reference; the runtime material API is Material API.
Where this lives
Materials belong to crates/renzora_shader, which declares two Runtime plugins in its manifest, so both ship in the editor and in games:
ShaderPlugin: the code-shader runtime and the built-in shader-language backends.material::MaterialPlugin: the node-graph material runtime and the resolver that turns a.materialgraph into a renderable Bevy material.
The two editors are separate Editor-scope plugins: MaterialEditorPlugin (renzora_material_editor, the visual graph) and ShaderEditorPlugin (renzora_shader_editor, the code editor).
Graph node types are compiled into renzora_shader. There is no runtime API for registering a new node type, and a native plugin cannot add one: adding a node is an engine-source change, below. Without editing the engine you have three tools: a material function (a saved subgraph, called like a node), a custom/code node (a few lines of shader code inside a graph), and a code shader.
How a graph compiles
A material is a MaterialGraph saved as a .material file (JSON). The compiler:
- finds the graph's output node (
output/surface,output/vegetation,output/unlitoroutput/sprite, by the graph'sdomain); - walks backwards through the connections from it;
- emits a small snippet per node, naming intermediate variables and inserting casts where a wire changes type;
- composes the snippets into a complete WESL material shader.
Nodes are therefore compile-time: they produce shader code, not runtime logic. When the editor saves a graph it stores the result in the graph's compiled field, so the runtime skips codegen entirely.
The data model
In renzora_shader::material::graph:
| Type | Purpose |
|---|---|
MaterialGraph | the whole material: name, domain, nodes, connections, alpha_mode, double_sided, compiled |
MaterialNode | one placed node: id, node_type, position, input_values |
Connection | a wire: from_node, from_pin, to_node, to_pin. An input accepts one connection |
PinTemplate | a declared pin: name, label, pin_type, direction, default_value |
PinValue | a concrete value stored on an input pin |
MaterialDomain | Surface, Vegetation, Unlit or Sprite (TerrainLayer in older files reads as Surface) |
A node stores only overrides in input_values; an unconnected pin with no override uses its template's default_value.
PinType is Float, Vec2, Vec3, Vec4, Color (same shader type as Vec4, edited with a picker), Bool, Texture2D, Sampler or String (never reaches the shader; used for names). The numeric types convert freely at the graph level: PinType::compatible allows the wire and PinType::cast_expr inserts the coercion.
math/* pins are dynamic: a math node latches to the widest type wired into any input (Float < Vec2 < Vec3 < Vec4), and its other inputs and result adopt it. When a node's code guards against a scalar (max(x, 0.000001)), emit the guard at the latched rank with Ctx::guard_lit; a bare scalar under a latched vector node is a type error.
Adding a built-in node
Three edits in crates/renzora_shader/src/material.
1. Declare it in the category's module under nodes/ (here nodes/math.rs):
pub static POSTERIZE: MaterialNodeDef = MaterialNodeDef {
node_type: "math/posterize",
display_name: "Posterize",
category: CAT_MATH,
description: "Quantize a value into N discrete steps",
pins: || {
vec![
PinTemplate::input("value", "Value", PinType::Float).with_default(PinValue::Float(0.5)),
PinTemplate::input("steps", "Steps", PinType::Float).with_default(PinValue::Float(4.0)),
PinTemplate::output("result", "Result", PinType::Float),
]
},
color: [120, 120, 120], // header colour in the graph
};
2. Register it by adding it to ALL_NODES in nodes/mod.rs, in its category's block. node_def(node_type), nodes_in_category(category) and the editor's palette all read that list.
3. Generate code with an arm in the category's emitter, codegen/emit/math.rs (gen_math_node):
"math/posterize" => {
let value = self.input(node, "value"); // the wire's expression, or the pin default
let steps = self.input(node, "steps");
let v = self.next_var("posterize"); // a fresh, collision-free name
self.emit(format!(" let {v} = floor({value} * {steps}) / {steps};"));
self.set_out(id, "result", v); // publish the output for downstream nodes
}
Ctx::gen_node_body (in codegen/ctx.rs) splits node_type at its first / and hands the node to that category's emitter; an unknown type becomes a comment in the generated shader rather than an error. A new category therefore also needs a CAT_ constant and an entry in categories(), an emitter module, and an arm in gen_node_body.
| Helper | Does |
|---|---|
self.input(node, "pin") | the expression feeding an input (an upstream output, or the pin's literal default), already cast to the pin's type |
self.next_var("prefix") | allocates a unique variable name |
self.emit(line) | appends a line to the function body |
self.set_out(id, "pin", expr) | records the expression for one of this node's outputs |
Ctx::guard_lit(type, lit) | a literal splatted to a pin type, for guards in dynamic nodes |
The node_type string in the definition and in the emitter's arm must match exactly: it is the only link between them.
Parameters and instances
param/* nodes are named inputs at the graph's boundary: the name pin is the identifier, the default pin the value compiled into the master shader. A graph may declare up to MAX_PARAMETER_SLOTS (32). A material instance is a .material that references a master and overrides parameters by name without recompiling the shader. Older .material_instance files still load.
Material functions
A material function is a subgraph bracketed by a function/input_point node and a function/output_point node. Other graphs invoke it with a function/call node; at compile time each call becomes a helper function at module scope, called at the call site. Recursive cycles are detected and reported.
Code shaders and shader backends
For shader code, renzora_shader has an extension point: the ShaderBackend trait and the ShaderBackendRegistry resource. A backend translates a source language into shader code Bevy can build.
pub trait ShaderBackend: Send + Sync + 'static {
fn name(&self) -> &str;
fn file_extensions(&self) -> &[&str];
fn to_wgsl(&self, source: &str) -> Result<String, ShaderCompileError>;
// optional
fn builtin_uniforms(&self) -> &[UniformMapping] { &[] }
fn syntax_tokens(&self) -> Option<&[SyntaxRule]> { None }
}
The built-in backends, registered by ShaderPlugin:
| Backend | Extensions | Does |
|---|---|---|
| Bevy | bevy.wgsl | the pre-0.20 #import / #ifdef dialect, translated to WESL |
| WESL | wesl | passed through; Bevy's WESL compiler resolves imports when the pipeline is built |
| WGSL | wgsl | plain WGSL, validated with naga |
| GLSL | glsl, frag, vert | GLSL fragment shaders translated through naga |
| ShaderToy | shadertoy | wraps a mainImage(...) and maps iTime, iResolution, iMouse, iTimeDelta and iFrame onto the engine's uniforms |
A new backend registers into the registry from an in-workspace crate that depends on renzora_shader, after ShaderPlugin has created the resource:
use renzora_shader::registry::ShaderBackendRegistry;
impl Plugin for MyHlslPlugin {
fn build(&self, app: &mut App) {
app.world_mut()
.resource_mut::<ShaderBackendRegistry>()
.register(Box::new(HlslBackend));
}
}
A native plugin cannot do this: renzora_shader is an engine crate, not part of the contract a plugin links.
@param constants
Code shaders expose editable constants through @param comments, which the Shader Editor shows as controls and the registry compiles into const declarations:
// @param name type default [min max] description
// @param speed float 1.0 0.1 5.0 Animation speed
// @param tint color 1.0 0.8 0.6 1.0
// @param offset vec2 0.0 0.0
// @param enabled bool true
// @param count int 4