view tools/preview.py @ 21:fa04481563b7

doc update
author ark
date 2026-10-20 00:44 +0200
parents 3a831478eda4
children 2f555a54c332
line wrap: on
line source

"""
preview images of the build, for checking routes, placement and tower levels
without starting the game.
"""

import math

from PIL import Image, ImageDraw

ROUTE_COLOURS = [(220, 0, 160), (0, 90, 255), (255, 120, 0), (0, 160, 60),
                 (140, 0, 255), (0, 180, 200), (200, 40, 40), (90, 90, 90)]


def _base(map_path, mp):
    """map image faded towards white, with the placement grid drawn on it."""
    im = Image.open(map_path).convert("RGBA")
    im = Image.blend(im, Image.new("RGBA", im.size, (255, 255, 255, 255)), 0.55)
    draw = ImageDraw.Draw(im)
    cell, cols = mp["cell"], mp["cols"]
    for i, c in enumerate(mp["grid"]):
        if c == "1":
            x, y = (i % cols) * cell, (i // cols) * cell
            draw.rectangle((x, y, x + cell - 2, y + cell - 2), fill=(60, 170, 60, 255))
    return im, draw


def _route(draw, pts, colour, width):
    pts = [tuple(p) for p in pts]
    draw.line(pts, fill=colour, width=width, joint="curve")
    for x, y in pts:
        draw.ellipse((x - 2, y - 2, x + 2, y + 2), fill=(0, 0, 0))
    # arrow heads at a few points, showing the walking direction
    for k in range(1, 6):
        i = k * (len(pts) - 1) // 6
        (x0, y0), (x1, y1) = pts[i], pts[i + 1]
        dx, dy = x1 - x0, y1 - y0
        n = (dx * dx + dy * dy) ** 0.5 or 1
        dx, dy = dx / n, dy / n
        tip = (x0 + dx * 6, y0 + dy * 6)
        draw.polygon([tip, (x0 - dx * 6 - dy * 6, y0 - dy * 6 + dx * 6),
                      (x0 - dx * 6 + dy * 6, y0 - dy * 6 - dx * 6)], fill=colour)


def _ends(draw, mp):
    for x, y, r in mp["entrances"]:
        draw.ellipse((x - r, y - r, x + r, y + r), outline=(0, 0, 255), width=3)
    for x, y, r in mp["exits"]:
        draw.ellipse((x - r, y - r, x + r, y + r), outline=(0, 160, 0), width=3)


def map_preview(map_path, mp):
    """the map with grid, centre line graph, routes, entrances and exits."""
    im, draw = _base(map_path, mp)
    for pts in mp["graph"]["edges"]:
        draw.line([tuple(p) for p in pts], fill=(120, 120, 120), width=1)
    for x, y in mp["graph"]["nodes"]:
        draw.rectangle((x - 3, y - 3, x + 3, y + 3), outline=(0, 0, 0))
    for k, r in enumerate(mp["routes"]):
        _route(draw, r["points"], ROUTE_COLOURS[k % len(ROUTE_COLOURS)], 3)
    _ends(draw, mp)
    for k, r in enumerate(mp["routes"]):
        x, y = r["points"][len(r["points"]) // 3]
        draw.text((x + 6, y + 6 + 10 * k), f"route {r['number']}", fill=(0, 0, 0))
    return im


def route_sheet(map_path, mp):
    """one panel per route, half size, for maps with several routes."""
    panels = []
    for k, r in enumerate(mp["routes"]):
        im, draw = _base(map_path, mp)
        _route(draw, r["points"], ROUTE_COLOURS[k % len(ROUTE_COLOURS)], 5)
        _ends(draw, mp)
        draw.text((10, 10), f"route {r['number']}: length {r['length']:.0f},"
                  f" turning {r['turning']:.0f}, value {r['value']:.2f}", fill=(0, 0, 0))
        panels.append(im.resize((im.width // 2, im.height // 2)))
    cols = min(3, len(panels))
    rows = (len(panels) + cols - 1) // cols
    pw, ph = panels[0].size
    sheet = Image.new("RGBA", (cols * pw, rows * ph), (255, 255, 255, 255))
    for k, p in enumerate(panels):
        sheet.paste(p, ((k % cols) * pw, (k // cols) * ph))
    return sheet


# screen angle the turning towers face on the tower sheet, the same as a new
# tower in the game: up
FACE = -90


def _turned(im, pivot, drawn):
    """
    im on a transparent square with the pivot (shares of width and height) at
    its centre. a sprite drawn pointing to angle drawn is turned around the
    pivot to face FACE; drawn None leaves it as it is.
    """
    px, py = round(im.width * pivot[0]), round(im.height * pivot[1])
    r = math.ceil(max(math.hypot(px - x, py - y) for x in (0, im.width) for y in (0, im.height)))
    sq = Image.new("RGBA", (2 * r, 2 * r), (0, 0, 0, 0))
    sq.alpha_composite(im, (r - px, r - py))
    if drawn is None:
        return sq
    # pillow turns anticlockwise, screen angles grow clockwise
    return sq.rotate(drawn - FACE, resample=Image.BICUBIC)


def tower_sheet(assets, angles, pivots, footprint, scale):
    """
    tower levels 1-5 per row: at full size on grey, so the white fill shows,
    and at game scale next to each other. turning towers are turned by their
    drawing direction in angles to face up, as in the game; a line from the
    pivot shows that direction, and each tower is labelled with its angle. a
    cross marks the rotation point, which is the tower position, and a circle
    the footprint around it. footprint is the footprint radius in map pixels,
    scale the sprite scale.
    """
    rows = []
    for t in range(4):
        names = [f"t{t}"] + [f"t{t}_{lv}" for lv in range(2, 6)]
        rows.append([(n, _turned(Image.open(assets / f"{n}.png"), pivots.get(n, (0.5, 0.5)),
                                 angles.get(n))) for n in names])
    pad = 16
    cell = max(im.width for r in rows for _, im in r) + pad
    cell_h = cell + 12
    small_w = round(cell * scale) + 4
    full_r = footprint / scale
    sheet = Image.new("RGBA", (5 * cell + 5 * small_w + pad, 4 * cell_h + 20),
                      (170, 170, 170, 255))
    draw = ImageDraw.Draw(sheet)
    for lv in range(5):
        draw.text((lv * cell + pad, 4), f"level {lv + 1}", fill=(0, 0, 0))
    draw.text((5 * cell + pad, 4), f"game scale {scale}, turning towers face {FACE}",
              fill=(0, 0, 0))
    dx, dy = math.cos(math.radians(FACE)), math.sin(math.radians(FACE))
    for t, r in enumerate(rows):
        y = 20 + t * cell_h
        cy = y + 12 + cell // 2
        for lv, (name, im) in enumerate(r):
            # label above, sprite centred on the pivot in the cell below it
            drawn = angles.get(name)
            draw.text((lv * cell + pad // 2, y), f"{name}: " + ("does not turn" if drawn is None
                                                               else f"angle {drawn}"),
                      fill=(0, 0, 0))
            cx = lv * cell + cell // 2
            sheet.alpha_composite(im, (cx - im.width // 2, cy - im.height // 2))
            if drawn is not None:
                arm = cell // 2 - pad // 2
                draw.line((cx, cy, cx + dx * arm, cy + dy * arm), fill=(255, 0, 0))
            draw.line((cx - 5, cy, cx + 5, cy), fill=(255, 0, 0))
            draw.line((cx, cy - 5, cx, cy + 5), fill=(255, 0, 0))
            draw.ellipse((cx - full_r, cy - full_r, cx + full_r, cy + full_r),
                         outline=(0, 0, 255), width=2)
            small = im.resize((max(1, round(im.width * scale)), max(1, round(im.height * scale))),
                              Image.LANCZOS)
            scx, scy = 5 * cell + pad + lv * small_w + small_w // 2, cy
            sheet.alpha_composite(small, (scx - small.width // 2, scy - small.height // 2))
            draw.ellipse((scx - footprint, scy - footprint, scx + footprint, scy + footprint),
                         outline=(0, 0, 255))
    return sheet