@threenative/three-native 0.3.11 → 0.3.13

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.
@@ -1,16 +1,30 @@
1
1
  import { PLAYTEST_OBSERVING_GLOBAL, callerOf } from "./bridge-meter.js";
2
2
 
3
- /** Kept local to the bridge so three-native does not depend on core. */
3
+ /**
4
+ * Kept local to the bridge so three-native does not depend on core, and held to core's rule by
5
+ * `scripts/__tests__/launch-flag-parity.spec.ts`: `0` and `false` are off, a named-but-empty value
6
+ * is on, an empty variable is unset, and every seam that names the flag is heard. The two copies
7
+ * disagreed before — core accepted `?tnDebug=true` and this did not — which is drift nobody sees
8
+ * until one layer's telemetry is off while the other's is on.
9
+ */
4
10
  export function debugRequested(): boolean {
5
11
  const host = globalThis as {
6
12
  process?: { env?: Record<string, unknown> };
7
13
  [name: string]: unknown;
8
14
  };
9
- return (
10
- host.process?.env?.TN_DEBUG === "1" ||
11
- /[?&]tnDebug=1(?:&|$)/u.test(globalThis.location?.search ?? "") ||
12
- host.__THREENATIVE_DEBUG__ === true
13
- );
15
+ const values: string[] = [];
16
+ const env = host.process?.env?.TN_DEBUG;
17
+ if (typeof env === "string" && env !== "") values.push(env);
18
+ const search = globalThis.location?.search;
19
+ if (typeof search === "string") {
20
+ const fromQuery = new URLSearchParams(search).get("tnDebug");
21
+ if (fromQuery !== null) values.push(fromQuery);
22
+ }
23
+ const set = host.__THREENATIVE_DEBUG__;
24
+ if (typeof set === "string") values.push(set);
25
+ else if (typeof set === "number") values.push(String(set));
26
+ else if (typeof set === "boolean") values.push(set ? "true" : "false");
27
+ return values.some((value) => value !== "0" && value !== "false");
14
28
  }
15
29
 
16
30
  type DebugSource = { area: string; caller: string; lever?: string; unit?: string };
