Effects

Decals, outlines, camera shake, and the dynamic-mesh path for content whose vertices change every frame.

meep’s rendering effects are ECS systems. You register the system, attach a component, and the system registers a render extension that draws at a declared phase of the renderer’s frame. The phase decides what an effect can see and what can cover it: decals run before anything is lit, so lighting, ambient occlusion and reflections all see them; outlines run after transparency, over the finished scene and before the upscale that anti-aliases them. Trails are the exception: they are drawn inside the transparency pipeline itself, as a transparency channel.

EffectSystemComponentsDraws at
DecalsDecalSystem(graphics, assets)Decal, Transform64AfterGBuffer, after the terrain
OutlinesOutlineSystem(graphics, scene, assets) + a pairing system per kindOutline + SGMesh, Outline + ShadedGeometryAfterTransparency
TrailsTrail3DSystem(graphics, scene)Trail3D, Transform64inside the transparency pipeline
Camera shakeCameraShakeBehavior, CameraShakeTraumaBehavior-not a render pass at all
Your own geometryGPUDynamicMeshRenderer inside your own extension-wherever you register it

Every one of these systems takes engine.graphics (the GraphicsEngine facade) as its first argument, not the engine.


Decals

A decal is a surface override, not a tint. It carries albedo, a tangent-space normal, roughness, metalness and emission, and it writes them into the G-buffer before anything is lit - so ambient occlusion, screen-space reflection and shading all see a decal exactly as they see the surface it is painted on. A scorch mark dulls the specular response of the floor it is on; a glowing rune actually emits.

Decals reach opaque surfaces only, by construction. The G-buffer is all they touch and transparency composites later, so a decal will never appear on water.

import { DecalSystem } from "@woosh/meep-engine/src/engine/graphics3/DecalSystem.js";
import { Decal } from "@woosh/meep-engine/src/engine/graphics/ecs/decal/v2/Decal.js";

await em.addSystem(new DecalSystem(engine.graphics, engine.assetManager));

// Attach a decal to an entity that also has a Transform64
entity.add(Decal.fromJSON({
    uri_albedo: "data/textures/decals/scorch_albedo.png",
    uri_normal: "data/textures/decals/scorch_normal.png",
    uri_orm: "data/textures/decals/scorch_orm.png",
    priority: 0,
    color: "#ffffff"
}));

DecalSystem declares dependencies = [Decal, Transform64], and its startup() registers a DecalExtension (name = "decals", phase = FramePhase.AfterGBuffer). Terrain has already shaded its splat layers through its material by this phase, so the decal composite sees textured ground without an extension ordering constraint.

The component

Decal is a named export from src/engine/graphics/ecs/decal/v2/Decal.js. Its fields:

FieldTypeNotes
uri_albedostringBase colour; its alpha is the decal’s mask, the coverage every channel blends by. Optional: with none, the mask is one across the whole projection volume and the colour is color
uri_normalstringTangent-space normal, applied in the decal’s own frame
uri_ormstringglTF packing: G is roughness, B is metalness. R (occlusion) is deliberately ignored, so an authored glTF ORM texture drops in unmodified
uri_emissivestringGreyscale mask, multiplied by emissive_color and emissive_intensity
uristringDeprecated. It shadows uri_albedo while both are set, so content authored with it keeps working
roughnessnumberMultiplies whatever uri_orm gives; default 1, so a decal with no ORM map is simply this value
metalnessnumberSame, default 0
emissive_colorColorDefault white
emissive_intensitynumberZero by default, so a decal that does not set it is non-emissive. Values above one are the point of it being a float
prioritynumberDraw order when decals overlap
colorColorPremultiplied into the decal
albedo_weight, normal_weight, roughness_weight, metalness_weight, emissive_weightnumberHow much of each channel is written, in [0, 1], default 1. Each scales the mask’s coverage for that one channel: 0 leaves the surface’s value exactly as it was. A decal that writes only normals keeps uri_albedo for its shape and sets albedo_weight: 0. A decal’s emission replaces what is beneath it, so emissive_weight: 0 is also what keeps an emitting surface emitting under a decal

