@pretty-chitty/core 2.3.3 → 2.3.6
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/dist/components/FullScreenGalleryDisplay.d.ts.map +1 -1
- package/dist/components/FullScreenGalleryDisplay.js +1 -1
- package/dist/components/FullScreenGalleryDisplay.js.map +1 -1
- package/dist/components/Gallery/GalleryViewer.d.ts +6 -1
- package/dist/components/Gallery/GalleryViewer.d.ts.map +1 -1
- package/dist/components/Gallery/GalleryViewer.js +69 -14
- package/dist/components/Gallery/GalleryViewer.js.map +1 -1
- package/dist/game/Chit.d.ts.map +1 -1
- package/dist/game/Chit.js +12 -2
- package/dist/game/Chit.js.map +1 -1
- package/dist/game/Turn.d.ts +11 -0
- package/dist/game/Turn.d.ts.map +1 -1
- package/dist/game/Turn.js +13 -2
- package/dist/game/Turn.js.map +1 -1
- package/dist/utilities/CanvasStack/CanvasStack.d.ts +12 -0
- package/dist/utilities/CanvasStack/CanvasStack.d.ts.map +1 -1
- package/dist/utilities/CanvasStack/CanvasStack.js +87 -0
- package/dist/utilities/CanvasStack/CanvasStack.js.map +1 -1
- package/package.json +1 -1
- package/src/library/components/FullScreenGalleryDisplay.tsx +1 -0
- package/src/library/components/Gallery/GalleryViewer.tsx +73 -13
- package/src/library/game/Chit.test.ts +50 -0
- package/src/library/game/Chit.ts +16 -5
- package/src/library/game/GameButton.ts +2 -0
- package/src/library/game/Pick.ts +3 -2
- package/src/library/game/PlayerPromptStatusChit.ts +2 -0
- package/src/library/game/SparkChit.ts +2 -0
- package/src/library/game/Turn.ts +14 -2
- package/src/library/game/serialize.test.ts +39 -0
- package/src/library/game/typeName.test.ts +51 -0
- package/src/library/game/typeName.ts +40 -0
- package/src/library/index.ts +1 -0
- package/src/library/utilities/CanvasStack/CanvasStack.ts +122 -0
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import v8 from "node:v8";
|
|
2
|
+
import vm from "node:vm";
|
|
1
3
|
import { expect, test } from "vitest";
|
|
2
4
|
|
|
3
5
|
import { ChildOutlet, NonEditable } from "../utilities/Annotations";
|
|
@@ -155,3 +157,51 @@ test("dirty tracking: array mutation via proxy marks dirty", () => {
|
|
|
155
157
|
const serialized = c.serialize();
|
|
156
158
|
expect(JSON.parse(serialized).items).toEqual([1, 2, 3, 4]);
|
|
157
159
|
});
|
|
160
|
+
|
|
161
|
+
test("dirty tracking: an object two chits share marks the chit it was written through", () => {
|
|
162
|
+
const shared = { a: 1 };
|
|
163
|
+
class ChitWithShared extends Chit {
|
|
164
|
+
public data = shared;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const c1 = new ChitWithShared();
|
|
168
|
+
const c2 = new ChitWithShared();
|
|
169
|
+
c1.serialize();
|
|
170
|
+
c2.serialize();
|
|
171
|
+
expect(c1.data.a).toBe(1); // c1 wraps the shared object first
|
|
172
|
+
|
|
173
|
+
c2.data.a = 2;
|
|
174
|
+
expect(c2._dirty).toBe(true);
|
|
175
|
+
expect(c1._dirty).toBe(false);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
test("dirty tracking: a chit that read long-lived data can still be collected", async () => {
|
|
179
|
+
// Game data in module scope lives as long as the bundle. Reading it through a chit must not tie
|
|
180
|
+
// the chit (and through its parents, a whole disposed match) to that data.
|
|
181
|
+
const gc = exposeGc();
|
|
182
|
+
const staticData = { nested: { value: 1 } };
|
|
183
|
+
class ChitWithStatic extends Chit {
|
|
184
|
+
public data = staticData;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
let ref: WeakRef<Chit> | undefined;
|
|
188
|
+
(() => {
|
|
189
|
+
const c = new ChitWithStatic();
|
|
190
|
+
c.serialize();
|
|
191
|
+
expect(c.data.nested.value).toBe(1);
|
|
192
|
+
ref = new WeakRef(c);
|
|
193
|
+
})();
|
|
194
|
+
|
|
195
|
+
// WeakRef targets stay alive until the current job ends
|
|
196
|
+
for (let i = 0; i < 5; i++) {
|
|
197
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
198
|
+
gc();
|
|
199
|
+
}
|
|
200
|
+
expect(ref?.deref()).toBeUndefined();
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
/** V8's gc(), without needing --expose-gc on the command line. */
|
|
204
|
+
function exposeGc(): () => void {
|
|
205
|
+
v8.setFlagsFromString("--expose-gc");
|
|
206
|
+
return vm.runInNewContext("gc") as () => void;
|
|
207
|
+
}
|
package/src/library/game/Chit.ts
CHANGED
|
@@ -8,6 +8,7 @@ import { Vector2 } from "three";
|
|
|
8
8
|
import { OrderedOutlet } from "./OrderedOutlet";
|
|
9
9
|
import { SparkChit } from "./SparkChit";
|
|
10
10
|
import StaticChitTypeRegistry from "./StaticChitTypeRegistry";
|
|
11
|
+
import { typeNameOfInstance } from "./typeName";
|
|
11
12
|
import type { Game } from "./Game";
|
|
12
13
|
import { IUpdatingCanvas } from "../utilities/IUpdatingCanvas";
|
|
13
14
|
import { ImageSpec } from "../utilities/CanvasStack/CanvasOperations";
|
|
@@ -18,14 +19,24 @@ const EXTRA_SERIALIZATION_PROPS_ARRAY = ["id", "_parent", "_parentOutlet", "_par
|
|
|
18
19
|
const EXTRA_SERIALIZATION_PROPS_SET = new Set(EXTRA_SERIALIZATION_PROPS_ARRAY);
|
|
19
20
|
const DELETED_SERIALIZED = JSON.stringify({ ____deleted: true });
|
|
20
21
|
|
|
21
|
-
|
|
22
|
+
// Per chit: value -> the proxy that marks that chit dirty. A proxy is bound to one chit, so the cache
|
|
23
|
+
// must be too. Keyed by value alone, an object several chits share (often static game data, which
|
|
24
|
+
// lives as long as the bundle) got the first chit's proxy for good: writes through it marked the
|
|
25
|
+
// wrong chit dirty, and the entry, whose key never dies, kept that chit and its whole match alive
|
|
26
|
+
// after the match was disposed. Keyed by chit, a chit's proxies go when the chit does.
|
|
27
|
+
const dirtyProxyCache = new WeakMap<Chit, WeakMap<object, object>>();
|
|
22
28
|
|
|
23
29
|
function wrapWithDirtyProxy(value: any, chit: Chit): any {
|
|
24
30
|
if (value === null || value === undefined) return value;
|
|
25
31
|
if (typeof value !== "object") return value;
|
|
26
32
|
if (value instanceof Chit || value instanceof OrderedOutlet) return value;
|
|
27
33
|
|
|
28
|
-
|
|
34
|
+
let chitProxies = dirtyProxyCache.get(chit);
|
|
35
|
+
if (!chitProxies) {
|
|
36
|
+
chitProxies = new WeakMap();
|
|
37
|
+
dirtyProxyCache.set(chit, chitProxies);
|
|
38
|
+
}
|
|
39
|
+
const existing = chitProxies.get(value);
|
|
29
40
|
if (existing) return existing;
|
|
30
41
|
|
|
31
42
|
const proxy = new Proxy(value, {
|
|
@@ -53,7 +64,7 @@ function wrapWithDirtyProxy(value: any, chit: Chit): any {
|
|
|
53
64
|
},
|
|
54
65
|
});
|
|
55
66
|
|
|
56
|
-
|
|
67
|
+
chitProxies.set(value, proxy);
|
|
57
68
|
return proxy;
|
|
58
69
|
}
|
|
59
70
|
|
|
@@ -173,7 +184,7 @@ export class Chit extends ObjectWithProps {
|
|
|
173
184
|
|
|
174
185
|
/** @internal */
|
|
175
186
|
chitTypeName() {
|
|
176
|
-
const result =
|
|
187
|
+
const result = typeNameOfInstance(this);
|
|
177
188
|
if (this.parentFallback) {
|
|
178
189
|
return `${result}-${this.parentFallback.id}-`;
|
|
179
190
|
}
|
|
@@ -624,7 +635,7 @@ export class Chit extends ObjectWithProps {
|
|
|
624
635
|
return acc;
|
|
625
636
|
},
|
|
626
637
|
{
|
|
627
|
-
__chitType:
|
|
638
|
+
__chitType: typeNameOfInstance(this),
|
|
628
639
|
__hiddenProps: playerIds ? this.hiddenPropertiesForSerialization(playerIds) : undefined,
|
|
629
640
|
} as { [key: string]: any },
|
|
630
641
|
),
|
|
@@ -7,6 +7,7 @@ import { GalleryItemSource } from "../components/GalleryViewer";
|
|
|
7
7
|
import { GalleryItemChitChildrenSource } from "./GalleryItemChitChildrenSource";
|
|
8
8
|
import { GalleryItemRawSource } from "./GalleryItemRawSource";
|
|
9
9
|
import { chitsToGalleryItems } from "../utilities/GalleryItemConversion";
|
|
10
|
+
import { setTypeName } from "./typeName";
|
|
10
11
|
|
|
11
12
|
export type ButtonCallback = () => void | Promise<void>;
|
|
12
13
|
|
|
@@ -140,3 +141,4 @@ export class Confirm extends GameButton {
|
|
|
140
141
|
/** @internal */
|
|
141
142
|
canAutoResolve = false;
|
|
142
143
|
}
|
|
144
|
+
setTypeName(Confirm, "Confirm");
|
package/src/library/game/Pick.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { GalleryItemChitChildrenSource } from "./GalleryItemChitChildrenSource";
|
|
|
3
3
|
import { IButtonLibrary } from "./Game";
|
|
4
4
|
import { Confirm, GameButton, ToggleGalleryButton } from "./GameButton";
|
|
5
5
|
import { OrderedOutlet } from "./OrderedOutlet";
|
|
6
|
+
import { typeNameOfInstance } from "./typeName";
|
|
6
7
|
import { PickPrompt } from "./Prompt";
|
|
7
8
|
import { MismatchError, Turn } from "./Turn";
|
|
8
9
|
|
|
@@ -187,7 +188,7 @@ export class ChitPick<T extends Chit> extends Pick {
|
|
|
187
188
|
|
|
188
189
|
if (this.button) {
|
|
189
190
|
result.b = this.button.serialize();
|
|
190
|
-
result.b.__buttonType =
|
|
191
|
+
result.b.__buttonType = typeNameOfInstance(this.button);
|
|
191
192
|
}
|
|
192
193
|
|
|
193
194
|
return result;
|
|
@@ -436,7 +437,7 @@ export class ButtonPick extends Pick {
|
|
|
436
437
|
}
|
|
437
438
|
|
|
438
439
|
const details = this.button.serialize();
|
|
439
|
-
details.__buttonType =
|
|
440
|
+
details.__buttonType = typeNameOfInstance(this.button);
|
|
440
441
|
details.__f = this.focusChits.map((chit) => chit.id);
|
|
441
442
|
return details;
|
|
442
443
|
}
|
|
@@ -3,6 +3,7 @@ import { EventChannel } from "../utilities/EventChannel";
|
|
|
3
3
|
import { Chit } from "./Chit";
|
|
4
4
|
import { Prompt } from "./Prompt";
|
|
5
5
|
import StaticChitTypeRegistry from "./StaticChitTypeRegistry";
|
|
6
|
+
import { setTypeName } from "./typeName";
|
|
6
7
|
|
|
7
8
|
export class PlayerPromptStatusChit extends Chit {
|
|
8
9
|
/** Plain text of the prompt the player is currently being asked to answer (`:token:` markup resolved). @internal */
|
|
@@ -21,4 +22,5 @@ export class PlayerPromptStatusChit extends Chit {
|
|
|
21
22
|
}
|
|
22
23
|
}
|
|
23
24
|
|
|
25
|
+
setTypeName(PlayerPromptStatusChit, "PlayerPromptStatusChit");
|
|
24
26
|
StaticChitTypeRegistry["PlayerPromptStatusChit"] = PlayerPromptStatusChit;
|
|
@@ -4,6 +4,7 @@ import { Vector2 } from "three";
|
|
|
4
4
|
import { NonEditable } from "../utilities/Annotations";
|
|
5
5
|
import { PlayerChit } from "./PlayerChit";
|
|
6
6
|
import StaticChitTypeRegistry from "./StaticChitTypeRegistry";
|
|
7
|
+
import { setTypeName } from "./typeName";
|
|
7
8
|
import { IUpdatingCanvas } from "../utilities/IUpdatingCanvas";
|
|
8
9
|
|
|
9
10
|
export class SparkChit extends Chit {
|
|
@@ -82,6 +83,7 @@ export class SparkChit extends Chit {
|
|
|
82
83
|
}
|
|
83
84
|
}
|
|
84
85
|
|
|
86
|
+
setTypeName(SparkChit, "SparkChit");
|
|
85
87
|
StaticChitTypeRegistry["SparkChit"] = SparkChit;
|
|
86
88
|
|
|
87
89
|
export abstract class BagSparkChit<T extends Chit> extends SparkChit {
|
package/src/library/game/Turn.ts
CHANGED
|
@@ -233,8 +233,20 @@ export class Turn<T, P extends PlayerChit, R extends RootChit<P>> {
|
|
|
233
233
|
return p.id;
|
|
234
234
|
});
|
|
235
235
|
|
|
236
|
-
|
|
237
|
-
|
|
236
|
+
this.captureLockedStates();
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Serializes every locked chit in its "locked" state. createTurn flushes the parent right before
|
|
241
|
+
* building us, so a clean chit's state there is already current and interned.
|
|
242
|
+
*
|
|
243
|
+
* This must stay out of the constructor. A local captured by a callback there lives in the
|
|
244
|
+
* constructor's closure context, which every closure made in the constructor shares, including
|
|
245
|
+
* the `findChit` field. `findChit` outlives the turn's absorption, so the parent's full chit-state
|
|
246
|
+
* map (a fresh copy per absorbed sub-turn) would stay pinned by every finished turn: tens of MB
|
|
247
|
+
* in a long game, out of reach of releasePostAbsorptionRefs.
|
|
248
|
+
*/
|
|
249
|
+
private captureLockedStates() {
|
|
238
250
|
const parentStates = this.parent?.lastChitStates;
|
|
239
251
|
Object.values(this.chitLookup).forEach((c) => {
|
|
240
252
|
if (!c.id) {
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import v8 from "node:v8";
|
|
2
|
+
import vm from "node:vm";
|
|
1
3
|
import { describe, expect, test } from "vitest";
|
|
2
4
|
|
|
3
5
|
import { Chit } from "./Chit";
|
|
@@ -100,6 +102,7 @@ type AnyTurn = {
|
|
|
100
102
|
clockSteps: { turns?: AnyTurn[]; absorbed?: AnyTurn[] }[];
|
|
101
103
|
_checkpoints: { nextIndex: number }[];
|
|
102
104
|
lockedChitStates: Record<string, string>;
|
|
105
|
+
lastChitStates: Record<string, string>;
|
|
103
106
|
absorbed: boolean;
|
|
104
107
|
serialize: (playerId: string, clock: number) => { chits: Record<string, string> };
|
|
105
108
|
chitsHistory: (playerId: string, ids: string[]) => unknown;
|
|
@@ -272,4 +275,40 @@ describe("Turn.serialize", () => {
|
|
|
272
275
|
expect(finished.filter((t) => t._checkpoints.length > 0)).toEqual([]);
|
|
273
276
|
expect(Object.keys(root.lockedChitStates).length).toBeGreaterThan(0);
|
|
274
277
|
});
|
|
278
|
+
|
|
279
|
+
test("finished turns do not keep old chit-state maps alive", async () => {
|
|
280
|
+
// A turn absorbing a sub-turn replaces its lastChitStates with a fresh full copy, so a long game
|
|
281
|
+
// makes hundreds of them. Once replaced, nothing should hold one: in particular not a closure
|
|
282
|
+
// made in the Turn constructor (findChit), which every finished turn keeps for the whole game.
|
|
283
|
+
const gc = exposeGc();
|
|
284
|
+
const seen = new WeakSet<object>();
|
|
285
|
+
const maps: WeakRef<object>[] = [];
|
|
286
|
+
const root = await play((root) => {
|
|
287
|
+
for (const t of allTurns(root)) {
|
|
288
|
+
if (!seen.has(t.lastChitStates)) {
|
|
289
|
+
seen.add(t.lastChitStates);
|
|
290
|
+
maps.push(new WeakRef(t.lastChitStates));
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
});
|
|
294
|
+
expect(maps.length).toBeGreaterThan(10);
|
|
295
|
+
|
|
296
|
+
// WeakRef targets stay alive until the current job ends, and the finished match may still have
|
|
297
|
+
// a notify or two queued: let those run, then collect, a few times over
|
|
298
|
+
for (let i = 0; i < 5; i++) {
|
|
299
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
300
|
+
gc();
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// The root (and through it every finished turn) is still alive, as in a running match
|
|
304
|
+
const current = new Set<object>(allTurns(root).map((t) => t.lastChitStates));
|
|
305
|
+
const leaked = maps.map((r) => r.deref()).filter((m) => m !== undefined && !current.has(m));
|
|
306
|
+
expect(`${leaked.length} of ${maps.length} replaced maps still alive`).toBe(`0 of ${maps.length} replaced maps still alive`);
|
|
307
|
+
});
|
|
275
308
|
});
|
|
309
|
+
|
|
310
|
+
/** V8's gc(), without needing --expose-gc on the command line. */
|
|
311
|
+
function exposeGc(): () => void {
|
|
312
|
+
v8.setFlagsFromString("--expose-gc");
|
|
313
|
+
return vm.runInNewContext("gc") as () => void;
|
|
314
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { describe, expect, test } from "vitest";
|
|
2
|
+
|
|
3
|
+
import { Chit } from "./Chit";
|
|
4
|
+
import { Game } from "./Game";
|
|
5
|
+
import { Confirm } from "./GameButton";
|
|
6
|
+
import { SparkChit } from "./SparkChit";
|
|
7
|
+
import { setTypeName, typeNameOf, typeNameOfInstance } from "./typeName";
|
|
8
|
+
|
|
9
|
+
/** Simulate a bundler renaming a class (`Card` → `Card2`). */
|
|
10
|
+
function renamed<T extends abstract new () => unknown>(ctor: T, name: string): T {
|
|
11
|
+
Object.defineProperty(ctor, "name", { value: name, configurable: true });
|
|
12
|
+
return ctor;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
describe("typeName", () => {
|
|
16
|
+
test("falls back to constructor.name", () => {
|
|
17
|
+
class Plain extends Chit {}
|
|
18
|
+
expect(typeNameOf(Plain)).toBe("Plain");
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test("pinned name wins over a renamed constructor", () => {
|
|
22
|
+
const Card = renamed(class Card extends Chit {}, "Card2");
|
|
23
|
+
setTypeName(Card, "Card");
|
|
24
|
+
expect(typeNameOf(Card)).toBe("Card");
|
|
25
|
+
expect(typeNameOfInstance(new Card())).toBe("Card");
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test("subclasses do not inherit a parent's pinned name", () => {
|
|
29
|
+
class Card extends Chit {}
|
|
30
|
+
setTypeName(Card, "Card");
|
|
31
|
+
class SpecialCard extends Card {}
|
|
32
|
+
expect(typeNameOf(SpecialCard)).toBe("SpecialCard");
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test("engine built-ins are pinned", () => {
|
|
36
|
+
expect(typeNameOf(SparkChit)).toBe("SparkChit");
|
|
37
|
+
expect(typeNameOf(Confirm)).toBe("Confirm");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("serialize/deflate round-trips through a renamed class", () => {
|
|
41
|
+
const Card = renamed(class Card extends Chit {}, "Card2");
|
|
42
|
+
setTypeName(Card, "Card");
|
|
43
|
+
const game = { chitLibrary: { Card } } as unknown as Game<any, any>;
|
|
44
|
+
|
|
45
|
+
const card = new Card();
|
|
46
|
+
card.id = "c1";
|
|
47
|
+
const serialized = card.serialize();
|
|
48
|
+
expect(JSON.parse(serialized).__chitType).toBe("Card");
|
|
49
|
+
expect(Chit.deflate(serialized, game)).toBeInstanceOf(Card);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Static property holding a class's serialized type name (`__chitType` / `__buttonType`).
|
|
3
|
+
*
|
|
4
|
+
* Bundlers may rename classes (minification, or `Card` → `Card2` to avoid collisions), so
|
|
5
|
+
* `constructor.name` is not stable across builds. Setting this on a class pins the name that
|
|
6
|
+
* gets written to saved state, and it must match that class's key in `chitLibrary` / `buttonLibrary`.
|
|
7
|
+
*/
|
|
8
|
+
export const TYPE_NAME_KEY = "__typeName";
|
|
9
|
+
|
|
10
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
11
|
+
type AnyClass = abstract new (...args: any[]) => unknown;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Pin the serialized type name for a chit or button class.
|
|
15
|
+
*
|
|
16
|
+
* ```ts
|
|
17
|
+
* setTypeName(Card, "Card");
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
export function setTypeName(ctor: AnyClass, name: string) {
|
|
21
|
+
Object.defineProperty(ctor, TYPE_NAME_KEY, { value: name, writable: true, configurable: true, enumerable: false });
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The serialized type name for a class: its own pinned `__typeName`, else `constructor.name`.
|
|
26
|
+
*
|
|
27
|
+
* Only an *own* property counts. Statics are inherited, so a subclass that wasn't stamped
|
|
28
|
+
* must not report its parent's name.
|
|
29
|
+
*/
|
|
30
|
+
export function typeNameOf(ctor: AnyClass): string {
|
|
31
|
+
if (Object.prototype.hasOwnProperty.call(ctor, TYPE_NAME_KEY)) {
|
|
32
|
+
return (ctor as any)[TYPE_NAME_KEY];
|
|
33
|
+
}
|
|
34
|
+
return ctor.name;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** `typeNameOf` for an instance. */
|
|
38
|
+
export function typeNameOfInstance(instance: object): string {
|
|
39
|
+
return typeNameOf(Object.getPrototypeOf(instance).constructor);
|
|
40
|
+
}
|
package/src/library/index.ts
CHANGED
|
@@ -6,6 +6,7 @@ export type { GameMetaData } from "./game/GameMetaData";
|
|
|
6
6
|
// NOTE: must be before Turn! or circular dependency!
|
|
7
7
|
/** @group Chits */
|
|
8
8
|
export { Chit } from "./game/Chit";
|
|
9
|
+
export { setTypeName, typeNameOf } from "./game/typeName";
|
|
9
10
|
|
|
10
11
|
/** @group Core Game Elements */
|
|
11
12
|
export { Turn } from "./game/Turn";
|
|
@@ -84,6 +84,7 @@ export class CanvasStack implements IUpdatingCanvas {
|
|
|
84
84
|
}
|
|
85
85
|
|
|
86
86
|
this._outlets = {};
|
|
87
|
+
this._fontsUsed.clear();
|
|
87
88
|
this.context.clearRect(0, 0, this.width, this.height);
|
|
88
89
|
this.operation.render(
|
|
89
90
|
this.context,
|
|
@@ -93,6 +94,7 @@ export class CanvasStack implements IUpdatingCanvas {
|
|
|
93
94
|
this._outlets[id] = coords;
|
|
94
95
|
},
|
|
95
96
|
);
|
|
97
|
+
this._noteUnloadedFonts();
|
|
96
98
|
this._renderMipCanvases();
|
|
97
99
|
this.cbs.forEach((cb) => cb());
|
|
98
100
|
}
|
|
@@ -132,6 +134,7 @@ export class CanvasStack implements IUpdatingCanvas {
|
|
|
132
134
|
throw "Invalid Context";
|
|
133
135
|
}
|
|
134
136
|
this.context = context;
|
|
137
|
+
this._trackFonts(context);
|
|
135
138
|
|
|
136
139
|
CanvasStack._liveStacks.add(this);
|
|
137
140
|
CanvasStack.ensureContextRestoreSubscription();
|
|
@@ -145,6 +148,118 @@ export class CanvasStack implements IUpdatingCanvas {
|
|
|
145
148
|
return this.operation.benefitsFromMipMap() ? 2 : 0;
|
|
146
149
|
}
|
|
147
150
|
|
|
151
|
+
// Webfonts load lazily, so a face drawn before its font arrives is rasterised in the fallback font, and nothing
|
|
152
|
+
// redrew it. Its custom mips, built a second or more later, came out in the real font, and trilinear filtering
|
|
153
|
+
// blended the two layouts into doubled, ghosted text. So each stack records the fonts it measured or drew with;
|
|
154
|
+
// any not loaded yet get loaded, and when one arrives every stack that used it redraws (base and custom mips) and
|
|
155
|
+
// re-uploads its texture, a few per frame.
|
|
156
|
+
private _fontsUsed = new Set<string>();
|
|
157
|
+
private _unloadedFonts = new Set<string>();
|
|
158
|
+
private static _fontLoads = new Set<string>();
|
|
159
|
+
private static _pendingFontRedraws = new Set<CanvasStack>();
|
|
160
|
+
private static _fontRedrawScheduled = false;
|
|
161
|
+
|
|
162
|
+
// Records the font as it was *set*, not as ctx.font reads back: WebKit's getter drops the weight ("700 27px X"
|
|
163
|
+
// reads "27px X"), so tracking the read-back only ever checked the regular face. Once that had loaded, bold text
|
|
164
|
+
// drawn in the fallback while its own face was still downloading looked loaded and never redrew (the ghosted
|
|
165
|
+
// titles and re-wrapped bodies on iPhone). save/restore carry the set value the way the context carries its font.
|
|
166
|
+
private _trackFonts(ctx: CanvasRenderingContext2D) {
|
|
167
|
+
const fontProp = Object.getOwnPropertyDescriptor(CanvasRenderingContext2D.prototype, "font");
|
|
168
|
+
let current = ctx.font;
|
|
169
|
+
if (fontProp?.get && fontProp.set) {
|
|
170
|
+
const { get, set } = fontProp;
|
|
171
|
+
const saved: string[] = [];
|
|
172
|
+
Object.defineProperty(ctx, "font", {
|
|
173
|
+
configurable: true,
|
|
174
|
+
get: () => get.call(ctx),
|
|
175
|
+
set: (value: string) => {
|
|
176
|
+
set.call(ctx, value);
|
|
177
|
+
current = value;
|
|
178
|
+
},
|
|
179
|
+
});
|
|
180
|
+
const save = ctx.save;
|
|
181
|
+
const restore = ctx.restore;
|
|
182
|
+
ctx.save = () => {
|
|
183
|
+
saved.push(current);
|
|
184
|
+
save.call(ctx);
|
|
185
|
+
};
|
|
186
|
+
ctx.restore = () => {
|
|
187
|
+
if (saved.length > 0) current = saved.pop()!;
|
|
188
|
+
restore.call(ctx);
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
for (const name of ["fillText", "strokeText", "measureText"] as const) {
|
|
192
|
+
const original = ctx[name] as (...args: unknown[]) => unknown;
|
|
193
|
+
(ctx as any)[name] = (...args: unknown[]) => {
|
|
194
|
+
this._fontsUsed.add(current);
|
|
195
|
+
return original.apply(ctx, args);
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** check() throws on a string that isn't a valid font (the context ignored that assignment); treat it as loaded. */
|
|
201
|
+
private static fontLoaded(font: string): boolean {
|
|
202
|
+
try {
|
|
203
|
+
return document.fonts.check(font);
|
|
204
|
+
} catch {
|
|
205
|
+
return true;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private _noteUnloadedFonts() {
|
|
210
|
+
this._unloadedFonts.clear();
|
|
211
|
+
const fonts = typeof document !== "undefined" ? document.fonts : undefined;
|
|
212
|
+
if (!fonts) return;
|
|
213
|
+
for (const font of this._fontsUsed) {
|
|
214
|
+
if (CanvasStack.fontLoaded(font)) continue;
|
|
215
|
+
this._unloadedFonts.add(font);
|
|
216
|
+
CanvasStack.whenFontLoads(font);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** A font this stack drew with before it loaded has loaded since: its pixels are stale. */
|
|
221
|
+
private _fontsArrived(): boolean {
|
|
222
|
+
for (const font of this._unloadedFonts) if (CanvasStack.fontLoaded(font)) return true;
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
private static whenFontLoads(font: string) {
|
|
227
|
+
if (CanvasStack._fontLoads.has(font)) return; // once per font: a font that never loads doesn't loop
|
|
228
|
+
CanvasStack._fontLoads.add(font);
|
|
229
|
+
document.fonts.load(font).then(
|
|
230
|
+
() => {
|
|
231
|
+
for (const stack of CanvasStack._liveStacks) {
|
|
232
|
+
if (stack._unloadedFonts.has(font)) CanvasStack._pendingFontRedraws.add(stack);
|
|
233
|
+
}
|
|
234
|
+
if (CanvasStack._pendingFontRedraws.size > 0 && !CanvasStack._fontRedrawScheduled) {
|
|
235
|
+
CanvasStack._fontRedrawScheduled = true;
|
|
236
|
+
requestAnimationFrame(CanvasStack.redrawPendingFonts);
|
|
237
|
+
}
|
|
238
|
+
},
|
|
239
|
+
() => {},
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
private static redrawPendingFonts = () => {
|
|
244
|
+
const start = performance.now();
|
|
245
|
+
for (const stack of CanvasStack._pendingFontRedraws) {
|
|
246
|
+
CanvasStack._pendingFontRedraws.delete(stack);
|
|
247
|
+
stack._redrawForFonts();
|
|
248
|
+
if (performance.now() - start > CanvasStack.MIP_FRAME_BUDGET_MS) break;
|
|
249
|
+
}
|
|
250
|
+
if (CanvasStack._pendingFontRedraws.size > 0) requestAnimationFrame(CanvasStack.redrawPendingFonts);
|
|
251
|
+
else CanvasStack._fontRedrawScheduled = false;
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
private _redrawForFonts() {
|
|
255
|
+
if (!this.context) return;
|
|
256
|
+
this.render(); // redraws the custom mips too, when they're built
|
|
257
|
+
if (this._texture) {
|
|
258
|
+
this._texture.needsUpdate = true;
|
|
259
|
+
CanvasStack.disposer.notifyChange(this._texture.uuid);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
148
263
|
// Faces with text get hand-drawn mip levels: text rasterised at the small size is sharper than GPU box-filtering.
|
|
149
264
|
// Building that chain (a canvas per level, down to 1×1) for every face while the table loads is what stalled
|
|
150
265
|
// phones — Safari queues 2D drawing in its GPU process and the first texture upload waits for all of it (8 s on an
|
|
@@ -182,6 +297,9 @@ export class CanvasStack implements IUpdatingCanvas {
|
|
|
182
297
|
|
|
183
298
|
private _buildMips() {
|
|
184
299
|
this._initMipCanvases();
|
|
300
|
+
// the base was drawn in a fallback font that has loaded since: redraw it (and these mips) in the real one,
|
|
301
|
+
// or the chain would hold two different layouts
|
|
302
|
+
if (this._fontsArrived()) this.render();
|
|
185
303
|
if (this._texture) {
|
|
186
304
|
this._applyMipmaps(this._texture);
|
|
187
305
|
this._texture.needsUpdate = true;
|
|
@@ -290,6 +408,10 @@ export class CanvasStack implements IUpdatingCanvas {
|
|
|
290
408
|
}
|
|
291
409
|
|
|
292
410
|
if (!this._texture) {
|
|
411
|
+
// Rebuilt after the disposer reclaimed it: the disposer also dropped the stack from the live set, so a font
|
|
412
|
+
// that arrived meanwhile never redrew it. Redraw now, and rejoin the live set for later fonts and context loss.
|
|
413
|
+
if (this._fontsArrived()) this.render();
|
|
414
|
+
CanvasStack._liveStacks.add(this);
|
|
293
415
|
const wrapper = getWebGlRendererInstance();
|
|
294
416
|
this._texture = new Texture(
|
|
295
417
|
this.canvas,
|