@threenative/core 0.3.13 → 0.3.16

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 (60) hide show
  1. package/capabilities.json +1008 -83
  2. package/dist/{chunk-4SRAQFTU.js → chunk-2GPHICV6.js} +1 -1
  3. package/dist/{chunk-EEABDLUC.js → chunk-5C4TCWI3.js} +2 -2
  4. package/dist/{chunk-DIPIJICH.js → chunk-FQURMC2F.js} +122 -18
  5. package/dist/{chunk-EFWZWLPY.js → chunk-OMGIYWW7.js} +400 -13
  6. package/dist/{chunk-SV4QVUTQ.js → chunk-QAQHYOWY.js} +1 -1
  7. package/dist/{chunk-GYUZJQ7U.js → chunk-VQRPEOKY.js} +4 -1
  8. package/dist/hot.js +10 -2
  9. package/dist/index.d.ts +608 -16
  10. package/dist/index.js +2037 -633
  11. package/dist/{model-lod-DPTzeCcD.d.ts → model-lod-B921F6kQ.d.ts} +0 -10
  12. package/dist/playtest.js +3 -3
  13. package/dist/{quality-BYqKGAwo.d.ts → quality-BADStsTn.d.ts} +2 -2
  14. package/dist/render-environment.d.ts +1 -1
  15. package/dist/ui-layer.js +2 -2
  16. package/dist/worker.js +2 -2
  17. package/dist/world.d.ts +14 -4
  18. package/dist/world.js +179 -36
  19. package/mcp/animation-server.mjs +1 -1
  20. package/mcp/engine-server.mjs +44 -17
  21. package/mcp/servers.mjs +4 -4
  22. package/package.json +6 -6
  23. package/patches/three@0.187.0-prd269-upgrade.patch +126 -2
  24. package/patches/three@0.187.0.patch +108 -21
  25. package/scripts/ensure-mcp.mjs +6 -1
  26. package/src/clustered-batch.ts +146 -3
  27. package/src/clustered-mesh.ts +548 -20
  28. package/src/debug.ts +16 -0
  29. package/src/displaced-surface.ts +428 -0
  30. package/src/engine-hooks.ts +29 -0
  31. package/src/frame-budget.ts +16 -0
  32. package/src/generated/console-markers.ts +1 -0
  33. package/src/grass-field.ts +628 -0
  34. package/src/grounding.ts +19 -10
  35. package/src/hot.ts +18 -2
  36. package/src/index.ts +112 -0
  37. package/src/instanced-batch-lod.ts +54 -0
  38. package/src/model-lod.ts +77 -1
  39. package/src/pose-measure.ts +27 -2
  40. package/src/render/material-key.ts +21 -1
  41. package/src/render/screen-probe-gather.ts +303 -0
  42. package/src/render/short-range-ao.ts +274 -0
  43. package/src/render/world-impostor-surface.ts +98 -3
  44. package/src/render-camera-cull.ts +9 -3
  45. package/src/renderer.ts +26 -4
  46. package/src/scatter-field.ts +497 -0
  47. package/src/startup-offscreen-bytes.ts +11 -5
  48. package/src/state.ts +16 -3
  49. package/src/static-transform.ts +109 -6
  50. package/src/tile-ring.ts +294 -0
  51. package/src/version.ts +1 -1
  52. package/src/warmup.ts +15 -2
  53. package/src/world-cell-batches.ts +4 -0
  54. package/src/world-cell-data.ts +7 -0
  55. package/src/world-cell-models.ts +36 -8
  56. package/src/world-cell-render-gpu-dress.ts +4 -2
  57. package/src/world-cell-render-util.ts +2 -2
  58. package/src/world-cells.ts +1 -1
  59. package/src/world-river-ribbon.ts +13 -22
  60. package/src/world-water-bodies.ts +113 -3
package/dist/index.js CHANGED
@@ -1,31 +1,32 @@
1
- import { onUiIntent, publishUiState } from './chunk-4SRAQFTU.js';
2
- import { installQuietMarkers, uninstallQuietMarkers } from './chunk-SV4QVUTQ.js';
3
- import { animationPacketReaders, animationPacketTimeReaders, trackAnimationRate, animationPacketTime, animationPacketMethodsPristine, untrackAnimationRate, beginSpan, SPANS, endSpan, autoBatchOf, isAutoBatchMerged, spanRecorder, DEFAULT_CLIP_EXTENTS, DEFAULT_MAX_LEVEL_RATIO, clipLadder, VIRTUAL_SHADOW_MOVER_LAYER, VIRTUAL_SHADOW_WIDE_CASTER_LAYER, VIRTUAL_SHADOW_KEY_LAYER, VIRTUAL_SHADOW_CASTER_LAYER, VIRTUAL_SHADOW_SMALL_CASTER_LAYER, frustumPlanes, rendererFacts, animationPacketField, DEFAULT_TARGET_FPS, worldSilencedByFreeze, composeSilencedByFreeze, isStatic, prepareSceneEnvironment, STARTUP_COMPILE_BUDGET_MS, warmUpComputeNodes, createAssetLoader, AutoBatch, RenderCameraCull, StartupReadiness, measureStartupOffscreenBytes, STARTUP_OFFSCREEN_BYTES_MARKER, reportUnusedModelsLater, warmUpSceneWithCompletion, resolveTargetFps, SpanRecorder, formatSpansWindow, staticTransformCensus, STATIC_TRANSFORM_MARKER, spansRequested, setSpanRecorder, noteSliceFrame, refreshStaticTransforms, spanNow, addSpan, drawWorld, staticRoots, endSliceFrames, warmUpScene, createProjectionScanWorkspace, scanProjection, isRenderable, releaseProjectionScanWorkspace, STARTUP_STALL_MS, sceneNeedsEnvironmentPreparation, STARTUP_STABLE_WINDOW_MS, geometryVersionSum, hasRenderHook, uniformUnchanged, isSimilarityTransform, SkinnedBatch, isLight, baseColorOf, observeAnimationRates, displacesVertices, hasMorphAttributes, MIN_BATCH_MEMBERS } from './chunk-DIPIJICH.js';
4
- export { ASSET_LATE_MARKER, DEFAULT_TARGET_FPS, InstancedBatch, MAX_TARGET_FPS, SPANS, SPANS_FLAG, SPANS_MARKER, SPAN_COUNT, SPAN_NAMES, STATIC_TRANSFORM_MARKER, SpanRecorder, VIRTUAL_SHADOW_CASTER_LAYER, VIRTUAL_SHADOW_MOVER_LAYER, VIRTUAL_SHADOW_WIDE_CASTER_LAYER, addInSlices, addSpan, alwaysRender, beginSpan, createAssetLoader, endSpan, fetchAsset, formatSpansWindow, invalidateStatic, isStatic, loadAll, markStatic, mergeByMaterial, mergeParts, reconcileMirroredClips, refreshStaticTransforms, resetStaticTransforms, resolveTargetFps, setSpanRecorder, snapRefreshRate, spanNow, spanRecorder, spansRequested, staticTransformCensus, unmarkStatic, warmUpScene } from './chunk-DIPIJICH.js';
1
+ import { onUiIntent, publishUiState } from './chunk-2GPHICV6.js';
2
+ import { installQuietMarkers, uninstallQuietMarkers } from './chunk-QAQHYOWY.js';
3
+ import { animationPacketReaders, animationPacketTimeReaders, trackAnimationRate, animationPacketTime, animationPacketMethodsPristine, untrackAnimationRate, beginSpan, SPANS, endSpan, autoBatchOf, isAutoBatchMerged, spanRecorder, DEFAULT_CLIP_EXTENTS, DEFAULT_MAX_LEVEL_RATIO, clipLadder, VIRTUAL_SHADOW_MOVER_LAYER, VIRTUAL_SHADOW_WIDE_CASTER_LAYER, VIRTUAL_SHADOW_KEY_LAYER, VIRTUAL_SHADOW_CASTER_LAYER, VIRTUAL_SHADOW_SMALL_CASTER_LAYER, frustumPlanes, rendererFacts, animationPacketField, DEFAULT_TARGET_FPS, worldSilencedByFreeze, composeSilencedByFreeze, isStatic, prepareSceneEnvironment, STARTUP_COMPILE_BUDGET_MS, warmUpComputeNodes, createAssetLoader, AutoBatch, RenderCameraCull, StartupReadiness, measureStartupOffscreenBytes, STARTUP_OFFSCREEN_BYTES_MARKER, reportUnusedModelsLater, warmUpSceneWithCompletion, resolveTargetFps, SpanRecorder, formatSpansWindow, staticTransformCensus, STATIC_TRANSFORM_MARKER, spansRequested, setSpanRecorder, noteSliceFrame, refreshStaticTransforms, spanNow, addSpan, drawWorld, staticRoots, endSliceFrames, warmUpScene, createProjectionScanWorkspace, scanProjection, isRenderable, releaseProjectionScanWorkspace, STARTUP_STALL_MS, sceneNeedsEnvironmentPreparation, STARTUP_STABLE_WINDOW_MS, geometryVersionSum, hasRenderHook, uniformUnchanged, isSimilarityTransform, SkinnedBatch, isLight, baseColorOf, observeAnimationRates, displacesVertices, hasMorphAttributes, MIN_BATCH_MEMBERS } from './chunk-FQURMC2F.js';
4
+ export { ASSET_LATE_MARKER, DEFAULT_TARGET_FPS, InstancedBatch, MAX_TARGET_FPS, SPANS, SPANS_FLAG, SPANS_MARKER, SPAN_COUNT, SPAN_NAMES, STATIC_TRANSFORM_MARKER, SpanRecorder, VIRTUAL_SHADOW_CASTER_LAYER, VIRTUAL_SHADOW_MOVER_LAYER, VIRTUAL_SHADOW_WIDE_CASTER_LAYER, addInSlices, addSpan, alwaysRender, beginSpan, createAssetLoader, endSpan, fetchAsset, formatSpansWindow, invalidateStatic, isStatic, loadAll, markStatic, mergeByMaterial, mergeParts, reconcileMirroredClips, refreshStaticTransforms, resetStaticTransforms, resolveTargetFps, setSpanRecorder, snapRefreshRate, spanNow, spanRecorder, spansRequested, staticTransformCensus, unmarkStatic, warmUpScene } from './chunk-FQURMC2F.js';
5
5
  export { CameraShake, GPUParticles3D } from './chunk-H4J6IAJE.js';
6
6
  import { GPUReadback } from './chunk-QWJEMUUT.js';
7
7
  export { GPUReadback } from './chunk-QWJEMUUT.js';
8
8
  export { addFoliageBackLight } from './chunk-GXY7B3JG.js';
9
- import { CORE_VERSION, RENDER_CHAIN_TIERS, publishDirectRenderChainReport, FrameCounters, counterDeviceOf, createCrossingReader, createEngineCounterReader, VelocityTracker, createPipelineCensus, isBatchedMeshVelocityPatched, ensureBatchedMeshVelocity, setBatchedMeshMatrixWithVelocity, setBatchedMeshPreviousMatrix, disposeBatchedMeshVelocity, RenderChain } from './chunk-EEABDLUC.js';
10
- export { DEFAULT_PIPELINE_CENSUS_LIMIT, FrameCounters, PIPELINE_CENSUS_CAPABILITY, PIPELINE_CENSUS_VERSION, PipelineCensus, RENDER_CHAIN_MARKER, RENDER_CHAIN_STAGE_ORDER, RENDER_CHAIN_TIERS, RenderChain, VELOCITY_OUTPUT_NAME, VELOCITY_PREVIOUS_BONE_MATRICES, VELOCITY_PREVIOUS_INSTANCE_MATRICES, VELOCITY_PREVIOUS_WORLD_MATRIX, VelocityTracker, counterDeviceOf, createPipelineCensus, ensureVelocityOutput, readRenderChainObservation, readRenderChainReport, readVelocityPreviousBoneMatrices, readVelocityPreviousMatrices, readVelocityPreviousWorldMatrix, velocityTexture, withVelocityContext } from './chunk-EEABDLUC.js';
11
- import { isLodJoinProxy, baseGeometryOf, pixelsPerUnit, selectClusterCut, lodChainOf, GeometryCapture, updateClusteredMeshes, updateModelLods, rendererBackendIdentity } from './chunk-EFWZWLPY.js';
12
- export { ClusteredMesh, DISCRETE_LOD_DEFAULT_ERROR_PIXELS, DISCRETE_LOD_DEFAULT_HYSTERESIS, GEOMETRY_ASSET_KEY, GEOMETRY_CAPTURE_DEFAULT_LIMIT, GEOMETRY_CAPTURE_MAX_LIMIT, GEOMETRY_CAPTURE_SORTS, GEOMETRY_CAPTURE_TIMEOUT_MS, GEOMETRY_CAPTURE_WALK_CAP, baseGeometryOf, isStreamedGeometry, lodChainOf, lodPixelScale, updateClusteredMeshes, updateModelLods } from './chunk-EFWZWLPY.js';
13
- import { debugRequested, countDebug, formatDebugReport, debugHotCalls, readLaunchFlag, observeDebugGc, measureDebug } from './chunk-GYUZJQ7U.js';
14
- export { debugFlag, exposeDebug } from './chunk-GYUZJQ7U.js';
9
+ import { CORE_VERSION, RENDER_CHAIN_TIERS, publishDirectRenderChainReport, FrameCounters, counterDeviceOf, createCrossingReader, createEngineCounterReader, VelocityTracker, createPipelineCensus, isBatchedMeshVelocityPatched, ensureBatchedMeshVelocity, setBatchedMeshMatrixWithVelocity, setBatchedMeshPreviousMatrix, disposeBatchedMeshVelocity, RenderChain } from './chunk-5C4TCWI3.js';
10
+ export { DEFAULT_PIPELINE_CENSUS_LIMIT, FrameCounters, PIPELINE_CENSUS_CAPABILITY, PIPELINE_CENSUS_VERSION, PipelineCensus, RENDER_CHAIN_MARKER, RENDER_CHAIN_STAGE_ORDER, RENDER_CHAIN_TIERS, RenderChain, VELOCITY_OUTPUT_NAME, VELOCITY_PREVIOUS_BONE_MATRICES, VELOCITY_PREVIOUS_INSTANCE_MATRICES, VELOCITY_PREVIOUS_WORLD_MATRIX, VelocityTracker, counterDeviceOf, createPipelineCensus, ensureVelocityOutput, readRenderChainObservation, readRenderChainReport, readVelocityPreviousBoneMatrices, readVelocityPreviousMatrices, readVelocityPreviousWorldMatrix, velocityTexture, withVelocityContext } from './chunk-5C4TCWI3.js';
11
+ import { isLodJoinProxy, baseGeometryOf, ClusterView, DEFAULT_VIEW_MARGIN, assertViewMargin, clusterTableRadius, pixelsPerUnit, worldFrustum, outsideFrustum, selectClusterCut, lodChainOf, GeometryCapture, updateClusteredMeshes, updateModelLods, rendererBackendIdentity } from './chunk-OMGIYWW7.js';
12
+ export { ClusteredMesh, DISCRETE_LOD_DEFAULT_ERROR_PIXELS, DISCRETE_LOD_DEFAULT_HYSTERESIS, GEOMETRY_ASSET_KEY, GEOMETRY_CAPTURE_DEFAULT_LIMIT, GEOMETRY_CAPTURE_MAX_LIMIT, GEOMETRY_CAPTURE_SORTS, GEOMETRY_CAPTURE_TIMEOUT_MS, GEOMETRY_CAPTURE_WALK_CAP, baseGeometryOf, isStreamedGeometry, lodChainOf, lodPixelScale, updateClusteredMeshes, updateModelLods } from './chunk-OMGIYWW7.js';
13
+ import { debugRequested, countDebug, formatDebugReport, debugHotCalls, readLaunchFlag, observeDebugGc, measureDebug } from './chunk-VQRPEOKY.js';
14
+ export { debugFlag, debugValue, exposeDebug } from './chunk-VQRPEOKY.js';
15
15
  export { AudioBus, resetAudioCueLedger } from './chunk-U4YHUKKL.js';
16
16
  import { getPlatform, hostDocument, hostWindow, hostResizeObserver } from './chunk-XDTZ4QMO.js';
17
17
  export { getPlatform, isConsole, isMobile, isNative, isPs4, isTouchscreenAvailable, isWeb } from './chunk-XDTZ4QMO.js';
18
18
  import { devGlobal, DEV_GLOBAL_KEY } from './chunk-VP43GIWW.js';
19
19
  export { DEV_GLOBAL_KEY, devGlobal, publishDevGlobal } from './chunk-VP43GIWW.js';
20
20
  import { UI_DEV_METRICS_MESSAGE, UI_STARTUP_MESSAGE, connectUiBridge, UI_READY_INTENT } from './chunk-CFGTPFUH.js';
21
- import { Vector3, Matrix4, Object3D, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, RGBA_BPTC_Format, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC2_Format, RGB_ETC1_Format, RGBA_ETC2_EAC_Format, R11_EAC_Format, SIGNED_R11_EAC_Format, RG11_EAC_Format, SIGNED_RG11_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, Matrix3, NoToneMapping, NeutralToneMapping, AgXToneMapping, ACESFilmicToneMapping, Scene, OrthographicCamera, Sphere, Box3, Quaternion, AnimationMixer, MathUtils, LoopOnce, LoopRepeat, Vector2, Raycaster, Mesh, CustomToneMapping, EquirectangularReflectionMapping, Group, HalfFloatType, CubeCamera, SphereGeometry, BackSide, Vector4, BufferAttribute, BufferGeometry, InstancedMesh, Frustum, PlaneGeometry, Box2, FrontSide, VSMShadowMap, PCFSoftShadowMap, PCFShadowMap, HemisphereLight, DirectionalLight, FogExp2, Texture, MaterialBlending, DataTexture as DataTexture$1, RGBAFormat as RGBAFormat$1, UnsignedByteType, CatmullRomCurve3, LessEqualCompare, GreaterEqualCompare, AttachedBindMode, InterpolateLinear, NumberKeyframeTrack, AnimationUtils, AnimationClip, QuaternionKeyframeTrack, InterpolateDiscrete, LinearFilter as LinearFilter$1, ClampToEdgeWrapping as ClampToEdgeWrapping$1, Euler, RenderTarget as RenderTarget$1, NearestFilter as NearestFilter$1, FloatType as FloatType$1, CylinderGeometry, PropertyBinding, getConsoleFunction, setConsoleFunction, NormalAnimationBlendMode, Color, PerspectiveCamera, Plane, AlwaysDepth, SRGBColorSpace, BatchedMesh, SkinnedMesh, Sprite, Points, LineSegments, LineLoop, Line, LOD, ExternalTexture, Source, ColorManagement, SRGBTransfer, StaticDrawUsage } from 'three';
21
+ import { Vector3, Matrix4, Object3D, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, RGBA_BPTC_Format, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC2_Format, RGB_ETC1_Format, RGBA_ETC2_EAC_Format, R11_EAC_Format, SIGNED_R11_EAC_Format, RG11_EAC_Format, SIGNED_RG11_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, Matrix3, NoToneMapping, NeutralToneMapping, AgXToneMapping, ACESFilmicToneMapping, Scene, OrthographicCamera, Sphere, Box3, Quaternion, AnimationMixer, MathUtils, LoopOnce, LoopRepeat, Vector2, Raycaster, Mesh, CustomToneMapping, EquirectangularReflectionMapping, Group, HalfFloatType, CubeCamera, SphereGeometry, BackSide, Vector4, Frustum, BufferAttribute, BufferGeometry, InstancedMesh, PlaneGeometry, Box2, FrontSide, VSMShadowMap, PCFSoftShadowMap, PCFShadowMap, HemisphereLight, DirectionalLight, FogExp2, Texture, MaterialBlending, InstancedBufferGeometry, InstancedBufferAttribute, DataTexture as DataTexture$1, RGBAFormat as RGBAFormat$1, UnsignedByteType, CatmullRomCurve3, LessEqualCompare, GreaterEqualCompare, AttachedBindMode, InterpolateLinear, NumberKeyframeTrack, AnimationUtils, AnimationClip, QuaternionKeyframeTrack, InterpolateDiscrete, LinearFilter as LinearFilter$1, ClampToEdgeWrapping as ClampToEdgeWrapping$1, Euler, RenderTarget as RenderTarget$1, NearestFilter as NearestFilter$1, FloatType as FloatType$1, CylinderGeometry, PropertyBinding, getConsoleFunction, setConsoleFunction, NormalAnimationBlendMode, Color, PerspectiveCamera, Plane, AlwaysDepth, SRGBColorSpace, BatchedMesh, SkinnedMesh, Sprite, Points, LineSegments, LineLoop, Line, LOD, ExternalTexture, Source, ColorManagement, SRGBTransfer, StaticDrawUsage } from 'three';
22
22
  import { clone } from 'three/addons/utils/SkeletonUtils.js';
23
23
  import { MeshBVH, SAH } from 'three-mesh-bvh';
24
24
  import { CubeRenderTarget, MeshBasicNodeMaterial, PMREMGenerator, DataTexture, RGBAFormat, FloatType, NearestFilter, HalfFloatType as HalfFloatType$1, LinearFilter, RenderTarget, RenderTarget3D, Data3DTexture, ClampToEdgeWrapping, NodeMaterial, ShadowBaseNode, AssignNode, Node, NodeUpdateType, RendererUtils, BlendMode, Storage3DTexture, StorageTexture, MeshStandardNodeMaterial, MeshPhysicalNodeMaterial, QuadMesh, StorageBufferAttribute, RenderPipeline, ReadbackBuffer } from 'three/webgpu';
25
25
  import * as tsl from 'three/tsl';
26
- import { uniform, vec2, float, exp, vec3, mix, vec4, uniformArray, vertexIndex, texture, smoothstep, clamp, floor, textureLoad, ivec2, int, Fn, Loop, If, Break, max, min, cross as cross$1, dot, abs, texture3D, positionWorld, normalWorld, normalize, select, length, cubeTexture, viewportCoordinate, renderGroup, property, shadow, reference, lightShadowMatrix, and, Stack, shadowPositionWorld, dFdx, dFdy, nodeObject, pass, mrt, emissive, diffuseColor, roughness, metalness, output, normalView, convertToTexture, instancedArray, instanceIndex, sin, cos, positionLocal, reflector, screenUV, viewportSharedTexture, viewportLinearDepth, linearDepth, viewportDepthTexture, cameraFar, cameraNear, cameraPosition, sqrt, step, exp2, storage, Return, pow, textureSize, screenCoordinate, uv, getViewPosition, color, compute, storageTexture as storageTexture$1, uvec2, uint, textureStore, sign, atan, log, hash, positionViewDirection, F_Schlick, specularF90, specularColor, reflect, rtt, deltaTime, screenSize, positionGeometry, saturate } from 'three/tsl';
26
+ import { uniform, vec2, float, exp, vec3, mix, vec4, uniformArray, vertexIndex, texture, smoothstep, clamp, floor, textureLoad, ivec2, int, Fn, Loop, If, Break, max, min, cross as cross$1, dot, abs, normalize, uv, cos, sin, length, pow, rtt, texture3D, positionWorld, normalWorld, select, cubeTexture, viewportCoordinate, renderGroup, property, shadow, reference, lightShadowMatrix, and, Stack, shadowPositionWorld, dFdx, dFdy, nodeObject, pass, mrt, emissive, diffuseColor, roughness, metalness, output, normalView, convertToTexture, instancedArray, instanceIndex, positionLocal, reflector, screenUV, viewportSharedTexture, viewportLinearDepth, linearDepth, viewportDepthTexture, cameraFar, cameraNear, cameraPosition, sqrt, step, exp2, storage, Return, textureSize, screenCoordinate, getViewPosition, color, compute, storageTexture as storageTexture$1, uvec2, uint, textureStore, sign, atan, log, hash, positionViewDirection, F_Schlick, specularF90, specularColor, reflect, deltaTime, screenSize, positionGeometry, saturate } from 'three/tsl';
27
27
  import { createStore } from 'zustand/vanilla';
28
28
  import * as upstreamWebGPU from 'three-mesh-bvh/webgpu';
29
+ import { ssgi } from 'three/addons/tsl/display/SSGINode.js';
29
30
  import { SkyMesh } from 'three/addons/objects/SkyMesh.js';
30
31
  import { bloom } from 'three/addons/tsl/display/BloomNode.js';
31
32
  import { denoise } from 'three/addons/tsl/display/DenoiseNode.js';
@@ -33,7 +34,6 @@ import { fxaa } from 'three/addons/tsl/display/FXAANode.js';
33
34
  import { ao } from 'three/addons/tsl/display/GTAONode.js';
34
35
  import { godrays } from 'three/addons/tsl/display/GodraysNode.js';
35
36
  import { smaa } from 'three/addons/tsl/display/SMAANode.js';
36
- import { ssgi } from 'three/addons/tsl/display/SSGINode.js';
37
37
  import { ssr } from 'three/addons/tsl/display/SSRNode.js';
38
38
  import { sharpen } from 'three/addons/tsl/display/SharpenNode.js';
39
39
  import { traa } from 'three/addons/tsl/display/TRAANode.js';
@@ -95,6 +95,35 @@ function countEngineBatch(batches) {
95
95
  const bag = host.__tnEngineCost;
96
96
  bag.animationTickBatches = (bag.animationTickBatches ?? 0) + batches;
97
97
  }
