dredless 1.4.1 → 1.4.2

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.
@@ -3427,6 +3427,7 @@
3427
3427
  }
3428
3428
  function toUint8Array(value) {
3429
3429
  if (value instanceof Uint8Array) return value;
3430
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
3430
3431
  if (isArrayBufferLike(value)) return new Uint8Array(value);
3431
3432
  if (ArrayBuffer.isView(value)) {
3432
3433
  return new Uint8Array(value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength));
@@ -3729,18 +3730,32 @@
3729
3730
  }
3730
3731
  return chacha20Into(out, key, nonce, data.length, data);
3731
3732
  }
3733
+ var WORLD_KEY_CACHE = /* @__PURE__ */ new Map();
3734
+ var WORLD_KEY_CACHE_LIMIT = 64;
3735
+ var MATERIAL_SCRATCH = new Uint8Array(44);
3736
+ function worldKeyBytes(worldId, seed) {
3737
+ const text2 = `${worldId}${seed}`;
3738
+ let bytes = WORLD_KEY_CACHE.get(text2);
3739
+ if (!bytes) {
3740
+ if (WORLD_KEY_CACHE.size >= WORLD_KEY_CACHE_LIMIT) WORLD_KEY_CACHE.clear();
3741
+ bytes = encoder.encode(text2);
3742
+ WORLD_KEY_CACHE.set(text2, bytes);
3743
+ }
3744
+ return bytes;
3745
+ }
3732
3746
  function decryptPayload(wireBytes, worldId, seed) {
3733
3747
  const wire = toUint8Array(wireBytes);
3734
- if (wire.length < 8) throw new Error("payload too short");
3735
- const view = new DataView(wire.buffer, wire.byteOffset, wire.byteLength);
3736
- const packetWordA = view.getUint32(0, true);
3737
- const packetWordB = view.getUint32(wire.length - 4, true);
3738
- const material = Uint8Array.from(SHARED_CHACHA_MATERIAL);
3739
- const worldKey = encoder.encode(`${worldId}${seed}`);
3748
+ const length = wire.length;
3749
+ if (length < 8) throw new Error("payload too short");
3750
+ const packetWordA = readLe32(wire, 0);
3751
+ const packetWordB = readLe32(wire, length - 4);
3752
+ const material = MATERIAL_SCRATCH;
3753
+ const worldKey = worldKeyBytes(worldId, seed);
3754
+ const keyLength = worldKey.length;
3740
3755
  for (let i = 0, l = 0, r = 0; i < 44; i++, l += 7, r += 11) {
3741
- material[i] ^= worldKey[i % worldKey.length] ^ rotl32(packetWordA, l) & 255 ^ rotr32(packetWordB, r) & 255;
3756
+ material[i] = SHARED_CHACHA_MATERIAL[i] ^ worldKey[i % keyLength] ^ rotl32(packetWordA, l) & 255 ^ rotr32(packetWordB, r) & 255;
3742
3757
  }
3743
- const ciphertext = wire.subarray(4, wire.length - 4);
3758
+ const ciphertext = wire.subarray(4, length - 4);
3744
3759
  return chacha20Xor(material.subarray(0, 32), material.subarray(32, 44), ciphertext);
3745
3760
  }
3746
3761
 
@@ -3957,10 +3972,36 @@
3957
3972
  for (let i = 0; i < count; i++) items[i] = readFast(bytes);
3958
3973
  return items;
3959
3974
  }
3975
+ var KEY_CACHE = /* @__PURE__ */ new Map();
3976
+ var KEY_CACHE_LIMIT = 512;
3977
+ function readKeyFast(bytes) {
3978
+ const head = bytes[cursor];
3979
+ if ((head & 224) !== 160) return readFast(bytes);
3980
+ const len = head & 31;
3981
+ const start = cursor + 1;
3982
+ const end = start + len;
3983
+ if (end > bytes.length) return readFast(bytes);
3984
+ let hash = len;
3985
+ for (let i = start; i < end; i++) hash = Math.imul(hash, 31) + bytes[i] | 0;
3986
+ const entry = KEY_CACHE.get(hash);
3987
+ if (entry !== void 0) {
3988
+ const cached = entry.bytes;
3989
+ let same = cached.length === len;
3990
+ for (let i = 0; same && i < len; i++) same = cached[i] === bytes[start + i];
3991
+ if (same) {
3992
+ cursor = end;
3993
+ return entry.text;
3994
+ }
3995
+ }
3996
+ cursor = start;
3997
+ const text2 = readStrFast(bytes, len);
3998
+ if (entry === void 0 && KEY_CACHE.size < KEY_CACHE_LIMIT) KEY_CACHE.set(hash, { bytes: bytes.slice(start, end), text: text2 });
3999
+ return text2;
4000
+ }
3960
4001
  function readMapFast(bytes, count) {
3961
4002
  const obj = {};
3962
4003
  for (let i = 0; i < count; i++) {
3963
- const key = readFast(bytes);
4004
+ const key = readKeyFast(bytes);
3964
4005
  obj[typeof key === "string" ? key : String(key)] = readFast(bytes);
3965
4006
  }
3966
4007
  return obj;
@@ -4609,12 +4650,14 @@
4609
4650
  if (!resolved) {
4610
4651
  cached = compute();
4611
4652
  resolved = true;
4653
+ compute = null;
4612
4654
  }
4613
4655
  return cached;
4614
4656
  },
