"""Frost on Five Lines — 2026-11-17 nightly art drop (concept: grains).

Wall instruction carried out as a program: black pencil. Rule five lines
a foot long at chance places. Then grains 1/32 inch wide, one at a time,
each sent straight from a chance point on the wall's edge at a chance
angle inward, stopping where it first touches a line or a stopped grain.

One seed fixes the five lines and every grain's entry point and angle.
The wall is 5 ft, so a foot is 500 px at 2500 px. Grains are drawn as
9 px dots at their stopping points (the print minimum 1/300 of the
canvas), no trails. Entry points sit on the print-area boundary
(140 px inset) so no mark crosses the 5% margin; a grain that exits the
print area without touching anything is lost. The five lines are the
seed skeleton: each line is a chain of overlapping discs in the
collision hash, so a grain stops where its centre comes within one
grain diameter of a stopped grain, or just touches a line.

This render fires 20,000 grains (the count is scaled by construction so
the reef stays one figure with a clear edge; the rule is identical at
any count — see log.md). 7,361 grains stopped. Paper ink on a black
ground: the piece reads on black shirts only.

Run with: python3 source.py — writes render-1.png beside itself.
Only the standard library and PIL are used; no file reads, no network,
no shelling out.
"""
import math
import random

from PIL import Image, ImageDraw

SEED = 20261118
COUNT = 20000
GROUND = "black"
CLUSTER = (0.47, 0.58)
CLUSTER_R = 500

SIZE = 2500
MARGIN = 125            # no ink within 125 px of the canvas edge
ENTRY = 140             # grain entry points / stop region
LINE_INSET = 140        # line endpoints
FOOT = 500              # one foot in px at 2500 px (5 ft wall)
GRAIN_D = 9             # grain dot diameter (print minimum 1/300 of canvas)
GRAIN_R = 4.5
LINE_W = 12
LINE_R = GRAIN_R + LINE_W / 2.0   # 10.5: grain centre stops this far from a line axis
GRAIN_STOP = float(GRAIN_D)       # 9.0: centre-to-centre stop distance
CELL = 16               # spatial-hash cell (px)
DISC_STEP = 4.0         # spacing of collision discs along a line
PAPER = "#FFFCF0"
BLACK = "#100F0F"


def hex2rgb(h):
    return (int(h[1:3], 16), int(h[3:5], 16), int(h[5:7], 16))


def make_lines(rng, layout, cluster=None, cluster_r=500):
    """Five 500 px lines at chance places. Draw order fixed: per line,
    centre x, centre y, angle; the whole triple is redrawn on rejection,
    so a layout change never shifts another line's draw."""
    lines = []
    tries = 0
    while len(lines) < 5:
        tries += 1
        if tries > 20000:
            raise RuntimeError("line placement failed")
        if layout == "cluster":
            cx0 = ENTRY + cluster[0] * (SIZE - 2 * ENTRY)
            cy0 = ENTRY + cluster[1] * (SIZE - 2 * ENTRY)
            u = rng.random()
            v = rng.random() * 2.0 * math.pi
            r = cluster_r * math.sqrt(u)
            cx = cx0 + r * math.cos(v)
            cy = cy0 + r * math.sin(v)
        else:  # scatter
            cx = ENTRY + rng.random() * (SIZE - 2 * ENTRY)
            cy = ENTRY + rng.random() * (SIZE - 2 * ENTRY)
        ang = rng.random() * math.pi
        dx, dy = math.cos(ang), math.sin(ang)
        x1, y1 = cx - 250.0 * dx, cy - 250.0 * dy
        x2, y2 = cx + 250.0 * dx, cy + 250.0 * dy
        if min(x1, x2) < LINE_INSET or max(x1, x2) > SIZE - LINE_INSET:
            continue
        if min(y1, y2) < LINE_INSET or max(y1, y2) > SIZE - LINE_INSET:
            continue
        lines.append((x1, y1, x2, y2))
    return lines


def line_discs(lines):
    """Collision discs along each line: centres every 4 px, stop radius
    10.5 px, so a grain's edge just touches the drawn 12 px line."""
    discs = []
    for (x1, y1, x2, y2) in lines:
        n = int(math.hypot(x2 - x1, y2 - y1) / DISC_STEP)
        for i in range(n + 1):
            t = i / n
            discs.append((x1 + t * (x2 - x1), y1 + t * (y2 - y1), LINE_R))
    return discs


