Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/pie-night

Pie night sign-ups: hosts start an event, guests add the pies they are bringing and watch the list fill in live. Installable, with optional push notifications.

FollowForkOpen app

Files

raster.ts

454 lines · 14.5 KB · TypeScript
/**
 * A tiny pure-JS rasterizer for the share image. Kody package code cannot
 * compile WebAssembly (so resvg-wasm is out), so this draws the solid-color
 * paths that Satori emits (text glyphs and rounded boxes) onto a decoded PNG
 * background and encodes the result as PNG. No runtime imports.
 *
 * Supported SVG: <path d fill fill-opacity opacity> and <rect> outside of
 * <mask>/<defs>/<clipPath>. Path commands: M L H V Q T C S A Z (any case).
 * Antialiasing: 5 sub-scanlines per pixel with exact horizontal coverage.
 */

export type Image = { width: number; height: number; data: Uint8Array } // RGB, 3 bytes per pixel

type Point = [number, number]
type Shape = { polys: Point[][]; r: number; g: number; b: number; a: number }

// ---------- PNG ----------

const CRC_TABLE = (() => {
	const t = new Uint32Array(256)
	for (let n = 0; n < 256; n++) {
		let c = n
		for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
		t[n] = c >>> 0
	}
	return t
})()

function crc32(bytes: Uint8Array, start = 0, end = bytes.length) {
	let c = 0xffffffff
	for (let i = start; i < end; i++) c = CRC_TABLE[(c ^ bytes[i]!) & 0xff]! ^ (c >>> 8)
	return (c ^ 0xffffffff) >>> 0
}

async function pipe(bytes: Uint8Array, stream: CompressionStream | DecompressionStream): Promise<Uint8Array> {
	const out = new Response(new Blob([bytes as BlobPart]).stream().pipeThrough(stream))
	return new Uint8Array(await out.arrayBuffer())
}

export async function decodePng(bytes: Uint8Array): Promise<Image> {
	const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
	let at = 8
	let width = 0
	let height = 0
	let colorType = 0
	const idat: Uint8Array[] = []
	while (at < bytes.length) {
		const len = view.getUint32(at)
		const type = String.fromCharCode(bytes[at + 4]!, bytes[at + 5]!, bytes[at + 6]!, bytes[at + 7]!)
		const body = bytes.subarray(at + 8, at + 8 + len)
		if (type === 'IHDR') {
			width = view.getUint32(at + 8)
			height = view.getUint32(at + 12)
			if (body[8] !== 8 || body[12] !== 0) throw new Error('Only 8-bit, non-interlaced PNGs are supported')
			colorType = body[9]!
			if (colorType !== 2 && colorType !== 6) throw new Error('Only RGB or RGBA PNGs are supported')
		} else if (type === 'IDAT') idat.push(body)
		else if (type === 'IEND') break
		at += 12 + len
	}
	const total = idat.reduce((n, c) => n + c.length, 0)
	const joined = new Uint8Array(total)
	let o = 0
	for (const c of idat) {
		joined.set(c, o)
		o += c.length
	}
	const raw = await pipe(joined, new DecompressionStream('deflate'))
	const bpp = colorType === 6 ? 4 : 3
	const stride = width * bpp
	const pixels = new Uint8Array(stride * height)
	for (let y = 0; y < height; y++) {
		const filter = raw[y * (stride + 1)]!
		const src = y * (stride + 1) + 1
		const dst = y * stride
		for (let x = 0; x < stride; x++) {
			const rawByte = raw[src + x]!
			const left = x >= bpp ? pixels[dst + x - bpp]! : 0
			const up = y ? pixels[dst - stride + x]! : 0
			const upLeft = y && x >= bpp ? pixels[dst - stride + x - bpp]! : 0
			let v = rawByte
			if (filter === 1) v += left
			else if (filter === 2) v += up
			else if (filter === 3) v += (left + up) >> 1
			else if (filter === 4) {
				const p = left + up - upLeft
				const pa = Math.abs(p - left)
				const pb = Math.abs(p - up)
				const pc = Math.abs(p - upLeft)
				v += pa <= pb && pa <= pc ? left : pb <= pc ? up : upLeft
			}
			pixels[dst + x] = v & 0xff
		}
	}
	if (bpp === 3) return { width, height, data: pixels }
	const rgb = new Uint8Array(width * height * 3)
	for (let i = 0, j = 0; i < pixels.length; i += 4, j += 3) {
		rgb[j] = pixels[i]!
		rgb[j + 1] = pixels[i + 1]!
		rgb[j + 2] = pixels[i + 2]!
	}
	return { width, height, data: rgb }
}

