@navaramap/three 0.0.1 → 0.0.3

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 (72) hide show
  1. package/README.md +70 -0
  2. package/dist/assets/fontWorker-wz61edjR.js +2 -0
  3. package/dist/assets/fontWorker-wz61edjR.js.map +1 -0
  4. package/dist/assets/index-ywHSGImj.js +25 -0
  5. package/dist/assets/index-ywHSGImj.js.map +1 -0
  6. package/dist/assets/{navara_wasm_font_worker_bg-Bnck8OGf.wasm → navara_wasm_font_worker_bg-Du9nb2Pn.wasm} +0 -0
  7. package/dist/assets/{navara_wasm_worker_bg-DG9ORAmj.wasm → navara_wasm_worker_bg-Xadu67fw.wasm} +0 -0
  8. package/dist/draco_decoder.wasm +0 -0
  9. package/dist/draco_decoder2.wasm +0 -0
  10. package/dist/index.d.ts +578 -18
  11. package/dist/index.js +5298 -4843
  12. package/dist/index.js.map +1 -1
  13. package/dist/index.umd.cjs +266 -234
  14. package/dist/index.umd.cjs.map +1 -1
  15. package/package.json +34 -33
  16. package/src/atmosphere.ts +43 -1
  17. package/src/core/EffectDesc.ts +2 -4
  18. package/src/core/MeshDesc.ts +1 -2
  19. package/src/core/MeshDescWithSelectiveEffect.ts +1 -2
  20. package/src/declutter/DeclutterManager.test.ts +235 -0
  21. package/src/declutter/DeclutterManager.ts +256 -0
  22. package/src/declutter/index.ts +7 -0
  23. package/src/declutter/kernel.ts +46 -0
  24. package/src/declutter/types.ts +61 -0
  25. package/src/declutter/wasmKernel.ts +13 -0
  26. package/src/device.ts +18 -4
  27. package/src/evaluations/FeatureEvaluator.ts +21 -0
  28. package/src/event/context.ts +12 -0
  29. package/src/event/feature.ts +43 -13
  30. package/src/event/features/modelGpuBytes.ts +1 -3
  31. package/src/event/features/polygon.ts +2 -1
  32. package/src/event/hillshade.test.ts +7 -13
  33. package/src/event/index.ts +2 -3
  34. package/src/event/tileHandler.ts +54 -0
  35. package/src/index.ts +137 -35
  36. package/src/input.ts +48 -15
  37. package/src/material/enhancer/ShaderReplacer.ts +1 -2
  38. package/src/material/enhancer/instancedSprite/instancedSpriteBaseEnhancer/mutates.test.ts +1 -0
  39. package/src/material/enhancer/instancedSprite/instancedSpriteBaseEnhancer/mutates.ts +2 -0
  40. package/src/material/enhancer/instancedSprite/instancedSpriteBaseEnhancer/types.ts +2 -0
  41. package/src/material/enhancer/polygon/polygonBaseEnhancer/mutates.ts +2 -0
  42. package/src/material/enhancer/polygon/polygonBaseEnhancer/shader.ts +5 -1
  43. package/src/material/enhancer/polygon/polygonBaseEnhancer/types.ts +2 -0
  44. package/src/material/enhancer/polyline/polylineBaseEnhancer/mutates.ts +2 -0
  45. package/src/material/enhancer/polyline/polylineBaseEnhancer/types.ts +2 -0
  46. package/src/material/enhancer/sdfText/sdfTextBaseEnhancer/mutates.ts +8 -0
  47. package/src/material/enhancer/sdfText/sdfTextBaseEnhancer/types.ts +13 -0
  48. package/src/material/enhancer/tileComposite/tileCompositeBaseEnhancer/mutates.test.ts +83 -0
  49. package/src/material/enhancer/tileComposite/tileCompositeBaseEnhancer/mutates.ts +13 -3
  50. package/src/material/overrideMaterialsForMRT.ts +7 -2
  51. package/src/mesh/batchTexture.ts +2 -4
  52. package/src/mesh/batchedSdfText.ts +294 -70
  53. package/src/mesh/instanced.ts +1 -1
  54. package/src/mesh/polygon.ts +11 -4
  55. package/src/mesh/polyline.ts +10 -2
  56. package/src/mesh/sdfText.ts +176 -6
  57. package/src/mesh/sprite/instancedSprite.ts +245 -3
  58. package/src/orchestrators/RenderPassOrchestrator.ts +25 -0
  59. package/src/passes/CustomRenderPass.ts +21 -5
  60. package/src/passes/RenderTargetCopyPass.ts +24 -2
  61. package/src/solar.test.ts +33 -0
  62. package/src/solar.ts +31 -0
  63. package/src/test-utils/engine.ts +53 -0
  64. package/src/tileTexture/TileTextureCompositor.test.ts +2 -0
  65. package/src/tileTexture/TileTextureCompositor.ts +7 -1
  66. package/src/utils/fixedGpuFootprint.test.ts +110 -0
  67. package/src/utils/fixedGpuFootprint.ts +162 -0
  68. package/src/worker/tasks/toCreasedNormals.ts +2 -7
  69. package/dist/assets/fontWorker-CCWL5pbx.js +0 -2
  70. package/dist/assets/fontWorker-CCWL5pbx.js.map +0 -1
  71. package/dist/assets/index-BdtHOOT9.js +0 -12
  72. package/dist/assets/index-BdtHOOT9.js.map +0 -1