98
+
99
+ // src/engine-hooks.ts
100
+ var COPY_MATRIX_WORLD_HOOK = "__tnCopyMatrixWorld";
101
+ function hookOf(object3) {
102
+ const hook = object3[COPY_MATRIX_WORLD_HOOK];
103
+ return typeof hook === "function" ? hook : void 0;
104
+ }
105
+ function hasCopyMatrixWorldHook(object3) {
106
+ return hookOf(object3) !== void 0;
107
+ }
108
+ function copyMatrixWorld(object3, target) {
109
+ const hook = hookOf(object3);
110
+ if (hook === void 0) return false;
111
+ hook.call(object3, target);
112
+ return true;
113
+ }
114
+ var SPHERE_BOUNDS_HOOK = "__tnSphereBounds";
115
+ var SPHERE_BOUNDS_ATTACH_HOOK = "__tnSphereBoundsAttach";
116
+ function sphereBoundsHook(root) {
117
+ const carrier = root;
118
+ const attach = carrier[SPHERE_BOUNDS_ATTACH_HOOK];
119
+ const bounds = carrier[SPHERE_BOUNDS_HOOK];
120
+ return typeof attach === "function" && typeof bounds === "function" ? {
121
+ attach,
122
+ bounds
123
+ } : void 0;
124
+ }
125
+
126
+ // src/pose-measure.ts
98
127
  function syncSkinBindings(root) {
99
128
  root.traverse((object3) => {
100
129
  const skinned = object3;
@@ -356,23 +385,43 @@ function getEnvelope(root, requestedMeshes) {
356
385
  else cached.push(envelope);
357
386
  return envelope;
358
387
  }
388
+ var engineEnvelope = /* @__PURE__ */ new WeakMap();
359
389
  function posedBounds(root, meshes) {
360
390
  const envelope = getEnvelope(root, meshes);
361
- root.updateWorldMatrix(true, true);
362
- rawBounds(envelope, envelope.raw);
363
391
  const raw = envelope.raw;
392
+ const engine = sphereBoundsHook(root);
393
+ if (engine === void 0) {
394
+ root.updateWorldMatrix(true, true);
395
+ rawBounds(envelope, raw);
396
+ } else {
397
+ if (engineEnvelope.get(root) !== envelope) {
398
+ engine.attach.call(
399
+ root,
400
+ [...envelope.bones.map((s) => s.bone), ...envelope.statics.map((s) => s.object)],
401
+ [...envelope.bones.map((s) => s.radius), ...envelope.statics.map((s) => s.radius)]
402
+ );
403
+ engineEnvelope.set(root, envelope);
404
+ }
405
+ const box = engine.bounds.call(root);
406
+ raw.minX = box[0] ?? Number.POSITIVE_INFINITY;
407
+ raw.minY = box[1] ?? Number.POSITIVE_INFINITY;
408
+ raw.minZ = box[2] ?? Number.POSITIVE_INFINITY;
409
+ raw.maxX = box[3] ?? Number.NEGATIVE_INFINITY;
410
+ raw.maxY = box[4] ?? Number.NEGATIVE_INFINITY;
411
+ raw.maxZ = box[5] ?? Number.NEGATIVE_INFINITY;
412
+ }
364
413
  const min8 = envelope.result.min;
365
- const max9 = envelope.result.max;
414
+ const max11 = envelope.result.max;
366
415
  const size = envelope.result.size;
367
416
  min8[0] = raw.minX;
368
417
  min8[1] = raw.minY + envelope.biasY;
369
418
  min8[2] = raw.minZ;
370
- max9[0] = raw.maxX;
371
- max9[1] = raw.maxY + envelope.biasY;
372
- max9[2] = raw.maxZ;
373
- size[0] = max9[0] - min8[0];
374
- size[1] = max9[1] - min8[1];
375
- size[2] = max9[2] - min8[2];
419
+ max11[0] = raw.maxX;
420
+ max11[1] = raw.maxY + envelope.biasY;
421
+ max11[2] = raw.maxZ;
422
+ size[0] = max11[0] - min8[0];
423
+ size[1] = max11[1] - min8[1];
424
+ size[2] = max11[2] - min8[2];
376
425
  return envelope.result;
377
426
  }
378
427
 
@@ -622,8 +671,8 @@ function clipPoseError(subject, reference3, options = {}) {
622
671
  const world = new Quaternion();
623
672
  let elapsedSubject = 0;
624
673
  let elapsedReference = 0;
625
- for (let sample = 0; sample < samples; sample += 1) {
626
- const phase = (sample + 0.5) / samples;
674
+ for (let sample2 = 0; sample2 < samples; sample2 += 1) {
675
+ const phase = (sample2 + 0.5) / samples;
627
676
  const subjectTime = subjectSeconds * phase;
628
677
  const referenceTime = referenceSeconds * phase;
629
678
  subjectMixer.update(subjectTime - elapsedSubject);
@@ -672,22 +721,6 @@ function deltaFromRest(bone, rest, world, out) {
672
721
  out.copy(rest).invert().premultiply(world);
673
722
  }
674
723
 
675
- // src/engine-hooks.ts
676
- var COPY_MATRIX_WORLD_HOOK = "__tnCopyMatrixWorld";
677
- function hookOf(object3) {
678
- const hook = object3[COPY_MATRIX_WORLD_HOOK];
679
- return typeof hook === "function" ? hook : void 0;
680
- }
681
- function hasCopyMatrixWorldHook(object3) {
682
- return hookOf(object3) !== void 0;
683
- }
684
- function copyMatrixWorld(object3, target) {
685
- const hook = hookOf(object3);
686
- if (hook === void 0) return false;
687
- hook.call(object3, target);
688
- return true;
689
- }
690
-
691
724
  // src/rig-preparation.ts
692
725
  var FNV_OFFSET = 2166136261;
693
726
  var FNV_PRIME = 16777619;
@@ -2551,7 +2584,7 @@ function prepareAnimationLayers(root, sources, samples, layers, consumedRoot) {
2551
2584
  return { duration: clip.duration, clips: groups };
2552
2585
  });
2553
2586
  const all = [
2554
- ...preparedSamples.flatMap((sample) => sample.clips),
2587
+ ...preparedSamples.flatMap((sample2) => sample2.clips),
2555
2588
  ...preparedLayers.map((layer) => layer.clip)
2556
2589
  ];
2557
2590
  if (all.length > 8)
@@ -2666,8 +2699,8 @@ var AnimationRootMotion = class {
2666
2699
  return { duration: clip.duration, position, yaw, cycle, cycleYaw, start, startYaw };
2667
2700
  });
2668
2701
  const buffers = /* @__PURE__ */ new Set();
2669
- for (const sample of this.#samples)
2670
- for (const item of [sample.position, sample.yaw]) {
2702
+ for (const sample2 of this.#samples)
2703
+ for (const item of [sample2.position, sample2.yaw]) {
2671
2704
  if (item === void 0) continue;
2672
2705
  for (const values of [item.parameterPositions, item.sampleValues, item.resultBuffer]) {
2673
2706
  if (ArrayBuffer.isView(values)) buffers.add(values);
@@ -2712,9 +2745,9 @@ var AnimationRootMotion = class {
2712
2745
  for (let i = 0; i < this.#samples.length; i += 1) {
2713
2746
  const weight = weights[i];
2714
2747
  if (weight === 0) continue;
2715
- const sample = this.#samples[i];
2716
- this.#cycle.addScaledVector(sample.cycle, weight);
2717
- cycleYaw += weight * sample.cycleYaw;
2748
+ const sample2 = this.#samples[i];
2749
+ this.#cycle.addScaledVector(sample2.cycle, weight);
2750
+ cycleYaw += weight * sample2.cycleYaw;
2718
2751
  }
2719
2752
  if (loops === 0) {
2720
2753
  rotateYaw(this.proposal.translation.copy(this.#last).sub(this.#first), -firstYaw);
@@ -2750,13 +2783,13 @@ var AnimationRootMotion = class {
2750
2783
  for (let i = 0; i < this.#samples.length; i += 1) {
2751
2784
  const weight = weights[i];
2752
2785
  if (weight === 0) continue;
2753
- const sample = this.#samples[i];
2754
- const time = phase * sample.duration;
2755
- if (sample.position !== void 0) {
2756
- this.#local.fromArray(sample.position.evaluate(time)).sub(sample.start);
2786
+ const sample2 = this.#samples[i];
2787
+ const time = phase * sample2.duration;
2788
+ if (sample2.position !== void 0) {
2789
+ this.#local.fromArray(sample2.position.evaluate(time)).sub(sample2.start);
2757
2790
  position.addScaledVector(this.#local, weight);
2758
2791
  }
2759
- yaw += weight * ((sample.yaw?.evaluate(time)[0] ?? 0) - sample.startYaw);
2792
+ yaw += weight * ((sample2.yaw?.evaluate(time)[0] ?? 0) - sample2.startYaw);
2760
2793
  }
2761
2794
  return yaw;
2762
2795
  }
@@ -2821,9 +2854,9 @@ var AnimationComposer = class {
2821
2854
  clips: prepared.clips,
2822
2855
  strideSync: false
2823
2856
  });
2824
- this.#samples = prepared.samples.map((sample) => ({
2825
- duration: sample.duration,
2826
- actions: sample.clips.map((clip) => ({
2857
+ this.#samples = prepared.samples.map((sample2) => ({
2858
+ duration: sample2.duration,
2859
+ actions: sample2.clips.map((clip) => ({
2827
2860
  action: this.mixer.clipAction(clip).setEffectiveTimeScale(0).setEffectiveWeight(0).play(),
2828
2861
  masked: clip.name.endsWith(":masked")
2829
2862
  }))
@@ -2860,7 +2893,7 @@ var AnimationComposer = class {
2860
2893
  return Array.from(this.#weights);
2861
2894
  }
2862
2895
  get sampleTimes() {
2863
- return this.#samples.map((sample) => sample.actions[0].action.time);
2896
+ return this.#samples.map((sample2) => sample2.actions[0].action.time);
2864
2897
  }
2865
2898
  get resources() {
2866
2899
  return {
@@ -3021,9 +3054,9 @@ var AnimationComposer = class {
3021
3054
  }
3022
3055
  const overrideWeight = this.#layers.find((layer) => layer.options.mode === "override")?.weight ?? 0;
3023
3056
  for (let i = 0; i < this.#samples.length; i += 1) {
3024
- const sample = this.#samples[i];
3025
- for (const { action, masked } of sample.actions) {
3026
- action.time = this.phase * sample.duration;
3057
+ const sample2 = this.#samples[i];
3058
+ for (const { action, masked } of sample2.actions) {
3059
+ action.time = this.phase * sample2.duration;
3027
3060
  action.setEffectiveWeight(this.#weights[i] * (masked ? 1 - overrideWeight : 1));
3028
3061
  }
3029
3062
  }
@@ -3374,11 +3407,11 @@ function createRandom(seed) {
3374
3407
  state = Math.imul(1664525, state) + 1013904223 >>> 0;
3375
3408
  return state / 4294967296;
3376
3409
  });
3377
- random.range = (min8, max9) => {
3378
- if (!Number.isFinite(min8) || !Number.isFinite(max9) || max9 <= min8) {
3410
+ random.range = (min8, max11) => {
3411
+ if (!Number.isFinite(min8) || !Number.isFinite(max11) || max11 <= min8) {
3379
3412
  throw new RangeError("range requires finite bounds with max greater than min.");
3380
3413
  }
3381
- return min8 + random() * (max9 - min8);
3414
+ return min8 + random() * (max11 - min8);
3382
3415
  };
3383
3416
  random.pick = (items) => {
3384
3417
  if (items.length === 0) throw new RangeError("pick requires a non-empty list.");
@@ -3620,6 +3653,7 @@ function clearScene(scene, computeDriven) {
3620
3653
 
3621
3654
  // src/generated/console-markers.ts
3622
3655
  var CONSOLE_MARKER = {
3656
+ firstFrame: "TN_FIRST_FRAME",
3623
3657
  frameBudget: "TN_FRAME_BUDGET",
3624
3658
  frameHitch: "TN_FRAME_HITCH",
3625
3659
  projection: "TN_PROJECTION"};
@@ -3701,17 +3735,17 @@ var UNMEASURED_WITHOUT_TOTALS = [
3701
3735
  ];
3702
3736
  var positive = (value) => value > 0 ? value : 0;
3703
3737
  function createStageReader(renderer) {
3704
- const sample = emptyStageSample();
3738
+ const sample2 = emptyStageSample();
3705
3739
  const last = new Float64Array(TOTAL_NAMES.length);
3706
3740
  let haveLast = false;
3707
3741
  return (jsBefore, engineCall, jsAfter) => {
3708
- sample.jsBefore = positive(jsBefore);
3709
- sample.jsAfter = positive(jsAfter);
3742
+ sample2.jsBefore = positive(jsBefore);
3743
+ sample2.jsAfter = positive(jsAfter);
3710
3744
  const totals = renderer()?.info?.engine?.cpuMs;
3711
3745
  if (totals === void 0) {
3712
- sample.engineJs = positive(engineCall);
3713
- for (const name of UNMEASURED_WITHOUT_TOTALS) sample[name] = void 0;
3714
- return sample;
3746
+ sample2.engineJs = positive(engineCall);
3747
+ for (const name of UNMEASURED_WITHOUT_TOTALS) sample2[name] = void 0;
3748
+ return sample2;
3715
3749
  }
3716
3750
  let delta0 = 0;
3717
3751
  const delta = (index) => {
@@ -3741,23 +3775,23 @@ function createStageReader(renderer) {
3741
3775
  return void 0;
3742
3776
  }
3743
3777
  const encodeOnly = positive(encode - post);
3744
- sample.wasmScene = scene;
3745
- sample.wasmPlan = prepare;
3746
- sample.wasmCompute = compute2;
3747
- sample.wasmEncode = encodeOnly;
3748
- sample.wasmPost = post;
3749
- sample.wasmSubmit = submit;
3750
- sample.wasmPoll = poll;
3751
- sample.wasmTail = tail;
3752
- sample.wasmRendererGap = positive(inRenderer - prepare - encode);
3753
- sample.wasmDatabaseGap = positive(inDatabase - scene - inRenderer);
3754
- sample.wasmTargets = targets;
3755
- sample.planVirtualPages = virtualPages;
3756
- sample.planDraws = draws;
3757
- sample.planShadowLists = shadowLists;
3758
- sample.wasmOther = positive(host - (inDatabase + targets + compute2 + submit + poll + tail));
3759
- sample.engineJs = positive(engineCall - host);
3760
- return sample;
3778
+ sample2.wasmScene = scene;
3779
+ sample2.wasmPlan = prepare;
3780
+ sample2.wasmCompute = compute2;
3781
+ sample2.wasmEncode = encodeOnly;
3782
+ sample2.wasmPost = post;
3783
+ sample2.wasmSubmit = submit;
3784
+ sample2.wasmPoll = poll;
3785
+ sample2.wasmTail = tail;
3786
+ sample2.wasmRendererGap = positive(inRenderer - prepare - encode);
3787
+ sample2.wasmDatabaseGap = positive(inDatabase - scene - inRenderer);
3788
+ sample2.wasmTargets = targets;
3789
+ sample2.planVirtualPages = virtualPages;
3790
+ sample2.planDraws = draws;
3791
+ sample2.planShadowLists = shadowLists;
3792
+ sample2.wasmOther = positive(host - (inDatabase + targets + compute2 + submit + poll + tail));
3793
+ sample2.engineJs = positive(engineCall - host);
3794
+ return sample2;
3761
3795
  };
3762
3796
  }
3763
3797
  function stageMetersRequested() {
@@ -4144,6 +4178,7 @@ function requireTarget(target) {
4144
4178
  return target;
4145
4179
  }
4146
4180
  var FRAME_BUDGET_MARKER = CONSOLE_MARKER.frameBudget;
4181
+ var FIRST_FRAME_MARKER = CONSOLE_MARKER.firstFrame;
4147
4182
  var FRAME_HITCH_MARKER = CONSOLE_MARKER.frameHitch;
4148
4183
  var FRAME_BUDGET_PHASES = [
4149
4184
  "hostGap",
@@ -4266,21 +4301,21 @@ var Ring = class {
4266
4301
  this.#total = 0;
4267
4302
  }
4268
4303
  /** Mean of this series over the frames where `gate` reaches `floor`. The rings fill and reset in step, so a slot is one frame. */
4269
- meanWhere(gate, floor5) {
4304
+ meanWhere(gate, floor6) {
4270
4305
  let frames = 0;
4271
4306
  let total = 0;
4272
4307
  for (let index = 0; index < this.#count; index += 1) {
4273
- if ((gate.#buffer[index] ?? 0) < floor5) continue;
4308
+ if ((gate.#buffer[index] ?? 0) < floor6) continue;
4274
4309
  frames += 1;
4275
4310
  total += this.#buffer[index] ?? 0;
4276
4311
  }
4277
4312
  return { frames, mean: frames === 0 ? 0 : total / frames };
4278
4313
  }
4279
- summarize(scratch3) {
4314
+ summarize(scratch4) {
4280
4315
  const count = this.#count;
4281
4316
  if (count === 0) return { max: 0, mean: 0, p50: 0, p95: 0, p99: 0, samples: 0 };
4282
- for (let index = 0; index < count; index += 1) scratch3[index] = this.#buffer[index] ?? 0;
4283
- const view = scratch3.subarray(0, count);
4317
+ for (let index = 0; index < count; index += 1) scratch4[index] = this.#buffer[index] ?? 0;
4318
+ const view = scratch4.subarray(0, count);
4284
4319
  view.sort();
4285
4320
  const rank = (fraction) => round(view[Math.min(count - 1, Math.ceil(fraction * count) - 1)] ?? 0);
4286
4321
  return {
@@ -4408,6 +4443,7 @@ var FrameBudget = class {
4408
4443
  #lastPresentCount;
4409
4444
  #presentsInWindow = 0;
4410
4445
  #firstFrameStart;
4446
+ #firstFrameReported = false;
4411
4447
  #firstTaskFrameStart;
4412
4448
  constructor(options = {}) {
4413
4449
  this.#simulation = options.simulation;
@@ -4644,9 +4680,9 @@ var FrameBudget = class {
4644
4680
  * p50 of a bucket that was never measured is absent from the window. An unknown bucket name
4645
4681
  * throws rather than being dropped, the same fail-closed rule as a phase.
4646
4682
  */
4647
- addGpuBucketMs(sample) {
4683
+ addGpuBucketMs(sample2) {
4648
4684
  if (!this.#open) throw new Error("FrameBudget.addGpuBucketMs called outside a frame.");
4649
- const shadowPasses = sample.shadowPasses;
4685
+ const shadowPasses = sample2.shadowPasses;
4650
4686
  if (shadowPasses !== void 0) {
4651
4687
  if (!Number.isInteger(shadowPasses) || shadowPasses < 0)
4652
4688
  throw new Error(
@@ -4655,7 +4691,7 @@ var FrameBudget = class {
4655
4691
  this.#gpuShadowPassesThisFrame = shadowPasses;
4656
4692
  }
4657
4693
  for (const bucket of FRAME_GPU_BUCKETS) {
4658
- const ms = sample[bucket];
4694
+ const ms = sample2[bucket];
4659
4695
  if (ms === void 0) continue;
4660
4696
  if (!Number.isFinite(ms) || ms < 0)
4661
4697
  throw new Error(
@@ -4748,6 +4784,16 @@ var FrameBudget = class {
4748
4784
  const simulationEnd = this.#simulationEnd ?? this.#frameStart;
4749
4785
  const frameMs = Math.max(0, nowMs - this.#frameStart);
4750
4786
  this.#lastFrameEnd = nowMs;
4787
+ if (!this.#firstFrameReported && !this.#covered && !this.#renderSkippedThisFrame) {
4788
+ this.#firstFrameReported = true;
4789
+ const threads = globalThis.__tnWebThreads;
4790
+ console.info(
4791
+ `${FIRST_FRAME_MARKER}:${JSON.stringify({
4792
+ frameMs: round(frameMs),
4793
+ ...typeof threads === "string" ? { threads } : {}
4794
+ })}`
4795
+ );
4796
+ }
4751
4797
  this.#countPresents();
4752
4798
  const drawn = !this.#renderSkippedThisFrame;
4753
4799
  const drawnDelta = drawn && this.#lastDrawnTimestamp !== void 0 ? Math.max(0, this.#frameTimestamp - this.#lastDrawnTimestamp) : 0;
@@ -4755,7 +4801,7 @@ var FrameBudget = class {
4755
4801
  const update = Math.max(0, simulationEnd - this.#frameStart);
4756
4802
  const tail = Math.max(0, nowMs - simulationEnd);
4757
4803
  const residual = Math.max(0, tail - this.#renderMs - this.#overlayMs - this.#uiMs);
4758
- const sample = wantSample ? {
4804
+ const sample2 = wantSample ? {
4759
4805
  hostGap: round(this.#hostGap),
4760
4806
  overlay: round(this.#overlayMs),
4761
4807
  render: round(this.#renderMs),
@@ -4777,7 +4823,7 @@ var FrameBudget = class {
4777
4823
  })}`
4778
4824
  );
4779
4825
  this.#maybeReport();
4780
- return sample;
4826
+ return sample2;
4781
4827
  }
4782
4828
  this.#frame.push(frameMs);
4783
4829
  this.#substeps.push(this.#substepCount);
@@ -4850,7 +4896,7 @@ var FrameBudget = class {
4850
4896
  }
4851
4897
  this.#framesInWindow += 1;
4852
4898
  this.#maybeReport();
4853
- return sample;
4899
+ return sample2;
4854
4900
  }
4855
4901
  /** Reads the window in progress without disturbing it. */
4856
4902
  window() {
@@ -5037,13 +5083,13 @@ var FrameBudget = class {
5037
5083
  }
5038
5084
  /** The stages' means over the frames at or above the sum's p95 (see `IFrameBudgetWindow.stagesAtP95`). */
5039
5085
  #stagesAtP95(sumRing, stageRings) {
5040
- const floor5 = sumRing.summarize(this.#scratch).p95;
5086
+ const floor6 = sumRing.summarize(this.#scratch).p95;
5041
5087
  const stages = {};
5042
5088
  let frames = 0;
5043
5089
  for (let index = 0; index < STAGE_NAMES.length; index += 1) {
5044
5090
  const ring = stageRings?.[index];
5045
5091
  if (ring === void 0 || ring.count === 0 || ring.count !== sumRing.count) continue;
5046
- const at3 = ring.meanWhere(sumRing, floor5);
5092
+ const at3 = ring.meanWhere(sumRing, floor6);
5047
5093
  frames = at3.frames;
5048
5094
  stages[STAGE_NAMES[index]] = round(at3.mean);
5049
5095
  }
@@ -5051,9 +5097,9 @@ var FrameBudget = class {
5051
5097
  }
5052
5098
  /** Pushes this frame's stages, with the phases that complete the partition of `frame`. */
5053
5099
  #pushStages(update, residual) {
5054
- const sample = this.#stagesThisFrame;
5100
+ const sample2 = this.#stagesThisFrame;
5055
5101
  this.#stagesThisFrame = void 0;
5056
- if (sample === void 0) return;
5102
+ if (sample2 === void 0) return;
5057
5103
  let rings = this.#stageRings;
5058
5104
  if (rings === void 0) {
5059
5105
  rings = STAGE_NAMES.map(() => new Ring(this.#capacity));
@@ -5063,7 +5109,7 @@ var FrameBudget = class {
5063
5109
  let sum = 0;
5064
5110
  for (let index = 0; index < STAGE_NAMES.length; index += 1) {
5065
5111
  const name = STAGE_NAMES[index];
5066
- const value = name === "update" ? update : name === "overlay" ? this.#overlayMs : name === "ui" ? this.#uiMs : name === "residual" ? residual : sample[name];
5112
+ const value = name === "update" ? update : name === "overlay" ? this.#overlayMs : name === "ui" ? this.#uiMs : name === "residual" ? residual : sample2[name];
5067
5113
  if (value === void 0) continue;
5068
5114
  rings[index]?.push(value);
5069
5115
  if (!STAGE_PARTS.includes(name)) sum += value;
@@ -6563,7 +6609,7 @@ var FixedStepLoop = class {
6563
6609
  return this.#fps;
6564
6610
  }
6565
6611
  runtimeDiagnosticsSeries() {
6566
- return this.#renderPerformanceSamples.map((sample) => ({ ...sample }));
6612
+ return this.#renderPerformanceSamples.map((sample2) => ({ ...sample2 }));
6567
6613
  }
6568
6614
  /**
6569
6615
  * Forget the render samples taken so far. The game calls it once, when the world first draws:
@@ -6786,7 +6832,7 @@ var FixedStepLoop = class {
6786
6832
  const sequence = ++this.#renderCompletionSequence;
6787
6833
  if (callbackMs !== void 0) this.#onFrame(callbackMs);
6788
6834
  if (this.#collectMetrics && frameMs !== void 0 && frameMs > 0) {
6789
- const sample = {
6835
+ const sample2 = {
6790
6836
  frameMs,
6791
6837
  sequence,
6792
6838
  completedAtMs: callbackFinishedAt,
@@ -6795,7 +6841,7 @@ var FixedStepLoop = class {
6795
6841
  ...phases === void 0 ? {} : { phases },
6796
6842
  ...metrics === void 0 || metrics.triangles === void 0 ? {} : { triangles: metrics.triangles }
6797
6843
  };
6798
- this.#renderPerformanceSamples.push(sample);
6844
+ this.#renderPerformanceSamples.push(sample2);
6799
6845
  if (this.#renderPerformanceSamples.length > MAX_RENDER_PERFORMANCE_SAMPLES)
6800
6846
  this.#renderPerformanceSamples.shift();
6801
6847
  }
@@ -6950,7 +6996,7 @@ var MatrixWorldPass = class {
6950
6996
  const childForce = composeWorld(root, force || stale) || force || stale;
6951
6997
  if (frozenLeaf(root)) return;
6952
6998
  const children = root.children;
6953
- for (let index = 0, length7 = children.length; index < length7; index += 1) {
6999
+ for (let index = 0, length8 = children.length; index < length8; index += 1) {
6954
7000
  this.#step(children[index], childForce, prune);
6955
7001
  }
6956
7002
  }
@@ -7135,8 +7181,8 @@ var ScenePicker = class {
7135
7181
  /** The hit as the authored source reports it: its object, and a normal in its own space. */
7136
7182
  #asSource(hit, source2) {
7137
7183
  const face = hit.face;
7138
- const normal = face.normal.clone().applyMatrix3(this.#normalMatrix.getNormalMatrix(source2.matrixWorld).invert()).normalize();
7139
- return { ...hit, face: { ...face, normal }, faceIndex: void 0, object: source2 };
7184
+ const normal2 = face.normal.clone().applyMatrix3(this.#normalMatrix.getNormalMatrix(source2.matrixWorld).invert()).normalize();
7185
+ return { ...hit, face: { ...face, normal: normal2 }, faceIndex: void 0, object: source2 };
7140
7186
  }
7141
7187
  #hitTest(object3, into) {
7142
7188
  if (isLodJoinProxy(object3) || isAutoBatchMerged(object3)) return;
@@ -8282,8 +8328,8 @@ var ProjectionMirror = class {
8282
8328
  }
8283
8329
  #createBatch(group, first, capacity) {
8284
8330
  const startedAt = globalThis.performance?.now() ?? 0;
8285
- const uniform20 = group.uniform === true;
8286
- const material = uniform20 ? whiteClone(first.material) : first.material;
8331
+ const uniform23 = group.uniform === true;
8332
+ const material = uniform23 ? whiteClone(first.material) : first.material;
8287
8333
  let mesh;
8288
8334
  try {
8289
8335
  mesh = new InstancedMesh(group.geometry, material, capacity);
@@ -8292,7 +8338,7 @@ var ProjectionMirror = class {
8292
8338
  }
8293
8339
  for (let slot = 0; slot < capacity; slot += 1) mesh.setMatrixAt(slot, ZERO_MATRIX);
8294
8340
  mesh.instanceMatrix.needsUpdate = true;
8295
- if (uniform20) mesh.setColorAt(0, material.color);
8341
+ if (uniform23) mesh.setColorAt(0, material.color);
8296
8342
  mesh.frustumCulled = false;
8297
8343
  mesh.castShadow = first.castShadow;
8298
8344
  mesh.receiveShadow = first.receiveShadow;
@@ -8302,7 +8348,7 @@ var ProjectionMirror = class {
8302
8348
  group,
8303
8349
  geometry: group.geometry,
8304
8350
  material,
8305
- uniform: uniform20,
8351
+ uniform: uniform23,
8306
8352
  instances: /* @__PURE__ */ new Map(),
8307
8353
  free: [],
8308
8354
  used: 0,
@@ -9911,20 +9957,20 @@ var ResolutionScaler = class {
9911
9957
  }
9912
9958
  #observeContinuous(window, gpuMs, stalled) {
9913
9959
  const overBudget = window.fps < this.targetFps && (gpuMs === void 0 || gpuMs > this.budgetMs);
9914
- const floor5 = RESOLUTION_SCALER.rungs[this.#limitIndex] ?? 0.23;
9960
+ const floor6 = RESOLUTION_SCALER.rungs[this.#limitIndex] ?? 0.23;
9915
9961
  if (overBudget) {
9916
9962
  this.#cleanWindows = 0;
9917
9963
  if (!this.#overBudget(window) || gpuMs === void 0) {
9918
- this.#atFloor = this.#continuousScale <= floor5;
9964
+ this.#atFloor = this.#continuousScale <= floor6;
9919
9965
  return void 0;
9920
9966
  }
9921
9967
  if (this.#insensitiveHold > 0 || this.#insensitiveFloor >= 0) return void 0;
9922
9968
  const estimate2 = this.#continuousScale * Math.sqrt(this.budgetMs / gpuMs);
9923
- const target = this.#quantizeContinuous(Math.max(floor5, estimate2), window);
9924
- this.#atFloor = target <= floor5;
9969
+ const target = this.#quantizeContinuous(Math.max(floor6, estimate2), window);
9970
+ this.#atFloor = target <= floor6;
9925
9971
  const fromIndex = this.#index;
9926
9972
  const fromScale = this.#continuousScale;
9927
- const changed = this.#continuousChange(Math.max(floor5, target), false);
9973
+ const changed = this.#continuousChange(Math.max(floor6, target), false);
9928
9974
  if (changed !== void 0 && this.#scaleSource === "auto" && 1 - (changed / fromScale) ** 2 >= RESOLUTION_SCALER.insensitiveMinPixelDrop)
9929
9975
  this.#insensitiveProbe = {
9930
9976
  fromIndex,
@@ -9960,7 +10006,7 @@ var ResolutionScaler = class {
9960
10006
  const height = Math.max(8, Math.ceil(fullHeight * scale / 8) * 8);
9961
10007
  return Math.min(1, width / fullWidth, height / fullHeight);
9962
10008
  }
9963
- #continuousChange(target, up) {
10009
+ #continuousChange(target, up2) {
9964
10010
  const current = this.#continuousScale;
9965
10011
  const change = Math.abs(target - current) / Math.max(current, Number.EPSILON);
9966
10012
  if (change < RESOLUTION_SCALER.continuousChangeThreshold) return void 0;
@@ -10036,9 +10082,9 @@ var ResolutionScaler = class {
10036
10082
  * says nothing either way.
10037
10083
  */
10038
10084
  #stalled(window) {
10039
- const { max: max9, p50, p99 } = window.presented;
10040
- if (!(p50 > 0) || !Number.isFinite(p99) || !Number.isFinite(max9)) return false;
10041
- return p99 >= p50 * RESOLUTION_SCALER.stallP99Multiple || max9 >= p50 * RESOLUTION_SCALER.stallMaxMultiple;
10085
+ const { max: max11, p50, p99 } = window.presented;
10086
+ if (!(p50 > 0) || !Number.isFinite(p99) || !Number.isFinite(max11)) return false;
10087
+ return p99 >= p50 * RESOLUTION_SCALER.stallP99Multiple || max11 >= p50 * RESOLUTION_SCALER.stallMaxMultiple;
10042
10088
  }
10043
10089
  /**
10044
10090
  * How many rungs one down-step should cross, from the fps deficit alone.
@@ -10506,11 +10552,11 @@ function planCompressedUpload(source2, block, maxBytesPerWrite) {
10506
10552
  const tileWidth = Math.min(tileColumns, columns - x);
10507
10553
  const tileHeight = Math.min(tileRows, rows - y);
10508
10554
  const offset = layer * imageBytes + y * stride + x * block.blockBytes;
10509
- const length7 = (tileHeight - 1) * stride + tileWidth * block.blockBytes;
10555
+ const length8 = (tileHeight - 1) * stride + tileWidth * block.blockBytes;
10510
10556
  tiles.push({
10511
10557
  mipLevel,
10512
10558
  origin: { x: x * block.blockWidth, y: y * block.blockHeight, z: layer },
10513
- data: bytes.subarray(offset, offset + length7),
10559
+ data: bytes.subarray(offset, offset + length8),
10514
10560
  layout: { offset: 0, bytesPerRow: stride, rowsPerImage: rows },
10515
10561
  extent: {
10516
10562
  width: tileWidth * block.blockWidth,
@@ -10518,7 +10564,7 @@ function planCompressedUpload(source2, block, maxBytesPerWrite) {
10518
10564
  depthOrArrayLayers: 1
10519
10565
  }
10520
10566
  });
10521
- totalBytes += length7;
10567
+ totalBytes += length8;
10522
10568
  }
10523
10569
  }
10524
10570
  }
@@ -11070,10 +11116,10 @@ var ComputeTimingScopes = class {
11070
11116
  );
11071
11117
  if (failed) throw failure;
11072
11118
  let consumed = false;
11073
- const queries = Object.freeze(captured.map((sample) => Object.freeze(sample)));
11119
+ const queries = Object.freeze(captured.map((sample2) => Object.freeze(sample2)));
11074
11120
  return Object.freeze({
11075
11121
  generation: this.#generation,
11076
- calls: Object.freeze(queries.map((sample) => sample.call)),
11122
+ calls: Object.freeze(queries.map((sample2) => sample2.call)),
11077
11123
  read: () => {
11078
11124
  this.#current(raw);
11079
11125
  if (consumed) throw new Error("TN_COMPUTE_TIMING_DUPLICATE: receipt already consumed.");
@@ -11081,12 +11127,12 @@ var ComputeTimingScopes = class {
11081
11127
  if (pool === void 0)
11082
11128
  throw new Error("TN_COMPUTE_TIMING_MISSING: compute query pool is absent.");
11083
11129
  const samples = [];
11084
- for (const sample of queries) {
11085
- if (!pool.timestamps.has(sample.uid)) return void 0;
11086
- const gpuMs = pool.timestamps.get(sample.uid);
11130
+ for (const sample2 of queries) {
11131
+ if (!pool.timestamps.has(sample2.uid)) return void 0;
11132
+ const gpuMs = pool.timestamps.get(sample2.uid);
11087
11133
  if (typeof gpuMs !== "number" || !Number.isFinite(gpuMs) || gpuMs <= 0)
11088
- throw new Error(`TN_COMPUTE_TIMING_INVALID: query ${sample.uid} duration ${gpuMs}.`);
11089
- samples.push(Object.freeze({ ...sample, gpuMs }));
11134
+ throw new Error(`TN_COMPUTE_TIMING_INVALID: query ${sample2.uid} duration ${gpuMs}.`);
11135
+ samples.push(Object.freeze({ ...sample2, gpuMs }));
11090
11136
  }
11091
11137
  consumed = true;
11092
11138
  return Object.freeze(samples);
@@ -11761,11 +11807,11 @@ var toDisplay = (c) => blend3(
11761
11807
  );
11762
11808
  var toLinear = (v) => blend3(v.div(12.92), v.add(0.055).div(1.055).pow(2.4), step(vec3(0.04045), v));
11763
11809
  function dithered(linear, steps) {
11764
- const uniform20 = hash(screenCoordinate.y.mul(4096).add(screenCoordinate.x));
11810
+ const uniform23 = hash(screenCoordinate.y.mul(4096).add(screenCoordinate.x));
11765
11811
  const grain = mix(
11766
- uniform20.mul(2).sqrt().sub(1),
11767
- float(1).sub(float(2).sub(uniform20.mul(2)).sqrt()),
11768
- step(0.5, uniform20)
11812
+ uniform23.mul(2).sqrt().sub(1),
11813
+ float(1).sub(float(2).sub(uniform23.mul(2)).sqrt()),
11814
+ step(0.5, uniform23)
11769
11815
  );
11770
11816
  return toLinear(clamp(toDisplay(linear).add(grain.mul(steps * EIGHT_BIT_STEP)), 0, 1));
11771
11817
  }
@@ -11938,7 +11984,7 @@ var exposureSettings = {
11938
11984
  maxDelta: 0.1,
11939
11985
  reportInterval: 0.5
11940
11986
  };
11941
- function exposureMeter(colour, uv7) {
11987
+ function exposureMeter(colour, uv8) {
11942
11988
  const luminance = dot(colour.rgb, vec3(1 / 3, 1 / 3, 1 / 3)).clamp(1e-4, 65504);
11943
11989
  const weight = float(1);
11944
11990
  return vec2(luminance, weight);
@@ -12918,10 +12964,10 @@ function wrapRenderer(raw, kind, applied, state, reapply, alphaAntialiasing, pip
12918
12964
  firstWorldFrame: () => rendererFirstWorldFrame(raw, presentationSince)
12919
12965
  } : {},
12920
12966
  gpuFrameAge: () => {
12921
- const sample = gpuFrameSample();
12967
+ const sample2 = gpuFrameSample();
12922
12968
  const frame = currentFrame();
12923
- if (sample === void 0 || frame === void 0 || !Number.isInteger(frame)) return void 0;
12924
- return frame - sample.frame;
12969
+ if (sample2 === void 0 || frame === void 0 || !Number.isInteger(frame)) return void 0;
12970
+ return frame - sample2.frame;
12925
12971
  },
12926
12972
  gpuFrameSample,
12927
12973
  observeGpuFrames: (options) => {
@@ -13125,6 +13171,7 @@ function wrapRenderer(raw, kind, applied, state, reapply, alphaAntialiasing, pip
13125
13171
  prepareTextures: async (textures, signal, onProgress, replacements) => {
13126
13172
  if (disposed) throw new Error("Renderer disposed during texture preparation.");
13127
13173
  if (kind !== "webgpu") return 0;
13174
+ if (raw.info?.engine !== void 0) return 0;
13128
13175
  const inputs = [];
13129
13176
  const originals = /* @__PURE__ */ new Set();
13130
13177
  for (const texture7 of textures) {
@@ -13181,11 +13228,11 @@ function wrapRenderer(raw, kind, applied, state, reapply, alphaAntialiasing, pip
13181
13228
  for (const value of Object.values(entry)) {
13182
13229
  if (value?.isTexture === true) pending2.add(value);
13183
13230
  }
13184
- for (const uniform20 of Object.values(
13231
+ for (const uniform23 of Object.values(
13185
13232
  entry.uniforms ?? {}
13186
13233
  )) {
13187
- if (uniform20?.value?.isTexture === true)
13188
- pending2.add(uniform20.value);
13234
+ if (uniform23?.value?.isTexture === true)
13235
+ pending2.add(uniform23.value);
13189
13236
  }
13190
13237
  }
13191
13238
  });
@@ -13636,6 +13683,7 @@ async function createRenderer(options = {}) {
13636
13683
  });
13637
13684
  let renderer;
13638
13685
  let webgpuFailure;
13686
+ let opening;
13639
13687
  if (preferWebGPU && (source2?.hasWebGPU() ?? "gpu" in (globalThis.navigator ?? {}))) {
13640
13688
  try {
13641
13689
  const raw = options.webgpuFactory ? await options.webgpuFactory(canvas, rendererParameters) : await import('three/webgpu').then(async (webgpu) => {
@@ -13647,6 +13695,7 @@ async function createRenderer(options = {}) {
13647
13695
  });
13648
13696
  });
13649
13697
  const instance = raw;
13698
+ opening = instance;
13650
13699
  await instance.init?.();
13651
13700
  applyRendererToneMapping(instance, options.toneMapping ?? "filmic", report);
13652
13701
  const alphaAntialiasing = arm(instance);
@@ -13670,8 +13719,14 @@ async function createRenderer(options = {}) {
13670
13719
  if (adapter.gpuClass !== void 0)
13671
13720
  report(`${GPU_CLASS_MARKER}:${JSON.stringify(adapter.gpuClass)}`);
13672
13721
  } catch (error) {
13673
- if (error instanceof Error && error.message.startsWith("TN_WASM_ABI_MISMATCH")) throw error;
13674
- webgpuFailure = error instanceof Error ? error.message : String(error);
13722
+ try {
13723
+ opening?.dispose?.();
13724
+ } catch {
13725
+ }
13726
+ const message = error instanceof Error ? error.message : String(error);
13727
+ const deviceFault = /^TN_WASM_(?:DEVICE_LOST|DEVICE|ADAPTER|SURFACE|INIT):/u;
13728
+ if (/^TN_(?:WASM|NATIVE|ABI)_/u.test(message) && !deviceFault.test(message)) throw error;
13729
+ webgpuFailure = message;
13675
13730
  renderer = void 0;
13676
13731
  }
13677
13732
  }
@@ -15829,9 +15884,15 @@ function createGameStore(initial, intervalMs) {
15829
15884
  gameStore.getState = () => current;
15830
15885
  gameStore.set = (patch) => {
15831
15886
  const next = typeof patch === "function" ? patch(current) : patch;
15832
- Object.assign(pending2, next);
15833
- Object.assign(current, next);
15834
- hasPending = true;
15887
+ let changed = false;
15888
+ for (const key in next) {
15889
+ const value = next[key];
15890
+ if (Object.is(value, current[key])) continue;
15891
+ Reflect.set(pending2, key, value);
15892
+ Reflect.set(current, key, value);
15893
+ changed = true;
15894
+ }
15895
+ if (changed) hasPending = true;
15835
15896
  };
15836
15897
  gameStore.flush = flush;
15837
15898
  gameStore.start = () => {
@@ -16238,8 +16299,8 @@ function directionalTransmittance(parameters, direction2) {
16238
16299
  const lengthSquared = direction2.lengthSq();
16239
16300
  if (!Number.isFinite(lengthSquared) || lengthSquared === 0)
16240
16301
  throw new Error("Atmosphere direction must be finite and non-zero.");
16241
- const normal = direction2.clone().normalize();
16242
- const cosine = Math.max(0.05, normal.y);
16302
+ const normal2 = direction2.clone().normalize();
16303
+ const cosine = Math.max(0.05, normal2.y);
16243
16304
  const airMass = 1 / cosine;
16244
16305
  const zenith = zenithTransmittance(parameters);
16245
16306
  return new Vector3(zenith[0] ** airMass, zenith[1] ** airMass, zenith[2] ** airMass);
@@ -16396,41 +16457,41 @@ function bake2d(target, resolution, value) {
16396
16457
  return Fn(() => {
16397
16458
  const x = instanceIndex.mod(resolution.width);
16398
16459
  const y = instanceIndex.div(resolution.width);
16399
- const uv7 = vec2(
16460
+ const uv8 = vec2(
16400
16461
  float(x).add(0.5).div(resolution.width),
16401
16462
  float(y).add(0.5).div(resolution.height)
16402
16463
  );
16403
- textureStore(target, uvec2(x, y), value(uv7, x, y));
16464
+ textureStore(target, uvec2(x, y), value(uv8, x, y));
16404
16465
  })().compute(resolution.width * resolution.height);
16405
16466
  }
16406
16467
  function bakeTransmittance(target, resolution, parameterUniforms) {
16407
- return bake2d(target, resolution, (uv7) => {
16468
+ return bake2d(target, resolution, (uv8) => {
16408
16469
  const thickness = parameterUniforms.atmosphereRadius.sub(parameterUniforms.planetRadius);
16409
16470
  const rayleighColumn = float(8).mul(float(1).sub(exp(thickness.negate().div(8))));
16410
16471
  const mieColumn = float(1.2).mul(float(1).sub(exp(thickness.negate().div(1.2))));
16411
- const airMass = float(1).div(uv7.x.max(0.05));
16472
+ const airMass = float(1).div(uv8.x.max(0.05));
16412
16473
  const opticalDepth = parameterUniforms.rayleigh.mul(rayleighColumn).add(parameterUniforms.mie.mul(mieColumn)).add(parameterUniforms.ozone.mul(15)).mul(airMass);
16413
16474
  return vec4(exp(opticalDepth.negate()), 1);
16414
16475
  });
16415
16476
  }
16416
- function sampleLut(target, uv7) {
16417
- return texture(target, uv7.clamp(0, 1)).level(float(0));
16477
+ function sampleLut(target, uv8) {
16478
+ return texture(target, uv8.clamp(0, 1)).level(float(0));
16418
16479
  }
16419
16480
  function bakeMultiScattering(target, resolution, parameterUniforms, transmittance) {
16420
- return bake2d(target, resolution, (uv7) => {
16421
- const altitudeWeight = float(1).sub(uv7.y);
16422
- const angularWeight = float(0.5).add(uv7.x.mul(0.5));
16423
- const directTransmittance = sampleLut(transmittance, uv7).rgb;
16481
+ return bake2d(target, resolution, (uv8) => {
16482
+ const altitudeWeight = float(1).sub(uv8.y);
16483
+ const angularWeight = float(0.5).add(uv8.x.mul(0.5));
16484
+ const directTransmittance = sampleLut(transmittance, uv8).rgb;
16424
16485
  const scattering = parameterUniforms.rayleigh.mul(altitudeWeight).add(parameterUniforms.mie.mul(angularWeight)).add(parameterUniforms.ozone.mul(0.02));
16425
16486
  return vec4(scattering.mul(directTransmittance), 1);
16426
16487
  });
16427
16488
  }
16428
16489
  function bakeSkyView(target, resolution, parameterUniforms, transmittance, multiScattering) {
16429
- return bake2d(target, resolution, (uv7) => {
16430
- const horizonWeight = float(1).sub(uv7.y).max(0);
16431
- const sunWeight = float(0.25).add(uv7.x.mul(0.75));
16432
- const directTransmittance = sampleLut(transmittance, uv7).rgb;
16433
- const higherOrderScattering = sampleLut(multiScattering, uv7).rgb;
16490
+ return bake2d(target, resolution, (uv8) => {
16491
+ const horizonWeight = float(1).sub(uv8.y).max(0);
16492
+ const sunWeight = float(0.25).add(uv8.x.mul(0.75));
16493
+ const directTransmittance = sampleLut(transmittance, uv8).rgb;
16494
+ const higherOrderScattering = sampleLut(multiScattering, uv8).rgb;
16434
16495
  const scattering = parameterUniforms.rayleigh.mul(horizonWeight.mul(1.5)).add(parameterUniforms.mie.mul(sunWeight)).add(parameterUniforms.ozone.mul(0.01));
16435
16496
  return vec4(scattering.mul(directTransmittance).add(higherOrderScattering), 1);
16436
16497
  });
@@ -16480,11 +16541,11 @@ var AtmosphereLuts = class {
16480
16541
  this.uniforms.rayleigh.value.copy(resolved.rayleigh);
16481
16542
  this.#hash = hashParameters(resolved, this.resolutions);
16482
16543
  }
16483
- sampleTransmittance(uv7) {
16484
- return sampleLut(this.transmittance, uv7);
16544
+ sampleTransmittance(uv8) {
16545
+ return sampleLut(this.transmittance, uv8);
16485
16546
  }
16486
- sampleSkyView(uv7) {
16487
- return sampleLut(this.skyView, uv7);
16547
+ sampleSkyView(uv8) {
16548
+ return sampleLut(this.skyView, uv8);
16488
16549
  }
16489
16550
  dispose() {
16490
16551
  for (const node of this.warmupNodes) node.dispose();
@@ -16609,27 +16670,27 @@ var Atmosphere = class extends Group {
16609
16670
  /** Return the game-owned sky radiance lookup as a TSL vec3 or a CPU validation sample. */
16610
16671
  radiance(direction2) {
16611
16672
  if (!isNode(direction2)) {
16612
- const normal2 = asVector(direction2);
16613
- const horizon = 1 - Math.max(0, normal2.y);
16614
- const sunWeight2 = Math.max(0, normal2.dot(this.#sunDirection));
16673
+ const normal3 = asVector(direction2);
16674
+ const horizon = 1 - Math.max(0, normal3.y);
16675
+ const sunWeight2 = Math.max(0, normal3.dot(this.#sunDirection));
16615
16676
  return new Vector3(
16616
16677
  this.#parameters.rayleigh.x * (0.75 + horizon) + this.#parameters.mie.x * sunWeight2,
16617
16678
  this.#parameters.rayleigh.y * (0.75 + horizon) + this.#parameters.mie.y * sunWeight2,
16618
16679
  this.#parameters.rayleigh.z * (0.75 + horizon) + this.#parameters.mie.z * sunWeight2
16619
16680
  );
16620
16681
  }
16621
- const normal = directionNode(direction2).normalize();
16622
- const uv7 = vec2(normal.x.mul(0.5).add(0.5), normal.y.mul(0.5).add(0.5));
16623
- const lookup = nodeRgb(this.luts.sampleSkyView(uv7));
16624
- const sunWeight = normal.dot(this.#sunDirectionNode).max(0);
16682
+ const normal2 = directionNode(direction2).normalize();
16683
+ const uv8 = vec2(normal2.x.mul(0.5).add(0.5), normal2.y.mul(0.5).add(0.5));
16684
+ const lookup = nodeRgb(this.luts.sampleSkyView(uv8));
16685
+ const sunWeight = normal2.dot(this.#sunDirectionNode).max(0);
16625
16686
  return lookup.mul(float(0.35).add(sunWeight.mul(0.65)));
16626
16687
  }
16627
16688
  /** Return direct solar transmittance as a TSL vec3 or a CPU validation sample. */
16628
16689
  sunTransmittance(direction2) {
16629
16690
  if (!isNode(direction2)) return directionalTransmittance(this.#parameters, asVector(direction2));
16630
- const normal = directionNode(direction2).normalize();
16631
- const uv7 = vec2(normal.y.max(0.05), float(0.5));
16632
- return nodeRgb(this.luts.sampleTransmittance(uv7));
16691
+ const normal2 = directionNode(direction2).normalize();
16692
+ const uv8 = vec2(normal2.y.max(0.05), float(0.5));
16693
+ return nodeRgb(this.luts.sampleTransmittance(uv8));
16633
16694
  }
16634
16695
  /**
16635
16696
  * Composite scene colour against game-supplied in-scattered radiance using scene-pass depth.
@@ -16671,11 +16732,11 @@ var SkyCaptureSchedule = class {
16671
16732
  }
16672
16733
  }
16673
16734
  next(sunDirection) {
16674
- const length7 = Math.hypot(sunDirection.x, sunDirection.y, sunDirection.z);
16675
- if (!Number.isFinite(length7) || length7 === 0) {
16735
+ const length8 = Math.hypot(sunDirection.x, sunDirection.y, sunDirection.z);
16736
+ if (!Number.isFinite(length8) || length8 === 0) {
16676
16737
  throw new Error("SkyCapture sun direction must be finite and nonzero.");
16677
16738
  }
16678
- const sun = sunDirection.clone().divideScalar(length7);
16739
+ const sun = sunDirection.clone().divideScalar(length8);
16679
16740
  if (this.#face === 6) {
16680
16741
  if (this.#sun !== void 0 && this.#sun.angleTo(sun) <= this.#threshold) return [];
16681
16742
  this.#sun = sun;
@@ -17193,11 +17254,11 @@ var SoftBody3D = class extends Mesh {
17193
17254
  }
17194
17255
  /** Latest asynchronous GPU positions and their age, when readback was requested. */
17195
17256
  get sample() {
17196
- const sample = this.#readback?.sample;
17197
- if (sample === void 0) return void 0;
17257
+ const sample2 = this.#readback?.sample;
17258
+ if (sample2 === void 0) return void 0;
17198
17259
  return {
17199
- data: compactClothVec3Readback(sample.data, this.uniqueVertexCount),
17200
- staleFrames: sample.staleFrames
17260
+ data: compactClothVec3Readback(sample2.data, this.uniqueVertexCount),
17261
+ staleFrames: sample2.staleFrames
17201
17262
  };
17202
17263
  }
17203
17264
  debug() {
@@ -17411,7 +17472,7 @@ function matrixFor(mesh, instance, target) {
17411
17472
  }
17412
17473
  return target.copy(mesh.matrixWorld);
17413
17474
  }
17414
- function appendVertices(mesh, position, normal, matrix, normalMatrix, state) {
17475
+ function appendVertices(mesh, position, normal2, matrix, normalMatrix, state) {
17415
17476
  const localPosition = new Vector3();
17416
17477
  const worldPosition = new Vector3();
17417
17478
  const localNormal = new Vector3();
@@ -17420,8 +17481,8 @@ function appendVertices(mesh, position, normal, matrix, normalMatrix, state) {
17420
17481
  mesh.getVertexPosition(vertex, localPosition);
17421
17482
  worldPosition.copy(localPosition).applyMatrix4(matrix);
17422
17483
  state.positions.push(worldPosition.x, worldPosition.y, worldPosition.z);
17423
- if (normal === void 0) localNormal.set(0, 1, 0);
17424
- else localNormal.set(normal.getX(vertex), normal.getY(vertex), normal.getZ(vertex));
17484
+ if (normal2 === void 0) localNormal.set(0, 1, 0);
17485
+ else localNormal.set(normal2.getX(vertex), normal2.getY(vertex), normal2.getZ(vertex));
17425
17486
  worldNormal.copy(localNormal).applyNormalMatrix(normalMatrix).normalize();
17426
17487
  state.normals.push(worldNormal.x, worldNormal.y, worldNormal.z);
17427
17488
  }
@@ -17470,12 +17531,12 @@ function appendMesh(mesh, state) {
17470
17531
  const instances = mesh instanceof InstancedMesh ? Math.max(0, mesh.count) : 1;
17471
17532
  const matrix = new Matrix4();
17472
17533
  const normalMatrix = new Matrix3();
17473
- const normal = mesh.geometry.getAttribute("normal");
17534
+ const normal2 = mesh.geometry.getAttribute("normal");
17474
17535
  for (let instance = 0; instance < instances; instance += 1) {
17475
17536
  const vertexOffset = state.positions.length / 3;
17476
17537
  matrixFor(mesh, instance, matrix);
17477
17538
  normalMatrix.getNormalMatrix(matrix);
17478
- appendVertices(mesh, position, normal, matrix, normalMatrix, state);
17539
+ appendVertices(mesh, position, normal2, matrix, normalMatrix, state);
17479
17540
  appendTriangles(mesh, index, ranges, vertexOffset, state);
17480
17541
  }
17481
17542
  }
@@ -17839,10 +17900,10 @@ function flatten(root, include, materials) {
17839
17900
  const wx = (n[0] ?? 0) * nx + (n[3] ?? 0) * ny + (n[6] ?? 0) * nz;
17840
17901
  const wy = (n[1] ?? 0) * nx + (n[4] ?? 0) * ny + (n[7] ?? 0) * nz;
17841
17902
  const wz = (n[2] ?? 0) * nx + (n[5] ?? 0) * ny + (n[8] ?? 0) * nz;
17842
- const length7 = Math.hypot(wx, wy, wz) || 1;
17843
- normals[target] = wx / length7;
17844
- normals[target + 1] = wy / length7;
17845
- normals[target + 2] = wz / length7;
17903
+ const length8 = Math.hypot(wx, wy, wz) || 1;
17904
+ normals[target] = wx / length8;
17905
+ normals[target + 1] = wy / length8;
17906
+ normals[target + 2] = wz / length8;
17846
17907
  }
17847
17908
  materialIds[filled] = id;
17848
17909
  sides[filled] = sideOf(material);
@@ -18201,7 +18262,7 @@ var TracedReflections = class {
18201
18262
  const interpolated = normalA.mul(weights.x).add(normalB.mul(weights.y)).add(normalC.mul(weights.z));
18202
18263
  const lengthSquared = max(dot(interpolated, interpolated), float(1e-12));
18203
18264
  const unit2 = interpolated.div(lengthSquared.sqrt());
18204
- const normal = dot(unit2, ray.direction).greaterThan(0).select(unit2.negate(), unit2);
18265
+ const normal2 = dot(unit2, ray.direction).greaterThan(0).select(unit2.negate(), unit2);
18205
18266
  const material = corner.w;
18206
18267
  const albedo = fetchMaterial(material.mul(MATERIAL_TEXELS));
18207
18268
  const emission = fetchMaterial(material.mul(MATERIAL_TEXELS).add(1));
@@ -18209,7 +18270,7 @@ var TracedReflections = class {
18209
18270
  hit,
18210
18271
  distance: hit.greaterThan(0).select(result.x, float(-1)),
18211
18272
  position: ray.origin.add(ray.direction.mul(result.x)),
18212
- normal,
18273
+ normal: normal2,
18213
18274
  triangle,
18214
18275
  albedo: albedo.xyz,
18215
18276
  roughness: albedo.w,
@@ -18222,12 +18283,322 @@ var TracedReflections = class {
18222
18283
  this.scene.dispose();
18223
18284
  }
18224
18285
  };
18286
+ var SCREEN_PROBE_GATHER_MARKER = "TN_SCREEN_PROBE_GATHER";
18287
+ var SCREEN_PROBE_PASSES = ["trace", "filter", "gather"];
18288
+ var DEFAULT_DOWNSAMPLE = 16;
18289
+ var DEFAULT_OCTAHEDRON = 8;
18290
+ var DEFAULT_CELL_SIZE = 1;
18291
+ var START_OFFSET = 0.01;
18292
+ var START_OFFSET_PER_METRE = 4e-3;
18293
+ var gatherScreenProbes = ssgi;
18294
+ function defineWorldMapping(camera) {
18295
+ const live = (index) => uniform(camera.matrixWorld.elements[index] ?? 0).onRenderUpdate(
18296
+ () => camera.matrixWorld.elements[index] ?? 0
18297
+ );
18298
+ const column = (first) => vec3(live(first), live(first + 1), live(first + 2));
18299
+ const [right, up2, back, at3] = [column(0), column(4), column(8), column(12)];
18300
+ return {
18301
+ /** A view-space vector in world space: the camera's rotation, which is all a direction needs. */
18302
+ direction: (value) => right.mul(value.x).add(up2.mul(value.y)).add(back.mul(value.z)),
18303
+ /** A view-space point in world space. */
18304
+ position: (value) => right.mul(value.x).add(up2.mul(value.y)).add(back.mul(value.z)).add(at3)
18305
+ };
18306
+ }
18307
+ var ScreenProbeGather = class {
18308
+ report;
18309
+ downsampleFactor;
18310
+ tracingOctahedronResolution;
18311
+ cacheCellSize;
18312
+ #camera;
18313
+ #viewport;
18314
+ #fallback;
18315
+ #radiance;
18316
+ #trace;
18317
+ #timedPass;
18318
+ #node;
18319
+ constructor(options) {
18320
+ const downsampleFactor = options.downsampleFactor ?? DEFAULT_DOWNSAMPLE;
18321
+ const tracingOctahedronResolution = options.tracingOctahedronResolution ?? DEFAULT_OCTAHEDRON;
18322
+ const cacheCellSize = options.cacheCellSize ?? DEFAULT_CELL_SIZE;
18323
+ if (!(Number.isInteger(downsampleFactor) && downsampleFactor >= 1))
18324
+ throw new RangeError(
18325
+ `TN_SCREEN_PROBE_GATHER: downsampleFactor ${downsampleFactor} must be a whole number of pixels, at least 1`
18326
+ );
18327
+ if (!(Number.isInteger(tracingOctahedronResolution) && tracingOctahedronResolution >= 2))
18328
+ throw new RangeError(
18329
+ `TN_SCREEN_PROBE_GATHER: tracingOctahedronResolution ${tracingOctahedronResolution} must be a whole number of rays, at least 2`
18330
+ );
18331
+ if (!(options.viewport.width > 0 && options.viewport.height > 0))
18332
+ throw new RangeError(
18333
+ `TN_SCREEN_PROBE_GATHER: viewport ${options.viewport.width}x${options.viewport.height} must be the drawing buffer`
18334
+ );
18335
+ if (options.timedPass != null && !SCREEN_PROBE_PASSES.includes(options.timedPass))
18336
+ throw new TypeError(
18337
+ `TN_SCREEN_PROBE_GATHER: timedPass ${String(options.timedPass)} is not one of ${SCREEN_PROBE_PASSES.join(", ")}`
18338
+ );
18339
+ if (options.trace !== void 0 && !(cacheCellSize > 0))
18340
+ throw new RangeError(
18341
+ `TN_SCREEN_PROBE_GATHER: cacheCellSize ${cacheCellSize} must be metres beyond 0`
18342
+ );
18343
+ if (options.trace !== void 0 && options.radiance === void 0)
18344
+ throw new TypeError(
18345
+ "TN_SCREEN_PROBE_GATHER_RADIANCE: a ray that leaves the screen reads options.radiance, and none was given"
18346
+ );
18347
+ if ((options.radiance !== void 0 || options.trace !== void 0) && options.camera?.matrixWorld === void 0)
18348
+ throw new TypeError(
18349
+ "TN_SCREEN_PROBE_GATHER_CAMERA: a gather that leaves the screen needs the scene camera's matrixWorld"
18350
+ );
18351
+ this.downsampleFactor = downsampleFactor;
18352
+ this.tracingOctahedronResolution = tracingOctahedronResolution;
18353
+ this.cacheCellSize = cacheCellSize;
18354
+ this.#camera = options.camera;
18355
+ this.#viewport = options.viewport;
18356
+ this.#fallback = options.fallback;
18357
+ this.#radiance = options.radiance;
18358
+ this.#trace = options.trace;
18359
+ this.#timedPass = options.timedPass;
18360
+ const tilesX = Math.ceil(options.viewport.width / downsampleFactor);
18361
+ const tilesY = Math.ceil(options.viewport.height / downsampleFactor);
18362
+ this.report = {
18363
+ downsampleFactor,
18364
+ tracingOctahedronResolution,
18365
+ viewportWidth: options.viewport.width,
18366
+ viewportHeight: options.viewport.height,
18367
+ probes: tilesX * tilesY,
18368
+ raysPerProbe: tracingOctahedronResolution * tracingOctahedronResolution,
18369
+ worldTrace: options.trace !== void 0
18370
+ };
18371
+ if (options.marker !== false)
18372
+ console.info(`${SCREEN_PROBE_GATHER_MARKER} ${JSON.stringify(this.report)}`);
18373
+ }
18374
+ /**
18375
+ * The gather itself: `ssgi(base, depth, normal, { camera, probes, fallback, miss })`, with `base` the lit frame the
18376
+ * traces read and the depth and normal of the scene pass. `getGINode()` and `getAONode()` read what it built.
18377
+ */
18378
+ gather(colorNode, depthNode, normalNode) {
18379
+ const { fallback, miss } = this.#tiers();
18380
+ const node = gatherScreenProbes(colorNode, depthNode, normalNode, {
18381
+ camera: this.#camera,
18382
+ probes: {
18383
+ downsampleFactor: this.downsampleFactor,
18384
+ tracingOctahedronResolution: this.tracingOctahedronResolution,
18385
+ viewport: this.#viewport,
18386
+ ...this.#timedPass === void 0 ? {} : { timedPass: this.#timedPass }
18387
+ },
18388
+ ...fallback === void 0 ? {} : { fallback },
18389
+ ...miss === void 0 ? {} : { miss }
18390
+ });
18391
+ this.#node = node;
18392
+ return node;
18393
+ }
18394
+ /** The gather's radiance, E / pi: multiply by the receiver's albedo and add it after the scene pass. */
18395
+ getGINode() {
18396
+ return this.#built().getGINode();
18397
+ }
18398
+ /** The share of the gather's rays that found nothing, as the occlusion the caller applies to the lit frame. */
18399
+ getAONode() {
18400
+ return this.#built().getAONode();
18401
+ }
18402
+ #built() {
18403
+ if (this.#node === void 0)
18404
+ throw new Error("TN_SCREEN_PROBE_GATHER_UNBUILT: call gather() before reading its nodes");
18405
+ return this.#node;
18406
+ }
18407
+ /**
18408
+ * The two tiers below the screen. Both are asked in view space, because the screen pass works there: the mapping to
18409
+ * the world is this class's, so a game answers one question in world space (what light arrives along this direction
18410
+ * at this point) and not two in two spaces.
18411
+ */
18412
+ #tiers() {
18413
+ const radiance = this.#radiance;
18414
+ const trace = this.#trace;
18415
+ const given = this.#fallback;
18416
+ if (radiance === void 0) return given === void 0 ? {} : { fallback: given };
18417
+ const mapping = defineWorldMapping(this.#camera);
18418
+ const cellSize = this.cacheCellSize;
18419
+ const fallback = given ?? ((position, direction2) => radiance(mapping.position(position), normalize(mapping.direction(direction2))));
18420
+ if (trace === void 0) return { fallback };
18421
+ return {
18422
+ // The tier below the screen along a ray that hit: what the cache holds there, which the composite already adds.
18423
+ fallback,
18424
+ // The tier past the screen along a ray that missed: the distance field continued to the cache's cell, then the
18425
+ // cache read where the ray ended, less the light this pixel already receives (the composite adds that too).
18426
+ miss: (position, direction2, normal2) => {
18427
+ const at3 = mapping.position(position);
18428
+ const towards = normalize(mapping.direction(direction2));
18429
+ const facing = normalize(mapping.direction(normal2));
18430
+ const offset = max(float(START_OFFSET), position.z.abs().mul(START_OFFSET_PER_METRE));
18431
+ const reached = at3.add(towards.mul(cellSize));
18432
+ const found = trace.trace({
18433
+ origin: at3.add(facing.mul(offset)),
18434
+ direction: towards,
18435
+ far: cellSize
18436
+ });
18437
+ const end = found.hit.greaterThan(0).select(found.position, reached);
18438
+ return radiance(end, towards).sub(radiance(at3, facing));
18439
+ }
18440
+ };
18441
+ }
18442
+ };
18443
+ var SHORT_RANGE_AO_MARKER = "TN_SHORT_RANGE_AO";
18444
+ var SLICE_COUNT = 2;
18445
+ var STEP_COUNT = 3;
18446
+ var REACH_PX = 32;
18447
+ var MAX_SLICES = 8;
18448
+ var MAX_STEPS = 8;
18449
+ var MIN_DISTANCE = 1e-5;
18450
+ var HALF_FLOAT_TYPE = 1016;
18451
+ var ShortRangeAO = class {
18452
+ report;
18453
+ horizonSearchSliceCount;
18454
+ horizonSearchStepCount;
18455
+ reachPx;
18456
+ bentNormal;
18457
+ intensity;
18458
+ #camera;
18459
+ #viewport;
18460
+ constructor(options) {
18461
+ const horizonSearchSliceCount = options.horizonSearchSliceCount ?? SLICE_COUNT;
18462
+ const horizonSearchStepCount = options.horizonSearchStepCount ?? STEP_COUNT;
18463
+ const reachPx = options.reachPx ?? REACH_PX;
18464
+ const intensity = options.intensity ?? 1;
18465
+ if (!(Number.isInteger(horizonSearchSliceCount) && horizonSearchSliceCount >= 1))
18466
+ throw new RangeError(
18467
+ `TN_SHORT_RANGE_AO: horizonSearchSliceCount ${horizonSearchSliceCount} must be a whole number of sweeps, at least 1`
18468
+ );
18469
+ if (!(Number.isInteger(horizonSearchStepCount) && horizonSearchStepCount >= 1))
18470
+ throw new RangeError(
18471
+ `TN_SHORT_RANGE_AO: horizonSearchStepCount ${horizonSearchStepCount} must be a whole number of samples, at least 1`
18472
+ );
18473
+ if (horizonSearchSliceCount > MAX_SLICES || horizonSearchStepCount > MAX_STEPS)
18474
+ throw new RangeError(
18475
+ `TN_SHORT_RANGE_AO: a sweep of ${horizonSearchSliceCount} x ${horizonSearchStepCount} is more than the pass compiles (${MAX_SLICES} x ${MAX_STEPS})`
18476
+ );
18477
+ if (!(reachPx > 0))
18478
+ throw new RangeError(
18479
+ `TN_SHORT_RANGE_AO: reachPx ${reachPx} must be pixels of the drawing buffer beyond 0`
18480
+ );
18481
+ if (!(intensity > 0))
18482
+ throw new RangeError(`TN_SHORT_RANGE_AO: intensity ${intensity} must be beyond 0`);
18483
+ if (!(options.viewport.width > 0 && options.viewport.height > 0))
18484
+ throw new RangeError(
18485
+ `TN_SHORT_RANGE_AO: viewport ${options.viewport.width}x${options.viewport.height} must be the drawing buffer`
18486
+ );
18487
+ if (options.camera?.projectionMatrix === void 0)
18488
+ throw new TypeError(
18489
+ "TN_SHORT_RANGE_AO_CAMERA: the pass needs the scene camera's projectionMatrix"
18490
+ );
18491
+ this.horizonSearchSliceCount = horizonSearchSliceCount;
18492
+ this.horizonSearchStepCount = horizonSearchStepCount;
18493
+ this.reachPx = reachPx;
18494
+ this.bentNormal = options.bentNormal ?? true;
18495
+ this.intensity = intensity;
18496
+ this.#camera = options.camera;
18497
+ this.#viewport = options.viewport;
18498
+ this.report = {
18499
+ horizonSearchSliceCount,
18500
+ horizonSearchStepCount,
18501
+ reachPx,
18502
+ samplesPerPixel: horizonSearchSliceCount * horizonSearchStepCount,
18503
+ bentNormal: this.bentNormal
18504
+ };
18505
+ if (options.marker !== false)
18506
+ console.info(`${SHORT_RANGE_AO_MARKER} ${JSON.stringify(this.report)}`);
18507
+ }
18508
+ /**
18509
+ * The occlusion of one frame: `rgb` the bent normal in view space, `a` the share of the hemisphere left open. `depth`
18510
+ * is the scene pass's depth target and `normal` its view-space normal target.
18511
+ */
18512
+ occlusion(depthNode, normalNode) {
18513
+ const element = (index) => uniform(this.#camera.projectionMatrix.elements[index] ?? 0).onRenderUpdate(
18514
+ () => this.#camera.projectionMatrix.elements[index] ?? 0
18515
+ );
18516
+ const [p0, p5, p8, p9, p10, p14] = [0, 5, 8, 9, 10, 14].map(element);
18517
+ const viewPosition = (coordinate, depth) => {
18518
+ const z = p14.negate().div(depth.add(p10));
18519
+ const ndc = vec2(coordinate.x.mul(2).sub(1), float(1).sub(coordinate.y).mul(2).sub(1));
18520
+ return vec3(z.negate().mul(ndc.x.add(p8)).div(p0), z.negate().mul(ndc.y.add(p9)).div(p5), z);
18521
+ };
18522
+ const slices = uniform(this.horizonSearchSliceCount);
18523
+ const steps = uniform(this.horizonSearchStepCount);
18524
+ const stepOffset = vec2(
18525
+ this.reachPx / this.#viewport.width,
18526
+ this.reachPx / this.#viewport.height
18527
+ );
18528
+ const intensity = uniform(this.intensity);
18529
+ const bent = this.bentNormal;
18530
+ const graph = Fn(() => {
18531
+ const coordinate = uv();
18532
+ const result = vec4(0, 0, 1, 1).toVar();
18533
+ const centreDepth = depthNode.sample(coordinate).r;
18534
+ const centreNormal = normalNode.sample(coordinate).xyz;
18535
+ If(centreDepth.lessThan(1).and(centreNormal.dot(centreNormal).greaterThan(0.25)), () => {
18536
+ const position = viewPosition(coordinate, centreDepth);
18537
+ const normal2 = normalize(centreNormal);
18538
+ const helper = normal2.y.abs().lessThan(0.99).select(vec3(0, 1, 0), vec3(1, 0, 0));
18539
+ const tangent = normalize(helper.cross(normal2));
18540
+ const bitangent = normal2.cross(tangent);
18541
+ const cell = coordinate.mul(2048).floor();
18542
+ const noise = cell.x.mul(0.06711056).add(cell.y.mul(583715e-8)).fract().mul(52.9829189).fract();
18543
+ const open = float(0).toVar();
18544
+ const direction2 = vec3(0, 0, 1).toVar();
18545
+ const bentNormal = vec3(0, 0, 0).toVar();
18546
+ Loop(
18547
+ { start: int(0), end: int(MAX_SLICES), type: "int", condition: "<" },
18548
+ ({ i: slice }) => {
18549
+ If(float(slice).greaterThanEqual(slices), () => {
18550
+ Break();
18551
+ });
18552
+ const angle = float(slice).add(noise).div(slices).mul(Math.PI);
18553
+ direction2.assign(normalize(tangent.mul(cos(angle)).add(bitangent.mul(sin(angle)))));
18554
+ const horizon = float(-1).toVar();
18555
+ Loop(
18556
+ { start: int(0), end: int(MAX_STEPS), type: "int", condition: "<" },
18557
+ ({ i: step3 }) => {
18558
+ If(float(step3).greaterThanEqual(steps), () => {
18559
+ Break();
18560
+ });
18561
+ const fraction = float(step3).add(1).div(steps);
18562
+ const sampleCoordinate = coordinate.add(
18563
+ stepOffset.mul(direction2.xy).mul(fraction.mul(fraction))
18564
+ );
18565
+ const sampleDepth = depthNode.sample(sampleCoordinate).r;
18566
+ const inside = sampleCoordinate.x.greaterThanEqual(0).and(sampleCoordinate.x.lessThanEqual(1)).and(sampleCoordinate.y.greaterThanEqual(0)).and(sampleCoordinate.y.lessThanEqual(1)).and(sampleDepth.lessThan(1));
18567
+ const delta = viewPosition(sampleCoordinate, sampleDepth).sub(position);
18568
+ const sine = delta.dot(normal2).div(max(length(delta), float(MIN_DISTANCE)));
18569
+ horizon.assign(max(horizon, inside.select(sine, float(-1))));
18570
+ }
18571
+ );
18572
+ const kept = clamp(float(1).sub(max(horizon, float(0))), float(0), float(1));
18573
+ open.assign(open.add(kept));
18574
+ if (bent)
18575
+ bentNormal.assign(
18576
+ bentNormal.add(direction2.mul(kept)).add(normal2.mul(kept.mul(0.5).add(0.25)))
18577
+ );
18578
+ }
18579
+ );
18580
+ const visibility = pow(clamp(open.div(slices), float(0), float(1)), intensity);
18581
+ const axis = bent ? normalize(normalize(bentNormal).add(normal2)) : normal2;
18582
+ result.assign(vec4(axis, visibility));
18583
+ });
18584
+ return result;
18585
+ })();
18586
+ const node = rtt(graph, null, null, { type: HALF_FLOAT_TYPE });
18587
+ return Object.defineProperties(node, {
18588
+ bentNormal: { value: bent },
18589
+ reachPx: { value: this.reachPx },
18590
+ slices: { value: this.horizonSearchSliceCount },
18591
+ steps: { value: this.horizonSearchStepCount }
18592
+ });
18593
+ }
18594
+ };
18225
18595
  var RECLAIM_AFTER_EMPTY_UPDATES = 4;
18226
18596
  var GROUPS_BUILT_PER_UPDATE = 4;
18227
18597
  var DEFAULT_DISTANCE_RATIO = 1.25;
18228
18598
  var DEFAULT_RECUT_FRACTION = 0.01;
18229
18599
  var DEFAULT_ERROR_PIXELS = 1;
18230
- var MIN_DISTANCE = 1e-3;
18600
+ var MIN_DISTANCE2 = 1e-3;
18601
+ var CULLED = -2147483648;
18231
18602
  var ClusteredBatchRoot = class _ClusteredBatchRoot extends Object3D {
18232
18603
  constructor(batch) {
18233
18604
  super();
@@ -18267,14 +18638,34 @@ var ClusteredBatch = class {
18267
18638
  #cameraWorld = new Vector3();
18268
18639
  #cameraLocal = new Vector3();
18269
18640
  #lastCut = new Vector3();
18641
+ #rotation = new Quaternion();
18642
+ #lastRotation = new Quaternion();
18643
+ #view = new ClusterView();
18270
18644
  #hasCut = false;
18271
18645
  #lastScale = 0;
18646
+ /** The projection the bands were chosen by: an aspect or zoom change keeps the pixel scale. */
18647
+ #lastProjection = new Matrix4();
18648
+ #culled = false;
18272
18649
  #distanceRatio;
18650
+ /** Radians the camera may turn before the bands are taken again. */
18651
+ viewMargin;
18652
+ /**
18653
+ * Whether copies the camera cannot see are skipped. Writable; the batch reports what it did
18654
+ * through {@link ClusteredBatch.viewCullReport}.
18655
+ */
18656
+ viewCull;
18273
18657
  /** Bands this camera wants that are not built yet; while any remain the cut cannot settle. */
18274
18658
  #pending = 0;
18275
18659
  #root = null;
18276
18660
  #built = null;
18277
18661
  #drawnTriangles = 0;
18662
+ #meshRadius;
18663
+ #frustum = new Frustum();
18664
+ #viewMatrix = new Matrix4();
18665
+ /** The band each copy was drawn in this update, or `CULLED` when it was not drawn at all. */
18666
+ #bandKey;
18667
+ #drawnCopiesOutsideView = 0;
18668
+ #drawnTrianglesOutsideView = 0;
18278
18669
  constructor(options) {
18279
18670
  this.#options = options;
18280
18671
  this.#distanceRatio = options.distanceRatio ?? DEFAULT_DISTANCE_RATIO;
@@ -18282,8 +18673,13 @@ var ClusteredBatch = class {
18282
18673
  throw new Error(
18283
18674
  `ClusteredBatch distanceRatio must be above one, got ${this.#distanceRatio}.`
18284
18675
  );
18676
+ this.viewCull = options.viewCull ?? true;
18677
+ this.viewMargin = options.viewMargin ?? DEFAULT_VIEW_MARGIN;
18678
+ assertViewMargin(this.viewMargin);
18285
18679
  this.#selection = new Uint32Array(options.table.ranges.length / 2);
18286
18680
  this.#wantedKey = new Int32Array(0);
18681
+ this.#bandKey = new Int32Array(0);
18682
+ this.#meshRadius = clusterTableRadius(options.table);
18287
18683
  }
18288
18684
  /** How many copies are placed. */
18289
18685
  get count() {
@@ -18299,6 +18695,30 @@ var ClusteredBatch = class {
18299
18695
  get drawnTriangles() {
18300
18696
  return this.#drawnTriangles;
18301
18697
  }
18698
+ /**
18699
+ * Copies the current cut submits whose own bounding sphere lies wholly outside the view volume.
18700
+ *
18701
+ * A measurement, not a cull: see {@link ClusteredMesh.drawnTrianglesOutsideView}.
18702
+ */
18703
+ get drawnCopiesOutsideView() {
18704
+ return this.#drawnCopiesOutsideView;
18705
+ }
18706
+ /** Triangles those copies submit: their own band's cut, times how many copies are outside. */
18707
+ get drawnTrianglesOutsideView() {
18708
+ return this.#drawnTrianglesOutsideView;
18709
+ }
18710
+ /**
18711
+ * What this batch does about copies outside the view, and why.
18712
+ *
18713
+ * `"on"` when copies the camera cannot see are skipped, and a reason when they are not — a batch
18714
+ * that silently kept drawing a whole copy behind the camera would be a cost with no symptom, and
18715
+ * one that silently dropped what a shadow camera can see would be a missing shadow with no cause.
18716
+ */
18717
+ get viewCullReport() {
18718
+ if (!this.viewCull) return "off (viewCull = false)";
18719
+ if (this.#built?.castShadow === true) return "off (castShadow)";
18720
+ return "on";
18721
+ }
18302
18722
  /** Adds one copy. Returns its index, so the game can move it later. */
18303
18723
  place(placement) {
18304
18724
  if (this.#built !== null)
@@ -18335,21 +18755,42 @@ var ClusteredBatch = class {
18335
18755
  const scale = pixelsPerUnit(camera, viewportHeight);
18336
18756
  camera.updateWorldMatrix(true, false);
18337
18757
  this.#cameraWorld.setFromMatrixPosition(camera.matrixWorld);
18758
+ camera.getWorldQuaternion(this.#rotation);
18759
+ const culled = this.viewCull && this.#built?.castShadow !== true;
18760
+ if (culled) {
18761
+ this.#view.setFromCamera(camera, this.viewMargin);
18762
+ root.updateWorldMatrix(true, false);
18763
+ this.#view.setTransform(root.matrixWorld);
18764
+ }
18338
18765
  let nearestCopy = Number.POSITIVE_INFINITY;
18339
18766
  for (const placed of this.#placed)
18340
18767
  nearestCopy = Math.min(nearestCopy, this.#cameraWorld.distanceTo(placed.position));
18341
- const settled = this.#hasCut && scale === this.#lastScale && this.#pending === 0 && this.#cameraWorld.distanceTo(this.#lastCut) <= Math.max(nearestCopy, MIN_DISTANCE) * (this.#options.recutFraction ?? DEFAULT_RECUT_FRACTION);
18768
+ const settled = this.#hasCut && culled === this.#culled && scale === this.#lastScale && camera.projectionMatrix.equals(this.#lastProjection) && this.#pending === 0 && this.#rotation.angleTo(this.#lastRotation) <= this.viewMargin && this.#cameraWorld.distanceTo(this.#lastCut) <= Math.max(nearestCopy, MIN_DISTANCE2) * (this.#options.recutFraction ?? DEFAULT_RECUT_FRACTION);
18342
18769
  if (settled) return this.#drawnTriangles;
18343
18770
  this.#lastCut.copy(this.#cameraWorld);
18771
+ this.#lastRotation.copy(this.#rotation);
18344
18772
  this.#lastScale = scale;
18773
+ this.#lastProjection.copy(camera.projectionMatrix);
18774
+ this.#culled = culled;
18345
18775
  this.#hasCut = true;
18346
- if (this.#wantedKey.length !== this.#placed.length)
18776
+ if (this.#wantedKey.length !== this.#placed.length) {
18347
18777
  this.#wantedKey = new Int32Array(this.#placed.length);
18778
+ this.#bandKey = new Int32Array(this.#placed.length);
18779
+ }
18348
18780
  for (const group of this.#groups.values()) group.copies.length = 0;
18349
18781
  const wantedKeys = /* @__PURE__ */ new Set();
18350
18782
  for (let copy = 0; copy < this.#placed.length; copy += 1) {
18351
18783
  const placed = this.#placed[copy];
18352
- const distance = Math.max(this.#cameraWorld.distanceTo(placed.position), MIN_DISTANCE);
18784
+ if (culled && !this.#view.touches(
18785
+ placed.position.x,
18786
+ placed.position.y,
18787
+ placed.position.z,
18788
+ this.#meshRadius * placed.scale
18789
+ )) {
18790
+ this.#wantedKey[copy] = CULLED;
18791
+ continue;
18792
+ }
18793
+ const distance = Math.max(this.#cameraWorld.distanceTo(placed.position), MIN_DISTANCE2);
18353
18794
  const wanted = Math.floor(Math.log(distance / placed.scale) / Math.log(this.#distanceRatio));
18354
18795
  this.#wantedKey[copy] = wanted;
18355
18796
  wantedKeys.add(wanted);
@@ -18369,7 +18810,12 @@ var ClusteredBatch = class {
18369
18810
  }
18370
18811
  for (let copy = 0; copy < this.#placed.length; copy += 1) {
18371
18812
  const wanted = this.#wantedKey[copy];
18813
+ if (wanted === CULLED) {
18814
+ this.#bandKey[copy] = CULLED;
18815
+ continue;
18816
+ }
18372
18817
  const key = open.has(wanted) ? wanted : this.#nearestOpenKey(wanted, open);
18818
+ this.#bandKey[copy] = key;
18373
18819
  let group = this.#groups.get(key);
18374
18820
  if (group === void 0) {
18375
18821
  group = { copies: [], cut: new Uint32Array(0), empty: 0, mesh: null };
@@ -18385,8 +18831,31 @@ var ClusteredBatch = class {
18385
18831
  this.#groups.delete(key);
18386
18832
  }
18387
18833
  }
18834
+ this.#countOutsideView(camera);
18388
18835
  return this.#drawnTriangles;
18389
18836
  }
18837
+ /**
18838
+ * Records how many copies of this batch, and how many of their triangles, lie wholly out of view.
18839
+ *
18840
+ * A copy is tested on its own bounding sphere — the body's radius at the copy's scale — which is
18841
+ * the sphere three itself would cull it by. Read-only, and taken only on a frame that re-cut.
18842
+ */
18843
+ #countOutsideView(camera) {
18844
+ const frustum = worldFrustum(camera, this.#frustum, this.#viewMatrix);
18845
+ let copies = 0;
18846
+ let triangles = 0;
18847
+ for (let copy = 0; copy < this.#placed.length; copy += 1) {
18848
+ if (this.#bandKey[copy] === CULLED) continue;
18849
+ const placed = this.#placed[copy];
18850
+ if (!outsideFrustum(frustum, placed.position, this.#meshRadius * placed.scale)) continue;
18851
+ copies += 1;
18852
+ const group = this.#groups.get(this.#bandKey[copy]);
18853
+ const mesh = group?.mesh;
18854
+ if (mesh?.visible === true) triangles += mesh.geometry.drawRange.count / 3;
18855
+ }
18856
+ this.#drawnCopiesOutsideView = copies;
18857
+ this.#drawnTrianglesOutsideView = triangles;
18858
+ }
18390
18859
  /**
18391
18860
  * Gives one group's index buffer back.
18392
18861
  *
@@ -18495,7 +18964,7 @@ var ClusteredBatch = class {
18495
18964
  #capacityFor(group, anchor, nearestDistance, scale) {
18496
18965
  const nearEdge = this.#distanceRatio ** Math.floor(Math.log(nearestDistance) / Math.log(this.#distanceRatio));
18497
18966
  const direction2 = this.#cameraLocal.clone().normalize();
18498
- const probe = direction2.multiplyScalar(Math.max(nearEdge, MIN_DISTANCE));
18967
+ const probe = direction2.multiplyScalar(Math.max(nearEdge, MIN_DISTANCE2));
18499
18968
  const selected = selectClusterCut(
18500
18969
  this.#options.table,
18501
18970
  probe,
@@ -19398,8 +19867,8 @@ function octahedralCellCentre(cell, resolution) {
19398
19867
  v = (1 - Math.abs(u)) * (v >= 0 ? 1 : -1);
19399
19868
  u = fu;
19400
19869
  }
19401
- const length7 = Math.hypot(u, v, z) || 1;
19402
- return [u / length7, v / length7, z / length7];
19870
+ const length8 = Math.hypot(u, v, z) || 1;
19871
+ return [u / length8, v / length8, z / length8];
19403
19872
  }
19404
19873
  function octahedralRayTable(directions, count, resolution) {
19405
19874
  const cells = resolution * resolution;
@@ -19486,7 +19955,7 @@ function createProbeTraceKernels(scene, grid, raysPerProbe, maxBatch, pointCount
19486
19955
  );
19487
19956
  const volumeMin = vec3(grid.min.x, grid.min.y, grid.min.z);
19488
19957
  const far = 4 * Math.max(grid.size.x, grid.size.y, grid.size.z, 1) + 1e4;
19489
- const previousIrradiance = (point, normal) => {
19958
+ const previousIrradiance = (point, normal2) => {
19490
19959
  const local2 = clamp(
19491
19960
  point.sub(volumeMin).div(vec3(spacing.x, spacing.y, spacing.z)),
19492
19961
  vec3(0),
@@ -19508,7 +19977,7 @@ function createProbeTraceKernels(scene, grid, raysPerProbe, maxBatch, pointCount
19508
19977
  );
19509
19978
  const weight = (dx ? fraction.x : float(1).sub(fraction.x)).mul(dy ? fraction.y : float(1).sub(fraction.y)).mul(dz ? fraction.z : float(1).sub(fraction.z)).mul(open);
19510
19979
  const coefficient = (index) => coefficientNode.element(probe.mul(int(9)).add(int(index))).xyz;
19511
- sum = sum.add(shIrradiance(coefficient, normal).mul(weight));
19980
+ sum = sum.add(shIrradiance(coefficient, normal2).mul(weight));
19512
19981
  total = total.add(weight);
19513
19982
  }
19514
19983
  return sum.div(max(total, 1e-4));
@@ -19546,15 +20015,15 @@ function createProbeTraceKernels(scene, grid, raysPerProbe, maxBatch, pointCount
19546
20015
  for (const light of points) {
19547
20016
  const toLight = light.position.sub(point);
19548
20017
  const squared = max(dot(toLight, toLight), 1e-4);
19549
- const length7 = sqrt(squared);
19550
- const toward = toLight.div(length7);
20018
+ const length8 = sqrt(squared);
20019
+ const toward = toLight.div(length8);
19551
20020
  const facingLight = max(dot(facing, toward), 0);
19552
20021
  If(facingLight.greaterThan(0), () => {
19553
- const shadow2 = traceRay(buffers, nodeCount, point, toward, length7.sub(0.02), true);
20022
+ const shadow2 = traceRay(buffers, nodeCount, point, toward, length8.sub(0.02), true);
19554
20023
  If(shadow2.triangle.lessThan(0), () => {
19555
20024
  const window = select(
19556
20025
  light.distance.greaterThan(0),
19557
- pow(clamp(float(1).sub(pow(length7.div(light.distance), 4)), 0, 1), 2),
20026
+ pow(clamp(float(1).sub(pow(length8.div(light.distance), 4)), 0, 1), 2),
19558
20027
  float(1)
19559
20028
  );
19560
20029
  direct.addAssign(light.radiance.mul(facingLight.mul(window).div(squared)));
@@ -19577,9 +20046,9 @@ function createProbeTraceKernels(scene, grid, raysPerProbe, maxBatch, pointCount
19577
20046
  Loop(
19578
20047
  { start: int(0), end: int(raysPerProbe), type: "int", condition: "<" },
19579
20048
  ({ i }) => {
19580
- const sample = radianceNode.element(slot.mul(int(raysPerProbe)).add(i));
19581
- const value = sample.xyz;
19582
- backfaces.addAssign(select(sample.w.lessThan(0), float(1), float(0)));
20049
+ const sample2 = radianceNode.element(slot.mul(int(raysPerProbe)).add(i));
20050
+ const value = sample2.xyz;
20051
+ backfaces.addAssign(select(sample2.w.lessThan(0), float(1), float(0)));
19583
20052
  const d = directions.element(i);
19584
20053
  add(0, value.mul(0.282095));
19585
20054
  add(1, value.mul(d.y.mul(0.488603)));
@@ -19622,9 +20091,9 @@ function createProbeTraceKernels(scene, grid, raysPerProbe, maxBatch, pointCount
19622
20091
  const depth = float(0).toVar();
19623
20092
  Loop({ start: int(0), end: count, type: "int", condition: "<" }, ({ i }) => {
19624
20093
  const ray = int(cellRays.element(first.add(i)).x);
19625
- const sample = radianceNode.element(slot.mul(int(raysPerProbe)).add(ray));
19626
- sum.addAssign(sample.xyz);
19627
- depth.addAssign(abs(sample.w));
20094
+ const sample2 = radianceNode.element(slot.mul(int(raysPerProbe)).add(ray));
20095
+ sum.addAssign(sample2.xyz);
20096
+ depth.addAssign(abs(sample2.w));
19628
20097
  });
19629
20098
  mapNode.element(probe.mul(int(cells)).add(cell)).assign(vec4(sum.div(float(count)), depth.div(float(count))));
19630
20099
  })().compute(maxBatch * cells);
@@ -20108,14 +20577,14 @@ var ProbeVolume = class extends Object3D {
20108
20577
  sceneOrOptions ?? {}
20109
20578
  );
20110
20579
  }
20111
- sample(position = positionWorld, normal = normalWorld) {
20112
- if (position instanceof Vector3 && normal instanceof Vector3) {
20113
- return this.sampleIrradiance(position, normal);
20580
+ sample(position = positionWorld, normal2 = normalWorld) {
20581
+ if (position instanceof Vector3 && normal2 instanceof Vector3) {
20582
+ return this.sampleIrradiance(position, normal2);
20114
20583
  }
20115
- return this.sampleNode(position, normal);
20584
+ return this.sampleNode(position, normal2);
20116
20585
  }
20117
- sampleIrradiance(position, normal) {
20118
- return this.#evaluateCpu(position, normal, SH_IRRADIANCE_WEIGHTS, "sampleIrradiance");
20586
+ sampleIrradiance(position, normal2) {
20587
+ return this.#evaluateCpu(position, normal2, SH_IRRADIANCE_WEIGHTS, "sampleIrradiance");
20119
20588
  }
20120
20589
  /**
20121
20590
  * The radiance arriving along `direction` (the SH itself, not convolved with a cosine lobe), clamped at zero. A
@@ -20125,12 +20594,12 @@ var ProbeVolume = class extends Object3D {
20125
20594
  sampleRadiance(position, direction2) {
20126
20595
  return this.#evaluateCpu(position, direction2, SH_RADIANCE_WEIGHTS, "sampleRadiance");
20127
20596
  }
20128
- #evaluateCpu(position, normal, weights, name) {
20129
- if (!(position instanceof Vector3) || !(normal instanceof Vector3)) {
20597
+ #evaluateCpu(position, normal2, weights, name) {
20598
+ if (!(position instanceof Vector3) || !(normal2 instanceof Vector3)) {
20130
20599
  throw new Error(`ProbeVolume.${name} requires Vector3 position and normal values.`);
20131
20600
  }
20132
20601
  const coefficients = this.#samplePackedCoefficients(position);
20133
- const direction2 = normal.clone().normalize();
20602
+ const direction2 = normal2.clone().normalize();
20134
20603
  const result = new Vector3();
20135
20604
  result.x = evaluateShChannel(coefficients, 0, direction2, weights);
20136
20605
  result.y = evaluateShChannel(coefficients, 1, direction2, weights);
@@ -20157,8 +20626,8 @@ var ProbeVolume = class extends Object3D {
20157
20626
  );
20158
20627
  }
20159
20628
  /** The GPU graph used by `sample`; exposed so generated materials can compose it explicitly. */
20160
- sampleNode(position = positionWorld, normal = normalWorld) {
20161
- return this.#shNode(position, normal, SH_IRRADIANCE_WEIGHTS);
20629
+ sampleNode(position = positionWorld, normal2 = normalWorld) {
20630
+ return this.#shNode(position, normal2, SH_IRRADIANCE_WEIGHTS);
20162
20631
  }
20163
20632
  /** The GPU graph of `sampleRadiance`: the radiance arriving along `direction`, clamped at zero. */
20164
20633
  sampleRadianceNode(position = positionWorld, direction2 = normalWorld) {
@@ -20284,7 +20753,7 @@ var ProbeVolume = class extends Object3D {
20284
20753
  sum = sum.add(texture(map, this.#mapTexelNode(probe, cell)).rgb.mul(weight));
20285
20754
  return sum.div(total.max(1e-6)).max(0);
20286
20755
  }
20287
- #shNode(position, normal, w) {
20756
+ #shNode(position, normal2, w) {
20288
20757
  const atlasAt = this.#atlasAt(position);
20289
20758
  const packed = this.#visibility ? this.#visiblePacked(position) : (subVolume) => this.#atlasNode.sample(atlasAt(subVolume));
20290
20759
  const packedValues = Array.from(
@@ -20303,7 +20772,7 @@ var ProbeVolume = class extends Object3D {
20303
20772
  vec3(packedAt(5).y, packedAt(5).z, packedAt(5).w),
20304
20773
  vec3(packedAt(6).x, packedAt(6).y, packedAt(6).z)
20305
20774
  ];
20306
- const direction2 = normalize(vec3(normal));
20775
+ const direction2 = normalize(vec3(normal2));
20307
20776
  const coefficientAt = (index) => valueAt2(coefficients, index, "SH coefficient");
20308
20777
  const value = coefficientAt(0).mul(w.l0).add(coefficientAt(1).mul(direction2.y).mul(w.l1)).add(coefficientAt(2).mul(direction2.z).mul(w.l1)).add(coefficientAt(3).mul(direction2.x).mul(w.l1)).add(coefficientAt(4).mul(direction2.x.mul(direction2.y)).mul(w.l2)).add(coefficientAt(5).mul(direction2.y.mul(direction2.z)).mul(w.l2)).add(coefficientAt(6).mul(direction2.z.mul(direction2.z).mul(w.l20).sub(w.l20Offset))).add(coefficientAt(7).mul(direction2.x.mul(direction2.z)).mul(w.l2)).add(
20309
20778
  coefficientAt(8).mul(direction2.x.mul(direction2.x).sub(direction2.y.mul(direction2.y))).mul(w.l22)
@@ -21272,9 +21741,9 @@ function clampedTextureCoordinate(value, size) {
21272
21741
  function uniquePair(lower, upper) {
21273
21742
  return lower === upper ? [lower] : [lower, upper];
21274
21743
  }
21275
- function interpolationFactor(sample, lower, upper, fraction) {
21744
+ function interpolationFactor(sample2, lower, upper, fraction) {
21276
21745
  if (lower === upper) return 1;
21277
- return sample === lower ? 1 - fraction : fraction;
21746
+ return sample2 === lower ? 1 - fraction : fraction;
21278
21747
  }
21279
21748
  function createCpuAtlas(data, resolution, depth) {
21280
21749
  const atlas = new Data3DTexture(data, resolution.x, resolution.y, depth);
@@ -21338,10 +21807,10 @@ function createRepackMaterials(batchTextureNode, slice, dimensions, probeCount)
21338
21807
  const ix = floor(viewportCoordinate.x);
21339
21808
  const iy = floor(viewportCoordinate.y);
21340
21809
  const probe = ix.add(iy.mul(dimensions.x)).add(int(slice).mul(dimensions.x * dimensions.y));
21341
- const uv7 = vec2(probe.add(0.5).div(probeCount), 0);
21810
+ const uv8 = vec2(probe.add(0.5).div(probeCount), 0);
21342
21811
  const samples = Array.from(
21343
21812
  { length: SH_COEFFICIENT_COUNT },
21344
- (_, index) => batchTextureNode.sample(vec2((index + 0.5) / SH_COEFFICIENT_COUNT, uv7.x))
21813
+ (_, index) => batchTextureNode.sample(vec2((index + 0.5) / SH_COEFFICIENT_COUNT, uv8.x))
21345
21814
  );
21346
21815
  const sampleAt2 = (index) => valueAt2(samples, index, "repack sample");
21347
21816
  const values = [
@@ -21391,27 +21860,27 @@ var SH_RADIANCE_WEIGHTS = {
21391
21860
  l20Offset: 0.315392,
21392
21861
  l22: 0.546274
21393
21862
  };
21394
- function evaluateShChannel(coefficients, channel, normal, w) {
21863
+ function evaluateShChannel(coefficients, channel, normal2, w) {
21395
21864
  const c = (index) => coefficients[index * SH_CHANNEL_COUNT + channel] ?? 0;
21396
- return c(0) * w.l0 + c(1) * normal.y * w.l1 + c(2) * normal.z * w.l1 + c(3) * normal.x * w.l1 + c(4) * normal.x * normal.y * w.l2 + c(5) * normal.y * normal.z * w.l2 + c(6) * (normal.z * normal.z * w.l20 - w.l20Offset) + c(7) * normal.x * normal.z * w.l2 + c(8) * (normal.x * normal.x - normal.y * normal.y) * w.l22;
21865
+ return c(0) * w.l0 + c(1) * normal2.y * w.l1 + c(2) * normal2.z * w.l1 + c(3) * normal2.x * w.l1 + c(4) * normal2.x * normal2.y * w.l2 + c(5) * normal2.y * normal2.z * w.l2 + c(6) * (normal2.z * normal2.z * w.l20 - w.l20Offset) + c(7) * normal2.x * normal2.z * w.l2 + c(8) * (normal2.x * normal2.x - normal2.y * normal2.y) * w.l22;
21397
21866
  }
21398
21867
  function normalizeBounds(value) {
21399
21868
  const min8 = new Vector3(value.min.x, value.min.y, value.min.z);
21400
- const max9 = new Vector3(value.max.x, value.max.y, value.max.z);
21869
+ const max11 = new Vector3(value.max.x, value.max.y, value.max.z);
21401
21870
  for (const [name, vector3] of [
21402
21871
  ["min", min8],
21403
- ["max", max9]
21872
+ ["max", max11]
21404
21873
  ]) {
21405
21874
  if (![vector3.x, vector3.y, vector3.z].every(Number.isFinite)) {
21406
21875
  throw new Error(`ProbeVolume bounds.${name} must contain finite x, y, and z values.`);
21407
21876
  }
21408
21877
  }
21409
- if (!(min8.x < max9.x && min8.y < max9.y && min8.z < max9.z)) {
21878
+ if (!(min8.x < max11.x && min8.y < max11.y && min8.z < max11.z)) {
21410
21879
  throw new Error(
21411
21880
  "ProbeVolume bounds must be non-degenerate and min must be below max on every axis."
21412
21881
  );
21413
21882
  }
21414
- return new Box3(min8, max9);
21883
+ return new Box3(min8, max11);
21415
21884
  }
21416
21885
  function normalizeDensity(value) {
21417
21886
  let density;
@@ -21584,9 +22053,9 @@ function isFiniteNonNegative(value) {
21584
22053
  function isFinitePositive(value) {
21585
22054
  return typeof value === "number" && Number.isFinite(value) && value > 0;
21586
22055
  }
21587
- function validateProbeIndex(index, length7, name) {
21588
- if (!Number.isSafeInteger(index) || index < 0 || index >= length7) {
21589
- throw new Error(`ProbeVolume ${name} must be an integer in [0, ${length7 - 1}].`);
22056
+ function validateProbeIndex(index, length8, name) {
22057
+ if (!Number.isSafeInteger(index) || index < 0 || index >= length8) {
22058
+ throw new Error(`ProbeVolume ${name} must be an integer in [0, ${length8 - 1}].`);
21590
22059
  }
21591
22060
  }
21592
22061
  function valueAt2(values, index, label2) {
@@ -21801,11 +22270,11 @@ var SurfaceLights = class {
21801
22270
  #scores;
21802
22271
  #order = [];
21803
22272
  constructor(lights, options = {}) {
21804
- const max9 = options.maxLights ?? 8;
21805
- if (!Number.isInteger(max9) || max9 < 1)
21806
- throw new RangeError(`maxLights ${max9} must be an integer of 1 or more`);
22273
+ const max11 = options.maxLights ?? 8;
22274
+ if (!Number.isInteger(max11) || max11 < 1)
22275
+ throw new RangeError(`maxLights ${max11} must be an integer of 1 or more`);
21807
22276
  this.#lights = lights;
21808
- this.#max = max9;
22277
+ this.#max = max11;
21809
22278
  this.#scores = new Array(lights.length).fill(0);
21810
22279
  }
21811
22280
  /**
@@ -21813,11 +22282,11 @@ var SurfaceLights = class {
21813
22282
  * (x cone for a spot). `visible(i)` answers the shadow ray to light `i`; it is not asked for a light behind the
21814
22283
  * surface, out of range or outside its cone.
21815
22284
  */
21816
- shade(point, normal, albedo, out, visible) {
22285
+ shade(point, normal2, albedo, out, visible) {
21817
22286
  const order = this.#order;
21818
22287
  order.length = 0;
21819
22288
  for (let i = 0; i < this.#lights.length; i += 1) {
21820
- const score = this.#score(this.#lights[i], point, normal);
22289
+ const score = this.#score(this.#lights[i], point, normal2);
21821
22290
  this.#scores[i] = score;
21822
22291
  if (score > 0) order.push(i);
21823
22292
  }
@@ -21837,8 +22306,8 @@ var SurfaceLights = class {
21837
22306
  const [dx, dy, dz] = [light.position[0] - px, light.position[1] - py, light.position[2] - pz];
21838
22307
  const d = Math.hypot(dx, dy, dz);
21839
22308
  if (d < 0.02 || light.distance > 0 && d >= light.distance) return 0;
21840
- const cos2 = (nx * dx + ny * dy + nz * dz) / d;
21841
- if (cos2 <= 0) return 0;
22309
+ const cos3 = (nx * dx + ny * dy + nz * dz) / d;
22310
+ if (cos3 <= 0) return 0;
21842
22311
  const window = light.distance > 0 ? Math.min(1, Math.max(0, 1 - (d / light.distance) ** 4)) ** 2 : 1;
21843
22312
  let cone = 1;
21844
22313
  if (light.kind === "spot") {
@@ -21849,7 +22318,7 @@ var SurfaceLights = class {
21849
22318
  const t = Math.min(1, Math.max(0, (toHit - outer) / Math.max(inner - outer, 1e-6)));
21850
22319
  cone = t * t * (3 - 2 * t);
21851
22320
  }
21852
- return light.intensity / Math.PI / (d * d) * window * cos2 * cone;
22321
+ return light.intensity / Math.PI / (d * d) * window * cos3 * cone;
21853
22322
  }
21854
22323
  };
21855
22324
  function shadowInput(node) {
@@ -21936,7 +22405,7 @@ function sourceAngleShadowFilter({
21936
22405
  ).div(shadowInput(reference("zoom", "float", camera)));
21937
22406
  const texel = vec2(1).div(size);
21938
22407
  const isArray = "isArrayTexture" in depthTexture && depthTexture.isArrayTexture === true;
21939
- const withLayer = (sample) => isArray ? sample.depth(float(depthLayer)) : sample;
22408
+ const withLayer = (sample2) => isArray ? sample2.depth(float(depthLayer)) : sample2;
21940
22409
  const linearDepth2 = (depth) => reversed ? depth.oneMinus() : depth;
21941
22410
  return Fn(
21942
22411
  (_inputs, builder) => {
@@ -21945,11 +22414,11 @@ function sourceAngleShadowFilter({
21945
22414
  const searchRadius = max(texel, vec2(receiver.mul(range).mul(reach)).div(span)).toVar();
21946
22415
  const blockerSum = float(0).toVar();
21947
22416
  const blockerCount = float(0).toVar();
21948
- const load = (uv7) => linearDepth2(
22417
+ const load = (uv8) => linearDepth2(
21949
22418
  withLayer(
21950
22419
  textureLoad(
21951
22420
  depthTexture,
21952
- ivec2(min(max(uv7.mul(size).floor(), vec2(0)), size.sub(1)))
22421
+ ivec2(min(max(uv8.mul(size).floor(), vec2(0)), size.sub(1)))
21953
22422
  )
21954
22423
  ).r
21955
22424
  );
@@ -22141,7 +22610,7 @@ function sourceRadiusShadowFilter({
22141
22610
  const tanHalf = uniform(1).setGroup(renderGroup).onRenderUpdate(() => Math.tan(camera.fov * Math.PI / 360) / camera.zoom);
22142
22611
  const uvPerTangent = float(0.5).div(tanHalf);
22143
22612
  const sizes = vec2(size);
22144
- const load = (uv7) => textureLoad(depthTexture, ivec2(min(max(uv7.mul(sizes).floor(), vec2(0)), sizes.sub(1)))).r;
22613
+ const load = (uv8) => textureLoad(depthTexture, ivec2(min(max(uv8.mul(sizes).floor(), vec2(0)), sizes.sub(1)))).r;
22145
22614
  return Fn(() => {
22146
22615
  const receiver = distanceOf(shadowCoord.z).toVar();
22147
22616
  const slope = slopeOf(dFdx(shadowCoord.xy), dFdy(shadowCoord.xy), receiver, uvPerTangent);
@@ -22447,7 +22916,7 @@ function dot5(a, b) {
22447
22916
  function cross5(a, b) {
22448
22917
  return { x: a.y * b.z - a.z * b.y, y: a.z * b.x - a.x * b.z, z: a.x * b.y - a.y * b.x };
22449
22918
  }
22450
- function normalize3(vector3) {
22919
+ function normalize5(vector3) {
22451
22920
  const magnitude = Math.sqrt(dot5(vector3, vector3));
22452
22921
  if (magnitude <= EPSILON3) throw new RangeError("direction must have non-zero length");
22453
22922
  return { x: vector3.x / magnitude, y: vector3.y / magnitude, z: vector3.z / magnitude };
@@ -22545,7 +23014,7 @@ var DirectionalClipmap = class {
22545
23014
  this.refreshStep = clipExtents.map((_, level) => this.#perLevel(steps, level));
22546
23015
  this.selectionGuard = guards;
22547
23016
  this.levelCount = clipExtents.length;
22548
- this.basisW = normalize3(direction2);
23017
+ this.basisW = normalize5(direction2);
22549
23018
  this.basisU = { x: 1, y: 0, z: 0 };
22550
23019
  this.basisV = { x: 0, y: 0, z: 1 };
22551
23020
  this.setDirection(direction2);
@@ -22553,12 +23022,12 @@ var DirectionalClipmap = class {
22553
23022
  /** Re-orient the basis; returns true when it changed enough that cached pages are stale. */
22554
23023
  setDirection(direction2) {
22555
23024
  assertFiniteVector("direction", direction2);
22556
- const nextW = normalize3(direction2);
23025
+ const nextW = normalize5(direction2);
22557
23026
  const unchanged = this.#windows.length > 0 && Math.abs(dot5(nextW, this.basisW) - 1) <= 1e-9;
22558
23027
  this.basisW = nextW;
22559
23028
  const reference3 = Math.abs(this.basisW.y) > 0.95 ? { x: 0, y: 0, z: 1 } : { x: 0, y: 1, z: 0 };
22560
- this.basisU = normalize3(cross5(this.basisW, reference3));
22561
- this.basisV = normalize3(cross5(this.basisW, this.basisU));
23029
+ this.basisU = normalize5(cross5(this.basisW, reference3));
23030
+ this.basisV = normalize5(cross5(this.basisW, this.basisU));
22562
23031
  this.vScale = Math.abs(this.basisW.y) > 0.95 ? 1 : Math.min(1, Math.max(this.minAspect, Math.abs(this.basisW.y)));
22563
23032
  if (!unchanged) this.#windows = [];
22564
23033
  this.updateCenter(this.centerWorld);
@@ -24210,8 +24679,8 @@ var VirtualShadowNode = class extends ShadowBaseNode {
24210
24679
  const extent = level.extent;
24211
24680
  const side = extent * Math.SQRT2;
24212
24681
  const fits = extent * 2 * MAX_MASS_WINDOW_WIDTHS;
24213
- const sin2 = basisW.y;
24214
- if (sin2 < MIN_SUN_COSINE) return void 0;
24682
+ const sin3 = basisW.y;
24683
+ if (sin3 < MIN_SUN_COSINE) return void 0;
24215
24684
  const heightReach = extent * (Math.abs(basisU.y) + Math.abs(basisV.y));
24216
24685
  let low2 = Number.POSITIVE_INFINITY;
24217
24686
  let high2 = Number.NEGATIVE_INFINITY;
@@ -24229,8 +24698,8 @@ var VirtualShadowNode = class extends ShadowBaseNode {
24229
24698
  const boxLow = pool[at3 + 5];
24230
24699
  const boxHigh = pool[at3 + 6];
24231
24700
  if (radius * 2 > fits) {
24232
- const from = (boxLow - centre.y - heightReach) / sin2;
24233
- const to = (boxHigh - centre.y + heightReach) / sin2;
24701
+ const from = (boxLow - centre.y - heightReach) / sin3;
24702
+ const to = (boxHigh - centre.y + heightReach) / sin3;
24234
24703
  if (from < low2) low2 = from;
24235
24704
  if (to > high2) high2 = to;
24236
24705
  continue;
@@ -24402,10 +24871,10 @@ var VirtualShadowNode = class extends ShadowBaseNode {
24402
24871
  const filter = stock.setupShadowFilter;
24403
24872
  stock.setupShadowFilter = (builder2, inputs) => {
24404
24873
  const levelTint = this.#levelTints.get(builder2);
24405
- const uv7 = inputs.shadowCoord;
24874
+ const uv8 = inputs.shadowCoord;
24406
24875
  const inside = and(
24407
- and(uv7.x.greaterThanEqual(0), uv7.x.lessThanEqual(1)),
24408
- and(uv7.y.greaterThanEqual(0), uv7.y.lessThanEqual(1))
24876
+ and(uv8.x.greaterThanEqual(0), uv8.x.lessThanEqual(1)),
24877
+ and(uv8.y.greaterThanEqual(0), uv8.y.lessThanEqual(1))
24409
24878
  );
24410
24879
  const colour = index === 0 ? vec3(1, 0, 0) : index === 1 ? vec3(0, 1, 0) : index === 2 ? vec3(0, 0, 1) : vec3(1, 1, 0);
24411
24880
  if (levelTint === void 0) return filter.call(stock, builder2, inputs);
@@ -24493,10 +24962,10 @@ var VirtualShadowNode = class extends ShadowBaseNode {
24493
24962
  this.setupShadowPosition(builder);
24494
24963
  if (this.options.receiverPlaneBias) {
24495
24964
  const received = vec3(shadowPositionWorld);
24496
- const normal = dFdx(received).cross(dFdy(received)).toVar();
24497
- const along = max(abs(normal.dot(this.#basisW)), max(length(normal).mul(1e-4), 1e-12));
24965
+ const normal2 = dFdx(received).cross(dFdy(received)).toVar();
24966
+ const along = max(abs(normal2.dot(this.#basisW)), max(length(normal2).mul(1e-4), 1e-12));
24498
24967
  this.#receiverSlope.assign(
24499
- abs(normal.dot(basisU)).add(abs(normal.dot(basisV)).div(basisV.dot(basisV))).div(along)
24968
+ abs(normal2.dot(basisU)).add(abs(normal2.dot(basisV)).div(basisV.dot(basisV))).div(along)
24500
24969
  );
24501
24970
  }
24502
24971
  const u = positionWorld.dot(vec3(basisU)).sub(centerU);
@@ -25007,7 +25476,7 @@ function roughDiffuseFactor(albedo, r, nov, nol, vol) {
25007
25476
  function roughen(model) {
25008
25477
  const lambert = model.direct;
25009
25478
  model.direct = function direct(input, builder) {
25010
- const scratch3 = vec3(0).toVar();
25479
+ const scratch4 = vec3(0).toVar();
25011
25480
  const specular = vec3(0).toVar();
25012
25481
  lambert.call(
25013
25482
  this,
@@ -25015,7 +25484,7 @@ function roughen(model) {
25015
25484
  ...input,
25016
25485
  reflectedLight: {
25017
25486
  ...input.reflectedLight,
25018
- directDiffuse: scratch3,
25487
+ directDiffuse: scratch4,
25019
25488
  directSpecular: specular
25020
25489
  }
25021
25490
  },
@@ -25038,7 +25507,7 @@ function roughen(model) {
25038
25507
  const factor = roughDiffuseFactor(albedo, r, nov, nol, vol).div(
25039
25508
  fresnel.oneMinus().max(EPSILON4)
25040
25509
  );
25041
- input.reflectedLight.directDiffuse.addAssign(scratch3.mul(factor));
25510
+ input.reflectedLight.directDiffuse.addAssign(scratch4.mul(factor));
25042
25511
  const weight3 = this.multiScatteringCompensation;
25043
25512
  input.reflectedLight.directSpecular.addAssign(
25044
25513
  weight3 === void 0 ? specular : specular.div(weight3)
@@ -25265,10 +25734,10 @@ function adaptExposure(histogram, previous, resetMode, seed, delta, policy, deco
25265
25734
  const fresh = resetMode.equal(2).or(resetMode.equal(0).and(history.g.lessThanEqual(0)));
25266
25735
  const error = goal.sub(old);
25267
25736
  const rate = error.greaterThan(0).select(float(policy.rateUp), float(policy.rateDown));
25268
- const normal = float(1).sub(delta.mul(rate).negate().exp());
25737
+ const normal2 = float(1).sub(delta.mul(rate).negate().exp());
25269
25738
  const cut = smoothstep(policy.snapLo, policy.snapHi, error.abs()).mul(policy.snapGain);
25270
25739
  const adapted = valid.select(
25271
- fresh.select(goal, mix(old, goal, mix(normal, float(1), cut))),
25740
+ fresh.select(goal, mix(old, goal, mix(normal2, float(1), cut))),
25272
25741
  old
25273
25742
  );
25274
25743
  const settled = goal.sub(adapted).abs().lessThanEqual(policy.settleStops).select(1, 0);
@@ -25404,7 +25873,7 @@ var AutoExposureNode = class extends Node {
25404
25873
  #gateSkips;
25405
25874
  // Three's runtime accepts undefined on first use, but its declaration requires a state.
25406
25875
  #rendererState;
25407
- constructor(input, settings, constantExposure, meter = (colour, uv7) => exposureMeter(colour), decode = (mean2) => exposureLuminance(mean2)) {
25876
+ constructor(input, settings, constantExposure, meter = (colour, uv8) => exposureMeter(colour), decode = (mean2) => exposureLuminance(mean2)) {
25408
25877
  super("float");
25409
25878
  validateExposureSettings(settings);
25410
25879
  if (!Number.isFinite(Math.fround(constantExposure)) || Math.fround(constantExposure) <= 0)
@@ -25567,9 +26036,9 @@ function cacheFallback(camera) {
25567
26036
  if (read === void 0) return void 0;
25568
26037
  const live = (index) => uniform(0).onRenderUpdate(() => camera.matrixWorld.elements[index] ?? 0);
25569
26038
  const column = (a) => vec3(live(a), live(a + 1), live(a + 2));
25570
- const [right, up, back, at3] = [column(0), column(4), column(8), column(12)];
25571
- const toWorld = (v) => right.mul(v.x).add(up.mul(v.y)).add(back.mul(v.z));
25572
- return (position, normal) => read(toWorld(position).add(at3), toWorld(normal).normalize());
26039
+ const [right, up2, back, at3] = [column(0), column(4), column(8), column(12)];
26040
+ const toWorld = (v) => right.mul(v.x).add(up2.mul(v.y)).add(back.mul(v.z));
26041
+ return (position, normal2) => read(toWorld(position).add(at3), toWorld(normal2).normalize());
25573
26042
  }
25574
26043
  var localExposureSettings = {
25575
26044
  /** Scale on how far a bright base sits above middle grey; 1 leaves the global exposure alone. */
@@ -25935,14 +26404,14 @@ function motionBlur(colour, velocity) {
25935
26404
  const timeScale = float(1 / targetFps).div(deltaTime.max(1e-4));
25936
26405
  const half = v.mul(vec2(1, -1)).mul(screenSize).mul(0.5).mul(timeScale.mul(amount * 0.5));
25937
26406
  const limit = screenSize.x.mul(0.5 * (maxPercent / 100));
25938
- const length7 = half.length();
25939
- const clamped = half.mul(float(1).min(limit.div(length7.max(1e-4))));
26407
+ const length8 = half.length();
26408
+ const clamped = half.mul(float(1).min(limit.div(length8.max(1e-4))));
25940
26409
  const sum = vec4(0).toVar();
25941
26410
  Loop({ start: int(0), end: int(SAMPLES), type: "int" }, ({ i }) => {
25942
26411
  const t = float(i).div(SAMPLES - 1).mul(2).sub(1);
25943
26412
  sum.addAssign(colour.sample(c.add(clamped.mul(t).div(screenSize))).level(float(0)));
25944
26413
  });
25945
- return length7.lessThan(0.25).select(colour.sample(c), sum.div(SAMPLES));
26414
+ return length8.lessThan(0.25).select(colour.sample(c), sum.div(SAMPLES));
25946
26415
  })();
25947
26416
  }
25948
26417
  var reflectionTrace = {};
@@ -25995,16 +26464,16 @@ function skyAmbientCube(environment, intensity = 1) {
25995
26464
  return sums;
25996
26465
  }
25997
26466
  var FADE_FROM = 0.5;
25998
- var START_OFFSET = 0.01;
25999
- var START_OFFSET_PER_METRE = 4e-3;
26467
+ var START_OFFSET2 = 0.01;
26468
+ var START_OFFSET_PER_METRE2 = 4e-3;
26000
26469
  var SHADOW_OFFSET = 0.02;
26001
26470
  var SHADOW_FAR = 2e3;
26002
26471
  var NO_CACHE_RADIANCE = 0;
26003
- function ambientCube(cube, normal) {
26472
+ function ambientCube(cube, normal2) {
26004
26473
  if (cube === void 0 || cube.length !== 6) return vec3(NO_CACHE_RADIANCE);
26005
26474
  const face = (index) => vec3(...cube[index]);
26006
- const squared = normal.mul(normal);
26007
- return select(normal.x.greaterThanEqual(0), face(0), face(1)).mul(squared.x).add(select(normal.y.greaterThanEqual(0), face(2), face(3)).mul(squared.y)).add(select(normal.z.greaterThanEqual(0), face(4), face(5)).mul(squared.z));
26475
+ const squared = normal2.mul(normal2);
26476
+ return select(normal2.x.greaterThanEqual(0), face(0), face(1)).mul(squared.x).add(select(normal2.y.greaterThanEqual(0), face(2), face(3)).mul(squared.y)).add(select(normal2.z.greaterThanEqual(0), face(4), face(5)).mul(squared.z));
26008
26477
  }
26009
26478
  var METAL_DIFFUSE = 0.12;
26010
26479
  function tracedReflections(stage2) {
@@ -26014,8 +26483,8 @@ function tracedReflections(stage2) {
26014
26483
  const [p00, p11, p02, p12, p22, p32] = [0, 5, 8, 9, 10, 14].map(projection);
26015
26484
  const world = (index) => live(() => camera.matrixWorld.elements[index] ?? 0);
26016
26485
  const column = (first) => vec3(world(first), world(first + 1), world(first + 2));
26017
- const [right, up, back, at3] = [column(0), column(4), column(8), column(12)];
26018
- const direction2 = (v) => right.mul(v.x).add(up.mul(v.y)).add(back.mul(v.z));
26486
+ const [right, up2, back, at3] = [column(0), column(4), column(8), column(12)];
26487
+ const direction2 = (v) => right.mul(v.x).add(up2.mul(v.y)).add(back.mul(v.z));
26019
26488
  const sun = stage2.sun;
26020
26489
  const sunDirection = vec3(
26021
26490
  live(() => sunVector(sun)[0]),
@@ -26089,7 +26558,7 @@ function tracedReflections(stage2) {
26089
26558
  const incidentView = normalize(position);
26090
26559
  const normalWorld3 = direction2(normalView3);
26091
26560
  const reflected = normalize(reflect(direction2(incidentView), normalWorld3));
26092
- const start = max(float(START_OFFSET), z.negate().mul(START_OFFSET_PER_METRE));
26561
+ const start = max(float(START_OFFSET2), z.negate().mul(START_OFFSET_PER_METRE2));
26093
26562
  const origin = direction2(position).add(at3).add(normalWorld3.mul(start));
26094
26563
  const hit = trace.trace({
26095
26564
  origin,
@@ -26139,8 +26608,8 @@ function sunVector(sun) {
26139
26608
  const x = sun.position.x - sun.target.position.x;
26140
26609
  const y = sun.position.y - sun.target.position.y;
26141
26610
  const z = sun.position.z - sun.target.position.z;
26142
- const length7 = Math.hypot(x, y, z) || 1;
26143
- return [x / length7, y / length7, z / length7];
26611
+ const length8 = Math.hypot(x, y, z) || 1;
26612
+ return [x / length8, y / length8, z / length8];
26144
26613
  }
26145
26614
  var unrealBloomSettings = {
26146
26615
  intensity: 0.675,
@@ -26468,10 +26937,10 @@ function bindSubrectSampler(node, view, bound) {
26468
26937
  }
26469
26938
  function bindSubrectTexture(node, view, bound) {
26470
26939
  if (Reflect.get(node, "isRTTNode") === true && !bound.has(node)) {
26471
- const rtt2 = node;
26472
- view.retain(rtt2, [rtt2.renderTarget]);
26473
- const update = rtt2.updateBefore;
26474
- rtt2.updateBefore = function(frame) {
26940
+ const rtt3 = node;
26941
+ view.retain(rtt3, [rtt3.renderTarget]);
26942
+ const update = rtt3.updateBefore;
26943
+ rtt3.updateBefore = function(frame) {
26475
26944
  this.width = view.active ? 1 : null;
26476
26945
  update.call(this, frame);
26477
26946
  };
@@ -26667,7 +27136,7 @@ var WorldEnvironment = class {
26667
27136
  const resolutionSubrect = requested.length === 0 || resolutionSubrectRefusal !== void 0 ? void 0 : renderer.createResolutionSubrect?.();
26668
27137
  resolutionSubrect?.retain(scenePass, [scenePass.renderTarget]);
26669
27138
  const boundSamplers = /* @__PURE__ */ new WeakSet();
26670
- const sample = (node) => {
27139
+ const sample2 = (node) => {
26671
27140
  if (resolutionSubrect) bindSubrectTexture(node, resolutionSubrect, boundSamplers);
26672
27141
  };
26673
27142
  if (options.ssgiEnabled || options.ssrEnabled || options.gtaoEnabled) {
@@ -26696,19 +27165,19 @@ var WorldEnvironment = class {
26696
27165
  const cached = nodes.get(name);
26697
27166
  if (cached !== void 0) return cached;
26698
27167
  const node = scenePass.getTextureNode(name);
26699
- sample(node);
27168
+ sample2(node);
26700
27169
  nodes.set(name, node);
26701
27170
  return node;
26702
27171
  };
26703
27172
  const depth = () => textureNode("depth");
26704
- const normal = () => textureNode("normal");
27173
+ const normal2 = () => textureNode("normal");
26705
27174
  const metal = () => textureNode("metalness");
26706
27175
  const rough = () => textureNode("roughness");
26707
27176
  const albedo = () => textureNode("diffuseColor");
26708
27177
  const view = camera;
26709
27178
  const base = target.baseColour?.(scenePass) ?? scenePass.getTextureNode("output");
26710
27179
  const colour = convertToTexture(base);
26711
- sample(colour);
27180
+ sample2(colour);
26712
27181
  const exposure = options.autoExposureEnabled ? new AutoExposureNode(colour, options.exposurePolicy, options.exposure) : void 0;
26713
27182
  const forgetExposure = publishStartupExposure(raw, exposure);
26714
27183
  const localExposure = options.localExposureEnabled ? new LocalExposureNode(colour, exposure?.exposureNode ?? float(options.exposure)) : void 0;
@@ -26733,14 +27202,14 @@ var WorldEnvironment = class {
26733
27202
  };
26734
27203
  const subrectTexture = (input) => {
26735
27204
  const texture7 = convertToTexture(input);
26736
- sample(texture7);
27205
+ sample2(texture7);
26737
27206
  return texture7;
26738
27207
  };
26739
27208
  const giDenoise = (node) => {
26740
27209
  let result = denoised(node);
26741
27210
  if (!options.denoiseEnabled) return result;
26742
27211
  for (let pass2 = 0; pass2 < options.giDenoisePasses; pass2 += 1) {
26743
- const filter = denoise(result, depth(), normal(), view);
27212
+ const filter = denoise(result, depth(), normal2(), view);
26744
27213
  filter.index.value = pass2;
26745
27214
  filter.resolutionScale = options.ssgiResolutionScale;
26746
27215
  if (options.ssgiTimedPass === void 0 || options.ssgiTimedPass === "denoise")
@@ -26763,11 +27232,11 @@ var WorldEnvironment = class {
26763
27232
  const base2 = convertToTexture(input);
26764
27233
  const wasmEngine = rendererFacts(renderer).ownedEngine;
26765
27234
  const cache = wasmEngine ? cacheFallback(view) : void 0;
26766
- const fallback = cache === void 0 ? void 0 : (position, normal2) => cache(position, normal2).mul(gain);
27235
+ const fallback = cache === void 0 ? void 0 : (position, normal3) => cache(position, normal3).mul(gain);
26767
27236
  const gi = ssgi(
26768
27237
  base2,
26769
27238
  depth(),
26770
- normal(),
27239
+ normal2(),
26771
27240
  wasmEngine ? {
26772
27241
  camera: view,
26773
27242
  fallback,
@@ -26814,7 +27283,7 @@ var WorldEnvironment = class {
26814
27283
  const at3 = uv();
26815
27284
  const cached = cache?.(
26816
27285
  getViewPosition(at3, depth().sample(at3).r, uniform(view.projectionMatrixInverse)),
26817
- normal().sample(at3).rgb.normalize()
27286
+ normal2().sample(at3).rgb.normalize()
26818
27287
  );
26819
27288
  const bounce = (cached === void 0 ? indirect.rgb : cached.mul(gain).add(indirect.rgb)).mul(options.ssgiIntensity);
26820
27289
  const indirectDiffuse = albedo().rgb.mul(float(1).sub(metal().r)).mul(bounce);
@@ -26891,7 +27360,7 @@ var WorldEnvironment = class {
26891
27360
  contact.resolutionScale = options.gtaoResolutionScale;
26892
27361
  const retained = contact;
26893
27362
  resolutionSubrect?.retain(retained, [retained._aoRenderTarget]);
26894
- sample(contact.getTextureNode());
27363
+ sample2(contact.getTextureNode());
26895
27364
  let filterTexture;
26896
27365
  releaseAo = () => {
26897
27366
  if (filterTexture) {
@@ -26904,7 +27373,7 @@ var WorldEnvironment = class {
26904
27373
  resolutionSubrect?.release(retained);
26905
27374
  contact.dispose();
26906
27375
  };
26907
- const filter = options.denoiseEnabled && options.gtaoDenoiseRadius !== 0 ? denoise(contact.getTextureNode(), depth(), normal(), view) : void 0;
27376
+ const filter = options.denoiseEnabled && options.gtaoDenoiseRadius !== 0 ? denoise(contact.getTextureNode(), depth(), normal2(), view) : void 0;
26908
27377
  if (filter && options.gtaoDenoiseRadius !== void 0)
26909
27378
  filter.radius.value = options.gtaoDenoiseRadius;
26910
27379
  if (filter)
@@ -26922,7 +27391,7 @@ var WorldEnvironment = class {
26922
27391
  filterTexture = convertToTexture(denoised(filter));
26923
27392
  filterTexture.setResolutionScale(options.gtaoResolutionScale);
26924
27393
  filterTexture.updateBeforeType = NodeUpdateType.FRAME;
26925
- sample(filterTexture);
27394
+ sample2(filterTexture);
26926
27395
  }
26927
27396
  const occlusion = filterTexture ?? (filter ? denoised(filter) : contact);
26928
27397
  const bounce = () => {
@@ -26972,7 +27441,7 @@ var WorldEnvironment = class {
26972
27441
  shafts.maxDensity.value = options.godraysMaxDensity;
26973
27442
  shafts.raymarchSteps.value = options.godraysSteps;
26974
27443
  let shaft = convertToTexture(shafts);
26975
- if (options.denoiseEnabled) shaft = denoised(denoise(shaft, depth(), normal(), view));
27444
+ if (options.denoiseEnabled) shaft = denoised(denoise(shaft, depth(), normal2(), view));
26976
27445
  const cleaned = shaft.rgb.sub(options.godraysFloor).max(0).mul(options.godraysIntensity);
26977
27446
  return input.add(cleaned.mul(color(light.color)));
26978
27447
  }
@@ -26992,7 +27461,7 @@ var WorldEnvironment = class {
26992
27461
  skyIrradiance: skyAmbientCube(scene.environment, scene.environmentIntensity),
26993
27462
  base: base2,
26994
27463
  depth: depth(),
26995
- normal: normal(),
27464
+ normal: normal2(),
26996
27465
  metalness: metal(),
26997
27466
  roughness: rough(),
26998
27467
  ...options.ssgiEnabled ? { albedo: albedo() } : {},
@@ -27004,7 +27473,7 @@ var WorldEnvironment = class {
27004
27473
  const reflections = ssr(
27005
27474
  base2,
27006
27475
  depth(),
27007
- normal().level(float(0)),
27476
+ normal2().level(float(0)),
27008
27477
  {
27009
27478
  camera: view,
27010
27479
  metalnessNode: metal().r,
@@ -27050,7 +27519,7 @@ var WorldEnvironment = class {
27050
27519
  );
27051
27520
  const colour2 = subrectTexture(input);
27052
27521
  const velocity = chain2.velocityNode;
27053
- sample(velocity);
27522
+ sample2(velocity);
27054
27523
  return motionBlur(colour2, velocity);
27055
27524
  }
27056
27525
  }),
@@ -27106,22 +27575,22 @@ var WorldEnvironment = class {
27106
27575
  retained._textureNodeBlur4,
27107
27576
  retained._textureOutput
27108
27577
  ])
27109
- sample(node);
27578
+ sample2(node);
27110
27579
  const material = retained._getSeparableBlurMaterial;
27111
27580
  retained._getSeparableBlurMaterial = function(builder, radius) {
27112
27581
  const result = material.call(this, builder, radius);
27113
- sample(result.colorTexture);
27582
+ sample2(result.colorTexture);
27114
27583
  return result;
27115
27584
  };
27116
27585
  }
27117
27586
  releaseBloom = () => {
27118
27587
  resolutionSubrect?.release(effect);
27119
27588
  effect.dispose();
27120
- const scratch3 = texture7;
27121
- if (texture7 !== input && scratch3.isRTTNode === true) {
27589
+ const scratch4 = texture7;
27590
+ if (texture7 !== input && scratch4.isRTTNode === true) {
27122
27591
  resolutionSubrect?.release(texture7);
27123
- scratch3.renderTarget.dispose();
27124
- scratch3._quadMesh.material.dispose();
27592
+ scratch4.renderTarget.dispose();
27593
+ scratch4._quadMesh.material.dispose();
27125
27594
  }
27126
27595
  };
27127
27596
  return unreal === void 0 ? colour2.add(effect) : vec4(colour2.rgb.add(unreal.bloomNode), colour2.a);
@@ -27151,7 +27620,7 @@ var WorldEnvironment = class {
27151
27620
  const peak = max(colour2.r, max(colour2.g, colour2.b));
27152
27621
  const squeezed = lookDiagnostics.aaAlphaSqueezed ? colour2.div(peak.add(1)) : vec4(colour2.rgb.div(peak.add(1)), colour2.a);
27153
27622
  const texture7 = convertToTexture(squeezed);
27154
- sample(texture7);
27623
+ sample2(texture7);
27155
27624
  const effect = options.screenSpaceAA === "fxaa" ? fxaa(texture7) : workerSafeSmaa(texture7);
27156
27625
  if (resolutionSubrect && options.screenSpaceAA !== "fxaa") {
27157
27626
  const retained = effect;
@@ -27165,7 +27634,7 @@ var WorldEnvironment = class {
27165
27634
  retained._weightsTextureUniform,
27166
27635
  retained._textureNode
27167
27636
  ])
27168
- sample(node);
27637
+ sample2(node);
27169
27638
  } else if (resolutionSubrect) {
27170
27639
  const filter = effect;
27171
27640
  const update = filter.updateBefore;
@@ -27187,8 +27656,8 @@ var WorldEnvironment = class {
27187
27656
  };
27188
27657
  const filtered = effect;
27189
27658
  const back = max(filtered.r, max(filtered.g, filtered.b));
27190
- const floor5 = float(1).sub(back).max(1e-4);
27191
- return lookDiagnostics.aaAlphaSqueezed ? filtered.div(floor5) : vec4(filtered.rgb.div(floor5), filtered.a);
27659
+ const floor6 = float(1).sub(back).max(1e-4);
27660
+ return lookDiagnostics.aaAlphaSqueezed ? filtered.div(floor6) : vec4(filtered.rgb.div(floor6), filtered.a);
27192
27661
  }
27193
27662
  }
27194
27663
  ];
@@ -27624,13 +28093,13 @@ var SpectralOcean = class extends Object3D {
27624
28093
  */
27625
28094
  sampleHeight(x, z) {
27626
28095
  if (this.#readback === void 0) return void 0;
27627
- const sample = this.#readback.sample;
27628
- if (sample === void 0) return void 0;
28096
+ const sample2 = this.#readback.sample;
28097
+ if (sample2 === void 0) return void 0;
27629
28098
  const patch = this.#cascadeStates[0].patchSize;
27630
28099
  return {
27631
- height: sampleGrid(sample.data, this.#readbackResolution, patch, x, z, 2),
27632
- verticalVelocity: sampleGrid(sample.data, this.#readbackResolution, patch, x, z, 2, 1),
27633
- staleFrames: sample.staleFrames
28100
+ height: sampleGrid(sample2.data, this.#readbackResolution, patch, x, z, 2),
28101
+ verticalVelocity: sampleGrid(sample2.data, this.#readbackResolution, patch, x, z, 2, 1),
28102
+ staleFrames: sample2.staleFrames
27634
28103
  };
27635
28104
  }
27636
28105
  attachRenderer(renderer) {
@@ -27681,7 +28150,7 @@ var SpectralOcean = class extends Object3D {
27681
28150
  "vec4"
27682
28151
  );
27683
28152
  const work = instancedArray(count, "vec4");
27684
- const scratch3 = instancedArray(count, "vec4");
28153
+ const scratch4 = instancedArray(count, "vec4");
27685
28154
  const displacement2 = instancedArray(count, "vec4");
27686
28155
  const reversal = instancedArray(
27687
28156
  Float32Array.from(bitReverseIndices(size)),
@@ -27702,11 +28171,11 @@ var SpectralOcean = class extends Object3D {
27702
28171
  const deepWater = kLength.mul(tuning.gravity);
27703
28172
  const dispersion = tuning.capillaryWavenumber === void 0 ? deepWater : deepWater.mul(kLength.div(tuning.capillaryWavenumber).pow(2).add(1));
27704
28173
  const omega = dispersion.sqrt().mul(time);
27705
- const cos2 = omega.cos();
27706
- const sin2 = omega.sin();
28174
+ const cos3 = omega.cos();
28175
+ const sin3 = omega.sin();
27707
28176
  const amplitudes = initial.element(instanceIndex);
27708
- const heightRe = amplitudes.x.mul(cos2).sub(amplitudes.y.mul(sin2)).add(amplitudes.z.mul(cos2)).add(amplitudes.w.mul(sin2));
27709
- const heightIm = amplitudes.x.mul(sin2).add(amplitudes.y.mul(cos2)).sub(amplitudes.z.mul(sin2)).add(amplitudes.w.mul(cos2));
28177
+ const heightRe = amplitudes.x.mul(cos3).sub(amplitudes.y.mul(sin3)).add(amplitudes.z.mul(cos3)).add(amplitudes.w.mul(sin3));
28178
+ const heightIm = amplitudes.x.mul(sin3).add(amplitudes.y.mul(cos3)).sub(amplitudes.z.mul(sin3)).add(amplitudes.w.mul(cos3));
27710
28179
  const displaceXRe = kx.div(kLength).mul(heightIm);
27711
28180
  const displaceXIm = kx.div(kLength).mul(heightRe).negate();
27712
28181
  const displaceZRe = kz.div(kLength).mul(heightIm);
@@ -27723,11 +28192,11 @@ var SpectralOcean = class extends Object3D {
27723
28192
  );
27724
28193
  })().compute(count)
27725
28194
  );
27726
- passes.push(this.#reversePass(work, scratch3, reversal, "row"));
28195
+ passes.push(this.#reversePass(work, scratch4, reversal, "row"));
27727
28196
  for (let stage2 = 0; stage2 < butterflyStageCount(size); stage2 += 1) {
27728
- passes.push(this.#butterflyPass(scratch3, stage2, "row"));
28197
+ passes.push(this.#butterflyPass(scratch4, stage2, "row"));
27729
28198
  }
27730
- passes.push(this.#reversePass(scratch3, work, reversal, "column"));
28199
+ passes.push(this.#reversePass(scratch4, work, reversal, "column"));
27731
28200
  for (let stage2 = 0; stage2 < butterflyStageCount(size); stage2 += 1) {
27732
28201
  passes.push(this.#butterflyPass(work, stage2, "column"));
27733
28202
  }
@@ -27755,7 +28224,7 @@ var SpectralOcean = class extends Object3D {
27755
28224
  kMax: band.kMax,
27756
28225
  initialSpectrum: initial,
27757
28226
  work,
27758
- scratch: scratch3,
28227
+ scratch: scratch4,
27759
28228
  displacement: displacement2,
27760
28229
  passes
27761
28230
  };
@@ -27835,6 +28304,934 @@ var SpectralOcean = class extends Object3D {
27835
28304
  return { field, pass: pass2 };
27836
28305
  }
27837
28306
  };
28307
+
28308
+ // src/tile-ring.ts
28309
+ var CREATE_BAND = 1.3;
28310
+ var DISCARD_BAND = 1.4;
28311
+ var TileRing = class {
28312
+ stats = { built: 0, pending: 0, tiles: 0, visible: 0 };
28313
+ #field;
28314
+ #tiles = /* @__PURE__ */ new Map();
28315
+ #queue = [];
28316
+ #frame = 0;
28317
+ #prewarm = false;
28318
+ constructor(field) {
28319
+ this.#field = field;
28320
+ }
28321
+ /** Every live tile, for a field that has to re-scatter or re-key its own build. */
28322
+ tiles() {
28323
+ return this.#tiles.values();
28324
+ }
28325
+ /** Builds every tile in range on the next `update` regardless of budget: on load or after a teleport. */
28326
+ prewarm() {
28327
+ this.#prewarm = true;
28328
+ }
28329
+ /** Drops every live tile: the field's density or layout changed. */
28330
+ clear() {
28331
+ for (const entry of this.#tiles.values())
28332
+ if (entry.tile !== null) this.#field.dispose(entry.tile);
28333
+ this.#tiles.clear();
28334
+ }
28335
+ /** Frees the tiles touching a rectangle, so only what changed re-scatters. */
28336
+ disposeInside(rect) {
28337
+ const S = this.#field.chunkSize;
28338
+ for (const [k, entry] of this.#tiles) {
28339
+ if (entry.ix * S > rect.maxX || (entry.ix + 1) * S < rect.minX || entry.iz * S > rect.maxZ || (entry.iz + 1) * S < rect.minZ)
28340
+ continue;
28341
+ if (entry.tile !== null) this.#field.dispose(entry.tile);
28342
+ this.#tiles.delete(k);
28343
+ }
28344
+ }
28345
+ /** Streams, shows and frees the tiles round `(cx, cz)`. Call once per rendered frame. */
28346
+ update(cx, cz) {
28347
+ const field = this.#field;
28348
+ const R = field.drawDistance;
28349
+ const frame = ++this.#frame;
28350
+ this.stats.visible = 0;
28351
+ this.#visit(cx, cz, R, frame);
28352
+ this.#buildQueued(frame);
28353
+ this.#prewarm = false;
28354
+ this.#evict(cx, cz, R, frame);
28355
+ this.stats.tiles = this.#tiles.size;
28356
+ }
28357
+ /** Marks the tiles inside the create band and queues the missing ones. */
28358
+ #visit(cx, cz, R, frame) {
28359
+ const S = this.#field.chunkSize;
28360
+ const reach = R * CREATE_BAND;
28361
+ const queue2 = this.#queue;
28362
+ queue2.length = 0;
28363
+ for (let iz = Math.floor((cz - reach) / S); iz <= Math.floor((cz + reach) / S); iz++) {
28364
+ for (let ix = Math.floor((cx - reach) / S); ix <= Math.floor((cx + reach) / S); ix++) {
28365
+ const d = tileDistance(ix, iz, cx, cz, S);
28366
+ if (d >= reach || !this.#field.inBounds(ix, iz)) continue;
28367
+ const k = tileKey(ix, iz);
28368
+ const entry = this.#tiles.get(k);
28369
+ if (!entry) {
28370
+ queue2.push({ d, ix, iz, k });
28371
+ continue;
28372
+ }
28373
+ entry.seen = frame;
28374
+ if (entry.tile !== null) this.#field.show(entry.tile, d);
28375
+ }
28376
+ }
28377
+ }
28378
+ /** Builds queued tiles nearest first; one always builds, the rest only inside the budget. */
28379
+ #buildQueued(frame) {
28380
+ const queue2 = this.#queue;
28381
+ queue2.sort((a, c) => a.d - c.d);
28382
+ const budget = this.#prewarm ? Number.POSITIVE_INFINITY : this.#field.buildBudgetMs;
28383
+ const t0 = performance.now();
28384
+ let built = 0;
28385
+ for (const q of queue2) {
28386
+ if (built > 0 && performance.now() - t0 > budget) break;
28387
+ const tile = this.#field.build(q.ix, q.iz);
28388
+ this.#tiles.set(q.k, { ix: q.ix, iz: q.iz, seen: frame, tile });
28389
+ if (tile !== null) this.#field.show(tile, q.d);
28390
+ built++;
28391
+ }
28392
+ this.stats.built += built;
28393
+ this.stats.pending = queue2.length - built;
28394
+ }
28395
+ /** Hides tiles that left the view radius and frees those past the discard band. */
28396
+ #evict(cx, cz, R, frame) {
28397
+ const S = this.#field.chunkSize;
28398
+ for (const [k, entry] of this.#tiles) {
28399
+ if (entry.seen === frame) continue;
28400
+ if (tileDistance(entry.ix, entry.iz, cx, cz, S) > R * DISCARD_BAND) {
28401
+ if (entry.tile !== null) this.#field.dispose(entry.tile);
28402
+ this.#tiles.delete(k);
28403
+ } else if (entry.tile !== null) this.#field.hide(entry.tile);
28404
+ }
28405
+ }
28406
+ };
28407
+ function tileDistance(ix, iz, cx, cz, S) {
28408
+ const dx = Math.max(ix * S - cx, 0, cx - (ix + 1) * S);
28409
+ const dz = Math.max(iz * S - cz, 0, cz - (iz + 1) * S);
28410
+ return Math.sqrt(dx * dx + dz * dz);
28411
+ }
28412
+ var tileKey = (ix, iz) => (ix + 32768) * 65536 + (iz + 32768);
28413
+ function hashInt(x, y, s) {
28414
+ let h = Math.imul(x | 0, 668265261) ^ Math.imul(y | 0, 374761393) ^ Math.imul(s | 0, 2654435761);
28415
+ h = Math.imul(h ^ h >>> 15, 2246822507);
28416
+ h = Math.imul(h ^ h >>> 13, 3266489909);
28417
+ return (h ^ h >>> 16) >>> 0;
28418
+ }
28419
+ function mulberry32(seed) {
28420
+ let a = seed >>> 0;
28421
+ return () => {
28422
+ a = a + 1831565813 | 0;
28423
+ let t = Math.imul(a ^ a >>> 15, 1 | a);
28424
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
28425
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
28426
+ };
28427
+ }
28428
+ function shuffled(total, rng) {
28429
+ const order = new Uint32Array(total);
28430
+ for (let i = 0; i < total; i++) order[i] = i;
28431
+ for (let i = total - 1; i > 0; i--) {
28432
+ const j = rng() * (i + 1) | 0;
28433
+ const tmp = order[i];
28434
+ order[i] = order[j];
28435
+ order[j] = tmp;
28436
+ }
28437
+ return order;
28438
+ }
28439
+ var sample = new Float64Array(3);
28440
+ function groundGrid(getHeight, ox, oz, S, spacing) {
28441
+ const G = Math.max(1, Math.ceil(S / Math.max(spacing, 0.05)));
28442
+ const gs = S / G;
28443
+ const N = G + 3;
28444
+ const hg = new Float32Array(N * N);
28445
+ for (let j = 0; j < N; j++)
28446
+ for (let i = 0; i < N; i++)
28447
+ hg[j * N + i] = getHeight(ox + (i - 1) * gs, oz + (j - 1) * gs) || 0;
28448
+ const gx = new Float32Array(N * N);
28449
+ const gz = new Float32Array(N * N);
28450
+ const inv2 = 1 / (2 * gs);
28451
+ for (let j = 1; j < N - 1; j++)
28452
+ for (let i = 1; i < N - 1; i++) {
28453
+ const o = j * N + i;
28454
+ gx[o] = (hg[o + 1] - hg[o - 1]) * inv2;
28455
+ gz[o] = (hg[o + N] - hg[o - N]) * inv2;
28456
+ }
28457
+ return {
28458
+ sample(lx, lz) {
28459
+ const fx = lx / gs + 1;
28460
+ const fz = lz / gs + 1;
28461
+ const i0 = Math.min(fx | 0, G);
28462
+ const j0 = Math.min(fz | 0, G);
28463
+ const u = fx - i0;
28464
+ const v = fz - j0;
28465
+ const o = j0 * N + i0;
28466
+ const w00 = (1 - u) * (1 - v);
28467
+ const w10 = u * (1 - v);
28468
+ const w01 = (1 - u) * v;
28469
+ const w11 = u * v;
28470
+ const o1 = o + 1;
28471
+ const oN = o + N;
28472
+ const oN1 = oN + 1;
28473
+ sample[0] = hg[o] * w00 + hg[o1] * w10 + hg[oN] * w01 + hg[oN1] * w11;
28474
+ sample[1] = gx[o] * w00 + gx[o1] * w10 + gx[oN] * w01 + gx[oN1] * w11;
28475
+ sample[2] = gz[o] * w00 + gz[o1] * w10 + gz[oN] * w01 + gz[oN1] * w11;
28476
+ }
28477
+ };
28478
+ }
28479
+ var clamp01 = (v) => v < 0 ? 0 : v > 1 ? 1 : v;
28480
+ function smoothstep6(e0, e1, x) {
28481
+ const t = clamp01((x - e0) / Math.max(e1 - e0, 1e-6));
28482
+ return t * t * (3 - 2 * t);
28483
+ }
28484
+
28485
+ // src/grass-field.ts
28486
+ var MAX_PUSHERS = 4;
28487
+ var DEG = Math.PI / 180;
28488
+ var GRASS_FIELD_ATTRIBUTES = {
28489
+ /** vec3: the blade's root, chunk-local (the chunk mesh sits at its corner). */
28490
+ root: "grassRoot",
28491
+ /** vec4: facing 0..1, height 0..1, thinning priority 0..1, coverage scale 0..1. */
28492
+ rand: "grassRand",
28493
+ /** vec4: angle away from the tuft centre, tuft random 0..1, ground normal x, ground normal z. */
28494
+ clump: "grassClump"
28495
+ };
28496
+ var GrassField3D = class extends Group {
28497
+ blade;
28498
+ material;
28499
+ nodes;
28500
+ /** x, y, z world position and w radius (0 = off) of what flattens the grass. */
28501
+ pushers;
28502
+ /** Chunks and budget from the shared ring; blades and triangles from this frame's LOD pass. */
28503
+ get stats() {
28504
+ return {
28505
+ blades: this.#shown.blades,
28506
+ built: this.#ring.stats.built,
28507
+ chunks: this.#ring.stats.tiles,
28508
+ pending: this.#ring.stats.pending,
28509
+ triangles: this.#shown.triangles,
28510
+ visibleChunks: this.#shown.visibleChunks
28511
+ };
28512
+ }
28513
+ getHeight;
28514
+ getDensity;
28515
+ bounds;
28516
+ density;
28517
+ chunkSize;
28518
+ seed;
28519
+ heightSampleSpacing;
28520
+ maxSlope;
28521
+ slopeFade;
28522
+ minAltitude;
28523
+ maxAltitude;
28524
+ clumpSize;
28525
+ drawDistance;
28526
+ fadeRange;
28527
+ lodDistances;
28528
+ thinStart;
28529
+ thinEnd;
28530
+ farDensity;
28531
+ buildBudgetMs;
28532
+ receiveShadow;
28533
+ densityScale;
28534
+ cullDistanceScale;
28535
+ #ring;
28536
+ #shown = { blades: 0, triangles: 0, visibleChunks: 0 };
28537
+ #version = 0;
28538
+ #layout = "";
28539
+ constructor(options) {
28540
+ super();
28541
+ this.name = "GrassField3D";
28542
+ if (typeof options.getHeight !== "function")
28543
+ throw new Error("GrassField3D.getHeight must be a function (x, z) => height.");
28544
+ if (typeof options.material !== "function")
28545
+ throw new Error("GrassField3D.material must be a function (nodes) => Material.");
28546
+ const lods = options.blade?.lods;
28547
+ if (!Array.isArray(lods) || lods.length === 0)
28548
+ throw new Error("GrassField3D.blade.lods must list at least one draw range.");
28549
+ this.blade = options.blade;
28550
+ this.getHeight = options.getHeight;
28551
+ this.getDensity = options.getDensity ?? null;
28552
+ this.bounds = options.bounds ?? null;
28553
+ this.density = options.density ?? 30;
28554
+ this.chunkSize = options.chunkSize ?? 12;
28555
+ this.seed = options.seed ?? 1337;
28556
+ this.heightSampleSpacing = options.heightSampleSpacing ?? 0.75;
28557
+ this.maxSlope = options.maxSlope ?? 42;
28558
+ this.slopeFade = options.slopeFade ?? 12;
28559
+ this.minAltitude = options.minAltitude ?? Number.NEGATIVE_INFINITY;
28560
+ this.maxAltitude = options.maxAltitude ?? Number.POSITIVE_INFINITY;
28561
+ this.clumpSize = options.clumpSize ?? 1.4;
28562
+ this.drawDistance = options.drawDistance ?? 75;
28563
+ this.fadeRange = options.fadeRange ?? 0.3;
28564
+ this.lodDistances = options.lodDistances ?? [16, 38];
28565
+ this.thinStart = options.thinStart ?? 10;
28566
+ this.thinEnd = options.thinEnd ?? 62;
28567
+ this.farDensity = options.farDensity ?? 0.22;
28568
+ this.buildBudgetMs = options.buildBudgetMs ?? 4;
28569
+ this.receiveShadow = options.receiveShadow ?? true;
28570
+ this.densityScale = options.densityScale ?? 1;
28571
+ this.cullDistanceScale = options.cullDistanceScale ?? 1;
28572
+ this.#validate();
28573
+ this.#ring = new TileRing(this.#hooks());
28574
+ this.pushers = Array.from({ length: MAX_PUSHERS }, () => new Vector4());
28575
+ const pushers = this.pushers.map((v) => uniform(v));
28576
+ this.nodes = {
28577
+ thinStart: uniform(0),
28578
+ thinEnd: uniform(0),
28579
+ farDensity: uniform(0),
28580
+ fadeStart: uniform(0),
28581
+ drawDistance: uniform(0),
28582
+ pushers,
28583
+ push: (root) => {
28584
+ let dir = vec2(0, 0);
28585
+ let press = float(0);
28586
+ for (const pu of pushers) {
28587
+ const d = root.sub(pu.xyz);
28588
+ const f = float(1).sub(d.length().div(pu.w.max(1e-3)).smoothstep(0, 1)).mul(pu.w.step(1e-3).oneMinus());
28589
+ dir = dir.add(d.xz.add(vec2(1e-4, 1e-4)).normalize().mul(f));
28590
+ press = press.max(f);
28591
+ }
28592
+ return vec3(dir.x, dir.y, press);
28593
+ }
28594
+ };
28595
+ this.#syncNodes();
28596
+ this.material = options.material(this.nodes);
28597
+ }
28598
+ /** The pushers' press 0..1 at a world point: the CPU mirror of `nodes.push`'s z. */
28599
+ pressAt(x, y, z) {
28600
+ let press = 0;
28601
+ for (const pu of this.pushers) {
28602
+ if (pu.w < 1e-3) continue;
28603
+ const f = 1 - smoothstep6(0, 1, Math.hypot(x - pu.x, y - pu.y, z - pu.z) / pu.w);
28604
+ press = Math.max(press, f);
28605
+ }
28606
+ return press;
28607
+ }
28608
+ /** Builds every chunk in range on the next `update` regardless of budget: on load or after a teleport. */
28609
+ prewarm() {
28610
+ this.#ring.prewarm();
28611
+ }
28612
+ /** Re-scatter after the ground or the density changed: all chunks, or those touching a rectangle. */
28613
+ refresh(rect) {
28614
+ if (rect === void 0) {
28615
+ this.#version++;
28616
+ return;
28617
+ }
28618
+ this.#ring.disposeInside(rect);
28619
+ }
28620
+ /** Streams, thins and LODs the chunks around `camera`. Call once per rendered frame. */
28621
+ update(camera) {
28622
+ this.#validate();
28623
+ this.#syncNodes();
28624
+ const layout = this.#layoutKey();
28625
+ if (layout !== this.#layout) {
28626
+ this.#ring.clear();
28627
+ this.#layout = layout;
28628
+ }
28629
+ camera.getWorldPosition(scratch3);
28630
+ this.worldToLocal(scratch3);
28631
+ this.#shown.visibleChunks = this.#shown.blades = this.#shown.triangles = 0;
28632
+ this.#ring.update(scratch3.x, scratch3.z);
28633
+ }
28634
+ #inBounds(ix, iz) {
28635
+ const b = this.bounds;
28636
+ const S = this.chunkSize;
28637
+ return b === null || !(ix * S >= b.maxX || (ix + 1) * S <= b.minX || iz * S >= b.maxZ || (iz + 1) * S <= b.minZ);
28638
+ }
28639
+ /** The ring's hooks: a chunk that leaves the radius hides, one past the band is freed. */
28640
+ #hooks() {
28641
+ const field = this;
28642
+ return {
28643
+ build: (ix, iz) => this.#build(ix, iz),
28644
+ get buildBudgetMs() {
28645
+ return field.buildBudgetMs;
28646
+ },
28647
+ get chunkSize() {
28648
+ return field.chunkSize;
28649
+ },
28650
+ get drawDistance() {
28651
+ return field.drawDistance * field.cullDistanceScale;
28652
+ },
28653
+ dispose: (chunk) => this.#dispose(chunk),
28654
+ hide: (chunk) => {
28655
+ if (chunk.mesh?.visible) chunk.mesh.visible = false;
28656
+ },
28657
+ inBounds: (ix, iz) => this.#inBounds(ix, iz),
28658
+ show: (chunk, distance) => this.#applyLod(chunk, distance)
28659
+ };
28660
+ }
28661
+ dispose() {
28662
+ this.#ring.clear();
28663
+ this.material.dispose();
28664
+ }
28665
+ #validate() {
28666
+ if (!(this.chunkSize > 0))
28667
+ throw new Error(`GrassField3D.chunkSize must be > 0, got ${this.chunkSize}.`);
28668
+ if (!(this.density >= 0))
28669
+ throw new Error(`GrassField3D.density must be >= 0, got ${this.density}.`);
28670
+ if (!(this.drawDistance > 0))
28671
+ throw new Error(`GrassField3D.drawDistance must be > 0, got ${this.drawDistance}.`);
28672
+ if (!(this.buildBudgetMs >= 0))
28673
+ throw new Error(`GrassField3D.buildBudgetMs must be >= 0, got ${this.buildBudgetMs}.`);
28674
+ if (!(this.densityScale >= 0) || !(this.cullDistanceScale > 0))
28675
+ throw new Error("GrassField3D.densityScale must be >= 0 and cullDistanceScale > 0.");
28676
+ const b = this.bounds;
28677
+ if (b === null) return;
28678
+ for (const key of ["minX", "minZ", "maxX", "maxZ"])
28679
+ if (!Number.isFinite(b[key])) throw new Error(`GrassField3D.bounds.${key} must be finite.`);
28680
+ if (b.minX >= b.maxX) throw new Error("GrassField3D.bounds.minX must be below bounds.maxX.");
28681
+ if (b.minZ >= b.maxZ) throw new Error("GrassField3D.bounds.minZ must be below bounds.maxZ.");
28682
+ }
28683
+ #syncNodes() {
28684
+ const k = this.cullDistanceScale;
28685
+ const n = this.nodes;
28686
+ setIfChanged(n.thinStart, this.thinStart * k);
28687
+ setIfChanged(n.thinEnd, Math.max(this.thinEnd, this.thinStart + 0.01) * k);
28688
+ setIfChanged(n.farDensity, this.farDensity);
28689
+ setIfChanged(n.drawDistance, this.drawDistance * k);
28690
+ setIfChanged(
28691
+ n.fadeStart,
28692
+ this.drawDistance * k * (1 - Math.min(Math.max(this.fadeRange, 0.01), 1))
28693
+ );
28694
+ }
28695
+ #layoutKey() {
28696
+ return [
28697
+ this.#version,
28698
+ this.density * this.densityScale,
28699
+ this.chunkSize,
28700
+ this.seed,
28701
+ this.heightSampleSpacing,
28702
+ this.maxSlope,
28703
+ this.slopeFade,
28704
+ this.minAltitude,
28705
+ this.maxAltitude,
28706
+ this.clumpSize
28707
+ ].join("|");
28708
+ }
28709
+ #applyLod(chunk, d) {
28710
+ const mesh = chunk.mesh;
28711
+ if (!mesh || !chunk.priority) return;
28712
+ const k = this.cullDistanceScale;
28713
+ const geo = mesh.geometry;
28714
+ const thinEnd = Math.max(this.thinEnd, this.thinStart + 0.01) * k;
28715
+ const edge = 1.1 + (this.farDensity - 1.1) * smoothstep6(this.thinStart * k, thinEnd, d);
28716
+ let n = chunk.count;
28717
+ if (edge < 1) {
28718
+ const pr = chunk.priority;
28719
+ let lo = 0;
28720
+ let hi = n;
28721
+ while (lo < hi) {
28722
+ const mid = lo + hi >> 1;
28723
+ if (pr[mid] < edge) lo = mid + 1;
28724
+ else hi = mid;
28725
+ }
28726
+ n = lo;
28727
+ }
28728
+ if (geo.instanceCount !== n) geo.instanceCount = n;
28729
+ const visible = n > 0 && d < this.drawDistance * this.cullDistanceScale;
28730
+ if (mesh.visible !== visible) mesh.visible = visible;
28731
+ if (!visible) return;
28732
+ const lods = this.blade.lods;
28733
+ let lod = 0;
28734
+ while (lod < lods.length - 1 && d >= (this.lodDistances[lod] ?? Number.POSITIVE_INFINITY) * k)
28735
+ lod++;
28736
+ const range = lods[lod];
28737
+ if (geo.drawRange.start !== range.start || geo.drawRange.count !== range.count)
28738
+ geo.setDrawRange(range.start, range.count);
28739
+ if (mesh.receiveShadow !== this.receiveShadow) mesh.receiveShadow = this.receiveShadow;
28740
+ this.#shown.visibleChunks++;
28741
+ this.#shown.blades += n;
28742
+ this.#shown.triangles += n * (range.count / 3);
28743
+ }
28744
+ #build(ix, iz) {
28745
+ const S = this.chunkSize;
28746
+ const ox = ix * S;
28747
+ const oz = iz * S;
28748
+ const seed = this.seed | 0;
28749
+ const rng = mulberry32(hashInt(ix, iz, seed));
28750
+ const b = this.bounds;
28751
+ const getHeight = this.getHeight;
28752
+ const height = b === null ? getHeight : (x, z) => getHeight(Math.min(b.maxX, Math.max(b.minX, x)), Math.min(b.maxZ, Math.max(b.minZ, z)));
28753
+ const ground = groundGrid(height, ox, oz, S, this.heightSampleSpacing);
28754
+ const n = Math.max(1, Math.ceil(Math.sqrt(this.density * this.densityScale * S * S)));
28755
+ const total = this.density * this.densityScale > 0 ? n * n : 0;
28756
+ const cell = S / n;
28757
+ const order = shuffled(total, rng);
28758
+ const pos = new Float32Array(total * 3);
28759
+ const rand = new Float32Array(total * 4);
28760
+ const clump = new Float32Array(total * 4);
28761
+ const priority = new Float32Array(total);
28762
+ const cosMax = Math.cos(this.maxSlope * DEG);
28763
+ const slopeSpan = Math.max(
28764
+ Math.cos(Math.max(this.maxSlope - this.slopeFade, 0) * DEG) - cosMax,
28765
+ 1e-5
28766
+ );
28767
+ const cs = Math.max(this.clumpSize, 0.05);
28768
+ prepareTufts(ox, oz, S, cs, seed);
28769
+ let k = 0;
28770
+ let minY = Number.POSITIVE_INFINITY;
28771
+ let maxY = Number.NEGATIVE_INFINITY;
28772
+ for (let q = 0; q < total; q++) {
28773
+ const c = order[q];
28774
+ const lx = (c % n + rng()) * cell;
28775
+ const lz = ((c / n | 0) + rng()) * cell;
28776
+ const rFacing = rng();
28777
+ const rHeight = rng();
28778
+ const rKeep = rng();
28779
+ const wx = ox + lx;
28780
+ const wz = oz + lz;
28781
+ if (!this.#pointInBounds(wx, wz)) continue;
28782
+ ground.sample(lx, lz);
28783
+ const y = sample[0];
28784
+ const dx = sample[1];
28785
+ const dz = sample[2];
28786
+ if (y < this.minAltitude || y > this.maxAltitude) continue;
28787
+ const ny = 1 / Math.sqrt(dx * dx + dz * dz + 1);
28788
+ const m = this.#coverage(wx, wz, y, ny, cosMax, slopeSpan);
28789
+ if (m <= 1e-3 || rKeep > m * 2) continue;
28790
+ nearestTuft(wx, wz, cs);
28791
+ pos[k * 3] = lx;
28792
+ pos[k * 3 + 1] = y;
28793
+ pos[k * 3 + 2] = lz;
28794
+ priority[k] = q / total;
28795
+ rand[k * 4] = rFacing;
28796
+ rand[k * 4 + 1] = rHeight;
28797
+ rand[k * 4 + 2] = q / total;
28798
+ rand[k * 4 + 3] = 0.45 + 0.55 * m;
28799
+ clump[k * 4] = fastAtan2(wz - tuft[1], wx - tuft[0]);
28800
+ clump[k * 4 + 1] = tuft[2];
28801
+ clump[k * 4 + 2] = -dx * ny;
28802
+ clump[k * 4 + 3] = -dz * ny;
28803
+ minY = Math.min(minY, y);
28804
+ maxY = Math.max(maxY, y);
28805
+ k++;
28806
+ }
28807
+ if (k === 0) return null;
28808
+ const blade = this.blade.geometry;
28809
+ const geo = new InstancedBufferGeometry();
28810
+ if (blade.index) geo.setIndex(new BufferAttribute(blade.index.array, 1));
28811
+ for (const [name, attr] of Object.entries(blade.attributes))
28812
+ geo.setAttribute(name, new BufferAttribute(attr.array, attr.itemSize, attr.normalized));
28813
+ geo.setAttribute(
28814
+ GRASS_FIELD_ATTRIBUTES.root,
28815
+ new InstancedBufferAttribute(pos.slice(0, k * 3), 3)
28816
+ );
28817
+ geo.setAttribute(
28818
+ GRASS_FIELD_ATTRIBUTES.rand,
28819
+ new InstancedBufferAttribute(rand.slice(0, k * 4), 4)
28820
+ );
28821
+ geo.setAttribute(
28822
+ GRASS_FIELD_ATTRIBUTES.clump,
28823
+ new InstancedBufferAttribute(clump.slice(0, k * 4), 4)
28824
+ );
28825
+ geo.instanceCount = k;
28826
+ const halfY = (maxY - minY) / 2;
28827
+ const radius = Math.sqrt(S * S * 0.5 + halfY * halfY);
28828
+ const pad = Math.max(this.blade.reach, 0) * 1.5 + 1;
28829
+ geo.boundingSphere = new Sphere(new Vector3(S / 2, minY + halfY, S / 2), radius + pad);
28830
+ geo.boundingBox = new Box3(
28831
+ new Vector3(-pad, minY - 1, -pad),
28832
+ new Vector3(S + pad, maxY + pad, S + pad)
28833
+ );
28834
+ const mesh = new Mesh(geo, this.material);
28835
+ mesh.name = `grass ${ix},${iz}`;
28836
+ mesh.position.set(ox, 0, oz);
28837
+ mesh.matrixAutoUpdate = false;
28838
+ mesh.updateMatrix();
28839
+ mesh.raycast = () => {
28840
+ };
28841
+ this.add(mesh);
28842
+ return { ix, iz, count: k, mesh, priority: priority.slice(0, k), radius };
28843
+ }
28844
+ #pointInBounds(x, z) {
28845
+ const b = this.bounds;
28846
+ return b === null || x >= b.minX && x <= b.maxX && z >= b.minZ && z <= b.maxZ;
28847
+ }
28848
+ /** Slope limit times the game's mask, 0..1. */
28849
+ #coverage(x, z, y, ny, cosMax, span) {
28850
+ const m = clamp01((ny - cosMax) / span);
28851
+ return m > 0 && this.getDensity ? m * clamp01(this.getDensity(x, z, y, ny)) : m;
28852
+ }
28853
+ #dispose(chunk) {
28854
+ if (!chunk.mesh) return;
28855
+ this.remove(chunk.mesh);
28856
+ chunk.mesh.geometry.dispose();
28857
+ }
28858
+ };
28859
+ var scratch3 = new Vector3();
28860
+ function setIfChanged(node, value) {
28861
+ if (node.value !== value) node.value = value;
28862
+ }
28863
+ var tuft = new Float64Array(3);
28864
+ var tuftCells = new Float64Array(0);
28865
+ var tuftX0 = 0;
28866
+ var tuftZ0 = 0;
28867
+ var tuftW = 0;
28868
+ function prepareTufts(ox, oz, S, cs, seed) {
28869
+ tuftX0 = Math.floor(ox / cs) - 1;
28870
+ tuftZ0 = Math.floor(oz / cs) - 1;
28871
+ tuftW = Math.floor((ox + S) / cs) - tuftX0 + 2;
28872
+ const rows = Math.floor((oz + S) / cs) - tuftZ0 + 2;
28873
+ if (tuftCells.length < tuftW * rows * 3) tuftCells = new Float64Array(tuftW * rows * 3);
28874
+ for (let r = 0; r < rows; r++)
28875
+ for (let c = 0; c < tuftW; c++) {
28876
+ const cx = tuftX0 + c;
28877
+ const cz = tuftZ0 + r;
28878
+ const h = hashInt(cx, cz, seed + 7919);
28879
+ const o = (r * tuftW + c) * 3;
28880
+ tuftCells[o] = (cx + (h & 1023) / 1023) * cs;
28881
+ tuftCells[o + 1] = (cz + (h >>> 10 & 1023) / 1023) * cs;
28882
+ tuftCells[o + 2] = (h >>> 20 & 1023) / 1023;
28883
+ }
28884
+ }
28885
+ function nearestTuft(wx, wz, cs) {
28886
+ const ccx = Math.floor(wx / cs);
28887
+ const ccz = Math.floor(wz / cs);
28888
+ let best = Number.POSITIVE_INFINITY;
28889
+ for (let jz = -1; jz <= 1; jz++)
28890
+ for (let jx = -1; jx <= 1; jx++) {
28891
+ const o = ((ccz + jz - tuftZ0) * tuftW + (ccx + jx - tuftX0)) * 3;
28892
+ const px = tuftCells[o];
28893
+ const pz = tuftCells[o + 1];
28894
+ const dd = (px - wx) * (px - wx) + (pz - wz) * (pz - wz);
28895
+ if (dd >= best) continue;
28896
+ best = dd;
28897
+ tuft[0] = px;
28898
+ tuft[1] = pz;
28899
+ tuft[2] = tuftCells[o + 2];
28900
+ }
28901
+ }
28902
+ function fastAtan2(y, x) {
28903
+ const ax = Math.abs(x);
28904
+ const ay = Math.abs(y);
28905
+ const hi = Math.max(ax, ay);
28906
+ if (hi === 0) return 0;
28907
+ const a = Math.min(ax, ay) / hi;
28908
+ const s = a * a;
28909
+ let r = ((((-0.01348047 * s + 0.057477314) * s - 0.121239071) * s + 0.195635925) * s - 0.332994597) * s * a + 0.99999563 * a;
28910
+ if (ay > ax) r = 1.57079637 - r;
28911
+ if (x < 0) r = 3.14159274 - r;
28912
+ return y < 0 ? -r : r;
28913
+ }
28914
+ var DEG2 = Math.PI / 180;
28915
+ var scratchPosition = new Vector3();
28916
+ var scratchScale2 = new Vector3();
28917
+ var scratchQuaternion = new Quaternion();
28918
+ var scratchTilt = new Quaternion();
28919
+ var scratchMatrix = new Matrix4();
28920
+ var up = new Vector3(0, 1, 0);
28921
+ var normal = new Vector3();
28922
+ var ScatterField3D = class extends Group {
28923
+ parts;
28924
+ place;
28925
+ getHeight;
28926
+ getDensity;
28927
+ bounds;
28928
+ density;
28929
+ chunkSize;
28930
+ seed;
28931
+ heightSampleSpacing;
28932
+ maxSlope;
28933
+ slopeFade;
28934
+ minAltitude;
28935
+ maxAltitude;
28936
+ drawDistance;
28937
+ lodDistances;
28938
+ thinStart;
28939
+ thinEnd;
28940
+ farDensity;
28941
+ buildBudgetMs;
28942
+ alignToGround;
28943
+ receiveShadow;
28944
+ castShadow;
28945
+ densityScale;
28946
+ cullDistanceScale;
28947
+ #ring;
28948
+ #shown = { instances: 0, visibleTiles: 0 };
28949
+ #version = 0;
28950
+ #layout = "";
28951
+ constructor(options) {
28952
+ super();
28953
+ this.name = "ScatterField3D";
28954
+ if (typeof options.place !== "function")
28955
+ throw new Error("ScatterField3D.place must be a function (point, out) => boolean.");
28956
+ if (typeof options.getHeight !== "function")
28957
+ throw new Error("ScatterField3D.getHeight must be a function (x, z) => height.");
28958
+ if (!Array.isArray(options.parts) || options.parts.length === 0)
28959
+ throw new Error("ScatterField3D.parts must list at least one part.");
28960
+ options.parts.forEach((part, index) => {
28961
+ if (!Array.isArray(part.lods) || part.lods.length === 0)
28962
+ throw new Error(`ScatterField3D.parts[${index}].lods must list at least one geometry.`);
28963
+ if (!part.material)
28964
+ throw new Error(`ScatterField3D.parts[${index}] has no material; the game owns the look.`);
28965
+ });
28966
+ this.parts = options.parts;
28967
+ this.place = options.place;
28968
+ this.getHeight = options.getHeight;
28969
+ this.getDensity = options.getDensity ?? null;
28970
+ this.bounds = options.bounds ?? null;
28971
+ this.density = options.density ?? 0.1;
28972
+ this.chunkSize = options.chunkSize ?? 16;
28973
+ this.seed = options.seed ?? 1337;
28974
+ this.heightSampleSpacing = options.heightSampleSpacing ?? 0.75;
28975
+ this.maxSlope = options.maxSlope ?? 42;
28976
+ this.slopeFade = options.slopeFade ?? 12;
28977
+ this.minAltitude = options.minAltitude ?? Number.NEGATIVE_INFINITY;
28978
+ this.maxAltitude = options.maxAltitude ?? Number.POSITIVE_INFINITY;
28979
+ this.drawDistance = options.drawDistance ?? 60;
28980
+ this.lodDistances = options.lodDistances ?? [20, 45];
28981
+ this.thinStart = options.thinStart ?? 10;
28982
+ this.thinEnd = options.thinEnd ?? 50;
28983
+ this.farDensity = options.farDensity ?? 0.3;
28984
+ this.buildBudgetMs = options.buildBudgetMs ?? 4;
28985
+ this.alignToGround = options.alignToGround ?? true;
28986
+ this.receiveShadow = options.receiveShadow ?? true;
28987
+ this.castShadow = options.castShadow ?? true;
28988
+ this.densityScale = options.densityScale ?? 1;
28989
+ this.cullDistanceScale = options.cullDistanceScale ?? 1;
28990
+ this.#validate();
28991
+ this.#ring = new TileRing(this.#hooks());
28992
+ }
28993
+ get stats() {
28994
+ return {
28995
+ built: this.#ring.stats.built,
28996
+ instances: this.#shown.instances,
28997
+ pending: this.#ring.stats.pending,
28998
+ tiles: this.#ring.stats.tiles,
28999
+ visibleTiles: this.#shown.visibleTiles
29000
+ };
29001
+ }
29002
+ /** Builds every tile in range on the next `update` regardless of budget: on load or after a teleport. */
29003
+ prewarm() {
29004
+ this.#ring.prewarm();
29005
+ }
29006
+ /** Re-scatter after the ground or the coverage changed: all tiles, or those touching a rectangle. */
29007
+ refresh(rect) {
29008
+ if (rect === void 0) {
29009
+ this.#version++;
29010
+ return;
29011
+ }
29012
+ this.#ring.disposeInside(rect);
29013
+ }
29014
+ /** Streams, thins and LODs the tiles round `follow`. Call once per rendered frame. */
29015
+ update(follow) {
29016
+ this.#validate();
29017
+ const layout = this.#layoutKey();
29018
+ if (layout !== this.#layout) {
29019
+ this.#ring.clear();
29020
+ this.#layout = layout;
29021
+ }
29022
+ scratchPosition.copy(follow);
29023
+ this.worldToLocal(scratchPosition);
29024
+ this.#shown.visibleTiles = this.#shown.instances = 0;
29025
+ this.#ring.update(scratchPosition.x, scratchPosition.z);
29026
+ }
29027
+ dispose() {
29028
+ this.#ring.clear();
29029
+ }
29030
+ #hooks() {
29031
+ const field = this;
29032
+ return {
29033
+ build: (ix, iz) => this.#build(ix, iz),
29034
+ get buildBudgetMs() {
29035
+ return field.buildBudgetMs;
29036
+ },
29037
+ get chunkSize() {
29038
+ return field.chunkSize;
29039
+ },
29040
+ get drawDistance() {
29041
+ return field.drawDistance * field.cullDistanceScale;
29042
+ },
29043
+ dispose: (tile) => this.#disposeTile(tile),
29044
+ hide: (tile) => {
29045
+ for (const part of tile.meshes)
29046
+ for (const mesh of part) if (mesh.visible) mesh.visible = false;
29047
+ },
29048
+ inBounds: (ix, iz) => this.#inBounds(ix, iz),
29049
+ show: (tile, distance) => this.#show(tile, distance)
29050
+ };
29051
+ }
29052
+ #validate() {
29053
+ if (!(this.chunkSize > 0))
29054
+ throw new Error(`ScatterField3D.chunkSize must be > 0, got ${this.chunkSize}.`);
29055
+ if (!(this.density >= 0))
29056
+ throw new Error(`ScatterField3D.density must be >= 0, got ${this.density}.`);
29057
+ if (!(this.drawDistance > 0))
29058
+ throw new Error(`ScatterField3D.drawDistance must be > 0, got ${this.drawDistance}.`);
29059
+ if (!(this.buildBudgetMs >= 0))
29060
+ throw new Error(`ScatterField3D.buildBudgetMs must be >= 0, got ${this.buildBudgetMs}.`);
29061
+ if (!(this.densityScale >= 0) || !(this.cullDistanceScale > 0))
29062
+ throw new Error("ScatterField3D.densityScale must be >= 0 and cullDistanceScale > 0.");
29063
+ const b = this.bounds;
29064
+ if (b === null) return;
29065
+ for (const key of ["minX", "minZ", "maxX", "maxZ"])
29066
+ if (!Number.isFinite(b[key])) throw new Error(`ScatterField3D.bounds.${key} must be finite.`);
29067
+ if (b.minX >= b.maxX) throw new Error("ScatterField3D.bounds.minX must be below bounds.maxX.");
29068
+ if (b.minZ >= b.maxZ) throw new Error("ScatterField3D.bounds.minZ must be below bounds.maxZ.");
29069
+ }
29070
+ #layoutKey() {
29071
+ return [
29072
+ this.#version,
29073
+ this.density * this.densityScale,
29074
+ this.chunkSize,
29075
+ this.seed,
29076
+ this.heightSampleSpacing,
29077
+ this.maxSlope,
29078
+ this.slopeFade,
29079
+ this.minAltitude,
29080
+ this.maxAltitude,
29081
+ this.alignToGround,
29082
+ this.parts.length
29083
+ ].join("|");
29084
+ }
29085
+ #inBounds(ix, iz) {
29086
+ const b = this.bounds;
29087
+ const S = this.chunkSize;
29088
+ return b === null || !(ix * S >= b.maxX || (ix + 1) * S <= b.minX || iz * S >= b.maxZ || (iz + 1) * S <= b.minZ);
29089
+ }
29090
+ #pointInBounds(x, z) {
29091
+ const b = this.bounds;
29092
+ return b === null || x >= b.minX && x <= b.maxX && z >= b.minZ && z <= b.maxZ;
29093
+ }
29094
+ /** Slope limit times the game's coverage mask, 0..1. */
29095
+ #coverage(x, z, y, ny, cosMax, span) {
29096
+ const m = clamp01((ny - cosMax) / span);
29097
+ return m > 0 && this.getDensity ? m * clamp01(this.getDensity(x, z, y, ny)) : m;
29098
+ }
29099
+ /** The thinning cut-off at a tile's nearest point: the same rule the material cannot apply here. */
29100
+ #kept(tile, distance) {
29101
+ const k = this.cullDistanceScale;
29102
+ const thinEnd = Math.max(this.thinEnd, this.thinStart + 0.01) * k;
29103
+ const edge = 1.1 + (this.farDensity - 1.1) * smoothstep6(this.thinStart * k, thinEnd, distance);
29104
+ if (edge >= 1) return tile.count;
29105
+ const pr = tile.priority;
29106
+ let lo = 0;
29107
+ let hi = tile.count;
29108
+ while (lo < hi) {
29109
+ const mid = lo + hi >> 1;
29110
+ if (pr[mid] < edge) lo = mid + 1;
29111
+ else hi = mid;
29112
+ }
29113
+ return lo;
29114
+ }
29115
+ #show(tile, distance) {
29116
+ const R = this.drawDistance * this.cullDistanceScale;
29117
+ const k = this.cullDistanceScale;
29118
+ const n = this.#kept(tile, distance);
29119
+ const inRange = n > 0 && distance < R;
29120
+ if (inRange) {
29121
+ this.#shown.visibleTiles++;
29122
+ this.#shown.instances += n;
29123
+ }
29124
+ for (let part = 0; part < this.parts.length; part++) {
29125
+ const meshes = tile.meshes[part];
29126
+ let level = 0;
29127
+ while (level < meshes.length - 1 && distance >= (this.lodDistances[level] ?? Number.POSITIVE_INFINITY) * k)
29128
+ level++;
29129
+ for (let l = 0; l < meshes.length; l++) {
29130
+ const mesh = meshes[l];
29131
+ const visible = inRange && l === level;
29132
+ if (mesh.visible !== visible) mesh.visible = visible;
29133
+ if (mesh.count !== n) mesh.count = n;
29134
+ if (mesh.receiveShadow !== this.receiveShadow) mesh.receiveShadow = this.receiveShadow;
29135
+ if (mesh.castShadow !== this.castShadow) mesh.castShadow = this.castShadow;
29136
+ }
29137
+ }
29138
+ }
29139
+ #build(ix, iz) {
29140
+ const S = this.chunkSize;
29141
+ const ox = ix * S;
29142
+ const oz = iz * S;
29143
+ const rng = mulberry32(hashInt(ix, iz, this.seed | 0));
29144
+ const ground = groundGrid(this.getHeight, ox, oz, S, this.heightSampleSpacing);
29145
+ const n = Math.max(1, Math.ceil(Math.sqrt(this.density * this.densityScale * S * S)));
29146
+ const total = this.density * this.densityScale > 0 ? n * n : 0;
29147
+ const cell = S / n;
29148
+ const order = shuffled(total, rng);
29149
+ const matrices = [];
29150
+ const priority = new Float32Array(total);
29151
+ const cosMax = Math.cos(this.maxSlope * DEG2);
29152
+ const slopeSpan = Math.max(
29153
+ Math.cos(Math.max(this.maxSlope - this.slopeFade, 0) * DEG2) - cosMax,
29154
+ 1e-5
29155
+ );
29156
+ const out = { priority: 0, scale: 1, x: 0, y: 0, z: 0, yaw: 0 };
29157
+ let k = 0;
29158
+ for (let q = 0; q < total; q++) {
29159
+ const c = order[q];
29160
+ const lx = (c % n + rng()) * cell;
29161
+ const lz = ((c / n | 0) + rng()) * cell;
29162
+ const rKeep = rng();
29163
+ const wx = ox + lx;
29164
+ const wz = oz + lz;
29165
+ if (!this.#pointInBounds(wx, wz)) continue;
29166
+ ground.sample(lx, lz);
29167
+ const y = sample[0];
29168
+ const dx = sample[1];
29169
+ const dz = sample[2];
29170
+ if (y < this.minAltitude || y > this.maxAltitude) continue;
29171
+ const ny = 1 / Math.sqrt(dx * dx + dz * dz + 1);
29172
+ const m = this.#coverage(wx, wz, y, ny, cosMax, slopeSpan);
29173
+ if (m <= 1e-3 || rKeep > m * 2) continue;
29174
+ out.x = wx;
29175
+ out.y = y;
29176
+ out.z = wz;
29177
+ out.yaw = 0;
29178
+ out.scale = 1;
29179
+ out.priority = q / total;
29180
+ const placed = this.place({ nx: -dx * ny, ny, nz: -dz * ny, x: wx, y, z: wz }, out);
29181
+ if (!placed) continue;
29182
+ if (!Number.isFinite(out.scale) || out.scale <= 0 || !Number.isFinite(out.yaw))
29183
+ throw new Error(
29184
+ `ScatterField3D.place returned scale ${out.scale} and yaw ${out.yaw} at (${wx}, ${wz}); both must be finite and the scale positive.`
29185
+ );
29186
+ priority[k] = q / total;
29187
+ scratchPosition.set(out.x, out.y, out.z);
29188
+ scratchScale2.setScalar(out.scale);
29189
+ if (this.alignToGround) {
29190
+ normal.set(-dx, 1, -dz).normalize();
29191
+ scratchTilt.setFromUnitVectors(up, normal);
29192
+ scratchQuaternion.setFromAxisAngle(up, out.yaw);
29193
+ scratchQuaternion.premultiply(scratchTilt);
29194
+ } else {
29195
+ scratchQuaternion.setFromAxisAngle(up, out.yaw);
29196
+ }
29197
+ matrices.push(
29198
+ scratchMatrix.clone().compose(scratchPosition, scratchQuaternion, scratchScale2)
29199
+ );
29200
+ k++;
29201
+ }
29202
+ if (k === 0) return null;
29203
+ const meshes = [];
29204
+ for (let part = 0; part < this.parts.length; part++) {
29205
+ const source2 = this.parts[part];
29206
+ const levels = [];
29207
+ for (let l = 0; l < source2.lods.length; l++) {
29208
+ const geometry = source2.lods[l];
29209
+ const mesh = new InstancedMesh(geometry, source2.material, k);
29210
+ mesh.name = `scatter part${part} lod${l} ${ix},${iz}`;
29211
+ for (let i = 0; i < k; i++) mesh.setMatrixAt(i, matrices[i]);
29212
+ mesh.instanceMatrix.needsUpdate = true;
29213
+ mesh.position.set(ox, 0, oz);
29214
+ mesh.matrixAutoUpdate = false;
29215
+ mesh.updateMatrix();
29216
+ mesh.visible = false;
29217
+ mesh.raycast = () => {
29218
+ };
29219
+ mesh.computeBoundingSphere();
29220
+ this.add(mesh);
29221
+ levels.push(mesh);
29222
+ }
29223
+ meshes.push(levels);
29224
+ }
29225
+ return { count: k, meshes, priority: priority.slice(0, k) };
29226
+ }
29227
+ #disposeTile(tile) {
29228
+ for (const part of tile.meshes)
29229
+ for (const mesh of part) {
29230
+ this.remove(mesh);
29231
+ mesh.dispose();
29232
+ }
29233
+ }
29234
+ };
27838
29235
  var DEFAULT_MAX_SPLATS = 8;
27839
29236
  var DEFAULT_TIME_STEP = 1 / 60;
27840
29237
  var DEFAULT_VORTICITY = 0.2;
@@ -27877,10 +29274,10 @@ function pixelUv(resolution) {
27877
29274
  function readFluidTexture(texture7) {
27878
29275
  return storageTexture$1(texture7).toReadOnly().setSampler(false);
27879
29276
  }
27880
- function sampleAt(texture7, uv7, resolution) {
29277
+ function sampleAt(texture7, uv8, resolution) {
27881
29278
  const size = resolution;
27882
29279
  return texture7.sample(
27883
- uvec2(uint(clamp(uv7.x.mul(size), 0, size - 1)), uint(clamp(uv7.y.mul(size), 0, size - 1)))
29280
+ uvec2(uint(clamp(uv8.x.mul(size), 0, size - 1)), uint(clamp(uv8.y.mul(size), 0, size - 1)))
27884
29281
  );
27885
29282
  }
27886
29283
  var FluidFieldSampler = class {
@@ -27890,8 +29287,8 @@ var FluidFieldSampler = class {
27890
29287
  this.#texture = readFluidTexture(texture7);
27891
29288
  this.#resolution = resolution;
27892
29289
  }
27893
- sample(uv7) {
27894
- return sampleAt(this.#texture, uv7, this.#resolution);
29290
+ sample(uv8) {
29291
+ return sampleAt(this.#texture, uv8, this.#resolution);
27895
29292
  }
27896
29293
  setTexture(texture7) {
27897
29294
  this.#texture.value = texture7;
@@ -27904,8 +29301,8 @@ function write(texture7, resolution, value) {
27904
29301
  value
27905
29302
  ).toWriteOnly();
27906
29303
  }
27907
- function neighbour(texture7, uv7, texel, resolution, x, y) {
27908
- return sampleAt(texture7, clamp(uv7.add(vec2(x, y).mul(texel)), 0, 1), resolution);
29304
+ function neighbour(texture7, uv8, texel, resolution, x, y) {
29305
+ return sampleAt(texture7, clamp(uv8.add(vec2(x, y).mul(texel)), 0, 1), resolution);
27909
29306
  }
27910
29307
  function pair(first, second) {
27911
29308
  return [first, second];
@@ -28048,9 +29445,9 @@ var FluidField2D = class extends Group {
28048
29445
  this.#renderer = renderer;
28049
29446
  for (const node of this.warmupNodes.slice(0, 8)) renderer.compute(node);
28050
29447
  }
28051
- splat(uv7, velocity, amount) {
29448
+ splat(uv8, velocity, amount) {
28052
29449
  if (this.#released) throw new Error("FluidField2D cannot splat after release.");
28053
- if (![uv7.x, uv7.y, velocity.x, velocity.y, amount].every(Number.isFinite))
29450
+ if (![uv8.x, uv8.y, velocity.x, velocity.y, amount].every(Number.isFinite))
28054
29451
  throw new Error("FluidField2D.splat arguments must be finite.");
28055
29452
  if (amount < 0) throw new Error("FluidField2D.splat amount must be non-negative.");
28056
29453
  if (amount === 0) return;
@@ -28058,7 +29455,7 @@ var FluidField2D = class extends Group {
28058
29455
  const offset = this.#queuedSplats * 4;
28059
29456
  const position = this.#splatPositions.array[offset / 4];
28060
29457
  const splatAmount = this.#splatAmounts.array[offset / 4];
28061
- position.set(clampNumber(uv7.x, 0, 1), clampNumber(uv7.y, 0, 1), velocity.x, velocity.y);
29458
+ position.set(clampNumber(uv8.x, 0, 1), clampNumber(uv8.y, 0, 1), velocity.x, velocity.y);
28062
29459
  splatAmount.set(amount, 0, 0, 0);
28063
29460
  this.#queuedSplats += 1;
28064
29461
  }
@@ -28145,13 +29542,13 @@ var FluidField2D = class extends Group {
28145
29542
  #makeVelocitySplatPair() {
28146
29543
  return this.#makePair("fluid.splat.velocity", this.#velocityTextures, (source2, target) => {
28147
29544
  const sourceNode = readFluidTexture(source2);
28148
- const uv7 = pixelUv(this.resolution);
28149
- const pixel = sampleAt(sourceNode, uv7, this.resolution).toVar();
29545
+ const uv8 = pixelUv(this.resolution);
29546
+ const pixel = sampleAt(sourceNode, uv8, this.resolution).toVar();
28150
29547
  Loop({ type: "uint", start: 0, end: this.#splatCount }, ({ i }) => {
28151
29548
  const position = this.#splatPositions.element(i);
28152
29549
  const impulse = this.#splatAmounts.element(i).x;
28153
29550
  const influence = clamp(
28154
- float(1).sub(length(uv7.sub(position.xy)).div(this.splatRadius)),
29551
+ float(1).sub(length(uv8.sub(position.xy)).div(this.splatRadius)),
28155
29552
  0,
28156
29553
  1
28157
29554
  );
@@ -28166,13 +29563,13 @@ var FluidField2D = class extends Group {
28166
29563
  #makeDyeSplatPair() {
28167
29564
  return this.#makePair("fluid.splat.dye", this.#dyeTextures, (source2, target) => {
28168
29565
  const sourceNode = readFluidTexture(source2);
28169
- const uv7 = pixelUv(this.resolution);
28170
- const pixel = sampleAt(sourceNode, uv7, this.resolution).toVar();
29566
+ const uv8 = pixelUv(this.resolution);
29567
+ const pixel = sampleAt(sourceNode, uv8, this.resolution).toVar();
28171
29568
  Loop({ type: "uint", start: 0, end: this.#splatCount }, ({ i }) => {
28172
29569
  const position = this.#splatPositions.element(i);
28173
29570
  const amount = this.#splatAmounts.element(i).x;
28174
29571
  const influence = clamp(
28175
- float(1).sub(length(uv7.sub(position.xy)).div(this.splatRadius)),
29572
+ float(1).sub(length(uv8.sub(position.xy)).div(this.splatRadius)),
28176
29573
  0,
28177
29574
  1
28178
29575
  );
@@ -28190,13 +29587,13 @@ var FluidField2D = class extends Group {
28190
29587
  #makeCurlKernel(name, sourceTexture) {
28191
29588
  const source2 = readFluidTexture(sourceTexture);
28192
29589
  return computeKernel(name, this.resolution, () => {
28193
- const uv7 = pixelUv(this.resolution);
29590
+ const uv8 = pixelUv(this.resolution);
28194
29591
  const texel = vec2(1 / this.resolution);
28195
- const center = sampleAt(source2, uv7, this.resolution);
28196
- const l = neighbour(source2, uv7, texel, this.resolution, -1, 0).y;
28197
- const r = neighbour(source2, uv7, texel, this.resolution, 1, 0).y;
28198
- const b = neighbour(source2, uv7, texel, this.resolution, 0, -1).x;
28199
- const t = neighbour(source2, uv7, texel, this.resolution, 0, 1).x;
29592
+ const center = sampleAt(source2, uv8, this.resolution);
29593
+ const l = neighbour(source2, uv8, texel, this.resolution, -1, 0).y;
29594
+ const r = neighbour(source2, uv8, texel, this.resolution, 1, 0).y;
29595
+ const b = neighbour(source2, uv8, texel, this.resolution, 0, -1).x;
29596
+ const t = neighbour(source2, uv8, texel, this.resolution, 0, 1).x;
28200
29597
  return write(
28201
29598
  this.#curlTexture,
28202
29599
  this.resolution,
@@ -28208,16 +29605,16 @@ var FluidField2D = class extends Group {
28208
29605
  return this.#makePair("fluid.vorticity", this.#velocityTextures, (source2, target) => {
28209
29606
  const velocity = readFluidTexture(source2);
28210
29607
  const curl = readFluidTexture(this.#curlTexture);
28211
- const uv7 = pixelUv(this.resolution);
29608
+ const uv8 = pixelUv(this.resolution);
28212
29609
  const texel = vec2(1 / this.resolution);
28213
- const center = sampleAt(velocity, uv7, this.resolution);
28214
- const curlCenter = sampleAt(curl, uv7, this.resolution).z;
29610
+ const center = sampleAt(velocity, uv8, this.resolution);
29611
+ const curlCenter = sampleAt(curl, uv8, this.resolution).z;
28215
29612
  const gradient = vec2(
28216
- abs(neighbour(curl, uv7, texel, this.resolution, 0, 1).z).sub(
28217
- abs(neighbour(curl, uv7, texel, this.resolution, 0, -1).z)
29613
+ abs(neighbour(curl, uv8, texel, this.resolution, 0, 1).z).sub(
29614
+ abs(neighbour(curl, uv8, texel, this.resolution, 0, -1).z)
28218
29615
  ),
28219
- abs(neighbour(curl, uv7, texel, this.resolution, 1, 0).z).sub(
28220
- abs(neighbour(curl, uv7, texel, this.resolution, -1, 0).z)
29616
+ abs(neighbour(curl, uv8, texel, this.resolution, 1, 0).z).sub(
29617
+ abs(neighbour(curl, uv8, texel, this.resolution, -1, 0).z)
28221
29618
  )
28222
29619
  );
28223
29620
  const force = gradient.div(length(gradient).add(1e-4));
@@ -28237,12 +29634,12 @@ var FluidField2D = class extends Group {
28237
29634
  #makeDivergenceKernel(name, sourceTexture) {
28238
29635
  const source2 = readFluidTexture(sourceTexture);
28239
29636
  return computeKernel(name, this.resolution, () => {
28240
- const uv7 = pixelUv(this.resolution);
29637
+ const uv8 = pixelUv(this.resolution);
28241
29638
  const texel = vec2(1 / this.resolution);
28242
- const left = neighbour(source2, uv7, texel, this.resolution, -1, 0).x;
28243
- const right = neighbour(source2, uv7, texel, this.resolution, 1, 0).x;
28244
- const bottom = neighbour(source2, uv7, texel, this.resolution, 0, -1).y;
28245
- const top = neighbour(source2, uv7, texel, this.resolution, 0, 1).y;
29639
+ const left = neighbour(source2, uv8, texel, this.resolution, -1, 0).x;
29640
+ const right = neighbour(source2, uv8, texel, this.resolution, 1, 0).x;
29641
+ const bottom = neighbour(source2, uv8, texel, this.resolution, 0, -1).y;
29642
+ const top = neighbour(source2, uv8, texel, this.resolution, 0, 1).y;
28246
29643
  return write(
28247
29644
  this.#divergenceTexture,
28248
29645
  this.resolution,
@@ -28277,13 +29674,13 @@ var FluidField2D = class extends Group {
28277
29674
  #makePressureKernel(name, sourceTexture, targetTexture, divergence) {
28278
29675
  return computeKernel(name, this.resolution, () => {
28279
29676
  const pressure = readFluidTexture(sourceTexture);
28280
- const uv7 = pixelUv(this.resolution);
29677
+ const uv8 = pixelUv(this.resolution);
28281
29678
  const texel = vec2(1 / this.resolution);
28282
- const left = neighbour(pressure, uv7, texel, this.resolution, -1, 0).x;
28283
- const right = neighbour(pressure, uv7, texel, this.resolution, 1, 0).x;
28284
- const bottom = neighbour(pressure, uv7, texel, this.resolution, 0, -1).x;
28285
- const top = neighbour(pressure, uv7, texel, this.resolution, 0, 1).x;
28286
- const value = left.add(right).add(bottom).add(top).sub(sampleAt(divergence, uv7, this.resolution).w).mul(0.25);
29679
+ const left = neighbour(pressure, uv8, texel, this.resolution, -1, 0).x;
29680
+ const right = neighbour(pressure, uv8, texel, this.resolution, 1, 0).x;
29681
+ const bottom = neighbour(pressure, uv8, texel, this.resolution, 0, -1).x;
29682
+ const top = neighbour(pressure, uv8, texel, this.resolution, 0, 1).x;
29683
+ const value = left.add(right).add(bottom).add(top).sub(sampleAt(divergence, uv8, this.resolution).w).mul(0.25);
28287
29684
  return write(targetTexture, this.resolution, vec4(value, 0, 0, 0));
28288
29685
  });
28289
29686
  }
@@ -28323,15 +29720,15 @@ var FluidField2D = class extends Group {
28323
29720
  return computeKernel(name, this.resolution, () => {
28324
29721
  const velocity = readFluidTexture(sourceTexture);
28325
29722
  const pressure = readFluidTexture(pressureTexture);
28326
- const uv7 = pixelUv(this.resolution);
29723
+ const uv8 = pixelUv(this.resolution);
28327
29724
  const texel = vec2(1 / this.resolution);
28328
- const center = sampleAt(velocity, uv7, this.resolution);
29725
+ const center = sampleAt(velocity, uv8, this.resolution);
28329
29726
  const gradient = vec2(
28330
- neighbour(pressure, uv7, texel, this.resolution, 1, 0).x.sub(
28331
- neighbour(pressure, uv7, texel, this.resolution, -1, 0).x
29727
+ neighbour(pressure, uv8, texel, this.resolution, 1, 0).x.sub(
29728
+ neighbour(pressure, uv8, texel, this.resolution, -1, 0).x
28332
29729
  ),
28333
- neighbour(pressure, uv7, texel, this.resolution, 0, 1).x.sub(
28334
- neighbour(pressure, uv7, texel, this.resolution, 0, -1).x
29730
+ neighbour(pressure, uv8, texel, this.resolution, 0, 1).x.sub(
29731
+ neighbour(pressure, uv8, texel, this.resolution, 0, -1).x
28335
29732
  )
28336
29733
  ).mul(0.5);
28337
29734
  return write(targetTexture, this.resolution, vec4(center.xy.sub(gradient), center.zw));
@@ -28340,12 +29737,12 @@ var FluidField2D = class extends Group {
28340
29737
  #makeAdvectVelocityPair() {
28341
29738
  return this.#makePair("fluid.advect.velocity", this.#velocityTextures, (source2, target) => {
28342
29739
  const velocity = readFluidTexture(source2);
28343
- const uv7 = pixelUv(this.resolution);
29740
+ const uv8 = pixelUv(this.resolution);
28344
29741
  const texel = vec2(1 / this.resolution);
28345
- const center = sampleAt(velocity, uv7, this.resolution);
28346
- const traced = clamp(uv7.sub(center.xy.mul(this.timeStep)), 0, 1);
29742
+ const center = sampleAt(velocity, uv8, this.resolution);
29743
+ const traced = clamp(uv8.sub(center.xy.mul(this.timeStep)), 0, 1);
28347
29744
  const advected = sampleAt(velocity, traced, this.resolution).xy;
28348
- const laplacian = neighbour(velocity, uv7, texel, this.resolution, -1, 0).xy.add(neighbour(velocity, uv7, texel, this.resolution, 1, 0).xy).add(neighbour(velocity, uv7, texel, this.resolution, 0, -1).xy).add(neighbour(velocity, uv7, texel, this.resolution, 0, 1).xy).sub(center.xy.mul(4));
29745
+ const laplacian = neighbour(velocity, uv8, texel, this.resolution, -1, 0).xy.add(neighbour(velocity, uv8, texel, this.resolution, 1, 0).xy).add(neighbour(velocity, uv8, texel, this.resolution, 0, -1).xy).add(neighbour(velocity, uv8, texel, this.resolution, 0, 1).xy).sub(center.xy.mul(4));
28349
29746
  const next = advected.add(laplacian.mul(this.viscosity * this.timeStep));
28350
29747
  return write(target, this.resolution, vec4(next, center.zw));
28351
29748
  });
@@ -28386,9 +29783,9 @@ var FluidField2D = class extends Group {
28386
29783
  return computeKernel(name, this.resolution, () => {
28387
29784
  const dye = readFluidTexture(sourceTexture);
28388
29785
  const velocity = readFluidTexture(velocityTexture2);
28389
- const uv7 = pixelUv(this.resolution);
29786
+ const uv8 = pixelUv(this.resolution);
28390
29787
  const traced = clamp(
28391
- uv7.sub(sampleAt(velocity, uv7, this.resolution).xy.mul(this.timeStep)),
29788
+ uv8.sub(sampleAt(velocity, uv8, this.resolution).xy.mul(this.timeStep)),
28392
29789
  0,
28393
29790
  1
28394
29791
  );
@@ -28403,8 +29800,8 @@ var FluidField2D = class extends Group {
28403
29800
  }
28404
29801
  #onRemoved = () => this.detach();
28405
29802
  };
28406
- function clampNumber(value, min8, max9) {
28407
- return Math.min(max9, Math.max(min8, value));
29803
+ function clampNumber(value, min8, max11) {
29804
+ return Math.min(max11, Math.max(min8, value));
28408
29805
  }
28409
29806
  function tupleValue(values, index, name) {
28410
29807
  const value = values[index];
@@ -28416,9 +29813,9 @@ function matrixValue(values, row, column, name) {
28416
29813
  }
28417
29814
  var tslNodes = tsl;
28418
29815
  var {
28419
- Fn: Fn16,
28420
- If: If10,
28421
- Loop: Loop9,
29816
+ Fn: Fn17,
29817
+ If: If11,
29818
+ Loop: Loop10,
28422
29819
  Return: Return2,
28423
29820
  abs: abs7,
28424
29821
  atomicAdd,
@@ -28427,28 +29824,28 @@ var {
28427
29824
  atomicMin,
28428
29825
  atomicStore,
28429
29826
  ceil,
28430
- clamp: clamp8,
29827
+ clamp: clamp9,
28431
29828
  dot: dot8,
28432
29829
  exp: exp6,
28433
- float: float20,
28434
- floor: floor4,
29830
+ float: float23,
29831
+ floor: floor5,
28435
29832
  hash: hash2,
28436
29833
  instanceIndex: instanceIndex6,
28437
29834
  instancedArray: instancedArray3,
28438
- int: int7,
29835
+ int: int8,
28439
29836
  ivec3,
28440
- length: length6,
28441
- max: max8,
29837
+ length: length7,
29838
+ max: max10,
28442
29839
  min: min7,
28443
29840
  select: select4,
28444
29841
  storageTexture: storageTexture3,
28445
29842
  textureStore: textureStore3,
28446
29843
  uint: uint2,
28447
- uniform: uniform18,
29844
+ uniform: uniform21,
28448
29845
  uniformArray: uniformArray3,
28449
29846
  uvec3,
28450
- vec3: vec316,
28451
- vec4: vec418
29847
+ vec3: vec319,
29848
+ vec4: vec419
28452
29849
  } = tslNodes;
28453
29850
  var DEFAULT_SPACING = 0.22;
28454
29851
  var DEFAULT_BOUNDS = { min: [-2.9, 0.0968, -1.6], max: [2.9, 4.65, 1.6] };
@@ -28475,15 +29872,15 @@ function integerAtLeast(name, value, least) {
28475
29872
  if (!Number.isInteger(value) || value < least)
28476
29873
  throw new Error(`FluidParticles3D.${name} must be an integer of at least ${least}.`);
28477
29874
  }
28478
- function finiteVec(name, value, length7) {
28479
- if (value.length !== length7 || !value.every(Number.isFinite))
28480
- throw new Error(`FluidParticles3D.${name} must be ${length7} finite numbers.`);
29875
+ function finiteVec(name, value, length8) {
29876
+ if (value.length !== length8 || !value.every(Number.isFinite))
29877
+ throw new Error(`FluidParticles3D.${name} must be ${length8} finite numbers.`);
28481
29878
  }
28482
29879
  function nodeVar(node) {
28483
29880
  return node.toVar();
28484
29881
  }
28485
29882
  function computeKernel2(name, count, body) {
28486
- const node = Fn16(body)().compute(count);
29883
+ const node = Fn17(body)().compute(count);
28487
29884
  node.setName(name);
28488
29885
  return node;
28489
29886
  }
@@ -28691,24 +30088,24 @@ var FluidParticles3D = class extends Group {
28691
30088
  this.density.magFilter = LinearFilter;
28692
30089
  this.density.generateMipmaps = false;
28693
30090
  this.density.needsUpdate = true;
28694
- this.#viscosity = uniform18(viscosity);
28695
- this.#cohesion = uniform18(cohesion);
28696
- this.#vorticity = uniform18(vorticity);
28697
- this.#gravity = uniform18(gravity);
28698
- this.#time = uniform18(0);
28699
- this.#slots = uniform18(0, "uint");
30091
+ this.#viscosity = uniform21(viscosity);
30092
+ this.#cohesion = uniform21(cohesion);
30093
+ this.#vorticity = uniform21(vorticity);
30094
+ this.#gravity = uniform21(gravity);
30095
+ this.#time = uniform21(0);
30096
+ this.#slots = uniform21(0, "uint");
28700
30097
  const zeros = (count) => Array.from({ length: count }, () => new Vector4());
28701
- this.#spawnCount = uniform18(0, "uint");
30098
+ this.#spawnCount = uniform21(0, "uint");
28702
30099
  this.#spawnA = uniformArray3(zeros(maxSpawns), "vec4");
28703
30100
  this.#spawnB = uniformArray3(zeros(maxSpawns), "vec4");
28704
30101
  this.#spawnC = uniformArray3(zeros(maxSpawns), "vec4");
28705
- this.#drainCount = uniform18(0, "uint");
30102
+ this.#drainCount = uniform21(0, "uint");
28706
30103
  this.#drainMin = uniformArray3(zeros(MAX_DRAINS), "vec4");
28707
30104
  this.#drainMax = uniformArray3(zeros(MAX_DRAINS), "vec4");
28708
- this.#stirCount = uniform18(0, "uint");
30105
+ this.#stirCount = uniform21(0, "uint");
28709
30106
  this.#stirA = uniformArray3(zeros(MAX_STIRS), "vec4");
28710
30107
  this.#stirB = uniformArray3(zeros(MAX_STIRS), "vec4");
28711
- this.#colliderCount = uniform18(0, "uint");
30108
+ this.#colliderCount = uniform21(0, "uint");
28712
30109
  this.#colliderA = uniformArray3(zeros(maxColliders), "vec4");
28713
30110
  this.#colliderB = uniformArray3(zeros(maxColliders), "vec4");
28714
30111
  this.#colliderRows = [
@@ -28716,87 +30113,87 @@ var FluidParticles3D = class extends Group {
28716
30113
  uniformArray3(zeros(maxColliders), "vec4"),
28717
30114
  uniformArray3(zeros(maxColliders), "vec4")
28718
30115
  ];
28719
- const dt = float20(timeStep);
30116
+ const dt = float23(timeStep);
28720
30117
  const live = (index) => positions.element(index).w.greaterThan(0.5);
28721
30118
  const guard = () => {
28722
- If10(instanceIndex6.greaterThanEqual(this.#slots), () => {
30119
+ If11(instanceIndex6.greaterThanEqual(this.#slots), () => {
28723
30120
  Return2();
28724
30121
  });
28725
- If10(live(instanceIndex6).not(), () => {
30122
+ If11(live(instanceIndex6).not(), () => {
28726
30123
  Return2();
28727
30124
  });
28728
30125
  };
28729
30126
  const cellOf = (point) => ivec3(
28730
- clamp8(
28731
- floor4(point.sub(vec316(...gridOrigin)).div(h)),
28732
- vec316(1),
28733
- vec316(gridDims[0] - 2, gridDims[1] - 2, gridDims[2] - 2)
30127
+ clamp9(
30128
+ floor5(point.sub(vec319(...gridOrigin)).div(h)),
30129
+ vec319(1),
30130
+ vec319(gridDims[0] - 2, gridDims[1] - 2, gridDims[2] - 2)
28734
30131
  )
28735
30132
  );
28736
30133
  const cellId = (cell) => cell.x.add(cell.y.mul(gridDims[0])).add(cell.z.mul(gridDims[0] * gridDims[1])).toUint();
28737
30134
  const forNeighbours = (point, self, body) => {
28738
30135
  const cell = cellOf(point);
28739
- Loop9(27, ({ i: k }) => {
30136
+ Loop10(27, ({ i: k }) => {
28740
30137
  const dx = k.mod(3).sub(1);
28741
30138
  const dy = k.div(3).mod(3).sub(1);
28742
30139
  const dz = k.div(9).sub(1);
28743
30140
  const id = cellId(cell.add(ivec3(dx, dy, dz)));
28744
30141
  const inCell = min7(atomicLoad(cellCount.element(id)), uint2(CELL_CAPACITY)).toVar();
28745
- Loop9({ start: uint2(0), end: inCell, type: "uint" }, ({ i: slot }) => {
30142
+ Loop10({ start: uint2(0), end: inCell, type: "uint" }, ({ i: slot }) => {
28746
30143
  const other = cellItems.element(id.mul(CELL_CAPACITY).add(slot));
28747
- If10(other.notEqual(self), () => {
30144
+ If11(other.notEqual(self), () => {
28748
30145
  const offset = point.sub(positions.element(other).xyz);
28749
30146
  const r2 = dot8(offset, offset);
28750
- If10(r2.lessThan(h2), () => body(other, offset, r2));
30147
+ If11(r2.lessThan(h2), () => body(other, offset, r2));
28751
30148
  });
28752
30149
  });
28753
30150
  });
28754
30151
  };
28755
- const kernel = (r2) => float20(h2).sub(r2).pow(3).mul(poly6);
28756
- const gradientScale = (r) => float20(h).sub(r).pow(2).mul(volumeOfParticle * spiky).div(r);
30152
+ const kernel = (r2) => float23(h2).sub(r2).pow(3).mul(poly6);
30153
+ const gradientScale = (r) => float23(h).sub(r).pow(2).mul(volumeOfParticle * spiky).div(r);
28757
30154
  const project = (point) => {
28758
- point.assign(clamp8(point, vec316(...min32), vec316(...max32)));
28759
- Loop9({ start: uint2(0), end: this.#colliderCount, type: "uint" }, ({ i }) => {
30155
+ point.assign(clamp9(point, vec319(...min32), vec319(...max32)));
30156
+ Loop10({ start: uint2(0), end: this.#colliderCount, type: "uint" }, ({ i }) => {
28760
30157
  const a = this.#colliderA.element(i);
28761
30158
  const b = this.#colliderB.element(i);
28762
30159
  const offset = point.sub(a.xyz);
28763
- If10(dot8(offset, offset).lessThan(b.w.add(radius).pow(2)), () => {
28764
- If10(a.w.lessThan(0.5), () => {
30160
+ If11(dot8(offset, offset).lessThan(b.w.add(radius).pow(2)), () => {
30161
+ If11(a.w.lessThan(0.5), () => {
28765
30162
  const reach = b.x.add(radius);
28766
- const distance = length6(offset);
28767
- If10(distance.lessThan(reach), () => {
30163
+ const distance = length7(offset);
30164
+ If11(distance.lessThan(reach), () => {
28768
30165
  const direction2 = select4(
28769
30166
  distance.lessThan(1e-9),
28770
- vec316(0, 1, 0),
28771
- offset.div(max8(distance, 1e-9))
30167
+ vec319(0, 1, 0),
30168
+ offset.div(max10(distance, 1e-9))
28772
30169
  );
28773
30170
  point.assign(a.xyz.add(direction2.mul(reach)));
28774
30171
  });
28775
30172
  }).Else(() => {
28776
30173
  const rows = this.#colliderRows.map((row) => row.element(i).xyz);
28777
- const local2 = vec316(
30174
+ const local2 = vec319(
28778
30175
  dot8(rows[0], offset),
28779
30176
  dot8(rows[1], offset),
28780
30177
  dot8(rows[2], offset)
28781
30178
  );
28782
30179
  const half = b.xyz.add(radius);
28783
30180
  const absolute = abs7(local2);
28784
- If10(
30181
+ If11(
28785
30182
  absolute.x.lessThan(half.x).and(absolute.y.lessThan(half.y)).and(absolute.z.lessThan(half.z)),
28786
30183
  () => {
28787
30184
  const gap = half.sub(absolute);
28788
30185
  const out = nodeVar(local2);
28789
- If10(gap.x.lessThan(gap.y).and(gap.x.lessThan(gap.z)), () => {
30186
+ If11(gap.x.lessThan(gap.y).and(gap.x.lessThan(gap.z)), () => {
28790
30187
  out.assign(
28791
- vec316(select4(local2.x.lessThan(0), half.x.negate(), half.x), local2.y, local2.z)
30188
+ vec319(select4(local2.x.lessThan(0), half.x.negate(), half.x), local2.y, local2.z)
28792
30189
  );
28793
30190
  }).ElseIf(gap.y.lessThan(gap.z), () => {
28794
30191
  out.assign(
28795
- vec316(local2.x, select4(local2.y.lessThan(0), half.y.negate(), half.y), local2.z)
30192
+ vec319(local2.x, select4(local2.y.lessThan(0), half.y.negate(), half.y), local2.z)
28796
30193
  );
28797
30194
  }).Else(() => {
28798
30195
  out.assign(
28799
- vec316(local2.x, local2.y, select4(local2.z.lessThan(0), half.z.negate(), half.z))
30196
+ vec319(local2.x, local2.y, select4(local2.z.lessThan(0), half.z.negate(), half.z))
28800
30197
  );
28801
30198
  });
28802
30199
  const world = rows[0].mul(out.x).add(rows[1].mul(out.y)).add(rows[2].mul(out.z));
@@ -28806,33 +30203,33 @@ var FluidParticles3D = class extends Group {
28806
30203
  });
28807
30204
  });
28808
30205
  });
28809
- point.assign(clamp8(point, vec316(...min32), vec316(...max32)));
30206
+ point.assign(clamp9(point, vec319(...min32), vec319(...max32)));
28810
30207
  };
28811
30208
  this.#inject = computeKernel2("fluidParticles.inject", capacity, () => {
28812
30209
  const slot = instanceIndex6;
28813
- If10(slot.greaterThanEqual(uint2(capacity)), () => {
30210
+ If11(slot.greaterThanEqual(uint2(capacity)), () => {
28814
30211
  Return2();
28815
30212
  });
28816
30213
  const body = positions.element(slot);
28817
30214
  const motion = velocities.element(slot);
28818
- Loop9({ start: uint2(0), end: this.#drainCount, type: "uint" }, ({ i }) => {
30215
+ Loop10({ start: uint2(0), end: this.#drainCount, type: "uint" }, ({ i }) => {
28819
30216
  const low2 = this.#drainMin.element(i).xyz;
28820
30217
  const high2 = this.#drainMax.element(i).xyz;
28821
30218
  const p = body.xyz;
28822
- If10(
30219
+ If11(
28823
30220
  body.w.greaterThan(0.5).and(p.x.greaterThanEqual(low2.x)).and(p.x.lessThanEqual(high2.x)).and(p.y.greaterThanEqual(low2.y)).and(p.y.lessThanEqual(high2.y)).and(p.z.greaterThanEqual(low2.z)).and(p.z.lessThanEqual(high2.z)),
28824
30221
  () => {
28825
- body.assign(vec418(p, 0));
28826
- motion.assign(vec418(0));
30222
+ body.assign(vec419(p, 0));
30223
+ motion.assign(vec419(0));
28827
30224
  }
28828
30225
  );
28829
30226
  });
28830
- Loop9({ start: uint2(0), end: this.#spawnCount, type: "uint" }, ({ i }) => {
30227
+ Loop10({ start: uint2(0), end: this.#spawnCount, type: "uint" }, ({ i }) => {
28831
30228
  const a = this.#spawnA.element(i);
28832
30229
  const b = this.#spawnB.element(i);
28833
30230
  const c = this.#spawnC.element(i);
28834
30231
  const relative = slot.add(uint2(capacity)).sub(a.w.toUint()).mod(uint2(capacity));
28835
- If10(relative.lessThan(b.w.toUint()), () => {
30232
+ If11(relative.lessThan(b.w.toUint()), () => {
28836
30233
  const nx = b.x.toUint();
28837
30234
  const nz = b.z.toUint();
28838
30235
  const ix = relative.mod(nx);
@@ -28840,16 +30237,16 @@ var FluidParticles3D = class extends Group {
28840
30237
  const iy = relative.div(nx.mul(nz));
28841
30238
  const jitter = select4(
28842
30239
  b.w.greaterThan(1.5),
28843
- vec316(
30240
+ vec319(
28844
30241
  hash2(slot.add(relative)).sub(0.5),
28845
30242
  hash2(slot.add(relative).add(uint2(104729))).sub(0.5),
28846
30243
  hash2(slot.add(relative).add(uint2(7919))).sub(0.5)
28847
30244
  ).mul(c.w.mul(0.1)),
28848
- vec316(0)
30245
+ vec319(0)
28849
30246
  );
28850
- const placed = a.xyz.add(vec316(float20(ix), float20(iy), float20(iz)).mul(c.w)).add(jitter);
28851
- body.assign(vec418(placed, 1));
28852
- motion.assign(vec418(c.xyz, 0));
30247
+ const placed = a.xyz.add(vec319(float23(ix), float23(iy), float23(iz)).mul(c.w)).add(jitter);
30248
+ body.assign(vec419(placed, 1));
30249
+ motion.assign(vec419(c.xyz, 0));
28853
30250
  });
28854
30251
  });
28855
30252
  });
@@ -28858,15 +30255,15 @@ var FluidParticles3D = class extends Group {
28858
30255
  const i = instanceIndex6;
28859
30256
  const velocity = nodeVar(velocities.element(i).xyz);
28860
30257
  const position = nodeVar(positions.element(i).xyz);
28861
- Loop9({ start: uint2(0), end: this.#stirCount, type: "uint" }, ({ i: s }) => {
30258
+ Loop10({ start: uint2(0), end: this.#stirCount, type: "uint" }, ({ i: s }) => {
28862
30259
  const centre = this.#stirA.element(s);
28863
30260
  const offset = position.sub(centre.xyz);
28864
- const distance = length6(offset);
28865
- If10(distance.lessThan(centre.w), () => {
28866
- const t = float20(1).sub(distance.div(centre.w)).mul(this.#stirB.element(s).x);
30261
+ const distance = length7(offset);
30262
+ If11(distance.lessThan(centre.w), () => {
30263
+ const t = float23(1).sub(distance.div(centre.w)).mul(this.#stirB.element(s).x);
28867
30264
  velocity.assign(
28868
30265
  velocity.add(
28869
- vec316(
30266
+ vec319(
28870
30267
  offset.x.div(distance.add(0.15)).mul(t),
28871
30268
  t.mul(0.65),
28872
30269
  offset.z.div(distance.add(0.15)).mul(t)
@@ -28875,29 +30272,29 @@ var FluidParticles3D = class extends Group {
28875
30272
  );
28876
30273
  });
28877
30274
  });
28878
- velocity.assign(velocity.add(vec316(0, this.#gravity.negate().mul(dt), 0)));
30275
+ velocity.assign(velocity.add(vec319(0, this.#gravity.negate().mul(dt), 0)));
28879
30276
  if (options.force !== void 0)
28880
30277
  velocity.assign(
28881
30278
  velocity.add(
28882
30279
  options.force(position, velocity, this.#time).mul(dt)
28883
30280
  )
28884
30281
  );
28885
- velocity.assign(velocity.mul(float20(maxSpeed).div(max8(length6(velocity), maxSpeed))));
28886
- previous.element(i).assign(vec418(position, 1));
28887
- const substeps = clamp8(
28888
- ceil(length6(velocity).mul(dt).div(radius)),
30282
+ velocity.assign(velocity.mul(float23(maxSpeed).div(max10(length7(velocity), maxSpeed))));
30283
+ previous.element(i).assign(vec419(position, 1));
30284
+ const substeps = clamp9(
30285
+ ceil(length7(velocity).mul(dt).div(radius)),
28889
30286
  1,
28890
30287
  Math.max(1, Math.ceil(maxSpeed * timeStep / radius))
28891
30288
  ).toUint().toVar("fluidSubsteps");
28892
- Loop9({ start: uint2(0), end: substeps, type: "uint" }, () => {
28893
- position.assign(position.add(velocity.mul(dt).div(float20(substeps))));
30289
+ Loop10({ start: uint2(0), end: substeps, type: "uint" }, () => {
30290
+ position.assign(position.add(velocity.mul(dt).div(float23(substeps))));
28894
30291
  project(position);
28895
30292
  });
28896
- positions.element(i).assign(vec418(position, 1));
28897
- velocities.element(i).assign(vec418(velocity, velocities.element(i).w));
30293
+ positions.element(i).assign(vec419(position, 1));
30294
+ velocities.element(i).assign(vec419(velocity, velocities.element(i).w));
28898
30295
  });
28899
30296
  this.#gridClear = computeKernel2("fluidParticles.grid.clear", cells, () => {
28900
- If10(instanceIndex6.greaterThanEqual(uint2(cells)), () => {
30297
+ If11(instanceIndex6.greaterThanEqual(uint2(cells)), () => {
28901
30298
  Return2();
28902
30299
  });
28903
30300
  atomicStore(cellCount.element(instanceIndex6), uint2(0));
@@ -28906,7 +30303,7 @@ var FluidParticles3D = class extends Group {
28906
30303
  guard();
28907
30304
  const id = cellId(cellOf(positions.element(instanceIndex6).xyz));
28908
30305
  const slot = atomicAdd(cellCount.element(id), uint2(1)).toVar();
28909
- If10(slot.lessThan(uint2(CELL_CAPACITY)), () => {
30306
+ If11(slot.lessThan(uint2(CELL_CAPACITY)), () => {
28910
30307
  cellItems.element(id.mul(CELL_CAPACITY).add(slot)).assign(instanceIndex6);
28911
30308
  });
28912
30309
  });
@@ -28914,20 +30311,20 @@ var FluidParticles3D = class extends Group {
28914
30311
  guard();
28915
30312
  const i = instanceIndex6;
28916
30313
  const p = positions.element(i).xyz;
28917
- const rho = nodeVar(float20(volumeOfParticle * wSelf));
28918
- const gradient = nodeVar(vec316(0));
28919
- const sum = nodeVar(float20(0));
30314
+ const rho = nodeVar(float23(volumeOfParticle * wSelf));
30315
+ const gradient = nodeVar(vec319(0));
30316
+ const sum = nodeVar(float23(0));
28920
30317
  forNeighbours(p, i, (_other, offset, r2) => {
28921
30318
  rho.addAssign(kernel(r2).mul(volumeOfParticle));
28922
30319
  const r = r2.sqrt();
28923
- If10(r.greaterThan(1e-6), () => {
30320
+ If11(r.greaterThan(1e-6), () => {
28924
30321
  const a = offset.mul(gradientScale(r));
28925
30322
  gradient.addAssign(a);
28926
30323
  sum.addAssign(dot8(a, a));
28927
30324
  });
28928
30325
  });
28929
30326
  densities.element(i).assign(rho);
28930
- const constraint = max8(rho.sub(1), 0);
30327
+ const constraint = max10(rho.sub(1), 0);
28931
30328
  lambdas.element(i).assign(constraint.negate().div(sum.add(dot8(gradient, gradient)).add(relaxation)));
28932
30329
  });
28933
30330
  this.#delta = computeKernel2("fluidParticles.delta", capacity, () => {
@@ -28935,10 +30332,10 @@ var FluidParticles3D = class extends Group {
28935
30332
  const i = instanceIndex6;
28936
30333
  const p = positions.element(i).xyz;
28937
30334
  const own = lambdas.element(i);
28938
- const total = nodeVar(vec316(0));
30335
+ const total = nodeVar(vec319(0));
28939
30336
  forNeighbours(p, i, (other, offset, r2) => {
28940
30337
  const r = r2.sqrt();
28941
- If10(r.greaterThan(1e-6), () => {
30338
+ If11(r.greaterThan(1e-6), () => {
28942
30339
  const ratio = kernel(r2).div(wReference);
28943
30340
  const tensile = ratio.pow(4).mul(-1e-3);
28944
30341
  const strength = own.add(lambdas.element(other)).add(tensile);
@@ -28946,31 +30343,31 @@ var FluidParticles3D = class extends Group {
28946
30343
  });
28947
30344
  });
28948
30345
  const limit = spacing * 0.24;
28949
- const magnitude = length6(total);
28950
- const scale = select4(magnitude.greaterThan(limit), float20(limit).div(magnitude), float20(1));
28951
- deltas.element(i).assign(vec418(total.mul(scale), 0));
30346
+ const magnitude = length7(total);
30347
+ const scale = select4(magnitude.greaterThan(limit), float23(limit).div(magnitude), float23(1));
30348
+ deltas.element(i).assign(vec419(total.mul(scale), 0));
28952
30349
  });
28953
30350
  this.#apply = computeKernel2("fluidParticles.apply", capacity, () => {
28954
30351
  guard();
28955
30352
  const i = instanceIndex6;
28956
30353
  const p = nodeVar(positions.element(i).xyz.add(deltas.element(i).xyz));
28957
30354
  project(p);
28958
- positions.element(i).assign(vec418(p, 1));
30355
+ positions.element(i).assign(vec419(p, 1));
28959
30356
  });
28960
30357
  this.#velocity = computeKernel2("fluidParticles.velocity", capacity, () => {
28961
30358
  guard();
28962
30359
  const i = instanceIndex6;
28963
30360
  const v = positions.element(i).xyz.sub(previous.element(i).xyz).div(dt);
28964
- velocities.element(i).assign(vec418(v, velocities.element(i).w));
30361
+ velocities.element(i).assign(vec419(v, velocities.element(i).w));
28965
30362
  });
28966
30363
  this.#smooth = computeKernel2("fluidParticles.smooth", capacity, () => {
28967
30364
  guard();
28968
30365
  const i = instanceIndex6;
28969
30366
  const p = positions.element(i).xyz;
28970
30367
  const v = velocities.element(i).xyz;
28971
- const change = nodeVar(vec316(0));
28972
- const curl = nodeVar(vec316(0));
28973
- const neighbours = nodeVar(float20(0));
30368
+ const change = nodeVar(vec319(0));
30369
+ const curl = nodeVar(vec319(0));
30370
+ const neighbours = nodeVar(float23(0));
28974
30371
  forNeighbours(p, i, (other, offset, r2) => {
28975
30372
  const w = kernel(r2).mul(volumeOfParticle);
28976
30373
  const dv = velocities.element(other).xyz.sub(v);
@@ -28979,10 +30376,10 @@ var FluidParticles3D = class extends Group {
28979
30376
  );
28980
30377
  neighbours.addAssign(1);
28981
30378
  const r = r2.sqrt();
28982
- If10(r.greaterThan(1e-6), () => {
30379
+ If11(r.greaterThan(1e-6), () => {
28983
30380
  const s = gradientScale(r);
28984
30381
  curl.addAssign(
28985
- vec316(
30382
+ vec319(
28986
30383
  dv.y.mul(offset.z).sub(dv.z.mul(offset.y)),
28987
30384
  dv.z.mul(offset.x).sub(dv.x.mul(offset.z)),
28988
30385
  dv.x.mul(offset.y).sub(dv.y.mul(offset.x))
@@ -28990,50 +30387,50 @@ var FluidParticles3D = class extends Group {
28990
30387
  );
28991
30388
  });
28992
30389
  });
28993
- deltas.element(i).assign(vec418(change, 0));
28994
- omega.element(i).assign(vec418(curl, neighbours));
30390
+ deltas.element(i).assign(vec419(change, 0));
30391
+ omega.element(i).assign(vec419(curl, neighbours));
28995
30392
  });
28996
30393
  this.#confine = computeKernel2("fluidParticles.confine", capacity, () => {
28997
30394
  guard();
28998
30395
  const i = instanceIndex6;
28999
30396
  const p = positions.element(i).xyz;
29000
- const own = length6(omega.element(i).xyz);
29001
- const eta = nodeVar(vec316(0));
30397
+ const own = length7(omega.element(i).xyz);
30398
+ const eta = nodeVar(vec319(0));
29002
30399
  forNeighbours(p, i, (other, offset, r2) => {
29003
30400
  const r = r2.sqrt();
29004
- If10(r.greaterThan(1e-6), () => {
29005
- const diff = length6(omega.element(other).xyz).sub(own);
30401
+ If11(r.greaterThan(1e-6), () => {
30402
+ const diff = length7(omega.element(other).xyz).sub(own);
29006
30403
  eta.addAssign(offset.mul(gradientScale(r).mul(diff)));
29007
30404
  });
29008
30405
  });
29009
30406
  const w = omega.element(i).xyz;
29010
- const scale = this.#vorticity.mul(dt).div(length6(eta).add(1e-5));
29011
- const force = vec316(
30407
+ const scale = this.#vorticity.mul(dt).div(length7(eta).add(1e-5));
30408
+ const force = vec319(
29012
30409
  eta.y.mul(w.z).sub(eta.z.mul(w.y)),
29013
30410
  eta.z.mul(w.x).sub(eta.x.mul(w.z)),
29014
30411
  eta.x.mul(w.y).sub(eta.y.mul(w.x))
29015
30412
  ).mul(scale);
29016
- const limited = clamp8(force, vec316(-0.15), vec316(0.15));
30413
+ const limited = clamp9(force, vec319(-0.15), vec319(0.15));
29017
30414
  const v = nodeVar(
29018
- velocities.element(i).xyz.add(deltas.element(i).xyz).add(select4(this.#vorticity.greaterThan(0), limited, vec316(0)))
30415
+ velocities.element(i).xyz.add(deltas.element(i).xyz).add(select4(this.#vorticity.greaterThan(0), limited, vec319(0)))
29019
30416
  );
29020
30417
  const position = positions.element(i).xyz;
29021
- If10(position.y.lessThanEqual(min32[1] + 2e-3), () => {
29022
- v.assign(vec316(v.x.mul(1 - wallFriction), v.y, v.z.mul(1 - wallFriction)));
30418
+ If11(position.y.lessThanEqual(min32[1] + 2e-3), () => {
30419
+ v.assign(vec319(v.x.mul(1 - wallFriction), v.y, v.z.mul(1 - wallFriction)));
29023
30420
  });
29024
- v.assign(v.mul(float20(maxSpeed).div(max8(length6(v), maxSpeed))));
29025
- const speed = length6(v);
29026
- const source2 = clamp8(speed.sub(1.5).mul(0.14), 0, 1).mul(
29027
- select4(omega.element(i).w.lessThan(22), float20(1), float20(0.2))
30421
+ v.assign(v.mul(float23(maxSpeed).div(max10(length7(v), maxSpeed))));
30422
+ const speed = length7(v);
30423
+ const source2 = clamp9(speed.sub(1.5).mul(0.14), 0, 1).mul(
30424
+ select4(omega.element(i).w.lessThan(22), float23(1), float23(0.2))
29028
30425
  );
29029
- const foam = max8(velocities.element(i).w.mul(exp6(dt.mul(-1.3))), source2);
29030
- velocities.element(i).assign(vec418(v, foam));
30426
+ const foam = max10(velocities.element(i).w.mul(exp6(dt.mul(-1.3))), source2);
30427
+ velocities.element(i).assign(vec419(v, foam));
29031
30428
  atomicAdd(stats.element(0), uint2(1));
29032
- atomicAdd(stats.element(1), uint2(max8(densities.element(i).sub(1), 0).mul(COMPRESSION_SCALE)));
30429
+ atomicAdd(stats.element(1), uint2(max10(densities.element(i).sub(1), 0).mul(COMPRESSION_SCALE)));
29033
30430
  atomicMax(stats.element(2), uint2(speed.mul(FIXED_POINT)));
29034
30431
  for (let axis = 0; axis < 3; axis += 1) {
29035
30432
  const offset = uint2(
29036
- max8(
30433
+ max10(
29037
30434
  [position.x, position.y, position.z][axis]?.sub(min32[axis]).add(1),
29038
30435
  0
29039
30436
  ).mul(FIXED_POINT)
@@ -29043,7 +30440,7 @@ var FluidParticles3D = class extends Group {
29043
30440
  }
29044
30441
  });
29045
30442
  this.#statsClear = computeKernel2("fluidParticles.stats.clear", STAT_WORDS, () => {
29046
- If10(instanceIndex6.greaterThanEqual(uint2(STAT_WORDS)), () => {
30443
+ If11(instanceIndex6.greaterThanEqual(uint2(STAT_WORDS)), () => {
29047
30444
  Return2();
29048
30445
  });
29049
30446
  const word = instanceIndex6;
@@ -29053,39 +30450,39 @@ var FluidParticles3D = class extends Group {
29053
30450
  );
29054
30451
  });
29055
30452
  this.#statsFinalize = computeKernel2("fluidParticles.stats.finalize", STAT_WORDS, () => {
29056
- If10(instanceIndex6.greaterThanEqual(uint2(STAT_WORDS)), () => {
30453
+ If11(instanceIndex6.greaterThanEqual(uint2(STAT_WORDS)), () => {
29057
30454
  Return2();
29058
30455
  });
29059
30456
  const word = instanceIndex6;
29060
- const count = float20(atomicLoad(stats.element(0)));
29061
- const raw = float20(atomicLoad(stats.element(word)));
30457
+ const count = float23(atomicLoad(stats.element(0)));
30458
+ const raw = float23(atomicLoad(stats.element(word)));
29062
30459
  const axis = word.sub(3).mod(3);
29063
30460
  const base = select4(
29064
30461
  axis.equal(0),
29065
- float20(min32[0]),
29066
- select4(axis.equal(1), float20(min32[1]), float20(min32[2]))
30462
+ float23(min32[0]),
30463
+ select4(axis.equal(1), float23(min32[1]), float23(min32[2]))
29067
30464
  );
29068
- const spatial = select4(count.lessThan(0.5), float20(0), raw.div(FIXED_POINT).sub(1).add(base));
30465
+ const spatial = select4(count.lessThan(0.5), float23(0), raw.div(FIXED_POINT).sub(1).add(base));
29069
30466
  const value = select4(
29070
30467
  word.equal(0),
29071
30468
  raw,
29072
30469
  select4(
29073
30470
  word.equal(1),
29074
- raw.div(COMPRESSION_SCALE).div(max8(count, 1)),
30471
+ raw.div(COMPRESSION_SCALE).div(max10(count, 1)),
29075
30472
  select4(word.equal(2), raw.div(FIXED_POINT), spatial)
29076
30473
  )
29077
30474
  );
29078
30475
  readout.element(word).assign(value);
29079
30476
  });
29080
30477
  this.#volume = computeKernel2("fluidParticles.volume", voxels, () => {
29081
- If10(instanceIndex6.greaterThanEqual(uint2(voxels)), () => {
30478
+ If11(instanceIndex6.greaterThanEqual(uint2(voxels)), () => {
29082
30479
  Return2();
29083
30480
  });
29084
30481
  const ix = instanceIndex6.mod(uint2(vx));
29085
30482
  const iy = instanceIndex6.div(uint2(vx)).mod(uint2(vy));
29086
30483
  const iz = instanceIndex6.div(uint2(vx * vy));
29087
- const centre = vec316(float20(ix), float20(iy), float20(iz)).add(0.5).mul(voxelSize).add(vec316(...min32));
29088
- const total = nodeVar(float20(0));
30484
+ const centre = vec319(float23(ix), float23(iy), float23(iz)).add(0.5).mul(voxelSize).add(vec319(...min32));
30485
+ const total = nodeVar(float23(0));
29089
30486
  forNeighbours(centre, uint2(4294967295), (_other, _offset, r2) => {
29090
30487
  total.addAssign(kernel(r2).mul(volumeOfParticle));
29091
30488
  });
@@ -29093,62 +30490,62 @@ var FluidParticles3D = class extends Group {
29093
30490
  textureStore3(
29094
30491
  storageTexture3(this.density).toWriteOnly(),
29095
30492
  uvec3(ix, iy, iz),
29096
- vec418(total, 0, 0, 1)
30493
+ vec419(total, 0, 0, 1)
29097
30494
  ).toWriteOnly();
29098
30495
  });
29099
30496
  const insideCollider = (point) => {
29100
- const inside = nodeVar(float20(0));
29101
- Loop9({ start: uint2(0), end: this.#colliderCount, type: "uint" }, ({ i }) => {
30497
+ const inside = nodeVar(float23(0));
30498
+ Loop10({ start: uint2(0), end: this.#colliderCount, type: "uint" }, ({ i }) => {
29102
30499
  const a = this.#colliderA.element(i);
29103
30500
  const b = this.#colliderB.element(i);
29104
30501
  const offset = point.sub(a.xyz);
29105
- If10(a.w.lessThan(0.5), () => {
29106
- If10(length6(offset).lessThan(b.x), () => {
29107
- inside.assign(float20(1));
30502
+ If11(a.w.lessThan(0.5), () => {
30503
+ If11(length7(offset).lessThan(b.x), () => {
30504
+ inside.assign(float23(1));
29108
30505
  });
29109
30506
  }).Else(() => {
29110
30507
  const rows = this.#colliderRows.map((row) => row.element(i).xyz);
29111
30508
  const local2 = abs7(
29112
- vec316(
30509
+ vec319(
29113
30510
  dot8(rows[0], offset),
29114
30511
  dot8(rows[1], offset),
29115
30512
  dot8(rows[2], offset)
29116
30513
  )
29117
30514
  );
29118
- If10(local2.x.lessThan(b.x).and(local2.y.lessThan(b.y)).and(local2.z.lessThan(b.z)), () => {
29119
- inside.assign(float20(1));
30515
+ If11(local2.x.lessThan(b.x).and(local2.y.lessThan(b.y)).and(local2.z.lessThan(b.z)), () => {
30516
+ inside.assign(float23(1));
29120
30517
  });
29121
30518
  });
29122
30519
  });
29123
30520
  return inside;
29124
30521
  };
29125
30522
  this.#columnHeights = computeKernel2("fluidParticles.columns", vx * vz, () => {
29126
- If10(instanceIndex6.greaterThanEqual(uint2(vx * vz)), () => {
30523
+ If11(instanceIndex6.greaterThanEqual(uint2(vx * vz)), () => {
29127
30524
  Return2();
29128
30525
  });
29129
30526
  const ix = instanceIndex6.mod(uint2(vx));
29130
30527
  const iz = instanceIndex6.div(uint2(vx));
29131
- const top = nodeVar(float20(min32[1]));
29132
- const topLayer = nodeVar(int7(-1));
29133
- Loop9({ start: int7(0), end: int7(vy), type: "int" }, ({ i: layer }) => {
30528
+ const top = nodeVar(float23(min32[1]));
30529
+ const topLayer = nodeVar(int8(-1));
30530
+ Loop10({ start: int8(0), end: int8(vy), type: "int" }, ({ i: layer }) => {
29134
30531
  const voxel = ix.add(uint2(layer).mul(uint2(vx))).add(iz.mul(uint2(vx * vy)));
29135
- If10(volumeBuffer.element(voxel).greaterThan(0.5), () => {
29136
- top.assign(float20(layer).add(1).mul(voxelSize).add(min32[1]));
30532
+ If11(volumeBuffer.element(voxel).greaterThan(0.5), () => {
30533
+ top.assign(float23(layer).add(1).mul(voxelSize).add(min32[1]));
29137
30534
  topLayer.assign(layer);
29138
30535
  });
29139
30536
  });
29140
- const covered = nodeVar(float20(0));
30537
+ const covered = nodeVar(float23(0));
29141
30538
  for (const above of [0, 1, 2]) {
29142
- const centre = vec316(
29143
- float20(ix).add(0.5).mul(voxelSize).add(min32[0]),
29144
- float20(topLayer.add(1 + above)).add(0.5).mul(voxelSize).add(min32[1]),
29145
- float20(iz).add(0.5).mul(voxelSize).add(min32[2])
30539
+ const centre = vec319(
30540
+ float23(ix).add(0.5).mul(voxelSize).add(min32[0]),
30541
+ float23(topLayer.add(1 + above)).add(0.5).mul(voxelSize).add(min32[1]),
30542
+ float23(iz).add(0.5).mul(voxelSize).add(min32[2])
29146
30543
  );
29147
- If10(insideCollider(centre).greaterThan(0.5), () => {
29148
- covered.assign(float20(1));
30544
+ If11(insideCollider(centre).greaterThan(0.5), () => {
30545
+ covered.assign(float23(1));
29149
30546
  });
29150
30547
  }
29151
- readout.element(uint2(READOUT_HEADER).add(instanceIndex6)).assign(select4(covered.greaterThan(0.5), float20(COVERED), top));
30548
+ readout.element(uint2(READOUT_HEADER).add(instanceIndex6)).assign(select4(covered.greaterThan(0.5), float23(COVERED), top));
29152
30549
  });
29153
30550
  this.#readback = new GPUReadback({ attribute: readout.value, everyFrames: readbackEvery });
29154
30551
  this.warmupNodes = [
@@ -29222,13 +30619,13 @@ var FluidParticles3D = class extends Group {
29222
30619
  * Place a lattice of particles in `[min, max]`, one per `spacing`, and return how many fit.
29223
30620
  * Particles never wrap: a full solver places none.
29224
30621
  */
29225
- fill(min8, max9, velocity = [0, 0, 0]) {
30622
+ fill(min8, max11, velocity = [0, 0, 0]) {
29226
30623
  this.#assertLive("fill");
29227
30624
  finiteVec("fill.min", min8, 3);
29228
- finiteVec("fill.max", max9, 3);
30625
+ finiteVec("fill.max", max11, 3);
29229
30626
  finiteVec("fill.velocity", velocity, 3);
29230
30627
  const dims = [0, 1, 2].map(
29231
- (axis) => Math.floor((max9[axis] - min8[axis]) / this.spacing + 1e-6) + 1
30628
+ (axis) => Math.floor((max11[axis] - min8[axis]) / this.spacing + 1e-6) + 1
29232
30629
  );
29233
30630
  if (dims.some((dim) => dim < 1)) throw new Error("FluidParticles3D.fill needs max >= min.");
29234
30631
  const wanted = dims[0] * dims[1] * dims[2];
@@ -29253,13 +30650,13 @@ var FluidParticles3D = class extends Group {
29253
30650
  return true;
29254
30651
  }
29255
30652
  /** Free every live particle inside the box on the next step. */
29256
- drain(min8, max9) {
30653
+ drain(min8, max11) {
29257
30654
  this.#assertLive("drain");
29258
30655
  finiteVec("drain.min", min8, 3);
29259
- finiteVec("drain.max", max9, 3);
30656
+ finiteVec("drain.max", max11, 3);
29260
30657
  if (this.#queuedDrains >= MAX_DRAINS) return false;
29261
30658
  this.#drainMin.array[this.#queuedDrains].set(min8[0], min8[1], min8[2], 0);
29262
- this.#drainMax.array[this.#queuedDrains].set(max9[0], max9[1], max9[2], 0);
30659
+ this.#drainMax.array[this.#queuedDrains].set(max11[0], max11[1], max11[2], 0);
29263
30660
  this.#queuedDrains += 1;
29264
30661
  return true;
29265
30662
  }
@@ -29314,9 +30711,9 @@ var FluidParticles3D = class extends Group {
29314
30711
  */
29315
30712
  sample(x, z, _time = 0) {
29316
30713
  const data = this.#readback.data;
29317
- const floor5 = this.bounds.min[1];
30714
+ const floor6 = this.bounds.min[1];
29318
30715
  if (data === void 0 || x < this.bounds.min[0] || x > this.bounds.max[0] || z < this.bounds.min[2] || z > this.bounds.max[2])
29319
- return { height: floor5 };
30716
+ return { height: floor6 };
29320
30717
  const [columns, rows] = this.#columns;
29321
30718
  const minimumOpen = Math.min(MIN_OPEN_COLUMNS, columns * rows);
29322
30719
  const cx = Math.round(
@@ -29338,7 +30735,7 @@ var FluidParticles3D = class extends Group {
29338
30735
  }
29339
30736
  if (found >= minimumOpen) return { height: sum / found };
29340
30737
  }
29341
- return { height: floor5 };
30738
+ return { height: floor6 };
29342
30739
  }
29343
30740
  /** Surface height at `(x, z)`; see {@link sample}. */
29344
30741
  heightAt(x, z) {
@@ -29353,16 +30750,16 @@ var FluidParticles3D = class extends Group {
29353
30750
  }
29354
30751
  /** Counts and extremes from the newest landed GPU copy, or `undefined` before one lands. */
29355
30752
  get stats() {
29356
- const sample = this.#readback.sample;
29357
- if (sample === void 0) return void 0;
29358
- const d = sample.data;
30753
+ const sample2 = this.#readback.sample;
30754
+ if (sample2 === void 0) return void 0;
30755
+ const d = sample2.data;
29359
30756
  return {
29360
30757
  count: d[0] ?? 0,
29361
30758
  meanCompression: d[1] ?? 0,
29362
30759
  maxSpeed: d[2] ?? 0,
29363
30760
  min: [d[3] ?? 0, d[4] ?? 0, d[5] ?? 0],
29364
30761
  max: [d[6] ?? 0, d[7] ?? 0, d[8] ?? 0],
29365
- staleFrames: sample.staleFrames
30762
+ staleFrames: sample2.staleFrames
29366
30763
  };
29367
30764
  }
29368
30765
  process(renderer = this.#renderer) {
@@ -29428,7 +30825,7 @@ function clampNumber2(value, low2, high2) {
29428
30825
  }
29429
30826
 
29430
30827
  // src/ripple-field.ts
29431
- var clamp9 = (x, lo, hi) => Math.max(lo, Math.min(hi, x));
30828
+ var clamp10 = (x, lo, hi) => Math.max(lo, Math.min(hi, x));
29432
30829
  var finite3 = (value, label2) => {
29433
30830
  if (!Number.isFinite(value)) throw new TypeError(`${label2} must be finite`);
29434
30831
  return value;
@@ -29504,7 +30901,7 @@ var RippleField = class {
29504
30901
  for (let j = 0; j < resolution; j++)
29505
30902
  for (let i = 0; i < resolution; i++) {
29506
30903
  const edge = Math.min(i, j, resolution - 1 - i, resolution - 1 - j);
29507
- const sponge = 1 - clamp9(edge / 12, 0, 1);
30904
+ const sponge = 1 - clamp10(edge / 12, 0, 1);
29508
30905
  this.#loss[j * resolution + i] = this.damping + 6 * sponge * sponge;
29509
30906
  }
29510
30907
  }
@@ -29541,17 +30938,17 @@ var RippleField = class {
29541
30938
  }
29542
30939
  #shift(data, di, dj) {
29543
30940
  const n = this.resolution;
29544
- const scratch3 = this.#scratch;
29545
- scratch3.fill(0);
30941
+ const scratch4 = this.#scratch;
30942
+ scratch4.fill(0);
29546
30943
  const i0 = Math.max(0, -di);
29547
30944
  const i1 = Math.min(n, n - di);
29548
30945
  const j0 = Math.max(0, -dj);
29549
30946
  const j1 = Math.min(n, n - dj);
29550
30947
  for (let j = j0; j < j1; j++) {
29551
30948
  const source2 = (j + dj) * n + i0 + di;
29552
- scratch3.set(data.subarray(source2, source2 + (i1 - i0)), j * n + i0);
30949
+ scratch4.set(data.subarray(source2, source2 + (i1 - i0)), j * n + i0);
29553
30950
  }
29554
- data.set(scratch3);
30951
+ data.set(scratch4);
29555
30952
  }
29556
30953
  /**
29557
30954
  * Push the surface at a point: a Gaussian of the given radius, with the kernel corrected so the
@@ -29590,7 +30987,7 @@ var RippleField = class {
29590
30987
  const q = ((i - ix) ** 2 + (j - iz) ** 2) / (r * r);
29591
30988
  const g = Math.exp(-q);
29592
30989
  this.#velocity[k] = this.#velocity[k] + amplitude * (1 - q - correction) * g;
29593
- if (foam !== 0) this.foam[k] = clamp9(this.foam[k] + g * foam, 0, 1);
30990
+ if (foam !== 0) this.foam[k] = clamp10(this.foam[k] + g * foam, 0, 1);
29594
30991
  }
29595
30992
  this.#empty = false;
29596
30993
  this.version++;
@@ -29612,7 +31009,7 @@ var RippleField = class {
29612
31009
  for (let i = Math.max(1, Math.floor(ix - 2 * r)); i <= Math.min(n - 2, Math.ceil(ix + 2 * r)); i++) {
29613
31010
  const k = j * n + i;
29614
31011
  const g = Math.exp(-(((i - ix) ** 2 + (j - iz) ** 2) / (r * r)));
29615
- this.foam[k] = clamp9(this.foam[k] + g * amount, 0, 1);
31012
+ this.foam[k] = clamp10(this.foam[k] + g * amount, 0, 1);
29616
31013
  }
29617
31014
  this.#empty = false;
29618
31015
  this.version++;
@@ -29658,10 +31055,10 @@ var RippleField = class {
29658
31055
  next[k] = h[k] + v[k] * dt;
29659
31056
  const gx = (b - a) / (2 * dx);
29660
31057
  const gz = (e - d) / (2 * dx);
29661
- flowX[k] = clamp9((flowX[k] - 9.81 * gx * dt) / (1 + 0.65 * dt), -9, 9);
29662
- flowZ[k] = clamp9((flowZ[k] - 9.81 * gz * dt) / (1 + 0.65 * dt), -9, 9);
31058
+ flowX[k] = clamp10((flowX[k] - 9.81 * gx * dt) / (1 + 0.65 * dt), -9, 9);
31059
+ flowZ[k] = clamp10((flowZ[k] - 9.81 * gz * dt) / (1 + 0.65 * dt), -9, 9);
29663
31060
  const breaking = lap < 0 ? Math.max(0, Math.sqrt(gx * gx + gz * gz) - 0.3) * Math.min(3, Math.abs(v[k])) : 0;
29664
- if (breaking > 0) foam[k] = clamp9(foam[k] + breaking * dt * 0.55, 0, 1);
31061
+ if (breaking > 0) foam[k] = clamp10(foam[k] + breaking * dt * 0.55, 0, 1);
29665
31062
  }
29666
31063
  this.height = next;
29667
31064
  this.#scratch = h;
@@ -29681,8 +31078,8 @@ var RippleField = class {
29681
31078
  for (let j = 1; j < n - 1; j++)
29682
31079
  for (let i = 1; i < n - 1; i++) {
29683
31080
  const k = j * n + i;
29684
- const x = clamp9(i - (current.x + flowX[k]) * dt / dx, 0, n - 1.001);
29685
- const z = clamp9(j - (current.z + flowZ[k]) * dt / dx, 0, n - 1.001);
31081
+ const x = clamp10(i - (current.x + flowX[k]) * dt / dx, 0, n - 1.001);
31082
+ const z = clamp10(j - (current.z + flowZ[k]) * dt / dx, 0, n - 1.001);
29686
31083
  const a = Math.floor(x);
29687
31084
  const b = Math.floor(z);
29688
31085
  const q = b * n + a;
@@ -29690,7 +31087,7 @@ var RippleField = class {
29690
31087
  const w = z - b;
29691
31088
  const back = (foam[q] * (1 - u) + foam[q + 1] * u) * (1 - w) + (foam[q + n] * (1 - u) + foam[q + n + 1] * u) * w;
29692
31089
  const lap = foam[k - 1] + foam[k + 1] + foam[k - n] + foam[k + n] - 4 * foam[k];
29693
- next[k] = clamp9((back + lap * 0.06 * dt) * decay, 0, 1);
31090
+ next[k] = clamp10((back + lap * 0.06 * dt) * decay, 0, 1);
29694
31091
  }
29695
31092
  this.foam = next;
29696
31093
  this.#foamScratch = foam;
@@ -29769,8 +31166,8 @@ function direction(value, name) {
29769
31166
  if (x === void 0 || z === void 0) throw new Error(`WaveField.${name} is incomplete.`);
29770
31167
  finite4(`${name}.x`, x);
29771
31168
  finite4(`${name}.z`, z);
29772
- const length7 = Math.hypot(x, z);
29773
- if (length7 <= Number.EPSILON) throw new Error(`WaveField.${name} must not be zero.`);
31169
+ const length8 = Math.hypot(x, z);
31170
+ if (length8 <= Number.EPSILON) throw new Error(`WaveField.${name} must not be zero.`);
29774
31171
  return [x, z];
29775
31172
  }
29776
31173
  function displacement(value, amplitude) {
@@ -29815,9 +31212,9 @@ var WaveField = class {
29815
31212
  if (wave === void 0 || typeof wave !== "object")
29816
31213
  throw new Error(`WaveField.waves[${index}] must be an object.`);
29817
31214
  const [rawX, rawZ] = direction(wave.direction, `waves[${index}].direction`);
29818
- const length7 = Math.hypot(rawX, rawZ);
29819
- const directionX = rawX / length7;
29820
- const directionZ = rawZ / length7;
31215
+ const length8 = Math.hypot(rawX, rawZ);
31216
+ const directionX = rawX / length8;
31217
+ const directionZ = rawZ / length8;
29821
31218
  const wavelength = positive5(`waves[${index}].wavelength`, wave.wavelength);
29822
31219
  const speed = finite4(`waves[${index}].speed`, wave.speed);
29823
31220
  const phase = wave.phase === void 0 ? 0 : finite4(`waves[${index}].phase`, wave.phase);
@@ -29849,8 +31246,8 @@ var WaveField = class {
29849
31246
  if (warp.direction === void 0)
29850
31247
  throw new Error(`WaveField.domainWarp[${index}] requires direction or waveVector.`);
29851
31248
  const [rawX, rawZ] = direction(warp.direction, `domainWarp[${index}].direction`);
29852
- const length7 = Math.hypot(rawX, rawZ);
29853
- waveVector = [rawX / length7, rawZ / length7];
31249
+ const length8 = Math.hypot(rawX, rawZ);
31250
+ waveVector = [rawX / length8, rawZ / length8];
29854
31251
  const rawWavelength = warp.wavelength;
29855
31252
  if (rawWavelength === void 0)
29856
31253
  throw new Error(`WaveField.domainWarp[${index}].wavelength is required.`);
@@ -29911,9 +31308,9 @@ var WaveField = class {
29911
31308
  * only the number should call `heightAt`, which is the same evaluation without either.
29912
31309
  */
29913
31310
  sample(x, z, time) {
29914
- const normal = new Vector3();
29915
- const height = this.#evaluateCpu(x, z, time, normal);
29916
- return { height, normal };
31311
+ const normal2 = new Vector3();
31312
+ const height = this.#evaluateCpu(x, z, time, normal2);
31313
+ return { height, normal: normal2 };
29917
31314
  }
29918
31315
  /**
29919
31316
  * Surface height at a point, as a number.
@@ -29932,7 +31329,7 @@ var WaveField = class {
29932
31329
  * it, nothing derivative is computed at all. The warp and wave loops run in the same order
29933
31330
  * either way, so the height a scalar caller gets is bit-identical to `sample`'s.
29934
31331
  */
29935
- #evaluateCpu(x, z, time, normal) {
31332
+ #evaluateCpu(x, z, time, normal2) {
29936
31333
  const sampleX = requireSampleValue("x", x);
29937
31334
  const sampleZ = requireSampleValue("z", z);
29938
31335
  const sampleTime = requireSampleValue("time", time);
@@ -29953,7 +31350,7 @@ var WaveField = class {
29953
31350
  const sine = Math.sin(phase);
29954
31351
  warpedX += displacementX * sine;
29955
31352
  warpedZ += displacementZ * sine;
29956
- if (normal === void 0) continue;
31353
+ if (normal2 === void 0) continue;
29957
31354
  const cosine = Math.cos(phase);
29958
31355
  const derivativeX = cosine * kx;
29959
31356
  const derivativeZ = cosine * kz;
@@ -29977,15 +31374,15 @@ var WaveField = class {
29977
31374
  const phase = waveNumber * (directionX * warpedX + directionZ * warpedZ) - sampleTime * this.parameters[offset + 4] + this.parameters[offset + 5];
29978
31375
  const amplitude = this.#amplitude[index];
29979
31376
  height += amplitude * Math.sin(phase);
29980
- if (normal === void 0) continue;
31377
+ if (normal2 === void 0) continue;
29981
31378
  const slope = amplitude * waveNumber * Math.cos(phase);
29982
31379
  gradientX += slope * directionX;
29983
31380
  gradientZ += slope * directionZ;
29984
31381
  }
29985
- if (normal === void 0) return height;
31382
+ if (normal2 === void 0) return height;
29986
31383
  const worldGradientX = gradientX * warpedXX + gradientZ * warpedZX;
29987
31384
  const worldGradientZ = gradientX * warpedXZ + gradientZ * warpedZZ;
29988
- normal.set(
31385
+ normal2.set(
29989
31386
  worldGradientX === 0 ? 0 : -worldGradientX,
29990
31387
  1,
29991
31388
  worldGradientZ === 0 ? 0 : -worldGradientZ
@@ -30356,7 +31753,7 @@ function softCircleDataTexture(size = 64, hardness = 0.25) {
30356
31753
  return texture7;
30357
31754
  }
30358
31755
  var UP2 = new Vector3(0, 1, 0);
30359
- var MIN_DISTANCE2 = 0.05;
31756
+ var MIN_DISTANCE3 = 0.05;
30360
31757
  var MAX_LEAD = 0.16;
30361
31758
  function validateSpawnOptions(options) {
30362
31759
  const { lifetime, segmentLength, widthScale } = options;
@@ -30456,7 +31853,7 @@ var TracerPool3D = class {
30456
31853
  const widthScale = options.widthScale ?? 1;
30457
31854
  const slot = this.#slots[this.#cursor % this.#slots.length];
30458
31855
  this.#cursor += 1;
30459
- if (slot === void 0 || distance < MIN_DISTANCE2) return;
31856
+ if (slot === void 0 || distance < MIN_DISTANCE3) return;
30460
31857
  this.#direction.copy(direction2).normalize();
30461
31858
  this.#quaternion.setFromUnitVectors(UP2, this.#direction);
30462
31859
  const segmentLength = Math.min(shotSegmentLength, distance);
@@ -30585,9 +31982,9 @@ var PathFollow3D = class {
30585
31982
  let nearest = Number.POSITIVE_INFINITY;
30586
31983
  let nearestIndex = 0;
30587
31984
  for (let index = 0; index < this.#samples.length; index += 1) {
30588
- const sample = this.#samples[index];
30589
- if (sample === void 0) throw new Error("PathFollow3D projection sample is missing.");
30590
- const distance = sample.distanceToSquared(position);
31985
+ const sample2 = this.#samples[index];
31986
+ if (sample2 === void 0) throw new Error("PathFollow3D projection sample is missing.");
31987
+ const distance = sample2.distanceToSquared(position);
30591
31988
  if (distance < nearest) {
30592
31989
  nearest = distance;
30593
31990
  nearestIndex = index;
@@ -30656,16 +32053,18 @@ var GroundSnap = class {
30656
32053
  if (!Number.isFinite(dt) || dt < 0)
30657
32054
  throw new Error("GroundSnap dt must be finite and non-negative.");
30658
32055
  validateMaxRate(this.maxRate);
30659
- const before = posedBounds(this.model, this.meshes);
30660
- if (!Number.isFinite(before.min[1])) {
32056
+ const lowest = posedBounds(this.model, this.meshes).min[1];
32057
+ if (!Number.isFinite(lowest)) {
30661
32058
  this.clearance = null;
30662
32059
  return;
30663
32060
  }
30664
- const desired = surfaceY - before.min[1];
32061
+ const desired = surfaceY - lowest;
30665
32062
  const correction = this.maxRate === void 0 || desired > 0 ? desired : Math.max(desired, -this.maxRate * dt);
30666
- if (this.enabled) this.applyWorldCorrection(group, correction);
30667
- const after = posedBounds(this.model, this.meshes);
30668
- this.clearance = after.min[1] - surfaceY;
32063
+ const moved = this.enabled && correction !== 0;
32064
+ if (moved) this.applyWorldCorrection(group, correction);
32065
+ if (!moved) this.clearance = lowest - surfaceY;
32066
+ else if (carries(group, this.model)) this.clearance = lowest + correction - surfaceY;
32067
+ else this.clearance = posedBounds(this.model, this.meshes).min[1] - surfaceY;
30669
32068
  }
30670
32069
  applyWorldCorrection(group, correction) {
30671
32070
  const parent = group.parent;
@@ -30692,6 +32091,11 @@ var GroundSnap = class {
30692
32091
  return estimate.min[1] - precise.min[1];
30693
32092
  }
30694
32093
  };
32094
+ function carries(group, model) {
32095
+ for (let node = model; node !== null; node = node.parent)
32096
+ if (node === group) return true;
32097
+ return false;
32098
+ }
30695
32099
  function validateMaxRate(maxRate) {
30696
32100
  if (maxRate !== void 0 && (!Number.isFinite(maxRate) || maxRate < 0)) {
30697
32101
  throw new Error("GroundSnap maxRate must be finite and non-negative.");
@@ -30708,29 +32112,29 @@ var NEUTRAL_FLIGHT_MODIFIERS = Object.freeze({
30708
32112
  });
30709
32113
  var TAU2 = Math.PI * 2;
30710
32114
  var SEA_WIND = Object.freeze({ x: 0, y: 0, z: 0 });
30711
- var clamp11 = (value, low2, high2) => Math.max(low2, Math.min(high2, value));
32115
+ var clamp12 = (value, low2, high2) => Math.max(low2, Math.min(high2, value));
30712
32116
  var lerp = (a, b, t) => a + (b - a) * t;
30713
32117
  var wrap2 = (angle) => (angle % TAU2 + TAU2) % TAU2;
30714
32118
  var dot9 = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;
30715
32119
  var unit = (a) => {
30716
- const length7 = Math.hypot(a.x, a.y, a.z) || 1;
30717
- return { x: a.x / length7, y: a.y / length7, z: a.z / length7 };
32120
+ const length8 = Math.hypot(a.x, a.y, a.z) || 1;
32121
+ return { x: a.x / length8, y: a.y / length8, z: a.z / length8 };
30718
32122
  };
30719
32123
  var smooth = (a, b, x) => {
30720
- const t = clamp11((x - a) / (b - a), 0, 1);
32124
+ const t = clamp12((x - a) / (b - a), 0, 1);
30721
32125
  return t * t * (3 - 2 * t);
30722
32126
  };
30723
- var move = (a, b, maxStep) => a + clamp11(b - a, -maxStep, maxStep);
32127
+ var move = (a, b, maxStep) => a + clamp12(b - a, -maxStep, maxStep);
30724
32128
  function airDensity(y) {
30725
32129
  return 1.225 * Math.max(0.19, 1 - 225577e-10 * Math.max(0, y)) ** 4.25588;
30726
32130
  }
30727
32131
  function aircraftMass(state, airframe) {
30728
- return airframe.dryMass + airframe.fuelMass * clamp11((state.fuel ?? 100) / 100, 0, 1) + (state.payloadMass ?? 0);
32132
+ return airframe.dryMass + airframe.fuelMass * clamp12((state.fuel ?? 100) / 100, 0, 1) + (state.payloadMass ?? 0);
30729
32133
  }
30730
32134
  function aerodynamicCoefficients(alpha, flaps = 0, gear = 0, brakes = 0) {
30731
32135
  const critical = 0.265 + flaps * 0.035;
30732
32136
  const stall = smooth(critical - 0.015, critical + 0.15, Math.abs(alpha));
30733
- const attached = clamp11(0.22 + flaps * 0.48 + 4.8 * alpha, -1.48, 1.58 + flaps * 0.35);
32137
+ const attached = clamp12(0.22 + flaps * 0.48 + 4.8 * alpha, -1.48, 1.58 + flaps * 0.35);
30734
32138
  const separated = 1.1 * Math.sin(2 * alpha);
30735
32139
  const cl = lerp(attached, separated, stall);
30736
32140
  const cd = 0.027 + 0.075 * cl * cl + 0.9 * Math.sin(alpha) ** 2 * stall + gear * 0.029 + brakes * 0.135 + flaps * flaps * 0.047;
@@ -30823,7 +32227,7 @@ function flightForces(state, environment) {
30823
32227
  state.gearPos || 0,
30824
32228
  state.brakePos || 0
30825
32229
  );
30826
- const health = 0.72 + 0.28 * clamp11((state.hp ?? 100) / 100, 0, 1);
32230
+ const health = 0.72 + 0.28 * clamp12((state.hp ?? 100) / 100, 0, 1);
30827
32231
  const mass = aircraftMass(state, airframe);
30828
32232
  const lift = qs * coeff.cl * health * modifiers.lift;
30829
32233
  const drag = qs * (coeff.cd + modifiers.drag + (state.payloadDrag ?? 0));
@@ -30877,13 +32281,13 @@ function updateActuators(state, dt, controls = {}) {
30877
32281
  state.gearPos = move(state.gearPos ?? (state.gear ? 1 : 0), state.gear ? 1 : 0, dt * 0.36);
30878
32282
  state.brakePos = move(state.brakePos ?? (state.brakes ? 1 : 0), state.brakes ? 1 : 0, dt * 0.85);
30879
32283
  state.flapPos = move(state.flapPos ?? 0, state.flaps ?? 0, dt * 0.23);
30880
- state.aileron = lerp(state.aileron || 0, clamp11(controls.turn || 0, -1, 1), 1 - Math.exp(-dt * 7));
32284
+ state.aileron = lerp(state.aileron || 0, clamp12(controls.turn || 0, -1, 1), 1 - Math.exp(-dt * 7));
30881
32285
  state.elevator = lerp(
30882
32286
  state.elevator || 0,
30883
- clamp11(controls.pitch || 0, -1, 1),
32287
+ clamp12(controls.pitch || 0, -1, 1),
30884
32288
  1 - Math.exp(-dt * 6)
30885
32289
  );
30886
- state.rudder = lerp(state.rudder || 0, clamp11(controls.rudder || 0, -1, 1), 1 - Math.exp(-dt * 7));
32290
+ state.rudder = lerp(state.rudder || 0, clamp12(controls.rudder || 0, -1, 1), 1 - Math.exp(-dt * 7));
30887
32291
  }
30888
32292
  function advanceQuaternion(state, dt) {
30889
32293
  const q = state.attitude;
@@ -30909,7 +32313,7 @@ function advanceQuaternion(state, dt) {
30909
32313
  q.w = w / n;
30910
32314
  const axes = attitudeAxes(state);
30911
32315
  state.heading = wrap2(Math.atan2(axes.f.x, -axes.f.z));
30912
- state.pitch = Math.asin(clamp11(axes.f.y, -1, 1));
32316
+ state.pitch = Math.asin(clamp12(axes.f.y, -1, 1));
30913
32317
  state.roll = Math.atan2(axes.r.y, axes.u.y);
30914
32318
  }
30915
32319
  function stepFlight(state, dt, controls, environment) {
@@ -30929,21 +32333,21 @@ function stepFlight(state, dt, controls, environment) {
30929
32333
  const speed = Math.max(12, f.airspeed);
30930
32334
  const neutralWeight = Math.exp(-Math.abs(state.elevator) * 12);
30931
32335
  const upright = f.axes.u.y > 0.35;
30932
- const assistLoad = state.assist && !controls.autopilot && upright ? neutralWeight * (clamp11(1 / Math.max(0.55, Math.cos(state.roll)), 1, 1.8) - 1 + clamp11(-state.vy * 0.05, -0.45, 0.45)) : 0;
32336
+ const assistLoad = state.assist && !controls.autopilot && upright ? neutralWeight * (clamp12(1 / Math.max(0.55, Math.cos(state.roll)), 1, 1.8) - 1 + clamp12(-state.vy * 0.05, -0.45, 0.45)) : 0;
30933
32337
  const desiredLoad = 1 + assistLoad + (state.elevator >= 0 ? 4.5 : 2.5) * state.elevator;
30934
- const trimAlpha = state.assist || controls.autopilot ? clamp11(
32338
+ const trimAlpha = state.assist || controls.autopilot ? clamp12(
30935
32339
  (desiredLoad * f.mass * gravity / Math.max(f.qs, 4e3) - 0.22 - state.flapPos * 0.48) / 4.8,
30936
32340
  -0.34,
30937
32341
  0.43
30938
32342
  ) : state.trim + state.elevator * 0.34;
30939
32343
  const dampingSpeed = Math.max(25, speed);
30940
- const controlPower = clamp11(f.qs, 0, 4e5);
32344
+ const controlPower = clamp12(f.qs, 0, 4e5);
30941
32345
  const pitchMoment = controlPower * airframe.chord * (0.64 * modifiers.controls * (trimAlpha - f.alpha) - 10 * state.pitchRate * airframe.chord / (2 * dampingSpeed) - 0.045 * f.stall);
30942
- const bankDemand = clamp11((state.roll + state.aileron * 1.1) * 1.7 - state.rollRate * 0.65, -1, 1);
32346
+ const bankDemand = clamp12((state.roll + state.aileron * 1.1) * 1.7 - state.rollRate * 0.65, -1, 1);
30943
32347
  const rollInput = state.assist && !controls.autopilot ? bankDemand : state.aileron;
30944
32348
  state.controlAileron = rollInput;
30945
32349
  const rollMoment = controlPower * airframe.span * (0.023 * rollInput * (0.35 + 0.65 * modifiers.lift) + modifiers.roll - 0.48 * state.rollRate * airframe.span / (2 * dampingSpeed) - 0.012 * f.beta);
30946
- const yawAssist = state.assist || controls.autopilot ? clamp11(f.beta * 1.3, -0.6, 0.6) : 0;
32350
+ const yawAssist = state.assist || controls.autopilot ? clamp12(f.beta * 1.3, -0.6, 0.6) : 0;
30947
32351
  const yawMoment = controlPower * airframe.span * (0.1 * f.beta + 0.024 * modifiers.controls * (state.rudder + yawAssist) - 0.29 * state.yawRate * airframe.span / (2 * dampingSpeed) - 17e-4 * state.aileron);
30948
32352
  state.pitchRate += pitchMoment / airframe.pitchInertia * dt;
30949
32353
  state.rollRate += rollMoment / airframe.rollInertia * dt;
@@ -30976,42 +32380,42 @@ function stepDeck(state, deck, dt, controls, environment) {
30976
32380
  state.deckSpeed = state.deckSpeed ?? 0;
30977
32381
  state.deckLateral = state.deckLateral ?? -2.5;
30978
32382
  state.deckOffset = state.deckOffset ?? -105;
30979
- const sin2 = Math.sin(deck.heading);
30980
- const cos2 = Math.cos(deck.heading);
30981
- const overDeck = deck.speed + wind.z * cos2 - wind.x * sin2;
32383
+ const sin3 = Math.sin(deck.heading);
32384
+ const cos3 = Math.cos(deck.heading);
32385
+ const overDeck = deck.speed + wind.z * cos3 - wind.x * sin3;
30982
32386
  const speed = state.deckSpeed + overDeck;
30983
32387
  const tailRise = smooth(22, 38, speed);
30984
32388
  const rotation = smooth(42, 51, speed);
30985
32389
  const neutralPitch = lerp(0.22, 0.025, tailRise) + (state.assist ? 0.145 * rotation : 0);
30986
- const desiredPitch = clamp11(neutralPitch + (controls.pitch || 0) * 0.13, -0.025, 0.26);
32390
+ const desiredPitch = clamp12(neutralPitch + (controls.pitch || 0) * 0.13, -0.025, 0.26);
30987
32391
  state.pitch = lerp(state.pitch, desiredPitch, 1 - Math.exp(-dt * 2.8));
30988
32392
  state.heading = wrap2(
30989
- state.heading + (controls.rudder || controls.turn || 0) * dt * 0.22 * clamp11(state.deckSpeed / 12, 0, 1)
32393
+ state.heading + (controls.rudder || controls.turn || 0) * dt * 0.22 * clamp12(state.deckSpeed / 12, 0, 1)
30990
32394
  );
30991
32395
  setAttitude(state, state.heading, state.pitch, 0);
30992
32396
  const yaw = Math.atan2(
30993
32397
  Math.sin(state.heading - deck.heading),
30994
32398
  Math.cos(state.heading - deck.heading)
30995
32399
  );
30996
- state.vx = Math.sin(state.heading) * state.deckSpeed + sin2 * deck.speed;
32400
+ state.vx = Math.sin(state.heading) * state.deckSpeed + sin3 * deck.speed;
30997
32401
  state.vy = 0;
30998
- state.vz = -Math.cos(state.heading) * state.deckSpeed - cos2 * deck.speed;
32402
+ state.vz = -Math.cos(state.heading) * state.deckSpeed - cos3 * deck.speed;
30999
32403
  const f = flightForces(state, environment);
31000
- const normal = Math.max(0, f.mass * gravity - f.lift * Math.cos(state.pitch));
32404
+ const normal2 = Math.max(0, f.mass * gravity - f.lift * Math.cos(state.pitch));
31001
32405
  if (state.chocks !== false && state.throttle < 0.55) {
31002
32406
  state.deckSpeed = 0;
31003
32407
  } else {
31004
32408
  state.chocks = false;
31005
- const acceleration = (f.thrust - f.drag - normal * (controls.wheelBrake ? 0.55 : 0.019)) / f.mass;
32409
+ const acceleration = (f.thrust - f.drag - normal2 * (controls.wheelBrake ? 0.55 : 0.019)) / f.mass;
31006
32410
  state.deckSpeed = Math.max(0, state.deckSpeed + acceleration * dt);
31007
32411
  }
31008
32412
  state.deckOffset += Math.cos(yaw) * state.deckSpeed * dt;
31009
32413
  state.deckLateral += Math.sin(yaw) * state.deckSpeed * dt;
31010
- state.x = deck.x + sin2 * state.deckOffset + cos2 * state.deckLateral;
31011
- state.z = deck.z - cos2 * state.deckOffset + sin2 * state.deckLateral;
32414
+ state.x = deck.x + sin3 * state.deckOffset + cos3 * state.deckLateral;
32415
+ state.z = deck.z - cos3 * state.deckOffset + sin3 * state.deckLateral;
31012
32416
  state.y = deckHeight + gearClearance(state);
31013
- state.vx = Math.sin(state.heading) * state.deckSpeed + sin2 * deck.speed;
31014
- state.vz = -Math.cos(state.heading) * state.deckSpeed - cos2 * deck.speed;
32417
+ state.vx = Math.sin(state.heading) * state.deckSpeed + sin3 * deck.speed;
32418
+ state.vz = -Math.cos(state.heading) * state.deckSpeed - cos3 * deck.speed;
31015
32419
  state.speed = Math.hypot(state.vx - wind.x, state.vz - wind.z);
31016
32420
  state.ias = state.speed * Math.sqrt(airDensity(state.y) / 1.225);
31017
32421
  state.groundSpeed = state.deckSpeed + deck.speed;
@@ -31103,13 +32507,13 @@ function parseReplayRecording(value) {
31103
32507
  fail("runtime fingerprint is invalid");
31104
32508
  let previousTick = -1;
31105
32509
  for (const rawSample of input) {
31106
- const sample = checked(rawSample, ["keys", "pointer", "tick"]);
31107
- const tick = sample.tick;
32510
+ const sample2 = checked(rawSample, ["keys", "pointer", "tick"]);
32511
+ const tick = sample2.tick;
31108
32512
  if (!Number.isInteger(tick) || tick <= previousTick || tick >= ticks) fail("bad tick");
31109
- const keys = sample.keys;
32513
+ const keys = sample2.keys;
31110
32514
  if (!Array.isArray(keys) || keys.some((key) => typeof key !== "string")) fail("bad keys");
31111
32515
  if (new Set(keys).size !== keys.length) fail("duplicate keys");
31112
- if (sample.pointer !== void 0) validatePointer(sample.pointer);
32516
+ if (sample2.pointer !== void 0) validatePointer(sample2.pointer);
31113
32517
  previousTick = tick;
31114
32518
  }
31115
32519
  return root;
@@ -31244,7 +32648,7 @@ function restoreRandomState(random, state) {
31244
32648
  }
31245
32649
  function createReplayDriver(recording, target, pointerTarget = target) {
31246
32650
  const value = parseReplayRecording(recording);
31247
- const samples = new Map(value.input.map((sample) => [sample.tick, sample]));
32651
+ const samples = new Map(value.input.map((sample2) => [sample2.tick, sample2]));
31248
32652
  let preparedRandom;
31249
32653
  const driver = Object.assign(
31250
32654
  (runtime) => {
@@ -31257,11 +32661,11 @@ function createReplayDriver(recording, target, pointerTarget = target) {
31257
32661
  replayDepth += 1;
31258
32662
  try {
31259
32663
  for (let tick = 0; tick < value.ticks; tick += 1) {
31260
- const sample = samples.get(tick);
31261
- if (sample !== void 0) {
31262
- dispatchKeys(target, keys, sample.keys);
31263
- if (sample.pointer !== void 0)
31264
- pointer = dispatchPointer(pointer, sample.pointer, pointerTarget);
32664
+ const sample2 = samples.get(tick);
32665
+ if (sample2 !== void 0) {
32666
+ dispatchKeys(target, keys, sample2.keys);
32667
+ if (sample2.pointer !== void 0)
32668
+ pointer = dispatchPointer(pointer, sample2.pointer, pointerTarget);
31265
32669
  }
31266
32670
  runtime.fixedStep(1);
31267
32671
  }
@@ -31582,4 +32986,4 @@ var version = CORE_VERSION;
31582
32986
  * SOFTWARE.
31583
32987
  */
31584
32988
 
31585
- export { ATLAS_PADDING, ATMOSPHERE_LUT_RESOLUTIONS, AnimationComposer, AnimationPlayer, Atmosphere, AtmosphereLuts, AutoExposureNode, Billboard3D, BlendSpace1D, BlendSpace2D, BudgetLadder, CanvasLayer, ClusteredBatch, ComputeDrivenRegistry, Daylight, ENVIRONMENT_TOO_SMALL_MARKER, EPIC_SSGI, FRAME_BUDGET_MARKER, FRAME_BUDGET_PHASES, FRAME_HITCH_MARKER, FlightModel, FluidField2D, FluidParticles3D, FrameBudget, GIBudget, GIVisualize, GI_METHODS, GI_VISUALIZE_MODES, GPUSceneBVH, GroundSnap, InputMap, LAMP_SHADOW_MARKER, LUT_RESOLUTIONS, MatrixWorldPass, NEUTRAL_FLIGHT_MODIFIERS, OPACITY_IGNORED_MARKER, PROBE_VOLUME_MARKER, PathFollow3D, PointerEvents3D, ProbeVolume, RENDERLIST_VALIDATE_FLAG, RENDERLIST_VALIDATE_MARKER, RadianceCache, RenderListValidator, RippleField, SCENE_WARNING_MARKER, SHADOW_FILTER_TIERS, SHADOW_STAGES, Scene6 as Scene, ScenePicker, Scheduler, ShadowFilterBudget, SkeletalMesh3D, SkyCapture, SkyCaptureSchedule, SoftBody3D, SpectralOcean, SpriteAnimator3D, SurfaceCache, SurfaceLights, TracedReflections, TracerPool3D, UNLIT_FOLIAGE_FIX, UNLIT_FOLIAGE_MARKER, VIRTUAL_SHADOW_MARKER, VirtualShadowNode, WaterSurface3D, WaveField, WorldEnvironment, aerodynamicCoefficients, afterPhysics, airDensity, aircraftMass, attachToBone, attitudeAxes, boneContact, boneLengthDeviations, boneLengths, bvhIntersectFirstHit, captureMouse, clipBoneCoverage, clipPoseError, clipTrackBindings, createRandom, createReplayDriver, defineGame, describeSceneShape, describeSceneWarning, directionFromSolarPosition, directionalTransmittance, displayPeriodMs, ev100FromCamera, ev100FromExposure, ev100FromLuminance, exposureFromEv100, exposureSettings, formatSceneWarning, formatUnlitFoliageWarning, formatValidationReport, gearClearance, installFilmicToneMapping, installSpanProbes, lampPenumbraTangent, lampShadowMarker, lookDiagnostics, measureThreePose, normaliseToMetres, onLaunchFailure, parseReplayRecording, penumbraUv, posedBounds, prewarm, qualityPreset, qualityTiers, rayStruct, readGIMarker, readLampShadowMarker, readProbeVolumeObservation, readShadowTierMarker, readVirtualShadowMarker, renderListValidationRequested, renderTrapAudit, replay, resolveAtmosphereLutResolutions, resolveAtmosphereParameters, sceneWarning, setAttitude, skeletonBones, softCircleDataTexture, solarPosition, solarPositionAt, sourceAngleShadowFilter, sourceRadiusShadowFilter, stageGpuReading, thinCards, unlitFoliageWarning, updateAtmosphereParameters, useRoughDiffuse, validateWorldMatrices, version, zenithTransmittance };
32989
+ export { ATLAS_PADDING, ATMOSPHERE_LUT_RESOLUTIONS, AnimationComposer, AnimationPlayer, Atmosphere, AtmosphereLuts, AutoExposureNode, Billboard3D, BlendSpace1D, BlendSpace2D, BudgetLadder, CanvasLayer, ClusteredBatch, ComputeDrivenRegistry, Daylight, ENVIRONMENT_TOO_SMALL_MARKER, EPIC_SSGI, FRAME_BUDGET_MARKER, FRAME_BUDGET_PHASES, FRAME_HITCH_MARKER, FlightModel, FluidField2D, FluidParticles3D, FrameBudget, GIBudget, GIVisualize, GI_METHODS, GI_VISUALIZE_MODES, GPUSceneBVH, GRASS_FIELD_ATTRIBUTES, GrassField3D, GroundSnap, InputMap, LAMP_SHADOW_MARKER, LUT_RESOLUTIONS, MatrixWorldPass, NEUTRAL_FLIGHT_MODIFIERS, OPACITY_IGNORED_MARKER, PROBE_VOLUME_MARKER, PathFollow3D, PointerEvents3D, ProbeVolume, RENDERLIST_VALIDATE_FLAG, RENDERLIST_VALIDATE_MARKER, RadianceCache, RenderListValidator, RippleField, SCENE_WARNING_MARKER, SHADOW_FILTER_TIERS, SHADOW_STAGES, ScatterField3D, Scene6 as Scene, ScenePicker, Scheduler, ScreenProbeGather, ShadowFilterBudget, ShortRangeAO, SkeletalMesh3D, SkyCapture, SkyCaptureSchedule, SoftBody3D, SpectralOcean, SpriteAnimator3D, SurfaceCache, SurfaceLights, TracedReflections, TracerPool3D, UNLIT_FOLIAGE_FIX, UNLIT_FOLIAGE_MARKER, VIRTUAL_SHADOW_MARKER, VirtualShadowNode, WaterSurface3D, WaveField, WorldEnvironment, aerodynamicCoefficients, afterPhysics, airDensity, aircraftMass, attachToBone, attitudeAxes, boneContact, boneLengthDeviations, boneLengths, bvhIntersectFirstHit, captureMouse, clipBoneCoverage, clipPoseError, clipTrackBindings, createRandom, createReplayDriver, defineGame, describeSceneShape, describeSceneWarning, directionFromSolarPosition, directionalTransmittance, displayPeriodMs, ev100FromCamera, ev100FromExposure, ev100FromLuminance, exposureFromEv100, exposureSettings, formatSceneWarning, formatUnlitFoliageWarning, formatValidationReport, gearClearance, installFilmicToneMapping, installSpanProbes, lampPenumbraTangent, lampShadowMarker, lookDiagnostics, measureThreePose, normaliseToMetres, onLaunchFailure, parseReplayRecording, penumbraUv, posedBounds, prewarm, qualityPreset, qualityTiers, rayStruct, readGIMarker, readLampShadowMarker, readProbeVolumeObservation, readShadowTierMarker, readVirtualShadowMarker, renderListValidationRequested, renderTrapAudit, replay, resolveAtmosphereLutResolutions, resolveAtmosphereParameters, sceneWarning, setAttitude, skeletonBones, softCircleDataTexture, solarPosition, solarPositionAt, sourceAngleShadowFilter, sourceRadiusShadowFilter, stageGpuReading, thinCards, unlitFoliageWarning, updateAtmosphereParameters, useRoughDiffuse, validateWorldMatrices, version, zenithTransmittance };