Three.js Node-Based Material Editor (Shader Graph)
A working node-graph material editor in Three.js where you drag nodes, wire outputs to inputs and see the graph compiled to GLSL and applied live, with UV, position, noise, stripes, fresnel, math nodes and presets.
Key topics: three.js shader graph, node editor, material editor, glsl generation, visual programming, shadermaterial
Game Over
What this code does
- Graph Model: nodes have typed inputs and one output; for simplicity every value is a vec3, with scalars broadcast.
- Code Generation: compiling recurses from the Output node, emitting each node once as `vec3 nX = …;`, with a guard against cycles.
- Live Compile: each edit builds a new `ShaderMaterial` and swaps it onto the preview mesh.
- Lighting: the generated albedo, emissive and roughness feed a small Blinn-Phong shader.
- Editing: drag headers to move, drag from a blue output to a purple input to connect, and drag an input away to disconnect.
- Presets: lava (warped noise), hologram (stripes + fresnel), candy stripes and normal debug.
- Controls: preset graph, preview mesh, generated GLSL and add-node buttons.
Related Demos
Continue Learning
JavaScript Implementation
// Node graph → GLSL: emit each node once (memoised), recursing through its inputs
function emit (node, lines, done) {
if (done.has(node)) return done.get(node)
const inputs = {}
for (const name of NODE_TYPES[node.type].inputs) {
const link = links.find(l => l.to === node && l.input === name)
inputs[name] = link ? emit(link.from, lines, done) : 'vec3(0.0)'
}
const v = 'n' + node.id
lines.push(`vec3 ${v} = ${NODE_TYPES[node.type].glsl(inputs, node.params)};`) // e.g. mix(n1, n2, n3.x)
done.set(node, v)
return v
}
// then build `void main () { ...lines; gl_FragColor = vec4(albedoVar, 1.0); }` and assign a new ShaderMaterial