@@ -26,6 +26,11 @@ import {
26
26
  Vector2,
27
27
  } from "three";
28
28
 
29
+ import {
30
+ DECLUTTER_FADE_MS,
31
+ type DeclutterCandidate,
32
+ type DeclutterParticipant,
33
+ } from "../declutter/types";
29
34
  import type { MaterialEnhancer } from "../material/enhancer/MaterialEnhancer";
30
35
  import {
31
36
  createSdfTextMaterialEnhancer,
@@ -219,6 +224,27 @@ export class SDFTextMesh
219
224
  private _requestRender?: () => void;
220
225
  // The COLRv1 color atlas is always FontManager-owned; no local field needed.
221
226
 
227
+ /** World-space anchor in ECEF meters (f64), kept in sync with the position
228
+ * uniforms so the declutter pass can project it without touching WASM. */
229
+ private _worldAnchor = new Float64Array(3);
230
+ /** Whether this label participates in screen-space decluttering. */
231
+ private _declutter = false;
232
+ /** Layer-level placement priority from the material. */
233
+ private _declutterPriority = 0;
234
+ /** Per-feature priority set through the evaluator; overrides the layer
235
+ * value when defined. */
236
+ private _declutterPriorityOverride: number | undefined;
237
+ /** Current animated hide factor (mirrors the uDeclutterHide uniform) and
238
+ * the placement target it is fading toward. */
239
+ private _declutterHide = 0;
240
+ private _declutterTarget = 0;
241
+ /** Text block dimensions in em units, mirroring the uTextWidth/uTextHeight/
242
+ * uBgYBounds uniforms; 0 width means "no collision box" (empty text). */
243
+ private _labelWidthEm = 0;
244
+ private _labelHeightEm = 0;
245
+ private _labelMinYEm = 0;
246
+ private _labelMaxYEm = 0;
247
+
222
248
  private _enhancer: MaterialEnhancer<
223
249
  ShaderMaterial,
224
250
  { base?: SdfTextBaseProps },
@@ -235,12 +261,17 @@ export class SDFTextMesh
235
261
  fontUrl: string,
236
262
  batchId: number | undefined,
237
263
  RTE: boolean,
264
+ // Quality is fixed by the owning batch (flipping it needs a new batch), so
265
+ // it is passed in rather than re-derived from `material.highQuality` — the
266
+ // stored material can carry a newer, mismatched value by the time a mesh is
267
+ // created lazily, which must not diverge from the batch's atlas/shaping.
268
+ highQuality: boolean,
238
269
  ) {
239
270
  super();
240
271
 
241
272
  this._fontManager = fontManager;
242
273
  this._fontUrl = fontUrl;
243
- this._highQuality = material.highQuality ?? false;
274
+ this._highQuality = highQuality;
244
275
  this._maxWidth = material.maxWidth ?? 0;
245
276
  this._lineHeight = material.lineHeight ?? 1.0;
246
277
  this._textAlign = ALIGN_FACTORS[material.textAlign ?? "center"] ?? 0.5;
@@ -311,6 +342,22 @@ export class SDFTextMesh
311
342
  transform.ty,
312
343
  transform.tz,
313
344
  ]);
345
+ this._cacheWorldAnchor(position, RTE, [
346
+ transform.tx,
347
+ transform.ty,
348
+ transform.tz,
349
+ ]);
350
+
351
+ // Decluttered labels start hidden and fade in once the placement pass
352
+ // grants them space — otherwise dense tiles flash their full clutter for
353
+ // a frame before the first pass runs.
354
+ this._declutter = material.declutter ?? true;
355
+ this._declutterPriority = material.declutterPriority ?? 0;
356
+ if (this._declutter) {
357
+ this._declutterHide = 1;
358
+ this._declutterTarget = 1;
359
+ mutates.setDeclutterHide(1);
360
+ }
314
361
 
315
362
  // Register shader hook
316
363
  mat.onBeforeCompile = this._enhancer.transformShader;
@@ -446,6 +493,7 @@ export class SDFTextMesh
446
493
 
447
494
  if (!text) {
448
495
  this.geometry.instanceCount = 0;
496
+ this._labelWidthEm = 0;
449
497
  this._setGlyphKeys([]);
450
498
  return;
451
499
  }
@@ -457,6 +505,7 @@ export class SDFTextMesh
457
505
  );
