#!/usr/bin/env python3 """Weltpalette — drei Vorschläge mit Vergleichsbildern. Kein Modell, kein pixelize: die vorhandenen Assets werden auf je eine Palette abgebildet (OKLab-Nächster-Nachbar), damit man sieht, ob die Palette den bestehenden Satz tragen kann. python3 art/tools/weltpalette.py [ZIELORDNER] # Default: art/prep/weltpalette Erzeugt je Palette ein Palettenbild (als `--palette` für pixelize brauchbar), einen Stadt-Screen, eine Materialprobe, einen Gesamtvergleich und Messwerte (mittlerer/maximaler OKLab-Abstand, genutzte Farben). """ from __future__ import annotations import sys from pathlib import Path from math import cbrt from PIL import Image, ImageDraw ART = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ART / "tools")) import font8 # noqa: E402 import map_mock # noqa: E402 import ui # noqa: E402 FINAL = ART / "final" W, H = 640, 360 # --------------------------------------------------------------- Farbraum ---- M1 = ((0.4122214708, 0.5363325363, 0.0514459929), (0.2119034982, 0.6806995451, 0.1073969566), (0.0883024619, 0.2817188376, 0.6299787005)) M2 = ((0.2104542553, 0.7936177850, -0.0040720468), (1.9779984951, -2.4285922050, 0.4505937099), (0.0259040371, 0.7827717662, -0.8086757660)) def _lin(c: int) -> float: c /= 255.0 return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 def _srgb(c: float) -> int: c = 0.0 if c < 0.0 else (1.0 if c > 1.0 else c) c = 12.92 * c if c <= 0.0031308 else 1.055 * c ** (1 / 2.4) - 0.055 return int(round(c * 255)) def hex2rgb(h: str) -> tuple[int, int, int]: h = h.lstrip("#") return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16) def rgb2hex(c) -> str: return "#%02x%02x%02x" % tuple(int(round(v)) for v in c) def to_oklab(c) -> tuple[float, float, float]: r, g, b = (_lin(int(v)) for v in c) l, m, s = (sum(M1[i][j] * v for j, v in enumerate((r, g, b))) for i in range(3)) l, m, s = cbrt(l), cbrt(m), cbrt(s) return tuple(sum(M2[i][j] * v for j, v in enumerate((l, m, s))) for i in range(3)) def oklab_to_srgb(lab) -> tuple[int, int, int]: L, a, b = lab l_ = L + 0.3963377774 * a + 0.2158037573 * b m_ = L - 0.1055613458 * a - 0.0638541728 * b s_ = L - 0.0894841775 * a - 1.2914855480 * b l, m, s = l_ ** 3, m_ ** 3, s_ ** 3 return (_srgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s), _srgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s), _srgb(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s)) def ramp(a: str, b: str, n: int) -> list[str]: """n Farben von a nach b, interpoliert in OKLab (gleichmäßige Helligkeit).""" la, lb = to_oklab(hex2rgb(a)), to_oklab(hex2rgb(b)) out = [] for i in range(n): t = i / (n - 1) out.append(rgb2hex(oklab_to_srgb(tuple(la[k] + (lb[k] - la[k]) * t for k in range(3))))) return out # ---------------------------------------------------------------- Paletten --- # W1: Richtung Pool of Radiance. 16 Farben, EGA-nahe Wertesprünge: kalte # Blauschattens, gesättigte Mittel, kein Zwischenton für Verläufe. W1 = [ "#08090f", # Tinte / Umriss "#141d2e", # Nachtblau, tiefster Schatten "#22344a", # Schiefer (Wasser dunkel) "#3a5570", # Stahlblau (Wasser) "#6d7f8a", # Blaugrau (Metall, kühler Stein) "#2e2e2a", # Stein, dunkel "#75756c", # Stein, mittel "#a8a89c", # Stein, hell "#2b2419", # dunkles Braun (Fachwerk, Balken) "#46422f", # Khaki (Fachwerk-Zwischenton) "#6b4520", # Erde "#a8865a", # Sand/Tan (Straße, Holz hell) "#123023", # Wald, tief "#2f6d38", # Gras "#6b8f3a", # Gras, beleuchtet "#9bb35a", # trockenes Gras / Olive "#c8912f", # Gold "#f2c06a", # Flamme, Fackellicht "#8f3325", # Rost (Blut, Ziegel) "#e8ddbd", # Knochen / Text ] # W2: Richtung Neverwinter Nights 1. 48 Farben in Rampen: viele Stufen pro # Farbfamilie, entsättigte Mitten, tiefe kühle Schatten, warme Lichtinseln. W2 = (ramp("#0b0e13", "#6d7983", 6) # Stein + ramp("#6f6557", "#eee3c9", 5) # Knochen + ramp("#0c1a11", "#4f8249", 6) # Wald + ramp("#414f28", "#b8c07a", 5) # Moos + ramp("#211407", "#a2713f", 6) # Erde + ramp("#6d4a12", "#f8dd93", 6) # Gold + ramp("#0d1823", "#3a6f8d", 5) # Wasser + ramp("#34100d", "#b0402c", 4) # Rost + ramp("#8fa3a8", "#e6eef0", 3) # kalter Akzent + ["#ffd38a", "#2a2033"]) # Flamme, Violet-Schatten # W3: eigener Vorschlag — Tageslicht, aus dem gemessenen Ist-Zustand # fortgeschrieben (häufigste Farben der 58 fertigen Assets, sortiert). W3 = [ "#000000", # Umriss (die Figuren sind so umrandet) "#14100d", # Tinte "#241c15", # dunkles Braun "#3a2f27", # Panelbraun (UI-Anker) "#4c4033", # Braun "#6b5744", # helles Braun "#7c674e", # Rahmenlinie / Holz (UI-Anker) "#8c7355", # Sand "#b0a082", # Knochen "#d8c8a8", # Creme "#f2e4ba", # helles Creme (Text) "#3d3d35", # Stein dunkel "#5d5f54", # Stein "#7a7f6c", # Stein hell "#3b4954", # Blaugrau, Schatten (Wasser tief) "#4c5e6a", # Blaugrau (Dach, Ferrum) "#21292e", # Nachtblau (Wasser, tiefster Schatten) "#35502f", # Grün tief "#4a6b3a", # Grün "#677f3f", # Grün hell "#6c7242", # Olive dunkel (UI-Anker) "#7c8a45", # Olive "#92a15e", # Olive hell "#9bb45e", # Gras (häufigste Kachelfarbe) "#b4bf78", # Olive blass "#cddb97", # Gras, hell "#7a5a2e", # Holz "#a3763c", # Holz hell "#b2925f", # Erdstraße (häufigste Bodenfarbe) "#d8b468", # Gold "#963a2e", # Rot (Blut, Ziegel) ] PALETTES = [ dict(key="w1", name="W1 — Pool of Radiance", count=20, colors=W1, note="20 Farben, harte Wertesprünge, kalte Schatten — EGA-Nachbarschaft"), dict(key="w2", name="W2 — Neverwinter Nights", count=48, colors=W2, note="48 Farben in Rampen, dunkel und warm — 2002er-3D-Stimmung"), dict(key="w3", name="W3 — Tageslicht", count=len(W3), colors=W3, note="aus dem Ist-Zustand fortgeschrieben — hell, wenig Umbau"), ] BAYER4 = [[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]] # --------------------------------------------------------------- Abbildung --- def nn_distance(palette) -> float: labs = [to_oklab(hex2rgb(c)) for c in palette] ds = [] for i, a in enumerate(labs): ds.append(min(sum((a[k] - b[k]) ** 2 for k in range(3)) ** 0.5 for j, b in enumerate(labs) if j != i)) ds.sort() return ds[len(ds) // 2] def mapper(palette, dither: float = 0.0): """Bild -> Palette. dither = Stärke des Bayer-4-Offsets (0 = flach).""" rgb = [hex2rgb(c) for c in palette] labs = [to_oklab(c) for c in rgb] amp = dither * nn_distance(palette) cache: dict[tuple, int] = {} def best(r, g, b, bi): key = (r >> 3, g >> 3, b >> 3, bi) hit = cache.get(key) if hit is not None: return hit L, A, B = to_oklab((r, g, b)) if amp: o = ((BAYER4[(bi // 4) % 4][bi % 4] + 0.5) / 16 - 0.5) * amp L, A, B = L + o, A + o * 0.5, B + o * 0.5 i = min(range(len(labs)), key=lambda k: (labs[k][0] - L) ** 2 + (labs[k][1] - A) ** 2 + (labs[k][2] - B) ** 2) cache[key] = i return i def run(im: Image.Image) -> tuple[Image.Image, list[int]]: src = im.convert("RGBA") out = Image.new("RGB", src.size) sp, dp = src.load(), out.load() used = [0] * len(palette) for y in range(src.height): for x in range(src.width): r, g, b, a = sp[x, y] if a < 255: r = (r * a + 20 * (255 - a)) // 255 g = (g * a + 18 * (255 - a)) // 255 b = (b * a + 14 * (255 - a)) // 255 i = best(r, g, b, (y % 4) * 4 + x % 4) used[i] += 1 dp[x, y] = rgb[i] return out, used return run def delta_e(a: Image.Image, b: Image.Image) -> tuple[float, float]: """Mittlerer und maximaler OKLab-Abstand (×100) zwischen zwei Bildern.""" pa, pb = a.convert("RGBA").load(), b.convert("RGB").load() total, worst = 0.0, 0.0 n = a.width * a.height for y in range(a.height): for x in range(a.width): ca, cb = pa[x, y][:3], pb[x, y] d = sum((u - v) ** 2 for u, v in zip(to_oklab(ca), to_oklab(cb))) ** 0.5 * 100 total += d worst = max(worst, d) return total / n, worst # ------------------------------------------------------------------ Motive --- def load1(rel: str, size: tuple[int, int]) -> Image.Image: return Image.open(FINAL / rel).convert("RGBA").resize(size, Image.NEAREST) def town_screen() -> Image.Image: return map_mock.frame(map_mock.screen_town(), "WACHE", ["Valyria zahlt in Ferrum, nicht in Gold.", "Was wollt Ihr in Garana?"]) def dungeon_screen() -> Image.Image: return map_mock.frame(map_mock.screen_dungeon(), "ERZAEHLER", ["Die Luft riecht nach nassem Stein.", "Seit Jahren war hier niemand."]) def material_probe() -> Image.Image: im = Image.new("RGBA", (W, 172), (138, 138, 138, 255)) x = 6 for rel in ("tile_grasland", "tile_steppe", "tile_wald", "tile_huegel", "tile_gebirge", "battle_gras", "battle_erde", "battle_stein"): im.alpha_composite(load1(f"Terrain/{rel}_32px.png", (32, 32)), (x, 6)) x += 34 for rel in ("tile_wand_stein", "tile_dach_fachwerk"): im.alpha_composite(load1(f"Terrain/{rel}_32px.png", (32, 32)), (x, 6)) x += 34 x += 6 for rel in ("fass", "tisch", "brunnen", "wagen", "tor", "fackel"): im.alpha_composite(load1(f"Objects/objekt_{rel}_32px.png", (32, 32)), (x, 6)) x += 34 x = 6 for name in ("dorfbewohner", "dorfbewohnerin", "wache", "haendler", "druide", "bettler"): im.alpha_composite(load1(f"NPCs/nsc_{name}_32px.png", (32, 40)), (x, 44)) x += 34 x += 10 for name in ("wolf", "goblin", "orc", "skelett"): im.alpha_composite(load1(f"Creatures/monster_{name}_96px.png", (48, 48)), (x, 40)) x += 52 x += 6 for name in ("krieger", "magierin", "elfin", "zwerg", "halbling", "gelehrter"): im.alpha_composite(load1(f"Players/portrait_{name}_32px.png", (32, 32)), (x, 46)) x += 34 d = ImageDraw.Draw(im) for i, (a, b) in enumerate((("#6b4520", "#e8ddbd"), ("#123023", "#c8912f"), ("#22344a", "#8fa5a5"), ("#8f3325", "#e8ddbd"))): x0 = 6 + i * 158 for x in range(x0, x0 + 154): t = (x - x0) / 153 la, lb = to_oklab(hex2rgb(a)), to_oklab(hex2rgb(b)) c = oklab_to_srgb(tuple(la[k] + (lb[k] - la[k]) * t for k in range(3))) d.line((x, 96, x, 103), fill=c) d.rectangle((6, 110, W - 7, 140), fill=ui.PANEL) d.rectangle((6, 110, W - 7, 140), outline=ui.INK) d.rectangle((7, 111, W - 8, 139), outline=ui.LINE) font8.draw_text(d, 12, 116, "Der Regen fällt auf Garana.", ui.CREAM) font8.draw_text(d, 12, 128, "Valyria zahlt in Ferrum, nicht in Gold.", ui.CREAM_D) d.rectangle((6, 146, W - 7, 166), fill=ui.INK) font8.draw_text(d, 12, 150, "36 px Dialogtext / 8x10-Font / Kontrast bei 1x", ui.GOLD) return im # ------------------------------------------------------------------ Ausgabe -- def strip(palette, width: int = W, block: int = 16) -> Image.Image: n = len(palette) bw = min(block, width // n) im = Image.new("RGB", (bw * n, 10), (0, 0, 0)) d = ImageDraw.Draw(im) for i, c in enumerate(palette): d.rectangle((i * bw, 0, (i + 1) * bw - 1, 9), fill=hex2rgb(c)) return im def sheet(rows, path: Path) -> None: """rows = [(titel, farben, bild), ...] untereinander, 1x und 2x.""" pad = 8 h = sum(16 + 10 + pad + im.height + pad for _, _, im in rows) out = Image.new("RGB", (W, h), (18, 16, 14)) d = ImageDraw.Draw(out) y = 0 for title, colors, im in rows: d.rectangle((0, y, W - 1, y + 15), fill=(24, 21, 18)) font8.draw_text(d, 6, y + 3, title, (232, 224, 200)) out.paste(strip(colors), (0, y + 16)) out.paste(im.convert("RGB"), (0, y + 26 + pad)) y += 16 + 10 + pad + im.height + pad out.save(path) out.resize((out.width * 2, out.height * 2), Image.NEAREST).save( path.with_name(path.stem.replace("_1x", "") + "_2x.png")) def install(palette, path: Path) -> None: """Schreibt die Palette als Streifen nach final/ und prüft sie exakt.""" path.parent.mkdir(parents=True, exist_ok=True) strip(palette, block=24).save(path) got = {c for _, c in Image.open(path).convert("RGB").getcolors(999)} want = {hex2rgb(c) for c in palette} if got != want: raise SystemExit(f"{path}: {len(got)} Farben im Bild, {len(want)} erwartet") print(f"geschrieben: {path.relative_to(ART)} " f"({len(want)} Farben, exakt, {len(got)} geprüft)") def main() -> int: rest = sys.argv[1:] flags = [a for a in rest if a.startswith("--")] pos = [a for a in rest if not a.startswith("--")] out = Path(pos[0]) if pos else ART / "prep" / "weltpalette" out.mkdir(parents=True, exist_ok=True) town, probe = town_screen(), material_probe() dungeon = dungeon_screen() probe.save(out / "_probe_original_640x172.png") rows_town, rows_probe, rows_dungeon, report = [], [], [], [] for p in PALETTES: run = mapper(p["colors"]) t2, used_t = run(town) p2, used_p = run(probe) d2, _ = run(dungeon) de_t = delta_e(town, t2) de_p = delta_e(probe, p2) used = len([c for c in used_p if c]) report.append((p, de_t, de_p, used)) base = p["key"] + "_" + p["name"].split("— ")[1].lower().replace(" ", "") t2.resize((W * 2, H * 2), Image.NEAREST).save(out / f"_{base}_stadt_1280x720.png") d2.resize((W * 2, H * 2), Image.NEAREST).save(out / f"_{base}_dungeon_1280x720.png") rows_town.append((f"{p['name']} — {p['count']} Farben — " f"Abweichung mittel {de_t[0]:.1f} / max {de_t[1]:.0f}", p["colors"], t2)) rows_dungeon.append((f"{p['name']} — {p['count']} Farben", p["colors"], d2)) rows_probe.append((f"{p['name']} — {used}/{p['count']} Farben im Bild", p["colors"], p2)) strip(p["colors"], block=24).save(out / f"_palette_{base}.png") sheet(rows_town, out / "_vergleich_stadt_1x.png") sheet(rows_dungeon, out / "_vergleich_dungeon_1x.png") sheet(rows_probe, out / "_vergleich_material_1x.png") # W1 zusätzlich mit Bayer-4-Dithering: die 16 Farben sind ohne Dither # hart; so hätte Pool of Radiance es gemacht. w1_d, _ = mapper(PALETTES[0]["colors"], dither=1.0)(town) w1_d.resize((W * 2, H * 2), Image.NEAREST).save( out / "_w1_poolofradiance_stadt_dither_1280x720.png") print(f"Ziel: {out}") print(f"{'Palette':28} {'Abw. Stadt':>11} {'Abw. Material':>14} {'genutzt':>8}") for p, dt, dp, used in report: print(f"{p['name']:28} {dt[0]:6.1f}/{dt[1]:<3.0f} " f"{dp[0]:8.1f}/{dp[1]:<3.0f} {used:4}/{p['count']}") which = next((f.split("=", 1)[1] for f in flags if f.startswith("--install=")), None) if "--install" in flags or which: chosen = next(p for p in PALETTES if p["key"] == (which or "w3")) install(chosen["colors"], FINAL / "Terrain" / "_palette_world.png") return 0 if __name__ == "__main__": sys.exit(main())