@threenative/three-native 0.3.6 → 0.3.8

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.
@@ -0,0 +1,237 @@
1
+ /**
2
+ * The bridge-read guard (PRD-748): on the web engine every read of a bridged property crosses JS to
3
+ * Wasm, so code that looks free in plain three.js (a light's intensity read in each uniform callback,
4
+ * a scene walk per frame) costs real time here. The back end keeps what it can (the property mirror
5
+ * and the hierarchy cache in `browser-backend.ts`); this meter names what is left.
6
+ *
7
+ * One frame in each window of `WINDOW_FRAMES` safe points, after `WARMUP_FRAMES`, is a census frame:
8
+ * every crossing counts by name, and a get of the same object's same property again in that frame is
9
+ * a redundant read, nothing changed it in between that the game could not have kept. The census frame
10
+ * also takes one stack for each name read redundantly, so the verdict names the caller.
11
+ *
12
+ * **The rule is derived, never a constant an author revisits.** It fires when the redundant reads,
13
+ * at this host's own measured cost per crossing, take more than `REDUNDANT_SHARE` of the frame: its
14
+ * median interval or the census frame's own length, the longer, so the guard holds on Xvfb, on a
15
+ * loaded host and across a frame that rebuilds a scene. The line
16
+ * is `TN_BRIDGE_WARNING`, which a playtest fails on (`packages/playtest` perf warnings).
17
+ *
18
+ * What *all* crossings cost is an observation, not a defect: a game that reads 995 distinct
19
+ * properties once each has nothing to batch, so no fix exists and a warning about it is noise every
20
+ * game pays. It rides the census a debug run or a playtest already asked for, and the debug report
21
+ * ranks it (`bridgeCrossingMs`); the always-on line stays on repeated reads.
22
+ */
23
+
24
+ import { debugRequested } from "./debug-telemetry.js";
25
+
26
+ export const BRIDGE_WARNING_MARKER = "TN_BRIDGE_WARNING";
27
+ /**
28
+ * Set above zero by the playtest bridge while it samples: its scene walk reads every mesh's material
29
+ * and bounds inside the census frame, and no player run makes those reads.
30
+ */
31
+ /**
32
+ * Set to `true` by a playtest that bounds engine counters (`engineCost`): every census then prints
33
+ * `TN_BRIDGE_CENSUS` with its top crossings and their callers, so an over-bound counter names who
34
+ * crossed. The counters themselves ride TN_FRAME_BUDGET.counters.engine.
35
+ */
36
+ export const ENGINE_COST_KNOB = "__THREENATIVE_ENGINE_COST__";
37
+ export const BRIDGE_CENSUS_MARKER = "TN_BRIDGE_CENSUS";
38
+
39
+ export const PLAYTEST_OBSERVING_GLOBAL = "__tnPlaytestObserving";
40
+
41
+ /** Safe points before the first census: loading and the first frames build, so their reads are not steady. */
42
+ export const WARMUP_FRAMES = 120;
43
+ /** One census frame in each window, so the census costs a frame in this many. */
44
+ export const WINDOW_FRAMES = 120;
45
+ /** The share of the frame that redundant reads may take; past it the waste is worth a named fix. */
46
+ export const REDUNDANT_SHARE = 1 / 50;
47
+
48
+ interface ICensus {
49
+ readonly byName: Map<string, number>;
50
+ /** `<object key> <name>` -> gets in this frame. */
51
+ readonly byRead: Map<string, number>;
52
+ readonly redundantByName: Map<string, number>;
53
+ readonly callers: Map<string, string>;
54
+ /** The census prints itself (ENGINE_COST_KNOB), so it names a caller for every crossing, not only re-reads. */
55
+ readonly printed: boolean;
56
+ }
57
+
58
+ export interface IBridgeMeterHost {
59
+ now(): number;
60
+ /** The cost of one crossing on this host, in microseconds; asked once, at the first census. */
61
+ crossingMicros(): number;
62
+ typeName(type: number): string;
63
+ /** The current stack, as `new Error().stack` gives it. */
64
+ stack(): string | undefined;
65
+ report(line: string): void;
66
+ }
67
+
68
+ export interface IBridgeMeter {
69
+ /** True while a census frame counts: the back end records each crossing only then. */
70
+ readonly counting: boolean;
71
+ record(kind: string, self: { readonly key: string; readonly type: number }, name: string): void;
72
+ /** The safe point, once per renderer frame. */
73
+ frame(): void;
74
+ }
75
+
76
+ /**
77
+ * The first frame of `stack` outside the back end and this meter (the files of its first two frames:
78
+ * the stack call, then `record`), and the two after it: `fn (file:line) < fn (file:line)`. A bundle
79
+ * that puts the game in the back end's file falls back to the fourth frame, the one above the accessor.
80
+ */
81
+ export function callerOf(stack: string | undefined): string {
82
+ const frames = (stack ?? "")
83
+ .split("\n")
84
+ .map((line) => line.trim())
85
+ .filter((line) => line.startsWith("at "))
86
+ .map((line) => line.slice(3));
87
+ const fileOf = (frame: string) => /\(?([^()\s]+?)(?::\d+){1,2}\)?$/u.exec(frame)?.[1] ?? frame;
88
+ const own = new Set(frames.slice(0, 2).map(fileOf));
89
+ let at = frames.findIndex(
90
+ (frame) =>
91
+ !own.has(fileOf(frame)) &&
92
+ !/(?:browser-backend|debug-telemetry|bridge-meter)\.[jt]s(?:[:?]|$)/u.test(fileOf(frame)),
93
+ );
94
+ if (at < 0) at = Math.min(3, frames.length - 1);
95
+ const short = (frame: string) =>
96
+ frame.replace(
97
+ /(?:[a-z]+:\/\/[^/]+)?\/(?:[^/()\s]*\/)*([^/()\s]+\/[^/()\s]+?)(?:\?[^:)\s]*)?(:\d+)(?::\d+)?/u,
98
+ "$1$2",
99
+ );
100
+ return (
101
+ frames
102
+ .slice(at, at + 3)
103
+ .map(short)
104
+ .join(" < ") || "unknown"
105
+ );
106
+ }
107
+
108
+ export function createBridgeMeter(host: IBridgeMeterHost): IBridgeMeter {
109
+ let frames = 0;
110
+ let last: number | undefined;
111
+ const intervals: number[] = [];
112
+ let census: ICensus | undefined;
113
+ let micros: number | undefined;
114
+ let window = 0;
115
+ const finish = (done: ICensus): void => {
116
+ window += 1;
117
+ const round = (value: number) => Math.round(value * 1000) / 1000;
118
+ // What one crossing costs on this host, asked once. A debug-off frame that repeated no read
119
+ // never pays for the calibration.
120
+ const costMicros = (): number => {
121
+ micros ??= host.crossingMicros();
122
+ if (!Number.isFinite(micros) || micros < 0)
123
+ throw new Error("TN_BRIDGE_WARNING: invalid crossing calibration.");
124
+ return micros;
125
+ };
126
+ const medianFrameMs = (): number => {
127
+ const sorted = [...intervals].sort((a, b) => a - b);
128
+ return sorted[Math.floor(sorted.length / 2)] as number;
129
+ };
130
+ let redundant = 0;
131
+ for (const count of done.redundantByName.values()) redundant += count;
132
+ if (done.printed) {
133
+ let crossed = 0;
134
+ for (const count of done.byName.values()) crossed += count;
135
+ const top = [...done.byName]
136
+ .sort((a, b) => b[1] - a[1])
137
+ .slice(0, 5)
138
+ .map(([name, perFrame]) => ({
139
+ name,
140
+ perFrame,
141
+ caller: done.callers.get(name) ?? "unknown",
142
+ }));
143
+ // The debug path's own observation: what every crossing of the frame cost, at this host's
144
+ // calibration. It is not a warning — a game with no repeated read has nothing to fix — so it
145
+ // rides the census a debug run or a playtest bound already asks for.
146
+ const frameMs = intervals.length === 0 ? undefined : medianFrameMs();
147
+ const crossingMs = crossed === 0 ? undefined : (crossed * costMicros()) / 1000;
148
+ host.report(
149
+ `${BRIDGE_CENSUS_MARKER}:${JSON.stringify({
150
+ window,
151
+ crossings: crossed,
152
+ ...(frameMs === undefined || crossingMs === undefined
153
+ ? {}
154
+ : {
155
+ crossingUs: round(costMicros()),
156
+ crossingMs: round(crossingMs),
157
+ share: round(crossingMs / frameMs),
158
+ }),
159
+ redundantReads: redundant,
160
+ top,
161
+ })}`,
162
+ );
163
+ }
164
+ if (redundant === 0 || intervals.length === 0) return;
165
+ // The census frame's own length is the last interval. A scene rebuild reads a lot once in a frame
166
+ // of seconds; a steady waster's frame is as long as its median, so the next census names it.
167
+ const frameMs = Math.max(medianFrameMs(), intervals[intervals.length - 1] as number);
168
+ const crossingUs = costMicros();
169
+ const redundantMs = (redundant * crossingUs) / 1000;
170
+ if (!(redundantMs > frameMs * REDUNDANT_SHARE)) return;
171
+ const top = [...done.redundantByName]
172
+ .sort((a, b) => b[1] - a[1])
173
+ .slice(0, 5)
174
+ .map(([name, count]) => ({
175
+ name,
176
+ perFrame: done.byName.get(name) ?? count,
177
+ redundant: count,
178
+ caller: done.callers.get(name) ?? "unknown",
179
+ }));
180
+ host.report(
181
+ `${BRIDGE_WARNING_MARKER}:${JSON.stringify({
182
+ window,
183
+ frameMs: round(frameMs),
184
+ crossingUs: round(crossingUs),
185
+ redundantReads: redundant,
186
+ redundantMs: round(redundantMs),
187
+ share: round(redundantMs / frameMs),
188
+ top,
189
+ fix: `${top[0]?.name ?? "a property"} is read again in one frame from ${top[0]?.caller ?? "unknown"}: read it once per frame into a local and pass that, or move the check out of the per-frame callback.`,
190
+ })}`,
191
+ );
192
+ };
193
+ return {
194
+ get counting() {
195
+ return census !== undefined;
196
+ },
197
+ record(kind, self, name) {
198
+ if (census === undefined) return;
199
+ if (((globalThis as Record<string, unknown>)[PLAYTEST_OBSERVING_GLOBAL] as number) > 0)
200
+ return;
201
+ const label = `${kind} ${host.typeName(self.type)}.${name}`;
202
+ census.byName.set(label, (census.byName.get(label) ?? 0) + 1);
203
+ if (census.printed && !census.callers.has(label))
204
+ census.callers.set(label, callerOf(host.stack()));
205
+ if (kind !== "get") return;
206
+ const read = `${self.key} ${name}`;
207
+ const seen = (census.byRead.get(read) ?? 0) + 1;
208
+ census.byRead.set(read, seen);
209
+ if (seen < 2) return;
210
+ census.redundantByName.set(label, (census.redundantByName.get(label) ?? 0) + 1);
211
+ if (!census.callers.has(label)) census.callers.set(label, callerOf(host.stack()));
212
+ },
213
+ frame() {
214
+ const now = host.now();
215
+ if (last !== undefined) {
216
+ intervals.push(now - last);
217
+ if (intervals.length > WINDOW_FRAMES) intervals.shift();
218
+ }
219
+ last = now;
220
+ frames += 1;
221
+ if (census !== undefined) {
222
+ const done = census;
223
+ census = undefined;
224
+ finish(done);
225
+ } else if (frames > WARMUP_FRAMES && frames % WINDOW_FRAMES === 0) {
226
+ census = {
227
+ byName: new Map(),
228
+ byRead: new Map(),
229
+ redundantByName: new Map(),
230
+ callers: new Map(),
231
+ printed:
232
+ debugRequested() || (globalThis as Record<string, unknown>)[ENGINE_COST_KNOB] === true,
233
+ };
234
+ }
235
+ },
236
+ };
237
+ }