# Repaint planning

> planRegions turns damage rects into a repaint plan: rects, bounds or full strategies, a region budget, pairwise-disjoint merging and opt-in full-frame promotion.

Source: https://dirtytalk.42.dog/docs/spatial/repaint-planning/

`planRegions` is the standalone planner behind `SceneRoot`'s paint stage. It turns a list of damage rects into the regions a renderer should repaint. Use it directly when you want a full-or-partial verdict and a guaranteed-disjoint region list without a `SceneRoot`.

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

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

const plan = planRegions(
  [
    { x: 0, y: 0, w: 10, h: 10 },
    { x: 2, y: 0, w: 10, h: 10 },
  ],
  bounds,
  { disjoint: true, promoteFraction: 0.6 },
);

if (plan.kind === 'partial') {
  console.log(plan.regions); // pairwise-disjoint rects to repaint
} else {
  console.log(plan.reason); // 'strategy' | 'area'
}
```

## Signature

```ts
type RepaintStrategy = 'rects' | 'bounds' | 'full';
type RegionCapStrategy = 'bounds' | 'nearest';

interface RegionPlanOptions {
  strategy?: RepaintStrategy;
  maxRegions?: number;
  capStrategy?: RegionCapStrategy;
  disjoint?: boolean | { slack: number };
  promoteFraction?: number;
}

type RegionPlan =
  | { kind: 'partial'; regions: readonly Rect[] }
  | { kind: 'full'; reason: 'strategy' | 'area' };

