@waica/engine 0.18.0 → 0.19.1

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 CHANGED
@@ -194,6 +194,28 @@ game.time.now // seconds of Game Time since the Game started
194
194
  - **Scope.** A timer or tween is scene-scoped by default: `unloadScene()` and every scene load — including a Game's first — cancel it, running no callback. `{ scope: 'session' }` survives a scene change. `{ owner: entity }` cancels it immediately when that entity is destroyed, whatever its scope; an owner already dead at scheduling time yields an inactive handle. `game.dispose()` cancels everything in both scopes. This is the opposite default from `game.onUpdate`/`game.events` (ADR 0011), which survive a scene change by construction, and the same one `game.audio.play()` uses (ADR 0012) — see ADR 0017 for why timers follow audio's rule rather than the host-subscription one: a timer's callback almost always closes over the scene that scheduled it.
195
195
  - **No Promises.** Nothing here returns one, and nothing is async — a `.then` continuation is not step-exact (it runs after the whole synchronous frame), which is exactly what `game.time` exists to avoid. Compose delays with `after`, not `await`.
196
196
 
197
+ ## game.cameraEffects: shake, fade and flash
198
+
199
+ Every `Game` owns a `cameraEffects: CameraEffects` service beside `game.camera`, which stays the plain `THREE.OrthographicCamera` (ADR 0020). Effects advance only inside a Simulation Step, right after the scene camera, so nothing moves while the Game is not simulating, is stopped, or a Run Session is paused; `step { frames: N }` advances them by exactly N steps.
200
+
201
+ ```ts
202
+ game.cameraEffects.shake({ intensity: 0.3, seconds: 0.25 }) // world units, decaying to 0
203
+ const out = game.cameraEffects.fade({ to: 'black', seconds: 0.4 }) // 'black' | 'white' | '#rrggbb' | 'clear'
204
+ game.cameraEffects.flash({ color: 'white', seconds: 0.15 }) // up to 1, back to exactly 0
205
+ out.cancel() // opacity stays where it was
206
+ await out.done // true: completed; false: cancelled or replaced
207
+ ```
208
+
209
+ - **Shake.** An offset added to the camera only while drawing (the world render and Anchored Pieces), never to the base center that follow, deadzone and limits compute, so smoothing never feeds on it. Each axis stays within `intensity · (1 − ease(t / seconds))` (`easing` takes `game.time`'s names, `'linear'` by default) and is exactly `{0, 0}` from `seconds` on. Overlapping shakes apply the largest current amplitude. The jitter is deterministic per Simulation Step (no `Math.random`), so a Run Session reproduces it. It is not re-clamped to `limits`: at a map edge up to `intensity` beyond them can show. Under a fixed `resolution` the offset snaps to whole screen pixels; the base center is never snapped.
210
+ - **Fade.** Carries an HTML layer over the game viewport — inside the letterbox, above the world, UI Pieces and Anchored Pieces — from its current opacity to 1 in the given color, or to 0 with `'clear'`, and then holds. A new `fade` cancels a running one (its `done` resolves `false`) and starts from the current opacity.
211
+ - **Flash.** Its own layer above the Fade, shown at opacity 1 and returned to exactly 0 over `seconds`; it never changes the Fade.
212
+ - **Scope.** A Fade is session-scoped: it survives `unloadScene()` and every scene load with its color, opacity and any running progress, so it can cover a scene change. A Shake or Flash is scene-scoped: `unloadScene()` ends it, running no callback (its `done` resolves `false`). `game.dispose()` ends everything and removes the layers. This follows the audio and timer scope notes above (ADR 0011, ADR 0017): a transition fade is exactly the case that must cross a scene change.
213
+ - **Invalid arguments never throw.** A non-finite or negative `seconds`/`intensity`, an unknown color or an unknown easing logs one `[waica]` warning and returns a handle whose `done` resolves `false`; no effect changes.
214
+ - **Scene Transition.** `SceneTransition` takes `fadeSeconds` (default 0: a hard cut) and `fadeColor` (default `'black'`): it fades out over `fadeSeconds`, loads its destination, then clears over `fadeSeconds` in the incoming scene. Simulation and input keep running; the component ignores further triggers during its outgoing fade. The Runtime Bridge `scene` operation stays a hard cut.
215
+ - **Runtime Snapshot.** Every snapshot carries `camera: { shake: { x, y }, fade: { color, opacity }, flash: { color, opacity } }` from the last completed step, under the `'camera-effects'` capability.
216
+
217
+ A Fade to a color that nothing clears leaves the view covered; the engine does not warn.
218
+
197
219
  ## game.ui.attach: Anchored Pieces
198
220
 
199
221
  A UI Piece shown with `game.ui.show(name)` is a screen-space singleton. `game.ui.attach(piece, entity, options?)` instead creates an **Anchored Piece**: a new instance of the piece that follows `entity` across the screen, with its own shadow root and its own values. Every call is a new instance — five orcs can each carry a `health-bar` — and the screen piece of the same name is never mounted, shown or changed by it.
@@ -11,11 +11,13 @@ export function sheetFrameCount(sheet) {
11
11
  */
12
12
  export function locateFrame(sheets, frame) {
13
13
  let rest = Math.max(0, Math.floor(frame));
14
- for (let i = 0; i < sheets.length; i++) {
15
- const count = sheetFrameCount(sheets[i]);
14
+ let i = 0;
15
+ for (const sheet of sheets) {
16
+ const count = sheetFrameCount(sheet);
16
17
  if (rest < count || i === sheets.length - 1)
17
18
  return { sheet: i, frame: Math.min(rest, count - 1) };
18
19
  rest -= count;
20
+ i++;
19
21
  }
20
22
  return { sheet: 0, frame: 0 };
21
23
  }
@@ -28,7 +30,11 @@ const positive = (value) => typeof value === 'number' && Number.isFinite(value)
28
30
  export function sheetCell(imageWidth, imageHeight, cols, rows, frame, params = {}) {
29
31
  if (params.cells?.length) {
30
32
  const index = Math.min(Math.max(0, Math.floor(frame)), params.cells.length - 1);
31
- return params.cells[index];
33
+ const cell = params.cells[index];
34
+ // Invariant: the index is clamped into a non-empty cells array.
35
+ if (!cell)
36
+ throw new Error(`sheetCell: missing cell at clamped index ${index}`);
37
+ return cell;
32
38
  }
33
39
  const c = Math.max(1, Math.floor(cols));
34
40
  const r = Math.max(1, Math.floor(rows));
@@ -1,5 +1,6 @@
1
1
  import * as THREE from 'three';
2
2
  import { ThreeTextureBackend } from './texture-backend.js';
3
+ import { reportRejection } from '../report-rejection.js';
3
4
  /**
4
5
  * Not `base.clone()`: `Texture.copy` sets `needsUpdate`, which bumps the
5
6
  * shared Source's version — a GPU re-upload of the same image for every
@@ -52,10 +53,10 @@ export class AssetLoader {
52
53
  if (entry.outcome === null) {
53
54
  // Chained here, before the consumer chains its own continuation on
54
55
  // `settled`, so the clone is uploadable by the time that one runs.
55
- void entry.settled.then((outcome) => {
56
+ reportRejection(entry.settled.then((outcome) => {
56
57
  if (outcome === 'loaded')
57
58
  texture.version = entry.base.version;
58
- });
59
+ }), 'texture upload');
59
60
  }
60
61
  return { texture, settled: entry.settled };
61
62
  }
@@ -1,3 +1,4 @@
1
+ import { reportRejection } from '../report-rejection.js';
1
2
  /**
2
3
  * The real WebAudio implementation (ADR 0013's default). Builds a small
3
4
  * mixing graph — one GainNode per sound feeding a StereoPannerNode, feeding
@@ -90,13 +91,19 @@ export class WebAudioBackend {
90
91
  this.masterGain.gain.value = volume;
91
92
  }
92
93
  suspend() {
93
- void this.context?.suspend();
94
+ const suspending = this.context?.suspend();
95
+ if (suspending)
96
+ reportRejection(suspending, 'audio suspend');
94
97
  }
95
98
  resume() {
96
- void this.ensureContext()?.resume();
99
+ const resuming = this.ensureContext()?.resume();
100
+ if (resuming)
101
+ reportRejection(resuming, 'audio resume');
97
102
  }
98
103
  close() {
99
- void this.context?.close();
104
+ const closing = this.context?.close();
105
+ if (closing)
106
+ reportRejection(closing, 'audio close');
100
107
  this.context = null;
101
108
  this.masterGain = null;
102
109
  this.channelGains.clear();
@@ -120,11 +127,13 @@ export class WebAudioBackend {
120
127
  const existing = this.channelGains.get(channel);
121
128
  if (existing)
122
129
  return existing;
123
- // Safe: only called once ensureContext() has already produced a context.
124
- const context = this.context;
130
+ const { context, masterGain } = this;
131
+ // Invariant: only called once ensureContext() has produced the context and master gain.
132
+ if (!context || !masterGain)
133
+ throw new Error('ensureChannelGain called before ensureContext');
125
134
  const gain = context.createGain();
126
135
  gain.gain.value = this.effectiveChannelGain(channel);
127
- gain.connect(this.masterGain);
136
+ gain.connect(masterGain);
128
137
  this.channelGains.set(channel, gain);
129
138
  return gain;
130
139
  }
@@ -5,11 +5,11 @@ function isSerializable(value) {
5
5
  const kind = typeof value;
6
6
  if (kind === 'string' || kind === 'number' || kind === 'boolean')
7
7
  return true;
8
- if (kind !== 'object')
8
+ if (typeof value !== 'object')
9
9
  return false;
10
10
  if (Array.isArray(value))
11
11
  return true;
12
- const proto = Object.getPrototypeOf(value);
12
+ const proto = Reflect.getPrototypeOf(value);
13
13
  return proto === Object.prototype || proto === null;
14
14
  }
15
15
  /**
@@ -32,7 +32,7 @@ export function authoringDefaults(Class, onError) {
32
32
  }
33
33
  const transient = new Set(Class.transient ?? []);
34
34
  const keys = new Set(Object.keys(instance));
35
- for (let proto = Object.getPrototypeOf(instance); proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
35
+ for (let proto = Reflect.getPrototypeOf(instance); proto && proto !== Object.prototype; proto = Reflect.getPrototypeOf(proto)) {
36
36
  for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(proto))) {
37
37
  if (descriptor.set)
38
38
  keys.add(key);
@@ -42,7 +42,7 @@ export function authoringDefaults(Class, onError) {
42
42
  for (const key of keys) {
43
43
  if (EXCLUDED_KEYS.has(key) || key.startsWith('_') || transient.has(key))
44
44
  continue;
45
- const value = instance[key];
45
+ const value = Reflect.get(instance, key);
46
46
  if (value === undefined || !isSerializable(value))
47
47
  continue;
48
48
  result[key] = value;
@@ -0,0 +1,142 @@
1
+ import type { ViewportRect } from './anchored-pieces.js';
2
+ import { type EasingName } from './game-time.js';
3
+ /** A Camera Effect color: a name or a six-digit hex, case-insensitive. */
4
+ export type CameraEffectColor = 'black' | 'white' | `#${string}`;
5
+ export interface ShakeOptions {
6
+ /** The largest offset, in world units, on each axis. Finite and >= 0. */
7
+ intensity: number;
8
+ /** Seconds of Game Time until the offset reaches 0. Finite and >= 0. */
9
+ seconds: number;
10
+ /** How the amplitude decays from `intensity` to 0; default `'linear'`. */
11
+ easing?: EasingName;
12
+ }
13
+ export interface FadeOptions {
14
+ /** The color to carry the view to (opacity 1), or `'clear'` (opacity 0, color kept). */
15
+ to: CameraEffectColor | 'clear';
16
+ /** Seconds of Game Time from the current opacity to the target. Finite and >= 0. */
17
+ seconds: number;
18
+ easing?: EasingName;
19
+ }
20
+ export interface FlashOptions {
21
+ color: CameraEffectColor;
22
+ /** Seconds of Game Time from opacity 1 back to 0. Finite and >= 0. */
23
+ seconds: number;
24
+ }
25
+ /** What `shake`, `fade` and `flash` hand back. */
26
+ export interface CameraEffectHandle {
27
+ /** Stops the effect where it is. Idempotent; resolves `done` with false. */
28
+ cancel(): void;
29
+ /** True once the effect completed; false if cancelled, replaced, ended by its scope or invalid. */
30
+ readonly done: Promise<boolean>;
31
+ /**
32
+ * True once a *later* call to the same kind of effect has taken over
33
+ * before this one ended on its own — false while it is still running,
34
+ * and false once it ends on its own accord (completes, is cancelled, or
35
+ * ends by its scope) with nothing else in its place. A Shake never
36
+ * supersedes another (CA-7: overlapping shakes coexist), so this is
37
+ * always false for a Shake handle. Unlike `done`, this reads
38
+ * synchronously: a Promise only notifies its `.then()` in a microtask,
39
+ * which can land well after a caller scheduled on Game Time needs the
40
+ * answer on an exact Simulation Step (PR #98 review, `scene-
41
+ * transition.ts`).
42
+ */
43
+ readonly superseded: boolean;
44
+ }
45
+ /** The effects' state after the last completed Simulation Step (read-only copy). */
46
+ export interface CameraEffectsState {
47
+ /** The offset, in world units, added to the camera only while drawing. */
48
+ shake: {
49
+ x: number;
50
+ y: number;
51
+ };
52
+ fade: {
53
+ color: string;
54
+ opacity: number;
55
+ };
56
+ flash: {
57
+ color: string;
58
+ opacity: number;
59
+ };
60
+ }
61
+ export interface CameraEffectsOptions {
62
+ /** Where the Fade and Flash layers mount (the canvas's parent); resolved lazily. */
63
+ host: () => HTMLElement;
64
+ /** One screen pixel in world units under a fixed resolution, or null (no snap). */
65
+ pixel: () => number | null;
66
+ }
67
+ declare const ADVANCE: unique symbol;
68
+ declare const LAYOUT: unique symbol;
69
+ /**
70
+ * Screen-level Camera Effects (issue #74, ADR 0020): Shake, Fade and Flash,
71
+ * beside `game.camera` and never written into it. They advance only inside
72
+ * a Simulation Step, right after the scene camera (spec inference 9), so
73
+ * nothing moves while the Game is not simulating or a Run Session is
74
+ * paused. A Shake is an offset the Game adds to the camera only while it
75
+ * draws; a Fade and a Flash are HTML layers over the letterboxed game
76
+ * viewport, above the UI overlay. A Fade is session-scoped (it survives a
77
+ * scene change, ADR 0011); a Shake or Flash dies with its scene.
78
+ */
79
+ export declare class CameraEffects {
80
+ private readonly options;
81
+ private steps;
82
+ private readonly shakes;
83
+ private offset;
84
+ private fadeRun;
85
+ private flashRun;
86
+ private readonly fadeLayer;
87
+ private readonly flashLayer;
88
+ private rect;
89
+ constructor(options: CameraEffectsOptions);
90
+ /** A fresh copy of the effects after the last completed Simulation Step. */
91
+ get state(): CameraEffectsState;
92
+ /**
93
+ * Jitters the drawn view by up to `intensity` world units per axis,
94
+ * decaying to 0 over `seconds`. Overlapping shakes apply the largest
95
+ * current amplitude. Not re-clamped to the scene camera's limits; snapped
96
+ * to whole screen pixels under a fixed resolution.
97
+ */
98
+ shake(options: ShakeOptions): CameraEffectHandle;
99
+ /**
100
+ * Carries the Fade layer from its current opacity to 1 in `to`'s color,
101
+ * or to 0 with `'clear'`, over `seconds`; the result then holds. A new
102
+ * fade cancels a running one (its `done` resolves false).
103
+ */
104
+ fade(options: FadeOptions): CameraEffectHandle;
105
+ /**
106
+ * Shows the Flash layer at opacity 1 in `color` and returns it to exactly
107
+ * 0 over `seconds`, independent of (and drawn above) the Fade. A new flash
108
+ * replaces a running one.
109
+ */
110
+ flash(options: FlashOptions): CameraEffectHandle;
111
+ /**
112
+ * Ends every Shake and Flash (their `done` resolves false) and keeps the
113
+ * Fade — opacity, color and any running progress. Called by
114
+ * `Game.unloadScene()`.
115
+ */
116
+ unloadScene(): void;
117
+ /** Ends every effect and removes the layers (`Game.dispose()`). */
118
+ dispose(): void;
119
+ /** Engine-internal: see advanceCameraEffects. */
120
+ [ADVANCE](): void;
121
+ /** Engine-internal: see layoutCameraEffects. */
122
+ [LAYOUT](rect: ViewportRect): void;
123
+ /** Normalized progress of a timed effect after the current step: 1 at (and past) its end. */
124
+ private progress;
125
+ private advanceShakes;
126
+ /** Mirrors both layers' state onto their elements, mounting them on first need. */
127
+ private draw;
128
+ private mount;
129
+ /** Sizes a layer to the game viewport (the whole host until the Game lays it out). */
130
+ private place;
131
+ private invalid;
132
+ }
133
+ /**
134
+ * Engine-internal: advances every Camera Effect by exactly one Simulation
135
+ * Step. `Game.simulateStep()` calls it right after the scene camera, so
136
+ * nothing advances while the Game is not simulating. Not re-exported from
137
+ * the package entry.
138
+ */
139
+ export declare function advanceCameraEffects(effects: CameraEffects): void;
140
+ /** Engine-internal: sizes the Fade and Flash layers to the game viewport (`Game.resize()`). */
141
+ export declare function layoutCameraEffects(effects: CameraEffects, rect: ViewportRect): void;
142
+ export {};
@@ -0,0 +1,338 @@
1
+ import { SIMULATION_STEP, SIMULATION_TIME_EPSILON } from './fixed-step.js';
2
+ import { resolveEasing } from './game-time.js';
3
+ const COLORS = new Map([
4
+ ['black', '#000000'],
5
+ ['white', '#ffffff'],
6
+ ]);
7
+ /** Above the UI overlay (`ui.ts`, z-index 9000): a Fade covers the HUD too. */
8
+ const FADE_Z = 9001;
9
+ const FLASH_Z = 9002;
10
+ const ADVANCE = Symbol('waica.cameraEffects.advance');
11
+ const LAYOUT = Symbol('waica.cameraEffects.layout');
12
+ function normalizeColor(value) {
13
+ if (typeof value !== 'string')
14
+ return null;
15
+ const named = COLORS.get(value);
16
+ if (named !== undefined)
17
+ return named;
18
+ return /^#[0-9a-fA-F]{6}$/.test(value) ? value.toLowerCase() : null;
19
+ }
20
+ function validSeconds(value) {
21
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
22
+ }
23
+ function easingOf(value) {
24
+ if (value !== undefined && typeof value !== 'string')
25
+ return null;
26
+ return resolveEasing(value);
27
+ }
28
+ /**
29
+ * Integer-only hash of (shake creation step, current step, axis) into
30
+ * [0, 1): the same bits in Node and every browser (spec inference 3), so a
31
+ * Run Session reproduces a shake frame for frame. No global RNG.
32
+ */
33
+ function jitter(seed, step, axis) {
34
+ let h = (Math.imul(seed + 1, 0x9e3779b1) ^ Math.imul(step + 1, 0x85ebca77) ^ Math.imul(axis + 1, 0xc2b2ae3d)) >>> 0;
35
+ h = Math.imul(h ^ (h >>> 16), 0x7feb352d) >>> 0;
36
+ h = Math.imul(h ^ (h >>> 15), 0x846ca68b) >>> 0;
37
+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
38
+ }
39
+ function settledHandle(done, cancel, superseded) {
40
+ return {
41
+ cancel,
42
+ done,
43
+ get superseded() {
44
+ return superseded();
45
+ },
46
+ };
47
+ }
48
+ /**
49
+ * Screen-level Camera Effects (issue #74, ADR 0020): Shake, Fade and Flash,
50
+ * beside `game.camera` and never written into it. They advance only inside
51
+ * a Simulation Step, right after the scene camera (spec inference 9), so
52
+ * nothing moves while the Game is not simulating or a Run Session is
53
+ * paused. A Shake is an offset the Game adds to the camera only while it
54
+ * draws; a Fade and a Flash are HTML layers over the letterboxed game
55
+ * viewport, above the UI overlay. A Fade is session-scoped (it survives a
56
+ * scene change, ADR 0011); a Shake or Flash dies with its scene.
57
+ */
58
+ export class CameraEffects {
59
+ options;
60
+ steps = 0;
61
+ shakes = [];
62
+ offset = { x: 0, y: 0 };
63
+ fadeRun = null;
64
+ flashRun = null;
65
+ fadeLayer = { color: '#000000', opacity: 0, element: null };
66
+ flashLayer = { color: '#ffffff', opacity: 0, element: null };
67
+ rect = null;
68
+ constructor(options) {
69
+ this.options = options;
70
+ }
71
+ /** A fresh copy of the effects after the last completed Simulation Step. */
72
+ get state() {
73
+ return {
74
+ shake: { ...this.offset },
75
+ fade: { color: this.fadeLayer.color, opacity: this.fadeLayer.opacity },
76
+ flash: { color: this.flashLayer.color, opacity: this.flashLayer.opacity },
77
+ };
78
+ }
79
+ /**
80
+ * Jitters the drawn view by up to `intensity` world units per axis,
81
+ * decaying to 0 over `seconds`. Overlapping shakes apply the largest
82
+ * current amplitude. Not re-clamped to the scene camera's limits; snapped
83
+ * to whole screen pixels under a fixed resolution.
84
+ */
85
+ shake(options) {
86
+ const { intensity, seconds } = options;
87
+ if (!validSeconds(intensity))
88
+ return this.invalid('shake(): intensity must be a finite number >= 0');
89
+ if (!validSeconds(seconds))
90
+ return this.invalid('shake(): seconds must be a finite number >= 0');
91
+ const ease = easingOf(options.easing);
92
+ if (!ease)
93
+ return this.invalid('shake(): easing must be a known easing name');
94
+ let resolve = () => { };
95
+ const done = new Promise((r) => (resolve = r));
96
+ const entry = { start: this.steps, seconds, ease, resolve, intensity, superseded: false };
97
+ this.shakes.push(entry);
98
+ return settledHandle(done, () => {
99
+ const index = this.shakes.indexOf(entry);
100
+ if (index === -1)
101
+ return;
102
+ this.shakes.splice(index, 1);
103
+ entry.resolve(false);
104
+ },
105
+ // Never superseded (CA-7): overlapping shakes coexist, so nothing
106
+ // ever sets a Shake entry's flag; it stays false for its own life.
107
+ () => entry.superseded);
108
+ }
109
+ /**
110
+ * Carries the Fade layer from its current opacity to 1 in `to`'s color,
111
+ * or to 0 with `'clear'`, over `seconds`; the result then holds. A new
112
+ * fade cancels a running one (its `done` resolves false).
113
+ */
114
+ fade(options) {
115
+ const clear = options.to === 'clear';
116
+ const color = clear ? this.fadeLayer.color : normalizeColor(options.to);
117
+ if (!color)
118
+ return this.invalid(`fade(): unknown color "${String(options.to)}"; use 'black', 'white', '#rrggbb' or 'clear'`);
119
+ if (!validSeconds(options.seconds))
120
+ return this.invalid('fade(): seconds must be a finite number >= 0');
121
+ const ease = easingOf(options.easing);
122
+ if (!ease)
123
+ return this.invalid('fade(): easing must be a known easing name');
124
+ // Marks the outgoing fade superseded (not just cancelled) before
125
+ // resolving `done` false: a caller checking `.superseded` later must
126
+ // see this, whatever happens to the layer afterwards (PR #98 review).
127
+ if (this.fadeRun)
128
+ this.fadeRun.superseded = true;
129
+ this.fadeRun?.resolve(false);
130
+ let resolve = () => { };
131
+ const done = new Promise((r) => (resolve = r));
132
+ const entry = {
133
+ start: this.steps,
134
+ seconds: options.seconds,
135
+ ease,
136
+ resolve,
137
+ from: this.fadeLayer.opacity,
138
+ to: clear ? 0 : 1,
139
+ superseded: false,
140
+ };
141
+ this.fadeRun = entry;
142
+ this.fadeLayer.color = color;
143
+ this.draw();
144
+ return settledHandle(done, () => {
145
+ if (this.fadeRun !== entry)
146
+ return;
147
+ this.fadeRun = null;
148
+ entry.resolve(false);
149
+ }, () => entry.superseded);
150
+ }
151
+ /**
152
+ * Shows the Flash layer at opacity 1 in `color` and returns it to exactly
153
+ * 0 over `seconds`, independent of (and drawn above) the Fade. A new flash
154
+ * replaces a running one.
155
+ */
156
+ flash(options) {
157
+ const color = normalizeColor(options.color);
158
+ if (!color)
159
+ return this.invalid(`flash(): unknown color "${String(options.color)}"; use 'black', 'white' or '#rrggbb'`);
160
+ if (!validSeconds(options.seconds))
161
+ return this.invalid('flash(): seconds must be a finite number >= 0');
162
+ if (this.flashRun)
163
+ this.flashRun.superseded = true;
164
+ this.flashRun?.resolve(false);
165
+ let resolve = () => { };
166
+ const done = new Promise((r) => (resolve = r));
167
+ const entry = { start: this.steps, seconds: options.seconds, ease: (t) => t, resolve, superseded: false };
168
+ this.flashRun = entry;
169
+ this.flashLayer.color = color;
170
+ this.flashLayer.opacity = 1;
171
+ this.draw();
172
+ return settledHandle(done, () => {
173
+ if (this.flashRun !== entry)
174
+ return;
175
+ this.flashRun = null;
176
+ this.flashLayer.opacity = 0;
177
+ this.draw();
178
+ entry.resolve(false);
179
+ }, () => entry.superseded);
180
+ }
181
+ /**
182
+ * Ends every Shake and Flash (their `done` resolves false) and keeps the
183
+ * Fade — opacity, color and any running progress. Called by
184
+ * `Game.unloadScene()`.
185
+ */
186
+ unloadScene() {
187
+ for (const shake of this.shakes.splice(0))
188
+ shake.resolve(false);
189
+ this.offset = { x: 0, y: 0 };
190
+ this.flashRun?.resolve(false);
191
+ this.flashRun = null;
192
+ this.flashLayer.opacity = 0;
193
+ this.draw();
194
+ }
195
+ /** Ends every effect and removes the layers (`Game.dispose()`). */
196
+ dispose() {
197
+ this.unloadScene();
198
+ this.fadeRun?.resolve(false);
199
+ this.fadeRun = null;
200
+ this.fadeLayer.color = '#000000';
201
+ this.fadeLayer.opacity = 0;
202
+ for (const layer of [this.fadeLayer, this.flashLayer]) {
203
+ layer.element?.remove();
204
+ layer.element = null;
205
+ }
206
+ }
207
+ /** Engine-internal: see advanceCameraEffects. */
208
+ [ADVANCE]() {
209
+ this.steps += 1;
210
+ this.advanceShakes();
211
+ const fade = this.fadeRun;
212
+ if (fade) {
213
+ const t = this.progress(fade);
214
+ this.fadeLayer.opacity = t >= 1 ? fade.to : fade.from + (fade.to - fade.from) * fade.ease(t);
215
+ if (t >= 1) {
216
+ this.fadeRun = null;
217
+ fade.resolve(true);
218
+ }
219
+ }
220
+ const flash = this.flashRun;
221
+ if (flash) {
222
+ const t = this.progress(flash);
223
+ this.flashLayer.opacity = t >= 1 ? 0 : 1 - flash.ease(t);
224
+ if (t >= 1) {
225
+ this.flashRun = null;
226
+ flash.resolve(true);
227
+ }
228
+ }
229
+ this.draw();
230
+ }
231
+ /** Engine-internal: see layoutCameraEffects. */
232
+ [LAYOUT](rect) {
233
+ this.rect = { ...rect };
234
+ for (const layer of [this.fadeLayer, this.flashLayer]) {
235
+ if (layer.element)
236
+ this.place(layer.element);
237
+ }
238
+ }
239
+ /** Normalized progress of a timed effect after the current step: 1 at (and past) its end. */
240
+ progress(entry) {
241
+ const elapsed = (this.steps - entry.start) * SIMULATION_STEP;
242
+ if (elapsed >= entry.seconds - SIMULATION_TIME_EPSILON)
243
+ return 1;
244
+ return elapsed / entry.seconds;
245
+ }
246
+ advanceShakes() {
247
+ let amplitude = 0;
248
+ let seed = 0;
249
+ for (const shake of [...this.shakes]) {
250
+ const t = this.progress(shake);
251
+ if (t >= 1) {
252
+ this.shakes.splice(this.shakes.indexOf(shake), 1);
253
+ shake.resolve(true);
254
+ continue;
255
+ }
256
+ const current = shake.intensity * (1 - shake.ease(t));
257
+ if (current > amplitude) {
258
+ amplitude = current;
259
+ seed = shake.start;
260
+ }
261
+ }
262
+ if (amplitude <= 0) {
263
+ this.offset = { x: 0, y: 0 };
264
+ return;
265
+ }
266
+ const pixel = this.options.pixel();
267
+ const axis = (index) => {
268
+ const raw = amplitude * (2 * jitter(seed, this.steps, index) - 1);
269
+ // Truncating toward zero keeps a snapped offset inside the envelope.
270
+ const snapped = pixel ? Math.trunc(raw / pixel) * pixel : raw;
271
+ return snapped + 0;
272
+ };
273
+ this.offset = { x: axis(0), y: axis(1) };
274
+ }
275
+ /** Mirrors both layers' state onto their elements, mounting them on first need. */
276
+ draw() {
277
+ const needed = this.fadeLayer.opacity > 0 || this.flashLayer.opacity > 0;
278
+ if (needed && !this.fadeLayer.element)
279
+ this.mount();
280
+ for (const layer of [this.fadeLayer, this.flashLayer]) {
281
+ const element = layer.element;
282
+ if (!element)
283
+ continue;
284
+ element.style.backgroundColor = layer.color;
285
+ element.style.opacity = String(layer.opacity);
286
+ element.style.display = layer.opacity > 0 ? '' : 'none';
287
+ }
288
+ }
289
+ mount() {
290
+ const host = this.options.host();
291
+ if (getComputedStyle(host).position === 'static')
292
+ host.style.position = 'relative';
293
+ for (const [layer, name, z] of [
294
+ [this.fadeLayer, 'fade', FADE_Z],
295
+ [this.flashLayer, 'flash', FLASH_Z],
296
+ ]) {
297
+ const element = document.createElement('div');
298
+ element.dataset.waicaCameraEffect = name;
299
+ element.style.position = 'absolute';
300
+ element.style.pointerEvents = 'none';
301
+ element.style.zIndex = String(z);
302
+ element.style.display = 'none';
303
+ this.place(element);
304
+ host.append(element);
305
+ layer.element = element;
306
+ }
307
+ }
308
+ /** Sizes a layer to the game viewport (the whole host until the Game lays it out). */
309
+ place(element) {
310
+ const rect = this.rect;
311
+ if (!rect) {
312
+ element.style.inset = '0';
313
+ return;
314
+ }
315
+ element.style.inset = '';
316
+ element.style.left = `${rect.x}px`;
317
+ element.style.top = `${rect.y}px`;
318
+ element.style.width = `${rect.width}px`;
319
+ element.style.height = `${rect.height}px`;
320
+ }
321
+ invalid(message) {
322
+ console.warn(`[waica] cameraEffects.${message}`);
323
+ return settledHandle(Promise.resolve(false), () => { }, () => false);
324
+ }
325
+ }
326
+ /**
327
+ * Engine-internal: advances every Camera Effect by exactly one Simulation
328
+ * Step. `Game.simulateStep()` calls it right after the scene camera, so
329
+ * nothing advances while the Game is not simulating. Not re-exported from
330
+ * the package entry.
331
+ */
332
+ export function advanceCameraEffects(effects) {
333
+ effects[ADVANCE]();
334
+ }
335
+ /** Engine-internal: sizes the Fade and Flash layers to the game viewport (`Game.resize()`). */
336
+ export function layoutCameraEffects(effects, rect) {
337
+ effects[LAYOUT](rect);
338
+ }