@threenative/core 0.3.12 → 0.3.15

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 (165) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1047 -44
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-2GPHICV6.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
  7. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  8. package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
  9. package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
  10. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  11. package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
  12. package/dist/chunk-VP43GIWW.js +18 -0
  13. package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +871 -1018
  20. package/dist/index.js +4786 -1631
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BADStsTn.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +280 -16
  33. package/dist/world.js +1529 -642
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +135 -11
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/scripts/ensure-mcp.mjs +6 -1
  39. package/src/animation-batch.ts +193 -0
  40. package/src/animation-layers.ts +7 -3
  41. package/src/animation.ts +209 -29
  42. package/src/asset-cache.ts +3 -3
  43. package/src/asset-memo.ts +202 -0
  44. package/src/assets.ts +436 -131
  45. package/src/auto-batch.ts +190 -44
  46. package/src/clustered-batch.ts +146 -3
  47. package/src/clustered-mesh.ts +548 -20
  48. package/src/compute-driven.ts +1 -1
  49. package/src/config.ts +8 -0
  50. package/src/debug.ts +119 -22
  51. package/src/dev-global.ts +54 -0
  52. package/src/displaced-surface.ts +428 -0
  53. package/src/engine-hooks.ts +37 -0
  54. package/src/frame-budget.ts +35 -3
  55. package/src/game-boot-phase.ts +269 -0
  56. package/src/game-dev-tools.ts +7 -14
  57. package/src/game-frame-loop.ts +45 -82
  58. package/src/game-startup.ts +145 -70
  59. package/src/game-ui.ts +84 -0
  60. package/src/game.ts +168 -552
  61. package/src/gamepad-mappings.ts +269 -0
  62. package/src/generated/console-markers.ts +14 -0
  63. package/src/geometry-capture.ts +28 -4
  64. package/src/gpu-readings.ts +98 -0
  65. package/src/gpu-scene-bvh.ts +149 -36
  66. package/src/grass-field.ts +628 -0
  67. package/src/hot.ts +4 -7
  68. package/src/index.ts +227 -8
  69. package/src/input.ts +237 -25
  70. package/src/instanced-batch-lod.ts +3 -8
  71. package/src/interpolation.ts +171 -40
  72. package/src/look/ao-admission.ts +4 -3
  73. package/src/look/auto-exposure.ts +5 -16
  74. package/src/look/default-tone-mapping.ts +41 -5
  75. package/src/look/local-exposure.ts +2 -7
  76. package/src/look/quad-pass.ts +21 -0
  77. package/src/look/quality.ts +4 -0
  78. package/src/look/unreal-bloom.ts +4 -13
  79. package/src/look/world-environment.ts +58 -115
  80. package/src/merge-parts.ts +20 -24
  81. package/src/model-lod.ts +97 -14
  82. package/src/particle-significance.ts +12 -0
  83. package/src/particles.ts +19 -10
  84. package/src/platform.ts +23 -4
  85. package/src/profiling/FrameStages.ts +5 -6
  86. package/src/profiling/Spans.ts +3 -17
  87. package/src/profiling/debug-telemetry.ts +2 -6
  88. package/src/profiling/render-list-validate.ts +6 -15
  89. package/src/projection-marker.ts +2 -1
  90. package/src/quiet-markers.ts +3 -10
  91. package/src/render/cpu-bvh.ts +100 -0
  92. package/src/render/depth-pyramid.ts +6 -14
  93. package/src/render/environment/environmentContribution.ts +202 -0
  94. package/src/render/environment/environmentRadiance.ts +44 -0
  95. package/src/render/environment/environmentSampleCache.ts +56 -0
  96. package/src/render/environment/environmentSampling.ts +201 -0
  97. package/src/render/environment/environmentSnapshot.ts +71 -0
  98. package/src/render/environment/gate.ts +57 -0
  99. package/src/render/material-key.ts +21 -1
  100. package/src/render/mesh-pool.ts +3 -19
  101. package/src/render/probe-trace.ts +872 -0
  102. package/src/render/probe-volume.ts +780 -34
  103. package/src/render/radiance-cache.ts +17 -0
  104. package/src/render/screen-probe-gather.ts +303 -0
  105. package/src/render/short-range-ao.ts +274 -0
  106. package/src/render/virtual-shadow-partial.ts +13 -0
  107. package/src/render/virtual-shadow.ts +18 -16
  108. package/src/render/world-impostor-surface.ts +207 -9
  109. package/src/render/world-impostor.ts +5 -2
  110. package/src/render-camera-cull.ts +105 -4
  111. package/src/render-environment.ts +41 -0
  112. package/src/renderer-config.ts +36 -0
  113. package/src/renderer-facts.ts +37 -0
  114. package/src/renderer.ts +78 -32
  115. package/src/resolution-scaler.ts +3 -2
  116. package/src/scatter-field.ts +496 -0
  117. package/src/scene-entry-inspectors.ts +61 -0
  118. package/src/snow-field.ts +1 -0
  119. package/src/startup-offscreen-bytes.ts +84 -0
  120. package/src/state.ts +16 -3
  121. package/src/static-transform.ts +100 -25
  122. package/src/streamed-textures.ts +112 -0
  123. package/src/streaming.ts +68 -4
  124. package/src/texture-streaming.ts +331 -0
  125. package/src/tile-ring.ts +294 -0
  126. package/src/version.ts +1 -1
  127. package/src/warmup.ts +15 -2
  128. package/src/worker.ts +12 -2
  129. package/src/world-bundle-safety.ts +55 -10
  130. package/src/world-cell-batches.ts +166 -200
  131. package/src/world-cell-chunks.ts +3 -7
  132. package/src/world-cell-data.ts +7 -0
  133. package/src/world-cell-impostors.ts +20 -8
  134. package/src/world-cell-models.ts +36 -8
  135. package/src/world-cell-options.ts +2 -14
  136. package/src/world-cell-placements.ts +194 -90
  137. package/src/world-cell-prewarm.ts +39 -4
  138. package/src/world-cell-records.ts +401 -0
  139. package/src/world-cell-render-bundles.ts +2 -2
  140. package/src/world-cell-render-gpu-dress.ts +17 -19
  141. package/src/world-cell-render-main-cull.ts +73 -17
  142. package/src/world-cell-render-util.ts +18 -5
  143. package/src/world-cell-render.ts +13 -5
  144. package/src/world-cell-residency.ts +15 -6
  145. package/src/world-cell-stale.ts +238 -0
  146. package/src/world-cells.ts +23 -6
  147. package/src/world-gpu-flags.ts +18 -50
  148. package/src/world-gpu-reference.ts +22 -8
  149. package/src/world-gpu-scene.ts +44 -24
  150. package/src/world-gpu-shadow.ts +21 -8
  151. package/src/world-gpu-types.ts +41 -13
  152. package/src/world-load-limiter.ts +5 -0
  153. package/src/world-model-sections.ts +80 -0
  154. package/src/world-river-ribbon.ts +273 -0
  155. package/src/world-root-frame.ts +39 -0
  156. package/src/world-shore-field.ts +91 -0
  157. package/src/world-static-pose.ts +163 -0
  158. package/src/world-surface-sampler.ts +48 -0
  159. package/src/world-terrain-splat.ts +10 -18
  160. package/src/world-tile-budget.ts +4 -11
  161. package/src/world-tiles.ts +79 -12
  162. package/src/world-validate.ts +6 -14
  163. package/src/world-warm.ts +51 -0
  164. package/src/world-water-bodies.ts +113 -3
  165. package/src/world.ts +13 -0
