@umicat/three-sdk 1.39.0 → 1.41.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,6 +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
77
  ```
77
78
 
78
79
  An effect has two kinds of layer. **Emitters** are particle systems modelled
@@ -119,7 +120,20 @@ every lit material in the scene; `new VfxInstance(doc, { lights: false })` or
119
120
  scales everything: world-space particles take it in speed and size, and a
120
121
  light's range follows it.
121
122
 
122
- **Write the lowest version.** `minimumVersion(doc)` is 5 with lights, 4 with meshes, 3 with a
123
+ **Trails (version 6, 1.40.0, ADR-055 step 4).** `emitter.trail: { length,
124
+ width, widthOverTrail?, material? }`: each particle keeps up to 16 points of
125
+ where it has been and draws a ribbon turned to the viewer in the vertex
126
+ shader (no camera needed). u runs from the particle (0) to the tail end (1);
127
+ without a material the trail takes the particle's colour and fades out. At
128
+ most 8000 trail points per effect, checked at parse.
129
+
130
+ **`stop()` (1.41.0, ADR-056).** Ends an effect the way it was meant to end:
131
+ emission stops, particles alive finish their lives, a looping sprite sheet
132
+ finishes its cycle, a mesh layer or light with a window plays it out and a
133
+ whole-cycle one goes out; then `finished` turns true. Works on every format
134
+ version, which is how a game ends a looping effect.
135
+
136
+ **Write the lowest version.** `minimumVersion(doc)` is 6 with trails, 5 with lights, 4 with meshes, 3 with a
123
137
  material, else 2; the editor and the agent write that, so an effect that needs nothing
124
138
  new stays version 2 and keeps playing on 1.36.
125
139
 
@@ -33,12 +33,15 @@ 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. */
37
+ private stoppedAt;
36
38
  /** Particles born so far: hashed into each particle's `seed`. */
37
39
  private serial;
38
40
  private accumulator;
39
41
  private live;
40
42
  constructor(document: VfxDocument, options?: VfxInstanceOptions);
41
43
  private buildParticles;
44
+ private buildTrail;
42
45
  /** (Re)creates the per-instance buffers with room for `capacity` particles. */
43
46
  private allocate;
44
47
  private buildMesh;
@@ -47,6 +50,17 @@ export declare class VfxInstance {
47
50
  private buildFlipbook;
48
51
  private random;
49
52
  /** Back to time 0 with the original seed: a replay is identical to the first play. */
53
+ /**
54
+ * End the effect the way it was meant to end (ADR-056): emission stops,
55
+ * particles already alive finish their lives, a looping sprite sheet
56
+ * finishes its cycle, a mesh layer or light with a window plays it out, and
57
+ * whole-cycle ones go out. `finished` turns true once all of that is done --
58
+ * so a looping status effect can be ended and then disposed. Works on every
59
+ * format version; `reset()` undoes it.
60
+ */
61
+ stop(): void;
62
+ /** True after `stop()`, until `reset()`. */
63
+ get stopped(): boolean;
50
64
  reset(): void;
51
65
  get particleCount(): number;
52
66
  /** The point lights this instance made (empty with `{ lights: false }`). Never changes after construction. */
@@ -68,6 +82,8 @@ export declare class VfxInstance {
68
82
  /** A new particle on `layer`, from its own emission shape -- around a parent particle when `at` is given. */
69
83
  private spawn;
70
84
  private spawnChildren;
85
+ /** Rebuilds an emitter's ribbons: each particle's position, then its history, newest first. */
86
+ private drawTrail;
71
87
  /** The frame a flipbook shows now, or -1 for none. A looping flipbook keeps
72
88
  * cycling while the effect runs and, once it stops, finishes its current
73
89
  * cycle -- the flipbook counterpart of particles draining. */
@@ -1,6 +1,7 @@
1
1
  import * as T from 'three';
2
2
  import { parseVfx, pickRange, sampleCurve, sampleGradient, LIMITS, } from './document.js';
3
- import { compileMaterial, materialDefaults } from './material.js';
3
+ import { compileMaterial, materialDefaults, maskDefaults } from './material.js';
4
+ import { TrailMesh, trailSampling, trailVertex, newHistory, pushHistory, historyAt } from './trail.js';
4
5
  import { meshGeometry, fixRingUv, meshLayerVertex, meshParticleVertex, meshFragment } from './mesh.js';
5
6
  /** Closed shapes are drawn front-only, so an additive sphere does not show its back through its front. */
6
7
  const closed = (s) => s.type === 'sphere' || s.type === 'box' || s.type === 'torus' || (s.type === 'cylinder' && s.caps);
@@ -168,6 +169,8 @@ export class VfxInstance {
168
169
  this.meshLayers = [];
169
170
  this.lightLayers = [];
170
171
  this.state = 1;
172
+ /** Effect time when `stop()` was called, or null. */
173
+ this.stoppedAt = null;
171
174
  /** Particles born so far: hashed into each particle's `seed`. */
172
175
  this.serial = 0;
173
176
  this.accumulator = 0;
@@ -239,14 +242,36 @@ export class VfxInstance {
239
242
  if (config.space === 'world')
240
243
  mesh.matrixAutoUpdate = false;
241
244
  this.root.add(mesh);
245
+ const trail = config.trail ? this.buildTrail(config, index, textureOf) : undefined;
242
246
  const layer = {
243
247
  config, index, particles: [], root, fraction: 0, cycle: 0, burstEmitted: config.bursts.map(() => 0),
244
248
  orient: emitterQuaternion(config), mesh, geometry, material, capacity: 0, attributes: undefined,
245
- images, compiled, repeats,
249
+ images, compiled, repeats, trail,
246
250
  };
247
251
  this.allocate(layer, 64);
248
252
  return layer;
249
253
  }
254
+ buildTrail(config, index, textureOf) {
255
+ const t = config.trail;
256
+ // 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' });
258
+ const images = [], repeats = [];
259
+ bindImages(compiled, textureOf, images, repeats);
260
+ const material = new T.ShaderMaterial({
261
+ transparent: true, depthWrite: false, side: T.DoubleSide,
262
+ blending: config.blend === 'additive' ? T.AdditiveBlending : T.NormalBlending,
263
+ uniforms: { ...compiled.uniforms }, vertexShader: trailVertex(compiled), fragmentShader: meshFragment(compiled),
264
+ });
265
+ const { points, interval } = trailSampling(t);
266
+ const mesh = new TrailMesh(material, points);
267
+ // Under its particles, which are the bright heads of the streaks.
268
+ mesh.mesh.name = config.id + ':trail';
269
+ mesh.mesh.renderOrder = index - .5;
270
+ if (config.space === 'world')
271
+ mesh.mesh.matrixAutoUpdate = false;
272
+ this.root.add(mesh.mesh);
273
+ return { mesh, compiled, points, interval, images, repeats };
274
+ }
250
275
  /** (Re)creates the per-instance buffers with room for `capacity` particles. */
251
276
  allocate(layer, capacity) {
252
277
  const make = (size) => new T.InstancedBufferAttribute(new Float32Array(capacity * size), size).setUsage(T.DynamicDrawUsage);
@@ -293,6 +318,20 @@ export class VfxInstance {
293
318
  if (!c.enabled)
294
319
  return -1;
295
320
  const d = this.document.duration, life = c.life ?? Math.max(.01, d - c.start);
321
+ if (this.stoppedAt !== null) {
322
+ // Stopped: a whole-cycle layer goes out; a window that had begun plays out; nothing new begins.
323
+ if (c.life === null)
324
+ return -1;
325
+ const base = this.document.loop ? Math.floor(this.stoppedAt / d) * d : 0;
326
+ for (const begin of [base + c.start, base - d + c.start]) {
327
+ if (begin > this.stoppedAt || (begin < 0))
328
+ continue;
329
+ const t = (this.time - begin) / life;
330
+ if (t >= 0 && t < 1)
331
+ return t;
332
+ }
333
+ return -1;
334
+ }
296
335
  const cycleTime = this.document.loop ? this.time % d : this.time;
297
336
  let t = (cycleTime - c.start) / life;
298
337
  // A looping layer that outlives its cycle carries over into the next one.
@@ -320,7 +359,20 @@ export class VfxInstance {
320
359
  }
321
360
  random() { this.state = this.state * 16807 % 2147483647; return (this.state - 1) / 2147483646; }
322
361
  /** Back to time 0 with the original seed: a replay is identical to the first play. */
362
+ /**
363
+ * End the effect the way it was meant to end (ADR-056): emission stops,
364
+ * particles already alive finish their lives, a looping sprite sheet
365
+ * finishes its cycle, a mesh layer or light with a window plays it out, and
366
+ * whole-cycle ones go out. `finished` turns true once all of that is done --
367
+ * so a looping status effect can be ended and then disposed. Works on every
368
+ * format version; `reset()` undoes it.
369
+ */
370
+ stop() { if (this.stoppedAt === null)
371
+ this.stoppedAt = this.time; }
372
+ /** True after `stop()`, until `reset()`. */
373
+ get stopped() { return this.stoppedAt !== null; }
323
374
  reset() {
375
+ this.stoppedAt = null;
324
376
  this.time = 0;
325
377
  this.accumulator = 0;
326
378
  this.state = this.document.seed;
@@ -343,6 +395,11 @@ export class VfxInstance {
343
395
  * died and every flipbook has played out -- the moment to `dispose()` a
344
396
  * one-shot. Always false for a looping effect. */
345
397
  get finished() {
398
+ if (this.stoppedAt !== null) {
399
+ // After stop(): no layer begins again, so done = nothing showing now.
400
+ const quiet = this.meshLayers.every(({ config }) => this.meshLife(config) < 0) && this.lightLayers.every(({ config }) => this.meshLife(config) < 0);
401
+ return this.live === 0 && quiet && this.flipbookLayers.every((f) => f.done);
402
+ }
346
403
  if (this.document.loop || this.time < this.document.duration)
347
404
  return false;
348
405
  const over = (c) => !c.enabled || this.time >= c.start + (c.life ?? Math.max(.01, this.document.duration - c.start));
@@ -363,7 +420,7 @@ export class VfxInstance {
363
420
  this.draw();
364
421
  }
365
422
  /** Whether the effect is still starting new particles / new flipbook cycles. */
366
- get running() { return this.document.loop || this.time < this.document.duration; }
423
+ get running() { return this.stoppedAt === null && (this.document.loop || this.time < this.document.duration); }
367
424
  /** The emitter's origin in its own simulation space. */
368
425
  origin(layer, out) {
369
426
  if (layer.config.space === 'world')
@@ -389,6 +446,13 @@ export class VfxInstance {
389
446
  continue;
390
447
  }
391
448
  this.move(c, p, dt, origin);
449
+ if (p.history && l.trail) {
450
+ p.history.acc += dt;
451
+ while (p.history.acc >= l.trail.interval - 1e-9) {
452
+ p.history.acc -= l.trail.interval;
453
+ pushHistory(p.history, p.x, p.y, p.z, l.trail.points);
454
+ }
455
+ }
392
456
  this.spawnChildren(l, p, 'life', dt);
393
457
  kept.push(p);
394
458
  }
@@ -553,6 +617,10 @@ export class VfxInstance {
553
617
  tangentialAccel: pickRange(c.tangentialAccel, r()), orbit: pickRange(c.orbit, r()), damping: pickRange(c.damping, r()),
554
618
  owed: c.children.map(() => 0),
555
619
  };
620
+ if (layer.trail) {
621
+ particle.history = newHistory(layer.trail.points);
622
+ pushHistory(particle.history, x, y, z, layer.trail.points);
623
+ }
556
624
  layer.particles.push(particle);
557
625
  this.live++;
558
626
  this.spawnChildren(layer, particle, 'birth', 0);
@@ -592,6 +660,37 @@ export class VfxInstance {
592
660
  this.spawn(child, { x, y, z, vx, vy, vz });
593
661
  });
594
662
  }
663
+ /** Rebuilds an emitter's ribbons: each particle's position, then its history, newest first. */
664
+ drawTrail(l, C) {
665
+ const tr = l.trail, cfg = l.config.trail, n = l.particles.length;
666
+ tr.mesh.grow(n);
667
+ const pts = trailScratch(tr.points), rgba = [0, 0, 0, 0];
668
+ const width = (u) => cfg.width * (cfg.widthOverTrail ? Math.max(0, sampleCurve(cfg.widthOverTrail, u)) : 1 - u);
669
+ for (let i = 0; i < n; i++) {
670
+ const p = l.particles[i], h = p.history;
671
+ pts[0][0] = p.x;
672
+ pts[0][1] = p.y;
673
+ pts[0][2] = p.z;
674
+ // The newest stored point can be the particle's own spot (it was just pushed): skip it then.
675
+ let k = 0, count = 1;
676
+ historyAt(h, 0, tr.points, pts[1]);
677
+ if (h.count && Math.hypot(pts[1][0] - p.x, pts[1][1] - p.y, pts[1][2] - p.z) < 1e-7)
678
+ k = 1;
679
+ for (; k < h.count && count < tr.points; k++, count++)
680
+ historyAt(h, k, tr.points, pts[count]);
681
+ rgba[0] = C[i * 4];
682
+ rgba[1] = C[i * 4 + 1];
683
+ rgba[2] = C[i * 4 + 2];
684
+ rgba[3] = C[i * 4 + 3];
685
+ tr.mesh.write(i, pts, count, rgba, width, p.age / p.life, p.seed);
686
+ }
687
+ tr.mesh.commit(n);
688
+ tr.compiled.uniforms.uTime.value = this.time;
689
+ syncRepeats(tr.repeats);
690
+ if (l.config.space === 'world')
691
+ tr.mesh.mesh.matrix.copy(this.root.matrixWorld).invert();
692
+ tr.mesh.mesh.visible = n > 0 && tr.images.every((x) => !!x?.image?.width);
693
+ }
595
694
  /** The frame a flipbook shows now, or -1 for none. A looping flipbook keeps
596
695
  * cycling while the effect runs and, once it stops, finishes its current
597
696
  * cycle -- the flipbook counterpart of particles draining. */
@@ -605,7 +704,8 @@ export class VfxInstance {
605
704
  if (this.running)
606
705
  return n % f.frames;
607
706
  // Stopped: the cycle that was playing when the effect stopped may finish.
608
- const stoppedAt = Math.floor(Math.max(0, this.document.duration - f.delay) * f.fps);
707
+ const end = this.document.loop ? (this.stoppedAt ?? this.document.duration) : Math.min(this.stoppedAt ?? Infinity, this.document.duration);
708
+ const stoppedAt = Math.floor(Math.max(0, end - f.delay) * f.fps);
609
709
  const cycleEnd = (Math.floor(stoppedAt / f.frames) + 1) * f.frames;
610
710
  return n < cycleEnd ? n % f.frames : -1;
611
711
  }
@@ -652,6 +752,8 @@ export class VfxInstance {
652
752
  A[i * 3 + 2] = xyz?.z ? sampleCurve(xyz.z, t) : 1;
653
753
  M[i * 4 + 2] = look.type !== 'sheet' ? 0 : look.fps === 'life' ? Math.min(look.frames - 1, Math.floor(t * look.frames)) : Math.floor(p.age * look.fps) % look.frames;
654
754
  }
755
+ if (l.trail)
756
+ this.drawTrail(l, C);
655
757
  l.geometry.instanceCount = n;
656
758
  for (const attribute of [pos, color, misc, vel, life, axes])
657
759
  attribute.needsUpdate = true;
@@ -732,6 +834,13 @@ export class VfxInstance {
732
834
  l.compiled?.dispose();
733
835
  for (const r of l.repeats)
734
836
  r.copy.dispose();
837
+ if (l.trail) {
838
+ l.trail.mesh.dispose();
839
+ (l.trail.mesh.material).dispose();
840
+ l.trail.compiled.dispose();
841
+ for (const r of l.trail.repeats)
842
+ r.copy.dispose();
843
+ }
735
844
  }
736
845
  for (const f of this.flipbookLayers)
737
846
  f.material.dispose();
@@ -772,6 +881,15 @@ function bindImages(compiled, textureOf, images, repeats) {
772
881
  compiled.uniforms[`uMask${i}`].value = copy;
773
882
  }
774
883
  }
884
+ const trailScratches = new Map();
885
+ function trailScratch(points) {
886
+ let s = trailScratches.get(points);
887
+ if (!s) {
888
+ s = Array.from({ length: points }, () => [0, 0, 0]);
889
+ trailScratches.set(points, s);
890
+ }
891
+ return s;
892
+ }
775
893
  /** A copy made before its image decoded never uploads on its own: follow the source's version. */
776
894
  function syncRepeats(repeats) {
777
895
  for (const r of repeats)
@@ -15,6 +15,8 @@
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 6 (1.40) adds TRAILS (`emitter.trail`, ADR-055 step 4).
19
+ *
18
20
  * Version 5 (1.39) adds LIGHTS (`lights`, point lights, ADR-055 step 3).
19
21
  *
20
22
  * Version 4 (1.38) adds MESHES: mesh layers (`meshes`) and mesh-shaped
@@ -27,6 +29,7 @@
27
29
  */
28
30
  import { type Material } from './material.js';
29
31
  import { type MeshShape, type MeshLayer } from './mesh.js';
32
+ import { type Trail } from './trail.js';
30
33
  /** A number, or `[min, max]`: picked uniformly per particle. */
31
34
  export type Range = number | [number, number];
32
35
  export type Vec3 = [number, number, number];
@@ -204,6 +207,8 @@ export interface Emitter {
204
207
  * `angle` about that line.
205
208
  */
206
209
  mesh?: MeshShape;
210
+ /** (version 6) A ribbon through where each particle has been: sparks, shrapnel, comet tails. */
211
+ trail?: Trail;
207
212
  }
208
213
  export interface Flipbook {
209
214
  id: string;
@@ -231,7 +236,7 @@ export interface Flipbook {
231
236
  blend: 'normal' | 'additive';
232
237
  }
233
238
  export interface VfxDocument {
234
- version: 2 | 3 | 4 | 5;
239
+ version: 2 | 3 | 4 | 5 | 6;
235
240
  name: string;
236
241
  seed: number;
237
242
  /** Seconds in one cycle. A looping effect repeats it; a one-shot stops emitting after it. */
@@ -376,7 +381,7 @@ export declare function parseVfx(value: unknown): VfxDocument;
376
381
  * emitter uses the material look, else 2. The editor and the agent write
377
382
  * this, so an effect that needs nothing new still plays on 1.36.
378
383
  */
379
- export declare function minimumVersion(d: Pick<VfxDocument, 'emitters' | 'meshes' | 'lights'>): 2 | 3 | 4 | 5;
384
+ export declare function minimumVersion(d: Pick<VfxDocument, 'emitters' | 'meshes' | 'lights'>): 2 | 3 | 4 | 5 | 6;
380
385
  /** A new mesh layer: a soft additive ring on the ground, for the editor's "Add" and the agent. */
381
386
  export declare function meshLayerDefaults(): Omit<MeshLayer, 'id'>;
382
387
  /** A new light: a warm glow just above the origin, lit for the whole cycle. */
@@ -389,6 +394,8 @@ export declare function meshLayer(id: string, patch?: Partial<MeshLayer>): MeshL
389
394
  * parent's count times what each parent particle spawns.
390
395
  */
391
396
  export declare function particleBudget(d: VfxDocument): number;
397
+ /** The most particles each emitter can have alive at once (see particleBudget), by id. */
398
+ export declare function particleBudgets(d: VfxDocument): Map<string, number>;
392
399
  /** An effect is a project ASSET named `<stem>.vfx.json`; the server keeps the
393
400
  * whole compound extension, so this suffix is what marks one. */
394
401
  export declare const VFX_SUFFIX = ".vfx.json";
@@ -15,6 +15,8 @@
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 6 (1.40) adds TRAILS (`emitter.trail`, ADR-055 step 4).
19
+ *
18
20
  * Version 5 (1.39) adds LIGHTS (`lights`, point lights, ADR-055 step 3).
19
21
  *
20
22
  * Version 4 (1.38) adds MESHES: mesh layers (`meshes`) and mesh-shaped
@@ -27,6 +29,7 @@
27
29
  */
28
30
  import { parseMaterial, materialTextures, materialDefaults } from './material.js';
29
31
  import { parseMeshShape } from './mesh.js';
32
+ import { trailSampling, TRAIL_POINT_BUDGET } from './trail.js';
30
33
  export const LIMITS = { emitters: 8, layers: 8, meshes: 8, lights: 2, particles: 4000, cells: 4096, bursts: 16, children: 4, curvePoints: 8, gradientStops: 16 };
31
34
  /** Every emitter field's value when a document leaves it out. */
32
35
  export function emitterDefaults() {
@@ -105,6 +108,8 @@ export function vfxTextures(document) {
105
108
  names.push(e.look.texture);
106
109
  else if (e.look.type === 'material')
107
110
  names.push(...materialTextures(e.look.material));
111
+ if (e.trail?.material)
112
+ names.push(...materialTextures(e.trail.material));
108
113
  }
109
114
  for (const m of document.meshes ?? [])
110
115
  names.push(...materialTextures(m.material));
@@ -184,8 +189,8 @@ export function parseVfx(value) {
184
189
  const d = structuredClone(value);
185
190
  const number = (v, min, max) => typeof v === 'number' && Number.isFinite(v) && v >= min && v <= max;
186
191
  const color = (v) => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v);
187
- if (![2, 3, 4, 5].includes(d.version))
188
- fail(`version must be 2, 3, 4 or 5 (or 1, which is upgraded)${typeof d.version === 'number' && d.version > 5 ? ` -- version ${d.version} was written by a newer editor: update @umicat/three-sdk` : ''}`);
192
+ if (![2, 3, 4, 5, 6].includes(d.version))
193
+ fail(`version must be 2-6 (or 1, which is upgraded)${typeof d.version === 'number' && d.version > 6 ? ` -- version ${d.version} was written by a newer editor: update @umicat/three-sdk` : ''}`);
189
194
  if (typeof d.name !== 'string' || !d.name.trim() || d.name.length > 80)
190
195
  fail('name must be 1-80 characters');
191
196
  if (!number(d.seed, 1, 2147483646) || !Number.isInteger(d.seed))
@@ -258,7 +263,7 @@ export function parseVfx(value) {
258
263
  fail(`${at} is not an object`);
259
264
  checkId(input.id, at);
260
265
  emitterIds.add(input.id);
261
- const known = new Set(['id', ...Object.keys(emitterDefaults()), ...CURVE_FIELDS, 'colorOverLife', 'mesh', 'sizeOverLifeXYZ']);
266
+ const known = new Set(['id', ...Object.keys(emitterDefaults()), ...CURVE_FIELDS, 'colorOverLife', 'mesh', 'sizeOverLifeXYZ', 'trail']);
262
267
  for (const key of Object.keys(input))
263
268
  if (!known.has(key))
264
269
  fail(`${at}.${key} is not an emitter field (a version-1 field? set "version": 1, or see emitterDefaults())`);
@@ -355,6 +360,25 @@ export function parseVfx(value) {
355
360
  fail(`${lat}.type must be dot, glow, star, texture, sheet or material`);
356
361
  if (!['camera', 'velocity', 'ground', 'axis'].includes(e.align))
357
362
  fail(`${at}.align must be "camera", "velocity", "ground" or "axis"`);
363
+ if (e.trail !== undefined) {
364
+ if (d.version < 6)
365
+ fail(`${at}.trail is version 6: set "version": 6 (needs @umicat/three-sdk 1.40 or later)`);
366
+ const tr = e.trail, tat = `${at}.trail`;
367
+ if (!tr || typeof tr !== 'object' || Array.isArray(tr))
368
+ fail(`${tat} must be { length, width, widthOverTrail?, material? }`);
369
+ for (const k of Object.keys(tr))
370
+ if (!['length', 'width', 'widthOverTrail', 'material'].includes(k))
371
+ fail(`${tat}.${k} is not a trail field (expected length, width, widthOverTrail, material)`);
372
+ e.trail = { ...{ length: .3, width: .1 }, ...tr };
373
+ if (!number(e.trail.length, .02, 10))
374
+ fail(`${tat}.length must be 0.02-10 seconds`);
375
+ if (!number(e.trail.width, 0, 50))
376
+ fail(`${tat}.width must be 0-50`);
377
+ if (e.trail.widthOverTrail !== undefined)
378
+ checkCurve(e.trail.widthOverTrail, `${tat}.widthOverTrail`);
379
+ if (e.trail.material !== undefined)
380
+ e.trail.material = parseMaterial(e.trail.material, `${tat}.material`, fail, { checkCurve, checkGradient, texturePattern: TEXTURE_PATTERN });
381
+ }
358
382
  if (e.sizeOverLifeXYZ !== undefined) {
359
383
  if (d.version < 4)
360
384
  fail(`${at}.sizeOverLifeXYZ is version 4: set "version": 4 (needs @umicat/three-sdk 1.38 or later)`);
@@ -409,6 +433,10 @@ export function parseVfx(value) {
409
433
  };
410
434
  for (const id of emitterIds)
411
435
  walk(id);
436
+ const budgets = particleBudgets(d);
437
+ const trailPoints = d.emitters.reduce((sum, e) => sum + (e.trail && e.enabled ? (budgets.get(e.id) ?? 0) * trailSampling(e.trail).points : 0), 0);
438
+ if (trailPoints > TRAIL_POINT_BUDGET)
439
+ fail(`too many trail points: up to ${Math.ceil(trailPoints)} (live particles with a trail x points per trail), the limit is ${TRAIL_POINT_BUDGET} -- shorten the trails or emit fewer`);
412
440
  const budget = particleBudget(d);
413
441
  if (budget > LIMITS.particles)
414
442
  fail(`too many live particles: the most this effect can have alive at once is about ${Math.ceil(budget)} (rate x lifetime + bursts, times sub-emitters), the limit is ${LIMITS.particles}`);
@@ -520,6 +548,8 @@ export function parseVfx(value) {
520
548
  * this, so an effect that needs nothing new still plays on 1.36.
521
549
  */
522
550
  export function minimumVersion(d) {
551
+ if (d.emitters.some((e) => e.trail !== undefined))
552
+ return 6;
523
553
  if (d.lights !== undefined)
524
554
  return 5;
525
555
  if (d.emitters.some((e) => e.mesh !== undefined || e.sizeOverLifeXYZ !== undefined) || d.meshes !== undefined)
@@ -546,6 +576,10 @@ export function meshLayer(id, patch = {}) { return { id, ...meshLayerDefaults(),
546
576
  * parent's count times what each parent particle spawns.
547
577
  */
548
578
  export function particleBudget(d) {
579
+ return [...particleBudgets(d).values()].reduce((s, n) => s + n, 0);
580
+ }
581
+ /** The most particles each emitter can have alive at once (see particleBudget), by id. */
582
+ export function particleBudgets(d) {
549
583
  const byId = new Map(d.emitters.map((e) => [e.id, e]));
550
584
  const isChild = new Set(d.emitters.flatMap((e) => e.children.map((c) => c.emitter)));
551
585
  const live = new Map();
@@ -566,7 +600,9 @@ export function particleBudget(d) {
566
600
  live.set(id, n);
567
601
  return n;
568
602
  };
569
- return d.emitters.reduce((s, e) => s + total(e.id), 0);
603
+ for (const e of d.emitters)
604
+ total(e.id);
605
+ return new Map(d.emitters.map((e) => [e.id, live.get(e.id) ?? 0]));
570
606
  }
571
607
  function checkV1(d, fail) {
572
608
  if (!Array.isArray(d.emitters))
@@ -3,6 +3,7 @@ export * from './templates.js';
3
3
  export { VfxInstance } from './VfxInstance.js';
4
4
  export * from './material.js';
5
5
  export * from './mesh.js';
6
+ export * from './trail.js';
6
7
  export type { VfxInstanceOptions, VfxTextureSource } from './VfxInstance.js';
7
8
  export { loadVfx, VfxEffect, siblingUrl, prepareSheetTexture } from './load.js';
8
9
  export type { LoadVfxOptions } from './load.js';
package/dist/vfx/index.js CHANGED
@@ -8,4 +8,5 @@ export * from './templates.js';
8
8
  export { VfxInstance } from './VfxInstance.js';
9
9
  export * from './material.js';
10
10
  export * from './mesh.js';
11
+ export * from './trail.js';
11
12
  export { loadVfx, VfxEffect, siblingUrl, prepareSheetTexture } from './load.js';
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Particle trails (format v6, umicat-design ADR-055 step 4): each particle
3
+ * remembers where it has been for `length` seconds and draws a camera-facing
4
+ * ribbon through those points. A ribbon, not Godot's TubeTrailMesh: from a
5
+ * game camera they read the same, and a ribbon is a quarter of the vertices.
6
+ *
7
+ * The ribbon is turned to the viewer in the VERTEX shader (each vertex knows
8
+ * its centre point, the trail's direction there and which side it is on), so
9
+ * the effect never needs to know where the camera is.
10
+ */
11
+ import * as T from 'three';
12
+ import type { CompiledMaterial, Material } from './material.js';
13
+ export interface Trail {
14
+ /** Seconds of the particle's past the trail covers. */
15
+ length: number;
16
+ /** World width at the head. */
17
+ width: number;
18
+ /** Width along the trail (t = 0 at the particle, 1 at the tail end). Default: tapers to nothing. */
19
+ widthOverTrail?: {
20
+ points: [number, number][];
21
+ smooth?: boolean;
22
+ };
23
+ /**
24
+ * How the ribbon is drawn; u runs along it (0 at the particle, 1 at the
25
+ * tail), v across. Default: the particle's colour, fading to the tail.
26
+ * Animated numbers follow the PARTICLE's life.
27
+ */
28
+ material?: Material;
29
+ }
30
+ /** Points per trail, at most: enough for a smooth curve, few enough for 4000 particles. */
31
+ export declare const TRAIL_SEGMENTS_MAX = 16;
32
+ /** Every trail point an effect can have alive at once, at most. */
33
+ export declare const TRAIL_POINT_BUDGET = 8000;
34
+ /** Points kept per trail, and the seconds between them. */
35
+ export declare function trailSampling(t: Trail): {
36
+ points: number;
37
+ interval: number;
38
+ };
39
+ /** Per-particle history: a ring of positions, newest last. */
40
+ export interface TrailHistory {
41
+ xyz: Float32Array;
42
+ count: number;
43
+ head: number;
44
+ acc: number;
45
+ }
46
+ export declare function newHistory(points: number): TrailHistory;
47
+ export declare function pushHistory(h: TrailHistory, x: number, y: number, z: number, points: number): void;
48
+ /** The k-th newest stored point (k = 0 is the newest). */
49
+ export declare function historyAt(h: TrailHistory, k: number, points: number, out: number[]): void;
50
+ export declare const trailVertex: (c: CompiledMaterial) => string;
51
+ /** One emitter's ribbons: a growable buffer rebuilt each frame. */
52
+ export declare class TrailMesh {
53
+ readonly material: T.ShaderMaterial;
54
+ readonly points: number;
55
+ readonly mesh: T.Mesh;
56
+ readonly geometry: T.BufferGeometry<T.NormalBufferAttributes, T.BufferGeometryEventMap>;
57
+ private capacity;
58
+ private attrs;
59
+ private index;
60
+ constructor(material: T.ShaderMaterial, points: number);
61
+ /** Room for `ribbons` trails of `points` points: 2 vertices a point, 2 triangles a segment. */
62
+ grow(ribbons: number): void;
63
+ /** Writes ribbon `r`: `pts` = its centre points head first (count <= points), the rest folded onto the last point. */
64
+ write(r: number, pts: number[][], count: number, rgba: number[], width: (u: number) => number, life: number, seed: number): void;
65
+ /** Draw the first `ribbons` written. */
66
+ commit(ribbons: number): void;
67
+ dispose(): void;
68
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Particle trails (format v6, umicat-design ADR-055 step 4): each particle
3
+ * remembers where it has been for `length` seconds and draws a camera-facing
4
+ * ribbon through those points. A ribbon, not Godot's TubeTrailMesh: from a
5
+ * game camera they read the same, and a ribbon is a quarter of the vertices.
6
+ *
7
+ * The ribbon is turned to the viewer in the VERTEX shader (each vertex knows
8
+ * its centre point, the trail's direction there and which side it is on), so
9
+ * the effect never needs to know where the camera is.
10
+ */
11
+ import * as T from 'three';
12
+ /** Points per trail, at most: enough for a smooth curve, few enough for 4000 particles. */
13
+ export const TRAIL_SEGMENTS_MAX = 16;
14
+ /** Every trail point an effect can have alive at once, at most. */
15
+ export const TRAIL_POINT_BUDGET = 8000;
16
+ /** Points kept per trail, and the seconds between them. */
17
+ export function trailSampling(t) {
18
+ const segments = Math.max(2, Math.min(TRAIL_SEGMENTS_MAX, Math.ceil(t.length * 60)));
19
+ return { points: segments + 1, interval: t.length / segments };
20
+ }
21
+ export function newHistory(points) { return { xyz: new Float32Array(points * 3), count: 0, head: 0, acc: 0 }; }
22
+ export function pushHistory(h, x, y, z, points) {
23
+ h.xyz[h.head * 3] = x;
24
+ h.xyz[h.head * 3 + 1] = y;
25
+ h.xyz[h.head * 3 + 2] = z;
26
+ h.head = (h.head + 1) % points;
27
+ h.count = Math.min(points, h.count + 1);
28
+ }
29
+ /** The k-th newest stored point (k = 0 is the newest). */
30
+ export function historyAt(h, k, points, out) {
31
+ const i = ((h.head - 1 - k) % points + points) % points;
32
+ out[0] = h.xyz[i * 3];
33
+ out[1] = h.xyz[i * 3 + 1];
34
+ out[2] = h.xyz[i * 3 + 2];
35
+ }
36
+ export const trailVertex = (c) => `
37
+ attribute vec3 tCenter; attribute vec3 tDir; attribute vec4 tColor; attribute vec4 tMisc; // misc: (side -1/+1, width, u, unused)
38
+ attribute vec2 tLife;
39
+ varying vec2 vUv; varying vec4 vColor; varying vec2 vLife; varying vec3 vN; varying vec3 vV;
40
+ ${c.code}
41
+ void main(){
42
+ vec4 cv = modelViewMatrix * vec4(tCenter, 1.0);
43
+ vec3 dv = (modelViewMatrix * vec4(tDir, 0.0)).xyz;
44
+ vec3 side = cross(dv, -cv.xyz);
45
+ float sl = length(side);
46
+ side = sl > 1e-8 ? side / sl : vec3(1.0, 0.0, 0.0);
47
+ float scale = length(modelMatrix[0].xyz);
48
+ cv.xyz += side * tMisc.x * tMisc.y * 0.5 * scale;
49
+ vUv = vec2(tMisc.z, tMisc.x * 0.5 + 0.5); vColor = tColor; vLife = tLife;
50
+ vV = -cv.xyz; vN = normalize(-cv.xyz);
51
+ gl_Position = projectionMatrix * cv;
52
+ }`;
53
+ /** One emitter's ribbons: a growable buffer rebuilt each frame. */
54
+ export class TrailMesh {
55
+ constructor(material, points) {
56
+ this.material = material;
57
+ this.points = points;
58
+ this.geometry = new T.BufferGeometry();
59
+ this.capacity = 0;
60
+ this.mesh = new T.Mesh(this.geometry, material);
61
+ this.mesh.frustumCulled = false;
62
+ this.grow(16);
63
+ }
64
+ /** Room for `ribbons` trails of `points` points: 2 vertices a point, 2 triangles a segment. */
65
+ grow(ribbons) {
66
+ if (ribbons <= this.capacity)
67
+ return;
68
+ const n = Math.max(ribbons, this.capacity * 2), v = n * this.points * 2;
69
+ const make = (size) => new T.BufferAttribute(new Float32Array(v * size), size).setUsage(T.DynamicDrawUsage);
70
+ this.attrs = { center: make(3), dir: make(3), color: make(4), misc: make(4), life: make(2) };
71
+ const g = this.geometry;
72
+ g.setAttribute('position', this.attrs.center); // three needs a `position`; the shader reads tCenter
73
+ g.setAttribute('tCenter', this.attrs.center);
74
+ g.setAttribute('tDir', this.attrs.dir);
75
+ g.setAttribute('tColor', this.attrs.color);
76
+ g.setAttribute('tMisc', this.attrs.misc);
77
+ g.setAttribute('tLife', this.attrs.life);
78
+ const idx = new Uint32Array(n * (this.points - 1) * 6);
79
+ for (let r = 0, w = 0; r < n; r++)
80
+ for (let k = 0; k < this.points - 1; k++) {
81
+ const a = (r * this.points + k) * 2;
82
+ idx[w++] = a;
83
+ idx[w++] = a + 1;
84
+ idx[w++] = a + 2;
85
+ idx[w++] = a + 1;
86
+ idx[w++] = a + 3;
87
+ idx[w++] = a + 2;
88
+ }
89
+ this.index = new T.BufferAttribute(idx, 1);
90
+ g.setIndex(this.index);
91
+ this.capacity = n;
92
+ }
93
+ /** Writes ribbon `r`: `pts` = its centre points head first (count <= points), the rest folded onto the last point. */
94
+ write(r, pts, count, rgba, width, life, seed) {
95
+ const { center, dir, color, misc, life: lf } = this.attrs;
96
+ const C = center.array, D = dir.array, K = color.array, M = misc.array, L = lf.array;
97
+ for (let k = 0; k < this.points; k++) {
98
+ const j = Math.min(k, count - 1), p = pts[j];
99
+ // Direction along the trail: towards the newer neighbour, so the head points where the particle is going.
100
+ const a = pts[Math.max(0, j - 1)], b = pts[Math.min(count - 1, j + 1)];
101
+ const dx = a[0] - b[0], dy = a[1] - b[1], dz = a[2] - b[2];
102
+ const u = count > 1 ? j / (count - 1) : 0, wd = k < count ? width(u) : 0;
103
+ for (let s = 0; s < 2; s++) {
104
+ const v = (r * this.points + k) * 2 + s;
105
+ C[v * 3] = p[0];
106
+ C[v * 3 + 1] = p[1];
107
+ C[v * 3 + 2] = p[2];
108
+ D[v * 3] = dx;
109
+ D[v * 3 + 1] = dy;
110
+ D[v * 3 + 2] = dz;
111
+ K[v * 4] = rgba[0];
112
+ K[v * 4 + 1] = rgba[1];
113
+ K[v * 4 + 2] = rgba[2];
114
+ K[v * 4 + 3] = rgba[3];
115
+ M[v * 4] = s ? 1 : -1;
116
+ M[v * 4 + 1] = wd;
117
+ M[v * 4 + 2] = u;
118
+ M[v * 4 + 3] = 0;
119
+ L[v * 2] = life;
120
+ L[v * 2 + 1] = seed;
121
+ }
122
+ }
123
+ }
124
+ /** Draw the first `ribbons` written. */
125
+ commit(ribbons) {
126
+ for (const a of Object.values(this.attrs))
127
+ a.needsUpdate = true;
128
+ this.geometry.setDrawRange(0, ribbons * (this.points - 1) * 6);
129
+ this.mesh.visible = ribbons > 0;
130
+ }
131
+ dispose() { this.geometry.dispose(); }
132
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umicat/three-sdk",
3
- "version": "1.39.0",
3
+ "version": "1.41.0",
4
4
  "description": "Three.js runtime for Umicat games: the scene3d design format, its loader with physics, a kinematic character controller, and the Umicat platform via @umicat/platform-sdk.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",