@umicat/three-sdk 1.36.0 → 1.38.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.
@@ -0,0 +1,532 @@
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, 32] };
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', cutoff: .5,
43
+ rim: { strength: 0, power: 2, mode: 'edge' }, displace: { amount: 0, offset: .5 },
44
+ };
45
+ }
46
+ const isCurve = (a) => typeof a === 'object' && a !== null;
47
+ /** The value of an Animated number at life t (0..1). */
48
+ export function sampleAnimated(a, t) { return isCurve(a) ? sampleCurve(a.overLife, t) : a; }
49
+ /** Every image filename a material reads. */
50
+ export function materialTextures(m) {
51
+ return m.masks.flatMap((k) => k.source.type === 'image' ? [k.source.texture] : []);
52
+ }
53
+ const num = (v, min, max) => typeof v === 'number' && Number.isFinite(v) && v >= min && v <= max;
54
+ const known = (o, keys, at, fail) => { for (const k of Object.keys(o))
55
+ if (!keys.includes(k))
56
+ fail(`${at}.${k} is not a field here (expected ${keys.join(', ')})`); };
57
+ /**
58
+ * Fills omitted fields from the defaults, refuses unknown ones, checks
59
+ * ranges. `checkCurve` / `checkGradient` / `texturePattern` come from the
60
+ * document parser so the messages read the same.
61
+ */
62
+ export function parseMaterial(input, at, fail, h) {
63
+ if (!input || typeof input !== 'object' || Array.isArray(input))
64
+ return fail(`${at} must be an object`);
65
+ const base = materialDefaults();
66
+ known(input, Object.keys(base), at, fail);
67
+ const m = { ...base, ...input };
68
+ const animated = (v, a, min, max) => {
69
+ if (num(v, min, max))
70
+ return;
71
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
72
+ known(v, ['overLife'], a, fail);
73
+ h.checkCurve(v.overLife, `${a}.overLife`);
74
+ return;
75
+ }
76
+ fail(`${a} must be a number ${min}-${max}, or { overLife: { points: [[t, value], ...] } }`);
77
+ };
78
+ for (const [k, [min, max]] of Object.entries(ANIMATED_FIELDS))
79
+ animated(m[k], `${at}.${k}`, min, max);
80
+ if (!num(m.softness, 0, 1))
81
+ fail(`${at}.softness must be 0-1`);
82
+ if (m.ramp !== 'smooth' && m.ramp !== 'linear')
83
+ fail(`${at}.ramp must be "smooth" or "linear"`);
84
+ if (!num(m.power, .1, 8))
85
+ fail(`${at}.power must be 0.1-8`);
86
+ if (!m.edge || typeof m.edge !== 'object')
87
+ fail(`${at}.edge must be { width, color, emission }`);
88
+ m.edge = { ...base.edge, ...m.edge };
89
+ known(m.edge, ['width', 'color', 'emission'], `${at}.edge`, fail);
90
+ if (!num(m.edge.width, 0, 1))
91
+ fail(`${at}.edge.width must be 0-1`);
92
+ if (typeof m.edge.color !== 'string' || !/^#[0-9a-f]{6}$/i.test(m.edge.color))
93
+ fail(`${at}.edge.color must be #rrggbb`);
94
+ if (!num(m.edge.emission, 0, 16))
95
+ fail(`${at}.edge.emission must be 0-16`);
96
+ h.checkGradient(m.color, `${at}.color`);
97
+ if (!['blend', 'cutout', 'dither'].includes(m.alphaMode))
98
+ fail(`${at}.alphaMode must be "blend", "cutout" or "dither"`);
99
+ m.rim = { ...base.rim, ...m.rim };
100
+ known(m.rim, ['strength', 'power', 'mode'], `${at}.rim`, fail);
101
+ if (!num(m.rim.strength, 0, 1))
102
+ fail(`${at}.rim.strength must be 0-1`);
103
+ if (!num(m.rim.power, .25, 8))
104
+ fail(`${at}.rim.power must be 0.25-8`);
105
+ if (m.rim.mode !== 'edge' && m.rim.mode !== 'center')
106
+ fail(`${at}.rim.mode must be "edge" or "center"`);
107
+ m.displace = { ...base.displace, ...m.displace };
108
+ known(m.displace, ['amount', 'offset'], `${at}.displace`, fail);
109
+ animated(m.displace.amount, `${at}.displace.amount`, -5, 5);
110
+ if (!num(m.cutoff, 0, 1))
111
+ fail(`${at}.cutoff must be 0-1`);
112
+ if (!num(m.displace.offset, 0, 1))
113
+ fail(`${at}.displace.offset must be 0-1`);
114
+ if (!Array.isArray(m.masks) || m.masks.length > MATERIAL_LIMITS.masks)
115
+ fail(`${at}.masks must be a list of 0-${MATERIAL_LIMITS.masks} (none = solid)`);
116
+ m.masks = m.masks.map((raw, i) => {
117
+ const mat = `${at}.masks[${i}]`;
118
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
119
+ fail(`${mat} must be an object`);
120
+ const mb = maskDefaults();
121
+ known(raw, Object.keys(mb), mat, fail);
122
+ const k = { ...mb, ...raw };
123
+ const pair = (v, a, min, max) => { if (!Array.isArray(v) || v.length !== 2 || !v.every((x) => num(x, min, max)))
124
+ fail(`${a} must be [u, v], each ${min}-${max}`); };
125
+ pair(k.scale, `${mat}.scale`, -100, 100);
126
+ pair(k.scroll, `${mat}.scroll`, -100, 100);
127
+ if (!num(k.spin, -3600, 3600))
128
+ fail(`${mat}.spin must be -3600-3600`);
129
+ if (!num(k.rotation, -360, 360))
130
+ fail(`${mat}.rotation must be -360-360`);
131
+ animated(k.offset, `${mat}.offset`, -2, 2);
132
+ for (const b of ['polar', 'randomOffset', 'invert'])
133
+ if (typeof k[b] !== 'boolean')
134
+ fail(`${mat}.${b} must be a boolean`);
135
+ if (k.levels !== null) {
136
+ pair(k.levels, `${mat}.levels`, -2, 3);
137
+ if (k.levels[0] === k.levels[1])
138
+ fail(`${mat}.levels must be [lo, hi] with lo != hi, or null`);
139
+ }
140
+ if (!MASK_BLENDS.includes(k.blend))
141
+ fail(`${mat}.blend must be one of ${MASK_BLENDS.join(', ')}`);
142
+ animated(k.strength, `${mat}.strength`, 0, 1);
143
+ k.source = parseSource(k.source, `${mat}.source`, fail, h.texturePattern);
144
+ return k;
145
+ });
146
+ const curves = curveFields(m).length;
147
+ if (curves > MATERIAL_LIMITS.curves)
148
+ fail(`${at} animates ${curves} numbers over life, the limit is ${MATERIAL_LIMITS.curves}`);
149
+ return m;
150
+ }
151
+ function parseSource(s, at, fail, texturePattern) {
152
+ if (!s || typeof s !== 'object' || Array.isArray(s))
153
+ return fail(`${at} must be an object with a type`);
154
+ const type = s.type;
155
+ if (type === 'noise') {
156
+ const n = { ...noiseDefaults(), ...s };
157
+ known(n, Object.keys(noiseDefaults()), at, fail);
158
+ if (!['perlin', 'value', 'cellular', 'cellEdges'].includes(n.kind))
159
+ fail(`${at}.kind must be perlin, value, cellular or cellEdges`);
160
+ if (!['none', 'fbm', 'ridged', 'pingpong'].includes(n.fractal))
161
+ fail(`${at}.fractal must be none, fbm, ridged or pingpong`);
162
+ if (!num(n.octaves, 1, 6) || !Number.isInteger(n.octaves))
163
+ fail(`${at}.octaves must be a whole number 1-6`);
164
+ if (!num(n.frequency, 1, 64) || !Number.isInteger(n.frequency))
165
+ fail(`${at}.frequency must be a whole number 1-64 (cells across the tile; whole so it tiles)`);
166
+ if (!num(n.seed, 0, 1e6) || !Number.isInteger(n.seed))
167
+ fail(`${at}.seed must be a whole number 0-1000000`);
168
+ if (!num(n.pingpong, .5, 8))
169
+ fail(`${at}.pingpong must be 0.5-8`);
170
+ if (!num(n.warp, 0, 4))
171
+ fail(`${at}.warp must be 0-4`);
172
+ if (![64, 128, 256, 512].includes(n.size))
173
+ fail(`${at}.size must be 64, 128, 256 or 512`);
174
+ return n;
175
+ }
176
+ if (type === 'gradient') {
177
+ const g = { fill: 'radial', center: [.5, .5], width: .25, ...s };
178
+ known(g, ['type', 'fill', 'center', 'width'], at, fail);
179
+ if (!['linear', 'radial', 'square', 'band'].includes(g.fill))
180
+ fail(`${at}.fill must be linear, radial, square or band`);
181
+ if (!num(g.width, .001, 1))
182
+ fail(`${at}.width must be 0.001-1`);
183
+ if (!Array.isArray(g.center) || g.center.length !== 2 || !g.center.every((x) => num(x, -1, 2)))
184
+ fail(`${at}.center must be [u, v], each -1-2`);
185
+ return g;
186
+ }
187
+ if (type === 'shape') {
188
+ const g = { ...shapeSource(), ...s };
189
+ known(g, Object.keys(shapeSource()), at, fail);
190
+ if (!['dot', 'glow', 'star', 'ring'].includes(g.shape))
191
+ fail(`${at}.shape must be dot, glow, star or ring`);
192
+ for (const k of ['softness', 'sharpness', 'radius', 'width'])
193
+ if (!num(g[k], 0, 1))
194
+ fail(`${at}.${k} must be 0-1`);
195
+ if (!num(g.points, 3, 12) || !Number.isInteger(g.points))
196
+ fail(`${at}.points must be a whole number 3-12`);
197
+ return g;
198
+ }
199
+ if (type === 'image') {
200
+ const g = { channel: 'luma', ...s };
201
+ known(g, ['type', 'texture', 'channel'], at, fail);
202
+ if (typeof g.texture !== 'string' || !texturePattern.test(g.texture))
203
+ fail(`${at}.texture must be the filename of a png, webp or jpg image in the same folder (no path)`);
204
+ if (!['luma', 'r', 'a'].includes(g.channel))
205
+ fail(`${at}.channel must be luma, r or a`);
206
+ return g;
207
+ }
208
+ return fail(`${at}.type must be noise, gradient, shape or image`);
209
+ }
210
+ /** The animated numbers that are curves, in a fixed order: each gets one row of the curve texture. */
211
+ function curveFields(m) {
212
+ const out = [];
213
+ for (const k of Object.keys(ANIMATED_FIELDS)) {
214
+ const v = m[k];
215
+ if (isCurve(v))
216
+ out.push({ key: k, value: v });
217
+ }
218
+ if (isCurve(m.displace.amount))
219
+ out.push({ key: 'displace', value: m.displace.amount });
220
+ m.masks.forEach((k, i) => {
221
+ if (isCurve(k.strength))
222
+ out.push({ key: `strength${i}`, value: k.strength });
223
+ if (isCurve(k.offset))
224
+ out.push({ key: `offset${i}`, value: k.offset });
225
+ });
226
+ return out;
227
+ }
228
+ // ------------------------------------------------------------------ noise
229
+ function hash(x, y, seed) {
230
+ let h = Math.imul(x, 0x27d4eb2d) ^ Math.imul(y, 0x165667b1) ^ Math.imul(seed + 1, 0x9e3779b1);
231
+ h = Math.imul(h ^ (h >>> 15), 0x85ebca6b);
232
+ h ^= h >>> 13;
233
+ h = Math.imul(h, 0xc2b2ae35);
234
+ h ^= h >>> 16;
235
+ return (h >>> 0) / 4294967296;
236
+ }
237
+ const fade = (t) => t * t * t * (t * (t * 6 - 15) + 10);
238
+ const wrap = (i, n) => ((i % n) + n) % n;
239
+ /** One octave at (x, y) in cell units, periodic in `period` cells. Returns -1..1 (perlin) or 0..1 (the rest). */
240
+ function octave(kind, x, y, period, seed) {
241
+ const ix = Math.floor(x), iy = Math.floor(y), fx = x - ix, fy = y - iy;
242
+ if (kind === 'value' || kind === 'perlin') {
243
+ const corner = (cx, cy) => {
244
+ const hx = wrap(ix + cx, period), hy = wrap(iy + cy, period);
245
+ if (kind === 'value')
246
+ return hash(hx, hy, seed);
247
+ const a = hash(hx, hy, seed) * Math.PI * 2;
248
+ return Math.cos(a) * (fx - cx) + Math.sin(a) * (fy - cy);
249
+ };
250
+ const u = fade(fx), v = fade(fy);
251
+ const a = corner(0, 0) + (corner(1, 0) - corner(0, 0)) * u;
252
+ const b = corner(0, 1) + (corner(1, 1) - corner(0, 1)) * u;
253
+ // perlin: scaled to Godot's simplex spread (sd ~0.54, measured against an exported
254
+ // NoiseTexture2D) so a pingpong / ridged fold lands where Godot's does.
255
+ return kind === 'perlin' ? Math.max(-1, Math.min(1, (a + (b - a) * v) * Math.SQRT2 * 1.75)) : a + (b - a) * v;
256
+ }
257
+ let f1 = 9, f2 = 9;
258
+ for (let oy = -1; oy <= 1; oy++)
259
+ for (let ox = -1; ox <= 1; ox++) {
260
+ const hx = wrap(ix + ox, period), hy = wrap(iy + oy, period);
261
+ const px = ox + hash(hx, hy, seed) - fx, py = oy + hash(hx, hy, seed + 7919) - fy;
262
+ const d = Math.hypot(px, py);
263
+ if (d < f1) {
264
+ f2 = f1;
265
+ f1 = d;
266
+ }
267
+ else if (d < f2)
268
+ f2 = d;
269
+ }
270
+ return kind === 'cellular' ? Math.min(1, f1) : Math.min(1, f2 - f1);
271
+ }
272
+ /**
273
+ * The noise as `size * size` bytes, normalised to the full 0..255 range (as
274
+ * Godot's NoiseTexture2D does by default). Tileable: every octave is periodic
275
+ * in a whole number of cells. Deterministic per source.
276
+ */
277
+ export function generateNoise(n) {
278
+ const size = n.size, out = new Float32Array(size * size);
279
+ const octaves = n.fractal === 'none' ? 1 : n.octaves;
280
+ let lo = Infinity, hi = -Infinity;
281
+ for (let py = 0; py < size; py++)
282
+ for (let px = 0; px < size; px++) {
283
+ let sum = 0, amp = 1;
284
+ // Warp: offset the sample point by a periodic perlin pair at the base frequency, so it still tiles.
285
+ let ux = (px + .5) / size, uy = (py + .5) / size;
286
+ if (n.warp > 0) {
287
+ // Two octaves (2f, 4f): one octave alone leaves perlin's zero-at-every-lattice-point grid visible as pinches.
288
+ 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);
289
+ const wx = w(n.seed + 5003), wy = w(n.seed + 9001);
290
+ ux += wx * n.warp / n.frequency;
291
+ uy += wy * n.warp / n.frequency;
292
+ }
293
+ for (let o = 0; o < octaves; o++) {
294
+ const period = n.frequency << o;
295
+ let v = octave(n.kind, ux * period, uy * period, period, n.seed + o * 101);
296
+ if (n.kind !== 'perlin')
297
+ v = v * 2 - 1; // all -1..1 from here
298
+ if (n.fractal === 'ridged')
299
+ v = 1 - Math.abs(v) * 2;
300
+ else if (n.fractal === 'pingpong') {
301
+ const t = (v + 1) * n.pingpong;
302
+ const p = t - Math.floor(t * .5) * 2;
303
+ v = (p < 1 ? p : 2 - p) * 2 - 1;
304
+ }
305
+ sum += v * amp;
306
+ amp *= .5;
307
+ }
308
+ out[py * size + px] = sum;
309
+ if (sum < lo)
310
+ lo = sum;
311
+ if (sum > hi)
312
+ hi = sum;
313
+ }
314
+ const bytes = new Uint8Array(size * size), k = hi > lo ? 255 / (hi - lo) : 0;
315
+ for (let i = 0; i < out.length; i++)
316
+ bytes[i] = Math.round((out[i] - lo) * k);
317
+ return bytes;
318
+ }
319
+ // Shared across instances: a texture per distinct noise, freed when the last user lets go.
320
+ const noiseCache = new Map();
321
+ export function acquireNoiseTexture(n) {
322
+ const key = JSON.stringify([n.kind, n.fractal, n.octaves, n.frequency, n.seed, n.warp, n.pingpong, n.size]);
323
+ let hit = noiseCache.get(key);
324
+ if (!hit) {
325
+ const t = new T.DataTexture(generateNoise(n), n.size, n.size, T.RedFormat, T.UnsignedByteType);
326
+ t.wrapS = t.wrapT = T.RepeatWrapping;
327
+ t.magFilter = T.LinearFilter;
328
+ t.minFilter = T.LinearMipmapLinearFilter;
329
+ t.generateMipmaps = true;
330
+ t.needsUpdate = true;
331
+ t.name = `noise:${key}`;
332
+ hit = { texture: t, users: 0 };
333
+ noiseCache.set(key, hit);
334
+ }
335
+ hit.users++;
336
+ return hit.texture;
337
+ }
338
+ export function releaseNoiseTexture(t) {
339
+ for (const [key, hit] of noiseCache)
340
+ if (hit.texture === t) {
341
+ if (--hit.users <= 0) {
342
+ t.dispose();
343
+ noiseCache.delete(key);
344
+ }
345
+ return;
346
+ }
347
+ }
348
+ /** For tests: how many distinct noise textures are alive. */
349
+ export function noiseTexturesAlive() { return noiseCache.size; }
350
+ // ------------------------------------------------------------------ shader
351
+ /** 256 x 1 sRGB ramp of the gradient map. */
352
+ function gradientTexture(g) {
353
+ const w = 256, data = new Uint8Array(w * 4), c = [0, 0, 0, 0];
354
+ for (let i = 0; i < w; i++) {
355
+ sampleGradient(g, i / (w - 1), c);
356
+ for (let k = 0; k < 4; k++)
357
+ data[i * 4 + k] = Math.round(Math.min(1, Math.max(0, c[k])) * 255);
358
+ }
359
+ const t = new T.DataTexture(data, w, 1, T.RGBAFormat, T.UnsignedByteType);
360
+ t.colorSpace = T.SRGBColorSpace;
361
+ t.magFilter = t.minFilter = T.LinearFilter;
362
+ t.wrapS = t.wrapT = T.ClampToEdgeWrapping;
363
+ t.needsUpdate = true;
364
+ return t;
365
+ }
366
+ /** Every curve as a 256-wide row, sampled at the row's centre texels. */
367
+ function curveTexture(curves) {
368
+ const w = 256, rows = Math.max(1, curves.length), data = new Float32Array(w * rows);
369
+ curves.forEach((c, r) => { for (let i = 0; i < w; i++)
370
+ data[r * w + i] = sampleCurve(c.overLife, i / (w - 1)); });
371
+ const t = new T.DataTexture(data, w, rows, T.RedFormat, T.FloatType);
372
+ t.magFilter = t.minFilter = T.NearestFilter;
373
+ t.needsUpdate = true;
374
+ return t;
375
+ }
376
+ const glslFloat = (x) => { const s = String(x); return /[.e]/.test(s) ? s : s + '.0'; };
377
+ /** GLSL for one mask's raw value (before invert) at uv. */
378
+ function sourceCode(s, i, lod) {
379
+ const tex = (expr) => lod ? `textureLod(uMask${i}, ${expr}, 0.0)` : `texture2D(uMask${i}, ${expr})`;
380
+ switch (s.type) {
381
+ case 'noise': return `${tex('uv')}.r`;
382
+ 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)`;
383
+ case 'gradient': {
384
+ const c = `vec2(${glslFloat(s.center[0])}, ${glslFloat(s.center[1])})`;
385
+ if (s.fill === 'band')
386
+ return `clamp(1.0 - abs(fract(uv.x) - ${glslFloat(s.center[0])}) / ${glslFloat(s.width)}, 0.0, 1.0)`;
387
+ 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))`;
388
+ }
389
+ case 'shape': return `vfxShape${s.shape[0].toUpperCase()}${s.shape.slice(1)}(fract(uv) * 2.0 - 1.0, uShape${i})`;
390
+ }
391
+ }
392
+ const BLEND_CODE = {
393
+ add: 'a + b', subtract: 'a - b', multiply: 'a * b', min: 'min(a, b)', max: 'max(a, b)',
394
+ 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))',
395
+ hardLight: '(b < 0.5 ? 2.0 * a * b : 1.0 - 2.0 * (1.0 - a) * (1.0 - b))',
396
+ 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))',
397
+ dodge: 'a / max(1.0 - b, 1e-3)', burn: '1.0 - (1.0 - a) / max(b, 1e-3)', linearBurn: 'a + b - 1.0',
398
+ };
399
+ const SHAPES = `
400
+ // p in -1..1; params = (softness, points, sharpness, radius) and the ring width in uShapeW.
401
+ 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)); }
402
+ 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)); }
403
+ 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); }
404
+ 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); }
405
+ `;
406
+ export function compileMaterial(m) {
407
+ const curves = curveFields(m), row = new Map(curves.map((c, i) => [c.key, i]));
408
+ const rows = Math.max(1, curves.length);
409
+ const value = (key, uniform) => row.has(key) ? `vfxCurve(${glslFloat(row.get(key))}, life.x)` : uniform;
410
+ const uniforms = {
411
+ uTime: { value: 0 }, uRamp: { value: gradientTexture(m.color) }, uCurves: { value: curveTexture(curves.map((c) => c.value)) },
412
+ uDissolve: { value: isCurve(m.dissolve) ? 0 : m.dissolve }, uThreshold: { value: isCurve(m.threshold) ? 0 : m.threshold },
413
+ uSoftness: { value: m.softness }, uPower: { value: m.power }, uOpacity: { value: isCurve(m.opacity) ? 1 : m.opacity }, uEmission: { value: isCurve(m.emission) ? 1 : m.emission },
414
+ uEdge: { value: new T.Vector3(m.edge.width, m.edge.emission, 0) }, uEdgeColor: { value: new T.Color(m.edge.color) },
415
+ uRim: { value: new T.Vector3(m.rim.strength, m.rim.power, m.rim.mode === 'edge' ? 1 : 0) },
416
+ uDisplace: { value: new T.Vector2(isCurve(m.displace.amount) ? 1 : m.displace.amount, m.displace.offset) },
417
+ uCutoff: { value: m.cutoff },
418
+ };
419
+ const owned = [uniforms.uRamp.value, uniforms.uCurves.value];
420
+ const noise = [];
421
+ const images = new Map();
422
+ const decl = [];
423
+ const fns = [];
424
+ const body = [];
425
+ m.masks.forEach((k, i) => {
426
+ const s = k.source;
427
+ uniforms[`uScale${i}`] = { value: new T.Vector2(...k.scale) };
428
+ uniforms[`uScroll${i}`] = { value: new T.Vector2(...k.scroll) };
429
+ uniforms[`uSpin${i}`] = { value: k.spin * Math.PI / 180 };
430
+ uniforms[`uTurn${i}`] = { value: k.rotation * Math.PI / 180 };
431
+ uniforms[`uOffset${i}`] = { value: isCurve(k.offset) ? 0 : k.offset };
432
+ uniforms[`uStrength${i}`] = { value: isCurve(k.strength) ? 1 : k.strength };
433
+ uniforms[`uLevels${i}`] = { value: new T.Vector2(...(k.levels ?? [0, 1])) };
434
+ 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};`);
435
+ if (s.type === 'noise') {
436
+ const t = acquireNoiseTexture(s);
437
+ noise.push(t);
438
+ uniforms[`uMask${i}`] = { value: t };
439
+ decl.push(`uniform sampler2D uMask${i};`);
440
+ }
441
+ else if (s.type === 'image') {
442
+ uniforms[`uMask${i}`] = { value: null };
443
+ images.set(i, s.texture);
444
+ decl.push(`uniform sampler2D uMask${i};`);
445
+ }
446
+ else if (s.type === 'shape') {
447
+ uniforms[`uShape${i}`] = { value: new T.Vector4(s.softness, s.shape === 'ring' ? s.width : s.points, s.sharpness, s.radius) };
448
+ decl.push(`uniform vec4 uShape${i};`);
449
+ }
450
+ const polar = k.polar ? `{ vec2 c = uv0 - 0.5; uv = vec2(atan(c.x, c.y) / 6.2831853 + 0.5, length(c) * 2.0); }` : '';
451
+ const random = k.randomOffset ? ` + life.y * vec2(17.31, 7.97)` : '';
452
+ // One function per mask, so a vertex shader can call mask 0 for displacement.
453
+ fns.push(`float vfxMask${i}(vec2 uv0, vec2 life){ vec2 uv = uv0; ${polar}
454
+ uv = uv * uScale${i} - uScroll${i} * uTime${random};
455
+ 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;
456
+ 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);` : ''}
457
+ return b; }`);
458
+ body.push(i === 0 ? ' m = vfxMask0(uv0, life);' : ` { float a = m, b = vfxMask${i}(uv0, life); m = mix(a, ${BLEND_CODE[k.blend]}, clamp(${value(`strength${i}`, `uStrength${i}`)}, 0.0, 1.0)); }`);
459
+ });
460
+ const code = `
461
+ uniform float uTime; uniform sampler2D uRamp; uniform sampler2D uCurves;
462
+ uniform float uDissolve; uniform float uThreshold; uniform float uSoftness; uniform float uPower; uniform float uOpacity; uniform float uEmission;
463
+ uniform vec3 uEdge; uniform vec3 uEdgeColor; uniform vec3 uRim; uniform vec2 uDisplace; uniform float uCutoff;
464
+ ${decl.join('\n')}
465
+ ${SHAPES}
466
+ 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; }
467
+ ${fns.join('\n')}
468
+ ${m.masks.length ? `float vfxDisplace(vec2 uv, vec2 life){ return (vfxMask0(uv, life) - uDisplace.y) * ${value('displace', 'uDisplace.x')}; }` : 'float vfxDisplace(vec2 uv, vec2 life){ return 0.0; }'}
469
+ /** facing: |dot(normal, view)|, 1 for a camera-facing quad. */
470
+ vec4 vfxMaterial(vec2 uv0, vec2 life, float facing){
471
+ float m = ${m.masks.length ? '0.0' : '1.0'};
472
+ ${body.join('\n')}
473
+ m = clamp(m, 0.0, 1.0);
474
+ float v = m - ${value('dissolve', 'uDissolve')};
475
+ float th = ${value('threshold', 'uThreshold')};
476
+ 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);
477
+ vec4 ramp = texture2D(uRamp, vec2(clamp(v, 0.0, 1.0) * (255.0 / 256.0) + 0.5 / 256.0, 0.5));
478
+ vec3 rgb = ramp.rgb;
479
+ 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)); }
480
+ if (uRim.x > 0.0) { float f = pow(1.0 - clamp(facing, 0.0, 1.0), uRim.y); alpha *= mix(1.0, uRim.z > 0.5 ? f : 1.0 - f, uRim.x); }
481
+ return vec4(rgb * max(0.0, ${value('emission', 'uEmission')}), ramp.a * alpha * clamp(${value('opacity', 'uOpacity')}, 0.0, 1.0));
482
+ }`;
483
+ return {
484
+ code, uniforms, images, alphaMode: m.alphaMode, displace: m.masks.length > 0 && (isCurve(m.displace.amount) || m.displace.amount !== 0),
485
+ dispose() { for (const t of owned)
486
+ t.dispose(); for (const t of noise)
487
+ releaseNoiseTexture(t); },
488
+ };
489
+ }
490
+ // ------------------------------------------------------------------ presets
491
+ const noise = (p) => ({ ...noiseDefaults(), ...p });
492
+ const mask = (source, p = {}) => ({ ...maskDefaults(source), ...p });
493
+ const curve = (...points) => ({ overLife: { points, smooth: true } });
494
+ /**
495
+ * Starting points, so nobody begins from a blank material. Each is what one
496
+ * of the reference rebuilds needed (ADR-055), with the numbers rounded.
497
+ */
498
+ export const MATERIAL_PRESETS = {
499
+ softGlow: () => ({ ...materialDefaults(), masks: [mask(shapeSource('glow'))], emission: 2, color: { stops: [[0, '#ffffff', 1]] } }),
500
+ noiseSmoke: () => ({
501
+ ...materialDefaults(),
502
+ masks: [
503
+ mask(noise({ kind: 'perlin', fractal: 'fbm', octaves: 3, frequency: 6, warp: .25 }), { scale: [.6, .6], scroll: [0, .2], randomOffset: true }),
504
+ 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 }),
505
+ mask({ type: 'gradient', fill: 'radial', center: [.5, .5], width: .25 }),
506
+ ],
507
+ threshold: 0, softness: 1, ramp: 'linear', power: 3, emission: 1.5, color: { stops: [[0, '#4b4b4b', 1]] },
508
+ }),
509
+ fireCore: () => ({
510
+ ...materialDefaults(),
511
+ masks: [
512
+ mask({ type: 'gradient', fill: 'radial', center: [.5, .5], width: .25 }, { levels: [-.2, 1] }),
513
+ mask(noise({ kind: 'perlin', fractal: 'ridged', octaves: 3, frequency: 6, warp: .35 }), { scale: [.15, .6], scroll: [0, .4], randomOffset: true }),
514
+ ],
515
+ threshold: .3, softness: .2, emission: curve([0, 4], [.3, 1.4], [1, 1]),
516
+ color: { stops: [[0, '#ff3a1a', 1], [.6, '#ff8a1a', 1], [1, '#ffe08a', 1]] },
517
+ }),
518
+ dissolveBurst: () => ({
519
+ ...materialDefaults(),
520
+ masks: [mask(shapeSource('dot')), mask(noise({ kind: 'cellular', fractal: 'fbm', octaves: 3, frequency: 5 }), { randomOffset: true, blend: 'multiply' })],
521
+ dissolve: curve([0, 0], [1, .9]), softness: .08, edge: { width: .12, color: '#ffb347', emission: 4 },
522
+ color: { stops: [[0, '#5a2a10', 1], [1, '#ffe2b0', 1]] }, emission: 1.5,
523
+ }),
524
+ energyRing: () => ({
525
+ ...materialDefaults(),
526
+ masks: [
527
+ mask({ type: 'shape', shape: 'ring', softness: .6, points: 4, sharpness: .5, radius: .7, width: .25 }),
528
+ mask(noise({ kind: 'perlin', fractal: 'ridged', octaves: 2, frequency: 4 }), { polar: true, scroll: [0, -.8], blend: 'multiply', strength: .7 }),
529
+ ],
530
+ emission: 3, color: { stops: [[0, '#2a6cff', 1], [1, '#d6f0ff', 1]] },
531
+ }),
532
+ };
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Mesh layers and mesh-shaped particles (format v3, umicat-design ADR-055
3
+ * step 2). The shapes are Godot's primitive meshes with Godot's parameters,
4
+ * so a rebuild copies the numbers: QuadMesh faces +Z, PlaneMesh faces +Y,
5
+ * Cylinder / Sphere / Torus stand on the Y axis.
6
+ */
7
+ import * as T from 'three';
8
+ import type { Curve, Gradient, Vec3 } from './document.js';
9
+ import type { CompiledMaterial, Material } from './material.js';
10
+ export type MeshShape =
11
+ /** Upright card in the XY plane, facing +Z. */
12
+ {
13
+ type: 'quad';
14
+ size: [number, number];
15
+ }
16
+ /** Flat on the ground (XZ), facing up. */
17
+ | {
18
+ type: 'plane';
19
+ size: [number, number];
20
+ }
21
+ /** `height` other than 2 x radius squashes it (Godot SphereMesh). */
22
+ | {
23
+ type: 'sphere';
24
+ radius: number;
25
+ height: number;
26
+ hemisphere: boolean;
27
+ }
28
+ /** top 0 is a cone. `caps` false leaves it an open tube (most effect rings and columns). */
29
+ | {
30
+ type: 'cylinder';
31
+ top: number;
32
+ bottom: number;
33
+ height: number;
34
+ caps: boolean;
35
+ }
36
+ /** Lies flat, around Y (Godot TorusMesh). */
37
+ | {
38
+ type: 'torus';
39
+ inner: number;
40
+ outer: number;
41
+ } | {
42
+ type: 'box';
43
+ size: Vec3;
44
+ }
45
+ /** A flat annulus on the ground: a shockwave, a target circle. */
46
+ | {
47
+ type: 'ring';
48
+ inner: number;
49
+ outer: number;
50
+ };
51
+ export interface MeshLayer {
52
+ id: string;
53
+ enabled: boolean;
54
+ shape: MeshShape;
55
+ position: Vec3;
56
+ rotation: Vec3;
57
+ scale: Vec3;
58
+ /** none: as placed. camera: a quad or plane turned to face the viewer, keeping its position and size (other shapes ignore it). */
59
+ facing: 'none' | 'camera';
60
+ /** Seconds into each cycle it appears, and for how long (null: to the end of the cycle). */
61
+ start: number;
62
+ life: number | null;
63
+ /** Over the layer's own life (0 = start, 1 = end). Multiplies `scale`. */
64
+ scaleOverLife?: Curve;
65
+ color: string;
66
+ colorOverLife?: Gradient;
67
+ alphaOverLife?: Curve;
68
+ intensity: number;
69
+ blend: 'normal' | 'additive';
70
+ side: 'front' | 'back' | 'both';
71
+ material: Material;
72
+ }
73
+ export declare const MESH_SHAPES: Record<MeshShape['type'], () => MeshShape>;
74
+ type Fail = (why: string) => never;
75
+ /** Fills a shape's missing parameters from its defaults and checks them. */
76
+ export declare function parseMeshShape(raw: unknown, at: string, fail: Fail): MeshShape;
77
+ /**
78
+ * The geometry, built once per layer. Enough segments for vertex
79
+ * displacement to read as a surface (Binbun subdivides its cards 16x16 for the
80
+ * same reason).
81
+ */
82
+ export declare function meshGeometry(s: MeshShape): T.BufferGeometry;
83
+ /** Ring UVs from three.js are planar; an effect ring wants u around and v across, like a cylinder's. */
84
+ export declare function fixRingUv(g: T.BufferGeometry, s: MeshShape): T.BufferGeometry<T.NormalBufferAttributes, T.BufferGeometryEventMap>;
85
+ /** A mesh layer: one mesh, its colour and life from uniforms. */
86
+ export declare const meshLayerVertex: (c: CompiledMaterial) => string;
87
+ /**
88
+ * A mesh particle: the mesh, scaled by the particle's size, stood on a basis
89
+ * whose Y is the particle's velocity (align velocity), the emitter's axis
90
+ * (axis) or the emitter's own up (otherwise), and turned by its angle about
91
+ * that Y -- Godot's transform_align / rotate_y.
92
+ */
93
+ export declare const meshParticleVertex: (c: CompiledMaterial) => string;
94
+ /** Shared by mesh layers and mesh particles: the material, times the colour, with the alpha mode. */
95
+ export declare const meshFragment: (c: CompiledMaterial) => string;
96
+ export {};