@thoughts-on-things/vantage-mc 0.10.0 → 0.12.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
@@ -109,6 +109,40 @@ scene, or call `viewer.invalidate()` after mutating it externally.
109
109
  `viewer.screenshot()` returns the current view as a PNG data URL (`<MapNav>`
110
110
  has a button for it, next to its fullscreen toggle).
111
111
 
112
+ ### Every dimension
113
+
114
+ `vantage render` bakes the nether and the end alongside the overworld and
115
+ writes a `world.json` index next to them. Point the viewer at that instead of a
116
+ single manifest and it opens one dimension, offers the rest, and takes each
117
+ one's sky, fog and light floor from its manifest — so the nether arrives
118
+ crimson and lit by its lava, the end as pale islands over the void:
119
+
120
+ ```tsx
121
+ import { VantageViewer, DimensionPicker } from '@thoughts-on-things/vantage-mc/react';
122
+
123
+ <VantageViewer world="/world.json">
124
+ <DimensionPicker />
125
+ </VantageViewer>
126
+ ```
127
+
128
+ `<DimensionPicker>` renders nothing for a single-dimension world, so it is safe
129
+ to include unconditionally. The dimension is part of the deep link
130
+ (`#the_nether@x,y,z,…`), and each dimension remembers where its camera was.
131
+ Engine API: `viewer.dimensions`, `viewer.dimension`,
132
+ `await viewer.setDimension('the_nether')`, and a `'dimension'` event.
133
+
134
+ It behaves as a toolbar: Tab reaches the open dimension, `←`/`→` walk the row,
135
+ Enter switches (arrowing never triggers a load). `position` puts it in any
136
+ corner or the top centre — on phone-width screens it moves above the navigation
137
+ cluster rather than fighting the corner panels. Passing `className` lets you
138
+ re-home it entirely: the desktop app resets its position and drops its glass to
139
+ seat the row inside its own toolbar.
140
+
141
+ Every dimension directory is a complete render — its own manifest, tiles, LOD
142
+ pyramid and texture array — so `world="/the_nether/manifest.json"` also works,
143
+ and a viewer that only knows about `manifest.json` still gets the overworld at
144
+ the render root.
145
+
112
146
  Worlds baked with `vantage render --caves full` get the **cave view**: a
113
147
  depth slice that cuts the world at any Y. Toggle it with `C` or `<MapNav>`'s
114
148
  layers button, set the depth with the `<DepthSlider>` gauge, and share it —
@@ -267,6 +267,33 @@ interface LowresLevel {
267
267
  span: number;
268
268
  tiles: ManifestTile[];
269
269
  }
270
+ /** Which Minecraft dimension a render covers. `slug` is the render's
271
+ * sub-directory (`overworld` for the root) and the id used in deep links. */
272
+ interface ManifestDimension {
273
+ /** Resource id, e.g. `minecraft:the_nether`. */
274
+ id: string;
275
+ slug: string;
276
+ label: string;
277
+ kind: 'overworld' | 'nether' | 'end' | 'custom';
278
+ }
279
+ /** How a dimension should look: the sky dome gradient, the fog it fades into,
280
+ * and the light defaults that make it read like the game. The nether has no
281
+ * daylight to speak of and a crimson haze; the end is a pale void.
282
+ *
283
+ * Colours arrive in the manifest as sRGB 0..255 and are normalized on parse,
284
+ * so every triple below is 0..1 — what the renderer's colour setters take. */
285
+ interface ManifestAtmosphere {
286
+ /** Normalized sRGB, 0..1. */
287
+ skyTop: readonly [number, number, number];
288
+ /** Normalized sRGB, 0..1. */
289
+ skyHorizon: readonly [number, number, number];
290
+ /** Normalized sRGB, 0..1. */
291
+ fog: readonly [number, number, number];
292
+ /** Brightness floor at zero baked light (the viewer's `light.ambient`). */
293
+ ambient: number;
294
+ /** How much baked sky light counts (the viewer's `light.daylight`). */
295
+ daylight: number;
296
+ }
270
297
  /** A parsed `manifest.json` for a tiled world render. */