function chunk(type: string, body: Uint8Array) {
	const out = new Uint8Array(12 + body.length)
	const v = new DataView(out.buffer)
	v.setUint32(0, body.length)
	for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i)
	out.set(body, 8)
	v.setUint32(8 + body.length, crc32(out, 4, 8 + body.length))
	return out
}

export async function encodePng(img: Image): Promise<Uint8Array> {
	const stride = img.width * 3
	const raw = new Uint8Array((stride + 1) * img.height)
	for (let y = 0; y < img.height; y++) {
		const o = y * (stride + 1)
		raw[o] = 1 // Sub filter: cheap and compresses gradients well.
		const s = y * stride
		for (let x = 0; x < stride; x++) raw[o + 1 + x] = (img.data[s + x]! - (x >= 3 ? img.data[s + x - 3]! : 0)) & 0xff
	}
	const ihdr = new Uint8Array(13)
	const v = new DataView(ihdr.buffer)
	v.setUint32(0, img.width)
	v.setUint32(4, img.height)
	ihdr[8] = 8
	ihdr[9] = 2
	const parts = [new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', await pipe(raw, new CompressionStream('deflate'))), chunk('IEND', new Uint8Array())]
	const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0))
	let o = 0
	for (const p of parts) {
		out.set(p, o)
		o += p.length
	}
	return out
}

// ---------- SVG parsing ----------

function parseColor(value: string | undefined): [number, number, number, number] | null {
	if (!value || value === 'none' || value === 'transparent') return null
	const v = value.trim().toLowerCase()
	if (v[0] === '#') {
		const h = v.slice(1)
		const full = h.length === 3 || h.length === 4 ? h.split('').map((c) => c + c).join('') : h
		const n = (i: number) => parseInt(full.slice(i, i + 2), 16)
		return [n(0), n(2), n(4), full.length === 8 ? n(6) / 255 : 1]
	}
	const m = v.match(/^rgba?\(([^)]+)\)$/)
	if (m) {
		const p = m[1]!.split(/[\s,/]+/).filter(Boolean).map(Number)
		return [p[0]!, p[1]!, p[2]!, p[3] ?? 1]
	}
	if (v === 'white') return [255, 255, 255, 1]
	if (v === 'black') return [0, 0, 0, 1]
	return null
}

function attrs(tag: string): Record<string, string> {
	const out: Record<string, string> = {}
	for (const m of tag.matchAll(/([a-zA-Z:-]+)="([^"]*)"/g)) out[m[1]!] = m[2]!
	return out
}

/** Pull drawable shapes out of a Satori SVG, in paint order. */
export function svgShapes(svg: string): Shape[] {
	const clean = svg.replace(/<(mask|defs|clipPath|pattern)[\s\S]*?<\/\1>/g, '')
	const shapes: Shape[] = []
	for (const m of clean.matchAll(/<(path|rect)\b[^>]*>/g)) {
		const a = attrs(m[0])
		const color = parseColor(a.fill ?? '#000')
		if (!color) continue
		const alpha = color[3] * Number(a['fill-opacity'] ?? 1) * Number(a.opacity ?? 1)
		if (alpha <= 0) continue
		let d = a.d
		if (m[1] === 'rect') {
			const x = Number(a.x ?? 0)
			const y = Number(a.y ?? 0)
			const w = Number(a.width ?? 0)
			const h = Number(a.height ?? 0)
			const rx = Math.min(Number(a.rx ?? a.ry ?? 0), w / 2, h / 2)
			d = rx > 0 ? `M${x + rx},${y} h${w - 2 * rx} a${rx},${rx} 0 0 1 ${rx},${rx} v${h - 2 * rx} a${rx},${rx} 0 0 1 -${rx},${rx} h-${w - 2 * rx} a${rx},${rx} 0 0 1 -${rx},-${rx} v-${h - 2 * rx} a${rx},${rx} 0 0 1 ${rx},-${rx} Z` : `M${x},${y} h${w} v${h} h-${w} Z`
		}
		if (!d) continue
		shapes.push({ polys: flattenPath(d), r: color[0], g: color[1], b: color[2], a: alpha })
	}
	return shapes
}

// ---------- Paths ----------

function steps(len: number) {
	return Math.max(2, Math.min(24, Math.ceil(len / 2.5)))
}

