Something went wrong. Try again.
doll.systems community website
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284import { Hct, QuantizerWu, argbFromRgb } from '@material/material-color-utilities';import { converter, formatHex, interpolate, toGamut, type Oklab } from 'culori';import { clamp } from './math.ts';import { bayer8 } from './dither.mjs';
export const paletteSizes = [8, 10, 12, 14, 16] as const;export type PaletteSize = (typeof paletteSizes)[number];export const defaultPaletteSize: PaletteSize = 12;export const paletteSize = (value: number): PaletteSize => paletteSizes.find((size) => size === value) ?? defaultPaletteSize;export const paletteSlots = (size: PaletteSize) => ({ site: size / 2, image: size / 2 });
export const siteColorNames = ['accent', 'black', 'ink', 'muted', 'line'] as const;export type SiteColors = Record<(typeof siteColorNames)[number], string>;export type Pixels = { data: Uint8ClampedArray<ArrayBuffer>; width: number; height: number };export type Swatch = { hex: string; rgb: [number, number, number]; lab: Oklab };export type Palette = { site: Swatch[]; companions: Swatch[] };type Sample = Swatch & { argb: number; weight: number };type Candidate = Swatch & { population: number };export type ImageAnalysis = Candidate[];
const lab = converter('oklab');const lch = converter('oklch');const toRgb = converter('rgb');const inSrgb = toGamut('rgb', 'oklch', null, 0);const distance = (a: Oklab, b: Oklab) => (a.l - b.l) ** 2 + (a.a - b.a) ** 2 + (a.b - b.b) ** 2;const hueDistance = (a: number, b: number) => ((a - b + 540) % 360) - 180;
function swatch(color: Oklab): Swatch { const converted = toRgb(color); // Round-trip noise at the sRGB boundary must not desaturate observed colors such as pure blue. const mapped = [converted.r, converted.g, converted.b].every( (channel) => channel >= -1e-6 && channel <= 1 + 1e-6, ) ? converted : inSrgb(color); const rgb = [mapped.r, mapped.g, mapped.b].map((channel) => Math.round(clamp(channel) * 255)) as [ number, number, number, ]; const rounded = { mode: 'rgb' as const, r: rgb[0] / 255, g: rgb[1] / 255, b: rgb[2] / 255 }; return { hex: formatHex(rounded), rgb, lab: lab(rounded) };}const fromArgb = (argb: number) => swatch( lab({ mode: 'rgb', r: ((argb >> 16) & 255) / 255, g: ((argb >> 8) & 255) / 255, b: (argb & 255) / 255, }), );
function mean(samples: Sample[]): Oklab { const sum = samples.reduce( (sum, { lab, weight }) => ({ l: sum.l + lab.l * weight, a: sum.a + lab.a * weight, b: sum.b + lab.b * weight, weight: sum.weight + weight, }), { l: 0, a: 0, b: 0, weight: 0 }, ); const weight = sum.weight || 1; return { mode: 'oklab', l: sum.l / weight, a: sum.a / weight, b: sum.b / weight };}
/** Sample original colors rather than blurred thumbnails; transparency contributes by coverage. */export function analyzeImage(image: Pixels): ImageAnalysis { const histogram = new Map<number, Sample>(); const pixels: number[] = []; const count = Math.min(16384, image.width * image.height); const stride = (image.width * image.height) / count; let coverage = 0; for (let index = 0; index < count; index++) { const pixel = Math.floor((index + ((index * 0.61803398875) % 1)) * stride); const offset = pixel * 4; if (image.data[offset + 3] < 24) continue; const argb = argbFromRgb(image.data[offset], image.data[offset + 1], image.data[offset + 2]); const weight = image.data[offset + 3] / 255; const existing = histogram.get(argb); if (existing) existing.weight += weight; else histogram.set(argb, { ...fromArgb(argb), argb, weight }); coverage += weight; if (coverage >= 1) { pixels.push(argb); coverage--; } } const samples = [...histogram.values()].sort((a, b) => a.lab.l - b.lab.l || a.argb - b.argb); if (!pixels.length && samples.length) pixels.push(samples[0].argb); return candidates(samples, pixels);}
function partition(samples: Sample[], centers: Oklab[]): Sample[][] { const groups: Sample[][] = centers.map(() => []); for (const sample of samples) { let closest = 0; for (let index = 1; index < centers.length; index++) if (distance(sample.lab, centers[index]) < distance(sample.lab, centers[closest])) closest = index; groups[closest].push(sample); } return groups;}
/** Quantizers find regions; medoids retain observed colors instead of muddy cluster averages. */function candidates(samples: Sample[], pixels: number[]): Candidate[] { if (!samples.length) return []; let centers = new QuantizerWu().quantize(pixels, 64).map((argb) => fromArgb(argb).lab); for (let iteration = 0; iteration < 8; iteration++) { const next = partition(samples, centers).map((group, index) => group.length ? mean(group) : centers[index], ); const change = next.reduce((sum, center, index) => sum + distance(center, centers[index]), 0); centers = next; if (change < 1e-7) break; } const result = partition(samples, centers) .filter((group) => group.length) .map((group) => { const center = mean(group); const representative = group.reduce((best, sample) => distance(sample.lab, center) < distance(best.lab, center) ? sample : best, ); return { hex: representative.hex, rgb: representative.rgb, lab: representative.lab, population: group.reduce((sum, sample) => sum + sample.weight, 0), }; }); return result;}
function representativeColors(pool: Candidate[], site: Swatch[], count: number): Candidate[] { const selected: Candidate[] = []; const remaining = [...pool]; const largest = Math.max(...pool.map(({ population }) => population), 1); const total = pool.reduce((sum, color) => sum + color.population, 0); const score = (color: Candidate) => { const population = (color.population / largest) ** 0.25; const chroma = clamp(lch(color.lab).c / 0.24); const novelty = Math.sqrt(Math.min(...site.map((pin) => distance(color.lab, pin.lab)))); const separation = selected.length ? Math.sqrt(Math.min(...selected.map((chosen) => distance(color.lab, chosen.lab)))) : 0.14; const confidence = Math.min(1, color.population / Math.max(2, total * 0.001)); return ( population * (1 + 2.5 * chroma) * confidence * (0.2 + 0.8 * clamp(novelty / 0.1)) * clamp(separation / 0.14) ** 2 ); }; while (selected.length < count && remaining.length) { const best = remaining.reduce((best, color) => (score(color) > score(best) ? color : best)); selected.push(best); remaining.splice(remaining.indexOf(best), 1); } return selected;}
/** Harmony is a bounded hue adjustment, never a replacement of the source color's identity. */function harmonize(color: Swatch, accentHue: number): Swatch { if (lch(color.lab).c > 0.01) { const source = Hct.fromInt(argbFromRgb(...color.rgb)); let rotation = clamp(hueDistance((accentHue + 180) % 360, source.hue), -15, 15); const sourceChroma = lch(color.lab).c; // At the gamut edge, prioritize vividness over rotating a bright color into a pastel. for (let attempt = 0; attempt < 9; attempt++) { const candidate = fromArgb( Hct.from(source.hue + rotation, source.chroma, source.tone).toInt(), ); if (lch(candidate.lab).c >= sourceChroma * 0.97) return candidate; rotation /= 2; } } return { hex: color.hex, rgb: color.rgb, lab: color.lab };}
/** At eight colors, keep four core anchors; larger budgets also pin the site's border shade. */function siteHalf(site: SiteColors, count: number): Swatch[] { const read = (value: string) => { const color = lab(value); if (!color) throw new Error('Invalid site color: ' + value); return swatch(color); }; const pins = [site.black, site.ink, site.accent, site.muted, site.line].map(read); const neutrals = count === 4 ? [pins[0], pins[3], pins[1]] : [pins[0], pins[4], pins[3], pins[1]]; while (neutrals.length < count - 1) { neutrals.sort((a, b) => a.lab.l - b.lab.l); let gap = 0; for (let index = 1; index < neutrals.length - 1; index++) if ( neutrals[index + 1].lab.l - neutrals[index].lab.l > neutrals[gap + 1].lab.l - neutrals[gap].lab.l ) gap = index; const middle = interpolate([neutrals[gap].lab, neutrals[gap + 1].lab], 'oklab'); neutrals.push(swatch(lab(middle(0.5)))); } return [...neutrals, pins[2]].sort((a, b) => a.lab.l - b.lab.l);}
/** Give the image half to distinct, representative colors with bounded complementary harmony. */export function derivePalette( analysis: ImageAnalysis, size: PaletteSize, site: SiteColors,): Palette { const slots = paletteSlots(size); const pinned = siteHalf(site, slots.site); const accentHue = Hct.fromInt(argbFromRgb(...swatch(lab(site.accent)!).rgb)).hue; const companions = representativeColors(analysis, pinned, slots.image) .map((color) => harmonize(color, accentHue)) .sort((a, b) => a.lab.l - b.lab.l); return { site: pinned, companions };}
/** Mix nearby palette colors when this improves the perceived color enough to justify the texture. */function ditherMix(source: Oklab, colors: Swatch[]) { const closest = colors.reduce((best, color) => distance(source, color.lab) < distance(source, best.lab) ? color : best, ); // Dither the source tone along the selected hue, so texture cannot undo its harmony. const tone = source.l - closest.lab.l; let partner = closest, amount = 0, error = tone * tone; for (const color of colors) { const dl = color.lab.l - closest.lab.l, da = color.lab.a - closest.lab.a, db = color.lab.b - closest.lab.b; const span = dl * dl + da * da + db * db; if (!span) continue; const mix = clamp((tone * dl) / span); // Penalize noisy pairs of distant colors, preserving vivid hues and exact palette matches. const cost = (tone - mix * dl) ** 2 + (mix * da) ** 2 + (mix * db) ** 2 + 0.1 * span * mix * (1 - mix); if (cost < error) { partner = color; amount = mix; error = cost; } } return { closest, partner, amount };}
/** Apply the art's ordered 8×8 pattern using only palette colors, retaining source alpha. */export function applyPalette(image: Pixels, palette: Palette): Pixels { const output = new Uint8ClampedArray(image.data.length); const colors = [...palette.site, ...palette.companions]; const mixes = new Map<number, ReturnType<typeof ditherMix>>(); for (let pixel = 0; pixel < image.width * image.height; pixel++) { const offset = pixel * 4; output[offset + 3] = image.data[offset + 3]; if (!image.data[offset + 3]) continue; const key = (image.data[offset] << 16) | (image.data[offset + 1] << 8) | image.data[offset + 2]; let mix = mixes.get(key); if (!mix) { mix = ditherMix( lab({ mode: 'rgb', r: image.data[offset] / 255, g: image.data[offset + 1] / 255, b: image.data[offset + 2] / 255, }), colors, ); // Bound worker memory even for full-resolution photographs with millions of unique colors. if (mixes.size === 32768) mixes.clear(); mixes.set(key, mix); } const x = pixel % image.width, y = Math.floor(pixel / image.width); const color = bayer8(x, y) < mix.amount ? mix.partner : mix.closest; output.set(color.rgb, offset); } return { data: output, width: image.width, height: image.height };}