4615
4657
  set(value) {
4616
4658
  cached = value;
4617
4659
  resolved = true;
4660
+ compute = null;
4618
4661
  }
4619
4662
  });
4620
4663
  return target;
@@ -5015,6 +5058,7 @@
5015
5058
  for (const blob of spec.blobs || []) blob.key = blobKey(blob.offset);
5016
5059
  for (const item of spec.packedBits || []) item.key = qKey(item.offset);
5017
5060
  if (spec.packedOffsets) spec.packedOffsetKeys = spec.packedOffsets.map(qKey);
5061
+ spec.packedAnyMask = (spec.packedBits || []).reduce((mask, item) => mask | item.bit, spec.packedMask || 0);
5018
5062
  if (spec.orderedValues) {
5019
5063
  spec.orderedItems = [
5020
5064
  ...(spec.blobs || []).map((item) => ({ bit: item.bit, offset: item.offset, key: item.key, kind: "blob" })),
@@ -6468,7 +6512,7 @@
6468
6512
  entity(entityId) {
6469
6513
  const id = Number(entityId);
6470
6514
  if (!Number.isFinite(id)) return null;
6471
- return this.#derivedState().entitiesById.get(id) || null;
6515
+ return this.#derivedEntityIndex().entitiesById.get(id) || null;
6472
6516
  }
6473
6517
  entities() {
6474
6518
  return this.#derivedState().entities.slice();
@@ -6480,7 +6524,7 @@
6480
6524
  // O(1) point lookup. Callers previously had to materialise and scan the whole
6481
6525
  // block list to answer this.
6482
6526
  blockAt(x, y) {
6483
- this.#derivedState();
6527
+ this.#derivedEntityIndex();
6484
6528
  return this.#blocksIndex().get(blockKey2(x, y)) || null;
6485
6529
  }
6486
6530
  apply(bytes, { full = false } = {}) {
@@ -6656,18 +6700,38 @@
6656
6700
  this._derived = null;
6657
6701
  }
6658
6702
  #updateDerived(update) {
6659
- if (!this._derived) return;
6703
+ const derived = this._derived;
6704
+ if (!derived) return;
6660
6705
  if (!update.removals.length && !update.changedEntities.size) return;
6661
6706
  for (const section2 of update.sections) {
6662
6707
  for (const record of section2.records || []) this.#addDerivedEntityTable(record.entity, section2.table);
6663
6708
  }
6709
+ const dirty = derived.dirtyEntities ??= /* @__PURE__ */ new Set();
6664
6710
  if (update.sections.some((section2) => section2.table === 12)) {
6665
6711
  for (const entityId of this.table(55).keys()) update.changedEntities.add(entityId);
6666
6712
  }
6667
- for (const entityId of update.removals) this.#removeDerivedEntity(entityId);
6668
- for (const entityId of update.changedEntities) this.#refreshDerivedEntity(entityId);
6669
- this._derived.summariesDirty = true;
6670
- this._derived.tableSummariesDirty = true;
6713
+ for (const entityId of update.removals) {
6714
+ derived.entityTableIds.delete(entityId);
6715
+ dirty.add(entityId);
6716
+ }
6717
+ for (const entityId of update.changedEntities) dirty.add(entityId);
6718
+ }
6719
+ #flushDerivedEntities() {
6720
+ const derived = this._derived;
6721
+ const dirty = derived.dirtyEntities;
6722
+ if (!dirty || dirty.size === 0) return;
6723
+ derived.dirtyEntities = null;
6724
+ for (const entityId of dirty) this.#refreshDerivedEntity(entityId);
6725
+ derived.summariesDirty = true;
6726
+ derived.tableSummariesDirty = true;
6727
+ }
6728
+ // Current entity summaries without the per-category lists. Point lookups go
6729
+ // through here: rebuilding those lists is O(total entities) and was the whole
6730
+ // cost of entity(id) on a large world.
6731
+ #derivedEntityIndex() {
6732
+ if (!this._derived) return this.#derivedState();
6733
+ this.#flushDerivedEntities();
6734
+ return this._derived;
6671
6735
  }
