@umicat/three-sdk 1.33.0 → 1.35.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 +21 -0
- package/dist/PixelRatio.d.ts +28 -0
- package/dist/PixelRatio.js +54 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/vfx/VfxInstance.d.ts +53 -0
- package/dist/vfx/VfxInstance.js +248 -0
- package/dist/vfx/document.d.ts +104 -0
- package/dist/vfx/document.js +134 -0
- package/dist/vfx/index.d.ts +6 -0
- package/dist/vfx/index.js +9 -0
- package/dist/vfx/load.d.ts +42 -0
- package/dist/vfx/load.js +79 -0
- package/dist/vfx/templates.d.ts +15 -0
- package/dist/vfx/templates.js +44 -0
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -61,6 +61,27 @@ guide**, which nothing here points at.
|
|
|
61
61
|
your game gameplay
|
|
62
62
|
```
|
|
63
63
|
|
|
64
|
+
## Effects — `@umicat/three-sdk/vfx` (1.35.0)
|
|
65
|
+
|
|
66
|
+
Plays `.vfx.json` effects made in the VFX Editor. A separate entry point that
|
|
67
|
+
imports `three` and nothing else, so the editor and any game can use it
|
|
68
|
+
without the physics or platform layers.
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
import { loadVfx } from '@umicat/three-sdk/vfx';
|
|
72
|
+
const fire = await loadVfx('uploaded/campfire.vfx.json'); // + every sprite sheet it names
|
|
73
|
+
const fx = fire.spawn(); // many copies share the sheets
|
|
74
|
+
scene.add(fx.root);
|
|
75
|
+
fx.setViewportHeight(renderer.domElement.height); // particle sizes are pixels
|
|
76
|
+
// each frame: fx.update(dt); one-shot: if (fx.finished) fx.dispose();
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
An effect has two kinds of layer: **emitters** (seeded, fixed-step CPU
|
|
80
|
+
particles fired upward from a disc) and **flipbooks** (a sprite sheet played
|
|
81
|
+
frame by frame on one quad, facing the camera or flat on the ground). A
|
|
82
|
+
flipbook names its sheet by bare filename; `loadVfx` resolves it beside the
|
|
83
|
+
effect file and rejects, naming the sheet, if it cannot load it.
|
|
84
|
+
|
|
64
85
|
## What is proven, and by what
|
|
65
86
|
|
|
66
87
|
`npm test` runs a real three.js game in a real browser against a host speaking
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import * as THREE from 'three';
|
|
2
|
+
/**
|
|
3
|
+
* The pixel ratio to render at, capped by AREA rather than by ratio.
|
|
4
|
+
*
|
|
5
|
+
* Every 3D game here copied `setPixelRatio(Math.min(devicePixelRatio, 2))` out
|
|
6
|
+
* of the template, and a ratio cap bounds nothing that matters: what varies
|
|
7
|
+
* between devices is the viewport's AREA. Measured on an iPhone Duo — closed
|
|
8
|
+
* display 466x678 CSS, open display 951x669, both dpr 3 — the same game goes
|
|
9
|
+
* from 2.84 to 5.72 megapixels of canvas by being unfolded. A Phaser game
|
|
10
|
+
* (Catopia) had its web process killed ~700ms into the load on the open
|
|
11
|
+
* display and was fine on the closed one; a 3D game draws more per pixel than
|
|
12
|
+
* that, not less.
|
|
13
|
+
*
|
|
14
|
+
* Below the cap this returns exactly what the old expression did, so no
|
|
15
|
+
* ordinary phone changes: a 3x 1080p phone is 2.4 megapixels at ratio 2.
|
|
16
|
+
*
|
|
17
|
+
* Never returns less than 1 — a backing store smaller than the CSS box is
|
|
18
|
+
* blurrier than doing nothing.
|
|
19
|
+
*/
|
|
20
|
+
export declare function fitPixelRatio(width?: number, height?: number): number;
|
|
21
|
+
/**
|
|
22
|
+
* Apply it, and keep applying it.
|
|
23
|
+
*
|
|
24
|
+
* The ratio is not a constant on a folding phone: unfolding changes the
|
|
25
|
+
* viewport's area under a renderer that was configured once at boot. Games
|
|
26
|
+
* already re-`setSize` on resize; this is the half they were missing.
|
|
27
|
+
*/
|
|
28
|
+
export declare function trackPixelRatio(renderer: THREE.WebGLRenderer): () => void;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ceiling on the BACKING STORE, in device pixels.
|
|
3
|
+
*
|
|
4
|
+
* Kept the same number as `@umicat/phaser-sdk` and both app player hosts, on
|
|
5
|
+
* purpose: a game should not get a different resolution for being written
|
|
6
|
+
* against a different engine.
|
|
7
|
+
*/
|
|
8
|
+
const MAX_PIXELS = 3500000;
|
|
9
|
+
/** Never above this, however small the viewport. Matches the template's. */
|
|
10
|
+
const RATIO_CAP = 2;
|
|
11
|
+
/**
|
|
12
|
+
* The pixel ratio to render at, capped by AREA rather than by ratio.
|
|
13
|
+
*
|
|
14
|
+
* Every 3D game here copied `setPixelRatio(Math.min(devicePixelRatio, 2))` out
|
|
15
|
+
* of the template, and a ratio cap bounds nothing that matters: what varies
|
|
16
|
+
* between devices is the viewport's AREA. Measured on an iPhone Duo — closed
|
|
17
|
+
* display 466x678 CSS, open display 951x669, both dpr 3 — the same game goes
|
|
18
|
+
* from 2.84 to 5.72 megapixels of canvas by being unfolded. A Phaser game
|
|
19
|
+
* (Catopia) had its web process killed ~700ms into the load on the open
|
|
20
|
+
* display and was fine on the closed one; a 3D game draws more per pixel than
|
|
21
|
+
* that, not less.
|
|
22
|
+
*
|
|
23
|
+
* Below the cap this returns exactly what the old expression did, so no
|
|
24
|
+
* ordinary phone changes: a 3x 1080p phone is 2.4 megapixels at ratio 2.
|
|
25
|
+
*
|
|
26
|
+
* Never returns less than 1 — a backing store smaller than the CSS box is
|
|
27
|
+
* blurrier than doing nothing.
|
|
28
|
+
*/
|
|
29
|
+
export function fitPixelRatio(width = typeof window === 'undefined' ? 0 : window.innerWidth, height = typeof window === 'undefined' ? 0 : window.innerHeight) {
|
|
30
|
+
const dpr = typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1;
|
|
31
|
+
if (width <= 0 || height <= 0)
|
|
32
|
+
return Math.min(dpr, RATIO_CAP);
|
|
33
|
+
const byArea = Math.sqrt(MAX_PIXELS / (width * height));
|
|
34
|
+
return Math.max(1, Math.min(dpr, RATIO_CAP, byArea));
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Apply it, and keep applying it.
|
|
38
|
+
*
|
|
39
|
+
* The ratio is not a constant on a folding phone: unfolding changes the
|
|
40
|
+
* viewport's area under a renderer that was configured once at boot. Games
|
|
41
|
+
* already re-`setSize` on resize; this is the half they were missing.
|
|
42
|
+
*/
|
|
43
|
+
export function trackPixelRatio(renderer) {
|
|
44
|
+
const apply = () => { renderer.setPixelRatio(fitPixelRatio()); };
|
|
45
|
+
apply();
|
|
46
|
+
if (typeof window === 'undefined')
|
|
47
|
+
return () => { };
|
|
48
|
+
window.addEventListener('resize', apply);
|
|
49
|
+
window.addEventListener('orientationchange', apply);
|
|
50
|
+
return () => {
|
|
51
|
+
window.removeEventListener('resize', apply);
|
|
52
|
+
window.removeEventListener('orientationchange', apply);
|
|
53
|
+
};
|
|
54
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ export { CharacterController3D } from './CharacterController3D.js';
|
|
|
6
6
|
export type { CharacterOptions, CharacterState, CharacterInput } from './CharacterController3D.js';
|
|
7
7
|
export { CharacterAnimator } from './CharacterAnimator.js';
|
|
8
8
|
export type { ClipMap, CharacterAnimatorOptions } from './CharacterAnimator.js';
|
|
9
|
+
export { fitPixelRatio, trackPixelRatio } from './PixelRatio.js';
|
|
9
10
|
export { Input3D } from './Input3D.js';
|
|
10
11
|
export type { Input3DOptions, Input3DAction } from './Input3D.js';
|
|
11
12
|
export { attachToSocket, findBone, boneNames } from './Sockets.js';
|
package/dist/index.js
CHANGED
|
@@ -8,6 +8,7 @@ export * from './scene3d.js';
|
|
|
8
8
|
export { loadScene3D, loadModelAsset, heightfieldGeometry, makeHeightfield, makeWaterSurface, HEIGHTMAP_LIBRARY, HEIGHTMAP_DEFAULT_SIZE } from './SceneLoader3D.js';
|
|
9
9
|
export { CharacterController3D } from './CharacterController3D.js';
|
|
10
10
|
export { CharacterAnimator } from './CharacterAnimator.js';
|
|
11
|
+
export { fitPixelRatio, trackPixelRatio } from './PixelRatio.js';
|
|
11
12
|
export { Input3D } from './Input3D.js';
|
|
12
13
|
export { attachToSocket, findBone, boneNames } from './Sockets.js';
|
|
13
14
|
export { flashTint, updateTints, isTinted } from './Tint.js';
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import * as T from 'three';
|
|
2
|
+
import { type VfxDocument } from './document.js';
|
|
3
|
+
/** Where a flipbook's sheet comes from. A Map / record keyed by the document's
|
|
4
|
+
* `texture` filename, or a function. A layer whose texture is missing draws
|
|
5
|
+
* nothing rather than failing the whole effect. */
|
|
6
|
+
export type VfxTextureSource = Map<string, T.Texture> | Record<string, T.Texture> | ((filename: string) => T.Texture | undefined);
|
|
7
|
+
export interface VfxInstanceOptions {
|
|
8
|
+
textures?: VfxTextureSource;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* One playing copy of an effect. Shared by the VFX Editor and games: it owns
|
|
12
|
+
* no renderer, no DOM and no animation loop -- add `root` to a scene and call
|
|
13
|
+
* `update(seconds)` from your own frame loop.
|
|
14
|
+
*
|
|
15
|
+
* Simulation is fixed-step (1/60 s) and seeded, so the same document plays the
|
|
16
|
+
* same way at any frame rate, and `reset()` replays it exactly.
|
|
17
|
+
*/
|
|
18
|
+
export declare class VfxInstance {
|
|
19
|
+
readonly root: T.Group<T.Object3DEventMap>;
|
|
20
|
+
readonly document: VfxDocument;
|
|
21
|
+
/** Seconds of simulated time since start (or the last reset). */
|
|
22
|
+
time: number;
|
|
23
|
+
private particleLayers;
|
|
24
|
+
private flipbookLayers;
|
|
25
|
+
private state;
|
|
26
|
+
private accumulator;
|
|
27
|
+
constructor(document: VfxDocument, options?: VfxInstanceOptions);
|
|
28
|
+
private buildParticles;
|
|
29
|
+
private buildFlipbook;
|
|
30
|
+
private random;
|
|
31
|
+
/** Back to time 0 with the original seed: a replay is identical to the first play. */
|
|
32
|
+
reset(): void;
|
|
33
|
+
get particleCount(): number;
|
|
34
|
+
/** True once a NON-looping effect has stopped emitting, every particle has
|
|
35
|
+
* died and every flipbook has played out -- the moment to `dispose()` a
|
|
36
|
+
* one-shot. Always false for a looping effect. */
|
|
37
|
+
get finished(): boolean;
|
|
38
|
+
/** Point sizes are in pixels, so particles need the drawing-buffer height (CSS height x pixel ratio). */
|
|
39
|
+
setViewportHeight(height: number): void;
|
|
40
|
+
/** Advance by `delta` seconds. Gaps over 250 ms are capped, so a backgrounded tab does not dump a burst. */
|
|
41
|
+
update(delta: number): void;
|
|
42
|
+
/** Whether the effect is still starting new particles / new flipbook cycles. */
|
|
43
|
+
private get running();
|
|
44
|
+
private step;
|
|
45
|
+
/** The frame a flipbook shows now, or -1 for none. A looping flipbook keeps
|
|
46
|
+
* cycling while the effect runs and, once it stops, finishes its current
|
|
47
|
+
* cycle -- the flipbook counterpart of particles draining. */
|
|
48
|
+
private frameOf;
|
|
49
|
+
private draw;
|
|
50
|
+
/** Frees this instance's GPU buffers. Textures are NOT disposed: they are
|
|
51
|
+
* shared between instances and belong to whoever loaded them (`VfxEffect`). */
|
|
52
|
+
dispose(): void;
|
|
53
|
+
}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import * as T from 'three';
|
|
2
|
+
import { parseVfx } from './document.js';
|
|
3
|
+
const SHARED_QUAD = (() => {
|
|
4
|
+
// Corners in [0,1]^2 with y UP; the shader turns them into a cell-sized quad.
|
|
5
|
+
const g = new T.BufferGeometry();
|
|
6
|
+
g.setAttribute('position', new T.BufferAttribute(new Float32Array([0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0]), 3));
|
|
7
|
+
g.setIndex([0, 1, 2, 0, 2, 3]);
|
|
8
|
+
return g;
|
|
9
|
+
})();
|
|
10
|
+
const FLIPBOOK_VERTEX = `
|
|
11
|
+
uniform vec2 uSize; uniform vec2 uOrigin; uniform vec3 uCell; uniform float uGround;
|
|
12
|
+
varying vec2 vUv;
|
|
13
|
+
void main(){
|
|
14
|
+
vec2 c = position.xy;
|
|
15
|
+
float top = 1.0 - c.y; // 0 at the cell's top edge
|
|
16
|
+
vec2 offset = vec2((c.x - uOrigin.x) * uSize.x, (uOrigin.y - top) * uSize.y);
|
|
17
|
+
float frame = uCell.z, cols = uCell.x, rows = uCell.y;
|
|
18
|
+
float col = mod(frame, cols), row = floor(frame / cols);
|
|
19
|
+
vUv = vec2((col + c.x) / cols, 1.0 - (row + top) / rows);
|
|
20
|
+
if (uGround > 0.5) {
|
|
21
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4(offset.x, 0.0, -offset.y, 1.0);
|
|
22
|
+
} else {
|
|
23
|
+
float scale = length(modelMatrix[0].xyz);
|
|
24
|
+
vec4 center = modelViewMatrix * vec4(0.0, 0.0, 0.0, 1.0);
|
|
25
|
+
center.xy += offset * scale;
|
|
26
|
+
gl_Position = projectionMatrix * center;
|
|
27
|
+
}
|
|
28
|
+
}`;
|
|
29
|
+
const FLIPBOOK_FRAGMENT = `
|
|
30
|
+
uniform sampler2D uMap; uniform vec3 uTint; uniform float uOpacity;
|
|
31
|
+
varying vec2 vUv;
|
|
32
|
+
void main(){
|
|
33
|
+
vec4 texel = texture2D(uMap, vUv);
|
|
34
|
+
gl_FragColor = vec4(texel.rgb * uTint, texel.a * uOpacity);
|
|
35
|
+
#include <tonemapping_fragment>
|
|
36
|
+
#include <colorspace_fragment>
|
|
37
|
+
}`;
|
|
38
|
+
function resolveTexture(source, name) {
|
|
39
|
+
if (!source)
|
|
40
|
+
return undefined;
|
|
41
|
+
if (typeof source === 'function')
|
|
42
|
+
return source(name);
|
|
43
|
+
if (source instanceof Map)
|
|
44
|
+
return source.get(name);
|
|
45
|
+
return Object.prototype.hasOwnProperty.call(source, name) ? source[name] : undefined;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* One playing copy of an effect. Shared by the VFX Editor and games: it owns
|
|
49
|
+
* no renderer, no DOM and no animation loop -- add `root` to a scene and call
|
|
50
|
+
* `update(seconds)` from your own frame loop.
|
|
51
|
+
*
|
|
52
|
+
* Simulation is fixed-step (1/60 s) and seeded, so the same document plays the
|
|
53
|
+
* same way at any frame rate, and `reset()` replays it exactly.
|
|
54
|
+
*/
|
|
55
|
+
export class VfxInstance {
|
|
56
|
+
constructor(document, options = {}) {
|
|
57
|
+
this.root = new T.Group();
|
|
58
|
+
/** Seconds of simulated time since start (or the last reset). */
|
|
59
|
+
this.time = 0;
|
|
60
|
+
this.particleLayers = [];
|
|
61
|
+
this.flipbookLayers = [];
|
|
62
|
+
this.state = 1;
|
|
63
|
+
this.accumulator = 0;
|
|
64
|
+
this.document = parseVfx(document);
|
|
65
|
+
this.state = this.document.seed;
|
|
66
|
+
this.root.name = this.document.name;
|
|
67
|
+
for (const config of this.document.emitters)
|
|
68
|
+
this.particleLayers.push(this.buildParticles(config));
|
|
69
|
+
for (const config of this.document.flipbooks ?? [])
|
|
70
|
+
this.flipbookLayers.push(this.buildFlipbook(config, resolveTexture(options.textures, config.texture)));
|
|
71
|
+
this.draw();
|
|
72
|
+
}
|
|
73
|
+
buildParticles(config) {
|
|
74
|
+
const capacity = Math.max(1, Math.ceil(config.rate * config.lifetime) + 2);
|
|
75
|
+
const positions = new Float32Array(capacity * 3), colors = new Float32Array(capacity * 3), sizes = new Float32Array(capacity), alphas = new Float32Array(capacity);
|
|
76
|
+
const geometry = new T.BufferGeometry();
|
|
77
|
+
for (const [name, array, itemSize] of [['position', positions, 3], ['color', colors, 3], ['particleSize', sizes, 1], ['particleAlpha', alphas, 1]]) {
|
|
78
|
+
geometry.setAttribute(name, new T.BufferAttribute(array, itemSize).setUsage(T.DynamicDrawUsage));
|
|
79
|
+
}
|
|
80
|
+
geometry.setDrawRange(0, 0);
|
|
81
|
+
const material = new T.ShaderMaterial({
|
|
82
|
+
transparent: true, depthWrite: false,
|
|
83
|
+
blending: config.blend === 'additive' ? T.AdditiveBlending : T.NormalBlending,
|
|
84
|
+
uniforms: { viewportHeight: { value: 600 } },
|
|
85
|
+
vertexShader: `attribute vec3 color; attribute float particleSize; attribute float particleAlpha; uniform float viewportHeight; varying vec3 tint; varying float alpha;
|
|
86
|
+
void main(){vec4 p=modelViewMatrix*vec4(position,1.);gl_Position=projectionMatrix*p;float scale=length(modelMatrix[0].xyz);gl_PointSize=clamp(particleSize*scale*viewportHeight*projectionMatrix[1][1]/max(.1,-p.z),1.,256.);tint=color;alpha=particleAlpha;}`,
|
|
87
|
+
fragmentShader: `varying vec3 tint; varying float alpha;
|
|
88
|
+
void main(){float r=length(gl_PointCoord-.5)*2.;if(r>=1.)discard;gl_FragColor=vec4(tint,alpha*pow(1.-r,2.));
|
|
89
|
+
#include <tonemapping_fragment>
|
|
90
|
+
#include <colorspace_fragment>
|
|
91
|
+
}`,
|
|
92
|
+
});
|
|
93
|
+
const mesh = new T.Points(geometry, material);
|
|
94
|
+
mesh.frustumCulled = false;
|
|
95
|
+
mesh.name = config.id;
|
|
96
|
+
this.root.add(mesh);
|
|
97
|
+
return { config, particles: [], fraction: 0, mesh, positions, colors, sizes, alphas, capacity };
|
|
98
|
+
}
|
|
99
|
+
buildFlipbook(config, texture) {
|
|
100
|
+
const material = new T.ShaderMaterial({
|
|
101
|
+
transparent: true, depthWrite: false, side: T.DoubleSide,
|
|
102
|
+
blending: config.blend === 'additive' ? T.AdditiveBlending : T.NormalBlending,
|
|
103
|
+
uniforms: {
|
|
104
|
+
uMap: { value: texture ?? null }, uSize: { value: new T.Vector2(config.size, config.size) },
|
|
105
|
+
uOrigin: { value: new T.Vector2(config.originU, config.originV) }, uCell: { value: new T.Vector3(config.cols, config.rows, 0) },
|
|
106
|
+
uGround: { value: config.facing === 'ground' ? 1 : 0 }, uTint: { value: new T.Color(config.color) }, uOpacity: { value: config.opacity },
|
|
107
|
+
},
|
|
108
|
+
vertexShader: FLIPBOOK_VERTEX, fragmentShader: FLIPBOOK_FRAGMENT,
|
|
109
|
+
});
|
|
110
|
+
const mesh = new T.Mesh(SHARED_QUAD, material);
|
|
111
|
+
mesh.frustumCulled = false;
|
|
112
|
+
mesh.name = config.id;
|
|
113
|
+
mesh.visible = false;
|
|
114
|
+
this.root.add(mesh);
|
|
115
|
+
return { config, mesh, material, texture, done: !config.enabled };
|
|
116
|
+
}
|
|
117
|
+
random() { this.state = this.state * 16807 % 2147483647; return (this.state - 1) / 2147483646; }
|
|
118
|
+
/** Back to time 0 with the original seed: a replay is identical to the first play. */
|
|
119
|
+
reset() {
|
|
120
|
+
this.time = 0;
|
|
121
|
+
this.accumulator = 0;
|
|
122
|
+
this.state = this.document.seed;
|
|
123
|
+
for (const l of this.particleLayers) {
|
|
124
|
+
l.particles = [];
|
|
125
|
+
l.fraction = 0;
|
|
126
|
+
}
|
|
127
|
+
for (const f of this.flipbookLayers)
|
|
128
|
+
f.done = !f.config.enabled;
|
|
129
|
+
this.draw();
|
|
130
|
+
}
|
|
131
|
+
get particleCount() { return this.particleLayers.reduce((sum, l) => sum + l.particles.length, 0); }
|
|
132
|
+
/** True once a NON-looping effect has stopped emitting, every particle has
|
|
133
|
+
* died and every flipbook has played out -- the moment to `dispose()` a
|
|
134
|
+
* one-shot. Always false for a looping effect. */
|
|
135
|
+
get finished() {
|
|
136
|
+
if (this.document.loop || this.time < this.document.duration)
|
|
137
|
+
return false;
|
|
138
|
+
return this.particleCount === 0 && this.flipbookLayers.every((f) => f.done);
|
|
139
|
+
}
|
|
140
|
+
/** Point sizes are in pixels, so particles need the drawing-buffer height (CSS height x pixel ratio). */
|
|
141
|
+
setViewportHeight(height) { for (const l of this.particleLayers)
|
|
142
|
+
l.mesh.material.uniforms.viewportHeight.value = height; }
|
|
143
|
+
/** Advance by `delta` seconds. Gaps over 250 ms are capped, so a backgrounded tab does not dump a burst. */
|
|
144
|
+
update(delta) {
|
|
145
|
+
if (!Number.isFinite(delta) || delta < 0)
|
|
146
|
+
return;
|
|
147
|
+
this.accumulator += Math.min(delta, .25);
|
|
148
|
+
while (this.accumulator >= 1 / 60) {
|
|
149
|
+
this.step(1 / 60);
|
|
150
|
+
this.accumulator -= 1 / 60;
|
|
151
|
+
}
|
|
152
|
+
this.draw();
|
|
153
|
+
}
|
|
154
|
+
/** Whether the effect is still starting new particles / new flipbook cycles. */
|
|
155
|
+
get running() { return this.document.loop || this.time < this.document.duration; }
|
|
156
|
+
step(dt) {
|
|
157
|
+
const emit = this.running;
|
|
158
|
+
this.time += dt;
|
|
159
|
+
for (const l of this.particleLayers) {
|
|
160
|
+
const c = l.config;
|
|
161
|
+
l.particles = l.particles.filter((p) => {
|
|
162
|
+
p.age += dt;
|
|
163
|
+
if (p.age >= p.life)
|
|
164
|
+
return false;
|
|
165
|
+
p.vy += c.gravity * dt;
|
|
166
|
+
p.x += p.vx * dt;
|
|
167
|
+
p.y += p.vy * dt;
|
|
168
|
+
p.z += p.vz * dt;
|
|
169
|
+
return true;
|
|
170
|
+
});
|
|
171
|
+
if (!emit || !c.enabled)
|
|
172
|
+
continue;
|
|
173
|
+
l.fraction += c.rate * dt;
|
|
174
|
+
while (l.fraction >= 1) {
|
|
175
|
+
l.fraction--;
|
|
176
|
+
const a = this.random() * Math.PI * 2, r = this.random() * .15;
|
|
177
|
+
if (l.particles.length >= l.capacity)
|
|
178
|
+
continue;
|
|
179
|
+
l.particles.push({ age: 0, life: c.lifetime, x: Math.cos(a) * r, y: 0, z: Math.sin(a) * r, vx: (this.random() - .5) * c.spread, vy: c.speed * (.8 + this.random() * .4), vz: (this.random() - .5) * c.spread });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/** The frame a flipbook shows now, or -1 for none. A looping flipbook keeps
|
|
184
|
+
* cycling while the effect runs and, once it stops, finishes its current
|
|
185
|
+
* cycle -- the flipbook counterpart of particles draining. */
|
|
186
|
+
frameOf(f) {
|
|
187
|
+
const t = this.time - f.delay;
|
|
188
|
+
if (!f.enabled || t < 0)
|
|
189
|
+
return -1;
|
|
190
|
+
const n = Math.floor(t * f.fps);
|
|
191
|
+
if (!f.loop)
|
|
192
|
+
return n < f.frames ? n : -1;
|
|
193
|
+
if (this.running)
|
|
194
|
+
return n % f.frames;
|
|
195
|
+
// Stopped: the cycle that was playing when the effect stopped may finish.
|
|
196
|
+
const stoppedAt = Math.floor(Math.max(0, this.document.duration - f.delay) * f.fps);
|
|
197
|
+
const cycleEnd = (Math.floor(stoppedAt / f.frames) + 1) * f.frames;
|
|
198
|
+
return n < cycleEnd ? n % f.frames : -1;
|
|
199
|
+
}
|
|
200
|
+
draw() {
|
|
201
|
+
for (const l of this.particleLayers) {
|
|
202
|
+
const c = l.config, start = new T.Color(c.color), end = new T.Color(c.endColor), color = new T.Color();
|
|
203
|
+
l.particles.forEach((p, i) => {
|
|
204
|
+
const t = p.age / p.life;
|
|
205
|
+
l.positions.set([p.x, p.y, p.z], i * 3);
|
|
206
|
+
color.copy(start).lerp(end, t);
|
|
207
|
+
l.colors.set([color.r, color.g, color.b], i * 3);
|
|
208
|
+
l.sizes[i] = T.MathUtils.lerp(c.size, c.endSize, t);
|
|
209
|
+
l.alphas[i] = c.opacity * Math.min(1, t * 8) * (1 - t);
|
|
210
|
+
});
|
|
211
|
+
l.mesh.geometry.setDrawRange(0, l.particles.length);
|
|
212
|
+
for (const attribute of Object.values(l.mesh.geometry.attributes))
|
|
213
|
+
attribute.needsUpdate = true;
|
|
214
|
+
}
|
|
215
|
+
for (const f of this.flipbookLayers) {
|
|
216
|
+
const frame = this.frameOf(f.config);
|
|
217
|
+
if (frame < 0 && this.time >= f.config.delay)
|
|
218
|
+
f.done = true;
|
|
219
|
+
if (frame >= 0)
|
|
220
|
+
f.done = false;
|
|
221
|
+
const image = f.texture?.image;
|
|
222
|
+
const ready = !!(image && image.width && image.height);
|
|
223
|
+
f.mesh.visible = frame >= 0 && ready;
|
|
224
|
+
if (!f.mesh.visible)
|
|
225
|
+
continue;
|
|
226
|
+
const c = f.config, u = f.material.uniforms;
|
|
227
|
+
// Height follows the CELL's aspect, read from the sheet itself, so a
|
|
228
|
+
// non-square sheet or grid is never stretched.
|
|
229
|
+
const cellAspect = (image.height / c.rows) / (image.width / c.cols);
|
|
230
|
+
u.uSize.value.set(c.size, c.size * cellAspect);
|
|
231
|
+
u.uCell.value.z = frame;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/** Frees this instance's GPU buffers. Textures are NOT disposed: they are
|
|
235
|
+
* shared between instances and belong to whoever loaded them (`VfxEffect`). */
|
|
236
|
+
dispose() {
|
|
237
|
+
for (const l of this.particleLayers) {
|
|
238
|
+
l.mesh.geometry.dispose();
|
|
239
|
+
l.mesh.material.dispose();
|
|
240
|
+
}
|
|
241
|
+
for (const f of this.flipbookLayers)
|
|
242
|
+
f.material.dispose();
|
|
243
|
+
this.particleLayers = [];
|
|
244
|
+
this.flipbookLayers = [];
|
|
245
|
+
this.root.removeFromParent();
|
|
246
|
+
this.root.clear();
|
|
247
|
+
}
|
|
248
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
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`: CPU-simulated point particles. Particles start on a small disc
|
|
6
|
+
* at the origin and fire UPWARD; `spread` is horizontal jitter and `gravity`
|
|
7
|
+
* a vertical acceleration (positive rises, negative falls).
|
|
8
|
+
* - `flipbooks`: a sprite sheet played frame by frame on one quad -- an
|
|
9
|
+
* explosion, a muzzle flash, a slash. The sheet is an IMAGE ASSET next to the
|
|
10
|
+
* effect, named by `texture`; the grid is `cols` x `rows`, read left to
|
|
11
|
+
* right, top to bottom, and the first `frames` cells are played.
|
|
12
|
+
*
|
|
13
|
+
* `flipbooks` is optional, so every document written before it existed is
|
|
14
|
+
* still valid unchanged.
|
|
15
|
+
*/
|
|
16
|
+
export interface Emitter {
|
|
17
|
+
id: string;
|
|
18
|
+
enabled: boolean;
|
|
19
|
+
rate: number;
|
|
20
|
+
lifetime: number;
|
|
21
|
+
speed: number;
|
|
22
|
+
spread: number;
|
|
23
|
+
gravity: number;
|
|
24
|
+
size: number;
|
|
25
|
+
endSize: number;
|
|
26
|
+
opacity: number;
|
|
27
|
+
color: string;
|
|
28
|
+
endColor: string;
|
|
29
|
+
blend: 'normal' | 'additive';
|
|
30
|
+
}
|
|
31
|
+
export interface Flipbook {
|
|
32
|
+
id: string;
|
|
33
|
+
enabled: boolean;
|
|
34
|
+
/** Filename of an image asset (png / webp / jpg) in the same folder as the effect. */
|
|
35
|
+
texture: string;
|
|
36
|
+
cols: number;
|
|
37
|
+
rows: number;
|
|
38
|
+
frames: number;
|
|
39
|
+
fps: number;
|
|
40
|
+
/** Repeat while the effect is running; otherwise play once. */
|
|
41
|
+
loop: boolean;
|
|
42
|
+
/** Seconds after the effect starts before the first frame shows. */
|
|
43
|
+
delay: number;
|
|
44
|
+
/** World WIDTH of one cell; the height follows the cell's own aspect. */
|
|
45
|
+
size: number;
|
|
46
|
+
/** Where the effect's origin sits inside the cell: 0..1 from the cell's LEFT and TOP edge. */
|
|
47
|
+
originU: number;
|
|
48
|
+
originV: number;
|
|
49
|
+
/** `camera`: a billboard that always faces the viewer. `ground`: lies flat (an area ring, a scorch mark). */
|
|
50
|
+
facing: 'camera' | 'ground';
|
|
51
|
+
opacity: number;
|
|
52
|
+
/** Multiplied with the sheet's colours; #ffffff leaves them unchanged. */
|
|
53
|
+
color: string;
|
|
54
|
+
blend: 'normal' | 'additive';
|
|
55
|
+
}
|
|
56
|
+
export interface VfxDocument {
|
|
57
|
+
version: 1;
|
|
58
|
+
name: string;
|
|
59
|
+
seed: number;
|
|
60
|
+
duration: number;
|
|
61
|
+
loop: boolean;
|
|
62
|
+
humanCurated: boolean;
|
|
63
|
+
emitters: Emitter[];
|
|
64
|
+
flipbooks?: Flipbook[];
|
|
65
|
+
}
|
|
66
|
+
export declare const LIMITS: {
|
|
67
|
+
readonly rate: 300;
|
|
68
|
+
readonly lifetime: 10;
|
|
69
|
+
readonly emitters: 8;
|
|
70
|
+
readonly layers: 8;
|
|
71
|
+
readonly particles: 4000;
|
|
72
|
+
readonly cells: 4096;
|
|
73
|
+
};
|
|
74
|
+
export declare function campfire(): VfxDocument;
|
|
75
|
+
/** Per-emitter numeric fields and their allowed ranges (shared with the editor's inputs). */
|
|
76
|
+
export declare const EMITTER_RANGES: readonly [readonly ["rate", 0, 300], readonly ["lifetime", 0.1, 10], readonly ["speed", 0, 10], readonly ["spread", 0, 5], readonly ["gravity", -10, 10], readonly ["size", 0.001, 5], readonly ["endSize", 0.001, 5], readonly ["opacity", 0, 1]];
|
|
77
|
+
/** Per-flipbook numeric fields and their allowed ranges. `frames` is further capped at cols x rows. */
|
|
78
|
+
export declare const FLIPBOOK_RANGES: readonly [readonly ["cols", 1, 64], readonly ["rows", 1, 64], readonly ["frames", 1, 4096], readonly ["fps", 1, 120], readonly ["delay", 0, 60], readonly ["size", 0.01, 50], readonly ["originU", 0, 1], readonly ["originV", 0, 1], readonly ["opacity", 0, 1]];
|
|
79
|
+
/** A bare filename with an image extension: no folders, so it can only name a sibling of the effect. */
|
|
80
|
+
export declare const TEXTURE_PATTERN: RegExp;
|
|
81
|
+
/** A new flipbook layer with sensible defaults, for the editor's "Add" and for the agent. */
|
|
82
|
+
export declare function flipbookLayer(id: string, texture: string): Flipbook;
|
|
83
|
+
/** Every texture filename a document needs, once each. */
|
|
84
|
+
export declare function vfxTextures(document: VfxDocument): string[];
|
|
85
|
+
/**
|
|
86
|
+
* Reject malformed/unsupported resources instead of silently rewriting them.
|
|
87
|
+
* The message names the field and its allowed range: the agent writes these
|
|
88
|
+
* documents by hand, and "Invalid VFX resource" gave it nothing to fix.
|
|
89
|
+
*/
|
|
90
|
+
export declare function parseVfx(value: unknown): VfxDocument;
|
|
91
|
+
/** An effect is a project ASSET named `<stem>.vfx.json`; the server keeps the
|
|
92
|
+
* whole compound extension, so this suffix is what marks one. */
|
|
93
|
+
export declare const VFX_SUFFIX = ".vfx.json";
|
|
94
|
+
export declare function isVfxFilename(filename: string): boolean;
|
|
95
|
+
/**
|
|
96
|
+
* A filename for a NEW effect, shaped the way the server's sanitizer will keep
|
|
97
|
+
* it (lowercase ASCII letters, digits, `-` and `_`) and free in this project.
|
|
98
|
+
*
|
|
99
|
+
* It has to be free client-side: an upload whose name the project already
|
|
100
|
+
* holds REPLACES that file -- that is the intended behaviour for re-uploading
|
|
101
|
+
* your own asset, and silent data loss for "New effect" twice in a row.
|
|
102
|
+
* A name with no ASCII in it (any CJK name) becomes `effect`.
|
|
103
|
+
*/
|
|
104
|
+
export declare function vfxFilename(name: string, taken: Iterable<string>): string;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
export const LIMITS = { rate: 300, lifetime: 10, emitters: 8, layers: 8, particles: 4000, cells: 4096 };
|
|
2
|
+
export function campfire() {
|
|
3
|
+
return { version: 1, name: 'Campfire', seed: 17, duration: 4, loop: true, humanCurated: false, emitters: [
|
|
4
|
+
{ 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' },
|
|
5
|
+
{ 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' },
|
|
6
|
+
{ 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' }
|
|
7
|
+
] };
|
|
8
|
+
}
|
|
9
|
+
/** Per-emitter numeric fields and their allowed ranges (shared with the editor's inputs). */
|
|
10
|
+
export const EMITTER_RANGES = [['rate', 0, 300], ['lifetime', .1, 10], ['speed', 0, 10], ['spread', 0, 5], ['gravity', -10, 10], ['size', .001, 5], ['endSize', .001, 5], ['opacity', 0, 1]];
|
|
11
|
+
/** Per-flipbook numeric fields and their allowed ranges. `frames` is further capped at cols x rows. */
|
|
12
|
+
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]];
|
|
13
|
+
const INTEGER_FIELDS = new Set(['cols', 'rows', 'frames']);
|
|
14
|
+
/** A bare filename with an image extension: no folders, so it can only name a sibling of the effect. */
|
|
15
|
+
export const TEXTURE_PATTERN = /^[^/\\?#]{1,200}\.(png|webp|jpe?g)$/i;
|
|
16
|
+
/** A new flipbook layer with sensible defaults, for the editor's "Add" and for the agent. */
|
|
17
|
+
export function flipbookLayer(id, texture) {
|
|
18
|
+
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' };
|
|
19
|
+
}
|
|
20
|
+
/** Every texture filename a document needs, once each. */
|
|
21
|
+
export function vfxTextures(document) {
|
|
22
|
+
return [...new Set((document.flipbooks ?? []).map((f) => f.texture))];
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Reject malformed/unsupported resources instead of silently rewriting them.
|
|
26
|
+
* The message names the field and its allowed range: the agent writes these
|
|
27
|
+
* documents by hand, and "Invalid VFX resource" gave it nothing to fix.
|
|
28
|
+
*/
|
|
29
|
+
export function parseVfx(value) {
|
|
30
|
+
const fail = (why) => { throw new Error(`Invalid VFX resource: ${why}`); };
|
|
31
|
+
if (!value || typeof value !== 'object')
|
|
32
|
+
return fail('not an object');
|
|
33
|
+
const d = value;
|
|
34
|
+
const number = (v, min, max) => typeof v === 'number' && Number.isFinite(v) && v >= min && v <= max;
|
|
35
|
+
const color = (v) => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v);
|
|
36
|
+
if (d.version !== 1)
|
|
37
|
+
fail('version must be 1');
|
|
38
|
+
if (typeof d.name !== 'string' || !d.name.trim() || d.name.length > 80)
|
|
39
|
+
fail('name must be 1-80 characters');
|
|
40
|
+
if (!number(d.seed, 1, 2147483646) || !Number.isInteger(d.seed))
|
|
41
|
+
fail('seed must be an integer 1-2147483646');
|
|
42
|
+
if (!number(d.duration, .1, 60))
|
|
43
|
+
fail('duration must be 0.1-60');
|
|
44
|
+
if (typeof d.loop !== 'boolean')
|
|
45
|
+
fail('loop must be a boolean');
|
|
46
|
+
if (typeof d.humanCurated !== 'boolean')
|
|
47
|
+
fail('humanCurated must be a boolean');
|
|
48
|
+
if (!Array.isArray(d.emitters) || d.emitters.length > LIMITS.emitters)
|
|
49
|
+
fail(`emitters must be a list of 0-${LIMITS.emitters} layers`);
|
|
50
|
+
if (d.flipbooks !== undefined && !Array.isArray(d.flipbooks))
|
|
51
|
+
fail('flipbooks must be a list');
|
|
52
|
+
const flipbooks = d.flipbooks ?? [];
|
|
53
|
+
const layers = d.emitters.length + flipbooks.length;
|
|
54
|
+
if (layers < 1 || layers > LIMITS.layers)
|
|
55
|
+
fail(`an effect needs 1-${LIMITS.layers} layers (emitters + flipbooks), it has ${layers}`);
|
|
56
|
+
const ids = new Set();
|
|
57
|
+
const checkId = (id, at) => {
|
|
58
|
+
if (typeof id !== 'string' || !/^[a-z0-9_-]{1,40}$/i.test(id))
|
|
59
|
+
fail(`${at}.id must be 1-40 of a-z 0-9 _ -`);
|
|
60
|
+
if (ids.has(id))
|
|
61
|
+
fail(`${at}.id "${id}" is used twice`);
|
|
62
|
+
ids.add(id);
|
|
63
|
+
};
|
|
64
|
+
let budget = 0;
|
|
65
|
+
d.emitters.forEach((e, i) => {
|
|
66
|
+
const at = `emitters[${i}]`;
|
|
67
|
+
if (!e || typeof e !== 'object')
|
|
68
|
+
fail(`${at} is not an object`);
|
|
69
|
+
checkId(e.id, at);
|
|
70
|
+
if (typeof e.enabled !== 'boolean')
|
|
71
|
+
fail(`${at}.enabled must be a boolean`);
|
|
72
|
+
for (const [key, min, max] of EMITTER_RANGES)
|
|
73
|
+
if (!number(e[key], min, max))
|
|
74
|
+
fail(`${at}.${key} must be ${min}-${max}`);
|
|
75
|
+
for (const key of ['color', 'endColor'])
|
|
76
|
+
if (!color(e[key]))
|
|
77
|
+
fail(`${at}.${key} must be #rrggbb`);
|
|
78
|
+
if (!['normal', 'additive'].includes(e.blend))
|
|
79
|
+
fail(`${at}.blend must be "normal" or "additive"`);
|
|
80
|
+
if (e.enabled)
|
|
81
|
+
budget += Math.ceil(e.rate * e.lifetime);
|
|
82
|
+
});
|
|
83
|
+
if (budget > LIMITS.particles)
|
|
84
|
+
fail(`too many live particles: the sum of rate x lifetime over enabled layers is ${budget}, the limit is ${LIMITS.particles}`);
|
|
85
|
+
flipbooks.forEach((f, i) => {
|
|
86
|
+
const at = `flipbooks[${i}]`;
|
|
87
|
+
if (!f || typeof f !== 'object')
|
|
88
|
+
fail(`${at} is not an object`);
|
|
89
|
+
checkId(f.id, at);
|
|
90
|
+
if (typeof f.enabled !== 'boolean')
|
|
91
|
+
fail(`${at}.enabled must be a boolean`);
|
|
92
|
+
if (typeof f.texture !== 'string' || !TEXTURE_PATTERN.test(f.texture))
|
|
93
|
+
fail(`${at}.texture must be the filename of a png, webp or jpg image in the same folder (no path)`);
|
|
94
|
+
for (const [key, min, max] of FLIPBOOK_RANGES) {
|
|
95
|
+
if (!number(f[key], min, max))
|
|
96
|
+
fail(`${at}.${key} must be ${min}-${max}`);
|
|
97
|
+
if (INTEGER_FIELDS.has(key) && !Number.isInteger(f[key]))
|
|
98
|
+
fail(`${at}.${key} must be a whole number`);
|
|
99
|
+
}
|
|
100
|
+
if (f.frames > f.cols * f.rows)
|
|
101
|
+
fail(`${at}.frames is ${f.frames} but a ${f.cols}x${f.rows} grid has only ${f.cols * f.rows} cells`);
|
|
102
|
+
if (typeof f.loop !== 'boolean')
|
|
103
|
+
fail(`${at}.loop must be a boolean`);
|
|
104
|
+
if (f.facing !== 'camera' && f.facing !== 'ground')
|
|
105
|
+
fail(`${at}.facing must be "camera" or "ground"`);
|
|
106
|
+
if (!color(f.color))
|
|
107
|
+
fail(`${at}.color must be #rrggbb`);
|
|
108
|
+
if (f.blend !== 'normal' && f.blend !== 'additive')
|
|
109
|
+
fail(`${at}.blend must be "normal" or "additive"`);
|
|
110
|
+
});
|
|
111
|
+
return structuredClone(d);
|
|
112
|
+
}
|
|
113
|
+
/** An effect is a project ASSET named `<stem>.vfx.json`; the server keeps the
|
|
114
|
+
* whole compound extension, so this suffix is what marks one. */
|
|
115
|
+
export const VFX_SUFFIX = '.vfx.json';
|
|
116
|
+
export function isVfxFilename(filename) { return filename.toLowerCase().endsWith(VFX_SUFFIX) && filename.length > VFX_SUFFIX.length; }
|
|
117
|
+
/**
|
|
118
|
+
* A filename for a NEW effect, shaped the way the server's sanitizer will keep
|
|
119
|
+
* it (lowercase ASCII letters, digits, `-` and `_`) and free in this project.
|
|
120
|
+
*
|
|
121
|
+
* It has to be free client-side: an upload whose name the project already
|
|
122
|
+
* holds REPLACES that file -- that is the intended behaviour for re-uploading
|
|
123
|
+
* your own asset, and silent data loss for "New effect" twice in a row.
|
|
124
|
+
* A name with no ASCII in it (any CJK name) becomes `effect`.
|
|
125
|
+
*/
|
|
126
|
+
export function vfxFilename(name, taken) {
|
|
127
|
+
const stem = (name.normalize('NFKD').toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/[-_]{2,}/g, '-').replace(/^[-_.]+|[-_.]+$/g, '').slice(0, 60).replace(/[-_.]+$/, '')) || 'effect';
|
|
128
|
+
const used = new Set(Array.from(taken, (f) => f.toLowerCase()));
|
|
129
|
+
for (let i = 1;; i++) {
|
|
130
|
+
const f = `${stem}${i === 1 ? '' : '-' + i}${VFX_SUFFIX}`;
|
|
131
|
+
if (!used.has(f))
|
|
132
|
+
return f;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -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>;
|
package/dist/vfx/load.js
ADDED
|
@@ -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,44 @@
|
|
|
1
|
+
import { campfire } 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
|
+
const TEMPLATES = {
|
|
15
|
+
// Blank is ONE plain layer, not zero: a document needs at least one emitter,
|
|
16
|
+
// and something on screen to change is a better start than an empty view.
|
|
17
|
+
blank: () => ({ version: 1, name: 'New Effect', seed: 7, duration: 3, loop: true, humanCurated: false, emitters: [
|
|
18
|
+
layer('layer-1', { rate: 20, lifetime: 1.5, speed: 1, spread: .5, gravity: 0, size: .15, endSize: .05, opacity: .8, color: '#ffffff', endColor: '#9aa3b2', blend: 'normal' })
|
|
19
|
+
] }),
|
|
20
|
+
campfire,
|
|
21
|
+
smoke: () => ({ version: 1, name: 'Smoke', seed: 23, duration: 4, loop: true, humanCurated: false, emitters: [
|
|
22
|
+
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' }),
|
|
23
|
+
layer('wisp', { rate: 6, lifetime: 3, speed: .9, spread: .2, gravity: 0, size: .12, endSize: .6, opacity: .2, color: '#b4b8c0', endColor: '#5b616b', blend: 'normal' })
|
|
24
|
+
] }),
|
|
25
|
+
sparks: () => ({ version: 1, name: 'Sparks', seed: 31, duration: 3, loop: true, humanCurated: false, emitters: [
|
|
26
|
+
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' }),
|
|
27
|
+
layer('glow', { rate: 20, lifetime: .25, speed: .3, spread: .3, gravity: 0, size: .35, endSize: .1, opacity: .5, color: '#ffd27a', endColor: '#ff8a2a', blend: 'additive' })
|
|
28
|
+
] }),
|
|
29
|
+
explosion: () => ({ version: 1, name: 'Explosion', seed: 41, duration: .15, loop: false, humanCurated: false, emitters: [
|
|
30
|
+
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' }),
|
|
31
|
+
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' }),
|
|
32
|
+
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' }),
|
|
33
|
+
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' })
|
|
34
|
+
] }),
|
|
35
|
+
magic: () => ({ version: 1, name: 'Magic Aura', seed: 53, duration: 4, loop: true, humanCurated: false, emitters: [
|
|
36
|
+
layer('motes', { rate: 40, lifetime: 2, speed: .6, spread: .9, gravity: .2, size: .08, endSize: .01, opacity: .9, color: '#b98cff', endColor: '#3fd3ff', blend: 'additive' }),
|
|
37
|
+
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' }),
|
|
38
|
+
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' })
|
|
39
|
+
] }),
|
|
40
|
+
};
|
|
41
|
+
export const VFX_TEMPLATE_IDS = Object.keys(TEMPLATES);
|
|
42
|
+
export const isVfxTemplateId = (id) => typeof id === 'string' && Object.prototype.hasOwnProperty.call(TEMPLATES, id);
|
|
43
|
+
/** A fresh copy every call: the editor mutates what it is given. */
|
|
44
|
+
export function vfxTemplate(id) { return TEMPLATES[id](); }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@umicat/three-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.35.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",
|
|
@@ -9,6 +9,10 @@
|
|
|
9
9
|
".": {
|
|
10
10
|
"types": "./dist/index.d.ts",
|
|
11
11
|
"default": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./vfx": {
|
|
14
|
+
"types": "./dist/vfx/index.d.ts",
|
|
15
|
+
"default": "./dist/vfx/index.js"
|
|
12
16
|
}
|
|
13
17
|
},
|
|
14
18
|
"scripts": {
|