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.
@@ -1,5 +1,6 @@
1
- import {decodeModelPayload, decodeWorldPayload, decompressWorldChunk} from "../../protocol/inbound/world-payload.js";
1
+ import {decodeWorldPayload, decompressWorldChunk} from "../../protocol/inbound/world-payload.js";
2
2
  import {ModelState} from "../model/index.js";
3
+ import {defineLazyProperty} from "../model/decoder.js";
3
4
  import {overworldZoneFromId} from "../overworld.js";
4
5
  import {getTilesetForWorld} from "../tilesets.js";
5
6
 
@@ -33,11 +34,78 @@ function pushBounded(target, value, limit) {
33
34
  if (target.length > limit) target.splice(0, target.length - limit);
34
35
  }
35
36
 
36
- const TILE_KEY_OFFSET = 1 << 24;
37
- const TILE_KEY_STRIDE = 1 << 25;
37
+ // Tiles are stored in columns rather than as one object per tile. Each 64x64
38
+ // chunk owns a single buffer of five byte columns (material, shape, hp, color,
39
+ // flags), so applying a chunk patch is a handful of bulk copies and a joined
40
+ // overworld costs a few bytes per tile instead of ~190. Tile objects are built
41
+ // only for callers that ask for them.
42
+ const CHUNK_SIZE = 64;
43
+ const CHUNK_CELLS = CHUNK_SIZE * CHUNK_SIZE;
44
+ const COLUMN_SHAPE = CHUNK_CELLS;
45
+ const COLUMN_HP = CHUNK_CELLS * 2;
46
+ const COLUMN_COLOR = CHUNK_CELLS * 3;
47
+ const COLUMN_FLAGS = CHUNK_CELLS * 4;
48
+ const CHUNK_COORD_LIMIT = 1 << 15;
49
+ const TILE_COORD_LIMIT = CHUNK_COORD_LIMIT * CHUNK_SIZE;
50
+ // Keys every stored tile object carries; anything beyond these is caller data
51
+ // that the columns cannot represent.
52
+ const TILE_OBJECT_KEY_COUNT = 13;
53
+ const CONCAT_BATCH = 4096;
54
+
55
+ // Values of a chunk view's `flags` column.
56
+ export const TileFlags = Object.freeze({
57
+ /** The cell holds a tile. Zero means the cell is empty. */
58
+ Present: 1,
59
+ /** The tile was sent without a color; its `color` is null. */
60
+ NoColor: 2
61
+ });
62
+
63
+ const SHAPE_NAMES_BY_ID = Array.from({length: 256}, (_, shape) => TILE_SHAPE_NAMES.get(shape) ?? null);
64
+
65
+ const isByte = (value) => typeof value === "number" && (value & 0xff) === value;
66
+ const isCellIndex = (value) => Number.isInteger(value) && value >= 0 && value < CHUNK_SIZE;
67
+ const isChunkCoord = (value) => Number.isInteger(value) && value >= -CHUNK_COORD_LIMIT && value < CHUNK_COORD_LIMIT;
68
+ const isTileCoord = (value) => Number.isInteger(value) && value >= -TILE_COORD_LIMIT && value < TILE_COORD_LIMIT;
69
+ const chunkKey = (chunkX, chunkY) => ((chunkY + CHUNK_COORD_LIMIT) * (CHUNK_COORD_LIMIT * 2)) + (chunkX + CHUNK_COORD_LIMIT);
70
+ const looseTileKey = (x, y) => `${x},${y}`;
71
+
72
+ // A world's tiles as objects. Deliberately small: each kind of read has one
73
+ // entry point, and it is the fastest one. There is no iterator, because walking
74
+ // 200k tiles through one costs several times what copying the array does.
75
+ // Scans that do not need objects should use WorldState.tileChunks().
76
+ class TileCollection {
77
+ #count;
78
+ #objects;
79
+
80
+ constructor(count, objects) {
81
+ this.#count = count;
82
+ this.#objects = objects;
83
+ }
84
+
85
+ get size() {
86
+ return this.#count();
87
+ }
88
+
89
+ // A fresh array of every tile.
90
+ toArray() {
91
+ return this.#objects().slice();
92
+ }
93
+ }
38
94
 
