Skip to content

Open source CapCut alternative.

TypeScript

feat(site): smart select falls to a color wand off the model's objects

David Lec51ad8182411
diff --git a/site/src/cut/lib/cutout.ts b/site/src/cut/lib/cutout.ts
index a002b5cc..5ece6a51 100644
--- a/site/src/cut/lib/cutout.ts
+++ b/site/src/cut/lib/cutout.ts
@@ -21,6 +21,7 @@ import {
withOutline,
} from "@donkeycut/effects-kit";
import { hostedPost } from "./hosted";
+import { touchAlpha, wandAlpha, type WandScratch } from "./removal/touchMask";
import { decodeRasterImage, rasterCanvasToDataUrl, rasterCanvasToPng } from "./raster";
import { geminiModelRoles } from "@/lib/inference/gemini-models";
@@ -175,17 +176,39 @@ export function interactiveSegmenter(): Promise<TouchSegmenter | null> {
return touchOnce;
}
+/** White canvas carrying `alpha`, or null when nearly nothing survived. */
+function alphaToCanvas(alpha: Uint8ClampedArray, w: number, h: number): HTMLCanvasElement | null {
+ const [out, ctx] = canvasOf(w, h);
+ const img = ctx.createImageData(w, h);
+ let kept = 0;
+ for (let i = 0; i < w * h; i++) {
+ img.data[i * 4] = 255;
+ img.data[i * 4 + 1] = 255;
+ img.data[i * 4 + 2] = 255;
+ img.data[i * 4 + 3] = alpha[i];
+ if (alpha[i] > 128) kept++;
+ }
+ if (kept < w * h * 0.001) return null;
+ ctx.putImageData(img, 0, 0);
+ return out;
+}
+
/**
- * Segment the object under a tap (or a scribbled path) and return its alpha
- * canvas at the mask's own resolution, white where the object is. Points are
- * frame fractions. Null when nothing registers. The `source` should be small
- * (≤ ~512px) — the model resamples anyway, and quick-brush strokes segment
- * per pointer move.
+ * Select what sits under a tap (or a scribbled path) and return its alpha
+ * canvas, white where the pick is. Points are frame fractions. The model's
+ * object pick leads; where it refuses to anchor on the touched spot — a
+ * backdrop, not an object to it — or anchors on too few pixels to hold a
+ * selection, the geodesic color wand takes the stroke instead, so flat
+ * regions select as cleanly as subjects. Null when nothing registers. The
+ * `source` should be small (≤ ~512px) — the model resamples anyway, and
+ * quick-brush strokes segment per pointer move; a caller re-segmenting the
+ * same frame can pass its pixels and a wand scratch to skip the re-reads.
*/
export function segmentTouchAlpha(
segmenter: TouchSegmenter,
source: HTMLCanvasElement,
- points: { x: number; y: number }[]
+ points: { x: number; y: number }[],
+ opts: { rgba?: Uint8ClampedArray; scratch?: WandScratch } = {}
): HTMLCanvasElement | null {
if (points.length === 0) return null;
const roi =
@@ -193,35 +216,32 @@ export function segmentTouchAlpha(
? { keypoint: { x: points[0].x, y: points[0].y } }
: { scribble: points.map((p) => ({ x: p.x, y: p.y })) };
const result = segmenter.segment(source, roi);
+ let picked: HTMLCanvasElement | null = null;
try {
const masks = result.confidenceMasks;
- if (!masks?.length) return null;
- // Two masks: background first, the touched object second (mirroring the
- // selfie model's layout). A single mask is the object itself.
- const conf = masks.length > 1 ? masks[1].getAsFloat32Array() : masks[0].getAsFloat32Array();
- const mw = masks[0].width;
- const mh = masks[0].height;
- const [out, ctx] = canvasOf(mw, mh);
- const img = ctx.createImageData(mw, mh);
- let kept = 0;
- for (let i = 0; i < mw * mh; i++) {
- const subject = conf[i];
- const a =
- subject > PERSON_THRESHOLD
- ? Math.min(255, Math.round((subject - PERSON_THRESHOLD) * 4 * 255))
- : 0;
- img.data[i * 4] = 255;
- img.data[i * 4 + 1] = 255;
- img.data[i * 4 + 2] = 255;
- img.data[i * 4 + 3] = a;
- if (a > 128) kept++;
+ if (masks?.length) {
+ // Two masks: background first, the touched object second (mirroring
+ // the selfie model's layout). A single mask is the object itself.
+ const conf = masks.length > 1 ? masks[1].getAsFloat32Array() : masks[0].getAsFloat32Array();
+ const mw = masks[0].width;
+ const mh = masks[0].height;
+ const alpha = touchAlpha(conf, mw, mh, points);
+ picked = alpha ? alphaToCanvas(alpha, mw, mh) : null;
}
- if (kept < mw * mh * 0.001) return null;
- ctx.putImageData(img, 0, 0);
- return out;
} finally {
result.close();
}
+ if (picked) return picked;
+ const sw = source.width;
+ const sh = source.height;
+ let rgba = opts.rgba;
+ if (!rgba) {
+ const sctx = source.getContext("2d");
+ if (!sctx) return null;
+ rgba = sctx.getImageData(0, 0, sw, sh).data;
+ }
+ const wand = wandAlpha(rgba, sw, sh, points, opts.scratch);
+ return wand ? alphaToCanvas(wand, sw, sh) : null;
}
/** Person matting, fully on-device. Null when no person registers (callers
diff --git a/site/src/cut/lib/removal/interactive.ts b/site/src/cut/lib/removal/interactive.ts
index 601a5fcb..9aa7ee26 100644
--- a/site/src/cut/lib/removal/interactive.ts
+++ b/site/src/cut/lib/removal/interactive.ts
@@ -13,6 +13,7 @@ import { matteLumaToAlpha } from "@donkeycut/effects-kit";
import { interactiveSegmenter, segmentTouchAlpha } from "../cutout";
import { sampleClipSource } from "../previewCanvas";
import { createRasterCanvas, rasterCanvasToDataUrl, type RasterSurface } from "../raster";
+import type { WandScratch } from "./touchMask";
import type { RemovalSeeds } from "../types";
/** Working-mask short side: enough for a crisp overlay, cheap to re-segment
@@ -38,6 +39,10 @@ export class QuickSelectSession {
private w = 2;
private h = 2;
private seg: Awaited<ReturnType<typeof interactiveSegmenter>> = null;
+ /** The working frame's pixels and the wand's tone field, read once per
+ * frame and shared across a stroke's per-move re-segmentations. */
+ private frameRgba: Uint8ClampedArray | null = null;
+ private wandScratch: WandScratch = {};
private constructor() {
this.work = createRasterCanvas(2, 2);
@@ -89,14 +94,29 @@ export class QuickSelectSession {
const ctx = this.work.getContext("2d") as CanvasRenderingContext2D | null;
if (!ctx) return false;
ctx.drawImage(src, 0, 0, w, h);
+ this.frameRgba = null;
+ this.wandScratch = {};
return true;
}
+ /** The working frame's pixels, read once per refreshed frame. */
+ private rgbaOf(): Uint8ClampedArray | undefined {
+ if (!this.frameRgba) {
+ const ctx = this.work.getContext("2d") as CanvasRenderingContext2D | null;
+ if (!ctx) return undefined;
+ this.frameRgba = ctx.getImageData(0, 0, this.w, this.h).data;
+ }
+ return this.frameRgba;
+ }
+
/** Run tap-to-select over the stroke and fold the result into the mask.
* `erase` subtracts the picked object. True when something registered. */
quickStroke(points: Point[], erase: boolean): boolean {
if (!this.seg || points.length === 0) return false;
- const alpha = segmentTouchAlpha(this.seg, this.work as HTMLCanvasElement, points);
+ const alpha = segmentTouchAlpha(this.seg, this.work as HTMLCanvasElement, points, {
+ rgba: this.rgbaOf(),
+ scratch: this.wandScratch,
+ });
if (!alpha) return false;
const ctx = this.mask.getContext("2d") as CanvasRenderingContext2D | null;
if (!ctx) return false;
@@ -112,7 +132,10 @@ export class QuickSelectSession {
* `commitTentative`. */
quickPreview(points: Point[], erase: boolean): boolean {
if (!this.seg || points.length === 0) return false;
- const alpha = segmentTouchAlpha(this.seg, this.work as HTMLCanvasElement, points);
+ const alpha = segmentTouchAlpha(this.seg, this.work as HTMLCanvasElement, points, {
+ rgba: this.rgbaOf(),
+ scratch: this.wandScratch,
+ });
const ctx = this.tentative.getContext("2d") as CanvasRenderingContext2D | null;
if (!ctx) return false;
ctx.clearRect(0, 0, this.w, this.h);
diff --git a/site/src/cut/lib/removal/touchMask.test.ts b/site/src/cut/lib/removal/touchMask.test.ts
new file mode 100644
index 00000000..8bca4766
--- /dev/null
+++ b/site/src/cut/lib/removal/touchMask.test.ts
@@ -0,0 +1,167 @@
+import { describe, expect, test } from "bun:test";
+import { TOUCH_FLOOR, touchAlpha, wandAlpha, type WandScratch } from "./touchMask";
+
+/** A confidence field painted from rectangles: [x0, y0, x1, y1, conf]. */
+function field(w: number, h: number, rects: [number, number, number, number, number][]) {
+ const conf = new Float32Array(w * h);
+ for (const [x0, y0, x1, y1, c] of rects) {
+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) conf[y * w + x] = c;
+ }
+ return conf;
+}
+
+const opaque = (a: Uint8ClampedArray | null, x: number, y: number, w: number) =>
+ !!a && a[y * w + x] > 128;
+
+describe("touchAlpha", () => {
+ test("keeps the touched blob and drops a disconnected one", () => {
+ const conf = field(20, 10, [
+ [1, 1, 6, 6, 0.95],
+ [12, 1, 18, 6, 0.95],
+ ]);
+ const a = touchAlpha(conf, 20, 10, [{ x: 3 / 20, y: 3 / 10 }]);
+ expect(opaque(a, 3, 3, 20)).toBe(true);
+ expect(opaque(a, 14, 3, 20)).toBe(false);
+ });
+
+ test("a confident stroke sheds connected low-confidence bleed", () => {
+ // The touched backdrop reads 0.95; the model bleeds 0.5 onto the
+ // adjoining subject. The floor alone would keep the bleed.
+ const conf = field(20, 10, [
+ [0, 0, 10, 10, 0.95],
+ [10, 0, 20, 10, 0.5],
+ ]);
+ const a = touchAlpha(conf, 20, 10, [{ x: 4 / 20, y: 5 / 10 }]);
+ expect(opaque(a, 4, 5, 20)).toBe(true);
+ expect(opaque(a, 15, 5, 20)).toBe(false);
+ });
+
+ test("a tap the model won't anchor returns null for the wand to take", () => {
+ // The model put nothing on the touched spot but found an object nearby.
+ const conf = field(20, 10, [[12, 1, 18, 6, 0.9]]);
+ expect(touchAlpha(conf, 20, 10, [{ x: 2 / 20, y: 8 / 10 }])).toBeNull();
+ });
+
+ test("nothing above the floor registers as null", () => {
+ const conf = field(20, 10, [[0, 0, 20, 10, TOUCH_FLOOR - 0.1]]);
+ expect(touchAlpha(conf, 20, 10, [{ x: 0.5, y: 0.5 }])).toBeNull();
+ });
+
+ test("a stroke keeps its first-touch anchor as later samples drag the median down", () => {
+ // The drag starts on a confident object and runs far into low-confidence
+ // ground: the tier holds — the object stays picked — and the pick never
+ // flips to the wand mid-stroke.
+ const conf = field(20, 10, [
+ [0, 0, 6, 10, 0.95],
+ [6, 0, 20, 10, 0.2],
+ ]);
+ const a = touchAlpha(conf, 20, 10, [
+ { x: 2 / 20, y: 5 / 10 },
+ { x: 8 / 20, y: 5 / 10 },
+ { x: 12 / 20, y: 5 / 10 },
+ { x: 16 / 20, y: 5 / 10 },
+ ]);
+ expect(opaque(a, 2, 5, 20)).toBe(true);
+ expect(opaque(a, 12, 5, 20)).toBe(false);
+ });
+
+ test("a scribble anchors on its median confidence", () => {
+ // One stroke point grazes the 0.55 bleed; the median holds at 0.95 and
+ // the bleed still drops.
+ const conf = field(20, 10, [
+ [0, 0, 10, 10, 0.95],
+ [10, 0, 20, 10, 0.55],
+ ]);
+ const a = touchAlpha(conf, 20, 10, [
+ { x: 3 / 20, y: 5 / 10 },
+ { x: 5 / 20, y: 5 / 10 },
+ { x: 11 / 20, y: 5 / 10 },
+ ]);
+ expect(opaque(a, 4, 5, 20)).toBe(true);
+ expect(opaque(a, 16, 5, 20)).toBe(false);
+ });
+});
+
+/** An rgba image painted per pixel. */
+function image(w: number, h: number, colorAt: (x: number, y: number) => [number, number, number]) {
+ const rgba = new Uint8ClampedArray(w * h * 4);
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const [r, g, b] = colorAt(x, y);
+ const i = (y * w + x) * 4;
+ rgba[i] = r;
+ rgba[i + 1] = g;
+ rgba[i + 2] = b;
+ rgba[i + 3] = 255;
+ }
+ }
+ return rgba;
+}
+
+describe("wandAlpha", () => {
+ test("a flat region selects whole and stops at the boundary", () => {
+ const rgba = image(24, 12, (x) => (x < 12 ? [20, 20, 40] : [180, 150, 130]));
+ const a = wandAlpha(rgba, 24, 12, [{ x: 4 / 24, y: 6 / 12 }]);
+ expect(opaque(a, 1, 1, 24)).toBe(true);
+ expect(opaque(a, 10, 10, 24)).toBe(true);
+ expect(opaque(a, 16, 6, 24)).toBe(false);
+ });
+
+ test("a smooth gradient stays on-signature, a strong edge does not", () => {
+ const rgba = image(24, 12, (x) => (x < 12 ? [20 + x, 20 + x, 40] : [200, 60, 60]));
+ const a = wandAlpha(rgba, 24, 12, [{ x: 2 / 24, y: 6 / 12 }]);
+ expect(opaque(a, 11, 6, 24)).toBe(true);
+ expect(opaque(a, 14, 6, 24)).toBe(false);
+ });
+
+ test("the same color across a wide bright gap stays out", () => {
+ const rgba = image(30, 12, (x) => (x < 10 || x >= 20 ? [30, 30, 30] : [200, 200, 200]));
+ const a = wandAlpha(rgba, 30, 12, [{ x: 5 / 30, y: 6 / 12 }]);
+ expect(opaque(a, 8, 6, 30)).toBe(true);
+ expect(opaque(a, 15, 6, 30)).toBe(false);
+ expect(opaque(a, 25, 6, 30)).toBe(false);
+ });
+
+ test("thin off-signature grooves are bridged, the far side joins", () => {
+ // A slatted wall: faces of 40 with 2px grooves of 8. One tap on a face
+ // takes the grooves and the faces beyond them.
+ const face = (x: number) => (x % 8 < 6 ? 40 : 8);
+ const rgba = image(32, 12, (x) => [face(x), face(x), face(x)]);
+ const a = wandAlpha(rgba, 32, 12, [{ x: 2 / 32, y: 6 / 12 }]);
+ expect(opaque(a, 7, 6, 32)).toBe(true);
+ expect(opaque(a, 20, 6, 32)).toBe(true);
+ expect(opaque(a, 30, 6, 32)).toBe(true);
+ });
+
+ test("a scratch reuses the tone field across moves of one stroke", () => {
+ const rgba = image(24, 12, (x) => (x < 12 ? [20, 20, 40] : [180, 150, 130]));
+ const scratch: WandScratch = {};
+ const first = wandAlpha(rgba, 24, 12, [{ x: 4 / 24, y: 6 / 12 }], scratch);
+ const heldTone = scratch.tone;
+ expect(heldTone).toBeDefined();
+ const second = wandAlpha(
+ rgba,
+ 24,
+ 12,
+ [
+ { x: 4 / 24, y: 6 / 12 },
+ { x: 8 / 24, y: 6 / 12 },
+ ],
+ scratch
+ );
+ expect(scratch.tone).toBe(heldTone!);
+ expect([...second!]).toEqual([...first!]);
+ });
+
+ test("a scribble across two tones adds both signatures", () => {
+ const tone = (x: number) => (Math.floor(x / 6) % 2 === 0 ? 40 : 100);
+ const rgba = image(24, 12, (x) => [tone(x), tone(x), tone(x)]);
+ const tap = wandAlpha(rgba, 24, 12, [{ x: 3 / 24, y: 6 / 12 }]);
+ expect(opaque(tap, 15, 6, 24)).toBe(false);
+ const scribble = wandAlpha(rgba, 24, 12, [
+ { x: 3 / 24, y: 6 / 12 },
+ { x: 8 / 24, y: 6 / 12 },
+ ]);
+ expect(opaque(scribble, 15, 6, 24)).toBe(true);
+ });
+});
diff --git a/site/src/cut/lib/removal/touchMask.ts b/site/src/cut/lib/removal/touchMask.ts
new file mode 100644
index 00000000..55047f52
--- /dev/null
+++ b/site/src/cut/lib/removal/touchMask.ts
@@ -0,0 +1,212 @@
+/**
+ * Smart select's mask math, two tiers. The tap-to-select model handles what
+ * it is built for — objects: its confidence mask is gated by the confidence
+ * at the stroke itself and by connectivity to it, so the object-centric
+ * model's bleed into the salient subject stays out of a pick. Where the
+ * model refuses to anchor — backdrops, walls, sky, anything it will not call
+ * an object — the pick falls to a geodesic color wand: distance from the
+ * stroke accumulates color change along the cheapest path, so a smooth
+ * region costs its total drift while a real boundary is a cost cliff, and
+ * the selection snaps there. The wand is the interactive-rate shape of the
+ * classic scribble segmentation energy (color model + contrast-aware cut).
+ */
+
+/** Floor confidence for a pixel to count as picked at all. */
+export const TOUCH_FLOOR = 0.35;
+/** How far below the stroke's own confidence a pixel may sit and still join
+ * the pick. */
+export const TOUCH_MARGIN = 0.3;
+
+type Point = { x: number; y: number };
+
+/** Index of the mask pixel under a frame-fraction point. */
+const at = (p: Point, mw: number, mh: number) =>
+ Math.min(mh - 1, Math.max(0, Math.round(p.y * mh))) * mw +
+ Math.min(mw - 1, Math.max(0, Math.round(p.x * mw)));
+
+const median = (v: number[]) => {
+ const s = [...v].sort((a, b) => a - b);
+ return s[s.length >> 1];
+};
+
+/**
+ * The picked region's alpha bytes (0..255, one per mask pixel), or null when
+ * the model puts no confidence on the touched spot itself — the stroke landed
+ * on something the model refuses to call an object, and the caller falls
+ * through to the color wand. Points are frame fractions.
+ *
+ * The stroke's first point alone decides which tier answers: it never moves
+ * while a drag grows, so the preview stays with one tier for the whole
+ * stroke. The median over the stroke then sets the confidence floor, which
+ * keeps one stray sample grazing model bleed from widening the pick.
+ */
+export function touchAlpha(
+ conf: Float32Array,
+ mw: number,
+ mh: number,
+ points: Point[]
+): Uint8ClampedArray | null {
+ if (points.length === 0) return null;
+ if (conf[at(points[0], mw, mh)] <= TOUCH_FLOOR) return null;
+ const seedConf = Math.max(TOUCH_FLOOR, median(points.map((p) => conf[at(p, mw, mh)])));
+ const floor = Math.max(TOUCH_FLOOR, seedConf - TOUCH_MARGIN);
+ const alpha = new Uint8ClampedArray(mw * mh);
+ let kept = 0;
+ const ramp = (c: number) => Math.min(255, Math.round((c - floor) * 4 * 255));
+ // Flood from the stroke over above-floor pixels; 4-connected.
+ const seen = new Uint8Array(mw * mh);
+ const queue: number[] = [];
+ const visit = (i: number) => {
+ if (!seen[i] && conf[i] > floor) {
+ seen[i] = 1;
+ queue.push(i);
+ }
+ };
+ for (const p of points) visit(at(p, mw, mh));
+ while (queue.length) {
+ const i = queue.pop()!;
+ alpha[i] = ramp(conf[i]);
+ if (alpha[i] > 128) kept++;
+ const x = i % mw;
+ if (x > 0) visit(i - 1);
+ if (x < mw - 1) visit(i + 1);
+ if (i >= mw) visit(i - mw);
+ if (i < mw * (mh - 1)) visit(i + mw);
+ }
+ return kept > 0 ? alpha : null;
+}
+
+/** Color distance (L1 mean, 0..255) within which a pixel counts as one of
+ * the stroke's own tones. */
+export const WAND_TONE = 26;
+/** How far past the tones a pixel may sit and still be selectable when the
+ * pick flows through it — soft shadows, grain, antialiased slivers. */
+const WAND_NEAR = 22;
+/** Off-tone cost budget a path may spend bridging thin foreign runs — a
+ * groove, a seam, a highlight line — before the pick stops. */
+const WAND_BARRIER = 64;
+/** Chamfer sweeps; two settle straight paths, the third the wiggly ones. */
+const WAND_PASSES = 3;
+
+/** The stroke's color signatures: its sampled colors, greedily merged so
+ * near-identical samples collapse into one representative. */
+function signatures(rgba: Uint8ClampedArray, seeds: number[]): number[][] {
+ const sig: number[][] = [];
+ for (const i of seeds) {
+ const c = [rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2]];
+ const near = sig.some(
+ (s) => Math.abs(s[0] - c[0]) + Math.abs(s[1] - c[1]) + Math.abs(s[2] - c[2]) < 36
+ );
+ if (!near) sig.push(c);
+ if (sig.length >= 16) break;
+ }
+ return sig;
+}
+
+/** Per-frame scratch a caller may hand `wandAlpha`: the tone field is the
+ * wand's heavy pass and depends only on the picture and the stroke's
+ * signature set, so across the pointer moves of one stroke it is usually
+ * reusable as-is. */
+export interface WandScratch {
+ key?: string;
+ tone?: Float32Array;
+}
+
+/**
+ * The color wand, shaped like SIOX's foreground select: the stroke's colors
+ * cluster into signatures, every pixel scores by its distance to the nearest
+ * signature, and the pick grows from the stroke over on-signature pixels.
+ * Growth carries a small budget for off-signature cost, so thin foreign runs
+ * — grooves, seams, texture lines — are bridged and their far side joins,
+ * while a real subject boundary is wide and costly enough to stop at.
+ * Scribbling over more tones adds signatures and widens the pick with it.
+ */
+export function wandAlpha(
+ rgba: Uint8ClampedArray,
+ w: number,
+ h: number,
+ points: Point[],
+ scratch?: WandScratch
+): Uint8ClampedArray | null {
+ if (points.length === 0) return null;
+ const seeds = points.map((p) => at(p, w, h));
+ const sig = signatures(rgba, seeds);
+ // Distance from each pixel's color to the nearest signature — cached in
+ // the scratch while the signature set holds.
+ const key = `${w}x${h}|${sig.map((s) => s.join(",")).join(";")}`;
+ let tone = scratch?.key === key ? scratch.tone : undefined;
+ if (!tone) {
+ tone = new Float32Array(w * h);
+ for (let i = 0; i < w * h; i++) {
+ const r = rgba[i * 4];
+ const g = rgba[i * 4 + 1];
+ const b = rgba[i * 4 + 2];
+ let best = Infinity;
+ for (const s of sig) {
+ const d = (Math.abs(s[0] - r) + Math.abs(s[1] - g) + Math.abs(s[2] - b)) / 3;
+ if (d < best) best = d;
+ }
+ tone[i] = best;
+ }
+ if (scratch) {
+ scratch.key = key;
+ scratch.tone = tone;
+ }
+ }
+ // Geodesic growth from the stroke: entering an on-signature pixel is free,
+ // an off-signature pixel charges its excess, and the accumulated charge
+ // along the cheapest 8-connected path is capped by the bridge budget.
+ const cost = (i: number) => Math.max(0, tone[i] - WAND_TONE);
+ const dist = new Float32Array(w * h).fill(Infinity);
+ for (const i of seeds) dist[i] = 0;
+ for (let pass = 0; pass < WAND_PASSES; pass++) {
+ let changed = false;
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const i = y * w + x;
+ let d = dist[i];
+ const c = cost(i);
+ if (x > 0) d = Math.min(d, dist[i - 1] + c);
+ if (y > 0) {
+ d = Math.min(d, dist[i - w] + c);
+ if (x > 0) d = Math.min(d, dist[i - w - 1] + c);
+ if (x < w - 1) d = Math.min(d, dist[i - w + 1] + c);
+ }
+ if (d < dist[i]) {
+ dist[i] = d;
+ changed = true;
+ }
+ }
+ }
+ for (let y = h - 1; y >= 0; y--) {
+ for (let x = w - 1; x >= 0; x--) {
+ const i = y * w + x;
+ let d = dist[i];
+ const c = cost(i);
+ if (x < w - 1) d = Math.min(d, dist[i + 1] + c);
+ if (y < h - 1) {
+ d = Math.min(d, dist[i + w] + c);
+ if (x < w - 1) d = Math.min(d, dist[i + w + 1] + c);
+ if (x > 0) d = Math.min(d, dist[i + w - 1] + c);
+ }
+ if (d < dist[i]) {
+ dist[i] = d;
+ changed = true;
+ }
+ }
+ }
+ // Straight paths settle in one pass, wiggly ones in two or three; once a
+ // pass moves nothing the field is final.
+ if (!changed) break;
+ }
+ const alpha = new Uint8ClampedArray(w * h);
+ const core = WAND_BARRIER * 0.6;
+ for (let i = 0; i < w * h; i++) {
+ if (tone[i] > WAND_TONE + WAND_NEAR) continue;
+ const d = dist[i];
+ if (d <= core) alpha[i] = 255;
+ else if (d < WAND_BARRIER)
+ alpha[i] = Math.round(255 * (1 - (d - core) / (WAND_BARRIER - core)));
+ }
+ return alpha;
+}