271
298
  interface WorldManifest {
272
299
  /** Manifest schema version (1 = hires tiles only, 2 adds `lowres`,
@@ -288,6 +315,12 @@ interface WorldManifest {
288
315
  y: number;
289
316
  z: number;
290
317
  };
318
+ /** Which dimension this render covers (absent in pre-dimension renders,
319
+ * which are always the overworld). */
320
+ dimension?: ManifestDimension;
321
+ /** The dimension's sky, fog and light defaults — applied on load unless the
322
+ * embedder passed its own `light` settings. */
323
+ atmosphere?: ManifestAtmosphere;
291
324
  /** True when the render kept full cave geometry (`--caves full`) — the
292
325
  * viewer's depth-slice cave view has real caves to reveal. */
293
326
  caves?: boolean;
@@ -335,6 +368,44 @@ declare function tileKey(x: number, z: number): string;
335
368
  */
336
369
  declare function parseManifest(data: unknown): WorldManifest;
337
370
 
371
+ /** One dimension of a rendered world. */
372
+ interface WorldDimension extends ManifestDimension {
373
+ /** This dimension's `manifest.json`, relative to `world.json`. */
374
+ manifest: string;
375
+ /** Hires tiles written for it (0 for a dimension that rendered empty). */
376
+ tiles: number;
377
+ /** Bytes on disk across its tiles and LOD pyramid. */
378
+ bytes: number;
379
+ /** Where the map opens: the world spawn mapped into this dimension. */
380
+ spawn?: {
381
+ x: number;
382
+ y: number;
383
+ z: number;
384
+ };
385
+ }
386
+ /** A parsed `world.json`. */
387
+ interface WorldIndex {
388
+ /** Index schema version (1 = the first). */
389
+ format: number;
390
+ dimensions: WorldDimension[];
391
+ }
392
+ /**
393
+ * Validate and type a fetched `world.json` value.
394
+ *
395
+ * @throws if the shape is not a Vantage world index this decoder understands.
396
+ */
397
+ declare function parseWorldIndex(data: unknown): WorldIndex;
398
+ /** Whether a fetched JSON value looks like a world index rather than a
399
+ * manifest — how the viewer accepts either URL in its `world` option. */
400
+ declare function isWorldIndex(data: unknown): boolean;
401
+ /** Resolve a dimension's manifest path against the index's own path, so
402
+ * `worlds/a/world.json` + `the_nether/manifest.json` reads as
403
+ * `worlds/a/the_nether/manifest.json`. */
404
+ declare function resolveManifestPath(indexPath: string, manifest: string): string;
405
+ /** Pick the dimension a viewer should open: the requested slug when it exists,
406
+ * else the overworld, else the first with any tiles, else the first listed. */
407
+ declare function pickDimension(index: WorldIndex, slug?: string | null): WorldDimension;
408
+
338
409
  /** Fetch one file of a world render by its manifest-relative path (e.g.
339
410
  * `tiles/t.0.0.vtile`). Reject with an `AbortError`-named error if `signal`
340
411
  * fires mid-read. */
@@ -392,17 +463,29 @@ declare function worldFromHttp(url: string, options?: HttpWorldOptions): Promise
392
463
  * for launchers; a host with its own player sessions can use
393
464
  * {@link worldFromHttp} with a session-gated manifest URL instead. */
394
465
  declare function worldFromVantageServer(endpoint: string, options?: VantageServerOptions): Promise<WorldSource>;
466
+ /**
467
+ * One dimension of a multi-dimension render, as its own world source.
468
+ *
469
+ * A render writes each dimension into its own sub-directory with a
470
+ * self-contained manifest, so switching dimensions is just re-rooting the paths
471
+ * — the same HTTP endpoint, directory handle or file list keeps serving them.
472
+ * `manifestPath` comes from `world.json` and is confined to the index's own
473
+ * directory by {@link parseWorldIndex}.
474
+ */
475
+ declare function worldFromIndexEntry(source: WorldSource, manifestPath: string): Promise<WorldSource>;
395
476
  /** A world in a local directory picked with the File System Access API
396
- * (`window.showDirectoryPicker()`, Chromium) — reads `manifest.json` from the
397
- * directory root and resolves tile paths through subdirectory handles on
398
- * demand, so nothing is read until it streams in. */
477
+ * (`window.showDirectoryPicker()`, Chromium) — reads `world.json` (or
478
+ * `manifest.json` for a single-dimension render) from the directory root and
479
+ * resolves tile paths through subdirectory handles on demand, so nothing is
480
+ * read until it streams in. */
399
481
  declare function worldFromDirectory(dir: FileSystemDirectoryHandle): Promise<WorldSource>;
400
482
  /** A world from a flat file list — `<input webkitdirectory>` or a drag-and-drop
401
483
  * walk (the fallback for browsers without `showDirectoryPicker`). Finds the
402
- * shallowest `manifest.json` and keys every file relative to its folder, so
403
- * picking a parent folder of the render also works. `pathOf` overrides how a
404
- * file's relative path is derived (default: `webkitRelativePath`, falling
405
- * back to `name`). */
484
+ * shallowest `world.json` (else the shallowest `manifest.json`) and keys every
485
+ * file relative to its folder, so picking a parent folder of the render also
486
+ * works, and a render carrying the nether and the end opens with all of them.
487
+ * `pathOf` overrides how a file's relative path is derived (default:
488
+ * `webkitRelativePath`, falling back to `name`). */
406
489
  declare function worldFromFiles(files: Iterable<File>, pathOf?: (file: File) => string): Promise<WorldSource>;