458
506
  if (!shapeResult) {
459
507
  this.geometry.instanceCount = 0;
508
+ this._labelWidthEm = 0;
460
509
  this._setGlyphKeys([]);
461
510
  return;
462
511
  }
@@ -546,6 +595,36 @@ export class SDFTextMesh
546
595
  this._enhancer.update({ base: { opacity: clampedOpacity } });
547
596
  }
548
597
 
598
+ /**
599
+ * Set this label's declutter fade target; the actual hide factor animates
600
+ * toward it in {@link stepDeclutterFade}. Deliberately separate from
601
+ * `visible`/`show`: it neither churns scene-graph membership nor releases
602
+ * glyph atlas retains, so the declutter pass can retarget it every
603
+ * placement run at no cost.
604
+ */
605
+ setDeclutterHidden(hidden: boolean): void {
606
+ this._declutterTarget = hidden ? 1 : 0;
607
+ }
608
+
609
+ /**
610
+ * Advance the hide factor toward its target by `deltaMs / DECLUTTER_FADE_MS`
611
+ * and push it to the uniform. Returns true while still mid-fade.
612
+ */
613
+ stepDeclutterFade(deltaMs: number): boolean {
614
+ const target = this._declutterTarget;
615
+ let value = this._declutterHide;
616
+ if (value === target) return false;
617
+
618
+ const step = deltaMs / DECLUTTER_FADE_MS;
619
+ value =
620
+ value < target
621
+ ? Math.min(value + step, target)
622
+ : Math.max(value - step, target);
623
+ this._declutterHide = value;
624
+ this._enhancer.mutates().setDeclutterHide(value);
625
+ return value !== target;
626
+ }
627
+
549
628
  _setFeatureWidth(_width: number): void {
550
629
  // Width is not applicable to text meshes.
551
630
  // This method is intentionally a no-op to satisfy the FeatureMesh guard.
@@ -565,6 +644,80 @@ export class SDFTextMesh
565
644
  this._enhancer
566
645
  .mutates()
567
646
  .setPosition(position, RTE, [transform.tx, transform.ty, transform.tz]);
647
+ this._cacheWorldAnchor(position, RTE, [
648
+ transform.tx,
649
+ transform.ty,
650
+ transform.tz,
651
+ ]);
652
+ }
653
+
654
+ /** Reconstruct the absolute ECEF anchor from the same inputs the position
655
+ * uniforms receive (RTE high+low split, or RTC-relative + center). */
656
+ private _cacheWorldAnchor(
657
+ position: Float32Array | { high: Float32Array; low: Float32Array },
658
+ RTE: boolean,
659
+ rtcCenter: [number, number, number],
660
+ ): void {
661
+ const anchor = this._worldAnchor;
662
+ if (RTE) {
663
+ const p = position as { high: Float32Array; low: Float32Array };
664
+ anchor[0] = p.high[0] + p.low[0];
665
+ anchor[1] = p.high[1] + p.low[1];
666
+ anchor[2] = (p.high[2] ?? 0.0) + (p.low[2] ?? 0.0);
667
+ } else {
668
+ const p = position as Float32Array;
669
+ anchor[0] = p[0] + rtcCenter[0];
670
+ anchor[1] = p[1] + rtcCenter[1];
671
+ anchor[2] = (p[2] ?? 0.0) + rtcCenter[2];
672
+ }
673
+ }
674
+
675
+ /**
676
+ * Build this label's collision candidate for the shared declutter pass, or
677
+ * null when it doesn't participate (declutter disabled, hidden, or empty).
678
+ * The local box mirrors the vertex shader's layout: glyphs span
679
+ * [0, textWidth] × [bgMinY, bgMaxY] in em units, shifted by the `center`
680
+ * anchor and scaled by the font size (sdfText.vert.glsl:111-115).
681
+ */
682
+ getDeclutterCandidate(
683
+ owner: DeclutterParticipant,
684
+ handle: number,
685
+ ): DeclutterCandidate | null {
686
+ if (!this._declutter || !this.visible || this._labelWidthEm <= 0) {
687
+ return null;
688
+ }
689
+ const state = this._enhancer.states();
690
+ const size = state.fontSize;
691
+ if (size <= 0) return null;
692
+
693
+ const cx = Math.min(Math.max(state.center[0], -0.5), 0.5);
694
+ const cy = Math.min(Math.max(state.center[1], -0.5), 0.5);
695
+ const w = this._labelWidthEm;
696
+ const h = this._labelHeightEm;
697
+ return {
698
+ anchorX: this._worldAnchor[0],
699
+ anchorY: this._worldAnchor[1],
700
+ anchorZ: this._worldAnchor[2],
701
+ addHeight: state.addHeight,
702
+ minX: (0 - cx * w) * size,
703
+ maxX: (w - cx * w) * size,
704
+ minY: (this._labelMinYEm - cy * h) * size,
705
+ maxY: (this._labelMaxYEm - cy * h) * size,
706
+ sizeInMeters: state.sizeInMeters,
707
+ priority: this._declutterPriorityOverride ?? this._declutterPriority,
708
+ isShown: this._declutterTarget === 0,
709
+ owner,
710
+ handle,
711
+ };
712
+ }
713
+
714
+ /**
715
+ * Set a per-feature placement priority (higher wins), overriding the
716
+ * layer-level `declutterPriority` for this label. Pass `undefined` to fall
717
+ * back to the layer value. Driven by the feature evaluator.
718
+ */
719
+ setDeclutterPriority(priority: number | undefined): void {
720
+ this._declutterPriorityOverride = priority;
568
721
  }