39
95
  export class WorldState {
40
- #materialCounts = new Map();
96
+ #chunkGrids = new Map();
97
+ // Tiles the columns cannot hold: non-byte values, out-of-range coordinates,
98
+ // or extra caller fields. Only reachable through setTile()/malformed patches.
99
+ #looseTiles = new Map();
100
+ #chunkViews = null;
101
+ #tileVersion = 0;
102
+ #tileStats = null;
103
+ #tileStatsVersion = -1;
104
+ #tileObjects = null;
105
+ #tileObjectsVersion = -1;
106
+ #tileObjectsRequestedVersion = -1;
107
+ #materialDefs = null;
108
+ #materialDefsTileset = null;
41
109
 
42
110
  constructor(id, limits = {}) {
43
111
  this.historyLimits = {
@@ -56,7 +124,7 @@ export class WorldState {
56
124
  this.blockHeight = null;
57
125
  this.parentWorld = null;
58
126
  this.parentEntity = null;
59
- this.tiles = new Map();
127
+ this.tiles = new TileCollection(() => this.#readTileStats().count, () => this.#readTileObjects());
60
128
  this.chunks = [];
61
129
  this.events = [];
62
130
  this.modelPackets = [];
@@ -123,43 +191,175 @@ export class WorldState {
123
191
  }
124
192
 
125
193
  applyChunk(value) {
194
+ const patch = this.applyChunkPatch(value);
195
+ return patch ? patch.tiles : null;
196
+ }
197
+
198
+ // Applies a chunk patch and returns its history entry. The entry's `tiles`
199
+ // array is built on first read, so ingestion never allocates tile objects.
200
+ applyChunkPatch(value) {
126
201
  if (!Array.isArray(value) || value.length !== 7) return null;
127
202
  const [chunkX, chunkY, minX, minY, maxX, maxY, compressedPatch] = value;
128
- // Index the decompressed bytes directly; spreading into a plain array cost
129
- // ~16k boxed elements for a full chunk.
130
203
  const patch = decompressWorldChunk(compressedPatch);
131
204
  const width = maxX - minX + 1;
132
205
  const height = maxY - minY + 1;
133
206
  const count = width * height;
134
207
  const hasColor = patch.length >= count * 4;
135
- const tiles = new Array(count);
136
208
  const baseX = chunkX << 6;
137
209
  const baseY = chunkY << 6;
138
- for (let i = 0; i < count; i++) {
139
- const localX = minX + (i % width);
140
- const localY = minY + Math.floor(i / width);
141
- const hp = patch[i + count * 2];
142
- tiles[i] = this.#storeTile(this.#buildTile(
143
- baseX + localX,
144
- baseY + localY,
145
- patch[i],
146
- patch[i + count],
147
- hp,
148
- hasColor ? patch[i + count * 3] : null
149
- ));
210
+ const entry = {chunkX, chunkY, minX, minY, maxX, maxY};
211
+
212
+ const wellFormed = isChunkCoord(chunkX) && isChunkCoord(chunkY)
213
+ && isCellIndex(minX) && isCellIndex(minY) && isCellIndex(maxX) && isCellIndex(maxY)
214
+ && width > 0 && height > 0 && patch.length >= count * 3;
215
+ if (wellFormed) {
216
+ this.#writeChunkColumns(this.#chunkGrid(chunkX, chunkY), patch, minX, minY, width, height, hasColor);
217
+ defineLazyProperty(entry, "tiles", () => {
218
+ const tiles = new Array(count);
219
+ for (let i = 0; i < count; i++) {
220
+ tiles[i] = this.#buildTile(
221
+ baseX + minX + (i % width),
222
+ baseY + minY + Math.floor(i / width),
223
+ patch[i],
224
+ patch[i + count],
225
+ patch[i + count * 2],
226
+ hasColor ? patch[i + count * 3] : null
227
+ );
228
+ }
229
+ return tiles;
230
+ });
231
+ } else {
232
+ // Out-of-range or truncated patch: store tile by tile so whatever
233
+ // the patch describes is still kept.
234
+ const tiles = new Array(count);
235
+ for (let i = 0; i < count; i++) {
236
+ tiles[i] = this.#storeTile(this.#buildTile(
237
+ baseX + minX + (i % width),
238
+ baseY + minY + Math.floor(i / width),
239
+ patch[i],
240
+ patch[i + count],
241
+ patch[i + count * 2],
242
+ hasColor ? patch[i + count * 3] : null
243
+ ));
244
+ }
245
+ entry.tiles = tiles;
150
246
  }
247
+
151
248
  this.totalChunkCount += 1;
152
- pushBounded(this.chunks, {chunkX, chunkY, minX, minY, maxX, maxY, tiles}, this.historyLimits.chunkHistory);
249
+ pushBounded(this.chunks, entry, this.historyLimits.chunkHistory);
153
250
  this.lastChunkPatch = {chunkX, chunkY, minX, minY, maxX, maxY, count, hasColor};
154
- return tiles;
251
+ return entry;
155
252
  }
156
253
 
157
254
  setTile(tile) {
158
255
  return this.#storeTile(this.normalizeTile(tile));
159
256
  }
160
257
 
161
- // Chunk decoding produces millions of tiles at join time, so build the final
162
- // object in one pass instead of a literal plus a spread copy.
258
+ /** Bumped on every tile write; compare to skip work when nothing changed. */
259
+ get tileVersion() {
260
+ return this.#tileVersion;
261
+ }
262
+
263
+ // Zero-copy access for consumers that scan tiles every tick. The returned
264
+ // views are live and stable for the life of the chunk: read the typed arrays
265
+ // directly and use each view's `version` to skip chunks that have not changed.
266
+ tileChunks() {
267
+ return this.#chunkViews ??= Array.from(this.#chunkGrids.values(), (grid) => grid.view);
268
+ }
269
+
270
+ tileAt(x, y) {
271
+ if (this.#looseTiles.size > 0) {
272
+ const loose = this.#looseTiles.get(looseTileKey(x, y));
273
+ if (loose) return loose;
274
+ }
275
+ if (!isTileCoord(x) || !isTileCoord(y)) return null;
276
+ const grid = this.#chunkGrids.get(chunkKey(x >> 6, y >> 6));
277
+ if (!grid) return null;
278
+ const data = grid.data;
279
+ const cell = ((y & 63) << 6) | (x & 63);
280
+ const flags = data[COLUMN_FLAGS + cell];
281
+ if (flags === 0) return null;
282
+ return this.#buildTile(
283
+ x,
284
+ y,
285
+ data[cell],
286
+ data[COLUMN_SHAPE + cell],
287
+ data[COLUMN_HP + cell],
288
+ flags & TileFlags.NoColor ? null : data[COLUMN_COLOR + cell]
289
+ );
290
+ }
291
+
292
+ // Drops tile objects retained for repeated `tiles.toArray()` reads. They are
293
+ // rebuilt on the next read.
294
+ releaseTileObjects() {
295
+ this.#tileObjects = null;
296
+ this.#tileObjectsRequestedVersion = -1;
297
+ for (const grid of this.#chunkGrids.values()) {
298
+ grid.objects = null;
299
+ grid.objectsRequestedVersion = -1;
300
+ }
301
+ }
302
+
303
+ #chunkGrid(chunkX, chunkY) {
304
+ const key = chunkKey(chunkX, chunkY);
305
+ let grid = this.#chunkGrids.get(key);
306
+ if (!grid) {
307
+ const data = new Uint8Array(CHUNK_CELLS * 5);
308
+ grid = {
309
+ data,
310
+ stats: null,
311
+ objects: null,
312
+ objectsRequestedVersion: -1,
313
+ view: {
314
+ chunkX,
315
+ chunkY,
316
+ originX: chunkX << 6,
317
+ originY: chunkY << 6,
318
+ version: 0,
319
+ material: data.subarray(0, COLUMN_SHAPE),
320
+ shape: data.subarray(COLUMN_SHAPE, COLUMN_HP),
321
+ hp: data.subarray(COLUMN_HP, COLUMN_COLOR),
322
+ color: data.subarray(COLUMN_COLOR, COLUMN_FLAGS),
323
+ flags: data.subarray(COLUMN_FLAGS, COLUMN_FLAGS + CHUNK_CELLS)
324
+ }
325
+ };
326
+ this.#chunkGrids.set(key, grid);
327
+ this.#chunkViews = null;
328
+ }
329
+ return grid;
330
+ }
331
+
332
+ // The only bookkeeping a tile write does. Counts and tile objects are derived
333
+ // later, on demand, from whichever chunks were touched.
334
+ #touchChunk(grid) {
335
+ grid.stats = null;
336
+ grid.objects = null;
337
+ grid.view.version = ++this.#tileVersion;
338
+ }
339
+
340
+ #writeChunkColumns(grid, patch, minX, minY, width, height, hasColor) {
341
+ const data = grid.data;
342
+ const count = width * height;
343
+ const columns = hasColor ? 4 : 3;
344
+ const flag = hasColor ? TileFlags.Present : TileFlags.Present | TileFlags.NoColor;
345
+ // The patch is column-major (all materials, then shapes, ...) and row
346
+ // ordered within a column, so each row of each column is one copy. A
347
+ // full-width patch is contiguous on both sides: one copy per column.
348
+ const rows = width === CHUNK_SIZE ? 1 : height;
349
+ const span = width === CHUNK_SIZE ? count : width;
350
+ for (let row = 0; row < rows; row++) {
351
+ const start = ((minY + row) << 6) + minX;
352
+ const from = row * width;
353
+ for (let column = 0; column < columns; column++) {
354
+ const source = column * count + from;
355
+ data.set(patch.subarray(source, source + span), column * CHUNK_CELLS + start);
356
+ }
357
+ if (!hasColor) data.fill(0, COLUMN_COLOR + start, COLUMN_COLOR + start + span);
358
+ data.fill(flag, COLUMN_FLAGS + start, COLUMN_FLAGS + start + span);
359
+ }
360
+ this.#touchChunk(grid);
361
+ }
362
+
163
363
  #buildTile(x, y, material, shape, hp, color) {