function planRegions(
  rects: readonly Rect[],
  bounds: Rect,
  options?: RegionPlanOptions,
): RegionPlan;
```

## Options

| Option            | Type                            | Default    | Meaning                                                                                                                                                    |
| ----------------- | ------------------------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `strategy`        | `'rects' \| 'bounds' \| 'full'` | `'rects'`  | How damage is planned (see [Strategies](#strategies)).                                                                                                     |
| `maxRegions`      | `number`                        | `16`       | Region budget. Must be a positive integer. Reduction follows `capStrategy`.                                                                                |
| `capStrategy`     | `'bounds' \| 'nearest'`         | `'bounds'` | Bounds collapse (default) or opt-in nearest-centre reduction. Applies to `rects` strategy only.                                                            |
| `disjoint`        | `boolean \| { slack }`          | `false`    | When truthy, merge touching/overlapping pairs to a fixpoint so the output is pairwise disjoint. `{ slack }` also merges pairs within `slack` on both axes. |
| `promoteFraction` | `number`                        | off        | Promote to a full repaint once planned coverage reaches this fraction of the bounds. Must be a finite fraction in `(0, 1]`.                                |

## Strategies

### `'rects'` (default)

Area-aware merging with a bounded working set. A rect joins the first earlier region whose bounding box costs no more than the pair's areas combined, so containment and a small move's overlapping old/new footprints collapse, while disjoint damage stays separate. Past `maxRegions` the plan collapses to one bounding rect.

```ts
planRegions(
  [
    { x: 0, y: 0, w: 10, h: 10 },
    { x: 100, y: 100, w: 10, h: 10 }, // disjoint: stays separate
  ],
  bounds,
);
// { kind: 'partial', regions: [ {0,0,10,10}, {100,100,10,10} ] }
```

### Nearest-centre cap reduction

Opt into `capStrategy: 'nearest'` to keep a small over-budget frame sparse:

```ts
planRegions(damage, bounds, {
  maxRegions: 12,
  capStrategy: 'nearest',
  disjoint: { slack: 4 },
  promoteFraction: 0.6,
});
```

In disjoint mode it near-merges **before** counting residual regions: 12 remain as-is,
13–24 are reduced by greedily unioning the nearest-centred pair, and more than 24 collapse
to one bounding rectangle. Every union is followed by near-merging again. Without disjoint,
it reduces raw clipped rects without initial near/area-aware merging. Ties are deterministic.

Near-merging sorts regions by left edge and only tests pairs whose x ranges come within
`slack`, so sparse marks and text-like rows of glyphs stay cheap. Near and nearest scans share
a **100,000-pair comparison budget**, which is only reached when hundreds of regions share an
x range (e.g. one tall column of marks). Exhaustion collapses all clipped input conservatively,
possibly before the global near fixpoint is reached. Validation/clipping still scan every
input; the guard bounds pair searches, not total allocations or wall time. Coverage, region
count and requested separation hold even on fallback. The default policy is unchanged.

### `'bounds'`

One region covering all damage — the union of every rect. Never more than one region.

### `'full'`

No regions; the renderer repaints the whole surface. Returns `{ kind: 'full', reason: 'strategy' }` after validating inputs (non-positive bounds still return empty).

## Disjoint mode

With `disjoint: true`, regions are merged to a fixpoint whenever they touch or overlap; `{ slack }` also merges pairs within `slack` on both axes. The output is pairwise disjoint, which a multi-rect scissor needs to skip the dead space between regions. A merge can create a new overlap with an earlier region, so the planner rescans until stable.

```ts
planRegions(
  [
    { x: 0, y: 0, w: 10, h: 10 },
    { x: 10, y: 0, w: 10, h: 10 }, // touches the first
  ],
  bounds,
  { disjoint: true },
);
// one region { x: 0, y: 0, w: 20, h: 10 }
```

> **Cost.** With the default `capStrategy: 'bounds'`, the fixpoint runs over at most `maxRegions` surviving regions. Nearest mode runs it before cap reduction and uses the shared pair-search guard. Repeated rescanning can be cubic without a guard; keep budgets modest — see [Performance](#performance).

## Full-frame promotion

`promoteFraction` promotes a plan to `{ kind: 'full', reason: 'area' }` once the planned coverage reaches that fraction of the bounds (inclusive `>=`, not strict `>`). Coverage is the **true union area** (a scanline over x-edges, so overlapping rects are never double-counted) when regions may overlap; with `disjoint: true` it is simply the sum of region areas.

```ts
planRegions(
  [{ x: 0, y: 0, w: 700, h: 500 }],
  { x: 0, y: 0, w: 800, h: 600 },
  {
    promoteFraction: 0.6,
  },
);
// { kind: 'full', reason: 'area' } — 350000 / 480000 ≈ 0.73
```

Use it to stop paying for per-region scissors once a frame is mostly dirty: a full clear plus one pass can be cheaper than N clips.

## Validation and empty results

- Every rect and `bounds` must be finite; invalid options (`maxRegions <= 0`, non-finite `slack`, `promoteFraction` outside `(0, 1]`, unknown `strategy` or `capStrategy`) throw an `Error` prefixed `planRegions:`.
- Rects with zero or negative area are dropped; the rest are clamped to `bounds`, and clamped rects that end up zero-sized are dropped.
- An empty or zero-area `bounds` returns `{ kind: 'partial', regions: [] }`.
- **An empty `partial` means "paint nothing", never an implicit full repaint.** `SceneRoot` skips the frame when the plan is empty, and materializes a full plan as `[bounds]`.

## Performance

The default bounds-collapse policy limits disjoint merging and coverage scans to at most `maxRegions` outputs. Nearest mode trades additional pair searches for potentially smaller repaint coverage and falls back when its comparison budget is spent. Raising the output cap also increases the promotion coverage scan's cost; the pair-search guard does not bound that scan. Measure planner CPU, output count and painted coverage separately on representative changed marks, not total scene size. In-repo microbenchmarks: `packages/spatial/src/region-plan.bench.ts` (`vp test bench`).

## In SceneRoot

`SceneRoot` runs `planRegions` with the root's `plan` options, feeding it both semantic damage and any repair from the renderer's `prepareFrame` hook, then freezes the result for the paint cull and the renderer clear. See [Rendering](/docs/spatial/rendering/#preparation-and-planning) and [API reference](/docs/spatial/api/#planregions).
