@crowdedkingdoms/crowdyjs 18.30.0 → 18.31.0-dev.1

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.
@@ -42,6 +42,31 @@ const MAX_BOX_CHUNKS = 17 ** 3;
42
42
  const MAX_BOXES = 8;
43
43
  /** How far before the connection dropped a catch-up read starts, for the client's and server's clocks. */
44
44
  const CATCH_UP_MARGIN_MS = 30000;
45
+ /**
46
+ * A server time more than this far past this machine's clock counts as this machine's clock plus
47
+ * this much, so that one wrong clock cannot hold a voxel against every later change.
48
+ */
49
+ const MAX_FUTURE_SKEW_MS = 5 * 60000;
50
+ /** More boxes than this (after cutting each to 17³) is not a view: {@link ChunkStore.catchUp} refuses it. */
51
+ const MAX_CATCH_UP_BOXES = 64;
52
+ /** The newest optimistic edit of a voxel: what it shows. */
53
+ function shownEdit(cell) {
54
+ for (let i = cell.edits.length - 1; i >= 0; i -= 1) {
55
+ if (cell.edits[i].optimistic)
56
+ return cell.edits[i];
57
+ }
58
+ return undefined;
59
+ }
60
+ /** Whether two base64 voxel states carry the same bytes (empty and absent are the same). */
61
+ function sameEncodedState(a, b) {
62
+ if (!a || !b)
63
+ return !a && !b;
64
+ if (a === b)
65
+ return true;
66
+ const x = decodeBase64(a);
67
+ const y = decodeBase64(b);
68
+ return x.length === y.length && x.every((v, i) => v === y[i]);
69
+ }
45
70
  function boxAround(coords) {
46
71
  const lo = { ...coords[0] };
47
72
  const hi = { ...coords[0] };
@@ -62,6 +87,49 @@ function storedAtMs(updatedAt) {
62
87
  const ms = typeof updatedAt === 'number' ? updatedAt : Date.parse(String(updatedAt));
63
88
  return Number.isFinite(ms) ? ms : null;
64
89
  }
90
+ /** The widest box one read covers along an axis: ck-api reads at most 17³ chunks. */
91
+ const BOX_SIDE = 17;
92
+ /** `coords` in boxes of at most 17³: the bounds of the coords in each cell of a 17-chunk lattice. */
93
+ function tileBoxes(coords) {
94
+ const tiles = new Map();
95
+ for (const c of coords) {
96
+ const tile = `${Math.floor(c.x / BOX_SIDE)}:${Math.floor(c.y / BOX_SIDE)}:${Math.floor(c.z / BOX_SIDE)}`;
97
+ const box = tiles.get(tile);
98
+ if (!box) {
99
+ tiles.set(tile, { lo: { ...c }, hi: { ...c } });
100
+ continue;
101
+ }
102
+ box.lo = { x: Math.min(box.lo.x, c.x), y: Math.min(box.lo.y, c.y), z: Math.min(box.lo.z, c.z) };
103
+ box.hi = { x: Math.max(box.hi.x, c.x), y: Math.max(box.hi.y, c.y), z: Math.max(box.hi.z, c.z) };
104
+ }
105
+ return [...tiles.values()];
106
+ }
107
+ /** A box cut into boxes of at most 17³. */
108
+ function cutBox(low, high) {
109
+ const lo = { x: Math.min(low.x, high.x), y: Math.min(low.y, high.y), z: Math.min(low.z, high.z) };
110
+ const hi = { x: Math.max(low.x, high.x), y: Math.max(low.y, high.y), z: Math.max(low.z, high.z) };
111
+ const out = [];
112
+ for (let x = lo.x; x <= hi.x; x += BOX_SIDE) {
113
+ for (let y = lo.y; y <= hi.y; y += BOX_SIDE) {
114
+ for (let z = lo.z; z <= hi.z; z += BOX_SIDE) {
115
+ out.push({
116
+ lo: { x, y, z },
117
+ hi: {
118
+ x: Math.min(hi.x, x + BOX_SIDE - 1),
119
+ y: Math.min(hi.y, y + BOX_SIDE - 1),
120
+ z: Math.min(hi.z, z + BOX_SIDE - 1),
121
+ },
122
+ });
123
+ }
124
+ }
125
+ }
126
+ return out;
127
+ }
128
+ /** How many boxes of 17³ a box cuts into. */
129
+ function boxPieces(low, high) {
130
+ const side = (a, b) => Math.floor(Math.abs(b - a) / BOX_SIDE) + 1;
131
+ return side(low.x, high.x) * side(low.y, high.y) * side(low.z, high.z);
132
+ }
65
133
  function boxVolume(box) {
66
134
  return (box.hi.x - box.lo.x + 1) * (box.hi.y - box.lo.y + 1) * (box.hi.z - box.lo.z + 1);
67
135
  }
@@ -185,17 +253,24 @@ function fitsDenseGrid(x, y, z, voxelType) {
185
253
  * edit with a type outside 0-255 or a position outside 0-15 goes to the
186
254
  * chunk's `overlay` instead). A `chunkChanged` (a hub's or mod's
187
255
  * `world.set_chunk`) reads the chunk again.
256
+ * - Merging (18.31.0): each voxel holds the last value the server confirmed and
257
+ * the server's time for it (a stored row's write, an entry's `updatedAt`, a
258
+ * notification's `epochMillis`, a recorded edit's `createdAt`). A change older
259
+ * than the value held is dropped, whatever order changes arrive in, and a
260
+ * stored copy that arrives after a newer realtime change keeps that change;
261
+ * a change to a chunk still being read is kept the same way.
188
262
  * - `setVoxel` applies locally (optimistic) and replicates via the UDP path,
189
263
  * paced: at most 128 edits unanswered and 250 a second by default. The
