view tools/images.py @ 6:910b26feca76

full game flow
author ark
date 2026-10-19 01:05 +0200
parents 5492efd60e2c
children
line wrap: on
line source

"""
image steps of the build: sprite trimming, tower level strips, map copies.

all functions take and return pillow images or file paths. no numpy; the
per-pixel loops run on crops of a few hundred pixels and stay fast enough.
"""

from PIL import Image, ImageDraw, ImageFilter

# pencil lines in the tower strips are darker than this luminance
INK_LUM = 225
# light pixels outside a drawing fade from opaque at LUM_OPAQUE to
# transparent at LUM_CLEAR, which removes the white paper halo
LUM_OPAQUE = 200
LUM_CLEAR = 250
# gaps in the pencil outline up to about twice this many pixels are closed
# before the inside is filled
GAP_CLOSE = 2


def trim(im):
    """return the image cropped to its non-transparent pixels."""
    box = im.getbbox()
    return im.crop(box) if box else im


def darken(im, factor):
    """return a copy with the colour scaled by factor, alpha unchanged."""
    r, g, b, a = im.split()
    r, g, b = (c.point(lambda v: int(v * factor)) for c in (r, g, b))
    return Image.merge("RGBA", (r, g, b, a))


def recolour(im, hue):
    """
    return a copy with every pixel's hue set to hue (degrees), saturation,
    brightness and alpha unchanged. grey and black pixels stay as they are.
    """
    a = im.getchannel("A")
    h, s, v = im.convert("RGB").convert("HSV").split()
    h = h.point(lambda _: round(hue / 360 * 255))
    out = Image.merge("HSV", (h, s, v)).convert("RGBA")
    out.putalpha(a)
    return out


def split_strip(im):
    """
    split a strip of drawings side by side at columns without pencil.

    returns a list of crops, left to right. column runs narrower than
    4 pixels count as specks and are dropped.
    """
    w, h = im.size
    data = im.tobytes()
    used = [False] * w
    for y in range(h):
        row = y * w * 4
        for x in range(w):
            i = row + x * 4
            if data[i + 3] and data[i] + data[i + 1] + data[i + 2] < 3 * INK_LUM:
                used[x] = True
    runs = []
    start = None
    for x, u in enumerate(used + [False]):
        if u and start is None:
            start = x
        elif not u and start is not None:
            if x - start > 3:
                runs.append((start, x))
            start = None
    # cut halfway between drawings so nothing of a drawing is lost
    crops = []
    for i, (a, b) in enumerate(runs):
        left = 0 if i == 0 else (runs[i - 1][1] + a) // 2
        right = w if i == len(runs) - 1 else (b + runs[i + 1][0]) // 2
        crops.append(im.crop((left, 0, right, h)))
    return crops


def fill_inside(im):
    """
    fill the inside of a pencil outline drawing with white.

    the outside is found by a flood fill from the image border over pixels
    that are not pencil. outline gaps are closed first by thickening the
    pencil lines, and the outside is grown back by the same amount
    afterwards. light pixels outside become transparent. returns a new
    image, trimmed.
    """
    pad = GAP_CLOSE + 2
    src = Image.new("RGBA", (im.width + 2 * pad, im.height + 2 * pad))
    src.paste(im, (pad, pad))
    w, h = src.size
    data = src.tobytes()

    ink = bytearray(w * h)
    for i in range(w * h):
        j = i * 4
        if data[j + 3] > 64 and data[j] + data[j + 1] + data[j + 2] < 3 * INK_LUM:
            ink[i] = 255
    size = 2 * GAP_CLOSE + 1
    walls = Image.frombytes("L", (w, h), bytes(ink)).filter(ImageFilter.MaxFilter(size))

    # outside: flood fill from a corner, which the padding keeps free
    ImageDraw.floodfill(walls, (0, 0), 128, thresh=0)
    outside = walls.point(lambda v: 255 if v == 128 else 0)
    outside = outside.filter(ImageFilter.MaxFilter(size)).tobytes()

    out = bytearray(w * h * 4)
    for i in range(w * h):
        j = i * 4
        r, g, b, a = data[j:j + 4]
        lum = (r + g + b) / 3
        if outside[i]:
            # fade light pixels out, keep pencil
            if lum >= LUM_CLEAR:
                a = 0
            elif lum > LUM_OPAQUE:
                a = int(a * (LUM_CLEAR - lum) / (LUM_CLEAR - LUM_OPAQUE))
            out[j:j + 4] = bytes((r, g, b, a))
        else:
            # composite over white
            k = a / 255
            out[j:j + 4] = bytes((int(r * k + 255 * (1 - k)),
                                  int(g * k + 255 * (1 - k)),
                                  int(b * k + 255 * (1 - k)), 255))
    return trim(Image.frombytes("RGBA", (w, h), bytes(out)))


def tower_levels(path):
    """return the four level images (levels 2-5) of a t*p strip."""
    strip = Image.open(path).convert("RGBA")
    levels = [fill_inside(c) for c in split_strip(strip)]
    if len(levels) != 4:
        raise ValueError(f"{path}: found {len(levels)} drawings, expected 4")
    return levels


def map_copy(src, dst, quality):
    """write the map scan as jpeg. maps are opaque, so nothing is lost."""
    im = Image.open(src)
    if im.mode == "RGBA" and im.getextrema()[3][0] < 255:
        raise ValueError(f"{src}: map has transparent pixels, jpeg would lose them")
    im.convert("RGB").save(dst, quality=quality, optimize=True)