164
364
  const def = this.tileDefinition(material);
165
365
  const maxHp = def?.hp ?? null;
@@ -181,23 +381,162 @@ export class WorldState {
181
381
  };
182
382
  }
183
383
 
184
- // Numeric key: a template string per tile was a measurable share of chunk
185
- // decode. The map is only ever read through values()/size, so the key format
186
- // is internal.
187
- #storeTile(normalized) {
188
- const key = ((normalized.y + TILE_KEY_OFFSET) * TILE_KEY_STRIDE) + (normalized.x + TILE_KEY_OFFSET);
189
- const previous = this.tiles.get(key);
190
- if (previous !== undefined) this.#countMaterial(previous.material, -1);
191
- this.#countMaterial(normalized.material, 1);
192
- this.tiles.set(key, normalized);
193
- return normalized;
384
+ #storeTile(tile) {
385
+ const {x, y} = tile;
386
+ const inRange = isTileCoord(x) && isTileCoord(y);
387
+ const columnar = inRange && isByte(tile.material) && isByte(tile.shape) && isByte(tile.hp)
388
+ && (tile.color === null || isByte(tile.color))
389
+ && Object.keys(tile).length === TILE_OBJECT_KEY_COUNT;
390
+
391
+ if (this.#looseTiles.size > 0 && this.#looseTiles.delete(looseTileKey(x, y))) this.#tileVersion++;
392
+
393
+ if (columnar) {
394
+ const grid = this.#chunkGrid(x >> 6, y >> 6);
395
+ const data = grid.data;
396
+ const cell = ((y & 63) << 6) | (x & 63);
397
+ data[cell] = tile.material;
398
+ data[COLUMN_SHAPE + cell] = tile.shape;
399
+ data[COLUMN_HP + cell] = tile.hp;
400
+ data[COLUMN_COLOR + cell] = tile.color ?? 0;
401
+ data[COLUMN_FLAGS + cell] = tile.color === null ? TileFlags.Present | TileFlags.NoColor : TileFlags.Present;
402
+ this.#touchChunk(grid);
403
+ return tile;
404
+ }
405
+
406
+ // Replace any columnar tile at the same position.
407
+ const grid = inRange ? this.#chunkGrids.get(chunkKey(x >> 6, y >> 6)) : undefined;
408
+ if (grid) {
409
+ const cell = ((y & 63) << 6) | (x & 63);
410
+ if (grid.data[COLUMN_FLAGS + cell] !== 0) {
411
+ grid.data[COLUMN_FLAGS + cell] = 0;
412
+ this.#touchChunk(grid);
413
+ }
414
+ }
415
+ this.#looseTiles.set(looseTileKey(x, y), tile);
416
+ this.#tileVersion++;
417
+ return tile;
418
+ }
419
+
420
+ // Tile and material counts, derived from the columns on first read after a
421
+ // write. Only chunks touched since the last read are rescanned.
422
+ #readTileStats() {
423
+ if (this.#tileStats && this.#tileStatsVersion === this.#tileVersion) return this.#tileStats;
424
+ const totals = new Int32Array(256);
425
+ let count = 0;
426
+ for (const grid of this.#chunkGrids.values()) {
427
+ let stats = grid.stats;
428
+ if (!stats) {
429
+ const data = grid.data;
430
+ const histogram = new Uint16Array(256);
431
+ let present = 0;
432
+ for (let cell = 0; cell < CHUNK_CELLS; cell++) {
433
+ if (data[COLUMN_FLAGS + cell] === 0) continue;
434
+ histogram[data[cell]]++;
435
+ present++;
436
+ }
437
+ stats = grid.stats = {count: present, histogram};
438
+ }
439
+ count += stats.count;
440
+ const histogram = stats.histogram;
441
+ for (let material = 0; material < 256; material++) totals[material] += histogram[material];
442
+ }
443
+ const materials = new Map();
444
+ for (let material = 0; material < 256; material++) {
445
+ if (totals[material] > 0) materials.set(material, totals[material]);
446
+ }
447
+ for (const tile of this.#looseTiles.values()) {
448
+ const id = Number(tile.material);
449
+ materials.set(id, (materials.get(id) || 0) + 1);
450
+ count++;
451
+ }
452
+ this.#tileStatsVersion = this.#tileVersion;
453
+ return this.#tileStats = {count, materials};
454
+ }
455
+
456
+ // Per-material fields of a tile object, resolved once per tileset instead of
457
+ // once per tile.
458
+ #readMaterialDefs() {
459
+ if (this.#materialDefs && this.#materialDefsTileset === this.tileset) return this.#materialDefs;
460
+ const defs = new Array(256);
461
+ for (let material = 0; material < 256; material++) {
462
+ const def = this.tileDefinition(material);
463
+ defs[material] = {name: def?.name ?? null, solid: def?.solid ?? null, maxHp: def?.hp ?? null};
464
+ }
465
+ this.#materialDefsTileset = this.tileset;
466
+ return this.#materialDefs = defs;
467
+ }
468
+
469
+ #buildChunkTiles(grid) {
470
+ const defs = this.#readMaterialDefs();
471
+ const data = grid.data;
472
+ const baseX = grid.view.originX;
473
+ const baseY = grid.view.originY;
474
+ const tiles = [];
475
+ for (let cell = 0; cell < CHUNK_CELLS; cell++) {
476
+ const flags = data[COLUMN_FLAGS + cell];
477
+ if (flags === 0) continue;
478
+ const material = data[cell];
479
+ const shape = data[COLUMN_SHAPE + cell];
480
+ const hp = data[COLUMN_HP + cell];
481
+ const def = defs[material];
482
+ const maxHp = def.maxHp;
483
+ // Same shape and key order as #buildTile.
484
+ tiles.push({
485
+ x: baseX + (cell & 63),
486
+ y: baseY + (cell >> 6),
487
+ material,
488
+ shape,
489
+ hp,
490
+ integrity: hp,
491
+ color: flags & TileFlags.NoColor ? null : data[COLUMN_COLOR + cell],
492
+ materialName: def.name,
493
+ shapeName: SHAPE_NAMES_BY_ID[shape],
494
+ solid: def.solid,
495
+ maxHp,
496
+ hpRatio: hp / 255,
497
+ hpValue: typeof maxHp === "number" ? Math.round((hp / 255) * maxHp) : null
498
+ });
499
+ }
500
+ return tiles;
194
501
  }