6672
6736
  #updateNavigationUnitAutoWarp(update) {
6673
6737
  const trackedBeforeUpdate = new Set(this.#navigationUnitAutoWarp.keys());
@@ -6782,6 +6846,7 @@
6782
6846
  }
6783
6847
  #derivedState() {
6784
6848
  if (this._derived) {
6849
+ this.#flushDerivedEntities();
6785
6850
  this.#ensureDerivedSummaries();
6786
6851
  return this._derived;
6787
6852
  }
@@ -6859,7 +6924,7 @@
6859
6924
  if (old) this.#removeEntityFromDerivedBlocks(derived, old);
6860
6925
  const next = this.#summarizeEntity(entityId, rows);
6861
6926
  derived.entitiesById.set(entityId, next);
6862
- if (!derived.entityIds.includes(entityId)) insertSorted(derived.entityIds, entityId);
6927
+ if (!old) insertSorted(derived.entityIds, entityId);
6863
6928
  this.#addEntityToDerivedBlocks(derived, next);
6864
6929
  derived.entityCount = derived.entityIds.length;
6865
6930
  }
@@ -7403,9 +7468,7 @@
7403
7468
  if (spec.scale) record.scaled = spec.scale(record);
7404
7469
  return;
7405
7470
  }
7406
- const hasPacked = Boolean(
7407
- spec.packedMask && mask & spec.packedMask || spec.packedBits?.some((item) => mask & item.bit)
7408
- );
7471
+ const hasPacked = (mask & spec.packedAnyMask) !== 0;
7409
7472
  let packed = null;
7410
7473
  if (hasPacked && spec.packedBeforeValues) packed = reader.readUnsigned();
7411
7474
  let packedIndex = 0;
@@ -7670,10 +7733,58 @@
7670
7733
  target.push(value);
7671
7734
  if (target.length > limit) target.splice(0, target.length - limit);
7672
7735
  }