569
722
 
570
723
  /**
@@ -596,6 +749,17 @@ export class SDFTextMesh
596
749
  this.setText(this._text, true);
597
750
  }
598
751
 
752
+ // Read before the visibility early-return: the declutter pass consults
753
+ // these even while other style state is skipped for hidden labels.
754
+ const nextDeclutter = material.declutter ?? true;
755
+ if (this._declutter && !nextDeclutter) {
756
+ // Leaving declutter mode: clear any hide the pass applied — the mesh
757
+ // stops producing candidates, so nothing else would ever re-show it.
758
+ this.setDeclutterHidden(false);
759
+ }
760
+ this._declutter = nextDeclutter;
761
+ this._declutterPriority = material.declutterPriority ?? 0;
762
+
599
763
  this.visible = (material.show ?? true) && !!this._text;
600
764
  this._syncGlyphRefs();
601
765
  if (!this.visible) return;
@@ -921,6 +1085,7 @@ export class SDFTextMesh
921
1085
  const count = renderable.length;
922
1086
  if (count === 0) {
923
1087
  this.geometry.instanceCount = 0;
1088
+ this._labelWidthEm = 0;
924
1089
  return;
925
1090
  }
926
1091
 
@@ -976,14 +1141,19 @@ export class SDFTextMesh
976
1141
 
977
1142
  this.geometry.instanceCount = count + 1;
978
1143
 
979
- // Update text dimension uniforms via mutates
1144
+ // Update text dimension uniforms via mutates, mirroring them CPU-side for
1145
+ // the declutter pass's collision box.
1146
+ this._labelWidthEm = textWidth / SDF_PX_SIZE;
1147
+ this._labelHeightEm = textHeight / SDF_PX_SIZE;
1148
+ this._labelMinYEm = bgMinY === Infinity ? 0.0 : bgMinY;
1149
+ this._labelMaxYEm = bgMaxY === -Infinity ? 1.0 : bgMaxY;
980
1150
  this._enhancer
981
1151
  .mutates()
982
1152
  .updateTextDimensions(
983
- textWidth / SDF_PX_SIZE,
984
- textHeight / SDF_PX_SIZE,
985
- bgMinY === Infinity ? 0.0 : bgMinY,
986
- bgMaxY === -Infinity ? 1.0 : bgMaxY,
1153
+ this._labelWidthEm,
1154
+ this._labelHeightEm,
1155
+ this._labelMinYEm,
1156
+ this._labelMaxYEm,
987
1157
  );
988
1158
  }
989
1159
 
@@ -10,14 +10,22 @@ import {
10
10
  Object3D,
11
11
  ShaderMaterial,
12
12
  BufferAttribute,
13
+ type BufferGeometry,
13
14
  Color,
15
+ type Material,
14
16
  PerspectiveCamera,
15
17
  Vector2,
16
18
  } from "three";
17
19
  import invariant from "tiny-invariant";
18
20
 
21
+ import {
22
+ DECLUTTER_FADE_MS,
23
+ type DeclutterCandidate,
24
+ type DeclutterParticipant,
25
+ } from "../../declutter/types";
19
26
  import type { EventContext } from "../../event/context";
20
27
  import { createInstancedSpriteMaterialEnhancer } from "../../material/enhancer";
28
+ import type { CustomObject3DEventMap } from "../../object3DEvent";
21
29
  import { PickableMesh } from "../pickableMesh";
22
30
 
23
31
  import { BillboardAtlas, type AtlasRect } from "./billboardAtlas";
@@ -46,7 +54,10 @@ type PositionsInfo = {
46
54
  const _tmpSize = new Vector2();
47
55
 
48
56
  // Coupled with crates/navara_feature/src/geometry/point.rs::pixel_to_world
49
- export class InstancedSpriteMesh extends Mesh implements PickableMesh {
57
+ export class InstancedSpriteMesh
58
+ extends Mesh<BufferGeometry, Material | Material[], CustomObject3DEventMap>
59
+ implements PickableMesh, DeclutterParticipant
60
+ {
50
61
  private _batchIdToInstance = new Map<number, number>();
51
62
  private _initialColor: Color = new Color(0xffffff);
52
63
  private _initialHeight = 0.0;
@@ -72,15 +83,182 @@ export class InstancedSpriteMesh extends Mesh implements PickableMesh {
72
83
  private _enhancedMaterial?: ReturnType<
73
84
  typeof createInstancedSpriteMaterialEnhancer
74
85
  >;
86
+ /** Per-instance world anchors in ECEF meters (f64, 3 per instance), kept in
87
+ * sync with the position attributes for the declutter pass. */
88
+ private _anchors: Float64Array | null = null;
89
+ /** Whether this mesh's instances participate in screen-space decluttering. */
90
+ private _declutter = false;
91
+ /** Layer-level placement priority from the material. */
92
+ private _declutterPriority = 0;
93
+ /** Per-instance priorities set through the evaluator (NaN = no override,
94
+ * fall back to the layer value). Lazily allocated on first use. */
95
+ private _declutterPriorityOverrides: Float32Array | null = null;
96
+ /** Per-instance fade targets for `instanceDeclutterHide` (0 = shown,
97
+ * 1 = hidden); the attribute animates toward these in stepDeclutterFade. */
98
+ private _declutterTargets: Float32Array | null = null;
99
+ /** True while any instance's hide factor may differ from its target. */
100
+ private _declutterAnimating = false;
101
+
75
102
  constructor(options: InstancedSpriteOptions) {
76
103
  super();
77
104
  this.renderOrder = options.renderOrder ?? this.renderOrder;
78
105
  this.ctx = options.ctx;
106
+ this.ctx.declutter?.register(this);
107
+ // `processObjectRemoved` dispatches this for every removed mesh; it is the
108
+ // reliable teardown signal (this class's dispose() is not called there).
109
+ this.addEventListener("removedFromWorld", () => {
110
+ this.ctx.declutter?.unregister(this);
111
+ });
79
112
  }