195
502
 
196
- #countMaterial(material, delta) {
197
- const id = Number(material);
198
- const next = (this.#materialCounts.get(id) || 0) + delta;
199
- if (next > 0) this.#materialCounts.set(id, next);
200
- else this.#materialCounts.delete(id);
503
+ // Every tile as an object. Objects are retained only once a caller asks a
504
+ // second time for the same unchanged data, so a one-off dump leaves nothing
505
+ // behind while a caller that polls pays only for chunks that changed.
506
+ #readTileObjects() {
507
+ if (this.#materialDefsTileset !== this.tileset) {
508
+ this.releaseTileObjects();
509
+ this.#materialDefs = null;
510
+ }
511
+ const version = this.#tileVersion;
512
+ if (this.#tileObjects && this.#tileObjectsVersion === version) return this.#tileObjects;
513
+
514
+ const parts = [];
515
+ for (const grid of this.#chunkGrids.values()) {
516
+ let tiles = grid.objects;
517
+ if (!tiles) {
518
+ tiles = this.#buildChunkTiles(grid);
519
+ if (grid.objectsRequestedVersion === grid.view.version) grid.objects = tiles;
520
+ else grid.objectsRequestedVersion = grid.view.version;
521
+ }
522
+ parts.push(tiles);
523
+ }
524
+ if (this.#looseTiles.size > 0) parts.push([...this.#looseTiles.values()]);
525
+ // One bulk concat per batch of chunks rather than a push per tile; the
526
+ // batching keeps the argument count bounded on very large worlds.
527
+ let out = [];
528
+ for (let start = 0; start < parts.length; start += CONCAT_BATCH) {
529
+ out = out.concat(...parts.slice(start, start + CONCAT_BATCH));
530
+ }
531
+
532
+ if (this.#tileObjectsRequestedVersion === version) {
533
+ this.#tileObjects = out;
534
+ this.#tileObjectsVersion = version;
535
+ } else {
536
+ this.#tileObjects = null;
537
+ this.#tileObjectsRequestedVersion = version;
538
+ }
539
+ return out;
201
540
  }
202
541
 
203
542
  normalizeTile(tile) {
@@ -217,10 +556,8 @@ export class WorldState {
217
556
  };
218
557
  }
219
558
 
220
- // Counts are maintained as tiles are stored; this used to rescan every tile
221
- // on each call and ran on every snapshot.
222
559
  materials() {
223
- return [...this.#materialCounts.entries()]
560
+ return [...this.#readTileStats().materials.entries()]
224
561
  .sort((a, b) => a[0] - b[0])
225
562
  .map(([material, count]) => {
226
563
  const def = this.tileDefinition(material);
@@ -248,7 +585,7 @@ export class WorldState {
248
585
  block_h: this.blockHeight,
249
586
  parent_world: this.parentWorld,
250
587
  parent_ent: this.parentEntity,
251
- tileCount: this.tiles.size,
588
+ tileCount: this.#readTileStats().count,
252
589
  chunkCount: this.totalChunkCount,
253
590
  lastChunkPatch: this.lastChunkPatch,
254
591
  lastPacket: this.lastPacket,
@@ -269,7 +606,7 @@ export class WorldState {
269
606
  pvpEvent: model.pvpEvent,
270
607
  pvpParties: model.pvpParties,
271
608
  commsBubbles: this.commsBubbles.slice(),
272
- tiles: includeTiles ? [...this.tiles.values()] : undefined
609
+ tiles: includeTiles ? this.tiles.toArray() : undefined
273
610
  };
274
611
  }
275
612