190
- * server delivers every accepted edit back to its sender: that echo is
191
- * matched (sender uuid + sequence number + voxel) and not applied again, so a
192
- * local edit fires one change event, and an older echo never rolls back a
193
- * newer local edit. It is applied only when another client's edit of that
194
- * voxel arrived in between (the server ordered yours last) or the edit was
195
- * sent with `optimistic: false`. An edit the server refuses, or whose echo
196
- * does not come back in time, is undone and reported ({@link onEditRefused}).
264
+ * server delivers every accepted edit back to its sender: that echo (sender
265
+ * uuid + sequence number + voxel + type + state) confirms the edit and is not
266
+ * applied again, so a local edit fires one change event. This client's
267
+ * unanswered edits show over the confirmed value; another client's edit that
268
+ * arrives meanwhile becomes the confirmed value. An edit the server refuses,
269
+ * or whose echo does not come back in time, is reported
270
+ * ({@link onEditRefused}) and the voxel shows the next unanswered edit, or
271
+ * the confirmed value.
197
272
  * - After the realtime connection drops and comes back, it reads what changed
198
- * in the area meanwhile ({@link catchUp}).
273
+ * meanwhile in every chunk it tracks ({@link catchUp}).
199
274
  * - `seed`/`flush` implement deterministic-worldgen write-back through
200
275
  * `chunks.update`, one throttled chunk at a time. Only seeded chunks are
201
276
  * written back: realtime edits are recorded by the server.
@@ -223,16 +298,20 @@ export class ChunkStore {
223
298
  this.fallbackUuid = generateCrowdyUuid();
224
299
  this.revisionValue = 0;
225
300
  this.sequence = 0;
226
- /** This client's edits not yet echoed back, oldest first, per `chunkKey|voxelKey`. */
227
- this.pendingEdits = new Map();
301
+ /** Voxels with this client's unanswered edits, per `chunkKey|voxelKey`. */
302
+ this.pendingCells = new Map();
303
+ /** Per chunk key: the server's time for each voxel whose value is newer than the stored row. */
304
+ this.cellTimes = new Map();
305
+ /** Per chunk key: the voxels merged since the stored copy. */
306
+ this.arrivals = new Map();
307
+ /** Confirmed values merged so far: without server times, what was merged after a read was asked for is newer. */
308
+ this.mergeSeq = 0;
228
309
  /** Edits waiting to be sent, in order. */
229
310
  this.sendQueue = [];
230
311
  /** Sent edits not yet answered, by sequence number. */
231
312
  this.inFlightEdits = new Map();
232
313
  /** Chunks being read again; a key mapped to true is read once more when that read ends. */
233
314
  this.reloading = new Map();
234
- /** The area the last {@link ensureAround} covered, for a catch-up. */
235
- this.lastArea = null;
236
315
  /** When the realtime connection was last lost (while the store had loaded an area). */
237
316
  this.disconnectedAt = null;
238
317
  this.wasConnected = false;
@@ -258,18 +337,23 @@ export class ChunkStore {
258
337
  y: Number(notification.chunkY),
259
338
  z: Number(notification.chunkZ),
260
339
  };
261
- const chunk = this.chunks.get(chunkKey(coord));
340
+ const key = chunkKey(coord);
341
+ let chunk = this.chunks.get(key);
342
+ // A chunk being read keeps what arrives meanwhile: its copy merges under it.
343
+ if (!chunk && (this.inFlight.has(key) || this.hydrating.has(key)))
344
+ chunk = this.ensureEntry(coord);
262
345
  if (!chunk)
263
346
  return; // only merge into chunks we track
264
- if (!this.takeEcho(chunk, notification))
347
+ const timeMs = Number(notification.epochMillis);
348
+ if (this.takeEcho(chunk, notification, timeMs))
265
349
  return;
266
- this.applyVoxel(chunk, notification.voxelX, notification.voxelY, notification.voxelZ, notification.voxelType, notification.voxelState || undefined);
350
+ this.confirm(chunk, notification.voxelX, notification.voxelY, notification.voxelZ, notification.voxelType, notification.voxelState || undefined, timeMs);
267
351
  }));
268
352
  // A refusal names the sequence number of the send it answers.
269
353
  ctx.onDispose(ctx.on('genericError', (notification) => {
270
354
  const entry = this.inFlightEdits.get(notification.sequenceNumber);
271
355
  if (entry)
272
- this.undoEdit(entry.key, entry.edit, String(notification.errorCode));
356
+ this.finishEdit(entry.key, entry.edit, String(notification.errorCode));
273
357
  }));