@@ -26,6 +40,9 @@ export class DebugTelemetry {
26
40
  name: string,
27
41
  amount = 1,
28
42
  area = "bridge",
43
+ // Every counter the back end adds keeps this name, including the ones `browser-wasm-runtime.ts`
44
+ // adds since PRD-803 split it out: the split moved code, so the attribution a debug report shows
45
+ // does not move with it.
29
46
  caller = "browser-backend.ts",
30
47
  unit?: string,
31
48
  ): void {
@@ -0,0 +1,111 @@
1
+ // three's EdgesGeometry over the engine's BufferGeometry, ported from three r187
2
+ // src/geometries/EdgesGeometry.js (MIT). The engine binds no Triangle, so the face normal is three's
3
+ // Triangle.getNormal written over plain numbers. The source arrays are read once: each engine
4
+ // `array` read is one copy, where three's per-vertex getX would be one engine call per component.
5
+ // ponytail: positions are read raw, so a normalized (quantized) position attribute is not denormalized.
6
+
7
+ type Constructor = new (...args: never[]) => object;
8
+ type V3 = [number, number, number];
9
+
10
+ interface IAttribute {
11
+ readonly array: ArrayLike<number>;
12
+ readonly itemSize: number;
13
+ readonly count: number;
14
+ }
15
+
16
+ interface IGeometry {
17
+ getIndex(): IAttribute | null;
18
+ getAttribute(name: string): IAttribute;
19
+ setAttribute(name: string, attribute: object): void;
20
+ }
21
+
22
+ // three's Triangle.getNormal: (c - b) x (a - b), normalized; zero for a degenerate triangle.
23
+ function faceNormal([ax, ay, az]: V3, [bx, by, bz]: V3, [cx, cy, cz]: V3): V3 {
24
+ const [ux, uy, uz] = [cx - bx, cy - by, cz - bz];
25
+ const [vx, vy, vz] = [ax - bx, ay - by, az - bz];
26
+ const [nx, ny, nz] = [uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx];
27
+ const lengthSq = nx * nx + ny * ny + nz * nz;
28
+ const scale = lengthSq > 0 ? 1 / Math.sqrt(lengthSq) : 0;
29
+ return [nx * scale, ny * scale, nz * scale];
30
+ }
31
+
32
+ interface IEdges {
33
+ readonly map: Map<string, { index0: number; index1: number; normal: V3 } | null>;
34
+ readonly vertices: number[];
35
+ readonly point: (vertex: number) => V3;
36
+ readonly thresholdDot: number;
37
+ }
38
+
39
+ const PRECISION = 10 ** 4;
40
+ const hash = (p: V3) => p.map((value) => Math.round(value * PRECISION)).join(",");
41
+
42
+ // One triangle's three edges: a shared edge is kept when its faces meet at the threshold angle or more.
43
+ function addFace(edges: IEdges, ids: V3): void {
44
+ const corners = [edges.point(ids[0]), edges.point(ids[1]), edges.point(ids[2])] as const;
45
+ const normal = faceNormal(...corners);
46
+ const hashes = corners.map(hash);
47
+ // Skip degenerate triangles.
48
+ if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) return;
49
+ for (let j = 0; j < 3; j++) {
50
+ const next = (j + 1) % 3;
51
+ const key = `${hashes[j]}_${hashes[next]}`;
52
+ const reverse = `${hashes[next]}_${hashes[j]}`;
53
+ const sibling = edges.map.get(reverse);
54
+ if (sibling) {
55
+ const [sx, sy, sz] = sibling.normal;
56
+ if (normal[0] * sx + normal[1] * sy + normal[2] * sz <= edges.thresholdDot)
57
+ edges.vertices.push(...(corners[j] as V3), ...(corners[next] as V3));
58
+ edges.map.set(reverse, null);
59
+ } else if (!edges.map.has(key))
60
+ edges.map.set(key, { index0: ids[j] as number, index1: ids[next] as number, normal });
61
+ }
62
+ }
63
+
64
+ // The edge segments of `geometry`: border edges and edges whose faces meet at `thresholdAngle` or more.
65
+ function edgeVertices(geometry: IGeometry, thresholdAngle: number): number[] {
66
+ const index = geometry.getIndex();
67
+ const indices = index?.array;
68
+ const attribute = geometry.getAttribute("position");
69
+ const { array: positions, itemSize: stride } = attribute;
70
+ const edges: IEdges = {
71
+ map: new Map(),
72
+ vertices: [],
73
+ point: (vertex) => {
74
+ const at = vertex * stride;
75
+ return [positions[at] ?? 0, positions[at + 1] ?? 0, positions[at + 2] ?? 0];
76
+ },
77
+ thresholdDot: Math.cos((Math.PI / 180) * thresholdAngle),
78
+ };
79
+ const vertexAt = (i: number) => (indices ? (indices[i] ?? 0) : i);
80
+ const indexCount = index ? index.count : attribute.count;
81
+ for (let i = 0; i < indexCount; i += 3)
82
+ addFace(edges, [vertexAt(i), vertexAt(i + 1), vertexAt(i + 2)]);
83
+ // Every unmatched edge is a border edge.
84
+ for (const edge of edges.map.values())
85
+ if (edge) edges.vertices.push(...edges.point(edge.index0), ...edges.point(edge.index1));
86
+ return edges.vertices;
87
+ }
88
+
89
+ export function defineEdgesGeometry(
90
+ classes: Readonly<Record<"BufferGeometry" | "Float32BufferAttribute", Constructor>>,
91
+ ) {
92
+ const BufferGeometry = classes.BufferGeometry as new () => IGeometry;
93
+ const Float32BufferAttribute = classes.Float32BufferAttribute as new (
94
+ array: number[],
95
+ itemSize: number,
96
+ ) => object;
97
+ return class EdgesGeometry extends BufferGeometry {
98
+ readonly type = "EdgesGeometry";
99
+ readonly parameters: { geometry: IGeometry | null; thresholdAngle: number };
100
+
101
+ constructor(geometry: IGeometry | null = null, thresholdAngle = 1) {
102
+ super();
103
+ this.parameters = { geometry, thresholdAngle };
104
+ if (geometry === null) return;
105
+ this.setAttribute(
106
+ "position",
107
+ new Float32BufferAttribute(edgeVertices(geometry, thresholdAngle), 3),
108
+ );
109
+ }
110
+ };
111
+ }
@@ -0,0 +1,13 @@
1
+ // Generated by @threenative/three-native from api/console-markers.json. Do not edit.
2
+ //
3
+ // The `TN_*` console markers the perf tooling parses. Add the colon where a line is matched.
4
+ export const CONSOLE_MARKER = {
5
+ bridgeCensus: "TN_BRIDGE_CENSUS",
6
+ frameBudget: "TN_FRAME_BUDGET",
7
+ frameHitch: "TN_FRAME_HITCH",
8
+ hostGap: "TN_HOST_GAP",
9
+ playerFrame: "TN_PLAYER_FRAME",
10
+ presentsTick: "TN_PRESENTS_TICK",
11
+ projection: "TN_PROJECTION",
12
+ slowPhase: "TN_SLOW_PHASE",
13
+ } as const;
@@ -0,0 +1,84 @@
1
+ // Generated by @threenative/three-native from api/web-frame-fields.json. Do not edit.
2
+ //
3
+ // The fields `tnw_web_frame` answers. Ids are frozen and append-only: a facade reads a number,
4
+ // so a renumbered field is one value read as another.
5
+ export const WEB_FRAME_FIELD = {
6
+ cpuMetersOff: -4,
7
+ cpuMetersOn: -3,
8
+ debugTimestampOff: -2,
9
+ debugTimestampOn: -1,
10
+ draws: 0,
11
+ triangles: 1,
12
+ pipelineCompiles: 2,
13
+ pipelineLookups: 3,
14
+ bindGroupsCreated: 4,
15
+ graphKeyBuilds: 5,
16
+ programs: 6,
17
+ gpuMs: 7,
18
+ gpuSamples: 8,
19
+ gpuSourceFrame: 9,
20
+ gpuTimerAvailable: 10,
21
+ gpuBusy: 11,
22
+ environmentPending: 12,
23
+ temporalActive: 13,
24
+ temporalFrame: 14,
25
+ temporalHistoryValid: 15,
26
+ temporalJitterX: 16,
27
+ temporalJitterY: 17,
28
+ sampleCount: 18,
29
+ gpuSegmentShadow: 19,
30
+ gpuSegmentScene: 20,
31
+ gpuSegmentOther: 21,
32
+ gpuSegmentOutput: 22,
33
+ gpuSegmentGather: 23,
34
+ gpuSegmentLampShadow: 24,
35
+ lampRedraws: 25,
36
+ lampShadowDraws: 26,
37
+ shadowDraws: 27,
38
+ lampMapMin: 28,
39
+ lampMapMax: 29,
40
+ temporalRejected: 30,
41
+ temporalClamped: 31,
42
+ temporalPixels: 32,
43
+ temporalCountedFrame: 33,
44
+ temporalUpscale: 34,
45
+ inputWidth: 35,
46
+ inputHeight: 36,
47
+ temporalJitterLength: 37,
48
+ width: 38,
49
+ height: 39,
50
+ keptShadowMaps: 40,
51
+ uniformBytes: 41,
52
+ mainRecorded: 60,
53
+ recordCause: 61,
54
+ auxRecorded: 62,
55
+ recordMs: 63,
56
+ shadowEncodeMs: 64,
57
+ shadowRecorded: 65,
58
+ cpuVirtualPagesMs: 66,
59
+ cpuPlanMs: 67,
60
+ cpuShadowBuildMs: 68,
61
+ cpuPrepareMs: 69,
62
+ cpuEncodeMs: 70,
63
+ worldSubmissions: 71,
64
+ shadowInputsReady: 72,
65
+ cpuPostMs: 73,
66
+ sceneMs: 74,
67
+ hostRenderMs: 75,
68
+ hostComputeMs: 76,
69
+ hostSubmitMs: 77,
70
+ stageTotalsAddress: 78,
71
+ hostPollMs: 79,
72
+ hostTailMs: 80,
73
+ rendererMs: 81,
74
+ hostDatabaseMs: 82,
75
+ hostTargetMs: 83,
76
+ cpuMetersActive: 84,
77
+ shadowTriangles: 85,
78
+ firstWorldFrameDrawn: 86,
79
+ textureCompressionBc: 87,
80
+ virtualShadowPendingLevels: 88,
81
+ frameSnapshot: 89,
82
+ } as const;
83
+
84
+ export type WebFrameField = (typeof WEB_FRAME_FIELD)[keyof typeof WEB_FRAME_FIELD];
package/src/gpu-stages.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  * a stage that drew no pass is absent. The order is the native stage id counting from 1
5
5
  * (`kStageScreenSpaceGi` in post_effects.h), so a new name goes last.
