@umicat/three-sdk 1.36.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.
package/README.md CHANGED
@@ -89,8 +89,21 @@ cannot load.
89
89
 
90
90
  `parseVfx` accepts version-1 documents (1.35's upward-firing disc) and
91
91
  upgrades them to the v2 emitter that plays the same, and fills every emitter
92
- field a document leaves out from `emitterDefaults()`. The editor and the agent
93
- always write version 2, which **needs 1.36.0 to play**.
92
+ field a document leaves out from `emitterDefaults()`.
93
+
94
+ **The effect material (version 3, 1.37.0, ADR-055).** `look: { type:
95
+ 'material', material }` draws a particle with up to three masks — procedural
96
+ noise (perlin / value / cellular / cell edges, fbm / ridged / ping-pong,
97
+ domain warp; generated in the browser and tileable), a gradient, a shape or an
98
+ image — each scaled, scrolled, spun, optionally polar, reshaped (`levels`) and
99
+ offset, combined with Binbun's twelve blend modes; then dissolve, an alpha
100
+ ramp, a gradient map for colour, an optional glowing edge, and HDR emission.
101
+ `dissolve`, `threshold`, `opacity`, `emission` and each mask's `strength` /
102
+ `offset` are a number or `{ overLife: Curve }`. See `src/vfx/material.ts`.
103
+
104
+ **Write the lowest version.** `minimumVersion(doc)` is 3 only when a material
105
+ is used; the editor and the agent write that, so an effect that needs nothing
106
+ new stays version 2 and keeps playing on 1.36.
94
107
 
95
108
  ## What is proven, and by what
96
109
 
@@ -25,6 +25,8 @@ export declare class VfxInstance {
25
25
  private byId;
26
26
  private flipbookLayers;
27
27
  private state;
28
+ /** Particles born so far: hashed into each particle's `seed`. */
29
+ private serial;
28
30
  private accumulator;
29
31
  private live;
30
32
  constructor(document: VfxDocument, options?: VfxInstanceOptions);
@@ -1,5 +1,6 @@
1
1
  import * as T from 'three';
2
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();
@@ -44,13 +45,14 @@ const PARTICLE_QUAD = (() => {
44
45
  })();
45
46
  // iMisc = (size, angle radians, frame, unused)
46
47
  const PARTICLE_VERTEX = `
47
- attribute vec3 iPos; attribute vec4 iColor; attribute vec4 iMisc; attribute vec3 iVel;
48
+ attribute vec3 iPos; attribute vec4 iColor; attribute vec4 iMisc; attribute vec3 iVel; attribute vec2 iLife;
48
49
  uniform float uAlign; uniform float uStretch; uniform vec2 uCell; uniform mat3 uOrient; uniform vec3 uAxis;
49
- varying vec2 vUv; varying vec2 vQuad; varying vec4 vColor;
50
+ varying vec2 vUv; varying vec2 vQuad; varying vec4 vColor; varying vec2 vLife;
50
51
  void main(){
51
52
  vec2 c = position.xy;
52
53
  vQuad = c * 2.0;
53
54
  vColor = iColor;
55
+ vLife = iLife;
54
56
  float size = iMisc.x, angle = iMisc.y, frame = iMisc.z;
55
57
  vec2 uv = c + 0.5;
56
58
  vUv = vec2((mod(frame, uCell.x) + uv.x) / uCell.x, 1.0 - (floor(frame / uCell.x) + 1.0 - uv.y) / uCell.y);
@@ -112,7 +114,21 @@ void main(){
112
114
  #include <tonemapping_fragment>
113
115
  #include <colorspace_fragment>
114
116
  }`;
115
- const LOOK_CODE = { dot: 0, glow: 1, star: 2, texture: 3, sheet: 3 };
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 };
116
132
  const ALIGN_CODE = { camera: 0, velocity: 1, ground: 2, axis: 3 };
117
133
  const TAU = Math.PI * 2, DEG = Math.PI / 180;
118
134
  function resolveTexture(source, name) {
@@ -145,6 +161,8 @@ export class VfxInstance {
145
161
  this.byId = new Map();
146
162
  this.flipbookLayers = [];
147
163
  this.state = 1;
164
+ /** Particles born so far: hashed into each particle's `seed`. */
165
+ this.serial = 0;
148
166
  this.accumulator = 0;
149
167
  this.live = 0;
150
168
  this.document = parseVfx(document);
@@ -152,9 +170,7 @@ export class VfxInstance {
152
170
  this.root.name = this.document.name;
153
171
  const children = new Set(this.document.emitters.flatMap((e) => e.children.map((c) => c.emitter)));
154
172
  this.document.emitters.forEach((config, index) => {
155
- const look = config.look;
156
- const texture = look.type === 'texture' || look.type === 'sheet' ? resolveTexture(options.textures, look.texture) : undefined;
157
- const layer = this.buildParticles(config, index, !children.has(config.id), texture);
173
+ const layer = this.buildParticles(config, index, !children.has(config.id), (name) => resolveTexture(options.textures, name));
158
174
  this.particleLayers.push(layer);
159
175
  this.byId.set(config.id, layer);
160
176
  });
@@ -162,11 +178,28 @@ export class VfxInstance {
162
178
  this.flipbookLayers.push(this.buildFlipbook(config, resolveTexture(options.textures, config.texture)));
163
179
  this.draw();
164
180
  }
165
- buildParticles(config, index, root, texture) {
181
+ buildParticles(config, index, root, textureOf) {
166
182
  const geometry = new T.InstancedBufferGeometry();
167
183
  geometry.index = PARTICLE_QUAD.index;
168
184
  geometry.setAttribute('position', PARTICLE_QUAD.getAttribute('position'));
169
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
+ }
170
203
  const material = new T.ShaderMaterial({
171
204
  transparent: true, depthWrite: false, side: T.DoubleSide,
172
205
  blending: config.blend === 'additive' ? T.AdditiveBlending : T.NormalBlending,
@@ -177,8 +210,9 @@ export class VfxInstance {
177
210
  uAlign: { value: ALIGN_CODE[config.align] }, uStretch: { value: config.stretch },
178
211
  uAxis: { value: new T.Vector3(...config.direction).applyQuaternion(emitterQuaternion(config)).normalize() },
179
212
  uOrient: { value: new T.Matrix3().setFromMatrix4(new T.Matrix4().makeRotationFromQuaternion(emitterQuaternion(config))) },
213
+ ...compiled?.uniforms,
180
214
  },
181
- vertexShader: PARTICLE_VERTEX, fragmentShader: PARTICLE_FRAGMENT,
215
+ vertexShader: PARTICLE_VERTEX, fragmentShader: compiled ? materialFragment(compiled) : PARTICLE_FRAGMENT,
182
216
  });
183
217
  const mesh = new T.Mesh(geometry, material);
184
218
  mesh.frustumCulled = false;
@@ -190,7 +224,7 @@ export class VfxInstance {
190
224
  const layer = {
191
225
  config, index, particles: [], root, fraction: 0, cycle: 0, burstEmitted: config.bursts.map(() => 0),
192
226
  orient: emitterQuaternion(config), mesh, geometry, material, capacity: 0, attributes: undefined,
193
- texture, needsTexture: look.type === 'texture' || look.type === 'sheet',
227
+ images, compiled, repeats,
194
228
  };
195
229
  this.allocate(layer, 64);
196
230
  return layer;
@@ -198,12 +232,13 @@ export class VfxInstance {
198
232
  /** (Re)creates the per-instance buffers with room for `capacity` particles. */
199
233
  allocate(layer, capacity) {
200
234
  const make = (size) => new T.InstancedBufferAttribute(new Float32Array(capacity * size), size).setUsage(T.DynamicDrawUsage);
201
- layer.attributes = { pos: make(3), color: make(4), misc: make(4), vel: make(3) };
235
+ layer.attributes = { pos: make(3), color: make(4), misc: make(4), vel: make(3), life: make(2) };
202
236
  const g = layer.geometry;
203
237
  g.setAttribute('iPos', layer.attributes.pos);
204
238
  g.setAttribute('iColor', layer.attributes.color);
205
239
  g.setAttribute('iMisc', layer.attributes.misc);
206
240
  g.setAttribute('iVel', layer.attributes.vel);
241
+ g.setAttribute('iLife', layer.attributes.life);
207
242
  layer.capacity = capacity;
208
243
  }
209
244
  buildFlipbook(config, texture) {
@@ -231,6 +266,7 @@ export class VfxInstance {
231
266
  this.accumulator = 0;
232
267
  this.state = this.document.seed;
233
268
  this.live = 0;
269
+ this.serial = 0;
234
270
  for (const l of this.particleLayers) {
235
271
  l.particles = [];
236
272
  l.fraction = 0;
@@ -447,6 +483,7 @@ export class VfxInstance {
447
483
  age: 0, life: pickRange(c.lifetime, r()), x, y, z, vx, vy, vz,
448
484
  angle: pickRange(c.angle, r()) * DEG, spin: pickRange(c.spin, r()) * DEG, size: pickRange(c.size, r()),
449
485
  r: scratchRgba[0], g: scratchRgba[1], b: scratchRgba[2], a: scratchRgba[3],
486
+ seed: seedOf(this.document.seed, this.serial++),
450
487
  radialSpeed: pickRange(c.radialSpeed, r()), radialAccel: pickRange(c.radialAccel, r()),
451
488
  tangentialAccel: pickRange(c.tangentialAccel, r()), orbit: pickRange(c.orbit, r()), damping: pickRange(c.damping, r()),
452
489
  owed: c.children.map(() => 0),
@@ -514,8 +551,8 @@ export class VfxInstance {
514
551
  const c = l.config, n = l.particles.length;
515
552
  if (n > l.capacity)
516
553
  this.allocate(l, Math.min(LIMITS.particles, Math.max(n, l.capacity * 2)));
517
- const { pos, color, misc, vel } = l.attributes;
518
- const P = pos.array, C = color.array, M = misc.array, V = vel.array;
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;
519
556
  const look = c.look;
520
557
  for (let i = 0; i < n; i++) {
521
558
  const p = l.particles[i], t = p.age / p.life;
@@ -542,14 +579,24 @@ export class VfxInstance {
542
579
  C[i * 4 + 3] = Math.min(1, a);
543
580
  M[i * 4] = p.size * (c.sizeOverLife ? Math.max(0, sampleCurve(c.sizeOverLife, t)) : 1);
544
581
  M[i * 4 + 1] = p.angle;
582
+ L[i * 2] = t;
583
+ L[i * 2 + 1] = p.seed;
545
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;
546
585
  }
547
586
  l.geometry.instanceCount = n;
548
- for (const attribute of [pos, color, misc, vel])
587
+ for (const attribute of [pos, color, misc, vel, life])
549
588
  attribute.needsUpdate = true;
550
- // A textured look waits for its image; a missing one draws nothing.
551
- const image = l.texture?.image;
552
- l.mesh.visible = n > 0 && (!l.needsTexture || !!image?.width);
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);
553
600
  if (c.space === 'world')
554
601
  l.mesh.matrix.copy(this.root.matrixWorld).invert();
555
602
  }
@@ -578,6 +625,9 @@ export class VfxInstance {
578
625
  for (const l of this.particleLayers) {
579
626
  l.geometry.dispose();
580
627
  l.material.dispose();
628
+ l.compiled?.dispose();
629
+ for (const r of l.repeats)
630
+ r.copy.dispose();
581
631
  }
582
632
  for (const f of this.flipbookLayers)
583
633
  f.material.dispose();
@@ -589,6 +639,14 @@ export class VfxInstance {
589
639
  this.root.clear();
590
640
  }
591
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
+ }
592
650
  /** An emitter's `rotation` (XYZ Euler degrees) as a quaternion. */
593
651
  function emitterQuaternion(e) {
594
652
  return new T.Quaternion().setFromEuler(new T.Euler(e.rotation[0] * DEG, e.rotation[1] * DEG, e.rotation[2] * DEG, 'XYZ'));
@@ -14,7 +14,12 @@
14
14
  *
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
+ *
18
+ * Version 3 (1.37) adds the effect MATERIAL (`look: { type: 'material' }`,
19
+ * ADR-055). A document that uses none of it is still written as version 2 --
20
+ * `minimumVersion()` -- so games whose lockfile holds 1.36 keep playing it.
17
21
  */
22
+ import { type Material } from './material.js';
18
23
  /** A number, or `[min, max]`: picked uniformly per particle. */
19
24
  export type Range = number | [number, number];
20
25
  export type Vec3 = [number, number, number];
@@ -83,6 +88,11 @@ export type ParticleLook =
83
88
  rows: number;
84
89
  frames: number;
85
90
  fps: number | 'life';
91
+ }
92
+ /** (version 3) The general effect material: masks, dissolve, a gradient map, emission. See material.ts. */
93
+ | {
94
+ type: 'material';
95
+ material: Material;
86
96
  };
87
97
  export interface Burst {
88
98
  time: number;
@@ -197,7 +207,7 @@ export interface Flipbook {
197
207
  blend: 'normal' | 'additive';
198
208
  }
199
209
  export interface VfxDocument {
200
- version: 2;
210
+ version: 2 | 3;
201
211
  name: string;
202
212
  seed: number;
203
213
  /** Seconds in one cycle. A looping effect repeats it; a one-shot stops emitting after it. */
@@ -310,6 +320,12 @@ export declare function sampleGradient(g: Gradient, t: number, out?: number[]):
310
320
  * fields left out take `emitterDefaults()`.
311
321
  */
312
322
  export declare function parseVfx(value: unknown): VfxDocument;
323
+ /**
324
+ * The lowest format version that can express this document: 3 when any
325
+ * emitter uses the material look, else 2. The editor and the agent write
326
+ * this, so an effect that needs nothing new still plays on 1.36.
327
+ */
328
+ export declare function minimumVersion(d: Pick<VfxDocument, 'emitters'>): 2 | 3;
313
329
  /**
314
330
  * The most particles an effect can have alive at once, estimated: per enabled
315
331
  * emitter, rate x longest life plus every burst, and for sub-emitters, the
@@ -14,7 +14,12 @@
14
14
  *
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
+ *
18
+ * Version 3 (1.37) adds the effect MATERIAL (`look: { type: 'material' }`,
19
+ * ADR-055). A document that uses none of it is still written as version 2 --
20
+ * `minimumVersion()` -- so games whose lockfile holds 1.36 keep playing it.
17
21
  */
22
+ import { parseMaterial, materialTextures } from './material.js';
18
23
  export const LIMITS = { emitters: 8, layers: 8, particles: 4000, cells: 4096, bursts: 16, children: 4, curvePoints: 8, gradientStops: 16 };
19
24
  /** Every emitter field's value when a document leaves it out. */
20
25
  export function emitterDefaults() {
@@ -88,9 +93,12 @@ export function flipbookLayer(id, texture) {
88
93
  /** Every texture filename a document needs (flipbook sheets and particle images), once each. */
89
94
  export function vfxTextures(document) {
90
95
  const names = (document.flipbooks ?? []).map((f) => f.texture);
91
- for (const e of document.emitters)
96
+ for (const e of document.emitters) {
92
97
  if (e.look.type === 'texture' || e.look.type === 'sheet')
93
98
  names.push(e.look.texture);
99
+ else if (e.look.type === 'material')
100
+ names.push(...materialTextures(e.look.material));
101
+ }
94
102
  return [...new Set(names)];
95
103
  }
96
104
  // ---------------------------------------------------------------- sampling
@@ -167,8 +175,8 @@ export function parseVfx(value) {
167
175
  const d = structuredClone(value);
168
176
  const number = (v, min, max) => typeof v === 'number' && Number.isFinite(v) && v >= min && v <= max;
169
177
  const color = (v) => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v);
170
- if (d.version !== 2)
171
- fail('version must be 2 (or 1, which is upgraded)');
178
+ if (d.version !== 2 && d.version !== 3)
179
+ fail(`version must be 2 or 3 (or 1, which is upgraded)${typeof d.version === 'number' && d.version > 3 ? ` -- version ${d.version} was written by a newer editor: update @umicat/three-sdk` : ''}`);
172
180
  if (typeof d.name !== 'string' || !d.name.trim() || d.name.length > 80)
173
181
  fail('name must be 1-80 characters');
174
182
  if (!number(d.seed, 1, 2147483646) || !Number.isInteger(d.seed))
@@ -322,8 +330,16 @@ export function parseVfx(value) {
322
330
  fail(`${lat}.fps must be 1-120 or "life"`);
323
331
  }
324
332
  }
333
+ else if (l.type === 'material') {
334
+ if (d.version < 3)
335
+ fail(`${lat}.type "material" is version 3: set "version": 3 (needs @umicat/three-sdk 1.37 or later)`);
336
+ for (const k of Object.keys(l))
337
+ if (k !== 'type' && k !== 'material')
338
+ fail(`${lat}.${k} is not a field here (expected type, material)`);
339
+ l.material = parseMaterial(l.material, `${lat}.material`, fail, { checkCurve, checkGradient, texturePattern: TEXTURE_PATTERN });
340
+ }
325
341
  else
326
- fail(`${lat}.type must be dot, glow, star, texture or sheet`);
342
+ fail(`${lat}.type must be dot, glow, star, texture, sheet or material`);
327
343
  if (!['camera', 'velocity', 'ground', 'axis'].includes(e.align))
328
344
  fail(`${at}.align must be "camera", "velocity", "ground" or "axis"`);
329
345
  if (!['normal', 'additive'].includes(e.blend))
@@ -394,6 +410,14 @@ export function parseVfx(value) {
394
410
  });
395
411
  return d;
396
412
  }
413
+ /**
414
+ * The lowest format version that can express this document: 3 when any
415
+ * emitter uses the material look, else 2. The editor and the agent write
416
+ * this, so an effect that needs nothing new still plays on 1.36.
417
+ */
418
+ export function minimumVersion(d) {
419
+ return d.emitters.some((e) => e.look?.type === 'material') ? 3 : 2;
420
+ }
397
421
  /**
398
422
  * The most particles an effect can have alive at once, estimated: per enabled
399
423
  * emitter, rate x longest life plus every burst, and for sub-emitters, the
@@ -1,6 +1,7 @@
1
1
  export * from './document.js';
2
2
  export * from './templates.js';
3
3
  export { VfxInstance } from './VfxInstance.js';
4
+ export * from './material.js';
4
5
  export type { VfxInstanceOptions, VfxTextureSource } from './VfxInstance.js';
5
6
  export { loadVfx, VfxEffect, siblingUrl, prepareSheetTexture } from './load.js';
6
7
  export type { LoadVfxOptions } from './load.js';
package/dist/vfx/index.js CHANGED
@@ -6,4 +6,5 @@
6
6
  export * from './document.js';
7
7
  export * from './templates.js';
8
8
  export { VfxInstance } from './VfxInstance.js';
9
+ export * from './material.js';
9
10
  export { loadVfx, VfxEffect, siblingUrl, prepareSheetTexture } from './load.js';
@@ -0,0 +1,191 @@
1
+ /**
2
+ * The effect MATERIAL (format v3, umicat-design ADR-055): how a particle (and,
3
+ * later, a mesh layer) is drawn. Plain data, compiled into one shader.
4
+ *
5
+ * Modelled on the general material the Binbun packs ship
6
+ * (`shared/shader/transparent.gdshader`, their most-used shader):
7
+ *
8
+ * 1. up to three MASKS -- procedural noise, a gradient, a shape or an image,
9
+ * each scaled / scrolled / spun / optionally in polar UVs -- combined
10
+ * into one value m (0..1);
11
+ * 2. DISSOLVE d is taken off m: v = m - d;
12
+ * 3. alpha = smoothstep(threshold, threshold + softness, v);
13
+ * 4. the colour is the GRADIENT MAP `color` at v (a colour ramp indexed by
14
+ * the mask -- the white-hot core of a flame), optionally with a glowing
15
+ * EDGE where v is just above the threshold;
16
+ * 5. x `emission` (HDR) x the particle's own colour and alpha.
17
+ *
18
+ * Numbers marked `Animated` are a constant or `{ overLife: Curve }` --
19
+ * sampled at the particle's age. That is what Binbun's shaders do by reading
20
+ * the particle COLOR as data; here the file says what the number is for.
21
+ */
22
+ import * as T from 'three';
23
+ import { type Curve, type Gradient } from './document.js';
24
+ export type Animated = number | {
25
+ overLife: Curve;
26
+ };
27
+ /**
28
+ * Generated in the browser, tileable. `frequency` is cells across the tile.
29
+ * Godot's simplex maps to perlin (same look, a periodic version is simpler).
30
+ * cellular: distance to the nearest feature point (Voronoi blobs);
31
+ * cellEdges: F2 - F1 (bright cell walls).
32
+ */
33
+ export interface NoiseSource {
34
+ type: 'noise';
35
+ kind: 'perlin' | 'value' | 'cellular' | 'cellEdges';
36
+ fractal: 'none' | 'fbm' | 'ridged' | 'pingpong';
37
+ octaves: number;
38
+ frequency: number;
39
+ seed: number;
40
+ /** Domain warp: each sample is pushed by a second, smooth noise, by up to this many cells -- swirls and smears (Godot domain_warp). 0 = off. */
41
+ warp: number;
42
+ /** pingpong only: how many times the value folds back (Godot's fractal_ping_pong_strength, default 2). Higher = thinner strands. */
43
+ pingpong: number;
44
+ /** Texture side in pixels. */
45
+ size: 64 | 128 | 256 | 512;
46
+ }
47
+ export type MaskSource = NoiseSource
48
+ /**
49
+ * linear: 0 at the left edge to 1 at the right. radial: 1 at `center` to 0
50
+ * half a tile away. square: the same, square. `center` is in UVs, v up.
51
+ */
52
+ | {
53
+ type: 'gradient';
54
+ fill: 'linear' | 'radial' | 'square';
55
+ center: [number, number];
56
+ }
57
+ /** The part-1 particle shapes, plus a ring (`radius` and `width` as fractions of the half-size). */
58
+ | {
59
+ type: 'shape';
60
+ shape: 'dot' | 'glow' | 'star' | 'ring';
61
+ softness: number;
62
+ points: number;
63
+ sharpness: number;
64
+ radius: number;
65
+ width: number;
66
+ }
67
+ /** An image asset next to the effect. `channel` luma = brightness x alpha. */
68
+ | {
69
+ type: 'image';
70
+ texture: string;
71
+ channel: 'luma' | 'r' | 'a';
72
+ };
73
+ /** Binbun's twelve (`util/blend.gdshaderinc`), in its order. dodge is a / (1 - b); linearBurn a + b - 1. */
74
+ export declare const MASK_BLENDS: readonly ["add", "subtract", "multiply", "min", "max", "screen", "overlay", "hardLight", "softLight", "dodge", "burn", "linearBurn"];
75
+ export type MaskBlend = typeof MASK_BLENDS[number];
76
+ export interface Mask {
77
+ source: MaskSource;
78
+ /** UV repeats across the surface. */
79
+ scale: [number, number];
80
+ /** Tiles a second the texture moves: +u to the right, +v up (Godot's v scroll has the same sign; negate its u). */
81
+ scroll: [number, number];
82
+ /** Degrees a second, around the middle. */
83
+ spin: number;
84
+ /** A fixed turn of the texture, degrees around the middle (Binbun's uv alignment modes are 90-degree turns). */
85
+ rotation: number;
86
+ /** Map the UVs to (angle, distance from the middle): a scroll in v then flows outward. */
87
+ polar: boolean;
88
+ /** Each particle starts at its own place in the texture, so a crowd of particles is not identical. */
89
+ randomOffset: boolean;
90
+ invert: boolean;
91
+ /** Reshape the value with smoothstep(lo, hi, value) -- a soft threshold on this mask alone. null = as is. */
92
+ levels: [number, number] | null;
93
+ /**
94
+ * Added to this mask's value, then clamped to 0..1. Animate it over life
95
+ * with a linear gradient mask and `subtract` for a wipe that eats the
96
+ * particle from one side.
97
+ */
98
+ offset: Animated;
99
+ /** How this mask combines into the ones before it (ignored on the first). */
100
+ blend: MaskBlend;
101
+ strength: Animated;
102
+ }
103
+ export interface Material {
104
+ masks: Mask[];
105
+ /** Taken off the mask value: 0 = whole, 1 = gone. Animate it over life to erode a particle away. */
106
+ dissolve: Animated;
107
+ /**
108
+ * alpha = ramp(threshold, threshold + softness, mask - dissolve) ^ power.
109
+ * `ramp` smooth is a smoothstep; linear a straight line (Binbun's
110
+ * transparent shader is linear with power 3).
111
+ */
112
+ threshold: Animated;
113
+ softness: number;
114
+ ramp: 'smooth' | 'linear';
115
+ power: number;
116
+ /** A glowing rim where the material is about to dissolve. width 0 = none. */
117
+ edge: {
118
+ width: number;
119
+ color: string;
120
+ emission: number;
121
+ };
122
+ /** The gradient map: the colour at each mask value (t = 0 the faint parts, 1 the strongest). */
123
+ color: Gradient;
124
+ opacity: Animated;
125
+ /** Brightness; above 1 is HDR. Multiplies the emitter's `intensity`. */
126
+ emission: Animated;
127
+ /** blend: soft alpha. cutout: hard edge at alpha 0.5. dither: a stipple instead of transparency. */
128
+ alphaMode: 'blend' | 'cutout' | 'dither';
129
+ }
130
+ export declare const MATERIAL_LIMITS: {
131
+ readonly masks: 3;
132
+ readonly curves: 8;
133
+ };
134
+ export declare const ANIMATED_FIELDS: {
135
+ readonly dissolve: readonly [-1, 2];
136
+ readonly threshold: readonly [-1, 2];
137
+ readonly opacity: readonly [0, 1];
138
+ readonly emission: readonly [0, 16];
139
+ };
140
+ export declare function noiseDefaults(): NoiseSource;
141
+ export declare function maskDefaults(source?: MaskSource): Mask;
142
+ export declare function shapeSource(shape?: 'dot' | 'glow' | 'star' | 'ring'): MaskSource;
143
+ /** A soft round particle with a noise texture: a blank material that already reads as something. */
144
+ export declare function materialDefaults(): Material;
145
+ /** The value of an Animated number at life t (0..1). */
146
+ export declare function sampleAnimated(a: Animated, t: number): number;
147
+ /** Every image filename a material reads. */
148
+ export declare function materialTextures(m: Material): string[];
149
+ type Fail = (why: string) => never;
150
+ /**
151
+ * Fills omitted fields from the defaults, refuses unknown ones, checks
152
+ * ranges. `checkCurve` / `checkGradient` / `texturePattern` come from the
153
+ * document parser so the messages read the same.
154
+ */
155
+ export declare function parseMaterial(input: unknown, at: string, fail: Fail, h: {
156
+ checkCurve: (v: unknown, at: string) => void;
157
+ checkGradient: (v: unknown, at: string) => void;
158
+ texturePattern: RegExp;
159
+ }): Material;
160
+ /**
161
+ * The noise as `size * size` bytes, normalised to the full 0..255 range (as
162
+ * Godot's NoiseTexture2D does by default). Tileable: every octave is periodic
163
+ * in a whole number of cells. Deterministic per source.
164
+ */
165
+ export declare function generateNoise(n: NoiseSource): Uint8Array;
166
+ export declare function acquireNoiseTexture(n: NoiseSource): T.DataTexture;
167
+ export declare function releaseNoiseTexture(t: T.Texture): void;
168
+ /** For tests: how many distinct noise textures are alive. */
169
+ export declare function noiseTexturesAlive(): number;
170
+ /**
171
+ * A compiled material: the fragment-shader body for these features, the
172
+ * uniforms it reads, and what to free. The GLSL depends only on the
173
+ * material's STRUCTURE (which sources, blends, which numbers are curves), not
174
+ * its numbers, so editing a number never recompiles.
175
+ */
176
+ export interface CompiledMaterial {
177
+ /** Declarations + `vec4 vfxMaterial(vec2 uv, vec2 life)`. life = (t, random). */
178
+ code: string;
179
+ uniforms: Record<string, T.IUniform>;
180
+ /** Image filenames, by mask index, the caller binds into `uMask<i>`. */
181
+ images: Map<number, string>;
182
+ alphaMode: Material['alphaMode'];
183
+ dispose(): void;
184
+ }
185
+ export declare function compileMaterial(m: Material): CompiledMaterial;
186
+ /**
187
+ * Starting points, so nobody begins from a blank material. Each is what one
188
+ * of the reference rebuilds needed (ADR-055), with the numbers rounded.
189
+ */
190
+ export declare const MATERIAL_PRESETS: Record<string, () => Material>;
191
+ export {};
@@ -0,0 +1,500 @@
1
+ /**
2
+ * The effect MATERIAL (format v3, umicat-design ADR-055): how a particle (and,
3
+ * later, a mesh layer) is drawn. Plain data, compiled into one shader.
4
+ *
5
+ * Modelled on the general material the Binbun packs ship
6
+ * (`shared/shader/transparent.gdshader`, their most-used shader):
7
+ *
8
+ * 1. up to three MASKS -- procedural noise, a gradient, a shape or an image,
9
+ * each scaled / scrolled / spun / optionally in polar UVs -- combined
10
+ * into one value m (0..1);
11
+ * 2. DISSOLVE d is taken off m: v = m - d;
12
+ * 3. alpha = smoothstep(threshold, threshold + softness, v);
13
+ * 4. the colour is the GRADIENT MAP `color` at v (a colour ramp indexed by
14
+ * the mask -- the white-hot core of a flame), optionally with a glowing
15
+ * EDGE where v is just above the threshold;
16
+ * 5. x `emission` (HDR) x the particle's own colour and alpha.
17
+ *
18
+ * Numbers marked `Animated` are a constant or `{ overLife: Curve }` --
19
+ * sampled at the particle's age. That is what Binbun's shaders do by reading
20
+ * the particle COLOR as data; here the file says what the number is for.
21
+ */
22
+ import * as T from 'three';
23
+ import { sampleCurve, sampleGradient } from './document.js';
24
+ /** Binbun's twelve (`util/blend.gdshaderinc`), in its order. dodge is a / (1 - b); linearBurn a + b - 1. */
25
+ export const MASK_BLENDS = ['add', 'subtract', 'multiply', 'min', 'max', 'screen', 'overlay', 'hardLight', 'softLight', 'dodge', 'burn', 'linearBurn'];
26
+ export const MATERIAL_LIMITS = { masks: 3, curves: 8 };
27
+ export const ANIMATED_FIELDS = { dissolve: [-1, 2], threshold: [-1, 2], opacity: [0, 1], emission: [0, 16] };
28
+ export function noiseDefaults() {
29
+ return { type: 'noise', kind: 'perlin', fractal: 'fbm', octaves: 4, frequency: 4, seed: 1, warp: 0, pingpong: 2, size: 256 };
30
+ }
31
+ export function maskDefaults(source = noiseDefaults()) {
32
+ return { source, scale: [1, 1], scroll: [0, 0], spin: 0, rotation: 0, polar: false, randomOffset: false, invert: false, levels: null, offset: 0, blend: 'multiply', strength: 1 };
33
+ }
34
+ export function shapeSource(shape = 'dot') {
35
+ return { type: 'shape', shape, softness: .5, points: 4, sharpness: .5, radius: .7, width: .2 };
36
+ }
37
+ /** A soft round particle with a noise texture: a blank material that already reads as something. */
38
+ export function materialDefaults() {
39
+ return {
40
+ masks: [maskDefaults(shapeSource('dot')), { ...maskDefaults(noiseDefaults()), blend: 'multiply', randomOffset: true }],
41
+ dissolve: 0, threshold: 0, softness: .3, ramp: 'smooth', power: 1, edge: { width: 0, color: '#ffffff', emission: 2 },
42
+ color: { stops: [[0, '#ffffff', 1]] }, opacity: 1, emission: 1, alphaMode: 'blend',
43
+ };
44
+ }
45
+ const isCurve = (a) => typeof a === 'object' && a !== null;
46
+ /** The value of an Animated number at life t (0..1). */
47
+ export function sampleAnimated(a, t) { return isCurve(a) ? sampleCurve(a.overLife, t) : a; }
48
+ /** Every image filename a material reads. */
49
+ export function materialTextures(m) {
50
+ return m.masks.flatMap((k) => k.source.type === 'image' ? [k.source.texture] : []);
51
+ }
52
+ const num = (v, min, max) => typeof v === 'number' && Number.isFinite(v) && v >= min && v <= max;
53
+ const known = (o, keys, at, fail) => { for (const k of Object.keys(o))
54
+ if (!keys.includes(k))
55
+ fail(`${at}.${k} is not a field here (expected ${keys.join(', ')})`); };
56
+ /**
57
+ * Fills omitted fields from the defaults, refuses unknown ones, checks
58
+ * ranges. `checkCurve` / `checkGradient` / `texturePattern` come from the
59
+ * document parser so the messages read the same.
60
+ */
61
+ export function parseMaterial(input, at, fail, h) {
62
+ if (!input || typeof input !== 'object' || Array.isArray(input))
63
+ return fail(`${at} must be an object`);
64
+ const base = materialDefaults();
65
+ known(input, Object.keys(base), at, fail);
66
+ const m = { ...base, ...input };
67
+ const animated = (v, a, min, max) => {
68
+ if (num(v, min, max))
69
+ return;
70
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
71
+ known(v, ['overLife'], a, fail);
72
+ h.checkCurve(v.overLife, `${a}.overLife`);
73
+ return;
74
+ }
75
+ fail(`${a} must be a number ${min}-${max}, or { overLife: { points: [[t, value], ...] } }`);
76
+ };
77
+ for (const [k, [min, max]] of Object.entries(ANIMATED_FIELDS))
78
+ animated(m[k], `${at}.${k}`, min, max);
79
+ if (!num(m.softness, 0, 1))
80
+ fail(`${at}.softness must be 0-1`);
81
+ if (m.ramp !== 'smooth' && m.ramp !== 'linear')
82
+ fail(`${at}.ramp must be "smooth" or "linear"`);
83
+ if (!num(m.power, .1, 8))
84
+ fail(`${at}.power must be 0.1-8`);
85
+ if (!m.edge || typeof m.edge !== 'object')
86
+ fail(`${at}.edge must be { width, color, emission }`);
87
+ m.edge = { ...base.edge, ...m.edge };
88
+ known(m.edge, ['width', 'color', 'emission'], `${at}.edge`, fail);
89
+ if (!num(m.edge.width, 0, 1))
90
+ fail(`${at}.edge.width must be 0-1`);
91
+ if (typeof m.edge.color !== 'string' || !/^#[0-9a-f]{6}$/i.test(m.edge.color))
92
+ fail(`${at}.edge.color must be #rrggbb`);
93
+ if (!num(m.edge.emission, 0, 16))
94
+ fail(`${at}.edge.emission must be 0-16`);
95
+ h.checkGradient(m.color, `${at}.color`);
96
+ if (!['blend', 'cutout', 'dither'].includes(m.alphaMode))
97
+ fail(`${at}.alphaMode must be "blend", "cutout" or "dither"`);
98
+ if (!Array.isArray(m.masks) || m.masks.length < 1 || m.masks.length > MATERIAL_LIMITS.masks)
99
+ fail(`${at}.masks must be a list of 1-${MATERIAL_LIMITS.masks}`);
100
+ m.masks = m.masks.map((raw, i) => {
101
+ const mat = `${at}.masks[${i}]`;
102
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
103
+ fail(`${mat} must be an object`);
104
+ const mb = maskDefaults();
105
+ known(raw, Object.keys(mb), mat, fail);
106
+ const k = { ...mb, ...raw };
107
+ const pair = (v, a, min, max) => { if (!Array.isArray(v) || v.length !== 2 || !v.every((x) => num(x, min, max)))
108
+ fail(`${a} must be [u, v], each ${min}-${max}`); };
109
+ pair(k.scale, `${mat}.scale`, -100, 100);
110
+ pair(k.scroll, `${mat}.scroll`, -100, 100);
111
+ if (!num(k.spin, -3600, 3600))
112
+ fail(`${mat}.spin must be -3600-3600`);
113
+ if (!num(k.rotation, -360, 360))
114
+ fail(`${mat}.rotation must be -360-360`);
115
+ animated(k.offset, `${mat}.offset`, -2, 2);
116
+ for (const b of ['polar', 'randomOffset', 'invert'])
117
+ if (typeof k[b] !== 'boolean')
118
+ fail(`${mat}.${b} must be a boolean`);
119
+ if (k.levels !== null) {
120
+ pair(k.levels, `${mat}.levels`, -2, 3);
121
+ if (k.levels[0] === k.levels[1])
122
+ fail(`${mat}.levels must be [lo, hi] with lo != hi, or null`);
123
+ }
124
+ if (!MASK_BLENDS.includes(k.blend))
125
+ fail(`${mat}.blend must be one of ${MASK_BLENDS.join(', ')}`);
126
+ animated(k.strength, `${mat}.strength`, 0, 1);
127
+ k.source = parseSource(k.source, `${mat}.source`, fail, h.texturePattern);
128
+ return k;
129
+ });
130
+ const curves = curveFields(m).length;
131
+ if (curves > MATERIAL_LIMITS.curves)
132
+ fail(`${at} animates ${curves} numbers over life, the limit is ${MATERIAL_LIMITS.curves}`);
133
+ return m;
134
+ }
135
+ function parseSource(s, at, fail, texturePattern) {
136
+ if (!s || typeof s !== 'object' || Array.isArray(s))
137
+ return fail(`${at} must be an object with a type`);
138
+ const type = s.type;
139
+ if (type === 'noise') {
140
+ const n = { ...noiseDefaults(), ...s };
141
+ known(n, Object.keys(noiseDefaults()), at, fail);
142
+ if (!['perlin', 'value', 'cellular', 'cellEdges'].includes(n.kind))
143
+ fail(`${at}.kind must be perlin, value, cellular or cellEdges`);
144
+ if (!['none', 'fbm', 'ridged', 'pingpong'].includes(n.fractal))
145
+ fail(`${at}.fractal must be none, fbm, ridged or pingpong`);
146
+ if (!num(n.octaves, 1, 6) || !Number.isInteger(n.octaves))
147
+ fail(`${at}.octaves must be a whole number 1-6`);
148
+ if (!num(n.frequency, 1, 64) || !Number.isInteger(n.frequency))
149
+ fail(`${at}.frequency must be a whole number 1-64 (cells across the tile; whole so it tiles)`);
150
+ if (!num(n.seed, 0, 1e6) || !Number.isInteger(n.seed))
151
+ fail(`${at}.seed must be a whole number 0-1000000`);
152
+ if (!num(n.pingpong, .5, 8))
153
+ fail(`${at}.pingpong must be 0.5-8`);
154
+ if (!num(n.warp, 0, 4))
155
+ fail(`${at}.warp must be 0-4`);
156
+ if (![64, 128, 256, 512].includes(n.size))
157
+ fail(`${at}.size must be 64, 128, 256 or 512`);
158
+ return n;
159
+ }
160
+ if (type === 'gradient') {
161
+ const g = { fill: 'radial', center: [.5, .5], ...s };
162
+ known(g, ['type', 'fill', 'center'], at, fail);
163
+ if (!['linear', 'radial', 'square'].includes(g.fill))
164
+ fail(`${at}.fill must be linear, radial or square`);
165
+ if (!Array.isArray(g.center) || g.center.length !== 2 || !g.center.every((x) => num(x, -1, 2)))
166
+ fail(`${at}.center must be [u, v], each -1-2`);
167
+ return g;
168
+ }
169
+ if (type === 'shape') {
170
+ const g = { ...shapeSource(), ...s };
171
+ known(g, Object.keys(shapeSource()), at, fail);
172
+ if (!['dot', 'glow', 'star', 'ring'].includes(g.shape))
173
+ fail(`${at}.shape must be dot, glow, star or ring`);
174
+ for (const k of ['softness', 'sharpness', 'radius', 'width'])
175
+ if (!num(g[k], 0, 1))
176
+ fail(`${at}.${k} must be 0-1`);
177
+ if (!num(g.points, 3, 12) || !Number.isInteger(g.points))
178
+ fail(`${at}.points must be a whole number 3-12`);
179
+ return g;
180
+ }
181
+ if (type === 'image') {
182
+ const g = { channel: 'luma', ...s };
183
+ known(g, ['type', 'texture', 'channel'], at, fail);
184
+ if (typeof g.texture !== 'string' || !texturePattern.test(g.texture))
185
+ fail(`${at}.texture must be the filename of a png, webp or jpg image in the same folder (no path)`);
186
+ if (!['luma', 'r', 'a'].includes(g.channel))
187
+ fail(`${at}.channel must be luma, r or a`);
188
+ return g;
189
+ }
190
+ return fail(`${at}.type must be noise, gradient, shape or image`);
191
+ }
192
+ /** The animated numbers that are curves, in a fixed order: each gets one row of the curve texture. */
193
+ function curveFields(m) {
194
+ const out = [];
195
+ for (const k of Object.keys(ANIMATED_FIELDS)) {
196
+ const v = m[k];
197
+ if (isCurve(v))
198
+ out.push({ key: k, value: v });
199
+ }
200
+ m.masks.forEach((k, i) => {
201
+ if (isCurve(k.strength))
202
+ out.push({ key: `strength${i}`, value: k.strength });
203
+ if (isCurve(k.offset))
204
+ out.push({ key: `offset${i}`, value: k.offset });
205
+ });
206
+ return out;
207
+ }
208
+ // ------------------------------------------------------------------ noise
209
+ function hash(x, y, seed) {
210
+ let h = Math.imul(x, 0x27d4eb2d) ^ Math.imul(y, 0x165667b1) ^ Math.imul(seed + 1, 0x9e3779b1);
211
+ h = Math.imul(h ^ (h >>> 15), 0x85ebca6b);
212
+ h ^= h >>> 13;
213
+ h = Math.imul(h, 0xc2b2ae35);
214
+ h ^= h >>> 16;
215
+ return (h >>> 0) / 4294967296;
216
+ }
217
+ const fade = (t) => t * t * t * (t * (t * 6 - 15) + 10);
218
+ const wrap = (i, n) => ((i % n) + n) % n;
219
+ /** One octave at (x, y) in cell units, periodic in `period` cells. Returns -1..1 (perlin) or 0..1 (the rest). */
220
+ function octave(kind, x, y, period, seed) {
221
+ const ix = Math.floor(x), iy = Math.floor(y), fx = x - ix, fy = y - iy;
222
+ if (kind === 'value' || kind === 'perlin') {
223
+ const corner = (cx, cy) => {
224
+ const hx = wrap(ix + cx, period), hy = wrap(iy + cy, period);
225
+ if (kind === 'value')
226
+ return hash(hx, hy, seed);
227
+ const a = hash(hx, hy, seed) * Math.PI * 2;
228
+ return Math.cos(a) * (fx - cx) + Math.sin(a) * (fy - cy);
229
+ };
230
+ const u = fade(fx), v = fade(fy);
231
+ const a = corner(0, 0) + (corner(1, 0) - corner(0, 0)) * u;
232
+ const b = corner(0, 1) + (corner(1, 1) - corner(0, 1)) * u;
233
+ // perlin: scaled to Godot's simplex spread (sd ~0.54, measured against an exported
234
+ // NoiseTexture2D) so a pingpong / ridged fold lands where Godot's does.
235
+ return kind === 'perlin' ? Math.max(-1, Math.min(1, (a + (b - a) * v) * Math.SQRT2 * 1.75)) : a + (b - a) * v;
236
+ }
237
+ let f1 = 9, f2 = 9;
238
+ for (let oy = -1; oy <= 1; oy++)
239
+ for (let ox = -1; ox <= 1; ox++) {
240
+ const hx = wrap(ix + ox, period), hy = wrap(iy + oy, period);
241
+ const px = ox + hash(hx, hy, seed) - fx, py = oy + hash(hx, hy, seed + 7919) - fy;
242
+ const d = Math.hypot(px, py);
243
+ if (d < f1) {
244
+ f2 = f1;
245
+ f1 = d;
246
+ }
247
+ else if (d < f2)
248
+ f2 = d;
249
+ }
250
+ return kind === 'cellular' ? Math.min(1, f1) : Math.min(1, f2 - f1);
251
+ }
252
+ /**
253
+ * The noise as `size * size` bytes, normalised to the full 0..255 range (as
254
+ * Godot's NoiseTexture2D does by default). Tileable: every octave is periodic
255
+ * in a whole number of cells. Deterministic per source.
256
+ */
257
+ export function generateNoise(n) {
258
+ const size = n.size, out = new Float32Array(size * size);
259
+ const octaves = n.fractal === 'none' ? 1 : n.octaves;
260
+ let lo = Infinity, hi = -Infinity;
261
+ for (let py = 0; py < size; py++)
262
+ for (let px = 0; px < size; px++) {
263
+ let sum = 0, amp = 1;
264
+ // Warp: offset the sample point by a periodic perlin pair at the base frequency, so it still tiles.
265
+ let ux = (px + .5) / size, uy = (py + .5) / size;
266
+ if (n.warp > 0) {
267
+ // Two octaves (2f, 4f): one octave alone leaves perlin's zero-at-every-lattice-point grid visible as pinches.
268
+ const f = n.frequency * 2, w = (seed) => octave('perlin', ux * f, uy * f, f, seed) + .5 * octave('perlin', ux * f * 2, uy * f * 2, f * 2, seed + 1);
269
+ const wx = w(n.seed + 5003), wy = w(n.seed + 9001);
270
+ ux += wx * n.warp / n.frequency;
271
+ uy += wy * n.warp / n.frequency;
272
+ }
273
+ for (let o = 0; o < octaves; o++) {
274
+ const period = n.frequency << o;
275
+ let v = octave(n.kind, ux * period, uy * period, period, n.seed + o * 101);
276
+ if (n.kind !== 'perlin')
277
+ v = v * 2 - 1; // all -1..1 from here
278
+ if (n.fractal === 'ridged')
279
+ v = 1 - Math.abs(v) * 2;
280
+ else if (n.fractal === 'pingpong') {
281
+ const t = (v + 1) * n.pingpong;
282
+ const p = t - Math.floor(t * .5) * 2;
283
+ v = (p < 1 ? p : 2 - p) * 2 - 1;
284
+ }
285
+ sum += v * amp;
286
+ amp *= .5;
287
+ }
288
+ out[py * size + px] = sum;
289
+ if (sum < lo)
290
+ lo = sum;
291
+ if (sum > hi)
292
+ hi = sum;
293
+ }
294
+ const bytes = new Uint8Array(size * size), k = hi > lo ? 255 / (hi - lo) : 0;
295
+ for (let i = 0; i < out.length; i++)
296
+ bytes[i] = Math.round((out[i] - lo) * k);
297
+ return bytes;
298
+ }
299
+ // Shared across instances: a texture per distinct noise, freed when the last user lets go.
300
+ const noiseCache = new Map();
301
+ export function acquireNoiseTexture(n) {
302
+ const key = JSON.stringify([n.kind, n.fractal, n.octaves, n.frequency, n.seed, n.warp, n.pingpong, n.size]);
303
+ let hit = noiseCache.get(key);
304
+ if (!hit) {
305
+ const t = new T.DataTexture(generateNoise(n), n.size, n.size, T.RedFormat, T.UnsignedByteType);
306
+ t.wrapS = t.wrapT = T.RepeatWrapping;
307
+ t.magFilter = T.LinearFilter;
308
+ t.minFilter = T.LinearMipmapLinearFilter;
309
+ t.generateMipmaps = true;
310
+ t.needsUpdate = true;
311
+ t.name = `noise:${key}`;
312
+ hit = { texture: t, users: 0 };
313
+ noiseCache.set(key, hit);
314
+ }
315
+ hit.users++;
316
+ return hit.texture;
317
+ }
318
+ export function releaseNoiseTexture(t) {
319
+ for (const [key, hit] of noiseCache)
320
+ if (hit.texture === t) {
321
+ if (--hit.users <= 0) {
322
+ t.dispose();
323
+ noiseCache.delete(key);
324
+ }
325
+ return;
326
+ }
327
+ }
328
+ /** For tests: how many distinct noise textures are alive. */
329
+ export function noiseTexturesAlive() { return noiseCache.size; }
330
+ // ------------------------------------------------------------------ shader
331
+ /** 256 x 1 sRGB ramp of the gradient map. */
332
+ function gradientTexture(g) {
333
+ const w = 256, data = new Uint8Array(w * 4), c = [0, 0, 0, 0];
334
+ for (let i = 0; i < w; i++) {
335
+ sampleGradient(g, i / (w - 1), c);
336
+ for (let k = 0; k < 4; k++)
337
+ data[i * 4 + k] = Math.round(Math.min(1, Math.max(0, c[k])) * 255);
338
+ }
339
+ const t = new T.DataTexture(data, w, 1, T.RGBAFormat, T.UnsignedByteType);
340
+ t.colorSpace = T.SRGBColorSpace;
341
+ t.magFilter = t.minFilter = T.LinearFilter;
342
+ t.wrapS = t.wrapT = T.ClampToEdgeWrapping;
343
+ t.needsUpdate = true;
344
+ return t;
345
+ }
346
+ /** Every curve as a 256-wide row, sampled at the row's centre texels. */
347
+ function curveTexture(curves) {
348
+ const w = 256, rows = Math.max(1, curves.length), data = new Float32Array(w * rows);
349
+ curves.forEach((c, r) => { for (let i = 0; i < w; i++)
350
+ data[r * w + i] = sampleCurve(c.overLife, i / (w - 1)); });
351
+ const t = new T.DataTexture(data, w, rows, T.RedFormat, T.FloatType);
352
+ t.magFilter = t.minFilter = T.NearestFilter;
353
+ t.needsUpdate = true;
354
+ return t;
355
+ }
356
+ const glslFloat = (x) => { const s = String(x); return /[.e]/.test(s) ? s : s + '.0'; };
357
+ /** GLSL for one mask's raw value (before invert) at uv. */
358
+ function sourceCode(s, i, lod) {
359
+ const tex = (expr) => lod ? `textureLod(uMask${i}, ${expr}, 0.0)` : `texture2D(uMask${i}, ${expr})`;
360
+ switch (s.type) {
361
+ case 'noise': return `${tex('uv')}.r`;
362
+ case 'image': return s.channel === 'r' ? `${tex('uv')}.r` : s.channel === 'a' ? `${tex('uv')}.a` : `(dot(${tex('uv')}.rgb, vec3(0.2126, 0.7152, 0.0722)) * ${tex('uv')}.a)`;
363
+ case 'gradient': {
364
+ const c = `vec2(${glslFloat(s.center[0])}, ${glslFloat(s.center[1])})`;
365
+ return s.fill === 'linear' ? 'fract(uv.x)' : s.fill === 'radial' ? `(1.0 - clamp(length(fract(uv) - ${c}) * 2.0, 0.0, 1.0))` : `(1.0 - clamp(max(abs(fract(uv.x) - ${c}.x), abs(fract(uv.y) - ${c}.y)) * 2.0, 0.0, 1.0))`;
366
+ }
367
+ case 'shape': return `vfxShape${s.shape[0].toUpperCase()}${s.shape.slice(1)}(fract(uv) * 2.0 - 1.0, uShape${i})`;
368
+ }
369
+ }
370
+ const BLEND_CODE = {
371
+ add: 'a + b', subtract: 'a - b', multiply: 'a * b', min: 'min(a, b)', max: 'max(a, b)',
372
+ screen: '1.0 - (1.0 - a) * (1.0 - b)', overlay: '(a < 0.5 ? 2.0 * a * b : 1.0 - 2.0 * (1.0 - a) * (1.0 - b))',
373
+ hardLight: '(b < 0.5 ? 2.0 * a * b : 1.0 - 2.0 * (1.0 - a) * (1.0 - b))',
374
+ softLight: '(b < 0.5 ? 2.0 * a * b + a * a * (1.0 - 2.0 * b) : sqrt(max(a, 0.0)) * (2.0 * b - 1.0) + 2.0 * a * (1.0 - b))',
375
+ dodge: 'a / max(1.0 - b, 1e-3)', burn: '1.0 - (1.0 - a) / max(b, 1e-3)', linearBurn: 'a + b - 1.0',
376
+ };
377
+ const SHAPES = `
378
+ // p in -1..1; params = (softness, points, sharpness, radius) and the ring width in uShapeW.
379
+ float vfxShapeDot(vec2 p, vec4 k){ float r = length(p); return r >= 1.0 ? 0.0 : pow(1.0 - r, max(k.x * 4.0, 1e-3)); }
380
+ float vfxShapeGlow(vec2 p, vec4 k){ float r = length(p); if (r >= 1.0) return 0.0; float core = 1.0 - smoothstep(0.0, 0.3, r); return min(1.0, max(core, pow(1.0 - r, 3.0) * 0.6) * (1.0 + core)); }
381
+ float vfxShapeStar(vec2 p, vec4 k){ float r = length(p); if (r >= 1.0) return 0.0; float e = mix(0.12, 1.0, pow(abs(cos(k.y * atan(p.y, p.x) * 0.5)), 1.0 + k.z * 12.0)); return max(1.0 - smoothstep(e * 0.5, e, r), (1.0 - smoothstep(0.0, 0.25, r)) * 0.8); }
382
+ float vfxShapeRing(vec2 p, vec4 k){ float d = abs(length(p) - k.w); float w = max(k.y, 1e-3); return 1.0 - smoothstep(w * (1.0 - k.x), w, d); }
383
+ `;
384
+ export function compileMaterial(m) {
385
+ const curves = curveFields(m), row = new Map(curves.map((c, i) => [c.key, i]));
386
+ const rows = Math.max(1, curves.length);
387
+ const value = (key, uniform) => row.has(key) ? `vfxCurve(${glslFloat(row.get(key))}, life.x)` : uniform;
388
+ const uniforms = {
389
+ uTime: { value: 0 }, uRamp: { value: gradientTexture(m.color) }, uCurves: { value: curveTexture(curves.map((c) => c.value)) },
390
+ uDissolve: { value: isCurve(m.dissolve) ? 0 : m.dissolve }, uThreshold: { value: isCurve(m.threshold) ? 0 : m.threshold },
391
+ uSoftness: { value: m.softness }, uPower: { value: m.power }, uOpacity: { value: isCurve(m.opacity) ? 1 : m.opacity }, uEmission: { value: isCurve(m.emission) ? 1 : m.emission },
392
+ uEdge: { value: new T.Vector3(m.edge.width, m.edge.emission, 0) }, uEdgeColor: { value: new T.Color(m.edge.color) },
393
+ };
394
+ const owned = [uniforms.uRamp.value, uniforms.uCurves.value];
395
+ const noise = [];
396
+ const images = new Map();
397
+ const decl = [];
398
+ const body = [];
399
+ m.masks.forEach((k, i) => {
400
+ const s = k.source;
401
+ uniforms[`uScale${i}`] = { value: new T.Vector2(...k.scale) };
402
+ uniforms[`uScroll${i}`] = { value: new T.Vector2(...k.scroll) };
403
+ uniforms[`uSpin${i}`] = { value: k.spin * Math.PI / 180 };
404
+ uniforms[`uTurn${i}`] = { value: k.rotation * Math.PI / 180 };
405
+ uniforms[`uOffset${i}`] = { value: isCurve(k.offset) ? 0 : k.offset };
406
+ uniforms[`uStrength${i}`] = { value: isCurve(k.strength) ? 1 : k.strength };
407
+ uniforms[`uLevels${i}`] = { value: new T.Vector2(...(k.levels ?? [0, 1])) };
408
+ decl.push(`uniform vec2 uScale${i}; uniform vec2 uScroll${i}; uniform float uSpin${i}; uniform float uStrength${i}; uniform vec2 uLevels${i}; uniform float uTurn${i}; uniform float uOffset${i};`);
409
+ if (s.type === 'noise') {
410
+ const t = acquireNoiseTexture(s);
411
+ noise.push(t);
412
+ uniforms[`uMask${i}`] = { value: t };
413
+ decl.push(`uniform sampler2D uMask${i};`);
414
+ }
415
+ else if (s.type === 'image') {
416
+ uniforms[`uMask${i}`] = { value: null };
417
+ images.set(i, s.texture);
418
+ decl.push(`uniform sampler2D uMask${i};`);
419
+ }
420
+ else if (s.type === 'shape') {
421
+ uniforms[`uShape${i}`] = { value: new T.Vector4(s.softness, s.shape === 'ring' ? s.width : s.points, s.sharpness, s.radius) };
422
+ decl.push(`uniform vec4 uShape${i};`);
423
+ }
424
+ const polar = k.polar ? `{ vec2 c = uv0 - 0.5; uv = vec2(atan(c.x, c.y) / 6.2831853 + 0.5, length(c) * 2.0); }` : '';
425
+ const random = k.randomOffset ? ` + life.y * vec2(17.31, 7.97)` : '';
426
+ body.push(` { vec2 uv = uv0; ${polar}
427
+ uv = uv * uScale${i} - uScroll${i} * uTime${random};
428
+ float sa = sin(uSpin${i} * uTime + uTurn${i}), ca = cos(uSpin${i} * uTime + uTurn${i}); uv = mat2(ca, sa, -sa, ca) * (uv - 0.5) + 0.5;
429
+ float b = ${sourceCode(s, i, k.polar)};${k.invert ? ' b = 1.0 - b;' : ''}${k.levels ? ` b = smoothstep(uLevels${i}.x, uLevels${i}.y, b);` : ''}${isCurve(k.offset) || k.offset !== 0 ? ` b = clamp(b + ${value(`offset${i}`, `uOffset${i}`)}, 0.0, 1.0);` : ''}
430
+ ${i === 0 ? 'm = b;' : `float a = m; m = mix(a, ${BLEND_CODE[k.blend]}, clamp(${value(`strength${i}`, `uStrength${i}`)}, 0.0, 1.0));`} }`);
431
+ });
432
+ const code = `
433
+ uniform float uTime; uniform sampler2D uRamp; uniform sampler2D uCurves;
434
+ uniform float uDissolve; uniform float uThreshold; uniform float uSoftness; uniform float uPower; uniform float uOpacity; uniform float uEmission;
435
+ uniform vec3 uEdge; uniform vec3 uEdgeColor;
436
+ ${decl.join('\n')}
437
+ ${SHAPES}
438
+ float vfxCurve(float row, float t){ return texture2D(uCurves, vec2((clamp(t, 0.0, 1.0) * 255.0 + 0.5) / 256.0, (row + 0.5) / ${glslFloat(rows)})).r; }
439
+ vec4 vfxMaterial(vec2 uv0, vec2 life){
440
+ float m = 0.0;
441
+ ${body.join('\n')}
442
+ m = clamp(m, 0.0, 1.0);
443
+ float v = m - ${value('dissolve', 'uDissolve')};
444
+ float th = ${value('threshold', 'uThreshold')};
445
+ float alpha = pow(${m.ramp === 'linear' ? 'clamp((v - th) / max(uSoftness, 1e-4), 0.0, 1.0)' : 'smoothstep(th, th + max(uSoftness, 1e-4), v)'}, uPower);
446
+ vec4 ramp = texture2D(uRamp, vec2(clamp(v, 0.0, 1.0) * (255.0 / 256.0) + 0.5 / 256.0, 0.5));
447
+ vec3 rgb = ramp.rgb;
448
+ if (uEdge.x > 0.0) { float e = 1.0 - smoothstep(th, th + uEdge.x, v); rgb = mix(rgb, uEdgeColor * uEdge.y, e * step(th, v)); }
449
+ return vec4(rgb * max(0.0, ${value('emission', 'uEmission')}), ramp.a * alpha * clamp(${value('opacity', 'uOpacity')}, 0.0, 1.0));
450
+ }`;
451
+ return {
452
+ code, uniforms, images, alphaMode: m.alphaMode,
453
+ dispose() { for (const t of owned)
454
+ t.dispose(); for (const t of noise)
455
+ releaseNoiseTexture(t); },
456
+ };
457
+ }
458
+ // ------------------------------------------------------------------ presets
459
+ const noise = (p) => ({ ...noiseDefaults(), ...p });
460
+ const mask = (source, p = {}) => ({ ...maskDefaults(source), ...p });
461
+ const curve = (...points) => ({ overLife: { points, smooth: true } });
462
+ /**
463
+ * Starting points, so nobody begins from a blank material. Each is what one
464
+ * of the reference rebuilds needed (ADR-055), with the numbers rounded.
465
+ */
466
+ export const MATERIAL_PRESETS = {
467
+ softGlow: () => ({ ...materialDefaults(), masks: [mask(shapeSource('glow'))], emission: 2, color: { stops: [[0, '#ffffff', 1]] } }),
468
+ noiseSmoke: () => ({
469
+ ...materialDefaults(),
470
+ masks: [
471
+ mask(noise({ kind: 'perlin', fractal: 'fbm', octaves: 3, frequency: 6, warp: .25 }), { scale: [.6, .6], scroll: [0, .2], randomOffset: true }),
472
+ mask(noise({ kind: 'perlin', fractal: 'pingpong', octaves: 1, frequency: 10, pingpong: 1, seed: 3 }), { invert: true, scale: [.4, .5], scroll: [0, -.1], randomOffset: true, blend: 'dodge', strength: .76 }),
473
+ mask({ type: 'gradient', fill: 'radial', center: [.5, .5] }),
474
+ ],
475
+ threshold: 0, softness: 1, ramp: 'linear', power: 3, emission: 1.5, color: { stops: [[0, '#4b4b4b', 1]] },
476
+ }),
477
+ fireCore: () => ({
478
+ ...materialDefaults(),
479
+ masks: [
480
+ mask({ type: 'gradient', fill: 'radial', center: [.5, .5] }, { levels: [-.2, 1] }),
481
+ mask(noise({ kind: 'perlin', fractal: 'ridged', octaves: 3, frequency: 6, warp: .35 }), { scale: [.15, .6], scroll: [0, .4], randomOffset: true }),
482
+ ],
483
+ threshold: .3, softness: .2, emission: curve([0, 4], [.3, 1.4], [1, 1]),
484
+ color: { stops: [[0, '#ff3a1a', 1], [.6, '#ff8a1a', 1], [1, '#ffe08a', 1]] },
485
+ }),
486
+ dissolveBurst: () => ({
487
+ ...materialDefaults(),
488
+ masks: [mask(shapeSource('dot')), mask(noise({ kind: 'cellular', fractal: 'fbm', octaves: 3, frequency: 5 }), { randomOffset: true, blend: 'multiply' })],
489
+ dissolve: curve([0, 0], [1, .9]), softness: .08, edge: { width: .12, color: '#ffb347', emission: 4 },
490
+ color: { stops: [[0, '#5a2a10', 1], [1, '#ffe2b0', 1]] }, emission: 1.5,
491
+ }),
492
+ energyRing: () => ({
493
+ ...materialDefaults(),
494
+ masks: [
495
+ mask({ type: 'shape', shape: 'ring', softness: .6, points: 4, sharpness: .5, radius: .7, width: .25 }),
496
+ mask(noise({ kind: 'perlin', fractal: 'ridged', octaves: 2, frequency: 4 }), { polar: true, scroll: [0, -.8], blend: 'multiply', strength: .7 }),
497
+ ],
498
+ emission: 3, color: { stops: [[0, '#2a6cff', 1], [1, '#d6f0ff', 1]] },
499
+ }),
500
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umicat/three-sdk",
3
- "version": "1.36.0",
3
+ "version": "1.37.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",