wobblyhead hg > minor_monsters
diff tools/masks.py @ 9:53f015966118
map, path, tower placement adjustments
| author | ark |
|---|---|
| date | 2026-10-19 15:55 +0200 |
| parents | 5492efd60e2c |
| children |
line wrap: on
line diff
--- a/tools/masks.py Mon Oct 19 13:37:52 2026 +0200 +++ b/tools/masks.py Mon Oct 19 15:55:37 2026 +0200 @@ -1,41 +1,50 @@ """ mask steps of the build: pixel classes, placement grid and routes. -a mask is a map-sized image with a red path, blue entrances and green exits -on a transparent background. pixels are indexed as y * width + x throughout. +a mask is a map-sized image with a red path centre line, blue entrances and +green exits on a transparent background. edges are hard: every pixel is +either fully transparent or opaque pure red, blue or green. pixels are +indexed as y * width + x throughout. """ import math from collections import deque -from PIL import Image, ImageDraw +from PIL import Image, ImageChops, ImageDraw FREE, PATH, ENTRANCE, EXIT = 0, 1, 2, 3 +# rgba bytes of the opaque mask colours +COLOURS = {b"\xff\x00\x00\xff": PATH, b"\x00\x00\xff\xff": ENTRANCE, + b"\x00\xff\x00\xff": EXIT} # 8-neighbour offsets in the order n, ne, e, se, s, sw, w, nw NEIGHBOURS = ((0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1)) class Mask: - """pixel classes of one map mask.""" + """ + pixel classes of one map mask. raises ValueError when a pixel is + neither transparent nor one of the mask colours. + """ def __init__(self, path): im = Image.open(path).convert("RGBA") self.w, self.h = im.size data = im.tobytes() cls = bytearray(self.w * self.h) - # the edges are soft: a pixel counts when it is at least half covered, - # and belongs to its strongest colour channel + bad = [] for i in range(self.w * self.h): j = i * 4 - if data[j + 3] >= 128: - r, g, b = data[j], data[j + 1], data[j + 2] - if r >= g and r >= b: - cls[i] = PATH - elif b >= g: - cls[i] = ENTRANCE - else: - cls[i] = EXIT + if data[j + 3] == 0: + continue + c = COLOURS.get(data[j:j + 4]) + if c is None: + bad.append(i) + else: + cls[i] = c + if bad: + raise ValueError(f"{path}: {len(bad)} pixels are not transparent, red, blue or" + f" green, the first at {bad[0] % self.w}, {bad[0] // self.w}") self.cls = cls def count(self, kind): @@ -97,20 +106,37 @@ return im -def placement_grid(mask, p): +def discs(w, h, points, radius): + """return an L image of size w x h, 255 within radius of any of the points.""" + im = Image.new("L", (w, h), 0) + draw = ImageDraw.Draw(im) + for x, y in points: + draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill=255) + return im + + +def placement_grid(mask, p, centre, half_width, spaces): """ - return (cols, rows, grid string) for placement table p. a cell is legal - when a tower footprint centred on it does not overlap the path, - entrances or exits, comes within max_gap of the path, and keeps - edge_distance from the map edge. the string has one '1' or '0' per - cell, row by row. + return (cols, rows, grid string) for placement table p. the road is + taken as half_width either side of the centre line, given as a list of + pixels. spaces is a list of (points, space). a cell is legal when a + tower footprint centred on it does not overlap the road, entrances or + exits, comes within max_gap of the road, keeps each space from its + points and keeps edge_distance from the map edge. the string has one + '1' or '0' per cell, row by row. """ cell = p["grid_cell"] r = p["footprint_radius"] - blocked = mask.grown((PATH, ENTRANCE, EXIT), r).tobytes() - near = mask.grown((PATH,), r + p["max_gap"]).tobytes() + w, h = mask.w, mask.h + # the centre line inside entrance and exit areas does not count as road + road = [(x, y) for x, y in centre if mask.cls[y * w + x] == PATH] + blocked = ImageChops.lighter(mask.grown((ENTRANCE, EXIT), r), + discs(w, h, road, r + half_width)) + for points, space in spaces: + blocked = ImageChops.lighter(blocked, discs(w, h, points, r + space)) + blocked = blocked.tobytes() + near = discs(w, h, road, r + half_width + p["max_gap"]).tobytes() edge = p["edge_distance"] - w, h = mask.w, mask.h cols, rows = w // cell, h // cell out = [] for cy in range(rows): @@ -411,16 +437,32 @@ return simplify(pts[:idx + 1], tol)[:-1] + simplify(pts[idx:], tol) -def path_width(mask, skel_len): - """average path width: path area divided by centre line length.""" +def line_width(mask, skel_len): + """average width of the drawn centre line: its area divided by its length.""" return mask.count(PATH) / skel_len if skel_len else 0.0 +def leave_point(graph, mask, n, kind): + """ + return the first centre line pixel outside the area of class kind, + walking from the line end n. + """ + a, b, pts = graph.edges[graph.incident(n)[0]] + if a != n: + pts = pts[::-1] + for x, y in pts: + if mask.cls[y * mask.w + x] != kind: + return (x, y) + return pts[-1] + + def extract_routes(mask, smooth_half, tol): """ - find the routes of a mask. returns a dict with the graph, the - entrance and exit blobs, the measured path width and the routes as - point lists, entrance to exit, smoothed and simplified. + find the routes of a mask. returns a dict with the graph, the entrance + and exit blobs, the measured line width, the centre line pixels, the + spawn points where the centre line leaves each entrance, the exit + points where it enters each exit, and the routes + as point lists, entrance to exit, smoothed and simplified. """ w, h = mask.w, mask.h shape = bytearray(1 if c != FREE else 0 for c in mask.cls) @@ -434,10 +476,7 @@ entrances = mask.blobs(ENTRANCE) exits = mask.blobs(EXIT) - # specks of colour from the soft edges are not entrances or exits - entrances = [b for b in entrances if b[3] >= 50] - exits = [b for b in exits if b[3] >= 50] - width = path_width(mask, sum(polyline_length(e[2]) for e in graph.edges.values())) + width = line_width(mask, sum(polyline_length(e[2]) for e in graph.edges.values())) terminals = [graph.nearest_end(b[0], b[1]) for b in entrances + exits] graph.prune(set(terminals), 0.8 * width) graph.contract(set(terminals), 0.75 * width) @@ -461,5 +500,8 @@ "entrances": entrances, "exits": exits, "width": width, + "centre": [p for e in graph.edges.values() for p in e[2]], + "spawns": [leave_point(graph, mask, s, ENTRANCE) for s in starts], + "exit_points": [leave_point(graph, mask, g, EXIT) for g in goals], "routes": routes, }