export function flattenPath(d: string): Point[][] {
	const tokens = d.match(/[a-zA-Z]|-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/g) ?? []
	const polys: Point[][] = []
	let cur: Point[] = []
	let x = 0
	let y = 0
	let sx = 0
	let sy = 0
	let cmd = ''
	let lastCtrl: Point | null = null
	let lastQuad: Point | null = null
	let i = 0
	const num = () => Number(tokens[i++])
	const isNum = () => i < tokens.length && !/^[a-zA-Z]$/.test(tokens[i]!)
	const push = (px: number, py: number) => {
		cur.push([px, py])
		x = px
		y = py
	}
	const close = () => {
		if (cur.length > 1) polys.push(cur)
		cur = []
	}
	while (i < tokens.length) {
		if (/^[a-zA-Z]$/.test(tokens[i]!)) cmd = tokens[i++]!
		const rel = cmd === cmd.toLowerCase()
		const c = cmd.toUpperCase()
		const ox = rel ? x : 0
		const oy = rel ? y : 0
		if (c === 'Z') {
			if (cur.length) cur.push([sx, sy])
			close()
			x = sx
			y = sy
			lastCtrl = lastQuad = null
			continue
		}
		if (!isNum()) {
			i++
			continue
		}
		if (c === 'M') {
			close()
			const px = num() + ox
			const py = num() + oy
			sx = px
			sy = py
			push(px, py)
			cmd = rel ? 'l' : 'L'
			lastCtrl = lastQuad = null
		} else if (c === 'L') {
			push(num() + ox, num() + oy)
			lastCtrl = lastQuad = null
		} else if (c === 'H') {
			push(num() + ox, y)
			lastCtrl = lastQuad = null
		} else if (c === 'V') {
			push(x, num() + oy)
			lastCtrl = lastQuad = null
		} else if (c === 'Q' || c === 'T') {
			let qx: number
			let qy: number
			if (c === 'Q') {
				qx = num() + ox
				qy = num() + oy
			} else {
				qx = lastQuad ? 2 * x - lastQuad[0] : x
				qy = lastQuad ? 2 * y - lastQuad[1] : y
			}
			const ex = num() + ox
			const ey = num() + oy
			const x0 = x
			const y0 = y
			const n = steps(Math.hypot(qx - x0, qy - y0) + Math.hypot(ex - qx, ey - qy))
			for (let k = 1; k <= n; k++) {
				const t = k / n
				const mt = 1 - t
				cur.push([mt * mt * x0 + 2 * mt * t * qx + t * t * ex, mt * mt * y0 + 2 * mt * t * qy + t * t * ey])
			}
			x = ex
			y = ey
			lastQuad = [qx, qy]
			lastCtrl = null
		} else if (c === 'C' || c === 'S') {
			let c1x: number
			let c1y: number
			if (c === 'C') {
				c1x = num() + ox
				c1y = num() + oy
			} else {
				c1x = lastCtrl ? 2 * x - lastCtrl[0] : x
				c1y = lastCtrl ? 2 * y - lastCtrl[1] : y
			}
			const c2x = num() + ox
			const c2y = num() + oy
			const ex = num() + ox
			const ey = num() + oy
			const x0 = x
			const y0 = y
			const n = steps(Math.hypot(c1x - x0, c1y - y0) + Math.hypot(c2x - c1x, c2y - c1y) + Math.hypot(ex - c2x, ey - c2y))
			for (let k = 1; k <= n; k++) {
				const t = k / n
				const mt = 1 - t
				cur.push([mt * mt * mt * x0 + 3 * mt * mt * t * c1x + 3 * mt * t * t * c2x + t * t * t * ex, mt * mt * mt * y0 + 3 * mt * mt * t * c1y + 3 * mt * t * t * c2y + t * t * t * ey])
			}
			x = ex
			y = ey
			lastCtrl = [c2x, c2y]
			lastQuad = null
		} else if (c === 'A') {
			const rx0 = Math.abs(num())
			const ry0 = Math.abs(num())
			const rot = (num() * Math.PI) / 180
			const large = num() !== 0
			const sweep = num() !== 0
			const ex = num() + ox
			const ey = num() + oy
			arc(cur, x, y, rx0, ry0, rot, large, sweep, ex, ey)
			x = ex
			y = ey
			lastCtrl = lastQuad = null
		} else i++
	}
	close()
	return polys
}

