@waica/engine 0.16.0 → 0.18.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 +53 -0
- package/dist/anchored-pieces.d.ts +122 -0
- package/dist/anchored-pieces.js +330 -0
- package/dist/assets/asset-loader.d.ts +76 -0
- package/dist/assets/asset-loader.js +138 -0
- package/dist/assets/texture-backend.d.ts +17 -0
- package/dist/assets/texture-backend.js +15 -0
- package/dist/component.d.ts +1 -1
- package/dist/components/animated-sprite.d.ts +17 -4
- package/dist/components/animated-sprite.js +41 -12
- package/dist/components/sprite.d.ts +6 -0
- package/dist/components/sprite.js +28 -6
- package/dist/components/tilemap.d.ts +6 -0
- package/dist/components/tilemap.js +28 -4
- package/dist/game.d.ts +16 -1
- package/dist/game.js +27 -2
- package/dist/index.d.ts +5 -1
- package/dist/index.js +1 -0
- package/dist/input.d.ts +6 -0
- package/dist/input.js +8 -0
- package/dist/runtime-bridge.d.ts +11 -2
- package/dist/runtime-bridge.js +7 -2
- package/dist/runtime-inspection.d.ts +26 -0
- package/dist/runtime-inspection.js +50 -15
- package/dist/ui-bindings.d.ts +12 -0
- package/dist/ui-bindings.js +51 -0
- package/dist/ui.d.ts +35 -3
- package/dist/ui.js +54 -45
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -193,3 +193,56 @@ game.time.now // seconds of Game Time since the Game started
|
|
|
193
193
|
- **Step placement.** At the start of every Simulation Step, before the Component Update Schedule, `game.time` advances `now`, runs every due timer (due time, then creation order), then advances every tween that existed before that step (creation order). Work a callback creates is never run or advanced in that same step.
|
|
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
|
+
|
|
197
|
+
## game.ui.attach: Anchored Pieces
|
|
198
|
+
|
|
199
|
+
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.
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
const hit = game.ui.attach('damage-number', orc, { offset: [0, 1.2], seconds: 0.8, values: { amount: 3 } })
|
|
203
|
+
const bar = game.ui.attach('health-bar', orc, { offset: [0, 1.4], values: { current: 7, max: 10 } })
|
|
204
|
+
bar.set('current', 6) // {{current}} and --current update live
|
|
205
|
+
bar.remove()
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
```html
|
|
209
|
+
<style>
|
|
210
|
+
.bar { position: absolute; transform: translate(-50%, -100%); width: calc(1.2 * var(--waica-unit)); height: 4px; background: #0008 }
|
|
211
|
+
.fill { width: calc(var(--current) / var(--max) * 100%); height: 100%; background: #ef476f }
|
|
212
|
+
</style>
|
|
213
|
+
<div class="bar"><div class="fill"></div></div>
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
- **Options.** `offset: [x, y]` (default `[0, 0]`) is in world units, added to the entity's render point in render space: `[0, 1]` is one unit up on screen, under `projection: 'isometric'` too. `seconds` gives the instance its own lifetime (below). `values` are the instance's own values.
|
|
217
|
+
- **Handle.** `set(name, value)`, `remove()`, `alive` and `element` — the piece's content root inside the instance's shadow root, `null` once removed.
|
|
218
|
+
- **Placement.** Once per render frame — after the isometric projection and the camera step, before the render, never per Simulation Step — each instance's shadow host is placed as a zero-size box at its anchor point, converted to whole CSS pixels from the top-left corner of the game viewport; the piece's own CSS centres itself around that point (e.g. `transform: translate(-50%, -100%)`). A move therefore shows on the next frame, not before. All instances live in one layer fitted to the game viewport — the whole canvas, or the letterboxed rectangle under a fixed `resolution` — with `overflow: hidden`, so they never draw over the letterbox bars.
|
|
219
|
+
- **Per-instance values.** Inside an instance, `{{name}}` renders the instance's own value when it has one and the Game stat of that name otherwise (booleans as ✓/✕, missing as empty); `set` updates it in place, and a stat change still updates every placeholder with no instance value. Every number value is also published as the custom property `--name` on the instance (`values: { current: 7, max: 10 }` gives `--current: 7` and `--max: 10`), booleans as `1`/`0`; strings are text only. There are no binding expressions: arithmetic belongs in CSS `calc()`.
|
|
220
|
+
- **`--waica-unit`.** Every frame, the anchored layer carries `--waica-unit` inline, and every instance inherits it through its shadow host: CSS pixels per world unit, the game viewport's CSS height divided by the current view height. It follows camera zoom and the letterbox scale, so `calc(1.1 * var(--waica-unit))` sizes a piece in world units while everything else keeps its CSS pixel size.
|
|
221
|
+
- **Draw order.** The anchored layer sits below every screen-space piece. Within it, every frame, the instance lower on screen draws on top, like y-sort; equal heights keep creation order, later on top.
|
|
222
|
+
- **Lifetime.** Without `seconds`, an instance is removed before its entity's `destroy()` returns. With `seconds: S`, it is removed exactly when a `game.time.after(S, …)` scheduled at the same moment would fire — it counts Game Time (ADR 0017), so it never runs out while the Game is paused or not simulating, and until then it counts in `game.time.pending`. If its entity is destroyed first, it lingers frozen where the entity was at `destroy()` time (still moving with the camera) until it expires. `unloadScene()`, every scene load that unloads and `game.dispose()` remove every instance: none outlives its scene. `remove()` is immediate; `set` and `remove` on a removed handle are silent no-ops. CSS animations and transitions inside an instance follow Game Time, not the wall clock: every frame each is paused at the Game Time since it started (the attach, for those the piece starts with), so a paused Game freezes a damage number mid-flight — it resumes from there, even after the overlay hid while not simulating — and `step { frames: N }` advances it by N/60 s.
|
|
223
|
+
- **Invalid attach never throws.** An undefined piece name logs one `[waica]` warning per name per Game; an entity that is no longer `alive` logs one per call. Both return a handle with `alive: false` and `element: null` that mounts nothing. To attach only when the project defines the piece, as `Interactable` does with `npc-bubble` and `interact-prompt`, check `game.ui.has(name)` first.
|
|
224
|
+
- **Runtime Snapshot.** Every snapshot carries `ui: { shown, anchored }`: the visible screen pieces by name, and each live instance in creation order as `{ piece, entity, x, y, clipped, values }`, with the pixel coordinates of its last placement; `values` are bounded like component state (a string over 4 KiB becomes a `$waica: 'truncated'` marker), and once every entity is cut the 1 MiB snapshot cap drops instances from the end.
|
|
225
|
+
|
|
226
|
+
The trade-off is ADR 0018's: Anchored Pieces are HTML drawn over the game view, not text rendered in the three scene. They always draw above the world — a label behind a tree draws over it — hide with the rest of the UI overlay while the Game is not simulating (including the editor's edit mode), and do not align to a pixel-art grid.
|
|
227
|
+
|
|
228
|
+
## game.assets: textures, preload and Assets Ready
|
|
229
|
+
|
|
230
|
+
Every `Game` owns an `assets: AssetLoader` — the engine's texture cache. `Sprite`, `AnimatedSprite` and `Tilemap` load through it: one fetch and one base texture per URL for the whole life of the Game, and every component gets its own clone of that base (three shares the GPU upload between clones with equal sampler parameters and reference-counts their disposal), so eight crates cost one image. A scene load never waits for images — `loadScene` stays synchronous — and **Assets Ready** is a promise beside it (ADR 0019):
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
game.registerSceneCatalog({ scenes, registry })
|
|
234
|
+
game.loadSceneByName('main')
|
|
235
|
+
await game.assets.ready() // every texture requested so far has loaded, or failed and been recorded
|
|
236
|
+
game.start()
|
|
237
|
+
|
|
238
|
+
await game.assets.preload(['waica:iso-crate', 'src/art/tree.png']) // ahead of a later scene
|
|
239
|
+
game.assets.status // { pending, loaded, failed } — a fresh object on every read
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
- **Cache rule.** Keyed by the URL as received: components pass what `resolveProps` resolved, `preload` resolves each uri through the registered scene catalog first (identity before `registerSceneCatalog`, and for a uri the resolver leaves unchanged). N requests of one URL call the backend once; `status.loaded` counts URLs, not requests. Keep-all: `unloadScene()`, `loadScene` and `loadSceneByName` never dispose, evict or reset an entry — `main → cave → main` re-downloads nothing — and only `game.dispose()` disposes every cached base, exactly once, leaving `status` at zeros. Components dispose only their own clone.
|
|
243
|
+
- **`ready()`.** Resolves the first time `pending` is 0 after the call: at once when nothing is pending, otherwise once every URL requested before or while waiting has settled. Readiness is relative to the moment it is awaited — a later spawn that requests new art reopens it until that art settles — and concurrent callers all resolve. It never rejects, and it has no timeout: a stalled image with no error event holds a host that awaits it (a Run Session is bounded by the MCP's session timeout instead).
|
|
244
|
+
- **`preload(uris)`.** Requests every uri and resolves once all of them settled, failures included. A component that later asks for the same resolved URL is a cache hit.
|
|
245
|
+
- **`status`.** `pending` is current; `loaded` and `failed` are cumulative for the Game and only grow until `dispose()`. A host that wants a loading bar reads it from `game.onUpdate`.
|
|
246
|
+
- **Failure rule.** A texture that fails to load is recorded, not thrown: `console.warn('[waica] assets: failed to load "<url>"', error)` once per Game per URL, `failed` counts it, `ready()` resolves, and every consumer falls back to its flat material — `Sprite` and `Tilemap` drop the failed map, dispose their clone and render their `color` again; `AnimatedSprite` never installs the failed sheet's clone, so that sheet's frames show a plain white quad. Asking for that URL again on the same Game is a cached failure — no retry, no second warning.
|
|
247
|
+
- **`GameOptions.textures`.** Replaces the real `THREE.TextureLoader` backend for that Game (ADR 0013's seam, applied to textures): `happy-dom` decodes no images, so a project's own tests inject a backend that resolves at once. The Runtime Bridge reports `assets` in its metadata under the `'assets'` capability, and a Run Session waits for `pending === 0` at readiness, after a `scene` operation and before every screenshot.
|
|
248
|
+
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import type { Entity } from './entity.js';
|
|
2
|
+
import type { PointerCamera, PointerResolution } from './pointer.js';
|
|
3
|
+
import type { RuntimeSnapshotUi } from './runtime-inspection.js';
|
|
4
|
+
import type { Stats, StatValue } from './stats.js';
|
|
5
|
+
/** Options for `game.ui.attach` (issue #72). */
|
|
6
|
+
export interface AttachOptions {
|
|
7
|
+
/**
|
|
8
|
+
* World units added to the entity's render point, in render space:
|
|
9
|
+
* `[0, 1]` is one unit up on screen, under isometric projection too.
|
|
10
|
+
* Default `[0, 0]`. Pixel fine-tuning belongs in the piece's CSS.
|
|
11
|
+
*/
|
|
12
|
+
offset?: [number, number];
|
|
13
|
+
/**
|
|
14
|
+
* Seconds of Game Time the instance lives for (ADR 0017). It outlives its
|
|
15
|
+
* entity, frozen where the entity last was, until then. Absent: the
|
|
16
|
+
* instance dies with its entity.
|
|
17
|
+
*/
|
|
18
|
+
seconds?: number;
|
|
19
|
+
/**
|
|
20
|
+
* The instance's own values: `{{name}}` reads these before the Game's
|
|
21
|
+
* stats, and every number (verbatim) or boolean (`1`/`0`) is also
|
|
22
|
+
* published as the custom property `--name` on the instance.
|
|
23
|
+
*/
|
|
24
|
+
values?: Record<string, StatValue>;
|
|
25
|
+
}
|
|
26
|
+
/** One Anchored Piece, as `game.ui.attach` hands it back. */
|
|
27
|
+
export interface AnchoredPieceHandle {
|
|
28
|
+
/** Sets one of the instance's own values: its `{{name}}` text and `--name` update in place. */
|
|
29
|
+
set(name: string, value: StatValue): void;
|
|
30
|
+
/** Removes the instance now. `set` and `remove` on a removed handle are silent no-ops. */
|
|
31
|
+
remove(): void;
|
|
32
|
+
/** False once removed, and from the start on an invalid attach. */
|
|
33
|
+
readonly alive: boolean;
|
|
34
|
+
/** The piece's content root inside the instance's own shadow root; null once removed. */
|
|
35
|
+
readonly element: HTMLElement | null;
|
|
36
|
+
}
|
|
37
|
+
/** A rectangle in CSS px, relative to the canvas's top-left corner. */
|
|
38
|
+
export interface ViewportRect {
|
|
39
|
+
x: number;
|
|
40
|
+
y: number;
|
|
41
|
+
width: number;
|
|
42
|
+
height: number;
|
|
43
|
+
}
|
|
44
|
+
/** What the Game tells the anchored layer each time it places: read live, never cached. */
|
|
45
|
+
export interface AnchorView {
|
|
46
|
+
camera: PointerCamera;
|
|
47
|
+
/** The game viewport: see gameViewport. */
|
|
48
|
+
viewport: ViewportRect;
|
|
49
|
+
projection: 'isometric' | null;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The game viewport (issue #72): the rectangle the renderer draws into —
|
|
53
|
+
* the whole canvas without a fixed resolution, the largest centred rect
|
|
54
|
+
* with its aspect (letterbox) with one. The same math as Game.resize() and
|
|
55
|
+
* the Pointer's letterbox, whose screen→world mapping placement inverts.
|
|
56
|
+
*/
|
|
57
|
+
export declare function gameViewport(width: number, height: number, resolution: PointerResolution | null): ViewportRect;
|
|
58
|
+
/** What GameUi lends the anchored layer: its catalog, the stats and its overlay. */
|
|
59
|
+
export interface AnchoredPiecesDeps {
|
|
60
|
+
stats: Stats;
|
|
61
|
+
/** A piece's HTML source, or undefined when the piece was never defined. */
|
|
62
|
+
source(name: string): string | undefined;
|
|
63
|
+
/** GameUi's overlay, mounted on demand. */
|
|
64
|
+
overlay(): HTMLElement;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Anchored Pieces (issue #72, ADR 0018) — instances of a UI Piece, as many
|
|
68
|
+
* as needed, each following an entity in one layer of GameUi's overlay,
|
|
69
|
+
* each with its own shadow root and its own values ahead of the Game's stats.
|
|
70
|
+
* Owned by GameUi, which reaches it through `attach`; the Game drives the
|
|
71
|
+
* rest through `anchoredPiecesOf` (ui.ts): `connect` once, `place` every
|
|
72
|
+
* render frame.
|
|
73
|
+
*/
|
|
74
|
+
export declare class AnchoredPieces {
|
|
75
|
+
private readonly deps;
|
|
76
|
+
private readonly instances;
|
|
77
|
+
/** Undefined piece names already warned about: one warning per name per Game. */
|
|
78
|
+
private readonly warnedPieces;
|
|
79
|
+
private layer?;
|
|
80
|
+
private view;
|
|
81
|
+
constructor(deps: AnchoredPiecesDeps);
|
|
82
|
+
/** Called once by the Game: where the camera, viewport and projection are read from. */
|
|
83
|
+
connect(view: () => AnchorView): void;
|
|
84
|
+
attach(piece: string, entity: Entity, options?: AttachOptions): AnchoredPieceHandle;
|
|
85
|
+
/**
|
|
86
|
+
* Called by the Game before an entity's destroy() returns: its instances
|
|
87
|
+
* go with it, except those given `seconds`, which stay frozen at its
|
|
88
|
+
* current anchor point until they expire.
|
|
89
|
+
*/
|
|
90
|
+
release(entity: Entity): void;
|
|
91
|
+
/**
|
|
92
|
+
* The live instances for the Runtime Snapshot, in creation order, with
|
|
93
|
+
* the coordinates of their last placement — or, for one attached since
|
|
94
|
+
* the last render frame, where the next frame will place it.
|
|
95
|
+
*/
|
|
96
|
+
snapshot(): RuntimeSnapshotUi['anchored'];
|
|
97
|
+
/** Removes every instance, lingering ones too (GameUi.unloadScene). */
|
|
98
|
+
clear(): void;
|
|
99
|
+
/** Removes every instance and forgets the layer along with the overlay (GameUi.dispose). */
|
|
100
|
+
dispose(): void;
|
|
101
|
+
/**
|
|
102
|
+
* Called by the Game once per render frame, after the isometric pass and
|
|
103
|
+
* before the render (never per Simulation Step, never on attach): fits
|
|
104
|
+
* the layer to the game viewport, sets the frame's `--waica-unit` on it
|
|
105
|
+
* (every instance inherits it through its shadow host) and puts every
|
|
106
|
+
* instance's zero-size shadow host at its anchor point, its CSS
|
|
107
|
+
* animations set to Game Time (followGameTime).
|
|
108
|
+
*/
|
|
109
|
+
place(): void;
|
|
110
|
+
private bind;
|
|
111
|
+
/** Writes a name's current value — the instance's own, else the Game stat — into its placeholders. */
|
|
112
|
+
private render;
|
|
113
|
+
private set;
|
|
114
|
+
private remove;
|
|
115
|
+
private handleFor;
|
|
116
|
+
/**
|
|
117
|
+
* The single layer every instance lives in, kept as the overlay's first
|
|
118
|
+
* child — even when a screen piece created the overlay first — so every
|
|
119
|
+
* screen-space piece draws above every anchored instance.
|
|
120
|
+
*/
|
|
121
|
+
private mountLayer;
|
|
122
|
+
}
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import { projectIsometric } from './projection.js';
|
|
2
|
+
import { placeholders, renderStat } from './ui-bindings.js';
|
|
3
|
+
/**
|
|
4
|
+
* The game viewport (issue #72): the rectangle the renderer draws into —
|
|
5
|
+
* the whole canvas without a fixed resolution, the largest centred rect
|
|
6
|
+
* with its aspect (letterbox) with one. The same math as Game.resize() and
|
|
7
|
+
* the Pointer's letterbox, whose screen→world mapping placement inverts.
|
|
8
|
+
*/
|
|
9
|
+
export function gameViewport(width, height, resolution) {
|
|
10
|
+
if (!resolution)
|
|
11
|
+
return { x: 0, y: 0, width, height };
|
|
12
|
+
const aspect = resolution.width / resolution.height;
|
|
13
|
+
const vw = Math.min(width, height * aspect);
|
|
14
|
+
const vh = vw / aspect;
|
|
15
|
+
return { x: (width - vw) / 2, y: (height - vh) / 2, width: vw, height: vh };
|
|
16
|
+
}
|
|
17
|
+
/** The handle of an invalid attach (CA-7): nothing mounted, nothing to change. */
|
|
18
|
+
const INERT_HANDLE = Object.freeze({
|
|
19
|
+
set() { },
|
|
20
|
+
remove() { },
|
|
21
|
+
alive: false,
|
|
22
|
+
element: null,
|
|
23
|
+
});
|
|
24
|
+
/** A GameUi no Game connected has no viewport: nothing it holds is ever placed. */
|
|
25
|
+
const UNPLACED = { x: 0, y: 0, clipped: true, depth: 0 };
|
|
26
|
+
/**
|
|
27
|
+
* Anchored Pieces (issue #72, ADR 0018) — instances of a UI Piece, as many
|
|
28
|
+
* as needed, each following an entity in one layer of GameUi's overlay,
|
|
29
|
+
* each with its own shadow root and its own values ahead of the Game's stats.
|
|
30
|
+
* Owned by GameUi, which reaches it through `attach`; the Game drives the
|
|
31
|
+
* rest through `anchoredPiecesOf` (ui.ts): `connect` once, `place` every
|
|
32
|
+
* render frame.
|
|
33
|
+
*/
|
|
34
|
+
export class AnchoredPieces {
|
|
35
|
+
deps;
|
|
36
|
+
instances = [];
|
|
37
|
+
/** Undefined piece names already warned about: one warning per name per Game. */
|
|
38
|
+
warnedPieces = new Set();
|
|
39
|
+
layer;
|
|
40
|
+
view = null;
|
|
41
|
+
constructor(deps) {
|
|
42
|
+
this.deps = deps;
|
|
43
|
+
}
|
|
44
|
+
/** Called once by the Game: where the camera, viewport and projection are read from. */
|
|
45
|
+
connect(view) {
|
|
46
|
+
this.view = view;
|
|
47
|
+
}
|
|
48
|
+
attach(piece, entity, options = {}) {
|
|
49
|
+
const html = this.deps.source(piece);
|
|
50
|
+
if (html === undefined && !this.warnedPieces.has(piece)) {
|
|
51
|
+
this.warnedPieces.add(piece);
|
|
52
|
+
console.warn(`[waica] cannot attach unknown ui piece: "${piece}"`);
|
|
53
|
+
}
|
|
54
|
+
if (!entity.alive) {
|
|
55
|
+
console.warn(`[waica] cannot attach ui piece "${piece}" to destroyed entity "${entity.name}"`);
|
|
56
|
+
}
|
|
57
|
+
if (html === undefined || !entity.alive)
|
|
58
|
+
return INERT_HANDLE;
|
|
59
|
+
const host = document.createElement('div');
|
|
60
|
+
host.style.cssText = 'position:absolute;left:0;top:0;width:0;height:0;pointer-events:none';
|
|
61
|
+
const shadow = host.attachShadow({ mode: 'open' });
|
|
62
|
+
const root = document.createElement('div');
|
|
63
|
+
root.style.display = 'contents';
|
|
64
|
+
root.innerHTML = html;
|
|
65
|
+
shadow.append(root);
|
|
66
|
+
const offset = options.offset ?? [0, 0];
|
|
67
|
+
const instance = {
|
|
68
|
+
piece,
|
|
69
|
+
entity,
|
|
70
|
+
offset: [offset[0], offset[1]],
|
|
71
|
+
values: new Map(Object.entries(options.values ?? {})),
|
|
72
|
+
host,
|
|
73
|
+
root,
|
|
74
|
+
texts: new Map(),
|
|
75
|
+
unsubs: [],
|
|
76
|
+
born: entity.game.time.now,
|
|
77
|
+
clocks: new WeakMap(),
|
|
78
|
+
named: new WeakMap(),
|
|
79
|
+
expiry: null,
|
|
80
|
+
frozen: null,
|
|
81
|
+
placed: null,
|
|
82
|
+
alive: true,
|
|
83
|
+
};
|
|
84
|
+
this.bind(instance);
|
|
85
|
+
for (const [name, value] of instance.values)
|
|
86
|
+
publish(host, name, value);
|
|
87
|
+
this.mountLayer().append(host);
|
|
88
|
+
this.instances.push(instance);
|
|
89
|
+
if (options.seconds !== undefined) {
|
|
90
|
+
// Not owned by the entity: it must outlive it. Scene-scoped, like the
|
|
91
|
+
// instance itself. A duration game.time rejects (it warns) leaves the
|
|
92
|
+
// instance to die with its entity instead of lingering forever.
|
|
93
|
+
const expiry = entity.game.time.after(options.seconds, () => this.remove(instance));
|
|
94
|
+
instance.expiry = expiry.active ? expiry : null;
|
|
95
|
+
}
|
|
96
|
+
return this.handleFor(instance);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Called by the Game before an entity's destroy() returns: its instances
|
|
100
|
+
* go with it, except those given `seconds`, which stay frozen at its
|
|
101
|
+
* current anchor point until they expire.
|
|
102
|
+
*/
|
|
103
|
+
release(entity) {
|
|
104
|
+
for (const instance of this.instances.filter((candidate) => candidate.entity === entity)) {
|
|
105
|
+
if (instance.expiry)
|
|
106
|
+
instance.frozen = anchorPoint(instance, this.view?.().projection ?? null);
|
|
107
|
+
else
|
|
108
|
+
this.remove(instance);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The live instances for the Runtime Snapshot, in creation order, with
|
|
113
|
+
* the coordinates of their last placement — or, for one attached since
|
|
114
|
+
* the last render frame, where the next frame will place it.
|
|
115
|
+
*/
|
|
116
|
+
snapshot() {
|
|
117
|
+
return this.instances.map((instance) => {
|
|
118
|
+
const { x, y, clipped } = instance.placed ?? (this.view ? locate(instance, this.view()) : UNPLACED);
|
|
119
|
+
return {
|
|
120
|
+
piece: instance.piece,
|
|
121
|
+
entity: instance.entity.name,
|
|
122
|
+
x,
|
|
123
|
+
y,
|
|
124
|
+
clipped,
|
|
125
|
+
values: Object.fromEntries(instance.values),
|
|
126
|
+
};
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
/** Removes every instance, lingering ones too (GameUi.unloadScene). */
|
|
130
|
+
clear() {
|
|
131
|
+
for (const instance of [...this.instances])
|
|
132
|
+
this.remove(instance);
|
|
133
|
+
}
|
|
134
|
+
/** Removes every instance and forgets the layer along with the overlay (GameUi.dispose). */
|
|
135
|
+
dispose() {
|
|
136
|
+
this.clear();
|
|
137
|
+
this.layer = undefined;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Called by the Game once per render frame, after the isometric pass and
|
|
141
|
+
* before the render (never per Simulation Step, never on attach): fits
|
|
142
|
+
* the layer to the game viewport, sets the frame's `--waica-unit` on it
|
|
143
|
+
* (every instance inherits it through its shadow host) and puts every
|
|
144
|
+
* instance's zero-size shadow host at its anchor point, its CSS
|
|
145
|
+
* animations set to Game Time (followGameTime).
|
|
146
|
+
*/
|
|
147
|
+
place() {
|
|
148
|
+
const layer = this.layer;
|
|
149
|
+
if (!layer || !this.view)
|
|
150
|
+
return;
|
|
151
|
+
const view = this.view();
|
|
152
|
+
const { camera, viewport } = view;
|
|
153
|
+
layer.style.left = `${viewport.x}px`;
|
|
154
|
+
layer.style.top = `${viewport.y}px`;
|
|
155
|
+
layer.style.width = `${viewport.width}px`;
|
|
156
|
+
layer.style.height = `${viewport.height}px`;
|
|
157
|
+
// The camera frames exactly viewHeight world units vertically (Game.resize).
|
|
158
|
+
layer.style.setProperty('--waica-unit', `${viewport.height / (camera.top - camera.bottom)}px`);
|
|
159
|
+
// Before any instance's style writes below: getAnimations() flushes style.
|
|
160
|
+
for (const instance of this.instances)
|
|
161
|
+
followGameTime(instance);
|
|
162
|
+
const byDepth = [];
|
|
163
|
+
for (const instance of this.instances) {
|
|
164
|
+
const placement = locate(instance, view);
|
|
165
|
+
instance.placed = placement;
|
|
166
|
+
instance.host.style.left = `${placement.x}px`;
|
|
167
|
+
instance.host.style.top = `${placement.y}px`;
|
|
168
|
+
byDepth.push([instance, placement.depth]);
|
|
169
|
+
}
|
|
170
|
+
// Lower on screen draws on top, like y-sort; the sort is stable, so
|
|
171
|
+
// equal heights keep creation order, later on top.
|
|
172
|
+
byDepth.sort(([, a], [, b]) => a - b);
|
|
173
|
+
for (const [index, [instance]] of byDepth.entries())
|
|
174
|
+
instance.host.style.zIndex = String(index + 1);
|
|
175
|
+
}
|
|
176
|
+
bind(instance) {
|
|
177
|
+
for (const [name, text] of placeholders(instance.root)) {
|
|
178
|
+
const texts = instance.texts.get(name);
|
|
179
|
+
if (texts)
|
|
180
|
+
texts.push(text);
|
|
181
|
+
else
|
|
182
|
+
instance.texts.set(name, [text]);
|
|
183
|
+
}
|
|
184
|
+
for (const name of instance.texts.keys()) {
|
|
185
|
+
this.render(instance, name);
|
|
186
|
+
instance.unsubs.push(this.deps.stats.onChange(name, () => {
|
|
187
|
+
if (!instance.values.has(name))
|
|
188
|
+
this.render(instance, name);
|
|
189
|
+
}));
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/** Writes a name's current value — the instance's own, else the Game stat — into its placeholders. */
|
|
193
|
+
render(instance, name) {
|
|
194
|
+
const value = instance.values.has(name) ? instance.values.get(name) : this.deps.stats.get(name);
|
|
195
|
+
for (const text of instance.texts.get(name) ?? [])
|
|
196
|
+
text.nodeValue = renderStat(value);
|
|
197
|
+
}
|
|
198
|
+
set(instance, name, value) {
|
|
199
|
+
if (!instance.alive)
|
|
200
|
+
return;
|
|
201
|
+
instance.values.set(name, value);
|
|
202
|
+
this.render(instance, name);
|
|
203
|
+
publish(instance.host, name, value);
|
|
204
|
+
}
|
|
205
|
+
remove(instance) {
|
|
206
|
+
if (!instance.alive)
|
|
207
|
+
return;
|
|
208
|
+
instance.alive = false;
|
|
209
|
+
instance.expiry?.cancel();
|
|
210
|
+
for (const off of instance.unsubs)
|
|
211
|
+
off();
|
|
212
|
+
instance.host.remove();
|
|
213
|
+
this.instances.splice(this.instances.indexOf(instance), 1);
|
|
214
|
+
}
|
|
215
|
+
handleFor(instance) {
|
|
216
|
+
const pieces = this;
|
|
217
|
+
return {
|
|
218
|
+
set(name, value) {
|
|
219
|
+
pieces.set(instance, name, value);
|
|
220
|
+
},
|
|
221
|
+
remove() {
|
|
222
|
+
pieces.remove(instance);
|
|
223
|
+
},
|
|
224
|
+
get alive() {
|
|
225
|
+
return instance.alive;
|
|
226
|
+
},
|
|
227
|
+
get element() {
|
|
228
|
+
return instance.alive ? instance.root : null;
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* The single layer every instance lives in, kept as the overlay's first
|
|
234
|
+
* child — even when a screen piece created the overlay first — so every
|
|
235
|
+
* screen-space piece draws above every anchored instance.
|
|
236
|
+
*/
|
|
237
|
+
mountLayer() {
|
|
238
|
+
if (this.layer)
|
|
239
|
+
return this.layer;
|
|
240
|
+
const layer = document.createElement('div');
|
|
241
|
+
// Until the first frame fits it to the game viewport, it covers the overlay.
|
|
242
|
+
// Its own stacking context (z-index:0) keeps every instance's z-index
|
|
243
|
+
// below the screen-piece shells that follow it.
|
|
244
|
+
layer.style.cssText =
|
|
245
|
+
'position:absolute;left:0;top:0;width:100%;height:100%;overflow:hidden;z-index:0;pointer-events:none';
|
|
246
|
+
this.deps.overlay().prepend(layer);
|
|
247
|
+
this.layer = layer;
|
|
248
|
+
return layer;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
/** The entity's render point plus the offset, in render space — or the point frozen at its destroy(). */
|
|
252
|
+
function anchorPoint(instance, projection) {
|
|
253
|
+
if (instance.frozen)
|
|
254
|
+
return instance.frozen;
|
|
255
|
+
const { x, y } = instance.entity.position;
|
|
256
|
+
const render = projection === 'isometric' ? projectIsometric(x, y) : { x, y };
|
|
257
|
+
return { x: render.x + instance.offset[0], y: render.y + instance.offset[1] };
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* The anchor point in whole CSS px from the game viewport's top-left
|
|
261
|
+
* corner: the exact inverse of the Pointer's screen→world mapping.
|
|
262
|
+
*/
|
|
263
|
+
function locate(instance, view) {
|
|
264
|
+
const anchor = anchorPoint(instance, view.projection);
|
|
265
|
+
const { camera, viewport } = view;
|
|
266
|
+
const nx = (anchor.x - (camera.position.x + camera.left)) / (camera.right - camera.left);
|
|
267
|
+
const ny = (camera.position.y + camera.top - anchor.y) / (camera.top - camera.bottom);
|
|
268
|
+
return {
|
|
269
|
+
x: whole(nx * viewport.width),
|
|
270
|
+
y: whole(ny * viewport.height),
|
|
271
|
+
clipped: nx < 0 || nx > 1 || ny < 0 || ny > 1,
|
|
272
|
+
depth: ny,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Drives the instance's CSS animations from Game Time instead of the
|
|
277
|
+
* document timeline: each is paused at the Game Time elapsed since it
|
|
278
|
+
* started, so a frame that runs no Simulation Step leaves it exactly where
|
|
279
|
+
* it was. One there at the first placement started with the instance (its
|
|
280
|
+
* attach); a later one (a transition a set() started) with the frame it
|
|
281
|
+
* first shows up in. Called before the frame updates `placed`. A DOM
|
|
282
|
+
* without the Web Animations API (happy-dom returns none) is left alone.
|
|
283
|
+
*/
|
|
284
|
+
function followGameTime(instance) {
|
|
285
|
+
const animations = instance.host.shadowRoot?.getAnimations?.() ?? [];
|
|
286
|
+
const now = instance.entity.game.time.now;
|
|
287
|
+
const firstSeen = instance.placed ? now : instance.born;
|
|
288
|
+
for (const animation of animations) {
|
|
289
|
+
const start = animationStart(instance, animation, firstSeen);
|
|
290
|
+
animation.pause();
|
|
291
|
+
animation.currentTime = (now - start) * 1000;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* The Game Time `animation` counts from, recorded as `firstSeen` the first
|
|
296
|
+
* time it is met. A named CSS animation is known by its target element and
|
|
297
|
+
* name, not by object: hiding the overlay (not simulating) cancels it, and
|
|
298
|
+
* the new one the browser makes when it shows again resumes mid-flight. A
|
|
299
|
+
* transition, or anything else without a name, is known by object.
|
|
300
|
+
*/
|
|
301
|
+
function animationStart(instance, animation, firstSeen) {
|
|
302
|
+
const name = 'animationName' in animation ? animation.animationName : undefined;
|
|
303
|
+
const effect = animation.effect;
|
|
304
|
+
const target = effect && 'target' in effect ? effect.target : null;
|
|
305
|
+
if (typeof name === 'string' && target instanceof Element) {
|
|
306
|
+
let byName = instance.named.get(target);
|
|
307
|
+
if (!byName)
|
|
308
|
+
instance.named.set(target, (byName = new Map()));
|
|
309
|
+
const start = byName.get(name) ?? firstSeen;
|
|
310
|
+
byName.set(name, start);
|
|
311
|
+
return start;
|
|
312
|
+
}
|
|
313
|
+
const start = instance.clocks.get(animation) ?? firstSeen;
|
|
314
|
+
instance.clocks.set(animation, start);
|
|
315
|
+
return start;
|
|
316
|
+
}
|
|
317
|
+
/** Rounds to a whole pixel, never -0. */
|
|
318
|
+
function whole(value) {
|
|
319
|
+
return Math.round(value) || 0;
|
|
320
|
+
}
|
|
321
|
+
/** Numbers verbatim and booleans as 1/0 become `--name`; a string publishes nothing. */
|
|
322
|
+
function publish(host, name, value) {
|
|
323
|
+
const property = `--${name}`;
|
|
324
|
+
if (typeof value === 'number')
|
|
325
|
+
host.style.setProperty(property, String(value));
|
|
326
|
+
else if (typeof value === 'boolean')
|
|
327
|
+
host.style.setProperty(property, value ? '1' : '0');
|
|
328
|
+
else
|
|
329
|
+
host.style.removeProperty(property);
|
|
330
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import * as THREE from 'three';
|
|
2
|
+
import { type TextureBackend } from './texture-backend.js';
|
|
3
|
+
/** `game.assets.status`: a fresh snapshot of the cache's counters, cumulative for the Game. */
|
|
4
|
+
export interface AssetStatus {
|
|
5
|
+
/** Requested URLs that have not settled yet. */
|
|
6
|
+
pending: number;
|
|
7
|
+
/** Settled URLs whose image arrived. */
|
|
8
|
+
loaded: number;
|
|
9
|
+
/** Settled URLs whose load failed — recorded, warned once, never retried. */
|
|
10
|
+
failed: number;
|
|
11
|
+
}
|
|
12
|
+
export type TextureOutcome = 'loaded' | 'failed';
|
|
13
|
+
/** What a consumer gets from `game.assets.texture(url)`: its own clone, and when the image settled. */
|
|
14
|
+
export interface TextureHandle {
|
|
15
|
+
texture: THREE.Texture;
|
|
16
|
+
settled: Promise<TextureOutcome>;
|
|
17
|
+
}
|
|
18
|
+
export interface AssetLoaderOptions {
|
|
19
|
+
/** Replaces the real `THREE.TextureLoader` implementation (ADR 0013); defaults to it. */
|
|
20
|
+
backend?: TextureBackend;
|
|
21
|
+
/**
|
|
22
|
+
* Resolves a uri for `preload()` the way the scene loader resolves every
|
|
23
|
+
* prefab's string prop (`resolveProps` in scene.ts). Looked up on every
|
|
24
|
+
* call: `Game` wires this to its registered scene catalog, which survives
|
|
25
|
+
* `unloadScene()`. Defaults to identity, so an already-resolved or
|
|
26
|
+
* unresolvable uri passes through unchanged either way.
|
|
27
|
+
*/
|
|
28
|
+
resolveAsset?: (uri: string) => string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The engine's texture cache (`game.assets`, ADR 0019): keep-all for the
|
|
32
|
+
* Game's whole life, keyed by the URL as received, one backend load and one
|
|
33
|
+
* base texture per URL. `ready()` is the **Assets Ready** signal — a
|
|
34
|
+
* promise beside the synchronous scene load — and a failed image is
|
|
35
|
+
* recorded, not thrown, so it never breaks a host or a Run Session that
|
|
36
|
+
* awaits it. `unloadScene()` never touches this cache; `dispose()` empties it.
|
|
37
|
+
*/
|
|
38
|
+
export declare class AssetLoader {
|
|
39
|
+
private readonly backend;
|
|
40
|
+
private readonly resolveAsset;
|
|
41
|
+
private readonly entries;
|
|
42
|
+
private pendingCount;
|
|
43
|
+
private loadedCount;
|
|
44
|
+
private failedCount;
|
|
45
|
+
constructor(options?: AssetLoaderOptions);
|
|
46
|
+
/** A fresh object on every read: `pending` is current, `loaded` and `failed` only grow until `dispose()`. */
|
|
47
|
+
get status(): AssetStatus;
|
|
48
|
+
/**
|
|
49
|
+
* The consumer entry (Sprite, AnimatedSprite, Tilemap): requests `url`
|
|
50
|
+
* — already resolved by `resolveProps` — and returns a clone of its base
|
|
51
|
+
* right away, so a mesh exists before the image arrives, plus the
|
|
52
|
+
* settlement of that URL, which also fires on a cache hit.
|
|
53
|
+
*/
|
|
54
|
+
texture(url: string): TextureHandle;
|
|
55
|
+
/**
|
|
56
|
+
* Requests every uri ahead of time, each resolved through the registered
|
|
57
|
+
* scene catalog. Resolves once all of them settled, failures included —
|
|
58
|
+
* a failure still only warns once, the same as a component's request.
|
|
59
|
+
*/
|
|
60
|
+
preload(uris: string[]): Promise<void>;
|
|
61
|
+
/**
|
|
62
|
+
* Assets Ready: resolves the first time `pending` is 0 after the call —
|
|
63
|
+
* at once when nothing is pending, otherwise once every URL requested
|
|
64
|
+
* before or while waiting has settled. Never rejects. Resolves after the
|
|
65
|
+
* `settled` continuations consumers chained before the call, so a host
|
|
66
|
+
* that does `await game.assets.ready()` then `game.start()` renders its
|
|
67
|
+
* first frame with the textures in place.
|
|
68
|
+
*/
|
|
69
|
+
ready(): Promise<void>;
|
|
70
|
+
/** Disposes every cached base exactly once and forgets everything; called by `Game.dispose()`. */
|
|
71
|
+
dispose(): void;
|
|
72
|
+
private request;
|
|
73
|
+
private load;
|
|
74
|
+
/** One backend load as an outcome, never a rejection — a backend that throws synchronously included. */
|
|
75
|
+
private attempt;
|
|
76
|
+
}
|