pixfx

Write an effect

An effect is a Rust static with metadata and a spawn function. This page shows its parts, the drawing API, the rules that keep it deterministic, and how to register and test it.

Anatomy

Effects live in crates/pixfx-effects/src/<category>/<name>.rs. The skeleton below follows fire/candle.rs:

use pixfx_core::{Effect, EffectState, Layer, Meta, NumOpt, Options};
use pixfx_draw::Painter;
use pixfx_draw::color::Rgba;

pub struct Ember;
pub static EMBER: Ember = Ember;

const SIZE: NumOpt = NumOpt::new("size", 3.0).within(1.0, 8.0); // an option of its own, held to a range
const META: Meta = Meta {
    id: "fire/ember",
    name: "Ember",
    desc: "A single coal glowing and dimming.",
    tags: &["fire", "prop", "light", "loop"],
    size: (40, 40),   // room for the glow's radius on every side of the origin
    origin: (20, 24), // the point that lands where the caller plays it
    duration: 2.0,    // seconds per loop (or of the one-shot)
    looping: true,
    fps: 30,
    seed: 1,
    state: None,
    options: &[SIZE.spec()],
};
const PALETTE: [Rgba; 3] = [
    Rgba::hex24(0x4a1712),
    Rgba::hex24(0xf2561d),
    Rgba::hex24(0xffc23d),
];

impl Effect for Ember {
    fn meta(&self) -> &Meta {
        &META
    }
    fn spawn(&self, opts: &Options, seed: u64) -> Box<dyn EffectState> {
        Box::new(State {
            ramp: opts.palette_or(&PALETTE),
            size: opts.num(&SIZE),
            seed: seed as f64,
        })
    }
}

struct State {
    ramp: Vec<Rgba>,
    size: f64,
    seed: f64,
}

impl EffectState for State {
    fn draw(&self, p: &mut Painter, t: f64, layer: Layer) {
        if layer == Layer::Back {
            return; // nothing behind the character
        }
        // 0..1, one period per `duration` (2 s), so the loop closes exactly
        let k = 0.5 + 0.5 * libm::sin(t * core::f64::consts::PI + self.seed);
        let last = self.ramp.len().saturating_sub(1);
        let pick = (k * last as f64) as usize; // dark to bright as it glows
        let Some(&c) = self.ramp.get(pick.min(last)) else {
            return;
        };
        let s = self.size;
        p.rect(-s, -s, s * 2.0, s * 2.0, c, 1.0);
        p.glow(0.0, 0.0, 10.0, c, 0.6 * k); // light is additive, drawn into the light layer
    }
}

Draw in local space: (0, 0) is the effect's origin, y grows downward. The instance places, mirrors and rotates the painter before calling draw, and applies fade-out and the light option, so the effect never handles them.

Draw from time, or simulate

Most effects draw purely from t (seconds into the loop) and the seed, so any frame can be drawn on its own and loops close exactly. Effects with real physics (sparks that bounce, debris that settles) keep state and override EffectState::update(dt), which the instance calls once per sub-step of at most 1/120 s.

The painter

Painter (crates/pixfx-draw/src/painter.rs) draws into the frame's two layers. All coordinates are local and may be fractional; shapes snap to whole pixels.

MethodDraws
px, dot, blendOne pixel: opaque; at an alpha faded by ordered dither; or translucent.
line, rect, ellipse, tri, polyFilled shapes and 1 px lines. Colour and alpha can be constants or functions of the shape's own coordinates.
each, shadeVisit every pixel in a local box and decide its colour and light yourself. Every filled shape is built on each, so shapes mirror and rotate exactly.
glow, glow_line, glow_ringLight only: radial glow falling as (1 − d)² to 0 at radius r, along a line, or round a ring.
put, add, blend_pxWrite colour or add light at a screen pixel.

Shared building blocks for fire (flame tongues, licks, sparks, embers, smoke puffs, floor light) are in crates/pixfx-effects/src/fire/lib.rs.

Rules

These keep native and wasm builds bit-identical and are enforced by the compiler and clippy:

Register it

Each effect has its own cargo feature, the id with / as -, so a game builds only the effects it plays. tests/features.rs fails if one of these is missing:

  1. In the category's mod.rs (for example src/fire/mod.rs): #[cfg(feature = "fire-ember")] mod ember; and #[cfg(feature = "fire-ember")] pub use ember::EMBER;.
  2. In crates/pixfx-effects/Cargo.toml: fire-ember = [], and add it to its category feature (fire), which is in all.
  3. In crates/pixfx-effects/src/lib.rs: #[cfg(feature = "fire-ember")] &fire::EMBER, in EFFECTS. The order there is the order effects() returns.

Check once with every effect built: cargo test -p pixfx-effects --test features. Every renderer, the scripts and the JS shells pick it up from the registry; nothing else needs changing.

Test it

Build and test the effect alone, behind its feature, so nothing else compiles or runs:

cargo test -p pixfx-effects --no-default-features --features fire-ember --all-targets
PIXFX_BLESS=1 cargo test -p pixfx-effects --no-default-features --features fire-ember --test determinism -- --ignored
cargo test -p pixfx-effects --no-default-features --features fire-ember --test determinism -- --ignored
cargo run -p pixfx-export --example gif -- fire/ember --scale 4
cargo run --release -p pixfx-effects --no-default-features --features fire-ember --example bench
  1. Look at the gif (target/out/fire_ember.gif) before you bless: blessing records what is drawn, right or wrong. Blessing with one effect built rewrites only its entry in tests/goldens/frame_hashes.json.
  2. For a port, run parity against its source (pixelfx or the vendored Sprite Fusion file).
  3. A change shared by many effects (pixfx-core, pixfx-draw, a category's lib.rs) runs the same tests without the feature flags, and the wasm check once: wasm-pack test --node crates/pixfx-effects --test determinism -- --include-ignored.