The entity’s Transform64 is the projector: a unit box, scaled to the volume you want, whose world matrix and inverse are what the GPU record carries. It projects along its local +Z, into the surface. The coverage fade is smoothstep(0.35, 0.6, dot(face_normal, -axis_z)), so a projector built by pointing +Z along the surface normal scores -1 and every pixel is rejected - silently: the entity links, the texture resolves, the record is well-formed, and nothing is drawn. Aim +Z at the surface.

What to expect at runtime

  • A decal is not packed until its albedo image has loaded. The image’s alpha is the decal’s shape, and drawing it with a placeholder would put a white square on the ground until the image landed, so it simply does not appear yet. Only a decal that names no albedo map at all draws with the full-volume mask.
  • Textures are reference counted across decals. Combat spawns a footprint decal per step and every one of them names the same file; packing a patch per footprint would repack three atlases and regenerate their mip chains several times a second. There are three atlases - albedo (sRGB), normal and ORM - because their contents want different mip filters and different alpha storage: the albedo atlas holds premultiplied colour, the others straight. Each atlas builds its mip chain patch by patch, so a patch’s border repeats its own edge at every level rather than blending in its neighbour.
  • Records are rebuilt every frame, on purpose. The froxel binning depends on the camera and has to run every frame regardless, and rebuilding the records alongside it means nothing has to watch a decal for changes - which matters, because a Color’s change signal does not fire for alpha-only edits.
  • Capacity grows with the record buffer. There is no fixed budget on the number of decals you may link; the system grows its record array to fit. What is bounded is the GPU side: DECAL_CULL_LIMIT = 4095 decals survive culling in a frame, and DECAL_CLUSTER_LOCAL_LIMIT = 32 fit in one froxel - deliberately smaller than the light limit, because a froxel crowded with decals is a pile of surface overrides where all but the last few are invisible.
  • The decal froxel grid has the lighting grid’s shape by construction: 32-pixel tiles, 24 Z slices.
  • When nothing is packed, the pass does not run at all and the frame keeps the G-buffer it already had.

Outlines

Outline marks an entity with up to two looks: one where it is the front surface, and one where other geometry hides it. Each look is an OutlineSpec: a solid line around the silhouette, a soft fade beyond it, a fill over the object, and a black-and-white mask for the line and one for the fill.

import { OutlineSystem } from "@woosh/meep-engine/src/engine/graphics3/OutlineSystem.js";
import { SGMeshOutlineSystem } from "@woosh/meep-engine/src/engine/graphics/ecs/outline/SGMeshOutlineSystem.js";
import {
    ShadedGeometryOutlineSystem
} from "@woosh/meep-engine/src/engine/graphics/ecs/outline/ShadedGeometryOutlineSystem.js";
import { Outline } from "@woosh/meep-engine/src/engine/graphics/ecs/outline/Outline.js";
import { OutlineSpec } from "@woosh/meep-engine/src/engine/graphics/ecs/outline/OutlineSpec.js";
import { MeshSystem } from "@woosh/meep-engine/src/engine/graphics3/MeshSystem.js";
import { EngineHarness } from "@woosh/meep-engine/src/engine/EngineHarness.js";
import { load_model_scene_bundle } from "@woosh/meep-engine/src/engine/asset/load_model_scene_bundle.js";

const scene = EngineHarness.shadeScene(engine);

// models draw through MeshSystem plus ShadedGeometrySystem, ParentEntitySystem and
// TransformAttachmentSystem, registered as for any model (see Meshes & materials)
const meshes = new MeshSystem(engine.graphics, scene, url => load_model_scene_bundle(engine.assetManager, url));
await em.addSystem(meshes);

// the pass. It observes no entities: the pairing systems tell it what to outline.
// The asset manager loads mask textures; pass null when no spec names one.
const outlines = new OutlineSystem(engine.graphics, scene, engine.assetManager);
await em.addSystem(outlines);