@@ -1,3 +1,4 @@
1
+ import { readLaunchFlag } from "../debug.js";
1
2
  // Generated for you: ordinary Three.js; ThreeNative does not read this file. Delete or
2
3
  // rewrite it freely — every default in here is a starting point, not a framework look.
3
4
  //
@@ -14,13 +15,9 @@
14
15
  // tier. Those are arguments, supplied by `postprocessing.ts`, yours to change.
15
16
 
16
17
  import {
17
- ACESFilmicToneMapping,
18
- AgXToneMapping,
19
18
  type Camera,
20
- CustomToneMapping,
21
19
  type DirectionalLight,
22
20
  MaterialBlending,
23
- NeutralToneMapping,
24
21
  type PerspectiveCamera,
25
22
  type RenderTarget,
26
23
  type Scene,
@@ -39,7 +36,6 @@ import { sharpen } from "three/addons/tsl/display/SharpenNode.js";
39
36
  import { traa } from "three/addons/tsl/display/TRAANode.js";
40
37
  import {
41
38
  Fn,
42
- If,
43
39
  color,
44
40
  convertToTexture,
45
41
  cross,
@@ -76,17 +72,23 @@ import {
76
72
  } from "../render/chain.js";
77
73
  import { GIVisualize, type GIVisualizeMode } from "../render/gi-visualize.js";
78
74
  import type { TracedReflections } from "../render/traced-reflections.js";
75
+ import { rendererFacts } from "../renderer-facts.js";
79
76
  import { STARTUP_EXPOSURE } from "../renderer.js";
80
77
  import { aoRefusal } from "./ao-admission.js";
81
78
  import { AO_MULTIBOUNCE_FIT, UNREAL_AO_MULTIBOUNCE_ALBEDO } from "./ao-multibounce.js";
82
79
  import { UNREAL_AO_REACH_PX } from "./ao-reach.js";
83
80
  import { AutoExposureNode, applyExposure } from "./auto-exposure.js";
81
+ import {
82
+ RENDERER_TONE_MAPPINGS,
83
+ type RendererToneMapping,
84
+ applyRendererToneMapping,
85
+ isRendererToneMapping,
86
+ } from "./default-tone-mapping.js";
84
87
  import { type IExposureSettings, exposureSettings } from "./exposure-settings.js";
85
88
  import {
86
89
  type ColorGradeOptions,
87
90
  FILMIC_CURVE,
88
91
  type IFilmicCurve,
89
- installFilmicToneMapping,
90
92
  resolveColorGrade,
91
93
  } from "./filmic-tone-mapping.js";
92
94
  import { cacheFallback, giCache } from "./gi-registry.js";
@@ -111,9 +113,10 @@ export type ScreenSpaceAA = "smaa" | "fxaa" | "disabled";
111
113
 
112
114
  /**
113
115
  * Godot's `Environment.tonemap_mode`: the modes Three.js ships, plus `filmic`, the Unreal 5
114
- * default curve written in `tonemap.ts`.
116
+ * default curve written in `tonemap.ts`. The list itself is `RendererToneMapping`'s, one owner
117
+ * beside `applyRendererToneMapping`, so a mode this accepts is a mode the renderer can install.
115
118
  */
116
- export type TonemapMode = "aces" | "agx" | "filmic" | "neutral";
119
+ export type TonemapMode = RendererToneMapping;
117
120
 
118
121
  /**
119
122
  * SSGI sample budget. The three tiers are the presets SSGINode's own documentation
@@ -132,13 +135,6 @@ const SSGI_QUALITY: Record<SsgiQuality, { sliceCount: number; stepCount: number
132
135
  epic: { sliceCount: 8, stepCount: 16 },
133
136
  };
134
137
 
135
- const TONEMAP: Record<TonemapMode, number> = {
136
- aces: ACESFilmicToneMapping,
137
- agx: AgXToneMapping,
138
- filmic: CustomToneMapping,
139
- neutral: NeutralToneMapping,
140
- };
141
-
142
138
  /**
143
139
  * Whether this launch draws the transparent draws' own target (see `seesThrough` below).
144
140
  *
@@ -149,17 +145,10 @@ const TONEMAP: Record<TonemapMode, number> = {
149
145
  * running the same pose both ways.
150
146
  */
151
147
  export function translucentTargetWanted(): boolean {
152
- const host = globalThis as { process?: { env?: Record<string, unknown> } } & Record<
153
- string,
154
- unknown
155
- >;
156
- const fromEnv = host.process?.env?.TN_TRANSLUCENT;
157
- if (fromEnv === "0" || fromEnv === "false") return false;
158
- const query = globalThis.location?.search;
159
- if (typeof query === "string" && /[?&]tnTranslucent=(?:0|false)(?:&|$)/u.test(query))
160
- return false;
161
- const set = host.__tnTranslucent;
162
- return !(set === false || set === 0 || set === "0" || set === "false");
148
+ return !readLaunchFlag(
149
+ { environment: "TN_TRANSLUCENT", global: "__tnTranslucent", query: "tnTranslucent" },
150
+ "off",
151
+ );
163
152
  }
164
153
 
165
154
  /**
@@ -790,10 +779,10 @@ export class WorldEnvironment {
790
779
  `Unknown ssgiQuality '${String(quality)}'. Use one of: ${Object.keys(SSGI_QUALITY).join(", ")}.`,
791
780
  );
792
781
  }
793
- const tonemapMode = options.tonemapMode ?? "aces";
794
- if (TONEMAP[tonemapMode] === undefined) {
782
+ const tonemapMode = options.tonemapMode ?? "filmic";
783
+ if (!isRendererToneMapping(tonemapMode)) {
795
784
  throw new Error(
796
- `Unknown tonemapMode '${String(tonemapMode)}'. Use one of: ${Object.keys(TONEMAP).join(", ")}.`,
785
+ `Unknown tonemapMode '${String(tonemapMode)}'. Use one of: ${RENDERER_TONE_MAPPINGS.join(", ")}.`,
797
786
  );
798
787
  }
799
788
  resolveColorGrade(options.colorGrade);
@@ -918,31 +907,21 @@ export class WorldEnvironment {
918
907
  ? this.#options
919
908
  : { ...this.#options, autoExposureEnabled: false };
920
909
  const raw = renderer.raw as { toneMapping?: number; toneMappingExposure?: number };
921
- raw.toneMapping = TONEMAP[options.tonemapMode];
922
- if (options.tonemapMode === "filmic") {
923
- // The curve is this game's source, registered as three's custom tone mapping. A renderer
924
- // without a node library cannot run it; that frame keeps ACES and says so.
925
- const installed = installFilmicToneMapping(
926
- renderer.raw,
927
- {
928
- ...FILMIC_CURVE,
929
- ...options.filmicCurve,
930
- ...(lookDiagnostics.lutClipOff ? { lutClip: 0 } : {}),
931
- },
932
- resolveColorGrade(options.colorGrade),
933
- );
934
- if (installed === undefined) {
935
- raw.toneMapping = ACESFilmicToneMapping;
936
- console.warn(
937
- `TN_TONEMAP ${JSON.stringify({ requested: "filmic", applied: "aces", reason: `renderer:${renderer.kind}` })}`,
938
- );
939
- }
940
- }
910
+ // One writer of `toneMapping` for the whole engine: the curve this game supplies reaches the
911
+ // same library the renderer's own default uses, and a renderer without a node library keeps
912
+ // ACES and reports `TN_TONEMAP` once, here or in the renderer.
913
+ applyRendererToneMapping(raw, options.tonemapMode, (line) => console.warn(line), {
914
+ curve: {
915
+ ...FILMIC_CURVE,
916
+ ...options.filmicCurve,
917
+ ...(lookDiagnostics.lutClipOff ? { lutClip: 0 } : {}),
918
+ },
919
+ grade: resolveColorGrade(options.colorGrade),
920
+ });
941
921
 
942
922
  // Temporal AA is the owned engine's: it jitters the camera and blends the frames ahead of every stage. Any other
943
923
  // renderer keeps the spatial filter, and the report says why.
944
- const engineInfo = (renderer.raw as { info?: object }).info;
945
- const ownedEngine = engineInfo !== undefined && "engine" in engineInfo;
924
+ const { ownedEngine } = rendererFacts(renderer);
946
925
  const temporalRefusal = !options.temporalAA
947
926
  ? undefined
948
927
  : renderer.kind !== "webgpu"
@@ -1043,14 +1022,13 @@ export class WorldEnvironment {
1043
1022
  const temporalReport = temporal
1044
1023
  ? (): Record<string, unknown> => ({
1045
1024
  method: "traa",
1046
- ...(engineInfo as { engine?: { temporal?: object } }).engine?.temporal,
1025
+ ...(renderer.raw as { info?: { engine?: { temporal?: object } } }).info?.engine?.temporal,
1047
1026
  })
1048
1027
  : undefined;
1049
- // Contact occlusion dims the light that comes from around. With the world cache baked the frame's indirect
1050
- // diffuse is known per pixel, so only that share takes the occlusion and the sun keeps its light, as
1051
- // Unreal's AO (indirect light only) leaves it. Without a cache (the three.js engine) the whole frame is dimmed.
1052
- const indirectOcclusion =
1053
- ownedEngine && giCache.irradiance !== undefined && options.gtaoIndirectOnly;
1028
+ // Contact occlusion dims the light that comes from around. The owned engine writes each pixel's indirect diffuse
1029
+ // light to its own target, so only that share takes the occlusion and the sun keeps its light, as Unreal's AO
1030
+ // (indirect light only) leaves it. Upstream three has no such target, so there the whole frame is dimmed.
1031
+ const indirectOcclusion = ownedEngine && options.gtaoIndirectOnly;
1054
1032
  // Both screen-space stages below darken the frame with an occlusion gathered at the opaque surface's depth, so both
1055
1033
  // must leave the draws composited over it alone (see the MRT's `translucent` output and `translucentFrame`).
1056
1034
  // `TN_TRANSLUCENT=0` or `?tnTranslucent=0` keeps the target off the frame — the occlusion then darkens the sheets
@@ -1209,7 +1187,7 @@ export class WorldEnvironment {
1209
1187
  build: (input) => {
1210
1188
  // The gather reads the lit frame at each ray's hit, so the frame is materialised once and reused.
1211
1189
  const base = convertToTexture(input);
1212
- const wasmEngine = "engine" in (renderer.raw as { info: object }).info;
1190
+ const wasmEngine = rendererFacts(renderer).ownedEngine;
1213
1191
  // Harness: on the owned engine the gather also answers for the tier below it (the world-space cache), so
1214
1192
  // a ray that hits returns `hit - cache` and the two never add the same light twice (Lumen's tiering,
1215
1193
  // Engine/Source/Runtime/Renderer/Private/Lumen/LumenScreenProbeGather.cpp).
@@ -1335,14 +1313,17 @@ export class WorldEnvironment {
1335
1313
  releaseAo = () => {};
1336
1314
  },
1337
1315
  build: (input) => {
1338
- // The reach form occludes indirect light only, so a frame without a baked world cache cannot run it:
1339
- // the whole-frame multiply it would fall back to darkens the sun, and the threejs arm drops the stage.
1316
+ // The reach form occludes indirect light only, so a frame that cannot tell its indirect share apart (upstream
1317
+ // three with no baked world cache) cannot run it: the whole-frame multiply it would fall back to darkens the sun.
1340
1318
  const refusal = aoRefusal({
1341
1319
  reach: options.gtaoRadius === undefined,
1342
1320
  indirectOnly: options.gtaoIndirectOnly,
1343
1321
  // The preset's own declaration covers the frame whose bake has not finished when the chain is built:
1344
1322
  // the gather's fallback reads the cache at render time, and the registration is the other signal.
1345
- hasIndirect: options.finalGatherMethod !== "none" || giCache.irradiance !== undefined,
1323
+ hasIndirect:
1324
+ ownedEngine ||
1325
+ options.finalGatherMethod !== "none" ||
1326
+ giCache.irradiance !== undefined,
1346
1327
  });
1347
1328
  if (refusal !== undefined) throw new Error(refusal);
1348
1329
  // GTAO rebuilds the normal from the depth, so it agrees with the depth's facets. The pass's
@@ -1511,60 +1492,22 @@ export class WorldEnvironment {
1511
1492
  const composited = input
1512
1493
  .mul(vec4(occlusion.r, occlusion.r, occlusion.r, 1))
1513
1494
  .add(vec4(emitted.mul(float(1).sub(occlusion.r)), 0));
1514
- const cache = indirectOcclusion ? cacheFallback(view) : undefined;
1515
- if (cache === undefined) return composited;
1516
- // The pixel's view-space position from its depth and the camera's projection terms, read live each
1517
- // render: the engine has no getViewPosition, and a post quad's own camera nodes are the quad's.
1518
- const term = (index: number) =>
1519
- uniform(view.projectionMatrix.elements[index] ?? 0).onRenderUpdate(
1520
- () => view.projectionMatrix.elements[index] ?? 0,
1521
- );
1522
- const [p0, p5, p8, p9, p10, p14] = [
1523
- term(0),
1524
- term(5),
1525
- term(8),
1526
- term(9),
1527
- term(10),
1528
- term(14),
1529
- ];
1530
- const compose = Fn(() => {
1531
- const coordinate = uv();
1532
- const result = vec3(composited.rgb).toVar();
1533
- const sceneDepth = depth().sample(coordinate).r;
1534
- const sceneNormal = normal().sample(coordinate).xyz;
1535
- // The sky and a draw the normal pass skips (an unlit material) keep the whole-frame multiply.
1536
- If(sceneDepth.lessThan(1).and(sceneNormal.dot(sceneNormal).greaterThan(0.25)), () => {
1537
- const viewZ = p14.negate().div(sceneDepth.add(p10));
1538
- const ndc = vec2(
1539
- coordinate.x.mul(2).sub(1),
1540
- float(1).sub(coordinate.y).mul(2).sub(1),
1541
- );
1542
- const position = vec3(
1543
- viewZ.negate().mul(ndc.x.add(p8)).div(p0),
1544
- viewZ.negate().mul(ndc.y.add(p9)).div(p5),
1545
- viewZ,
1546
- );
1547
- // The indirect diffuse the material added: the cache's irradiance times the albedo, in the frame's
1548
- // units (the gather's own fallback reads it the same way). Only it takes the occlusion, and the
1549
- // result is never darker than the whole-frame multiply.
1550
- const indirect = albedo()
1551
- .rgb.mul(float(1).sub(metal().r))
1552
- .mul(cache(position, sceneNormal.normalize()))
1553
- .mul(frameGain);
1554
- // Only the opaque part of the frame carries that indirect light: a draw composited over it did not receive it.
1555
- const opaque = input.rgb.sub(translucentFrame);
1556
- result.assign(
1557
- max(
1558
- opaque
1559
- .sub(indirect.mul(float(1).sub(keeps ?? occlusion.r)))
1560
- .add(translucentFrame),
1561
- composited.rgb,
1562
- ),
1563
- );
1564
- });
1565
- return vec4(result, input.a);
1566
- });
1567
- return compose();
1495
+ if (!indirectOcclusion) return composited;
1496
+ // The indirect diffuse light the materials added, from the engine's own target (hemisphere, ambient,
1497
+ // environment and baked irradiance, never a direct light), in the frame's units. Only it takes the
1498
+ // occlusion, as Unreal's composite multiplies only the indirect term by the AO (UE 5.8.3:
1499
+ // Engine/Shaders/Private/DiffuseIndirectComposite.usf:195). An unlit draw and the sky add none, so
1500
+ // they keep their colour. The result is never darker than the whole-frame multiply.
1501
+ const indirect = textureNode("indirectDiffuse").rgb.mul(frameGain);
1502
+ // Only the opaque part of the frame carries that indirect light: a draw composited over it did not receive it.
1503
+ const opaque = input.rgb.sub(translucentFrame);
1504
+ return vec4(
1505
+ max(
1506
+ opaque.sub(indirect.mul(float(1).sub(keeps ?? occlusion.r))).add(translucentFrame),
1507
+ composited.rgb,
1508
+ ),
1509
+ input.a,
1510
+ );
1568
1511
  },
1569
1512
  }),
1570
1513
  stage({
@@ -233,17 +233,13 @@ type NormalElements = readonly [
233
233
  * Positions of one part, placed, written into `values` at `at`.
234
234
  *
235
235
  * The expression is three's `Vector3.applyMatrix4` term for term over the same elements in the same
236
- * order, including its homogeneous divide, so a merged buffer holds the values it held before. The
237
- * second half of it is what `setXYZ` wrote back into the part's own typed array before the
238
- * de-quantizing copy read it again: `normalize` rounds into the channel's own range — the scratch
239
- * store keeps a value outside that range wrapping exactly as three's store did — and `denormalize`
240
- * reads it back as a float.
236
+ * order, including its homogeneous divide. A placed position leaves a quantized channel's range, so
237
+ * it goes straight to float and never back into the channel's own type.
241
238
  */
242
239
  function writePosition(
243
240
  channel: IChannel,
244
241
  indices: Uint16Array | Uint32Array | null,
245
242
  elements: PlacementElements | null,
246
- scratch: IScratch | null,
247
243
  values: Float32Array,
248
244
  at: number,
249
245
  ): void {
@@ -271,14 +267,6 @@ function writePosition(
271
267
  pz = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
272
268
  }
273
269
  const out = at + vertex * 3;
274
- if (scratch !== null) {
275
- scratch[0] = Math.round(px * scale);
276
- scratch[1] = Math.round(py * scale);
277
- scratch[2] = Math.round(pz * scale);
278
- px = Math.max((scratch[0] as number) / scale, -1);
279
- py = Math.max((scratch[1] as number) / scale, -1);
280
- pz = Math.max((scratch[2] as number) / scale, -1);
281
- }
282
270
  values[out] = px;
283
271
  values[out + 1] = py;
284
272
  values[out + 2] = pz;
@@ -399,6 +387,15 @@ function scratchOf(array: IRawNumbers): IScratch | null {
399
387
  return null;
400
388
  }
401
389
 
390
+ /** A channel as plain float, read through its own accessors so normalization and interleaving resolve. */
391
+ function floatCopy(attribute: BufferAttribute | InterleavedBufferAttribute): BufferAttribute {
392
+ const values = new Float32Array(attribute.count * attribute.itemSize);
393
+ for (let index = 0; index < attribute.count; index += 1)
394
+ for (let component = 0; component < attribute.itemSize; component += 1)
395
+ values[index * attribute.itemSize + component] = attribute.getComponent(index, component);
396
+ return new BufferAttribute(values, attribute.itemSize);
397
+ }
398
+
402
399
  function flatten(
403
400
  part: IMergePart,
404
401
  paint: boolean,
@@ -406,6 +403,10 @@ function flatten(
406
403
  deindex: boolean,
407
404
  ): BufferGeometry {
408
405
  const placed = part.geometry.clone();
406
+ // Placed before it is float, a quantized position is stored back into its own range and clamps.
407
+ const position = placed.getAttribute("position");
408
+ if (position !== undefined && (!(position.array instanceof Float32Array) || position.normalized))
409
+ placed.setAttribute("position", floatCopy(position));
409
410
  const matrix = placementMatrix(part);
410
411
  if (matrix !== undefined) placed.applyMatrix4(matrix);
411
412
  const flat = deindex && placed.index !== null ? placed.toNonIndexed() : placed;
@@ -428,17 +429,13 @@ function flatten(
428
429
  !("isInterleavedBufferAttribute" in attribute)
429
430
  )
430
431
  continue;
431
- const values = new Float32Array(attribute.count * attribute.itemSize);
432
- for (let index = 0; index < attribute.count; index += 1)
433
- for (let component = 0; component < attribute.itemSize; component += 1)
434
- values[index * attribute.itemSize + component] = attribute.getComponent(index, component);
435
- flat.setAttribute(name, new BufferAttribute(values, attribute.itemSize));
432
+ flat.setAttribute(name, floatCopy(attribute));
436
433
  }
437
- const position = flat.getAttribute("position");
438
- if (!paint || position === undefined) return flat;
434
+ const flatPosition = flat.getAttribute("position");
435
+ if (!paint || flatPosition === undefined) return flat;
439
436
  const tone = new Color(part.color);
440
- const painted = new Float32Array(position.count * 3);
441
- for (let vertex = 0; vertex < position.count; vertex += 1) {
437
+ const painted = new Float32Array(flatPosition.count * 3);
438
+ for (let vertex = 0; vertex < flatPosition.count; vertex += 1) {
442
439
  painted[vertex * 3] = tone.r;
443
440
  painted[vertex * 3 + 1] = tone.g;
444
441
  painted[vertex * 3 + 2] = tone.b;
@@ -602,7 +599,6 @@ function writeChannel(
602
599
  indices,
603
600
  // quality-allow: Matrix4.elements is number[] in three's types and always 16 long.
604
601
  matrix === undefined ? null : (matrix.elements as unknown as PlacementElements),
605
- scratchOf(channel.array),
606
602
  values,
607
603
  at,
608
604
  );
package/src/model-lod.ts CHANGED
@@ -130,6 +130,16 @@ export function biasedLodDistance(distance: number): number {
130
130
 
131
131
  const nearest = new Vector3();
132
132
 
133
+ /**
134
+ * The near plane a caller with no camera `near` uses for the degenerate test.
135
+ *
136
+ * `degenerate` is whether the sphere's nearest surface reaches the camera plane (`depth <= near`).
137
+ * Two callers used `0.1` and the rest `0`, so a camera with no `near` answered two different
138
+ * questions; this is the one value, and it is `0` because the test is about the surface reaching the
139
+ * camera, not the surface being close to it.
140
+ */
141
+ export const LOD_NEAR_PLANE = 0;
142
+
133
143
  /**
134
144
  * The conservative nearest view-space depth of a world-space bounding sphere.
135
145
  *
@@ -148,6 +158,29 @@ export function conservativeViewDepth(
148
158
  return { depth, degenerate: depth <= nearPlane };
149
159
  }
150
160
 
161
+ /**
162
+ * The LOD recipe every caller repeats: the sphere in the camera's view, how far its nearest surface
163
+ * is, and that distance biased for the level table.
164
+ *
165
+ * `depth` is the raw conservative view depth, which a reporter projects an error from; `biased` is
166
+ * the same distance with {@link biasedLodDistance} applied, which a level selection compares. The
167
+ * two are returned together because the six callers each want one of them and each used to spell the
168
+ * step itself — one of them with a near plane of its own.
169
+ */
170
+ export function selectLodFor(
171
+ camera: Camera,
172
+ sphere: Sphere,
173
+ nearPlane: number,
174
+ ): { readonly depth: number; readonly degenerate: boolean; readonly biased: number } {
175
+ const { depth, degenerate } = conservativeViewDepth(
176
+ camera,
177
+ sphere.center,
178
+ sphere.radius,
179
+ nearPlane,
180
+ );
181
+ return { biased: biasedLodDistance(depth), degenerate, depth };
182
+ }
183
+
151
184
  /** The world-space bounding sphere of a cached local sphere under a node's world matrix. */
152
185
  export function worldSphere(
153
186
  local: Sphere,
@@ -315,10 +348,21 @@ export interface ILodChain {
315
348
  readonly sphere: Sphere;
316
349
  }
317
350
 
318
- /** Triangles one level of a chain submits. */
319
- function drawTriangles(geometry: BufferGeometry): number {
320
- const drawn = geometry.index?.count ?? geometry.getAttribute("position")?.count ?? 0;
321
- return Math.floor(drawn / 3);
351
+ const levelTriangles = new WeakMap<BufferGeometry, number>();
352
+
353
+ /**
354
+ * Triangles one level of a chain submits, read once: a level is an index view nothing edits, and on
355
+ * the owned engine each `geometry.index` read is a bridge crossing (Midway's fleet read it 528 times
356
+ * a frame, `TN_BRIDGE_WARNING`).
357
+ */
358
+ export function drawTriangles(geometry: BufferGeometry): number {
359
+ let triangles = levelTriangles.get(geometry);
360
+ if (triangles === undefined) {
361
+ const drawn = geometry.index?.count ?? geometry.getAttribute("position")?.count ?? 0;
362
+ triangles = Math.floor(drawn / 3);
363
+ levelTriangles.set(geometry, triangles);
364
+ }
365
+ return triangles;
322
366
  }
323
367
 
324
368
  /**
@@ -375,16 +419,15 @@ class ModelLod {
375
419
  return;
376
420
  }
377
421
  const world = worldSphere(this.#chain.sphere, this.#mesh, undefined, this.#mesh.matrixWorld);
378
- const { depth, degenerate } = conservativeViewDepth(
422
+ const { biased, degenerate } = selectLodFor(
379
423
  camera,
380
- world.center,
381
- world.radius,
424
+ world,
382
425
  (camera as ILodCameraLike).near ?? 0,
383
426
  );
384
427
  const view: ILodView = {
385
428
  camera,
386
429
  degenerate,
387
- depth: biasedLodDistance(depth),
430
+ depth: biased,
388
431
  viewportHeight,
389
432
  };
390
433
  const index = selectLodLevel(
@@ -412,10 +455,9 @@ class ModelLod {
412
455
  const container = this.#container;
413
456
  if (container === null) return;
414
457
  const world = worldSphere(rung.sphere, container, undefined, container.matrixWorld);
415
- const { depth, degenerate } = conservativeViewDepth(
458
+ const { biased, degenerate } = selectLodFor(
416
459
  camera,
417
- world.center,
418
- world.radius,
460
+ world,
419
461
  (camera as ILodCameraLike).near ?? 0,
420
462
  );
421
463
  const errors = [...this.#chain.errors, rung.error];
@@ -423,7 +465,7 @@ class ModelLod {
423
465
  const view: ILodView = {
424
466
  camera,
425
467
  degenerate,
426
- depth: biasedLodDistance(depth),
468
+ depth: biased,
427
469
  viewportHeight,
428
470
  };
429
471
  const index = selectLodLevel(
@@ -876,7 +918,47 @@ export function registerModelLodController(mesh: Mesh, controller: IModelLodCont
876
918
  function isChained(object: object): boolean {
877
919
  const mesh = object as Partial<Mesh>;
878
920
  const geometry = mesh.geometry;
879
- return mesh.isMesh === true && geometry !== undefined && chains.has(geometry);
921
+ return (
922
+ mesh.isMesh === true &&
923
+ geometry !== undefined &&
924
+ (chains.has(geometry) || streaming.has(geometry))
925
+ );
926
+ }
927
+
928
+ /**
929
+ * Coarse geometries of streamed models (PRD-860) whose full model is still downloading. They are
930
+ * tracked like a chained mesh, so on the frame the full model lands every mesh over them, a game's
931
+ * clones included, picks its chain up.
932
+ */
933
+ const streaming = new WeakSet<BufferGeometry>();
934
+
935
+ /** A coarse companion's geometry, drawn until {@link upgradeStreamedGeometry} gives it the full model. */
936
+ export function markStreamedGeometry(coarse: BufferGeometry): void {
937
+ streaming.add(coarse);
938
+ }
939
+
940
+ /** True while a geometry is a streamed coarse companion the full model has not replaced yet. */
941
+ export function isStreamedGeometry(geometry: BufferGeometry): boolean {
942
+ return streaming.has(geometry);
943
+ }
944
+
945
+ /**
946
+ * The full model landed: the coarse geometry takes the full base's index and attributes in place,
947
+ * so every mesh holding it (a game's clones, a projection mirror) draws the full model with no
948
+ * object swapped under the game, and it adopts the full chain.
949
+ */
950
+ export function upgradeStreamedGeometry(coarse: BufferGeometry, full: BufferGeometry): void {
951
+ const attributes = full.attributes as Record<string, BufferAttribute>;
952
+ for (const name of Object.keys(coarse.attributes))
953
+ if (attributes[name] === undefined) coarse.deleteAttribute(name);
954
+ for (const [name, attribute] of Object.entries(attributes)) coarse.setAttribute(name, attribute);
955
+ coarse.setIndex(full.index);
956
+ coarse.computeBoundingBox();
957
+ coarse.computeBoundingSphere();
958
+ levelTriangles.delete(coarse);
959
+ const registered = chains.get(full);
960
+ if (registered !== undefined) chains.set(coarse, registered);
961
+ streaming.delete(coarse);
880
962
  }
881
963
 
882
964
  /**
@@ -1357,7 +1439,8 @@ export function updateModelLods(
1357
1439
  for (const mesh of tracking.items) {
1358
1440
  const entry = controllerFor(mesh);
1359
1441
  if (entry === undefined) {
1360
- tracking.items.delete(mesh);
1442
+ // A streamed coarse mesh stays tracked until its full model lands and brings the chain.
1443
+ if (!streaming.has(mesh.geometry)) tracking.items.delete(mesh);
1361
1444
  continue;
1362
1445
  }
1363
1446
  entry.update(camera, viewportHeight);
@@ -31,6 +31,8 @@ export interface IParticleSignificanceOptions {
31
31
  */
32
32
  export class ParticleSignificance {
33
33
  #shed = 0;
34
+ /** Candidates this pass has yielded and not yet resumed. */
35
+ #yielded = 0;
34
36
  readonly #decayPerSecond: number;
35
37
  readonly #graceSeconds: number;
36
38
  readonly #states = new WeakMap<IBudgetCandidate, { yielded: boolean; changedAt: number }>();
@@ -78,7 +80,16 @@ export class ParticleSignificance {
78
80
  return this.#shed;
79
81
  }
80
82
 
83
+ /**
84
+ * Nothing to shed and nothing yielded: {@link apply} would change nothing, so the caller can skip
85
+ * asking each candidate its significance (an engine crossing per emitter on the owned engine, PRD-828).
86
+ */
87
+ get idle(): boolean {
88
+ return this.#shed === 0 && this.#yielded === 0;
89
+ }
90
+
81
91
  apply(candidates: Iterable<IBudgetCandidate>, camera: Camera, nowSeconds: number): void {
92
+ if (this.idle) return;
82
93
  const ranked: { candidate: IBudgetCandidate; significance: number }[] = [];
83
94
  for (const candidate of candidates) {
84
95
  const significance = candidate.significance(camera);
@@ -95,6 +106,7 @@ export class ParticleSignificance {
95
106
  const yielded = index < count;
96
107
  if (state.yielded === yielded || nowSeconds - state.changedAt < this.#graceSeconds) continue;
97
108
  candidate.yield(yielded);
109
+ this.#yielded += yielded ? 1 : -1;
98
110
  state.yielded = yielded;
99
111
  state.changedAt = nowSeconds;
100
112
  }
package/src/particles.ts CHANGED
@@ -492,17 +492,26 @@ export class GPUParticles3D extends Sprite implements IComputeDriven {
492
492
  if (camera !== undefined && !this.castShadow && this.#authoredVisible) {
493
493
  const bounds = this.measuredBounds;
494
494
  if (bounds !== undefined && this.#graceSeconds !== Number.POSITIVE_INFINITY) {
495
- if (camera.matrixWorldAutoUpdate) camera.updateMatrixWorld();
496
- this.updateWorldMatrix(true, false);
497
- viewProjection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
498
- frustum.setFromProjectionMatrix(
499
- viewProjection,
500
- camera.coordinateSystem,
501
- camera.reversedDepth,
502
- );
503
- worldBox.copy(bounds).applyMatrix4(this.matrixWorld).expandByScalar(this.#worldPadding);
495
+ // The native engine folds the same test in one call (PRD-828); a NaN padding asks for the default.
496
+ const engine = (this as { __boundsInView?: (c: Camera, b: Box3, p: number) => boolean })
497
+ .__boundsInView;
498
+ let inView: boolean;
499
+ if (typeof engine === "function")
500
+ inView = engine.call(this, camera, bounds, this.#padding ?? Number.NaN);
501
+ else {
502
+ if (camera.matrixWorldAutoUpdate) camera.updateMatrixWorld();
503
+ this.updateWorldMatrix(true, false);
504
+ viewProjection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
505
+ frustum.setFromProjectionMatrix(
506
+ viewProjection,
507
+ camera.coordinateSystem,
508
+ camera.reversedDepth,
509
+ );
510
+ worldBox.copy(bounds).applyMatrix4(this.matrixWorld).expandByScalar(this.#worldPadding);
511
+ inView = frustum.intersectsBox(worldBox);
512
+ }
504
513
  // ponytail: bounds lag by boundsEveryFrames; grace delays culling and paused clouds do not move.
505
- if (frustum.intersectsBox(worldBox)) this.#outsideSince = undefined;
514
+ if (inView) this.#outsideSince = undefined;
506
515
  else {
507
516
  // Wall time is only for callers without a loop clock.
508
517
  const now = simulatedSeconds ?? performance.now() / 1000;