// Wake field — a Meep example for the GPU fluid simulation + wake effector +
// GPU particles.
//
// A ball streaks left-to-right across a field of ~60,000 GPU particles, towing a
// WakeFluidEffector through a 2-cascade GPUFluidComponent domain centred above
// the ground. The particles spawn across the 14×10 grid where the plantation
// stands and sample the GPU wind field every frame through the particle VM's
// `wind` opcode (`SAMPLE_WIND`) — so the ball's slipstream and shed vortex pair
// roll through the particle field as a visible 3D wave.
//
// The pieces and who does what:
//
// - GPUFluidComponent the domain: nested, two-way coupled 3D cascades
// centred on its entity's Transform64.
// - WakeFluidEffector the stirrer: rides the ball entity inside a
// FluidEffectorsComponent. On the GPU its swept
// capsule is derived from the ball's current and
// previous world matrices (`global` vs `prev_global`).
// - GlobalFluidEffector the calm far field (`wind = 0`, `drag = 1.25`):
// gives the GPU cascades a still-air reference to
// relax toward so wakes settle between passes.
// - GPUFluidSystem steps the cascade stack on the GPU and publishes
// the velocity field to `GPUSceneContext#wind`.
// - GPUParticleEmitterSystem spawns and simulates ~60k particles on the GPU,
// sampling `wind` at each particle's world position.
//
// Sections:
// §1 Tuning constants
// §2 Shade materials & particle sprite
// §3 Engine bootstrap
// §4 Ground
// §5 The GPU fluid volume + calm far field
// §6 The particle field ~60k GPU particles arranged across the 14×10 grid
// §7 The ball + its wake
// §8 Per-frame fly the ball, HUD
import { EngineHarness } from "@woosh/meep-engine/src/engine/EngineHarness.js";
import TopDownCameraController from "@woosh/meep-engine/src/engine/graphics/ecs/camera/topdown/TopDownCameraController.js";
import { Light } from "@woosh/meep-engine/src/engine/graphics/ecs/light/Light.js";
import { LightType } from "@woosh/meep-engine/src/engine/graphics/ecs/light/LightType.js";
import Entity from "@woosh/meep-engine/src/engine/ecs/Entity.js";
import { Transform64 } from "@woosh/meep-engine/src/engine/ecs/transform/Transform64.js";
import { TRANSFORM64_EVENT_PLACED } from "@woosh/meep-engine/src/engine/ecs/transform/TRANSFORM64_EVENT_PLACED.js";
import { t64_announce_change } from "@woosh/meep-engine/src/engine/ecs/transform/t64_announce_change.js";
import { ShadedGeometry } from "@woosh/meep-engine/src/engine/graphics/ecs/mesh-v2/ShadedGeometry.js";
import { ShadedGeometrySystem } from "@woosh/meep-engine/src/engine/graphics3/ShadedGeometrySystem.js";
import { make_box_geometry } from "@woosh/meep-engine/src/shade/renderer/geometry/primitives/make_box_geometry.js";
import { make_octahedron_geometry } from "@woosh/meep-engine/src/shade/renderer/geometry/primitives/make_octahedron_geometry.js";
import { meshlet_geometry_build_from_geometry } from "@woosh/meep-engine/src/shade/renderer/geometry/meshlet_geometry_build_from_geometry.js";
import { StandardShadeMaterial } from "@woosh/meep-engine/src/shade/renderer/material/StandardShadeMaterial.js";
import Trail3D from "@woosh/meep-engine/src/engine/graphics/ecs/trail3d/Trail3D.js";
import { Trail3DSystem } from "@woosh/meep-engine/src/engine/graphics3/Trail3DSystem.js";
import { NodeGraph } from "@woosh/meep-engine/src/core/model/node-graph/NodeGraph.js";
import { ParticleEffect } from "@woosh/meep-engine/src/engine/graphics/ecs/particles/ParticleEffect.js";
import { GPUParticleEmitterSystem } from "@woosh/meep-engine/src/engine/graphics3/GPUParticleEmitterSystem.js";
import {
EMITTER_BLEND,
EMITTER_PROJECTION,
} from "@woosh/meep-engine/src/shade/renderer/particles/data/PARTICLE_EMITTER_STRUCT.js";
import {
particle_node,
particle_wire,
} from "@woosh/meep-engine/src/shade/renderer/particles/graph/particle_graph_authoring.js";
import { VM_BUILTIN } from "@woosh/meep-engine/src/shade/renderer/particles/isa/ParticleVMISA.js";
import { ParticleLayout } from "@woosh/meep-engine/src/shade/renderer/particles/layout/ParticleLayout.js";
import { create_particle_effect } from "@woosh/meep-engine/src/shade/renderer/particles/runtime/create_particle_effect.js";
import { GPUFluidComponent } from "@woosh/meep-engine/src/engine/physics/fluid/ecs/GPUFluidComponent.js";
import { GPUFluidSystem } from "@woosh/meep-engine/src/engine/graphics3/GPUFluidSystem.js";
import { FluidEffectorsComponent } from "@woosh/meep-engine/src/engine/physics/fluid/ecs/FluidEffectorsComponent.js";
import { FluidEffectorsSystem } from "@woosh/meep-engine/src/engine/physics/fluid/ecs/FluidEffectorsSystem.js";
import { GlobalFluidEffector } from "@woosh/meep-engine/src/engine/physics/fluid/effector/GlobalFluidEffector.js";
import { WakeFluidEffector } from "@woosh/meep-engine/src/engine/physics/fluid/effector/WakeFluidEffector.js";
import { Color } from "@woosh/meep-engine/src/core/color/Color.js";
import Vector3 from "@woosh/meep-engine/src/core/geom/Vector3.js";
// ─── §1 Tuning constants ────────────────────────────────────────────────────
// The spawn volume: spans the 14 × 10 plantation footprint (23.8 m × 17.0 m).
const SITES_X = 14;
const SITES_Z = 10;
const SITE_SPACING = 1.7;
const SPAWN_HALF_X = (SITES_X * SITE_SPACING) * 0.5;
const SPAWN_HALF_Z = (SITES_Z * SITE_SPACING) * 0.5;
const SPAWN_Y_MIN = 0.15; // vertical spawn band above the ground (m)
const SPAWN_Y_MAX = 2.75;
// ~60,000 average live particles by Little's Law: 20,000/s × 3.0 s mean life = 60,000.
const PARTICLE_SPAWN_RATE = 20000;
const PARTICLE_LIFE_MIN = 2.8;
const PARTICLE_LIFE_MAX = 3.2;
// Ground footprint.
const FIELD_SIZE_X = 30;
const FIELD_SIZE_Z = 20;
// The GPU fluid cascade stack: 2 cascades of 64 × 32 × 64 cells, finest cell 0.6 m.
// Centred at Y = 6.0 m so cascade 0 (38.4 × 19.2 × 38.4 m) covers the entire
// ground footprint and 15.6 m of headroom above the ground, while cascade 1
// reaches 76.8 × 38.4 × 76.8 m.
const FLUID_RESOLUTION = [64, 32, 64];
const FLUID_CELL_SIZE = 0.6;
const FLUID_CASCADES = 2;
const FLUID_CENTER_Y = 6.0;
const CALM_DRAG = 1.25; // 1/s relaxation toward still air between passes
// The ball + its wake.
const BALL_RADIUS = 0.5;
const BALL_Y = 1.65; // flies right through the heart of the particle layer
const BALL_SPEED = 32.0; // m/s along its heading
const BALL_X_LIMIT = 16; // wrap when past this — just outside the field
const MAX_HEADING = Math.PI / 6; // ±30° — cap on the random per-pass tilt off the X axis
const WAKE_RADIUS = 3.0; // world-space influence radius of the swept capsule
const WAKE_STRENGTH = 2.2;
const PASS_PAUSE = 2.2; // seconds of off-screen run-up between passes
// The visible tube trail behind the ball.
const TRAIL_MAX_AGE = 0.6;
const TRAIL_WIDTH = 0.6;
const TRAIL_RADIAL_SEGMENTS = 6;
const GROUND_COLOR = "#161c24";
const BALL_COLOR = "#ffcf54";
// 7-stop velocity LUT in HDR linear RGB (emerald → teal → cobalt → violet → magenta → coral → gold),
// indexed by normalized wind speed (`excitement ∈ [0, 1]`).
const PLASMA_LUT_STOPS = [
{ position: 0.00, color: [0.10, 0.52, 0.34, 0.70] },
{ position: 0.10, color: [0.08, 0.64, 0.68, 0.73] },
{ position: 0.22, color: [0.14, 0.38, 0.98, 0.76] },
{ position: 0.36, color: [0.44, 0.16, 0.92, 0.80] },
{ position: 0.50, color: [0.71, 0.15, 0.40, 0.84] },
{ position: 0.75, color: [1.11, 0.43, 0.14, 0.90] },
{ position: 1.00, color: [1.40, 1.16, 0.27, 0.96] },
];
// ─── §2 Shade materials & particle sprite ───────────────────────────────────
function standardMaterial(hexColor, roughness, metalness = 0) {
const material = new StandardShadeMaterial();
material.diffuse_color.copy(Color.from_sRGB_to_linear(Color.parse(hexColor)));
material.roughness_factor = roughness;
material.metallic_factor = metalness;
return material;
}
// A soft radial sprite encoded as a PNG data URL so each particle billboard draws
// as an anti-aliased glowing mote / flow streak rather than a hard square quad.
function makeMoteSprite() {
const size = 48;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
const img = ctx.createImageData(size, size);
const data = img.data;
for (let iy = 0; iy < size; iy++) {
for (let ix = 0; ix < size; ix++) {
const x = ((ix + 0.5) / size) * 2 - 1;
const y = ((iy + 0.5) / size) * 2 - 1;
const r = Math.hypot(x, y);
const offset = (iy * size + ix) * 4;
data[offset] = 255;
data[offset + 1] = 255;
data[offset + 2] = 255;
if (r >= 1) {
data[offset + 3] = 0;
} else {
const falloff = 1 - r;
const core = Math.max(0, 1 - r * 1.65);
const alpha = Math.min(1, falloff * falloff * 0.65 + core * core * 0.55);
data[offset + 3] = Math.round(alpha * 255);
}
}
}
ctx.putImageData(img, 0, 0);
return canvas.toDataURL("image/png");
}
// ─── §3 Engine bootstrap ────────────────────────────────────────────────────
const engine = await EngineHarness.bootstrap({
configuration: (config, engine) => {
const shadeScene = EngineHarness.shadeScene(engine);
config.addSystem(new ShadedGeometrySystem(engine.graphics, shadeScene));
config.addSystem(new Trail3DSystem(engine.graphics, shadeScene));
config.addSystem(new FluidEffectorsSystem());
config.addSystem(new GPUFluidSystem(engine.graphics, shadeScene));
config.addSystem(new GPUParticleEmitterSystem(engine.graphics, shadeScene, engine.assetManager));
},
});
await EngineHarness.buildBasics({
engine,
enableTerrain: false,
enableWater: false,
enableLights: true,
enableShadows: true,
focus: new Vector3(0, 1.5, 0),
distance: 28,
pitch: 0.88,
yaw: 0,
cameraFarDistance: 84,
showFps: false,
});
engine.entityManager.dataset.getAnyComponent(TopDownCameraController).component.distanceMax = 56;
engine.graphics.renderer.feature_automatic_exposure_enabled = false;
engine.entityManager.dataset.traverseEntities([Light], (light) => {
if (light.type.getValue() === LightType.DIRECTION) {
light.intensity.set(6);
}
});
const ecd = engine.entityManager.dataset;
// ─── §4 Ground ──────────────────────────────────────────────────────────────
{
const t = new Transform64();
t.setTranslation(0, -0.25, 0);
new Entity()
.add(t)
.add(ShadedGeometry.from(
meshlet_geometry_build_from_geometry(
make_box_geometry(FIELD_SIZE_X + 10, 0.5, FIELD_SIZE_Z + 8),
),
standardMaterial(GROUND_COLOR, 1),
))
.build(ecd);
}
// ─── §5 The GPU fluid volume + calm far field ───────────────────────────────
//
// `GPUFluidComponent` + `Transform64` defines the nested 3D cascade stack that
// `GPUFluidSystem` steps on the GPU and publishes as the scene's wind field.
// Centring the domain at Y = 6.0 m places the finest cascade (38.4 × 19.2 × 38.4 m)
// over the entire meadow and well up into the space above the ground.
const fluid = new GPUFluidComponent();
fluid.resolution = FLUID_RESOLUTION;
fluid.cell_size = FLUID_CELL_SIZE;
fluid.cascade_count = FLUID_CASCADES;
const fluidTransform = new Transform64();
fluidTransform.setTranslation(0, FLUID_CENTER_Y, 0);
new Entity().add(fluidTransform).add(fluid).build(ecd);
// A calm GlobalFluidEffector (`wind = [0, 0, 0]`, `drag = 1.25`) provides the
// still-air far field that the GPU cascades relax toward so each pass's shed
// vortex pair plays out across the field and then settles.
const calmAtmosphere = new GlobalFluidEffector();
calmAtmosphere.wind = [0, 0, 0];
calmAtmosphere.drag = CALM_DRAG;
const calmEffectors = new FluidEffectorsComponent();
calmEffectors.addEffector(calmAtmosphere);
new Entity().add(calmEffectors).build(ecd);
// ─── §6 The particle field (~60k GPU particles) ─────────────────────────────
//
// In INIT, each newborn particle picks a random (ix, iz) site from the 14 × 10
// plantation grid and jitters around that column within [SPAWN_Y_MIN, SPAWN_Y_MAX].
// In UPDATE, each particle samples the 3D GPU fluid velocity at its world
// position via the `wind` node (`SAMPLE_WIND`), relaxes its velocity toward the
// local air flow, stretches along its screen-projected velocity, and shifts from
// calm meadow-emerald to bright mint-gold when swept into the ball's wake.
function node(graph, type, inputs = {}, parameters = {}) {
const id = particle_node(graph, type, parameters);
for (const [port, source] of Object.entries(inputs)) {
particle_wire(graph, id, port, source);
}
return id;
}
const read = (graph, name) => node(graph, "particleField", {}, { name });
const write = (graph, name, value) => node(graph, "setParticleField", { value }, { name });
function randomRange(graph, min, max) {
if (min === max) return [min];
const r = node(graph, "random", {}, { components: 1 });
return node(graph, "mad", { a: r, b: [max - min], c: [min] });
}
function scaleCurve(stops) {
const slope = (a, b) => (b[1] - a[1]) / (b[0] - a[0]);
return {
keys: stops.map(([time, value], i) => ({
time,
value,
inTangent: i === 0 ? 0 : slope(stops[i - 1], stops[i]),
outTangent: i === stops.length - 1 ? 0 : slope(stops[i], stops[i + 1]),
})),
};
}
function buildWakeParticleEffect(spriteUrl) {
const layout = new ParticleLayout([
{ name: "position", components: 3 },
{ name: "velocity", components: 3 },
{ name: "streak", components: 3 },
{ name: "age", components: 1 },
{ name: "life", components: 1 },
{ name: "size0", components: 1 },
{ name: "size", components: 1 },
{ name: "color", components: 4, type: "color" },
]);
const init = new NodeGraph();
const px = randomRange(init, -SPAWN_HALF_X, SPAWN_HALF_X);
const py = randomRange(init, SPAWN_Y_MIN, SPAWN_Y_MAX);
const pz = randomRange(init, -SPAWN_HALF_Z, SPAWN_HALF_Z);
write(init, "position", node(init, "vec3", { x: px, y: py, z: pz }));
const vy = randomRange(init, 0.08, 0.22);
write(init, "velocity", node(init, "vec3", { x: [0], y: vy, z: [0] }));
write(init, "streak", [0, 0, 0]);
write(init, "age", [0]);
write(init, "life", randomRange(init, PARTICLE_LIFE_MIN, PARTICLE_LIFE_MAX));
write(init, "size0", randomRange(init, 0.032, 0.056));
write(init, "size", [0]);
write(init, "color", [0.10, 0.52, 0.34, 0]);
const update = new NodeGraph();
const dt = node(update, "builtin", {}, { id: VM_BUILTIN.DELTA_TIME });
const age = node(update, "add", { a: read(update, "age"), b: dt });
const life = read(update, "life");
write(update, "age", age);
const expired = node(update, "compare", { a: age, b: life }, { op: "ge" });
node(update, "kill", { condition: expired });
const pos = read(update, "position");
const vel = read(update, "velocity");
const rawWind = node(update, "wind", { position: pos });
const speed = node(update, "length", { x: rawWind });
const gain = node(update, "div", {
a: [1.0],
b: node(update, "mad", { a: speed, b: [0.06], c: [1.0] }),
});
const w = node(update, "scale", { v: rawWind, s: gain });
const targetVel = node(update, "add", { a: w, b: [0, 0.15, 0] });
const dragT = node(update, "saturate", {
x: node(update, "mul", { a: dt, b: [6.5] }),
});
const velNext = node(update, "mix", { a: vel, b: targetVel, t: dragT });
const posNext = node(update, "add", {
a: pos,
b: node(update, "scale", { v: velNext, s: dt }),
});
write(update, "velocity", velNext);
write(update, "position", posNext);
write(update, "streak", node(update, "scale", { v: velNext, s: [0.34] }));
const u = node(update, "saturate", {
x: node(update, "div", { a: age, b: life }),
});
const excitement = node(update, "saturate", {
x: node(update, "mul", { a: speed, b: [0.14] }),
});
const env = node(
update,
"curveLiteral",
{ t: u },
{
curve: scaleCurve([
[0.0, 0.0],
[0.12, 1.0],
[0.78, 1.0],
[1.0, 0.0],
]),
},
);
const boost = node(update, "add", {
a: [1.0],
b: node(update, "mul", { a: excitement, b: [0.35] }),
});
write(
update,
"size",
node(update, "mul", {
a: read(update, "size0"),
b: node(update, "mul", { a: env, b: boost }),
}),
);
const plasmaColor = node(
update,
"gradientRGBA",
{ t: excitement },
{ stops: PLASMA_LUT_STOPS },
);
const ageFade = node(update, "vec4", { x: [1], y: [1], z: [1], w: env });
write(
update,
"color",
node(update, "mul", { a: plasmaColor, b: ageFade }),
);
return ParticleEffect.from({
...create_particle_effect({ layout, init, update }),
texture: spriteUrl,
spawn_rate: PARTICLE_SPAWN_RATE,
prewarm: PARTICLE_LIFE_MAX,
flags: {
soft_depth: true,
blend: EMITTER_BLEND.ALPHA,
projection: EMITTER_PROJECTION.STRETCHED,
},
render: {
position: "position",
velocity: "streak",
size: "size",
color: "color",
},
});
}
new Entity()
.add(new Transform64())
.add(buildWakeParticleEffect(makeMoteSprite()))
.build(ecd);
// ─── §7 The ball + its wake ─────────────────────────────────────────────────
const ballTransform = new Transform64();
ballTransform.setTranslation(-BALL_X_LIMIT, BALL_Y, 0);
const wake = new WakeFluidEffector();
wake.radius = WAKE_RADIUS;
wake.strength = WAKE_STRENGTH;
const effectors = new FluidEffectorsComponent();
effectors.addEffector(wake);
const trail = new Trail3D();
trail.maxAge = TRAIL_MAX_AGE;
trail.width = TRAIL_WIDTH;
trail.radialSegments = TRAIL_RADIAL_SEGMENTS;
trail.color.set(1.0, 0.82, 0.32, 0.85);
const ballMaterial = standardMaterial(BALL_COLOR, 0.35);
ballMaterial.emissive_factor.copy(Color.from_sRGB_to_linear(Color.parse(BALL_COLOR)));
ballMaterial.emissive_factor.multiplyScalar(0.45);
const ballEntity = new Entity()
.add(ballTransform)
.add(effectors)
.add(trail)
.add(ShadedGeometry.from(
meshlet_geometry_build_from_geometry(make_octahedron_geometry(BALL_RADIUS, 12)),
ballMaterial,
))
.build(ecd);
// ─── §8 Per-frame: fly the ball, HUD ────────────────────────────────────────
const fpsEl = document.getElementById("fps");
const LANE_MAX = ((SITES_Z - 1) / 2) * SITE_SPACING - 1;
let pass = 0;
let ballVx = BALL_SPEED;
let ballVz = 0;
function launchBall(lane, runUp) {
const exitZ = (Math.random() * 2 - 1) * LANE_MAX;
let heading = Math.atan2(exitZ - lane, 2 * BALL_X_LIMIT);
heading = Math.max(-MAX_HEADING, Math.min(MAX_HEADING, heading));
ballVx = BALL_SPEED * Math.cos(heading);
ballVz = BALL_SPEED * Math.sin(heading);
ballTransform.setTranslation(
-BALL_X_LIMIT - ballVx * runUp,
BALL_Y,
lane - ballVz * runUp,
);
}
launchBall(0, 0);
ecd.sendEvent(ballEntity, TRANSFORM64_EVENT_PLACED);
let fpsWindow = 0, fpsFrames = 0;
let lastFrameMs = performance.now();
engine.graphics.on.postRender.add(() => {
const nowMs = performance.now();
const dt = Math.min((nowMs - lastFrameMs) / 1000, 0.1);
lastFrameMs = nowMs;
const x = ballTransform.translation_x + ballVx * dt;
if (x > BALL_X_LIMIT) {
pass++;
const lane = (((pass * 0.618) % 1) - 0.5) * 2 * LANE_MAX;
launchBall(lane, PASS_PAUSE);
wake.reset_trail();
trail.clear();
t64_announce_change(ecd, ballEntity);
// Tell `GPUSceneRows` that the ball teleported so `prev_global` is
// re-seeded to `global` instead of sweeping a GPU wake across the wrap.
ecd.sendEvent(ballEntity, TRANSFORM64_EVENT_PLACED);
} else {
ballTransform.setTranslation(x, BALL_Y, ballTransform.translation_z + ballVz * dt);
t64_announce_change(ecd, ballEntity);
}
// — HUD
fpsWindow += dt;
fpsFrames++;
if (fpsWindow >= 0.5) {
fpsEl.textContent = (fpsFrames / fpsWindow).toFixed(0);
fpsWindow = 0;
fpsFrames = 0;
}
});