@umicat/three-sdk 1.39.0 → 1.40.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
@@ -119,7 +119,14 @@ every lit material in the scene; `new VfxInstance(doc, { lights: false })` or
119
119
  scales everything: world-space particles take it in speed and size, and a
120
120
  light's range follows it.
121
121
 
122
- **Write the lowest version.** `minimumVersion(doc)` is 5 with lights, 4 with meshes, 3 with a
122
+ **Trails (version 6, 1.40.0, ADR-055 step 4).** `emitter.trail: { length,
123
+ width, widthOverTrail?, material? }`: each particle keeps up to 16 points of
124
+ where it has been and draws a ribbon turned to the viewer in the vertex
125
+ shader (no camera needed). u runs from the particle (0) to the tail end (1);
126
+ without a material the trail takes the particle's colour and fades out. At
127
+ most 8000 trail points per effect, checked at parse.
128
+
129
+ **Write the lowest version.** `minimumVersion(doc)` is 6 with trails, 5 with lights, 4 with meshes, 3 with a
123
130
  material, else 2; the editor and the agent write that, so an effect that needs nothing
124
131
  new stays version 2 and keeps playing on 1.36.
125
132
 
@@ -39,6 +39,7 @@ export declare class VfxInstance {
39
39
  private live;
40
40
  constructor(document: VfxDocument, options?: VfxInstanceOptions);
41
41
  private buildParticles;
42
+ private buildTrail;
42
43
  /** (Re)creates the per-instance buffers with room for `capacity` particles. */
43
44
  private allocate;
44
45
  private buildMesh;
@@ -68,6 +69,8 @@ export declare class VfxInstance {
68
69
  /** A new particle on `layer`, from its own emission shape -- around a parent particle when `at` is given. */
69
70
  private spawn;
70
71
  private spawnChildren;
72
+ /** Rebuilds an emitter's ribbons: each particle's position, then its history, newest first. */
73
+ private drawTrail;
71
74
  /** The frame a flipbook shows now, or -1 for none. A looping flipbook keeps
72
75
  * cycling while the effect runs and, once it stops, finishes its current
73
76
  * 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);
@@ -239,14 +240,36 @@ export class VfxInstance {
239
240
  if (config.space === 'world')
240
241
  mesh.matrixAutoUpdate = false;
241
242
  this.root.add(mesh);
243
+ const trail = config.trail ? this.buildTrail(config, index, textureOf) : undefined;
242
244
  const layer = {
243
245
  config, index, particles: [], root, fraction: 0, cycle: 0, burstEmitted: config.bursts.map(() => 0),
244
246
  orient: emitterQuaternion(config), mesh, geometry, material, capacity: 0, attributes: undefined,
245
- images, compiled, repeats,
247
+ images, compiled, repeats, trail,
246
248
  };
247
249
  this.allocate(layer, 64);
248
250
  return layer;
249
251
  }
252
+ buildTrail(config, index, textureOf) {
253
+ const t = config.trail;
254
+ // Default: the particle's colour, fading from the particle to the tail (u runs head -> tail).
255
+ const compiled = compileMaterial(t.material ?? { ...materialDefaults(), masks: [{ ...maskDefaults({ type: 'gradient', fill: 'linear', center: [.5, .5], width: .25 }), invert: true }], softness: 1, ramp: 'linear' });
256
+ const images = [], repeats = [];
257
+ bindImages(compiled, textureOf, images, repeats);
258
+ const material = new T.ShaderMaterial({
259
+ transparent: true, depthWrite: false, side: T.DoubleSide,
260
+ blending: config.blend === 'additive' ? T.AdditiveBlending : T.NormalBlending,
261
+ uniforms: { ...compiled.uniforms }, vertexShader: trailVertex(compiled), fragmentShader: meshFragment(compiled),
262
+ });
263
+ const { points, interval } = trailSampling(t);
264
+ const mesh = new TrailMesh(material, points);
265
+ // Under its particles, which are the bright heads of the streaks.
266
+ mesh.mesh.name = config.id + ':trail';
267
+ mesh.mesh.renderOrder = index - .5;
268
+ if (config.space === 'world')
269
+ mesh.mesh.matrixAutoUpdate = false;
270
+ this.root.add(mesh.mesh);
271
+ return { mesh, compiled, points, interval, images, repeats };
272
+ }
250
273
  /** (Re)creates the per-instance buffers with room for `capacity` particles. */
251
274
  allocate(layer, capacity) {
252
275
  const make = (size) => new T.InstancedBufferAttribute(new Float32Array(capacity * size), size).setUsage(T.DynamicDrawUsage);
@@ -389,6 +412,13 @@ export class VfxInstance {
389
412
  continue;
390
413
  }
391
414
  this.move(c, p, dt, origin);
415
+ if (p.history && l.trail) {
416
+ p.history.acc += dt;
417
+ while (p.history.acc >= l.trail.interval - 1e-9) {
418
+ p.history.acc -= l.trail.interval;
419
+ pushHistory(p.history, p.x, p.y, p.z, l.trail.points);
420
+ }
421
+ }
392
422
  this.spawnChildren(l, p, 'life', dt);
393
423
  kept.push(p);
394
424
  }
@@ -553,6 +583,10 @@ export class VfxInstance {
553
583
  tangentialAccel: pickRange(c.tangentialAccel, r()), orbit: pickRange(c.orbit, r()), damping: pickRange(c.damping, r()),
554
584
  owed: c.children.map(() => 0),
555
585
  };
586
+ if (layer.trail) {
587
+ particle.history = newHistory(layer.trail.points);
588
+ pushHistory(particle.history, x, y, z, layer.trail.points);
589
+ }
556
590
  layer.particles.push(particle);
557
591
  this.live++;
558
592
  this.spawnChildren(layer, particle, 'birth', 0);
@@ -592,6 +626,37 @@ export class VfxInstance {
592
626
  this.spawn(child, { x, y, z, vx, vy, vz });
593
627
  });
594
628
  }