7673
- var TILE_KEY_OFFSET = 1 << 24;
7674
- var TILE_KEY_STRIDE = 1 << 25;
7736
+ var CHUNK_SIZE = 64;
7737
+ var CHUNK_CELLS = CHUNK_SIZE * CHUNK_SIZE;
7738
+ var COLUMN_SHAPE = CHUNK_CELLS;
7739
+ var COLUMN_HP = CHUNK_CELLS * 2;
7740
+ var COLUMN_COLOR = CHUNK_CELLS * 3;
7741
+ var COLUMN_FLAGS = CHUNK_CELLS * 4;
7742
+ var CHUNK_COORD_LIMIT = 1 << 15;
7743
+ var TILE_COORD_LIMIT = CHUNK_COORD_LIMIT * CHUNK_SIZE;
7744
+ var TILE_OBJECT_KEY_COUNT = 13;
7745
+ var CONCAT_BATCH = 4096;
7746
+ var TileFlags = Object.freeze({
7747
+ /** The cell holds a tile. Zero means the cell is empty. */
7748
+ Present: 1,
7749
+ /** The tile was sent without a color; its `color` is null. */
7750
+ NoColor: 2
7751
+ });
7752
+ var SHAPE_NAMES_BY_ID = Array.from({ length: 256 }, (_, shape) => TILE_SHAPE_NAMES.get(shape) ?? null);
7753
+ var isByte = (value) => typeof value === "number" && (value & 255) === value;
7754
+ var isCellIndex = (value) => Number.isInteger(value) && value >= 0 && value < CHUNK_SIZE;
7755
+ var isChunkCoord = (value) => Number.isInteger(value) && value >= -CHUNK_COORD_LIMIT && value < CHUNK_COORD_LIMIT;
7756
+ var isTileCoord = (value) => Number.isInteger(value) && value >= -TILE_COORD_LIMIT && value < TILE_COORD_LIMIT;
7757
+ var chunkKey = (chunkX, chunkY) => (chunkY + CHUNK_COORD_LIMIT) * (CHUNK_COORD_LIMIT * 2) + (chunkX + CHUNK_COORD_LIMIT);
7758
+ var looseTileKey = (x, y) => `${x},${y}`;
7759
+ var TileCollection = class {
7760
+ #count;
7761
+ #objects;
7762
+ constructor(count, objects) {
7763
+ this.#count = count;
7764
+ this.#objects = objects;
7765
+ }
7766
+ get size() {
7767
+ return this.#count();
7768
+ }
7769
+ // A fresh array of every tile.
7770
+ toArray() {
7771
+ return this.#objects().slice();
7772
+ }
7773
+ };
7675
7774
  var WorldState = class {
7676
- #materialCounts = /* @__PURE__ */ new Map();
7775
+ #chunkGrids = /* @__PURE__ */ new Map();
7776
+ // Tiles the columns cannot hold: non-byte values, out-of-range coordinates,
7777
+ // or extra caller fields. Only reachable through setTile()/malformed patches.
7778
+ #looseTiles = /* @__PURE__ */ new Map();
7779
+ #chunkViews = null;
7780
+ #tileVersion = 0;
7781
+ #tileStats = null;
7782
+ #tileStatsVersion = -1;
7783
+ #tileObjects = null;
7784
+ #tileObjectsVersion = -1;
7785
+ #tileObjectsRequestedVersion = -1;
7786
+ #materialDefs = null;
7787
+ #materialDefsTileset = null;
7677
7788
  constructor(id, limits = {}) {
7678
7789
  this.historyLimits = {
7679
7790
  eventHistory: normalizeLimit(limits.eventHistory, DEFAULT_HISTORY_LIMITS.eventHistory),
@@ -7690,7 +7801,7 @@
7690
7801
  this.blockHeight = null;
7691
7802
  this.parentWorld = null;
7692
7803
  this.parentEntity = null;
7693
- this.tiles = /* @__PURE__ */ new Map();
7804
+ this.tiles = new TileCollection(() => this.#readTileStats().count, () => this.#readTileObjects());
7694
7805
  this.chunks = [];
7695
7806
  this.events = [];
7696
7807
  this.modelPackets = [];
@@ -7751,6 +7862,12 @@
7751
7862
  return this.setTile({ x, y, material, shape, hp, integrity: hp, color });
7752
7863
  }
7753
7864
  applyChunk(value) {
7865
+ const patch = this.applyChunkPatch(value);
7866
+ return patch ? patch.tiles : null;
7867
+ }
7868
+ // Applies a chunk patch and returns its history entry. The entry's `tiles`
7869
+ // array is built on first read, so ingestion never allocates tile objects.
7870
+ applyChunkPatch(value) {
7754
7871
  if (!Array.isArray(value) || value.length !== 7) return null;
7755
7872
  const [chunkX, chunkY, minX, minY, maxX, maxY, compressedPatch] = value;
7756
7873
  const patch = decompressWorldChunk(compressedPatch);
@@ -7758,32 +7875,143 @@
7758
7875
  const height = maxY - minY + 1;
7759
7876
  const count = width * height;
7760
7877
  const hasColor = patch.length >= count * 4;
7761
- const tiles = new Array(count);
7762
7878
  const baseX = chunkX << 6;
7763
7879
  const baseY = chunkY << 6;
7764
- for (let i = 0; i < count; i++) {
7765
- const localX = minX + i % width;
7766
- const localY = minY + Math.floor(i / width);
7767
- const hp = patch[i + count * 2];
7768
- tiles[i] = this.#storeTile(this.#buildTile(
7769
- baseX + localX,
7770
- baseY + localY,
7771
- patch[i],
7772
- patch[i + count],
7773
- hp,
7774
- hasColor ? patch[i + count * 3] : null
7775
- ));
7880
+ const entry = { chunkX, chunkY, minX, minY, maxX, maxY };
7881
+ const wellFormed = isChunkCoord(chunkX) && isChunkCoord(chunkY) && isCellIndex(minX) && isCellIndex(minY) && isCellIndex(maxX) && isCellIndex(maxY) && width > 0 && height > 0 && patch.length >= count * 3;
7882
+ if (wellFormed) {
7883
+ this.#writeChunkColumns(this.#chunkGrid(chunkX, chunkY), patch, minX, minY, width, height, hasColor);
7884
+ defineLazyProperty(entry, "tiles", () => {
7885
+ const tiles = new Array(count);
7886
+ for (let i = 0; i < count; i++) {
7887
+ tiles[i] = this.#buildTile(
7888
+ baseX + minX + i % width,
7889
+ baseY + minY + Math.floor(i / width),
7890
+ patch[i],
7891
+ patch[i + count],
7892
+ patch[i + count * 2],
7893
+ hasColor ? patch[i + count * 3] : null
7894
+ );
7895
+ }
7896
+ return tiles;
7897
+ });
7898
+ } else {
7899
+ const tiles = new Array(count);
7900
+ for (let i = 0; i < count; i++) {
7901
+ tiles[i] = this.#storeTile(this.#buildTile(
7902
+ baseX + minX + i % width,
7903
+ baseY + minY + Math.floor(i / width),
7904
+ patch[i],
7905
+ patch[i + count],
7906
+ patch[i + count * 2],
7907
+ hasColor ? patch[i + count * 3] : null
7908
+ ));
7909
+ }
7910
+ entry.tiles = tiles;
7776
7911
  }