// one pairing system per kind of outlined thing. Register the ones you need.
await em.addSystem(new SGMeshOutlineSystem(outlines, meshes));   // loaded models
await em.addSystem(new ShadedGeometryOutlineSystem(outlines));   // primitives

// a 3 px orange line where the unit can be seen...
const selected = new OutlineSpec();
selected.solid_color.set(1.0, 0.6, 0.2, 1);
selected.solid_width = 3;

// ...and a thin line with a faint fill, drawn over whatever hides it
const behind = new OutlineSpec();
behind.solid_color.set(0.6, 0.5, 1.0, 1);
behind.solid_width = 1.5;
behind.fill_color.set(0.6, 0.5, 1.0, 0.3);

const outline = new Outline();
outline.visible = selected;
outline.hidden = behind;
entity.add(outline);

All five are named exports. OutlineSystem registers an OutlineExtension (name = "outline") at FramePhase.AfterTransparency, before the upscale: the outline is drawn into the scene from the jittered visibility buffer, so the temporal resolve anti-aliases its edges along with every other silhouette’s.

The two specs

FieldDraws
visiblewhere the entity is the front surface
hiddenwhere other geometry stands in front of the entity, over that geometry

Either may be OutlineSpec.NONE, the frozen spec that draws nothing, and that side is not drawn. A fresh Outline holds two fresh OutlineSpecs, and a fresh spec is a 2 px white line, so an Outline added as it comes outlines the entity in white through walls too. Set the side you do not want to OutlineSpec.NONE.

A spec that paints no pixel is skipped entirely, so it claims no space from other outlines: a band paints only with both a width and some alpha, the fill only with some alpha. outline_spec_is_drawing(spec) (.../ecs/outline/outline_spec_is_drawing.js) is that test. Fading solid_color.a to zero is therefore a clean way to switch a line off.

The spec

FieldDefaultNotes
solid_colorwhite, alpha 1the line
solid_width2output pixels out from the silhouette’s edge
soft_colorwhite, alpha 0the fade beyond the line; its alpha is the fade’s opacity where it begins, at the line’s outer edge, and it fades to nothing
soft_width0output pixels beyond the line
fill_colorwhite, alpha 0over the object’s own pixels
outline_mask, fill_masknullURL of a mask texture for the line (solid and soft) or the fill
outline_mask_scale, fill_mask_scale1
outline_mask_offset, fill_mask_offset0

Colours are linear RGB with straight alpha: the outline is drawn into the scene before tone mapping, so a colour picked as sRGB hex needs Color.from_sRGB_to_linear first. Widths are output pixels, so a line is the same width at every distance and at every internal resolution. spec.reach is solid_width + soft_width, how far past the silhouette it paints; the pass runs as many flood rounds as the widest spec in use needs.

A mask is tiled across the screen, at one texel per output pixel, and does not follow the object. Its red channel m multiplies the part it masks by saturate(m * scale + offset), so stripes give a dashed line or a hatched fill, and a non-zero offset keeps the dark texels partly drawn. A null mask reads as white, so scale and offset alone then make a constant factor. Masks load through the asset manager as GameAssetType.Image, so the engine needs a loader for that type (ImageRGBADataLoader), and a data URL drawn into a canvas is as good a URL as a file. The Outlines example builds both of its masks that way.

OutlineSpec has copy, clone, equals, hash and JSON round-tripping, and Outline serializes through OutlineSerializationAdapter, which the engine’s serialization registry includes.

Specs are shared by reference

Specs are held by reference and read every frame. That gives two behaviours for free:

  1. Edit a spec in place and every entity holding it changes on the next frame. A pulsing selection is a per-frame write to spec.soft_width or spec.solid_color.a; there is nothing to announce.
  2. Entities holding the same spec object are outlined as one shape. Their outlines merge where they meet, which is what a group selection wants. Give each entity its own spec (spec.clone()) when they should stay apart. Two different specs sharing space are drawn as two outlines, each pixel belonging to one of them.

How it is drawn

