from math import cos, sin, pi, sqrt, floor, ceil
from pathlib import Path
import struct
import zlib

WIDTH, HEIGHT = 640, 520
RINGS, SIDES = 48, 24
BACKGROUND = (12, 14, 17)


def subtract(a, b):
    return tuple(x - y for x, y in zip(a, b))


def cross(a, b):
    return (a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0])


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def normalize(v):
    length = sqrt(dot(v, v))
    return tuple(x / length for x in v)


def rotate(v):
    x, y, z = v
    y, z = y * cos(0.85) - z * sin(0.85), y * sin(0.85) + z * cos(0.85)
    x, z = x * cos(0.3) + z * sin(0.3), -x * sin(0.3) + z * cos(0.3)
    return (x * cos(-0.28) - y * sin(-0.28),
            x * sin(-0.28) + y * cos(-0.28), z)


def project(v):
    x, y, z = v
    inverse_depth = 1 / (5.2 - z)
    return (WIDTH / 2 + 750 * x * inverse_depth,
            HEIGHT / 2 - 750 * y * inverse_depth, inverse_depth)


def edge(a, b, p):
    return (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])


def write_png(path, pixels):
    def chunk(kind, payload):
        return (struct.pack(">I", len(payload)) + kind + payload
                + struct.pack(">I", zlib.crc32(kind + payload) & 0xffffffff))
    rows = b"".join(b"\x00" + pixels[y * WIDTH * 3:(y + 1) * WIDTH * 3]
                    for y in range(HEIGHT))
    path.write_bytes(b"\x89PNG\r\n\x1a\n"
                     + chunk(b"IHDR", struct.pack(">IIBBBBB", WIDTH, HEIGHT, 8, 2, 0, 0, 0))
                     + chunk(b"IDAT", zlib.compress(rows, 9))
                     + chunk(b"IEND", b""))


vertices = []
for ring in range(RINGS):
    u = 2 * pi * ring / RINGS
    for side in range(SIDES):
        v = 2 * pi * side / SIDES
        radius = 1.25 + 0.48 * cos(v)
        vertices.append(rotate((radius * cos(u), radius * sin(u), 0.48 * sin(v))))

faces = []
for ring in range(RINGS):
    for side in range(SIDES):
        a = ring * SIDES + side
        b = ((ring + 1) % RINGS) * SIDES + side
        c = ((ring + 1) % RINGS) * SIDES + (side + 1) % SIDES
        d = ring * SIDES + (side + 1) % SIDES
        faces.extend(((a, b, c), (a, c, d)))

projected = list(map(project, vertices))
depth = [0.0] * (WIDTH * HEIGHT)
shaded = bytearray(BACKGROUND * (WIDTH * HEIGHT))
wireframe = bytearray(BACKGROUND * (WIDTH * HEIGHT))
visible_faces = []
light = normalize((-0.6, 0.8, 1.0))

for indices in faces:
    a3, b3, c3 = [vertices[i] for i in indices]
    normal = normalize(cross(subtract(b3, a3), subtract(c3, a3)))
    if dot(normal, subtract((0, 0, 5.2), a3)) <= 0:
        continue
    visible_faces.append(indices)
    a, b, c = [projected[i] for i in indices]
    area = edge(a, b, c)
    intensity = 0.16 + 0.84 * max(0, dot(normal, light))
    color = bytes(round(channel * intensity) for channel in (164, 214, 189))
    for y in range(max(0, floor(min(a[1], b[1], c[1]))),
                   min(HEIGHT - 1, ceil(max(a[1], b[1], c[1]))) + 1):
        for x in range(max(0, floor(min(a[0], b[0], c[0]))),
                       min(WIDTH - 1, ceil(max(a[0], b[0], c[0]))) + 1):
            p = (x + 0.5, y + 0.5)
            weights = (edge(b, c, p) / area, edge(c, a, p) / area, edge(a, b, p) / area)
            if min(weights) < -1e-9:
                continue
            z = sum(w * vertex[2] for w, vertex in zip(weights, (a, b, c)))
            offset = y * WIDTH + x
            if z > depth[offset]:
                depth[offset] = z
                shaded[3 * offset:3 * offset + 3] = color

for face in visible_faces:
    for start, end in zip(face, (face[1], face[2], face[0])):
        a, b = projected[start], projected[end]
        steps = ceil(max(abs(a[0] - b[0]), abs(a[1] - b[1]))) * 2
        for step in range(steps + 1):
            t = step / max(1, steps)
            x, y = floor(a[0] + t * (b[0] - a[0])), floor(a[1] + t * (b[1] - a[1]))
            z = a[2] + t * (b[2] - a[2])
            if 0 <= x < WIDTH and 0 <= y < HEIGHT:
                offset = y * WIDTH + x
                if z >= depth[offset] - 0.0012:
                    wireframe[3 * offset:3 * offset + 3] = bytes((133, 168, 154))

destination = Path(__file__).resolve().parent
write_png(destination / "demo-torus-shaded.png", shaded)
write_png(destination / "demo-torus-wireframe.png", wireframe)
print(f"Rendered {len(vertices)} vertices, {len(faces)} triangles at {WIDTH} × {HEIGHT}")
