@umicat/three-sdk 1.41.0 → 1.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -73,7 +73,7 @@ const fire = await loadVfx('uploaded/campfire.vfx.json'); // + every image it na
73
73
  const fx = fire.spawn(); // many copies share the images
74
74
  scene.add(fx.root);
75
75
  // each frame: fx.update(dt); one-shot: if (fx.finished) fx.dispose();
76
- // a looping effect (a status aura): fx.stop() when it should end -- it drains, then fx.finished
76
+ // a looping effect (a status aura): fx.stop() when it should end -- it plays its `close` clip or drains, then fx.finished
77
77
  ```
78
78
 
79
79
  An effect has two kinds of layer. **Emitters** are particle systems modelled
@@ -133,7 +133,43 @@ finishes its cycle, a mesh layer or light with a window plays it out and a
133
133
  whole-cycle one goes out; then `finished` turns true. Works on every format
134
134
  version, which is how a game ends a looping effect.
135
135
 
136
- **Write the lowest version.** `minimumVersion(doc)` is 6 with trails, 5 with lights, 4 with meshes, 3 with a
136
+ **Tracks and clips (version 7, 1.42.0, ADR-056 step 2).** Godot's
137
+ AnimationPlayer for an effect. A track animates one value of one layer:
138
+ `{ target: 'meshes.ring.scale', keys: [[0, [0, 0, 0]], [.4, [1, 1, 1], .5]], interp? }`.
139
+ A target is `<emitters|meshes|lights|flipbooks>.<id>.<field>` and may go deeper
140
+ (`emitters.core.look.material.dissolve`, `meshes.ring.material.masks.1.strength`).
141
+ Numbers, vectors, `#rrggbb` colours (blended in linear space) and `enabled`
142
+ (always stepped) can be animated; a Range field takes a plain number while a
143
+ track drives it. A mesh's shape, a material's structure, curves, gradients and
144
+ ids cannot, and the parser says so by name. A key is `[time, value, ease?]`,
145
+ `ease` being Godot's transition exponent as-is (2 in, 0.5 out, negative
146
+ in-out, 0 hold); `interp: smooth` is Godot's cubic.
147
+
148
+ Without `clips`, a top-level `tracks` list plays over `duration` (the clip
149
+ `main`). With `clips: [{ name, duration, loop, next?, tracks }]` (and
150
+ `startClip`), each clip is a cycle of its own: emitter windows and bursts,
151
+ mesh and light windows and track times count from the clip's start; a clip
152
+ with `next` hands over when it ends; one with neither `loop` nor `next` ends
153
+ the effect. A field a clip does not animate holds the last value it was given,
154
+ as in Godot -- an `idle` with no tracks keeps a portal open.
155
+ `fx.play('idle')` switches at once, `fx.clip` / `fx.clipTime` say where it is,
156
+ **`fx.stop()` plays the clip named `close` when there is one**, and
157
+ `fx.seek(t, clip?)` replays to that moment at the fixed step (a clip reached
158
+ by `next` is played through its predecessors).
159
+
160
+ **Parameters and bindings (version 8, 1.43.0, ADR-056 step 4).** `params:
161
+ [{ name: 'open', value: 1, min: 0, max: 1 }]` are named numbers a game sets
162
+ (`fx.set('open', 0.4)`, `fx.get('open')`, `fx.paramNames`) and tracks can
163
+ animate (`params.open`). `bindings: [{ param: 'open', target:
164
+ 'lights.glow.range', map? }]` write a parameter into a layer's number or
165
+ vector (every component) after the tracks, every step -- so one number can
166
+ open a portal's light, particles and material together, which Godot's packs
167
+ do with a controller script. `map` is a Curve sampled at the parameter's place
168
+ in its range (0 at min, 1 at max). `animatableTargets(doc)` lists every target
169
+ the parser accepts; `timelineWarnings(doc)` names a field that is both keyed
170
+ and bound (the binding wins).
171
+
172
+ **Write the lowest version.** `minimumVersion(doc)` is 8 with parameters or bindings, 7 with tracks or clips, 6 with trails, 5 with lights, 4 with meshes, 3 with a
137
173
  material, else 2; the editor and the agent write that, so an effect that needs nothing
138
174
  new stays version 2 and keeps playing on 1.36.
139
175
 