Each pixel belongs to one spec, so outlines never paint over each other. A pixel’s owner is the front surface’s visible spec; failing that, the hidden spec of the nearest outlined row behind it. The nearer silhouette’s outline is on top, a pixel two outlined entities both cover shows the front one’s fill, and where outlined entities overlap, the one behind loses its hidden part to the one in front.

The pass works from the visibility buffer the frame already wrote. Only the rows with a hidden spec are rasterized a second time, to find where they are hidden. A full-screen classify labels every pixel with its spec, and a jump flood that keeps each pixel’s two nearest specs runs only on the 8×8 screen tiles within reach of a silhouette, so its cost follows the silhouettes’ length rather than the area they enclose. The inside of a large object is drawn as its fill alone, and not at all when the fill is transparent. With nothing outlined the pass does not run.

Pairing systems

OutlineSystem owns everything about drawing and declares no component tuple, because which mesh rows an entity has depends on what kind of thing it is. A pairing system per kind contributes entries through outlines.add_entry(entity, outline, rows) and hands them back on unlink:

Pairing systemTupleConstructorOutlines
SGMeshOutlineSystem[Outline, SGMesh](outlines, meshes)every primitive the model spawned, asked of MeshSystem every frame
ShadedGeometryOutlineSystem[Outline, ShadedGeometry](outlines)the primitive’s own row

Two consequences:

  1. The Outline goes on the model’s entity, the one carrying SGMesh, not on the primitives MeshSystem builds under it. A model still loading has no primitives yet and starts being outlined when they arrive.
  2. A primitive needs its own pairing system. An Outline on a bare ShadedGeometry draws nothing unless ShadedGeometryOutlineSystem is registered. Where an outlined primitive sits inside an outlined model, the primitive’s own outline wins.

Highlight (deprecated)

Highlight is a selection component holding a list of HighlightDefinition colours that composite over in list order. It is deprecated in favour of Outline, which does everything it does and more. Its systems still exist and draw through the same pass: SGMeshHighlightSystem(outlines, meshes) and ShadedGeometryHighlightSystem(outlines) take an OutlineSystem and draw each Highlight as a 3 px solid line (HIGHLIGHT_LINE_WIDTH) in its composited colour, visible side only, with a spec of its own per entity. To migrate, replace Highlight.fromOne(r, g, b, a) with an Outline whose visible.solid_color is that colour, visible.solid_width = 3 and hidden = OutlineSpec.NONE, and register the Outline pairing systems. Give each entity a spec of its own (spec.clone()), as Highlight did: entities sharing one spec merge into one outline.


Ribbons and trails

Trail3D is the one trail component the engine draws, and it has its own page: see Trails for the component surface, the sizing rules and make_gradient_stroke, which authors a beam or a streak. A trail’s knots are simulated in compute and its tube is extruded in the vertex stage, so the CPU builds no geometry for it. There is no screen-facing ribbon: Trail2D deserializes but nothing renders it.

If what you actually want is arbitrary geometry you rewrite yourself each frame, that is the dynamic-mesh path below.


Camera shake

Camera shake is a pair of Behavior subclasses in src/engine/graphics/camera/. It touches no render pass; it moves a TopDownCameraController.

CameraShake (CameraShake.js) owns six independent 2D simplex noise streams - yaw, pitch, roll and X/Y/Z offset - seeded from a fixed value so a replay shakes identically. shake.read(value, time, offset, rotation) writes into the offset and rotation Vector3s you hand it, scaled by value (0-1) and clamped by limitsOffset / limitsRotation.

CameraShakeBehavior wraps a CameraShake and updates the controller’s target, pitch, yaw and roll every tick. It takes a single options object; the limits are set at construction:

import { CameraShakeBehavior } from "@woosh/meep-engine/src/engine/graphics/camera/CameraShakeBehavior.js";

const shakeBehavior = new CameraShakeBehavior({
    controller,
    maxPitch: 0.05,
    maxYaw:   0.05,
    maxRoll:  0.02,
    maxOffsetX: 0.1,
    maxOffsetY: 0.1,
    strength: 0,
});

CameraShakeTraumaBehavior adds a trauma accumulator on top. trauma is clamped to 0-1, decays at decay units per second, and is mapped through a cubic curve before being written to the underlying behaviour’s strength. Add trauma in response to impacts:

