@threenative/core 0.3.11 → 0.3.12

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 (157) hide show
  1. package/capabilities.json +1096 -26
  2. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  3. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-CWuFRT7G.d.ts} +1 -1
  4. package/dist/chunk-2Z44XSI2.js +35 -0
  5. package/dist/chunk-5O73CDMR.js +1849 -0
  6. package/dist/chunk-6KLNISRJ.js +153 -0
  7. package/dist/chunk-7UUT3TY5.js +133 -0
  8. package/dist/chunk-CFGTPFUH.js +231 -0
  9. package/dist/chunk-DBELTTTM.js +615 -0
  10. package/dist/chunk-GMHATRPW.js +7701 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-KIRUKTBQ.js +187 -0
  13. package/dist/chunk-N5LRP4BR.js +220 -0
  14. package/dist/chunk-OKXUCASC.js +2238 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-VAZM36TV.js +497 -0
  17. package/dist/{game-DzMcitDO.d.ts → game-D7pAzZUY.d.ts} +15 -3
  18. package/dist/hot.d.ts +3 -3
  19. package/dist/hot.js +2 -46
  20. package/dist/index.d.ts +329 -302
  21. package/dist/index.js +10566 -22552
  22. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-B6BMqS1r.d.ts} +33 -3
  23. package/dist/playtest.d.ts +3 -3
  24. package/dist/playtest.js +24 -75
  25. package/dist/react-css.js +1 -215
  26. package/dist/react.d.ts +2 -2
  27. package/dist/{renderer-rZm0hVqq.d.ts → renderer-DvFVoAgj.d.ts} +13 -4
  28. package/dist/spells/index.d.ts +643 -0
  29. package/dist/spells/index.js +1558 -0
  30. package/dist/spells/ultra/index.d.ts +1600 -0
  31. package/dist/spells/ultra/index.js +6804 -0
  32. package/dist/terrain-jobs-worker.js +1 -123
  33. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  34. package/dist/ui-layer.js +5 -384
  35. package/dist/worker.js +4 -41
  36. package/dist/world.d.ts +725 -259
  37. package/dist/world.js +16714 -18284
  38. package/mcp/animation-server.mjs +1 -1
  39. package/mcp/animation.mjs +2 -3
  40. package/mcp/engine-server.mjs +142 -47
  41. package/mcp/servers.mjs +9 -2
  42. package/mcp/terrain.mjs +8 -0
  43. package/package.json +14 -6
  44. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  45. package/patches/three@0.187.0.patch +2004 -407
  46. package/src/assets.ts +9 -2
  47. package/src/card-lod.ts +152 -0
  48. package/src/compressed-texture-preparation.ts +1008 -0
  49. package/src/frame-budget.ts +31 -20
  50. package/src/game-dev-tools.ts +93 -0
  51. package/src/game-frame-loop.ts +995 -0
  52. package/src/game-renderer-metrics.ts +77 -0
  53. package/src/game-startup.ts +1001 -0
  54. package/src/game-validate.ts +70 -0
  55. package/src/game.ts +253 -1935
  56. package/src/index.ts +27 -2
  57. package/src/launch-diagnostics.ts +22 -12
  58. package/src/look/ao-admission.ts +24 -0
  59. package/src/look/filmic-tone-mapping.ts +15 -13
  60. package/src/look/look-diagnostics.ts +3 -3
  61. package/src/look/quality.ts +10 -5
  62. package/src/look/world-environment.ts +76 -9
  63. package/src/loop.ts +29 -0
  64. package/src/model-lod.ts +42 -3
  65. package/src/particle-kinds.ts +515 -0
  66. package/src/picking.ts +17 -3
  67. package/src/playtest.ts +27 -1
  68. package/src/projection-apply.ts +4 -1
  69. package/src/projection-plan.ts +9 -6
  70. package/src/render/mesh-pool.ts +1 -1
  71. package/src/render/resolution-subrect.ts +2 -0
  72. package/src/render/rough-diffuse.ts +46 -12
  73. package/src/render/soft-shadow.ts +27 -12
  74. package/src/render/virtual-shadow-adaptive.ts +55 -0
  75. package/src/render/virtual-shadow-casters.ts +175 -0
  76. package/src/render/virtual-shadow-layers.ts +76 -0
  77. package/src/render/virtual-shadow-level.ts +224 -0
  78. package/src/render/virtual-shadow-markers.ts +193 -0
  79. package/src/render/virtual-shadow-options.ts +370 -0
  80. package/src/render/virtual-shadow-pages.ts +5 -0
  81. package/src/render/virtual-shadow.ts +213 -992
  82. package/src/render/world-impostor-surface.ts +293 -34
  83. package/src/render-pass-budget.ts +34 -7
  84. package/src/renderProjection.ts +22 -0
  85. package/src/renderer.ts +92 -37
  86. package/src/snow-field.ts +1 -1
  87. package/src/spells/cast-pool.ts +361 -0
  88. package/src/spells/index.ts +177 -0
  89. package/src/spells/mechanisms.ts +295 -0
  90. package/src/spells/reaction-field.ts +415 -0
  91. package/src/spells/spell-lights.ts +139 -0
  92. package/src/spells/spell-world.ts +187 -0
  93. package/src/spells/spell.ts +397 -0
  94. package/src/spells/spells.ts +283 -0
  95. package/src/spells/ultra/engine/camera.ts +184 -0
  96. package/src/spells/ultra/engine/quality.ts +96 -0
  97. package/src/spells/ultra/index.ts +52 -0
  98. package/src/spells/ultra/main.ts +305 -0
  99. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  100. package/src/spells/ultra/spells/cast.ts +233 -0
  101. package/src/spells/ultra/spells/fire.ts +1267 -0
  102. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  103. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  104. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  105. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  106. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  107. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  108. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  109. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  110. package/src/spells/ultra/vfx/common.ts +1195 -0
  111. package/src/spells/ultra/vfx/noise.ts +441 -0
  112. package/src/startup-readiness.ts +128 -34
  113. package/src/version.ts +1 -1
  114. package/src/warmup.ts +56 -8
  115. package/src/water-surface.ts +9 -3
  116. package/src/world-bundle-safety.ts +401 -0
  117. package/src/world-cell-batches.ts +1216 -0
  118. package/src/world-cell-chunks.ts +1132 -0
  119. package/src/world-cell-data.ts +995 -0
  120. package/src/world-cell-impostors.ts +1449 -0
  121. package/src/world-cell-lod-bias.ts +151 -0
  122. package/src/world-cell-models.ts +1074 -0
  123. package/src/world-cell-options.ts +189 -0
  124. package/src/world-cell-placements.ts +694 -0
  125. package/src/world-cell-prewarm.ts +557 -0
  126. package/src/world-cell-readiness.ts +357 -0
  127. package/src/world-cell-render-bundles.ts +459 -0
  128. package/src/world-cell-render-gpu-dress.ts +714 -0
  129. package/src/world-cell-render-main-cull.ts +484 -0
  130. package/src/world-cell-render-shadow-claims.ts +198 -0
  131. package/src/world-cell-render-util.ts +246 -0
  132. package/src/world-cell-render.ts +1493 -0
  133. package/src/world-cell-residency.ts +745 -0
  134. package/src/world-cells.ts +1318 -10418
  135. package/src/world-chunk-shadow.ts +308 -0
  136. package/src/world-collar.ts +315 -0
  137. package/src/world-gpu-flags.ts +163 -0
  138. package/src/world-gpu-readback.ts +881 -0
  139. package/src/world-gpu-reference.ts +510 -0
  140. package/src/world-gpu-scene.ts +214 -2264
  141. package/src/world-gpu-shadow.ts +190 -0
  142. package/src/world-gpu-types.ts +381 -0
  143. package/src/world-gpu-validation.ts +518 -0
  144. package/src/world-heightfield.ts +802 -0
  145. package/src/world-load-limiter.ts +106 -0
  146. package/src/world-noise.ts +241 -0
  147. package/src/world-package.ts +42 -0
  148. package/src/world-region.ts +1 -1
  149. package/src/world-terrain-splat.ts +365 -149
  150. package/src/world-tile-budget.ts +256 -0
  151. package/src/world-tile-geometry.ts +469 -0
  152. package/src/world-tile-lod.ts +408 -0
  153. package/src/world-tile-observation.ts +566 -0
  154. package/src/world-tile-stitch.ts +166 -0
  155. package/src/world-tiles.ts +170 -1745
  156. package/src/world-water-bodies.ts +359 -0
  157. package/src/world.ts +35 -741