80
113
 
81
114
  setActive(active: boolean) {
82
115
  this._active = active;
83
116
  this.updateVisibility();
117
+ this.ctx.declutter?.markDirty();
118
+ }
119
+
120
+ // --- DeclutterParticipant ---
121
+
122
+ collectDeclutterCandidates(out: DeclutterCandidate[]): void {
123
+ if (!this.visible || !this._declutter || !this._anchors) return;
124
+ const enhancer = this._enhancedMaterial;
125
+ const params = this.geometry?.getAttribute("instanceParams") as
126
+ InstancedBufferAttribute | undefined;
127
+ if (!enhancer || !params) return;
128
+
129
+ const state = enhancer.states();
130
+ const cx = Math.min(Math.max(state.center[0], -0.5), 0.5);
131
+ const cy = Math.min(Math.max(state.center[1], -0.5), 0.5);
132
+ // Mirror of instancedSprite.vert.glsl:100-104 — aspect is per-instance
133
+ // (from the atlas rect), not a material-level uniform; there is no
134
+ // material-wide "aspect" state to read.
135
+ const uvRect = state.billboard
136
+ ? (this.geometry?.getAttribute("instanceUvRect") as
137
+ InstancedBufferAttribute | undefined)
138
+ : undefined;
139
+ const anchors = this._anchors;
140
+ const overrides = this._declutterPriorityOverrides;
141
+ const targets = this._declutterTargets;
142
+ const count = Math.min(params.count, anchors.length / 3);
143
+
144
+ for (let i = 0; i < count; i++) {
145
+ if (params.getZ(i) <= 0.5) continue; // hidden by user `show`
146
+ const instanceSize = params.getY(i);
147
+ const size = instanceSize >= 0.0 ? instanceSize : state.scale;
148
+ if (size <= 0.0) continue;
149
+
150
+ const override = overrides ? overrides[i] : Number.NaN;
151
+ const rectH = uvRect ? uvRect.getW(i) : 0;
152
+ const aspect = uvRect && rectH > 0.0 ? uvRect.getZ(i) / rectH : 1.0;
153
+
154
+ // Mirror of instancedSprite.vert.glsl:95-97 — the quad spans
155
+ // (position.xy - center) * vec2(aspect, 1) * size around the anchor.
156
+ out.push({
157
+ anchorX: anchors[i * 3],
158
+ anchorY: anchors[i * 3 + 1],
159
+ anchorZ: anchors[i * 3 + 2],
160
+ addHeight: params.getX(i),
161
+ minX: (-0.5 - cx) * aspect * size,
162
+ maxX: (0.5 - cx) * aspect * size,
163
+ minY: (-0.5 - cy) * size,
164
+ maxY: (0.5 - cy) * size,
165
+ sizeInMeters: state.sizeInMeters,
166
+ // NaN-safe: an unset override falls back to the layer priority.
167
+ priority: Number.isNaN(override) ? this._declutterPriority : override,
168
+ isShown: targets ? targets[i] === 0 : true,
169
+ owner: this,
170
+ handle: i,
171
+ });
172
+ }
173
+ }
174
+
175
+ applyDeclutter(handle: number, hidden: boolean): void {
176
+ this.setDeclutterHiddenByInstance(handle, hidden);
177
+ }
178
+
179
+ stepDeclutterFade(deltaMs: number): boolean {
180
+ if (!this._declutterAnimating) return false;
181
+ const attr = this.geometry?.getAttribute("instanceDeclutterHide") as
182
+ InstancedBufferAttribute | undefined;
183
+ const targets = this._declutterTargets;
184
+ if (!attr || !targets) {
185
+ this._declutterAnimating = false;
186
+ return false;
187
+ }
188
+
189
+ const step = deltaMs / DECLUTTER_FADE_MS;
190
+ const count = Math.min(attr.count, targets.length);
191
+ let stillAnimating = false;
192
+ let changed = false;
193
+ for (let i = 0; i < count; i++) {
194
+ let value = attr.getX(i);
195
+ const target = targets[i];
196
+ if (value === target) continue;
197
+ value =
198
+ value < target
199
+ ? Math.min(value + step, target)
200
+ : Math.max(value - step, target);
201
+ attr.setX(i, value);
202
+ changed = true;
203
+ if (value !== target) stillAnimating = true;
204
+ }
205
+ if (changed) attr.needsUpdate = true;
206
+ this._declutterAnimating = stillAnimating;
207
+ return stillAnimating;
208
+ }
209
+
210
+ private _cacheDeclutterState(m: NavaraPointMesh | NavaraBillboardMesh) {
211
+ const nextDeclutter = m.material.declutter ?? true;
212
+ if (this._declutter && !nextDeclutter) {
213
+ // Leaving declutter mode: clear hides the pass applied — the mesh stops
214
+ // producing candidates, so nothing else would ever re-show them.
215
+ this._clearDeclutterHidden();
216
+ }
217
+ this._declutter = nextDeclutter;
218
+ this._declutterPriority = m.material.declutterPriority ?? 0;
219
+ }
220
+
221
+ private _clearDeclutterHidden(): void {
222
+ const targets = this._declutterTargets;
223
+ if (!targets) return;
224
+ targets.fill(0.0);
225
+ // Everything fades back in from wherever its hide factor currently is.
226
+ this._declutterAnimating = true;
227
+ }
228
+
229
+ /** Reconstruct absolute ECEF anchors from the same arrays the position
230
+ * attributes receive (RTE high+low split, or RTC-relative + center). */
231
+ private _cacheAnchors(
232
+ positionsInfo: PositionsInfo,
233
+ transform: { tx: number; ty: number; tz: number },
234
+ ): void {
235
+ const { nPositions, positionSize, RTE } = positionsInfo;
236
+ const anchors =
237
+ this._anchors && this._anchors.length === nPositions * 3
238
+ ? this._anchors
239
+ : new Float64Array(nPositions * 3);
240
+
241
+ if (RTE) {
242
+ const pos = positionsInfo.position as {
243
+ high: Float32Array<ArrayBufferLike>;
244
+ low: Float32Array<ArrayBufferLike>;
245
+ };
246
+ for (let i = 0; i < nPositions; i++) {
247
+ const s = i * positionSize;
248
+ anchors[i * 3] = pos.high[s] + pos.low[s];
249
+ anchors[i * 3 + 1] = pos.high[s + 1] + pos.low[s + 1];
250
+ anchors[i * 3 + 2] = (pos.high[s + 2] ?? 0.0) + (pos.low[s + 2] ?? 0.0);
251
+ }
252
+ } else {
253
+ const pos = positionsInfo.position as Float32Array<ArrayBufferLike>;
254
+ for (let i = 0; i < nPositions; i++) {
255
+ const s = i * positionSize;
256
+ anchors[i * 3] = pos[s] + transform.tx;
257
+ anchors[i * 3 + 1] = pos[s + 1] + transform.ty;
258
+ anchors[i * 3 + 2] = (pos[s + 2] ?? 0.0) + transform.tz;
259
+ }
260
+ }
261
+ this._anchors = anchors;
84
262
  }
