@umicat/three-sdk 1.35.0 → 1.37.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.
@@ -1,5 +1,6 @@
1
1
  import * as T from 'three';
2
- import { parseVfx } from './document.js';
2
+ import { parseVfx, pickRange, sampleCurve, sampleGradient, LIMITS, } from './document.js';
3
+ import { compileMaterial } from './material.js';
3
4
  const SHARED_QUAD = (() => {
4
5
  // Corners in [0,1]^2 with y UP; the shader turns them into a cell-sized quad.
5
6
  const g = new T.BufferGeometry();
@@ -35,6 +36,101 @@ void main(){
35
36
  #include <tonemapping_fragment>
36
37
  #include <colorspace_fragment>
37
38
  }`;
39
+ /** The particle quad: corners at +-0.5, one instance per particle. */
40
+ const PARTICLE_QUAD = (() => {
41
+ const g = new T.InstancedBufferGeometry();
42
+ g.setAttribute('position', new T.BufferAttribute(new Float32Array([-.5, -.5, 0, .5, -.5, 0, .5, .5, 0, -.5, .5, 0]), 3));
43
+ g.setIndex([0, 1, 2, 0, 2, 3]);
44
+ return g;
45
+ })();
46
+ // iMisc = (size, angle radians, frame, unused)
47
+ const PARTICLE_VERTEX = `
48
+ attribute vec3 iPos; attribute vec4 iColor; attribute vec4 iMisc; attribute vec3 iVel; attribute vec2 iLife;
49
+ uniform float uAlign; uniform float uStretch; uniform vec2 uCell; uniform mat3 uOrient; uniform vec3 uAxis;
50
+ varying vec2 vUv; varying vec2 vQuad; varying vec4 vColor; varying vec2 vLife;
51
+ void main(){
52
+ vec2 c = position.xy;
53
+ vQuad = c * 2.0;
54
+ vColor = iColor;
55
+ vLife = iLife;
56
+ float size = iMisc.x, angle = iMisc.y, frame = iMisc.z;
57
+ vec2 uv = c + 0.5;
58
+ vUv = vec2((mod(frame, uCell.x) + uv.x) / uCell.x, 1.0 - (floor(frame / uCell.x) + 1.0 - uv.y) / uCell.y);
59
+ float s = sin(angle), co = cos(angle);
60
+ vec2 turned = vec2(c.x * co - c.y * s, c.x * s + c.y * co) * size;
61
+ if (uAlign > 1.5 && uAlign < 2.5) {
62
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(iPos + uOrient * vec3(turned.x, 0.0, -turned.y), 1.0);
63
+ return;
64
+ }
65
+ float scale = length(modelMatrix[0].xyz);
66
+ vec4 center = modelViewMatrix * vec4(iPos, 1.0);
67
+ vec3 offset = vec3(turned, 0.0);
68
+ if (uAlign > 0.5) {
69
+ // An axial billboard: the long side lies along a 3D direction (the
70
+ // particle's velocity, or the emitter's axis) and foreshortens with it;
71
+ // the quad only spins about that line to face the viewer.
72
+ vec3 along = (modelViewMatrix * vec4(uAlign > 2.5 ? uAxis : iVel, 0.0)).xyz;
73
+ float l = length(along);
74
+ if (l > 1e-6) {
75
+ vec3 dir = along / l;
76
+ vec3 side = cross(dir, normalize(-center.xyz));
77
+ float sl = length(side);
78
+ if (sl > 1e-4) {
79
+ side /= sl;
80
+ vec2 r = vec2(c.x * co - c.y * s, c.x * s + c.y * co);
81
+ offset = side * (r.x * size) + dir * (r.y * size * (1.0 + uStretch * length(iVel)));
82
+ }
83
+ }
84
+ }
85
+ center.xyz += offset * scale;
86
+ gl_Position = projectionMatrix * center;
87
+ }`;
88
+ const PARTICLE_FRAGMENT = `
89
+ uniform float uLook; uniform float uSoft; uniform float uPoints; uniform float uSharp; uniform sampler2D uMap;
90
+ varying vec2 vUv; varying vec2 vQuad; varying vec4 vColor;
91
+ void main(){
92
+ float r = length(vQuad);
93
+ vec3 rgb = vColor.rgb;
94
+ float a;
95
+ if (uLook < 0.5) { // dot
96
+ if (r >= 1.0) discard;
97
+ a = pow(1.0 - r, uSoft * 4.0);
98
+ } else if (uLook < 1.5) { // glow: a hot core and a long halo
99
+ if (r >= 1.0) discard;
100
+ float core = 1.0 - smoothstep(0.0, 0.3, r);
101
+ a = max(core, pow(1.0 - r, 3.0) * 0.6);
102
+ rgb *= 1.0 + core;
103
+ } else if (uLook < 2.5) { // star
104
+ if (r >= 1.0) discard;
105
+ float k = abs(cos(uPoints * atan(vQuad.y, vQuad.x) * 0.5));
106
+ float edge = mix(0.12, 1.0, pow(k, 1.0 + uSharp * 12.0));
107
+ a = max(1.0 - smoothstep(edge * 0.5, edge, r), (1.0 - smoothstep(0.0, 0.25, r)) * 0.8);
108
+ } else { // texture / sheet
109
+ vec4 texel = texture2D(uMap, vUv);
110
+ rgb *= texel.rgb;
111
+ a = texel.a;
112
+ }
113
+ gl_FragColor = vec4(rgb, vColor.a * a);
114
+ #include <tonemapping_fragment>
115
+ #include <colorspace_fragment>
116
+ }`;
117
+ /** The material look: the material's colour and alpha times the particle's. */
118
+ const materialFragment = (c) => `
119
+ varying vec2 vQuad; varying vec4 vColor; varying vec2 vLife;
120
+ ${c.code}
121
+ float vfxBayer(vec2 p){ ivec2 q = ivec2(mod(p, 4.0)); int i = q.x + q.y * 4;
122
+ float m[16] = float[16](0.,8.,2.,10.,12.,4.,14.,6.,3.,11.,1.,9.,15.,7.,13.,5.); return (m[i] + 0.5) / 16.0; }
123
+ void main(){
124
+ vec4 m = vfxMaterial(vQuad * 0.5 + 0.5, vLife);
125
+ float a = m.a * vColor.a;
126
+ ${c.alphaMode === 'cutout' ? 'if (a < 0.5) discard; a = 1.0;' : c.alphaMode === 'dither' ? 'if (a < vfxBayer(gl_FragCoord.xy)) discard; a = 1.0;' : 'if (a <= 0.002) discard;'}
127
+ gl_FragColor = vec4(m.rgb * vColor.rgb, a);
128
+ #include <tonemapping_fragment>
129
+ #include <colorspace_fragment>
130
+ }`;
131
+ const LOOK_CODE = { dot: 0, glow: 1, star: 2, texture: 3, sheet: 3, material: 0 };
132
+ const ALIGN_CODE = { camera: 0, velocity: 1, ground: 2, axis: 3 };
133
+ const TAU = Math.PI * 2, DEG = Math.PI / 180;
38
134
  function resolveTexture(source, name) {
39
135
  if (!source)
40
136
  return undefined;
@@ -44,13 +140,17 @@ function resolveTexture(source, name) {
44
140
  return source.get(name);
45
141
  return Object.prototype.hasOwnProperty.call(source, name) ? source[name] : undefined;
46
142
  }
143
+ const scratchColor = new T.Color();
144
+ const scratchRgba = [0, 0, 0, 0];
145
+ const scratchVec = new T.Vector3();
47
146
  /**
48
147
  * One playing copy of an effect. Shared by the VFX Editor and games: it owns
49
148
  * no renderer, no DOM and no animation loop -- add `root` to a scene and call
50
149
  * `update(seconds)` from your own frame loop.
51
150
  *
52
- * Simulation is fixed-step (1/60 s) and seeded, so the same document plays the
53
- * same way at any frame rate, and `reset()` replays it exactly.
151
+ * Simulation is fixed-step (1/60 s), seeded and on the CPU, so the same
152
+ * document plays the same way at any frame rate, and `reset()` replays it
153
+ * exactly. Each particle layer draws as one instanced quad mesh.
54
154
  */
55
155
  export class VfxInstance {
56
156
  constructor(document, options = {}) {
@@ -58,43 +158,88 @@ export class VfxInstance {
58
158
  /** Seconds of simulated time since start (or the last reset). */
59
159
  this.time = 0;
60
160
  this.particleLayers = [];
161
+ this.byId = new Map();
61
162
  this.flipbookLayers = [];
62
163
  this.state = 1;
164
+ /** Particles born so far: hashed into each particle's `seed`. */
165
+ this.serial = 0;
63
166
  this.accumulator = 0;
167
+ this.live = 0;
64
168
  this.document = parseVfx(document);
65
169
  this.state = this.document.seed;
66
170
  this.root.name = this.document.name;
67
- for (const config of this.document.emitters)
68
- this.particleLayers.push(this.buildParticles(config));
171
+ const children = new Set(this.document.emitters.flatMap((e) => e.children.map((c) => c.emitter)));
172
+ this.document.emitters.forEach((config, index) => {
173
+ const layer = this.buildParticles(config, index, !children.has(config.id), (name) => resolveTexture(options.textures, name));
174
+ this.particleLayers.push(layer);
175
+ this.byId.set(config.id, layer);
176
+ });
69
177
  for (const config of this.document.flipbooks ?? [])
70
178
  this.flipbookLayers.push(this.buildFlipbook(config, resolveTexture(options.textures, config.texture)));
71
179
  this.draw();
72
180
  }
73
- buildParticles(config) {
74
- const capacity = Math.max(1, Math.ceil(config.rate * config.lifetime) + 2);
75
- const positions = new Float32Array(capacity * 3), colors = new Float32Array(capacity * 3), sizes = new Float32Array(capacity), alphas = new Float32Array(capacity);
76
- const geometry = new T.BufferGeometry();
77
- for (const [name, array, itemSize] of [['position', positions, 3], ['color', colors, 3], ['particleSize', sizes, 1], ['particleAlpha', alphas, 1]]) {
78
- geometry.setAttribute(name, new T.BufferAttribute(array, itemSize).setUsage(T.DynamicDrawUsage));
79
- }
80
- geometry.setDrawRange(0, 0);
181
+ buildParticles(config, index, root, textureOf) {
182
+ const geometry = new T.InstancedBufferGeometry();
183
+ geometry.index = PARTICLE_QUAD.index;
184
+ geometry.setAttribute('position', PARTICLE_QUAD.getAttribute('position'));
185
+ const look = config.look;
186
+ const texture = look.type === 'texture' || look.type === 'sheet' ? textureOf(look.texture) : undefined;
187
+ const images = look.type === 'texture' || look.type === 'sheet' ? [texture] : [];
188
+ const compiled = look.type === 'material' ? compileMaterial(look.material) : undefined;
189
+ const repeats = [];
190
+ if (compiled)
191
+ for (const [i, name] of compiled.images) {
192
+ const t = textureOf(name);
193
+ images.push(t);
194
+ if (!t) {
195
+ compiled.uniforms[`uMask${i}`].value = null;
196
+ continue;
197
+ }
198
+ const copy = t.clone();
199
+ copy.wrapS = copy.wrapT = T.RepeatWrapping;
200
+ repeats.push({ source: t, copy, version: -1 });
201
+ compiled.uniforms[`uMask${i}`].value = copy;
202
+ }
81
203
  const material = new T.ShaderMaterial({
82
- transparent: true, depthWrite: false,
204
+ transparent: true, depthWrite: false, side: T.DoubleSide,
83
205
  blending: config.blend === 'additive' ? T.AdditiveBlending : T.NormalBlending,
84
- uniforms: { viewportHeight: { value: 600 } },
85
- vertexShader: `attribute vec3 color; attribute float particleSize; attribute float particleAlpha; uniform float viewportHeight; varying vec3 tint; varying float alpha;
86
- void main(){vec4 p=modelViewMatrix*vec4(position,1.);gl_Position=projectionMatrix*p;float scale=length(modelMatrix[0].xyz);gl_PointSize=clamp(particleSize*scale*viewportHeight*projectionMatrix[1][1]/max(.1,-p.z),1.,256.);tint=color;alpha=particleAlpha;}`,
87
- fragmentShader: `varying vec3 tint; varying float alpha;
88
- void main(){float r=length(gl_PointCoord-.5)*2.;if(r>=1.)discard;gl_FragColor=vec4(tint,alpha*pow(1.-r,2.));
89
- #include <tonemapping_fragment>
90
- #include <colorspace_fragment>
91
- }`,
206
+ uniforms: {
207
+ uLook: { value: LOOK_CODE[look.type] }, uSoft: { value: look.type === 'dot' ? look.softness : 0 },
208
+ uPoints: { value: look.type === 'star' ? look.points : 5 }, uSharp: { value: look.type === 'star' ? look.sharpness : 0 },
209
+ uMap: { value: texture ?? null }, uCell: { value: new T.Vector2(look.type === 'sheet' ? look.cols : 1, look.type === 'sheet' ? look.rows : 1) },
210
+ uAlign: { value: ALIGN_CODE[config.align] }, uStretch: { value: config.stretch },
211
+ uAxis: { value: new T.Vector3(...config.direction).applyQuaternion(emitterQuaternion(config)).normalize() },
212
+ uOrient: { value: new T.Matrix3().setFromMatrix4(new T.Matrix4().makeRotationFromQuaternion(emitterQuaternion(config))) },
213
+ ...compiled?.uniforms,
214
+ },
215
+ vertexShader: PARTICLE_VERTEX, fragmentShader: compiled ? materialFragment(compiled) : PARTICLE_FRAGMENT,
92
216
  });
93
- const mesh = new T.Points(geometry, material);
217
+ const mesh = new T.Mesh(geometry, material);
94
218
  mesh.frustumCulled = false;
95
219
  mesh.name = config.id;
220
+ mesh.renderOrder = index;
221
+ if (config.space === 'world')
222
+ mesh.matrixAutoUpdate = false;
96
223
  this.root.add(mesh);
97
- return { config, particles: [], fraction: 0, mesh, positions, colors, sizes, alphas, capacity };
224
+ const layer = {
225
+ config, index, particles: [], root, fraction: 0, cycle: 0, burstEmitted: config.bursts.map(() => 0),
226
+ orient: emitterQuaternion(config), mesh, geometry, material, capacity: 0, attributes: undefined,
227
+ images, compiled, repeats,
228
+ };
229
+ this.allocate(layer, 64);
230
+ return layer;
231
+ }
232
+ /** (Re)creates the per-instance buffers with room for `capacity` particles. */
233
+ allocate(layer, capacity) {
234
+ const make = (size) => new T.InstancedBufferAttribute(new Float32Array(capacity * size), size).setUsage(T.DynamicDrawUsage);
235
+ layer.attributes = { pos: make(3), color: make(4), misc: make(4), vel: make(3), life: make(2) };
236
+ const g = layer.geometry;
237
+ g.setAttribute('iPos', layer.attributes.pos);
238
+ g.setAttribute('iColor', layer.attributes.color);
239
+ g.setAttribute('iMisc', layer.attributes.misc);
240
+ g.setAttribute('iVel', layer.attributes.vel);
241
+ g.setAttribute('iLife', layer.attributes.life);
242
+ layer.capacity = capacity;
98
243
  }
99
244
  buildFlipbook(config, texture) {
100
245
  const material = new T.ShaderMaterial({
@@ -120,26 +265,29 @@ void main(){float r=length(gl_PointCoord-.5)*2.;if(r>=1.)discard;gl_FragColor=ve
120
265
  this.time = 0;
121
266
  this.accumulator = 0;
122
267
  this.state = this.document.seed;
268
+ this.live = 0;
269
+ this.serial = 0;
123
270
  for (const l of this.particleLayers) {
124
271
  l.particles = [];
125
272
  l.fraction = 0;
273
+ l.cycle = 0;
274
+ l.burstEmitted.fill(0);
126
275
  }
127
276
  for (const f of this.flipbookLayers)
128
277
  f.done = !f.config.enabled;
129
278
  this.draw();
130
279
  }
131
- get particleCount() { return this.particleLayers.reduce((sum, l) => sum + l.particles.length, 0); }
280
+ get particleCount() { return this.live; }
132
281
  /** True once a NON-looping effect has stopped emitting, every particle has
133
282
  * died and every flipbook has played out -- the moment to `dispose()` a
134
283
  * one-shot. Always false for a looping effect. */
135
284
  get finished() {
136
285
  if (this.document.loop || this.time < this.document.duration)
137
286
  return false;
138
- return this.particleCount === 0 && this.flipbookLayers.every((f) => f.done);
287
+ return this.live === 0 && this.flipbookLayers.every((f) => f.done);
139
288
  }
140
- /** Point sizes are in pixels, so particles need the drawing-buffer height (CSS height x pixel ratio). */
141
- setViewportHeight(height) { for (const l of this.particleLayers)
142
- l.mesh.material.uniforms.viewportHeight.value = height; }
289
+ /** Kept for 1.35 callers. Particles are world-sized quads now, so the viewport no longer matters. */
290
+ setViewportHeight(_height) { }
143
291
  /** Advance by `delta` seconds. Gaps over 250 ms are capped, so a backgrounded tab does not dump a burst. */
144
292
  update(delta) {
145
293
  if (!Number.isFinite(delta) || delta < 0)
@@ -153,32 +301,231 @@ void main(){float r=length(gl_PointCoord-.5)*2.;if(r>=1.)discard;gl_FragColor=ve
153
301
  }
154
302
  /** Whether the effect is still starting new particles / new flipbook cycles. */
155
303
  get running() { return this.document.loop || this.time < this.document.duration; }
304
+ /** The emitter's origin in its own simulation space. */
305
+ origin(layer, out) {
306
+ if (layer.config.space === 'world')
307
+ return out.setFromMatrixPosition(this.root.matrixWorld);
308
+ return out.set(0, 0, 0);
309
+ }
156
310
  step(dt) {
157
- const emit = this.running;
311
+ const running = this.running;
312
+ const cycleTime = this.document.loop ? this.time % this.document.duration : this.time;
313
+ const cycle = this.document.loop ? Math.floor(this.time / this.document.duration) : 0;
158
314
  this.time += dt;
315
+ this.root.updateWorldMatrix(true, false);
316
+ const origin = new T.Vector3();
159
317
  for (const l of this.particleLayers) {
160
318
  const c = l.config;
161
- l.particles = l.particles.filter((p) => {
319
+ this.origin(l, origin);
320
+ const kept = [];
321
+ for (const p of l.particles) {
162
322
  p.age += dt;
163
- if (p.age >= p.life)
164
- return false;
165
- p.vy += c.gravity * dt;
166
- p.x += p.vx * dt;
167
- p.y += p.vy * dt;
168
- p.z += p.vz * dt;
169
- return true;
170
- });
171
- if (!emit || !c.enabled)
172
- continue;
173
- l.fraction += c.rate * dt;
174
- while (l.fraction >= 1) {
175
- l.fraction--;
176
- const a = this.random() * Math.PI * 2, r = this.random() * .15;
177
- if (l.particles.length >= l.capacity)
323
+ if (p.age >= p.life) {
324
+ this.live--;
325
+ this.spawnChildren(l, p, 'death', dt);
178
326
  continue;
179
- l.particles.push({ age: 0, life: c.lifetime, x: Math.cos(a) * r, y: 0, z: Math.sin(a) * r, vx: (this.random() - .5) * c.spread, vy: c.speed * (.8 + this.random() * .4), vz: (this.random() - .5) * c.spread });
327
+ }
328
+ this.move(c, p, dt, origin);
329
+ this.spawnChildren(l, p, 'life', dt);
330
+ kept.push(p);
331
+ }
332
+ l.particles = kept;
333
+ if (!running || !c.enabled || !l.root)
334
+ continue;
335
+ // Continuous emission inside [start, stop).
336
+ if (cycleTime >= c.start && (c.stop === null || cycleTime < c.stop)) {
337
+ l.fraction += c.rate * dt;
338
+ while (l.fraction >= 1) {
339
+ l.fraction--;
340
+ this.spawn(l, null);
341
+ }
342
+ }
343
+ // Bursts, counted per cycle so a looping effect repeats them.
344
+ if (cycle !== l.cycle) {
345
+ l.cycle = cycle;
346
+ l.burstEmitted.fill(0);
180
347
  }
348
+ c.bursts.forEach((b, i) => {
349
+ // Particle i of a spread burst is born at time + i * over / count, as
350
+ // Godot does (its first particle at the START of the window, not after
351
+ // one slice -- a 1-particle burst "over" its lifetime appears at once).
352
+ const due = cycleTime < b.time ? 0 : b.over > 0 ? Math.min(b.count, Math.floor(b.count * (cycleTime - b.time) / b.over + 1e-9) + 1) : b.count;
353
+ while (l.burstEmitted[i] < due) {
354
+ l.burstEmitted[i]++;
355
+ this.spawn(l, null);
356
+ }
357
+ });
358
+ }
359
+ }
360
+ move(c, p, dt, origin) {
361
+ const t = p.age / p.life;
362
+ let rx = p.x - origin.x, ry = p.y - origin.y, rz = p.z - origin.z;
363
+ const rl = Math.hypot(rx, ry, rz);
364
+ let ax = c.gravity[0], ay = c.gravity[1], az = c.gravity[2];
365
+ if (rl > 1e-6) {
366
+ const radial = p.radialAccel * (c.radialAccelOverLife ? sampleCurve(c.radialAccelOverLife, t) : 1);
367
+ ax += rx / rl * radial;
368
+ ay += ry / rl * radial;
369
+ az += rz / rl * radial;
370
+ const hl = Math.hypot(rx, rz);
371
+ if (hl > 1e-6 && p.tangentialAccel) {
372
+ ax += -rz / hl * p.tangentialAccel;
373
+ az += rx / hl * p.tangentialAccel;
374
+ }
375
+ }
376
+ p.vx += ax * dt;
377
+ p.vy += ay * dt;
378
+ p.vz += az * dt;
379
+ let speed = Math.hypot(p.vx, p.vy, p.vz);
380
+ if (p.damping > 0 && speed > 0) {
381
+ const k = Math.max(0, speed - p.damping * dt) / speed;
382
+ p.vx *= k;
383
+ p.vy *= k;
384
+ p.vz *= k;
385
+ speed *= k;
386
+ }
387
+ if (c.speedLimit && speed > 0) {
388
+ const lim = Math.max(0, sampleCurve(c.speedLimit, t));
389
+ if (speed > lim) {
390
+ const k = lim / speed;
391
+ p.vx *= k;
392
+ p.vy *= k;
393
+ p.vz *= k;
394
+ }
395
+ }
396
+ p.x += p.vx * dt;
397
+ p.y += p.vy * dt;
398
+ p.z += p.vz * dt;
399
+ if (p.radialSpeed && rl > 1e-6) {
400
+ const k = p.radialSpeed * dt / rl;
401
+ p.x += rx * k;
402
+ p.y += ry * k;
403
+ p.z += rz * k;
181
404
  }
405
+ const orbit = p.orbit * (c.orbitOverLife ? sampleCurve(c.orbitOverLife, t) : 1);
406
+ if (orbit) {
407
+ rx = p.x - origin.x;
408
+ rz = p.z - origin.z;
409
+ const a = orbit * TAU * dt, s = Math.sin(a), co = Math.cos(a);
410
+ p.x = origin.x + rx * co - rz * s;
411
+ p.z = origin.z + rx * s + rz * co;
412
+ }
413
+ p.angle += p.spin * dt;
414
+ }
415
+ /** A new particle on `layer`, from its own emission shape -- around a parent particle when `at` is given. */
416
+ spawn(layer, at) {
417
+ if (this.live >= LIMITS.particles)
418
+ return;
419
+ const c = layer.config, r = () => this.random();
420
+ // Shape (Godot's emission shapes, then scale, then offset).
421
+ let x = 0, y = 0, z = 0;
422
+ const s = c.shape;
423
+ if (s.type === 'sphere') {
424
+ const u = r() * 2 - 1, th = r() * TAU, k = s.surface ? 1 : r(), ring = s.radius * Math.sqrt(1 - u * u);
425
+ x = ring * Math.cos(th) * k;
426
+ y = ring * Math.sin(th) * k;
427
+ z = s.radius * u * k;
428
+ }
429
+ else if (s.type === 'box') {
430
+ x = (r() * 2 - 1) * s.extents[0];
431
+ y = (r() * 2 - 1) * s.extents[1];
432
+ z = (r() * 2 - 1) * s.extents[2];
433
+ }
434
+ else if (s.type === 'ring') {
435
+ const th = r() * TAU, rad = Math.sqrt(r() * (s.radius ** 2 - s.inner ** 2) + s.inner ** 2), h = (r() - .5) * s.height;
436
+ const axis = scratchVec.set(...s.axis).normalize();
437
+ const ortho = Math.abs(axis.x) < .9 ? new T.Vector3(1, 0, 0) : new T.Vector3(0, 1, 0);
438
+ const u = ortho.cross(axis).normalize(), v = axis.clone().cross(u);
439
+ x = (u.x * Math.cos(th) + v.x * Math.sin(th)) * rad + axis.x * h;
440
+ y = (u.y * Math.cos(th) + v.y * Math.sin(th)) * rad + axis.y * h;
441
+ z = (u.z * Math.cos(th) + v.z * Math.sin(th)) * rad + axis.z * h;
442
+ }
443
+ x = x * c.shapeScale[0] + c.shapeOffset[0];
444
+ y = y * c.shapeScale[1] + c.shapeOffset[1];
445
+ z = z * c.shapeScale[2] + c.shapeOffset[2];
446
+ // Direction cone (Godot's spread + flatness).
447
+ const [dx, dy, dz] = coneDirection(c.direction, c.spread * DEG, c.flatness, r(), r());
448
+ const speed = pickRange(c.speed, r());
449
+ let vx = dx * speed + (r() * 2 - 1) * c.randomVelocity[0];
450
+ let vy = dy * speed + (r() * 2 - 1) * c.randomVelocity[1];
451
+ let vz = dz * speed + (r() * 2 - 1) * c.randomVelocity[2];
452
+ if (layer.orient.w < 1 - 1e-12) {
453
+ const p = scratchVec.set(x, y, z).applyQuaternion(layer.orient);
454
+ x = p.x;
455
+ y = p.y;
456
+ z = p.z;
457
+ const v = scratchVec.set(vx, vy, vz).applyQuaternion(layer.orient);
458
+ vx = v.x;
459
+ vy = v.y;
460
+ vz = v.z;
461
+ }
462
+ if (at) {
463
+ x += at.x;
464
+ y += at.y;
465
+ z += at.z;
466
+ vx += at.vx;
467
+ vy += at.vy;
468
+ vz += at.vz;
469
+ }
470
+ else if (c.space === 'world') {
471
+ const m = this.root.matrixWorld;
472
+ const p = scratchVec.set(x, y, z).applyMatrix4(m);
473
+ x = p.x;
474
+ y = p.y;
475
+ z = p.z;
476
+ const v = scratchVec.set(vx, vy, vz).transformDirection(m).multiplyScalar(Math.hypot(vx, vy, vz));
477
+ vx = v.x;
478
+ vy = v.y;
479
+ vz = v.z;
480
+ }
481
+ sampleGradient(c.color, c.color.stops.length > 1 ? r() : 0, scratchRgba);
482
+ const particle = {
483
+ age: 0, life: pickRange(c.lifetime, r()), x, y, z, vx, vy, vz,
484
+ angle: pickRange(c.angle, r()) * DEG, spin: pickRange(c.spin, r()) * DEG, size: pickRange(c.size, r()),
485
+ r: scratchRgba[0], g: scratchRgba[1], b: scratchRgba[2], a: scratchRgba[3],
486
+ seed: seedOf(this.document.seed, this.serial++),
487
+ radialSpeed: pickRange(c.radialSpeed, r()), radialAccel: pickRange(c.radialAccel, r()),
488
+ tangentialAccel: pickRange(c.tangentialAccel, r()), orbit: pickRange(c.orbit, r()), damping: pickRange(c.damping, r()),
489
+ owed: c.children.map(() => 0),
490
+ };
491
+ layer.particles.push(particle);
492
+ this.live++;
493
+ this.spawnChildren(layer, particle, 'birth', 0);
494
+ }
495
+ spawnChildren(layer, p, when, dt) {
496
+ layer.config.children.forEach((sub, i) => {
497
+ if (sub.when !== when)
498
+ return;
499
+ const child = this.byId.get(sub.emitter);
500
+ if (!child || !child.config.enabled)
501
+ return;
502
+ let n = sub.count;
503
+ if (when === 'life') {
504
+ p.owed[i] += sub.rate * dt;
505
+ n = Math.floor(p.owed[i]);
506
+ p.owed[i] -= n;
507
+ }
508
+ if (n <= 0)
509
+ return;
510
+ // The parent's position (and velocity) in the CHILD's space.
511
+ let x = p.x, y = p.y, z = p.z, vx = sub.inheritVelocity ? p.vx : 0, vy = sub.inheritVelocity ? p.vy : 0, vz = sub.inheritVelocity ? p.vz : 0;
512
+ if (layer.config.space !== child.config.space) {
513
+ const m = child.config.space === 'world' ? this.root.matrixWorld : this.root.matrixWorld.clone().invert();
514
+ const pos = scratchVec.set(x, y, z).applyMatrix4(m);
515
+ x = pos.x;
516
+ y = pos.y;
517
+ z = pos.z;
518
+ const len = Math.hypot(vx, vy, vz);
519
+ if (len > 0) {
520
+ const v = scratchVec.set(vx, vy, vz).transformDirection(m).multiplyScalar(len);
521
+ vx = v.x;
522
+ vy = v.y;
523
+ vz = v.z;
524
+ }
525
+ }
526
+ for (let k = 0; k < n; k++)
527
+ this.spawn(child, { x, y, z, vx, vy, vz });
528
+ });
182
529
  }
183
530
  /** The frame a flipbook shows now, or -1 for none. A looping flipbook keeps
184
531
  * cycling while the effect runs and, once it stops, finishes its current
@@ -198,19 +545,60 @@ void main(){float r=length(gl_PointCoord-.5)*2.;if(r>=1.)discard;gl_FragColor=ve
198
545
  return n < cycleEnd ? n % f.frames : -1;
199
546
  }
200
547
  draw() {
548
+ if (this.particleLayers.some((l) => l.config.space === 'world'))
549
+ this.root.updateWorldMatrix(true, false);
201
550
  for (const l of this.particleLayers) {
202
- const c = l.config, start = new T.Color(c.color), end = new T.Color(c.endColor), color = new T.Color();
203
- l.particles.forEach((p, i) => {
204
- const t = p.age / p.life;
205
- l.positions.set([p.x, p.y, p.z], i * 3);
206
- color.copy(start).lerp(end, t);
207
- l.colors.set([color.r, color.g, color.b], i * 3);
208
- l.sizes[i] = T.MathUtils.lerp(c.size, c.endSize, t);
209
- l.alphas[i] = c.opacity * Math.min(1, t * 8) * (1 - t);
210
- });
211
- l.mesh.geometry.setDrawRange(0, l.particles.length);
212
- for (const attribute of Object.values(l.mesh.geometry.attributes))
551
+ const c = l.config, n = l.particles.length;
552
+ if (n > l.capacity)
553
+ this.allocate(l, Math.min(LIMITS.particles, Math.max(n, l.capacity * 2)));
554
+ const { pos, color, misc, vel, life } = l.attributes;
555
+ const P = pos.array, C = color.array, M = misc.array, V = vel.array, L = life.array;
556
+ const look = c.look;
557
+ for (let i = 0; i < n; i++) {
558
+ const p = l.particles[i], t = p.age / p.life;
559
+ let r = p.r, g = p.g, b = p.b, a = p.a;
560
+ if (c.colorOverLife) {
561
+ sampleGradient(c.colorOverLife, t, scratchRgba);
562
+ r *= scratchRgba[0];
563
+ g *= scratchRgba[1];
564
+ b *= scratchRgba[2];
565
+ a *= scratchRgba[3];
566
+ }
567
+ if (c.alphaOverLife)
568
+ a *= Math.max(0, sampleCurve(c.alphaOverLife, t));
569
+ scratchColor.setRGB(r, g, b, T.SRGBColorSpace);
570
+ P[i * 3] = p.x;
571
+ P[i * 3 + 1] = p.y;
572
+ P[i * 3 + 2] = p.z;
573
+ V[i * 3] = p.vx;
574
+ V[i * 3 + 1] = p.vy;
575
+ V[i * 3 + 2] = p.vz;
576
+ C[i * 4] = scratchColor.r * c.intensity;
577
+ C[i * 4 + 1] = scratchColor.g * c.intensity;
578
+ C[i * 4 + 2] = scratchColor.b * c.intensity;
579
+ C[i * 4 + 3] = Math.min(1, a);
580
+ M[i * 4] = p.size * (c.sizeOverLife ? Math.max(0, sampleCurve(c.sizeOverLife, t)) : 1);
581
+ M[i * 4 + 1] = p.angle;
582
+ L[i * 2] = t;
583
+ L[i * 2 + 1] = p.seed;
584
+ 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;
585
+ }
586
+ l.geometry.instanceCount = n;
587
+ for (const attribute of [pos, color, misc, vel, life])
213
588
  attribute.needsUpdate = true;
589
+ if (l.compiled)
590
+ l.compiled.uniforms.uTime.value = this.time;
591
+ // A copy made before its image decoded never uploads on its own: follow the source's version.
592
+ for (const r of l.repeats)
593
+ if (r.version !== r.source.version && r.source.image?.width) {
594
+ r.copy.image = r.source.image;
595
+ r.copy.needsUpdate = true;
596
+ r.version = r.source.version;
597
+ }
598
+ // A textured look waits for its images; a missing one draws nothing.
599
+ l.mesh.visible = n > 0 && l.images.every((t) => !!t?.image?.width);
600
+ if (c.space === 'world')
601
+ l.mesh.matrix.copy(this.root.matrixWorld).invert();
214
602
  }
215
603
  for (const f of this.flipbookLayers) {
216
604
  const frame = this.frameOf(f.config);
@@ -235,14 +623,71 @@ void main(){float r=length(gl_PointCoord-.5)*2.;if(r>=1.)discard;gl_FragColor=ve
235
623
  * shared between instances and belong to whoever loaded them (`VfxEffect`). */
236
624
  dispose() {
237
625
  for (const l of this.particleLayers) {
238
- l.mesh.geometry.dispose();
239
- l.mesh.material.dispose();
626
+ l.geometry.dispose();
627
+ l.material.dispose();
628
+ l.compiled?.dispose();
629
+ for (const r of l.repeats)
630
+ r.copy.dispose();
240
631
  }
241
632
  for (const f of this.flipbookLayers)
242
633
  f.material.dispose();
243
634
  this.particleLayers = [];
244
635
  this.flipbookLayers = [];
636
+ this.byId.clear();
637
+ this.live = 0;
245
638
  this.root.removeFromParent();
246
639
  this.root.clear();
247
640
  }
248
641
  }
642
+ /** A particle's material seed, 0..1, from the effect seed and its birth order. */
643
+ function seedOf(seed, serial) {
644
+ let h = Math.imul(serial + 1, 0x9e3779b1) ^ Math.imul(seed, 0x85ebca6b);
645
+ h = Math.imul(h ^ (h >>> 16), 0x7feb352d);
646
+ h = Math.imul(h ^ (h >>> 15), 0x846ca68b);
647
+ h ^= h >>> 16;
648
+ return (h >>> 0) / 4294967296;
649
+ }
650
+ /** An emitter's `rotation` (XYZ Euler degrees) as a quaternion. */
651
+ function emitterQuaternion(e) {
652
+ return new T.Quaternion().setFromEuler(new T.Euler(e.rotation[0] * DEG, e.rotation[1] * DEG, e.rotation[2] * DEG, 'XYZ'));
653
+ }
654
+ /**
655
+ * A random direction inside the cone around `direction` with half-angle
656
+ * `spread` (radians), following Godot's ParticleProcessMaterial: one angle in
657
+ * the cone's first plane, a second one scaled down by `flatness`, so
658
+ * flatness 1 is a flat fan.
659
+ */
660
+ export function coneDirection(direction, spread, flatness, u1, u2) {
661
+ const a1 = (u1 * 2 - 1) * spread, a2 = (u2 * 2 - 1) * spread * (1 - flatness);
662
+ let sx = Math.sin(a1) * Math.cos(a2), sy = Math.sin(a2), sz = Math.cos(a1) * Math.cos(a2);
663
+ const sl = Math.hypot(sx, sy, sz) || 1;
664
+ sx /= sl;
665
+ sy /= sl;
666
+ sz /= sl;
667
+ let [nx, ny, nz] = direction;
668
+ const nl = Math.hypot(nx, ny, nz);
669
+ if (nl < 1e-9) {
670
+ nx = 0;
671
+ ny = 0;
672
+ nz = 1;
673
+ }
674
+ else {
675
+ nx /= nl;
676
+ ny /= nl;
677
+ nz /= nl;
678
+ }
679
+ // binormal = Y x n (or Z when n is vertical); normal = binormal x n
680
+ let bx = nz, by = 0, bz = -nx;
681
+ let bl = Math.hypot(bx, by, bz);
682
+ if (bl < 1e-4) {
683
+ bx = 0;
684
+ by = 0;
685
+ bz = 1;
686
+ bl = 1;
687
+ }
688
+ bx /= bl;
689
+ by /= bl;
690
+ bz /= bl;
691
+ const mx = by * nz - bz * ny, my = bz * nx - bx * nz, mz = bx * ny - by * nx;
692
+ return [bx * sx + mx * sy + nx * sz, by * sx + my * sy + ny * sz, bz * sx + mz * sy + nz * sz];
693
+ }