@umicat/three-sdk 1.34.0 → 1.36.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,461 @@
1
+ /**
2
+ * The `.vfx.json` effect document: what the VFX Editor writes, what the agent
3
+ * writes, and what a game plays. Two kinds of layer:
4
+ *
5
+ * - `emitters`: particle systems modelled on Godot's ParticleProcessMaterial
6
+ * -- an emission shape, a direction cone, velocities and accelerations,
7
+ * random ranges, curves and gradients over each particle's life, a look
8
+ * (a procedural dot / glow / star, an image, or a sprite sheet), and
9
+ * sub-emitters. Design: umicat-design ADR-054.
10
+ * - `flipbooks`: a sprite sheet played frame by frame on one quad -- an
11
+ * explosion, a muzzle flash, a slash. The sheet is an IMAGE ASSET next to the
12
+ * effect, named by `texture`; the grid is `cols` x `rows`, read left to
13
+ * right, top to bottom, and the first `frames` cells are played.
14
+ *
15
+ * Version 2. A version-1 document (the upward-firing disc emitter of 1.35) is
16
+ * still accepted: `parseVfx` upgrades it to the v2 emitter that plays the same.
17
+ */
18
+ export const LIMITS = { emitters: 8, layers: 8, particles: 4000, cells: 4096, bursts: 16, children: 4, curvePoints: 8, gradientStops: 16 };
19
+ /** Every emitter field's value when a document leaves it out. */
20
+ export function emitterDefaults() {
21
+ return {
22
+ enabled: true, rate: 20, bursts: [], start: 0, stop: null, lifetime: 1.5, space: 'local',
23
+ shape: { type: 'point' }, shapeOffset: [0, 0, 0], shapeScale: [1, 1, 1], rotation: [0, 0, 0],
24
+ direction: [0, 1, 0], spread: 15, flatness: 0, speed: 1, randomVelocity: [0, 0, 0], gravity: [0, 0, 0],
25
+ radialSpeed: 0, radialAccel: 0, tangentialAccel: 0, orbit: 0, damping: 0,
26
+ angle: 0, spin: 0, size: .2,
27
+ color: { stops: [[0, '#ffffff', 1]] }, intensity: 1,
28
+ look: { type: 'dot', softness: .5 }, align: 'camera', stretch: 0, blend: 'normal', children: [],
29
+ };
30
+ }
31
+ /** A new particle layer: the defaults, plus a fade-out so it reads as particles at once. */
32
+ export function emitterLayer(id, patch = {}) {
33
+ return { id, ...emitterDefaults(), alphaOverLife: { points: [[0, 0], [.1, 1], [1, 0]] }, ...patch };
34
+ }
35
+ export function campfire() {
36
+ return upgradeV1({ version: 1, name: 'Campfire', seed: 17, duration: 4, loop: true, humanCurated: false, emitters: [
37
+ { id: 'flame', enabled: true, rate: 55, lifetime: 1.1, speed: 1.3, spread: .25, gravity: .3, size: .28, endSize: .02, opacity: .8, color: '#ff9b32', endColor: '#e93616', blend: 'additive' },
38
+ { id: 'embers', enabled: true, rate: 10, lifetime: 2, speed: 1.8, spread: .45, gravity: -.25, size: .035, endSize: .005, opacity: 1, color: '#ffce72', endColor: '#fa5214', blend: 'additive' },
39
+ { id: 'smoke', enabled: true, rate: 12, lifetime: 3.5, speed: .55, spread: .2, gravity: .1, size: .18, endSize: .8, opacity: .12, color: '#777b85', endColor: '#333943', blend: 'normal' }
40
+ ] });
41
+ }
42
+ /**
43
+ * A version-1 document as the v2 document that plays the same: same spawn
44
+ * disc, speeds, jitter, gravity, colour, size and alpha over life. (Not
45
+ * bit-identical -- random numbers are drawn in a different order -- but the
46
+ * same effect.) v1 `size` was a point RADIUS; v2 `size` is the width.
47
+ */
48
+ export function upgradeV1(v1) {
49
+ const emitters = v1.emitters.map((e) => ({
50
+ ...emitterDefaults(), id: e.id, enabled: e.enabled, rate: e.rate, lifetime: e.lifetime,
51
+ shape: { type: 'ring', radius: .15, inner: 0, height: 0, axis: [0, 1, 0] },
52
+ direction: [0, 1, 0], spread: 0, speed: [e.speed * .8, e.speed * 1.2],
53
+ randomVelocity: [e.spread / 2, 0, e.spread / 2], gravity: [0, e.gravity, 0],
54
+ size: e.size * 2, sizeOverLife: { points: [[0, 1], [1, e.size > 0 ? e.endSize / e.size : 1]] },
55
+ color: { stops: [[0, '#ffffff', 1]] }, colorOverLife: { stops: [[0, e.color, 1], [1, e.endColor, 1]] },
56
+ alphaOverLife: { points: [[0, 0], [.125, .875 * e.opacity], [1, 0]] },
57
+ look: { type: 'dot', softness: .5 }, blend: e.blend,
58
+ }));
59
+ const doc = { version: 2, name: v1.name, seed: v1.seed, duration: v1.duration, loop: v1.loop, humanCurated: v1.humanCurated, emitters };
60
+ if (v1.flipbooks !== undefined)
61
+ doc.flipbooks = v1.flipbooks;
62
+ return doc;
63
+ }
64
+ /** Per-flipbook numeric fields and their allowed ranges. `frames` is further capped at cols x rows. */
65
+ export const FLIPBOOK_RANGES = [['cols', 1, 64], ['rows', 1, 64], ['frames', 1, 4096], ['fps', 1, 120], ['delay', 0, 60], ['size', .01, 50], ['originU', 0, 1], ['originV', 0, 1], ['opacity', 0, 1]];
66
+ const INTEGER_FIELDS = new Set(['cols', 'rows', 'frames']);
67
+ /** A bare filename with an image extension: no folders, so it can only name a sibling of the effect. */
68
+ export const TEXTURE_PATTERN = /^[^/\\?#]{1,200}\.(png|webp|jpe?g)$/i;
69
+ /** Numeric emitter fields that take a `Range`, with their allowed bounds. Shared with the editor's inputs. */
70
+ export const EMITTER_RANGES = {
71
+ lifetime: [.01, 30], speed: [-1000, 1000], radialSpeed: [-100, 100], radialAccel: [-1000, 1000],
72
+ tangentialAccel: [-1000, 1000], orbit: [-100, 100], damping: [0, 1000], angle: [-3600, 3600],
73
+ spin: [-36000, 36000], size: [0, 100],
74
+ };
75
+ /** Plain numeric emitter fields and their bounds. */
76
+ export const EMITTER_NUMBERS = {
77
+ rate: [0, 1000], start: [0, 60], spread: [0, 180], flatness: [0, 1], intensity: [0, 16], stretch: [0, 10],
78
+ };
79
+ /** Vector emitter fields and the bound on each component. */
80
+ export const EMITTER_VECTORS = {
81
+ shapeOffset: [-100, 100], shapeScale: [-100, 100], rotation: [-360, 360], direction: [-1000, 1000], randomVelocity: [0, 100], gravity: [-100, 100],
82
+ };
83
+ export const CURVE_FIELDS = ['speedLimit', 'radialAccelOverLife', 'orbitOverLife', 'sizeOverLife', 'alphaOverLife'];
84
+ /** A new flipbook layer with sensible defaults, for the editor's "Add" and for the agent. */
85
+ export function flipbookLayer(id, texture) {
86
+ return { id, enabled: true, texture, cols: 4, rows: 4, frames: 16, fps: 24, loop: true, delay: 0, size: 1.5, originU: .5, originV: .5, facing: 'camera', opacity: 1, color: '#ffffff', blend: 'additive' };
87
+ }
88
+ /** Every texture filename a document needs (flipbook sheets and particle images), once each. */
89
+ export function vfxTextures(document) {
90
+ const names = (document.flipbooks ?? []).map((f) => f.texture);
91
+ for (const e of document.emitters)
92
+ if (e.look.type === 'texture' || e.look.type === 'sheet')
93
+ names.push(e.look.texture);
94
+ return [...new Set(names)];
95
+ }
96
+ // ---------------------------------------------------------------- sampling
97
+ /** The value of a Range for one random number u in [0, 1). */
98
+ export function pickRange(r, u) { return typeof r === 'number' ? r : r[0] + (r[1] - r[0]) * u; }
99
+ export function rangeMax(r) { return typeof r === 'number' ? r : Math.max(r[0], r[1]); }
100
+ /** Curve value at t (0..1). Monotone cubic (Fritsch-Carlson) when `smooth`, so it never overshoots its points. */
101
+ export function sampleCurve(c, t) {
102
+ const p = c.points, n = p.length;
103
+ if (t <= p[0][0])
104
+ return p[0][1];
105
+ if (t >= p[n - 1][0])
106
+ return p[n - 1][1];
107
+ let i = 0;
108
+ while (i < n - 2 && t > p[i + 1][0])
109
+ i++;
110
+ const [x0, y0] = p[i], [x1, y1] = p[i + 1], h = x1 - x0;
111
+ if (h <= 0)
112
+ return y1;
113
+ const s = (t - x0) / h;
114
+ if (!c.smooth)
115
+ return y0 + (y1 - y0) * s;
116
+ const slope = (a) => (p[a + 1][1] - p[a][1]) / Math.max(1e-9, p[a + 1][0] - p[a][0]);
117
+ const tangent = (k) => {
118
+ if (k === 0)
119
+ return slope(0);
120
+ if (k === n - 1)
121
+ return slope(n - 2);
122
+ const a = slope(k - 1), b = slope(k);
123
+ return a * b <= 0 ? 0 : 3 * (p[k + 1][0] - p[k - 1][0]) / ((2 * p[k + 1][0] - p[k][0] - p[k - 1][0]) / a + (p[k + 1][0] + p[k][0] - 2 * p[k - 1][0]) / b);
124
+ };
125
+ const m0 = tangent(i) * h, m1 = tangent(i + 1) * h, s2 = s * s, s3 = s2 * s;
126
+ return (2 * s3 - 3 * s2 + 1) * y0 + (s3 - 2 * s2 + s) * m0 + (-2 * s3 + 3 * s2) * y1 + (s3 - s2) * m1;
127
+ }
128
+ const hex = (h, k) => parseInt(h.slice(1 + k * 2, 3 + k * 2), 16) / 255;
129
+ /** Gradient at t, written into out as [r, g, b, a] (sRGB components 0..1). */
130
+ export function sampleGradient(g, t, out = [0, 0, 0, 0]) {
131
+ const s = g.stops, n = s.length;
132
+ let a = s[0], b = s[0], f = 0;
133
+ if (t >= s[n - 1][0]) {
134
+ a = b = s[n - 1];
135
+ }
136
+ else if (t > s[0][0]) {
137
+ let i = 0;
138
+ while (i < n - 2 && t > s[i + 1][0])
139
+ i++;
140
+ a = s[i];
141
+ b = s[i + 1];
142
+ f = b[0] > a[0] ? (t - a[0]) / (b[0] - a[0]) : 1;
143
+ }
144
+ for (let k = 0; k < 3; k++)
145
+ out[k] = hex(a[1], k) + (hex(b[1], k) - hex(a[1], k)) * f;
146
+ out[3] = a[2] + (b[2] - a[2]) * f;
147
+ return out;
148
+ }
149
+ // ---------------------------------------------------------------- validation
150
+ /**
151
+ * Reject malformed/unsupported resources instead of silently rewriting them.
152
+ * The message names the field and its allowed range: the agent writes these
153
+ * documents by hand, and "Invalid VFX resource" gave it nothing to fix.
154
+ *
155
+ * Returns a COMPLETE copy: a version-1 document is upgraded, and emitter
156
+ * fields left out take `emitterDefaults()`.
157
+ */
158
+ export function parseVfx(value) {
159
+ const fail = (why) => { throw new Error(`Invalid VFX resource: ${why}`); };
160
+ if (!value || typeof value !== 'object')
161
+ return fail('not an object');
162
+ const raw = value;
163
+ if (raw.version === 1) {
164
+ checkV1(value, fail);
165
+ return parseVfx(upgradeV1(structuredClone(value)));
166
+ }
167
+ const d = structuredClone(value);
168
+ const number = (v, min, max) => typeof v === 'number' && Number.isFinite(v) && v >= min && v <= max;
169
+ 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)');
172
+ if (typeof d.name !== 'string' || !d.name.trim() || d.name.length > 80)
173
+ fail('name must be 1-80 characters');
174
+ if (!number(d.seed, 1, 2147483646) || !Number.isInteger(d.seed))
175
+ fail('seed must be an integer 1-2147483646');
176
+ if (!number(d.duration, .02, 60))
177
+ fail('duration must be 0.02-60');
178
+ if (typeof d.loop !== 'boolean')
179
+ fail('loop must be a boolean');
180
+ if (typeof d.humanCurated !== 'boolean')
181
+ fail('humanCurated must be a boolean');
182
+ if (!Array.isArray(d.emitters) || d.emitters.length > LIMITS.emitters)
183
+ fail(`emitters must be a list of 0-${LIMITS.emitters} layers`);
184
+ if (d.flipbooks !== undefined && !Array.isArray(d.flipbooks))
185
+ fail('flipbooks must be a list');
186
+ const flipbooks = d.flipbooks ?? [];
187
+ const layers = d.emitters.length + flipbooks.length;
188
+ if (layers < 1 || layers > LIMITS.layers)
189
+ fail(`an effect needs 1-${LIMITS.layers} layers (emitters + flipbooks), it has ${layers}`);
190
+ const ids = new Set();
191
+ const checkId = (id, at) => {
192
+ if (typeof id !== 'string' || !/^[a-z0-9_-]{1,40}$/i.test(id))
193
+ fail(`${at}.id must be 1-40 of a-z 0-9 _ -`);
194
+ if (ids.has(id))
195
+ fail(`${at}.id "${id}" is used twice`);
196
+ ids.add(id);
197
+ };
198
+ const checkRange = (v, at, min, max) => {
199
+ if (number(v, min, max))
200
+ return;
201
+ if (Array.isArray(v) && v.length === 2 && number(v[0], min, max) && number(v[1], min, max) && v[0] <= v[1])
202
+ return;
203
+ fail(`${at} must be a number ${min}-${max}, or [min, max] within that`);
204
+ };
205
+ const checkVec = (v, at, min, max) => {
206
+ if (!Array.isArray(v) || v.length !== 3 || !v.every((x) => number(x, min, max)))
207
+ fail(`${at} must be [x, y, z], each ${min}-${max}`);
208
+ };
209
+ const checkCurve = (v, at) => {
210
+ const c = v;
211
+ if (!c || typeof c !== 'object' || !Array.isArray(c.points) || c.points.length < 1 || c.points.length > LIMITS.curvePoints)
212
+ fail(`${at} must be { points: [[t, value], ...] } with 1-${LIMITS.curvePoints} points`);
213
+ c.points.forEach((p, i) => {
214
+ if (!Array.isArray(p) || p.length !== 2 || !number(p[0], 0, 1) || !number(p[1], -1000, 1000))
215
+ fail(`${at}.points[${i}] must be [t 0-1, value -1000-1000]`);
216
+ if (i > 0 && p[0] < c.points[i - 1][0])
217
+ fail(`${at}.points must be in increasing t`);
218
+ });
219
+ if (c.smooth !== undefined && typeof c.smooth !== 'boolean')
220
+ fail(`${at}.smooth must be a boolean`);
221
+ };
222
+ const checkGradient = (v, at) => {
223
+ const g = v;
224
+ if (!g || typeof g !== 'object' || !Array.isArray(g.stops) || g.stops.length < 1 || g.stops.length > LIMITS.gradientStops)
225
+ fail(`${at} must be { stops: [[t, "#rrggbb", alpha], ...] } with 1-${LIMITS.gradientStops} stops`);
226
+ g.stops.forEach((s, i) => {
227
+ if (!Array.isArray(s) || s.length !== 3 || !number(s[0], 0, 1) || !color(s[1]) || !number(s[2], 0, 1))
228
+ fail(`${at}.stops[${i}] must be [t 0-1, "#rrggbb", alpha 0-1]`);
229
+ if (i > 0 && s[0] < g.stops[i - 1][0])
230
+ fail(`${at}.stops must be in increasing t`);
231
+ });
232
+ };
233
+ const emitterIds = new Set();
234
+ d.emitters = d.emitters.map((input, i) => {
235
+ const at = `emitters[${i}]`;
236
+ if (!input || typeof input !== 'object' || Array.isArray(input))
237
+ fail(`${at} is not an object`);
238
+ checkId(input.id, at);
239
+ emitterIds.add(input.id);
240
+ const known = new Set(['id', ...Object.keys(emitterDefaults()), ...CURVE_FIELDS, 'colorOverLife']);
241
+ for (const key of Object.keys(input))
242
+ if (!known.has(key))
243
+ fail(`${at}.${key} is not an emitter field (a version-1 field? set "version": 1, or see emitterDefaults())`);
244
+ const e = { ...emitterDefaults(), ...input };
245
+ if (typeof e.enabled !== 'boolean')
246
+ fail(`${at}.enabled must be a boolean`);
247
+ for (const [key, [min, max]] of Object.entries(EMITTER_NUMBERS))
248
+ if (!number(e[key], min, max))
249
+ fail(`${at}.${key} must be ${min}-${max}`);
250
+ for (const [key, [min, max]] of Object.entries(EMITTER_RANGES))
251
+ checkRange(e[key], `${at}.${key}`, min, max);
252
+ for (const [key, [min, max]] of Object.entries(EMITTER_VECTORS))
253
+ checkVec(e[key], `${at}.${key}`, min, max);
254
+ if (typeof e.lifetime === 'number' ? e.lifetime < .01 : e.lifetime[0] < .01)
255
+ fail(`${at}.lifetime must be at least 0.01`);
256
+ if (e.stop !== null && !(number(e.stop, 0, 60) && e.stop > e.start))
257
+ fail(`${at}.stop must be null or a time after start (${e.start}), up to 60`);
258
+ if (!Array.isArray(e.bursts) || e.bursts.length > LIMITS.bursts)
259
+ fail(`${at}.bursts must be a list of 0-${LIMITS.bursts}`);
260
+ e.bursts.forEach((b, k) => {
261
+ if (!b || !number(b.time, 0, 60) || !number(b.count, 1, 1000) || !Number.isInteger(b.count) || !number(b.over, 0, 60))
262
+ fail(`${at}.bursts[${k}] must be { time 0-60, count 1-1000 whole, over 0-60 }`);
263
+ });
264
+ if (!['local', 'world'].includes(e.space))
265
+ fail(`${at}.space must be "local" or "world"`);
266
+ const s = e.shape;
267
+ const sat = `${at}.shape`;
268
+ if (!s || typeof s !== 'object')
269
+ fail(`${sat} must be an object with a type`);
270
+ else if (s.type === 'point') { /* nothing */ }
271
+ else if (s.type === 'sphere') {
272
+ if (!number(s.radius, 0, 100))
273
+ fail(`${sat}.radius must be 0-100`);
274
+ if (typeof s.surface !== 'boolean')
275
+ fail(`${sat}.surface must be a boolean`);
276
+ }
277
+ else if (s.type === 'box')
278
+ checkVec(s.extents, `${sat}.extents`, 0, 100);
279
+ else if (s.type === 'ring') {
280
+ if (!number(s.radius, 0, 100))
281
+ fail(`${sat}.radius must be 0-100`);
282
+ if (!number(s.inner, 0, s.radius))
283
+ fail(`${sat}.inner must be 0-radius (${s.radius})`);
284
+ if (!number(s.height, 0, 100))
285
+ fail(`${sat}.height must be 0-100`);
286
+ checkVec(s.axis, `${sat}.axis`, -1, 1);
287
+ if (Math.hypot(...s.axis) < 1e-6)
288
+ fail(`${sat}.axis must not be [0, 0, 0]`);
289
+ }
290
+ else
291
+ fail(`${sat}.type must be point, sphere, box or ring`);
292
+ for (const key of CURVE_FIELDS)
293
+ if (e[key] !== undefined)
294
+ checkCurve(e[key], `${at}.${key}`);
295
+ checkGradient(e.color, `${at}.color`);
296
+ if (e.colorOverLife !== undefined)
297
+ checkGradient(e.colorOverLife, `${at}.colorOverLife`);
298
+ const l = e.look, lat = `${at}.look`;
299
+ if (!l || typeof l !== 'object')
300
+ fail(`${lat} must be an object with a type`);
301
+ else if (l.type === 'dot') {
302
+ if (!number(l.softness, 0, 1))
303
+ fail(`${lat}.softness must be 0-1`);
304
+ }
305
+ else if (l.type === 'glow') { /* nothing */ }
306
+ else if (l.type === 'star') {
307
+ if (!number(l.points, 3, 12) || !Number.isInteger(l.points))
308
+ fail(`${lat}.points must be a whole number 3-12`);
309
+ if (!number(l.sharpness, 0, 1))
310
+ fail(`${lat}.sharpness must be 0-1`);
311
+ }
312
+ else if (l.type === 'texture' || l.type === 'sheet') {
313
+ if (typeof l.texture !== 'string' || !TEXTURE_PATTERN.test(l.texture))
314
+ fail(`${lat}.texture must be the filename of a png, webp or jpg image in the same folder (no path)`);
315
+ if (l.type === 'sheet') {
316
+ for (const k of ['cols', 'rows', 'frames'])
317
+ if (!number(l[k], 1, k === 'frames' ? 4096 : 64) || !Number.isInteger(l[k]))
318
+ fail(`${lat}.${k} must be a whole number 1-${k === 'frames' ? 4096 : 64}`);
319
+ if (l.frames > l.cols * l.rows)
320
+ fail(`${lat}.frames is ${l.frames} but a ${l.cols}x${l.rows} grid has only ${l.cols * l.rows} cells`);
321
+ if (l.fps !== 'life' && !number(l.fps, 1, 120))
322
+ fail(`${lat}.fps must be 1-120 or "life"`);
323
+ }
324
+ }
325
+ else
326
+ fail(`${lat}.type must be dot, glow, star, texture or sheet`);
327
+ if (!['camera', 'velocity', 'ground', 'axis'].includes(e.align))
328
+ fail(`${at}.align must be "camera", "velocity", "ground" or "axis"`);
329
+ if (!['normal', 'additive'].includes(e.blend))
330
+ fail(`${at}.blend must be "normal" or "additive"`);
331
+ if (!Array.isArray(e.children) || e.children.length > LIMITS.children)
332
+ fail(`${at}.children must be a list of 0-${LIMITS.children}`);
333
+ return e;
334
+ });
335
+ // Sub-emitters: a real emitter, not itself, no loops.
336
+ const childrenOf = new Map(d.emitters.map((e) => [e.id, e.children.map((c) => c.emitter)]));
337
+ d.emitters.forEach((e, i) => e.children.forEach((c, k) => {
338
+ const at = `emitters[${i}].children[${k}]`;
339
+ if (!c || typeof c !== 'object')
340
+ fail(`${at} is not an object`);
341
+ if (!emitterIds.has(c.emitter))
342
+ fail(`${at}.emitter "${c.emitter}" is not an emitter in this effect`);
343
+ if (!['birth', 'life', 'death'].includes(c.when))
344
+ fail(`${at}.when must be "birth", "life" or "death"`);
345
+ if (!number(c.count, 0, 100) || !Number.isInteger(c.count))
346
+ fail(`${at}.count must be a whole number 0-100`);
347
+ if (!number(c.rate, 0, 240))
348
+ fail(`${at}.rate must be 0-240`);
349
+ if (typeof c.inheritVelocity !== 'boolean')
350
+ fail(`${at}.inheritVelocity must be a boolean`);
351
+ }));
352
+ const visiting = new Set(), done = new Set();
353
+ const walk = (id) => {
354
+ if (done.has(id))
355
+ return;
356
+ if (visiting.has(id))
357
+ fail(`emitter "${id}" spawns itself through its children`);
358
+ visiting.add(id);
359
+ for (const c of childrenOf.get(id) ?? [])
360
+ walk(c);
361
+ visiting.delete(id);
362
+ done.add(id);
363
+ };
364
+ for (const id of emitterIds)
365
+ walk(id);
366
+ const budget = particleBudget(d);
367
+ if (budget > LIMITS.particles)
368
+ fail(`too many live particles: the most this effect can have alive at once is about ${Math.ceil(budget)} (rate x lifetime + bursts, times sub-emitters), the limit is ${LIMITS.particles}`);
369
+ flipbooks.forEach((f, i) => {
370
+ const at = `flipbooks[${i}]`;
371
+ if (!f || typeof f !== 'object')
372
+ fail(`${at} is not an object`);
373
+ checkId(f.id, at);
374
+ if (typeof f.enabled !== 'boolean')
375
+ fail(`${at}.enabled must be a boolean`);
376
+ if (typeof f.texture !== 'string' || !TEXTURE_PATTERN.test(f.texture))
377
+ fail(`${at}.texture must be the filename of a png, webp or jpg image in the same folder (no path)`);
378
+ for (const [key, min, max] of FLIPBOOK_RANGES) {
379
+ if (!number(f[key], min, max))
380
+ fail(`${at}.${key} must be ${min}-${max}`);
381
+ if (INTEGER_FIELDS.has(key) && !Number.isInteger(f[key]))
382
+ fail(`${at}.${key} must be a whole number`);
383
+ }
384
+ if (f.frames > f.cols * f.rows)
385
+ fail(`${at}.frames is ${f.frames} but a ${f.cols}x${f.rows} grid has only ${f.cols * f.rows} cells`);
386
+ if (typeof f.loop !== 'boolean')
387
+ fail(`${at}.loop must be a boolean`);
388
+ if (f.facing !== 'camera' && f.facing !== 'ground')
389
+ fail(`${at}.facing must be "camera" or "ground"`);
390
+ if (!color(f.color))
391
+ fail(`${at}.color must be #rrggbb`);
392
+ if (f.blend !== 'normal' && f.blend !== 'additive')
393
+ fail(`${at}.blend must be "normal" or "additive"`);
394
+ });
395
+ return d;
396
+ }
397
+ /**
398
+ * The most particles an effect can have alive at once, estimated: per enabled
399
+ * emitter, rate x longest life plus every burst, and for sub-emitters, the
400
+ * parent's count times what each parent particle spawns.
401
+ */
402
+ export function particleBudget(d) {
403
+ const byId = new Map(d.emitters.map((e) => [e.id, e]));
404
+ const isChild = new Set(d.emitters.flatMap((e) => e.children.map((c) => c.emitter)));
405
+ const live = new Map();
406
+ const own = (e) => isChild.has(e.id) ? 0 : e.rate * rangeMax(e.lifetime) + e.bursts.reduce((s, b) => s + b.count, 0);
407
+ const total = (id, seen = new Set()) => {
408
+ if (live.has(id))
409
+ return live.get(id);
410
+ const e = byId.get(id);
411
+ if (!e || !e.enabled || seen.has(id))
412
+ return 0;
413
+ seen.add(id);
414
+ let n = own(e);
415
+ for (const parent of d.emitters)
416
+ for (const c of parent.children)
417
+ if (c.emitter === id && parent.enabled) {
418
+ n += total(parent.id, seen) * (c.when === 'life' ? c.rate * rangeMax(e.lifetime) : c.count);
419
+ }
420
+ live.set(id, n);
421
+ return n;
422
+ };
423
+ return d.emitters.reduce((s, e) => s + total(e.id), 0);
424
+ }
425
+ function checkV1(d, fail) {
426
+ if (!Array.isArray(d.emitters))
427
+ fail('emitters must be a list');
428
+ const fields = ['rate', 'lifetime', 'speed', 'spread', 'gravity', 'size', 'endSize', 'opacity'];
429
+ d.emitters.forEach((e, i) => {
430
+ if (!e || typeof e !== 'object')
431
+ fail(`emitters[${i}] is not an object`);
432
+ for (const k of fields)
433
+ if (typeof e[k] !== 'number')
434
+ fail(`emitters[${i}].${k} must be a number (version 1)`);
435
+ for (const k of ['color', 'endColor'])
436
+ if (typeof e[k] !== 'string' || !/^#[0-9a-f]{6}$/i.test(e[k]))
437
+ fail(`emitters[${i}].${k} must be #rrggbb`);
438
+ });
439
+ }
440
+ /** An effect is a project ASSET named `<stem>.vfx.json`; the server keeps the
441
+ * whole compound extension, so this suffix is what marks one. */
442
+ export const VFX_SUFFIX = '.vfx.json';
443
+ export function isVfxFilename(filename) { return filename.toLowerCase().endsWith(VFX_SUFFIX) && filename.length > VFX_SUFFIX.length; }
444
+ /**
445
+ * A filename for a NEW effect, shaped the way the server's sanitizer will keep
446
+ * it (lowercase ASCII letters, digits, `-` and `_`) and free in this project.
447
+ *
448
+ * It has to be free client-side: an upload whose name the project already
449
+ * holds REPLACES that file -- that is the intended behaviour for re-uploading
450
+ * your own asset, and silent data loss for "New effect" twice in a row.
451
+ * A name with no ASCII in it (any CJK name) becomes `effect`.
452
+ */
453
+ export function vfxFilename(name, taken) {
454
+ const stem = (name.normalize('NFKD').toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/[-_]{2,}/g, '-').replace(/^[-_.]+|[-_.]+$/g, '').slice(0, 60).replace(/[-_.]+$/, '')) || 'effect';
455
+ const used = new Set(Array.from(taken, (f) => f.toLowerCase()));
456
+ for (let i = 1;; i++) {
457
+ const f = `${stem}${i === 1 ? '' : '-' + i}${VFX_SUFFIX}`;
458
+ if (!used.has(f))
459
+ return f;
460
+ }
461
+ }
@@ -0,0 +1,6 @@
1
+ export * from './document.js';
2
+ export * from './templates.js';
3
+ export { VfxInstance } from './VfxInstance.js';
4
+ export type { VfxInstanceOptions, VfxTextureSource } from './VfxInstance.js';
5
+ export { loadVfx, VfxEffect, siblingUrl, prepareSheetTexture } from './load.js';
6
+ export type { LoadVfxOptions } from './load.js';
@@ -0,0 +1,9 @@
1
+ // @umicat/three-sdk/vfx -- plays `.vfx.json` effects made in the VFX Editor.
2
+ //
3
+ // A separate entry point on purpose: it depends on three.js and nothing else
4
+ // (no physics, no platform bridge), so the editor and any game can import it
5
+ // without pulling in the rest of the SDK.
6
+ export * from './document.js';
7
+ export * from './templates.js';
8
+ export { VfxInstance } from './VfxInstance.js';
9
+ export { loadVfx, VfxEffect, siblingUrl, prepareSheetTexture } from './load.js';
@@ -0,0 +1,42 @@
1
+ import * as T from 'three';
2
+ import { type VfxDocument } from './document.js';
3
+ import { VfxInstance } from './VfxInstance.js';
4
+ export interface LoadVfxOptions {
5
+ /** Where a flipbook's `texture` filename lives. Defaults to the effect file's own folder. */
6
+ resolveTexture?: (filename: string, effectUrl: string) => string;
7
+ /** Defaults to `fetch`. */
8
+ fetch?: (url: string) => Promise<Response>;
9
+ }
10
+ /** Joins a sibling filename onto the effect's URL: `uploaded/fire.vfx.json` + `fire-sheet.webp` -> `uploaded/fire-sheet.webp`. */
11
+ export declare function siblingUrl(filename: string, effectUrl: string): string;
12
+ /**
13
+ * A loaded effect: the document plus its sheets, decoded once. `spawn()` as
14
+ * many playing copies as you like -- every copy shares the textures and owns
15
+ * its own particles.
16
+ */
17
+ export declare class VfxEffect {
18
+ readonly document: VfxDocument;
19
+ readonly textures: Map<string, T.Texture>;
20
+ private disposed;
21
+ constructor(document: VfxDocument, textures: Map<string, T.Texture>);
22
+ spawn(): VfxInstance;
23
+ /** Frees the shared textures. Dispose the spawned instances first. */
24
+ dispose(): void;
25
+ }
26
+ /** A texture configured the way a sprite sheet needs: colours in sRGB, and no
27
+ * mipmaps -- a mip level averages neighbouring CELLS together, which shows up
28
+ * as the next frame bleeding into the edge of this one. */
29
+ export declare function prepareSheetTexture(texture: T.Texture): T.Texture;
30
+ /**
31
+ * Fetch a `.vfx.json`, check it, and load every sheet its flipbooks name.
32
+ * Rejects -- naming the file -- when the document is invalid or a sheet cannot
33
+ * be loaded, so a missing texture is an error you see rather than an effect
34
+ * that is silently half there.
35
+ *
36
+ * const fire = await loadVfx('uploaded/campfire.vfx.json');
37
+ * const burst = fire.spawn();
38
+ * scene.add(burst.root);
39
+ * // every frame: burst.update(dt)
40
+ * // a one-shot: if (burst.finished) burst.dispose();
41
+ */
42
+ export declare function loadVfx(url: string, options?: LoadVfxOptions): Promise<VfxEffect>;
@@ -0,0 +1,79 @@
1
+ import * as T from 'three';
2
+ import { parseVfx, vfxTextures } from './document.js';
3
+ import { VfxInstance } from './VfxInstance.js';
4
+ /** Joins a sibling filename onto the effect's URL: `uploaded/fire.vfx.json` + `fire-sheet.webp` -> `uploaded/fire-sheet.webp`. */
5
+ export function siblingUrl(filename, effectUrl) {
6
+ const cut = effectUrl.split(/[?#]/)[0];
7
+ const slash = cut.lastIndexOf('/');
8
+ return (slash < 0 ? '' : cut.slice(0, slash + 1)) + encodeURIComponent(filename);
9
+ }
10
+ /**
11
+ * A loaded effect: the document plus its sheets, decoded once. `spawn()` as
12
+ * many playing copies as you like -- every copy shares the textures and owns
13
+ * its own particles.
14
+ */
15
+ export class VfxEffect {
16
+ constructor(document, textures) {
17
+ this.document = document;
18
+ this.textures = textures;
19
+ this.disposed = false;
20
+ }
21
+ spawn() {
22
+ if (this.disposed)
23
+ throw new Error(`VfxEffect "${this.document.name}" was disposed`);
24
+ return new VfxInstance(this.document, { textures: this.textures });
25
+ }
26
+ /** Frees the shared textures. Dispose the spawned instances first. */
27
+ dispose() { this.disposed = true; for (const t of this.textures.values())
28
+ t.dispose(); this.textures.clear(); }
29
+ }
30
+ /** A texture configured the way a sprite sheet needs: colours in sRGB, and no
31
+ * mipmaps -- a mip level averages neighbouring CELLS together, which shows up
32
+ * as the next frame bleeding into the edge of this one. */
33
+ export function prepareSheetTexture(texture) {
34
+ texture.colorSpace = T.SRGBColorSpace;
35
+ texture.generateMipmaps = false;
36
+ texture.minFilter = T.LinearFilter;
37
+ texture.magFilter = T.LinearFilter;
38
+ texture.wrapS = texture.wrapT = T.ClampToEdgeWrapping;
39
+ texture.needsUpdate = true;
40
+ return texture;
41
+ }
42
+ /**
43
+ * Fetch a `.vfx.json`, check it, and load every sheet its flipbooks name.
44
+ * Rejects -- naming the file -- when the document is invalid or a sheet cannot
45
+ * be loaded, so a missing texture is an error you see rather than an effect
46
+ * that is silently half there.
47
+ *
48
+ * const fire = await loadVfx('uploaded/campfire.vfx.json');
49
+ * const burst = fire.spawn();
50
+ * scene.add(burst.root);
51
+ * // every frame: burst.update(dt)
52
+ * // a one-shot: if (burst.finished) burst.dispose();
53
+ */
54
+ export async function loadVfx(url, options = {}) {
55
+ const get = options.fetch ?? ((u) => fetch(u));
56
+ const response = await get(url);
57
+ if (!response.ok)
58
+ throw new Error(`loadVfx: ${url} answered ${response.status}`);
59
+ let document;
60
+ try {
61
+ document = parseVfx(await response.json());
62
+ }
63
+ catch (e) {
64
+ throw new Error(`loadVfx: ${url}: ${e instanceof Error ? e.message : String(e)}`);
65
+ }
66
+ const resolve = options.resolveTexture ?? siblingUrl;
67
+ const loader = new T.TextureLoader();
68
+ const textures = new Map();
69
+ await Promise.all(vfxTextures(document).map(async (name) => {
70
+ const at = resolve(name, url);
71
+ try {
72
+ textures.set(name, prepareSheetTexture(await loader.loadAsync(at)));
73
+ }
74
+ catch {
75
+ throw new Error(`loadVfx: ${url} needs the sheet "${name}" (${at}) and it could not be loaded`);
76
+ }
77
+ }));
78
+ return new VfxEffect(document, textures);
79
+ }
@@ -0,0 +1,15 @@
1
+ import { campfire, type VfxDocument } from './document.js';
2
+ declare const TEMPLATES: {
3
+ readonly blank: () => VfxDocument;
4
+ readonly campfire: typeof campfire;
5
+ readonly smoke: () => VfxDocument;
6
+ readonly sparks: () => VfxDocument;
7
+ readonly explosion: () => VfxDocument;
8
+ readonly magic: () => VfxDocument;
9
+ };
10
+ export type VfxTemplateId = keyof typeof TEMPLATES;
11
+ export declare const VFX_TEMPLATE_IDS: VfxTemplateId[];
12
+ export declare const isVfxTemplateId: (id: unknown) => id is VfxTemplateId;
13
+ /** A fresh copy every call: the editor mutates what it is given. */
14
+ export declare function vfxTemplate(id: VfxTemplateId): VfxDocument;
15
+ export {};
@@ -0,0 +1,46 @@
1
+ import { campfire, upgradeV1, emitterLayer } from './document.js';
2
+ /**
3
+ * Starting points for "New effect". They ship WITH the editor rather than
4
+ * coming from the Store, so creating an effect never depends on somebody
5
+ * having published one.
6
+ *
7
+ * The emitter model is a disc at the origin firing UPWARD (vy is always
8
+ * positive, `spread` is the horizontal jitter, `gravity` is a vertical
9
+ * acceleration: positive rises, negative falls). Every template is a shape
10
+ * that model can actually draw -- an "explosion" is a one-shot upward burst
11
+ * that falls back, not a sphere.
12
+ */
13
+ const layer = (id, e) => ({ id, enabled: true, ...e });
14
+ // The ready-made ones were written in the version-1 model and are upgraded on the way out.
15
+ const v1 = (d) => upgradeV1({ version: 1, ...d });
16
+ const TEMPLATES = {
17
+ // Blank is ONE plain layer, not zero: a document needs at least one emitter,
18
+ // and something on screen to change is a better start than an empty view.
19
+ blank: () => ({ version: 2, name: 'New Effect', seed: 7, duration: 3, loop: true, humanCurated: false, emitters: [
20
+ emitterLayer('layer-1', { size: .3, sizeOverLife: { points: [[0, 1], [1, .35]] }, color: { stops: [[0, '#ffffff', .8]] }, colorOverLife: { stops: [[0, '#ffffff', 1], [1, '#9aa3b2', 1]] } })
21
+ ] }),
22
+ campfire,
23
+ smoke: () => v1({ name: 'Smoke', seed: 23, duration: 4, loop: true, humanCurated: false, emitters: [
24
+ layer('puff', { rate: 14, lifetime: 4, speed: .6, spread: .35, gravity: .05, size: .25, endSize: 1.2, opacity: .35, color: '#8a8f99', endColor: '#3d424b', blend: 'normal' }),
25
+ layer('wisp', { rate: 6, lifetime: 3, speed: .9, spread: .2, gravity: 0, size: .12, endSize: .6, opacity: .2, color: '#b4b8c0', endColor: '#5b616b', blend: 'normal' })
26
+ ] }),
27
+ sparks: () => v1({ name: 'Sparks', seed: 31, duration: 3, loop: true, humanCurated: false, emitters: [
28
+ layer('sparks', { rate: 80, lifetime: .9, speed: 3.2, spread: 2.4, gravity: -6, size: .04, endSize: .01, opacity: 1, color: '#fff3b0', endColor: '#ff7a1a', blend: 'additive' }),
29
+ layer('glow', { rate: 20, lifetime: .25, speed: .3, spread: .3, gravity: 0, size: .35, endSize: .1, opacity: .5, color: '#ffd27a', endColor: '#ff8a2a', blend: 'additive' })
30
+ ] }),
31
+ explosion: () => v1({ name: 'Explosion', seed: 41, duration: .15, loop: false, humanCurated: false, emitters: [
32
+ layer('flash', { rate: 300, lifetime: .35, speed: 1.2, spread: 4, gravity: 0, size: .9, endSize: .2, opacity: .9, color: '#fff2c4', endColor: '#ff6a1a', blend: 'additive' }),
33
+ layer('fire', { rate: 300, lifetime: .8, speed: 2.5, spread: 5, gravity: -1.5, size: .45, endSize: .1, opacity: .8, color: '#ffb347', endColor: '#d4290f', blend: 'additive' }),
34
+ layer('debris', { rate: 300, lifetime: 1.4, speed: 4, spread: 5, gravity: -7, size: .05, endSize: .02, opacity: 1, color: '#ffe08a', endColor: '#ff4d00', blend: 'additive' }),
35
+ layer('smoke', { rate: 200, lifetime: 2.5, speed: .8, spread: 2, gravity: .4, size: .4, endSize: 1.4, opacity: .25, color: '#5a5550', endColor: '#2a2724', blend: 'normal' })
36
+ ] }),
37
+ magic: () => v1({ name: 'Magic Aura', seed: 53, duration: 4, loop: true, humanCurated: false, emitters: [
38
+ layer('motes', { rate: 40, lifetime: 2, speed: .6, spread: .9, gravity: .2, size: .08, endSize: .01, opacity: .9, color: '#b98cff', endColor: '#3fd3ff', blend: 'additive' }),
39
+ layer('core', { rate: 12, lifetime: 1.2, speed: .2, spread: .2, gravity: .4, size: .5, endSize: .15, opacity: .35, color: '#7a5cff', endColor: '#2bb8ff', blend: 'additive' }),
40
+ layer('sparkle', { rate: 18, lifetime: .6, speed: 1.4, spread: 1.2, gravity: -.5, size: .05, endSize: .005, opacity: 1, color: '#ffffff', endColor: '#c9a8ff', blend: 'additive' })
41
+ ] }),
42
+ };
43
+ export const VFX_TEMPLATE_IDS = Object.keys(TEMPLATES);
44
+ export const isVfxTemplateId = (id) => typeof id === 'string' && Object.prototype.hasOwnProperty.call(TEMPLATES, id);
45
+ /** A fresh copy every call: the editor mutates what it is given. */
46
+ export function vfxTemplate(id) { return TEMPLATES[id](); }