@zaisma/effects 1.2.0 → 2.0.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/batches/warps.js CHANGED
@@ -1,83 +1,74 @@
1
1
  // The warp batch: effects that bend the picture (a shockwave's ripple, a bulge, the shimmer over heat), in one draw
2
- // call. Warps are drawn last. Just before, the picture drawn so far is copied once; each warp then redraws its own
3
- // patch of it, pulled out of place. So the copy is made only on frames with a warp alive, and only a warp's own
4
- // pixels cost anything.
5
- //
6
- // The copy can't be made from a picture that's drawn with smoothed edges into a render target (the lighting effects'
7
- // at high quality); the game then calls effects.drawWarps(camera) after its last draw, and they're laid on the screen.
8
- import * as THREE from "three";
2
+ // call. Warps are drawn last. Just before, the picture drawn so far is copied once (three's shared copy of the
3
+ // picture, made only on frames with a warp alive); each warp then redraws its own patch of it, pulled out of place,
4
+ // so only a warp's own pixels cost anything.
5
+ import * as THREE from "three/webgpu";
6
+ import { Fn, If, attribute, cameraProjectionMatrix, cameraViewMatrix, dot, exp, floor, fract, length, mix, screenSize, screenUV, sin, smoothstep, varyingProperty, vec2, vec4, viewportSharedTexture } from "three/tsl";
9
7
  import { valueOverLife } from "../format.js";
8
+ import { batchMaterial, leaveNormals } from "./shared.js";
10
9
 
11
10
  const FLOAT_COUNT_PER_WARP = 8;
12
11
  const MAXIMUM_WARP_COUNT = 32;
13
12
  const WARP_KIND_NUMBERS = { ripple: 0, pulse: 1, haze: 2 };
14
- // three took the picture first and the texture second until r165.
15
- const IS_TEXTURE_FIRST = Number(THREE.REVISION) >= 165;
16
13
 
17
- const WARP_VERTEX = /* glsl */ `
18
- attribute vec4 aPlace;
19
- attribute vec4 aBend;
20
- uniform float uIsReady;
21
- varying vec2 vLocal;
22
- varying vec4 vBend;
23
- varying float vRadiusOnScreen;
24
- void main() {
25
- if (uIsReady < 0.5 || aBend.x <= 0.0) {
26
- gl_Position = vec4(0.0, 0.0, 2.0, 1.0);
27
- return;
28
- }
29
- vec4 mvPosition = viewMatrix * vec4(aPlace.xyz, 1.0);
30
- mvPosition.xy += position.xy * aPlace.w * 1.15;
31
- gl_Position = projectionMatrix * mvPosition;
32
- vLocal = position.xy * 1.15;
33
- vBend = aBend;
34
- // How big the warp's radius is on screen, as a share of the picture's height.
35
- vRadiusOnScreen = aPlace.w * projectionMatrix[1][1] * 0.5 / max(-mvPosition.z, 0.05);
36
- }`;
14
+ const NOISE_WAY = vec2(127.1, 311.7);
15
+ const warpNoise = Fn(([spot]) => {
16
+ const cell = floor(spot).toVar();
17
+ const within = fract(spot).toVar();
18
+ const eased = within.mul(within).mul(within.mul(-2.0).add(3.0)).toVar();
19
+ const corners = fract(sin(vec4(dot(cell, NOISE_WAY), dot(cell.add(vec2(1.0, 0.0)), NOISE_WAY), dot(cell.add(vec2(0.0, 1.0)), NOISE_WAY), dot(cell.add(vec2(1.0, 1.0)), NOISE_WAY))).mul(43758.5453)).toVar();
20
+ return mix(mix(corners.x, corners.y, eased.x), mix(corners.z, corners.w, eased.x), eased.y);
21
+ });
37
22
 
