// Restricted color modes with dithering. // // The image is converted to a float "working" buffer (one luminance channel or three RGB // channels, values 0..1 in sRGB or linear light). An algorithm rewrites that buffer so // every value is one of the channel's levels; `finish` then maps each value to its level's // output color. That last step snaps to the nearest level, so whatever an algorithm (or a // user script) leaves in the buffer, the result only ever uses the restricted palette. // // This module touches no DOM: dither-worker.js imports it to give user scripts the same // helpers (see scriptApi). // ------------------------------------------------------------------ color spaces const srgbToLinear = (u) => (u <= 0.04045 ? u / 12.92 : ((u + 0.055) / 1.055) ** 2.4); const linearToSrgb = (l) => (l <= 0.0031308 ? l * 12.92 : 1.055 * l ** (1 / 2.4) - 0.055); const BYTE_TO_LINEAR = Float32Array.from({ length: 256 }, (_, i) => srgbToLinear(i / 255)); const clamp01 = (v) => (v < 0 ? 0 : v > 1 ? 1 : v); // ------------------------------------------------------------------ levels /** Index of the level nearest to v (levels ascending). NaN maps to 0. */ export function nearestIndex(levels, v) { const n = levels.length; if (!(v > levels[0])) return 0; if (v >= levels[n - 1]) return n - 1; let lo = 0, hi = n - 1; // levels[lo] < v < levels[hi] while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (levels[mid] <= v) lo = mid; else hi = mid; } return v - levels[lo] < levels[hi] - v ? lo : hi; } /** Index k such that levels[k] <= v < levels[k + 1] (clamped to 0..n-2). */ function lowerIndex(levels, v) { let lo = 0, hi = levels.length - 1; while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (levels[mid] <= v) lo = mid; else hi = mid; } return lo; } // ------------------------------------------------------------------ error diffusion /** Kernels as [dx, dy, weight] taps relative to the current pixel; weights / divisor. */ export const KERNELS = { 'floyd-steinberg': { label: 'Floyd–Steinberg', divisor: 16, taps: [[1, 0, 7], [-1, 1, 3], [0, 1, 5], [1, 1, 1]] }, atkinson: { label: 'Atkinson', divisor: 8, taps: [[1, 0, 1], [2, 0, 1], [-1, 1, 1], [0, 1, 1], [1, 1, 1], [0, 2, 1]] }, jarvis: { label: 'Jarvis–Judice–Ninke', divisor: 48, taps: [[1, 0, 7], [2, 0, 5], [-2, 1, 3], [-1, 1, 5], [0, 1, 7], [1, 1, 5], [2, 1, 3], [-2, 2, 1], [-1, 2, 3], [0, 2, 5], [1, 2, 3], [2, 2, 1]], }, stucki: { label: 'Stucki', divisor: 42, taps: [[1, 0, 8], [2, 0, 4], [-2, 1, 2], [-1, 1, 4], [0, 1, 8], [1, 1, 4], [2, 1, 2], [-2, 2, 1], [-1, 2, 2], [0, 2, 4], [1, 2, 2], [2, 2, 1]], }, burkes: { label: 'Burkes', divisor: 32, taps: [[1, 0, 8], [2, 0, 4], [-2, 1, 2], [-1, 1, 4], [0, 1, 8], [1, 1, 4], [2, 1, 2]] }, sierra: { label: 'Sierra', divisor: 32, taps: [[1, 0, 5], [2, 0, 3], [-2, 1, 2], [-1, 1, 4], [0, 1, 5], [1, 1, 4], [2, 1, 2], [-1, 2, 2], [0, 2, 3], [1, 2, 2]], }, 'sierra-2': { label: 'Two-Row Sierra', divisor: 16, taps: [[1, 0, 4], [2, 0, 3], [-2, 1, 1], [-1, 1, 2], [0, 1, 3], [1, 1, 2], [2, 1, 1]] }, 'sierra-lite': { label: 'Sierra Lite', divisor: 4, taps: [[1, 0, 2], [-1, 1, 1], [0, 1, 1]] }, }; /** * Error diffusion in place. buf: w*h*ch floats; alpha: w*h bytes (0 = skip the pixel, and * error that lands on it is dropped). levels: one ascending Float32Array per channel. */ export function diffuse(buf, w, h, ch, alpha, levels, taps, { divisor, serpentine = true, strength = 1 } = {}) { const div = divisor || taps.reduce((s, t) => s + t[2], 0) || 1; const n = taps.length; const dx = taps.map((t) => t[0]), dy = taps.map((t) => t[1]), wt = taps.map((t) => (t[2] / div) * strength); for (let y = 0; y < h; y++) { const rev = serpentine && (y & 1) === 1; for (let xi = 0; xi < w; xi++) { const x = rev ? w - 1 - xi : xi; const p = y * w + x; if (!alpha[p]) continue; for (let c = 0; c < ch; c++) { const i = p * ch + c, L = levels[c]; const v = buf[i]; const q = L[nearestIndex(L, v)]; buf[i] = q; const e = v - q; if (e === 0 || !Number.isFinite(e)) continue; for (let t = 0; t < n; t++) { const xx = rev ? x - dx[t] : x + dx[t], yy = y + dy[t]; if (xx < 0 || xx >= w || yy >= h || yy < 0) continue; buf[(yy * w + xx) * ch + c] += e * wt[t]; } } } } } // ------------------------------------------------------------------ ordered dithering /** * Ordered dithering in place: each value is rounded up to the next level when its position * between the two surrounding levels exceeds threshold(gx, gy) in 0..1. (gx, gy) are document * coordinates divided by `scale`, so patterns line up across selections. */ export function ordered(buf, w, h, ch, alpha, levels, threshold, { x0 = 0, y0 = 0, scale = 1 } = {}) { scale = Math.max(1, scale); for (let y = 0; y < h; y++) { const gy = Math.floor((y + y0) / scale); for (let x = 0; x < w; x++) { const p = y * w + x; if (!alpha[p]) continue; const t = threshold(Math.floor((x + x0) / scale), gy); for (let c = 0; c < ch; c++) { const i = p * ch + c, L = levels[c], v = buf[i]; if (!(v > L[0])) { buf[i] = L[0]; continue; } if (v >= L[L.length - 1]) { buf[i] = L[L.length - 1]; continue; } const k = lowerIndex(L, v); buf[i] = (v - L[k]) / (L[k + 1] - L[k]) > t ? L[k + 1] : L[k]; } } } } /** A threshold matrix built from any square/rectangular 2D array: values are ranked. */ export function matrixFromValues(rows) { const h = rows.length, w = rows[0].length; const cells = []; for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) cells.push({ i: y * w + x, v: Number(rows[y][x]) || 0 }); cells.sort((a, b) => a.v - b.v || a.i - b.i); const t = new Float32Array(w * h); cells.forEach((c, rank) => { t[c.i] = (rank + 0.5) / cells.length; }); return { w, h, t }; } export const matrixThreshold = (m) => (gx, gy) => m.t[(gy % m.h) * m.w + (gx % m.w)]; /** Bayer index matrix as a 2D array of ranks 0..n²-1 (n a power of two). */ export function bayer(n) { let m = [[0]]; while (m.length < n) { const s = m.length, next = []; for (let y = 0; y < s * 2; y++) next.push(new Array(s * 2)); for (let y = 0; y < s; y++) { for (let x = 0; x < s; x++) { const v = m[y][x] * 4; next[y][x] = v; next[y][x + s] = v + 2; next[y + s][x] = v + 3; next[y + s][x + s] = v + 1; } } m = next; } return m; } /** Clustered-dot halftone: dots grow from the cell center (light) and corners (dark). */ function halftone(n) { const rows = []; for (let y = 0; y < n; y++) { rows.push([]); for (let x = 0; x < n; x++) { const u = (2 * Math.PI * (x + 0.5)) / n, v = (2 * Math.PI * (y + 0.5)) / n; // tiny angular term breaks the four-way ties so dots grow round, not in a scan order rows[y].push(Math.cos(u) + Math.cos(v) + 1e-4 * Math.atan2(y + 0.5 - n / 2, x + 0.5 - n / 2)); } } return rows; } /** Horizontal line screen: lines thicken row by row; Bayer order within a row. */ function lineScreen(n) { const b = bayer(n)[0]; return Array.from({ length: n }, (_, y) => Array.from({ length: n }, (_, x) => Math.cos((2 * Math.PI * (y + 0.5)) / n) + 1e-3 * b[x])); } /** Small fast seeded PRNG. */ export function mulberry32(seed) { let a = seed >>> 0; return () => { a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } /** Stateless hash of integer coordinates to [0, 1). */ export function hash(x, y, seed = 0) { let h = Math.imul(x | 0, 0x27d4eb2d) ^ Math.imul(y | 0, 0x165667b1) ^ Math.imul(seed | 0, 0x9e3779b9); h = Math.imul(h ^ (h >>> 15), 0x85ebca6b); h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35); h ^= h >>> 16; return (h >>> 0) / 4294967296; } /** * 64×64 blue-noise threshold matrix by void-and-cluster (Ulichney 1993), generated once. * Phase 3 keeps filling the largest voids, which ranks the last zeros evenly too. */ let blueNoiseCache = null; export function blueNoise() { if (blueNoiseCache) return blueNoiseCache; const N = 64, n = N * N, sigma = 1.5; const K = new Float32Array(n); for (let y = 0; y < N; y++) { for (let x = 0; x < N; x++) { const dx = Math.min(x, N - x), dy = Math.min(y, N - y); K[y * N + x] = Math.exp(-(dx * dx + dy * dy) / (2 * sigma * sigma)); } } const splat = (E, p, sign) => { const px = p % N, py = (p / N) | 0; for (let y = 0; y < N; y++) { const krow = ((y - py + N) % N) * N, erow = y * N; for (let x = 0; x < N; x++) E[erow + x] += sign * K[krow + ((x - px + N) % N)]; } }; const extreme = (bits, E, want, max) => { let best = -1, bv = max ? -Infinity : Infinity; for (let p = 0; p < n; p++) { if (bits[p] !== want) continue; if (max ? E[p] > bv : E[p] < bv) { bv = E[p]; best = p; } } return best; }; const rnd = mulberry32(0x5eed); const bits = new Uint8Array(n), E = new Float32Array(n); const ones = n / 10; for (let placed = 0; placed < ones;) { const p = (rnd() * n) | 0; if (!bits[p]) { bits[p] = 1; splat(E, p, 1); placed++; } } // relax the initial pattern: move the tightest cluster into the largest void until stable for (let iter = 0; iter < n; iter++) { const c = extreme(bits, E, 1, true); bits[c] = 0; splat(E, c, -1); const v = extreme(bits, E, 0, false); bits[v] = 1; splat(E, v, 1); if (v === c) break; } const rank = new Uint32Array(n); const b1 = bits.slice(), E1 = E.slice(); for (let r = ones - 1; r >= 0; r--) { const c = extreme(b1, E1, 1, true); b1[c] = 0; splat(E1, c, -1); rank[c] = r; } for (let r = ones; r < n; r++) { const v = extreme(bits, E, 0, false); bits[v] = 1; splat(E, v, 1); rank[v] = r; } const t = new Float32Array(n); for (let p = 0; p < n; p++) t[p] = (rank[p] + 0.5) / n; blueNoiseCache = { w: N, h: N, t }; return blueNoiseCache; } const fromRows = (rowsFn) => { let m = null; return () => matrixThreshold(m ||= matrixFromValues(rowsFn())); }; // ------------------------------------------------------------------ algorithm registry /** * kind: 'none' (nearest level), 'diffusion' (uses KERNELS[id]), 'ordered' (threshold(params) * returns a (gx, gy) => 0..1 function), or 'script' (user scripts; see the worker). */ export const ALGORITHMS = [ { id: 'none', label: 'None (nearest color)', kind: 'none' }, ...Object.entries(KERNELS).map(([id, k]) => ({ id, label: k.label, kind: 'diffusion' })), { id: 'bayer2', label: 'Bayer 2×2', kind: 'ordered', threshold: fromRows(() => bayer(2)) }, { id: 'bayer4', label: 'Bayer 4×4', kind: 'ordered', threshold: fromRows(() => bayer(4)) }, { id: 'bayer8', label: 'Bayer 8×8', kind: 'ordered', threshold: fromRows(() => bayer(8)) }, { id: 'bayer16', label: 'Bayer 16×16', kind: 'ordered', threshold: fromRows(() => bayer(16)) }, { id: 'halftone4', label: 'Halftone dots 4×4', kind: 'ordered', threshold: fromRows(() => halftone(4)) }, { id: 'halftone8', label: 'Halftone dots 8×8', kind: 'ordered', threshold: fromRows(() => halftone(8)) }, { id: 'lines', label: 'Line screen', kind: 'ordered', threshold: fromRows(() => lineScreen(8)) }, { id: 'blue-noise', label: 'Blue noise', kind: 'ordered', threshold: () => matrixThreshold(blueNoise()) }, { id: 'ign', label: 'Interleaved gradient noise', kind: 'ordered', threshold: () => (x, y) => { const f = 52.9829189 * ((0.06711056 * x + 0.00583715 * y) % 1); return f - Math.floor(f); }, }, { id: 'random', label: 'Random (white noise)', kind: 'ordered', threshold: (p) => (x, y) => hash(x, y, p.seed) }, ]; // ------------------------------------------------------------------ user scripts let userScripts = []; /** [{ id, name, source }]; the app loads these from preferences. */ export function setUserScripts(list) { userScripts = Array.isArray(list) ? list.filter((s) => s && s.id && typeof s.source === 'string') : []; } export function getUserScripts() { return userScripts; } export function algorithmKind(id) { if (typeof id === 'string' && id.startsWith('script:')) return 'script'; return ALGORITHMS.find((a) => a.id === id)?.kind || 'none'; } export function algorithmOptions() { return [ ...ALGORITHMS.map((a) => ({ value: a.id, label: a.label })), ...userScripts.map((s) => ({ value: `script:${s.id}`, label: `Script: ${s.name || 'Untitled'}` })), ]; } // ------------------------------------------------------------------ filter params export function ditherParams() { const mono = (v) => v.mode !== 'rgb', rgb = (v) => v.mode === 'rgb'; const kind = (v) => algorithmKind(v.algorithm); return [ { key: 'mode', label: 'Color mode', type: 'select', default: 'mono', options: [{ value: 'mono', label: 'Luminance (1 channel)' }, { value: 'rgb', label: 'RGB (3 channels)' }], }, { key: 'levels', label: 'Levels', min: 2, max: 64, default: 2, when: mono }, { key: 'ink', label: 'Colors', type: 'select', default: 'bw', when: mono, options: [{ value: 'bw', label: 'Black → White' }, { value: 'fgbg', label: 'Foreground → Background' }], }, { key: 'rLevels', label: 'Red levels', min: 2, max: 64, default: 2, when: rgb }, { key: 'gLevels', label: 'Green levels', min: 2, max: 64, default: 2, when: rgb }, { key: 'bLevels', label: 'Blue levels', min: 2, max: 64, default: 2, when: rgb }, { key: 'algorithm', label: 'Algorithm', type: 'select', default: 'floyd-steinberg', options: algorithmOptions() }, { key: 'strength', label: 'Diffusion', min: 0, max: 100, default: 100, unit: '%', when: (v) => kind(v) === 'diffusion' || kind(v) === 'script' }, { key: 'serpentine', label: 'Serpentine scan', type: 'checkbox', default: true, when: (v) => kind(v) === 'diffusion' || kind(v) === 'script' }, { key: 'scale', label: 'Pattern scale', min: 1, max: 16, default: 1, unit: '×', when: (v) => kind(v) === 'ordered' || kind(v) === 'script' }, { key: 'seed', label: 'Seed', min: 0, max: 999, default: 1, when: (v) => v.algorithm === 'random' || kind(v) === 'script' }, { key: 'brightness', label: 'Brightness', min: -100, max: 100, default: 0 }, { key: 'contrast', label: 'Contrast', min: -100, max: 100, default: 0 }, { key: 'linear', label: 'Dither in linear light', type: 'checkbox', default: false, title: 'Measure error in linear light: tones match at 100% zoom, but midtones look lighter than the usual sRGB result' }, { key: 'hardAlpha', label: 'Hard-edged transparency', type: 'checkbox', default: false, title: 'Make every pixel fully opaque or fully transparent (threshold at 50%)' }, ]; } // ------------------------------------------------------------------ pipeline const levelCount = (n) => Math.max(2, Math.min(256, Math.round(Number(n) || 2))); /** * Build the working buffer for an ImageData. Returns everything `finish` and the * algorithms need. env: { fg, bg } colors ({r, g, b}). */ export function prepare(src, p, env = {}) { const { width: w, height: h, data: d } = src; const mono = p.mode !== 'rgb'; const ch = mono ? 1 : 3; const counts = mono ? [levelCount(p.levels)] : [levelCount(p.rLevels), levelCount(p.gLevels), levelCount(p.bLevels)]; const lin = !!p.linear; const space = lin ? srgbToLinear : (u) => u; // Output levels are evenly spaced sRGB bytes; in linear mode their working values are not. const bytes = counts.map((n) => Uint8ClampedArray.from({ length: n }, (_, k) => Math.round((k * 255) / (n - 1)))); const levels = bytes.map((b) => Float32Array.from(b, (v) => space(v / 255))); // Output color per level, for mono modes (rgb modes use `bytes` per channel). let colors = null; if (mono) { const n = counts[0]; const a = p.ink === 'fgbg' && env.fg ? env.fg : { r: 0, g: 0, b: 0 }; const b = p.ink === 'fgbg' && env.bg ? env.bg : { r: 255, g: 255, b: 255 }; colors = Array.from({ length: n }, (_, k) => { const t = k / (n - 1); return [Math.round(a.r + (b.r - a.r) * t), Math.round(a.g + (b.g - a.g) * t), Math.round(a.b + (b.b - a.b) * t)]; }); } // brightness / contrast (same curve as the Brightness/Contrast adjustment), then the space const con = Math.tan((((p.contrast || 0) / 100 + 1) * Math.PI) / 4), bri = (p.brightness || 0) / 200; const STEPS = 4080; // 16 per byte value const lut = new Float32Array(STEPS + 1); for (let i = 0; i <= STEPS; i++) lut[i] = space(clamp01((i / STEPS - 0.5) * con + 0.5 + bri)); const toWork = (g) => lut[Math.round(g * 16)]; const n = w * h; const buf = new Float32Array(n * ch); const alpha = new Uint8Array(n); for (let px = 0, i = 0; px < n; px++, i += 4) { let a = d[i + 3]; if (p.hardAlpha) a = a >= 128 ? 255 : 0; alpha[px] = a; if (!a) continue; if (mono) { const g = lin ? linearToSrgb(0.2126 * BYTE_TO_LINEAR[d[i]] + 0.7152 * BYTE_TO_LINEAR[d[i + 1]] + 0.0722 * BYTE_TO_LINEAR[d[i + 2]]) * 255 : 0.2126 * d[i] + 0.7152 * d[i + 1] + 0.0722 * d[i + 2]; buf[px] = toWork(g); } else { buf[px * 3] = toWork(d[i]); buf[px * 3 + 1] = toWork(d[i + 1]); buf[px * 3 + 2] = toWork(d[i + 2]); } } return { w, h, ch, buf, alpha, levels, bytes, colors }; } /** Write the (snapped) buffer back into `out` (an ImageData of the same size). */ export function finish(s, out, buf = s.buf) { const d = out.data, { ch, alpha, levels, bytes, colors } = s; const n = s.w * s.h; for (let px = 0, i = 0; px < n; px++, i += 4) { const a = alpha[px]; d[i + 3] = a; if (!a) continue; if (ch === 1) { const c = colors[nearestIndex(levels[0], buf[px])]; d[i] = c[0]; d[i + 1] = c[1]; d[i + 2] = c[2]; } else { const o = px * 3; d[i] = bytes[0][nearestIndex(levels[0], buf[o])]; d[i + 1] = bytes[1][nearestIndex(levels[1], buf[o + 1])]; d[i + 2] = bytes[2][nearestIndex(levels[2], buf[o + 2])]; } } return out; } /** Run a built-in algorithm on a prepared buffer. */ export function runBuiltin(s, p, env = {}) { const alg = ALGORITHMS.find((a) => a.id === p.algorithm) || ALGORITHMS[0]; if (alg.kind === 'diffusion') { const k = KERNELS[alg.id]; diffuse(s.buf, s.w, s.h, s.ch, s.alpha, s.levels, k.taps, { divisor: k.divisor, serpentine: p.serpentine !== false, strength: (p.strength ?? 100) / 100, }); } else if (alg.kind === 'ordered') { ordered(s.buf, s.w, s.h, s.ch, s.alpha, s.levels, alg.threshold(p), { x0: env.x || 0, y0: env.y || 0, scale: p.scale || 1 }); } // 'none': finish() snaps to the nearest level } /** * The filter entry point: ImageData → ImageData (in place). Returns a Promise when the * algorithm is a user script, which runs in a worker. */ export function applyDither(id, p, env = {}) { const s = prepare(id, p, env); if (algorithmKind(p.algorithm) !== 'script') { runBuiltin(s, p, env); return finish(s, id); } const sid = p.algorithm.slice('script:'.length); const script = userScripts.find((x) => x.id === sid); if (!script) throw new Error('That dither script no longer exists. Pick another algorithm.'); return runScript(script.source, s, p, env).then(({ data }) => finish(s, id, data)); } // ------------------------------------------------------------------ script runner (main thread) let running = null; export const SCRIPT_TIMEOUT_MS = 30000; /** * Run a user script on a prepared buffer in a module worker. Starting a new run cancels the * previous one (its promise rejects with err.superseded = true), so a slow or stuck script * never piles up behind live-preview updates. Resolves { data, ms }. */ export function runScript(source, s, p, env = {}, { timeout = SCRIPT_TIMEOUT_MS } = {}) { running?.cancel(); return new Promise((resolve, reject) => { const worker = new Worker(new URL('./dither-worker.js', import.meta.url), { type: 'module' }); let timer = 0; const job = {}; const done = () => { clearTimeout(timer); worker.terminate(); if (running === job) running = null; }; job.cancel = () => { done(); reject(Object.assign(new Error('Superseded by a newer run'), { superseded: true })); }; running = job; timer = setTimeout(() => { done(); reject(new Error(`The script was still running after ${timeout / 1000} s, so it was stopped.`)); }, timeout); worker.onmessage = (e) => { done(); const r = e.data; if (!r.ok) reject(new Error(r.error)); else if (!(r.data instanceof Float32Array) || r.data.length !== s.buf.length) reject(new Error('The script replaced img.data with an array of the wrong type or size.')); else resolve(r); }; worker.onerror = (e) => { e.preventDefault?.(); done(); reject(new Error(e.message || 'The script worker failed to start.')); }; const img = { width: s.w, height: s.h, channels: s.ch, data: s.buf, alpha: s.alpha, x0: env.x || 0, y0: env.y || 0, params: { strength: (p.strength ?? 100) / 100, serpentine: p.serpentine !== false, scale: p.scale || 1, seed: p.seed ?? 1 }, }; worker.postMessage({ source, img, levels: s.levels }); }); } // ------------------------------------------------------------------ script API (worker side) /** The `api` object a user script receives. Documented in ui/ditherscripts.js. */ export function scriptApi(img, levels) { const { width: w, height: h, channels: ch, alpha, params } = img; const rnd = mulberry32(params.seed ?? 1); return { levels: levels.map((l) => Array.from(l)), nearest: (v, c = 0) => levels[c][nearestIndex(levels[c], v)], bracket(v, c = 0) { const L = levels[c]; if (!(v > L[0])) return { lo: L[0], hi: L[0], t: 0 }; if (v >= L[L.length - 1]) return { lo: L[L.length - 1], hi: L[L.length - 1], t: 0 }; const k = lowerIndex(L, v); return { lo: L[k], hi: L[k + 1], t: (v - L[k]) / (L[k + 1] - L[k]) }; }, diffuse(kernel, opts = {}) { if (typeof kernel === 'string') { if (!KERNELS[kernel]) throw new Error(`Unknown kernel "${kernel}". Known: ${Object.keys(KERNELS).join(', ')}`); opts = { divisor: KERNELS[kernel].divisor, ...opts }; kernel = KERNELS[kernel].taps; } diffuse(img.data, w, h, ch, alpha, levels, kernel, { divisor: opts.divisor, serpentine: opts.serpentine ?? params.serpentine, strength: opts.strength ?? params.strength, }); }, ordered(pattern, opts = {}) { let fn = pattern; if (typeof pattern === 'string') { const a = ALGORITHMS.find((x) => x.id === pattern && x.kind === 'ordered'); if (!a) throw new Error(`Unknown pattern "${pattern}". Known: ${ALGORITHMS.filter((x) => x.kind === 'ordered').map((x) => x.id).join(', ')}`); fn = a.threshold({ seed: params.seed }); } else if (Array.isArray(pattern)) fn = matrixThreshold(matrixFromValues(pattern)); ordered(img.data, w, h, ch, alpha, levels, fn, { x0: img.x0, y0: img.y0, scale: opts.scale ?? params.scale }); }, bayer, random: rnd, hash, }; }