import { CameraShakeTraumaBehavior } from "@woosh/meep-engine/src/engine/graphics/camera/CameraShakeTraumaBehavior.js";

const traumaBehavior = new CameraShakeTraumaBehavior({
    shakeBehavior,
    decay: 1.5  // full trauma decays in ~0.67 s
});

// On explosion:
traumaBehavior.trauma = Math.min(1, traumaBehavior.trauma + 0.6);

Both behaviours are based on Squirrel Eiserloh’s 2016 GDC talk “Math for Game Programmers: Juicing Your Cameras With Math”.


Dynamic meshes

A tube along a path, a gizmo, a debug line: content whose vertices are rewritten every frame cannot pay for a meshlet build, and rebuilding meshlets per frame to force it down the standard path is explicitly not the answer. The renderer gives it a path of its own.

This is a separate path, not a variant of the standard one. A DynamicMesh holds a plain Geometry rather than a MeshletGeometry and its own transform, is no entity of the scene, gets no row in the scene database, and is drawn by a pipeline of its own after the standard geometry path has finished with the frame. It is what PathDisplaySystem and DebugDrawSystem are built on - the two shipping systems whose content is rebuilt on the CPU. (Particles and trails do not use it; each is simulated on the GPU and has a pipeline of its own.)

The pieces

import { DynamicMesh } from "@woosh/meep-engine/src/shade/renderer/scene/DynamicMesh.js";
import { DynamicMeshBatch } from "@woosh/meep-engine/src/shade/renderer/scene/DynamicMeshBatch.js";

const batch = new DynamicMeshBatch();          // yours, not the Scene's

const mesh = DynamicMesh.from(geometry, [1, 0.5, 0, 1]);   // Geometry + flat RGBA
batch.add(mesh);

mesh.visible = false;         // hide without losing GPU residency
geometry.needsUpdate = true;  // you say when the vertices changed; nothing watches the arrays

DynamicMesh is a node of nothing: it carries its own transform, a Transform64 posed directly and refreshed with updateMatrix(), with no parent above it and no row in the scene database. Its color is a Float32Array RGBA multiplied into whatever per-vertex colour the geometry carries - the alpha is what fades a mesh out as a whole. DynamicMeshBatch exposes add, remove, clear, and the getters meshes (insertion order, which is draw order, because these are blended), count and version.

The vertex layout is fixed

src/shade/renderer/dynamic/DYNAMIC_MESH_VERTEX.js exports DYNAMIC_MESH_VERTEX_STRIDE = 8, DYNAMIC_MESH_VERTEX_POSITION_OFFSET = 0 and DYNAMIC_MESH_VERTEX_COLOR_OFFSET = 4:

FloatsMeaning
[0..2]position x, y, z, object space
[3]reserved - keeps the stride a power of two and leaves room for a UV later
[4..7]colour r, g, b, a

One layout rather than a described one, because a dynamic mesh is drawn by a single pipeline: letting each geometry declare its own attribute set would buy nothing and cost either a pipeline per layout or a shader that branches per vertex.

Your geometry needs a position attribute and an index. A colour attribute is optional; without one, every vertex is uploaded white and the mesh’s flat color is the whole colour. Whatever colour components you do supply (3 or 4) are copied; the rest stay at 1.

import { Geometry } from "@woosh/meep-engine/src/shade/renderer/geometry/Geometry.js";
import { Attribute } from "@woosh/meep-engine/src/shade/renderer/geometry/Attribute.js";
import { StandardAttributes } from "@woosh/meep-engine/src/shade/renderer/geometry/StandardAttributes.js";

const geometry = new Geometry();
geometry.setAttribute(Attribute.from(positions, 3, StandardAttributes.Position));
geometry.setAttribute(Attribute.from(colors, 4, StandardAttributes.Color));
geometry.index = Attribute.from(indices, 1, StandardAttributes.Index);

There is no material and no lighting on this path - one pipeline, position and colour, straight alpha over the finished scene. That is why path display and debug draw carry no per-object texture, material or lit shading.