38
- const WARP_FRAGMENT = /* glsl */ `
39
- uniform sampler2D uPicture;
40
- uniform vec2 uPictureSizePx;
41
- uniform float uTime;
42
- varying vec2 vLocal;
43
- varying vec4 vBend;
44
- varying float vRadiusOnScreen;
23
+ /** The warps' vertex and fragment stages, on a material. shared: createSharedUniforms' answer. */
24
+ function drawWarps(material, shared) {
25
+ const placeAttribute = attribute("aPlace", "vec4");
26
+ // Strength, thickness, kind and seed.
27
+ const bendAttribute = attribute("aBend", "vec4");
28
+ const corner = attribute("position", "vec3").xy;
29
+ const localVarying = varyingProperty("vec2", "zaismaLocal");
30
+ const bendVarying = varyingProperty("vec4", "zaismaBend");
31
+ const radiusOnScreenVarying = varyingProperty("float", "zaismaRadiusOnScreen");
45
32
 
46
- float warpNoise(vec2 p) {
47
- vec2 cell = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f);
48
- vec4 corners = fract(sin(vec4(dot(cell, vec2(127.1, 311.7)), dot(cell + vec2(1.0, 0.0), vec2(127.1, 311.7)), dot(cell + vec2(0.0, 1.0), vec2(127.1, 311.7)), dot(cell + vec2(1.0, 1.0), vec2(127.1, 311.7)))) * 43758.5453);
49
- return mix(mix(corners.x, corners.y, f.x), mix(corners.z, corners.w, f.x), f.y);
50
- }
33
+ material.vertexNode = Fn(() => {
34
+ const clip = vec4(0.0, 0.0, 2.0, 1.0).toVar();
35
+ If(bendAttribute.x.greaterThan(0.0), () => {
36
+ const viewPlace = cameraViewMatrix.mul(vec4(placeAttribute.xyz, 1.0)).toVar();
37
+ clip.assign(cameraProjectionMatrix.mul(vec4(viewPlace.xy.add(corner.mul(placeAttribute.w).mul(1.15)), viewPlace.zw)));
38
+ localVarying.assign(corner.mul(1.15));
39
+ bendVarying.assign(bendAttribute);
40
+ // How big the warp's radius is on screen, as a share of the picture's height.
41
+ radiusOnScreenVarying.assign(placeAttribute.w.mul(cameraProjectionMatrix.element(1).y).mul(0.5).div(viewPlace.z.negate().max(0.05)));
42
+ });
43
+ return clip;
44
+ })();
51
45
 
52
- void main() {
53
- float fromMiddle = length(vLocal);
54
- vec2 outward = fromMiddle > 1e-4 ? vLocal / fromMiddle : vec2(0.0);
55
- vec2 pull;
56
- float amount;
57
- if (vBend.z < 0.5) {
46
+ material.fragmentNode = Fn(() => {
47
+ const fromMiddle = length(localVarying).toVar();
48
+ const outward = fromMiddle.greaterThan(1e-4).select(localVarying.div(fromMiddle.max(1e-4)), vec2(0.0)).toVar();
58
49
  // A ripple: a ring at its radius that pushes the picture outward as it passes.
59
- float across = (fromMiddle - 1.0) / max(vBend.y, 0.02);
60
- amount = exp(-across * across * 4.0);
61
- pull = -outward * amount * across * vBend.y * 1.2;
62
- } else if (vBend.z < 1.5) {
50
+ const across = fromMiddle.sub(1.0).div(bendVarying.y.max(0.02)).toVar();
51
+ const ring = exp(across.mul(across).mul(-4.0)).toVar();
52
+ const ripplePull = outward.mul(ring).mul(across).mul(bendVarying.y).mul(-1.2);
63
53
  // A pulse: the picture swells from its middle.
64
- amount = clamp(1.0 - fromMiddle * fromMiddle, 0.0, 1.0);
65
- pull = -outward * amount * fromMiddle * 0.3;
66
- } else {
54
+ const dome = fromMiddle.mul(fromMiddle).oneMinus().clamp().toVar();
55
+ const pulsePull = outward.mul(dome).mul(fromMiddle).mul(-0.3);
67
56
  // A haze: the picture wavers, rising.
68
- amount = clamp(1.0 - fromMiddle * fromMiddle, 0.0, 1.0);
69
- vec2 drift = vLocal * 4.0 + vec2(vBend.w * 7.0, -uTime * 2.2);
70
- pull = (vec2(warpNoise(drift), warpNoise(drift + 17.3)) - 0.5) * amount * 0.2;
71
- }
72
- vec2 onScreen = gl_FragCoord.xy / uPictureSizePx;
73
- vec2 bent = onScreen + pull * vBend.x * vRadiusOnScreen * vec2(uPictureSizePx.y / uPictureSizePx.x, 1.0);
74
- gl_FragColor = vec4(texture2D(uPicture, clamp(bent, 0.001, 0.999)).rgb, smoothstep(0.0, 0.06, amount));
75
- }`;
57
+ const drift = localVarying.mul(4.0).add(vec2(bendVarying.w.mul(7.0), shared.uTime.mul(-2.2))).toVar();
58
+ const hazePull = vec2(warpNoise(drift), warpNoise(drift.add(17.3))).sub(0.5).mul(dome).mul(0.2);
59
+ const isRipple = bendVarying.z.lessThan(0.5);
60
+ const amount = isRipple.select(ring, dome);
61
+ const pull = isRipple.select(ripplePull, bendVarying.z.lessThan(1.5).select(pulsePull, hazePull));
62
+ // The screen's own y runs down, a warp's up.
63
+ const bent = screenUV.add(pull.mul(bendVarying.x).mul(radiusOnScreenVarying).mul(vec2(screenSize.y.div(screenSize.x), -1.0)));
64
+ return vec4(viewportSharedTexture(bent.clamp(0.001, 0.999)).rgb, smoothstep(0.0, 0.06, amount));
65
+ })();
66
+ return material;
67
+ }
76
68
 
77
- const sizePx = new THREE.Vector2();
78
69
  const place = new THREE.Vector3();
79
70
 