85
263
 
86
264
  async _init(m: NavaraPointMesh | NavaraBillboardMesh) {
@@ -90,6 +268,9 @@ export class InstancedSpriteMesh extends Mesh implements PickableMesh {
90
268
  return;
91
269
  }
92
270
 
271
+ this._cacheDeclutterState(m);
272
+ this._cacheAnchors(positionsInfo, m.transform);
273
+
93
274
  // Create Geometry
94
275
  this.geometry = this._initGeometry(positionsInfo, m);
95
276
 
@@ -97,12 +278,15 @@ export class InstancedSpriteMesh extends Mesh implements PickableMesh {
97
278
  this.material = await this._initMaterial(positionsInfo, m);
98
279
 
99
280
  this.frustumCulled = false; // Disable since bounding box doesn't account for instance positions
281
+ this.ctx.declutter?.markDirty();
100
282
  }
101
283
 
102
284
  async _update(m: NavaraPointMesh | NavaraBillboardMesh) {
103
285
  const enhancer = this.getEnhancer();
104
286
  const material = this.material as ShaderMaterial;
105
287
 
288
+ this._cacheDeclutterState(m);
289
+
106
290
  if (material.visible !== m.material.show) {
107
291
  material.visible = m.material.show ?? true;
108
292
  this.updateVisibility();
@@ -162,6 +346,7 @@ export class InstancedSpriteMesh extends Mesh implements PickableMesh {
162
346
  const positionsInfo = this.extractPositions(m);
163
347
 
164
348
  if (positionsInfo) {
349
+ this._cacheAnchors(positionsInfo, m.transform);
165
350
  if (positionsInfo.RTE) {
166
351
  const pos = positionsInfo.position as {
167
352
  high: Float32Array<ArrayBufferLike>;
@@ -198,6 +383,8 @@ export class InstancedSpriteMesh extends Mesh implements PickableMesh {
198
383
  await this._setDefaultImage(m.material.url);
199
384
  }
200
385
  }
386
+
387
+ this.ctx.declutter?.markDirty();
201
388
  }
202
389
 
203
390
  private _initGeometry(
@@ -307,6 +494,16 @@ export class InstancedSpriteMesh extends Mesh implements PickableMesh {
307
494
  "instanceColor",
308
495
  new InstancedBufferAttribute(colorBuffer, 3),
309
496
  );
497
+ // Declutter hide factors (0 = shown … 1 = hidden). Decluttered instances
498
+ // start hidden and fade in once the placement pass grants them space, so
499
+ // dense tiles don't flash their full clutter before the first pass runs.
500
+ const initialHide = this._declutter ? 1.0 : 0.0;
501
+ const declutterBuffer = new Float32Array(instanceCount).fill(initialHide);
502
+ this._declutterTargets = new Float32Array(instanceCount).fill(initialHide);
503
+ instancedGeometry.setAttribute(
504
+ "instanceDeclutterHide",
505
+ new InstancedBufferAttribute(declutterBuffer, 1),
506
+ );
310
507
  instancedGeometry.setAttribute(
311
508
  "instanceBatchID",
312
509
  new InstancedBufferAttribute(
@@ -572,6 +769,7 @@ export class InstancedSpriteMesh extends Mesh implements PickableMesh {
572
769
  ) as InstancedBufferAttribute;
573
770
  paramsAttr.setZ(instanceId, rawVisible ? 1.0 : 0.0);
574
771
  paramsAttr.needsUpdate = true;
772
+ this.ctx.declutter?.markDirty();
575
773
  }
576
774
 
577
775
  setFeatureOpacityByBatchId(batchId: number, opacity: number) {
@@ -599,6 +797,46 @@ export class InstancedSpriteMesh extends Mesh implements PickableMesh {
599
797
  const sanitizedHeight = Number.isFinite(height) ? height : 0.0;
600
798
  paramsAttr.setX(instanceId, sanitizedHeight);
601
799
  paramsAttr.needsUpdate = true;
800
+ this.ctx.declutter?.markDirty();
801
+ }
802
+
803
+ /**
804
+ * Set one instance's declutter fade target; the attribute animates toward
805
+ * it in {@link stepDeclutterFade}. Deliberately separate from the `show`
806
+ * component of `instanceParams` so user-driven visibility and declutter
807
+ * results compose instead of clobbering each other.
808
+ */
809
+ setDeclutterHiddenByInstance(instanceIndex: number, hidden: boolean) {
810
+ const targets = this._declutterTargets;
811
+ if (!targets || instanceIndex < 0 || instanceIndex >= targets.length) {
812
+ return;
813
+ }
814
+ targets[instanceIndex] = hidden ? 1.0 : 0.0;
815
+ // Cheap over-approximation; stepDeclutterFade clears it when everything
816
+ // has reached its target.
817
+ this._declutterAnimating = true;
818
+ }
819
+
820
+ /**
821
+ * Set a per-feature placement priority (higher wins), overriding the
822
+ * layer-level `declutterPriority` for this instance. Driven by the feature
823
+ * evaluator.
824
+ */
825
+ setFeatureDeclutterPriorityByBatchId(batchId: number, priority: number) {
826
+ const instanceId = this._batchIdToInstance.get(batchId);
827
+ if (instanceId === undefined) return;
828
+
829
+ if (!this._declutterPriorityOverrides) {
830
+ const count = this._anchors ? this._anchors.length / 3 : 0;
831
+ if (count === 0) return;
832
+ this._declutterPriorityOverrides = new Float32Array(count).fill(
833
+ Number.NaN,
834
+ );
835
+ }
836
+ if (instanceId >= this._declutterPriorityOverrides.length) return;
837
+ if (this._declutterPriorityOverrides[instanceId] === priority) return;
838
+ this._declutterPriorityOverrides[instanceId] = priority;
839
+ this.ctx.declutter?.markDirty();
602
840
  }
603
841
 
604
842
  setFeatureSizeByBatchId(batchId: number, size: number) {
@@ -616,6 +854,7 @@ export class InstancedSpriteMesh extends Mesh implements PickableMesh {
616
854
  : -1.0;
617
855
  paramsAttr.setY(instanceId, sanitizedSize);
618
856
  paramsAttr.needsUpdate = true;
857
+ this.ctx.declutter?.markDirty();
619
858
  }
620
859
 
621
860
  /**
@@ -634,8 +873,7 @@ export class InstancedSpriteMesh extends Mesh implements PickableMesh {
634
873
  if (instanceId === undefined) return;
635
874
 
636
875
  const rectAttr = this.geometry.getAttribute("instanceUvRect") as
637
- | InstancedBufferAttribute
638
- | undefined;
876
+ InstancedBufferAttribute | undefined;
639
877
  if (!rectAttr) return;
640
878
 
641
879
  if (url == null) {
@@ -669,6 +907,7 @@ export class InstancedSpriteMesh extends Mesh implements PickableMesh {
669
907
  }
670
908
 
671
909
  dispose(): void {
910
+ this.ctx.declutter?.unregister(this);
672
911
  this.geometry?.dispose();
673
912
 
674
913
  // The material's uTexture points at the atlas texture; the atlas owns it.
@@ -688,6 +927,9 @@ export class InstancedSpriteMesh extends Mesh implements PickableMesh {
688
927
 
689
928
  // Clear internal collections to release references
690
929
  this._batchIdToInstance.clear();
930
+ this._anchors = null;
931
+ this._declutterTargets = null;
932
+ this._declutterPriorityOverrides = null;
691
933
  this._imageOverrides.clear();
692
934
  this._requestedImageUrls.clear();
693
935
  }
@@ -2,6 +2,8 @@ import { NamedIndexMap } from "@navaramap/core";
2
2
  import { EffectComposer, Pass as PostProcessingPass } from "postprocessing";
3
3
  import { HalfFloatType, Scene, WebGLRenderer, Group } from "three";
4
4
 
5
+ import { estimateFixedGpuBytes } from "../utils/fixedGpuFootprint";
6
+
5
7
  export type RenderPassOrchestratorOptions = {
6
8
  halfFloat?: boolean;
7
9
  multisampling?: number;
@@ -34,6 +36,12 @@ export class RenderPassOrchestrator {
34
36
  };
35
37
  effectComposer: EffectComposer;
36
38
 
39
+ /**
40
+ * Invoked whenever the pass list changes (add/insert/remove/clear), so the
41
+ * owner can re-report the fixed GPU footprint to the memory ledger.
42
+ */
43
+ onPassesChanged?: () => void;
44
+
37
45
  private passMap = new NamedIndexMap<NamedPass>();
38
46
 
39
47
  constructor(renderer: WebGLRenderer, options: RenderPassOrchestratorOptions) {
@@ -60,6 +68,7 @@ export class RenderPassOrchestrator {
60
68
  const namedPass: NamedPass = { name, pass };
61
69
  this.passMap.add(namedPass);
62
70
  this.effectComposer.addPass(pass);
71
+ this.onPassesChanged?.();
63
72
  }
64
73
 
65
74
  /**
@@ -73,6 +82,7 @@ export class RenderPassOrchestrator {
73
82
  const namedPass: NamedPass = { name, pass };
74
83
  const targetIndex = this.passMap.insertBefore(targetName, namedPass);
75
84
  this.effectComposer.addPass(pass, targetIndex);
85
+ this.onPassesChanged?.();
76
86
  }
77
87
 
78
88
  /**
@@ -86,6 +96,7 @@ export class RenderPassOrchestrator {
86
96
  const namedPass: NamedPass = { name, pass };
87
97
  const targetIndex = this.passMap.insertAfter(targetName, namedPass);
88
98
  this.effectComposer.addPass(pass, targetIndex);
99
+ this.onPassesChanged?.();
89
100
  }
90
101
 
91
102
  /**
@@ -100,6 +111,7 @@ export class RenderPassOrchestrator {
100
111
  this.effectComposer.removePass(targetPass.pass);
101
112
  this.passMap.list = this.passMap.list.filter((p) => p.name !== name);
102
113
  this.rebuildIndexMap();
114
+ this.onPassesChanged?.();
103
115
  }
104
116
 
105
117
  /**
@@ -125,6 +137,19 @@ export class RenderPassOrchestrator {
125
137
  }
126
138
  this.passMap.list = [];
127
139
  this.passMap.indexMap = {};
140
+ this.onPassesChanged?.();
141
+ }
142
+
143
+ /**
144
+ * Estimates the resident GPU bytes of the fixed, screen-sized render-target
145
+ * stack (composer buffers + every target reachable from the passes), for
146
+ * reporting into the memory ledger's `fixed_gpu_bytes` term.
147
+ */
148
+ estimateFixedGpuBytes(): number {
149
+ return estimateFixedGpuBytes(
150
+ this.effectComposer,
151
+ this.passMap.list.map((p) => p.pass),
152
+ );
128
153
  }
129
154
 
130
155
  /**