function arc(out: Point[], x1: number, y1: number, rx: number, ry: number, phi: number, large: boolean, sweep: boolean, x2: number, y2: number) {
	if (!rx || !ry) {
		out.push([x2, y2])
		return
	}
	const cos = Math.cos(phi)
	const sin = Math.sin(phi)
	const dx = (x1 - x2) / 2
	const dy = (y1 - y2) / 2
	const x1p = cos * dx + sin * dy
	const y1p = -sin * dx + cos * dy
	const lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry)
	if (lambda > 1) {
		rx *= Math.sqrt(lambda)
		ry *= Math.sqrt(lambda)
	}
	const num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p
	const den = rx * rx * y1p * y1p + ry * ry * x1p * x1p
	let coef = Math.sqrt(Math.max(0, num / den))
	if (large === sweep) coef = -coef
	const cxp = (coef * rx * y1p) / ry
	const cyp = (-coef * ry * x1p) / rx
	const cx = cos * cxp - sin * cyp + (x1 + x2) / 2
	const cy = sin * cxp + cos * cyp + (y1 + y2) / 2
	const ang = (ux: number, uy: number, vx: number, vy: number) => {
		const a = Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy)
		return a
	}
	const t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry)
	let dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry)
	if (!sweep && dt > 0) dt -= 2 * Math.PI
	else if (sweep && dt < 0) dt += 2 * Math.PI
	const n = Math.max(2, Math.min(48, Math.ceil((Math.abs(dt) * Math.max(rx, ry)) / 2.5)))
	for (let k = 1; k <= n; k++) {
		const t = t1 + (dt * k) / n
		const ex = rx * Math.cos(t)
		const ey = ry * Math.sin(t)
		out.push([cos * ex - sin * ey + cx, sin * ex + cos * ey + cy])
	}
}

// ---------- Filling ----------

const SUB = 5

/** Fill one shape (nonzero winding) onto the RGB image, offset by dx, dy. */
export function fillShape(img: Image, shape: Shape, dx = 0, dy = 0, color?: { r: number; g: number; b: number; a: number }) {
	const col = color ?? shape
	type Edge = { x0: number; y0: number; x1: number; y1: number; dir: number }
	const edges: Edge[] = []
	let minX = Infinity
	let maxX = -Infinity
	let minY = Infinity
	let maxY = -Infinity
	for (const poly of shape.polys) {
		for (let k = 0; k < poly.length; k++) {
			const p = poly[k]!
			const q = poly[(k + 1) % poly.length]!
			const ax = p[0] + dx
			const ay = p[1] + dy
			const bx = q[0] + dx
			const by = q[1] + dy
			minX = Math.min(minX, ax)
			maxX = Math.max(maxX, ax)
			minY = Math.min(minY, ay)
			maxY = Math.max(maxY, ay)
			if (ay === by) continue
			edges.push(ay < by ? { x0: ax, y0: ay, x1: bx, y1: by, dir: 1 } : { x0: bx, y0: by, x1: ax, y1: ay, dir: -1 })
		}
	}
	if (!edges.length) return
	const left = Math.max(0, Math.floor(minX))
	const right = Math.min(img.width - 1, Math.ceil(maxX))
	const top = Math.max(0, Math.floor(minY))
	const bottom = Math.min(img.height - 1, Math.ceil(maxY))
	if (left > right || top > bottom) return
	const w = right - left + 2
	const acc = new Float32Array(w)
	edges.sort((a, b) => a.y0 - b.y0)
	let next = 0
	let active: Edge[] = []
	const xs: Array<[number, number]> = []
	const weight = 1 / SUB
	for (let py = top; py <= bottom; py++) {
		acc.fill(0)
		let any = false
		for (let s = 0; s < SUB; s++) {
			const sy = py + (s + 0.5) / SUB
			while (next < edges.length && edges[next]!.y0 <= sy) active.push(edges[next++]!)
			active = active.filter((e) => e.y1 > sy)
			xs.length = 0
			for (const e of active) {
				if (e.y0 > sy) continue
				xs.push([e.x0 + ((sy - e.y0) * (e.x1 - e.x0)) / (e.y1 - e.y0), e.dir])
			}
			if (xs.length < 2) continue
			xs.sort((a, b) => a[0] - b[0])
			let wind = 0
			for (let k = 0; k < xs.length - 1; k++) {
				wind += xs[k]![1]
				if (!wind) continue
				const a = Math.max(left, xs[k]![0]) - left
				const b = Math.min(right + 1, xs[k + 1]![0]) - left
				if (b <= a) continue
				any = true
				const ia = Math.floor(a)
				const ib = Math.floor(b)
				if (ia === ib) acc[ia]! += (b - a) * weight
				else {
					acc[ia]! += (ia + 1 - a) * weight
					for (let q = ia + 1; q < ib; q++) acc[q]! += weight
					if (ib < w) acc[ib]! += (b - ib) * weight
				}
			}
		}
		if (!any) continue
		const row = py * img.width
		for (let q = 0; q < w; q++) {
			const cov = Math.min(1, acc[q]!) * col.a
			if (cov <= 0.002) continue
			const px = left + q
			if (px >= img.width) break
			const o = (row + px) * 3
			const inv = 1 - cov
			img.data[o] = img.data[o]! * inv + col.r * cov
			img.data[o + 1] = img.data[o + 1]! * inv + col.g * cov
			img.data[o + 2] = img.data[o + 2]! * inv + col.b * cov
		}
	}
}