#!/usr/bin/env python3 """figures.py: the map, charts and cover for "The Goths". Usage: figures.py --cache DIR [--out DIR] Needs: Pillow, rsvg-convert, the Noto fonts (Serif and Sans Gothic) The map is written as an SVG fragment that the goth-map shortcode inlines into the page, so that it follows the light and dark theme: it carries class names only, the colours are in assets/css/widgets.css. """ from __future__ import annotations import argparse import base64 import io import json import math import subprocess from pathlib import Path from PIL import Image, ImageEnhance HERE = Path(__file__).resolve().parent INK = "#f6eff8" MUTED = "#a99ab4" FAINT = "#5b4d6b" NIGHT = "#0f0c17" ROSE = "#f45ba4" VIOLET = "#a78bfa" BLUE = "#60a5fa" GOLD = "#f2c45a" TEAL = "#5eead4" FONT = "Noto Serif" GOTHIC = "Noto Sans Gothic" def escape(content: str) -> str: return content.replace("&", "&").replace("<", "<").replace('"', """) # -------------------------------------------------------------------------------------- # SVG helpers (after content/posts/nebra-sky-disc/figures.py) # -------------------------------------------------------------------------------------- class Svg: def __init__(self, width: int, height: int): self.width, self.height = width, height self.parts = [ f'' '' f'' "" '' ] def add(self, markup: str) -> None: self.parts.append(markup) def rect(self, x, y, w, h, fill="none", stroke="none", width=1.5, radius=14, opacity=1.0) -> None: self.add( f'' ) def path(self, d, stroke=FAINT, width=2.0, dash="") -> None: extra = f' stroke-dasharray="{dash}"' if dash else "" self.add(f'') def text(self, x, y, content, size=24, fill=INK, anchor="middle", family=FONT, extra="") -> None: self.add( f'{escape(content)}' ) def image(self, picture: Image.Image, x, y, w, h, opacity=1.0) -> None: buffer = io.BytesIO() picture.save(buffer, "JPEG", quality=92) data = base64.b64encode(buffer.getvalue()).decode() self.add( f'' ) def save(self, path: Path) -> None: self.add("") subprocess.run( ["rsvg-convert", "--unlimited", "-o", str(path)], input="".join(self.parts).encode(), check=True ) print(f" {path.name}") # -------------------------------------------------------------------------------------- # The map: a Lambert conformal conic of Europe, from Natural Earth (public domain) # -------------------------------------------------------------------------------------- MAP_W, MAP_H = 1200, 860 WEST, EAST, SOUTH, NORTH = -22.0, 62.0, 25.0, 66.0 # clipping box, wider than the picture LON0, LAT0, PHI1, PHI2 = 18.0, 47.0, 40.0, 56.0 RIVERS = {"Danube", "Donau", "Rhine", "Rhein", "Rhin", "Vistula", "Dnipro", "Dnepre", "Dniester", "Don", "Volga", "Elbe", "Po", "Rhône", "Ebro"} # fmt: skip def _conic(lon: float, lat: float) -> tuple[float, float]: n = math.log(math.cos(math.radians(PHI1)) / math.cos(math.radians(PHI2))) / math.log( math.tan(math.pi / 4 + math.radians(PHI2) / 2) / math.tan(math.pi / 4 + math.radians(PHI1) / 2) ) f = math.cos(math.radians(PHI1)) * math.tan(math.pi / 4 + math.radians(PHI1) / 2) ** n / n rho = f / math.tan(math.pi / 4 + math.radians(lat) / 2) ** n rho0 = f / math.tan(math.pi / 4 + math.radians(LAT0) / 2) ** n theta = n * math.radians(lon - LON0) return rho * math.sin(theta), rho0 - rho * math.cos(theta) def _frame(): """Scale and offset that fit the area the story covers into the picture.""" points = [_conic(lon, lat) for lon, lat in ((-9.5, 36), (-6, 34.6), (48.5, 49), (14, 59.4), (44, 40), (-9, 44))] xs, ys = [p[0] for p in points], [p[1] for p in points] scale = min((MAP_W - 40) / (max(xs) - min(xs)), (MAP_H - 30) / (max(ys) - min(ys))) return scale, MAP_W / 2 - scale * (max(xs) + min(xs)) / 2, MAP_H / 2 + scale * (max(ys) + min(ys)) / 2 SCALE, DX, DY = _frame() def project(lon: float, lat: float) -> tuple[float, float]: x, y = _conic(lon, lat) return DX + SCALE * x, DY - SCALE * y def clip_ring(ring: list) -> list: """Sutherland-Hodgman against the longitude and latitude box.""" for axis, limit, keep_above in ((0, WEST, True), (0, EAST, False), (1, SOUTH, True), (1, NORTH, False)): inside = (lambda p: p[axis] >= limit) if keep_above else (lambda p: p[axis] <= limit) out = [] for a, b in zip(ring[-1:] + ring[:-1], ring): if inside(a) != inside(b): t = (limit - a[axis]) / (b[axis] - a[axis]) out.append((a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1]))) if inside(b): out.append((b[0], b[1])) ring = out if not ring: break return ring def thin(points: list, step: float) -> list: kept = points[:1] for p in points[1:-1]: if math.dist(p, kept[-1]) >= step: kept.append(p) return kept + points[-1:] def polyline(points: list) -> str: return "M" + "L".join(f"{x:.1f} {y:.1f}" for x, y in points) def smooth(points: list) -> str: """A Catmull-Rom curve through the waypoints.""" d = f"M{points[0][0]:.1f} {points[0][1]:.1f}" for i in range(len(points) - 1): p0, p1, p2 = points[max(i - 1, 0)], points[i], points[i + 1] p3 = points[min(i + 2, len(points) - 1)] c1 = (p1[0] + (p2[0] - p0[0]) / 6, p1[1] + (p2[1] - p0[1]) / 6) c2 = (p2[0] - (p3[0] - p1[0]) / 6, p2[1] - (p3[1] - p1[1]) / 6) d += f"C{c1[0]:.1f} {c1[1]:.1f} {c2[0]:.1f} {c2[1]:.1f} {p2[0]:.1f} {p2[1]:.1f}" return d def arrow_head(points: list, size=17.0) -> str: (x0, y0), (x1, y1) = points[-2], points[-1] angle = math.atan2(y1 - y0, x1 - x0) left = (x1 - size * math.cos(angle - 0.45), y1 - size * math.sin(angle - 0.45)) right = (x1 - size * math.cos(angle + 0.45), y1 - size * math.sin(angle + 0.45)) return polyline([(x1, y1), left, right]) + "Z" def polygons(geometry: dict) -> list: if geometry["type"] == "Polygon": return [geometry["coordinates"]] return geometry["coordinates"] def land_path(cache: Path, name: str) -> str: d = [] for feature in json.loads((cache / name).read_text())["features"]: for polygon in polygons(feature["geometry"]): for ring in polygon: ring = clip_ring([tuple(p[:2]) for p in ring]) if len(ring) < 4: continue points = thin([project(*p) for p in ring], 1.6) xs, ys = [p[0] for p in points], [p[1] for p in points] if len(points) > 3 and (max(xs) - min(xs)) * (max(ys) - min(ys)) > 12: d.append(polyline(points) + "Z") return "".join(d) def river_path(cache: Path) -> str: d = [] for feature in json.loads((cache / "rivers.geojson").read_text())["features"]: if feature["properties"].get("name") not in RIVERS: continue geometry = feature["geometry"] lines = [geometry["coordinates"]] if geometry["type"] == "LineString" else geometry["coordinates"] for line in lines: # "Don" and "Po" also name rivers far outside the map if all(WEST < p[0] < EAST and SOUTH < p[1] < NORTH for p in line): d.append(polyline(thin([project(*p[:2]) for p in line], 2.0))) return "".join(d) def fig_map(cache: Path, steps: list, out: Path) -> None: parts = [ f'', f'', f'', f'', f'', ] for number, step in enumerate(steps, 1): parts.append(f'') for kind, key in (("own", "routes"), ("foe", "foes")): for route in step.get(key, []): points = [project(*p) for p in route] length = ' pathLength="1"' if kind == "own" else "" parts.append(f'') parts.append(f'') for place in step["places"]: x, y = project(*place["at"]) flip = place.get("left", False) or x > MAP_W - 230 if place.get("label_only"): parts.append(f'{escape(place["name"])}') continue parts.append(f'') anchor = ' text-anchor="end"' if flip else "" parts.append( f'' f"{escape(place['name'])}" ) # the step's number, at the end of its first path: this is what links map and list without JavaScript first = (step.get("routes") or step.get("foes"))[0] x, y = project(*first[-1]) dx, dy = step.get("badge", (0, 20)) parts.append( f'' f'{number}' ) parts.append("") (out / "goths-map.svg").write_text("\n".join(parts) + "\n") print(" goths-map.svg") # -------------------------------------------------------------------------------------- # Charts # -------------------------------------------------------------------------------------- def box(svg: Svg, cx, y, name, note="", colour=VIOLET, w=190, h=62) -> None: svg.rect(cx - w / 2, y, w, h, fill="#1a1426", stroke=colour, width=2) svg.text(cx, y + (27 if note else 39), name, 22) if note: svg.text(cx, y + 49, note, 15, MUTED) def fig_amals(out: Path) -> None: """The line of the Amals as Jordanes gives it (Getica 79-80).""" svg = Svg(1200, 1180) svg.text(600, 58, "The family tree of the Amals", 40) svg.text(600, 94, "as Jordanes tells it, about AD 551: the top of the tree is legend", 22, MUTED) trunk = [("Gapt", "Gaut?", GOLD), ("Hulmul", "", GOLD), ("Augis", "", GOLD), ("Amal", "names the house", GOLD), ("Hisarnis", "", VIOLET), ("Ostrogotha", "", VIOLET), ("Hunuil", "", VIOLET), ("Athal", "", VIOLET), ("Achiulf", "", VIOLET)] # fmt: skip y = 130 for name, note, colour in trunk[:5]: box(svg, 330, y, name, note, colour) if name != "Hisarnis": svg.path(f"M330 {y + 62}v24") y += 86 svg.path("M425 505H480V161H775") y = 130 for name, note, colour in trunk[5:]: box(svg, 870, y, name, note, colour) svg.path(f"M870 {y + 62}v24") y += 86 # Achiulf's two sons that matter here svg.path("M870 474V486M600 486H930M600 486v18M930 486v18") box(svg, 930, 504, "Ermanaric", "in history: d. c. 376", BLUE, 210) box(svg, 600, 504, "Vultuulf", "", VIOLET) y = 590 for name in ("Valaravans", "Vinitharius", "Vandalarius"): svg.path(f"M600 {y - 24}v24") box(svg, 600, y, name) y += 86 svg.path("M600 824V836M300 836H900M300 836v18M600 836v18M900 836v18") box(svg, 300, 854, "Valamir", "fought for Attila", BLUE, 210) box(svg, 600, 854, "Thiudimir", "", BLUE, 210) box(svg, 900, 854, "Vidimir", "", BLUE, 210) svg.path("M600 916v24") box(svg, 600, 940, "Theodoric", "the Great, d. 526", ROSE, 240) svg.path("M600 1002v24") box(svg, 600, 1026, "Amalasuintha", "queen, d. 535", ROSE, 240) svg.path("M720 1057H800") box(svg, 920, 1026, "Athalaric", "her son, d. 534", ROSE, 240) for k, (colour, text) in enumerate(((GOLD, "legendary ancestors"), (VIOLET, "known from Jordanes"), (BLUE, "also in other sources"), (ROSE, "rulers of Italy"))): # fmt: skip x = 170 + k * 270 svg.rect(x, 1128, 22, 22, stroke=colour, width=3, radius=5) svg.text(x + 34, 1146, text, 19, MUTED, "start") svg.save(out / "goths-amals.png") def fig_battle(out: Path) -> None: """Who stood against whom in 451.""" svg = Svg(1200, 760) svg.text(600, 56, "The Catalaunian Plains, AD 451", 40) svg.text(600, 92, "Goths, Franks and Burgundians stood on both sides", 22, MUTED) left = [("Romans", "Flavius Aëtius", MUTED), ("Visigoths", "Theodoric I and Thorismund", ROSE), ("Alans", "Sangiban", MUTED), ("Franks", "part of them", TEAL), ("Burgundians", "of Savoy", GOLD)] # fmt: skip right = [("Huns", "Attila", MUTED), ("Ostrogoths", "Valamir", ROSE), ("Gepids", "Ardaric", MUTED), ("Franks", "from east of the Rhine", TEAL), ("Burgundians", "part of them", GOLD), ("and others", "Heruli, Scirians and more", MUTED)] # fmt: skip for cx, title, host, colour in ((300, "With Aëtius", left, BLUE), (900, "With Attila", right, VIOLET)): svg.text(cx, 150, title, 30, colour) for i, (name, who, edge) in enumerate(host): box(svg, cx, 175 + i * 86, name, who, edge, 400, 70) svg.path("M600 150V690", FAINT, 2, "3 10") svg.rect(556, 372, 88, 56, fill=NIGHT, stroke=GOLD, width=2, radius=28) svg.text(600, 411, "vs", 30, GOLD) svg.text(600, 735, "After the list in the German article on the battle; troop numbers in ancient sources are not credible.", 18, MUTED) svg.save(out / "goths-battle.png") def fig_alphabet(letters: list, out: Path) -> None: svg = Svg(1200, 944) svg.text(600, 56, "The Gothic alphabet", 40) svg.text(600, 92, "letter, Latin transliteration, value as a number", 22, MUTED) for i, item in enumerate(letters): col, row = i % 9, i // 9 x, y = 34 + col * 128, 126 + row * 258 numeral = item["latin"] is None svg.rect(x, y, 112, 236, fill="#1a1426", stroke=FAINT if numeral else VIOLET) svg.text(x + 56, y + 100, item["letter"], 82, GOLD if not numeral else MUTED, family=GOTHIC) svg.text(x + 56, y + 168, item["latin"] or "–", 34, INK) svg.text(x + 56, y + 213, str(item["value"]), 24, MUTED) svg.text(600, 920, "𐍁 (90) and 𐍊 (900) stand for numbers only.", 20, MUTED, family=f"{FONT}, {GOTHIC}") svg.save(out / "goths-alphabet.png") def fig_cover(cache: Path, out: Path) -> None: """Luminais's river crossing, cropped to the shape of a preview image.""" painting = Image.open(cache / "luminais.jpg").convert("RGB") w, h = painting.size height = round(w * 630 / 1200) top = round((h - height) * 0.42) painting = painting.crop((0, top, w, top + height)).resize((1200, 630), Image.LANCZOS) painting = ImageEnhance.Color(painting).enhance(1.15) svg = Svg(1200, 630) svg.image(painting, 0, 0, 1200, 630) svg.save(out / "goths-cover.png") def main() -> None: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--cache", type=Path, required=True, help="folder with the downloads of build.sh") parser.add_argument("--out", type=Path, default=HERE) args = parser.parse_args() steps = json.loads((HERE / "goths-map.json").read_text()) letters = json.loads((HERE / "gothic-letters.json").read_text()) args.out.mkdir(parents=True, exist_ok=True) fig_map(args.cache, steps, args.out) fig_amals(args.out) fig_battle(args.out) fig_alphabet(letters, args.out) fig_cover(args.cache, args.out) if __name__ == "__main__": main()