80
- /** Makes the batch. Answers { mesh, add, update, drawOnScreen, liveCount, dispose }. */
71
+ /** Makes the batch. Answers { mesh, add, update, liveCount, dispose }. */
81
72
  export function createWarpBatch({ sharedUniforms }) {
82
73
  const values = new Float32Array(MAXIMUM_WARP_COUNT * FLOAT_COUNT_PER_WARP);
83
74
  const buffer = new THREE.InstancedInterleavedBuffer(values, FLOAT_COUNT_PER_WARP);
@@ -88,9 +79,7 @@ export function createWarpBatch({ sharedUniforms }) {
88
79
  geometry.setAttribute("aPlace", new THREE.InterleavedBufferAttribute(buffer, 4, 0));
89
80
  geometry.setAttribute("aBend", new THREE.InterleavedBufferAttribute(buffer, 4, 4));
90
81
  geometry.instanceCount = 0;
91
- let picture = new THREE.FramebufferTexture(1, 1);
92
- const uniforms = { uPicture: { value: picture }, uPictureSizePx: { value: new THREE.Vector2(1, 1) }, uIsReady: { value: 0 }, uTime: sharedUniforms.uTime };
93
- const material = new THREE.ShaderMaterial({ name: "zaisma_effect_warps", vertexShader: WARP_VERTEX, fragmentShader: WARP_FRAGMENT, uniforms, transparent: true, depthWrite: false, toneMapped: false, fog: false });
82
+ const material = leaveNormals(drawWarps(batchMaterial("zaisma_effect_warps", { transparent: true, depthWrite: false }), sharedUniforms));
94
83
  const mesh = new THREE.Mesh(geometry, material);
95
84
  mesh.name = "zaisma_effect_warps";
96
85
  mesh.frustumCulled = false;
@@ -98,41 +87,6 @@ export function createWarpBatch({ sharedUniforms }) {
98
87
  mesh.visible = false;
99
88
 
100
89
  const warps = new Set();
101
- let isDeferred = false;
102
- let hasCopyFailed = false;
103
-
104
- /** Copies the picture drawn so far, when it can be copied. Answers whether it was. */
105
- function copyPicture(renderer) {
106
- const target = renderer.getRenderTarget();
107
- if (hasCopyFailed || (target && target.samples > 0)) return false;
108
- if (target) sizePx.set(target.width, target.height);
109
- else renderer.getDrawingBufferSize(sizePx);
110
- const typeNumber = target ? target.texture.type : THREE.UnsignedByteType;
111
- if (picture.image.width !== sizePx.x || picture.image.height !== sizePx.y || picture.type !== typeNumber) {
112
- picture.dispose();
113
- picture = new THREE.FramebufferTexture(sizePx.x, sizePx.y);
114
- picture.type = typeNumber;
115
- uniforms.uPicture.value = picture;
116
- }
117
- try {
118
- if (IS_TEXTURE_FIRST) renderer.copyFramebufferToTexture(picture);
119
- else renderer.copyFramebufferToTexture(new THREE.Vector2(0, 0), picture);
120
- } catch (error) {
121
- hasCopyFailed = true;
122
- console.error("@zaisma/effects: the picture couldn't be copied for warps, so they're off.", error);
123
- return false;
124
- }
125
- uniforms.uPictureSizePx.value.copy(sizePx);
126
- return true;
127
- }
128
-
129
- mesh.onBeforeRender = (renderer) => {
130
- const isCopied = copyPicture(renderer);
131
- // A picture that can't be copied here waits for drawOnScreen.
132
- isDeferred = !isCopied && !hasCopyFailed;
133
- uniforms.uIsReady.value = isCopied ? 1 : 0;
134
- material.uniformsNeedUpdate = true;
135
- };
136
90
 
137
91
  /**
138
92
  * A warp: { play, warpKind, startSec, lifeSec, radiusKeys (m), strengthKeys (0 to 100), thicknessShare,
@@ -183,40 +137,16 @@ export function createWarpBatch({ sharedUniforms }) {
183
137
  }
184
138
  }
185
139
 
186
- /** Lays the warps on the screen after the game's last draw, when they couldn't be drawn with the scene. */
187
- function drawOnScreen(renderer, camera) {
188
- if (!isDeferred || !mesh.visible) return;
189
- const parent = mesh.parent;
190
- const earlierAutoClear = renderer.autoClear;
191
- const earlierCallback = mesh.onBeforeRender;
192
- renderer.autoClear = false;
193
- mesh.onBeforeRender = () => {};
194
- if (copyPicture(renderer)) {
195
- uniforms.uIsReady.value = 1;
196
- material.depthTest = false;
197
- const alone = new THREE.Scene();
198
- alone.add(mesh);
199
- renderer.render(alone, camera);
200
- parent?.add(mesh);
201
- material.depthTest = true;
202
- }
203
- mesh.onBeforeRender = earlierCallback;
204
- renderer.autoClear = earlierAutoClear;
205
- isDeferred = false;
206
- }
207
-
208
140
  return {
209
141
  mesh,
210
142
  add,
211
143
  update,
212
- drawOnScreen,
213
144
  get liveCount() {
214
145
  return warps.size;
215
146
  },
216
147
  dispose() {
217
148
  geometry.dispose();
218
149
  material.dispose();
219
- picture.dispose();
220
150
  },
221
151
  };
222
152
  }
package/budget.js CHANGED
@@ -11,9 +11,9 @@ export const QUALITY_ORDER = ["low", "medium", "high"];
11
11
  * screens' worth of see-through particles may be drawn over each other before the guard thins them.
12
12
  */
13
13
  export const QUALITY_BUDGETS = {
14
- low: { particleCount: 2000, markCount: 64, debrisCount: 60, flashLightCount: 0, hasWarps: false, hasRainShelter: false, hasSunShadows: false, keptPct: 45, fillScreenCount: 2.5, atlasSizePx: 1024 },
15
- medium: { particleCount: 6000, markCount: 256, debrisCount: 150, flashLightCount: 2, hasWarps: true, hasRainShelter: true, hasSunShadows: false, keptPct: 75, fillScreenCount: 4, atlasSizePx: 1024 },
16
- high: { particleCount: 20000, markCount: 512, debrisCount: 300, flashLightCount: 4, hasWarps: true, hasRainShelter: true, hasSunShadows: true, keptPct: 100, fillScreenCount: 8, atlasSizePx: 2048 },
14
+ low: { particleCount: 2000, markCount: 64, debrisCount: 60, flashLightCount: 0, hasWarps: false, hasRainShelter: false, keptPct: 45, fillScreenCount: 2.5, atlasSizePx: 1024 },
15
+ medium: { particleCount: 6000, markCount: 256, debrisCount: 150, flashLightCount: 2, hasWarps: true, hasRainShelter: true, keptPct: 75, fillScreenCount: 4, atlasSizePx: 1024 },
16
+ high: { particleCount: 20000, markCount: 512, debrisCount: 300, flashLightCount: 4, hasWarps: true, hasRainShelter: true, keptPct: 100, fillScreenCount: 8, atlasSizePx: 2048 },
17
17
  };
18
18
 
19
19
  /** The share of the particle budget solid chunks may take: each is up to sixty corners, where a sprite is four. */
package/flashes.js CHANGED
@@ -2,32 +2,65 @@
2
2
  // what the camera sees (its brightness, its reach, how near it is); the best few get a real light and the rest only
3
3
  // glow, so twenty explosions cost the frame rate what two do.
4
4
  //
5
- // The real lights are a fixed pool of three's point lights, always in the scene (dark when unused), because adding
6
- // or removing a light makes three build every material's shader again. This file is the one seam to the scene's
7
- // lights: when the lighting piece brings its own cheap lights, flashes go through those from here.
8
- import * as THREE from "three";
5
+ // The real lights are a fixed pool, always in the scene (dark when unused). With the lighting piece they're its own
6
+ // cheap lights (lighting.lights), so a flash lights the scene exactly as a lamp does and costs as little; without
7
+ // it they're three's point lights, kept in the scene because adding or removing one makes three build every
8
+ // material's shader again. This file is the one seam to the scene's lights.
9
+ import * as THREE from "three/webgpu";
9
10
  import { valueOverLife } from "./format.js";
10
11
  import { PARTICLE_FLASH_COUNT } from "./batches/shared.js";
11
12
 
12
13
  const place = new THREE.Vector3();
14
+ const shown = new THREE.Color();
15
+ /** What the lighting piece's lights take at most. */
16
+ const MAXIMUM_STRENGTH_LUX = 10_000;
17
+ const MAXIMUM_RANGE_M = 500;
13
18
 
14
- export function createFlashes({ scene, sharedUniforms }) {
19
+ /** lightApi: the lighting piece's lights (lighting.lights), or null for three's own point lights. */
20
+ export function createFlashes({ scene, sharedUniforms, lightApi = null }) {
15
21
  const lights = [];
16
22
  const flashes = new Set();
17
23
  const ranked = [];
18
24
 
19
- function setLightCount(lightCount) {
20
- while (lights.length > lightCount) {
21
- const light = lights.pop();
22
- scene.remove(light);
23
- light.dispose();
24
- }
25
- while (lights.length < lightCount) {
26
- const light = new THREE.PointLight(0xffffff, 0, 1, 2);
27
- light.name = "zaisma_effect_flash";
28
- scene.add(light);
29
- lights.push(light);
25
+ function makeLight() {
26
+ if (lightApi) {
27
+ const handle = lightApi.add({ positionM: { x: 0, y: 0, z: 0 }, color: "#ffffff", strengthLux: 0, rangeM: 1 });
28
+ let isDark = true;
29
+ return {
30
+ shine(x, y, z, color, strength, radiusM) {
31
+ handle.set({ positionM: { x, y, z }, color: `#${color.getHexString()}`, strengthLux: Math.min(strength, MAXIMUM_STRENGTH_LUX), rangeM: Math.min(Math.max(radiusM, 0.01), MAXIMUM_RANGE_M) });
32
+ isDark = false;
33
+ },
34
+ darken() {
35
+ if (!isDark) handle.set({ strengthLux: 0 });
36
+ isDark = true;
37
+ },
38
+ remove: () => handle.remove(),
39
+ };
30
40
  }
41
+ const light = new THREE.PointLight(0xffffff, 0, 1, 2);
42
+ light.name = "zaisma_effect_flash";
43
+ scene.add(light);
44
+ return {
45
+ shine(x, y, z, color, strength, radiusM) {
46
+ light.position.set(x, y, z);
47
+ light.color.copy(color);
48
+ light.intensity = strength;
49
+ light.distance = radiusM;
50
+ },
51
+ darken() {
52
+ light.intensity = 0;
53
+ },
54
+ remove() {
55
+ scene.remove(light);
56
+ light.dispose();
57
+ },
58
+ };
59
+ }
60
+
61
+ function setLightCount(lightCount) {
62
+ while (lights.length > lightCount) lights.pop().remove();
63
+ while (lights.length < lightCount) lights.push(makeLight());
31
64
  }
32
65
 
33
66
  /**
@@ -75,23 +108,16 @@ export function createFlashes({ scene, sharedUniforms }) {
75
108
  }
76
109
  ranked.sort((first, second) => second.score - first.score);
77
110
  for (let index = 0; index < lights.length; index += 1) {
78
- const light = lights[index];
79
111
  const flash = ranked[index];
80
- if (!flash) {
81
- light.intensity = 0;
82
- continue;
83
- }
84
- light.position.set(flash.nowX, flash.nowY, flash.nowZ);
85
- light.color.copy(flash.color).multiply(flash.play.tint);
86
- light.intensity = flash.nowStrength;
87
- light.distance = flash.nowRadiusM;
112
+ if (flash) lights[index].shine(flash.nowX, flash.nowY, flash.nowZ, shown.copy(flash.color).multiply(flash.play.tint), flash.nowStrength, flash.nowRadiusM);
113
+ else lights[index].darken();
88
114
  }
89
115
  for (let index = 0; index < PARTICLE_FLASH_COUNT; index += 1) {
90
116
  const flash = ranked[index];
91
117
  if (flash) {
92
- sharedUniforms.uFlashPlace.value[index].set(flash.nowX, flash.nowY, flash.nowZ, flash.nowRadiusM);
93
- sharedUniforms.uFlashColor.value[index].copy(flash.color).multiply(flash.play.tint).multiplyScalar(flash.nowStrength);
94
- } else sharedUniforms.uFlashColor.value[index].setRGB(0, 0, 0);
118
+ sharedUniforms.uFlashPlace.array[index].set(flash.nowX, flash.nowY, flash.nowZ, flash.nowRadiusM);
119
+ sharedUniforms.uFlashColor.array[index].copy(flash.color).multiply(flash.play.tint).multiplyScalar(flash.nowStrength);
120
+ } else sharedUniforms.uFlashColor.array[index].setRGB(0, 0, 0);
95
121
  }
96
122
  }
97
123
 
package/index.d.ts CHANGED
@@ -1,16 +1,18 @@
1
1
  /**
2
- * @zaisma/effects: spectacle that holds a phone's frame rate, for three.js. Thousands of lit particles, hits,
2
+ * @zaisma/effects: spectacle that holds a phone's frame rate, for three.js's WebGPURenderer (it draws on WebGPU,
3
+ * and on WebGL 2 where a device has none; a game on THREE.WebGLRenderer keeps @zaisma/effects 1). Thousands of lit particles, hits,
3
4
  * explosions, magic, fire, smoke, trails, shockwaves, marks on surfaces, screen warps, debris that bounces and
4
5
  * weather, drawn in the look a game picks. An effect is a small file (EFFECT-FILES.md is its format), and the
5
6
  * library/ folder holds the ones that come with the piece.
6
7
  *
7
8
  * @example
8
9
  * import { createEffects } from "./pieces/@zaisma/effects/index.js";
9
- * const effects = createEffects({ scene, renderer, lighting, settings: { look: "glowing" } });
10
+ * const lighting = await createLighting({ canvas, scene }); // @zaisma/lighting 2: it makes the renderer
11
+ * const effects = createEffects({ scene, renderer: lighting.renderer, lighting, settings: { look: "glowing" } });
10
12
  * await effects.load(["explosion_large", "campfire", "./effects/my_spell.json"]);
11
13
  * // each frame, before rendering:
12
14
  * effects.update(camera);
13
- * renderer.render(scene, camera);
15
+ * lighting.render(camera); // or renderer.render(scene, camera) without the lighting piece
14
16
  * // while playing:
15
17
  * effects.play("explosion_large", { positionM: { x: 4, y: 0, z: -2 } });
16
18
  * const fire = effects.play("campfire", { positionM: camp }); // looping: plays until fire.stop()
@@ -133,9 +135,9 @@ export interface RayHit {
133
135
  export interface EffectsGiven extends GivenToPiece<EffectsSettings, EffectsHooks> {
134
136
  /** The scene the effects play in. */
135
137
  scene: Scene;
136
- /** The renderer that draws it: a THREE.WebGLRenderer. */
138
+ /** The renderer that draws it: the lighting piece's lighting.renderer, or a THREE.WebGPURenderer (from "three/webgpu") of the game's own. */
137
139
  renderer: { render(scene: Scene, camera: Camera): void };
138
- /** The lighting piece (createLighting's answer): particles take its light and fog, flashes light its scene, quality follows its own. */
140
+ /** The lighting piece (createLighting's answer, @zaisma/lighting 2): particles take its light and stand in its air (fog, haze, lamp halos), flashes light its scene through its own cheap lights, quality follows its own. */
139
141
  lighting?: object | null;
140
142
  /** The physics piece: every collision throws an impact, chunks bounce off its world, marks find its surfaces. */
141
143
  physics?: object | null;
@@ -299,8 +301,6 @@ export interface Effects {
299
301
  clearMarks(): void;
300
302
  /** Every frame, before rendering. nowMs defaults to performance.now(). Throws PieceError "camera_needed". */
301
303
  update(camera: Camera, nowMs?: number): void;
302
- /** For a game that draws through the lighting effects at high quality: call after its last draw, and warps are laid on the picture. */
303
- drawWarps(camera: Camera): void;
304
304
  /** Defines the game's own look and draws in it (the look setting becomes "own"). Throws PieceError "bad_look". */
305
305
  defineOwnLook(look: OwnLook): void;
306
306
  /** The look in use. */
@@ -366,7 +366,7 @@ export declare const LOOKS: Record<LookName, Record<MaterialName, MaterialStyle>
366
366
  /** A material style's fields with their ranges and choices: what defineOwnLook checks against. */
367
367
  export declare const LOOK_STYLE_FIELDS: Record<keyof MaterialStyle, { valueKind: "choice" | "choice_or_null" | "number" | "integer"; choices?: readonly string[]; minimumNumber?: number; maximumNumber?: number }>;
368
368
  /** What each quality level draws. */
369
- export declare const QUALITY_BUDGETS: Record<QualityLevel, { particleCount: number; markCount: number; debrisCount: number; flashLightCount: number; hasWarps: boolean; hasRainShelter: boolean; hasSunShadows: boolean; keptPct: number; fillScreenCount: number; atlasSizePx: number }>;
369
+ export declare const QUALITY_BUDGETS: Record<QualityLevel, { particleCount: number; markCount: number; debrisCount: number; flashLightCount: number; hasWarps: boolean; hasRainShelter: boolean; keptPct: number; fillScreenCount: number; atlasSizePx: number }>;
370
370
  /** Whether the device is a phone or tablet: touch with no mouse. */
371
371
  export declare function isTouchDevice(): boolean;
372
372
  /** Where "auto" starts without the lighting piece. */
package/index.js CHANGED
@@ -9,14 +9,14 @@
9
9
  // the look or the quality level changes while effects play. Everything is drawn in a handful of draw calls
10
10
  // (batches/), whatever plays.
11
11
 
12
- import * as THREE from "three";
12
+ import * as THREE from "three/webgpu";
13
13
  import { openPiece } from "../piece/index.js";
14
14
  import statement from "./piece.json.js";
15
15
  import { CHUNK_BUDGET_SHARE_NUMBER, QUALITY_BUDGETS, QUALITY_ORDER, createFillGuard, createFrameWatcher, isTouchDevice, particleBudget, planEmitter, startingQualityLevel } from "./budget.js";
16
16
  import { createChunkBatch } from "./batches/chunks.js";
17
17
  import { createMarkBatch } from "./batches/marks.js";
18
18
  import { createRibbonBatch } from "./batches/ribbons.js";
19
- import { createSharedUniforms } from "./batches/shared.js";
19
+ import { createSharedUniforms, readSceneFog } from "./batches/shared.js";
20
20
  import { ELEMENT_ROW, createSpriteBatch } from "./batches/sprites.js";
21
21
  import { createWarpBatch } from "./batches/warps.js";
22
22
  import { createDebris } from "./debris.js";
@@ -56,6 +56,8 @@ const RAD_PER_DEG = Math.PI / 180;
56
56
  const UPRIGHT_SHAPE_NAMES = ["flame", "angular_flame", "drop"];
57
57
  const HEX_COLOR_PATTERN = /^#[0-9a-f]{6}$/;
58
58
  const UP = new THREE.Vector3(0, 1, 0);
59
+ /** How fast the lighting piece's wind blows at its strongest (wind_strength_pct 100), in metres a second. */
60
+ const LIGHTING_FULL_WIND_M_PER_SEC = 12;
59
61
  /** The clock the graphics chip counts on starts over after this long, so a particle's age stays exact however long a game runs. */
60
62
  const CLOCK_RESTART_SEC = 600;
61
63
  const CLOCK_RESTART_SPAN_SEC = 512;
@@ -66,6 +68,10 @@ const LIGHT_SEARCH_INTERVAL_SEC = 3;
66
68
  const GUARDED_SCREEN_SHARE_NUMBER = 0.002;
67
69
  const MAXIMUM_LANDING_EFFECT_COUNT_PER_FRAME = 6;
68
70
  const LIBRARY_URL = new URL("./library/", import.meta.url);
71
+ /** What a scene's surroundings add to the light on effects from above and from below, at full strength. */
72
+ const SURROUNDINGS_SKY_COLOR = new THREE.Color(0.7, 0.8, 0.95);
73
+ const SURROUNDINGS_GROUND_COLOR = new THREE.Color(0.42, 0.4, 0.38);
74
+ const surroundingsColor = new THREE.Color();
69
75
 
70
76
  const isPoint = (given) => given !== null && typeof given === "object" && Number.isFinite(given.x) && Number.isFinite(given.y) && Number.isFinite(given.z);
71
77
  const isNumberIn = (given, minimumNumber, maximumNumber) => typeof given === "number" && given >= minimumNumber && given <= maximumNumber;
@@ -84,12 +90,15 @@ export function createEffects(given = {}) {
84
90
  const lighting = given.lighting ?? null;
85
91
  const physics = given.physics ?? null;
86
92
  if (!(scene instanceof THREE.Scene)) refuse("scene_needed", { message: "createEffects needs the three.js scene the effects play in.", field: "scene", fix: "Give createEffects({ scene, renderer }), with scene a THREE.Scene." });
87
- if (!renderer || typeof renderer.render !== "function") refuse("renderer_needed", { message: "createEffects needs the three.js renderer that draws the scene.", field: "renderer", fix: "Give createEffects({ scene, renderer }), with renderer a THREE.WebGLRenderer." });
93
+ if (!renderer || typeof renderer.render !== "function") refuse("renderer_needed", { message: "createEffects needs the three.js renderer that draws the scene.", field: "renderer", fix: "Give createEffects({ scene, renderer }), with renderer the lighting piece's lighting.renderer or a THREE.WebGPURenderer of the game's own." });
94
+ if (renderer.isWebGLRenderer === true) refuse("renderer_not_supported", { message: "These effects draw with three's WebGPURenderer (from three/webgpu), which draws on WebGPU and on WebGL 2; a THREE.WebGLRenderer can't draw them.", field: "renderer", fix: "Give the lighting piece's lighting.renderer or a THREE.WebGPURenderer; a game that stays on THREE.WebGLRenderer keeps @zaisma/effects 1." });
88
95
  if (given.castRay !== undefined && typeof given.castRay !== "function") refuse("bad_cast_ray", { message: "castRay isn't a function.", field: "castRay", fix: "Give a function taking { fromM, directionM, maximumDistanceM } and answering { pointM, normal } or null: the level's own ray test." });
89
96
  const canDraw = canRendererDraw(renderer);
90
97
 
91
98
  // ---- What every batch reads ----
92
- const sharedUniforms = createSharedUniforms();
99
+ // With the lighting piece the particles stand in its air (fog, haze, lamp halos); without it, in three's own fog.
100
+ const lightingAirAt = typeof lighting?.airAt === "function" ? lighting.airAt : null;
101
+ const sharedUniforms = createSharedUniforms({ airAt: lightingAirAt });
93
102
  const elementTable = createTable(ELEMENT_ROW_TEXEL_COUNT, MAXIMUM_ELEMENT_ROW_COUNT);
94
103
  const playTable = createTable(PLAY_ROW_TEXEL_COUNT, MAXIMUM_PLAY_ROW_COUNT);
95
104
  sharedUniforms.uElements.value = elementTable.texture;
@@ -139,9 +148,9 @@ export function createEffects(given = {}) {
139
148
  let sprites = null;
140
149
  let chunks = null;
141
150
  const marks = createMarkBatch({ markCount: 0, sharedUniforms });
142
- const ribbons = createRibbonBatch();
151
+ const ribbons = createRibbonBatch({ sharedUniforms });
143
152
  const warps = createWarpBatch({ sharedUniforms });
144
- const flashes = createFlashes({ scene, sharedUniforms });
153
+ const flashes = createFlashes({ scene, sharedUniforms, lightApi: typeof lighting?.lights?.add === "function" ? lighting.lights : null });
145
154
  group.add(marks.mesh, ribbons.mesh, warps.mesh);
146
155
 
147
156
  // ---- The level, for marks and debris ----
@@ -202,14 +211,30 @@ export function createEffects(given = {}) {
202
211
  playTable.write(weatherPlayRow, 3, 0, 0, 0, 0);
203
212
  const weather = createWeather({ sprites: null, sharedUniforms, scene, renderer, playRow: weatherPlayRow });
204
213
  const weatherRows = weather.elements.map(() => elementTable.takeRow());
205
- const weatherTarget = () => ({
206
- rainPct: settings.get("rainPct"),
207
- snowPct: settings.get("snowPct"),
208
- fogPct: settings.get("fogPct"),
209
- windSpeedMPerSec: settings.get("windSpeedMPerSec"),
210
- windDirectionDeg: settings.get("windDirectionDeg"),
211
- windGustPct: settings.get("windGustPct"),
212
- });
214
+ /**
215
+ * What the weather should be: the game's settings, and with the lighting piece its sky's weather on top, so a
216
+ * storm set there rains here. The stronger of the two winds blows, in its own direction.
217
+ */
218
+ function weatherTarget() {
219
+ const target = {
220
+ rainPct: settings.get("rainPct"),
221
+ snowPct: settings.get("snowPct"),
222
+ fogPct: settings.get("fogPct"),
223
+ windSpeedMPerSec: settings.get("windSpeedMPerSec"),
224
+ windDirectionDeg: settings.get("windDirectionDeg"),
225
+ windGustPct: settings.get("windGustPct"),
226
+ };
227
+ const sky = lighting?.weatherNow;
228
+ if (!sky) return target;
229
+ target.rainPct = Math.max(target.rainPct, sky.rainPct ?? 0);
230
+ target.snowPct = Math.max(target.snowPct, sky.snowPct ?? 0);
231
+ const skyWindMPerSec = ((sky.windPct ?? 0) / 100) * LIGHTING_FULL_WIND_M_PER_SEC;
232
+ if (skyWindMPerSec > target.windSpeedMPerSec && sky.windDirection) {
233
+ target.windSpeedMPerSec = skyWindMPerSec;
234
+ target.windDirectionDeg = ((Math.atan2(-sky.windDirection.z, sky.windDirection.x) * 180) / Math.PI + 360) % 360;
235
+ }
236
+ return target;
237
+ }
213
238
  let weatherToldSec = -Infinity;
214
239
  let wasWeatherTurning = false;
215
240
 
@@ -834,23 +859,6 @@ export function createEffects(given = {}) {
834
859
  let fillLight = null;
835
860
  let lightSearchedSec = -Infinity;
836
861
  const sunTarget = new THREE.Vector3();
837
- /**
838
- * The sun's shadow on the particles, at high quality: read from the shadow map three already drew for the scene,
839
- * so it costs no drawing of its own. Only a map three compares depths in for the shader (its usual kind) is read;
840
- * with any other, or none, particles stand in open sun as before.
841
- */
842
- function readSunShadow() {
843
- const shadow = sunLight?.castShadow && sunLight.visible ? sunLight.shadow : null;
844
- const map = shadow?.map?.depthTexture ?? null;
845
- const canRead = map !== null && map.compareFunction === THREE.LessEqualCompare && renderer.shadowMap?.enabled === true && QUALITY_BUDGETS[qualityLevel].hasSunShadows && canDraw;
846
- sharedUniforms.uSunShadow.value = canRead ? map : null;
847
- sharedUniforms.uSunShadowShare.value = canRead ? Math.min(Math.max(shadow.intensity ?? 1, 0), 1) : 0;
848
- if (!canRead) return;
849
- sharedUniforms.uSunShadowMatrix.value.copy(shadow.matrix);
850
- // A third of a metre between readings, as a share of the map's width.
851
- const widthM = shadow.camera.right - shadow.camera.left;
852
- sharedUniforms.uSunShadowSpread.value = widthM > 0 ? 0.33 / widthM : 0;
853
- }
854
862
  function readLight() {
855
863
  if (lighting) {
856
864
  sunLight = lighting.sun ?? null;
@@ -873,7 +881,6 @@ export function createEffects(given = {}) {
873
881
  }
874
882
  sharedUniforms.uSunColor.value.copy(sunLight.color).multiplyScalar(sunLight.visible ? sunLight.intensity : 0);
875
883
  } else sharedUniforms.uSunColor.value.setRGB(0, 0, 0);
876
- readSunShadow();
877
884
  if (fillLight) {
878
885
  sharedUniforms.uSkyColor.value.copy(fillLight.color).multiplyScalar(fillLight.visible ? fillLight.intensity : 0);
879
886
  if (fillLight.isHemisphereLight) sharedUniforms.uGroundColor.value.copy(fillLight.groundColor).multiplyScalar(fillLight.visible ? fillLight.intensity : 0);
@@ -890,10 +897,8 @@ export function createEffects(given = {}) {
890
897
  // The scene's surroundings light its solids from every side; effects take about as much, so their shaded sides match.
891
898
  if (scene.environment) {
892
899
  const share = scene.environmentIntensity ?? 1;
893
- const sky = sharedUniforms.uSkyColor.value;
894
- const ground = sharedUniforms.uGroundColor.value;
895
- sky.setRGB(sky.r + share * 0.7, sky.g + share * 0.8, sky.b + share * 0.95);
896
- ground.setRGB(ground.r + share * 0.42, ground.g + share * 0.4, ground.b + share * 0.38);
900
+ sharedUniforms.uSkyColor.value.add(surroundingsColor.copy(SURROUNDINGS_SKY_COLOR).multiplyScalar(share));
901
+ sharedUniforms.uGroundColor.value.add(surroundingsColor.copy(SURROUNDINGS_GROUND_COLOR).multiplyScalar(share));
897
902
  }
898
903
  }
899
904
 
@@ -990,6 +995,7 @@ export function createEffects(given = {}) {
990
995
  }
991
996
  sharedUniforms.uPxPerM.value = pxPerM;
992
997
  readLight();
998
+ if (!lightingAirAt) readSceneFog(sharedUniforms, scene);
993
999
 
994
1000
  // Rows of plays that ended last frame are free now; the ones that ended this frame wait one more.
995
1001
  for (const row of freedRows) playTable.giveRow(row);
@@ -1100,10 +1106,6 @@ export function createEffects(given = {}) {
1100
1106
  /** Takes every mark off the level: a level starting over. */
1101
1107
  clearMarks: () => marks.clear(),
1102
1108
  update,
1103
- /** For a game that draws through the lighting effects at high quality: call after its last draw, and warps are laid on the picture. */
1104
- drawWarps(camera) {
1105
- warps.drawOnScreen(renderer, camera);
1106
- },
1107
1109
  /** Defines the game's own look, { basedOnLookName, materials }, and draws in it. */
1108
1110
  defineOwnLook(look) {
1109
1111
  const found = ownLookProblem(look);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaisma/effects",
3
- "version": "1.2.0",
3
+ "version": "2.0.0",
4
4
  "description": "Spectacle that holds a phone's frame rate, for three.js: thousands of lit particles, hits, explosions, magic, trails, screen warps, marks on surfaces, debris that bounces and weather, in the look a game picks. An effect is a small file an AI writes; 92 come with it. Flashes light the scene, the character and physics bring effects free, and online every player sees the same effect at once.",
5
5
  "license": "PolyForm-Shield-1.0.0",
6
6
  "homepage": "https://zaisma.com",
@@ -44,6 +44,7 @@
44
44
  "README.md",
45
45
  "batches/chunks.js",
46
46
  "batches/marks.js",
47
+ "batches/motion-nodes.js",
47
48
  "batches/ribbons.js",
48
49
  "batches/shared.js",
49
50
  "batches/sprites.js",