@thoughts-on-things/vantage-mc 0.6.0 → 0.7.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.
package/README.md CHANGED
@@ -64,6 +64,36 @@ pasting a new hash into the address bar pans there live. Pass
64
64
  `urlState={false}` if your page owns its hash (e.g. a router); the plain
65
65
  engine keeps it opt-in (`new VantageViewer(el, { urlState: true })`).
66
66
 
67
+ ### Authenticated multiplayer servers
68
+
69
+ To exercise this integration from a repository checkout, run
70
+ `just server-dev` at the repository root. It launches an authenticated
71
+ loopback sidecar and this demo together, with a fresh credential and coordinated
72
+ shutdown. `just server-smoke` performs a headless protocol and lazy-bake
73
+ preflight. These credentials are for the local walkthrough only.
74
+
75
+ Use a `WorldSource` when a launcher needs to attach its existing session to
76
+ the manifest and every streamed artifact. `worldFromHttp` supports a custom
77
+ native fetch transport and confines manifest paths to the same origin and
78
+ directory before attaching credentials:
79
+
80
+ ```ts
81
+ import { worldFromHttp } from '@thoughts-on-things/vantage-mc/core';
82
+ import { VantageViewer } from '@thoughts-on-things/vantage-mc/three';
83
+
84
+ const world = await worldFromHttp(
85
+ 'https://host.example/map-app/world/manifest.json',
86
+ { accessToken: sessionToken, fetch: nativeHttpFetch },
87
+ );
88
+ const viewer = await VantageViewer.mount('#app', { world });
89
+ ```
90
+
91
+ For a direct connection to protocol v1, use
92
+ `worldFromVantageServer('https://map.example/', { accessToken })`. Hosts with
93
+ their own player sessions should prefer an existing session-gated same-origin
94
+ proxy. See the [multiplayer server guide](../docs/server.md) for the trust
95
+ boundary and deployment contract.
96
+
67
97
  The viewer **renders on demand**: a frame draws only when something changed —
68
98
  camera motion, tiles streaming in, a setting — plus a gentle 10 fps tick while
69
99
  animated textures (water, lava) are on screen, so an idle map costs ~0 GPU/CPU