7777
7912
  this.totalChunkCount += 1;
7778
- pushBounded(this.chunks, { chunkX, chunkY, minX, minY, maxX, maxY, tiles }, this.historyLimits.chunkHistory);
7913
+ pushBounded(this.chunks, entry, this.historyLimits.chunkHistory);
7779
7914
  this.lastChunkPatch = { chunkX, chunkY, minX, minY, maxX, maxY, count, hasColor };
7780
- return tiles;
7915
+ return entry;
7781
7916
  }
7782
7917
  setTile(tile) {
7783
7918
  return this.#storeTile(this.normalizeTile(tile));
7784
7919
  }
7785
- // Chunk decoding produces millions of tiles at join time, so build the final
7786
- // object in one pass instead of a literal plus a spread copy.
7920
+ /** Bumped on every tile write; compare to skip work when nothing changed. */
7921
+ get tileVersion() {
7922
+ return this.#tileVersion;
7923
+ }
7924
+ // Zero-copy access for consumers that scan tiles every tick. The returned
7925
+ // views are live and stable for the life of the chunk: read the typed arrays
7926
+ // directly and use each view's `version` to skip chunks that have not changed.
7927
+ tileChunks() {
7928
+ return this.#chunkViews ??= Array.from(this.#chunkGrids.values(), (grid) => grid.view);
7929
+ }
7930
+ tileAt(x, y) {
7931
+ if (this.#looseTiles.size > 0) {
7932
+ const loose = this.#looseTiles.get(looseTileKey(x, y));
7933
+ if (loose) return loose;
7934
+ }
7935
+ if (!isTileCoord(x) || !isTileCoord(y)) return null;
7936
+ const grid = this.#chunkGrids.get(chunkKey(x >> 6, y >> 6));
7937
+ if (!grid) return null;
7938
+ const data = grid.data;
7939
+ const cell = (y & 63) << 6 | x & 63;
7940
+ const flags = data[COLUMN_FLAGS + cell];
7941
+ if (flags === 0) return null;
7942
+ return this.#buildTile(
7943
+ x,
7944
+ y,
7945
+ data[cell],
7946
+ data[COLUMN_SHAPE + cell],
7947
+ data[COLUMN_HP + cell],
7948
+ flags & TileFlags.NoColor ? null : data[COLUMN_COLOR + cell]
7949
+ );
7950
+ }
7951
+ // Drops tile objects retained for repeated `tiles.toArray()` reads. They are
7952
+ // rebuilt on the next read.
7953
+ releaseTileObjects() {
7954
+ this.#tileObjects = null;
7955
+ this.#tileObjectsRequestedVersion = -1;
7956
+ for (const grid of this.#chunkGrids.values()) {
7957
+ grid.objects = null;
7958
+ grid.objectsRequestedVersion = -1;
7959
+ }
7960
+ }
7961
+ #chunkGrid(chunkX, chunkY) {
7962
+ const key = chunkKey(chunkX, chunkY);
7963
+ let grid = this.#chunkGrids.get(key);
7964
+ if (!grid) {
7965
+ const data = new Uint8Array(CHUNK_CELLS * 5);
7966
+ grid = {
7967
+ data,
7968
+ stats: null,
7969
+ objects: null,
7970
+ objectsRequestedVersion: -1,
7971
+ view: {
7972
+ chunkX,
7973
+ chunkY,
7974
+ originX: chunkX << 6,
7975
+ originY: chunkY << 6,
7976
+ version: 0,
7977
+ material: data.subarray(0, COLUMN_SHAPE),
7978
+ shape: data.subarray(COLUMN_SHAPE, COLUMN_HP),
7979
+ hp: data.subarray(COLUMN_HP, COLUMN_COLOR),
7980
+ color: data.subarray(COLUMN_COLOR, COLUMN_FLAGS),
7981
+ flags: data.subarray(COLUMN_FLAGS, COLUMN_FLAGS + CHUNK_CELLS)
7982
+ }
7983
+ };
7984
+ this.#chunkGrids.set(key, grid);
7985
+ this.#chunkViews = null;
7986
+ }
7987
+ return grid;
7988
+ }
7989
+ // The only bookkeeping a tile write does. Counts and tile objects are derived
7990
+ // later, on demand, from whichever chunks were touched.
7991
+ #touchChunk(grid) {
7992
+ grid.stats = null;
7993
+ grid.objects = null;
7994
+ grid.view.version = ++this.#tileVersion;
7995
+ }
7996
+ #writeChunkColumns(grid, patch, minX, minY, width, height, hasColor) {
7997
+ const data = grid.data;
7998
+ const count = width * height;
7999
+ const columns = hasColor ? 4 : 3;
8000
+ const flag = hasColor ? TileFlags.Present : TileFlags.Present | TileFlags.NoColor;
8001
+ const rows = width === CHUNK_SIZE ? 1 : height;
8002
+ const span = width === CHUNK_SIZE ? count : width;
8003
+ for (let row = 0; row < rows; row++) {
8004
+ const start = (minY + row << 6) + minX;
8005
+ const from = row * width;
8006
+ for (let column = 0; column < columns; column++) {
8007
+ const source = column * count + from;
8008
+ data.set(patch.subarray(source, source + span), column * CHUNK_CELLS + start);
8009
+ }
8010
+ if (!hasColor) data.fill(0, COLUMN_COLOR + start, COLUMN_COLOR + start + span);
8011
+ data.fill(flag, COLUMN_FLAGS + start, COLUMN_FLAGS + start + span);
8012
+ }
8013
+ this.#touchChunk(grid);
8014
+ }
7787
8015
  #buildTile(x, y, material, shape, hp, color) {
