@threenative/core 0.3.4 → 0.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.
Files changed (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Jz4Fdoeb.d.ts} +114 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12437 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +57 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2408 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +574 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +850 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -0,0 +1,308 @@
1
+ import { yieldToHost } from "./warmup.js";
2
+
3
+ /**
4
+ * Two load-time mechanisms every streaming game writes by hand, and gets wrong in the same places.
5
+ *
6
+ * A game that shows a loading curtain and builds its world behind it has two loops that decide how
7
+ * long the curtain stays up, and neither is about how anything looks: the loop that **fetches** the
8
+ * models and the loop that **attaches** the finished objects to the scene. Written naively, the
9
+ * first is serial and the second is one-object-per-frame, and both are slow for reasons that have
10
+ * nothing to do with the game.
11
+ *
12
+ * Measured in a real game (a 190 m valley, ~70 GLBs, ~400 attached objects), on the same build and
13
+ * the same content:
14
+ *
15
+ * | Attach loop | Detail tier |
16
+ * | ------------ | ----------- |
17
+ * | 1 per frame | 16.5 s |
18
+ * | 6 per frame | 11.26 s |
19
+ * | 24 per frame | 9.39 s |
20
+ * | 256 per frame| **6.89 s** |
21
+ * | all at once | 7.18 s |
22
+ *
23
+ * and the fetch loop: 52 models one at a time took **38.4 s**; six at a time took **8.8 s**.
24
+ *
25
+ * Neither of these decides how anything looks. `addInSlices` never creates an object and never
26
+ * chooses where it goes — it is handed a list and the game's own `add`. `loadAll` never chooses
27
+ * what to load — it is handed a list and the game's own `load`. Geometry, material, colour,
28
+ * texture, curve and timing stay with the game in both, and a game can change its appearance
29
+ * completely without editing either.
30
+ *
31
+ * What they are not is code a game can get right portably by itself, which is why they live here.
32
+ * Yielding correctly is a platform seam: awaiting `requestAnimationFrame` deadlocks a host whose
33
+ * frames are pumped by the code doing the waiting, racing it against a timer reorders the frame
34
+ * sequence a harness observes, and a hard-coded `setTimeout(16)` is neither a frame on the native
35
+ * runtime nor a frame on a machine that cannot hold 60. See `yieldToHost` in `warmup.ts` for the
36
+ * two wrong versions that came before the one both of these use.
37
+ */
38
+
39
+ /** How far a sliced attachment has got, reported once per slice. */
40
+ export interface IAddInSlicesProgress {
41
+ /** Objects attached so far. Never greater than `total`. */
42
+ readonly added: number;
43
+ /** Objects the run was given. Known before the first slice. */
44
+ readonly total: number;
45
+ }
46
+
47
+ export interface IAddInSlicesOptions {
48
+ /**
49
+ * Objects attached between presented frames, when the game wants that count.
50
+ *
51
+ * Omitted, a slice ends on elapsed time instead: the loop measures what the game's own `add`
52
+ * costs, in the place where the cost is paid, and presents a frame once the slice has run for its
53
+ * budget. Objects that cost nothing stop paying a frame each, and objects that cost more than any
54
+ * fixed count allows get cut sooner than that count would. Given, the count decides and the budget
55
+ * is not used at all.
56
+ */
57
+ readonly sliceSize?: number;
58
+ /** Called once per slice, and once more for a partial final slice. */
59
+ readonly onProgress?: (progress: IAddInSlicesProgress) => void;
60
+ /**
61
+ * How the run hands the loop back to the host between slices. Defaults to yielding one
62
+ * macrotask, which is one native-runtime loop iteration and therefore one presented frame.
63
+ */
64
+ readonly yieldFrame?: () => Promise<void>;
65
+ /**
66
+ * Asked before every object; a false answer stops the run.
67
+ *
68
+ * This is how a scene that can be torn down mid-attach stays correct. A generation invalidated
69
+ * by a restart, a scene change, or an HMR reload must stop attaching into a graph that is no
70
+ * longer current, and it must do so **without throwing** — a throw here is indistinguishable
71
+ * from a real attachment failure at the catch site, and games end up reporting a teardown as an
72
+ * asset error. The stop is reported instead, as `stopped` on the report.
73
+ */
74
+ readonly while?: () => boolean;
75
+ /** Silences the `TN_ADD_SLICES` marker. Never silences the report. Default true (on). */
76
+ readonly marker?: boolean;
77
+ }
78
+
79
+ /** What a sliced attachment did, so a caller can report it rather than assume it. */
80
+ export interface IAddInSlicesReport {
81
+ /** Objects actually handed to `add`. */
82
+ readonly added: number;
83
+ /** Objects the run was given. */
84
+ readonly total: number;
85
+ /** Slices the work was cut into: one host turn between each, several of which can share a frame. */
86
+ readonly slices: number;
87
+ /** Wall-clock milliseconds the run took, attaching and yielding together. */
88
+ readonly elapsedMs: number;
89
+ /**
90
+ * Objects per slice this run actually landed on: the count the game chose, or — when
91
+ * the budget chose — the measured average, which is the number a caller copies into `sliceSize`.
92
+ */
93
+ readonly sliceSize: number;
94
+ /** Whether that count came from the game rather than from the engine. */
95
+ readonly sliceSizeOverridden: boolean;
96
+ /** Milliseconds of attaching one slice may spend before it presents. Absent when the game gave a count. */
97
+ readonly sliceBudgetMs?: number;
98
+ /** True when `while` ended the run early. `added` is then less than `total`. */
99
+ readonly stopped: boolean;
100
+ }
101
+
102
+ /** How far a bounded-concurrency load has got, reported once per settled item. */
103
+ export interface ILoadAllProgress {
104
+ /** Loads that have resolved. */
105
+ readonly settled: number;
106
+ /** Loads the run was given. Known before the first one starts. */
107
+ readonly total: number;
108
+ }
109
+
110
+ export interface ILoadAllOptions {
111
+ /**
112
+ * Loads in flight at once. Default 6.
113
+ *
114
+ * Bounded rather than unbounded, because a full-width fan-out coalesces its completion callbacks
115
+ * into 100-200 ms tasks and freezes the loading screen it is filling — which reads as the hang
116
+ * the concurrency was added to remove. Six is also the per-host connection limit a browser
117
+ * applies to HTTP/1.1, so a larger number frequently buys queueing rather than parallelism.
118
+ */
119
+ readonly concurrency?: number;
120
+ /** Called after each load settles. */
121
+ readonly onProgress?: (progress: ILoadAllProgress) => void;
122
+ /**
123
+ * How the run hands the loop back to the host after each settled load. Defaults to yielding one
124
+ * macrotask, which is what keeps a progress bar moving while the lanes are busy.
125
+ */
126
+ readonly yieldFrame?: () => Promise<void>;
127
+ /** Silences the `TN_LOAD_ALL` marker. Never silences `onProgress`. Default true (on). */
128
+ readonly marker?: boolean;
129
+ }
130
+
131
+ const DEFAULT_SLICE_BUDGET_MS = 8;
132
+ export const DEFAULT_CONCURRENCY = 6;
133
+
134
+ const now = (): number => globalThis.performance?.now() ?? Date.now();
135
+
136
+ function assertWholeAtLeastOne(value: number, name: string, code: string): void {
137
+ if (!Number.isInteger(value) || value < 1) {
138
+ throw new Error(
139
+ `${code}: ${name} must be a whole number of at least one, received ${String(value)}.`,
140
+ );
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Attach a built list of objects to the scene in slices, presenting a frame between each.
146
+ *
147
+ * The objects are already built and already the game's; this decides only *when* each one joins
148
+ * the graph. Order is the list's order, and there is no option to change it — an attach loop that
149
+ * reordered its input would change which object a positional lookup finds.
150
+ *
151
+ * @situation add hundreds of built objects to the scene without one multi-second frame
152
+ * @situation stream a detail tier in behind a loading curtain without the page looking hung
153
+ * @example
154
+ * const report = await addInSlices(detailObjects, (object) => ctx.add(object), {
155
+ * onProgress: ({ added, total }) => setProgress(added / total),
156
+ * while: () => generation.live,
157
+ * });
158
+ */
159
+ export async function addInSlices<T>(
160
+ objects: Iterable<T>,
161
+ add: (object: T, index: number) => void,
162
+ options: IAddInSlicesOptions = {},
163
+ ): Promise<IAddInSlicesReport> {
164
+ const sliceSize = options.sliceSize;
165
+ if (sliceSize !== undefined) {
166
+ assertWholeAtLeastOne(sliceSize, "sliceSize", "TN_ADD_SLICES_SLICE_INVALID");
167
+ }
168
+ const countSlices = sliceSize !== undefined;
169
+ const sliceBudgetMs = countSlices ? undefined : DEFAULT_SLICE_BUDGET_MS;
170
+ const yieldFrame = options.yieldFrame ?? yieldToHost;
171
+ const shouldContinue = options.while;
172
+ const startedAt = now();
173
+
174
+ // Materialised once: the caller may pass any iterable, and `total` has to be known before the
175
+ // first slice so a progress bar has a denominator rather than a moving one.
176
+ const list = [...objects];
177
+ const total = list.length;
178
+
179
+ let added = 0;
180
+ let reported = 0;
181
+ let slices = 0;
182
+ let stopped = false;
183
+ let sliceStartedAt = now();
184
+
185
+ const flush = async (yieldAfter: boolean): Promise<void> => {
186
+ slices += 1;
187
+ reported = added;
188
+ options.onProgress?.({ added, total });
189
+ if (yieldAfter) {
190
+ await yieldFrame();
191
+ // The presented frame is not part of the next slice's work.
192
+ if (sliceBudgetMs !== undefined) sliceStartedAt = now();
193
+ }
194
+ };
195
+
196
+ /** A slice ends on the count the game gave, or on the budget this run has spent. */
197
+ const sliceSpent = (): boolean =>
198
+ sliceSize !== undefined
199
+ ? added % sliceSize === 0
200
+ : now() - sliceStartedAt >= DEFAULT_SLICE_BUDGET_MS;
201
+
202
+ for (let index = 0; index < total; index += 1) {
203
+ if (shouldContinue !== undefined && !shouldContinue()) {
204
+ stopped = true;
205
+ break;
206
+ }
207
+ add(list[index] as T, index);
208
+ added += 1;
209
+ // Never after the final object: the caller is about to render anyway, and one more empty frame
210
+ // would only be added to the load. The clock is read per object, because `performance.now()` is
211
+ // cheap beside the game's own `add` and a fixed count cannot see what that `add` costs.
212
+ if (added < total && sliceSpent()) await flush(true);
213
+ }
214
+ if (added > reported) await flush(false);
215
+
216
+ const report: IAddInSlicesReport = {
217
+ added,
218
+ total,
219
+ slices,
220
+ elapsedMs: now() - startedAt,
221
+ // Measured rather than assumed: with no count to divide by, the average is what the run did.
222
+ sliceSize: sliceSize ?? Math.round(added / Math.max(slices, 1)),
223
+ sliceSizeOverridden: countSlices,
224
+ sliceBudgetMs,
225
+ stopped,
226
+ };
227
+ if (options.marker !== false) {
228
+ console.info(
229
+ `TN_ADD_SLICES added=${String(added)} total=${String(total)} slices=${String(slices)} ` +
230
+ `sliceSize=${String(report.sliceSize)} overridden=${String(countSlices)} ` +
231
+ `budgetMs=${String(sliceBudgetMs ?? "none")} ` +
232
+ `stopped=${String(stopped)} ms=${report.elapsedMs.toFixed(1)}`,
233
+ );
234
+ }
235
+ return report;
236
+ }
237
+
238
+ /**
239
+ * Load a list with bounded concurrency, and hand the results back **in the input's order**.
240
+ *
241
+ * The ordering is the whole point and has no override. `Promise.all` already keeps order but runs
242
+ * everything at once; a hand-rolled worker pool bounds the lanes but pushes results as they land,
243
+ * so the array comes back in completion order — whatever the network happened to return. A game
244
+ * that picks from that list positionally then places a different model in the same spot on every
245
+ * load, and its world is never the same twice. That defect shipped in a real game and is why this
246
+ * writes each result to its item's own index and never appends.
247
+ *
248
+ * Fails closed like `Promise.all`: the first rejection rejects the call, and no lane starts a load
249
+ * it had not already begun.
250
+ *
251
+ * @situation load many models or textures in parallel instead of one at a time
252
+ * @situation keep a loading screen moving while a list of assets downloads
253
+ * @example
254
+ * const species = await loadAll(names, (name) => ctx.assets.model(`flora/${name}.glb`), {
255
+ * onProgress: ({ settled, total }) => setProgress(settled / total),
256
+ * });
257
+ */
258
+ export async function loadAll<TIn, TOut>(
259
+ items: readonly TIn[],
260
+ load: (item: TIn, index: number) => Promise<TOut>,
261
+ options: ILoadAllOptions = {},
262
+ ): Promise<TOut[]> {
263
+ const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
264
+ assertWholeAtLeastOne(concurrency, "concurrency", "TN_LOAD_ALL_CONCURRENCY_INVALID");
265
+ const concurrencyOverridden = options.concurrency !== undefined;
266
+ const yieldFrame = options.yieldFrame ?? yieldToHost;
267
+ const startedAt = now();
268
+ const total = items.length;
269
+
270
+ const results = new Array<TOut>(total);
271
+ // Lanes pull from one shared cursor rather than taking a contiguous chunk each: a chunked split
272
+ // runs at the speed of the slowest item in each chunk, and asset lists routinely range from a
273
+ // 40 kB clover to a 4 MB pine.
274
+ let next = 0;
275
+ let settled = 0;
276
+ let failed = false;
277
+
278
+ const lane = async (): Promise<void> => {
279
+ for (;;) {
280
+ // A lane that keeps pulling after a sibling has failed spends bandwidth on a load whose
281
+ // result is already going to be thrown away.
282
+ if (failed) return;
283
+ const index = next;
284
+ next += 1;
285
+ if (index >= total) return;
286
+ try {
287
+ // The slot, never a push. See this function's doc comment.
288
+ results[index] = await load(items[index] as TIn, index);
289
+ } catch (error) {
290
+ failed = true;
291
+ throw error;
292
+ }
293
+ settled += 1;
294
+ options.onProgress?.({ settled, total });
295
+ await yieldFrame();
296
+ }
297
+ };
298
+
299
+ await Promise.all(Array.from({ length: Math.min(concurrency, total) }, () => lane()));
300
+
301
+ if (options.marker !== false) {
302
+ console.info(
303
+ `TN_LOAD_ALL items=${String(total)} concurrency=${String(concurrency)} ` +
304
+ `overridden=${String(concurrencyOverridden)} ms=${(now() - startedAt).toFixed(1)}`,
305
+ );
306
+ }
307
+ return results;
308
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * One rule for what `display.maxFps` means when a game does not say.
3
+ *
4
+ * A template that shipped `maxFps: 60` taught every agent to copy the line, and every 120 Hz
5
+ * desktop then ran its game at half the panel it was sitting on — a default that is a constant the
6
+ * author is told to revisit later is a bug, not an option. So the default follows the display,
7
+ * capped at 120 on desktop and web, and stays 60 on mobile where the ceiling is power and heat
8
+ * rather than pixels. An explicit number still wins and `0` still removes the ceiling.
9
+ *
10
+ * **A browser has no refresh-rate API**, so "follows the display" is a measurement: the median
11
+ * interval between presented frames over the frame budget's first window is the panel's period,
12
+ * because on the web one rAF callback is one vblank. A native host says its own rate through the
13
+ * present counter, which is the only series there that counts displays rather than loop
14
+ * iterations. Both arrive as `measuredRefreshHz`; until one does, the answer is 60 and says so.
15
+ */
16
+
17
+ import type { IPlatformInfo } from "./platform.js";
18
+
19
+ /** What a game gets before anything has been measured, and all a mobile gets. */
20
+ export const DEFAULT_TARGET_FPS = 60;
21
+ /** The desktop and web ceiling, whatever the panel runs at. */
22
+ export const MAX_TARGET_FPS = 120;
23
+
24
+ /**
25
+ * The rates a display actually ships at, nearest one wins. 144 and 165 exist in the list and are
26
+ * then capped, because a 144 Hz gaming monitor is exactly the case where a player expects the
27
+ * panel to be used.
28
+ */
29
+ const COMMON_REFRESH_RATES = [60, 75, 90, 120, 144, 165] as const;
30
+
31
+ /**
32
+ * Where a resolved target came from, so a harness can assert the *rule* and not just the number:
33
+ * `"config"` is the game naming it, `"display"` a measured panel rate, `"mobile-default"` the
34
+ * mobile power ceiling, and `"fallback"` the 60 held until a measurement exists. An unmeasured 60
35
+ * is not the display's rate and does not report as one.
36
+ */
37
+ export type TargetFpsSource = "config" | "display" | "fallback" | "mobile-default";
38
+
39
+ /** A resolved frame budget: the rate the loop holds, and what decided it. */
40
+ export interface ITargetFps {
41
+ readonly targetFps: number;
42
+ readonly source: TargetFpsSource;
43
+ }
44
+
45
+ /** Whatever holds `display.maxFps` — `IGameConfig`, `IThreeNativeConfig`, or a bare object. */
46
+ export interface ITargetFpsConfig {
47
+ readonly display?: { readonly maxFps?: number | undefined } | undefined;
48
+ }
49
+
50
+ /** Only the one field the rule reads, so a caller need not hold a whole `IPlatformInfo`. */
51
+ export type ITargetFpsPlatform = Pick<IPlatformInfo, "formFactor">;
52
+
53
+ /**
54
+ * The nearest common refresh rate, never above `MAX_TARGET_FPS`.
55
+ *
56
+ * A measured 59.94 Hz panel and a measured 60 Hz one are the same panel, and a value the engine
57
+ * invents rather than reads is a value no display can be asked to hold.
58
+ */
59
+ export function snapRefreshRate(refreshHz: number): number {
60
+ if (!Number.isFinite(refreshHz) || refreshHz <= 0) return DEFAULT_TARGET_FPS;
61
+ let nearest: number = COMMON_REFRESH_RATES[0];
62
+ for (const rate of COMMON_REFRESH_RATES)
63
+ if (Math.abs(rate - refreshHz) < Math.abs(nearest - refreshHz)) nearest = rate;
64
+ return Math.min(nearest, MAX_TARGET_FPS);
65
+ }
66
+
67
+ /**
68
+ * The single reader of `display.maxFps`, used by the loop, the resolution scaler, the scene-shape
69
+ * warning, the frame-budget marker and the templates.
70
+ *
71
+ * `measuredRefreshHz` is the display's own rate when the platform can say it, and is what turns
72
+ * `"fallback"` into `"display"`. A negative or non-finite configured rate throws rather than
73
+ * quietly falling back: a config the engine ignored is worse than a config it rejected.
74
+ */
75
+ export function resolveTargetFps(
76
+ config: ITargetFpsConfig | undefined,
77
+ platform: ITargetFpsPlatform | undefined,
78
+ measuredRefreshHz?: number,
79
+ ): ITargetFps {
80
+ const configured = config?.display?.maxFps;
81
+ if (configured !== undefined) {
82
+ if (!Number.isFinite(configured) || configured < 0)
83
+ throw new Error(
84
+ `display.maxFps must be a finite number of at least zero, received ${String(configured)}.`,
85
+ );
86
+ return { source: "config", targetFps: configured };
87
+ }
88
+ if (platform?.formFactor === "mobile")
89
+ return { source: "mobile-default", targetFps: DEFAULT_TARGET_FPS };
90
+ if (measuredRefreshHz === undefined) return { source: "fallback", targetFps: DEFAULT_TARGET_FPS };
91
+ return { source: "display", targetFps: snapRefreshRate(measuredRefreshHz) };
92
+ }
@@ -0,0 +1,17 @@
1
+ /// <reference lib="webworker" />
2
+
3
+ import {
4
+ type ITerrainJob,
5
+ type ITerrainJobResult,
6
+ runTerrainJob,
7
+ terrainJobTransfers,
8
+ } from "./terrain-jobs.js";
9
+
10
+ /** The worker half of the terrain jobs: one message in, one transferred result back. */
11
+ declare const self: DedicatedWorkerGlobalScope;
12
+
13
+ self.onmessage = (event: MessageEvent): void => {
14
+ const request = event.data as { id: number; job: ITerrainJob };
15
+ const result: ITerrainJobResult = runTerrainJob(request.job);
16
+ self.postMessage({ id: request.id, result }, terrainJobTransfers(result));
17
+ };