#!/usr/bin/env python3
"""
White crayon on a black wall.
One grain 1/16 inch wide at the center.
Then three hundred thousand more, one at a time,
each sent straight from a chance point on the wall's edge
toward the center, stopping where it first touches a stopped grain.
"""

import random
import math
from PIL import Image, ImageDraw

# Decisions where open:
# - Wall rendered as 2000 x 2000 px square.
# - Grain diameter: 5 px (representing 1/16 inch; relative scale is free).
# - One fixed seed for all chance points.
# - Touching: grains collide when centers are closer than diameter.
# - Only the stopped grains are drawn; no trajectories.
# - Exact count of 300000 additional grains.

WIDTH = 2000
HEIGHT = 2000
CENTER = (WIDTH // 2, HEIGHT // 2)
GRAIN_DIAM = 5
GRAIN_R = GRAIN_DIAM / 2.0
N_GRAINS = 300000
SEED = 42

random.seed(SEED)

# Occupancy grid for fast collision: cell size ~ grain diameter
CELL = 6
GRID_W = (WIDTH + CELL - 1) // CELL
GRID_H = (HEIGHT + CELL - 1) // CELL
occupied = [[[] for _ in range(GRID_H)] for _ in range(GRID_W)]

def add_grain(x, y):
    gx = int(x // CELL)
    gy = int(y // CELL)
    if 0 <= gx < GRID_W and 0 <= gy < GRID_H:
        occupied[gx][gy].append((x, y))

def collides(x, y):
    gx = int(x // CELL)
    gy = int(y // CELL)
    for dx in (-1, 0, 1):
        for dy in (-1, 0, 1):
            nx, ny = gx + dx, gy + dy
            if 0 <= nx < GRID_W and 0 <= ny < GRID_H:
                for ox, oy in occupied[nx][ny]:
                    if (x - ox)**2 + (y - oy)**2 < GRAIN_DIAM**2:
                        return True
    return False

# First grain at center
grains = [CENTER]
add_grain(*CENTER)

def random_edge_point():
    side = random.randint(0, 3)
    if side == 0:  # top
        return (random.uniform(0, WIDTH), 0)
    elif side == 1:  # right
        return (WIDTH - 1, random.uniform(0, HEIGHT))
    elif side == 2:  # bottom
        return (random.uniform(0, WIDTH), HEIGHT - 1)
    else:  # left
        return (0, random.uniform(0, HEIGHT))

print("Simulating...")
for i in range(N_GRAINS):
    if i % 50000 == 0:
        print(f"  {i} grains...")
    ex, ey = random_edge_point()
    # Direction toward center
    dx = CENTER[0] - ex
    dy = CENTER[1] - ey
    dist = math.hypot(dx, dy)
    if dist < 1:
        continue
    # Unit step
    step = 1.5  # slightly larger than half grain for speed
    ux = dx / dist * step
    uy = dy / dist * step
    x, y = ex, ey
    steps = int(dist / step) + 2
    stopped = False
    for _ in range(steps):
        x += ux
        y += uy
        if collides(x, y):
            # Back up a bit to the last free position? or stop at contact
            # For simplicity, place at previous position if possible, else current
            grains.append((x - ux, y - uy))
            add_grain(x - ux, y - uy)
            stopped = True
            break
        # Safety: if past center, stop
        if math.hypot(x - CENTER[0], y - CENTER[1]) < GRAIN_R:
            grains.append((x, y))
            add_grain(x, y)
            stopped = True
            break
    if not stopped:
        # Rare: place near center
        grains.append(CENTER)
        add_grain(*CENTER)

print(f"Placed {len(grains)} grains.")

# Render
print("Rendering...")
img = Image.new("RGB", (WIDTH, HEIGHT), (0, 0, 0))
draw = ImageDraw.Draw(img)
for gx, gy in grains:
    # Draw filled circle
    draw.ellipse([gx - GRAIN_R, gy - GRAIN_R, gx + GRAIN_R, gy + GRAIN_R], fill=(255, 255, 255))

img.save("/tmp/art/render-1.png", "PNG")
print("Saved render-1.png")
