wobblyhead hg > minor_monsters
view tools/masks.py @ 8:2c4fed8baed9
art update, persistent sound setting, tower selling as double action
| author | ark |
|---|---|
| date | 2026-10-19 13:37 +0200 |
| parents | 5492efd60e2c |
| children | 53f015966118 |
line wrap: on
line source
""" 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. """ import math from collections import deque from PIL import Image, ImageDraw FREE, PATH, ENTRANCE, EXIT = 0, 1, 2, 3 # 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.""" 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 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 self.cls = cls def count(self, kind): return self.cls.count(kind) def blobs(self, kind): """ return the connected areas of one class, largest first, as a list of (centre x, centre y, radius, pixel count). radius is that of a disc with the same area. """ w, h, cls = self.w, self.h, self.cls seen = bytearray(w * h) out = [] for start in range(w * h): if cls[start] != kind or seen[start]: continue seen[start] = 1 queue = deque([start]) sx = sy = n = 0 while queue: i = queue.popleft() x, y = i % w, i // w sx += x sy += y n += 1 for dx, dy in NEIGHBOURS: nx, ny = x + dx, y + dy if 0 <= nx < w and 0 <= ny < h: k = ny * w + nx if cls[k] == kind and not seen[k]: seen[k] = 1 queue.append(k) out.append((sx / n, sy / n, math.sqrt(n / math.pi), n)) out.sort(key=lambda b: -b[3]) return out def grown(self, kinds, radius): """ return an L image, 255 on pixels of the given classes and on every pixel within radius of one. drawn as discs around the edge pixels of the area, which is the same as a distance test. """ w, h, cls = self.w, self.h, self.cls im = Image.new("L", (w, h), 0) draw = ImageDraw.Draw(im) inside = bytes(255 if c in kinds else 0 for c in cls) im.paste(Image.frombytes("L", (w, h), inside)) for y in range(h): row = y * w for x in range(w): if not inside[row + x]: continue edge = (x == 0 or x == w - 1 or y == 0 or y == h - 1 or not inside[row + x - 1] or not inside[row + x + 1] or not inside[row + x - w] or not inside[row + x + w]) if edge: draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill=255) return im def placement_grid(mask, p): """ 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. """ 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() edge = p["edge_distance"] w, h = mask.w, mask.h cols, rows = w // cell, h // cell out = [] for cy in range(rows): y = cy * cell + cell // 2 for cx in range(cols): x = cx * cell + cell // 2 i = y * w + x ok = (near[i] and not blocked[i] and edge <= x <= w - edge and edge <= y <= h - edge) out.append("1" if ok else "0") return cols, rows, "".join(out) def thin(shape, w, h): """ reduce a 0/1 bytearray shape to a one pixel wide centre line (zhang-suen thinning). the shape must not touch the image border. only pixels next to removed ones are re-examined, which keeps the pure python loop fast. returns the thinned bytearray. """ img = bytearray(shape) offs = [dy * w + dx for dx, dy in NEIGHBOURS] def touches_background(i): return any(not img[i + o] for o in offs) cand = {i for i in range(w * h) if img[i] and touches_background(i)} while True: removed_any = False for step in (0, 1): remove = [] for i in cand: if not img[i]: continue p = [img[i + o] for o in offs] b = sum(p) if b < 2 or b > 6: continue a = sum(1 for k in range(8) if not p[k] and p[(k + 1) % 8]) if a != 1: continue n, e, s, wst = p[0], p[2], p[4], p[6] if step == 0: if n and e and s or e and s and wst: continue else: if n and e and wst or n and s and wst: continue remove.append(i) if remove: removed_any = True nxt = set() for i in remove: img[i] = 0 for i in remove: for o in offs: if img[i + o]: nxt.add(i + o) cand = (cand | nxt) - set(remove) if not removed_any: return img class Graph: """ the centre line as a graph. nodes are junctions and line ends, edges the pixel chains between them. nodes: id -> (x, y) edges: id -> [node a, node b, [(x, y), ...] from a to b] """ def __init__(self, skel, w): self.w = w pix = {i for i, v in enumerate(skel) if v} offs = [dy * w + dx for dx, dy in NEIGHBOURS] def nbrs(i): return [i + o for o in offs if i + o in pix] # line pixels have exactly two neighbours, all others belong to nodes nodepix = {i for i in pix if len(nbrs(i)) != 2} node_of = {} self.nodes = {} for i in nodepix: if i in node_of: continue nid = len(self.nodes) members = [] queue = deque([i]) node_of[i] = nid while queue: j = queue.popleft() members.append(j) for k in nbrs(j): if k in nodepix and k not in node_of: node_of[k] = nid queue.append(k) self.nodes[nid] = (sum(m % w for m in members) / len(members), sum(m // w for m in members) / len(members)) self.edges = {} seen = set() for i in nodepix: for j in nbrs(i): if j in nodepix or j in seen: continue chain = [i, j] seen.add(j) prev, cur = i, j while True: nxt = [k for k in nbrs(cur) if k != prev] if not nxt: break k = nxt[0] chain.append(k) if k in nodepix: break seen.add(k) prev, cur = cur, k if chain[-1] not in nodepix: continue a, b = node_of[i], node_of[chain[-1]] if a == b and len(chain) < 8: continue self.add_edge(a, b, [(c % w, c // w) for c in chain]) def add_edge(self, a, b, pts): eid = max(self.edges, default=-1) + 1 self.edges[eid] = [a, b, pts] return eid def degree(self, n): return sum((e[0] == n) + (e[1] == n) for e in self.edges.values()) def incident(self, n): return [eid for eid, e in self.edges.items() if n in (e[0], e[1])] def nearest_end(self, x, y): """return the node of degree 1 nearest to a point.""" ends = [n for n in self.nodes if self.degree(n) == 1] return min(ends, key=lambda n: math.dist(self.nodes[n], (x, y))) def prune(self, keep, min_len): """drop dead ends shorter than min_len, except at nodes in keep.""" changed = True while changed: changed = False for n in list(self.nodes): if n in keep or self.degree(n) != 1: continue eid = self.incident(n)[0] if polyline_length(self.edges[eid][2]) < min_len: del self.edges[eid] del self.nodes[n] changed = True changed |= self.merge() def contract(self, keep, min_len): """ join junctions closer than min_len along an edge into one node, except nodes in keep. thinning splits a wide crossing into several nearby junctions; a loop attached to one of them could otherwise not be walked without visiting a junction twice. """ changed = True while changed: changed = False # shortest first, so a chain of nearby junctions joins around its middle for eid, (a, b, pts) in sorted(self.edges.items(), key=lambda e: polyline_length(e[1][2])): if a == b or a in keep or b in keep or polyline_length(pts) >= min_len: continue del self.edges[eid] # reattach the edges of b to a, extended by the joining pixels for f in self.edges.values(): if f[0] == b: f[0], f[2] = a, pts[:-1] + f[2] if f[1] == b: f[1], f[2] = a, f[2] + pts[::-1][1:] del self.nodes[b] changed = True break def merge(self): """join the two edges at every node of degree 2. returns True on change.""" changed = False for n in list(self.nodes): inc = self.incident(n) if len(inc) != 2 or inc[0] == inc[1]: continue e1, e2 = (self.edges[i] for i in inc) p1 = e1[2] if e1[1] == n else e1[2][::-1] a = e1[0] if e1[1] == n else e1[1] p2 = e2[2] if e2[0] == n else e2[2][::-1] b = e2[1] if e2[0] == n else e2[0] if a == n or b == n: continue del self.edges[inc[0]], self.edges[inc[1]] del self.nodes[n] self.add_edge(a, b, p1 + p2[1:]) changed = True return changed def paths(self, start, goal): """ list every route from start to goal that visits no node twice, as a list of (points, key) pairs. a loop that leaves a node and comes back to it (a self-loop edge) may be walked once, in either direction; key names the edges taken without the loop directions, so the two directions of the same route share a key. """ out = [] def walk(n, visited, used, pts, key): if n == goal: out.append((pts, tuple(key))) return for eid in self.incident(n): a, b, epts = self.edges[eid] if a == b: if eid in used: continue for seg in (epts, epts[::-1]): walk(n, visited, used | {eid}, pts + seg[1:], key + [("loop", eid)]) continue if a == n: m, seg = b, epts else: m, seg = a, epts[::-1] if m in visited: continue walk(m, visited | {m}, used, pts + seg[1:], key + [eid]) walk(start, {start}, frozenset(), [self.nodes[start]], []) return out def polyline_length(pts): return sum(math.dist(pts[i], pts[i + 1]) for i in range(len(pts) - 1)) def turning(pts): """sum of direction changes along a polyline, in degrees.""" total = 0.0 for i in range(1, len(pts) - 1): a1 = math.atan2(pts[i][1] - pts[i - 1][1], pts[i][0] - pts[i - 1][0]) a2 = math.atan2(pts[i + 1][1] - pts[i][1], pts[i + 1][0] - pts[i][0]) d = (a2 - a1 + math.pi) % (2 * math.pi) - math.pi total += abs(d) return math.degrees(total) def resample(pts, step): """return points spaced step apart along the polyline, ends kept.""" out = [pts[0]] carry = 0.0 for i in range(len(pts) - 1): (x0, y0), (x1, y1) = pts[i], pts[i + 1] seg = math.dist(pts[i], pts[i + 1]) d = step - carry while d <= seg: t = d / seg out.append((x0 + (x1 - x0) * t, y0 + (y1 - y0) * t)) d += step carry = seg - (d - step) if math.dist(out[-1], pts[-1]) > step * 0.25: out.append(pts[-1]) else: out[-1] = pts[-1] return out def smooth(pts, half): """moving average over 2 * half + 1 points; the window shrinks at the ends.""" n = len(pts) out = [] for i in range(n): k = min(half, i, n - 1 - i) xs = pts[i - k:i + k + 1] out.append((sum(p[0] for p in xs) / len(xs), sum(p[1] for p in xs) / len(xs))) return out def simplify(pts, tol): """ramer-douglas-peucker: drop points closer than tol to the line.""" if len(pts) < 3: return list(pts) (x0, y0), (x1, y1) = pts[0], pts[-1] dx, dy = x1 - x0, y1 - y0 norm = math.hypot(dx, dy) or 1.0 best, idx = 0.0, 0 for i in range(1, len(pts) - 1): d = abs(dy * (pts[i][0] - x0) - dx * (pts[i][1] - y0)) / norm if d > best: best, idx = d, i if best <= tol: return [pts[0], pts[-1]] 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.""" return mask.count(PATH) / skel_len if skel_len else 0.0 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. """ w, h = mask.w, mask.h shape = bytearray(1 if c != FREE else 0 for c in mask.cls) # keep a free border so the thinning never reads past the image for x in range(w): shape[x] = shape[(h - 1) * w + x] = 0 for y in range(h): shape[y * w] = shape[y * w + w - 1] = 0 skel = thin(shape, w, h) graph = Graph(skel, w) 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())) 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) graph.merge() starts = terminals[:len(entrances)] goals = terminals[len(entrances):] routes = [] for s in starts: for g in goals: # of the two directions around a loop, keep the one that turns less best = {} for raw, key in graph.paths(s, g): pts = resample(raw, 1.0) pts = simplify(smooth(smooth(pts, smooth_half), smooth_half), tol) if key not in best or turning(pts) < turning(best[key]): best[key] = pts routes.extend(best.values()) return { "graph": graph, "entrances": entrances, "exits": exits, "width": width, "routes": routes, }