@@ -180,9 +210,11 @@ returns only the fields a given version carries (`textured`, `hasBiome`, `fluid`
180
210
 
181
211
  **`@thoughts-on-things/vantage-mc/core`** — `parseTile`, `parseTextureArray`, `parseManifest`,
182
212
  `parseLowresTile`, `maybeInflate`, `isGzip`, `tileKey`, `summarizeBiomes`,
183
- `biomePalette`, `stripNamespace`, `ByteReader`; types `DecodedTile`,
213
+ `biomePalette`, `stripNamespace`, `ByteReader`, `worldFromUrl`,
214
+ `worldFromHttp`, `worldFromVantageServer`; types `DecodedTile`,
184
215
  `MeshSection`, `SurfaceMap`, `DecodedTextureArray`, `WorldManifest`,
185
- `ManifestTile`, `LowresTile`, `BiomeEntry`, `Rgb`.
216
+ `ManifestTile`, `LowresTile`, `BiomeEntry`, `Rgb`, `WorldSource`,
217
+ `WorldConditionalFetch`, `HttpWorldOptions`, `VantageServerOptions`.
186
218
 
187
219
  **`@thoughts-on-things/vantage-mc/three`** — `buildTerrain`, `buildTileMeshes`,
188
220
  `buildQuantizedTileMeshes`, `buildLowresMesh`, `TileManager`,
@@ -241,6 +241,9 @@ interface ManifestTile {
241
241
  path: string;
242
242
  /** File size in bytes (gzip-wrapped on disk), for progress UI / budgeting. */
243
243
  bytes: number;
244
+ /** Opaque source revision. Continuous servers change this only when the
245
+ * region files that feed this tile (including its seam apron) change. */
246
+ revision?: string;
244
247
  }
245
248
  /** One lowres LOD level: the whole world at 1/2^level detail, in tiles of
246
249
  * `tileBlocks` blocks (each a fixed cell grid — see {@link WorldManifest.lowres}). */
@@ -285,9 +288,9 @@ interface WorldManifest {
285
288
  /** Biome display names indexed by the per-vertex biome id (0 = no data).
286
289
  * Globally consistent across every tile of the render. */
287
290
  biomes: string[];
288
- /** True while a progressive render is still baking: the manifest grows and
289
- * the viewer polls it, streaming new tiles in as they land. Absent/false in
290
- * a finished render. */
291
+ /** True while the viewer should poll this manifest. A progressive batch
292
+ * flips false when finished; a continuous server keeps it true so saved
293
+ * terrain can revise tiles in place. */
291
294
  rendering?: boolean;
292
295
  /** True for an on-demand live server (`vantage live`): every populated tile
293
296
  * is listed up front but baked lazily on first fetch. Implies `rendering`;
@@ -324,6 +327,13 @@ declare function parseManifest(data: unknown): WorldManifest;
324
327
  * `tiles/t.0.0.vtile`). Reject with an `AbortError`-named error if `signal`
325
328
  * fires mid-read. */
326
329
  type WorldFetch = (path: string, signal?: AbortSignal) => Promise<ArrayBuffer>;
330
+ /** Conditionally fetch a file: present the validator from the previous read
331
+ * and resolve `'unchanged'` when the source still has that exact content
332
+ * (an HTTP 304). Resolves the bytes plus their new validator otherwise. */
333
+ type WorldConditionalFetch = (path: string, etag: string | undefined, signal?: AbortSignal) => Promise<{
334
+ buffer: ArrayBuffer;
335
+ etag?: string;
336
+ } | 'unchanged'>;
327
337
  /** A tiled world render, wherever it lives. Pass one to the viewer's `world`
328
338
  * option (or build one with {@link worldFromUrl}, {@link worldFromDirectory},
329
339
  * or {@link worldFromFiles}). */
@@ -334,11 +344,42 @@ interface WorldSource {
334
344
  label: string;
335
345
  /** Fetch a file by manifest-relative path. */
336
346
  fetch: WorldFetch;
347
+ /** Optional validator-aware fetch. The viewer's manifest poll uses it when
348
+ * present so an unchanged continuous manifest costs a 304, not a body. */
349
+ fetchConditional?: WorldConditionalFetch;
350
+ }
351
+ /** Fetch implementation used by authenticated/native HTTP sources. Tauri and
352
+ * Electron hosts can pass their CORS-exempt fetch without coupling Vantage to
353
+ * a particular desktop runtime. */
354
+ type WorldHttpFetch = (input: string, init?: RequestInit) => Promise<Response>;
355
+ interface HttpWorldOptions {
356
+ /** Resolve a relative manifest URL outside a browser document. */
357
+ base?: string;
358
+ /** Bearer credential sent in the Authorization header, never in the URL. */
359
+ accessToken?: string;
360
+ /** Additional headers applied to the manifest and every artifact request. */
361
+ headers?: Readonly<Record<string, string>>;
362
+ /** Alternate fetch implementation (for example `@tauri-apps/plugin-http`). */
363
+ fetch?: WorldHttpFetch;
364
+ /** Safe human-facing source name. Defaults to the manifest URL. */
365
+ label?: string;
366
+ }
367
+ interface VantageServerOptions extends Omit<HttpWorldOptions, 'base'> {
368
+ /** Opaque server world id. The v1 sidecar exposes `default`. */
369
+ worldId?: string;
337
370
  }
338
371
  /** A world served over HTTP: fetches `manifest.json` at `url` and resolves
339
372
  * tile paths relative to it. This is what a plain string `world` option
340
373
  * turns into. */
341
374
  declare function worldFromUrl(url: string, base?: string): Promise<WorldSource>;
375
+ /** An HTTP world with optional bearer auth and a pluggable fetch transport.
376
+ * Manifest-owned paths are confined to the manifest directory before any
377
+ * credential is attached. */
378
+ declare function worldFromHttp(url: string, options?: HttpWorldOptions): Promise<WorldSource>;
379
+ /** Connect to the Vantage server protocol v1. This is the direct-server path
380
+ * for launchers; a host with its own player sessions can use
381
+ * {@link worldFromHttp} with a session-gated manifest URL instead. */
382
+ declare function worldFromVantageServer(endpoint: string, options?: VantageServerOptions): Promise<WorldSource>;
342
383
  /** A world in a local directory picked with the File System Access API
343
384
  * (`window.showDirectoryPicker()`, Chromium) — reads `manifest.json` from the
344
385
  * directory root and resolves tile paths through subdirectory handles on
@@ -393,4 +434,4 @@ declare function summarizeSurfaceBiomes(surface: SurfaceMap, names: string[], pa
393
434
  */
394
435
  declare function summarizeBiomes(tile: DecodedTile, palette?: Rgb[]): BiomeEntry[];
395
436
 
396
- export { type BiomeEntry as B, type DecodedTile as D, type Lightmap as L, type ManifestTile as M, type QuantizedTile as Q, type Rgb as R, type SurfaceMap as S, TEXTURE_MAGIC as T, UV_SCALE as U, type WorldFetch as W, type DecodedTextureArray as a, ByteReader as b, type LowresLevel as c, type MeshSection as d, type QuantizedSection as e, TILE_MAGIC as f, type TextureAnimation as g, type TileMagic as h, type WorldManifest as i, type WorldSource as j, biomePalette as k, canonicalQuadIndices as l, parseTextureArray as m, parseTile as n, parseTileQuantized as o, parseManifest as p, summarizeBiomes as q, summarizeSurfaceBiomes as r, stripNamespace as s, tileKey as t, worldFromFiles as u, worldFromUrl as v, worldFromDirectory as w };
437
+ export { worldFromVantageServer as A, type BiomeEntry as B, type DecodedTile as D, type HttpWorldOptions as H, type Lightmap as L, type ManifestTile as M, type QuantizedTile as Q, type Rgb as R, type SurfaceMap as S, TEXTURE_MAGIC as T, UV_SCALE as U, type VantageServerOptions as V, type WorldConditionalFetch as W, type DecodedTextureArray as a, ByteReader as b, type LowresLevel as c, type MeshSection as d, type QuantizedSection as e, TILE_MAGIC as f, type TextureAnimation as g, type TileMagic as h, type WorldFetch as i, type WorldHttpFetch as j, type WorldManifest as k, type WorldSource as l, biomePalette as m, canonicalQuadIndices as n, parseTextureArray as o, parseManifest as p, parseTile as q, parseTileQuantized as r, stripNamespace as s, summarizeBiomes as t, summarizeSurfaceBiomes as u, tileKey as v, worldFromDirectory as w, worldFromFiles as x, worldFromHttp as y, worldFromUrl as z };
@@ -1,4 +1,4 @@
1
- import { biomePalette, LOWRES_EMPTY, tileKey, parseLowresTile, maybeInflate, parseTileQuantized, summarizeSurfaceBiomes, parseTile, summarizeBiomes, worldFromUrl, parseManifest, parseTextureArray } from './chunk-EVPUXVSB.js';
1
+ import { biomePalette, LOWRES_EMPTY, tileKey, parseLowresTile, maybeInflate, parseTileQuantized, summarizeSurfaceBiomes, parseTile, summarizeBiomes, worldFromUrl, parseManifest, parseTextureArray } from './chunk-QQJHRHBC.js';
2
2
  import * as THREE2 from 'three';
3
3
 
4
4
  var SKY_TOP = [0.3, 0.52, 0.84];
@@ -1079,6 +1079,7 @@ var TileManager = class _TileManager {
1079
1079
  pump() {
1080
1080
  while (this.inFlight < this.opts.concurrency && this.inFlight + this.pendingBuilt < this.opts.concurrency && this.queue.length > 0) {
1081
1081
  const { ref, level } = this.queue.pop();
1082
+ if (level === 0 && this.index.get(tileKey(ref.x, ref.z)) !== ref) continue;
1082
1083
  if (level === 0) void this.loadTile(ref);
1083
1084
  else void this.loadLowres(ref, level);
1084
1085
  }
@@ -1175,21 +1176,49 @@ var TileManager = class _TileManager {
1175
1176
  * update(); already-known tiles are ignored. Returns whether anything was
1176
1177
  * added. */
1177
1178
  addTiles(tiles) {
1178
- let added = false;
1179
+ return this.reconcileTiles(tiles, false);
1180
+ }
1181
+ /** Reconcile the complete hires index from a continuous server manifest.
1182
+ * Revision changes evict only affected resident tiles; removed coordinates
1183
+ * disappear. Unchanged terrain remains on the GPU without a network fetch. */
1184
+ syncTiles(tiles) {
1185
+ return this.reconcileTiles(tiles, true);
1186
+ }
1187
+ reconcileTiles(tiles, prune) {
1188
+ let changed = false;
1189
+ const incoming = prune ? new Set(tiles.map((tile) => tileKey(tile.x, tile.z))) : null;
1190
+ if (incoming) {
1191
+ for (const [key] of this.index) {
1192
+ if (incoming.has(key)) continue;
1193
+ this.index.delete(key);
1194
+ const rec = this.records.get(key);
1195
+ if (rec) this.unload(key, rec);
1196
+ changed = true;
1197
+ }
1198
+ }
1179
1199
  for (const t of tiles) {
1180
1200
  const k = tileKey(t.x, t.z);
1181
- if (!this.index.has(k)) {
1201
+ const previous = this.index.get(k);
1202
+ if (!previous) {
1182
1203
  this.index.set(k, t);
1183
- added = true;
1204
+ changed = true;
1205
+ } else if (t.revision !== previous.revision) {
1206
+ this.index.set(k, t);
1207
+ const rec = this.records.get(k);
1208
+ if (rec) this.unload(k, rec);
1209
+ changed = true;
1210
+ } else {
1211
+ previous.path = t.path;
1212
+ previous.bytes = t.bytes;
1184
1213
  }
1185
1214
  }
1186
- if (added) {
1215
+ if (changed) {
1187
1216
  this.lastFocusX = Infinity;
1188
1217
  this.lastFocusZ = Infinity;
1189
1218
  this.invalidate();
1190
1219
  this.emitter.emit("change", this.stats);
1191
1220
  }
1192
- return added;
1221
+ return changed;
1193
1222
  }
1194
1223
  /** Install the lowres pyramid once a progressive render finishes (its earlier
1195
1224
  * manifests carried no lowres). No-op without a lowres material, or if a
@@ -1368,8 +1397,10 @@ var TileManager = class _TileManager {
1368
1397
  }
1369
1398
  }
1370
1399
  unload(key, rec) {
1400
+ const priorState = rec.state;
1401
+ rec.state = "empty";
1371
1402
  rec.abort?.abort();
1372
- if (rec.state === "built") this.pendingBuilt--;
1403
+ if (priorState === "built") this.pendingBuilt--;
1373
1404
  for (const mesh of [rec.terrain, rec.terrainLm, rec.water]) {
1374
1405
  if (!mesh) continue;
1375
1406
  this.opts.scene.remove(mesh);
@@ -2382,6 +2413,8 @@ var VantageViewer = class _VantageViewer {
2382
2413
  // world reloads (the poll checks its manager is still current).
2383
2414
  progressiveManager = null;
2384
2415
  lastTextureLayers = 0;
2416
+ /** Last progress payload emitted, for deduplication across identical polls. */
2417
+ lastProgress = null;
2385
2418
  /** An in-flight atlas re-fetch, so the tile-insert gate and the progressive
2386
2419
  * poll coalesce onto one request instead of racing separate fetches. */
2387
2420
  atlasRefresh = null;
@@ -2584,40 +2617,64 @@ var VantageViewer = class _VantageViewer {
2584
2617
  });
2585
2618
  if (manifest.rendering) {
2586
2619
  this.progressiveManager = this.tiles;
2620
+ this.lastProgress = null;
2587
2621
  this.emitProgress(manifest);
2588
2622
  void this.pollProgressive(source, this.tiles);
2589
2623
  }
2590
2624
  }
2591
2625
  /** Emit a `progress` event from a manifest (falling back to the tile count
2592
- * when the generator didn't include a `progress` block). */
2626
+ * when the generator didn't include a `progress` block). Deduplicated: a
2627
+ * continuous server reports the same numbers poll after poll, and repeating
2628
+ * them would tick every listener (React state, HUDs) for nothing. Returns
2629
+ * whether anything actually changed (and was emitted). */
2593
2630
  emitProgress(m) {
2594
- this.emitter.emit("progress", {
2631
+ const progress = {
2595
2632
  done: m.progress?.done ?? m.tiles.length,
2596
2633
  total: m.progress?.total ?? m.tiles.length,
2597
2634
  rendering: m.rendering ?? false
2598
- });
2635
+ };
2636
+ const last = this.lastProgress;
2637
+ if (last && last.done === progress.done && last.total === progress.total && last.rendering === progress.rendering) return false;
2638
+ this.lastProgress = progress;
2639
+ this.emitter.emit("progress", progress);
2640
+ return true;
2599
2641
  }
2600
2642
  /** Follow a live (`rendering: true`) render: re-fetch the manifest on an
2601
- * interval, stream newly-baked tiles in, widen the texture array when the
2602
- * atlas grows, and install the lowres pyramid once the bake completes. Runs
2603
- * until the render finishes or the world is replaced. */
2643
+ * interval, stream new/revised tiles in, widen the texture array when the
2644
+ * atlas grows, and install the lowres pyramid once a batch bake completes.
2645
+ * Continuous sources run until the world is replaced. */
2604
2646
  async pollProgressive(source, manager) {
2605
2647
  const dec = new TextDecoder();
2648
+ let delay = _VantageViewer.POLL_MS;
2649
+ let manifestEtag;
2606
2650
  for (; ; ) {
2607
- await new Promise((r) => setTimeout(r, 1200));
2651
+ await new Promise((r) => setTimeout(r, delay));
2608
2652
  if (this.tiles !== manager || this.progressiveManager !== manager) return;
2609
2653
  let m;
2610
2654
  try {
2611
- m = parseManifest(JSON.parse(dec.decode(await source.fetch("manifest.json"))));
2655
+ if (source.fetchConditional) {
2656
+ const res = await source.fetchConditional("manifest.json", manifestEtag);
2657
+ if (res === "unchanged") {
2658
+ delay = Math.min(delay * 2, _VantageViewer.POLL_MAX_MS);
2659
+ continue;
2660
+ }
2661
+ m = parseManifest(JSON.parse(dec.decode(res.buffer)));
2662
+ manifestEtag = res.etag;
2663
+ } else {
2664
+ m = parseManifest(JSON.parse(dec.decode(await source.fetch("manifest.json"))));
2665
+ }
2612
2666
  } catch {
2667
+ delay = Math.min(delay * 2, _VantageViewer.POLL_MAX_MS);
2613
2668
  continue;
2614
2669
  }
2615
- if ((m.textureLayers ?? 0) > this.lastTextureLayers) {
2670
+ const atlasGrew = (m.textureLayers ?? 0) > this.lastTextureLayers;
2671
+ if (atlasGrew) {
2616
2672
  await this.ensureAtlasLayers(source, m.textureLayers ?? 0);
2617
2673
  if (this.tiles !== manager) return;
2618
2674
  }
2619
- manager.addTiles(m.tiles);
2620
- this.emitProgress(m);
2675
+ const changed = m.dynamic ? manager.syncTiles(m.tiles) : manager.addTiles(m.tiles);
2676
+ const progressed = this.emitProgress(m);
2677
+ delay = !m.dynamic || changed || atlasGrew || progressed ? _VantageViewer.POLL_MS : Math.min(delay * 2, _VantageViewer.POLL_MAX_MS);
2621
2678
  if (!m.rendering) {
2622
2679
  this.manifest = m;
2623
2680
  if (m.lowres) manager.ingestLowres(m.lowres);
@@ -3288,6 +3345,11 @@ var VantageViewer = class _VantageViewer {
3288
3345
  /** Idle animation cadence (ms). Water/lava bake at a 2-tick frametime
3289
3346
  * (100 ms), so a 10 fps tick steps them at exactly their authored rate. */
3290
3347
  static ANIM_TICK_MS = 100;
3348
+ /** Manifest poll cadence (ms) while a render is streaming in. */
3349
+ static POLL_MS = 1200;
3350
+ /** Ceiling the poll cadence relaxes to while a continuous server reports no
3351
+ * changes — a saved world edit still shows up within ~one ceiling. */
3352
+ static POLL_MAX_MS = 5e3;
3291
3353
  frame() {
3292
3354
  const now = performance.now();
3293
3355
  const dtMs = this.lastFrameMs ? now - this.lastFrameMs : 16.7;
@@ -552,7 +552,17 @@ function parseManifest(data) {
552
552
  if (typeof o !== "object" || o === null || typeof o["x"] !== "number" || typeof o["z"] !== "number" || typeof o["path"] !== "string" || typeof o["bytes"] !== "number") {
553
553
  throw new Error(`vantage: manifest ${what} ${i} is malformed`);
554
554
  }
555
- return { x: o["x"], z: o["z"], path: o["path"], bytes: o["bytes"] };
555
+ const revision = o["revision"];
556
+ if (revision !== void 0 && (typeof revision !== "string" || revision.length === 0 || revision.length > 128)) {
557
+ throw new Error(`vantage: manifest ${what} ${i} has an invalid revision`);
558
+ }
559
+ return {
560
+ x: o["x"],
561
+ z: o["z"],
562
+ path: o["path"],
563
+ bytes: o["bytes"],
564
+ ...typeof revision === "string" ? { revision } : {}
565
+ };
556
566
  });
557
567
  const parsedTiles = parseTiles(tiles, "tile");
558
568
  let lowres;
@@ -619,22 +629,86 @@ function throwIfAborted(signal) {
619
629
  function normalizePath(path) {
620
630
  return path.startsWith("./") ? path.slice(2) : path;
621
631
  }
632
+ function safeRemotePath(path) {
633
+ const normalized = normalizePath(path);
634
+ if (normalized.length === 0 || normalized.length > 512 || !/^[A-Za-z0-9._/-]+$/.test(normalized)) {
635
+ throw new Error(`vantage: unsafe remote artifact path ${path}`);
636
+ }
637
+ const segments = normalized.split("/");
638
+ if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) {
639
+ throw new Error(`vantage: unsafe remote artifact path ${path}`);
640
+ }
641
+ return normalized;
642
+ }
622
643
  async function worldFromUrl(url, base) {
623
- const abs = new URL(url, base ?? (typeof document !== "undefined" ? document.baseURI : void 0)).toString();
624
- const res = await fetch(abs);
644
+ return worldFromHttp(url, { base });
645
+ }
646
+ async function worldFromHttp(url, options = {}) {
647
+ const abs = new URL(
648
+ url,
649
+ options.base ?? (typeof document !== "undefined" ? document.baseURI : void 0)
650
+ ).toString();
651
+ const manifestUrl = new URL(abs);
652
+ if (manifestUrl.protocol !== "http:" && manifestUrl.protocol !== "https:") {
653
+ throw new Error(`vantage: HTTP world requires an http(s) manifest URL`);
654
+ }
655
+ if (manifestUrl.username || manifestUrl.password) {
656
+ throw new Error(`vantage: HTTP world credentials belong in headers, not the manifest URL`);
657
+ }
658
+ const root = new URL(".", manifestUrl);
659
+ const http = options.fetch ?? ((input, init) => fetch(input, init));
660
+ const headers = {};
661
+ for (const [name, value] of Object.entries(options.headers ?? {})) headers[name.toLowerCase()] = value;
662
+ if (options.accessToken) headers["authorization"] = `Bearer ${options.accessToken}`;
663
+ const request = (target, signal, extra) => http(target, {
664
+ ...Object.keys(headers).length > 0 || extra ? { headers: { ...headers, ...extra } } : {},
665
+ ...signal ? { signal } : {}
666
+ });
667
+ const resolveTarget = (path) => {
668
+ const targetUrl = new URL(safeRemotePath(path), root);
669
+ if (targetUrl.origin !== root.origin || !targetUrl.pathname.startsWith(root.pathname)) {
670
+ throw new Error(`vantage: unsafe remote artifact path ${path}`);
671
+ }
672
+ return targetUrl.toString();
673
+ };
674
+ const res = await request(abs);
625
675
  if (!res.ok) throw new Error(`${res.status} ${res.statusText} for ${abs}`);
626
676
  const manifest = await res.json();
627
677
  return {
628
678
  manifest,
629
- label: abs,
679
+ label: options.label ?? abs,
630
680
  fetch: async (path, signal) => {
631
- const target = new URL(normalizePath(path), abs).toString();
632
- const r = await fetch(target, signal ? { signal } : void 0);
681
+ const target = resolveTarget(path);
682
+ const r = await request(target, signal);
633
683
  if (!r.ok) throw new Error(`${r.status} ${r.statusText} for ${target}`);
634
684
  return r.arrayBuffer();
685
+ },
686
+ fetchConditional: async (path, etag, signal) => {
687
+ const target = resolveTarget(path);
688
+ const r = await request(target, signal, etag ? { "if-none-match": etag } : void 0);
689
+ if (r.status === 304) return "unchanged";
690
+ if (!r.ok) throw new Error(`${r.status} ${r.statusText} for ${target}`);
691
+ const next = r.headers.get("etag");
692
+ return { buffer: await r.arrayBuffer(), ...next ? { etag: next } : {} };
635
693
  }
636
694
  };
637
695
  }
696
+ function worldFromVantageServer(endpoint, options = {}) {
697
+ const worldId = options.worldId ?? "default";
698
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(worldId)) throw new Error(`vantage: invalid server world id`);
699
+ const base = new URL(endpoint);
700
+ if (base.protocol !== "http:" && base.protocol !== "https:") {
701
+ throw new Error(`vantage: server endpoint must use http(s)`);
702
+ }
703
+ if (base.username || base.password) {
704
+ throw new Error(`vantage: server credentials belong in headers, not the endpoint URL`);
705
+ }
706
+ base.pathname = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
707
+ base.search = "";
708
+ base.hash = "";
709
+ const manifest = new URL(`v1/worlds/${encodeURIComponent(worldId)}/manifest.json`, base).toString();
710
+ return worldFromHttp(manifest, options);
711
+ }
638
712
  async function worldFromDirectory(dir) {
639
713
  const readFile = async (path, signal) => {
640
714
  throwIfAborted(signal);
@@ -810,4 +884,4 @@ function summarizeBiomes(tile, palette) {
810
884
  return toEntries(counts, names, pal);
811
885
  }
812
886
 
813
- export { ByteReader, LOWRES_EMPTY, LOWRES_MAGIC, TEXTURE_MAGIC, TILE_MAGIC, UV_SCALE, biomePalette, canonicalQuadIndices, isGzip, maybeInflate, parseLowresTile, parseManifest, parseTextureArray, parseTile, parseTileQuantized, stripNamespace, summarizeBiomes, summarizeSurfaceBiomes, tileKey, worldFromDirectory, worldFromFiles, worldFromUrl };
887
+ export { ByteReader, LOWRES_EMPTY, LOWRES_MAGIC, TEXTURE_MAGIC, TILE_MAGIC, UV_SCALE, biomePalette, canonicalQuadIndices, isGzip, maybeInflate, parseLowresTile, parseManifest, parseTextureArray, parseTile, parseTileQuantized, stripNamespace, summarizeBiomes, summarizeSurfaceBiomes, tileKey, worldFromDirectory, worldFromFiles, worldFromHttp, worldFromUrl, worldFromVantageServer };
@@ -1,4 +1,4 @@
1
- export { B as BiomeEntry, b as ByteReader, a as DecodedTextureArray, D as DecodedTile, L as Lightmap, c as LowresLevel, M as ManifestTile, d as MeshSection, e as QuantizedSection, Q as QuantizedTile, R as Rgb, S as SurfaceMap, T as TEXTURE_MAGIC, f as TILE_MAGIC, g as TextureAnimation, h as TileMagic, U as UV_SCALE, W as WorldFetch, i as WorldManifest, j as WorldSource, k as biomePalette, l as canonicalQuadIndices, p as parseManifest, m as parseTextureArray, n as parseTile, o as parseTileQuantized, s as stripNamespace, q as summarizeBiomes, r as summarizeSurfaceBiomes, t as tileKey, w as worldFromDirectory, u as worldFromFiles, v as worldFromUrl } from '../biome-NBWIY7dT.js';
1
+ export { B as BiomeEntry, b as ByteReader, a as DecodedTextureArray, D as DecodedTile, H as HttpWorldOptions, L as Lightmap, c as LowresLevel, M as ManifestTile, d as MeshSection, e as QuantizedSection, Q as QuantizedTile, R as Rgb, S as SurfaceMap, T as TEXTURE_MAGIC, f as TILE_MAGIC, g as TextureAnimation, h as TileMagic, U as UV_SCALE, V as VantageServerOptions, W as WorldConditionalFetch, i as WorldFetch, j as WorldHttpFetch, k as WorldManifest, l as WorldSource, m as biomePalette, n as canonicalQuadIndices, p as parseManifest, o as parseTextureArray, q as parseTile, r as parseTileQuantized, s as stripNamespace, t as summarizeBiomes, u as summarizeSurfaceBiomes, v as tileKey, w as worldFromDirectory, x as worldFromFiles, y as worldFromHttp, z as worldFromUrl, A as worldFromVantageServer } from '../biome-CelByWgf.js';
2
2
 
3
3
  declare const LOWRES_MAGIC = "VLR1";
4
4
  /** Height sentinel for samples with no terrain (unpopulated chunks). */
@@ -1 +1 @@
1
- export { ByteReader, LOWRES_EMPTY, LOWRES_MAGIC, TEXTURE_MAGIC, TILE_MAGIC, UV_SCALE, biomePalette, canonicalQuadIndices, isGzip, maybeInflate, parseLowresTile, parseManifest, parseTextureArray, parseTile, parseTileQuantized, stripNamespace, summarizeBiomes, summarizeSurfaceBiomes, tileKey, worldFromDirectory, worldFromFiles, worldFromUrl } from '../chunk-EVPUXVSB.js';
1
+ export { ByteReader, LOWRES_EMPTY, LOWRES_MAGIC, TEXTURE_MAGIC, TILE_MAGIC, UV_SCALE, biomePalette, canonicalQuadIndices, isGzip, maybeInflate, parseLowresTile, parseManifest, parseTextureArray, parseTile, parseTileQuantized, stripNamespace, summarizeBiomes, summarizeSurfaceBiomes, tileKey, worldFromDirectory, worldFromFiles, worldFromHttp, worldFromUrl, worldFromVantageServer } from '../chunk-QQJHRHBC.js';
@@ -1,9 +1,9 @@
1
1
  import * as react from 'react';
2
2
  import { CSSProperties, ReactNode } from 'react';
3
- import { j as WorldSource, B as BiomeEntry } from '../biome-NBWIY7dT.js';
4
- export { D as DecodedTile } from '../biome-NBWIY7dT.js';
5
- import { g as TileSource, T as TextureSource, S as StreamingSettings, k as ViewMode, L as LightSettings, a as DisplaySettings, d as TileInfo, i as VantageViewer$1 } from '../viewer-C5vYxrL1.js';
6
- export { D as DEFAULT_ORBIT_ANGLE, V as VANILLA_DISPLAY } from '../viewer-C5vYxrL1.js';
3
+ import { l as WorldSource, B as BiomeEntry } from '../biome-CelByWgf.js';
4
+ export { D as DecodedTile } from '../biome-CelByWgf.js';
5
+ import { g as TileSource, T as TextureSource, S as StreamingSettings, k as ViewMode, L as LightSettings, a as DisplaySettings, d as TileInfo, i as VantageViewer$1 } from '../viewer-DYu-AUUt.js';
6
+ export { D as DEFAULT_ORBIT_ANGLE, V as VANILLA_DISPLAY } from '../viewer-DYu-AUUt.js';
7
7
  import 'three';
8
8
 
9
9
  interface VantageViewerProps {
@@ -1,6 +1,6 @@
1
- import { VantageViewer, DEFAULT_ORBIT_ANGLE } from '../chunk-46RBFJ4D.js';
2
- export { DEFAULT_ORBIT_ANGLE, VANILLA_DISPLAY } from '../chunk-46RBFJ4D.js';
3
- import '../chunk-EVPUXVSB.js';
1
+ import { VantageViewer, DEFAULT_ORBIT_ANGLE } from '../chunk-F5RGBOVF.js';
2
+ export { DEFAULT_ORBIT_ANGLE, VANILLA_DISPLAY } from '../chunk-F5RGBOVF.js';
3
+ import '../chunk-QQJHRHBC.js';
4
4
  import { createContext, forwardRef, useRef, useState, useImperativeHandle, useEffect, useMemo, useContext } from 'react';
5
5
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
6
6
 
@@ -1,9 +1,9 @@
1
1
  import * as THREE from 'three';
2
- import { R as Rgb, Q as QuantizedTile, D as DecodedTile, a as DecodedTextureArray, S as SurfaceMap } from '../biome-NBWIY7dT.js';
3
- export { B as BiomeEntry, b as ByteReader, L as Lightmap, c as LowresLevel, M as ManifestTile, d as MeshSection, e as QuantizedSection, T as TEXTURE_MAGIC, f as TILE_MAGIC, g as TextureAnimation, h as TileMagic, U as UV_SCALE, W as WorldFetch, i as WorldManifest, j as WorldSource, k as biomePalette, l as canonicalQuadIndices, p as parseManifest, m as parseTextureArray, n as parseTile, o as parseTileQuantized, s as stripNamespace, q as summarizeBiomes, r as summarizeSurfaceBiomes, t as tileKey, w as worldFromDirectory, u as worldFromFiles, v as worldFromUrl } from '../biome-NBWIY7dT.js';
2
+ import { R as Rgb, Q as QuantizedTile, D as DecodedTile, a as DecodedTextureArray, S as SurfaceMap } from '../biome-CelByWgf.js';
3
+ export { B as BiomeEntry, b as ByteReader, H as HttpWorldOptions, L as Lightmap, c as LowresLevel, M as ManifestTile, d as MeshSection, e as QuantizedSection, T as TEXTURE_MAGIC, f as TILE_MAGIC, g as TextureAnimation, h as TileMagic, U as UV_SCALE, V as VantageServerOptions, W as WorldConditionalFetch, i as WorldFetch, j as WorldHttpFetch, k as WorldManifest, l as WorldSource, m as biomePalette, n as canonicalQuadIndices, p as parseManifest, o as parseTextureArray, q as parseTile, r as parseTileQuantized, s as stripNamespace, t as summarizeBiomes, u as summarizeSurfaceBiomes, v as tileKey, w as worldFromDirectory, x as worldFromFiles, y as worldFromHttp, z as worldFromUrl, A as worldFromVantageServer } from '../biome-CelByWgf.js';
4
4
  import { LowresTile } from '../core/index.js';
5
5
  export { LOWRES_EMPTY, LOWRES_MAGIC, isGzip, maybeInflate, parseLowresTile } from '../core/index.js';
6
- export { D as DEFAULT_ORBIT_ANGLE, a as DisplaySettings, H as HeightSampler, L as LightSettings, b as LoadOptions, M as MapControls, c as MapControlsOptions, S as StreamingSettings, T as TextureSource, d as TileInfo, e as TileManager, f as TileManagerOptions, g as TileSource, h as TileStats, V as VANILLA_DISPLAY, i as VantageViewer, j as VantageViewerOptions, k as ViewMode } from '../viewer-C5vYxrL1.js';
6
+ export { D as DEFAULT_ORBIT_ANGLE, a as DisplaySettings, H as HeightSampler, L as LightSettings, b as LoadOptions, M as MapControls, c as MapControlsOptions, S as StreamingSettings, T as TextureSource, d as TileInfo, e as TileManager, f as TileManagerOptions, g as TileSource, h as TileStats, V as VANILLA_DISPLAY, i as VantageViewer, j as VantageViewerOptions, k as ViewMode } from '../viewer-DYu-AUUt.js';
7
7
 
8
8
  /** The objects and metadata produced from a tile. */
9
9
  interface TerrainObjects {
@@ -1,2 +1,2 @@
1
- export { DEFAULT_ORBIT_ANGLE, MapControls, SKY_HORIZON, SKY_TOP, TileManager, VANILLA_DISPLAY, VantageViewer, buildLowresMesh, buildQuantizedTileMeshes, buildTerrain, buildTileMeshes, createLowresMaterial, createSky, createTerrainMaterial, createWaterMaterial, pickBiome } from '../chunk-46RBFJ4D.js';
2
- export { ByteReader, LOWRES_EMPTY, LOWRES_MAGIC, TEXTURE_MAGIC, TILE_MAGIC, UV_SCALE, biomePalette, canonicalQuadIndices, isGzip, maybeInflate, parseLowresTile, parseManifest, parseTextureArray, parseTile, parseTileQuantized, stripNamespace, summarizeBiomes, summarizeSurfaceBiomes, tileKey, worldFromDirectory, worldFromFiles, worldFromUrl } from '../chunk-EVPUXVSB.js';
1
+ export { DEFAULT_ORBIT_ANGLE, MapControls, SKY_HORIZON, SKY_TOP, TileManager, VANILLA_DISPLAY, VantageViewer, buildLowresMesh, buildQuantizedTileMeshes, buildTerrain, buildTileMeshes, createLowresMaterial, createSky, createTerrainMaterial, createWaterMaterial, pickBiome } from '../chunk-F5RGBOVF.js';
2
+ export { ByteReader, LOWRES_EMPTY, LOWRES_MAGIC, TEXTURE_MAGIC, TILE_MAGIC, UV_SCALE, biomePalette, canonicalQuadIndices, isGzip, maybeInflate, parseLowresTile, parseManifest, parseTextureArray, parseTile, parseTileQuantized, stripNamespace, summarizeBiomes, summarizeSurfaceBiomes, tileKey, worldFromDirectory, worldFromFiles, worldFromHttp, worldFromUrl, worldFromVantageServer } from '../chunk-QQJHRHBC.js';
@@ -1,5 +1,5 @@
1
1
  import * as THREE from 'three';
2
- import { i as WorldManifest, W as WorldFetch, R as Rgb, M as ManifestTile, c as LowresLevel, B as BiomeEntry, a as DecodedTextureArray, D as DecodedTile, j as WorldSource } from './biome-NBWIY7dT.js';
2
+ import { k as WorldManifest, i as WorldFetch, R as Rgb, M as ManifestTile, c as LowresLevel, B as BiomeEntry, a as DecodedTextureArray, D as DecodedTile, l as WorldSource } from './biome-CelByWgf.js';
3
3
 
4
4
  interface TileManagerOptions {
5
5
  manifest: WorldManifest;
@@ -157,6 +157,11 @@ declare class TileManager {
157
157
  * update(); already-known tiles are ignored. Returns whether anything was
158
158
  * added. */
159
159
  addTiles(tiles: ManifestTile[]): boolean;
160
+ /** Reconcile the complete hires index from a continuous server manifest.
161
+ * Revision changes evict only affected resident tiles; removed coordinates
162
+ * disappear. Unchanged terrain remains on the GPU without a network fetch. */
163
+ syncTiles(tiles: ManifestTile[]): boolean;
164
+ private reconcileTiles;
160
165
  /** Install the lowres pyramid once a progressive render finishes (its earlier
161
166
  * manifests carried no lowres). No-op without a lowres material, or if a
162
167
  * pyramid is already present. Forces a re-plan so the coarse rings stream in. */
@@ -536,8 +541,8 @@ interface ViewerEvents extends Record<string, unknown> {
536
541
  slice: {
537
542
  y: number | null;
538
543
  };
539
- /** Progressive render progress, while a live bake streams in. `done` reaches
540
- * `total` and `rendering` flips false on the final manifest. */
544
+ /** Progressive/live render progress. Finished batch renders flip false;
545
+ * continuous multiplayer sources keep rendering true for change polling. */
541
546
  progress: {
542
547
  done: number;
543
548
  total: number;
@@ -573,6 +578,8 @@ declare class VantageViewer {
573
578
  private lastBiomesEmit;
574
579
  private progressiveManager;
575
580
  private lastTextureLayers;
581
+ /** Last progress payload emitted, for deduplication across identical polls. */
582
+ private lastProgress;
576
583
  /** An in-flight atlas re-fetch, so the tile-insert gate and the progressive
577
584
  * poll coalesce onto one request instead of racing separate fetches. */
578
585
  private atlasRefresh;
@@ -617,12 +624,15 @@ declare class VantageViewer {
617
624
  * without ever holding more than the streaming budget in memory. */
618
625
  private loadWorld;
619
626
  /** Emit a `progress` event from a manifest (falling back to the tile count
620
- * when the generator didn't include a `progress` block). */
627
+ * when the generator didn't include a `progress` block). Deduplicated: a
628
+ * continuous server reports the same numbers poll after poll, and repeating
629
+ * them would tick every listener (React state, HUDs) for nothing. Returns
630
+ * whether anything actually changed (and was emitted). */
621
631
  private emitProgress;
622
632
  /** Follow a live (`rendering: true`) render: re-fetch the manifest on an
623
- * interval, stream newly-baked tiles in, widen the texture array when the
624
- * atlas grows, and install the lowres pyramid once the bake completes. Runs
625
- * until the render finishes or the world is replaced. */
633
+ * interval, stream new/revised tiles in, widen the texture array when the
634
+ * atlas grows, and install the lowres pyramid once a batch bake completes.
635
+ * Continuous sources run until the world is replaced. */
626
636
  private pollProgressive;
627
637
  /** Ensure the terrain atlas covers at least `layers` texture-array layers,
628
638
  * re-fetching `terrain.vtexarr` if it's behind. Coalesces concurrent callers
@@ -787,6 +797,11 @@ declare class VantageViewer {
787
797
  /** Idle animation cadence (ms). Water/lava bake at a 2-tick frametime
788
798
  * (100 ms), so a 10 fps tick steps them at exactly their authored rate. */
789
799
  private static readonly ANIM_TICK_MS;
800
+ /** Manifest poll cadence (ms) while a render is streaming in. */
801
+ private static readonly POLL_MS;
802
+ /** Ceiling the poll cadence relaxes to while a continuous server reports no
803
+ * changes — a saved world edit still shows up within ~one ceiling. */
804
+ private static readonly POLL_MAX_MS;
790
805
  private frame;
791
806
  private draw;
792
807
  /** Draw a fresh frame and return the canvas as a PNG data URL, for a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thoughts-on-things/vantage-mc",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Render a Minecraft (Java) world as a fast, beautiful 3D web map. The web frontend for the Vantage generator.",
5
5
  "type": "module",
6
6
  "license": "MIT",