7788
8016
  const def = this.tileDefinition(material);
7789
8017
  const maxHp = def?.hp ?? null;
@@ -7804,22 +8032,147 @@
7804
8032
  hpValue: typeof value === "number" && typeof maxHp === "number" ? Math.round(value / 255 * maxHp) : null
7805
8033
  };
7806
8034
  }
7807
- // Numeric key: a template string per tile was a measurable share of chunk
7808
- // decode. The map is only ever read through values()/size, so the key format
7809
- // is internal.
7810
- #storeTile(normalized) {
7811
- const key = (normalized.y + TILE_KEY_OFFSET) * TILE_KEY_STRIDE + (normalized.x + TILE_KEY_OFFSET);
7812
- const previous = this.tiles.get(key);
7813
- if (previous !== void 0) this.#countMaterial(previous.material, -1);
7814
- this.#countMaterial(normalized.material, 1);
7815
- this.tiles.set(key, normalized);
7816
- return normalized;
7817
- }
7818
- #countMaterial(material, delta) {
7819
- const id = Number(material);
7820
- const next = (this.#materialCounts.get(id) || 0) + delta;
7821
- if (next > 0) this.#materialCounts.set(id, next);
7822
- else this.#materialCounts.delete(id);
8035
+ #storeTile(tile) {
8036
+ const { x, y } = tile;
8037
+ const inRange = isTileCoord(x) && isTileCoord(y);
8038
+ const columnar = inRange && isByte(tile.material) && isByte(tile.shape) && isByte(tile.hp) && (tile.color === null || isByte(tile.color)) && Object.keys(tile).length === TILE_OBJECT_KEY_COUNT;
8039
+ if (this.#looseTiles.size > 0 && this.#looseTiles.delete(looseTileKey(x, y))) this.#tileVersion++;
8040
+ if (columnar) {
8041
+ const grid2 = this.#chunkGrid(x >> 6, y >> 6);
8042
+ const data = grid2.data;
8043
+ const cell = (y & 63) << 6 | x & 63;
8044
+ data[cell] = tile.material;
8045
+ data[COLUMN_SHAPE + cell] = tile.shape;
8046
+ data[COLUMN_HP + cell] = tile.hp;
8047
+ data[COLUMN_COLOR + cell] = tile.color ?? 0;
8048
+ data[COLUMN_FLAGS + cell] = tile.color === null ? TileFlags.Present | TileFlags.NoColor : TileFlags.Present;
8049
+ this.#touchChunk(grid2);
8050
+ return tile;
8051
+ }
8052
+ const grid = inRange ? this.#chunkGrids.get(chunkKey(x >> 6, y >> 6)) : void 0;
8053
+ if (grid) {
8054
+ const cell = (y & 63) << 6 | x & 63;
8055
+ if (grid.data[COLUMN_FLAGS + cell] !== 0) {
8056
+ grid.data[COLUMN_FLAGS + cell] = 0;
8057
+ this.#touchChunk(grid);
8058
+ }
8059
+ }
8060
+ this.#looseTiles.set(looseTileKey(x, y), tile);
8061
+ this.#tileVersion++;
8062
+ return tile;
8063
+ }
8064
+ // Tile and material counts, derived from the columns on first read after a
8065
+ // write. Only chunks touched since the last read are rescanned.
8066
+ #readTileStats() {
8067
+ if (this.#tileStats && this.#tileStatsVersion === this.#tileVersion) return this.#tileStats;
8068
+ const totals = new Int32Array(256);
8069
+ let count = 0;
8070
+ for (const grid of this.#chunkGrids.values()) {
8071
+ let stats = grid.stats;
8072
+ if (!stats) {
8073
+ const data = grid.data;
8074
+ const histogram2 = new Uint16Array(256);
8075
+ let present = 0;
8076
+ for (let cell = 0; cell < CHUNK_CELLS; cell++) {
8077
+ if (data[COLUMN_FLAGS + cell] === 0) continue;
8078
+ histogram2[data[cell]]++;
8079
+ present++;
8080
+ }
8081
+ stats = grid.stats = { count: present, histogram: histogram2 };
8082
+ }
8083
+ count += stats.count;
8084
+ const histogram = stats.histogram;
8085
+ for (let material = 0; material < 256; material++) totals[material] += histogram[material];
8086
+ }
8087
+ const materials = /* @__PURE__ */ new Map();
8088
+ for (let material = 0; material < 256; material++) {
8089
+ if (totals[material] > 0) materials.set(material, totals[material]);
8090
+ }
8091
+ for (const tile of this.#looseTiles.values()) {
8092
+ const id = Number(tile.material);
8093
+ materials.set(id, (materials.get(id) || 0) + 1);
8094
+ count++;
8095
+ }
8096
+ this.#tileStatsVersion = this.#tileVersion;
8097
+ return this.#tileStats = { count, materials };
8098
+ }
8099
+ // Per-material fields of a tile object, resolved once per tileset instead of
8100
+ // once per tile.
8101
+ #readMaterialDefs() {
8102
+ if (this.#materialDefs && this.#materialDefsTileset === this.tileset) return this.#materialDefs;
8103
+ const defs = new Array(256);
8104
+ for (let material = 0; material < 256; material++) {
8105
+ const def = this.tileDefinition(material);
8106
+ defs[material] = { name: def?.name ?? null, solid: def?.solid ?? null, maxHp: def?.hp ?? null };
8107
+ }
8108
+ this.#materialDefsTileset = this.tileset;
8109
+ return this.#materialDefs = defs;
8110
+ }
8111
+ #buildChunkTiles(grid) {
8112
+ const defs = this.#readMaterialDefs();
8113
+ const data = grid.data;
8114
+ const baseX = grid.view.originX;
8115
+ const baseY = grid.view.originY;
8116
+ const tiles = [];
8117
+ for (let cell = 0; cell < CHUNK_CELLS; cell++) {
8118
+ const flags = data[COLUMN_FLAGS + cell];
8119
+ if (flags === 0) continue;
8120
+ const material = data[cell];
8121
+ const shape = data[COLUMN_SHAPE + cell];
8122
+ const hp = data[COLUMN_HP + cell];
8123
+ const def = defs[material];
8124
+ const maxHp = def.maxHp;
8125
+ tiles.push({
8126
+ x: baseX + (cell & 63),
8127
+ y: baseY + (cell >> 6),
8128
+ material,
8129
+ shape,
8130
+ hp,
8131
+ integrity: hp,
8132
+ color: flags & TileFlags.NoColor ? null : data[COLUMN_COLOR + cell],
8133
+ materialName: def.name,
8134
+ shapeName: SHAPE_NAMES_BY_ID[shape],
8135
+ solid: def.solid,
8136
+ maxHp,
8137
+ hpRatio: hp / 255,
8138
+ hpValue: typeof maxHp === "number" ? Math.round(hp / 255 * maxHp) : null
8139
+ });
8140
+ }
8141
+ return tiles;
8142
+ }
8143
+ // Every tile as an object. Objects are retained only once a caller asks a
8144
+ // second time for the same unchanged data, so a one-off dump leaves nothing
8145
+ // behind while a caller that polls pays only for chunks that changed.
8146
+ #readTileObjects() {
8147
+ if (this.#materialDefsTileset !== this.tileset) {
8148
+ this.releaseTileObjects();
8149
+ this.#materialDefs = null;
8150
+ }
8151
+ const version = this.#tileVersion;
8152
+ if (this.#tileObjects && this.#tileObjectsVersion === version) return this.#tileObjects;
8153
+ const parts = [];
8154
+ for (const grid of this.#chunkGrids.values()) {
8155
+ let tiles = grid.objects;
8156
+ if (!tiles) {
8157
+ tiles = this.#buildChunkTiles(grid);
8158
+ if (grid.objectsRequestedVersion === grid.view.version) grid.objects = tiles;
8159
+ else grid.objectsRequestedVersion = grid.view.version;
8160
+ }
8161
+ parts.push(tiles);
8162
+ }
8163
+ if (this.#looseTiles.size > 0) parts.push([...this.#looseTiles.values()]);
8164
+ let out = [];
8165
+ for (let start = 0; start < parts.length; start += CONCAT_BATCH) {
8166
+ out = out.concat(...parts.slice(start, start + CONCAT_BATCH));
8167
+ }
8168
+ if (this.#tileObjectsRequestedVersion === version) {
8169
+ this.#tileObjects = out;
8170
+ this.#tileObjectsVersion = version;
8171
+ } else {
8172
+ this.#tileObjects = null;
8173
+ this.#tileObjectsRequestedVersion = version;
8174
+ }
8175
+ return out;
7823
8176
  }
7824
8177
  normalizeTile(tile) {
7825
8178
  const def = this.tileDefinition(tile.material);
@@ -7837,10 +8190,8 @@
7837
8190
  hpValue: typeof hp === "number" && typeof maxHp === "number" ? Math.round(hp / 255 * maxHp) : null
7838
8191
  };
7839
8192
  }
