Ugly Sweater Forge: procedural knitted Christmas sweater generator (Day 2)

This commit is contained in:
hermes committed 2026-12-02 13:19:42 +00:00
1 parent cd563cdfc2
commit bed6eb3b03
11 files changed
+1024 -60

No files matched your search

+1 -2
View File
@@ -1,3 +1,2 @@
# The address of the published site, for the og: tags. No secrets here: this file is committed.
# The publish workflow sets the real one; this is for `pnpm dev`.
VITE_SITE_URL=http://localhost:5173
VITE_SITE_URL=https://pages.obahan.xyz/lullu/advent-of-slop-02-ugly-sweater
-51
View File
@@ -1,51 +0,0 @@
name: Publish
# Builds the site and publishes it on GitHub Pages after every push to main.
# Needs, once: Settings > Pages > Source: "GitHub Actions".
on:
push:
branches: [main]
workflow_dispatch:
concurrency:
group: pages
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
pages: read # configure-pages looks up the site's address
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version-file: .nvmrc
cache: pnpm
- id: pages
uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6.0.0
- run: pnpm install --frozen-lockfile
- run: pnpm build
env:
# The address of the published site, for the og: tags.
VITE_SITE_URL: ${{ steps.pages.outputs.base_url }}
- uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
with:
path: dist
deploy:
needs: build
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- id: deployment
uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 285 KiB

+5 -5
View File
@@ -3,11 +3,11 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>My Advent of AI Slop entry</title>
<meta name="description" content="Made for Advent of AI Slop, December 2026." />
<title>Ugly Sweater Forge — Advent of AI Slop Day 2</title>
<meta name="description" content="Procedurally knitted crimes against fashion. An ugly Christmas sweater generator with an embarrassment meter, made for Advent of AI Slop Day 2." />
<meta property="og:type" content="website" />
<meta property="og:title" content="My Advent of AI Slop entry" />
<meta property="og:description" content="Made for Advent of AI Slop, December 2026." />
<meta property="og:title" content="Ugly Sweater Forge — Advent of AI Slop Day 2" />
<meta property="og:description" content="Procedurally knitted crimes against fashion. An ugly Christmas sweater generator with an embarrassment meter." />
<meta property="og:url" content="%VITE_SITE_URL%/" />
<meta property="og:image" content="%VITE_SITE_URL%/preview.png" />
<meta name="twitter:card" content="summary_large_image" />
@@ -16,7 +16,7 @@
</head>
<body>
<!-- day: the day of December this was made for, 1 to 24. name: the title of that day. -->
<advent-badge day="1" name="Living fishtank"></advent-badge>
<advent-badge day="2" name="Ugly sweater"></advent-badge>
<main id="app"></main>
</body>
</html>
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 289 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 289 KiB

