@thoughts-on-things/vantage-mc 0.2.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-TC3HQWAD.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];
@@ -18,10 +18,20 @@ var VERT = (
18
18
  in vec4 anrm;
19
19
  uniform vec3 uPosMin;
20
20
  uniform vec3 uPosScale;
21
+ uniform float uUvScale; // texture units per stored uv step (1 = f32 VTL6,
22
+ // 1/128 = VTL7's i16 fixed point); set per mesh
21
23
  uniform sampler2D uPalette;
22
24
  #else
23
25
  in vec3 abcol;
24
26
  in float alight; // packed (sky<<4)|block, 0..255
27
+ #endif
28
+ #ifdef LIGHTMAP
29
+ // Atlas-lit geometry (VTL8's greedy tail): baked light + AO come from a
30
+ // per-tile texture sampled in the fragment shader \u2014 per-BLOCK gradients on
31
+ // arbitrarily large merged quads \u2014 instead of per-vertex values.
32
+ in vec2 almuv; // half-texel atlas coords
33
+ uniform vec2 uLmSize; // atlas dims in texels
34
+ out vec2 vLmUv;
25
35
  #endif
26
36
  uniform vec2 uFogCenter; // streaming focus (world XZ)
27
37
  uniform float uFogRadial; // 1 = fog by XZ distance from
@@ -35,18 +45,20 @@ var VERT = (
35
45
  out float vFog;
36
46
  out float vSky; // saved sky light, 0..1
37
47
  out float vBlk; // saved block light, 0..1
48
+ out float vWorldY; // world-space Y, for the depth slice
38
49
  void main() {
39
- vUv = uv;
40
50
  vTint = atint;
41
51
  vLayer = alayer;
42
52
  vBiome = abiome;
43
53
  #ifdef QUANTIZED
54
+ vUv = uv * uUvScale;
44
55
  vec3 pos = uPosMin + position * uPosScale;
45
56
  vec3 nrm = anrm.xyz;
46
57
  // The light byte was stored as the int8 normal's 4th lane; undo the sign.
47
58
  float light = anrm.w < 0.0 ? anrm.w + 256.0 : anrm.w;
48
59
  vBcol = texelFetch(uPalette, ivec2(int(abiome + 0.5), 0), 0).rgb;
49
60
  #else
61
+ vUv = uv;
50
62
  vec3 pos = position;
51
63
  vec3 nrm = normal;
52
64
  float light = alight;
@@ -55,12 +67,16 @@ var VERT = (
55
67
  float sky = floor(light / 16.0);
56
68
  vSky = sky / 15.0;
57
69
  vBlk = (light - sky * 16.0) / 15.0;
70
+ #ifdef LIGHTMAP
71
+ vLmUv = almuv * 0.5 / uLmSize;
72
+ #endif
58
73
  // Water surface waves come from real mesh geometry (Minecraft flowing-water
59
74
  // heights, baked in the mesher) \u2014 the normal here carries the slope, so the
60
75
  // waves catch light. No vertex animation \u2014 motion comes from the animated
61
76
  // texture frames (see the fragment shader's uAnim/uTime).
62
77
  vN = normalize(mat3(modelMatrix) * nrm);
63
78
  vec4 wp = modelMatrix * vec4(pos, 1.0);
79
+ vWorldY = wp.y;
64
80
  vec4 mv = viewMatrix * wp;
65
81
  // Streamed worlds fog by horizontal distance from the streaming focus \u2014
66
82
  // exactly the ring where tiles stop \u2014 so looking straight down from any
@@ -93,6 +109,12 @@ var FRAG = (
93
109
  uniform float uSaturation; // colour saturation (1 = neutral)
94
110
  uniform float uContrast; // colour contrast around mid grey (1 = neutral)
95
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.
96
118
  in vec2 vUv;
97
119
  in vec4 vTint;
98
120
  in vec3 vBcol;
@@ -102,6 +124,11 @@ var FRAG = (
102
124
  in float vFog;
103
125
  in float vSky;
104
126
  in float vBlk;
127
+ in float vWorldY;
128
+ #ifdef LIGHTMAP
129
+ uniform sampler2D uLightmap; // per-tile baked light+AO atlas
130
+ in vec2 vLmUv;
131
+ #endif
105
132
  out vec4 frag;
106
133
  const vec3 SKY = vec3(0.62, 0.72, 0.88); // hemispheric sky ambient
107
134
  const vec3 GND = vec3(0.34, 0.31, 0.27); // hemispheric ground ambient
@@ -111,16 +138,16 @@ var FRAG = (
111
138
  // Baked sky+block light -> a (brightness, colour) pair. Effective level is the
112
139
  // brighter of (sky * daylight) and block light, eased and floored so caves read
113
140
  // on a map; block-lit areas pick up a warm cast that sunlit ones don't.
114
- void bakedLight(out float amt, out vec3 col) {
115
- float sky = vSky * uDay;
116
- float lvl = max(sky, vBlk);
141
+ void bakedLight(float skyIn, float blkIn, out float amt, out vec3 col) {
142
+ float sky = skyIn * uDay;
143
+ float lvl = max(sky, blkIn);
117
144
  // Minecraft's exact lightmap curve: brightness = l / (4 - 3l) (LightTexture).
118
145
  // Concave \u2014 far darker in the midtones than a smoothstep (a light-7 nook is
119
146
  // ~0.18, not ~0.5). Surface terrain is full skylight (l=1 \u2192 1.0); the curve
120
147
  // only deepens shaded overhangs and caves, matching the game.
121
148
  float curve = lvl / (4.0 - 3.0 * lvl);
122
149
  amt = mix(uAmbient, 1.0, curve);
123
- col = mix(vec3(1.0), TORCH, 0.6 * clamp(vBlk - sky, 0.0, 1.0));
150
+ col = mix(vec3(1.0), TORCH, 0.6 * clamp(blkIn - sky, 0.0, 1.0));
124
151
  }
125
152
 
126
153
  // Pixel-art textures + the colour uniforms are authored in sRGB; decode to
@@ -156,8 +183,24 @@ var FRAG = (
156
183
  }
157
184
 
158
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;
190
+ // Light + AO source: per-vertex (interpolated), or \u2014 for atlas-lit
191
+ // geometry \u2014 the tile lightmap, whose bilinear filter reproduces the
192
+ // per-block-corner values exactly and keeps gradients inside big quads.
193
+ float skyL = vSky;
194
+ float blkL = vBlk;
195
+ float aoV = vTint.a;
196
+ #ifdef LIGHTMAP
197
+ vec3 lmS = texture(uLightmap, vLmUv).rgb;
198
+ skyL = lmS.r;
199
+ blkL = lmS.g;
200
+ aoV = lmS.b;
201
+ #endif
159
202
  float lightAmt; vec3 lightCol;
160
- bakedLight(lightAmt, lightCol);
203
+ bakedLight(skyL, blkL, lightAmt, lightCol);
161
204
  // Animated textures (water, lava, magma, kelp, \u2026): the LUT row for this
162
205
  // base layer holds the baked frame count and frametime; frames occupy the
163
206
  // consecutive layers after the base, so playback is base + wrap(frame).
@@ -202,11 +245,11 @@ var FRAG = (
202
245
  vec3 wlit = grade(wcol * (0.62 + 0.28 * SUN * ndl2) * lightAmt * lightCol * uExposure);
203
246
  float wf = smoothstep(uFog.x, uFog.y, vFog) * uFogDensity;
204
247
  float wa = mix(0.5, 0.74, depth); // blue tint, seabed still reads through
205
- frag = vec4(toSRGB(mix(wlit, fogCol, wf)), wa);
248
+ frag = vec4(toSRGB(mix(wlit, fogCol, wf)), wa * uFade);
206
249
  return;
207
250
  }
208
251
 
209
- float ao = 1.0 - (1.0 - vTint.a) * uAoStrength; // baked AO (colour alpha), strength-scaled
252
+ float ao = 1.0 - (1.0 - aoV) * uAoStrength; // baked AO, strength-scaled
210
253
  vec3 texcol = t.rgb * toLinear(vTint.rgb);
211
254
  float luma = dot(texcol, vec3(0.299, 0.587, 0.114));
212
255
  // Biome view keeps terrain relief by modulating the flat biome colour by luma.
@@ -224,8 +267,13 @@ var FRAG = (
224
267
  vec3 hemi = mix(GND, SKY, 0.5 + 0.5 * N.y);
225
268
  vec3 shade = mix(vec3(1.0), hemi, 0.16) * fshade;
226
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);
227
275
  float f = smoothstep(uFog.x, uFog.y, vFog) * uFogDensity; // aerial depth into the horizon
228
- 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)
229
277
  }
230
278
  `
231
279
  );
@@ -286,6 +334,11 @@ function createTerrainMaterial(texData, opts = {}) {
286
334
  // (quantized path only; inert otherwise).
287
335
  uPosMin: { value: new THREE2.Vector3() },
288
336
  uPosScale: { value: new THREE2.Vector3(1, 1, 1) },
337
+ uUvScale: { value: 1 },
338
+ // Per-tile lightmap atlas, set per-mesh (used by the LIGHTMAP sibling
339
+ // material — see createLightmappedMaterial; inert here).
340
+ uLightmap: { value: null },
341
+ uLmSize: { value: new THREE2.Vector2(1, 1) },
289
342
  uPalette: { value: opts.quantized ? paletteTexture(opts.palette ?? []) : null },
290
343
  uFogCenter: { value: new THREE2.Vector2() },
291
344
  // streaming focus (world XZ)
@@ -313,8 +366,12 @@ function createTerrainMaterial(texData, opts = {}) {
313
366
  // colour saturation (1 = neutral)
314
367
  uContrast: { value: 1 },
315
368
  // colour contrast (1 = neutral)
316
- uFogDensity: { value: 1 }
369
+ uFogDensity: { value: 1 },
317
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
318
375
  },
319
376
  vertexShader: VERT,
320
377
  fragmentShader: FRAG,
@@ -326,6 +383,18 @@ function createTerrainMaterial(texData, opts = {}) {
326
383
  alphaToCoverage: true
327
384
  });
328
385
  }
386
+ function createLightmappedMaterial(terrain) {
387
+ const u = {};
388
+ for (const k in terrain.uniforms) u[k] = terrain.uniforms[k];
389
+ return new THREE2.ShaderMaterial({
390
+ glslVersion: THREE2.GLSL3,
391
+ defines: { ...terrain.defines, LIGHTMAP: "" },
392
+ uniforms: u,
393
+ vertexShader: VERT,
394
+ fragmentShader: FRAG,
395
+ alphaToCoverage: true
396
+ });
397
+ }
329
398
  function createWaterMaterial(terrain) {
330
399
  const u = {};
331
400
  for (const k in terrain.uniforms) u[k] = terrain.uniforms[k];
@@ -353,7 +422,11 @@ function createLowresMaterial(terrain) {
353
422
  uFogDensity: t["uFogDensity"],
354
423
  uExposure: t["uExposure"],
355
424
  uSaturation: t["uSaturation"],
356
- 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 }
357
430
  },
358
431
  vertexShader: (
359
432
  /* glsl */
@@ -363,9 +436,11 @@ function createLowresMaterial(terrain) {
363
436
  uniform float uFogRadial;
364
437
  out vec3 vCol;
365
438
  out float vFog;
439
+ out float vWorldY;
366
440
  void main() {
367
441
  vCol = acol;
368
442
  vec4 wp = modelMatrix * vec4(position, 1.0);
443
+ vWorldY = wp.y;
369
444
  vec4 mv = viewMatrix * wp;
370
445
  vFog = mix(-mv.z, distance(wp.xz, uFogCenter), uFogRadial);
371
446
  gl_Position = projectionMatrix * mv;
@@ -382,8 +457,11 @@ function createLowresMaterial(terrain) {
382
457
  uniform float uExposure;
383
458
  uniform float uSaturation;
384
459
  uniform float uContrast;
460
+ uniform float uClipY;
461
+ uniform float uFade;
385
462
  in vec3 vCol;
386
463
  in float vFog;
464
+ in float vWorldY;
387
465
  out vec4 frag;
388
466
  vec3 toLinear(vec3 c) {
389
467
  return mix(c / 12.92, pow((c + 0.055) / 1.055, vec3(2.4)), step(0.04045, c));
@@ -393,15 +471,21 @@ function createLowresMaterial(terrain) {
393
471
  return mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
394
472
  }
395
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;
396
477
  vec3 c = toLinear(vCol) * uExposure;
397
478
  float l = dot(c, vec3(0.299, 0.587, 0.114));
398
479
  c = mix(vec3(l), c, uSaturation);
399
480
  c = max((c - 0.5) * uContrast + 0.5, vec3(0.0));
400
481
  float f = smoothstep(uFog.x, uFog.y, vFog) * uFogDensity;
401
- frag = vec4(toSRGB(mix(c, toLinear(uFogColor), f)), 1.0);
482
+ frag = vec4(toSRGB(mix(c, toLinear(uFogColor), f)), uFade);
402
483
  }
403
484
  `
404
- )
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
405
489
  });
406
490
  }
407
491
  function createSky() {
@@ -474,6 +558,30 @@ function baseGeometry(section) {
474
558
  return geom;
475
559
  }
476
560
  var WATER_FALLBACK = [0.3, 0.5, 0.85];
561
+ function lightmapTexture(lm) {
562
+ const tex = new THREE2.DataTexture(lm.pixels, lm.width, lm.height, THREE2.RGBAFormat, THREE2.UnsignedByteType);
563
+ tex.magFilter = THREE2.LinearFilter;
564
+ tex.minFilter = THREE2.LinearFilter;
565
+ tex.wrapS = THREE2.ClampToEdgeWrapping;
566
+ tex.wrapT = THREE2.ClampToEdgeWrapping;
567
+ tex.generateMipmaps = false;
568
+ tex.needsUpdate = true;
569
+ return tex;
570
+ }
571
+ function sliceSection(sec, start, end) {
572
+ return {
573
+ ...sec,
574
+ vertexCount: end - start,
575
+ indexCount: (end - start) / 4 * 6,
576
+ positions: sec.positions.subarray(start * 3, end * 3),
577
+ uv: sec.uv.subarray(start * 2, end * 2),
578
+ colors: sec.colors.subarray(start * 4, end * 4),
579
+ normals: sec.normals.subarray(start * 4, end * 4),
580
+ layer: sec.layer.subarray(start, end),
581
+ biome: sec.biome.subarray(start, end),
582
+ indices: null
583
+ };
584
+ }
477
585
  function buildTileMeshes(tile, palette, material, waterMaterial) {
478
586
  const geom = baseGeometry(tile);
479
587
  applyTexturedAttributes(geom, tile, palette, WATER_FALLBACK);
@@ -496,15 +604,41 @@ function quantizedBox(sec) {
496
604
  const [sx, sy, sz] = sec.posScale;
497
605
  return new THREE2.Box3(new THREE2.Vector3(mx, my, mz), new THREE2.Vector3(mx + 65535 * sx, my + 65535 * sy, mz + 65535 * sz));
498
606
  }
499
- function quantizedMesh(sec, material) {
607
+ var sharedQuadIndexAttr = null;
608
+ function sharedQuadIndex(vertexCount) {
609
+ const needed = vertexCount / 4 * 6;
610
+ if (!sharedQuadIndexAttr || sharedQuadIndexAttr.count < needed) {
611
+ const verts = Math.ceil(vertexCount * (sharedQuadIndexAttr ? 1.5 : 1) / 4) * 4;
612
+ const out = new Uint32Array(verts / 4 * 6);
613
+ for (let b = 0, o = 0; b < verts; b += 4) {
614
+ out[o++] = b;
615
+ out[o++] = b + 1;
616
+ out[o++] = b + 2;
617
+ out[o++] = b;
618
+ out[o++] = b + 2;
619
+ out[o++] = b + 3;
620
+ }
621
+ sharedQuadIndexAttr = new THREE2.BufferAttribute(out, 1);
622
+ }
623
+ return sharedQuadIndexAttr;
624
+ }
625
+ function isSharedQuadIndex(attr) {
626
+ return attr !== null && attr === sharedQuadIndexAttr;
627
+ }
628
+ function quantizedMesh(sec, material, lm) {
500
629
  const geom = new THREE2.BufferGeometry();
501
630
  geom.setAttribute("position", new THREE2.BufferAttribute(sec.positions, 3, false));
502
631
  geom.setAttribute("anrm", new THREE2.BufferAttribute(sec.normals, 4, false));
503
- geom.setAttribute("uv", new THREE2.BufferAttribute(sec.uv, 2));
632
+ geom.setAttribute("uv", new THREE2.BufferAttribute(sec.uv, 2, false));
504
633
  geom.setAttribute("atint", new THREE2.BufferAttribute(sec.colors, 4, true));
505
634
  geom.setAttribute("alayer", new THREE2.BufferAttribute(sec.layer, 1, false));
506
635
  geom.setAttribute("abiome", new THREE2.BufferAttribute(sec.biome, 1, false));
507
- geom.setIndex(new THREE2.BufferAttribute(sec.indices, 1));
636
+ if (sec.indices) {
637
+ geom.setIndex(new THREE2.BufferAttribute(sec.indices, 1));
638
+ } else {
639
+ geom.setIndex(sharedQuadIndex(sec.vertexCount));
640
+ geom.setDrawRange(0, sec.indexCount);
641
+ }
508
642
  const box = quantizedBox(sec);
509
643
  geom.boundingBox = box;
510
644
  const sphere = new THREE2.Sphere();
@@ -513,24 +647,43 @@ function quantizedMesh(sec, material) {
513
647
  const mesh = new THREE2.Mesh(geom, material);
514
648
  const posMin = new THREE2.Vector3(...sec.posMin);
515
649
  const posScale = new THREE2.Vector3(...sec.posScale);
650
+ const uvScale = sec.uvScale;
516
651
  mesh.onBeforeRender = (_r, _s, _c, _g, mat) => {
517
652
  const m = mat;
518
653
  m.uniforms["uPosMin"].value.copy(posMin);
519
654
  m.uniforms["uPosScale"].value.copy(posScale);
655
+ m.uniforms["uUvScale"].value = uvScale;
656
+ if (lm) {
657
+ m.uniforms["uLightmap"].value = lm.tex;
658
+ m.uniforms["uLmSize"].value.copy(lm.size);
659
+ }
520
660
  m.uniformsNeedUpdate = true;
521
661
  };
522
662
  return mesh;
523
663
  }
524
- function buildQuantizedTileMeshes(tile, material, waterMaterial) {
525
- const terrain = quantizedMesh(tile.solid, material);
664
+ function buildQuantizedTileMeshes(tile, material, waterMaterial, lmMaterial) {
665
+ const solid = tile.solid;
666
+ const lmStart = solid.lmStart ?? solid.vertexCount;
667
+ const hasLm = tile.lightmap !== void 0 && lmMaterial !== void 0 && lmStart < solid.vertexCount;
668
+ const head = hasLm ? sliceSection(solid, 0, lmStart) : solid;
669
+ const terrain = quantizedMesh(head, material);
526
670
  const bounds = terrain.geometry.boundingBox.clone();
671
+ let terrainLm;
672
+ let lightmapTex;
673
+ if (hasLm) {
674
+ const lm = tile.lightmap;
675
+ lightmapTex = lightmapTexture(lm);
676
+ const tail = sliceSection(solid, lmStart, solid.vertexCount);
677
+ terrainLm = quantizedMesh(tail, lmMaterial, { tex: lightmapTex, size: new THREE2.Vector2(lm.width, lm.height) });
678
+ terrainLm.geometry.setAttribute("almuv", new THREE2.BufferAttribute(solid.lmuv, 2, false));
679
+ }
527
680
  let water;
528
681
  if (tile.fluid.vertexCount > 0) {
529
682
  water = quantizedMesh(tile.fluid, waterMaterial);
530
683
  water.renderOrder = 1;
531
684
  bounds.union(water.geometry.boundingBox);
532
685
  }
533
- return { terrain, water, bounds };
686
+ return { terrain, terrainLm, lightmapTex, water, bounds };
534
687
  }
535
688
  function buildTerrain(tile, texData) {
536
689
  const palette = biomePalette(tile.biomeNames?.length ?? 1);
@@ -636,11 +789,12 @@ function releaseAfterUpload(geom) {
636
789
  for (const name of Object.keys(geom.attributes)) {
637
790
  geom.getAttribute(name).onUpload(release);
638
791
  }
639
- if (geom.index) geom.index.onUpload(release);
792
+ if (geom.index && !isSharedQuadIndex(geom.index)) geom.index.onUpload(release);
640
793
  }
641
- var TileManager = class {
794
+ var TileManager = class _TileManager {
642
795
  opts;
643
796
  lowresMaterial;
797
+ lmMaterial;
644
798
  index = /* @__PURE__ */ new Map();
645
799
  records = /* @__PURE__ */ new Map();
646
800
  emitter = new Emitter();
@@ -651,6 +805,8 @@ var TileManager = class {
651
805
  lowIndex = /* @__PURE__ */ new Map();
652
806
  /** Set when residency changed and lowres visibility needs recomputing. */
653
807
  coverageDirty = false;
808
+ /** Tiles mid stream-in fade; drained by update(), keeps the viewer drawing. */
809
+ fadingKeys = /* @__PURE__ */ new Set();
654
810
  queue = [];
655
811
  /** Built tiles awaiting scene insertion — flushed ONE per update() call so
656
812
  * multi-MB GPU uploads never pile into a single frame. */
@@ -669,7 +825,7 @@ var TileManager = class {
669
825
  minY = 0;
670
826
  maxY = 320;
671
827
  constructor(options) {
672
- const { lowresMaterial, ...rest } = options;
828
+ const { lowresMaterial, lmMaterial, ...rest } = options;
673
829
  this.opts = {
674
830
  viewDistance: 768,
675
831
  // Sized to fill the whole view-distance disc for 128-block tiles
@@ -680,7 +836,9 @@ var TileManager = class {
680
836
  ...rest
681
837
  };
682
838
  this.lowresMaterial = lowresMaterial ?? null;
839
+ this.lmMaterial = lmMaterial ?? null;
683
840
  this.tileBlocks = options.manifest.tileBlocks;
841
+ if (options.manifest.maxSectionVerts) sharedQuadIndex(options.manifest.maxSectionVerts);
684
842
  for (const t of options.manifest.tiles) this.index.set(tileKey(t.x, t.z), t);
685
843
  this.lowLevels = this.lowresMaterial ? [...options.manifest.lowres?.levels ?? []].sort((a, b) => a.level - b.level) : [];
686
844
  for (const lvl of this.lowLevels) {
@@ -711,6 +869,16 @@ var TileManager = class {
711
869
  if (this.disposed) return;
712
870
  this.flushOne();
713
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
+ }
714
882
  if (this.coverageDirty) this.applyCoverage();
715
883
  const moved = Math.hypot(focusX - this.lastFocusX, focusZ - this.lastFocusZ);
716
884
  if (moved < this.tileBlocks / 4) {
@@ -783,7 +951,10 @@ var TileManager = class {
783
951
  const rec = this.records.get(key);
784
952
  if (!rec || rec.state !== "built") continue;
785
953
  rec.state = "ready";
954
+ rec.fadeStart = performance.now();
955
+ this.fadingKeys.add(key);
786
956
  this.opts.scene.add(rec.terrain);
957
+ if (rec.terrainLm) this.opts.scene.add(rec.terrainLm);
787
958
  if (rec.water) this.opts.scene.add(rec.water);
788
959
  this.coverageDirty = true;
789
960
  this.invalidate();
@@ -791,6 +962,28 @@ var TileManager = class {
791
962
  budget--;
792
963
  }
793
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
+ }
794
987
  /**
795
988
  * Hide every lowres tile whose footprint is fully SHOWN by finer data.
796
989
  * "Shown" is transitive, computed bottom-up: a hires tile shows its area by
@@ -808,8 +1001,8 @@ var TileManager = class {
808
1001
  applyCoverage() {
809
1002
  this.coverageDirty = false;
810
1003
  let shown = /* @__PURE__ */ new Set();
811
- for (const rec of this.records.values()) {
812
- 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));
813
1006
  }
814
1007
  let finerIndex = this.index;
815
1008
  for (const lvl of this.lowLevels) {
@@ -867,6 +1060,7 @@ var TileManager = class {
867
1060
  mesh.renderOrder = -level;
868
1061
  releaseAfterUpload(mesh.geometry);
869
1062
  rec.terrain = mesh;
1063
+ this.attachFade(rec, mesh);
870
1064
  rec.low = {
871
1065
  originX: tile.originX,
872
1066
  originZ: tile.originZ,
@@ -929,7 +1123,7 @@ var TileManager = class {
929
1123
  if (q) {
930
1124
  rec.biomes = summarizeSurfaceBiomes(q.surface, q.biomeNames, this.opts.palette);
931
1125
  rec.surface = { ...q.surface, biome: q.surface.biome.slice(), height: q.surface.height.slice() };
932
- meshes = buildQuantizedTileMeshes(q, this.opts.material, this.opts.waterMaterial);
1126
+ meshes = buildQuantizedTileMeshes(q, this.opts.material, this.opts.waterMaterial, this.lmMaterial ?? void 0);
933
1127
  rec.vertexCount = q.solid.vertexCount + q.fluid.vertexCount;
934
1128
  rec.triangleCount = (q.solid.indexCount + q.fluid.indexCount) / 3;
935
1129
  } else {
@@ -943,9 +1137,13 @@ var TileManager = class {
943
1137
  rec.triangleCount = (tile.indexCount + (tile.fluid?.indexCount ?? 0)) / 3;
944
1138
  }
945
1139
  releaseAfterUpload(meshes.terrain.geometry);
1140
+ if (meshes.terrainLm) releaseAfterUpload(meshes.terrainLm.geometry);
946
1141
  if (meshes.water) releaseAfterUpload(meshes.water.geometry);
947
1142
  rec.terrain = meshes.terrain;
1143
+ rec.terrainLm = meshes.terrainLm;
1144
+ rec.lightmapTex = meshes.lightmapTex;
948
1145
  rec.water = meshes.water;
1146
+ this.attachFade(rec, meshes.terrain, meshes.terrainLm, meshes.water);
949
1147
  this.minY = Math.min(this.minY, meshes.bounds.min.y);
950
1148
  this.maxY = Math.max(this.maxY, meshes.bounds.max.y);
951
1149
  rec.state = "built";
@@ -965,13 +1163,16 @@ var TileManager = class {
965
1163
  }
966
1164
  unload(key, rec) {
967
1165
  rec.abort?.abort();
968
- for (const mesh of [rec.terrain, rec.water]) {
1166
+ for (const mesh of [rec.terrain, rec.terrainLm, rec.water]) {
969
1167
  if (!mesh) continue;
970
1168
  this.opts.scene.remove(mesh);
1169
+ if (isSharedQuadIndex(mesh.geometry.index)) mesh.geometry.setIndex(null);
971
1170
  mesh.geometry.dispose();
972
1171
  }
1172
+ rec.lightmapTex?.dispose();
973
1173
  this.records.delete(key);
974
1174
  this.failCounts.delete(key);
1175
+ this.fadingKeys.delete(key);
975
1176
  this.coverageDirty = true;
976
1177
  this.invalidate();
977
1178
  this.emitter.emit("change", this.stats);
@@ -1947,6 +2148,18 @@ var VantageViewer = class _VantageViewer {
1947
2148
  highlight = null;
1948
2149
  mixTarget = 0;
1949
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;
1950
2163
  // Live lighting appearance (applied to the shader on load and on change).
1951
2164
  light = { ...DEFAULT_LIGHT };
1952
2165
  // Live display fidelity (shader uniforms + render scale).
@@ -1961,6 +2174,15 @@ var VantageViewer = class _VantageViewer {
1961
2174
  // sentinel distinct from -1 (off-terrain)
1962
2175
  // Last-frame timestamp, for frame-rate-independent control inertia.
1963
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;
1964
2186
  // The framing the current tile loaded into, so the UI can re-home to it.
1965
2187
  framedState = null;
1966
2188
  // URL-hash deep links (urlState option): debounce handle for hash writes and
@@ -1977,7 +2199,8 @@ var VantageViewer = class _VantageViewer {
1977
2199
  light: options.light ?? {},
1978
2200
  display: options.display ?? {},
1979
2201
  streaming: options.streaming ?? {},
1980
- urlState: options.urlState ?? false
2202
+ urlState: options.urlState ?? false,
2203
+ renderOnDemand: options.renderOnDemand ?? true
1981
2204
  };
1982
2205
  if (options.light) this.light = { ...this.light, ...options.light };
1983
2206
  if (options.display) this.display = { ...this.display, ...options.display };
@@ -2064,11 +2287,13 @@ var VantageViewer = class _VantageViewer {
2064
2287
  const shader = createTerrainMaterial(texData, { quantized: true, palette });
2065
2288
  const waterShader = createWaterMaterial(shader);
2066
2289
  shader.uniforms["uFogRadial"].value = 1;
2290
+ const lmShader = manifest.format >= 4 ? createLightmappedMaterial(shader) : void 0;
2067
2291
  const lowresShader = manifest.lowres ? createLowresMaterial(shader) : void 0;
2068
2292
  this.shader = shader;
2069
2293
  this.waterShader = waterShader;
2070
2294
  this.lowresShader = lowresShader ?? null;
2071
2295
  this.manifest = manifest;
2296
+ this.hasAnims = texData.anims.length > 0;
2072
2297
  this.tile = null;
2073
2298
  this.tiles = new TileManager({
2074
2299
  manifest,
@@ -2076,12 +2301,14 @@ var VantageViewer = class _VantageViewer {
2076
2301
  scene: this.scene,
2077
2302
  material: shader,
2078
2303
  waterMaterial: waterShader,
2304
+ ...lmShader ? { lmMaterial: lmShader } : {},
2079
2305
  ...lowresShader ? { lowresMaterial: lowresShader } : {},
2080
2306
  palette,
2081
2307
  ...this.options.streaming
2082
2308
  });
2083
- this.controls.heightAt = this.tiles.heightAt;
2309
+ this.setHeightSampler(this.tiles.heightAt);
2084
2310
  this.tilesUnsub = this.tiles.on("change", (stats) => {
2311
+ this.needsRender = true;
2085
2312
  this.emitter.emit("stats", stats);
2086
2313
  const now = performance.now();
2087
2314
  if (stats.loading === 0 || now - this.lastBiomesEmit > 500) {
@@ -2095,12 +2322,14 @@ var VantageViewer = class _VantageViewer {
2095
2322
  this.applyBiomeUniforms();
2096
2323
  this.applyLight();
2097
2324
  this.applyDisplay();
2325
+ this.applySlice();
2098
2326
  this.tiles.update(this.controls.position.x, this.controls.position.z);
2099
2327
  const size = new THREE2.Vector3();
2100
2328
  this.bounds.getSize(size);
2101
2329
  this._biomes = [];
2102
2330
  this.emitter.emit("load", {
2103
- magic: "VTL6",
2331
+ // Streamed worlds: the tile format follows the manifest schema version.
2332
+ magic: manifest.format >= 4 ? "VTL8" : manifest.format >= 3 ? "VTL7" : "VTL6",
2104
2333
  vertexCount: 0,
2105
2334
  triangleCount: 0,
2106
2335
  size,
@@ -2187,6 +2416,7 @@ var VantageViewer = class _VantageViewer {
2187
2416
  this.disposeCurrent();
2188
2417
  const built = buildTerrain(tile, textures);
2189
2418
  this.tile = tile;
2419
+ this.hasAnims = (textures?.anims.length ?? 0) > 0;
2190
2420
  this.shader = built.shader ?? null;
2191
2421
  this.bounds = built.bounds;
2192
2422
  this.scene.add(built.terrain);
@@ -2199,13 +2429,14 @@ var VantageViewer = class _VantageViewer {
2199
2429
  this.scene.add(hemi, sun);
2200
2430
  this.current.lights = [hemi, sun];
2201
2431
  }
2202
- this.controls.heightAt = makeHeightSampler(tile.surface);
2432
+ this.setHeightSampler(makeHeightSampler(tile.surface));
2203
2433
  this._biomes = summarizeBiomes(tile, built.palette);
2204
2434
  this.frameCamera(view);
2205
2435
  if (this.options.urlState) this.applyViewHash(window.location.hash);
2206
2436
  this.applyBiomeUniforms();
2207
2437
  this.applyLight();
2208
2438
  this.applyDisplay();
2439
+ this.applySlice();
2209
2440
  const size = new THREE2.Vector3();
2210
2441
  this.bounds.getSize(size);
2211
2442
  this.emitter.emit("load", {
@@ -2327,7 +2558,9 @@ var VantageViewer = class _VantageViewer {
2327
2558
  }
2328
2559
  applyBiomeUniforms() {
2329
2560
  if (!this.shader) return;
2561
+ this.shader.uniforms["uBiomeMix"].value = this.mixCurrent;
2330
2562
  this.shader.uniforms["uHi"].value = this.biomeEnabled && this.highlight !== null ? this.highlight : -1;
2563
+ this.needsRender = true;
2331
2564
  }
2332
2565
  // --- lighting appearance ---------------------------------------------------
2333
2566
  /** The current live lighting appearance. */
@@ -2342,9 +2575,156 @@ var VantageViewer = class _VantageViewer {
2342
2575
  }
2343
2576
  applyLight() {
2344
2577
  if (!this.shader) return;
2345
- 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;
2346
2580
  this.shader.uniforms["uDay"].value = this.light.daylight;
2347
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;
2348
2728
  }
2349
2729
  // --- display fidelity ------------------------------------------------------
2350
2730
  /** The current live display fidelity (sharpness, colour grade, fog, scale). */
@@ -2363,10 +2743,14 @@ var VantageViewer = class _VantageViewer {
2363
2743
  }
2364
2744
  }
2365
2745
  /** devicePixelRatio × renderScale, capped by maxPixelRatio (and a hard 4 so a
2366
- * 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. */
2367
2750
  targetPixelRatio() {
2368
- const want = window.devicePixelRatio * this.display.renderScale;
2369
- 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));
2370
2754
  }
2371
2755
  applyDisplay() {
2372
2756
  if (!this.shader) return;
@@ -2376,6 +2760,7 @@ var VantageViewer = class _VantageViewer {
2376
2760
  this.shader.uniforms["uSaturation"].value = d.saturation;
2377
2761
  this.shader.uniforms["uContrast"].value = d.contrast;
2378
2762
  this.shader.uniforms["uFogDensity"].value = d.fog;
2763
+ this.needsRender = true;
2379
2764
  }
2380
2765
  // --- streaming -------------------------------------------------------------
2381
2766
  /** The current streaming settings (view distance, tile budget, concurrency). */
@@ -2395,22 +2780,26 @@ var VantageViewer = class _VantageViewer {
2395
2780
  if (!this.tiles) return;
2396
2781
  this.tiles.configure(settings);
2397
2782
  this.applyViewLimits();
2783
+ this.needsRender = true;
2398
2784
  }
2399
2785
  // --- URL-hash deep links ----------------------------------------------------
2400
- /** The current view serialized as a `#@x,y,z,dist,rot,tilt` hash fragment —
2401
- * 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. */
2402
2790
  getViewHash() {
2403
2791
  const p = this.controls.position;
2404
2792
  const r1 = (v) => Math.round(v * 10) / 10;
2405
2793
  const r3 = (v) => Math.round(v * 1e3) / 1e3;
2406
- 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}`;
2407
2796
  }
2408
- /** Apply a `#@x,y,z,dist,rot,tilt` hash to the camera (leading `#` optional).
2409
- * 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. */
2410
2799
  applyViewHash(hash) {
2411
- const m = /^#?@(-?[\d.]+),(-?[\d.]+),(-?[\d.]+),([\d.]+),(-?[\d.]+),(-?[\d.]+)$/.exec(hash);
2800
+ const m = /^#?@(-?[\d.]+),(-?[\d.]+),(-?[\d.]+),([\d.]+),(-?[\d.]+),(-?[\d.]+)(?:,(-?[\d.]+))?$/.exec(hash);
2412
2801
  if (!m) return false;
2413
- 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);
2414
2803
  if (![x, y, z, distance, rotation, angle].every(Number.isFinite)) return false;
2415
2804
  this.controls.setView({
2416
2805
  position: new THREE2.Vector3(x, y, z),
@@ -2419,15 +2808,15 @@ var VantageViewer = class _VantageViewer {
2419
2808
  angle,
2420
2809
  floorY: y
2421
2810
  });
2811
+ const slice = m[7] !== void 0 ? Number(m[7]) : null;
2812
+ this.setSlice(Number.isFinite(slice) ? slice : null);
2813
+ this.needsRender = true;
2422
2814
  return true;
2423
2815
  }
2424
2816
  /** Debounced camera→hash sync plus hashchange→camera (pasted links apply
2425
2817
  * live). `history.replaceState` avoids history spam and hashchange echo. */
2426
2818
  bindUrlState() {
2427
- const onChange = () => {
2428
- if (this.hashTimer !== null) clearTimeout(this.hashTimer);
2429
- this.hashTimer = setTimeout(() => this.writeHash(), 250);
2430
- };
2819
+ const onChange = () => this.queueHashWrite();
2431
2820
  this.controls.addEventListener("change", onChange);
2432
2821
  const onHash = () => {
2433
2822
  if (window.location.hash === this.lastWrittenHash) return;
@@ -2441,6 +2830,12 @@ var VantageViewer = class _VantageViewer {
2441
2830
  this.hashTimer = null;
2442
2831
  };
2443
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
+ }
2444
2839
  writeHash() {
2445
2840
  const hash = this.getViewHash();
2446
2841
  if (hash === this.lastWrittenHash) return;
@@ -2487,6 +2882,7 @@ var VantageViewer = class _VantageViewer {
2487
2882
  if (this.controls.flyMode === on) return;
2488
2883
  this.controls.setMode(on ? "fly" : "map");
2489
2884
  if (on) this.emitHover(-1);
2885
+ this.needsRender = true;
2490
2886
  this.emitter.emit("mode", { fly: on });
2491
2887
  }
2492
2888
  /** Toggle free-flight on/off. */
@@ -2552,31 +2948,76 @@ var VantageViewer = class _VantageViewer {
2552
2948
  this.raycaster.setFromCamera(this.ndc, this.camera);
2553
2949
  this.emitHover(pickBiome(this.raycaster.ray, surface, this.bounds));
2554
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;
2555
2960
  frame() {
2556
2961
  const now = performance.now();
2557
2962
  const dtMs = this.lastFrameMs ? now - this.lastFrameMs : 16.7;
2558
2963
  this.lastFrameMs = now;
2559
- this.controls.update(dtMs);
2560
- this.sky.position.copy(this.camera.position);
2964
+ if (this.controls.update(dtMs)) this.needsRender = true;
2561
2965
  if (this.tiles) {
2562
2966
  const focus = this.controls.flyMode ? this.camera.position : this.controls.position;
2563
2967
  this.tiles.update(focus.x, focus.z);
2968
+ if (this.tiles.fading) this.needsRender = true;
2564
2969
  if (this.shader) this.shader.uniforms["uFogCenter"].value.set(focus.x, focus.z);
2565
2970
  }
2566
- if (this.shader) {
2971
+ if (this.shader && this.mixCurrent !== this.mixTarget) {
2567
2972
  this.mixCurrent += (this.mixTarget - this.mixCurrent) * 0.2;
2568
2973
  if (Math.abs(this.mixCurrent - this.mixTarget) < 15e-4) this.mixCurrent = this.mixTarget;
2569
2974
  this.shader.uniforms["uBiomeMix"].value = this.mixCurrent;
2570
- 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
+ }
2571
2994
  }
2572
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;
2573
3006
  this.renderer.setRenderTarget(this.msaa);
2574
3007
  this.renderer.clear();
2575
3008
  this.renderer.render(this.scene, this.camera);
2576
3009
  this.renderer.setRenderTarget(null);
2577
3010
  this.renderer.render(this.present, this.presentCamera);
2578
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
+ }
2579
3019
  resize() {
3020
+ this.needsRender = true;
2580
3021
  const w = this.container.clientWidth || window.innerWidth;
2581
3022
  const h = this.container.clientHeight || window.innerHeight;
2582
3023
  this.camera.aspect = w / h;
@@ -2587,6 +3028,14 @@ var VantageViewer = class _VantageViewer {
2587
3028
  this.msaa.setSize(Math.max(1, size.x), Math.max(1, size.y));
2588
3029
  }
2589
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;
2590
3039
  if (this.current) {
2591
3040
  for (const mesh of [this.current.terrain, this.current.water]) {
2592
3041
  if (!mesh) continue;