7840
- // Counts are maintained as tiles are stored; this used to rescan every tile
7841
- // on each call and ran on every snapshot.
7842
8193
  materials() {
7843
- return [...this.#materialCounts.entries()].sort((a, b) => a[0] - b[0]).map(([material, count]) => {
8194
+ return [...this.#readTileStats().materials.entries()].sort((a, b) => a[0] - b[0]).map(([material, count]) => {
7844
8195
  const def = this.tileDefinition(material);
7845
8196
  return {
7846
8197
  material,
@@ -7865,7 +8216,7 @@
7865
8216
  block_h: this.blockHeight,
7866
8217
  parent_world: this.parentWorld,
7867
8218
  parent_ent: this.parentEntity,
7868
- tileCount: this.tiles.size,
8219
+ tileCount: this.#readTileStats().count,
7869
8220
  chunkCount: this.totalChunkCount,
7870
8221
  lastChunkPatch: this.lastChunkPatch,
7871
8222
  lastPacket: this.lastPacket,
@@ -7886,7 +8237,7 @@
7886
8237
  pvpEvent: model.pvpEvent,
7887
8238
  pvpParties: model.pvpParties,
7888
8239
  commsBubbles: this.commsBubbles.slice(),
7889
- tiles: includeTiles ? [...this.tiles.values()] : void 0
8240
+ tiles: includeTiles ? this.tiles.toArray() : void 0
7890
8241
  };
7891
8242
  }
7892
8243
  table(id) {
@@ -8036,8 +8387,10 @@
8036
8387
  if (decoded && typeof decoded === "object") {
8037
8388
  for (const [kind, value] of Object.entries(decoded)) {
8038
8389
  try {
8039
- if (kind === "0") updates.push({ kind, tiles: world.applyChunk(value) });
8040
- else if (kind === "1") updates.push({ kind, tile: world.applyTile(value) });
8390
+ if (kind === "0") {
8391
+ const patch = world.applyChunkPatch(value);
8392
+ updates.push(defineLazyProperty({ kind }, "tiles", () => patch ? patch.tiles : null));
8393
+ } else if (kind === "1") updates.push({ kind, tile: world.applyTile(value) });
8041
8394
  else updates.push({ kind, value });
8042
8395
  } catch (error) {
8043
8396
  errors.push(error);
@@ -9600,6 +9953,7 @@
9600
9953
  this.recyclers = new EntitySummaryCollection(client, scope, "recyclers");
9601
9954
  this.blocks = new BlockCollection(client, scope);
9602
9955
  this.materials = new MaterialCollection(client, scope);
9956
+ this.tiles = new TileDomain(client, scope);
9603
9957
  }
9604
9958
  get id() {
9605
9959
  return worldStateFor(this.client, this.scope)?.id ?? null;
@@ -9800,6 +10154,27 @@
9800
10154
  return worldStateFor(this.client, this.scope)?.materials() || [];
9801
10155
  }
9802
10156
  };
10157
+ var TileDomain = class {
10158
+ constructor(client, scope) {
10159
+ this.client = client;
10160
+ this.scope = scope;
10161
+ }
10162
+ get count() {
10163
+ return worldStateFor(this.client, this.scope)?.tiles.size ?? 0;
10164
+ }
10165
+ get version() {
10166
+ return worldStateFor(this.client, this.scope)?.tileVersion ?? 0;
10167
+ }
10168
+ chunks() {
10169
+ return worldStateFor(this.client, this.scope)?.tileChunks() || [];
10170
+ }
10171
+ at(x, y) {
10172
+ return worldStateFor(this.client, this.scope)?.tileAt(x, y) ?? null;
10173
+ }
10174
+ all() {
10175
+ return worldStateFor(this.client, this.scope)?.tiles.toArray() || [];
10176
+ }
10177
+ };
9803
10178
  var MachineCollection = class {
9804
10179
  constructor(client, scope) {
9805
10180
  this.client = client;