+153 -2
View File
@@ -1,4 +1,155 @@
// The page starts here. This line only shows that it is published.
// Ugly Sweater Forge — page wiring: controls, persistence, download.
import './style.css';
import { PALETTES } from './palettes';
import { generate, render, type SweaterConfig } from './sweater';
const app = document.querySelector<HTMLElement>('#app');
if (app === null) throw new Error('Missing #app in index.html');
app.textContent = 'Nothing here yet.';
const STORE_KEY = 'aos02-ugly-sweater';
function loadConfig(): SweaterConfig {
try {
const raw = localStorage.getItem(STORE_KEY);
if (raw !== null) {
const p = JSON.parse(raw) as Partial<SweaterConfig>;
if (typeof p.seed === 'number' && typeof p.paletteId === 'number' && typeof p.ugliness === 'number') {
return { seed: p.seed, paletteId: p.paletteId, ugliness: p.ugliness };
}
}
} catch {
// fall through to a fresh sweater
}
return { seed: Math.floor(Math.random() * 1_000_000), paletteId: -1, ugliness: 65 };
}
function saveConfig(cfg: SweaterConfig): void {
localStorage.setItem(STORE_KEY, JSON.stringify(cfg));
}
const config = loadConfig();
app.innerHTML = `
<div class="wrap">
<header>
<h1>🧶 Ugly Sweater Forge</h1>
<p class="sub">Procedurally knitted crimes against fashion. Every stitch is deterministic — share the seed.</p>
</header>
<div class="layout">
<div class="stage">
<canvas id="sweater" aria-label="Generated ugly Christmas sweater"></canvas>
</div>
<aside class="panel">
<div class="name-card">
<div class="sweater-name" id="name"></div>
<div class="meter-row">
<span class="meter-label">Embarrassment</span>
<div class="meter"><div class="meter-fill" id="meter"></div></div>
<span class="meter-score" id="score"></span>
</div>
<div class="meter-verdict" id="verdict"></div>
<div class="palette-line" id="palette-line"></div>
</div>
<div class="controls">
<button id="knit" class="big">🧶 Knit a new sweater</button>
<label class="ctl">
<span>Ugliness <b id="ugl-val"></b></span>
<input type="range" id="ugliness" min="0" max="100" step="1">
</label>
<label class="ctl">
<span>Yarn palette</span>
<select id="palette"></select>
</label>
<label class="ctl">
<span>Seed</span>
<div class="seed-row">
<input type="number" id="seed" min="0" max="999999" step="1">
<button id="copy-seed" title="Copy seed">📋</button>
</div>
</label>
<button id="download">⬇️ Save as PNG</button>
</div>
<p class="hint">Low ugliness knits tasteful Nordic patterns. Push it up until HR gets involved.</p>
</aside>
</div>
</div>
`;
const canvas = document.querySelector<HTMLCanvasElement>('#sweater')!;
const nameEl = document.querySelector<HTMLElement>('#name')!;
const meterEl = document.querySelector<HTMLElement>('#meter')!;
const scoreEl = document.querySelector<HTMLElement>('#score')!;
const verdictEl = document.querySelector<HTMLElement>('#verdict')!;
const paletteLineEl = document.querySelector<HTMLElement>('#palette-line')!;
const uglEl = document.querySelector<HTMLInputElement>('#ugliness')!;
const uglValEl = document.querySelector<HTMLElement>('#ugl-val')!;
const paletteEl = document.querySelector<HTMLSelectElement>('#palette')!;
const seedEl = document.querySelector<HTMLInputElement>('#seed')!;
paletteEl.innerHTML =
'<option value="-1">🎲 Surprise me</option>' +
PALETTES.map((p, i) => `<option value="${i}">${p.name}</option>`).join('');
function redraw(): void {
const sweater = generate(config);
render(canvas, sweater);
nameEl.textContent = `“${sweater.name}”`;
meterEl.style.width = sweater.embarrassment + '%';
meterEl.style.background = 'linear-gradient(90deg, #4caf50, #ffc107 55%, #f44336)';
scoreEl.textContent = String(sweater.embarrassment);
verdictEl.textContent = sweater.label;
paletteLineEl.textContent = `Yarn: ${sweater.palette.name}`;
uglValEl.textContent = config.ugliness >= 85 ? '☠️' : String(config.ugliness);
saveConfig(config);
}
function syncControls(): void {
uglEl.value = String(config.ugliness);
paletteEl.value = String(config.paletteId);
seedEl.value = String(config.seed);
}
document.querySelector('#knit')!.addEventListener('click', () => {
config.seed = Math.floor(Math.random() * 1_000_000);
syncControls();
redraw();
});
uglEl.addEventListener('input', () => {
config.ugliness = Number(uglEl.value);
redraw();
});
paletteEl.addEventListener('change', () => {
config.paletteId = Number(paletteEl.value);
redraw();
});
seedEl.addEventListener('change', () => {
const v = Math.floor(Number(seedEl.value));
config.seed = Number.isFinite(v) ? Math.max(0, Math.min(999999, v)) : 0;
seedEl.value = String(config.seed);
redraw();
});
document.querySelector('#copy-seed')!.addEventListener('click', (ev) => {
void navigator.clipboard.writeText(String(config.seed));
const btn = ev.currentTarget as HTMLButtonElement;
btn.textContent = '✓';
setTimeout(() => (btn.textContent = '📋'), 900);
});
document.querySelector('#download')!.addEventListener('click', () => {
canvas.toBlob((blob) => {
if (blob === null) return;
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = `ugly-sweater-${config.seed}.png`;
a.click();
URL.revokeObjectURL(a.href);
}, 'image/png');
});
syncControls();
redraw();
+161
View File
@@ -0,0 +1,161 @@
// Cross-stitch pixel motifs for the sweater bands. '#' = motif color, '.' = transparent.
export interface Motif {
name: string;
w: number;
h: number;
rows: string[];
tame: boolean; // fits a low-ugliness sweater
}
const m = (name: string, rows: string[], tame = false): Motif => ({
name,
w: rows[0]!.length,
h: rows.length,
rows,
tame,
});
// '#' = primary motif color, 'o' = secondary color (face/fill), '.' = transparent.
export const MOTIFS: Motif[] = [
m('tree', [
'...##...',
'..####..',
'..####..',
'.######.',
'.######.',
'########',
'...oo...',
'...oo...',
], true),
m('snowflake', [
'#..##..#',
'.#.##.#.',
'..####..',
'########',
'########',
'..####..',
'.#.##.#.',
'#..##..#',
], true),
m('star', [
'...##...',
'..####..',
'########',
'########',
'.######.',
'..####..',
'.#.##.#.',
'#..##..#',
], true),
m('snowman', [
'...##...',
'..####..',
'.######.',
'..oooo..',
'.o#oo#o.',
'..oooo..',
'.oooooo.',
'oooooooo',
], true),
m('santa', [
'.....##.',
'....###.',
'..####..',
'########',
'.oooooo.',
'.o#oo#o.',
'.oooooo.',
'..oooo..',
]),
m('reindeer', [
'#......#',
'.#....#.',
'..####..',
'.oooooo.',
'.o#oo#o.',
'.oooooo.',
'..o##o..',
'...oo...',
]),
m('candycane', [
'..####..',
'.#....#.',
'#......#',
'#......#',
'...#....',
'...#....',
'...#....',
'...#....',
]),
m('present', [
'..o..o..',
'.oooooo.',
'oo####oo',
'oo####oo',
'oo####oo',
'oo####oo',
'oo####oo',
'oo####oo',
]),
m('gingerbread', [
'..####..',
'..####..',
'########',
'.######.',
'..####..',
'..#..#..',
'.#....#.',
'#......#',
]),
m('bell', [
'...##...',
'...##...',
'..####..',
'.######.',
'.######.',
'########',
'########',
'...oo...',
]),
m('heart', [
'.#....#.',
'########',
'########',
'########',
'.######.',
'..####..',
'...##...',
'........',
]),
m('mitten', [
'..####..',
'.######.',
'#######.',
'######..',
'######..',
'.######.',
'.######.',
'........',
]),
m('stocking', [
'..####..',
'..####..',
'..####..',
'..####..',
'..#####.',
'.#######',
'########',
'#####...',
]),
];
// Small 6x6 snowflake for the sleeves.
export const SLEEVE_MOTIF: Motif = m('flake6', [
'#.##.#',
'.####.',
'######',
'######',
'.####.',
'#.##.#',
]);
+109
View File
@@ -0,0 +1,109 @@
// Yarn palettes. clash = how embarrassing the palette is by itself (0..100).
export interface Palette {
name: string;
clash: number;
body: string; // main sweater color
colors: string[]; // motif / band colors
}
export const PALETTES: Palette[] = [
{
name: 'Sleigh Crash',
clash: 70,
body: '#b3121f',
colors: ['#1e7d32', '#f4c430', '#ffffff', '#ff5fa2'],
},
{
name: 'Eggnog Nightmare',
clash: 85,
body: '#f3e3b8',
colors: ['#39d353', '#ff2f92', '#ff7b00', '#26c6da'],
},
{
name: 'Radioactive Pine',
clash: 92,
body: '#2fbf3f',
colors: ['#7b2ff7', '#ff1744', '#ffe600', '#00e5ff'],
},
{
name: 'Tinsel Overload',
clash: 65,
body: '#1c1c1c',
colors: ['#ffd700', '#e91e63', '#00bcd4', '#ff5252'],
},
{
name: 'Grinch Sick',
clash: 75,
body: '#43a047',
colors: ['#f06292', '#ba68c8', '#ffee58', '#4fc3f7'],
},
{
name: 'Candy Cane Vomit',
clash: 80,
body: '#ff8fa3',
colors: ['#d90429', '#ffffff', '#80ed99', '#ffd60a'],
},
{
name: 'Nordic Normie',
clash: 28,
body: '#274b7a',
colors: ['#e8e8e8', '#c0392b', '#f1c40f', '#7fb3d5'],
},
{
name: 'Reindeer Roadkill',
clash: 88,
body: '#6d4c41',
colors: ['#ffeb3b', '#e53935', '#4caf50', '#ff9800'],
},
];
const PREFIX = [
'The ',
"Aunt Helga's ",
"Grandpa Ole's ",
"Cousin Kim's ",
'The Office Party ',
'Christmas 1987 ',
"Mom's ",
];
const ADJ = [
'Eggnog-Soaked ',
'Tinsel-Loaded ',
'Radioactive ',
'Cursed ',
'Maximum ',
'Aggressively Festive ',
'Glitter-Bombed ',
'Sleigh-Chasing ',
'Mulled-Wine ',
'Ginger-Infused ',
];
const NOUN = [
'Disaster',
'Nightmare',
'Menace',
'Warcrime',
'Masterpiece',
'Catastrophe',
'Legend',
'Special',
'Tragedy',
'Showstopper',
];
export const pick = <T>(rng: () => number, arr: readonly T[]): T =>
arr[Math.floor(rng() * arr.length)]!;
export function sweaterName(rng: () => number): string {
return pick(rng, PREFIX) + pick(rng, ADJ) + pick(rng, NOUN);
}
export function embarrassmentLabel(score: number): string {
if (score < 20) return 'Potentially office-safe';
if (score < 40) return 'Mildly festive';
if (score < 60) return 'Aunt-approved';
if (score < 80) return 'Family intervention needed';
if (score < 95) return 'Documented war crime';
return 'Nuclear';
}
+231
View File
@@ -0,0 +1,231 @@
:root {
color-scheme: dark;
--bg: #14181f;
--card: #1d232e;
--line: #2c3542;
--text: #e8e2d5;
--dim: #9aa4b2;
--accent: #e0b64f;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
background:
radial-gradient(1200px 600px at 70% -10%, #1f2a3a 0%, transparent 60%),
var(--bg);
color: var(--text);
font: 15px/1.5 system-ui, -apple-system, 'Segoe UI', sans-serif;
}
.wrap {
max-width: 1150px;
margin: 0 auto;
padding: 0.9rem 1.25rem 1rem;
}
header h1 {
margin: 0;
font-size: 1.55rem;
letter-spacing: 0.01em;
}
header .sub {
margin: 0.15rem 0 0;
color: var(--dim);
font-size: 0.9rem;
}
.layout {
display: flex;
gap: 1.25rem;
margin-top: 0.8rem;
align-items: flex-start;
}
.stage {
flex: 1 1 auto;
background:
radial-gradient(420px 320px at 50% 42%, rgba(224, 182, 79, 0.09), transparent 70%),
var(--card);
border: 1px solid var(--line);
border-radius: 14px;
display: flex;
align-items: center;
justify-content: center;
padding: 0.75rem;
min-height: 480px;
}
canvas {
max-width: 100%;
max-height: 70vh;
height: auto;
filter: drop-shadow(0 10px 24px rgba(0, 0, 0, 0.45));
}
.panel {
flex: 0 0 320px;
display: flex;
flex-direction: column;
gap: 0.7rem;
}
.name-card {
background: var(--card);
border: 1px solid var(--line);
border-radius: 14px;
padding: 0.75rem 0.9rem;
}
.sweater-name {
font-size: 1.15rem;
font-weight: 700;
color: var(--accent);
min-height: 1.4em;
}
.meter-row {
display: flex;
align-items: center;
gap: 0.5rem;
margin-top: 0.45rem;
}
.meter-label {
font-size: 0.72rem;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--dim);
white-space: nowrap;
}
.meter {
flex: 1;
height: 10px;
background: #0e1218;
border-radius: 6px;
overflow: hidden;
}
.meter-fill {
height: 100%;
width: 0;
border-radius: 6px;
transition: width 0.35s ease;
}
.meter-score {
font-variant-numeric: tabular-nums;
font-weight: 700;
min-width: 2.2em;
text-align: right;
}
.meter-verdict {
margin-top: 0.3rem;
font-size: 0.85rem;
color: var(--dim);
font-style: italic;
}
.palette-line {
margin-top: 0.45rem;
font-size: 0.8rem;
color: var(--dim);
}
.controls {
background: var(--card);
border: 1px solid var(--line);
border-radius: 14px;
padding: 0.75rem 0.9rem;
display: flex;
flex-direction: column;
gap: 0.55rem;
}
button {
font: inherit;
font-weight: 600;
color: #1a1408;
background: linear-gradient(180deg, #f0c964, #d9a83e);
border: 0;
border-radius: 9px;
padding: 0.45rem 0.9rem;
cursor: pointer;
}
button:hover {
filter: brightness(1.08);
}
button.big {
font-size: 1rem;
padding: 0.6rem 0.9rem;
}
button:not(.big) {
background: #2c3542;
color: var(--text);
}
.ctl {
display: flex;
flex-direction: column;
gap: 0.25rem;
font-size: 0.82rem;
color: var(--dim);
}
.ctl b {
color: var(--text);
}
input[type='range'] {
accent-color: var(--accent);
}
select,
input[type='number'] {
font: inherit;
background: #0e1218;
color: var(--text);
border: 1px solid var(--line);
border-radius: 8px;
padding: 0.35rem 0.55rem;
}
.seed-row {
display: flex;
gap: 0.4rem;
}
.seed-row input {
flex: 1;
min-width: 0;
}
.seed-row button {
padding: 0.4rem 0.6rem;
}
.hint {
margin: 0;
font-size: 0.75rem;
color: var(--dim);
}
@media (max-width: 860px) {
.layout {
flex-direction: column;
}
.panel {
flex: 1 1 auto;
width: 100%;
}
}
+364
View File
@@ -0,0 +1,364 @@
// Procedural ugly-sweater generation and canvas rendering.
// The sweater is a grid of "stitches"; bands of cross-stitch motifs are knitted
// onto a flat-lay silhouette. Everything is deterministic from the seed.
import { MOTIFS, SLEEVE_MOTIF, type Motif } from './motifs';
import { PALETTES, type Palette, embarrassmentLabel, pick, sweaterName } from './palettes';
export const GRID_W = 52;
export const GRID_H = 46;
const CELL = 12;
export interface SweaterConfig {
seed: number;
paletteId: number; // -1 = surprise me (derived from seed)
ugliness: number; // 0..100
}
export interface Sweater {
config: SweaterConfig;
palette: Palette;
name: string;
embarrassment: number;
label: string;
cells: (string | null)[][]; // [row][col] stitch color, null = not sweater
}
// ---- seeded rng ----
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
a |= 0;
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;
};
}
// deterministic per-cell noise for stitch shading
function hash2(seed: number, x: number, y: number): number {
let h = seed ^ Math.imul(x, 0x9e3779b1) ^ Math.imul(y, 0x85ebca6b);
h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
h ^= h >>> 16;
return (h >>> 0) / 4294967296;
}
// ---- color helpers ----
const hexToRgb = (hex: string): [number, number, number] => [
parseInt(hex.slice(1, 3), 16),
parseInt(hex.slice(3, 5), 16),
parseInt(hex.slice(5, 7), 16),
];
const rgbToHex = (r: number, g: number, b: number): string =>
'#' +
[r, g, b]
.map((v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0'))
.join('');
const shade = (hex: string, f: number): string => {
const [r, g, b] = hexToRgb(hex);
return rgbToHex(r * f, g * f, b * f);
};
// ---- silhouette ----
// Regions: 0 = empty, 1 = body, 2 = sleeve, 3 = rib (collar/cuffs/hem)
function regionOf(r: number, c: number): number {
// body rows 4..43, cols 14..37
if (r >= 4 && r <= 43 && c >= 14 && c <= 37) {
// neck hole: symmetric rounded scoop
if ((r === 4 || r === 7) && c >= 23 && c <= 28) return 0;
if ((r === 5 || r === 6) && c >= 22 && c <= 29) return 0;
if (r <= 8) return 3; // collar rib
if (r >= 41) return 3; // hem rib
return 1;
}
// sleeves rows 4..22, diagonal outer edge
if (r >= 4 && r <= 22) {
const out = Math.max(0, 12 - (r - 4)); // left sleeve outer col
if (c >= out && c <= 13) return r >= 21 ? 3 : 2;
const outR = Math.min(GRID_W - 1, 39 + (r - 4)); // right sleeve outer col
if (c >= 38 && c <= outR) return r >= 21 ? 3 : 2;
}
return 0;
}
// ---- band patterns ----
type BandFn = (
put: (r: number, c: number, color: string) => void,
r0: number,
r1: number,
c0: number,
c1: number,
cols: string[],
rng: () => number,
) => void;
const zigzag: BandFn = (put, r0, r1, c0, c1, cols) => {
const h = r1 - r0 + 1;
const amp = Math.max(1, Math.floor((h - 1) / 2));
const mid = r0 + amp;
const period = 2 * amp * 2;
for (let c = c0; c <= c1; c++) {
const t = (c - c0) % period;
const dy = t < period / 2 ? t : period - t; // triangle 0..amp
put(mid - amp + dy, c, cols[0]!);
if (mid - amp + dy + 1 <= r1) put(mid - amp + dy + 1, c, cols[1]!);
}
};
const dots: BandFn = (put, r0, r1, c0, c1, cols) => {
const mid = Math.floor((r0 + r1) / 2);
for (let c = c0; c <= c1; c++) {
if ((c - c0) % 2 === 0) put(mid, c, cols[0]!);
else if (r0 !== mid) put(r0, c, cols[1]!);
}
};
const diamonds: BandFn = (put, r0, r1, c0, c1, cols) => {
const mid = Math.floor((r0 + r1) / 2);
for (let c = c0; c <= c1; c++) {
for (let r = r0; r <= r1; r++) {
const d = Math.abs(((c - c0) % 6) - 3) + Math.abs(r - mid);
if (d <= 1) put(r, c, cols[0]!);
else if (d === 2) put(r, c, cols[1]!);
}
}
};
const stripes: BandFn = (put, r0, r1, c0, c1, cols) => {
for (let r = r0; r <= r1; r++) {
const col = (r - r0) % 2 === 0 ? cols[0]! : cols[1]!;
for (let c = c0; c <= c1; c++) if ((c + r) % 2 === 0) put(r, c, col);
}
};
const crosses: BandFn = (put, r0, r1, c0, c1, cols) => {
const mid = Math.floor((r0 + r1) / 2);
for (let c = c0; c <= c1; c++) {
if ((c - c0) % 4 === 0) {
put(mid, c, cols[0]!);
if (mid - 1 >= r0) put(mid - 1, c, cols[0]!);
if (mid + 1 <= r1) put(mid + 1, c, cols[0]!);
put(mid, Math.min(c1, c + 1), cols[0]!);
if (c > c0) put(mid, c - 1, cols[0]!);
} else if ((c - c0) % 4 === 2) {
put(r0, c, cols[1]!);
if (r1 !== r0) put(r1, c, cols[1]!);
}
}
};
const BANDS: BandFn[] = [zigzag, dots, diamonds, stripes, crosses];
// ---- generation ----
function resolvePalette(cfg: SweaterConfig): Palette {
if (cfg.paletteId >= 0 && cfg.paletteId < PALETTES.length) return PALETTES[cfg.paletteId]!;
return PALETTES[Math.abs(cfg.seed) % PALETTES.length]!;
}
export function generate(cfg: SweaterConfig): Sweater {
const rng = mulberry32(cfg.seed);
const palette = resolvePalette(cfg);
const u = cfg.ugliness / 100;
const cells: (string | null)[][] = [];
const regions: number[][] = [];
for (let r = 0; r < GRID_H; r++) {
cells.push(new Array<string | null>(GRID_W).fill(null));
regions.push(new Array<number>(GRID_W).fill(0));
for (let c = 0; c < GRID_W; c++) regions[r]![c] = regionOf(r, c);
}
const put = (r: number, c: number, color: string): void => {
if (r < 0 || r >= GRID_H || c < 0 || c >= GRID_W) return;
const reg = regions[r]![c];
// patterns paint over the base fill but never over ribbing or empty space
if (reg === 1 || reg === 2) cells[r]![c] = color;
};
const ribLight = shade(palette.body, 1.25);
const ribDark = shade(palette.body, 0.72);
const bodyDark = shade(palette.body, 0.88);
// base fill
for (let r = 0; r < GRID_H; r++)
for (let c = 0; c < GRID_W; c++)
if (regions[r]![c] === 1 || regions[r]![c] === 2) cells[r]![c] = palette.body;
// ribbing: vertical ribs on cuffs/hem, horizontal rows around the collar
for (let r = 0; r < GRID_H; r++)
for (let c = 0; c < GRID_W; c++)
if (regions[r]![c] === 3)
cells[r]![c] = r <= 8 ? (r % 2 === 0 ? ribLight : ribDark) : c % 2 === 0 ? ribLight : ribDark;
// how many colors are in play scales with ugliness
const colorCount = 2 + Math.round(u * 2); // 2..4
const colors = palette.colors.slice(0, colorCount);
const pool = MOTIFS.filter((mo) => (u < 0.35 ? mo.tame : true));
const usedColors = new Set<string>();
const band = (
fn: BandFn,
r0: number,
r1: number,
c0: number,
c1: number,
cols: string[],
): void => {
fn(put, r0, r1, c0, c1, cols, rng);
for (const col of cols) usedColors.add(col);
};
const motifBand = (
motif: Motif,
r0: number,
r1: number,
c0: number,
c1: number,
motifColor: string,
secColor: string,
altBg: string | null,
forcedRepeats?: number,
): void => {
const width = c1 - c0 + 1;
// +2 gap so motifs never merge into a solid panel
const repeats = forcedRepeats ?? Math.max(1, Math.round(width / (motif.w + 2)));
const step = width / repeats;
for (let k = 0; k < repeats; k++) {
const cx = Math.round(c0 + k * step + (step - motif.w) / 2);
if (altBg !== null) {
for (let r = r0; r <= r1; r++)
for (let c = cx - 1; c <= cx + motif.w; c++)
if (regions[r]![c] === 1 || regions[r]![c] === 2) cells[r]![c] = altBg;
}
for (let dy = 0; dy < motif.h; dy++)
for (let dx = 0; dx < motif.w; dx++) {
const ch = motif.rows[dy]![dx];
if (ch === '#') put(r0 + dy, cx + dx, motifColor);
else if (ch === 'o') put(r0 + dy, cx + dx, secColor);
}
}
usedColors.add(motifColor);
if (altBg !== null) usedColors.add(altBg);
};
// pick band content
const shuffled = [...pool].sort(() => rng() - 0.5);
const motifA = shuffled[0]!;
const motifB = shuffled[1 % shuffled.length]!;
const motifC = u > 0.5 ? shuffled[2 % shuffled.length]! : motifA;
const band1 = BANDS[Math.floor(rng() * BANDS.length)]!;
const band2 = BANDS[Math.floor(rng() * BANDS.length)]!;
const yokeBand = u > 0.4 ? band1 : zigzag;
const cA = colors[0]!;
const cB = colors[1 % colors.length]!;
const cC = colors[2 % colors.length]!;
const cD = colors[3 % colors.length]!;
const altBg = u > 0.45 ? colors[Math.floor(rng() * colors.length)]! : null;
// body layout: yoke 9..11, A 12..19, band1 20..22, B 23..30, band2 31..32, C 33..40
yokeBand(put, 9, 11, 14, 37, [cB, bodyDark], rng);
motifBand(motifA, 12, 19, 14, 37, cA, cB, altBg);
band(band1, 20, 22, 14, 37, [cC, cD]);
motifBand(motifB, 23, 30, 14, 37, cB, cC, altBg);
band(dots, 31, 32, 14, 37, [cD, cA]);
motifBand(motifC, 33, 40, 14, 37, cC, cD, altBg);
// sleeves: zigzag 9..11, flake band 12..17, dots 18..20
for (const [c0, c1] of [
[0, 13],
[38, GRID_W - 1],
] as const) {
zigzag(put, 9, 11, c0, c1, [cC, bodyDark], rng);
motifBand(SLEEVE_MOTIF, 12, 17, c0, c1, cA, cB, null, 1);
dots(put, 18, 20, c0, c1, [cD, bodyDark], rng);
}
// name + embarrassment score
const name = sweaterName(rng);
const distinct = usedColors.size;
const score = Math.max(
4,
Math.min(
100,
Math.round(
palette.clash * (0.55 + 0.45 * u) +
distinct * 3 +
(altBg !== null ? 6 : 0) +
rng() * 8,
),
),
);
return {
config: cfg,
palette,
name,
embarrassment: score,
label: embarrassmentLabel(score),
cells,
};
}
// ---- rendering ----
export function render(canvas: HTMLCanvasElement, sweater: Sweater): void {
const dpr = Math.min(2, window.devicePixelRatio || 1);
canvas.width = GRID_W * CELL * dpr;
canvas.height = GRID_H * CELL * dpr;
const ctx = canvas.getContext('2d')!;
ctx.scale(dpr, dpr);
ctx.clearRect(0, 0, GRID_W * CELL, GRID_H * CELL);
const seed = sweater.config.seed >>> 0;
const noise = 0.05 + (sweater.config.ugliness / 100) * 0.05;
for (let r = 0; r < GRID_H; r++) {
for (let c = 0; c < GRID_W; c++) {
const color = sweater.cells[r]?.[c] ?? null;
if (color === null) continue;
const x = c * CELL;
const y = r * CELL;
// per-stitch brightness jitter
const j = 1 + (hash2(seed, c, r) - 0.5) * 2 * noise;
const base = shade(color, j);
ctx.fillStyle = base;
ctx.fillRect(x, y, CELL, CELL);
// knit chevron: dark V + light highlight (subtle so motifs stay readable)
ctx.strokeStyle = shade(base, 0.86);
ctx.lineWidth = 1.6;
ctx.beginPath();
ctx.moveTo(x + 1, y + 2.5);
ctx.lineTo(x + CELL / 2, y + CELL - 2);
ctx.lineTo(x + CELL - 1, y + 2.5);
ctx.stroke();
ctx.strokeStyle = shade(base, 1.12);
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(x + 1, y + 1.5);
ctx.lineTo(x + CELL / 2, y + CELL - 3);
ctx.stroke();
}
}
// subtle outline around the silhouette
ctx.strokeStyle = 'rgba(0,0,0,0.35)';
ctx.lineWidth = 1;
for (let r = 0; r < GRID_H; r++) {
for (let c = 0; c < GRID_W; c++) {
if (sweater.cells[r]![c] === null) continue;
const x = c * CELL;
const y = r * CELL;
const edge = (dr: number, dc: number): boolean => {
const rr = r + dr;
const cc = c + dc;
return rr < 0 || rr >= GRID_H || cc < 0 || cc >= GRID_W || sweater.cells[rr]![cc] === null;
};
ctx.beginPath();
if (edge(-1, 0)) { ctx.moveTo(x, y); ctx.lineTo(x + CELL, y); }
if (edge(1, 0)) { ctx.moveTo(x, y + CELL); ctx.lineTo(x + CELL, y + CELL); }
if (edge(0, -1)) { ctx.moveTo(x, y); ctx.lineTo(x, y + CELL); }
if (edge(0, 1)) { ctx.moveTo(x + CELL, y); ctx.lineTo(x + CELL, y + CELL); }
ctx.stroke();
}
}
}