Shaders
Updated
A shader is a small program that runs on the graphics card and decides the position and colour of every point of a surface. The Shader Material draws a mesh with one: either a preset the engine ships (hologram, toon, frozen, lava and more), a preset a script registers, or code you write. MIRA shaders are written much like Behavior scripts: #pragma lines declare the setup, the hooks, the inputs and the editable values, and hook functions hold the GLSL code. This page covers the component, the shader language, the built-in presets, textures, and how scripts drive all of it.
Before you start
Section titled “Before you start”- Materials. The Shader Material is one of the material kinds and takes the entity’s single material slot. See Materials.
- Pragmas and hooks. Behavior scripts declare hooks with
#pragma lifecycle(...); shaders use the same idea. See Scripting. - GLSL is the language graphics cards run. You only need it to write your own shaders; using presets needs none.
- Vectors and colours. In GLSL,
vec3holds three numbers: a position, a direction or an RGB colour.
Key ideas
Section titled “Key ideas”- Preset. A named shader source in the app’s registry. A Shader Material draws one by setting its
presetprop. The registry is theShaderPresetglobal. - Uniform. A value the shader reads that stays the same across the whole draw, such as a tint colour or a speed. Declared with
#pragma uniform, it becomes an editor field and a key in the material’suniformsprop. Changing a uniform value is cheap: no rebuild. - Hook. A function MIRA calls at a stage of drawing:
vertexto move points,fragmentto colour pixels,rampto shape toon lighting. - Input. Live data the engine feeds a shader:
time, thepointer, the entity’sbounds. - Pass. An extra draw built from the mesh, such as a glowing shell, an ink outline or sparks.
- Variant. A named set of uniform values a preset offers, such as the hologram’s Blue, Cyan or Amber.
Shader Material
Section titled “Shader Material”ShaderMaterialComponent · comp-shader-material
| Prop | Type | Default | Description |
|---|---|---|---|
preset |
string |
'custom' |
A shader from Shader, or 'custom' to draw shader. |
shader |
string |
a starter source | The material’s own shader source, drawn when preset is 'custom'. |
uniforms |
object |
{} |
Values of the shader’s #pragma uniform inputs, by name. A missing one takes the pragma’s default. |
color |
string | number |
'#ffffff' |
Where the surface colour starts; color in a raw shader. |
opacity |
number |
1 |
0 to 1. Where the surface alpha starts; opacity in a raw shader. |
wireframe |
boolean |
false |
Draw edges only. |
side |
'front' | 'back' | 'double' |
'front' |
Which faces render. |
How the props behave:
- By reference. A preset is read from the registry each time the material is built, so a fix to a preset reaches every entity that names it.
shaderis kept while a preset is chosen, so switching back to'custom'restores it. - Values follow the shader. Values for uniforms the active shader does not declare are dropped. Numbers clamp to the pragma’s
minandmax. - Unknown preset. A name not yet registered draws nothing until a script registers it; the material then builds itself.
- Errors. A source with a bad pragma or a missing hook makes
setPropsthrow, with the line. A GLSL compile error is reported once, and the mesh draws nothing until the shader is fixed. - On models a surface shader (unlit, lit or toon) restyles each of the model’s own materials, keeping its texture, transparency and side. A
rawshader draws every mesh with one material.
Script members
Section titled “Script members”| Member | What it does |
|---|---|
material. |
The source drawn now: the preset’s, or shader. undefined while the preset is unknown. |
material. |
Reads the source drawn now as the editor does: its shader info, material settings, hooks, inputs, uniforms, variants, passes and error. |
Shader |
The same reading for any source string, before you use it. |
material. |
On a loaded model whose Shader Material is disabled, draw a registered preset for this instance only. Returns true when applied, false when the preset is unknown or the material is enabled. Call with no arguments to clear. |
material. |
On a loaded model, override one numeric uniform for this instance only, updated in place on repeated calls. Call with no arguments to clear. |
Transient overrides are local: they are not saved and not sent to other players.
The ShaderPreset registry
Section titled “The ShaderPreset registry”| Global | What it is |
|---|---|
ShaderPreset | The app's shader presets, by name: ShaderPreset.list(), get(name), register(source); a Shader Material draws one with setProps({ preset: name }). |
ShaderMaterialComponent | A material drawn by a shader written like a Behavior script, or by a named preset of one. |
ShaderTextureComponent | An image its entity's Shader Material reads through one #pragma uniform(…, type=Texture), named by uniform. An entity has one per texture; without one, or while it loads, the uniform reads white. Swapping the image updates the shader in place, without rebuilding it. |
| Member | What it does |
|---|---|
Shader |
Every preset available to scene materials, each { name, label, description }, in registration order. |
Shader |
The source of name, or undefined when there is none. |
Shader |
Add a source under its #pragma shader name. Throws on a bad source, a missing #pragma shader, the name custom, or a name already taken. Materials waiting for that name build themselves. |
Default presets
Section titled “Default presets”Every app’s registry starts with these presets, designed for VR and phones: lit by the scene’s own lights, with every animation running on the graphics card.
| Preset | Look | Variants |
|---|---|---|
hologram |
See-through hologram with rolling scanlines and a glowing, flickering rim | Blue, Cyan, Amber, Mint, Rose |
toon |
Lighting flattened into two soft tones over the model’s own colours, with a thin ink outline | Subtle, Anime, Comic, Ghibli, Mono |
burn |
The surface burns away behind a flame front, with char and embers | Wood, Gas, Copper, Lithium |
spectral |
A translucent ghost with flowing ectoplasm and glitch slices | Wraith, Phantom, Poltergeist, Banshee |
electricArc |
Lightning jumping between points on the surface | Storm, Sith, Toxic, Arcane |
plasma |
Plasma flowing over the body, a hot core and a glowing shell | Ion, Inferno, Venom, Nova |
lava |
Basalt plates split by glowing magma cracks | Magma, Hellfire, Sulfur, Cobalt |
energy |
Twisting energy ribbons and a hazy rim | Arcane, Frost, Fel, Solar |
frozen |
Glassy ice creeping over the surface behind a frosty front | Glacier, Frostbite, Arctic, Cryo |
holoFoil |
Angle-shifting rainbow foil with sparkling flakes | Rainbow, Pearl, Beetle, Sunset |
fireAura |
Flames licking off the silhouette over burning skin | Inferno, Soulfire, Hellfire, Witchfire |
reboot |
A sweep rebuilds the surface tile by tile, shedding pixels | Reboot, Legend, Glitch, Matrix |
stench |
Soft fumes rising off the body | Stink, Toxic, Rot, Miasma |
blood |
Tap the model to splatter it; splashes drip, dry and fade | Blood, Zombie, Alien, Ichor |
The shader language
Section titled “The shader language”A source is GLSL with pragma lines. The pragma lines are removed before compiling; their options use the same grammar as script slots, so values may be numbers, true, quoted text or [lists].
#pragma shader(name=pulse, label="Pulse", description="A glow that beats.")#pragma material(shading=unlit, blending=additive, depthWrite=false)#pragma lifecycle(fragment)#pragma input(time)#pragma uniform(ref=tint, type=Color, default=0x00ffaa, group="Look")#pragma uniform(ref=rate, type=Slider, min=0.5, max=8, step=0.1, default=4)#pragma variant(name=Mint, swatch="#00ffaa", tint=0x00ffaa)#pragma variant(name=Rose, swatch="#ff3fa4", tint=0xff3fa4)
void fragment(inout Surface s) { s.emissive = tint * (0.5 + 0.5 * sin(time * rate));}| Pragma | Options | Default |
|---|---|---|
#pragma shader(... |
name (one word: the registry key), label, description. Needed to register a preset. |
none |
#pragma material(... |
shading: unlit, lit, toon or raw. blending: normal or additive. depthWrite, shadows: true or false. |
unlit, normal, true, true |
#pragma lifecycle(... |
The hooks: vertex, fragment, and ramp for toon; startup, update and dispose for the shader’s own script. hook=function names another function. |
the functions named vertex and fragment |
#pragma input(... |
time, pointer, bounds, smoothNormals. |
none |
#pragma uniform(... |
An editable value. See Uniforms. | |
#pragma variant(... |
name, swatch (a CSS colour for the editor button), then ref=value for any uniform, color and opacity. |
|
#pragma pass(... |
An extra draw. See Passes. |
Shading and hooks
Section titled “Shading and hooks”| Shading | Lighting | vertex hook |
fragment hook |
|---|---|---|---|
unlit |
None | void vertex(inout Vertex v), optional |
void fragment(inout Surface s), optional; output is s. |
lit |
Every scene light and light probe: a soft diffuse term and a highlight that s.roughness sharpens, plus s.emissive |
same | same; s.color is the base colour, s.metalness tints the highlight |
toon |
Every scene light in two tones, shaped by an optional vec3 ramp(float light) hook (light is 0 facing away to 1 facing the light) |
same | same |
raw |
Your own | void vertex(): the whole vertex stage; it sets gl_Position |
void fragment(): the whole fragment stage; it sets gl_FragColor |
unlit, lit and toon build one lean shader around your hooks, so instancing, skinning, morphs, vertex colours, a model’s textures, fog and clipping keep working, and the shader compiles fast. They have no physically based shading, no environment light and receive no shadows. A source with no fragment hook keeps the surface’s own colours.
The data your hooks receive:
struct Vertex { vec3 position; vec3 normal; }: in the object’s own space, after skinning and morphs. Changepositionto move the surface.struct Surface { vec3 color; float alpha; vec3 emissive; float roughness; float metalness; vec3 normal; }:colorstarts as the material’scolortimes its texture,alphaasopacity.- Varyings, available when a source uses them:
vLocalPositionandvLocalNormal(object space),vWorldPosition,vWorldNormal,vEntityPosition(needs theboundsinput) andvUv.cameraPositionis each eye’s in a headset.
Everything outside a hook (constants, helper functions) is shared by every stage. SHADER_VERTEX or SHADER_FRAGMENT is defined in each stage, SHADER_RAW in raw stages and SHADER_SHADOW in the shadow pass, so stage-specific code can sit inside #ifdef.
Uniforms
Section titled “Uniforms”#pragma uniform declares the GLSL uniform for you (do not declare it again) and gives it an editor field. It takes ref, type, label, tooltip, group, default, min, max, step, items, enabled and visible, plus define and size.
type |
GLSL | Value in uniforms |
|---|---|---|
Number, Slider |
float |
a number |
Integer |
int |
a whole number |
Color |
vec3, linear |
a colour: 0xff8800 or '#ff8800' |
Vector2, Vector3, Quaternion, Vector4 |
vec2, vec3, vec4, vec4 |
[x, y, …] |
Boolean |
bool |
true or false |
Dropdown |
int: the item’s number, else its index |
an item |
Texture |
sampler2D |
none: a Shader Texture feeds it |
ifor#if. A Boolean or Dropdown is a uniform, soif (glow) { … }works and toggling it never recompiles. Withdefine=trueit becomes a compile-time switch (#if glow … #endif): no runtime branch, but each combination is its own program. Use it for features that are usually off and cost something when on.- Arrays.
size=Ndeclares an array that only the shader’s own script writes; it is never saved inuniforms.visible=falsehides a uniform’s editor field. - Names are camelCase, such as
rimColor. Names the engine already uses (time,color,opacity,normal,roughness, …) are rejected.
Inputs
Section titled “Inputs”| Input | GLSL | Cost |
|---|---|---|
time |
float time, in seconds |
One value shared by every Shader Material |
pointer |
vec3 pointer (the last hit, in the hit mesh’s space), float pointer, float pointer (0 or 1), float pointer |
Nothing per frame: written only on pointer events, in play |
bounds |
vec3 bounds, vec3 bounds: the entity’s box in its own space; v; to in vertex stages |
One matrix inverse per frame |
smoothNormals |
vec3 smooth, one normal per position, so a hull pushed along it stays closed at hard edges |
Memory for one more attribute |
pointer makes the entity a pointer target, so pointers stop at it. A shader with pointer, bounds, smoothNormals or passes is not drawn in a Cache Mesh batch.
Passes
Section titled “Passes”#pragma pass(...) adds a draw built once from each mesh, attached to it. Passes are never picked, cast no shadow and are not outlined. The main options are name, geometry (mesh to draw the mesh again, points for up to 4096 small quads sampled on the surface, arcs for up to 64 ribbons between surface points), the pass’s own vertex and fragment functions, and blending, depthWrite and side. A mesh pass with colorWrite=false draws depth only, first, which keeps an additive shader’s inside hidden. Each pass adds one draw per mesh; nothing runs on the CPU per frame.
The shader’s own script
Section titled “The shader’s own script”What the graphics card cannot remember from frame to frame lives in a small JavaScript block inside the source, between #script_begin and #script_end, with startup(shader), update(dt, time) and dispose() hooks named in #pragma lifecycle. It runs once per entity, and update runs each frame while the entity is drawn. shader.uniforms holds the uniform objects (write .value), shader.value(ref) reads a uniform’s current prop value, and shader.entity is the entity. The blood preset keeps its splats this way.
Textures
Section titled “Textures”A Texture uniform reads a Shader Texture on the same entity: ShaderTextureComponent, type comp-shader-texture. An entity has one per texture.
| Prop | Type | Default | Description |
|---|---|---|---|
uniform |
string |
'' |
The ref of the Texture uniform it feeds. |
src |
string |
'' |
The image: a PNG, JPEG or WebP, or a .ktx2 (GPU-compressed). |
The image repeats and is read as sRGB. Until it loads, the uniform reads white. Changing or removing a Shader Texture updates the shader in place, without rebuilding it.
| Component | Type | What it does |
|---|---|---|
| Shader Material | comp-shader-material | Draws its mesh with a shader: a preset, or code written with pragmas and hooks. |
| Shader Texture | comp-shader-texture | One image a shader material reads through a texture uniform. |
A custom Shader Material declares a Texture uniform, and a Shader Texture on the same entity feeds it an image: the print scrolls around an amber drum, and the script swaps the image every few seconds without rebuilding the shader.
Watch the print scroll around the drum and change image every three seconds. Drag to orbit the camera, scroll to zoom.
Examples
Section titled “Examples”1. Apply a built-in preset
Section titled “1. Apply a built-in preset”The simplest use: turn an object into a hologram when the scene starts, and log every preset the app offers. Place the Behavior entity under the object.
#pragma lifecycle(startup)
function startup() { for (const preset of ShaderPreset.list()) { log(preset.name, '-', preset.label); }
const target = self.parent; let material = target.getComponent(ShaderMaterialComponent); if (!material) { material = new ShaderMaterialComponent({ preset: 'hologram' }); target.addComponent(material); } else { material.setProps({ preset: 'hologram' }); }}A statue turns into a hologram when the scene starts, and the log lists every built-in shader preset: a Shader Material added by a Behavior script with the hologram preset.
Read the list of presets in the log. Drag to orbit the camera, scroll to zoom.
ShaderPreset.list()returns{ name, label, description }for each preset. Usenamein props;labelis the friendly title.- If the object has no Shader Material yet, the script creates one already set to
'hologram'and adds it. Because all materials share one slot, it replaces the existing material. - On a loaded model the hologram is drawn on every mesh of the model. A surface preset such as
toonwould instead restyle each mesh’s own material.
2. Cycle a preset’s variants on click
Section titled “2. Cycle a preset’s variants on click”Presets come with named looks, their variants. A variant is applied by writing its values: color and opacity as props, everything else into uniforms. The object has a Shader Material, a Selectable and a Signal Emitter with the signal orb/clicked.
#pragma lifecycle(startup)
let material;let variants = [];let current = 0;
function applyVariant(variant) { const props = {}; const uniforms = Object.assign({}, material.props.uniforms); for (const key of Object.keys(variant.values)) { if (key === 'color' || key === 'opacity') props[key] = variant.values[key]; else uniforms[key] = variant.values[key]; } props.uniforms = uniforms; material.setProps(props); log('Variant:', variant.name);}
function startup() { material = self.parent.getComponent(ShaderMaterialComponent); const info = material.inspect(); variants = info ? info.variants : []; if (variants.length === 0) return;
on('orb/clicked', (event) => { if (event.eventType !== EventType.Selectable.Select) return; findEntity(event.entityId)?.getComponent(SelectableComponent)?.setSelected(false); // so the next click selects it again current = (current + 1) % variants.length; applyVariant(variants[current]); });}Each click on the orb applies the next variant of its Holo Foil preset, writing the variant's values into the props and uniforms.
Click the orb to step through the variants of its shader. Drag to orbit the camera, scroll to zoom.
material.inspect()reads the shader drawn now and returns itsvariants, each{ name, swatch, values }. It returnsundefinedwhile the preset is unknown, hence the check.applyVariantsorts each value into a prop (color,opacity) or a uniform. It copies the existinguniformsfirst withObject.assign, so values the variant does not mention are kept.- Everything goes into one
setPropscall. Uniform values update without a rebuild;colorandopacitydo rebuild, once.
3. Register your own preset and drive it
Section titled “3. Register your own preset and drive it”A custom dissolve shader: pixels whose noise value falls below progress are cut away, with a glowing edge. The script registers it, applies it, and tweens progress from 0 to 1 when the signal crate/destroy arrives.
#pragma lifecycle(startup)
const DISSOLVE = `#pragma shader(name=dissolve, label="Dissolve", description="Burns away along a blocky noise pattern.")#pragma material(shading=lit)#pragma uniform(ref=progress, type=Slider, min=0, max=1, step=0.01, default=0)#pragma uniform(ref=edgeColor, type=Color, default=0xff6a00)#pragma uniform(ref=cells, type=Number, min=1, max=64, default=8)
float hash(vec3 p) { return fract(sin(dot(p, vec3(12.9898, 78.233, 37.719))) * 43758.5453);}
void fragment(inout Surface s) { float n = hash(floor(vLocalPosition * cells)); if (n < progress) discard; float edge = 1.0 - smoothstep(0.0, 0.08, n - progress); s.emissive = edgeColor * edge * 4.0;}`;
let material;
function setProgress(value) { material.setProps({ uniforms: Object.assign({}, material.props.uniforms, { progress: value }) });}
function startup() { if (!ShaderPreset.get('dissolve')) ShaderPreset.register(DISSOLVE);
const crate = self.parent; material = new ShaderMaterialComponent({ preset: 'dissolve', color: '#a16207' }); crate.addComponent(material);
on('crate/destroy', async () => { const finished = await Tween.value(0, 1, setProgress, { duration: 1.5, ease: Ease.InQuad }); if (finished) destroy(crate); });}A script registers a custom dissolve preset, gives the crate a Shader Material with it, and tweens its progress uniform from 0 to 1 on crate/destroy before destroying the crate.
Press Destroy to burn the crate away along a blocky pattern. Drag to orbit the camera, scroll to zoom.
- The source is a JavaScript template string.
#pragma shadernames itdissolve;shading=litlets the scene’s lights shade it. - Each
#pragma uniformdeclares a GLSL uniform and an editor field.progressis a Slider from 0 to 1. vLocalPositionis the pixel’s position in the object’s own space;floor(… * cells)turns it into blocks, andhashgives each block a random value.discarddrops the pixel.ShaderPreset.get('dissolve')checks whether it is already registered.registerthrows on a name already taken, which happens when the script restarts.Tween.valuecallssetProgressevery frame for 1.5 seconds. Changing a uniform value writes it straight into the drawn material, with no rebuild, so this is cheap, unlike animating a Standard material’s props.awaiton the tween resolvestruewhen it finished, and the crate is then removed withdestroy.- Because the shader discards pixels, its shadow follows the dissolving shape too.
4. A hover glow using the pointer input
Section titled “4. A hover glow using the pointer input”A shader can react to the pointer by itself, with no script work per frame. This custom shader is set as the material’s own shader, with preset: 'custom'.
#pragma lifecycle(startup)
const HOVER = `#pragma material(shading=lit)#pragma input(pointer, time)#pragma uniform(ref=glowColor, type=Color, default=0x38bdf8)
void fragment(inout Surface s) { float pulse = 0.6 + 0.4 * sin(time * 6.0); float pressFlash = exp(-(time - pointerPressTime) * 4.0); s.emissive = glowColor * (pointerOver * pulse + pressFlash * 2.0);}`;
function startup() { const button = self.parent; const check = ShaderMaterialComponent.inspect(HOVER); if (check.error) { console.error('Shader error: ' + check.error); return; } button.addComponent(new ShaderMaterialComponent({ preset: 'custom', shader: HOVER, color: '#1e293b' }));}A custom shader reads the pointer and time inputs by itself: the button pulses while the pointer is over it and flashes when pressed, with no script work per frame.
Move the pointer over the button to make it pulse, and press on it to flash it. Drag elsewhere to orbit the camera, scroll to zoom.
#pragma input(pointer, time)asks for the pointer values and the clock.pointerOveris 1 while a mouse, finger or XR ray is over the entity;pointerPressTimeis thetimeof the last press.exp(-(time - pointerPressTime) * 4.0)is 1 at the moment of a press and fades quickly toward 0: a flash with no script involved.ShaderMaterialComponent.inspect(source)checks the pragmas before the material is built, so the script can report a clear error instead of drawing nothing. (GLSL compile errors are only found when the shader is first drawn.)- The pointer input makes the entity a pointer target and keeps it out of Cache Mesh batches.
5. Freeze one copy of a shared model
Section titled “5. Freeze one copy of a shared model”On a loaded model, setTransientModelPreset draws a preset on this one instance without changing the saved material. The model has a disabled Shader Material and a Signal Emitter with the signal knight/freeze.
#pragma lifecycle(startup)
const FROZEN_MS = 3000;
function startup() { const material = self.parent.getComponent(ShaderMaterialComponent);
on('knight/freeze', () => { const applied = material.setTransientModelPreset('frozen'); if (!applied) { console.warn('Could not freeze: is the Shader Material disabled and the preset registered?'); return; } delay(() => material.setTransientModelPreset(), FROZEN_MS); });}On knight/freeze, a disabled Shader Material draws the frozen preset on this one model with setTransientModelPreset, and three seconds later restores the model's own look.
Press Freeze to cover the knight in ice for three seconds. Drag to orbit the camera, scroll to zoom.
- The Shader Material must be disabled: the transient preset is a temporary look on top of the model’s own materials, not a change to the material component.
setTransientModelPreset('frozen')returnstruewhen applied. Calling it with no arguments clears it and the model looks as authored.- Nothing is saved or replicated, so each player can see a different effect on their own copy.
6. A toon ramp with three bands
Section titled “6. A toon ramp with three bands”The toon shading accepts a ramp hook that maps how much light a point receives (0 facing away, 1 facing the light) to a brightness. That is how you design cel shading. This script registers a three-band ramp and applies it to several characters.
#pragma lifecycle(startup)
const THREE_BAND = `#pragma shader(name=threeBand, label="Three band", description="Cel shading in three hard bands.")#pragma material(shading=toon)#pragma lifecycle(ramp)#pragma uniform(ref=shadowTone, type=Slider, min=0, max=1, default=0.35)
vec3 ramp(float light) { if (light < 0.3) return vec3(shadowTone); if (light < 0.75) return vec3(0.75); return vec3(1.0);}`;
function startup() { if (!ShaderPreset.get('threeBand')) ShaderPreset.register(THREE_BAND);
for (const name of ['Hero', 'Sidekick', 'Villain']) { const character = findEntity(name); if (!character) { console.warn('No entity named ' + name); continue; } character.addComponent(new ShaderMaterialComponent({ preset: 'threeBand' })); }}A script registers a toon preset whose ramp maps light to three hard bands, and gives it to three characters.
Orbit around the three characters to see the light fall in three flat bands. Drag to orbit the camera, scroll to zoom.
- Inside the shader source,
#pragma lifecycle(ramp)declares the toon hook. It is the shader’s own pragma and has nothing to do with the script’s#pragma lifecycle(startup)above it. - With no
fragmenthook, each model keeps its own colours and textures: only the lighting is banded. - Because
toonis a surface shading, applying it to a model restyles each of the model’s own materials rather than replacing them. shadowToneis a uniform, so each character’s material can darken or lighten its shadow band without a rebuild.- A material naming a preset that is not registered yet waits and builds itself as soon as the name is registered, so the order of scripts does not matter.
Performance
Section titled “Performance”- Built on change. The material is rebuilt only when its props change. Materials with the same source and compile switches share one GPU program.
- Uniform values are cheap. Changing a uniform value writes into the drawn material without a rebuild. A
define=trueswitch,color,opacity, the preset or the shader does rebuild, and so does any change on an entity drawn in a Cache Mesh batch. - First draw compiles. The first time a source is drawn, its program compiles, which can hold a frame. Later draws reuse it. Lean
litandtoonprograms compile much faster than physically based ones. - Passes add one draw per mesh each. Particles and cards cost fill rate where they overlap, most on phones and headsets.
- Shadows. A Shader Material never receives shadows. It casts unless it is additive or says
shadows=false. - Headsets. Use object, world or view space in your code, never
gl_FragCoord, which differs per eye.
Common mistakes
Section titled “Common mistakes”- Registering twice.
ShaderPreset.registerthrows when the name is taken, for example when the script restarts. Check withShaderPreset.get(name)first. - Replacing all uniforms.
setProps({ uniforms: { tint: 0xff0000 } })replaces the wholeuniformsobject, resetting the others to their defaults. Copy the existing ones withObject.assign({}, material.props.uniforms, { … }). - Declaring a uniform twice.
#pragma uniformalready declares it in GLSL. Writinguniform vec3 tint;again is a compile error. - Reserved names. A uniform called
time,colororopacityis rejected. Use names such astintorfade. - Animating
colororopacityevery frame. These rebuild the material. Animate a uniform instead. - Expecting received shadows. Shader Materials never show shadows cast on them. Use a Standard material where shadows matter.
- Using
gl_FragCoordfor patterns: they swim between the eyes of a headset. UsevLocalPositionorvWorldPosition. - Endless loops. A runaway loop in a shader can stall the graphics card until the browser resets it. Keep loops bounded by constants.