@thoughts-on-things/vantage-mc 0.12.0 → 0.14.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, isWorldIndex, parseWorldIndex, pickDimension, worldFromIndexEntry, parseManifest, parseTextureArray } from './chunk-GKNIX375.js';
1
+ import { biomePalette, LOWRES_EMPTY, tileKey, parseLowresTile, maybeInflate, parseTileQuantized, summarizeSurfaceBiomes, parseTile, summarizeBiomes, angleDelta, NO_PLAYERS, worldFromUrl, isWorldIndex, parseWorldIndex, pickDimension, worldFromIndexEntry, parseManifest, parseTextureArray, parsePlayers, samePlayers } from './chunk-CAQDMI2B.js';
2
2
  import * as THREE2 from 'three';
3
3
 
4
4
  var SKY_TOP = [0.3, 0.52, 0.84];
@@ -1600,8 +1600,12 @@ var TileManager = class _TileManager {
1600
1600
  records = /* @__PURE__ */ new Map();
1601
1601
  emitter = new Emitter();
1602
1602
  tileBlocks;
1603
- /** Lowres pyramid levels, finest first ([] when the manifest has none). */
1603
+ /** Lowres pyramid levels, finest first ([] when the manifest has none).
1604
+ * A live world's pyramid grows mid-session — see {@link syncLowres}. */
1604
1605
  lowLevels;
1606
+ /** On-demand world (`vantage live`/`server`): tiles and the LOD pyramid are
1607
+ * produced as the map is watched, so both keep being reconciled. */
1608
+ dynamic;
1605
1609
  /** Tile-existence index per lowres level (for the coverage pass). */
1606
1610
  lowIndex = /* @__PURE__ */ new Map();
1607
1611
  /** Set when residency changed and lowres visibility needs recomputing. */
@@ -1665,6 +1669,7 @@ var TileManager = class _TileManager {
1665
1669
  this.ensureAtlas = ensureAtlas ?? null;
1666
1670
  this.atlasLayers = ensureAtlas ? options.manifest.textureLayers ?? 0 : Infinity;
1667
1671
  this.tileBlocks = options.manifest.tileBlocks;
1672
+ this.dynamic = options.manifest.dynamic ?? false;
1668
1673
  if (options.manifest.maxSectionVerts) sharedQuadIndex(options.manifest.maxSectionVerts);
1669
1674
  for (const t of options.manifest.tiles) this.index.set(tileKey(t.x, t.z), t);
1670
1675
  this.lowLevels = this.lowresMaterial ? [...options.manifest.lowres?.levels ?? []].sort((a, b) => a.level - b.level) : [];
@@ -1673,7 +1678,7 @@ var TileManager = class _TileManager {
1673
1678
  }
1674
1679
  this.renderer = renderer ?? null;
1675
1680
  const res = mapMemory ?? 64;
1676
- if (renderer && res > 0 && !options.manifest.lowres) {
1681
+ if (renderer && res > 0 && (!options.manifest.lowres || this.dynamic)) {
1677
1682
  this.impostors = new ImpostorLayer(renderer, options.scene, options.material, this.tileBlocks, res, this.readySurface);
1678
1683
  this.applyHazeFloor();
1679
1684
  }
@@ -1975,19 +1980,67 @@ var TileManager = class _TileManager {
1975
1980
  return changed;
1976
1981
  }
1977
1982
  /** Install the lowres pyramid once a progressive render finishes (its earlier
1978
- * manifests carried no lowres). No-op without a lowres material, or if a
1979
- * pyramid is already present. Forces a re-plan so the coarse rings stream in. */
1983
+ * manifests carried no lowres). Forces a re-plan so the coarse rings stream
1984
+ * in. No-op without a lowres material. */
1980
1985
  ingestLowres(lowres) {
1981
- if (!this.lowresMaterial || this.lowLevels.length > 0) return;
1986
+ if (!this.lowresMaterial) return;
1987
+ this.syncLowres(lowres);
1988
+ if (!this.dynamic) {
1989
+ this.impostors?.dispose();
1990
+ this.impostors = null;
1991
+ }
1992
+ }
1993
+ /**
1994
+ * Reconcile the lowres pyramid from a continuous manifest.
1995
+ *
1996
+ * A live/server session builds its pyramid as tiles bake, so levels appear
1997
+ * and individual overview tiles are rebuilt while the map is being watched.
1998
+ * Tiles whose fingerprint moved are evicted so the next plan re-fetches
1999
+ * them; everything unchanged stays on the GPU. Returns whether anything
2000
+ * moved (the caller re-applies view limits and redraws).
2001
+ */
2002
+ syncLowres(lowres) {
2003
+ if (!this.lowresMaterial) return false;
1982
2004
  const levels = [...lowres.levels].sort((a, b) => a.level - b.level);
2005
+ const stamp = (t) => t.revision ?? `b${t.bytes}`;
2006
+ let changed = false;
2007
+ const live = /* @__PURE__ */ new Set();
2008
+ for (const lvl of levels) {
2009
+ const index = this.lowIndex.get(lvl.level);
2010
+ for (const t of lvl.tiles) {
2011
+ const key = recKey(lvl.level, t.x, t.z);
2012
+ live.add(key);
2013
+ const previous = index?.get(tileKey(t.x, t.z));
2014
+ if (!previous) {
2015
+ changed = true;
2016
+ continue;
2017
+ }
2018
+ if (stamp(previous) === stamp(t)) continue;
2019
+ const rec = this.records.get(key);
2020
+ if (rec) this.unload(key, rec);
2021
+ changed = true;
2022
+ }
2023
+ }
2024
+ for (const [lvl, index] of this.lowIndex) {
2025
+ for (const previous of index.values()) {
2026
+ const key = recKey(lvl, previous.x, previous.z);
2027
+ if (live.has(key)) continue;
2028
+ const rec = this.records.get(key);
2029
+ if (rec) this.unload(key, rec);
2030
+ changed = true;
2031
+ }
2032
+ }
2033
+ this.lowLevels.length = 0;
1983
2034
  this.lowLevels.push(...levels);
2035
+ this.lowIndex.clear();
1984
2036
  for (const lvl of levels) this.lowIndex.set(lvl.level, new Map(lvl.tiles.map((t) => [tileKey(t.x, t.z), t])));
1985
- this.impostors?.dispose();
1986
- this.impostors = null;
1987
- this.lastFocusX = Infinity;
1988
- this.lastFocusZ = Infinity;
1989
- this.coverageDirty = true;
1990
- this.invalidate();
2037
+ if (changed) {
2038
+ this.lastFocusX = Infinity;
2039
+ this.lastFocusZ = Infinity;
2040
+ this.coverageDirty = true;
2041
+ this.invalidate();
2042
+ }
2043
+ return changed;
1991
2044
  }
1992
2045
  /** Show or hide every resident tile's cave-dark geometry (VTLA tiles order
1993
2046
  * it as a contiguous tail per mesh, so hiding is a shorter draw range —
@@ -2021,7 +2074,7 @@ var TileManager = class _TileManager {
2021
2074
  if (settings.mapMemory !== void 0 && settings.mapMemory !== this.mapMemoryResolution) {
2022
2075
  this.impostors?.dispose();
2023
2076
  this.impostors = null;
2024
- if (this.renderer && settings.mapMemory > 0 && this.lowLevels.length === 0) {
2077
+ if (this.renderer && settings.mapMemory > 0 && (this.lowLevels.length === 0 || this.dynamic)) {
2025
2078
  this.impostors = new ImpostorLayer(this.renderer, this.opts.scene, this.opts.material, this.tileBlocks, settings.mapMemory, this.readySurface);
2026
2079
  }
2027
2080
  this.invalidate();
@@ -2416,9 +2469,708 @@ function pickBiome(ray, surf, bounds) {
2416
2469
  }
2417
2470
  return -1;
2418
2471
  }
2472
+
2473
+ // src/three/skin.ts
2474
+ var SKIN_SIZE = 64;
2475
+ function boxFaces(x, y, w, h, d) {
2476
+ return [
2477
+ { x: x + d + w, y: y + d, w: d, h },
2478
+ // +X — the player's left
2479
+ { x, y: y + d, w: d, h },
2480
+ // -X — the player's right
2481
+ { x: x + d, y, w, h: d },
2482
+ // +Y — top
2483
+ { x: x + d + w, y, w, h: d },
2484
+ // -Y — bottom
2485
+ { x: x + d, y: y + d, w, h },
2486
+ // +Z — front (the face)
2487
+ { x: x + 2 * d + w, y: y + d, w, h }
2488
+ // -Z — back
2489
+ ];
2490
+ }
2491
+ var NODE_PIVOTS = {
2492
+ head: [0, 24, 0],
2493
+ body: [0, 0, 0],
2494
+ rightArm: [-6, 22, 0],
2495
+ leftArm: [6, 22, 0],
2496
+ rightLeg: [-2, 12, 0],
2497
+ leftLeg: [2, 12, 0]
2498
+ };
2499
+ var WIDE_MODEL = [
2500
+ { node: "head", size: [8, 8, 8], offset: [0, 4, 0], base: [0, 0], overlay: [32, 0], inflate: 0.5 },
2501
+ { node: "body", size: [8, 12, 4], offset: [0, 18, 0], base: [16, 16], overlay: [16, 32], inflate: 0.25 },
2502
+ { node: "rightArm", size: [4, 12, 4], offset: [0, -4, 0], base: [40, 16], overlay: [40, 32], inflate: 0.25 },
2503
+ { node: "leftArm", size: [4, 12, 4], offset: [0, -4, 0], base: [32, 48], overlay: [48, 48], inflate: 0.25 },
2504
+ { node: "rightLeg", size: [4, 12, 4], offset: [0, -6, 0], base: [0, 16], overlay: [0, 32], inflate: 0.25 },
2505
+ { node: "leftLeg", size: [4, 12, 4], offset: [0, -6, 0], base: [16, 48], overlay: [0, 48], inflate: 0.25 }
2506
+ ];
2507
+ function modelParts(slim) {
2508
+ if (!slim) return WIDE_MODEL;
2509
+ return WIDE_MODEL.map((part) => {
2510
+ if (part.node !== "rightArm" && part.node !== "leftArm") return part;
2511
+ const sign = part.node === "rightArm" ? -1 : 1;
2512
+ return {
2513
+ ...part,
2514
+ size: [3, part.size[1], part.size[2]],
2515
+ // Half a pixel back toward the body, so the sleeve hangs off the same shoulder.
2516
+ offset: [part.offset[0] + sign * 0.5, part.offset[1], part.offset[2]]
2517
+ };
2518
+ });
2519
+ }
2520
+ var PIXEL = 1 / 16;
2521
+ var FACE_SHADE = [0.72, 0.72, 1, 0.62, 0.86, 0.86];
2522
+ function hashId(id) {
2523
+ let h = 2166136261;
2524
+ for (let i = 0; i < id.length; i++) {
2525
+ h ^= id.charCodeAt(i);
2526
+ h = Math.imul(h, 16777619);
2527
+ }
2528
+ return h >>> 0;
2529
+ }
2530
+ function hsl(h, s, l) {
2531
+ return `hsl(${Math.round(h)} ${Math.round(s * 100)}% ${Math.round(l * 100)}%)`;
2532
+ }
2533
+ function defaultSlim(id) {
2534
+ return (hashId(id) & 1) === 1;
2535
+ }
2536
+ var TONES = ["#f0c8a0", "#d9a271", "#b4784a", "#8a552f", "#5c3a20"];
2537
+ var SHADES = ["#d8b28c", "#c08e61", "#9c6640", "#744628", "#4a2e19"];
2538
+ var HAIRS = ["#2a1c12", "#54331a", "#8a5a2b", "#c8a24c", "#7a7a7a"];
2539
+ var EYES = ["#3b6ea5", "#4d7a3a", "#5a4634", "#3a3a3a"];
2540
+ function defaultPalette(id) {
2541
+ const h = hashId(id);
2542
+ const hue = h % 360;
2543
+ const accent = (hue + 150 + (h >>> 9) % 60) % 360;
2544
+ const tone = (h >>> 5) % TONES.length;
2545
+ return {
2546
+ skinTone: TONES[tone],
2547
+ skinShade: SHADES[tone],
2548
+ hair: HAIRS[(h >>> 13) % HAIRS.length],
2549
+ eyes: EYES[(h >>> 17) % EYES.length],
2550
+ shirt: hsl(hue, 0.52, 0.52),
2551
+ shirtDark: hsl(hue, 0.5, 0.4),
2552
+ trousers: hsl(accent, 0.3, 0.34),
2553
+ trousersDark: hsl(accent, 0.3, 0.26),
2554
+ shoes: "#3a3a42"
2555
+ };
2556
+ }
2557
+ function defaultSkinCanvas(id, doc = document) {
2558
+ const canvas = doc.createElement("canvas");
2559
+ canvas.width = SKIN_SIZE;
2560
+ canvas.height = SKIN_SIZE;
2561
+ const g = canvas.getContext("2d");
2562
+ const { skinTone, skinShade, hair, shirt, shirtDark, trousers, trousersDark, shoes, eyes } = defaultPalette(id);
2563
+ const fill = (rect, color) => {
2564
+ g.fillStyle = color;
2565
+ g.fillRect(rect.x, rect.y, rect.w, rect.h);
2566
+ };
2567
+ const paintBox = (faces, main, side, top, bottom) => {
2568
+ fill(faces[0], side);
2569
+ fill(faces[1], side);
2570
+ fill(faces[2], top ?? main);
2571
+ fill(faces[3], bottom ?? side);
2572
+ fill(faces[4], main);
2573
+ fill(faces[5], main);
2574
+ };
2575
+ const head = boxFaces(0, 0, 8, 8, 8);
2576
+ paintBox(head, skinTone, skinShade, hair, skinShade);
2577
+ g.fillStyle = hair;
2578
+ g.fillRect(head[4].x, head[4].y, 8, 2);
2579
+ g.fillRect(head[0].x, head[0].y, 8, 2);
2580
+ g.fillRect(head[1].x, head[1].y, 8, 2);
2581
+ g.fillRect(head[5].x, head[5].y, 8, 3);
2582
+ const fx = head[4].x;
2583
+ const fy = head[4].y;
2584
+ g.fillStyle = "#f4f4f4";
2585
+ g.fillRect(fx + 1, fy + 3, 2, 1);
2586
+ g.fillRect(fx + 5, fy + 3, 2, 1);
2587
+ g.fillStyle = eyes;
2588
+ g.fillRect(fx + 2, fy + 3, 1, 1);
2589
+ g.fillRect(fx + 5, fy + 3, 1, 1);
2590
+ g.fillStyle = skinShade;
2591
+ g.fillRect(fx + 3, fy + 5, 2, 1);
2592
+ paintBox(boxFaces(16, 16, 8, 12, 4), shirt, shirtDark, shirtDark, trousersDark);
2593
+ for (const [x, y] of [[40, 16], [32, 48]]) {
2594
+ const arm = boxFaces(x, y, 4, 12, 4);
2595
+ paintBox(arm, shirt, shirtDark, shirtDark, skinTone);
2596
+ g.fillStyle = skinTone;
2597
+ for (const face of [arm[0], arm[1], arm[4], arm[5]]) g.fillRect(face.x, face.y + 8, face.w, 4);
2598
+ fill(arm[3], skinTone);
2599
+ }
2600
+ for (const [x, y] of [[0, 16], [16, 48]]) {
2601
+ const leg = boxFaces(x, y, 4, 12, 4);
2602
+ paintBox(leg, trousers, trousersDark, trousersDark, shoes);
2603
+ g.fillStyle = shoes;
2604
+ for (const face of [leg[0], leg[1], leg[4], leg[5]]) g.fillRect(face.x, face.y + 10, face.w, 2);
2605
+ }
2606
+ return canvas;
2607
+ }
2608
+ function normalizeSkin(image, width, height, doc = document) {
2609
+ const canvas = doc.createElement("canvas");
2610
+ canvas.width = SKIN_SIZE;
2611
+ canvas.height = SKIN_SIZE;
2612
+ const g = canvas.getContext("2d");
2613
+ g.imageSmoothingEnabled = false;
2614
+ const scale = width >= SKIN_SIZE ? width / SKIN_SIZE : 1;
2615
+ g.drawImage(image, 0, 0, width, height, 0, 0, SKIN_SIZE, height / scale);
2616
+ if (height / scale >= SKIN_SIZE) return canvas;
2617
+ const mirror = (from, to, order) => {
2618
+ for (let i = 0; i < 6; i++) {
2619
+ const src = from[order[i]];
2620
+ const dst = to[i];
2621
+ g.save();
2622
+ g.translate(dst.x + dst.w, dst.y);
2623
+ g.scale(-1, 1);
2624
+ g.drawImage(canvas, src.x, src.y, src.w, src.h, 0, 0, dst.w, dst.h);
2625
+ g.restore();
2626
+ }
2627
+ };
2628
+ const swap = [1, 0, 2, 3, 4, 5];
2629
+ mirror(boxFaces(40, 16, 4, 12, 4), boxFaces(32, 48, 4, 12, 4), swap);
2630
+ mirror(boxFaces(0, 16, 4, 12, 4), boxFaces(16, 48, 4, 12, 4), swap);
2631
+ return canvas;
2632
+ }
2633
+ function headIconCanvas(skin, size = 64, doc = document) {
2634
+ const canvas = doc.createElement("canvas");
2635
+ canvas.width = size;
2636
+ canvas.height = size;
2637
+ const g = canvas.getContext("2d");
2638
+ g.imageSmoothingEnabled = false;
2639
+ const face = boxFaces(0, 0, 8, 8, 8)[4];
2640
+ const hat = boxFaces(32, 0, 8, 8, 8)[4];
2641
+ g.drawImage(skin, face.x, face.y, face.w, face.h, 0, 0, size, size);
2642
+ g.drawImage(skin, hat.x, hat.y, hat.w, hat.h, 0, 0, size, size);
2643
+ return canvas;
2644
+ }
2645
+
2646
+ // src/three/players.ts
2647
+ var DEFAULTS = {
2648
+ enabled: true,
2649
+ names: true,
2650
+ offline: true,
2651
+ foreign: false,
2652
+ scale: 1,
2653
+ tagSize: 0.03
2654
+ };
2655
+ var WALK_SPEED = 4.3;
2656
+ var MIN_LERP_MS = 120;
2657
+ var MAX_LERP_MS = 2e3;
2658
+ var MAX_HEAD_TURN = 55;
2659
+ var MODEL_HEIGHT = 32 * PIXEL;
2660
+ var MIN_MODEL_FRACTION = 4e-3;
2661
+ var PlayerModel = class {
2662
+ group = new THREE2.Group();
2663
+ body = new THREE2.Group();
2664
+ nodes = /* @__PURE__ */ new Map();
2665
+ material;
2666
+ geometries = [];
2667
+ texture;
2668
+ ownedTextures = [];
2669
+ tag = null;
2670
+ tagTexture = null;
2671
+ tagAspect = 1;
2672
+ tagLabel = "";
2673
+ skinCanvas;
2674
+ icon = null;
2675
+ from;
2676
+ to;
2677
+ startMs;
2678
+ durationMs = MIN_LERP_MS;
2679
+ /** Where the model is drawn right now, after interpolation. */
2680
+ draw;
2681
+ /** The direction the torso faces, which lags the look direction while
2682
+ * walking — that lag is what makes a player look like they are walking
2683
+ * somewhere rather than sliding. */
2684
+ bodyYaw;
2685
+ /** Accumulated walk cycle, in radians, advanced by distance travelled. */
2686
+ limbPhase = 0;
2687
+ limbAmount = 0;
2688
+ state;
2689
+ /** 0..1 fade-in, so a player who joins appears rather than pops. */
2690
+ opacity = 0;
2691
+ removing = false;
2692
+ constructor(player, slim, doc) {
2693
+ this.state = player;
2694
+ this.from = sampleOf(player);
2695
+ this.to = sampleOf(player);
2696
+ this.draw = sampleOf(player);
2697
+ this.bodyYaw = player.yaw;
2698
+ this.startMs = 0;
2699
+ this.skinCanvas = defaultSkinCanvas(player.uuid, doc);
2700
+ this.texture = skinTexture(this.skinCanvas);
2701
+ this.ownedTextures.push(this.texture);
2702
+ this.material = new THREE2.MeshBasicMaterial({
2703
+ map: this.texture,
2704
+ // One material for the base and the outer layer: the outer layer's empty
2705
+ // texels are cut away by the alpha test, which is what lets all six nodes
2706
+ // share a single material. The threshold is deliberately *low*: the
2707
+ // fragment's alpha is the texel's times `material.opacity`, so a 0.5 cut
2708
+ // would erase a whole player until they had faded past half — turning
2709
+ // every join and every last-known position into a pop.
2710
+ alphaTest: 0.04,
2711
+ transparent: true,
2712
+ // The winding is built face by face (see FACE_CORNERS), so back faces are
2713
+ // genuinely inside the model and never need rasterizing.
2714
+ side: THREE2.FrontSide,
2715
+ vertexColors: true,
2716
+ depthWrite: true
2717
+ });
2718
+ this.material.opacity = 0;
2719
+ for (const [node, pivot] of Object.entries(NODE_PIVOTS)) {
2720
+ const object = new THREE2.Group();
2721
+ object.position.set(pivot[0] * PIXEL, pivot[1] * PIXEL, pivot[2] * PIXEL);
2722
+ this.nodes.set(node, object);
2723
+ this.body.add(object);
2724
+ }
2725
+ for (const part of modelParts(slim)) {
2726
+ const geometry = partGeometry(part);
2727
+ this.geometries.push(geometry);
2728
+ this.nodes.get(part.node).add(new THREE2.Mesh(geometry, this.material));
2729
+ }
2730
+ this.group.add(this.body);
2731
+ }
2732
+ /** The name tag, once one has been built. */
2733
+ get tagSprite() {
2734
+ return this.tag;
2735
+ }
2736
+ /** This player's face as a data URL, for HTML UI outside the canvas. Built
2737
+ * once per skin — a roster that repeats every second must not re-encode a
2738
+ * PNG per player per second. */
2739
+ headIcon(doc) {
2740
+ return this.icon ??= headIconCanvas(this.skinCanvas, 32, doc).toDataURL("image/png");
2741
+ }
2742
+ /** Swap in a real skin once one has loaded. */
2743
+ setSkin(canvas) {
2744
+ this.skinCanvas = canvas;
2745
+ this.icon = null;
2746
+ const next = skinTexture(canvas);
2747
+ this.ownedTextures.push(next);
2748
+ this.material.map = next;
2749
+ this.material.needsUpdate = true;
2750
+ this.texture = next;
2751
+ this.tagLabel = "";
2752
+ }
2753
+ /** Redraw the name tag when the label, the skin, the settings or the
2754
+ * followed state change. */
2755
+ syncTag(names, followed, doc) {
2756
+ const label = names ? this.state.name : "";
2757
+ const key = `${label}|${this.state.stale ? "s" : ""}${this.state.foreign ? "f" : ""}${followed ? "*" : ""}`;
2758
+ if (this.tag && this.tagLabel === key) return;
2759
+ this.tagLabel = key;
2760
+ const canvas = tagCanvas(this.skinCanvas, label, this.state, followed, doc);
2761
+ this.tagAspect = canvas.width / canvas.height;
2762
+ const texture = new THREE2.CanvasTexture(canvas);
2763
+ texture.colorSpace = THREE2.SRGBColorSpace;
2764
+ texture.minFilter = THREE2.LinearFilter;
2765
+ texture.magFilter = THREE2.LinearFilter;
2766
+ texture.generateMipmaps = false;
2767
+ if (!this.tag) {
2768
+ const material = new THREE2.SpriteMaterial({
2769
+ map: texture,
2770
+ // A tag is a locator, not scenery: it stays legible through terrain,
2771
+ // which is the entire point of having one on a 3D map.
2772
+ depthTest: false,
2773
+ depthWrite: false,
2774
+ transparent: true,
2775
+ sizeAttenuation: false
2776
+ });
2777
+ this.tag = new THREE2.Sprite(material);
2778
+ this.tag.center.set(0.5, 0);
2779
+ this.tag.renderOrder = 1e3;
2780
+ this.group.add(this.tag);
2781
+ } else {
2782
+ this.tagTexture?.dispose();
2783
+ this.tag.material.map = texture;
2784
+ this.tag.material.needsUpdate = true;
2785
+ }
2786
+ this.tagTexture = texture;
2787
+ }
2788
+ /** Size the tag so it covers a fixed fraction of the viewport whatever the
2789
+ * distance — `sizeAttenuation: false` sprites are scaled in units at unit
2790
+ * depth, so the viewport's angular height is the conversion factor. */
2791
+ layoutTag(fraction, fovHeight, scale) {
2792
+ if (!this.tag) return;
2793
+ const height = fraction * fovHeight;
2794
+ this.tag.scale.set(height * this.tagAspect, height, 1);
2795
+ this.tag.position.set(0, MODEL_HEIGHT * scale + 0.12, 0);
2796
+ }
2797
+ dispose() {
2798
+ for (const geometry of this.geometries) geometry.dispose();
2799
+ this.geometries = [];
2800
+ for (const texture of this.ownedTextures) texture.dispose();
2801
+ this.ownedTextures = [];
2802
+ this.material.dispose();
2803
+ this.tagTexture?.dispose();
2804
+ if (this.tag) this.tag.material.dispose();
2805
+ this.group.removeFromParent();
2806
+ }
2807
+ };
2808
+ function sampleOf(p) {
2809
+ return { x: p.x, y: p.y, z: p.z, yaw: p.yaw, pitch: p.pitch };
2810
+ }
2811
+ function copySample(into, from) {
2812
+ into.x = from.x;
2813
+ into.y = from.y;
2814
+ into.z = from.z;
2815
+ into.yaw = from.yaw;
2816
+ into.pitch = from.pitch;
2817
+ }
2818
+ function copyPlayerSample(into, from) {
2819
+ into.x = from.x;
2820
+ into.y = from.y;
2821
+ into.z = from.z;
2822
+ into.yaw = from.yaw;
2823
+ into.pitch = from.pitch;
2824
+ }
2825
+ function skinTexture(source) {
2826
+ const texture = new THREE2.Texture(source);
2827
+ texture.colorSpace = THREE2.SRGBColorSpace;
2828
+ texture.magFilter = THREE2.NearestFilter;
2829
+ texture.minFilter = THREE2.LinearMipmapLinearFilter;
2830
+ texture.generateMipmaps = true;
2831
+ texture.needsUpdate = true;
2832
+ return texture;
2833
+ }
2834
+ function partGeometry(part) {
2835
+ const positions = [];
2836
+ const uvs = [];
2837
+ const colors = [];
2838
+ const indices = [];
2839
+ pushBox(positions, uvs, colors, indices, part, 0, part.base);
2840
+ pushBox(positions, uvs, colors, indices, part, part.inflate, part.overlay);
2841
+ const geometry = new THREE2.BufferGeometry();
2842
+ geometry.setAttribute("position", new THREE2.Float32BufferAttribute(positions, 3));
2843
+ geometry.setAttribute("uv", new THREE2.Float32BufferAttribute(uvs, 2));
2844
+ geometry.setAttribute("color", new THREE2.Float32BufferAttribute(colors, 3));
2845
+ geometry.setIndex(indices);
2846
+ return geometry;
2847
+ }
2848
+ var FACE_CORNERS = [
2849
+ [[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1]],
2850
+ // +X
2851
+ [[-1, 1, -1], [-1, 1, 1], [-1, -1, -1], [-1, -1, 1]],
2852
+ // -X
2853
+ [[-1, 1, -1], [1, 1, -1], [-1, 1, 1], [1, 1, 1]],
2854
+ // +Y
2855
+ [[-1, -1, 1], [1, -1, 1], [-1, -1, -1], [1, -1, -1]],
2856
+ // -Y
2857
+ [[-1, 1, 1], [1, 1, 1], [-1, -1, 1], [1, -1, 1]],
2858
+ // +Z
2859
+ [[1, 1, -1], [-1, 1, -1], [1, -1, -1], [-1, -1, -1]]
2860
+ // -Z
2861
+ ];
2862
+ function pushBox(positions, uvs, colors, indices, part, inflate, origin) {
2863
+ const [w, h, d] = part.size;
2864
+ const faces = boxFaces(origin[0], origin[1], w, h, d);
2865
+ const hx = (w / 2 + inflate) * PIXEL;
2866
+ const hy = (h / 2 + inflate) * PIXEL;
2867
+ const hz = (d / 2 + inflate) * PIXEL;
2868
+ const cx = part.offset[0] * PIXEL;
2869
+ const cy = part.offset[1] * PIXEL;
2870
+ const cz = part.offset[2] * PIXEL;
2871
+ for (let f = 0; f < 6; f++) {
2872
+ const base = positions.length / 3;
2873
+ const rect = faces[f];
2874
+ const shade = FACE_SHADE[f];
2875
+ const u0 = rect.x / SKIN_SIZE;
2876
+ const u1 = (rect.x + rect.w) / SKIN_SIZE;
2877
+ const v0 = 1 - rect.y / SKIN_SIZE;
2878
+ const v1 = 1 - (rect.y + rect.h) / SKIN_SIZE;
2879
+ const corners = FACE_CORNERS[f];
2880
+ const cornerUv = [[u0, v0], [u1, v0], [u0, v1], [u1, v1]];
2881
+ for (let c = 0; c < 4; c++) {
2882
+ const [sx, sy, sz] = corners[c];
2883
+ positions.push(cx + sx * hx, cy + sy * hy, cz + sz * hz);
2884
+ uvs.push(cornerUv[c][0], cornerUv[c][1]);
2885
+ colors.push(shade, shade, shade);
2886
+ }
2887
+ indices.push(base, base + 2, base + 3, base, base + 3, base + 1);
2888
+ }
2889
+ }
2890
+ function tagCanvas(skin, label, player, followed, doc) {
2891
+ const scale = 2;
2892
+ const height = 26 * scale;
2893
+ const pad = 5 * scale;
2894
+ const icon = height - pad * 2;
2895
+ const font = `${13 * scale}px system-ui, -apple-system, "Segoe UI", Roboto, sans-serif`;
2896
+ const measure = doc.createElement("canvas").getContext("2d");
2897
+ measure.font = font;
2898
+ const textWidth = label ? Math.ceil(measure.measureText(label).width) : 0;
2899
+ const width = pad + icon + (label ? pad * 0.8 + textWidth + pad : pad);
2900
+ const canvas = doc.createElement("canvas");
2901
+ canvas.width = Math.max(1, Math.ceil(width));
2902
+ canvas.height = height;
2903
+ const g = canvas.getContext("2d");
2904
+ g.fillStyle = followed ? "rgba(16,38,72,0.86)" : player.stale ? "rgba(10,13,18,0.55)" : "rgba(10,13,18,0.74)";
2905
+ roundRect(g, 0, 0, canvas.width, canvas.height, height / 2);
2906
+ g.fill();
2907
+ const ring = followed ? "rgba(91,155,255,0.95)" : player.foreign ? "rgba(160,140,255,0.55)" : player.stale ? "rgba(255,255,255,0.16)" : null;
2908
+ if (ring) {
2909
+ g.strokeStyle = ring;
2910
+ g.lineWidth = (followed ? 1.6 : 1) * scale;
2911
+ roundRect(g, 0.8 * scale, 0.8 * scale, canvas.width - 1.6 * scale, canvas.height - 1.6 * scale, height / 2);
2912
+ g.stroke();
2913
+ }
2914
+ g.imageSmoothingEnabled = false;
2915
+ const face = boxFaces(0, 0, 8, 8, 8)[4];
2916
+ const hat = boxFaces(32, 0, 8, 8, 8)[4];
2917
+ g.save();
2918
+ roundRect(g, pad, pad, icon, icon, 3 * scale);
2919
+ g.clip();
2920
+ g.drawImage(skin, face.x, face.y, face.w, face.h, pad, pad, icon, icon);
2921
+ g.drawImage(skin, hat.x, hat.y, hat.w, hat.h, pad, pad, icon, icon);
2922
+ g.restore();
2923
+ g.imageSmoothingEnabled = true;
2924
+ if (label) {
2925
+ g.font = font;
2926
+ g.textBaseline = "middle";
2927
+ g.fillStyle = player.stale ? "rgba(230,238,251,0.72)" : "#eef4ff";
2928
+ g.fillText(label, pad + icon + pad * 0.8, canvas.height / 2 + 0.5 * scale);
2929
+ }
2930
+ return canvas;
2931
+ }
2932
+ function roundRect(g, x, y, w, h, r) {
2933
+ const radius = Math.min(r, w / 2, h / 2);
2934
+ g.beginPath();
2935
+ g.moveTo(x + radius, y);
2936
+ g.arcTo(x + w, y, x + w, y + h, radius);
2937
+ g.arcTo(x + w, y + h, x, y + h, radius);
2938
+ g.arcTo(x, y + h, x, y, radius);
2939
+ g.arcTo(x, y, x + w, y, radius);
2940
+ g.closePath();
2941
+ }
2942
+ var PlayerLayer = class {
2943
+ root = new THREE2.Group();
2944
+ scene;
2945
+ camera;
2946
+ fetchSkin;
2947
+ resolveSkin;
2948
+ models = /* @__PURE__ */ new Map();
2949
+ /** Skin loads in flight or done, so a roster that repeats every second
2950
+ * doesn't re-fetch a skin every second. */
2951
+ skinRequests = /* @__PURE__ */ new Set();
2952
+ settings;
2953
+ /** Who the camera is following, so their tag can say so. */
2954
+ followed = null;
2955
+ snapshot = null;
2956
+ lastSnapshotMs = 0;
2957
+ lastFrameMs = 0;
2958
+ tone = 1;
2959
+ disposed = false;
2960
+ constructor(options) {
2961
+ this.scene = options.scene;
2962
+ this.camera = options.camera;
2963
+ this.fetchSkin = options.fetchSkin;
2964
+ this.resolveSkin = options.resolveSkin;
2965
+ this.settings = { ...DEFAULTS, ...options.settings };
2966
+ this.root.name = "vantage-players";
2967
+ this.root.renderOrder = 5;
2968
+ this.scene.add(this.root);
2969
+ }
2970
+ /** The players the layer is tracking, with their live drawn positions. */
2971
+ get players() {
2972
+ const out = [];
2973
+ for (const player of this.snapshot?.players ?? []) {
2974
+ const model = this.models.get(player.uuid);
2975
+ out.push({
2976
+ ...player,
2977
+ drawX: model?.draw.x ?? player.x,
2978
+ drawY: model?.draw.y ?? player.y,
2979
+ drawZ: model?.draw.z ?? player.z,
2980
+ visible: model !== void 0
2981
+ });
2982
+ }
2983
+ return out;
2984
+ }
2985
+ /** A player's face as a data URL, for a list or a tooltip in the DOM. */
2986
+ headIcon(uuid) {
2987
+ return this.models.get(uuid)?.headIcon(document) ?? null;
2988
+ }
2989
+ /** Where a player is being drawn right now, for the camera to fly to. */
2990
+ positionOf(uuid) {
2991
+ const model = this.models.get(uuid);
2992
+ return model ? new THREE2.Vector3(model.draw.x, model.draw.y, model.draw.z) : null;
2993
+ }
2994
+ setSettings(settings) {
2995
+ this.settings = { ...this.settings, ...settings };
2996
+ this.root.visible = this.settings.enabled;
2997
+ if (this.snapshot) this.resync();
2998
+ }
2999
+ /** Mark a player as the one the camera is following (`null` clears it). */
3000
+ setFollowed(uuid) {
3001
+ if (this.followed === uuid) return;
3002
+ this.followed = uuid;
3003
+ for (const [id, model] of this.models) model.syncTag(this.settings.names, id === uuid, document);
3004
+ }
3005
+ /** Add or drop models so the scene matches the current roster and settings,
3006
+ * without touching anybody's interpolation. */
3007
+ resync() {
3008
+ const live = /* @__PURE__ */ new Set();
3009
+ for (const player of this.snapshot?.players ?? []) {
3010
+ if (!this.shouldPlace(player)) continue;
3011
+ live.add(player.uuid);
3012
+ const model = this.models.get(player.uuid) ?? this.spawn(player);
3013
+ model.removing = false;
3014
+ model.syncTag(this.settings.names, player.uuid === this.followed, document);
3015
+ }
3016
+ for (const [uuid, model] of this.models) model.removing = !live.has(uuid);
3017
+ }
3018
+ spawn(player) {
3019
+ const model = new PlayerModel(player, defaultSlim(player.uuid), document);
3020
+ model.material.color.setScalar(this.tone);
3021
+ this.models.set(player.uuid, model);
3022
+ this.root.add(model.group);
3023
+ this.loadSkin(player, model);
3024
+ return model;
3025
+ }
3026
+ /** Follow the viewer's exposure so players sit in the same light as the
3027
+ * terrain instead of glowing against a dimmed world. */
3028
+ setTone(exposure) {
3029
+ this.tone = Math.max(0.15, Math.min(2, exposure));
3030
+ for (const model of this.models.values()) model.material.color.setScalar(this.tone);
3031
+ }
3032
+ /** Take a new roster. Players that are new appear, players that left fade
3033
+ * out, and everyone else gets a fresh interpolation target. */
3034
+ setSnapshot(snapshot, now) {
3035
+ if (this.disposed) return;
3036
+ const previous = this.snapshot;
3037
+ this.snapshot = snapshot;
3038
+ const cadence = previous && this.lastSnapshotMs ? now - this.lastSnapshotMs : 0;
3039
+ this.lastSnapshotMs = now;
3040
+ const live = /* @__PURE__ */ new Set();
3041
+ for (const player of snapshot.players) {
3042
+ if (!this.shouldPlace(player)) continue;
3043
+ live.add(player.uuid);
3044
+ const model = this.models.get(player.uuid) ?? this.spawn(player);
3045
+ model.state = player;
3046
+ model.removing = false;
3047
+ copySample(model.from, model.draw);
3048
+ copyPlayerSample(model.to, player);
3049
+ model.startMs = now;
3050
+ model.durationMs = Math.max(MIN_LERP_MS, Math.min(MAX_LERP_MS, cadence || MIN_LERP_MS));
3051
+ model.syncTag(this.settings.names, player.uuid === this.followed, document);
3052
+ }
3053
+ for (const [uuid, model] of this.models) {
3054
+ if (!live.has(uuid)) model.removing = true;
3055
+ }
3056
+ }
3057
+ /** Whether a player belongs on the map itself (as opposed to merely in the
3058
+ * list): foreign coordinates mean something else, and last-known positions
3059
+ * are opt-out. */
3060
+ shouldPlace(player) {
3061
+ if (player.foreign && !this.settings.foreign) return false;
3062
+ if (player.stale && !this.settings.offline) return false;
3063
+ return true;
3064
+ }
3065
+ /**
3066
+ * Advance every model to `now`.
3067
+ *
3068
+ * Returns whether anything moved, which the viewer's render-on-demand loop
3069
+ * uses to decide whether this frame is worth drawing — a map of standing
3070
+ * players costs nothing, and one walking player wakes the loop.
3071
+ */
3072
+ update(now) {
3073
+ if (this.disposed || !this.settings.enabled || this.models.size === 0) return false;
3074
+ const dt = this.lastFrameMs ? Math.min(0.25, (now - this.lastFrameMs) / 1e3) : 0;
3075
+ this.lastFrameMs = now;
3076
+ let moved = false;
3077
+ const fovHeight = 2 * Math.tan(this.camera.fov * Math.PI / 360);
3078
+ const scale = this.settings.scale;
3079
+ for (const [uuid, model] of this.models) {
3080
+ const alpha = model.durationMs > 0 ? Math.min(1, (now - model.startMs) / model.durationMs) : 1;
3081
+ const previousX = model.draw.x;
3082
+ const previousZ = model.draw.z;
3083
+ model.draw.x = model.from.x + (model.to.x - model.from.x) * alpha;
3084
+ model.draw.y = model.from.y + (model.to.y - model.from.y) * alpha;
3085
+ model.draw.z = model.from.z + (model.to.z - model.from.z) * alpha;
3086
+ const turn = 1 - Math.exp(-dt * 9);
3087
+ model.draw.yaw += angleDelta(model.draw.yaw, model.to.yaw) * turn;
3088
+ model.draw.pitch += (model.to.pitch - model.draw.pitch) * turn;
3089
+ const stepX = model.draw.x - previousX;
3090
+ const stepZ = model.draw.z - previousZ;
3091
+ const speed = dt > 0 ? Math.hypot(stepX, stepZ) / dt : 0;
3092
+ if (speed > 0.05) {
3093
+ const heading = -(Math.atan2(stepX, stepZ) * 180) / Math.PI;
3094
+ model.bodyYaw += angleDelta(model.bodyYaw, heading) * (1 - Math.exp(-dt * 6));
3095
+ } else {
3096
+ model.bodyYaw += angleDelta(model.bodyYaw, model.draw.yaw) * (1 - Math.exp(-dt * 5));
3097
+ }
3098
+ const targetSwing = model.state.stale ? 0 : Math.min(1, speed / WALK_SPEED);
3099
+ model.limbAmount += (targetSwing - model.limbAmount) * (1 - Math.exp(-dt * 8));
3100
+ model.limbPhase += speed * dt * 2.2;
3101
+ model.group.position.set(model.draw.x, model.draw.y, model.draw.z);
3102
+ model.group.scale.setScalar(scale);
3103
+ model.body.rotation.y = -model.bodyYaw * Math.PI / 180;
3104
+ const head = model.nodes.get("head");
3105
+ head.rotation.x = model.draw.pitch * Math.PI / 180;
3106
+ head.rotation.y = -clamp(angleDelta(model.bodyYaw, model.draw.yaw), -MAX_HEAD_TURN, MAX_HEAD_TURN) * Math.PI / 180;
3107
+ const swing = Math.sin(model.limbPhase) * model.limbAmount * 0.85;
3108
+ model.nodes.get("rightLeg").rotation.x = swing;
3109
+ model.nodes.get("leftLeg").rotation.x = -swing;
3110
+ model.nodes.get("rightArm").rotation.x = -swing * 0.8;
3111
+ model.nodes.get("leftArm").rotation.x = swing * 0.8;
3112
+ model.layoutTag(this.settings.tagSize, fovHeight, scale);
3113
+ const eye = this.camera.position;
3114
+ const distance = Math.hypot(eye.x - model.draw.x, eye.y - model.draw.y, eye.z - model.draw.z);
3115
+ const screenFraction = distance > 0 ? MODEL_HEIGHT * scale / (fovHeight * distance) : 1;
3116
+ model.body.visible = screenFraction > MIN_MODEL_FRACTION;
3117
+ const target = model.removing ? 0 : model.state.stale ? 0.55 : 1;
3118
+ if (Math.abs(model.opacity - target) > 2e-3) {
3119
+ model.opacity += (target - model.opacity) * (1 - Math.exp(-dt * 7));
3120
+ moved = true;
3121
+ } else {
3122
+ model.opacity = target;
3123
+ }
3124
+ model.material.opacity = model.opacity;
3125
+ if (model.tagSprite) model.tagSprite.material.opacity = model.opacity;
3126
+ if (model.removing && model.opacity <= 0.01) {
3127
+ model.dispose();
3128
+ this.models.delete(uuid);
3129
+ moved = true;
3130
+ continue;
3131
+ }
3132
+ if (alpha < 1 || speed > 1e-3 || model.limbAmount > 0.01) moved = true;
3133
+ }
3134
+ return moved;
3135
+ }
3136
+ dispose() {
3137
+ this.disposed = true;
3138
+ for (const model of this.models.values()) model.dispose();
3139
+ this.models.clear();
3140
+ this.skinRequests.clear();
3141
+ this.root.removeFromParent();
3142
+ }
3143
+ /** Load a player's real skin, if there is one to load. Failures are silent:
3144
+ * the procedural skin the model already has is a perfectly good fallback. */
3145
+ loadSkin(player, model) {
3146
+ const key = player.uuid;
3147
+ if (this.skinRequests.has(key)) return;
3148
+ const url = this.resolveSkin?.(player);
3149
+ const path = player.skin;
3150
+ if (!url && !(path && this.fetchSkin)) return;
3151
+ this.skinRequests.add(key);
3152
+ void (async () => {
3153
+ try {
3154
+ const blob = url ? await (await fetch(url, { credentials: "omit", mode: "cors" })).blob() : new Blob([await this.fetchSkin(path)], { type: "image/png" });
3155
+ const bitmap = await createImageBitmap(blob);
3156
+ try {
3157
+ if (this.disposed || !this.models.has(key)) return;
3158
+ model.setSkin(normalizeSkin(bitmap, bitmap.width, bitmap.height, document));
3159
+ model.syncTag(this.settings.names, key === this.followed, document);
3160
+ } finally {
3161
+ bitmap.close();
3162
+ }
3163
+ } catch {
3164
+ }
3165
+ })();
3166
+ }
3167
+ };
3168
+ function clamp(v, lo, hi) {
3169
+ return v < lo ? lo : v > hi ? hi : v;
3170
+ }
2419
3171
  var HALF_PI = Math.PI * 0.5;
2420
3172
  var HALF_PI_DIV = 1 / HALF_PI;
2421
- function clamp(v, lo, hi) {
3173
+ function clamp2(v, lo, hi) {
2422
3174
  return v < lo ? lo : v > hi ? hi : v;
2423
3175
  }
2424
3176
  function softMin(v, min, k) {
@@ -2615,8 +3367,8 @@ var MapControls = class _MapControls {
2615
3367
  } else {
2616
3368
  this.mode = "map";
2617
3369
  const dist = this.savedDistance > this.minDistance ? this.savedDistance : 200;
2618
- this.distance = clamp(dist, this.minDistance, this.maxDistance);
2619
- this.angle = clamp(this.angle, 0, this.maxAngleForDistance(this.distance));
3370
+ this.distance = clamp2(dist, this.minDistance, this.maxDistance);
3371
+ this.angle = clamp2(this.angle, 0, this.maxAngleForDistance(this.distance));
2620
3372
  this.position.add(this.lookDir().multiplyScalar(this.distance));
2621
3373
  this.targetHeight = this.cameraHeight = this.position.y;
2622
3374
  this.exitPointerLock();
@@ -2665,9 +3417,9 @@ var MapControls = class _MapControls {
2665
3417
  setView(state) {
2666
3418
  this.goal = null;
2667
3419
  this.position.copy(state.position);
2668
- this.distance = clamp(state.distance, this.minDistance, this.maxDistance);
3420
+ this.distance = clamp2(state.distance, this.minDistance, this.maxDistance);
2669
3421
  this.rotation = state.rotation;
2670
- this.angle = clamp(state.angle, 0, this.maxAngleForDistance(this.distance));
3422
+ this.angle = clamp2(state.angle, 0, this.maxAngleForDistance(this.distance));
2671
3423
  if (state.floorY !== void 0) this.floorY = state.floorY;
2672
3424
  this.targetHeight = this.position.y;
2673
3425
  this.cameraHeight = this.position.y;
@@ -2723,7 +3475,7 @@ var MapControls = class _MapControls {
2723
3475
  /** `stiffness` is the per-frame lerp at 60fps, scaled by
2724
3476
  * the (averaged) frame time so feel is frame-rate independent. */
2725
3477
  smoothing(stiffness, dt) {
2726
- return clamp(stiffness / (16.666 / dt), 0, 1);
3478
+ return clamp2(stiffness / (16.666 / dt), 0, 1);
2727
3479
  }
2728
3480
  /** Max tilt (radians from top-down) allowed at a dolly distance, scaled to
2729
3481
  * *this* world's zoom range: full tilt up close, eased to a flat top-down
@@ -2731,12 +3483,12 @@ var MapControls = class _MapControls {
2731
3483
  * view, whatever the world's size. */
2732
3484
  maxAngleForDistance(distance) {
2733
3485
  const span = Math.max(this.maxDistance - this.minDistance, 1);
2734
- const t = clamp((distance - this.minDistance) / span, 0, 1);
2735
- return clamp((1 - Math.sqrt(t)) * HALF_PI, 0, HALF_PI);
3486
+ const t = clamp2((distance - this.minDistance) / span, 0, 1);
3487
+ return clamp2((1 - Math.sqrt(t)) * HALF_PI, 0, HALF_PI);
2736
3488
  }
2737
3489
  /** Inverse: the farthest distance at which `angle` is still a legal tilt. */
2738
3490
  maxDistanceForAngle(angle) {
2739
- const t = Math.pow(clamp(1 - angle * HALF_PI_DIV, 0, 1), 2);
3491
+ const t = Math.pow(clamp2(1 - angle * HALF_PI_DIV, 0, 1), 2);
2740
3492
  return this.minDistance + t * (this.maxDistance - this.minDistance);
2741
3493
  }
2742
3494
  // --- motion application (drains the buffers) -------------------------------
@@ -2822,7 +3574,7 @@ var MapControls = class _MapControls {
2822
3574
  * to dodge the gimbal flip), distance is pinned to the eye, azimuth wraps. */
2823
3575
  applyFlyBounds() {
2824
3576
  this.distance = 0;
2825
- this.angle = clamp(this.angle, 0.02, Math.PI - 0.02);
3577
+ this.angle = clamp2(this.angle, 0.02, Math.PI - 0.02);
2826
3578
  if (this.rotation > Math.PI) this.rotation -= 2 * Math.PI;
2827
3579
  else if (this.rotation < -Math.PI) this.rotation += 2 * Math.PI;
2828
3580
  }
@@ -2830,7 +3582,7 @@ var MapControls = class _MapControls {
2830
3582
  * view has settled close enough. */
2831
3583
  applyGoal(dt) {
2832
3584
  if (!this.goal) return;
2833
- const k = clamp(0.12 * (dt / 16.666), 0, 1);
3585
+ const k = clamp2(0.12 * (dt / 16.666), 0, 1);
2834
3586
  const g = this.goal;
2835
3587
  let done = true;
2836
3588
  if (g.rotation !== void 0) {
@@ -2872,7 +3624,7 @@ var MapControls = class _MapControls {
2872
3624
  * near top-down (insensitive to pivot Y). */
2873
3625
  applyHeight(dt) {
2874
3626
  if (!this.heightAt) return;
2875
- const ts = clamp(0.15 * (dt / 16.666), 0, 1);
3627
+ const ts = clamp2(0.15 * (dt / 16.666), 0, 1);
2876
3628
  const hp = this.heightAt(this.position.x, this.position.z);
2877
3629
  const targetTerrain = (hp === null ? this.floorY : hp) + 3;
2878
3630
  this.targetHeight += (targetTerrain - this.targetHeight) * ts;
@@ -2880,7 +3632,7 @@ var MapControls = class _MapControls {
2880
3632
  let suggested = this.targetHeight;
2881
3633
  const maxAngle = this.maxAngleForDistance(this.distance);
2882
3634
  if (maxAngle >= 0.1) {
2883
- const cs = clamp(0.2 * (dt / 16.666), 0, 1);
3635
+ const cs = clamp2(0.2 * (dt / 16.666), 0, 1);
2884
3636
  const hc = this.heightAt(this.camera.position.x, this.camera.position.z);
2885
3637
  const cameraTerrain = hc === null ? this.floorY : hc;
2886
3638
  this.cameraHeight += (cameraTerrain - this.cameraHeight) * cs;
@@ -3100,7 +3852,7 @@ var MapControls = class _MapControls {
3100
3852
  if (e.deltaMode === 1) delta *= 16;
3101
3853
  else if (e.deltaMode === 2) delta *= 100;
3102
3854
  if (this.mode === "fly") {
3103
- this.moveSpeed = clamp(this.moveSpeed * Math.pow(1.0016, -delta), 0.05, 5);
3855
+ this.moveSpeed = clamp2(this.moveSpeed * Math.pow(1.0016, -delta), 0.05, 5);
3104
3856
  return;
3105
3857
  }
3106
3858
  this.zoomBuf += delta * 0.01;
@@ -3274,6 +4026,17 @@ var VantageViewer = class _VantageViewer {
3274
4026
  /** An in-flight atlas re-fetch, so the tile-insert gate and the progressive
3275
4027
  * poll coalesce onto one request instead of racing separate fetches. */
3276
4028
  atlasRefresh = null;
4029
+ // Live players: the scene layer, the roster it was last given, and the poll
4030
+ // that keeps it current. `playersAvailable` latches false once the world has
4031
+ // proved it serves no roster, so a static render costs one failed fetch
4032
+ // rather than one per second forever.
4033
+ playersLayer = null;
4034
+ playerSnapshot = NO_PLAYERS;
4035
+ playersAvailable = false;
4036
+ /** Who the camera is glued to, and where follow last put the pivot — the
4037
+ * comparison that lets a pan of the user's own release it. */
4038
+ following = null;
4039
+ followAnchor = new THREE2.Vector2();
3277
4040
  // Biome layer state machine.
3278
4041
  biomeEnabled = false;
3279
4042
  highlight = null;
@@ -3340,7 +4103,8 @@ var VantageViewer = class _VantageViewer {
3340
4103
  streaming: options.streaming ?? {},
3341
4104
  urlState: options.urlState ?? false,
3342
4105
  renderOnDemand: options.renderOnDemand ?? true,
3343
- caveGeometry: options.caveGeometry ?? "auto"
4106
+ caveGeometry: options.caveGeometry ?? "auto",
4107
+ players: options.players ?? {}
3344
4108
  };
3345
4109
  this.caveMode = this.options.caveGeometry;
3346
4110
  if (options.light) {
@@ -3513,6 +4277,17 @@ var VantageViewer = class _VantageViewer {
3513
4277
  biomes: this._biomes
3514
4278
  });
3515
4279
  this.emitter.emit("dimension", { dimensions: this.worldIndex, current: this.currentDimension });
4280
+ if (this.options.players.enabled !== false) {
4281
+ this.playersLayer = new PlayerLayer({
4282
+ scene: this.scene,
4283
+ camera: this.camera,
4284
+ fetchSkin: (path) => source.fetch(path),
4285
+ ...this.options.players.resolveSkin ? { resolveSkin: this.options.players.resolveSkin } : {},
4286
+ settings: this.options.players
4287
+ });
4288
+ this.playersLayer.setTone(this.light.exposure);
4289
+ void this.pollPlayers(source, this.playersLayer, manifest.dimension?.id ?? "minecraft:overworld");
4290
+ }
3516
4291
  if (manifest.rendering) {
3517
4292
  this.progressiveManager = this.tiles;
3518
4293
  this.lastProgress = null;
@@ -3618,8 +4393,15 @@ var VantageViewer = class _VantageViewer {
3618
4393
  if (this.tiles !== manager) return;
3619
4394
  }
3620
4395
  const changed = m.dynamic ? manager.syncTiles(m.tiles) : manager.addTiles(m.tiles);
4396
+ const lowresChanged = m.lowres ? manager.syncLowres(m.lowres) : false;
4397
+ if (lowresChanged) {
4398
+ this.manifest = m;
4399
+ this.updateWorldBounds(m);
4400
+ this.applyViewLimits();
4401
+ this.needsRender = true;
4402
+ }
3621
4403
  const progressed = this.emitProgress(m);
3622
- delay = !m.dynamic || changed || atlasGrew || progressed ? _VantageViewer.POLL_MS : Math.min(delay * 2, _VantageViewer.POLL_MAX_MS);
4404
+ delay = !m.dynamic || changed || lowresChanged || atlasGrew || progressed ? _VantageViewer.POLL_MS : Math.min(delay * 2, _VantageViewer.POLL_MAX_MS);
3623
4405
  if (!m.rendering) {
3624
4406
  this.manifest = m;
3625
4407
  if (m.lowres) manager.ingestLowres(m.lowres);
@@ -3631,6 +4413,127 @@ var VantageViewer = class _VantageViewer {
3631
4413
  }
3632
4414
  }
3633
4415
  }
4416
+ // --- live players ----------------------------------------------------------
4417
+ /**
4418
+ * Follow `players.json` for as long as this world is loaded.
4419
+ *
4420
+ * The roster is small and changes constantly while anyone is moving, so this
4421
+ * polls on its own short cadence rather than riding the manifest poll. A
4422
+ * conditional source turns a still world into a `304` per tick, and repeated
4423
+ * quiet ticks stretch the cadence — a map nobody is walking around on costs
4424
+ * almost nothing, and a player who starts moving is on screen within a tick.
4425
+ *
4426
+ * A world that serves no roster answers 404: after a few consecutive
4427
+ * failures the loop gives up for good rather than retrying forever against a
4428
+ * static render that will never have one.
4429
+ */
4430
+ async pollPlayers(source, layer, dimension) {
4431
+ const path = this.options.players.path ?? "players.json";
4432
+ const base = Math.max(200, this.options.players.pollMs ?? _VantageViewer.PLAYER_POLL_MS);
4433
+ const dec = new TextDecoder();
4434
+ let delay = base;
4435
+ let etag;
4436
+ let failures = 0;
4437
+ for (; ; ) {
4438
+ await new Promise((r) => setTimeout(r, delay));
4439
+ if (this.playersLayer !== layer) return;
4440
+ let snapshot;
4441
+ try {
4442
+ if (source.fetchConditional) {
4443
+ const res = await source.fetchConditional(path, etag);
4444
+ if (res === "unchanged") {
4445
+ failures = 0;
4446
+ delay = Math.min(delay * 1.5, base * _VantageViewer.PLAYER_POLL_RELAX);
4447
+ continue;
4448
+ }
4449
+ snapshot = parsePlayers(JSON.parse(dec.decode(res.buffer)), dimension);
4450
+ etag = res.etag;
4451
+ } else {
4452
+ snapshot = parsePlayers(JSON.parse(dec.decode(await source.fetch(path))), dimension);
4453
+ }
4454
+ } catch {
4455
+ if (!this.playersAvailable && ++failures >= _VantageViewer.PLAYER_POLL_GIVE_UP) return;
4456
+ delay = Math.min(delay * 2, base * _VantageViewer.PLAYER_POLL_RELAX);
4457
+ continue;
4458
+ }
4459
+ failures = 0;
4460
+ if (this.playersLayer !== layer) return;
4461
+ const changed = !this.playersAvailable || !samePlayers(this.playerSnapshot, snapshot);
4462
+ this.playersAvailable = true;
4463
+ this.playerSnapshot = snapshot;
4464
+ layer.setSnapshot(snapshot, performance.now());
4465
+ if (changed) {
4466
+ this.needsRender = true;
4467
+ this.emitPlayers();
4468
+ }
4469
+ delay = changed ? base : Math.min(delay * 1.5, base * _VantageViewer.PLAYER_POLL_RELAX);
4470
+ }
4471
+ }
4472
+ emitPlayers() {
4473
+ this.emitter.emit("players", {
4474
+ players: this.playersLayer?.players ?? [],
4475
+ source: this.playerSnapshot.source,
4476
+ updated: this.playerSnapshot.updated,
4477
+ available: this.playersAvailable
4478
+ });
4479
+ }
4480
+ /** The players on the map right now, with their live interpolated positions.
4481
+ * Empty when the world serves no roster. */
4482
+ get players() {
4483
+ return this.playersLayer?.players ?? [];
4484
+ }
4485
+ /** A player's face as a data URL, for HTML chrome outside the canvas (a
4486
+ * roster panel, a tooltip). Null until their model exists. */
4487
+ playerIcon(uuid) {
4488
+ return this.playersLayer?.headIcon(uuid) ?? null;
4489
+ }
4490
+ /** Change how players are drawn — names, offline/foreign visibility, model
4491
+ * scale. Applied immediately, no reload. */
4492
+ setPlayers(settings) {
4493
+ Object.assign(this.options.players, settings);
4494
+ this.playersLayer?.setSettings(settings);
4495
+ if (settings.enabled === false) this.followPlayer(null);
4496
+ this.needsRender = true;
4497
+ }
4498
+ /** Fly the camera to a player. Returns false if they aren't on this map. */
4499
+ focusPlayer(uuid) {
4500
+ const position = this.playersLayer?.positionOf(uuid);
4501
+ if (!position) return false;
4502
+ this.controls.animateTo({
4503
+ position,
4504
+ // Coming in from a whole-world view, land close enough to actually see
4505
+ // them; an already-close camera keeps the zoom the user chose.
4506
+ ...this.controls.distance > 260 ? { distance: 140 } : {}
4507
+ });
4508
+ this.needsRender = true;
4509
+ return true;
4510
+ }
4511
+ /** Keep the camera pinned to a player as they move — `null` releases it.
4512
+ * Panning the map releases it too: the pivot moving somewhere follow didn't
4513
+ * put it is the user saying they want to look elsewhere. */
4514
+ followPlayer(uuid) {
4515
+ const position = uuid === null ? null : this.playersLayer?.positionOf(uuid);
4516
+ if (uuid !== null && !position) return false;
4517
+ if (this.following === uuid) return true;
4518
+ this.following = uuid;
4519
+ if (position) {
4520
+ this.controls.setView({
4521
+ position,
4522
+ distance: this.controls.distance,
4523
+ rotation: this.controls.rotation,
4524
+ angle: this.controls.angle
4525
+ });
4526
+ this.followAnchor.set(position.x, position.z);
4527
+ }
4528
+ this.playersLayer?.setFollowed(uuid);
4529
+ this.emitter.emit("follow", { uuid });
4530
+ this.needsRender = true;
4531
+ return true;
4532
+ }
4533
+ /** Who the camera is following, if anyone. */
4534
+ get followedPlayer() {
4535
+ return this.following;
4536
+ }
3634
4537
  /** Ensure the terrain atlas covers at least `layers` texture-array layers,
3635
4538
  * re-fetching `terrain.vtexarr` if it's behind. Coalesces concurrent callers
3636
4539
  * — the on-demand tile-insert gate and the progressive poll — onto one
@@ -3925,6 +4828,7 @@ var VantageViewer = class _VantageViewer {
3925
4828
  this.shader.uniforms["uAmbient"].value = ambient;
3926
4829
  this.shader.uniforms["uDay"].value = this.light.daylight;
3927
4830
  this.shader.uniforms["uExposure"].value = this.light.exposure;
4831
+ this.playersLayer?.setTone(this.light.exposure);
3928
4832
  this.needsRender = true;
3929
4833
  }
3930
4834
  // --- depth slice (cave view) -------------------------------------------------
@@ -4362,11 +5266,18 @@ var VantageViewer = class _VantageViewer {
4362
5266
  /** Ceiling the poll cadence relaxes to while a continuous server reports no
4363
5267
  * changes — a saved world edit still shows up within ~one ceiling. */
4364
5268
  static POLL_MAX_MS = 5e3;
5269
+ /** Player roster cadence, and how far a quiet one is allowed to relax. */
5270
+ static PLAYER_POLL_MS = 1e3;
5271
+ static PLAYER_POLL_RELAX = 2.5;
5272
+ /** Consecutive failed roster fetches before concluding this world has none. */
5273
+ static PLAYER_POLL_GIVE_UP = 3;
4365
5274
  frame() {
4366
5275
  const now = performance.now();
4367
5276
  const dtMs = this.lastFrameMs ? now - this.lastFrameMs : 16.7;
4368
5277
  this.lastFrameMs = now;
5278
+ if (this.following) this.applyFollow();
4369
5279
  if (this.controls.update(dtMs)) this.needsRender = true;
5280
+ if (this.playersLayer?.update(now)) this.needsRender = true;
4370
5281
  if (this.tiles) {
4371
5282
  const focus = this.controls.flyMode ? this.camera.position : this.controls.position;
4372
5283
  this.tiles.update(focus.x, focus.z);
@@ -4406,6 +5317,25 @@ var VantageViewer = class _VantageViewer {
4406
5317
  this.lastRenderMs = now;
4407
5318
  this.draw(now);
4408
5319
  }
5320
+ /** Glue the pivot to the followed player, unless the user has moved it
5321
+ * themselves since the last frame — a deliberate pan outranks follow. */
5322
+ applyFollow() {
5323
+ const uuid = this.following;
5324
+ if (!uuid) return;
5325
+ const position = this.playersLayer?.positionOf(uuid);
5326
+ if (!position) {
5327
+ this.followPlayer(null);
5328
+ return;
5329
+ }
5330
+ const panned = Math.abs(this.controls.position.x - this.followAnchor.x) > 0.05 || Math.abs(this.controls.position.z - this.followAnchor.y) > 0.05;
5331
+ if (panned) {
5332
+ this.followPlayer(null);
5333
+ return;
5334
+ }
5335
+ this.controls.position.set(position.x, position.y, position.z);
5336
+ this.followAnchor.set(position.x, position.z);
5337
+ this.needsRender = true;
5338
+ }
4409
5339
  draw(now) {
4410
5340
  this.sky.position.copy(this.camera.position);
4411
5341
  if (this.shader) this.shader.uniforms["uTime"].value = now / 1e3 % 3600;
@@ -4460,6 +5390,13 @@ var VantageViewer = class _VantageViewer {
4460
5390
  this.manifest = null;
4461
5391
  this.progressiveManager = null;
4462
5392
  }
5393
+ if (this.playersLayer) {
5394
+ this.playersLayer.dispose();
5395
+ this.playersLayer = null;
5396
+ this.playerSnapshot = NO_PLAYERS;
5397
+ this.playersAvailable = false;
5398
+ this.following = null;
5399
+ }
4463
5400
  if (this.shader) {
4464
5401
  this.shader.uniforms["map"]?.value?.dispose();
4465
5402
  this.shader.uniforms["uPalette"]?.value?.dispose();
@@ -4495,4 +5432,4 @@ var VantageViewer = class _VantageViewer {
4495
5432
  }
4496
5433
  };
4497
5434
 
4498
- export { DEFAULT_ORBIT_ANGLE, MapControls, SKY_HORIZON, SKY_TOP, TileManager, VANILLA_DISPLAY, VantageViewer, applyCaveRange, buildLowresMesh, buildQuantizedTileMeshes, buildTerrain, buildTileMeshes, createLowresMaterial, createSky, createTerrainMaterial, createWaterMaterial, pickBiome, setSkyColors };
5435
+ export { DEFAULT_ORBIT_ANGLE, MapControls, PlayerLayer, SKIN_SIZE, SKY_HORIZON, SKY_TOP, TileManager, VANILLA_DISPLAY, VantageViewer, applyCaveRange, boxFaces, buildLowresMesh, buildQuantizedTileMeshes, buildTerrain, buildTileMeshes, createLowresMaterial, createSky, createTerrainMaterial, createWaterMaterial, defaultSkinCanvas, hashId, headIconCanvas, normalizeSkin, pickBiome, setSkyColors };