def _grid_add(grid, x, y, r):
    cx = int(x // CELL)
    cy = int(y // CELL)
    for ax in (cx - 1, cx, cx + 1):
        for ay in (cy - 1, cy, cy + 1):
            grid.setdefault((ax, ay), []).append((x, y, r))


def _t_exit(ox, oy, dx, dy):
    t = float("inf")
    if dx > 0:
        t = min(t, (SIZE - ENTRY - ox) / dx)
    elif dx < 0:
        t = min(t, (ENTRY - ox) / dx)
    if dy > 0:
        t = min(t, (SIZE - ENTRY - oy) / dy)
    elif dy < 0:
        t = min(t, (ENTRY - oy) / dy)
    return t


def _ray_first_hit(ox, oy, dx, dy, grid, t_exit):
    """First t>0 where the ray centre comes within a disc's stop radius.
    DDA grid walk; exact: a disc is tested in every cell its touch point
    could sit in, and the walk stops only once the next cell starts past
    the best hit found."""
    cx = int(ox // CELL)
    cy = int(oy // CELL)
    if dx > 0:
        stepx, tmaxx, tdx = 1, ((cx + 1) * CELL - ox) / dx, CELL / dx
    elif dx < 0:
        stepx, tmaxx, tdx = -1, (cx * CELL - ox) / dx, -CELL / dx
    else:
        stepx, tmaxx, tdx = 0, float("inf"), float("inf")
    if dy > 0:
        stepy, tmaxy, tdy = 1, ((cy + 1) * CELL - oy) / dy, CELL / dy
    elif dy < 0:
        stepy, tmaxy, tdy = -1, (cy * CELL - oy) / dy, -CELL / dy
    else:
        stepy, tmaxy, tdy = 0, float("inf"), float("inf")
    best = None
    guard = 0
    while True:
        guard += 1
        if guard > 20000:
            break
        discs = grid.get((cx, cy))
        if discs:
            for (gx, gy, gr) in discs:
                fx = ox - gx
                fy = oy - gy
                b = dx * fx + dy * fy
                cc = fx * fx + fy * fy - gr * gr
                if cc < 0:
                    t = 0.0
                else:
                    disc = b * b - cc
                    if disc < 0:
                        continue
                    t = -b - math.sqrt(disc)
                    if t < 0:
                        continue
                if best is None or t < best:
                    best = t
        if tmaxx < tmaxy:
            tnext = tmaxx
            tmaxx += tdx
            cx += stepx
        else:
            tnext = tmaxy
            tmaxy += tdy
            cy += stepy
        if tnext > t_exit:
            break
        if best is not None and tnext > best:
            break
    return best


def simulate(seed, count, lines):
    """Fire `count` grains from chance edge points at chance inward
    angles; each stops at first touch of a line or a stopped grain.
    Returns (stopped points, lost count)."""
    rng = random.Random(seed)
    grid = {}
    for (x, y, r) in line_discs(lines):
        _grid_add(grid, x, y, r)
    stopped = []
    lost = 0
    span = SIZE - 2 * ENTRY
    for _ in range(count):
        e = int(rng.random() * 4)
        u = rng.random()
        a = (rng.random() * 2.0 - 1.0) * (math.pi / 2.0)
        if e == 0:      # left edge, inward +x
            ox, oy = ENTRY, ENTRY + u * span
            dx, dy = math.cos(a), math.sin(a)
        elif e == 1:    # right edge, inward -x
            ox, oy = SIZE - ENTRY, ENTRY + u * span
            dx, dy = -math.cos(a), math.sin(a)
        elif e == 2:    # top edge, inward +y
            ox, oy = ENTRY + u * span, ENTRY
            dx, dy = math.sin(a), math.cos(a)
        else:           # bottom edge, inward -y
            ox, oy = ENTRY + u * span, SIZE - ENTRY
            dx, dy = math.sin(a), -math.cos(a)
        te = _t_exit(ox, oy, dx, dy)
        t = _ray_first_hit(ox, oy, dx, dy, grid, te)
        if t is None or t > te:
            lost += 1
            continue
        sx = ox + t * dx
        sy = oy + t * dy
        stopped.append((sx, sy))
        _grid_add(grid, sx, sy, GRAIN_STOP)
    return stopped, lost


def render(lines, stopped, ground):
    g = hex2rgb(PAPER if ground == "paper" else BLACK)
    ink = hex2rgb(BLACK if ground == "paper" else PAPER)
    img = Image.new("RGB", (SIZE, SIZE), g)
    d = ImageDraw.Draw(img)
    for (x1, y1, x2, y2) in lines:
        d.line([(x1, y1), (x2, y2)], fill=ink, width=LINE_W)
    r = GRAIN_R
    for (x, y) in stopped:
        d.ellipse([x - r, y - r, x + r, y + r], fill=ink)
    return img


def main():
    rng = random.Random(SEED)
    lines = make_lines(rng, "cluster", CLUSTER, CLUSTER_R)
    stopped, lost = simulate(SEED, COUNT, lines)
    img = render(lines, stopped, GROUND)
    img.save("render-1.png")
    print("render-1.png: %d grains stopped, %d lost" % (len(stopped), lost))


if __name__ == "__main__":
    main()