629
+ /** Rebuilds an emitter's ribbons: each particle's position, then its history, newest first. */
630
+ drawTrail(l, C) {
631
+ const tr = l.trail, cfg = l.config.trail, n = l.particles.length;
632
+ tr.mesh.grow(n);
633
+ const pts = trailScratch(tr.points), rgba = [0, 0, 0, 0];
634
+ const width = (u) => cfg.width * (cfg.widthOverTrail ? Math.max(0, sampleCurve(cfg.widthOverTrail, u)) : 1 - u);
635
+ for (let i = 0; i < n; i++) {
636
+ const p = l.particles[i], h = p.history;
637
+ pts[0][0] = p.x;
638
+ pts[0][1] = p.y;
639
+ pts[0][2] = p.z;
640
+ // The newest stored point can be the particle's own spot (it was just pushed): skip it then.
641
+ let k = 0, count = 1;
642
+ historyAt(h, 0, tr.points, pts[1]);
643
+ if (h.count && Math.hypot(pts[1][0] - p.x, pts[1][1] - p.y, pts[1][2] - p.z) < 1e-7)
644
+ k = 1;
645
+ for (; k < h.count && count < tr.points; k++, count++)
646
+ historyAt(h, k, tr.points, pts[count]);
647
+ rgba[0] = C[i * 4];
648
+ rgba[1] = C[i * 4 + 1];
649
+ rgba[2] = C[i * 4 + 2];
650
+ rgba[3] = C[i * 4 + 3];
651
+ tr.mesh.write(i, pts, count, rgba, width, p.age / p.life, p.seed);
652
+ }
653
+ tr.mesh.commit(n);
654
+ tr.compiled.uniforms.uTime.value = this.time;
655
+ syncRepeats(tr.repeats);
656
+ if (l.config.space === 'world')
657
+ tr.mesh.mesh.matrix.copy(this.root.matrixWorld).invert();
658
+ tr.mesh.mesh.visible = n > 0 && tr.images.every((x) => !!x?.image?.width);
659
+ }
595
660
  /** The frame a flipbook shows now, or -1 for none. A looping flipbook keeps
596
661
  * cycling while the effect runs and, once it stops, finishes its current
597
662
  * cycle -- the flipbook counterpart of particles draining. */
@@ -652,6 +717,8 @@ export class VfxInstance {
652
717
  A[i * 3 + 2] = xyz?.z ? sampleCurve(xyz.z, t) : 1;
653
718
  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
719
  }
720
+ if (l.trail)
721
+ this.drawTrail(l, C);
655
722
  l.geometry.instanceCount = n;
656
723
  for (const attribute of [pos, color, misc, vel, life, axes])
657
724
  attribute.needsUpdate = true;
@@ -732,6 +799,13 @@ export class VfxInstance {
732
799
  l.compiled?.dispose();
733
800
  for (const r of l.repeats)
734
801
  r.copy.dispose();
802
+ if (l.trail) {
803
+ l.trail.mesh.dispose();
804
+ (l.trail.mesh.material).dispose();
805
+ l.trail.compiled.dispose();
806
+ for (const r of l.trail.repeats)
807
+ r.copy.dispose();
808
+ }
735
809
  }
736
810
  for (const f of this.flipbookLayers)
737
811
  f.material.dispose();
@@ -772,6 +846,15 @@ function bindImages(compiled, textureOf, images, repeats) {
772
846
  compiled.uniforms[`uMask${i}`].value = copy;
773
847
  }
774
848
  }
849
+ const trailScratches = new Map();
850
+ function trailScratch(points) {
851
+ let s = trailScratches.get(points);
852
+ if (!s) {
853
+ s = Array.from({ length: points }, () => [0, 0, 0]);
854
+ trailScratches.set(points, s);
855
+ }
856
+ return s;
857
+ }
775
858
  /** A copy made before its image decoded never uploads on its own: follow the source's version. */
776
859
  function syncRepeats(repeats) {
777
860
  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.40.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",