Files
feuerwerk/src/viewport/particles.ts
T
adminandClaude Opus 5.5 808e1eefc2
game-maker / gate (push) Successful in 3m2s
game-maker / suite (push) Successful in 15m29s
Clean up duplicates and dead code, and fix the + menu check (#85)
Refactoring round 9 covers everything since round 8 (14972d0): 62
commits with about 29 000 new lines in src, api, tools and tests.
Behaviour is unchanged. The one fix is in a check: e2e 04 counted 25
asset types, and the shader function from #303 makes 26, so the run
of a526e1b failed there.

Duplicate code (jscpd over src, 50 tokens, without the two licence
texts: 35 clones / 289 lines before, 29 / 232 after):

- ShaderPicture (new, viewport/shaderPicture.ts) is the picture a
  camera's shader and a particle field's shader are laid over. It
  keeps the render texture while its size holds and frees the
  replaced one once the shader holds the new one. CameraShade and
  ParticleField.shadeField drew it the same way, line for line.
- CameraShade builds its mesh on the first draw. Before, every redraw
  of a view without a camera shader built a mesh and threw it away.
- emptyHost in inspector/host.ts builds the empty host the Inspector,
  the Variables tab and the Tilemap panel start from.
- paddedQuad(null) is the plain unit quad. symbols.ts and
  shaderPasses.ts each wrote it out by hand.
- In graph/nested.ts, calls of shader functions and On behavior
  nodes are followed by one walk, `reaches`, over ids `namedBy` a
  node type.

Dead code:

- ShaderEditor.colorFieldOf and the getter CurveCanvas.snapping had
  no reader.
- 22 values used only in their own file lose their `export`. Types
  and the node catalogues of shaders and particles stay exported.
- Kept on purpose: PhysicsSystem.holdsJoint is read by tests only,
  but it is their one view of whether a joint holds.
- A pass with stricter lint rules over every file changed since
  round 8 found no bug. PixelArtEditor.started is now readonly.

Comments and docs:

- Ten comments told history ("since #190", "used to", "any more").
  They now describe what is. The bundle is md5-identical before and
  after, and the four e2e files minify to the same bytes.
- README: joint and shader function in the asset list, joints on the
  Physics row, what the Shaders page covers, two CI runners.
- e2e 04 keeps the number of asset types once, as ASSET_TYPE_COUNT.
- screenshot.png in the README is a new picture of the editor
  (3840x2160 instead of 1825x1140), taken by the user.

Tests:
- Gate on melektaus-atx: 229 files, 3514 tests, CHECK EXIT 0
  (+3 for emptyHost, +1 for the unit quad).
- e2e 1-4, 31, 63 on melektaus-atx: ALL PASSED, 195 checks. That is
  the + menu of 04, the field shader of 31 and the camera shader of
  63, both through ShaderPicture.
- No new e2e check, so the sum stays 1728.
- Counter-checks, each put back and compared with cmp: reaches that
  never goes on fails 1 test, listensTo reading the wrong parameter
  fails 1, emptyHost dropping what a panel hands in fails 1, folding
  without a relayout fails 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 17:38:39 +02:00

301 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Container, type Mesh, Particle, ParticleContainer, type Renderer, type Texture } from 'pixi.js';
import { type CompiledParticles, emptyParticleOut, type ParticleOut } from '../core/particles/compile';
import { birthTime, type EmitterSettings, fieldTime, liveRange } from '../core/particles/emission';
import type { ParticleEnv } from '../core/particles/nodes';
import { rectsIntersect, type WorldRect } from '../core/properties/camera';
import { type Mat, scaleOf } from '../core/model/matrix';
import { booleanOf, type PropertyBag } from '../core/model/Properties';
import {
BURST_COUNT_KEY,
emitModeOf,
EMITTING_KEY,
fieldShaderOf,
fieldSizeOf,
LIFETIME_KEY,
MAX_PARTICLES_KEY,
MOVE_WITH_SOURCE_KEY,
PARTICLE_COLOR_KEY,
PARTICLE_SIZE_KEY,
PREWARM_KEY,
RATE_KEY,
TIME_SCALE_KEY,
} from '../core/properties/particles';
import { fieldFrame } from './fieldFrame';
import { ShaderPicture } from './shaderPicture';
import { disposeParticleShader, type ShaderSource, syncParticleShader, syncShader } from './shaders';
import { disposeSpriteMesh, newSpriteMesh, placeNode } from './symbols';
const DEG = Math.PI / 180;
function emitterSettings(props: PropertyBag): EmitterSettings {
return {
mode: emitModeOf(props),
rate: numberOf(props[RATE_KEY], 20),
count: numberOf(props[BURST_COUNT_KEY], 20),
lifetime: numberOf(props[LIFETIME_KEY], 1),
timeScale: Math.max(0, numberOf(props[TIME_SCALE_KEY], 1)),
prewarm: booleanOf(props[PREWARM_KEY] ?? false),
max: Math.max(1, numberOf(props[MAX_PARTICLES_KEY], 500)),
};
}
function numberOf(value: unknown, fallback: number): number {
const n = Number(value);
return Number.isFinite(n) ? n : fallback;
}
/**
* One particle source as it is drawn: a Pixi `ParticleContainer`, which puts all of them in a single
* draw call, plus the little state a formula cannot hold – when emission started and, for particles
* left behind in the world, where their source stood when they were born.
*
* `node` is what a view attaches. It holds the particles themselves, or – while the source wears a
* field shader (#170) – the picture they were drawn into, with the shader laid over it.
*/
export class ParticleField {
readonly node = new Container();
readonly container = new ParticleContainer<Particle>({
dynamicProperties: { position: true, vertex: true, rotation: true, color: true, uvs: false },
});
/** Where the particles are drawn from while a field shader is worn: on no stage at all. */
private readonly offstage = new Container();
private fieldMesh: Mesh | null = null;
private readonly fieldPicture = new ShaderPicture();
private readonly out: ParticleOut = emptyParticleOut();
private readonly pool: Particle[] = [];
/** Seconds, on the library's clock, at which this source last started emitting. */
private startedAt: number | null = null;
/** How far it was still taking in new particles: frozen while `emitting` is off. */
private emittedUntil = 0;
/** The source's transform when each particle was born, kept per index modulo the capacity. */
private born: Mat[] = [];
private capacity = 0;
private highest = -1;
/** The Emit count last seen; a change is a request to start over. */
private emits = -1;
/** Set while a panel holds the field at one age, instead of reading it off the clock. */
private heldAge: number | null = null;
constructor() {
this.container.eventMode = 'none';
this.node.eventMode = 'none';
this.node.addChild(this.container);
}
/** Seconds the source has been emitting; -1 before it ever started. */
elapsed(now: number): number {
return this.startedAt === null ? -1 : now - this.startedAt;
}
/**
* Stands the field at exactly this age; null lets it read the clock again. Handing it a clock that
* *would* read that age instead costs the last bits of the second – 0.5 comes out as
* 0.49999999999999994 about one time in ten, which is one particle short of the field due there.
*/
hold(age: number | null): void {
this.heldAge = age;
}
/** Starts the clock over: a burst goes out again, a continuous stream begins at particle 0. */
restart(now: number): void {
this.startedAt = now;
this.emittedUntil = 0;
this.reset();
}
/**
* Moves the origin so the field is `to` seconds old at `now`, keeping every particle where it is.
* What a held preview needs when it is let go: without it the clock ran on underneath the freeze.
*/
rebase(now: number, to: number): void {
this.startedAt = now - to;
}
private reset(): void {
this.highest = -1;
this.born = [];
this.capacity = 0;
}
/**
* Brings the drawn particles up to `now`. Everything about one particle comes out of `compiled`;
* the only thing read from a frame is how far the clock has moved.
*/
sync(
compiled: CompiledParticles | null,
props: PropertyBag,
params: readonly number[],
m: Mat,
texture: Texture,
now: number,
emits = 0,
/** Mixed into every particle's seed, so two sources of one asset do not scatter identically. */
salt = 0,
): void {
const emitting = booleanOf(props[EMITTING_KEY] ?? true);
if (this.emits !== emits) {
// Not on the first sight of a source: that would throw its first burst away again.
if (this.emits >= 0) this.restart(now);
this.emits = emits;
}
// An origin in the future means the global clock went back to zero under the field (a play run
// began or ended); ageing every particle backwards from there is no state worth keeping.
let startedAt = this.startedAt;
if (startedAt === null || now < startedAt) {
this.restart(now);
startedAt = now;
}
const settings = emitterSettings(props);
const time = fieldTime(settings, this.heldAge ?? now - startedAt);
if (emitting) this.emittedUntil = time;
const range = compiled ? liveRange(settings, time, this.emittedUntil) : { from: 0, to: -1 };
const capacity = Math.max(1, Math.floor(settings.max));
if (capacity !== this.capacity) {
this.capacity = capacity;
this.born = [];
this.highest = -1;
}
// Stepping back in time (the tab's slider) leaves birth places that no longer belong to anyone.
if (range.to < this.highest) this.highest = range.from - 1;
for (let i = Math.max(this.highest + 1, range.from); i <= range.to; i++) this.born[i % capacity] = m;
this.highest = Math.max(this.highest, range.to);
const moves = booleanOf(props[MOVE_WITH_SOURCE_KEY] ?? false);
const size = Math.max(0.01, numberOf(props[PARTICLE_SIZE_KEY], 16));
const sourceColor = numberOf(props[PARTICLE_COLOR_KEY], 0xffffff);
const baseW = texture.width || 1;
const baseH = texture.height || 1;
const env: ParticleEnv = {
age: 0,
ageSeconds: 0,
time,
index: 0,
seed: 0,
color: sourceColor,
params,
};
// The shader samples the container's own texture, not each particle's, so it has to be set here.
this.container.texture = texture;
const particles = this.container.particleChildren;
particles.length = 0;
if (compiled)
for (let index = range.from; index <= range.to; index++) {
const ageSeconds = time - birthTime(settings, index);
env.index = index;
env.seed = index ^ salt;
env.ageSeconds = ageSeconds;
env.age = settings.lifetime > 0 ? ageSeconds / settings.lifetime : 0;
compiled.evaluate(env, this.out);
const place = moves ? m : (this.born[index % capacity] ?? m);
const p = this.take(particles.length, texture);
p.texture = texture;
p.x = place.a * this.out.x + place.c * this.out.y + place.tx;
p.y = place.b * this.out.x + place.d * this.out.y + place.ty;
const scale = scaleOf(place);
p.scaleX = (size * this.out.scaleX * scale) / baseW;
p.scaleY = (size * this.out.scaleY * scale) / baseH;
p.rotation = this.out.rotation * DEG + Math.atan2(place.b, place.a);
p.tint = this.out.color;
p.alpha = this.out.alpha;
particles.push(p);
}
this.container.update();
}
/** Puts the shader the source names on every particle of this field, or takes one off (#88). */
wear(props: PropertyBag, shaders: ShaderSource, texture: Texture | null): void {
// Without a picture a particle is its plain square, and a pixel is one unit of its size.
const size = Math.max(0.01, numberOf(props[PARTICLE_SIZE_KEY], 16));
const picture = texture ? { w: texture.width, h: texture.height } : { w: size, h: size };
syncParticleShader(this.container, props, shaders, picture, texture);
}
/**
* Lays the field shader the source names over the whole field (#170): the particles are drawn into
* a picture of the frame, with as many pixels as the frame covers on screen, and the shader draws
* that picture where the frame stands. Without one – or with one that does not compile – the
* particles are drawn as they are. `bounds` is the world the view shows: a frame outside it costs
* no pass at all. Call it after `sync`, which is what moves the particles.
*/
shadeField(
props: PropertyBag,
shaders: ShaderSource,
m: Mat,
pixelsPerUnit: number,
renderer: Renderer,
bounds: WorldRect | null,
): void {
const id = fieldShaderOf(props);
const compiled = id ? shaders.compiled(id) : null;
if (!compiled) {
this.unshade();
return;
}
const mesh = this.fieldMesh ?? this.newFieldMesh();
if (this.container.parent !== this.offstage) this.offstage.addChild(this.container);
const size = fieldSizeOf(props);
const frame = fieldFrame(m, size.w, size.h, pixelsPerUnit);
mesh.visible = !bounds || rectsIntersect(frame.extent, bounds);
if (!mesh.visible) return;
const picture = this.fieldPicture.draw(
renderer,
this.offstage,
frame.pixels,
frame.toPicture,
null,
compiled.edge,
);
placeNode(mesh, m, size.w, size.h);
mesh.texture = picture;
// Nothing to count pixels in: the frame is the edge, so neither Padding nor Vertex output moves it.
// A pixel the shader reads counts as a unit of the frame, not of the screen.
syncShader(mesh, props, shaders, null, id, frame.unitsPerPixel);
this.fieldPicture.release();
}
/** The field shader's picture in device pixels while one is drawn, else null (test hook). */
get fieldPixels(): { w: number; h: number } | null {
return this.fieldMesh?.visible ? this.fieldPicture.pixels : null;
}
private newFieldMesh(): Mesh {
const mesh = newSpriteMesh();
this.node.addChild(mesh);
this.fieldMesh = mesh;
return mesh;
}
/** Back to drawing the particles themselves. */
private unshade(): void {
if (this.container.parent !== this.node) this.node.addChild(this.container);
if (this.fieldMesh) disposeSpriteMesh(this.fieldMesh);
this.fieldMesh = null;
this.fieldPicture.destroy();
}
/** Particles are reused rather than rebuilt: a stream of 500 would otherwise allocate 500 a frame. */
private take(slot: number, texture: Texture): Particle {
let p = this.pool[slot];
if (!p) {
p = new Particle({ texture, anchorX: 0.5, anchorY: 0.5 });
this.pool[slot] = p;
}
return p;
}
/** How many are drawn right now – what the checks read. */
get count(): number {
return this.container.particleChildren.length;
}
destroy(): void {
this.unshade();
disposeParticleShader(this.container);
this.container.destroy();
this.offstage.destroy();
this.node.destroy();
}
}