274
358
  if (config.reloadReplacedChunks ?? true) {
275
359
  ctx.onDispose(ctx.on('chunkChanged', (notification) => {
@@ -363,6 +447,22 @@ export class ChunkStore {
363
447
  return undefined;
364
448
  return chunk.voxelStates.get(this.voxelIndex(x, y, z));
365
449
  }
450
+ /**
451
+ * When the server confirmed the value the store holds for a voxel (epoch ms): the last change it
452
+ * merged there, or the stored row's write. Null when unknown. An unanswered local edit shows over
453
+ * that value and does not change it.
454
+ */
455
+ confirmedAt(coord, x, y, z) {
456
+ const key = chunkKey(coord);
457
+ const cell = this.pendingCells.get(`${key}|${voxelKey(x, y, z)}`);
458
+ if (cell)
459
+ return cell.baseTimeMs > 0 ? cell.baseTimeMs : null;
460
+ const chunk = this.chunks.get(key);
461
+ if (!chunk)
462
+ return null;
463
+ const at = this.timeOf(chunk, voxelKey(x, y, z));
464
+ return at > 0 ? at : null;
465
+ }
366
466
  /** Subscribe to per-chunk changes (loads, merges, edits). @returns off. */
367
467
  onChunkChanged(listener) {
368
468
  this.changeListeners.add(listener);
@@ -422,7 +522,6 @@ export class ChunkStore {
422
522
  */
423
523
  async ensureAround(center, radius) {
424
524
  const range = Math.max(0, Math.min(8, Math.floor(radius)));
425
- this.lastArea = { center: { ...center }, radius: range };
426
525
  const around = chunksAround(center, range);
427
526
  const wanted = around.filter((coord) => {
428
527
  const key = chunkKey(coord);
@@ -437,17 +536,19 @@ export class ChunkStore {
437
536
  for (const key of wantedKeys)
438
537
  this.inFlight.add(key);
439
538
  const pending = new Set(wantedKeys);
539
+ const requestedSeq = this.mergeSeq;
440
540
  try {
441
541
  for (const box of coverWithBoxes(wanted)) {
442
542
  await this.readBox(box, (coord, chunk) => {
443
543
  const key = chunkKey(coord);
444
- if (!wantedKeys.has(key))
544
+ // Not asked for, or evicted while the read was out.
545
+ if (!wantedKeys.has(key) || !this.inFlight.has(key))
445
546
  return;
446
- // A chunk tracked meanwhile (an edit, a seed) keeps what it has.
547
+ // A chunk loaded meanwhile, or a seed, keeps what it has.
447
548
  if (this.chunks.get(key)?.loadState === 'loaded' || this.chunks.get(key)?.dirty)
448
549
  return;
449
550
  returned.add(key);
450
- this.applyServerChunk(coord, chunk.voxels ?? null, chunk.chunkState ?? null, chunk.updatedAt);
551
+ this.applyServerChunk(coord, chunk.voxels ?? null, chunk.chunkState ?? null, chunk.updatedAt, requestedSeq);
451
552
  });
452
553
  // Requested-but-absent chunks have never been stored server-side.
453
554
  for (const coord of wanted) {
@@ -455,7 +556,7 @@ export class ChunkStore {
455
556
  if (!pending.has(key) || !inBox(box, coord))
456
557
  continue;
457
558
  pending.delete(key);
458
- if (!returned.has(key))
559
+ if (!returned.has(key) && this.inFlight.has(key))
459
560
  this.markMissing(coord);
460
561
  }
461
562
  }
@@ -551,97 +652,81 @@ export class ChunkStore {
551
652
  }
552
653
  }
553
654
  /**
554
- * Hydrate one chunk's sparse voxel states (and chunk state) via a
555
- * single-chunk fetch — bulk loads omit them. This client's edits the server has not echoed yet
556
- * stay over the stored copy, which may predate them.
655
+ * Hydrate one chunk's sparse voxel states (and chunk state) via a single-chunk fetch — bulk loads
656
+ * omit them — merged as a load is: a value merged since the read was asked for that is newer than
657
+ * the copy stays, and this client's unanswered edits show over it. Resolves once that read has
658
+ * ended: true when its copy was applied (or a newer one was already held), false when the chunk
659
+ * was never stored or was evicted while the read was out.
557
660
  */
558
661
  async hydrate(coord) {
662
+ const key = chunkKey(coord);
663
+ const before = this.chunks.get(key);
664
+ const requestedSeq = this.mergeSeq;
559
665
  const full = await this.ctx.client.chunks.get({
560
666
  appId: this.ctx.appId,
561
667
  coordinates: toChunkInput(coord),
562
668
  });
669
+ if (before && this.chunks.get(key) !== before)
670
+ return false;
563
671
  if (!full) {
564
672
  this.markMissing(coord);
565
- return;
673
+ return false;
566
674
  }
567
675
  const chunk = this.ensureEntry(coord);
568
- if (full.voxels != null)
569
- chunk.voxels = decodeBase64(full.voxels);
676
+ const rowMs = storedAtMs(full.updatedAt);
677
+ // A newer copy came first (another read's): the store already holds this one's news.
678
+ if (chunk.hydrated && rowMs !== null && chunk.storedAt !== null && chunk.storedAt > rowMs)
679
+ return true;
570
680
  chunk.chunkState = this.decodeChunkState(full.chunkState ?? null);
571
681
  chunk.voxelStatesTruncated = full.voxelStatesTruncated === true;
572
- chunk.storedAt = storedAtMs(full.updatedAt);
573
- // The stored copy replaces what the store held for the chunk (a `world.set_chunk` drops the
574
- // chunk's older edits); a state blob this codec cannot read keeps the one cached before.
575
- const cachedStates = new Map(chunk.voxelStates);
576
- const cachedOverlay = new Map(chunk.overlay);
577
- chunk.voxelStates.clear();
578
- chunk.overlay.clear();
579
- for (const entry of full.voxelStates ?? []) {
580
- const { x, y, z } = entry.voxelCoord;
581
- if (!fitsDenseGrid(x, y, z, entry.voxelType)) {
582
- const key = voxelKey(x, y, z);
583
- let state = entry.state ? cachedOverlay.get(key)?.state : undefined;
584
- if (entry.state) {
585
- try {
586
- state = this.voxelStateCodec.decode(entry.state);
587
- }
588
- catch {
589
- // As below: a foreign blob keeps the state already cached.
590
- }
591
- }
592
- this.putOverlay(chunk, x, y, z, entry.voxelType, state);
593
- continue;
594
- }
595
- const index = this.voxelIndex(x, y, z);
596
- // A chunk stored with `voxels: null` still carries its recorded edits.
597
- if (!chunk.voxels)
598
- chunk.voxels = new Uint8Array(CHUNK_VOLUME);
599
- chunk.voxels[index] = entry.voxelType;
600
- if (entry.state) {
601
- try {
602
- chunk.voxelStates.set(index, this.voxelStateCodec.decode(entry.state));
603
- }
604
- catch {
605
- // Foreign/legacy blobs keep the state cached before; the dense type still applied.
606
- const cached = cachedStates.get(index);
607
- if (cached !== undefined)
608
- chunk.voxelStates.set(index, cached);
609
- }
610
- }
611
- }
612
- this.reapplyPendingEdits(chunk);
682
+ this.adoptCopy(chunk, full.voxels ?? null, full.voxelStates ?? [], rowMs, requestedSeq);
613
683
  chunk.loadState = 'loaded';
614
684
  chunk.hydrated = true;
615
685
  this.touch(chunk);
686
+ return true;
616
687
  }
617
688
  /**
618
- * Read the chunks in the last area {@link ensureAround} loaded that changed since `since`: the
619
- * recorded edits (`voxels.listByDistance`, when the client has `voxels`) are applied to the
620
- * chunks the store holds, and a chunk whose stored row was written since then
621
- * (`chunks.byDistance` with `since`: `updateChunk`, `world.set_chunk`) is read again. The store
622
- * calls it when the realtime connection comes back ({@link ChunkStoreConfig.catchUpOnReconnect}),
623
- * from 30 s before the connection dropped. Needs ck-api v2.67.0.
689
+ * Read what changed since `since` in every chunk the store tracks (18.31.0; the last area
690
+ * {@link ensureAround} loaded before), or in `boxes`: the recorded edits
691
+ * (`voxels.listByDistance`, when the client has `voxels`) merge into the chunks the store tracks
692
+ * by their `createdAt`, the never-stored (`missing`) ones included, and a chunk whose stored row
693
+ * was written since then (`chunks.byDistance` with `since`: `updateChunk`, `world.set_chunk`) is
694
+ * read again. The area is read in boxes of at most 17³ chunks; a box larger than that is cut, and
695
+ * more than 64 such boxes is refused (resolves false). The store calls it when the realtime
696
+ * connection comes back ({@link ChunkStoreConfig.catchUpOnReconnect}), from 30 s before the
697
+ * connection dropped. Needs ck-api v2.67.0. Resolves whether anything was read.
624
698
  */
625
- async catchUp(since) {
626
- const area = this.lastArea;
627
- if (!area)
628
- return;
629
- const box = {
630
- lo: { x: area.center.x - area.radius, y: area.center.y - area.radius, z: area.center.z - area.radius },
631
- hi: { x: area.center.x + area.radius, y: area.center.y + area.radius, z: area.center.z + area.radius },
632
- };
633
- const replaced = [];
634
- await this.readBox(box, (coord, stored) => {
635
- const chunk = this.chunks.get(chunkKey(coord));
636
- if (!chunk || chunk.dirty || chunk.loadState !== 'loaded')
637
- return;
638
- const at = storedAtMs(stored.updatedAt);
639
- if (at !== null && chunk.storedAt !== null && chunk.storedAt >= at)
640
- return;
641
- replaced.push(coord);
642
- }, since);
699
+ async catchUp(since, boxes) {
700
+ let read;
701
+ if (boxes) {
702
+ let pieces = 0;
703
+ for (const box of boxes)
704
+ pieces += boxPieces(box.low, box.high);
705
+ if (pieces > MAX_CATCH_UP_BOXES)
706
+ return false;
707
+ read = boxes.flatMap((box) => cutBox(box.low, box.high));
708
+ }
709
+ else {
710
+ read = tileBoxes([...this.chunks.values()].map((chunk) => chunk.coord));
711
+ }
712
+ if (read.length === 0)
713
+ return false;
714
+ const requestedSeq = this.mergeSeq;
715
+ const replaced = new Map();
643
716
  const voxels = this.ctx.client.voxels;
644
- if (voxels) {
717
+ for (const box of read) {
718
+ await this.readBox(box, (coord, stored) => {
719
+ const chunk = this.chunks.get(chunkKey(coord));
720
+ if (!chunk || chunk.dirty)
721
+ return;
722
+ const at = storedAtMs(stored.updatedAt);
723
+ if (chunk.loadState === 'loaded' && at !== null && chunk.storedAt !== null && chunk.storedAt >= at) {
724
+ return;
725
+ }
726
+ replaced.set(chunk.key, coord);
727
+ }, since);
728
+ if (!voxels)
729
+ continue;
645
730
  for (let skip = 0;;) {
646
731
  const page = await whenNotBusy(() => voxels.listByDistance({
647
732
  appId: this.ctx.appId,
@@ -653,14 +738,11 @@ export class ChunkStore {
653
738
  }));
654
739
  for (const group of page.chunks) {
655
740
  const chunk = this.chunks.get(chunkKey(fromChunkInput(group.coordinates)));
656
- if (!chunk || chunk.loadState !== 'loaded')
741
+ if (!chunk)
657
742
  continue;
658
743
  for (const edit of group.voxels) {
659
744
  const { x, y, z } = edit.location;
660
- // This client's own unanswered edit of the voxel settles with its echo.
661
- if (this.livePendingEdits(`${chunk.key}|${voxelKey(x, y, z)}`).length > 0)
662
- continue;
663
- this.applyVoxel(chunk, x, y, z, edit.voxelType, edit.state ?? undefined);
745
+ this.confirm(chunk, x, y, z, edit.voxelType, edit.state ?? undefined, storedAtMs(edit.createdAt) ?? 0, requestedSeq);
664
746
  }
665
747
  }
666
748
  const applied = page.limit ?? PAGE_SIZE;
@@ -669,7 +751,8 @@ export class ChunkStore {
669
751
  skip = (page.skip ?? skip) + applied;
670
752
  }
671
753
  }
672
- await Promise.all(replaced.map((coord) => this.reload(coord)));
754
+ await Promise.all([...replaced.values()].map((coord) => this.reload(coord)));
755
+ return true;
673
756
  }
674
757
  /**
675
758
  * Edit one voxel: applies to the cache immediately (optimistic) and
@@ -688,14 +771,27 @@ export class ChunkStore {
688
771
  return false;
689
772
  const chunk = this.ensureEntry(input.chunk);
690
773
  const optimistic = input.optimistic ?? true;
691
- const previous = {
692
- voxelType: this.voxelTypeAt(input.chunk, input.x, input.y, input.z),
693
- };
694
- const previousState = this.voxelStateAt(input.chunk, input.x, input.y, input.z);
695
- if (previousState !== undefined)
696
- previous.state = previousState;
697
- if (optimistic) {
698
- this.applyVoxel(chunk, input.x, input.y, input.z, input.voxelType, undefined, input.state);
774
+ const key = `${chunk.key}|${voxelKey(voxel.x, voxel.y, voxel.z)}`;
775
+ this.expireEdits();
776
+ let cell = this.pendingCells.get(key);
777
+ if (!cell) {
778
+ // The value under the edits: what the store holds now, as the server confirmed it.
779
+ const vk = voxelKey(voxel.x, voxel.y, voxel.z);
780
+ const base = {
781
+ voxelType: this.voxelTypeAt(input.chunk, input.x, input.y, input.z),
782
+ };
783
+ const baseState = this.voxelStateAt(input.chunk, input.x, input.y, input.z);
784
+ if (baseState !== undefined)
785
+ base.state = baseState;
786
+ cell = {
787
+ coord: { ...input.chunk },
788
+ voxel,
789
+ edits: [],
790
+ base,
791
+ baseTimeMs: this.timeOf(chunk, vk),
792
+ baseArrival: this.arrivalOf(chunk, vk),
793
+ };
794
+ this.pendingCells.set(key, cell);
699
795
  }
700
796
  const edit = {
701
797
  coord: { ...input.chunk },
@@ -705,11 +801,12 @@ export class ChunkStore {
705
801
  voxelType: input.voxelType,
706
802
  ...(encodedState !== undefined ? { encodedState } : {}),
707
803
  ...(input.state !== undefined ? { state: input.state } : {}),
708
- stale: !optimistic,
709
804
  optimistic,
710
- previous,
711
805
  };
712
- const key = this.rememberEdit(chunk, voxel, edit);
806
+ cell.edits.push(edit);
807
+ if (optimistic) {
808
+ this.applyVoxel(chunk, input.x, input.y, input.z, input.voxelType, undefined, input.state);
809
+ }
713
810
  return new Promise((resolve, reject) => {
714
811
  this.sendQueue.push({ key, edit, resolve, reject });
715
812
  this.pump();
@@ -762,17 +859,35 @@ export class ChunkStore {
762
859
  }
763
860
  return failures;
764
861
  }
765
- /** Drop tracked chunks farther than `radius` from `center` (dirty ones kept). */
862
+ /** Drop tracked chunks farther than `radius` from `center` (dirty ones kept). Returns how many. */
766
863
  pruneBeyond(center, radius) {
767
- for (const [key, chunk] of this.chunks) {
768
- if (chunk.dirty)
864
+ return this.pruneIf((chunk) => chunkDistance(chunk.coord, center) > radius);
865
+ }
866
+ /**
867
+ * Drop one tracked chunk (18.31.0), as {@link pruneBeyond} does. Returns whether it was dropped:
868
+ * false when the store does not track it, or it is queued for write-back. A read of it that is
869
+ * out is not applied.
870
+ */
871
+ evict(coord) {
872
+ const chunk = this.chunks.get(chunkKey(coord));
873
+ if (!chunk || chunk.dirty)
874
+ return false;
875
+ this.forget(chunk.key);
876
+ return true;
877
+ }
878
+ /**
879
+ * Drop every tracked chunk `drop` returns true for (18.31.0), for a view that is not a cube (a
880
+ * sphere, a column, several players); chunks queued for write-back stay. Returns how many.
881
+ */
882
+ pruneIf(drop) {
883
+ let dropped = 0;
884
+ for (const chunk of [...this.chunks.values()]) {
885
+ if (chunk.dirty || !drop(chunk))
769
886
  continue;
770
- if (chunkDistance(chunk.coord, center) > radius) {
771
- this.chunks.delete(key);
772
- this.hydrateFailures.delete(key);
773
- this.revisionValue += 1;
774
- }
887
+ this.forget(chunk.key);
888
+ dropped += 1;
775
889
  }
890
+ return dropped;
776
891
  }
777
892
  // -- internals --------------------------------------------------------------
778
893
  /**
@@ -879,40 +994,134 @@ export class ChunkStore {
879
994
  this.reloading.delete(key);
880
995
  }
881
996
  }
882
- applyServerChunk(coord, voxels, chunkState, updatedAt) {
997
+ applyServerChunk(coord, voxels, chunkState, updatedAt, requestedSeq) {
883
998
  const chunk = this.ensureEntry(coord);
884
- if (voxels != null)
885
- chunk.voxels = decodeBase64(voxels);
886
999
  chunk.chunkState = this.decodeChunkState(chunkState);
887
- chunk.storedAt = storedAtMs(updatedAt);
888
- this.reapplyPendingEdits(chunk);
1000
+ this.adoptCopy(chunk, voxels, undefined, storedAtMs(updatedAt), requestedSeq);
889
1001
  chunk.loadState = 'loaded';
890
1002
  this.touch(chunk);
891
1003
  }
892
1004
  /**
893
- * Put this client's unanswered optimistic edits of a chunk back over a stored copy just applied,
894
- * which may predate them. What the copy holds for each such voxel becomes what an undo restores.
1005
+ * Apply a stored copy (`entries` undefined: a bulk read, which has no `voxelStates`) under what
1006
+ * the store merged since the read was asked for: a value newer than the copy's for its voxel
1007
+ * stays (by the server's times; without them, a value merged after `requestedSeq`). This
1008
+ * client's unanswered edits show over the copy, which becomes their confirmed value unless the
1009
+ * one held is newer.
895
1010
  */
896
- reapplyPendingEdits(chunk) {
1011
+ adoptCopy(chunk, voxels, entries, rowMs, requestedSeq) {
1012
+ const row = rowMs ?? 0;
1013
+ const entryTimes = new Map();
1014
+ for (const entry of entries ?? []) {
1015
+ const vk = voxelKey(entry.voxelCoord.x, entry.voxelCoord.y, entry.voxelCoord.z);
1016
+ // A voxel the copy lists twice counts at its latest time.
1017
+ entryTimes.set(vk, Math.max(entryTimes.get(vk) ?? 0, storedAtMs(entry.updatedAt) ?? row));
1018
+ }
1019
+ const copyTime = (vk) => entryTimes.get(vk) ?? row;
1020
+ const heldIsNewer = (vk, heldMs, heldArrival) => {
1021
+ const copyMs = copyTime(vk);
1022
+ return copyMs > 0 ? heldMs > copyMs : heldArrival > requestedSeq;
1023
+ };
897
1024
  const prefix = `${chunk.key}|`;
898
- for (const [key, edits] of this.pendingEdits) {
899
- if (!key.startsWith(prefix))
1025
+ const kept = [];
1026
+ const replaced = [];
1027
+ for (const [vk, arrival] of this.arrivals.get(chunk.key) ?? []) {
1028
+ if (this.pendingCells.has(prefix + vk))
900
1029
  continue;
901
- const live = edits.filter((edit) => !edit.stale);
902
- if (live.length === 0)
1030
+ const heldMs = this.timeOf(chunk, vk);
1031
+ if (!heldIsNewer(vk, heldMs, arrival.seq)) {
1032
+ replaced.push(arrival);
903
1033
  continue;
904
- const { x, y, z } = live[0].voxel;
905
- const stored = {
1034
+ }
1035
+ const { x, y, z } = arrival;
1036
+ const value = {
1037
+ ...arrival,
906
1038
  voxelType: this.voxelTypeAt(chunk.coord, x, y, z),
1039
+ timeMs: heldMs,
907
1040
  };
908
- const storedState = this.voxelStateAt(chunk.coord, x, y, z);
909
- if (storedState !== undefined)
910
- stored.state = storedState;
911
- live[0].previous = stored;
912
- const newest = live[live.length - 1];
913
- if (!newest.optimistic)
1041
+ const state = this.voxelStateAt(chunk.coord, x, y, z);
1042
+ if (state !== undefined)
1043
+ value.state = state;
1044
+ kept.push(value);
1045
+ }
1046
+ chunk.storedAt = rowMs;
1047
+ if (voxels != null)
1048
+ chunk.voxels = decodeBase64(voxels);
1049
+ this.cellTimes.delete(chunk.key);
1050
+ this.arrivals.delete(chunk.key);
1051
+ if (entries) {
1052
+ // The stored copy replaces what the store held for the chunk (a `world.set_chunk` drops the
1053
+ // chunk's older edits); a state blob this codec cannot read keeps the one cached before.
1054
+ const cachedStates = new Map(chunk.voxelStates);
1055
+ const cachedOverlay = new Map(chunk.overlay);
1056
+ chunk.voxelStates.clear();
1057
+ chunk.overlay.clear();
1058
+ for (const entry of entries) {
1059
+ const { x, y, z } = entry.voxelCoord;
1060
+ const vk = voxelKey(x, y, z);
1061
+ const entryMs = entryTimes.get(vk) ?? row;
1062
+ if (entryMs > row)
1063
+ this.mapOf(this.cellTimes, chunk.key).set(vk, entryMs);
1064
+ if (!fitsDenseGrid(x, y, z, entry.voxelType)) {
1065
+ let state = entry.state ? cachedOverlay.get(vk)?.state : undefined;
1066
+ if (entry.state) {
1067
+ try {
1068
+ state = this.voxelStateCodec.decode(entry.state);
1069
+ }
1070
+ catch {
1071
+ // As below: a foreign blob keeps the state already cached.
1072
+ }
1073
+ }
1074
+ this.putOverlay(chunk, x, y, z, entry.voxelType, state);
1075
+ continue;
1076
+ }
1077
+ const index = this.voxelIndex(x, y, z);
1078
+ // A chunk stored with `voxels: null` still carries its recorded edits.
1079
+ if (!chunk.voxels)
1080
+ chunk.voxels = new Uint8Array(CHUNK_VOLUME);
1081
+ chunk.voxels[index] = entry.voxelType;
1082
+ if (entry.state) {
1083
+ try {
1084
+ chunk.voxelStates.set(index, this.voxelStateCodec.decode(entry.state));
1085
+ }
1086
+ catch {
1087
+ // Foreign/legacy blobs keep the state cached before; the dense type still applied.
1088
+ const cached = cachedStates.get(index);
1089
+ if (cached !== undefined)
1090
+ chunk.voxelStates.set(index, cached);
1091
+ }
1092
+ }
1093
+ }
1094
+ }
1095
+ else {
1096
+ // A bulk copy has no states: a merged voxel it supersedes keeps none of its own.
1097
+ for (const { x, y, z } of replaced) {
1098
+ chunk.overlay.delete(voxelKey(x, y, z));
1099
+ if (inDenseGrid(x, y, z))
1100
+ chunk.voxelStates.delete(this.voxelIndex(x, y, z));
1101
+ }
1102
+ }
1103
+ for (const value of kept) {
1104
+ this.writeVoxel(chunk, value.x, value.y, value.z, value.voxelType, value.state);
1105
+ this.setTime(chunk, value.x, value.y, value.z, value.timeMs, value.seq);
1106
+ }
1107
+ for (const [key, cell] of this.pendingCells) {
1108
+ if (!key.startsWith(prefix))
914
1109
  continue;
915
- this.writeVoxel(chunk, x, y, z, newest.voxelType, newest.state);
1110
+ const { x, y, z } = cell.voxel;
1111
+ const vk = voxelKey(x, y, z);
1112
+ if (!heldIsNewer(vk, cell.baseTimeMs, cell.baseArrival)) {
1113
+ const base = { voxelType: this.voxelTypeAt(chunk.coord, x, y, z) };
1114
+ const state = this.voxelStateAt(chunk.coord, x, y, z);
1115
+ if (state !== undefined)
1116
+ base.state = state;
1117
+ cell.base = base;
1118
+ const copyMs = copyTime(vk);
1119
+ if (copyMs > 0)
1120
+ cell.baseTimeMs = copyMs;
1121
+ cell.baseArrival = 0;
1122
+ }
1123
+ const shown = shownEdit(cell) ?? cell.base;
1124
+ this.writeVoxel(chunk, x, y, z, shown.voxelType, shown.state);
916
1125
  }
917
1126
  }
918
1127
  /** Send queued edits while the pace and the in-flight limit allow. */
@@ -927,7 +1136,7 @@ export class ChunkStore {
927
1136
  this.sendTokens >= 1) {
928
1137
  const send = this.sendQueue.shift();
929
1138
  // An edit undone while it waited (a pruned chunk's) is not sent.
930
- if (!this.pendingEdits.get(send.key)?.includes(send.edit)) {
1139
+ if (!this.pendingCells.get(send.key)?.edits.includes(send.edit)) {
931
1140
  send.resolve(false);
932
1141
  continue;
933
1142
  }
@@ -977,10 +1186,10 @@ export class ChunkStore {
977
1186
  }
978
1187
  sent.then((accepted) => {
979
1188
  if (!accepted)
980
- this.undoEdit(key, edit, 'NOT_SENT');
1189
+ this.finishEdit(key, edit, 'NOT_SENT');
981
1190
  send.resolve(accepted);
982
1191
  }, (error) => {
983
- this.undoEdit(key, edit, 'SEND_FAILED');
1192
+ this.finishEdit(key, edit, 'SEND_FAILED');
984
1193
  send.reject(error);
985
1194
  });
986
1195
  }
@@ -989,39 +1198,51 @@ export class ChunkStore {
989
1198
  const cutoff = this.now() - this.editTimeoutMs;
990
1199
  for (const { key, edit } of [...this.inFlightEdits.values()]) {
991
1200
  if (edit.sentAt !== undefined && edit.sentAt < cutoff)
992
- this.undoEdit(key, edit, 'TIMEOUT');
1201
+ this.finishEdit(key, edit, 'TIMEOUT');
993
1202
  }
994
1203
  }
995
1204
  /**
996
- * Forget an edit the server will not apply and put its voxel back as it was before it, unless a
997
- * newer edit is what the voxel shows. Reports it, then lets the next queued edit go.
1205
+ * End an edit: echoed (`reason` null; at `echoTimeMs` it becomes the voxel's confirmed value,
1206
+ * unless the one held is newer), or one the server will not apply (reported). The voxel then
1207
+ * shows its next unanswered edit, or its confirmed value. Lets the next queued edit go.
998
1208
  */
999
- undoEdit(key, edit, reason) {
1000
- const edits = this.pendingEdits.get(key);
1001
- const index = edits?.indexOf(edit) ?? -1;
1002
- if (!edits || index < 0)
1209
+ finishEdit(key, edit, reason, echoTimeMs = 0) {
1210
+ const cell = this.pendingCells.get(key);
1211
+ const index = cell?.edits.indexOf(edit) ?? -1;
1212
+ if (!cell || index < 0)
1003
1213
  return;
1004
- edits.splice(index, 1);
1005
- if (edits.length === 0)
1006
- this.pendingEdits.delete(key);
1214
+ const wasShown = shownEdit(cell) === edit;
1215
+ cell.edits.splice(index, 1);
1007
1216
  if (this.inFlightEdits.get(edit.sequenceNumber)?.edit === edit) {
1008
1217
  this.inFlightEdits.delete(edit.sequenceNumber);
1009
1218
  }
1010
- let restored = false;
1011
- const chunk = this.chunks.get(chunkKey(edit.coord));
1012
- if (chunk && edit.optimistic && !edit.stale) {
1013
- const next = edits[index];
1014
- if (next) {
1015
- // A newer edit of this voxel shows; it now undoes to what this one replaced.
1016
- if (!next.stale)
1017
- next.previous = edit.previous;
1219
+ if (reason === null) {
1220
+ const at = this.clampTime(echoTimeMs);
1221
+ if (at <= 0 || at >= cell.baseTimeMs) {
1222
+ cell.base = { voxelType: edit.voxelType, ...(edit.state !== undefined ? { state: edit.state } : {}) };
1223
+ if (at > 0)
1224
+ cell.baseTimeMs = at;
1225
+ cell.baseArrival = ++this.mergeSeq;
1018
1226
  }
1019
- else {
1020
- const { x, y, z } = edit.voxel;
1021
- this.applyVoxel(chunk, x, y, z, edit.previous.voxelType, undefined, edit.previous.state);
1022
- restored = true;
1227
+ }
1228
+ const chunk = this.chunks.get(chunkKey(edit.coord));
1229
+ const { x, y, z } = edit.voxel;
1230
+ if (cell.edits.length === 0) {
1231
+ this.pendingCells.delete(key);
1232
+ if (chunk) {
1233
+ const vk = voxelKey(x, y, z);
1234
+ this.setTime(chunk, x, y, z, Math.max(cell.baseTimeMs, this.timeOf(chunk, vk)), cell.baseArrival);
1235
+ this.show(chunk, x, y, z, cell.base);
1023
1236
  }
1024
1237
  }
1238
+ else if (chunk) {
1239
+ this.show(chunk, x, y, z, shownEdit(cell) ?? cell.base);
1240
+ }
1241
+ if (reason === null) {
1242
+ this.pump();
1243
+ return;
1244
+ }
1245
+ const restored = wasShown && chunk !== undefined;
1025
1246
  const refusal = {
1026
1247
  coord: edit.coord,
1027
1248
  voxel: edit.voxel,
@@ -1057,47 +1278,112 @@ export class ChunkStore {
1057
1278
  this.seed(coord, generated.voxels, { writeBack: generated.writeBack ?? true });
1058
1279
  }
1059
1280
  }
1060
- rememberEdit(chunk, voxel, edit) {
1061
- const key = `${chunk.key}|${voxelKey(voxel.x, voxel.y, voxel.z)}`;
1062
- const edits = this.livePendingEdits(key);
1063
- edits.push(edit);
1064
- this.pendingEdits.set(key, edits);
1065
- return key;
1066
- }
1067
- /** The pending edits for one voxel, oldest first, after undoing the ones that timed out. */
1068
- livePendingEdits(key) {
1069
- this.expireEdits();
1070
- return this.pendingEdits.get(key) ?? [];
1071
- }
1072
1281
  /**
1073
- * Match a realtime voxel edit against this client's pending edits. Returns whether to apply it.
1074
- * The server delivers every accepted edit back to its sender: the echo of an edit already
1075
- * applied optimistically is not applied again (no second change event), and an echo is never
1076
- * applied over a newer local edit of the same voxel. Another client's edit is applied, and
1077
- * marks the pending local edits of that voxel stale so their echoes restore them.
1282
+ * Whether a realtime voxel edit is the echo of one of this client's unanswered edits (sender uuid,
1283
+ * sequence number, voxel, type and state); one is ended as echoed at the notification's time.
1078
1284
  */
1079
- takeEcho(chunk, notification) {
1285
+ takeEcho(chunk, notification, timeMs) {
1080
1286
  const key = `${chunk.key}|${voxelKey(notification.voxelX, notification.voxelY, notification.voxelZ)}`;
1081
- const edits = this.livePendingEdits(key);
1082
- if (edits.length === 0)
1083
- return true;
1084
- const index = edits.findIndex((edit) => edit.sentAt !== undefined &&
1287
+ this.expireEdits();
1288
+ const cell = this.pendingCells.get(key);
1289
+ if (!cell)
1290
+ return false;
1291
+ const echoed = cell.edits.find((edit) => edit.sentAt !== undefined &&
1085
1292
  edit.uuid === notification.uuid &&
1086
- edit.sequenceNumber === notification.sequenceNumber);
1087
- if (index < 0) {
1088
- for (const edit of edits)
1089
- edit.stale = true;
1090
- return true;
1293
+ edit.sequenceNumber === notification.sequenceNumber &&
1294
+ edit.voxelType === notification.voxelType &&
1295
+ sameEncodedState(edit.encodedState, notification.voxelState));
1296
+ if (!echoed)
1297
+ return false;
1298
+ this.finishEdit(key, echoed, null, timeMs);
1299
+ return true;
1300
+ }
1301
+ /**
1302
+ * Merge a confirmed value at the server's time for it. Without one (0), it is new unless it came
1303
+ * from a read asked for at `readSeq` and the voxel changed after that. Under this client's
1304
+ * unanswered edits it becomes their confirmed value, and the voxel keeps showing the newest edit.
1305
+ */
1306
+ confirm(chunk, x, y, z, voxelType, encodedState, timeMs, readSeq = 0) {
1307
+ const vk = voxelKey(x, y, z);
1308
+ const at = this.clampTime(timeMs);
1309
+ const older = (heldMs, heldArrival) => at > 0 ? at < heldMs : readSeq > 0 && heldArrival > readSeq;
1310
+ let state;
1311
+ if (encodedState) {
1312
+ try {
1313
+ state = this.voxelStateCodec.decode(encodedState);
1314
+ }
1315
+ catch {
1316
+ state = undefined;
1317
+ }
1091
1318
  }
1092
- const [echoed] = edits.splice(index, 1);
1093
- if (edits.length === 0)
1094
- this.pendingEdits.delete(key);
1095
- if (this.inFlightEdits.get(echoed.sequenceNumber)?.edit === echoed) {
1096
- this.inFlightEdits.delete(echoed.sequenceNumber);
1097
- this.pump();
1319
+ const cell = this.pendingCells.get(`${chunk.key}|${vk}`);
1320
+ if (cell) {
1321
+ if (older(cell.baseTimeMs, cell.baseArrival))
1322
+ return;
1323
+ cell.base = { voxelType, ...(state !== undefined ? { state } : {}) };
1324
+ if (at > 0)
1325
+ cell.baseTimeMs = at;
1326
+ cell.baseArrival = ++this.mergeSeq;
1327
+ return;
1328
+ }
1329
+ const heldMs = this.timeOf(chunk, vk);
1330
+ if (older(heldMs, this.arrivalOf(chunk, vk)))
1331
+ return;
1332
+ this.setTime(chunk, x, y, z, at > 0 ? at : heldMs, ++this.mergeSeq);
1333
+ this.writeVoxel(chunk, x, y, z, voxelType, state);
1334
+ this.touch(chunk);
1335
+ }
1336
+ /** Show a value at a voxel; a change event only when it differs from what the voxel shows. */
1337
+ show(chunk, x, y, z, value) {
1338
+ if (this.voxelTypeAt(chunk.coord, x, y, z) === value.voxelType &&
1339
+ this.voxelStateAt(chunk.coord, x, y, z) === value.state) {
1340
+ return;
1098
1341
  }
1099
- const newerLocalEdit = edits.length > index;
1100
- return echoed.stale && !newerLocalEdit;
1342
+ this.writeVoxel(chunk, x, y, z, value.voxelType, value.state);
1343
+ this.touch(chunk);
1344
+ }
1345
+ /** A server time, no further past this machine's clock than {@link MAX_FUTURE_SKEW_MS}; 0 when unknown. */
1346
+ clampTime(timeMs) {
1347
+ if (!(timeMs > 0))
1348
+ return 0;
1349
+ return Math.min(timeMs, Date.now() + MAX_FUTURE_SKEW_MS);
1350
+ }
1351
+ /** The server's time for a voxel's value: its own, or the stored row's (0 when unknown). */
1352
+ timeOf(chunk, vk) {
1353
+ return this.cellTimes.get(chunk.key)?.get(vk) ?? chunk.storedAt ?? 0;
1354
+ }
1355
+ /** The merge a voxel's value arrived in (0: the stored copy). */
1356
+ arrivalOf(chunk, vk) {
1357
+ return this.arrivals.get(chunk.key)?.get(vk)?.seq ?? 0;
1358
+ }
1359
+ /** Record a voxel's server time and the merge it arrived in (0: the stored copy). */
1360
+ setTime(chunk, x, y, z, timeMs, arrival) {
1361
+ const vk = voxelKey(x, y, z);
1362
+ if (timeMs > (chunk.storedAt ?? 0))
1363
+ this.mapOf(this.cellTimes, chunk.key).set(vk, timeMs);
1364
+ else
1365
+ this.cellTimes.get(chunk.key)?.delete(vk);
1366
+ if (arrival > 0)
1367
+ this.mapOf(this.arrivals, chunk.key).set(vk, { x, y, z, seq: arrival });
1368
+ else
1369
+ this.arrivals.get(chunk.key)?.delete(vk);
1370
+ }
1371
+ mapOf(maps, key) {
1372
+ let map = maps.get(key);
1373
+ if (!map) {
1374
+ map = new Map();
1375
+ maps.set(key, map);
1376
+ }
1377
+ return map;
1378
+ }
1379
+ /** Stop tracking a chunk. A read of it that is out is not applied. */
1380
+ forget(key) {
1381
+ this.chunks.delete(key);
1382
+ this.inFlight.delete(key);
1383
+ this.hydrateFailures.delete(key);
1384
+ this.cellTimes.delete(key);
1385
+ this.arrivals.delete(key);
1386
+ this.revisionValue += 1;
1101
1387
  }
1102
1388
  applyVoxel(chunk, x, y, z, voxelType, encodedState, decodedState) {
1103
1389
  let state = decodedState;