ScopeBee
Back to the site

Materials, shaders and particles

Materials and the particle system keep the classes, properties and modules you already know, so a converted script compiles as it is. Inside they are built differently: a shader is two functions, and a living particle costs the CPU nothing.

Materials: familiar names, fewer copies

Shader is a class, and Shader.Find looks a shader up by name. Material properties keep the names you are used to — _BaseColor, _BaseMap, _Metallic, _Smoothness — so SetColor, SetFloat and the .mat file speak the same language as the original project. renderer.material is a lazy copy owned by the renderer, and sharedMaterial is the common asset.

Where it differs is where the usual approach makes you pay:

  • A colour per object without a copy. Every renderer has its own color that multiplies the material’s, so 25 cubes on one material can each change colour every frame — with no material copy per object and no property block.
  • 2,000 instances in one call. Graphics.DrawMeshInstanced draws the whole batch with a colour per instance, casts and receives shadows and is culled as one box.
  • Transparent meshes sort with sprites. Surface Type Transparent puts a mesh into the same back-to-front order as the 2D layer, so a glass cube and a sprite overlap the right way round.

A shader is two functions

A custom shader is a .coshader file: a short header, a list of properties and up to two GLSL functions, vertex() and fragment(). Everything around them — vertex attributes, uniform blocks, matrices, lights, shadows, linear colour and tonemapping — the engine generates. A lit shader goes through the same lighting code as the built-in Lit, so it is lit exactly like it by construction.

Dissolve.coshader

shader  "Custom/Dissolve"
type    mesh
mode    lit
surface opaque

properties {
    color   _BaseColor = (1, 1, 1, 1)        "Base Color"
    texture _BaseMap   = white               "Albedo"
    texture _NoiseMap  = gray                "Noise"
    float   _Cutoff    = 0.3  range(0, 1)    "Dissolve"
    float   _EdgeWidth = 0.05 range(0, 0.2)  "Edge Width"
    color   _EdgeColor = (1, 0.5, 0, 1) hdr  "Edge Color"
}

void fragment() {
    float n = texture(_NoiseMap, UV).r;
    if (n < _Cutoff) {
        discard;
    }
    vec4 albedo = texture(_BaseMap, UV) * _BaseColor;
    ALBEDO     = albedo.rgb;
    SMOOTHNESS = 0.3;
    EMISSION   = _EdgeColor.rgb * step(n, _Cutoff + _EdgeWidth);
}
The whole dissolve shader: lit, with shadows, with its properties in the material inspector

The listing above is the complete shader, and the generator does more than save typing:

  • Shadows follow the shader on their own. The shadow program is generated from the same vertex(), so a waving surface casts a waving shadow; a fragment() with discard goes into the shadow pass too, so a dissolving cube casts a shadow with the same holes. There is no separate shadow pass to write by hand, so the displacement and the clip are never written twice — and the shadow cannot drift away from its object.
  • Properties need no code. Declared once in the header, they appear in the material inspector, are saved into .mat and answer to SetFloat and SetColor; the engine packs them into uniforms itself.
  • Shader.Find works in a build. Every shader of the project is baked into the package — a few kilobytes — so there is no list of shaders to keep in the build and no null in the build that never showed up in the editor.
  • No variants, no warm-up stall. One shader is one program with no keywords to multiply it; its pipelines are created when the scene loads, not on the first frame that draws it.
  • Edit and look. A shader saved in an external editor recompiles when the editor gets focus back, and a compile error points at the line of your file, not of the generated wrapper.
  • Sprites too. A shader of the sprite type runs inside the sprite batch: the outline in the demo is a sprite shader written the same way.
  • Shaders icon

    Shaders

    Eight stands from Lit materials and transparency to custom vertex and fragment shaders, sprite shaders and 2,000 instanced cubes in one call.

Particles: familiar modules, the GPU’s work

ParticleSystem has the modules you know under the names you know — main, emission, shape, colour, size, rotation and velocity over lifetime, the by-speed modules, texture sheet animation, noise, sub-emitters, trails and the renderer’s billboard, stretched and mesh modes. Writing var main = ps.main; main.startSpeed = 5f; compiles as it is.

Inside it works the other way round. A classic particle system steps every living particle on the CPU every frame. Here almost everything the modules describe is a function of a particle’s age, so the vertex shader computes position, size, rotation and colour from a 64-byte record written once, at birth. The CPU only spawns new particles and drops the dead ones — whose time of death is known from the moment they are born. A fountain of 10,000 particles costs the CPU about as much as one of a hundred.

That one decision is what the rest comes from:

  • Rewind for free. An effect is its births plus a seed, so any moment can be evaluated directly rather than stepped to: pause, slow motion and scrubbing the timeline backwards in the editor show the exact frame, and Prewarm is just a different start time.
  • Fifty systems in one draw call. Systems sharing a texture and a blend mode are drawn together even with different colours, curves, gravity and simulation spaces: their parameters ride in a texture, their curves in a shared atlas.
  • Motion-vector flipbooks. Frames are blended along per-pixel motion vectors, so a 4×4 sheet plays as smoothly as an 8×8 one at a quarter of the texture.
  • Trails without history. Each point of a ribbon is the same formula at an earlier age, so a trail stores nothing per particle.
  • Deterministic sub-emitters. A death known at birth needs no tracking: a firework with three levels of sub-emitters plays the same in the editor and on the web, forward and backward.
  • SetParticles still works. A script can read every particle, push it and write it back; the birth record is rewritten so the formula continues from the new position and velocity, and the particle goes on ageing at no CPU cost.
  • Particles icon

    Particles

    Eight stands from 20,000 particles at no CPU cost per particle to rewind, one-call batching, motion-vector flipbooks, trails and fireworks.

What motion vectors buy

The explosion from the particles demo: an 8×8 sheet, with every fourth frame kept as a 4×4 sheet. The 4×4 sheet is played back and compared with the frames it skipped; the figure is the RMS error over RGBA between what the shader draws and the missing frame — lower is closer.

Simple Blended Motion vectors
Explosion, 4×4 from 8×8 0.031 0.0084 0.0061

Simple shows the nearest frame and Blended crossfades two, the usual choices for a particle shader. With motion vectors the error is about a quarter lower than a crossfade’s, and the edge of the cloud stops doubling. The vectors for this sheet were recovered from its own frames; vectors exported from the tool the effect was made in follow the motion more closely.