"""Share. A wall drawing carried out by a program: writes render-1.png (1024 x 1024) beside this file.
Requires numpy. Runs for several minutes (about 94 steps, each a couple of seconds)."""
import os, zlib, struct, sys
import numpy as np

SEED = 20261124
GRAIN = 1 / 32            # inch
N = 1024                  # grains per side: a square wall 32 in x 32 in
R_NEAR = 2                # 1/16 inch = 2 grains
R_TOP = 4                 # 1/8 inch = 4 grains (ceiling = row 0)
R_BOTTOM = 96             # 3 inches = 96 grains (floor = last row)
MAX_ITER = 400
INK = (0x10, 0x0F, 0x0F)  # Flexoki black
PAPER = (0xFF, 0xFC, 0xF0)  # Flexoki paper

def far_radius(y):
    return int(round(R_TOP + (R_BOTTOM - R_TOP) * y / (N - 1)))

def disc_halfwidths(R):
    # grains whose centre is within distance R of the centre grain
    return [int(np.floor(np.sqrt(R * R - dy * dy))) for dy in range(-R, R + 1)]

def disc_sums(a, R_of_row):
    """Sum of a over the disc around each grain, radius depends on its row."""
    P = np.pad(a.astype(np.int32), ((0, 0), (1, 0))).cumsum(axis=1)  # P[:, k] = sum of first k columns
    out = np.zeros(a.shape, np.int32)
    xs = np.arange(N)
    cache = {}
    for y in range(N):
        R = R_of_row[y]
        if R not in cache:
            cache[R] = disc_halfwidths(R)
        hw = cache[R]
        acc = np.zeros(N, np.int32)
        for i, dy in enumerate(range(-R, R + 1)):
            yy = y + dy
            if yy < 0 or yy >= N:
                continue
            lo = np.clip(xs - hw[i], 0, N)
            hi = np.clip(xs + hw[i] + 1, 0, N)
            acc += P[yy, hi] - P[yy, lo]
        out[y] = acc
    return out

def write_png(path, rgb):
    h, w, _ = rgb.shape
    raw = b"".join(b"\x00" + rgb[y].tobytes() for y in range(h))
    def chunk(t, d):
        c = struct.pack(">I", len(d)) + t + d
        return c + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
    png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
    png += chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b"")
    open(path, "wb").write(png)

def main():
    rng = np.random.default_rng(SEED)
    a = rng.random((N, N)) < 0.5                      # chance half inked
    near_rows = [R_NEAR] * N
    far_rows = [far_radius(y) for y in range(N)]
    ones = np.ones((N, N), np.int32)
    n_near = disc_sums(ones, near_rows)
    n_far = disc_sums(ones, far_rows)
    prev = None
    status = "iteration limit reached"
    for it in range(1, MAX_ITER + 1):
        s_near = disc_sums(a, near_rows)
        s_far = disc_sums(a, far_rows)
        # larger share within 1/16 inch than within the far distance (cross-multiplied, exact)
        new = (s_near.astype(np.int64) * n_far) > (s_far.astype(np.int64) * n_near)
        changed = int((new != a).sum())
        print("iter", it, "changed", changed, "inked", round(float(new.mean()), 4), flush=True)
        if changed == 0:
            status = "fixed point at iteration %d" % it
            break
        if prev is not None and np.array_equal(new, prev):
            status = "two-step cycle at iteration %d" % it
            a = new
            break
        prev, a = a, new
    print(status)
    img = np.empty((N, N, 3), np.uint8)
    img[:] = PAPER
    img[a] = INK
    here = os.path.dirname(os.path.abspath(__file__))
    write_png(os.path.join(here, "render-1.png"), img)

main()