@@ -33,13 +33,67 @@ export declare class VfxInstance {
33
33
  private meshLayers;
34
34
  private lightLayers;
35
35
  private state;
36
- /** Effect time when `stop()` was called, or null. */
36
+ /** CLIP time when `stop()` was called with no `close` clip to play, or null. */
37
37
  private stoppedAt;
38
+ private stopRequested;
39
+ private clips;
40
+ private startClip;
41
+ private cur;
42
+ /** Effect time the current clip began. */
43
+ private clipStart;
44
+ /** The static value of every field some track writes, for `reset()`. */
45
+ private restores;
46
+ private wires;
47
+ /** Each parameter's value in the document, for `reset()`. */
48
+ private paramDefaults;
38
49
  /** Particles born so far: hashed into each particle's `seed`. */
39
50
  private serial;
40
51
  private accumulator;
41
52
  private live;
42
53
  constructor(document: VfxDocument, options?: VfxInstanceOptions);
54
+ private liveOf;
55
+ /** Refreshes what was derived from a layer's config when a track wrote into it. */
56
+ private syncer;
57
+ /** Starts `clip` at effect time `start`: its windows, bursts and track times count from there. */
58
+ private enter;
59
+ /** Writes every track of the current clip at the clip's time. Fields no track of it names hold their last value. */
60
+ private applyTracks;
61
+ /** Parameters into their fields: after the tracks, so a bound field follows its parameter. */
62
+ private applyBindings;
63
+ private writeTracks;
64
+ /** A clip that ended hands over to its `next`, exactly at its end -- after landing on its own last values, as Godot does. */
65
+ private advanceClip;
66
+ /**
67
+ * Sets parameter `name` (clamped to its min-max) and carries it into its
68
+ * bindings at once. A track on the parameter in the clip playing writes it
69
+ * again on the next step -- the clip wins while it animates it, as in Godot.
70
+ */
71
+ set(name: string, value: number): void;
72
+ /** A parameter's value now, or undefined when the effect has no such parameter. */
73
+ get(name: string): number | undefined;
74
+ /** Every parameter this effect has. */
75
+ get paramNames(): string[];
76
+ /** The clip playing now (`main` for an effect without clips). */
77
+ get clip(): string;
78
+ /** Every clip this effect has, in document order. */
79
+ get clipNames(): string[];
80
+ /** Seconds since the current clip began. */
81
+ get clipTime(): number;
82
+ /**
83
+ * Switches to clip `name` at once (Godot snaps, so do we): particles alive
84
+ * keep living, fields its tracks do not name keep their last value. Also
85
+ * undoes a `stop()`.
86
+ */
87
+ play(name: string): void;
88
+ /**
89
+ * Jumps to `seconds` into `clip` (default: the current one), by replaying
90
+ * from `reset()` at the fixed step -- so the frame is exactly what
91
+ * `update()` would have reached. A clip reached from the start clip by
92
+ * `next` is played through its predecessors, so it starts with the values
93
+ * they leave (an `idle` after an `open`); any other clip starts from the
94
+ * document's own values.
95
+ */
96
+ seek(seconds: number, clip?: string): void;
43
97
  private buildParticles;
44
98
  private buildTrail;
45
99
  /** (Re)creates the per-instance buffers with room for `capacity` particles. */
@@ -59,7 +113,7 @@ export declare class VfxInstance {
59
113
  * format version; `reset()` undoes it.
60
114
  */
61
115
  stop(): void;
62
- /** True after `stop()`, until `reset()`. */
116
+ /** True after `stop()`, until `reset()` or `play()`. */
63
117
  get stopped(): boolean;
64
118
  reset(): void;
65
119
  get particleCount(): number;
@@ -1,11 +1,13 @@
1
1
  import * as T from 'three';
2
2
  import { parseVfx, pickRange, sampleCurve, sampleGradient, LIMITS, } from './document.js';
3
- import { compileMaterial, materialDefaults, maskDefaults } from './material.js';
3
+ import { compileMaterial, materialDefaults, maskDefaults, updateMaterialUniforms } from './material.js';
4
+ import { effectClips, resolveTarget, prepareTrack, sampleTrack, linearToHex } from './timeline.js';
4
5
  import { TrailMesh, trailSampling, trailVertex, newHistory, pushHistory, historyAt } from './trail.js';
5
6
  import { meshGeometry, fixRingUv, meshLayerVertex, meshParticleVertex, meshFragment } from './mesh.js';
6
7
  /** Closed shapes are drawn front-only, so an additive sphere does not show its back through its front. */
7
8
  const closed = (s) => s.type === 'sphere' || s.type === 'box' || s.type === 'torus' || (s.type === 'cylinder' && s.caps);
8
9
  const SIDE = { front: T.FrontSide, back: T.BackSide, both: T.DoubleSide };
10
+ const trackScratch = [];
9
11
  const SHARED_QUAD = (() => {
10
12
  // Corners in [0,1]^2 with y UP; the shader turns them into a cell-sized quad.
11
13
  const g = new T.BufferGeometry();
@@ -169,8 +171,17 @@ export class VfxInstance {
169
171
  this.meshLayers = [];
170
172
  this.lightLayers = [];
171
173
  this.state = 1;
172
- /** Effect time when `stop()` was called, or null. */
174
+ /** CLIP time when `stop()` was called with no `close` clip to play, or null. */
173
175
  this.stoppedAt = null;
176
+ this.stopRequested = false;
177
+ this.clips = new Map();
178
+ /** Effect time the current clip began. */
179
+ this.clipStart = 0;
180
+ /** The static value of every field some track writes, for `reset()`. */
181
+ this.restores = [];
182
+ this.wires = [];
183
+ /** Each parameter's value in the document, for `reset()`. */
184
+ this.paramDefaults = [];
174
185
  /** Particles born so far: hashed into each particle's `seed`. */
175
186
  this.serial = 0;
176
187
  this.accumulator = 0;
@@ -178,6 +189,21 @@ export class VfxInstance {
178
189
  this.document = parseVfx(document);
179
190
  this.state = this.document.seed;
180
191
  this.root.name = this.document.name;
192
+ // Tracks first: a material whose numbers a track drives compiles them in even at 0.
193
+ const timeline = effectClips(this.document);
194
+ const resolved = timeline.clips.map((c) => c.tracks.map((t) => [t, resolveTarget(this.document, t.target)]));
195
+ const live = new Map();
196
+ for (const [, r] of resolved.flat())
197
+ if (r.material) {
198
+ const key = `${r.kind}.${r.id}.${r.material.join('.')}`, sub = r.path.slice(r.material.length);
199
+ const set = live.get(key) ?? new Set();
200
+ live.set(key, set);
201
+ if (sub[0] === 'masks' && sub[2] === 'offset')
202
+ set.add(`offset${sub[1]}`);
203
+ if (sub[0] === 'displace' && sub[1] === 'amount')
204
+ set.add('displace');
205
+ }
206
+ this.liveOf = (key) => live.get(key) ?? new Set();
181
207
  const children = new Set(this.document.emitters.flatMap((e) => e.children.map((c) => c.emitter)));
182
208
  this.document.emitters.forEach((config, index) => {
183
209
  const layer = this.buildParticles(config, index, !children.has(config.id), (name) => resolveTexture(options.textures, name));
@@ -197,6 +223,219 @@ export class VfxInstance {
197
223
  this.root.add(light);
198
224
  this.lightLayers.push({ config, light, seed: seedOf(this.document.seed, 200000 + i) });
199
225
  });
226
+ const restored = new Set();
227
+ timeline.clips.forEach((clip, ci) => {
228
+ const bindings = resolved[ci].map(([track, r]) => {
229
+ let parent = this.document[r.kind][r.index];
230
+ for (const seg of r.path.slice(0, -1))
231
+ parent = parent[seg];
232
+ const key = r.path[r.path.length - 1], sync = this.syncer(r.kind, r.index);
233
+ const where = `${r.kind}.${r.index}.${r.path.join('.')}`;
234
+ if (!restored.has(where)) {
235
+ restored.add(where);
236
+ this.restores.push({ parent, key, base: structuredClone(parent[key]), sync });
237
+ }
238
+ return { sampled: prepareTrack(track, r.value), parent, key, kind: r.value, sync };
239
+ });
240
+ this.clips.set(clip.name, { name: clip.name, duration: clip.duration, loop: clip.loop, next: clip.next, bindings });
241
+ });
242
+ const params = this.document.params ?? [];
243
+ this.paramDefaults = params.map((p) => p.value);
244
+ for (const b of this.document.bindings ?? []) {
245
+ const r = resolveTarget(this.document, b.target);
246
+ let parent = this.document[r.kind][r.index];
247
+ for (const seg of r.path.slice(0, -1))
248
+ parent = parent[seg];
249
+ const key = r.path[r.path.length - 1], sync = this.syncer(r.kind, r.index);
250
+ const where = `${r.kind}.${r.index}.${r.path.join('.')}`;
251
+ if (!restored.has(where)) {
252
+ restored.add(where);
253
+ this.restores.push({ parent, key, base: structuredClone(parent[key]), sync });
254
+ }
255
+ this.wires.push({ param: params.find((p) => p.name === b.param), map: b.map, parent, key, kind: r.value, sync });
256
+ }
257
+ this.startClip = this.clips.get(timeline.start);
258
+ this.enter(this.startClip, 0);
259
+ this.applyTracks();
260
+ this.draw();
261
+ }
262
+ /** Refreshes what was derived from a layer's config when a track wrote into it. */
263
+ syncer(kind, index) {
264
+ // A parameter derives nothing itself; the bindings read it after every write.
265
+ if (kind === 'params')
266
+ return () => { };
267
+ if (kind === 'emitters')
268
+ return () => {
269
+ const l = this.particleLayers[index], c = l.config, u = l.material.uniforms;
270
+ l.orient.copy(emitterQuaternion(c));
271
+ u.uAxis.value.set(...c.direction).applyQuaternion(l.orient).normalize();
272
+ u.uOrient.value.setFromMatrix4(new T.Matrix4().makeRotationFromQuaternion(l.orient));
273
+ u.uStretch.value = c.stretch;
274
+ if (c.look.type === 'dot')
275
+ u.uSoft.value = c.look.softness;
276
+ if (c.look.type === 'star') {
277
+ u.uPoints.value = c.look.points;
278
+ u.uSharp.value = c.look.sharpness;
279
+ }
280
+ if (c.look.type === 'material' && l.compiled)
281
+ updateMaterialUniforms(l.compiled, c.look.material);
282
+ if (c.trail?.material && l.trail)
283
+ updateMaterialUniforms(l.trail.compiled, c.trail.material);
284
+ };
285
+ if (kind === 'meshes')
286
+ return () => {
287
+ const m = this.meshLayers[index], c = m.config;
288
+ m.mesh.position.set(...c.position);
289
+ m.mesh.rotation.set(c.rotation[0] * DEG, c.rotation[1] * DEG, c.rotation[2] * DEG, 'XYZ');
290
+ updateMaterialUniforms(m.compiled, c.material);
291
+ };
292
+ if (kind === 'lights')
293
+ return () => {
294
+ // With { lights: false } there is no light to refresh; the config still follows the track.
295
+ const l = this.lightLayers.find((x) => x.config === this.document.lights[index]);
296
+ if (l) {
297
+ l.light.position.set(...l.config.position);
298
+ l.light.color.set(l.config.color);
299
+ }
300
+ };
301
+ return () => {
302
+ const f = this.flipbookLayers[index], c = f.config, u = f.material.uniforms;
303
+ u.uTint.value.set(c.color);
304
+ u.uOpacity.value = c.opacity;
305
+ u.uOrigin.value.set(c.originU, c.originV);
306
+ };
307
+ }
308
+ /** Starts `clip` at effect time `start`: its windows, bursts and track times count from there. */
309
+ enter(clip, start) {
310
+ this.cur = clip;
311
+ this.clipStart = start;
312
+ for (const l of this.particleLayers) {
313
+ l.fraction = 0;
314
+ l.cycle = 0;
315
+ l.burstEmitted.fill(0);
316
+ }
317
+ for (const f of this.flipbookLayers)
318
+ f.done = !f.config.enabled;
319
+ }
320
+ /** Writes every track of the current clip at the clip's time. Fields no track of it names hold their last value. */
321
+ applyTracks(c = this.cur, at) {
322
+ if (c.bindings.length)
323
+ this.writeTracks(c, at);
324
+ this.applyBindings();
325
+ }
326
+ /** Parameters into their fields: after the tracks, so a bound field follows its parameter. */
327
+ applyBindings() {
328
+ if (!this.wires.length)
329
+ return;
330
+ const dirty = new Set();
331
+ for (const w of this.wires) {
332
+ const p = w.param;
333
+ const v = w.map ? sampleCurve(w.map, (p.value - p.min) / (p.max - p.min)) : p.value;
334
+ if (w.kind === 'number')
335
+ w.parent[w.key] = v;
336
+ else
337
+ w.parent[w.key].fill(v);
338
+ dirty.add(w.sync);
339
+ }
340
+ for (const f of dirty)
341
+ f();
342
+ }
343
+ writeTracks(c, at) {
344
+ const ct = at ?? this.clipTime, t = at !== undefined ? at : c.loop ? ct % c.duration : ct;
345
+ const dirty = new Set();
346
+ for (const b of c.bindings) {
347
+ const v = sampleTrack(b.sampled, t, trackScratch);
348
+ if (b.kind === 'number')
349
+ b.parent[b.key] = v[0];
350
+ else if (b.kind === 'bool')
351
+ b.parent[b.key] = v[0] > .5;
352
+ else if (b.kind === 'color')
353
+ b.parent[b.key] = linearToHex(v);
354
+ else {
355
+ const a = b.parent[b.key];
356
+ for (let i = 0; i < a.length; i++)
357
+ a[i] = v[i];
358
+ }
359
+ dirty.add(b.sync);
360
+ }
361
+ for (const f of dirty)
362
+ f();
363
+ }
364
+ /** A clip that ended hands over to its `next`, exactly at its end -- after landing on its own last values, as Godot does. */
365
+ advanceClip() {
366
+ while (this.stoppedAt === null && !this.cur.loop && this.cur.next && this.time - this.clipStart >= this.cur.duration - 1e-9) {
367
+ this.applyTracks(this.cur, this.cur.duration);
368
+ this.enter(this.clips.get(this.cur.next), this.clipStart + this.cur.duration);
369
+ }
370
+ }
371
+ /**
372
+ * Sets parameter `name` (clamped to its min-max) and carries it into its
373
+ * bindings at once. A track on the parameter in the clip playing writes it
374
+ * again on the next step -- the clip wins while it animates it, as in Godot.
375
+ */
376
+ set(name, value) {
377
+ const p = this.document.params?.find((x) => x.name === name);
378
+ if (!p)
379
+ throw new Error(`VfxInstance.set: no parameter "${name}" (this effect has ${this.paramNames.join(', ') || 'none'})`);
380
+ if (!Number.isFinite(value))
381
+ return;
382
+ p.value = Math.max(p.min, Math.min(p.max, value));
383
+ this.applyBindings();
384
+ this.draw();
385
+ }
386
+ /** A parameter's value now, or undefined when the effect has no such parameter. */
387
+ get(name) { return this.document.params?.find((x) => x.name === name)?.value; }
388
+ /** Every parameter this effect has. */
389
+ get paramNames() { return (this.document.params ?? []).map((p) => p.name); }
390
+ /** The clip playing now (`main` for an effect without clips). */
391
+ get clip() { return this.cur.name; }
392
+ /** Every clip this effect has, in document order. */
393
+ get clipNames() { return [...this.clips.keys()]; }
394
+ /** Seconds since the current clip began. */
395
+ get clipTime() { return Math.max(0, this.time - this.clipStart); }
396
+ /**
397
+ * Switches to clip `name` at once (Godot snaps, so do we): particles alive
398
+ * keep living, fields its tracks do not name keep their last value. Also
399
+ * undoes a `stop()`.
400
+ */
401
+ play(name) {
402
+ const c = this.clips.get(name);
403
+ if (!c)
404
+ throw new Error(`VfxInstance.play: no clip "${name}" (this effect has ${this.clipNames.join(', ')})`);
405
+ this.stoppedAt = null;
406
+ this.stopRequested = false;
407
+ this.enter(c, this.time);
408
+ this.applyTracks();
409
+ this.draw();
410
+ }
411
+ /**
412
+ * Jumps to `seconds` into `clip` (default: the current one), by replaying
413
+ * from `reset()` at the fixed step -- so the frame is exactly what
414
+ * `update()` would have reached. A clip reached from the start clip by
415
+ * `next` is played through its predecessors, so it starts with the values
416
+ * they leave (an `idle` after an `open`); any other clip starts from the
417
+ * document's own values.
418
+ */
419
+ seek(seconds, clip = this.cur.name) {
420
+ const target = this.clips.get(clip);
421
+ if (!target)
422
+ throw new Error(`VfxInstance.seek: no clip "${clip}" (this effect has ${this.clipNames.join(', ')})`);
423
+ this.reset();
424
+ let lead = 0, c = this.cur;
425
+ const seen = new Set();
426
+ while (c !== target && c.next && !seen.has(c)) {
427
+ seen.add(c);
428
+ lead += c.duration;
429
+ c = this.clips.get(c.next);
430
+ }
431
+ if (c !== target) {
432
+ lead = 0;
433
+ this.enter(target, 0);
434
+ this.applyTracks();
435
+ }
436
+ const steps = Math.round(Math.max(0, Math.min(60, lead + seconds)) * 60);
437
+ for (let i = 0; i < steps; i++)
438
+ this.step(1 / 60);
200
439
  this.draw();
201
440
  }
202
441
  buildParticles(config, index, root, textureOf) {
@@ -216,7 +455,7 @@ export class VfxInstance {
216
455
  const texture = !solid && (look.type === 'texture' || look.type === 'sheet') ? textureOf(look.texture) : undefined;
217
456
  const images = texture || (!solid && (look.type === 'texture' || look.type === 'sheet')) ? [texture] : [];
218
457
  // A mesh particle always draws through a material: its look's, or a solid one.
219
- const compiled = look.type === 'material' ? compileMaterial(look.material) : solid ? compileMaterial({ ...materialDefaults(), masks: [] }) : undefined;
458
+ const compiled = look.type === 'material' ? compileMaterial(look.material, this.liveOf(`emitters.${config.id}.look.material`)) : solid ? compileMaterial({ ...materialDefaults(), masks: [] }) : undefined;
220
459
  const repeats = [];
221
460
  if (compiled)
222
461
  bindImages(compiled, textureOf, images, repeats);
@@ -254,7 +493,7 @@ export class VfxInstance {
254
493
  buildTrail(config, index, textureOf) {
255
494
  const t = config.trail;
256
495
  // Default: the particle's colour, fading from the particle to the tail (u runs head -> tail).
257
- const compiled = compileMaterial(t.material ?? { ...materialDefaults(), masks: [{ ...maskDefaults({ type: 'gradient', fill: 'linear', center: [.5, .5], width: .25 }), invert: true }], softness: 1, ramp: 'linear' });
496
+ const compiled = compileMaterial(t.material ?? { ...materialDefaults(), masks: [{ ...maskDefaults({ type: 'gradient', fill: 'linear', center: [.5, .5], width: .25 }), invert: true }], softness: 1, ramp: 'linear' }, this.liveOf(`emitters.${config.id}.trail.material`));
258
497
  const images = [], repeats = [];
259
498
  bindImages(compiled, textureOf, images, repeats);
260
499
  const material = new T.ShaderMaterial({
@@ -287,7 +526,7 @@ export class VfxInstance {
287
526
  }
288
527
  buildMesh(config, index, textureOf) {
289
528
  const geometry = fixRingUv(meshGeometry(config.shape), config.shape);
290
- const compiled = compileMaterial(config.material);
529
+ const compiled = compileMaterial(config.material, this.liveOf(`meshes.${config.id}.material`));
291
530
  const images = [], repeats = [];
292
531
  bindImages(compiled, textureOf, images, repeats);
293
532
  const s = config.shape;
@@ -317,25 +556,25 @@ export class VfxInstance {
317
556
  meshLife(c) {
318
557
  if (!c.enabled)
319
558
  return -1;
320
- const d = this.document.duration, life = c.life ?? Math.max(.01, d - c.start);
559
+ const clip = this.cur, d = clip.duration, ct = this.clipTime, life = c.life ?? Math.max(.01, d - c.start);
321
560
  if (this.stoppedAt !== null) {
322
561
  // Stopped: a whole-cycle layer goes out; a window that had begun plays out; nothing new begins.
323
562
  if (c.life === null)
324
563
  return -1;
325
- const base = this.document.loop ? Math.floor(this.stoppedAt / d) * d : 0;
564
+ const base = clip.loop ? Math.floor(this.stoppedAt / d) * d : 0;
326
565
  for (const begin of [base + c.start, base - d + c.start]) {
327
566
  if (begin > this.stoppedAt || (begin < 0))
328
567
  continue;
329
- const t = (this.time - begin) / life;
568
+ const t = (ct - begin) / life;
330
569
  if (t >= 0 && t < 1)
331
570
  return t;
332
571
  }
333
572
  return -1;
334
573
  }
335
- const cycleTime = this.document.loop ? this.time % d : this.time;
574
+ const cycleTime = clip.loop ? ct % d : ct;
336
575
  let t = (cycleTime - c.start) / life;
337
576
  // A looping layer that outlives its cycle carries over into the next one.
338
- if (this.document.loop && t < 0 && this.time >= d)
577
+ if (clip.loop && t < 0 && ct >= d)
339
578
  t = (cycleTime + d - c.start) / life;
340
579
  return t >= 0 && t < 1 ? t : -1;
341
580
  }
@@ -367,25 +606,43 @@ export class VfxInstance {
367
606
  * so a looping status effect can be ended and then disposed. Works on every
368
607
  * format version; `reset()` undoes it.
369
608
  */
370
- stop() { if (this.stoppedAt === null)
371
- this.stoppedAt = this.time; }
372
- /** True after `stop()`, until `reset()`. */
373
- get stopped() { return this.stoppedAt !== null; }
609
+ stop() {
610
+ if (this.stopRequested)
611
+ return;
612
+ this.stopRequested = true;
613
+ // An author's outro (ADR-056): a clip named `close` is how an effect asks to end its own way.
614
+ const close = this.clips.get('close');
615
+ if (close) {
616
+ if (this.cur !== close) {
617
+ this.enter(close, this.time);
618
+ this.applyTracks();
619
+ }
620
+ return;
621
+ }
622
+ this.stoppedAt = this.clipTime;
623
+ }
624
+ /** True after `stop()`, until `reset()` or `play()`. */
625
+ get stopped() { return this.stopRequested; }
374
626
  reset() {
375
627
  this.stoppedAt = null;
628
+ this.stopRequested = false;
376
629
  this.time = 0;
377
630
  this.accumulator = 0;
378
631
  this.state = this.document.seed;
379
632
  this.live = 0;
380
633
  this.serial = 0;
381
- for (const l of this.particleLayers) {
634
+ for (const l of this.particleLayers)
382
635
  l.particles = [];
383
- l.fraction = 0;
384
- l.cycle = 0;
385
- l.burstEmitted.fill(0);
636
+ const dirty = new Set();
637
+ for (const r of this.restores) {
638
+ r.parent[r.key] = structuredClone(r.base);
639
+ dirty.add(r.sync);
386
640
  }
387
- for (const f of this.flipbookLayers)
388
- f.done = !f.config.enabled;
641
+ (this.document.params ?? []).forEach((p, i) => { p.value = this.paramDefaults[i]; });
642
+ for (const f of dirty)
643
+ f();
644
+ this.enter(this.startClip, 0);
645
+ this.applyTracks();
389
646
  this.draw();
390
647
  }
391
648
  get particleCount() { return this.live; }
@@ -400,9 +657,10 @@ export class VfxInstance {
400
657
  const quiet = this.meshLayers.every(({ config }) => this.meshLife(config) < 0) && this.lightLayers.every(({ config }) => this.meshLife(config) < 0);
401
658
  return this.live === 0 && quiet && this.flipbookLayers.every((f) => f.done);
402
659
  }
403
- if (this.document.loop || this.time < this.document.duration)
660
+ const clip = this.cur, ct = this.clipTime;
661
+ if (clip.loop || clip.next || ct < clip.duration)
404
662
  return false;
405
- const over = (c) => !c.enabled || this.time >= c.start + (c.life ?? Math.max(.01, this.document.duration - c.start));
663
+ const over = (c) => !c.enabled || ct >= c.start + (c.life ?? Math.max(.01, clip.duration - c.start));
406
664
  const meshesDone = this.meshLayers.every(({ config }) => over(config)) && this.lightLayers.every(({ config }) => over(config));
407
665
  return this.live === 0 && meshesDone && this.flipbookLayers.every((f) => f.done);
408
666
  }
@@ -420,7 +678,7 @@ export class VfxInstance {
420
678
  this.draw();
421
679
  }
422
680
  /** Whether the effect is still starting new particles / new flipbook cycles. */
423
- get running() { return this.stoppedAt === null && (this.document.loop || this.time < this.document.duration); }
681
+ get running() { return this.stoppedAt === null && (this.cur.loop || this.clipTime < this.cur.duration); }
424
682
  /** The emitter's origin in its own simulation space. */
425
683
  origin(layer, out) {
426
684
  if (layer.config.space === 'world')
@@ -428,9 +686,9 @@ export class VfxInstance {
428
686
  return out.set(0, 0, 0);
429
687
  }
430
688
  step(dt) {
431
- const running = this.running;
432
- const cycleTime = this.document.loop ? this.time % this.document.duration : this.time;
433
- const cycle = this.document.loop ? Math.floor(this.time / this.document.duration) : 0;
689
+ const running = this.running, clip = this.cur, ct = this.clipTime;
690
+ const cycleTime = clip.loop ? ct % clip.duration : ct;
691
+ const cycle = clip.loop ? Math.floor(ct / clip.duration) : 0;
434
692
  this.time += dt;
435
693
  this.root.updateWorldMatrix(true, false);
436
694
  const origin = new T.Vector3();
@@ -483,6 +741,8 @@ export class VfxInstance {
483
741
  }
484
742
  });
485
743
  }
744
+ this.advanceClip();
745
+ this.applyTracks();
486
746
  }
487
747
  move(c, p, dt, origin) {
488
748
  const t = p.age / p.life;
@@ -695,7 +955,7 @@ export class VfxInstance {
695
955
  * cycling while the effect runs and, once it stops, finishes its current
696
956
  * cycle -- the flipbook counterpart of particles draining. */
697
957
  frameOf(f) {
698
- const t = this.time - f.delay;
958
+ const t = this.clipTime - f.delay;
699
959
  if (!f.enabled || t < 0)
700
960
  return -1;
701
961
  const n = Math.floor(t * f.fps);
@@ -704,7 +964,8 @@ export class VfxInstance {
704
964
  if (this.running)
705
965
  return n % f.frames;
706
966
  // Stopped: the cycle that was playing when the effect stopped may finish.
707
- const end = this.document.loop ? (this.stoppedAt ?? this.document.duration) : Math.min(this.stoppedAt ?? Infinity, this.document.duration);
967
+ const clip = this.cur;
968
+ const end = clip.loop ? (this.stoppedAt ?? clip.duration) : Math.min(this.stoppedAt ?? Infinity, clip.duration);
708
969
  const stoppedAt = Math.floor(Math.max(0, end - f.delay) * f.fps);
709
970
  const cycleEnd = (Math.floor(stoppedAt / f.frames) + 1) * f.frames;
710
971
  return n < cycleEnd ? n % f.frames : -1;
@@ -808,7 +1069,7 @@ export class VfxInstance {
808
1069
  }
809
1070
  for (const f of this.flipbookLayers) {
810
1071
  const frame = this.frameOf(f.config);
811
- if (frame < 0 && this.time >= f.config.delay)
1072
+ if (frame < 0 && this.clipTime >= f.config.delay)
812
1073
  f.done = true;
813
1074
  if (frame >= 0)
814
1075
  f.done = false;
@@ -15,6 +15,12 @@
15
15
  * Version 2. A version-1 document (the upward-firing disc emitter of 1.35) is
16
16
  * still accepted: `parseVfx` upgrades it to the v2 emitter that plays the same.
17
17
  *
18
+ * Version 8 (1.43) adds PARAMETERS and BINDINGS (`params`, `bindings`, ADR-056
19
+ * step 4): named numbers a game sets, carried into the layers.
20
+ *
21
+ * Version 7 (1.42) adds TRACKS and CLIPS (`tracks`, `clips`, `startClip`,
22
+ * ADR-056 step 2): keyframes on a layer's numbers, and named states.
23
+ *
18
24
  * Version 6 (1.40) adds TRAILS (`emitter.trail`, ADR-055 step 4).
19
25
  *
20
26
  * Version 5 (1.39) adds LIGHTS (`lights`, point lights, ADR-055 step 3).
@@ -30,6 +36,7 @@
30
36
  import { type Material } from './material.js';
31
37
  import { type MeshShape, type MeshLayer } from './mesh.js';
32
38
  import { type Trail } from './trail.js';
39
+ import { type Track, type Clip, type Param, type ParamBinding } from './timeline.js';
33
40
  /** A number, or `[min, max]`: picked uniformly per particle. */
34
41
  export type Range = number | [number, number];
35
42
  export type Vec3 = [number, number, number];
@@ -236,7 +243,7 @@ export interface Flipbook {
236
243
  blend: 'normal' | 'additive';
237
244
  }
238
245
  export interface VfxDocument {
239
- version: 2 | 3 | 4 | 5 | 6;
246
+ version: 2 | 3 | 4 | 5 | 6 | 7 | 8;
240
247
  name: string;
241
248
  seed: number;
242
249
  /** Seconds in one cycle. A looping effect repeats it; a one-shot stops emitting after it. */
@@ -249,6 +256,20 @@ export interface VfxDocument {
249
256
  meshes?: MeshLayer[];
250
257
  /** (version 5) Point lights: the flash of a muzzle, the glow a fire throws on the ground. At most 2. */
251
258
  lights?: LightLayer[];
259
+ /** (version 7) Keyframes over the one cycle (`duration`, `loop`) of an effect without clips: the clip named `main`. */
260
+ tracks?: Track[];
261
+ /**
262
+ * (version 7) Named states, each a cycle of its own (open -> idle -> close).
263
+ * With clips, the top-level `duration` / `loop` are not played; `stop()`
264
+ * plays the clip named `close` when there is one.
265
+ */
266
+ clips?: Clip[];
267
+ /** (version 7) The clip that plays first, and after `reset()`. Default: the first. */
268
+ startClip?: string;
269
+ /** (version 8) Named numbers a game can set and tracks can animate. */
270
+ params?: Param[];
271
+ /** (version 8) A parameter written into a layer's number or vector, optionally through a curve. */
272
+ bindings?: ParamBinding[];
252
273
  }
253
274
  /**
254
275
  * A point light, created once with the effect and dimmed to 0 when it is off
@@ -377,11 +398,13 @@ export declare function sampleGradient(g: Gradient, t: number, out?: number[]):
377
398
  */
378
399
  export declare function parseVfx(value: unknown): VfxDocument;
379
400
  /**
380
- * The lowest format version that can express this document: 3 when any
381
- * emitter uses the material look, else 2. The editor and the agent write
382
- * this, so an effect that needs nothing new still plays on 1.36.
401
+ * The lowest format version that can express this document: 8 with
402
+ * parameters or bindings, 7 with tracks
403
+ * or clips, 6 with trails, 5 with lights, 4 with meshes, 3 with the material
404
+ * look, else 2. The editor and the agent write this, so an effect that needs
405
+ * nothing new still plays on an older SDK.
383
406
  */
384
- export declare function minimumVersion(d: Pick<VfxDocument, 'emitters' | 'meshes' | 'lights'>): 2 | 3 | 4 | 5 | 6;
407
+ export declare function minimumVersion(d: Pick<VfxDocument, 'emitters' | 'meshes' | 'lights'> & Partial<Pick<VfxDocument, 'tracks' | 'clips' | 'startClip' | 'params' | 'bindings'>>): 2 | 3 | 4 | 5 | 6 | 7 | 8;
385
408
  /** A new mesh layer: a soft additive ring on the ground, for the editor's "Add" and the agent. */
386
409
  export declare function meshLayerDefaults(): Omit<MeshLayer, 'id'>;
387
410
  /** A new light: a warm glow just above the origin, lit for the whole cycle. */