407
490
 
408
491
  /** An RGB triple in 0..1. */
@@ -446,4 +529,4 @@ declare function summarizeSurfaceBiomes(surface: SurfaceMap, names: string[], pa
446
529
  */
447
530
  declare function summarizeBiomes(tile: DecodedTile, palette?: Rgb[]): BiomeEntry[];
448
531
 
449
- 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 };
532
+ export { stripNamespace as A, type BiomeEntry as B, summarizeBiomes as C, type DecodedTile as D, summarizeSurfaceBiomes as E, tileKey as F, worldFromDirectory as G, type HttpWorldOptions as H, worldFromFiles as I, worldFromHttp as J, worldFromIndexEntry as K, type Lightmap as L, type ManifestAtmosphere as M, worldFromUrl as N, worldFromVantageServer as O, 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 ManifestDimension as d, type ManifestTile as e, type MeshSection as f, type QuantizedSection as g, TILE_MAGIC as h, type TextureAnimation as i, type TileMagic as j, type WorldDimension as k, type WorldFetch as l, type WorldHttpFetch as m, type WorldIndex as n, type WorldManifest as o, type WorldSource as p, biomePalette as q, canonicalQuadIndices as r, isWorldIndex as s, parseManifest as t, parseTextureArray as u, parseTile as v, parseTileQuantized as w, parseWorldIndex as x, pickDimension as y, resolveManifestPath as z };
@@ -547,6 +547,41 @@ function parseTextureArray(buffer) {
547
547
  function tileKey(x, z) {
548
548
  return `${x},${z}`;
549
549
  }
550
+ var DIMENSION_KINDS = /* @__PURE__ */ new Set(["overworld", "nether", "end", "custom"]);
551
+ var SLUG_RE = /^[a-z0-9._-]{1,64}$/;
552
+ function parseDimension(value) {
553
+ if (typeof value !== "object" || value === null) return void 0;
554
+ const o = value;
555
+ const { id, slug, label, kind } = o;
556
+ if (typeof id !== "string" || typeof slug !== "string" || !SLUG_RE.test(slug)) return void 0;
557
+ return {
558
+ id,
559
+ slug,
560
+ label: typeof label === "string" && label.length > 0 ? label : id,
561
+ kind: typeof kind === "string" && DIMENSION_KINDS.has(kind) ? kind : "custom"
562
+ };
563
+ }
564
+ function parseRgb(value) {
565
+ if (!Array.isArray(value) || value.length !== 3) return void 0;
566
+ if (!value.every((c) => typeof c === "number" && Number.isFinite(c))) return void 0;
567
+ return value.map((c) => Math.min(255, Math.max(0, c)) / 255);
568
+ }
569
+ function parseAtmosphere(value) {
570
+ if (typeof value !== "object" || value === null) return void 0;
571
+ const o = value;
572
+ const skyTop = parseRgb(o["skyTop"]);
573
+ const skyHorizon = parseRgb(o["skyHorizon"]);
574
+ const fog = parseRgb(o["fog"]);
575
+ if (!skyTop || !skyHorizon || !fog) return void 0;
576
+ const unit = (v, fallback) => typeof v === "number" && Number.isFinite(v) ? Math.min(1, Math.max(0, v)) : fallback;
577
+ return {
578
+ skyTop,
579
+ skyHorizon,
580
+ fog,
581
+ ambient: unit(o["ambient"], 0.12),
582
+ daylight: unit(o["daylight"], 1)
583
+ };
584
+ }
550
585
  function parseManifest(data) {
551
586
  if (typeof data !== "object" || data === null) throw new Error("vantage: manifest is not an object");
552
587
  const m = data;
@@ -618,6 +653,8 @@ function parseManifest(data) {
618
653
  if (typeof yr === "object" && yr !== null && typeof yr["min"] === "number" && typeof yr["max"] === "number" && yr["min"] < yr["max"]) {
619
654
  yRange = { min: yr["min"], max: yr["max"] };
620
655
  }
656
+ const dimension = parseDimension(m["dimension"]);
657
+ const atmosphere = parseAtmosphere(m["atmosphere"]);
621
658
  const maxSectionVerts = m["maxSectionVerts"];
622
659
  const textureLayers = m["textureLayers"];
623
660
  const pr = m["progress"];
@@ -633,6 +670,8 @@ function parseManifest(data) {
633
670
  ...m["dynamic"] === true ? { dynamic: true } : {},
634
671
  ...progress ? { progress } : {},
635
672
  ...spawn ? { spawn } : {},
673
+ ...dimension ? { dimension } : {},
674
+ ...atmosphere ? { atmosphere } : {},
636
675
  ...m["caves"] === true ? { caves: true } : {},
637
676
  ...yRange ? { yRange } : {},
638
677
  ...lowres ? { lowres } : {},
@@ -641,6 +680,59 @@ function parseManifest(data) {
641
680
  };
642
681
  }
643
682
 
683
+ // src/core/world.ts
684
+ var KINDS = /* @__PURE__ */ new Set(["overworld", "nether", "end", "custom"]);
685
+ var SLUG_RE2 = /^[a-z0-9._-]{1,64}$/;
686
+ var MANIFEST_RE = /^(?:[A-Za-z0-9._-]+\/)*manifest\.json$/;
687
+ function parseWorldIndex(data) {
688
+ if (typeof data !== "object" || data === null) throw new Error("vantage: world index is not an object");
689
+ const m = data;
690
+ const format = m["format"];
691
+ if (format !== 1) throw new Error(`vantage: unsupported world index format ${String(format)} (expected 1)`);
692
+ const list = m["dimensions"];
693
+ if (!Array.isArray(list) || list.length === 0) throw new Error("vantage: world index has no dimensions");
694
+ const dimensions = list.map((entry, i) => {
695
+ const o = entry;
696
+ if (typeof o !== "object" || o === null) throw new Error(`vantage: world index dimension ${i} is malformed`);
697
+ const { id, slug, label, kind, manifest, tiles, bytes } = o;
698
+ if (typeof id !== "string" || typeof slug !== "string" || !SLUG_RE2.test(slug)) {
699
+ throw new Error(`vantage: world index dimension ${i} has an invalid id/slug`);
700
+ }
701
+ if (typeof manifest !== "string" || manifest.includes("..") || !MANIFEST_RE.test(manifest)) {
702
+ throw new Error(`vantage: world index dimension ${i} has an invalid manifest path`);
703
+ }
704
+ const s = o["spawn"];
705
+ const coord = (v) => typeof v === "number" && Number.isFinite(v);
706
+ const spawn = typeof s === "object" && s !== null && coord(s["x"]) && coord(s["y"]) && coord(s["z"]) ? { x: s["x"], y: s["y"], z: s["z"] } : void 0;
707
+ return {
708
+ id,
709
+ slug,
710
+ label: typeof label === "string" && label.length > 0 ? label : id,
711
+ kind: typeof kind === "string" && KINDS.has(kind) ? kind : "custom",
712
+ manifest,
713
+ tiles: typeof tiles === "number" && Number.isFinite(tiles) && tiles >= 0 ? tiles : 0,
714
+ bytes: typeof bytes === "number" && Number.isFinite(bytes) && bytes >= 0 ? bytes : 0,
715
+ ...spawn ? { spawn } : {}
716
+ };
717
+ });
718
+ return { format, dimensions };
719
+ }
720
+ function isWorldIndex(data) {
721
+ return typeof data === "object" && data !== null && Array.isArray(data["dimensions"]);
722
+ }
723
+ function resolveManifestPath(indexPath, manifest) {
724
+ const slash = indexPath.lastIndexOf("/");
725
+ return slash < 0 ? manifest : `${indexPath.slice(0, slash + 1)}${manifest}`;
726
+ }
727
+ function pickDimension(index, slug) {
728
+ const dims = index.dimensions;
729
+ if (slug) {
730
+ const wanted = dims.find((d) => d.slug === slug || d.id === slug);
731
+ if (wanted) return wanted;
732
+ }
733
+ return dims.find((d) => d.kind === "overworld") ?? dims.find((d) => d.tiles > 0) ?? dims[0];
734
+ }
735
+
644
736
  // src/core/source.ts
645
737
  function throwIfAborted(signal) {
646
738
  if (signal?.aborted) throw new DOMException("The operation was aborted.", "AbortError");
@@ -728,6 +820,26 @@ function worldFromVantageServer(endpoint, options = {}) {
728
820
  const manifest = new URL(`v1/worlds/${encodeURIComponent(worldId)}/manifest.json`, base).toString();
729
821
  return worldFromHttp(manifest, options);
730
822
  }
823
+ async function worldFromIndexEntry(source, manifestPath) {
824
+ const slash = manifestPath.lastIndexOf("/");
825
+ const prefix = slash < 0 ? "" : manifestPath.slice(0, slash + 1);
826
+ const bytes = await source.fetch(manifestPath);
827
+ const manifest = JSON.parse(new TextDecoder().decode(bytes));
828
+ const under = (path) => prefix + normalizePath(path);
829
+ return {
830
+ manifest,
831
+ label: prefix.length === 0 ? source.label : `${source.label}/${prefix.slice(0, -1)}`,
832
+ fetch: (path, signal) => source.fetch(under(path), signal),
833
+ ...source.fetchConditional ? { fetchConditional: (path, etag, signal) => source.fetchConditional(under(path), etag, signal) } : {}
834
+ };
835
+ }
836
+ async function readOptional(read, path) {
837
+ try {
838
+ return await read(path);
839
+ } catch {
840
+ return void 0;
841
+ }
842
+ }
731
843
  async function worldFromDirectory(dir) {
732
844
  const readFile = async (path, signal) => {
733
845
  throwIfAborted(signal);
@@ -738,16 +850,14 @@ async function worldFromDirectory(dir) {
738
850
  const handle = await node.getFileHandle(segments[segments.length - 1]);
739
851
  return handle.getFile();
740
852
  };
741
- let manifestFile;
742
- try {
743
- manifestFile = await readFile("manifest.json");
744
- } catch {
853
+ const entry = await readOptional(readFile, "world.json") ?? await readOptional(readFile, "manifest.json");
854
+ if (!entry) {
745
855
  throw new Error(
746
- `vantage: no manifest.json in "${dir.name}" \u2014 pick the folder a \`vantage render\` wrote (it holds manifest.json, terrain.vtexarr, and tiles/)`
856
+ `vantage: no world.json or manifest.json in "${dir.name}" \u2014 pick the folder a \`vantage render\` wrote (it holds manifest.json, terrain.vtexarr, and tiles/)`
747
857
  );
748
858
  }
749
859
  return {
750
- manifest: JSON.parse(await manifestFile.text()),
860
+ manifest: JSON.parse(await entry.text()),
751
861
  label: dir.name,
752
862
  fetch: async (path, signal) => {
753
863
  const file = await readFile(path, signal);
@@ -759,17 +869,22 @@ async function worldFromDirectory(dir) {
759
869
  async function worldFromFiles(files, pathOf = (f) => f.webkitRelativePath || f.name) {
760
870
  const byPath = /* @__PURE__ */ new Map();
761
871
  for (const file of files) byPath.set(normalizePath(pathOf(file)).replace(/\\/g, "/"), file);
762
- let manifestPath = null;
763
- for (const path of byPath.keys()) {
764
- if (path !== "manifest.json" && !path.endsWith("/manifest.json")) continue;
765
- if (manifestPath === null || path.split("/").length < manifestPath.split("/").length) manifestPath = path;
766
- }
872
+ const shallowest = (name) => {
873
+ let found = null;
874
+ for (const path of byPath.keys()) {
875
+ if (path !== name && !path.endsWith(`/${name}`)) continue;
876
+ if (found === null || path.split("/").length < found.split("/").length) found = path;
877
+ }
878
+ return found;
879
+ };
880
+ const entryName = shallowest("world.json") !== null ? "world.json" : "manifest.json";
881
+ const manifestPath = shallowest(entryName);
767
882
  if (manifestPath === null) {
768
883
  throw new Error(
769
884
  "vantage: no manifest.json among the selected files \u2014 pick the folder a `vantage render` wrote (it holds manifest.json, terrain.vtexarr, and tiles/)"
770
885
  );
771
886
  }
772
- const prefix = manifestPath.slice(0, manifestPath.length - "manifest.json".length);
887
+ const prefix = manifestPath.slice(0, manifestPath.length - entryName.length);
773
888
  const root = prefix === "" ? "world" : prefix.slice(0, -1);
774
889
  return {
775
890
  manifest: JSON.parse(await byPath.get(manifestPath).text()),
@@ -903,4 +1018,4 @@ function summarizeBiomes(tile, palette) {
903
1018
  return toEntries(counts, names, pal);
904
1019
  }
905
1020
 
906
- 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 };
1021
+ export { ByteReader, LOWRES_EMPTY, LOWRES_MAGIC, TEXTURE_MAGIC, TILE_MAGIC, UV_SCALE, biomePalette, canonicalQuadIndices, isGzip, isWorldIndex, maybeInflate, parseLowresTile, parseManifest, parseTextureArray, parseTile, parseTileQuantized, parseWorldIndex, pickDimension, resolveManifestPath, stripNamespace, summarizeBiomes, summarizeSurfaceBiomes, tileKey, worldFromDirectory, worldFromFiles, worldFromHttp, worldFromIndexEntry, worldFromUrl, worldFromVantageServer };