@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,380 @@
1
+ import { HIT_REGIONS_MESSAGE, type IUiBridge } from "./ui-bridge.js";
2
+
3
+ /**
4
+ * The interactive-rect registry — how a touch decides whether it belongs to the UI or the game.
5
+ *
6
+ * A web view is a native view with a **rectangular** hit-test region owned by the platform.
7
+ * CSS hit-testing happens inside that surface, after the native view has already claimed the
8
+ * gesture, so `pointer-events: none` does not hand a touch back to the game beneath. It is a
9
+ * useful property inside the page and it is not the pass-through mechanism.
10
+ *
11
+ * The mechanism is this: the page marks its interactive islands with `data-tn-interactive`,
12
+ * this registry publishes where they are, and the native input host does the hit test before
13
+ * either surface sees the gesture.
14
+ *
15
+ * ```tsx
16
+ * <button data-tn-interactive onClick={restart}>Restart</button>
17
+ * ```
18
+ *
19
+ * Three properties make it correct, and each one is a defect this file exists to prevent:
20
+ *
21
+ * - **Published, never queried.** The host owns a snapshot. Asking the page per touch means an
22
+ * async round trip inside the input path: latency, and a race with the frame that moved it.
23
+ * - **Decided on pointer-down, held to pointer-up.** That rule belongs to the host, because
24
+ * only the host sees the whole gesture; this file just keeps the snapshot true.
25
+ * - **Republished per frame while a transition is live.** A sliding menu is drawn where the
26
+ * compositor put it this frame, and a rect published before the slide points at empty space.
27
+ *
28
+ * Rects are **normalized to the viewport**, 0..1, so no host has to know about CSS pixels,
29
+ * device pixel ratio, or the page's zoom to place them on its own surface. That is also what
30
+ * lets a sibling-layer host and an offscreen-texture host read the same payload.
31
+ */
32
+
33
+ /** One interactive rectangle, normalized to the UI viewport: `0,0` top-left, `1,1` bottom-right. */
34
+ export interface IHitRegion {
35
+ readonly x: number;
36
+ readonly y: number;
37
+ readonly width: number;
38
+ readonly height: number;
39
+ }
40
+
41
+ export interface IHitRegionRegistry {
42
+ /** Recompute and publish now. Called for you; exposed for a game that moves a rect itself. */
43
+ refresh(): void;
44
+ /** The regions as last published. */
45
+ regions(): readonly IHitRegion[];
46
+ /** Stop observing and publish an empty set, so the host stops consuming touches. */
47
+ stop(): void;
48
+ }
49
+
50
+ interface IRegistryOptions {
51
+ /** The connected bridge whose `ui` end publishes the regions. */
52
+ readonly bridge: IUiBridge;
53
+ /** The realm to observe. Defaults to `globalThis`; injected by tests. */
54
+ readonly scope?: IScopeLike;
55
+ /** The marker attribute. Defaults to `data-tn-interactive`; a game should not change it. */
56
+ readonly attribute?: string;
57
+ }
58
+
59
+ /** The attribute a game puts on an element it wants to receive touches. */
60
+ export const INTERACTIVE_ATTRIBUTE = "data-tn-interactive";
61
+
62
+ interface IRectLike {
63
+ readonly left: number;
64
+ readonly top: number;
65
+ readonly width: number;
66
+ readonly height: number;
67
+ }
68
+
69
+ interface IElementLike {
70
+ getClientRects?: () => ArrayLike<IRectLike>;
71
+ getBoundingClientRect: () => IRectLike;
72
+ /** Used only to name an unmarked control in the development warning below. */
73
+ closest?: (selector: string) => IElementLike | null;
74
+ tagName?: string;
75
+ id?: string;
76
+ className?: string;
77
+ }
78
+
79
+ /** A `MutationObserver` or a `ResizeObserver`, as the two things this file asks of either. */
80
+ interface IObserverLike {
81
+ observe: (target: unknown, options?: unknown) => void;
82
+ disconnect: () => void;
83
+ }
84
+
85
+ /** Anything that can be listened to. The document and the window both satisfy it structurally. */
86
+ interface IEventTargetLike {
87
+ addEventListener?: (type: string, listener: () => void, options?: unknown) => void;
88
+ removeEventListener?: (type: string, listener: () => void, options?: unknown) => void;
89
+ }
90
+
91
+ interface IDocumentLike extends IEventTargetLike {
92
+ querySelectorAll: (selector: string) => ArrayLike<IElementLike>;
93
+ documentElement?: { clientWidth?: number; clientHeight?: number };
94
+ }
95
+
96
+ /**
97
+ * The realm the registry observes, as the parts of it this file actually touches.
98
+ *
99
+ * Declared structurally rather than as `Window`, because the registry has to be drivable from a
100
+ * test with no DOM — and because the host it really runs in is a web view whose globals the type
101
+ * system here has never seen.
102
+ */
103
+ interface IScopeLike extends IEventTargetLike {
104
+ // Indexed because a real realm carries far more than this, and a fake one is free to.
105
+ [key: string]: unknown;
106
+ document?: IDocumentLike;
107
+ console?: { warn?: (message: string) => void };
108
+ innerWidth?: number;
109
+ innerHeight?: number;
110
+ requestAnimationFrame?: (callback: () => void) => number;
111
+ cancelAnimationFrame?: (handle: number) => void;
112
+ // `MutationObserver` and `ResizeObserver` are read through the index signature above rather than
113
+ // declared here: they are browser globals and keep the host's capitalisation, which the naming
114
+ // rule is right to reject for an ordinary property.
115
+ }
116
+
117
+ /** A `MutationObserver` or a `ResizeObserver`, as the two things this file asks of either. */
118
+ interface IObserverLike {
119
+ observe: (target: unknown, options?: unknown) => void;
120
+ disconnect: () => void;
121
+ }
122
+
123
+ /** Five decimals of a normalized rect is a tenth of a pixel on a 10k display. */
124
+ function quantize(value: number): number {
125
+ return Math.round(value * 1e5) / 1e5;
126
+ }
127
+
128
+ /** Events that mean "something is moving and its published rect is now a frame behind". */
129
+ const TRANSITION_START = ["transitionrun", "transitionstart", "animationstart"] as const;
130
+ const TRANSITION_END = [
131
+ "transitionend",
132
+ "transitioncancel",
133
+ "animationend",
134
+ "animationcancel",
135
+ ] as const;
136
+ /** Events that change layout without changing the DOM, so no observer would fire. */
137
+ const LAYOUT_EVENTS = ["resize", "orientationchange", "scroll"] as const;
138
+
139
+ /**
140
+ * Start publishing interactive rectangles over `bridge`.
141
+ *
142
+ * Fail closed: with no document there is nothing to measure, and a registry that quietly
143
+ * published nothing would look exactly like a UI with no buttons — every touch would fall
144
+ * through to the game and the bug would present as "the button does nothing".
145
+ * @situation give native input hosts the rectangles claimed by UI controls
146
+ * @situation keep touch hit testing aligned with a moving web or native HUD
147
+ * @example const regions = publishHitRegions({ bridge });
148
+ */
149
+ export function publishHitRegions(options: IRegistryOptions): IHitRegionRegistry {
150
+ const scope: IScopeLike = options.scope ?? (globalThis as IScopeLike);
151
+ const document = scope.document;
152
+ if (document === undefined || typeof document.querySelectorAll !== "function") {
153
+ throw new Error(
154
+ "TN_UI_HIT_REGIONS_NO_DOCUMENT: the interactive-rect registry runs in the UI page and found no document.",
155
+ );
156
+ }
157
+ const selector = `[${options.attribute ?? INTERACTIVE_ATTRIBUTE}]`;
158
+ const bridge = options.bridge;
159
+ if (bridge.end !== "ui") {
160
+ throw new Error(
161
+ `TN_UI_HIT_REGIONS_WRONG_END: hit regions are published by the 'ui' end, not '${bridge.end}'.`,
162
+ );
163
+ }
164
+
165
+ const unmarkedWarning = { warned: false };
166
+ let published: readonly IHitRegion[] = [];
167
+ let publishedFrame = "";
168
+ let stopped = false;
169
+ let liveTransitions = 0;
170
+ let frameHandle: number | undefined;
171
+
172
+ const viewport = (): { width: number; height: number } => ({
173
+ width: scope.innerWidth ?? document.documentElement?.clientWidth ?? 0,
174
+ height: scope.innerHeight ?? document.documentElement?.clientHeight ?? 0,
175
+ });
176
+
177
+ /**
178
+ * `getClientRects()` and not `getBoundingClientRect()`: a wrapped inline control is several
179
+ * boxes, and their union covers empty page between them.
180
+ */
181
+ const boxesOf = (element: IElementLike): IRectLike[] => {
182
+ const list = element.getClientRects?.();
183
+ if (list === undefined || list.length === 0) return [element.getBoundingClientRect()];
184
+ const boxes: IRectLike[] = [];
185
+ for (let index = 0; index < list.length; index += 1) {
186
+ const rect = list[index];
187
+ if (rect !== undefined) boxes.push(rect);
188
+ }
189
+ return boxes;
190
+ };
191
+
192
+ /**
193
+ * A zero-area box is a hidden element. Publishing it would let the host swallow a touch on a
194
+ * control the player cannot see.
195
+ */
196
+ const normalize = (boxes: readonly IRectLike[], width: number, height: number): IHitRegion[] =>
197
+ boxes
198
+ .filter((rect) => rect.width > 0 && rect.height > 0)
199
+ .map((rect) => ({
200
+ x: quantize(rect.left / width),
201
+ y: quantize(rect.top / height),
202
+ width: quantize(rect.width / width),
203
+ height: quantize(rect.height / height),
204
+ }));
205
+
206
+ const measure = (): IHitRegion[] => {
207
+ const { width, height } = viewport();
208
+ if (width <= 0 || height <= 0) return [];
209
+ const regions: IHitRegion[] = [];
210
+ const elements = document.querySelectorAll(selector);
211
+ for (let index = 0; index < elements.length; index += 1) {
212
+ const element = elements[index];
213
+ if (element !== undefined) regions.push(...normalize(boxesOf(element), width, height));
214
+ }
215
+ warnAboutUnmarkedControls(document, selector, scope, unmarkedWarning);
216
+ return regions;
217
+ };
218
+
219
+ const publish = (regions: readonly IHitRegion[]): void => {
220
+ const frame = JSON.stringify(regions);
221
+ if (frame === publishedFrame) return;
222
+ publishedFrame = frame;
223
+ published = regions;
224
+ bridge.post({ type: HIT_REGIONS_MESSAGE, regions });
225
+ };
226
+
227
+ const refresh = (): void => {
228
+ if (stopped) return;
229
+ publish(measure());
230
+ };
231
+
232
+ const requestFrame = scope.requestAnimationFrame;
233
+ const cancelFrame = scope.cancelAnimationFrame;
234
+
235
+ /**
236
+ * While anything is transitioning, the published rect is a frame behind wherever the
237
+ * compositor drew it, so this republishes every frame until the last transition ends. It is
238
+ * deliberately not the steady-state path: a HUD that republishes 60 times a second when
239
+ * nothing moved is a message per frame across a process boundary for no reason.
240
+ */
241
+ const pump = (): void => {
242
+ frameHandle = undefined;
243
+ if (stopped || liveTransitions <= 0) return;
244
+ refresh();
245
+ if (requestFrame !== undefined) frameHandle = requestFrame(pump);
246
+ };
247
+
248
+ const onTransitionStart = (): void => {
249
+ liveTransitions += 1;
250
+ if (frameHandle === undefined && requestFrame !== undefined) frameHandle = requestFrame(pump);
251
+ };
252
+ const onTransitionEnd = (): void => {
253
+ liveTransitions = Math.max(0, liveTransitions - 1);
254
+ // One last measurement at the resting position: the final frame of a transition can land
255
+ // after the last rAF this pump scheduled.
256
+ refresh();
257
+ };
258
+
259
+ const listen = (
260
+ on: "addEventListener" | "removeEventListener",
261
+ host: IEventTargetLike,
262
+ types: readonly string[],
263
+ listener: () => void,
264
+ ): void => {
265
+ const method = host[on];
266
+ if (typeof method !== "function") return;
267
+ for (const type of types) method.call(host, type, listener, true);
268
+ };
269
+
270
+ listen("addEventListener", document, TRANSITION_START, onTransitionStart);
271
+ listen("addEventListener", document, TRANSITION_END, onTransitionEnd);
272
+ listen("addEventListener", scope, LAYOUT_EVENTS, refresh);
273
+
274
+ const MutationObserverCtor = scope.MutationObserver as
275
+ | (new (
276
+ callback: () => void,
277
+ ) => IObserverLike)
278
+ | undefined;
279
+ const mutations =
280
+ MutationObserverCtor === undefined ? undefined : new MutationObserverCtor(refresh);
281
+ mutations?.observe(document, {
282
+ attributes: true,
283
+ childList: true,
284
+ subtree: true,
285
+ characterData: true,
286
+ });
287
+
288
+ const ResizeObserverCtor = scope.ResizeObserver as
289
+ | (new (
290
+ callback: () => void,
291
+ ) => IObserverLike)
292
+ | undefined;
293
+ const resizes = ResizeObserverCtor === undefined ? undefined : new ResizeObserverCtor(refresh);
294
+ if (resizes !== undefined && document.documentElement !== undefined) {
295
+ resizes.observe(document.documentElement);
296
+ }
297
+
298
+ refresh();
299
+
300
+ return {
301
+ refresh,
302
+ regions: () => published,
303
+ stop() {
304
+ if (stopped) return;
305
+ stopped = true;
306
+ if (frameHandle !== undefined && cancelFrame !== undefined) cancelFrame(frameHandle);
307
+ frameHandle = undefined;
308
+ listen("removeEventListener", document, TRANSITION_START, onTransitionStart);
309
+ listen("removeEventListener", document, TRANSITION_END, onTransitionEnd);
310
+ listen("removeEventListener", scope, LAYOUT_EVENTS, refresh);
311
+ mutations?.disconnect();
312
+ resizes?.disconnect();
313
+ // Publishing the empty set is the point of stopping: a host still holding the last
314
+ // snapshot would keep eating touches over a UI that is gone.
315
+ published = [];
316
+ publishedFrame = "[]";
317
+ bridge.post({ type: HIT_REGIONS_MESSAGE, regions: [] });
318
+ },
319
+ };
320
+ }
321
+
322
+ /**
323
+ * Controls that look pressable but publish no rectangle, named once in development.
324
+ *
325
+ * The attribute is documented in every template's instructions as the one thing a UI must do
326
+ * differently from a web page, and it is still the easiest thing in this layer to forget: the
327
+ * button renders, `pointer-events-auto` looks like it should be enough, and on web it *is*. The
328
+ * failure only appears on a device, as a button that does nothing, with no error anywhere — the
329
+ * platform handed the gesture to the game before any CSS ran.
330
+ *
331
+ * So the registry says so at the moment the page runs, in the browser, which is where a UI is
332
+ * built. Once per page: a warning repeated every frame is noise, and noise is not read.
333
+ */
334
+ const UNMARKED_CONTROL_SELECTOR = 'button, [role="button"], a[href], input, select, textarea';
335
+
336
+ /** Once per registry, not once per process: two pages in one test run are two pages. */
337
+ interface IWarnedOnce {
338
+ warned: boolean;
339
+ }
340
+
341
+ function warnAboutUnmarkedControls(
342
+ document: IDocumentLike,
343
+ selector: string,
344
+ scope: IScopeLike,
345
+ once: IWarnedOnce,
346
+ ): void {
347
+ if (once.warned || !isDevelopment()) return;
348
+ if (typeof document.querySelectorAll !== "function") return;
349
+ const candidates = document.querySelectorAll(UNMARKED_CONTROL_SELECTOR);
350
+ const unmarked: string[] = [];
351
+ for (let index = 0; index < candidates.length; index += 1) {
352
+ const element = candidates[index];
353
+ if (element === undefined) continue;
354
+ if (element.closest?.(selector) != null) continue;
355
+ unmarked.push(describe(element));
356
+ }
357
+ if (unmarked.length === 0) return;
358
+ once.warned = true;
359
+ const names = unmarked.slice(0, 5).join(", ");
360
+ const rest = unmarked.length > 5 ? ` and ${unmarked.length - 5} more` : "";
361
+ scope.console?.warn?.(
362
+ `TN_UI_UNMARKED_CONTROLS: ${unmarked.length} control(s) publish no hit region, so on native ` +
363
+ `the press reaches the game instead: ${names}${rest}. Mark each with ` +
364
+ `${INTERACTIVE_ATTRIBUTE}, or wrap them in an element that carries it.`,
365
+ );
366
+ }
367
+
368
+ /** A short, recognisable name for one element: tag, id, and the first class. */
369
+ function describe(element: IElementLike): string {
370
+ const tag = (element.tagName ?? "element").toLowerCase();
371
+ const id = element.id === undefined || element.id === "" ? "" : `#${element.id}`;
372
+ const first = (element.className ?? "").split(/\s+/u).filter(Boolean)[0];
373
+ return `<${tag}${id}${first === undefined ? "" : `.${first}`}>`;
374
+ }
375
+
376
+ function isDevelopment(): boolean {
377
+ return (
378
+ (import.meta as ImportMeta & { env?: Record<"DEV", boolean | undefined> }).env?.DEV === true
379
+ );
380
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The UI layer's platform seam: one bridge and one hit-region protocol, host-independent.
3
+ *
4
+ * A game's `src/ui/` renders through the platform's own browser-class renderer on every
5
+ * target — react-dom, Tailwind, CSS, SVG and fonts unchanged. Everything the UI needs from
6
+ * the game and everything the game needs from the UI crosses through here.
7
+ *
8
+ * Most games never import this file: `@threenative/ui`'s `<UiLayer>` connects the UI end and
9
+ * `game.ui` is the game end. Reach for it directly when writing a UI without React.
10
+ *
11
+ * @see ./ui-bridge.js for the message channel, ./ui-hit-regions.js for the input protocol.
12
+ */
13
+
14
+ /**
15
+ * Open the message channel between a game and its UI, whatever host is underneath.
16
+ * @situation write a UI that talks to the game on web and on a phone alike
17
+ * @situation send a message from a HUD rendered over the game surface
18
+ * @constraint the transport is discovered, never configured; no game names the web view
19
+ * @example const bridge = connectUiBridge({ end: "ui" });
20
+ */
21
+ export { connectUiBridge } from "./ui-bridge.js";
22
+ export {
23
+ GAME_STATE_MESSAGE,
24
+ HIT_REGIONS_MESSAGE,
25
+ UI_BRIDGE_GLOBALS,
26
+ UI_DEV_METRICS_MESSAGE,
27
+ UI_INTENT_MESSAGE,
28
+ UI_READY_INTENT,
29
+ type IUiBridge,
30
+ type IUiMessage,
31
+ type UiBridgeEnd,
32
+ type UiBridgeTransport,
33
+ } from "./ui-bridge.js";
34
+ /**
35
+ * Publish the game's state so a UI in another process can mirror it.
36
+ * @situation show score or health in a UI rendered over the game surface
37
+ * @situation keep a HUD in step with the game without re-rendering on the loop
38
+ * @alias journal objective panel
39
+ * @alias readable HUD
40
+ * @constraint publishes once per rendered frame unless stateFlushMs selects a slower interval, and not at all with no UI listening
41
+ * @example publishUiState(bridge, game.state);
42
+ */
43
+ export { publishUiState } from "./ui-state.js";
44
+ /**
45
+ * Mirror the game's published state on the UI side.
46
+ * @situation read game state from a HUD that runs in the platform's web view
47
+ * @constraint returns undefined until the game publishes its first state
48
+ * @example const mirror = subscribeUiState(bridge);
49
+ */
50
+ export { subscribeUiState } from "./ui-state.js";
51
+ /**
52
+ * Send a player action from the UI back to the game.
53
+ * @situation wire a Restart button in a HUD to the running game
54
+ * @situation pause a game from a menu drawn over its surface
55
+ * @constraint one-way; the game decides what each name means and may ignore one
56
+ * @example sendUiIntent(bridge, "restart");
57
+ */
58
+ export { sendUiIntent } from "./ui-state.js";
59
+ /**
60
+ * Handle the actions a UI sends back to the game.
61
+ * @situation restart or pause a game from a button in its HUD
62
+ * @constraint prefer game.ui.onIntent, which connects the bridge for you
63
+ * @example onUiIntent(bridge, (intent) => { if (intent === "restart") game.goto("Play"); });
64
+ */
65
+ export { onUiIntent } from "./ui-state.js";
66
+ export type {
67
+ IPublishableStore,
68
+ IUiStateMirror,
69
+ IUiStatePublisher,
70
+ } from "./ui-state.js";
71
+ /**
72
+ * Tell the native input host where a UI's touchable controls are.
73
+ * @situation let a touch on empty HUD space reach the game instead of the UI
74
+ * @situation make a HUD button receive taps on a phone
75
+ * @constraint mark controls with data-tn-interactive; pointer-events is not the mechanism
76
+ * @example publishHitRegions({ bridge });
77
+ */
78
+ export { publishHitRegions } from "./ui-hit-regions.js";
79
+ export {
80
+ INTERACTIVE_ATTRIBUTE,
81
+ type IHitRegion,
82
+ type IHitRegionRegistry,
83
+ } from "./ui-hit-regions.js";
@@ -0,0 +1,220 @@
1
+ import {
2
+ GAME_STATE_MESSAGE,
3
+ type IUiBridge,
4
+ type IUiMessage,
5
+ UI_INTENT_MESSAGE,
6
+ postUiState,
7
+ serializeUiState,
8
+ } from "./ui-bridge.js";
9
+
10
+ /**
11
+ * What crosses the bridge, in both directions: published state out, intents back.
12
+ *
13
+ * The UI is a different realm from the game on every native target, so it cannot hold the game
14
+ * object, subscribe to its store, or call its methods. It holds a **mirror** — the last state
15
+ * the game published — and it sends **intents**, which the game is free to ignore.
16
+ *
17
+ * That asymmetry is deliberate and it is what keeps one `src/ui/` honest. A HUD written against
18
+ * a live store works on web and silently has nothing to read on a phone; a HUD written against
19
+ * the mirror behaves identically on both, because on web the mirror is fed by the same
20
+ * publication through an in-process channel.
21
+ *
22
+ * Publications are **coalesced**: many simulation writes produce one state message per rendered
23
+ * frame. React consumes that snapshot in the UI realm, independently of the game's render work.
24
+ */
25
+
26
+ /**
27
+ * The minimum a store must offer to be published.
28
+ *
29
+ * `getPublishedState` is optional and preferred when present: ThreeNative's game store keeps a
30
+ * live `getState()` that moves every tick and a stable `getPublishedState()` snapshot published
31
+ * once per rendered frame, unless the game selected a slower `stateFlushMs` interval.
32
+ */
33
+ export interface IPublishableStore<T> {
34
+ getState(): T;
35
+ getPublishedState?(): T;
36
+ subscribe(listener: () => void): () => void;
37
+ }
38
+
39
+ export interface IUiStatePublisher {
40
+ /** Send the current state now, whether or not it changed. */
41
+ publish(): void;
42
+ /** Stop publishing. The mirror keeps whatever it last received. */
43
+ stop(): void;
44
+ }
45
+
46
+ export interface IUiStateMirror<T> {
47
+ /** The last state the game published, or undefined before the first frame arrives. */
48
+ get(): T | undefined;
49
+ /** Called after each accepted publication. Returns an unsubscribe function. */
50
+ subscribe(listener: () => void): () => void;
51
+ /** Stop listening. */
52
+ stop(): void;
53
+ }
54
+
55
+ interface IPublishOptions {
56
+ /**
57
+ * How a coalesced publication is deferred. Defaults to a microtask, which collapses every
58
+ * write in one turn into one frame. A game with a chatty store may pass a frame scheduler.
59
+ */
60
+ readonly schedule?: (flush: () => void) => void;
61
+ }
62
+
63
+ const microtask = (flush: () => void): void => {
64
+ void Promise.resolve().then(flush);
65
+ };
66
+
67
+ /**
68
+ * Publish a store to the UI over `bridge`.
69
+ *
70
+ * Only the `game` end publishes: the UI is a mirror, and a UI that could write the game's state
71
+ * directly would be a second source of truth that only diverges on the platform where the two
72
+ * are actually separate processes.
73
+ * @situation publish game state to a HUD in another realm
74
+ * @situation keep a web and native UI mirror on the same coalesced state stream
75
+ * @example const publisher = publishUiState(bridge, store);
76
+ */
77
+ export function publishUiState<T>(
78
+ bridge: IUiBridge,
79
+ store: IPublishableStore<T>,
80
+ options: IPublishOptions = {},
81
+ ): IUiStatePublisher {
82
+ if (bridge.end !== "game") {
83
+ throw new Error(
84
+ `TN_UI_STATE_WRONG_END: state is published by the 'game' end, not '${bridge.end}'.`,
85
+ );
86
+ }
87
+ const schedule = options.schedule ?? microtask;
88
+ const read = (): T =>
89
+ store.getPublishedState === undefined ? store.getState() : store.getPublishedState();
90
+ let stopped = false;
91
+ let queued = false;
92
+ let lastFrame = "";
93
+
94
+ const send = (state: T, frame: string): void => {
95
+ lastFrame = frame;
96
+ postUiState(bridge, state, frame);
97
+ };
98
+
99
+ const publish = (): void => {
100
+ if (stopped) return;
101
+ const state = read();
102
+ send(state, serializeUiState(state));
103
+ };
104
+
105
+ const flush = (): void => {
106
+ queued = false;
107
+ if (stopped) return;
108
+ // Nothing is listening — a `native` renderer, or an overlay that has not come up. Serialising
109
+ // the whole store several times a second for no reader is exactly the cost acceptance
110
+ // criterion 5 says a game that did not opt in must not pay.
111
+ if (!bridge.hasPeer()) return;
112
+ // Skip a publication that would carry the bytes the UI already has. A store that writes the
113
+ // same value every tick is common and must not become a message per tick.
114
+ const state = read();
115
+ const frame = serializeUiState(state);
116
+ if (frame === lastFrame) return;
117
+ send(state, frame);
118
+ };
119
+
120
+ const unsubscribe = store.subscribe(() => {
121
+ if (stopped || queued) return;
122
+ queued = true;
123
+ schedule(flush);
124
+ });
125
+
126
+ if (bridge.hasPeer()) publish();
127
+ return {
128
+ publish,
129
+ stop() {
130
+ stopped = true;
131
+ unsubscribe();
132
+ },
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Mirror the game's published state on the UI end.
138
+ *
139
+ * Fail closed: a `tn:state` frame with no `state` object throws rather than leaving the mirror
140
+ * showing stale values, which is the failure mode where a HUD keeps displaying the last health
141
+ * it saw and nobody can tell it stopped updating.
142
+ * @situation read published game state from a UI HUD
143
+ * @situation subscribe a web or native UI to the game's mirrored state
144
+ * @example const mirror = subscribeUiState<{ health: number }>(bridge);
145
+ */
146
+ export function subscribeUiState<T>(bridge: IUiBridge): IUiStateMirror<T> {
147
+ if (bridge.end !== "ui") {
148
+ throw new Error(
149
+ `TN_UI_STATE_WRONG_END: state is mirrored by the 'ui' end, not '${bridge.end}'.`,
150
+ );
151
+ }
152
+ const listeners = new Set<() => void>();
153
+ let current: T | undefined;
154
+ const off = bridge.onMessage((message) => {
155
+ if (message.type !== GAME_STATE_MESSAGE) return;
156
+ const state = message.state;
157
+ if (typeof state !== "object" || state === null || Array.isArray(state)) {
158
+ throw new Error("TN_UI_STATE_FRAME_INVALID: a published state frame must carry an object.");
159
+ }
160
+ current = state as T;
161
+ for (const listener of [...listeners]) listener();
162
+ });
163
+ return {
164
+ get: () => current,
165
+ subscribe(listener) {
166
+ listeners.add(listener);
167
+ return () => listeners.delete(listener);
168
+ },
169
+ stop() {
170
+ off();
171
+ listeners.clear();
172
+ },
173
+ };
174
+ }
175
+
176
+ /**
177
+ * Send one intent from the UI to the game. The game may ignore it; that is not an error.
178
+ * @situation send a button or menu action from a UI HUD to game code
179
+ * @situation keep UI input portable across web and native hosts
180
+ * @example sendUiIntent(bridge, "restart");
181
+ */
182
+ export function sendUiIntent(bridge: IUiBridge, intent: string, payload?: unknown): void {
183
+ if (bridge.end !== "ui") {
184
+ throw new Error(
185
+ `TN_UI_INTENT_WRONG_END: intents are sent by the 'ui' end, not '${bridge.end}'.`,
186
+ );
187
+ }
188
+ if (typeof intent !== "string" || intent.length === 0) {
189
+ throw new Error("TN_UI_INTENT_INVALID: an intent needs a non-empty name.");
190
+ }
191
+ bridge.post({
192
+ type: UI_INTENT_MESSAGE,
193
+ intent,
194
+ ...(payload === undefined ? {} : { payload }),
195
+ } as IUiMessage);
196
+ }
197
+
198
+ /**
199
+ * Receive UI intents on the game end. Returns an unsubscribe function.
200
+ * @situation handle a HUD button action in game code
201
+ * @situation route native and web UI commands through one listener
202
+ * @example const stop = onUiIntent(bridge, (intent) => handleIntent(intent));
203
+ */
204
+ export function onUiIntent(
205
+ bridge: IUiBridge,
206
+ listener: (intent: string, payload: unknown) => void,
207
+ ): () => void {
208
+ if (bridge.end !== "game") {
209
+ throw new Error(
210
+ `TN_UI_INTENT_WRONG_END: intents are received by the 'game' end, not '${bridge.end}'.`,
211
+ );
212
+ }
213
+ return bridge.onMessage((message) => {
214
+ if (message.type !== UI_INTENT_MESSAGE) return;
215
+ if (typeof message.intent !== "string" || message.intent.length === 0) {
216
+ throw new Error("TN_UI_INTENT_INVALID: an intent frame must carry a non-empty name.");
217
+ }
218
+ listener(message.intent, message.payload);
219
+ });
220
+ }
package/src/version.ts ADDED
@@ -0,0 +1,2 @@
1
+ // Generated by scripts/generate-version.mjs - do not edit. Source: package.json.
2
+ export const CORE_VERSION = "0.3.6";