FERRETGame engine over Babylon.js
Ferret

Special effects

@ferret/vfx makes the things that happen in a scene and are not bodies: a campfire, a burning house, a shell bursting, a fountain, a breath on a cold morning, a lightning stroke. The module is a library of numbers: a definition (JSON) is compiled, a deterministic simulation steps it in the fixed 60 Hz step, a gather turns the live particles into flat arrays, and one view file draws them (Babylon in the browser, the plugin's materials in Unreal). Everything that decides what is drawn is pure TypeScript, so every peer of a networked game and the Unreal build make the same choices.

The first rule is the one the physics guides state: an effect follows the physics. A fire is as big as its heat release, a splash as wide as the energy of the body that fell, smoke as dark as the fuel makes it; a number you set by hand wins over the physical one, and every art value in the catalogue is marked as art (the plan keeps the list).

The layers#

layerfileswhat it does
definitiondef.ts, expr.ts, params.ts, validate.tsthe JSON of an effect: parameters with units and limits, emitters, modules, sub-emitters, volume, impostor, dot, light, decal, sound; every number may be an expression; the validator names the JSON path of a fault
simcompile.ts, sim.ts, rng.tsVfxSystem: spawn, step, stop, set a parameter, snapshot and restore; seeded, so the same inputs make the same particles
ladderladder.ts, select.ts, governor.tsthe rungs volume, particles, impostor, dot, none, chosen by size on the screen with a cross-fade, capped by a governor
viewgather.ts, view.ts, parts*.ts, volume*.ts, textures.tsthe arrays and the drawing: soft particles, lights under a budget, decals, far strips and dots, the volume raymarch, flipbooks
cataloguecatalog-*.ts, catalog-kit.tsthe effects shipped: fire, blast, world, energy, with their sound (FULL_CATALOG)
physicsdrive.ts, world-fx.ts, blast-fx.tsthe physics events and the formulas that turn them into effects and their parameters
firespread.ts, spread-bridge.ts, plume.tsa fire front on a grid (Rothermel), from house to house by radiation, and the plume the smoke makes
sightsight.tssmoke against sight: the optical depth of a ray, transmittance, for the AI and visibility
soundsound-fx.ts, sound-play.ts, catalog-sound.tsspeed of sound, air absorption, loudness by distance, the player that follows the effects
netvfx-net.tscommands cross the wire, not particles; late join by a snapshot
editingvfx-commands.tsthe vfx.* commands, an exact undo, the manifest block, the vfx world service

A first effect#

import { VfxSystem, FIRE_CATALOG, VfxBabylonView } from '@ferret/vfx';

const sys = new VfxSystem();
sys.registerAll(FIRE_CATALOG);
sys.host = { wind: (_x, _y, _z, _t, out) => { out[0] = 4; out[2] = 1; }, groundHeight: () => 0 };
const fire = sys.spawn('fire.campfire', { at: [0, 0, 0], seed: 7, params: { heat: 2e5 } });   // heat in watts

const view = new VfxBabylonView(scene, sys, camera, { soft: true, supports: ['particles', 'impostor', 'dot'] });
// in the fixed step:
sys.step(1 / 60);
// once a frame:
view.draw({ cameraPosition: [cam.x, cam.y, cam.z], fov: camera.fov, heightPx: engine.getRenderHeight(), tier: 'high', dt, night: 0 });

sys.spawn takes a name from the catalogue, a place, a seed and the parameters the definition names (vfx.list shows them with units, defaults and limits). A parameter outside its limits is clamped, a name the definition does not know is an error that says so.

Driven by physics#

import { driveFromPhysics } from '@ferret/vfx';
const stop = driveFromPhysics(world.events, sys, { materialOf, dustAt });

The drive listens to the events the physics capabilities already emit (a blast, a gun's fire, an impact, a body falling into water, a fire in a chamber, a vessel that bursts) and starts the effect whose parameters come from the event's numbers: the energy of a blast scales the fireball by the cube root, the material under an impact picks the debris, a body of 500 J or more falling into water makes water.splash of radius 0.5 (E / ρg)^¼. Nothing is drawn below minImpactEnergy. A game that does not use the physics host starts effects by hand with sys.spawn.

The catalogue#

FULL_CATALOG is the four families with their sound:

  • FIRE_CATALOG: candles, campfires, torches, fires of grass, ground, crowns and buildings, jets, flamethrowers, chimney and screen smoke;
  • BLAST_CATALOG: bombs, shells, mines, depth charges, flak, grenades, fuel-air; muzzle flashes by calibre; impacts by material;
  • WORLD_CATALOG: splashes, wakes, waterfalls, fountains, bubbles, steam, breath, fog, dust by cause and surface, sparks, arcs, wind crests;
  • ENERGY_CATALOG: beams, plasma, shields, force fields, teleports, lightning, implosions.

sys.registerAll takes any of them; a game registers the families it uses. The names are family.thing (fire.campfire, blast.he-ground, water.splash, energy.lightning). Your own effect is a JSON object checked with validateDef and registered the same way; catalog-kit.ts has the builders (puff, streaks, glow) the shipped ones use.

The ladder#

An effect far away is not drawn with every particle. By its size in pixels it is a volume (a raymarched box, only where supports has it and the definition has a volume), particles, an impostor (a leaning strip the colour of the effect, as tall as its plume), a dot (never less than a pixel and a half, brighter at night for a light), or none. A change of rung cross-fades over a quarter of a second; the thresholds are measured, not guessed, and Governor lowers the cap when the frame is over budget. view.rungOf(handle) and view.stats say what is drawn.

Fire that spreads, smoke that hides#

FireSpread is a fire front on a grid of fuel cells (Rothermel's model: wind, slope, moisture, the residence time of the fuel, spotting by embers). FireBridge makes the burning cells fire effects (one per stride cells) and carries heat between targets: a house is { id, at, material, burn: { effect, params } }, and the radiation of a burning neighbour heats it to its ignition temperature. SmokeSight reads the live smoke of a simulation as a sight contract: transmittance(a, b) is the share of light that gets through, 1 clear to 0 hidden; the Attention of the AI module and a visibility ray ask the same question.

Sound#

Every catalogue effect carries its sound (SILENT lists the few that do not: candle, chimney, white smoke, fog). The numbers are physical: sound arrives after d / c with c = 331.3 √(1 + T / 273.15) (1480 m/s in water), the high frequencies fall by ISO 9613-1 air absorption (a lowpass whose cutoff goes down with distance), the loudness law is an inverse one from a radius that comes from the energy. VfxSoundPlayer follows the instances: spawned(id, name, at, params) when one starts, stopped(id) when it ends, update() each frame; a loop takes live parameters (setParam). The 28 synthesised presets are vfx-* in @ferret/media (defineSynthPresets(audio, { names: SOUND_PRESETS })), and the library package vfx-sounds has them rendered.

The network#

What crosses the wire is commands, never particles: VfxReplica stamps each command with time = now + lead (0.25 s), every peer applies them in (time, peer, n) order, and a command that arrives late is counted (late). A peer that joins says hello and receives a snapshot (the simulation, the fire log and the pending commands), with its clock advanced by half the round trip. installVfxNet(net, replica) connects it to a NetService; replica.asSim() is the facade the physics drive can start effects on.

Editing by commands#

registerVfxCommands(registry, session) gives a person, a test and an agent the same commands: vfx.list, vfx.spawn, vfx.place, vfx.unplace, vfx.remove, vfx.stop, vfx.set, vfx.attach, vfx.def.create, vfx.def.patch (JSON pointer), vfx.def.validate, vfx.undo, vfx.redo, vfx.opticalDepth, vfx.manifest, vfx.stats. A VfxSession keeps the undo exact: after undo the simulation, the decals and the picture are the ones before. A level's manifest has a vfx block, { "defs": [...], "place": [{ "id", "def", "at", "params" }] }, started while the level is loaded and removed when it goes (the vfx service, found by the level loader), and checked by validateVfxBlock.

The ?vfx viewer (node tools/build.mjs viewer) adds vfx.view (an effect at a distance, a tier, a time, a wind, day or night), vfx.step, vfx.screenshot and vfx.renderer.

The sample#

examples/vfx is a gallery of the whole catalogue (?gallery: select, next, night, wind) and a village under shelling: fires spread through the grass and from house to house, smoke hides the courier from the lookout, each bang is heard after the time sound takes to come. Build it with node tools/build.mjs vfx.

In Unreal#

The Unreal side is not finished; work on it was stopped by the owner. What exists: the package is translated with the game; vfx/view, vfx/parts-view, vfx/volume-view and vfx/textures are written for the UE side (they hand the arrays of the browser view to the plugin, __ueHostApi.vfx, Private/FerretVfx.cpp, with materials M_Ferret_Vfx_*), facade.mjs check examples/vfx passes, and the packaged game runs on the RTX 3050 with decals and effect lights drawn. What does not work: the particle sprites and the volume do not appear on screen (the cause is not found), and neither the gallery nor side-by-side screenshots with the browser were made. The pixel generators live in pixels.ts (translated), textures.ts only wraps them for Babylon. Do not rely on effects in a UE build until this is picked up again; plans/PLAN-VFX.md (F15) has the details.

What to know#

  • The simulation costs about a millisecond per thousand particles on the CPU. A scene with many effects needs its own governor (the village stops the farthest effect over 5000 particles).
  • A definition with a volume falls back to its particles where the view cannot draw a volume (not supported, or no source yet).
  • Effects are deterministic only through the seed and the fixed step: never step from the frame time.
  • Honest limits are written in plans/PLAN-VFX.md beside each stage: the shield ripple is a ring of motes, the sound's lowpass is set at the start of a sound, the network was not run over a real transport.