6
6
  */
7
+ import { WEB_FRAME_FIELD } from "./generated/web-frame-fields.js";
7
8
  export const GPU_STAGES = ["SSGI"] as const;
8
9
 
9
10
  export type GpuStage = (typeof GPU_STAGES)[number];
@@ -26,7 +27,7 @@ export function gpuStageId(name: unknown): number {
26
27
  export const SHADOW_STAGE = "Shadow";
27
28
 
28
29
  /** `tnw_web_frame` field of the shadow passes' segment (web_host.cpp). */
29
- export const SHADOW_SEGMENT_FIELD = 19;
30
+ export const SHADOW_SEGMENT_FIELD: number = WEB_FRAME_FIELD.gpuSegmentShadow;
30
31
 
31
32
  /**
32
33
  * The renderer's CPU stages by `tnw_web_frame` field (web_host.cpp 66 to 77): running ms of every render, which
@@ -39,21 +40,21 @@ export const SHADOW_SEGMENT_FIELD = 19;
39
40
  * and the batched queue submit that ends it (PRD-771), then the `tnw_web_poll` that opens it and its tail (surface texture release, frame gate, diagnostics) and the wall time of `Renderer::render` itself (`rendererMs`, which holds the prepare and encode halves) inside the whole `RenderDatabase::render` call (`hostDatabaseMs`), then the render targets' draws (`hostTargetMs`). The order of the names is the order the page reads them.
40
41
  */
41
42
  export const CPU_STAGE_FIELDS = {
42
- cpuVirtualPagesMs: 66,
43
- cpuPlanMs: 67,
44
- cpuShadowBuildMs: 68,
45
- cpuPrepareMs: 69,
46
- cpuEncodeMs: 70,
47
- cpuPostMs: 73,
48
- cpuSceneMs: 74,
49
- hostRenderMs: 75,
50
- hostComputeMs: 76,
51
- hostSubmitMs: 77,
52
- hostPollMs: 79,
53
- hostTailMs: 80,
54
- rendererMs: 81,
55
- hostDatabaseMs: 82,
56
- hostTargetMs: 83,
43
+ cpuVirtualPagesMs: WEB_FRAME_FIELD.cpuVirtualPagesMs,
44
+ cpuPlanMs: WEB_FRAME_FIELD.cpuPlanMs,
45
+ cpuShadowBuildMs: WEB_FRAME_FIELD.cpuShadowBuildMs,
46
+ cpuPrepareMs: WEB_FRAME_FIELD.cpuPrepareMs,
47
+ cpuEncodeMs: WEB_FRAME_FIELD.cpuEncodeMs,
48
+ cpuPostMs: WEB_FRAME_FIELD.cpuPostMs,
49
+ cpuSceneMs: WEB_FRAME_FIELD.sceneMs,
50
+ hostRenderMs: WEB_FRAME_FIELD.hostRenderMs,
51
+ hostComputeMs: WEB_FRAME_FIELD.hostComputeMs,
52
+ hostSubmitMs: WEB_FRAME_FIELD.hostSubmitMs,
53
+ hostPollMs: WEB_FRAME_FIELD.hostPollMs,
54
+ hostTailMs: WEB_FRAME_FIELD.hostTailMs,
55
+ rendererMs: WEB_FRAME_FIELD.rendererMs,
56
+ hostDatabaseMs: WEB_FRAME_FIELD.hostDatabaseMs,
57
+ hostTargetMs: WEB_FRAME_FIELD.hostTargetMs,
57
58
  } as const;
58
59
 
59
60
  export type CpuStageName = keyof typeof CPU_STAGE_FIELDS;
@@ -0,0 +1,49 @@
1
+ // three's GridHelper over the engine's LineSegments, ported from three r180 src/helpers/GridHelper.js (MIT).
2
+ // The engine binds LineSegments, BufferGeometry and LineBasicMaterial, so the helper is those three: no
3
+ // engine class of its own. `type` stays the engine's "LineSegments", which is how the renderer picks the
4
+ // line-list topology; `isGridHelper` marks it as three's does.
5
+
6
+ type Constructor = new (...args: unknown[]) => object;
7
+
8
+ type EngineClasses = Readonly<
9
+ Record<
10
+ "LineSegments" | "BufferGeometry" | "Float32BufferAttribute" | "LineBasicMaterial" | "Color",
11
+ Constructor
12
+ >
13
+ >;
14
+
15
+ export function defineGridHelper(classes: EngineClasses) {
16
+ const LineSegments = classes.LineSegments as new (
17
+ geometry: object,
18
+ material: object,
19
+ ) => { geometry: { dispose(): void }; material: { dispose(): void } };
20
+ return class GridHelper extends LineSegments {
21
+ readonly isGridHelper = true;
22
+
23
+ constructor(size = 10, divisions = 10, color1: unknown = 0x444444, color2: unknown = 0x888888) {
24
+ const center = new classes.Color(color1) as { r: number; g: number; b: number };
25
+ const line = new classes.Color(color2) as { r: number; g: number; b: number };
26
+ const middle = divisions / 2;
27
+ const step = size / divisions;
28
+ const halfSize = size / 2;
29
+ const vertices: number[] = [];
30
+ const colors: number[] = [];
31
+ for (let i = 0, k = -halfSize; i <= divisions; i++, k += step) {
32
+ vertices.push(-halfSize, 0, k, halfSize, 0, k, k, 0, -halfSize, k, 0, halfSize);
33
+ const color = i === middle ? center : line;
34
+ for (let vertex = 0; vertex < 4; vertex++) colors.push(color.r, color.g, color.b);
35
+ }
36
+ const geometry = new classes.BufferGeometry() as {
37
+ setAttribute(name: string, attribute: object): void;
38
+ };
39
+ geometry.setAttribute("position", new classes.Float32BufferAttribute(vertices, 3));
40
+ geometry.setAttribute("color", new classes.Float32BufferAttribute(colors, 3));
41
+ super(geometry, new classes.LineBasicMaterial({ vertexColors: true, toneMapped: false }));
42
+ }
43
+
44
+ dispose(): void {
45
+ this.geometry.dispose();
46
+ this.material.dispose();
47
+ }
48
+ };
49
+ }
@@ -196,14 +196,31 @@ export function defineObjectSurface(classes: ISurfaceClasses): void {
196
196
  }
197
197
 
198
198
  // three's scene classes and the `is<Class>` flag each one defines; every light is also `isLight`.
199
+ // type-flags.spec.ts fails when a bound class lacks a flag three's own instance reads true.
199
200
  const FLAGGED_CLASSES = [
200
201
  "NodeMaterial",
201
202
  "MeshBasicNodeMaterial",
202
203
  "MeshStandardNodeMaterial",
204
+ "MeshPhysicalNodeMaterial",
203
205
  "SpriteNodeMaterial",
206
+ // Its parent is MeshStandardMaterial, so the material base (Material's direct children) misses it.
207
+ "MeshPhysicalMaterial",
204
208
  "Texture",
205
209
  "DataTexture",
206
210
  "CanvasTexture",
211
+ "CubeTexture",
212
+ "Data3DTexture",
213
+ "DataArrayTexture",
214
+ "DepthTexture",
215
+ "Source",
216
+ "RenderTarget",
217
+ "Matrix4",
218
+ "CatmullRomCurve3",
219
+ // A particle batch re-sends only the attributes it finds by this flag, as three's idiom has it.
220
+ "InstancedBufferAttribute",
221
+ "InstancedBufferGeometry",
222
+ "InterleavedBufferAttribute",
223
+ "CompressedTexture",
207
224
  "Object3D",
208
225
  "Scene",
209
226
  "Group",
@@ -227,6 +244,35 @@ const FLAGGED_CLASSES = [
227
244
  "SpotLight",
228
245
  ] as const;
229
246
 
247
+ /**
248
+ * three's `dispose()` on lights and instanced meshes frees a shadow map or the instance textures. The
249
+ * engine frees those with the object, so the call has nothing to release (core's projection mirror
250
+ * and a scene's exit make it). A back end's own `dispose` stays.
251
+ */
252
+ export function defineReleaseNoops(classes: Readonly<Record<string, unknown>>): void {
253
+ for (const name of [
254
+ "BatchedMesh",
255
+ "InstancedMesh",
256
+ ...FLAGGED_CLASSES.filter((n) => n.endsWith("Light")),
257
+ ]) {
258
+ const cls = classes[name] as (new () => { dispose?: () => void }) | undefined;
259
+ if (typeof cls === "function") cls.prototype.dispose ??= () => {};
260
+ }
261
+ }
262
+
263
+ /** The flags three's own instance of a listed class reads true. */
264
+ function flagsOf(name: string): string[] {
265
+ if (name.endsWith("Light")) return [`is${name}`, "isLight"];
266
+ // three renamed Source to TextureSource and keeps both flags.
267
+ if (name === "Source") return ["isSource", "isTextureSource"];
268
+ if (!name.endsWith("NodeMaterial")) return [`is${name}`];
269
+ // three's node material copies its classic material's defaults, flag included: a
270
+ // MeshStandardNodeMaterial reads isMeshStandardMaterial, as a physical one reads both.
271
+ const flags = [`is${name}`, "isNodeMaterial", `is${name.replace("Node", "")}`];
272
+ if (name === "MeshPhysicalNodeMaterial") flags.push("isMeshStandardMaterial");
273
+ return flags;
274
+ }
275
+
230
276
  /**
231
277
  * Puts three's type flags (`isMesh`, `isCamera`, `isLight`, ...) on a back end's scene classes. A
232
278
  * subclass inherits its parent's through the prototype chain, as in three; a missing class is skipped.
@@ -235,12 +281,7 @@ export function defineTypeFlags(classes: Readonly<Record<string, unknown>>): voi
235
281
  for (const name of FLAGGED_CLASSES) {
236
282
  const cls = classes[name] as Constructor | undefined;
237
283
  if (typeof cls !== "function") continue;
238
- const flags = name.endsWith("Light")
239
- ? [`is${name}`, "isLight"]
240
- : name.endsWith("NodeMaterial")
241
- ? [`is${name}`, "isNodeMaterial"]
242
- : [`is${name}`];
243
- for (const flag of flags)
284
+ for (const flag of flagsOf(name))
244
285
  Object.defineProperty(cls.prototype, flag, {
245
286
  configurable: true,
246
287
  writable: true,