Drawing it

GPUDynamicMeshRenderer (src/shade/renderer/dynamic/GPUDynamicMeshRenderer.js) owns the GPU buffers and records the draws. You put one inside a render extension of your own:

import { GPUDynamicMeshRenderer } from "@woosh/meep-engine/src/shade/renderer/dynamic/GPUDynamicMeshRenderer.js";
import { RenderExtension } from "@woosh/meep-engine/src/shade/renderer/extension/RenderExtension.js";
import { FramePhase } from "@woosh/meep-engine/src/shade/renderer/extension/FramePhase.js";
import { SceneColor } from "@woosh/meep-engine/src/shade/renderer/extension/SceneColor.js";
import { ViewTextures } from "@woosh/meep-engine/src/shade/renderer/extension/ViewTextures.js";

class SparkExtension extends RenderExtension {
    name = "sparks";
    phase = FramePhase.AfterTransparency;

    #mesh_renderer = new GPUDynamicMeshRenderer();
    #batch;

    constructor(batch) {
        super();
        this.#batch = batch;
    }

    record(frame) {
        if (this.#batch.count === 0) {
            // nothing to draw, and the frame's colour is left exactly as it was
            return;
        }

        const scene = frame.get(SceneColor);
        const view = frame.get(ViewTextures);

        const drawn = this.#mesh_renderer.graph_draw({
            graph: frame.graph,
            batch: this.#batch,
            color: scene.color,
            depth: view.depth,
            camera: frame.view.camera.buffer
        });

        scene.color = drawn.color;
        view.depth = drawn.depth;
    }
}

const extension = engine.graphics.add_extension(new SparkExtension(batch));

graph_draw({graph, batch, color, depth, camera}) returns { color, depth }. Publish the colour into SceneColor.color and the depth into ViewTextures.depth, as above. An opaque draw produces a new depth handle; later extensions, depth of field, motion blur and the NSS upscaler must consume it. A blended draw returns the input depth unchanged. A development build rejects a frame that reads a superseded depth handle.

Opaque or blended

GPUDynamicMeshRenderer.opaque chooses between the two modes, and it is a property of the pass, not of a mesh - the whole batch moves together:

opaqueBehaviour
false (default)Blended, depth-tested, depth never written. What effects want
trueNo blending; the pass writes the depth it is given

Set it before the first draw. Changing it later rebuilds the pipeline, which is cheap but not free. The true case exists for a solid surface with no meshlet build behind it - geometry generated on the fly, or decoded out of some other container - which has no depth ordering of its own otherwise, and no CPU sort can give it one: a painter’s order over triangles is wrong wherever two of them interpenetrate.

For solid content that transparent surfaces should cover, record at AfterLighting: transparency then tests against the depth you published. At AfterTransparency, transparent surfaces have already been composited into the colour and the dynamic batch draws over them.

Residency

Residency is keyed on the geometry, not on batch membership. A mesh that blinks off for a frame, or is removed and re-added, keeps its buffers - which is also why a system should write into the geometry it already holds rather than building a fresh one each frame, or it strands a vertex buffer per frame. A geometry that is gone for good should say so:

mesh_renderer.release(geometry);   // -> boolean, whether anything was held

// on shutdown
engine.graphics.remove_extension(extension);
mesh_renderer.destroy();           // frees every geometry still held

Upload happens inside the pass: every visible mesh’s geometry whose version has moved is re-interleaved into the fixed layout and written before the draws are executed.


Occlusion is not an API

Occlusion culling is GPU-driven inside the rasterizer, and the Hi-Z pyramid is internal to the renderer. There is no occlusion query to issue, no readback to drive from a post-render hook, and nothing to size or register.

Where to go next

  • Rendering overview - what the renderer is, the GraphicsEngine facade, and the six frame phases.
  • Render extensions - the mechanism every system on this page registers through.
  • Trails - Trail3D, tubes simulated and extruded on the GPU.
  • Meshes & materials - the standard path a dynamic mesh is the exception to.