# Keyed box diffing

> diffBoxes compares two keyed collections of box snapshots and returns the raw damage footprints of what was added, removed, moved or restyled.

Source: https://dirtytalk.42.dog/docs/spatial/box-diffing/

`diffBoxes` diffs two snapshots of a keyed collection — a scene layer, a list of items with bounds — and returns the damage rects of what changed. Keys are entity identity, so reordering the collection with unchanged keys, rects and content produces no damage.

```ts
import { diffBoxes, planRegions } from '@dirtytalk/spatial';
import type { BoxSnapshot, Rect } from '@dirtytalk/spatial';

const bounds: Rect = { x: 0, y: 0, w: 800, h: 600 };

const prev = new Map<string, BoxSnapshot<number>>();
const next = new Map<string, BoxSnapshot<number>>();

// Populate prev/next with { rect, content } per entity key.
prev.set('a', { rect: { x: 0, y: 0, w: 10, h: 10 }, content: 1 });
next.set('a', { rect: { x: 5, y: 5, w: 10, h: 10 }, content: 1 }); // moved
next.set('b', { rect: { x: 100, y: 100, w: 10, h: 10 }, content: 2 }); // added

const damage = diffBoxes(prev, next); // raw damage rects
const plan = planRegions(damage, bounds); // clip, merge, budget
```

## Signature

```ts
interface BoxSnapshot<V> {
  readonly rect: Rect;
  readonly content: V;
}

interface BoxDiffOptions<V, K> {
  equalsContent?: (prev: V, next: V, key: K) => boolean;
}

function diffBoxes<K, V>(
  prev: ReadonlyMap<K, BoxSnapshot<V>>,
  next: ReadonlyMap<K, BoxSnapshot<V>>,
  options?: BoxDiffOptions<V, K>,
): Rect[];
```

## What it returns

`diffBoxes` returns the raw damage footprints — the rects whose pixels changed — **not** a clipped, disjoint or budgeted region list. Feed the result to [`planRegions`](/docs/spatial/repaint-planning/) for clamping, merging and budgeting.

| Change                                        | Emitted rects                         |
| --------------------------------------------- | ------------------------------------- |
| Content changed, same rect                    | the rect twice (old + new footprints) |
| Rect moved, same content                      | old rect, then new rect               |
| Key added                                     | the new rect                          |
| Key removed                                   | the old rect                          |
| Unchanged (same rect, same content)           | nothing                               |
| Key present in both, reordered with no change | nothing                               |

- Keys are **identity**, not collection position. A z-order change with identical keys, rects and content emits nothing; invalidate ordering-aware composition yourself or supply order metadata alongside the snapshots.
- **Snapshots must be independently retained.** If `prev` and `next` share the same snapshot object and you mutate it in place, both sides change and the old geometry/content is unrecoverable.
- Every rect must be finite; non-finite values throw an `Error` prefixed `diffBoxes:`. Zero- and negative-area rects are emitted as-is (they are dropped later by `planRegions`).

## Content equality

The default comparator is `Object.is` over `content`. Supply `equalsContent` when content is a non-primitive or a shallow/deep equality is the right test for your consumer.

```ts
import { diffBoxes } from '@dirtytalk/spatial';
import type { BoxSnapshot } from '@dirtytalk/spatial';

const diff = diffBoxes(prev, next, {
  equalsContent: (a, b, key) => key.endsWith(':style') && shallowEqual(a, b),
});
```

`equalsContent` receives the key, so you can compare differently per entity kind. It runs for keys present on both sides whose boxes are unchanged; a moved box emits both footprints without consulting it.

## Determinism

Iteration follows `Map` insertion order, so the emitted rect order is deterministic given the same maps. The output rects are freshly copied, never references into your snapshots; mutation of the returned array or rects does not affect `prev` or `next`.

## Packed, index-aligned snapshots

Use `diffAlignedBoxes` rather than building Maps when the producer already stores aligned
Float32 AABBs and Uint32 content tokens:

```ts
import { diffAlignedBoxes } from '@dirtytalk/spatial';
import type { AlignedBoxes } from '@dirtytalk/spatial';

const prev: AlignedBoxes = {
  boxes: new Float32Array([0, 0, 10, 10]), // minX, minY, maxX, maxY
  tokens: new Uint32Array([1]),
  count: 1,
};
const next: AlignedBoxes = {
  boxes: new Float32Array([5, 0, 15, 10]),
  tokens: new Uint32Array([1]),
  count: 1,
};
const result = diffAlignedBoxes(prev, next, (index, kind) => {
  console.log(index, kind); // 0, 'geometry'
  // Project/copy old and new footprints here. Return false to stop.
});
console.log(result.completed); // true
```

- Identity is **index**, not a stable key. Visits are ascending overlapping indices followed
  by the added or removed tail. Kinds are `geometry`, `content`, `geometry+content`, `add`, `remove`.
- Only changed entries invoke the visitor. No per-entry objects or intermediate changed-index
  lists are allocated; the consumer owns damage construction and projection.
- `count` must be a non-negative safe integer within both buffers' capacity. Every changed or
  tail entry is validated for finite geometry **before** the first visit; unchanged entries
  (which produce no damage) and trailing capacity are not checked. Invalid input throws
  `diffAlignedBoxes:` errors even if a visitor would have stopped early.
- A strict `false` return stops visiting and yields `{ completed: false }`, including on the last
  change. Other returns continue; visitor errors propagate.
- Zero/inverted boxes are compared as finite geometry, not special raw-span sentinels. Hashing,
  projection and interpreting unbounded geometry remain consumer-owned. Geometry compares
  `-0` and `+0` as equal; tokens compare Uint32 values without a collision-safety guarantee.
- Retain independent snapshots and do not mutate either during visiting. Reorders/compositing
  changes invisible to geometry/tokens require separate invalidation, just as with keyed diffing.

## When to use it

- A scene layer whose children are keyed by entity id, and you snapshot `{ bounds, contentHash }` each commit.
- A virtualized list: diff two viewport snapshots to get the exact added/removed/moved rows to repaint, instead of invalidating the whole viewport.
- Feeding [`planRegions`](/docs/spatial/repaint-planning/) so raw footprints become a budgeted, optionally disjoint repaint plan.