@@ -0,0 +1,46 @@
1
+ import { vec3, materialEmissive, normalView, positionViewDirection, float, uniform } from 'three/tsl';
2
+
3
+ // src/render/two-sided-foliage.ts
4
+ function addFoliageBackLight(material, backIrradiance) {
5
+ const colour = material.subsurfaceColor;
6
+ if (material.twoSidedFoliage !== true || colour === void 0) return false;
7
+ const back = vec3(colour.r, colour.g, colour.b).mul(backIrradiance);
8
+ const target = material;
9
+ target.emissiveNode = (target.emissiveNode ?? materialEmissive).add(back);
10
+ return true;
11
+ }
12
+ function foliageTransmission(lightDirection, lightColor, subsurface) {
13
+ const wrap = normalView.dot(lightDirection).negate().add(0.5).div(2.25).clamp();
14
+ const cosine = positionViewDirection.dot(lightDirection).negate().clamp();
15
+ const denominator = float(1).sub(cosine.mul(cosine).mul(0.64));
16
+ const scatter = float(0.36 / Math.PI).div(denominator.mul(denominator));
17
+ return lightColor.mul(wrap.mul(scatter)).mul(subsurface);
18
+ }
19
+ var PATCHED = /* @__PURE__ */ Symbol.for("threenative.foliageTransmission");
20
+ function installFoliageTransmission(classes) {
21
+ let patched = 0;
22
+ for (const name of ["MeshStandardNodeMaterial", "MeshPhysicalNodeMaterial"]) {
23
+ const prototype = classes[name]?.prototype;
24
+ const setup = prototype?.setupLightingModel;
25
+ if (prototype === void 0 || typeof setup !== "function" || Object.hasOwn(prototype, PATCHED))
26
+ continue;
27
+ prototype.setupLightingModel = function(builder) {
28
+ const model = setup.call(this, builder);
29
+ if (this.twoSidedFoliage !== true || this.subsurfaceColor === void 0) return model;
30
+ const direct = model.direct.bind(model);
31
+ const subsurface = uniform(this.subsurfaceColor);
32
+ model.direct = (input, inner) => {
33
+ direct(input, inner);
34
+ input.reflectedLight.directDiffuse.addAssign(
35
+ foliageTransmission(input.lightDirection, input.lightColor, subsurface)
36
+ );
37
+ };
38
+ return model;
39
+ };
40
+ prototype[PATCHED] = true;
41
+ patched++;
42
+ }
43
+ return patched;
44
+ }
45
+
46
+ export { addFoliageBackLight, foliageTransmission, installFoliageTransmission };
@@ -0,0 +1,187 @@
1
+ // src/terrain-jobs.ts
2
+ function mergeBlockAttributes(job) {
3
+ let vertexCount = 0;
4
+ let indexCount = 0;
5
+ for (const part of job.parts) {
6
+ vertexCount += part.positions.length / 3;
7
+ indexCount += part.indices.length;
8
+ }
9
+ const positions = new Float32Array(vertexCount * 3);
10
+ const normals = new Float32Array(vertexCount * 3);
11
+ const indices = new Uint32Array(indexCount);
12
+ let vertexOffset = 0;
13
+ let indexOffset = 0;
14
+ for (const part of job.parts) {
15
+ const dx = part.origin.x - job.blockOrigin.x;
16
+ const dz = part.origin.z - job.blockOrigin.z;
17
+ const count = part.positions.length / 3;
18
+ for (let vertex = 0; vertex < count; vertex += 1) {
19
+ const at = (vertexOffset + vertex) * 3;
20
+ const from = vertex * 3;
21
+ positions[at] = part.positions[from] + dx;
22
+ positions[at + 1] = part.positions[from + 1];
23
+ positions[at + 2] = part.positions[from + 2] + dz;
24
+ normals[at] = part.normals[from];
25
+ normals[at + 1] = part.normals[from + 1];
26
+ normals[at + 2] = part.normals[from + 2];
27
+ }
28
+ for (let element = 0; element < part.indices.length; element += 1)
29
+ indices[indexOffset + element] = part.indices[element] + vertexOffset;
30
+ vertexOffset += count;
31
+ indexOffset += part.indices.length;
32
+ }
33
+ return { indices, kind: "merge", normals, positions };
34
+ }
35
+ function interpolatedEdgeSample(samples, normalized, name) {
36
+ const position = Math.max(0, Math.min(1, normalized)) * (samples.length - 1);
37
+ const lower = Math.floor(position);
38
+ const upper = Math.min(samples.length - 1, lower + 1);
39
+ const mix = position - lower;
40
+ const lowerValue = samples[lower];
41
+ const upperValue = samples[upper];
42
+ if (!Number.isFinite(lowerValue) || !Number.isFinite(upperValue))
43
+ throw new Error(`TerrainTiles retained ${name} edge sample must be finite.`);
44
+ return lowerValue * (1 - mix) + upperValue * mix;
45
+ }
46
+ function edgeWorldPoint(edge, normalized, height) {
47
+ const minimumX = edge.origin.x - edge.width / 2;
48
+ const minimumZ = edge.origin.z - edge.depth / 2;
49
+ const x = edge.side === "west" ? minimumX : edge.side === "east" ? minimumX + edge.width : minimumX + normalized * edge.width;
50
+ const z = edge.side === "north" ? minimumZ : edge.side === "south" ? minimumZ + edge.depth : minimumZ + normalized * edge.depth;
51
+ return [x, height, z];
52
+ }
53
+ function stitchBridgeAttributes(fine, coarse) {
54
+ const positions = new Float32Array(fine.resolution * 6);
55
+ const normals = new Float32Array(fine.resolution * 6);
56
+ const indices = new Uint32Array((fine.resolution - 1) * 12);
57
+ let coverageDepth = 0;
58
+ for (let index = 0; index < fine.resolution; index += 1) {
59
+ const normalized = index / (fine.resolution - 1);
60
+ const fineHeight = interpolatedEdgeSample(
61
+ fine.samples,
62
+ normalized,
63
+ `${fine.side} of finer LOD`
64
+ );
65
+ const coarseHeight = interpolatedEdgeSample(
66
+ coarse.samples,
67
+ normalized,
68
+ `${coarse.side} of coarser LOD`
69
+ );
70
+ coverageDepth = Math.max(coverageDepth, Math.abs(fineHeight - coarseHeight));
71
+ const at = index * 6;
72
+ const finePoint = edgeWorldPoint(fine, normalized, fineHeight);
73
+ const coarsePoint = edgeWorldPoint(coarse, normalized, coarseHeight);
74
+ positions[at] = finePoint[0];
75
+ positions[at + 1] = finePoint[1];
76
+ positions[at + 2] = finePoint[2];
77
+ positions[at + 3] = coarsePoint[0];
78
+ positions[at + 4] = coarsePoint[1];
79
+ positions[at + 5] = coarsePoint[2];
80
+ normals[at] = 0;
81
+ normals[at + 1] = 1;
82
+ normals[at + 2] = 0;
83
+ normals[at + 3] = 0;
84
+ normals[at + 4] = 1;
85
+ normals[at + 5] = 0;
86
+ }
87
+ for (let index = 0; index < fine.resolution - 1; index += 1) {
88
+ const fine2 = index * 2;
89
+ const coarse2 = fine2 + 1;
90
+ const nextFine = fine2 + 2;
91
+ const nextCoarse = coarse2 + 2;
92
+ const at = index * 12;
93
+ indices[at] = fine2;
94
+ indices[at + 1] = coarse2;
95
+ indices[at + 2] = nextFine;
96
+ indices[at + 3] = nextFine;
97
+ indices[at + 4] = coarse2;
98
+ indices[at + 5] = nextCoarse;
99
+ indices[at + 6] = nextFine;
100
+ indices[at + 7] = coarse2;
101
+ indices[at + 8] = fine2;
102
+ indices[at + 9] = nextCoarse;
103
+ indices[at + 10] = coarse2;
104
+ indices[at + 11] = nextFine;
105
+ }
106
+ return { coverageDepth, indices, normals, positions };
107
+ }
108
+ function runTerrainJob(job) {
109
+ if (job.kind === "merge") return mergeBlockAttributes(job);
110
+ return {
111
+ bridges: job.pairs.map(({ coarse, fine }) => stitchBridgeAttributes(fine, coarse)),
112
+ kind: "seam"
113
+ };
114
+ }
115
+ function terrainJobTransfers(result) {
116
+ if (result.kind === "merge")
117
+ return [result.positions.buffer, result.normals.buffer, result.indices.buffer];
118
+ return result.bridges.flatMap((bridge) => [
119
+ bridge.positions.buffer,
120
+ bridge.normals.buffer,
121
+ bridge.indices.buffer
122
+ ]);
123
+ }
124
+ function spawnTerrainWorker() {
125
+ if (typeof Worker === "undefined") return { reason: "no Worker on this host", worker: void 0 };
126
+ try {
127
+ const worker = new Worker(new URL("./terrain-jobs-worker.js", import.meta.url), {
128
+ type: "module"
129
+ });
130
+ return { reason: void 0, worker };
131
+ } catch (error) {
132
+ const message = error instanceof Error ? error.message : String(error);
133
+ return { reason: `module worker refused: ${message}`, worker: void 0 };
134
+ }
135
+ }
136
+ function createTerrainJobRunner() {
137
+ const pending = /* @__PURE__ */ new Map();
138
+ let nextId = 0;
139
+ const spawned = spawnTerrainWorker();
140
+ let worker = spawned.worker;
141
+ const abandon = () => {
142
+ for (const [, job] of pending) job.resolve(job.compute());
143
+ pending.clear();
144
+ worker?.terminate();
145
+ worker = void 0;
146
+ };
147
+ if (worker !== void 0) {
148
+ worker.onmessage = (event) => {
149
+ const reply = event.data;
150
+ pending.get(reply.id)?.resolve(reply.result);
151
+ pending.delete(reply.id);
152
+ };
153
+ worker.onerror = abandon;
154
+ }
155
+ const dispatch = (job, compute) => {
156
+ const active = worker;
157
+ if (active === void 0) return compute();
158
+ const id = nextId;
159
+ nextId += 1;
160
+ const sent = new Promise((resolve) => {
161
+ pending.set(id, {
162
+ compute,
163
+ resolve
164
+ });
165
+ });
166
+ try {
167
+ active.postMessage({ id, job });
168
+ } catch {
169
+ pending.delete(id);
170
+ return compute();
171
+ }
172
+ return sent;
173
+ };
174
+ return {
175
+ dispose: () => {
176
+ pending.clear();
177
+ worker?.terminate();
178
+ worker = void 0;
179
+ },
180
+ inlineReason: spawned.reason,
181
+ merge: (job) => dispatch(job, () => runTerrainJob(job)),
182
+ offThread: worker !== void 0,
183
+ seam: (job) => dispatch(job, () => runTerrainJob(job))
184
+ };
185
+ }
186
+
187
+ export { createTerrainJobRunner, edgeWorldPoint, runTerrainJob, terrainJobTransfers };
@@ -0,0 +1,220 @@
1
+ // src/profiling/debug-telemetry.ts
2
+ var CONTENT_SCALED_LIMIT = 10;
3
+ function isContentScaled(name) {
4
+ return name.startsWith("bridge:") || /^(?:assetDispatch|assetLoad|textureDecode)\./u.test(name);
5
+ }
6
+ var DEBUG_GLOBAL = "__THREENATIVE_DEBUG__";
7
+ function debugRequested() {
8
+ const host = globalThis;
9
+ return host.process?.env?.TN_DEBUG === "1" || globalThis[DEBUG_GLOBAL] === true || /[?&]tnDebug=1(?:&|$)/u.test(globalThis.location?.search ?? "");
10
+ }
11
+ function countDebug(name, value, area, caller, unit = "count") {
12
+ if (!Number.isFinite(value) || value < 0)
13
+ throw new Error(`TN_DEBUG: invalid ${name} observation.`);
14
+ const host = globalThis;
15
+ host.__tnEngineCost ??= {};
16
+ host.__tnDebugSources ??= {};
17
+ host.__tnEngineCost[name] = (host.__tnEngineCost[name] ?? 0) + value;
18
+ host.__tnDebugSources[name] ??= { area, caller, unit };
19
+ }
20
+ function measureDebug(name, area, caller, run) {
21
+ const start = performance.now();
22
+ try {
23
+ return run();
24
+ } finally {
25
+ countDebug(`${name}Ms`, performance.now() - start, area, caller, "ms");
26
+ countDebug(`${name}Calls`, 1, area, caller);
27
+ }
28
+ }
29
+ function observeDebugGc() {
30
+ if (!globalThis.PerformanceObserver?.supportedEntryTypes?.includes("gc")) return void 0;
31
+ const observer = new PerformanceObserver((list) => {
32
+ for (const entry of list.getEntries()) {
33
+ countDebug("gcPauses", 1, "memory", "PerformanceObserver.gc");
34
+ countDebug("gcPauseMs", entry.duration, "memory", "PerformanceObserver.gc", "ms");
35
+ }
36
+ });
37
+ observer.observe({ type: "gc" });
38
+ return () => observer.disconnect();
39
+ }
40
+ function sourceOf(name) {
41
+ const source = globalThis.__tnDebugSources?.[name];
42
+ if (source !== void 0)
43
+ return { ...source, unit: source.unit ?? (name.endsWith("Ms") ? "ms" : "count") };
44
+ const areas = [
45
+ [/bridge|children|wrapper|share|scratch|widen|overflow/iu, "bridge"],
46
+ [/velocity|temporal|history|rejected|clamped/iu, "temporal"],
47
+ [
48
+ /heap|memory|live|released|allocated|gc|CreatedBytes|FreedBytes|handleCreates|handleReleases/iu,
49
+ "memory"
50
+ ],
51
+ [/gpu|map|timestamp|gate|submit|completion/iu, "gpu"],
52
+ [/matrix|travers|transform|hierarchy|walk/iu, "scene"]
53
+ ];
54
+ const area = areas.find(([pattern]) => pattern.test(name))?.[1] ?? "renderer";
55
+ const nativeCallers = [
56
+ [/^gate/u, "renderer/frame_gate.h:FrameGate::decline"],
57
+ [/^(pipeline|bindGroups)/u, "renderer/pipeline_cache.cpp"],
58
+ [/^(buffer|texture|queue|readback)/u, "renderer/gpu_resources.cpp"],
59
+ [/^handle/u, "foundation/handles.cpp"],
60
+ [
61
+ /^(velocity|temporal|timestamp|gpuTimestamp|render|shadow|aux|uniform|attribute)/u,
62
+ "renderer/renderer.cpp"
63
+ ],
64
+ [/^cull/u, "scene/projected_cull.cpp"],
65
+ [/scene|matrix|hierarchy/iu, "scene/object3d.cpp"]
66
+ ];
67
+ const site = nativeCallers.find(([pattern]) => pattern.test(name))?.[1];
68
+ const async = /queueCallback|queueDelivery/iu.test(name);
69
+ return {
70
+ area,
71
+ caller: /^gc/u.test(name) ? `packages/runtime-native/src/adapters/v8/adapter.cpp (${name})` : site === void 0 ? `engine counter: ${name}` : `packages/runtime-native/src/engine/${site} (${name})`,
72
+ unit: async ? "async-ms" : name.endsWith("Ms") ? "ms" : "count"
73
+ };
74
+ }
75
+ function leverOf(area) {
76
+ const anchor = {
77
+ bridge: "2026-10-27--web-engine-bridge-keep-what-game-code-reads-again-three-native-back-end--keep",
78
+ renderer: "2026-10-27--wasted-work-on-the-shooter-counted-by-class--diagnostic-2-of-6-classes-have-a-fix-in-another-lane",
79
+ scene: "2026-10-27--a-scratch-objects-death-leaves-the-hierarchy-counter-alone-native-engine--keep",
80
+ ui: "2026-10-14--publishuistate-serializes-a-changed-hud-frame-once-instead-of-three-times--keep",
81
+ update: "2026-10-27--rapier-step-grew-from-21-to-34-66-ms-a-frame-in-profiler-round-2--not-a-cause-host-load",
82
+ host: "method-lessons"
83
+ };
84
+ return anchor[area] === void 0 ? void 0 : `PERFORMANCE-LEARNINGS.md#${anchor[area]}`;
85
+ }
86
+ function formatDebugReport(window) {
87
+ const interval = window.presented.samples > 0 && window.presented.mean > 0 ? window.presented.mean : void 0;
88
+ const engine = window.counters?.engine ?? {};
89
+ const durationMs = window.durationMs;
90
+ const observations = Object.fromEntries(
91
+ Object.entries(engine).map(([name, series]) => {
92
+ if (!Number.isFinite(series.mean) || series.mean < 0)
93
+ throw new Error(`TN_DEBUG: invalid ${name} series.`);
94
+ const source = sourceOf(name);
95
+ const rate = source.unit === "count" || source.unit?.endsWith("bytes");
96
+ return [
97
+ name,
98
+ {
99
+ ...series,
100
+ ...source,
101
+ ...rate ? {
102
+ perSecond: durationMs !== void 0 && durationMs > 0 && series.samples === window.frames ? series.mean * series.samples * 1e3 / durationMs : null
103
+ } : {}
104
+ }
105
+ ];
106
+ })
107
+ );
108
+ const offenders = [];
109
+ const add = (name, ms, source, basis) => {
110
+ if (ms <= 0) return;
111
+ const lever = source.lever ?? leverOf(source.area);
112
+ offenders.push({
113
+ name,
114
+ ms,
115
+ area: source.area,
116
+ caller: source.caller,
117
+ share: interval === void 0 ? null : ms / interval,
118
+ basis,
119
+ ...lever === void 0 ? {} : { lever }
120
+ });
121
+ };
122
+ for (const [name, series] of Object.entries(engine)) {
123
+ const source = sourceOf(name);
124
+ if (source.unit === "ms" || source.unit === "estimated-ms")
125
+ add(
126
+ name,
127
+ series.mean,
128
+ source,
129
+ source.unit === "estimated-ms" ? "estimated-getter-equivalent" : "measured"
130
+ );
131
+ }
132
+ for (const [name, series] of Object.entries(window.phases))
133
+ add(
134
+ `phase.${name}`,
135
+ series.mean,
136
+ { area: name === "hostGap" ? "host" : name, caller: "FixedStepLoop"},
137
+ "measured-parent"
138
+ );
139
+ for (const [name, ms] of [
140
+ ["main", window.gpuMain],
141
+ ["shadow", window.gpuShadow],
142
+ ["other", window.gpuOther],
143
+ ["compute", window.gpuCompute]
144
+ ])
145
+ if (ms !== void 0)
146
+ add(
147
+ `gpu.${name}`,
148
+ ms,
149
+ { area: "gpu", caller: "GPU timestamp query"},
150
+ "gpu-execution"
151
+ );
152
+ offenders.sort((a, b) => (b.share ?? -1) - (a.share ?? -1) || a.name.localeCompare(b.name));
153
+ const findings = [];
154
+ const total = (name) => {
155
+ const series = engine[name];
156
+ return series === void 0 ? void 0 : series.mean * series.samples;
157
+ };
158
+ const ratio = (code, numerator, denominator, limit) => {
159
+ const n = total(numerator);
160
+ const d = total(denominator);
161
+ if (n === void 0 || d === void 0 || d <= 0 || n / d <= limit) return;
162
+ const source = sourceOf(numerator);
163
+ const timing = engine[`${numerator}Ms`];
164
+ const lever = source.lever ?? leverOf(source.area);
165
+ findings.push({
166
+ code,
167
+ ratio: n / d,
168
+ share: timing === void 0 || interval === void 0 ? null : timing.mean / interval,
169
+ caller: source.caller,
170
+ ...lever === void 0 ? {} : { lever }
171
+ });
172
+ };
173
+ ratio("temporal-missing-velocity", "velocitySkipped", "velocityCandidates", 0);
174
+ ratio("temporal-history-unavailable", "temporalInvalidFrames", "temporalActiveFrames", 0);
175
+ const activity = (code, counter) => {
176
+ const value = engine[counter]?.mean;
177
+ if (value === void 0 || value <= 0) return;
178
+ const source = sourceOf(counter);
179
+ const lever = source.lever ?? leverOf(source.area);
180
+ findings.push({
181
+ code,
182
+ perFrame: value,
183
+ share: null,
184
+ caller: source.caller,
185
+ ...lever === void 0 ? {} : { lever }
186
+ });
187
+ };
188
+ activity("timestamp-oversampling", "gpuTimestampUnrequestedSamples");
189
+ activity("bridge-arena-overflow", "bridgeOverflowAllocations");
190
+ activity("gate-capacity-decline", "gateDeclinedCapacity");
191
+ activity("gate-completion-age-decline", "gateDeclinedAge");
192
+ ratio("bridge-typed-array-widening", "bridgeTypedEncodedBytes", "bridgeTypedSourceBytes", 1);
193
+ const host = globalThis;
194
+ const contentScaled = Object.entries({ ...host.__tnEngineCounters?.(), ...host.__tnEngineCost }).filter(([name, total2]) => {
195
+ if (!isContentScaled(name)) return false;
196
+ if (!Number.isFinite(total2) || total2 < 0)
197
+ throw new Error(`TN_DEBUG: invalid ${name} counter.`);
198
+ return total2 > 0;
199
+ }).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, CONTENT_SCALED_LIMIT).map(([name, total2]) => ({ name, total: total2, ...sourceOf(name) }));
200
+ return `TN_DEBUG_REPORT:${JSON.stringify({ window: window.window, frames: window.frames, durationMs: durationMs ?? null, intervalMs: interval ?? null, offenders, findings, observations, contentScaled: { basis: "run-total", top: contentScaled }, longTasks: window.longTasks, gpu: window.gpu, passes: window.passes })}`;
201
+ }
202
+ function debugHotCalls(window) {
203
+ const interval = window.presented.mean;
204
+ if (!(interval > 0)) return void 0;
205
+ const calls = Object.entries(window.counters?.engine ?? {}).flatMap(([name, series]) => {
206
+ const source = sourceOf(name);
207
+ return source.area === "update" && source.unit === "ms" && series.p95 > interval ? [
208
+ {
209
+ name,
210
+ caller: source.caller,
211
+ ms: series.p95,
212
+ share: series.p95 / interval,
213
+ lever: source.lever ?? leverOf(source.area)
214
+ }
215
+ ] : [];
216
+ }).sort((a, b) => b.share - a.share);
217
+ return calls.length === 0 ? void 0 : `TN_HOT_CALL:${JSON.stringify({ window: window.window, intervalMs: interval, calls })}`;
218
+ }
219
+
220
+ export { countDebug, debugHotCalls, debugRequested, formatDebugReport, isContentScaled, measureDebug, observeDebugGc };