@thoughts-on-things/vantage-mc 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { biomePalette, LOWRES_EMPTY, tileKey, parseLowresTile, maybeInflate, parseTileQuantized, summarizeSurfaceBiomes, parseTile, summarizeBiomes, worldFromUrl, parseManifest, parseTextureArray } from './chunk-M6KVJXCR.js';
1
+ import { biomePalette, LOWRES_EMPTY, tileKey, parseLowresTile, maybeInflate, parseTileQuantized, summarizeSurfaceBiomes, parseTile, summarizeBiomes, worldFromUrl, parseManifest, parseTextureArray } from './chunk-ILHVIGCI.js';
2
2
  import * as THREE2 from 'three';
3
3
 
4
4
  var SKY_TOP = [0.3, 0.52, 0.84];
@@ -45,6 +45,7 @@ var VERT = (
45
45
  out float vFog;
46
46
  out float vSky; // saved sky light, 0..1
47
47
  out float vBlk; // saved block light, 0..1
48
+ out float vWorldY; // world-space Y, for the depth slice
48
49
  void main() {
49
50
  vTint = atint;
50
51
  vLayer = alayer;
@@ -75,6 +76,7 @@ var VERT = (
75
76
  // texture frames (see the fragment shader's uAnim/uTime).
76
77
  vN = normalize(mat3(modelMatrix) * nrm);
77
78
  vec4 wp = modelMatrix * vec4(pos, 1.0);
79
+ vWorldY = wp.y;
78
80
  vec4 mv = viewMatrix * wp;
79
81
  // Streamed worlds fog by horizontal distance from the streaming focus \u2014
80
82
  // exactly the ring where tiles stop \u2014 so looking straight down from any
@@ -107,6 +109,12 @@ var FRAG = (
107
109
  uniform float uSaturation; // colour saturation (1 = neutral)
108
110
  uniform float uContrast; // colour contrast around mid grey (1 = neutral)
109
111
  uniform float uFogDensity; // atmospheric haze amount (1 = full, 0 = clear)
112
+ uniform float uClipY; // depth-slice plane: fragments above this world Y
113
+ // are cut away (1e9 = slice off). See setSlice().
114
+ uniform float uFade; // per-tile stream-in fade (set per mesh, 0..1):
115
+ // alpha-to-coverage dithers it under MSAA, so new
116
+ // tiles dissolve in over the lowres placeholder
117
+ // instead of popping their lighting on.
110
118
  in vec2 vUv;
111
119
  in vec4 vTint;
112
120
  in vec3 vBcol;
@@ -116,6 +124,7 @@ var FRAG = (
116
124
  in float vFog;
117
125
  in float vSky;
118
126
  in float vBlk;
127
+ in float vWorldY;
119
128
  #ifdef LIGHTMAP
120
129
  uniform sampler2D uLightmap; // per-tile baked light+AO atlas
121
130
  in vec2 vLmUv;
@@ -174,6 +183,10 @@ var FRAG = (
174
183
  }
175
184
 
176
185
  void main() {
186
+ // Depth slice (cave view): cut everything above the clip plane. With
187
+ // backface culling on, the first thing visible below the cut is a cave
188
+ // FLOOR (ceilings face away) \u2014 exactly the readable cave-map view.
189
+ if (vWorldY > uClipY) discard;
177
190
  // Light + AO source: per-vertex (interpolated), or \u2014 for atlas-lit
178
191
  // geometry \u2014 the tile lightmap, whose bilinear filter reproduces the
179
192
  // per-block-corner values exactly and keeps gradients inside big quads.
@@ -232,7 +245,7 @@ var FRAG = (
232
245
  vec3 wlit = grade(wcol * (0.62 + 0.28 * SUN * ndl2) * lightAmt * lightCol * uExposure);
233
246
  float wf = smoothstep(uFog.x, uFog.y, vFog) * uFogDensity;
234
247
  float wa = mix(0.5, 0.74, depth); // blue tint, seabed still reads through
235
- frag = vec4(toSRGB(mix(wlit, fogCol, wf)), wa);
248
+ frag = vec4(toSRGB(mix(wlit, fogCol, wf)), wa * uFade);
236
249
  return;
237
250
  }
238
251
 
@@ -254,8 +267,13 @@ var FRAG = (
254
267
  vec3 hemi = mix(GND, SKY, 0.5 + 0.5 * N.y);
255
268
  vec3 shade = mix(vec3(1.0), hemi, 0.16) * fshade;
256
269
  vec3 lit = grade(base * shade * ao * lightAmt * lightCol * uExposure);
270
+ // Depth-slice cut edge: a thin warm rim on the top ~1.5 blocks below the
271
+ // clip plane outlines the section like a CAD cutaway. Free when the slice
272
+ // is off \u2014 uClipY sits ~1e9 above any terrain, so cut is exactly 0.
273
+ float cut = 1.0 - smoothstep(0.0, 1.5, uClipY - vWorldY);
274
+ lit += vec3(1.0, 0.72, 0.35) * (0.2 * cut);
257
275
  float f = smoothstep(uFog.x, uFog.y, vFog) * uFogDensity; // aerial depth into the horizon
258
- frag = vec4(toSRGB(mix(lit, fogCol, f)), uAlpha * t.a); // alpha \u2192 MSAA coverage (foliage AA)
276
+ frag = vec4(toSRGB(mix(lit, fogCol, f)), uAlpha * t.a * uFade); // alpha \u2192 MSAA coverage (foliage AA)
259
277
  }
260
278
  `
261
279
  );
@@ -348,8 +366,12 @@ function createTerrainMaterial(texData, opts = {}) {
348
366
  // colour saturation (1 = neutral)
349
367
  uContrast: { value: 1 },
350
368
  // colour contrast (1 = neutral)
351
- uFogDensity: { value: 1 }
369
+ uFogDensity: { value: 1 },
352
370
  // atmospheric haze amount (1 = full)
371
+ uClipY: { value: 1e9 },
372
+ // depth-slice plane (1e9 = off)
373
+ uFade: { value: 1 }
374
+ // stream-in fade; written per mesh each draw
353
375
  },
354
376
  vertexShader: VERT,
355
377
  fragmentShader: FRAG,
@@ -400,7 +422,11 @@ function createLowresMaterial(terrain) {
400
422
  uFogDensity: t["uFogDensity"],
401
423
  uExposure: t["uExposure"],
402
424
  uSaturation: t["uSaturation"],
403
- uContrast: t["uContrast"]
425
+ uContrast: t["uContrast"],
426
+ uClipY: t["uClipY"],
427
+ // Own fade uniform (not the terrain's ref): both are rewritten per mesh
428
+ // each draw, but separate objects keep the two materials independent.
429
+ uFade: { value: 1 }
404
430
  },
405
431
  vertexShader: (
406
432
  /* glsl */
@@ -410,9 +436,11 @@ function createLowresMaterial(terrain) {
410
436
  uniform float uFogRadial;
411
437
  out vec3 vCol;
412
438
  out float vFog;
439
+ out float vWorldY;
413
440
  void main() {
414
441
  vCol = acol;
415
442
  vec4 wp = modelMatrix * vec4(position, 1.0);
443
+ vWorldY = wp.y;
416
444
  vec4 mv = viewMatrix * wp;
417
445
  vFog = mix(-mv.z, distance(wp.xz, uFogCenter), uFogRadial);
418
446
  gl_Position = projectionMatrix * mv;
@@ -429,8 +457,11 @@ function createLowresMaterial(terrain) {
429
457
  uniform float uExposure;
430
458
  uniform float uSaturation;
431
459
  uniform float uContrast;
460
+ uniform float uClipY;
461
+ uniform float uFade;
432
462
  in vec3 vCol;
433
463
  in float vFog;
464
+ in float vWorldY;
434
465
  out vec4 frag;
435
466
  vec3 toLinear(vec3 c) {
436
467
  return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));
@@ -440,15 +471,21 @@ function createLowresMaterial(terrain) {
440
471
  return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
441
472
  }
442
473
  void main() {
474
+ // The lowres rings clip with the hires terrain (shared uClipY), so the
475
+ // depth slice cuts the whole world, not just the streamed disc.
476
+ if (vWorldY > uClipY) discard;
443
477
  vec3 c = toLinear(vCol) * uExposure;
444
478
  float l = dot(c, vec3(0.299, 0.587, 0.114));
445
479
  c = mix(vec3(l), c, uSaturation);
446
480
  c = max((c - 0.5) * uContrast + 0.5, vec3(0.0));
447
481
  float f = smoothstep(uFog.x, uFog.y, vFog) * uFogDensity;
448
- frag = vec4(toSRGB(mix(c, toLinear(uFogColor), f)), 1.0);
482
+ frag = vec4(toSRGB(mix(c, toLinear(uFogColor), f)), uFade);
449
483
  }
450
484
  `
451
- )
485
+ ),
486
+ // Turns the stream-in fade's fractional alpha into MSAA coverage (the
487
+ // material is otherwise fully opaque, so this costs nothing once faded).
488
+ alphaToCoverage: true
452
489
  });
453
490
  }
454
491
  function createSky() {
@@ -754,7 +791,7 @@ function releaseAfterUpload(geom) {
754
791
  }
755
792
  if (geom.index && !isSharedQuadIndex(geom.index)) geom.index.onUpload(release);
756
793
  }
757
- var TileManager = class {
794
+ var TileManager = class _TileManager {
758
795
  opts;
759
796
  lowresMaterial;
760
797
  lmMaterial;
@@ -768,6 +805,8 @@ var TileManager = class {
768
805
  lowIndex = /* @__PURE__ */ new Map();
769
806
  /** Set when residency changed and lowres visibility needs recomputing. */
770
807
  coverageDirty = false;
808
+ /** Tiles mid stream-in fade; drained by update(), keeps the viewer drawing. */
809
+ fadingKeys = /* @__PURE__ */ new Set();
771
810
  queue = [];
772
811
  /** Built tiles awaiting scene insertion — flushed ONE per update() call so
773
812
  * multi-MB GPU uploads never pile into a single frame. */
@@ -830,6 +869,16 @@ var TileManager = class {
830
869
  if (this.disposed) return;
831
870
  this.flushOne();
832
871
  this.retrySweep();
872
+ if (this.fadingKeys.size > 0) {
873
+ const now = performance.now();
874
+ for (const key of this.fadingKeys) {
875
+ const rec = this.records.get(key);
876
+ if (!rec || rec.fadeStart === void 0 || now - rec.fadeStart >= _TileManager.FADE_MS) {
877
+ this.fadingKeys.delete(key);
878
+ this.coverageDirty = true;
879
+ }
880
+ }
881
+ }
833
882
  if (this.coverageDirty) this.applyCoverage();
834
883
  const moved = Math.hypot(focusX - this.lastFocusX, focusZ - this.lastFocusZ);
835
884
  if (moved < this.tileBlocks / 4) {
@@ -902,6 +951,8 @@ var TileManager = class {
902
951
  const rec = this.records.get(key);
903
952
  if (!rec || rec.state !== "built") continue;
904
953
  rec.state = "ready";
954
+ rec.fadeStart = performance.now();
955
+ this.fadingKeys.add(key);
905
956
  this.opts.scene.add(rec.terrain);
906
957
  if (rec.terrainLm) this.opts.scene.add(rec.terrainLm);
907
958
  if (rec.water) this.opts.scene.add(rec.water);
@@ -911,6 +962,28 @@ var TileManager = class {
911
962
  budget--;
912
963
  }
913
964
  }
965
+ /** Stream-in fade length. Long enough to read as a dissolve, short enough
966
+ * that a fast pan still feels instant. */
967
+ static FADE_MS = 280;
968
+ /** Whether any tile is mid stream-in fade — the viewer keeps drawing while
969
+ * true so the dissolve actually animates under render-on-demand. */
970
+ get fading() {
971
+ return this.fadingKeys.size > 0;
972
+ }
973
+ /** Chain a per-draw uFade write onto each mesh's onBeforeRender (after the
974
+ * dequantize-uniform hook terrain.ts installs). Every TileManager mesh gets
975
+ * one — the materials are shared, so each draw must set its own fade. */
976
+ attachFade(rec, ...meshes) {
977
+ for (const mesh of meshes) {
978
+ if (!mesh) continue;
979
+ const orig = mesh.onBeforeRender;
980
+ mesh.onBeforeRender = (renderer, scene, camera, geometry, material, group) => {
981
+ orig.call(mesh, renderer, scene, camera, geometry, material, group);
982
+ const u = material.uniforms?.["uFade"];
983
+ if (u) u.value = rec.fadeStart === void 0 ? 1 : Math.min(1, (performance.now() - rec.fadeStart) / _TileManager.FADE_MS);
984
+ };
985
+ }
986
+ }
914
987
  /**
915
988
  * Hide every lowres tile whose footprint is fully SHOWN by finer data.
916
989
  * "Shown" is transitive, computed bottom-up: a hires tile shows its area by
@@ -928,8 +1001,8 @@ var TileManager = class {
928
1001
  applyCoverage() {
929
1002
  this.coverageDirty = false;
930
1003
  let shown = /* @__PURE__ */ new Set();
931
- for (const rec of this.records.values()) {
932
- if (rec.level === 0 && rec.state === "ready") shown.add(tileKey(rec.ref.x, rec.ref.z));
1004
+ for (const [key, rec] of this.records) {
1005
+ if (rec.level === 0 && rec.state === "ready" && !this.fadingKeys.has(key)) shown.add(tileKey(rec.ref.x, rec.ref.z));
933
1006
  }
934
1007
  let finerIndex = this.index;
935
1008
  for (const lvl of this.lowLevels) {
@@ -987,6 +1060,7 @@ var TileManager = class {
987
1060
  mesh.renderOrder = -level;
988
1061
  releaseAfterUpload(mesh.geometry);
989
1062
  rec.terrain = mesh;
1063
+ this.attachFade(rec, mesh);
990
1064
  rec.low = {
991
1065
  originX: tile.originX,
992
1066
  originZ: tile.originZ,
@@ -1069,6 +1143,7 @@ var TileManager = class {
1069
1143
  rec.terrainLm = meshes.terrainLm;
1070
1144
  rec.lightmapTex = meshes.lightmapTex;
1071
1145
  rec.water = meshes.water;
1146
+ this.attachFade(rec, meshes.terrain, meshes.terrainLm, meshes.water);
1072
1147
  this.minY = Math.min(this.minY, meshes.bounds.min.y);
1073
1148
  this.maxY = Math.max(this.maxY, meshes.bounds.max.y);
1074
1149
  rec.state = "built";
@@ -1097,6 +1172,7 @@ var TileManager = class {
1097
1172
  rec.lightmapTex?.dispose();
1098
1173
  this.records.delete(key);
1099
1174
  this.failCounts.delete(key);
1175
+ this.fadingKeys.delete(key);
1100
1176
  this.coverageDirty = true;
1101
1177
  this.invalidate();
1102
1178
  this.emitter.emit("change", this.stats);
@@ -2072,6 +2148,18 @@ var VantageViewer = class _VantageViewer {
2072
2148
  highlight = null;
2073
2149
  mixTarget = 0;
2074
2150
  mixCurrent = 0;
2151
+ // Depth slice (cave view): everything above the clip plane is cut away,
2152
+ // revealing cave floors below. `sliceTarget` is where the user set it (null =
2153
+ // off); `sliceCurrent` eases toward it each frame, so toggling peels the
2154
+ // world open instead of popping. `sliceActive` stays true through the
2155
+ // toggle-off ease until the plane has lifted clear.
2156
+ sliceTarget = null;
2157
+ sliceCurrent = 0;
2158
+ sliceActive = false;
2159
+ /** The last depth used, so re-opening the cave view returns there. */
2160
+ lastSliceY = null;
2161
+ /** The dark "unexplored rock" floor under a sliced world. */
2162
+ slicePlane = null;
2075
2163
  // Live lighting appearance (applied to the shader on load and on change).
2076
2164
  light = { ...DEFAULT_LIGHT };
2077
2165
  // Live display fidelity (shader uniforms + render scale).
@@ -2086,6 +2174,15 @@ var VantageViewer = class _VantageViewer {
2086
2174
  // sentinel distinct from -1 (off-terrain)
2087
2175
  // Last-frame timestamp, for frame-rate-independent control inertia.
2088
2176
  lastFrameMs = 0;
2177
+ // Render-on-demand: a frame draws only when this is set (camera moved, tiles
2178
+ // changed, a setting changed, …) or the idle animation tick fires. See
2179
+ // `invalidate()`.
2180
+ needsRender = true;
2181
+ // Whether the loaded texture array animates (water/lava frames) — drives the
2182
+ // idle tick. Set on load from the decoded anim table.
2183
+ hasAnims = false;
2184
+ // When the last frame actually rendered, for the idle animation cadence.
2185
+ lastRenderMs = 0;
2089
2186
  // The framing the current tile loaded into, so the UI can re-home to it.
2090
2187
  framedState = null;
2091
2188
  // URL-hash deep links (urlState option): debounce handle for hash writes and
@@ -2102,7 +2199,8 @@ var VantageViewer = class _VantageViewer {
2102
2199
  light: options.light ?? {},
2103
2200
  display: options.display ?? {},
2104
2201
  streaming: options.streaming ?? {},
2105
- urlState: options.urlState ?? false
2202
+ urlState: options.urlState ?? false,
2203
+ renderOnDemand: options.renderOnDemand ?? true
2106
2204
  };
2107
2205
  if (options.light) this.light = { ...this.light, ...options.light };
2108
2206
  if (options.display) this.display = { ...this.display, ...options.display };
@@ -2195,6 +2293,7 @@ var VantageViewer = class _VantageViewer {
2195
2293
  this.waterShader = waterShader;
2196
2294
  this.lowresShader = lowresShader ?? null;
2197
2295
  this.manifest = manifest;
2296
+ this.hasAnims = texData.anims.length > 0;
2198
2297
  this.tile = null;
2199
2298
  this.tiles = new TileManager({
2200
2299
  manifest,
@@ -2207,8 +2306,9 @@ var VantageViewer = class _VantageViewer {
2207
2306
  palette,
2208
2307
  ...this.options.streaming
2209
2308
  });
2210
- this.controls.heightAt = this.tiles.heightAt;
2309
+ this.setHeightSampler(this.tiles.heightAt);
2211
2310
  this.tilesUnsub = this.tiles.on("change", (stats) => {
2311
+ this.needsRender = true;
2212
2312
  this.emitter.emit("stats", stats);
2213
2313
  const now = performance.now();
2214
2314
  if (stats.loading === 0 || now - this.lastBiomesEmit > 500) {
@@ -2222,6 +2322,7 @@ var VantageViewer = class _VantageViewer {
2222
2322
  this.applyBiomeUniforms();
2223
2323
  this.applyLight();
2224
2324
  this.applyDisplay();
2325
+ this.applySlice();
2225
2326
  this.tiles.update(this.controls.position.x, this.controls.position.z);
2226
2327
  const size = new THREE2.Vector3();
2227
2328
  this.bounds.getSize(size);
@@ -2315,6 +2416,7 @@ var VantageViewer = class _VantageViewer {
2315
2416
  this.disposeCurrent();
2316
2417
  const built = buildTerrain(tile, textures);
2317
2418
  this.tile = tile;
2419
+ this.hasAnims = (textures?.anims.length ?? 0) > 0;
2318
2420
  this.shader = built.shader ?? null;
2319
2421
  this.bounds = built.bounds;
2320
2422
  this.scene.add(built.terrain);
@@ -2327,13 +2429,14 @@ var VantageViewer = class _VantageViewer {
2327
2429
  this.scene.add(hemi, sun);
2328
2430
  this.current.lights = [hemi, sun];
2329
2431
  }
2330
- this.controls.heightAt = makeHeightSampler(tile.surface);
2432
+ this.setHeightSampler(makeHeightSampler(tile.surface));
2331
2433
  this._biomes = summarizeBiomes(tile, built.palette);
2332
2434
  this.frameCamera(view);
2333
2435
  if (this.options.urlState) this.applyViewHash(window.location.hash);
2334
2436
  this.applyBiomeUniforms();
2335
2437
  this.applyLight();
2336
2438
  this.applyDisplay();
2439
+ this.applySlice();
2337
2440
  const size = new THREE2.Vector3();
2338
2441
  this.bounds.getSize(size);
2339
2442
  this.emitter.emit("load", {
@@ -2455,7 +2558,9 @@ var VantageViewer = class _VantageViewer {
2455
2558
  }
2456
2559
  applyBiomeUniforms() {
2457
2560
  if (!this.shader) return;
2561
+ this.shader.uniforms["uBiomeMix"].value = this.mixCurrent;
2458
2562
  this.shader.uniforms["uHi"].value = this.biomeEnabled && this.highlight !== null ? this.highlight : -1;
2563
+ this.needsRender = true;
2459
2564
  }
2460
2565
  // --- lighting appearance ---------------------------------------------------
2461
2566
  /** The current live lighting appearance. */
@@ -2470,9 +2575,156 @@ var VantageViewer = class _VantageViewer {
2470
2575
  }
2471
2576
  applyLight() {
2472
2577
  if (!this.shader) return;
2473
- this.shader.uniforms["uAmbient"].value = this.light.ambient;
2578
+ const ambient = this.sliceActive ? Math.max(this.light.ambient, 0.32) : this.light.ambient;
2579
+ this.shader.uniforms["uAmbient"].value = ambient;
2474
2580
  this.shader.uniforms["uDay"].value = this.light.daylight;
2475
2581
  this.shader.uniforms["uExposure"].value = this.light.exposure;
2582
+ this.needsRender = true;
2583
+ }
2584
+ // --- depth slice (cave view) -------------------------------------------------
2585
+ /** Whether the loaded world was baked with full cave geometry
2586
+ * (`vantage render --caves full`) — i.e. the depth slice has real caves to
2587
+ * reveal. The slice API works regardless; this is the "show the UI?" bit. */
2588
+ get hasCaves() {
2589
+ return this.manifest?.caves ?? false;
2590
+ }
2591
+ /** The world-Y bounds for the depth slice, from the manifest's baked extent
2592
+ * (falling back to the loaded bounds / vanilla build limits). */
2593
+ get sliceRange() {
2594
+ const yr = this.manifest?.yRange;
2595
+ if (yr) return { min: yr.min, max: yr.max };
2596
+ if (Number.isFinite(this.bounds.min.y) && this.bounds.min.y < this.bounds.max.y) {
2597
+ return { min: this.bounds.min.y, max: this.bounds.max.y };
2598
+ }
2599
+ return { min: -64, max: 320 };
2600
+ }
2601
+ /** The current depth-slice Y, or `null` when the cave view is off. */
2602
+ get slice() {
2603
+ return this.sliceTarget;
2604
+ }
2605
+ /** Slice the world at world-Y `y` (everything above is cut away, exposing
2606
+ * the caves below — the cave / X-ray view); `null` turns it off. The plane
2607
+ * eases to its target, so toggling peels the world open. Emits `'slice'`. */
2608
+ setSlice(y) {
2609
+ const r = this.sliceRange;
2610
+ const target = y === null ? null : Math.min(Math.max(y, r.min + 2), r.max);
2611
+ if (target === this.sliceTarget) return;
2612
+ if (target !== null) {
2613
+ if (!this.sliceActive) this.sliceCurrent = r.max + 24;
2614
+ this.sliceActive = true;
2615
+ this.lastSliceY = target;
2616
+ }
2617
+ this.sliceTarget = target;
2618
+ this.applySlice();
2619
+ this.queueHashWrite();
2620
+ this.emitter.emit("slice", { y: target });
2621
+ }
2622
+ /** Toggle the cave view: off → the last used depth (or a sensible cave
2623
+ * depth on first open), on → off. */
2624
+ toggleSlice() {
2625
+ if (this.sliceTarget !== null) {
2626
+ this.setSlice(null);
2627
+ return;
2628
+ }
2629
+ const r = this.sliceRange;
2630
+ this.setSlice(this.lastSliceY ?? Math.round(r.min + (r.max - r.min) * 0.25));
2631
+ }
2632
+ /** Push slice state to the shader + scene: clip uniform, ambient floor, and
2633
+ * the void floor's presence. Also called on (re)load to seed a fresh shader. */
2634
+ applySlice() {
2635
+ if (!this.shader) return;
2636
+ this.shader.uniforms["uClipY"].value = this.sliceActive ? this.sliceCurrent : 1e9;
2637
+ if (this.sliceActive && !this.slicePlane) {
2638
+ this.slicePlane = this.buildSlicePlane();
2639
+ this.scene.add(this.slicePlane);
2640
+ } else if (!this.sliceActive && this.slicePlane) {
2641
+ this.scene.remove(this.slicePlane);
2642
+ this.slicePlane.geometry.dispose();
2643
+ this.slicePlane.material.dispose();
2644
+ this.slicePlane = null;
2645
+ }
2646
+ this.applyLight();
2647
+ }
2648
+ /** The "unexplored rock" floor under a sliced world: a huge dark plane at
2649
+ * the world's bottom, so solid ground reads as solid where no cave is
2650
+ * exposed (instead of sky bleeding through the planet). Carries a faint
2651
+ * 16-block chunk grid for scale and shares the terrain's fog uniforms so
2652
+ * its distance haze matches. Follows the camera focus each frame. */
2653
+ buildSlicePlane() {
2654
+ const t = this.shader.uniforms;
2655
+ const mat = new THREE2.ShaderMaterial({
2656
+ glslVersion: THREE2.GLSL3,
2657
+ uniforms: {
2658
+ uFogColor: t["uFogColor"],
2659
+ uFog: t["uFog"],
2660
+ uFogCenter: t["uFogCenter"],
2661
+ uFogRadial: t["uFogRadial"],
2662
+ uFogDensity: t["uFogDensity"]
2663
+ },
2664
+ vertexShader: (
2665
+ /* glsl */
2666
+ `
2667
+ out vec2 vXZ;
2668
+ out float vViewZ;
2669
+ void main() {
2670
+ vec4 wp = modelMatrix * vec4(position, 1.0);
2671
+ vXZ = wp.xz;
2672
+ vec4 mv = viewMatrix * wp;
2673
+ vViewZ = -mv.z;
2674
+ gl_Position = projectionMatrix * mv;
2675
+ }
2676
+ `
2677
+ ),
2678
+ fragmentShader: (
2679
+ /* glsl */
2680
+ `
2681
+ precision highp float;
2682
+ uniform vec3 uFogColor;
2683
+ uniform vec2 uFog;
2684
+ uniform vec2 uFogCenter;
2685
+ uniform float uFogRadial;
2686
+ uniform float uFogDensity;
2687
+ in vec2 vXZ;
2688
+ in float vViewZ;
2689
+ out vec4 frag;
2690
+ void main() {
2691
+ // A faint 16-block chunk grid, antialiased via screen-space
2692
+ // derivatives and faded with the fog so it never shimmers.
2693
+ vec2 cell = vXZ / 16.0;
2694
+ vec2 q = abs(fract(cell) - 0.5);
2695
+ vec2 w = max(fwidth(cell), vec2(1e-5));
2696
+ vec2 d = (0.5 - q) / w;
2697
+ float g = 1.0 - smoothstep(0.8, 2.2, min(d.x, d.y));
2698
+ // Radial fog must be computed HERE, not in the vertex shader: this
2699
+ // plane is two screen-covering triangles, and distance() is not
2700
+ // affine \u2014 interpolating it from far-away corners fogs the whole
2701
+ // interior solid. The view-depth term IS affine, so it interpolates
2702
+ // exactly as a varying.
2703
+ float fogd = mix(vViewZ, distance(vXZ, uFogCenter), uFogRadial);
2704
+ float f = smoothstep(uFog.x, uFog.y, fogd) * uFogDensity;
2705
+ // Authored sRGB, straight to the canvas (like the sky dome).
2706
+ vec3 c = mix(vec3(0.055, 0.06, 0.075), vec3(0.115, 0.125, 0.155), g * (1.0 - f));
2707
+ frag = vec4(mix(c, uFogColor, f), 1.0);
2708
+ }
2709
+ `
2710
+ )
2711
+ });
2712
+ const mesh = new THREE2.Mesh(new THREE2.PlaneGeometry(1, 1), mat);
2713
+ mesh.rotation.x = -Math.PI / 2;
2714
+ mesh.scale.setScalar(4e5);
2715
+ mesh.frustumCulled = false;
2716
+ return mesh;
2717
+ }
2718
+ /** Install the terrain-follow height source, wrapped so the controls' pivot
2719
+ * never rides the (now invisible) surface above an open depth slice —
2720
+ * zooming in descends to the exposed cave level instead of stopping at the
2721
+ * clipped-away hilltops. */
2722
+ setHeightSampler(base) {
2723
+ this.controls.heightAt = base ? (x, z) => {
2724
+ const h = base(x, z);
2725
+ if (h == null || this.sliceTarget == null) return h;
2726
+ return Math.min(h, this.sliceTarget);
2727
+ } : null;
2476
2728
  }
2477
2729
  // --- display fidelity ------------------------------------------------------
2478
2730
  /** The current live display fidelity (sharpness, colour grade, fog, scale). */
@@ -2491,10 +2743,14 @@ var VantageViewer = class _VantageViewer {
2491
2743
  }
2492
2744
  }
2493
2745
  /** devicePixelRatio × renderScale, capped by maxPixelRatio (and a hard 4 so a
2494
- * fat-fingered scale can't allocate a giant framebuffer). */
2746
+ * fat-fingered scale can't allocate a giant framebuffer). Floored at 0.25:
2747
+ * a hidden/headless window can report devicePixelRatio 0, which would
2748
+ * otherwise zero the framebuffer and break screenshot() and the first
2749
+ * visible frame. */
2495
2750
  targetPixelRatio() {
2496
- const want = window.devicePixelRatio * this.display.renderScale;
2497
- return Math.min(want, this.options.maxPixelRatio * Math.max(1, this.display.renderScale), 4);
2751
+ const dpr = window.devicePixelRatio || 1;
2752
+ const want = dpr * this.display.renderScale;
2753
+ return Math.max(0.25, Math.min(want, this.options.maxPixelRatio * Math.max(1, this.display.renderScale), 4));
2498
2754
  }
2499
2755
  applyDisplay() {
2500
2756
  if (!this.shader) return;
@@ -2504,6 +2760,7 @@ var VantageViewer = class _VantageViewer {
2504
2760
  this.shader.uniforms["uSaturation"].value = d.saturation;
2505
2761
  this.shader.uniforms["uContrast"].value = d.contrast;
2506
2762
  this.shader.uniforms["uFogDensity"].value = d.fog;
2763
+ this.needsRender = true;
2507
2764
  }
2508
2765
  // --- streaming -------------------------------------------------------------
2509
2766
  /** The current streaming settings (view distance, tile budget, concurrency). */
@@ -2523,22 +2780,26 @@ var VantageViewer = class _VantageViewer {
2523
2780
  if (!this.tiles) return;
2524
2781
  this.tiles.configure(settings);
2525
2782
  this.applyViewLimits();
2783
+ this.needsRender = true;
2526
2784
  }
2527
2785
  // --- URL-hash deep links ----------------------------------------------------
2528
- /** The current view serialized as a `#@x,y,z,dist,rot,tilt` hash fragment —
2529
- * paste-able into any URL serving the same world. */
2786
+ /** The current view serialized as a `#@x,y,z,dist,rot,tilt[,sliceY]` hash
2787
+ * fragment — paste-able into any URL serving the same world. The trailing
2788
+ * component appears only while the cave view is open, so those deep links
2789
+ * reopen sliced at the same depth. */
2530
2790
  getViewHash() {
2531
2791
  const p = this.controls.position;
2532
2792
  const r1 = (v) => Math.round(v * 10) / 10;
2533
2793
  const r3 = (v) => Math.round(v * 1e3) / 1e3;
2534
- return `#@${r1(p.x)},${r1(p.y)},${r1(p.z)},${r1(this.controls.distance)},${r3(this.controls.rotation)},${r3(this.controls.angle)}`;
2794
+ const slice = this.sliceTarget !== null ? `,${r1(this.sliceTarget)}` : "";
2795
+ return `#@${r1(p.x)},${r1(p.y)},${r1(p.z)},${r1(this.controls.distance)},${r3(this.controls.rotation)},${r3(this.controls.angle)}${slice}`;
2535
2796
  }
2536
- /** Apply a `#@x,y,z,dist,rot,tilt` hash to the camera (leading `#` optional).
2537
- * Returns whether the hash parsed. */
2797
+ /** Apply a `#@x,y,z,dist,rot,tilt[,sliceY]` hash to the camera (leading `#`
2798
+ * optional). Returns whether the hash parsed. */
2538
2799
  applyViewHash(hash) {
2539
- const m = /^#?@(-?[\d.]+),(-?[\d.]+),(-?[\d.]+),([\d.]+),(-?[\d.]+),(-?[\d.]+)$/.exec(hash);
2800
+ const m = /^#?@(-?[\d.]+),(-?[\d.]+),(-?[\d.]+),([\d.]+),(-?[\d.]+),(-?[\d.]+)(?:,(-?[\d.]+))?$/.exec(hash);
2540
2801
  if (!m) return false;
2541
- const [x, y, z, distance, rotation, angle] = m.slice(1).map(Number);
2802
+ const [x, y, z, distance, rotation, angle] = m.slice(1, 7).map(Number);
2542
2803
  if (![x, y, z, distance, rotation, angle].every(Number.isFinite)) return false;
2543
2804
  this.controls.setView({
2544
2805
  position: new THREE2.Vector3(x, y, z),
@@ -2547,15 +2808,15 @@ var VantageViewer = class _VantageViewer {
2547
2808
  angle,
2548
2809
  floorY: y
2549
2810
  });
2811
+ const slice = m[7] !== void 0 ? Number(m[7]) : null;
2812
+ this.setSlice(Number.isFinite(slice) ? slice : null);
2813
+ this.needsRender = true;
2550
2814
  return true;
2551
2815
  }
2552
2816
  /** Debounced camera→hash sync plus hashchange→camera (pasted links apply
2553
2817
  * live). `history.replaceState` avoids history spam and hashchange echo. */
2554
2818
  bindUrlState() {
2555
- const onChange = () => {
2556
- if (this.hashTimer !== null) clearTimeout(this.hashTimer);
2557
- this.hashTimer = setTimeout(() => this.writeHash(), 250);
2558
- };
2819
+ const onChange = () => this.queueHashWrite();
2559
2820
  this.controls.addEventListener("change", onChange);
2560
2821
  const onHash = () => {
2561
2822
  if (window.location.hash === this.lastWrittenHash) return;
@@ -2569,6 +2830,12 @@ var VantageViewer = class _VantageViewer {
2569
2830
  this.hashTimer = null;
2570
2831
  };
2571
2832
  }
2833
+ /** Debounce a hash write — camera motion and slice changes funnel here. */
2834
+ queueHashWrite() {
2835
+ if (!this.options.urlState) return;
2836
+ if (this.hashTimer !== null) clearTimeout(this.hashTimer);
2837
+ this.hashTimer = setTimeout(() => this.writeHash(), 250);
2838
+ }
2572
2839
  writeHash() {
2573
2840
  const hash = this.getViewHash();
2574
2841
  if (hash === this.lastWrittenHash) return;
@@ -2615,6 +2882,7 @@ var VantageViewer = class _VantageViewer {
2615
2882
  if (this.controls.flyMode === on) return;
2616
2883
  this.controls.setMode(on ? "fly" : "map");
2617
2884
  if (on) this.emitHover(-1);
2885
+ this.needsRender = true;
2618
2886
  this.emitter.emit("mode", { fly: on });
2619
2887
  }
2620
2888
  /** Toggle free-flight on/off. */
@@ -2680,31 +2948,76 @@ var VantageViewer = class _VantageViewer {
2680
2948
  this.raycaster.setFromCamera(this.ndc, this.camera);
2681
2949
  this.emitHover(pickBiome(this.raycaster.ray, surface, this.bounds));
2682
2950
  }
2951
+ /** Request a redraw on the next animation frame. The viewer invalidates
2952
+ * itself for everything it owns (camera motion, tile streaming, settings,
2953
+ * the biome layer); call this only if you mutate the scene from outside. */
2954
+ invalidate() {
2955
+ this.needsRender = true;
2956
+ }
2957
+ /** Idle animation cadence (ms). Water/lava bake at a 2-tick frametime
2958
+ * (100 ms), so a 10 fps tick steps them at exactly their authored rate. */
2959
+ static ANIM_TICK_MS = 100;
2683
2960
  frame() {
2684
2961
  const now = performance.now();
2685
2962
  const dtMs = this.lastFrameMs ? now - this.lastFrameMs : 16.7;
2686
2963
  this.lastFrameMs = now;
2687
- this.controls.update(dtMs);
2688
- this.sky.position.copy(this.camera.position);
2964
+ if (this.controls.update(dtMs)) this.needsRender = true;
2689
2965
  if (this.tiles) {
2690
2966
  const focus = this.controls.flyMode ? this.camera.position : this.controls.position;
2691
2967
  this.tiles.update(focus.x, focus.z);
2968
+ if (this.tiles.fading) this.needsRender = true;
2692
2969
  if (this.shader) this.shader.uniforms["uFogCenter"].value.set(focus.x, focus.z);
2693
2970
  }
2694
- if (this.shader) {
2971
+ if (this.shader && this.mixCurrent !== this.mixTarget) {
2695
2972
  this.mixCurrent += (this.mixTarget - this.mixCurrent) * 0.2;
2696
2973
  if (Math.abs(this.mixCurrent - this.mixTarget) < 15e-4) this.mixCurrent = this.mixTarget;
2697
2974
  this.shader.uniforms["uBiomeMix"].value = this.mixCurrent;
2698
- this.shader.uniforms["uTime"].value = now / 1e3 % 3600;
2975
+ this.needsRender = true;
2976
+ }
2977
+ if (this.sliceActive && this.shader) {
2978
+ const goal = this.sliceTarget ?? this.sliceRange.max + 24;
2979
+ if (this.sliceCurrent !== goal) {
2980
+ this.sliceCurrent += (goal - this.sliceCurrent) * (1 - Math.exp(-dtMs / 110));
2981
+ if (Math.abs(this.sliceCurrent - goal) < 0.05) this.sliceCurrent = goal;
2982
+ this.needsRender = true;
2983
+ }
2984
+ if (this.sliceTarget === null && this.sliceCurrent === goal) {
2985
+ this.sliceActive = false;
2986
+ this.applySlice();
2987
+ } else {
2988
+ this.shader.uniforms["uClipY"].value = this.sliceCurrent;
2989
+ if (this.slicePlane) {
2990
+ const focus = this.controls.flyMode ? this.camera.position : this.controls.position;
2991
+ this.slicePlane.position.set(focus.x, this.sliceRange.min - 0.4, focus.z);
2992
+ }
2993
+ }
2699
2994
  }
2700
2995
  this.pickHover();
2996
+ if (this.hasAnims && now - this.lastRenderMs >= _VantageViewer.ANIM_TICK_MS) this.needsRender = true;
2997
+ if (!this.options.renderOnDemand) this.needsRender = true;
2998
+ if (!this.needsRender) return;
2999
+ this.needsRender = false;
3000
+ this.lastRenderMs = now;
3001
+ this.draw(now);
3002
+ }
3003
+ draw(now) {
3004
+ this.sky.position.copy(this.camera.position);
3005
+ if (this.shader) this.shader.uniforms["uTime"].value = now / 1e3 % 3600;
2701
3006
  this.renderer.setRenderTarget(this.msaa);
2702
3007
  this.renderer.clear();
2703
3008
  this.renderer.render(this.scene, this.camera);
2704
3009
  this.renderer.setRenderTarget(null);
2705
3010
  this.renderer.render(this.present, this.presentCamera);
2706
3011
  }
3012
+ /** Draw a fresh frame and return the canvas as a PNG data URL, for a
3013
+ * screenshot button / download link. Draws synchronously first because the
3014
+ * default framebuffer is not preserved between the on-demand renders. */
3015
+ screenshot() {
3016
+ this.draw(performance.now());
3017
+ return this.renderer.domElement.toDataURL("image/png");
3018
+ }
2707
3019
  resize() {
3020
+ this.needsRender = true;
2708
3021
  const w = this.container.clientWidth || window.innerWidth;
2709
3022
  const h = this.container.clientHeight || window.innerHeight;
2710
3023
  this.camera.aspect = w / h;
@@ -2715,6 +3028,14 @@ var VantageViewer = class _VantageViewer {
2715
3028
  this.msaa.setSize(Math.max(1, size.x), Math.max(1, size.y));
2716
3029
  }
2717
3030
  disposeCurrent() {
3031
+ if (this.slicePlane) {
3032
+ this.scene.remove(this.slicePlane);
3033
+ this.slicePlane.geometry.dispose();
3034
+ this.slicePlane.material.dispose();
3035
+ this.slicePlane = null;
3036
+ }
3037
+ this.sliceTarget = null;
3038
+ this.sliceActive = false;
2718
3039
  if (this.current) {
2719
3040
  for (const mesh of [this.current.terrain, this.current.water]) {
2720
3041
  if (!mesh) continue;