@umicat/three-sdk 1.41.0 → 1.42.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 +26 -2
- package/dist/vfx/VfxInstance.d.ts +40 -2
- package/dist/vfx/VfxInstance.js +229 -29
- package/dist/vfx/document.d.ts +20 -5
- package/dist/vfx/document.js +14 -5
- package/dist/vfx/index.d.ts +1 -0
- package/dist/vfx/index.js +1 -0
- package/dist/vfx/material.d.ts +12 -1
- package/dist/vfx/material.js +43 -3
- package/dist/vfx/timeline.d.ts +82 -0
- package/dist/vfx/timeline.js +291 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -73,7 +73,7 @@ const fire = await loadVfx('uploaded/campfire.vfx.json'); // + every image it na
|
|
|
73
73
|
const fx = fire.spawn(); // many copies share the images
|
|
74
74
|
scene.add(fx.root);
|
|
75
75
|
// each frame: fx.update(dt); one-shot: if (fx.finished) fx.dispose();
|
|
76
|
-
// a looping effect (a status aura): fx.stop() when it should end -- it drains, then fx.finished
|
|
76
|
+
// a looping effect (a status aura): fx.stop() when it should end -- it plays its `close` clip or drains, then fx.finished
|
|
77
77
|
```
|
|
78
78
|
|
|
79
79
|
An effect has two kinds of layer. **Emitters** are particle systems modelled
|
|
@@ -133,7 +133,31 @@ finishes its cycle, a mesh layer or light with a window plays it out and a
|
|
|
133
133
|
whole-cycle one goes out; then `finished` turns true. Works on every format
|
|
134
134
|
version, which is how a game ends a looping effect.
|
|
135
135
|
|
|
136
|
-
**
|
|
136
|
+
**Tracks and clips (version 7, 1.42.0, ADR-056 step 2).** Godot's
|
|
137
|
+
AnimationPlayer for an effect. A track animates one value of one layer:
|
|
138
|
+
`{ target: 'meshes.ring.scale', keys: [[0, [0, 0, 0]], [.4, [1, 1, 1], .5]], interp? }`.
|
|
139
|
+
A target is `<emitters|meshes|lights|flipbooks>.<id>.<field>` and may go deeper
|
|
140
|
+
(`emitters.core.look.material.dissolve`, `meshes.ring.material.masks.1.strength`).
|
|
141
|
+
Numbers, vectors, `#rrggbb` colours (blended in linear space) and `enabled`
|
|
142
|
+
(always stepped) can be animated; a Range field takes a plain number while a
|
|
143
|
+
track drives it. A mesh's shape, a material's structure, curves, gradients and
|
|
144
|
+
ids cannot, and the parser says so by name. A key is `[time, value, ease?]`,
|
|
145
|
+
`ease` being Godot's transition exponent as-is (2 in, 0.5 out, negative
|
|
146
|
+
in-out, 0 hold); `interp: smooth` is Godot's cubic.
|
|
147
|
+
|
|
148
|
+
Without `clips`, a top-level `tracks` list plays over `duration` (the clip
|
|
149
|
+
`main`). With `clips: [{ name, duration, loop, next?, tracks }]` (and
|
|
150
|
+
`startClip`), each clip is a cycle of its own: emitter windows and bursts,
|
|
151
|
+
mesh and light windows and track times count from the clip's start; a clip
|
|
152
|
+
with `next` hands over when it ends; one with neither `loop` nor `next` ends
|
|
153
|
+
the effect. A field a clip does not animate holds the last value it was given,
|
|
154
|
+
as in Godot -- an `idle` with no tracks keeps a portal open.
|
|
155
|
+
`fx.play('idle')` switches at once, `fx.clip` / `fx.clipTime` say where it is,
|
|
156
|
+
**`fx.stop()` plays the clip named `close` when there is one**, and
|
|
157
|
+
`fx.seek(t, clip?)` replays to that moment at the fixed step (a clip reached
|
|
158
|
+
by `next` is played through its predecessors).
|
|
159
|
+
|
|
160
|
+
**Write the lowest version.** `minimumVersion(doc)` is 7 with tracks or clips, 6 with trails, 5 with lights, 4 with meshes, 3 with a
|
|
137
161
|
material, else 2; the editor and the agent write that, so an effect that needs nothing
|
|
138
162
|
new stays version 2 and keeps playing on 1.36.
|
|
139
163
|
|
|
@@ -33,13 +33,51 @@ export declare class VfxInstance {
|
|
|
33
33
|
private meshLayers;
|
|
34
34
|
private lightLayers;
|
|
35
35
|
private state;
|
|
36
|
-
/**
|
|
36
|
+
/** CLIP time when `stop()` was called with no `close` clip to play, or null. */
|
|
37
37
|
private stoppedAt;
|
|
38
|
+
private stopRequested;
|
|
39
|
+
private clips;
|
|
40
|
+
private startClip;
|
|
41
|
+
private cur;
|
|
42
|
+
/** Effect time the current clip began. */
|
|
43
|
+
private clipStart;
|
|
44
|
+
/** The static value of every field some track writes, for `reset()`. */
|
|
45
|
+
private restores;
|
|
38
46
|
/** Particles born so far: hashed into each particle's `seed`. */
|
|
39
47
|
private serial;
|
|
40
48
|
private accumulator;
|
|
41
49
|
private live;
|
|
42
50
|
constructor(document: VfxDocument, options?: VfxInstanceOptions);
|
|
51
|
+
private liveOf;
|
|
52
|
+
/** Refreshes what was derived from a layer's config when a track wrote into it. */
|
|
53
|
+
private syncer;
|
|
54
|
+
/** Starts `clip` at effect time `start`: its windows, bursts and track times count from there. */
|
|
55
|
+
private enter;
|
|
56
|
+
/** Writes every track of the current clip at the clip's time. Fields no track of it names hold their last value. */
|
|
57
|
+
private applyTracks;
|
|
58
|
+
/** A clip that ended hands over to its `next`, exactly at its end -- after landing on its own last values, as Godot does. */
|
|
59
|
+
private advanceClip;
|
|
60
|
+
/** The clip playing now (`main` for an effect without clips). */
|
|
61
|
+
get clip(): string;
|
|
62
|
+
/** Every clip this effect has, in document order. */
|
|
63
|
+
get clipNames(): string[];
|
|
64
|
+
/** Seconds since the current clip began. */
|
|
65
|
+
get clipTime(): number;
|
|
66
|
+
/**
|
|
67
|
+
* Switches to clip `name` at once (Godot snaps, so do we): particles alive
|
|
68
|
+
* keep living, fields its tracks do not name keep their last value. Also
|
|
69
|
+
* undoes a `stop()`.
|
|
70
|
+
*/
|
|
71
|
+
play(name: string): void;
|
|
72
|
+
/**
|
|
73
|
+
* Jumps to `seconds` into `clip` (default: the current one), by replaying
|
|
74
|
+
* from `reset()` at the fixed step -- so the frame is exactly what
|
|
75
|
+
* `update()` would have reached. A clip reached from the start clip by
|
|
76
|
+
* `next` is played through its predecessors, so it starts with the values
|
|
77
|
+
* they leave (an `idle` after an `open`); any other clip starts from the
|
|
78
|
+
* document's own values.
|
|
79
|
+
*/
|
|
80
|
+
seek(seconds: number, clip?: string): void;
|
|
43
81
|
private buildParticles;
|
|
44
82
|
private buildTrail;
|
|
45
83
|
/** (Re)creates the per-instance buffers with room for `capacity` particles. */
|
|
@@ -59,7 +97,7 @@ export declare class VfxInstance {
|
|
|
59
97
|
* format version; `reset()` undoes it.
|
|
60
98
|
*/
|
|
61
99
|
stop(): void;
|
|
62
|
-
/** True after `stop()`, until `reset()`. */
|
|
100
|
+
/** True after `stop()`, until `reset()` or `play()`. */
|
|
63
101
|
get stopped(): boolean;
|
|
64
102
|
reset(): void;
|
|
65
103
|
get particleCount(): number;
|
package/dist/vfx/VfxInstance.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import * as T from 'three';
|
|
2
2
|
import { parseVfx, pickRange, sampleCurve, sampleGradient, LIMITS, } from './document.js';
|
|
3
|
-
import { compileMaterial, materialDefaults, maskDefaults } from './material.js';
|
|
3
|
+
import { compileMaterial, materialDefaults, maskDefaults, updateMaterialUniforms } from './material.js';
|
|
4
|
+
import { effectClips, resolveTarget, prepareTrack, sampleTrack, linearToHex } from './timeline.js';
|
|
4
5
|
import { TrailMesh, trailSampling, trailVertex, newHistory, pushHistory, historyAt } from './trail.js';
|
|
5
6
|
import { meshGeometry, fixRingUv, meshLayerVertex, meshParticleVertex, meshFragment } from './mesh.js';
|
|
6
7
|
/** Closed shapes are drawn front-only, so an additive sphere does not show its back through its front. */
|
|
7
8
|
const closed = (s) => s.type === 'sphere' || s.type === 'box' || s.type === 'torus' || (s.type === 'cylinder' && s.caps);
|
|
8
9
|
const SIDE = { front: T.FrontSide, back: T.BackSide, both: T.DoubleSide };
|
|
10
|
+
const trackScratch = [];
|
|
9
11
|
const SHARED_QUAD = (() => {
|
|
10
12
|
// Corners in [0,1]^2 with y UP; the shader turns them into a cell-sized quad.
|
|
11
13
|
const g = new T.BufferGeometry();
|
|
@@ -169,8 +171,14 @@ export class VfxInstance {
|
|
|
169
171
|
this.meshLayers = [];
|
|
170
172
|
this.lightLayers = [];
|
|
171
173
|
this.state = 1;
|
|
172
|
-
/**
|
|
174
|
+
/** CLIP time when `stop()` was called with no `close` clip to play, or null. */
|
|
173
175
|
this.stoppedAt = null;
|
|
176
|
+
this.stopRequested = false;
|
|
177
|
+
this.clips = new Map();
|
|
178
|
+
/** Effect time the current clip began. */
|
|
179
|
+
this.clipStart = 0;
|
|
180
|
+
/** The static value of every field some track writes, for `reset()`. */
|
|
181
|
+
this.restores = [];
|
|
174
182
|
/** Particles born so far: hashed into each particle's `seed`. */
|
|
175
183
|
this.serial = 0;
|
|
176
184
|
this.accumulator = 0;
|
|
@@ -178,6 +186,21 @@ export class VfxInstance {
|
|
|
178
186
|
this.document = parseVfx(document);
|
|
179
187
|
this.state = this.document.seed;
|
|
180
188
|
this.root.name = this.document.name;
|
|
189
|
+
// Tracks first: a material whose numbers a track drives compiles them in even at 0.
|
|
190
|
+
const timeline = effectClips(this.document);
|
|
191
|
+
const resolved = timeline.clips.map((c) => c.tracks.map((t) => [t, resolveTarget(this.document, t.target)]));
|
|
192
|
+
const live = new Map();
|
|
193
|
+
for (const [, r] of resolved.flat())
|
|
194
|
+
if (r.material) {
|
|
195
|
+
const key = `${r.kind}.${r.id}.${r.material.join('.')}`, sub = r.path.slice(r.material.length);
|
|
196
|
+
const set = live.get(key) ?? new Set();
|
|
197
|
+
live.set(key, set);
|
|
198
|
+
if (sub[0] === 'masks' && sub[2] === 'offset')
|
|
199
|
+
set.add(`offset${sub[1]}`);
|
|
200
|
+
if (sub[0] === 'displace' && sub[1] === 'amount')
|
|
201
|
+
set.add('displace');
|
|
202
|
+
}
|
|
203
|
+
this.liveOf = (key) => live.get(key) ?? new Set();
|
|
181
204
|
const children = new Set(this.document.emitters.flatMap((e) => e.children.map((c) => c.emitter)));
|
|
182
205
|
this.document.emitters.forEach((config, index) => {
|
|
183
206
|
const layer = this.buildParticles(config, index, !children.has(config.id), (name) => resolveTexture(options.textures, name));
|
|
@@ -197,6 +220,162 @@ export class VfxInstance {
|
|
|
197
220
|
this.root.add(light);
|
|
198
221
|
this.lightLayers.push({ config, light, seed: seedOf(this.document.seed, 200000 + i) });
|
|
199
222
|
});
|
|
223
|
+
const restored = new Set();
|
|
224
|
+
timeline.clips.forEach((clip, ci) => {
|
|
225
|
+
const bindings = resolved[ci].map(([track, r]) => {
|
|
226
|
+
let parent = this.document[r.kind][r.index];
|
|
227
|
+
for (const seg of r.path.slice(0, -1))
|
|
228
|
+
parent = parent[seg];
|
|
229
|
+
const key = r.path[r.path.length - 1], sync = this.syncer(r.kind, r.index);
|
|
230
|
+
const where = `${r.kind}.${r.index}.${r.path.join('.')}`;
|
|
231
|
+
if (!restored.has(where)) {
|
|
232
|
+
restored.add(where);
|
|
233
|
+
this.restores.push({ parent, key, base: structuredClone(parent[key]), sync });
|
|
234
|
+
}
|
|
235
|
+
return { sampled: prepareTrack(track, r.value), parent, key, kind: r.value, sync };
|
|
236
|
+
});
|
|
237
|
+
this.clips.set(clip.name, { name: clip.name, duration: clip.duration, loop: clip.loop, next: clip.next, bindings });
|
|
238
|
+
});
|
|
239
|
+
this.startClip = this.clips.get(timeline.start);
|
|
240
|
+
this.enter(this.startClip, 0);
|
|
241
|
+
this.applyTracks();
|
|
242
|
+
this.draw();
|
|
243
|
+
}
|
|
244
|
+
/** Refreshes what was derived from a layer's config when a track wrote into it. */
|
|
245
|
+
syncer(kind, index) {
|
|
246
|
+
if (kind === 'emitters')
|
|
247
|
+
return () => {
|
|
248
|
+
const l = this.particleLayers[index], c = l.config, u = l.material.uniforms;
|
|
249
|
+
l.orient.copy(emitterQuaternion(c));
|
|
250
|
+
u.uAxis.value.set(...c.direction).applyQuaternion(l.orient).normalize();
|
|
251
|
+
u.uOrient.value.setFromMatrix4(new T.Matrix4().makeRotationFromQuaternion(l.orient));
|
|
252
|
+
u.uStretch.value = c.stretch;
|
|
253
|
+
if (c.look.type === 'dot')
|
|
254
|
+
u.uSoft.value = c.look.softness;
|
|
255
|
+
if (c.look.type === 'star') {
|
|
256
|
+
u.uPoints.value = c.look.points;
|
|
257
|
+
u.uSharp.value = c.look.sharpness;
|
|
258
|
+
}
|
|
259
|
+
if (c.look.type === 'material' && l.compiled)
|
|
260
|
+
updateMaterialUniforms(l.compiled, c.look.material);
|
|
261
|
+
if (c.trail?.material && l.trail)
|
|
262
|
+
updateMaterialUniforms(l.trail.compiled, c.trail.material);
|
|
263
|
+
};
|
|
264
|
+
if (kind === 'meshes')
|
|
265
|
+
return () => {
|
|
266
|
+
const m = this.meshLayers[index], c = m.config;
|
|
267
|
+
m.mesh.position.set(...c.position);
|
|
268
|
+
m.mesh.rotation.set(c.rotation[0] * DEG, c.rotation[1] * DEG, c.rotation[2] * DEG, 'XYZ');
|
|
269
|
+
updateMaterialUniforms(m.compiled, c.material);
|
|
270
|
+
};
|
|
271
|
+
if (kind === 'lights')
|
|
272
|
+
return () => {
|
|
273
|
+
// With { lights: false } there is no light to refresh; the config still follows the track.
|
|
274
|
+
const l = this.lightLayers.find((x) => x.config === this.document.lights[index]);
|
|
275
|
+
if (l) {
|
|
276
|
+
l.light.position.set(...l.config.position);
|
|
277
|
+
l.light.color.set(l.config.color);
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
return () => {
|
|
281
|
+
const f = this.flipbookLayers[index], c = f.config, u = f.material.uniforms;
|
|
282
|
+
u.uTint.value.set(c.color);
|
|
283
|
+
u.uOpacity.value = c.opacity;
|
|
284
|
+
u.uOrigin.value.set(c.originU, c.originV);
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
/** Starts `clip` at effect time `start`: its windows, bursts and track times count from there. */
|
|
288
|
+
enter(clip, start) {
|
|
289
|
+
this.cur = clip;
|
|
290
|
+
this.clipStart = start;
|
|
291
|
+
for (const l of this.particleLayers) {
|
|
292
|
+
l.fraction = 0;
|
|
293
|
+
l.cycle = 0;
|
|
294
|
+
l.burstEmitted.fill(0);
|
|
295
|
+
}
|
|
296
|
+
for (const f of this.flipbookLayers)
|
|
297
|
+
f.done = !f.config.enabled;
|
|
298
|
+
}
|
|
299
|
+
/** Writes every track of the current clip at the clip's time. Fields no track of it names hold their last value. */
|
|
300
|
+
applyTracks(c = this.cur, at) {
|
|
301
|
+
if (!c.bindings.length)
|
|
302
|
+
return;
|
|
303
|
+
const ct = at ?? this.clipTime, t = at !== undefined ? at : c.loop ? ct % c.duration : ct;
|
|
304
|
+
const dirty = new Set();
|
|
305
|
+
for (const b of c.bindings) {
|
|
306
|
+
const v = sampleTrack(b.sampled, t, trackScratch);
|
|
307
|
+
if (b.kind === 'number')
|
|
308
|
+
b.parent[b.key] = v[0];
|
|
309
|
+
else if (b.kind === 'bool')
|
|
310
|
+
b.parent[b.key] = v[0] > .5;
|
|
311
|
+
else if (b.kind === 'color')
|
|
312
|
+
b.parent[b.key] = linearToHex(v);
|
|
313
|
+
else {
|
|
314
|
+
const a = b.parent[b.key];
|
|
315
|
+
for (let i = 0; i < a.length; i++)
|
|
316
|
+
a[i] = v[i];
|
|
317
|
+
}
|
|
318
|
+
dirty.add(b.sync);
|
|
319
|
+
}
|
|
320
|
+
for (const f of dirty)
|
|
321
|
+
f();
|
|
322
|
+
}
|
|
323
|
+
/** A clip that ended hands over to its `next`, exactly at its end -- after landing on its own last values, as Godot does. */
|
|
324
|
+
advanceClip() {
|
|
325
|
+
while (this.stoppedAt === null && !this.cur.loop && this.cur.next && this.time - this.clipStart >= this.cur.duration - 1e-9) {
|
|
326
|
+
this.applyTracks(this.cur, this.cur.duration);
|
|
327
|
+
this.enter(this.clips.get(this.cur.next), this.clipStart + this.cur.duration);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
/** The clip playing now (`main` for an effect without clips). */
|
|
331
|
+
get clip() { return this.cur.name; }
|
|
332
|
+
/** Every clip this effect has, in document order. */
|
|
333
|
+
get clipNames() { return [...this.clips.keys()]; }
|
|
334
|
+
/** Seconds since the current clip began. */
|
|
335
|
+
get clipTime() { return Math.max(0, this.time - this.clipStart); }
|
|
336
|
+
/**
|
|
337
|
+
* Switches to clip `name` at once (Godot snaps, so do we): particles alive
|
|
338
|
+
* keep living, fields its tracks do not name keep their last value. Also
|
|
339
|
+
* undoes a `stop()`.
|
|
340
|
+
*/
|
|
341
|
+
play(name) {
|
|
342
|
+
const c = this.clips.get(name);
|
|
343
|
+
if (!c)
|
|
344
|
+
throw new Error(`VfxInstance.play: no clip "${name}" (this effect has ${this.clipNames.join(', ')})`);
|
|
345
|
+
this.stoppedAt = null;
|
|
346
|
+
this.stopRequested = false;
|
|
347
|
+
this.enter(c, this.time);
|
|
348
|
+
this.applyTracks();
|
|
349
|
+
this.draw();
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Jumps to `seconds` into `clip` (default: the current one), by replaying
|
|
353
|
+
* from `reset()` at the fixed step -- so the frame is exactly what
|
|
354
|
+
* `update()` would have reached. A clip reached from the start clip by
|
|
355
|
+
* `next` is played through its predecessors, so it starts with the values
|
|
356
|
+
* they leave (an `idle` after an `open`); any other clip starts from the
|
|
357
|
+
* document's own values.
|
|
358
|
+
*/
|
|
359
|
+
seek(seconds, clip = this.cur.name) {
|
|
360
|
+
const target = this.clips.get(clip);
|
|
361
|
+
if (!target)
|
|
362
|
+
throw new Error(`VfxInstance.seek: no clip "${clip}" (this effect has ${this.clipNames.join(', ')})`);
|
|
363
|
+
this.reset();
|
|
364
|
+
let lead = 0, c = this.cur;
|
|
365
|
+
const seen = new Set();
|
|
366
|
+
while (c !== target && c.next && !seen.has(c)) {
|
|
367
|
+
seen.add(c);
|
|
368
|
+
lead += c.duration;
|
|
369
|
+
c = this.clips.get(c.next);
|
|
370
|
+
}
|
|
371
|
+
if (c !== target) {
|
|
372
|
+
lead = 0;
|
|
373
|
+
this.enter(target, 0);
|
|
374
|
+
this.applyTracks();
|
|
375
|
+
}
|
|
376
|
+
const steps = Math.round(Math.max(0, Math.min(60, lead + seconds)) * 60);
|
|
377
|
+
for (let i = 0; i < steps; i++)
|
|
378
|
+
this.step(1 / 60);
|
|
200
379
|
this.draw();
|
|
201
380
|
}
|
|
202
381
|
buildParticles(config, index, root, textureOf) {
|
|
@@ -216,7 +395,7 @@ export class VfxInstance {
|
|
|
216
395
|
const texture = !solid && (look.type === 'texture' || look.type === 'sheet') ? textureOf(look.texture) : undefined;
|
|
217
396
|
const images = texture || (!solid && (look.type === 'texture' || look.type === 'sheet')) ? [texture] : [];
|
|
218
397
|
// A mesh particle always draws through a material: its look's, or a solid one.
|
|
219
|
-
const compiled = look.type === 'material' ? compileMaterial(look.material) : solid ? compileMaterial({ ...materialDefaults(), masks: [] }) : undefined;
|
|
398
|
+
const compiled = look.type === 'material' ? compileMaterial(look.material, this.liveOf(`emitters.${config.id}.look.material`)) : solid ? compileMaterial({ ...materialDefaults(), masks: [] }) : undefined;
|
|
220
399
|
const repeats = [];
|
|
221
400
|
if (compiled)
|
|
222
401
|
bindImages(compiled, textureOf, images, repeats);
|
|
@@ -254,7 +433,7 @@ export class VfxInstance {
|
|
|
254
433
|
buildTrail(config, index, textureOf) {
|
|
255
434
|
const t = config.trail;
|
|
256
435
|
// Default: the particle's colour, fading from the particle to the tail (u runs head -> tail).
|
|
257
|
-
const compiled = compileMaterial(t.material ?? { ...materialDefaults(), masks: [{ ...maskDefaults({ type: 'gradient', fill: 'linear', center: [.5, .5], width: .25 }), invert: true }], softness: 1, ramp: 'linear' });
|
|
436
|
+
const compiled = compileMaterial(t.material ?? { ...materialDefaults(), masks: [{ ...maskDefaults({ type: 'gradient', fill: 'linear', center: [.5, .5], width: .25 }), invert: true }], softness: 1, ramp: 'linear' }, this.liveOf(`emitters.${config.id}.trail.material`));
|
|
258
437
|
const images = [], repeats = [];
|
|
259
438
|
bindImages(compiled, textureOf, images, repeats);
|
|
260
439
|
const material = new T.ShaderMaterial({
|
|
@@ -287,7 +466,7 @@ export class VfxInstance {
|
|
|
287
466
|
}
|
|
288
467
|
buildMesh(config, index, textureOf) {
|
|
289
468
|
const geometry = fixRingUv(meshGeometry(config.shape), config.shape);
|
|
290
|
-
const compiled = compileMaterial(config.material);
|
|
469
|
+
const compiled = compileMaterial(config.material, this.liveOf(`meshes.${config.id}.material`));
|
|
291
470
|
const images = [], repeats = [];
|
|
292
471
|
bindImages(compiled, textureOf, images, repeats);
|
|
293
472
|
const s = config.shape;
|
|
@@ -317,25 +496,25 @@ export class VfxInstance {
|
|
|
317
496
|
meshLife(c) {
|
|
318
497
|
if (!c.enabled)
|
|
319
498
|
return -1;
|
|
320
|
-
const
|
|
499
|
+
const clip = this.cur, d = clip.duration, ct = this.clipTime, life = c.life ?? Math.max(.01, d - c.start);
|
|
321
500
|
if (this.stoppedAt !== null) {
|
|
322
501
|
// Stopped: a whole-cycle layer goes out; a window that had begun plays out; nothing new begins.
|
|
323
502
|
if (c.life === null)
|
|
324
503
|
return -1;
|
|
325
|
-
const base =
|
|
504
|
+
const base = clip.loop ? Math.floor(this.stoppedAt / d) * d : 0;
|
|
326
505
|
for (const begin of [base + c.start, base - d + c.start]) {
|
|
327
506
|
if (begin > this.stoppedAt || (begin < 0))
|
|
328
507
|
continue;
|
|
329
|
-
const t = (
|
|
508
|
+
const t = (ct - begin) / life;
|
|
330
509
|
if (t >= 0 && t < 1)
|
|
331
510
|
return t;
|
|
332
511
|
}
|
|
333
512
|
return -1;
|
|
334
513
|
}
|
|
335
|
-
const cycleTime =
|
|
514
|
+
const cycleTime = clip.loop ? ct % d : ct;
|
|
336
515
|
let t = (cycleTime - c.start) / life;
|
|
337
516
|
// A looping layer that outlives its cycle carries over into the next one.
|
|
338
|
-
if (
|
|
517
|
+
if (clip.loop && t < 0 && ct >= d)
|
|
339
518
|
t = (cycleTime + d - c.start) / life;
|
|
340
519
|
return t >= 0 && t < 1 ? t : -1;
|
|
341
520
|
}
|
|
@@ -367,25 +546,42 @@ export class VfxInstance {
|
|
|
367
546
|
* so a looping status effect can be ended and then disposed. Works on every
|
|
368
547
|
* format version; `reset()` undoes it.
|
|
369
548
|
*/
|
|
370
|
-
stop() {
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
549
|
+
stop() {
|
|
550
|
+
if (this.stopRequested)
|
|
551
|
+
return;
|
|
552
|
+
this.stopRequested = true;
|
|
553
|
+
// An author's outro (ADR-056): a clip named `close` is how an effect asks to end its own way.
|
|
554
|
+
const close = this.clips.get('close');
|
|
555
|
+
if (close) {
|
|
556
|
+
if (this.cur !== close) {
|
|
557
|
+
this.enter(close, this.time);
|
|
558
|
+
this.applyTracks();
|
|
559
|
+
}
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
this.stoppedAt = this.clipTime;
|
|
563
|
+
}
|
|
564
|
+
/** True after `stop()`, until `reset()` or `play()`. */
|
|
565
|
+
get stopped() { return this.stopRequested; }
|
|
374
566
|
reset() {
|
|
375
567
|
this.stoppedAt = null;
|
|
568
|
+
this.stopRequested = false;
|
|
376
569
|
this.time = 0;
|
|
377
570
|
this.accumulator = 0;
|
|
378
571
|
this.state = this.document.seed;
|
|
379
572
|
this.live = 0;
|
|
380
573
|
this.serial = 0;
|
|
381
|
-
for (const l of this.particleLayers)
|
|
574
|
+
for (const l of this.particleLayers)
|
|
382
575
|
l.particles = [];
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
576
|
+
const dirty = new Set();
|
|
577
|
+
for (const r of this.restores) {
|
|
578
|
+
r.parent[r.key] = structuredClone(r.base);
|
|
579
|
+
dirty.add(r.sync);
|
|
386
580
|
}
|
|
387
|
-
for (const f of
|
|
388
|
-
f
|
|
581
|
+
for (const f of dirty)
|
|
582
|
+
f();
|
|
583
|
+
this.enter(this.startClip, 0);
|
|
584
|
+
this.applyTracks();
|
|
389
585
|
this.draw();
|
|
390
586
|
}
|
|
391
587
|
get particleCount() { return this.live; }
|
|
@@ -400,9 +596,10 @@ export class VfxInstance {
|
|
|
400
596
|
const quiet = this.meshLayers.every(({ config }) => this.meshLife(config) < 0) && this.lightLayers.every(({ config }) => this.meshLife(config) < 0);
|
|
401
597
|
return this.live === 0 && quiet && this.flipbookLayers.every((f) => f.done);
|
|
402
598
|
}
|
|
403
|
-
|
|
599
|
+
const clip = this.cur, ct = this.clipTime;
|
|
600
|
+
if (clip.loop || clip.next || ct < clip.duration)
|
|
404
601
|
return false;
|
|
405
|
-
const over = (c) => !c.enabled ||
|
|
602
|
+
const over = (c) => !c.enabled || ct >= c.start + (c.life ?? Math.max(.01, clip.duration - c.start));
|
|
406
603
|
const meshesDone = this.meshLayers.every(({ config }) => over(config)) && this.lightLayers.every(({ config }) => over(config));
|
|
407
604
|
return this.live === 0 && meshesDone && this.flipbookLayers.every((f) => f.done);
|
|
408
605
|
}
|
|
@@ -420,7 +617,7 @@ export class VfxInstance {
|
|
|
420
617
|
this.draw();
|
|
421
618
|
}
|
|
422
619
|
/** Whether the effect is still starting new particles / new flipbook cycles. */
|
|
423
|
-
get running() { return this.stoppedAt === null && (this.
|
|
620
|
+
get running() { return this.stoppedAt === null && (this.cur.loop || this.clipTime < this.cur.duration); }
|
|
424
621
|
/** The emitter's origin in its own simulation space. */
|
|
425
622
|
origin(layer, out) {
|
|
426
623
|
if (layer.config.space === 'world')
|
|
@@ -428,9 +625,9 @@ export class VfxInstance {
|
|
|
428
625
|
return out.set(0, 0, 0);
|
|
429
626
|
}
|
|
430
627
|
step(dt) {
|
|
431
|
-
const running = this.running;
|
|
432
|
-
const cycleTime =
|
|
433
|
-
const cycle =
|
|
628
|
+
const running = this.running, clip = this.cur, ct = this.clipTime;
|
|
629
|
+
const cycleTime = clip.loop ? ct % clip.duration : ct;
|
|
630
|
+
const cycle = clip.loop ? Math.floor(ct / clip.duration) : 0;
|
|
434
631
|
this.time += dt;
|
|
435
632
|
this.root.updateWorldMatrix(true, false);
|
|
436
633
|
const origin = new T.Vector3();
|
|
@@ -483,6 +680,8 @@ export class VfxInstance {
|
|
|
483
680
|
}
|
|
484
681
|
});
|
|
485
682
|
}
|
|
683
|
+
this.advanceClip();
|
|
684
|
+
this.applyTracks();
|
|
486
685
|
}
|
|
487
686
|
move(c, p, dt, origin) {
|
|
488
687
|
const t = p.age / p.life;
|
|
@@ -695,7 +894,7 @@ export class VfxInstance {
|
|
|
695
894
|
* cycling while the effect runs and, once it stops, finishes its current
|
|
696
895
|
* cycle -- the flipbook counterpart of particles draining. */
|
|
697
896
|
frameOf(f) {
|
|
698
|
-
const t = this.
|
|
897
|
+
const t = this.clipTime - f.delay;
|
|
699
898
|
if (!f.enabled || t < 0)
|
|
700
899
|
return -1;
|
|
701
900
|
const n = Math.floor(t * f.fps);
|
|
@@ -704,7 +903,8 @@ export class VfxInstance {
|
|
|
704
903
|
if (this.running)
|
|
705
904
|
return n % f.frames;
|
|
706
905
|
// Stopped: the cycle that was playing when the effect stopped may finish.
|
|
707
|
-
const
|
|
906
|
+
const clip = this.cur;
|
|
907
|
+
const end = clip.loop ? (this.stoppedAt ?? clip.duration) : Math.min(this.stoppedAt ?? Infinity, clip.duration);
|
|
708
908
|
const stoppedAt = Math.floor(Math.max(0, end - f.delay) * f.fps);
|
|
709
909
|
const cycleEnd = (Math.floor(stoppedAt / f.frames) + 1) * f.frames;
|
|
710
910
|
return n < cycleEnd ? n % f.frames : -1;
|
|
@@ -808,7 +1008,7 @@ export class VfxInstance {
|
|
|
808
1008
|
}
|
|
809
1009
|
for (const f of this.flipbookLayers) {
|
|
810
1010
|
const frame = this.frameOf(f.config);
|
|
811
|
-
if (frame < 0 && this.
|
|
1011
|
+
if (frame < 0 && this.clipTime >= f.config.delay)
|
|
812
1012
|
f.done = true;
|
|
813
1013
|
if (frame >= 0)
|
|
814
1014
|
f.done = false;
|
package/dist/vfx/document.d.ts
CHANGED
|
@@ -15,6 +15,9 @@
|
|
|
15
15
|
* Version 2. A version-1 document (the upward-firing disc emitter of 1.35) is
|
|
16
16
|
* still accepted: `parseVfx` upgrades it to the v2 emitter that plays the same.
|
|
17
17
|
*
|
|
18
|
+
* Version 7 (1.42) adds TRACKS and CLIPS (`tracks`, `clips`, `startClip`,
|
|
19
|
+
* ADR-056 step 2): keyframes on a layer's numbers, and named states.
|
|
20
|
+
*
|
|
18
21
|
* Version 6 (1.40) adds TRAILS (`emitter.trail`, ADR-055 step 4).
|
|
19
22
|
*
|
|
20
23
|
* Version 5 (1.39) adds LIGHTS (`lights`, point lights, ADR-055 step 3).
|
|
@@ -30,6 +33,7 @@
|
|
|
30
33
|
import { type Material } from './material.js';
|
|
31
34
|
import { type MeshShape, type MeshLayer } from './mesh.js';
|
|
32
35
|
import { type Trail } from './trail.js';
|
|
36
|
+
import { type Track, type Clip } from './timeline.js';
|
|
33
37
|
/** A number, or `[min, max]`: picked uniformly per particle. */
|
|
34
38
|
export type Range = number | [number, number];
|
|
35
39
|
export type Vec3 = [number, number, number];
|
|
@@ -236,7 +240,7 @@ export interface Flipbook {
|
|
|
236
240
|
blend: 'normal' | 'additive';
|
|
237
241
|
}
|
|
238
242
|
export interface VfxDocument {
|
|
239
|
-
version: 2 | 3 | 4 | 5 | 6;
|
|
243
|
+
version: 2 | 3 | 4 | 5 | 6 | 7;
|
|
240
244
|
name: string;
|
|
241
245
|
seed: number;
|
|
242
246
|
/** Seconds in one cycle. A looping effect repeats it; a one-shot stops emitting after it. */
|
|
@@ -249,6 +253,16 @@ export interface VfxDocument {
|
|
|
249
253
|
meshes?: MeshLayer[];
|
|
250
254
|
/** (version 5) Point lights: the flash of a muzzle, the glow a fire throws on the ground. At most 2. */
|
|
251
255
|
lights?: LightLayer[];
|
|
256
|
+
/** (version 7) Keyframes over the one cycle (`duration`, `loop`) of an effect without clips: the clip named `main`. */
|
|
257
|
+
tracks?: Track[];
|
|
258
|
+
/**
|
|
259
|
+
* (version 7) Named states, each a cycle of its own (open -> idle -> close).
|
|
260
|
+
* With clips, the top-level `duration` / `loop` are not played; `stop()`
|
|
261
|
+
* plays the clip named `close` when there is one.
|
|
262
|
+
*/
|
|
263
|
+
clips?: Clip[];
|
|
264
|
+
/** (version 7) The clip that plays first, and after `reset()`. Default: the first. */
|
|
265
|
+
startClip?: string;
|
|
252
266
|
}
|
|
253
267
|
/**
|
|
254
268
|
* A point light, created once with the effect and dimmed to 0 when it is off
|
|
@@ -377,11 +391,12 @@ export declare function sampleGradient(g: Gradient, t: number, out?: number[]):
|
|
|
377
391
|
*/
|
|
378
392
|
export declare function parseVfx(value: unknown): VfxDocument;
|
|
379
393
|
/**
|
|
380
|
-
* The lowest format version that can express this document:
|
|
381
|
-
*
|
|
382
|
-
* this, so an effect that needs
|
|
394
|
+
* The lowest format version that can express this document: 7 with tracks
|
|
395
|
+
* or clips, 6 with trails, 5 with lights, 4 with meshes, 3 with the material
|
|
396
|
+
* look, else 2. The editor and the agent write this, so an effect that needs
|
|
397
|
+
* nothing new still plays on an older SDK.
|
|
383
398
|
*/
|
|
384
|
-
export declare function minimumVersion(d: Pick<VfxDocument, 'emitters' | 'meshes' | 'lights'>): 2 | 3 | 4 | 5 | 6;
|
|
399
|
+
export declare function minimumVersion(d: Pick<VfxDocument, 'emitters' | 'meshes' | 'lights'> & Partial<Pick<VfxDocument, 'tracks' | 'clips' | 'startClip'>>): 2 | 3 | 4 | 5 | 6 | 7;
|
|
385
400
|
/** A new mesh layer: a soft additive ring on the ground, for the editor's "Add" and the agent. */
|
|
386
401
|
export declare function meshLayerDefaults(): Omit<MeshLayer, 'id'>;
|
|
387
402
|
/** A new light: a warm glow just above the origin, lit for the whole cycle. */
|
package/dist/vfx/document.js
CHANGED
|
@@ -15,6 +15,9 @@
|
|
|
15
15
|
* Version 2. A version-1 document (the upward-firing disc emitter of 1.35) is
|
|
16
16
|
* still accepted: `parseVfx` upgrades it to the v2 emitter that plays the same.
|
|
17
17
|
*
|
|
18
|
+
* Version 7 (1.42) adds TRACKS and CLIPS (`tracks`, `clips`, `startClip`,
|
|
19
|
+
* ADR-056 step 2): keyframes on a layer's numbers, and named states.
|
|
20
|
+
*
|
|
18
21
|
* Version 6 (1.40) adds TRAILS (`emitter.trail`, ADR-055 step 4).
|
|
19
22
|
*
|
|
20
23
|
* Version 5 (1.39) adds LIGHTS (`lights`, point lights, ADR-055 step 3).
|
|
@@ -30,6 +33,7 @@
|
|
|
30
33
|
import { parseMaterial, materialTextures, materialDefaults } from './material.js';
|
|
31
34
|
import { parseMeshShape } from './mesh.js';
|
|
32
35
|
import { trailSampling, TRAIL_POINT_BUDGET } from './trail.js';
|
|
36
|
+
import { parseTimeline } from './timeline.js';
|
|
33
37
|
export const LIMITS = { emitters: 8, layers: 8, meshes: 8, lights: 2, particles: 4000, cells: 4096, bursts: 16, children: 4, curvePoints: 8, gradientStops: 16 };
|
|
34
38
|
/** Every emitter field's value when a document leaves it out. */
|
|
35
39
|
export function emitterDefaults() {
|
|
@@ -189,8 +193,8 @@ export function parseVfx(value) {
|
|
|
189
193
|
const d = structuredClone(value);
|
|
190
194
|
const number = (v, min, max) => typeof v === 'number' && Number.isFinite(v) && v >= min && v <= max;
|
|
191
195
|
const color = (v) => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v);
|
|
192
|
-
if (![2, 3, 4, 5, 6].includes(d.version))
|
|
193
|
-
fail(`version must be 2-
|
|
196
|
+
if (![2, 3, 4, 5, 6, 7].includes(d.version))
|
|
197
|
+
fail(`version must be 2-7 (or 1, which is upgraded)${typeof d.version === 'number' && d.version > 7 ? ` -- version ${d.version} was written by a newer editor: update @umicat/three-sdk` : ''}`);
|
|
194
198
|
if (typeof d.name !== 'string' || !d.name.trim() || d.name.length > 80)
|
|
195
199
|
fail('name must be 1-80 characters');
|
|
196
200
|
if (!number(d.seed, 1, 2147483646) || !Number.isInteger(d.seed))
|
|
@@ -540,14 +544,19 @@ export function parseVfx(value) {
|
|
|
540
544
|
if (f.blend !== 'normal' && f.blend !== 'additive')
|
|
541
545
|
fail(`${at}.blend must be "normal" or "additive"`);
|
|
542
546
|
});
|
|
547
|
+
// Last: a track's target is resolved against the completed layers.
|
|
548
|
+
parseTimeline(d, fail);
|
|
543
549
|
return d;
|
|
544
550
|
}
|
|
545
551
|
/**
|
|
546
|
-
* The lowest format version that can express this document:
|
|
547
|
-
*
|
|
548
|
-
* this, so an effect that needs
|
|
552
|
+
* The lowest format version that can express this document: 7 with tracks
|
|
553
|
+
* or clips, 6 with trails, 5 with lights, 4 with meshes, 3 with the material
|
|
554
|
+
* look, else 2. The editor and the agent write this, so an effect that needs
|
|
555
|
+
* nothing new still plays on an older SDK.
|
|
549
556
|
*/
|
|
550
557
|
export function minimumVersion(d) {
|
|
558
|
+
if (d.tracks !== undefined || d.clips !== undefined || d.startClip !== undefined)
|
|
559
|
+
return 7;
|
|
551
560
|
if (d.emitters.some((e) => e.trail !== undefined))
|
|
552
561
|
return 6;
|
|
553
562
|
if (d.lights !== undefined)
|
package/dist/vfx/index.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ export { VfxInstance } from './VfxInstance.js';
|
|
|
4
4
|
export * from './material.js';
|
|
5
5
|
export * from './mesh.js';
|
|
6
6
|
export * from './trail.js';
|
|
7
|
+
export * from './timeline.js';
|
|
7
8
|
export type { VfxInstanceOptions, VfxTextureSource } from './VfxInstance.js';
|
|
8
9
|
export { loadVfx, VfxEffect, siblingUrl, prepareSheetTexture } from './load.js';
|
|
9
10
|
export type { LoadVfxOptions } from './load.js';
|
package/dist/vfx/index.js
CHANGED
package/dist/vfx/material.d.ts
CHANGED
|
@@ -206,7 +206,18 @@ export interface CompiledMaterial {
|
|
|
206
206
|
displace: boolean;
|
|
207
207
|
dispose(): void;
|
|
208
208
|
}
|
|
209
|
-
|
|
209
|
+
/**
|
|
210
|
+
* `live`: numbers a track drives (ADR-056), kept in the shader even while
|
|
211
|
+
* they are 0 -- `offset<i>` (a mask's offset) and `displace`. Without it a
|
|
212
|
+
* track that starts at 0 would write a uniform nothing reads.
|
|
213
|
+
*/
|
|
214
|
+
export declare function compileMaterial(m: Material, live?: ReadonlySet<string>): CompiledMaterial;
|
|
215
|
+
/**
|
|
216
|
+
* Writes a material's NUMBERS into an already-compiled shader's uniforms --
|
|
217
|
+
* what a track changes. Structure (masks, sources, blends, curves, the
|
|
218
|
+
* gradient map) is not touched: that needs `compileMaterial`.
|
|
219
|
+
*/
|
|
220
|
+
export declare function updateMaterialUniforms(c: CompiledMaterial, m: Material): void;
|
|
210
221
|
/**
|
|
211
222
|
* Starting points, so nobody begins from a blank material. Each is what one
|
|
212
223
|
* of the reference rebuilds needed (ADR-055), with the numbers rounded.
|
package/dist/vfx/material.js
CHANGED
|
@@ -403,7 +403,12 @@ float vfxShapeGlow(vec2 p, vec4 k){ float r = length(p); if (r >= 1.0) return 0.
|
|
|
403
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
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
405
|
`;
|
|
406
|
-
|
|
406
|
+
/**
|
|
407
|
+
* `live`: numbers a track drives (ADR-056), kept in the shader even while
|
|
408
|
+
* they are 0 -- `offset<i>` (a mask's offset) and `displace`. Without it a
|
|
409
|
+
* track that starts at 0 would write a uniform nothing reads.
|
|
410
|
+
*/
|
|
411
|
+
export function compileMaterial(m, live = new Set()) {
|
|
407
412
|
const curves = curveFields(m), row = new Map(curves.map((c, i) => [c.key, i]));
|
|
408
413
|
const rows = Math.max(1, curves.length);
|
|
409
414
|
const value = (key, uniform) => row.has(key) ? `vfxCurve(${glslFloat(row.get(key))}, life.x)` : uniform;
|
|
@@ -453,7 +458,7 @@ export function compileMaterial(m) {
|
|
|
453
458
|
fns.push(`float vfxMask${i}(vec2 uv0, vec2 life){ vec2 uv = uv0; ${polar}
|
|
454
459
|
uv = uv * uScale${i} - uScroll${i} * uTime${random};
|
|
455
460
|
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);` : ''}
|
|
461
|
+
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 || live.has(`offset${i}`) ? ` b = clamp(b + ${value(`offset${i}`, `uOffset${i}`)}, 0.0, 1.0);` : ''}
|
|
457
462
|
return b; }`);
|
|
458
463
|
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
464
|
});
|
|
@@ -481,12 +486,47 @@ ${body.join('\n')}
|
|
|
481
486
|
return vec4(rgb * max(0.0, ${value('emission', 'uEmission')}), ramp.a * alpha * clamp(${value('opacity', 'uOpacity')}, 0.0, 1.0));
|
|
482
487
|
}`;
|
|
483
488
|
return {
|
|
484
|
-
code, uniforms, images, alphaMode: m.alphaMode, displace: m.masks.length > 0 && (isCurve(m.displace.amount) || m.displace.amount !== 0),
|
|
489
|
+
code, uniforms, images, alphaMode: m.alphaMode, displace: m.masks.length > 0 && (isCurve(m.displace.amount) || m.displace.amount !== 0 || live.has('displace')),
|
|
485
490
|
dispose() { for (const t of owned)
|
|
486
491
|
t.dispose(); for (const t of noise)
|
|
487
492
|
releaseNoiseTexture(t); },
|
|
488
493
|
};
|
|
489
494
|
}
|
|
495
|
+
/**
|
|
496
|
+
* Writes a material's NUMBERS into an already-compiled shader's uniforms --
|
|
497
|
+
* what a track changes. Structure (masks, sources, blends, curves, the
|
|
498
|
+
* gradient map) is not touched: that needs `compileMaterial`.
|
|
499
|
+
*/
|
|
500
|
+
export function updateMaterialUniforms(c, m) {
|
|
501
|
+
const u = c.uniforms;
|
|
502
|
+
if (!isCurve(m.dissolve))
|
|
503
|
+
u.uDissolve.value = m.dissolve;
|
|
504
|
+
if (!isCurve(m.threshold))
|
|
505
|
+
u.uThreshold.value = m.threshold;
|
|
506
|
+
if (!isCurve(m.opacity))
|
|
507
|
+
u.uOpacity.value = m.opacity;
|
|
508
|
+
if (!isCurve(m.emission))
|
|
509
|
+
u.uEmission.value = m.emission;
|
|
510
|
+
u.uSoftness.value = m.softness;
|
|
511
|
+
u.uPower.value = m.power;
|
|
512
|
+
u.uCutoff.value = m.cutoff;
|
|
513
|
+
u.uEdge.value.set(m.edge.width, m.edge.emission, 0);
|
|
514
|
+
u.uEdgeColor.value.set(m.edge.color);
|
|
515
|
+
u.uRim.value.set(m.rim.strength, m.rim.power, m.rim.mode === 'edge' ? 1 : 0);
|
|
516
|
+
u.uDisplace.value.set(isCurve(m.displace.amount) ? 1 : m.displace.amount, m.displace.offset);
|
|
517
|
+
m.masks.forEach((k, i) => {
|
|
518
|
+
u[`uScale${i}`].value.set(k.scale[0], k.scale[1]);
|
|
519
|
+
u[`uScroll${i}`].value.set(k.scroll[0], k.scroll[1]);
|
|
520
|
+
u[`uSpin${i}`].value = k.spin * Math.PI / 180;
|
|
521
|
+
u[`uTurn${i}`].value = k.rotation * Math.PI / 180;
|
|
522
|
+
if (!isCurve(k.offset))
|
|
523
|
+
u[`uOffset${i}`].value = k.offset;
|
|
524
|
+
if (!isCurve(k.strength))
|
|
525
|
+
u[`uStrength${i}`].value = k.strength;
|
|
526
|
+
if (k.levels)
|
|
527
|
+
u[`uLevels${i}`].value.set(k.levels[0], k.levels[1]);
|
|
528
|
+
});
|
|
529
|
+
}
|
|
490
530
|
// ------------------------------------------------------------------ presets
|
|
491
531
|
const noise = (p) => ({ ...noiseDefaults(), ...p });
|
|
492
532
|
const mask = (source, p = {}) => ({ ...maskDefaults(source), ...p });
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tracks and clips (format v7, umicat-design ADR-056 step 2): Godot's
|
|
3
|
+
* AnimationPlayer for an effect. A TRACK animates one value of one layer
|
|
4
|
+
* over a CLIP's time; clips are the states a persistent effect goes through
|
|
5
|
+
* (open -> idle -> close).
|
|
6
|
+
*
|
|
7
|
+
* This file is the data side: the shapes, what a target path may name, the
|
|
8
|
+
* parser's checks and the sampling. `VfxInstance` turns resolved targets into
|
|
9
|
+
* setters once, at construction.
|
|
10
|
+
*/
|
|
11
|
+
import { type VfxDocument } from './document.js';
|
|
12
|
+
/** number; [x, y] or [x, y, z]; "#rrggbb"; or a boolean (`enabled` only). */
|
|
13
|
+
export type TrackValue = number | number[] | string | boolean;
|
|
14
|
+
/**
|
|
15
|
+
* `[time, value, ease?]`. `ease` is Godot's transition exponent as-is, applied
|
|
16
|
+
* to the segment the key STARTS: 1 linear (the default), 2 ease in, 0.5 ease
|
|
17
|
+
* out, negative in-out, 0 hold this value until the next key.
|
|
18
|
+
*/
|
|
19
|
+
export type TrackKey = [number, TrackValue] | [number, TrackValue, number];
|
|
20
|
+
export interface Track {
|
|
21
|
+
/** `<emitters|meshes|lights|flipbooks>.<layer id>.<field>[.<field>...]`, e.g. `meshes.ring.material.masks.1.strength`. */
|
|
22
|
+
target: string;
|
|
23
|
+
keys: TrackKey[];
|
|
24
|
+
/** linear (default); smooth: Godot's cubic; step: each key holds until the next. Booleans always step. */
|
|
25
|
+
interp?: 'linear' | 'smooth' | 'step';
|
|
26
|
+
}
|
|
27
|
+
export interface Clip {
|
|
28
|
+
name: string;
|
|
29
|
+
/** Seconds. Emitter windows and bursts, mesh-layer and light windows and track times all count from the clip's start. */
|
|
30
|
+
duration: number;
|
|
31
|
+
/** Repeat this clip until told otherwise. */
|
|
32
|
+
loop: boolean;
|
|
33
|
+
/** The clip that follows when this one ends (open -> idle). A clip with neither `loop` nor `next` ends the effect. */
|
|
34
|
+
next?: string;
|
|
35
|
+
tracks: Track[];
|
|
36
|
+
}
|
|
37
|
+
export declare const TIMELINE_LIMITS: {
|
|
38
|
+
readonly clips: 8;
|
|
39
|
+
readonly tracks: 64;
|
|
40
|
+
readonly keys: 16;
|
|
41
|
+
};
|
|
42
|
+
export type TrackKind = 'number' | 'vec2' | 'vec3' | 'color' | 'bool';
|
|
43
|
+
export type LayerKind = 'emitters' | 'meshes' | 'lights' | 'flipbooks';
|
|
44
|
+
export interface ResolvedTarget {
|
|
45
|
+
kind: LayerKind;
|
|
46
|
+
index: number;
|
|
47
|
+
id: string;
|
|
48
|
+
/** Field path inside the layer; numbers index lists (`masks.1`). */
|
|
49
|
+
path: (string | number)[];
|
|
50
|
+
value: TrackKind;
|
|
51
|
+
/** Per component, for numbers and vectors. */
|
|
52
|
+
bounds: [number, number];
|
|
53
|
+
/** A Range field (`speed`, `size`, ...): a track writes a plain number. */
|
|
54
|
+
range: boolean;
|
|
55
|
+
/** The material this path is inside (its path in the layer), if any -- the instance refreshes its uniforms. */
|
|
56
|
+
material?: (string | number)[];
|
|
57
|
+
}
|
|
58
|
+
/** Resolves `target` against a COMPLETE (parsed) document, or says why not. */
|
|
59
|
+
export declare function resolveTarget(d: VfxDocument, target: unknown): ResolvedTarget | string;
|
|
60
|
+
type Fail = (why: string) => never;
|
|
61
|
+
/** Checks `tracks`, `clips` and `startClip` against a parsed document (layers already complete). */
|
|
62
|
+
export declare function parseTimeline(d: VfxDocument, fail: Fail): void;
|
|
63
|
+
/** The clips an instance plays: the document's own, or one named `main` made of `duration`, `loop` and `tracks`. */
|
|
64
|
+
export declare function effectClips(d: VfxDocument): {
|
|
65
|
+
clips: Clip[];
|
|
66
|
+
start: string;
|
|
67
|
+
};
|
|
68
|
+
/** Godot's `ease(x, c)`, exactly (core/math/math_funcs.cpp). */
|
|
69
|
+
export declare function godotEase(x: number, c: number): number;
|
|
70
|
+
export declare const linearToHex: (rgb: number[]) => string;
|
|
71
|
+
/** A track ready to sample: numbers per key (colours in linear space, booleans 0/1). */
|
|
72
|
+
export interface SampledTrack {
|
|
73
|
+
kind: TrackKind;
|
|
74
|
+
times: number[];
|
|
75
|
+
values: number[][];
|
|
76
|
+
eases: number[];
|
|
77
|
+
interp: 'linear' | 'smooth' | 'step';
|
|
78
|
+
}
|
|
79
|
+
export declare function prepareTrack(t: Track, kind: TrackKind): SampledTrack;
|
|
80
|
+
/** The track's value at clip time `t`, into `out` (one number per component). Before the first key it holds the first; after the last, the last. */
|
|
81
|
+
export declare function sampleTrack(s: SampledTrack, t: number, out: number[]): number[];
|
|
82
|
+
export {};
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tracks and clips (format v7, umicat-design ADR-056 step 2): Godot's
|
|
3
|
+
* AnimationPlayer for an effect. A TRACK animates one value of one layer
|
|
4
|
+
* over a CLIP's time; clips are the states a persistent effect goes through
|
|
5
|
+
* (open -> idle -> close).
|
|
6
|
+
*
|
|
7
|
+
* This file is the data side: the shapes, what a target path may name, the
|
|
8
|
+
* parser's checks and the sampling. `VfxInstance` turns resolved targets into
|
|
9
|
+
* setters once, at construction.
|
|
10
|
+
*/
|
|
11
|
+
import { EMITTER_NUMBERS, EMITTER_RANGES, EMITTER_VECTORS, FLIPBOOK_RANGES } from './document.js';
|
|
12
|
+
export const TIMELINE_LIMITS = { clips: 8, tracks: 64, keys: 16 };
|
|
13
|
+
const MATERIAL_FIELDS = {
|
|
14
|
+
dissolve: [-1, 2], threshold: [-1, 2], opacity: [0, 1], emission: [0, 32], softness: [0, 1], power: [.1, 8], cutoff: [0, 1],
|
|
15
|
+
'edge.width': [0, 1], 'edge.emission': [0, 16], 'edge.color': 'color', 'rim.strength': [0, 1], 'rim.power': [.25, 8],
|
|
16
|
+
'displace.amount': [-5, 5], 'displace.offset': [0, 1],
|
|
17
|
+
'masks.*.scale': [-100, 100], 'masks.*.scroll': [-100, 100], 'masks.*.spin': [-3600, 3600], 'masks.*.rotation': [-360, 360],
|
|
18
|
+
'masks.*.offset': [-2, 2], 'masks.*.strength': [0, 1], 'masks.*.levels': [-2, 3],
|
|
19
|
+
};
|
|
20
|
+
const withMaterial = (prefix) => Object.fromEntries(Object.entries(MATERIAL_FIELDS).map(([k, v]) => [`${prefix}.${k}`, v]));
|
|
21
|
+
// Built on first use: document.ts imports this file, so its constants are not ready at load time.
|
|
22
|
+
let fieldTable;
|
|
23
|
+
const fields = () => fieldTable ?? (fieldTable = {
|
|
24
|
+
emitters: {
|
|
25
|
+
enabled: 'bool', ...EMITTER_RANGES, ...EMITTER_NUMBERS, ...EMITTER_VECTORS, stop: [0, 60],
|
|
26
|
+
'shape.radius': [0, 100], 'shape.inner': [0, 100], 'shape.height': [0, 100], 'shape.extents': [0, 100], 'shape.axis': [-1, 1],
|
|
27
|
+
'look.softness': [0, 1], 'look.points': [3, 12], 'look.sharpness': [0, 1], 'trail.width': [0, 50],
|
|
28
|
+
...withMaterial('look.material'), ...withMaterial('trail.material'),
|
|
29
|
+
},
|
|
30
|
+
meshes: {
|
|
31
|
+
enabled: 'bool', position: [-100, 100], rotation: [-360, 360], scale: [-100, 100], start: [0, 60], life: [.01, 60], color: 'color', intensity: [0, 16],
|
|
32
|
+
...withMaterial('material'),
|
|
33
|
+
},
|
|
34
|
+
lights: { enabled: 'bool', position: [-100, 100], color: 'color', intensity: [0, 1000], range: [.1, 100], start: [0, 60], life: [.01, 60], flicker: [0, 1] },
|
|
35
|
+
flipbooks: {
|
|
36
|
+
enabled: 'bool', color: 'color',
|
|
37
|
+
...Object.fromEntries(FLIPBOOK_RANGES.filter(([k]) => k !== 'cols' && k !== 'rows' && k !== 'frames').map(([k, a, b]) => [k, [a, b]])),
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
const LAYER_KINDS = ['emitters', 'meshes', 'lights', 'flipbooks'];
|
|
41
|
+
const HEX = /^#[0-9a-f]{6}$/i;
|
|
42
|
+
/** Why a path names something no track may drive -- said by name, so the agent can fix it. */
|
|
43
|
+
function refusal(kind, path, value) {
|
|
44
|
+
const p = path.join('.');
|
|
45
|
+
if (kind === 'meshes' && path[0] === 'shape')
|
|
46
|
+
return `the shape of a mesh cannot be animated (it would rebuild the geometry): animate "scale" instead`;
|
|
47
|
+
if (kind === 'emitters' && path[0] === 'mesh')
|
|
48
|
+
return `a particle's mesh shape cannot be animated: animate "size" instead`;
|
|
49
|
+
if (kind === 'emitters' && path[0] === 'trail' && path[1] === 'length')
|
|
50
|
+
return `a trail's length cannot be animated (it sets how many points each trail keeps)`;
|
|
51
|
+
if (kind === 'flipbooks' && ['cols', 'rows', 'frames'].includes(path[0]))
|
|
52
|
+
return `a flipbook's grid (${path[0]}) cannot be animated`;
|
|
53
|
+
const m = path.indexOf('material');
|
|
54
|
+
if (m >= 0 && path[m + 1] === 'masks' && path[m + 3] !== undefined && !['scale', 'scroll', 'spin', 'rotation', 'offset', 'strength', 'levels'].includes(path[m + 3]))
|
|
55
|
+
return `a mask's ${path[m + 3]} is the material's structure (it would recompile the shader): animate its scale, scroll, spin, rotation, offset, strength or levels`;
|
|
56
|
+
if (m >= 0 && ['color', 'ramp', 'alphaMode'].includes(path[m + 1]))
|
|
57
|
+
return `the material's ${path[m + 1]} is its structure and cannot be animated`;
|
|
58
|
+
if (value === null)
|
|
59
|
+
return `${p} is null here; give it a number first to animate it`;
|
|
60
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
61
|
+
if ('overLife' in value)
|
|
62
|
+
return `${p} is a curve over each particle's life; a track cannot drive it as well (make it a number first)`;
|
|
63
|
+
if ('points' in value || 'stops' in value)
|
|
64
|
+
return `${p} is a curve or gradient, which cannot be animated -- animate a number instead`;
|
|
65
|
+
return `${p} is a group; name one of its numbers`;
|
|
66
|
+
}
|
|
67
|
+
return `${p} cannot be animated`;
|
|
68
|
+
}
|
|
69
|
+
/** Resolves `target` against a COMPLETE (parsed) document, or says why not. */
|
|
70
|
+
export function resolveTarget(d, target) {
|
|
71
|
+
if (typeof target !== 'string' || !target)
|
|
72
|
+
return 'target must be a path like "emitters.sparks.rate"';
|
|
73
|
+
const [kind, id, ...rest] = target.split('.');
|
|
74
|
+
if (kind === 'params')
|
|
75
|
+
return 'parameters (params.*) are not supported yet';
|
|
76
|
+
if (!LAYER_KINDS.includes(kind))
|
|
77
|
+
return `"${kind}" is not a layer kind (expected emitters, meshes, lights or flipbooks)`;
|
|
78
|
+
const k = kind;
|
|
79
|
+
const layers = (d[k] ?? []);
|
|
80
|
+
const index = layers.findIndex((l) => l.id === id);
|
|
81
|
+
if (index < 0)
|
|
82
|
+
return `there is no ${k.slice(0, -1)} "${id}" in this effect`;
|
|
83
|
+
if (!rest.length)
|
|
84
|
+
return `name a field of ${k}.${id}, e.g. ${k}.${id}.${k === 'emitters' ? 'rate' : 'enabled'}`;
|
|
85
|
+
let at = layers[index];
|
|
86
|
+
const path = [];
|
|
87
|
+
for (const seg of rest) {
|
|
88
|
+
if (Array.isArray(at) && /^\d+$/.test(seg)) {
|
|
89
|
+
if (+seg >= at.length)
|
|
90
|
+
return `${target}: there is no item ${seg}`;
|
|
91
|
+
path.push(+seg);
|
|
92
|
+
at = at[+seg];
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (!at || typeof at !== 'object' || Array.isArray(at) || !Object.prototype.hasOwnProperty.call(at, seg))
|
|
96
|
+
return `${target}: "${seg}" is not a field there`;
|
|
97
|
+
path.push(seg);
|
|
98
|
+
at = at[seg];
|
|
99
|
+
}
|
|
100
|
+
const pattern = path.map((s) => typeof s === 'number' ? '*' : s).join('.');
|
|
101
|
+
const bound = fields()[k][pattern];
|
|
102
|
+
if (!bound || at === null || (typeof at === 'object' && !Array.isArray(at)))
|
|
103
|
+
return `${target}: ${refusal(k, rest, at)}`;
|
|
104
|
+
const range = k === 'emitters' && path.length === 1 && path[0] in EMITTER_RANGES;
|
|
105
|
+
let value;
|
|
106
|
+
if (bound === 'bool')
|
|
107
|
+
value = 'bool';
|
|
108
|
+
else if (bound === 'color')
|
|
109
|
+
value = 'color';
|
|
110
|
+
else if (range || typeof at === 'number')
|
|
111
|
+
value = 'number';
|
|
112
|
+
else if (Array.isArray(at) && (at.length === 2 || at.length === 3))
|
|
113
|
+
value = at.length === 2 ? 'vec2' : 'vec3';
|
|
114
|
+
else
|
|
115
|
+
return `${target}: ${refusal(k, rest, at)}`;
|
|
116
|
+
const m = path.indexOf('material');
|
|
117
|
+
return { kind: k, index, id, path, value, bounds: Array.isArray(bound) ? [bound[0], bound[1]] : [0, 1], range, material: m >= 0 ? path.slice(0, m + 1) : undefined };
|
|
118
|
+
}
|
|
119
|
+
const num = (v, min, max) => typeof v === 'number' && Number.isFinite(v) && v >= min && v <= max;
|
|
120
|
+
function checkTracks(d, tracks, at, fail) {
|
|
121
|
+
if (!Array.isArray(tracks) || tracks.length > TIMELINE_LIMITS.tracks)
|
|
122
|
+
fail(`${at} must be a list of 0-${TIMELINE_LIMITS.tracks} tracks`);
|
|
123
|
+
const seen = new Set();
|
|
124
|
+
return tracks.map((raw, i) => {
|
|
125
|
+
const ta = `${at}[${i}]`;
|
|
126
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
127
|
+
fail(`${ta} must be { target, keys, interp? }`);
|
|
128
|
+
for (const k of Object.keys(raw))
|
|
129
|
+
if (!['target', 'keys', 'interp'].includes(k))
|
|
130
|
+
fail(`${ta}.${k} is not a track field (expected target, keys, interp)`);
|
|
131
|
+
const t = raw;
|
|
132
|
+
const r = resolveTarget(d, t.target);
|
|
133
|
+
if (typeof r === 'string')
|
|
134
|
+
fail(`${ta}.target ${r}`);
|
|
135
|
+
const res = r;
|
|
136
|
+
if (seen.has(t.target))
|
|
137
|
+
fail(`${ta}.target "${t.target}" is animated twice in this clip`);
|
|
138
|
+
seen.add(t.target);
|
|
139
|
+
if (t.interp !== undefined && !['linear', 'smooth', 'step'].includes(t.interp))
|
|
140
|
+
fail(`${ta}.interp must be "linear", "smooth" or "step"`);
|
|
141
|
+
if (!Array.isArray(t.keys) || t.keys.length < 1 || t.keys.length > TIMELINE_LIMITS.keys)
|
|
142
|
+
fail(`${ta}.keys must be a list of 1-${TIMELINE_LIMITS.keys} keys [time, value, ease?]`);
|
|
143
|
+
const [lo, hi] = res.bounds;
|
|
144
|
+
const shape = res.value === 'bool' ? 'true or false' : res.value === 'color' ? '"#rrggbb"' : res.value === 'number' ? `a number ${lo}-${hi}${res.range ? ' (a plain number while a track drives it, not [min, max])' : ''}` : `[${res.value === 'vec2' ? 'u, v' : 'x, y, z'}], each ${lo}-${hi}`;
|
|
145
|
+
t.keys.forEach((key, j) => {
|
|
146
|
+
const ka = `${ta}.keys[${j}]`;
|
|
147
|
+
if (!Array.isArray(key) || key.length < 2 || key.length > 3)
|
|
148
|
+
fail(`${ka} must be [time, value] or [time, value, ease]`);
|
|
149
|
+
if (!num(key[0], 0, 60))
|
|
150
|
+
fail(`${ka} time must be 0-60 seconds`);
|
|
151
|
+
if (j > 0 && !(key[0] > t.keys[j - 1][0]))
|
|
152
|
+
fail(`${ta}.keys must be in increasing time`);
|
|
153
|
+
const v = key[1];
|
|
154
|
+
const ok = res.value === 'bool' ? typeof v === 'boolean' : res.value === 'color' ? typeof v === 'string' && HEX.test(v)
|
|
155
|
+
: res.value === 'number' ? num(v, lo, hi) : Array.isArray(v) && v.length === (res.value === 'vec2' ? 2 : 3) && v.every((x) => num(x, lo, hi));
|
|
156
|
+
if (!ok)
|
|
157
|
+
fail(`${ka} value must be ${shape} for ${t.target}`);
|
|
158
|
+
if (key.length === 3 && !num(key[2], -100, 100))
|
|
159
|
+
fail(`${ka} ease must be a number -100-100 (Godot's transition: 1 linear, 2 ease in, 0.5 ease out, negative in-out, 0 hold)`);
|
|
160
|
+
});
|
|
161
|
+
return t;
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
/** Checks `tracks`, `clips` and `startClip` against a parsed document (layers already complete). */
|
|
165
|
+
export function parseTimeline(d, fail) {
|
|
166
|
+
const used = d.tracks !== undefined || d.clips !== undefined || d.startClip !== undefined;
|
|
167
|
+
if (!used)
|
|
168
|
+
return;
|
|
169
|
+
if (d.version < 7)
|
|
170
|
+
fail('tracks and clips are version 7: set "version": 7 (needs @umicat/three-sdk 1.42 or later)');
|
|
171
|
+
if (d.clips !== undefined && d.tracks !== undefined)
|
|
172
|
+
fail('tracks: with clips, each clip has its own tracks -- move these into a clip');
|
|
173
|
+
if (d.startClip !== undefined && d.clips === undefined)
|
|
174
|
+
fail('startClip names a clip, but there are no clips');
|
|
175
|
+
if (d.tracks !== undefined)
|
|
176
|
+
d.tracks = checkTracks(d, d.tracks, 'tracks', fail);
|
|
177
|
+
if (d.clips === undefined)
|
|
178
|
+
return;
|
|
179
|
+
if (!Array.isArray(d.clips) || d.clips.length < 1 || d.clips.length > TIMELINE_LIMITS.clips)
|
|
180
|
+
fail(`clips must be a list of 1-${TIMELINE_LIMITS.clips}`);
|
|
181
|
+
const names = new Set();
|
|
182
|
+
d.clips.forEach((c, i) => {
|
|
183
|
+
const at = `clips[${i}]`;
|
|
184
|
+
if (!c || typeof c !== 'object' || Array.isArray(c))
|
|
185
|
+
fail(`${at} must be { name, duration, loop, next?, tracks }`);
|
|
186
|
+
for (const k of Object.keys(c))
|
|
187
|
+
if (!['name', 'duration', 'loop', 'next', 'tracks'].includes(k))
|
|
188
|
+
fail(`${at}.${k} is not a clip field (expected name, duration, loop, next, tracks)`);
|
|
189
|
+
if (typeof c.name !== 'string' || !/^[a-z0-9_-]{1,40}$/i.test(c.name))
|
|
190
|
+
fail(`${at}.name must be 1-40 of a-z 0-9 _ -`);
|
|
191
|
+
if (names.has(c.name))
|
|
192
|
+
fail(`${at}.name "${c.name}" is used twice`);
|
|
193
|
+
names.add(c.name);
|
|
194
|
+
});
|
|
195
|
+
d.clips = d.clips.map((c, i) => {
|
|
196
|
+
const at = `clips[${i}]`;
|
|
197
|
+
if (!num(c.duration, .02, 60))
|
|
198
|
+
fail(`${at}.duration must be 0.02-60`);
|
|
199
|
+
if (typeof c.loop !== 'boolean')
|
|
200
|
+
fail(`${at}.loop must be a boolean`);
|
|
201
|
+
if (c.next !== undefined) {
|
|
202
|
+
if (!names.has(c.next))
|
|
203
|
+
fail(`${at}.next "${c.next}" is not a clip in this effect`);
|
|
204
|
+
if (c.next === c.name)
|
|
205
|
+
fail(`${at}.next is the clip itself: set "loop": true instead`);
|
|
206
|
+
if (c.loop)
|
|
207
|
+
fail(`${at} loops, so it never ends and its next ("${c.next}") would never play: drop one`);
|
|
208
|
+
}
|
|
209
|
+
return { ...c, tracks: checkTracks(d, c.tracks ?? [], `${at}.tracks`, fail) };
|
|
210
|
+
});
|
|
211
|
+
if (d.startClip !== undefined && !names.has(d.startClip))
|
|
212
|
+
fail(`startClip "${d.startClip}" is not a clip in this effect`);
|
|
213
|
+
}
|
|
214
|
+
/** The clips an instance plays: the document's own, or one named `main` made of `duration`, `loop` and `tracks`. */
|
|
215
|
+
export function effectClips(d) {
|
|
216
|
+
if (d.clips?.length)
|
|
217
|
+
return { clips: d.clips, start: d.startClip ?? d.clips[0].name };
|
|
218
|
+
return { clips: [{ name: 'main', duration: d.duration, loop: d.loop, tracks: d.tracks ?? [] }], start: 'main' };
|
|
219
|
+
}
|
|
220
|
+
// ------------------------------------------------------------------ sampling
|
|
221
|
+
/** Godot's `ease(x, c)`, exactly (core/math/math_funcs.cpp). */
|
|
222
|
+
export function godotEase(x, c) {
|
|
223
|
+
x = x < 0 ? 0 : x > 1 ? 1 : x;
|
|
224
|
+
if (c > 0)
|
|
225
|
+
return c < 1 ? 1 - Math.pow(1 - x, 1 / c) : Math.pow(x, c);
|
|
226
|
+
if (c < 0)
|
|
227
|
+
return x < .5 ? Math.pow(x * 2, -c) * .5 : (1 - Math.pow(1 - (x - .5) * 2, -c)) * .5 + .5;
|
|
228
|
+
return 0;
|
|
229
|
+
}
|
|
230
|
+
const toLinear = (c) => c <= .04045 ? c / 12.92 : Math.pow((c + .055) / 1.055, 2.4);
|
|
231
|
+
const toSrgb = (c) => c <= .0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - .055;
|
|
232
|
+
const hexToLinear = (h) => [1, 3, 5].map((i) => toLinear(parseInt(h.slice(i, i + 2), 16) / 255));
|
|
233
|
+
export const linearToHex = (rgb) => '#' + rgb.map((c) => Math.round(Math.max(0, Math.min(1, toSrgb(Math.max(0, c)))) * 255).toString(16).padStart(2, '0')).join('');
|
|
234
|
+
export function prepareTrack(t, kind) {
|
|
235
|
+
const values = t.keys.map(([, v]) => kind === 'color' ? hexToLinear(v) : kind === 'bool' ? [v ? 1 : 0] : Array.isArray(v) ? [...v] : [v]);
|
|
236
|
+
return { kind, times: t.keys.map((k) => k[0]), values, eases: t.keys.map((k) => k[2] ?? 1), interp: kind === 'bool' ? 'step' : t.interp ?? 'linear' };
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Godot's cubic between keys at non-uniform times (Barry-Goldman, as
|
|
240
|
+
* `cubic_interpolate_in_time`): `pre`/`post` are the neighbouring keys, or
|
|
241
|
+
* mirrored when there is none.
|
|
242
|
+
*/
|
|
243
|
+
function cubicInTime(from, to, pre, post, w, toT, preT, postT) {
|
|
244
|
+
const lerp = (a, b, x) => a + (b - a) * x;
|
|
245
|
+
const t = toT * w;
|
|
246
|
+
const a1 = lerp(pre, from, preT === 0 ? 0 : (t - preT) / -preT);
|
|
247
|
+
const a2 = lerp(from, to, toT === 0 ? .5 : t / toT);
|
|
248
|
+
const a3 = lerp(to, post, postT - toT === 0 ? 1 : (t - toT) / (postT - toT));
|
|
249
|
+
const b1 = lerp(a1, a2, toT - preT === 0 ? 0 : (t - preT) / (toT - preT));
|
|
250
|
+
const b2 = lerp(a2, a3, postT === 0 ? 1 : t / postT);
|
|
251
|
+
return lerp(b1, b2, toT === 0 ? .5 : t / toT);
|
|
252
|
+
}
|
|
253
|
+
/** The track's value at clip time `t`, into `out` (one number per component). Before the first key it holds the first; after the last, the last. */
|
|
254
|
+
export function sampleTrack(s, t, out) {
|
|
255
|
+
const { times, values } = s, n = times.length;
|
|
256
|
+
out.length = values[0].length;
|
|
257
|
+
if (t <= times[0] || n === 1) {
|
|
258
|
+
for (let c = 0; c < out.length; c++)
|
|
259
|
+
out[c] = values[0][c];
|
|
260
|
+
return out;
|
|
261
|
+
}
|
|
262
|
+
if (t >= times[n - 1]) {
|
|
263
|
+
for (let c = 0; c < out.length; c++)
|
|
264
|
+
out[c] = values[n - 1][c];
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
let i = 0;
|
|
268
|
+
while (i < n - 2 && t >= times[i + 1])
|
|
269
|
+
i++;
|
|
270
|
+
const ease = s.eases[i];
|
|
271
|
+
if (s.interp === 'step' || ease === 0) {
|
|
272
|
+
for (let c = 0; c < out.length; c++)
|
|
273
|
+
out[c] = values[i][c];
|
|
274
|
+
return out;
|
|
275
|
+
}
|
|
276
|
+
const span = times[i + 1] - times[i];
|
|
277
|
+
let w = (t - times[i]) / span;
|
|
278
|
+
if (ease !== 1)
|
|
279
|
+
w = godotEase(w, ease);
|
|
280
|
+
for (let c = 0; c < out.length; c++) {
|
|
281
|
+
const a = values[i][c], b = values[i + 1][c];
|
|
282
|
+
if (s.interp === 'linear') {
|
|
283
|
+
out[c] = a + (b - a) * w;
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
const pre = i > 0 ? values[i - 1][c] : a, post = i + 2 < n ? values[i + 2][c] : b;
|
|
287
|
+
const preT = i > 0 ? times[i - 1] - times[i] : -span, postT = i + 2 < n ? times[i + 2] - times[i] : 2 * span;
|
|
288
|
+
out[c] = cubicInTime(a, b, pre, post, w, span, preT, postT);
|
|
289
|
+
}
|
|
290
|
+
return out;
|
|
291
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@umicat/three-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.42.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",
|