Make a fresh clone servable after `git lfs pull` alone, and rebuildable with `tools/build.py` without re-rendering unchanged PSDs: - Track build/ (rendered base PNGs, previews, world composites), web/tiles/, web/tiles-trimmed/, web/data/world.json and web/data/markers/. Large PNGs and the tile pyramids go through Git LFS (.gitattributes); JSON stays plain. - build.py: decide PSD re-export from build/<id>/base.stamp.json (PSD size, mtime, SHA-256 recorded at export time) instead of file mtimes, which are meaningless after an LFS checkout. Same size + new mtime hashes once and refreshes the stamp; --stamp-only writes stamps for existing base.pngs. - Ignore .DS_Store and .env files; track sources/**/*.jpg through LFS. Viewer: - Right-click (long-press) the map for a category menu that drops a draft marker under the pointer and enters marker edit mode for that map. - Marker editing moves out of the side panel into a box anchored next to the marker: Enter or a left click anywhere else saves, Esc cancels, Delete inside the box; drags save position plus the box contents. - Maps panel expands on hover, header click pins/unpins (status shown in the header), unpinned collapses 2 s after the pointer leaves; Overview is the first list entry instead of a separate button. Only the panel scrolls; the page never grows past the viewport. Hover tooltips render above markers. Also includes the pending source additions (overall square base, skirt textures, AI regeneration tooling and notes), service worker, Caddyfile and map config updates. Co-Authored-By: Claude Fable 5 <[email protected]>
254 lines
11 KiB
Python
254 lines
11 KiB
Python
"""Generate an AI terrain texture to dress a map's non-playable margin.
|
|
|
|
EXPERIMENTAL. Detail maps arrive with their own frame -- black bars, a sky
|
|
gradient, a vignette -- and that frame sits on the satellite base. The trim
|
|
polygon already fades it; a *skirt* replaces it: a terrain texture in the
|
|
style of the map's own art, tiled under the playable area and out to the
|
|
map's rectangle. tile.py bakes it into the trimmed pyramid (see
|
|
``render_trimmed_copy``), the original pyramid stays untouched.
|
|
|
|
python tools/skirt.py woods # vision -> prompt -> image
|
|
python tools/skirt.py woods --seed 11 # another roll of the dice
|
|
python tools/skirt.py woods --prompt "..." # your own prompt, skip vision
|
|
python tools/skirt.py woods --dry-run # show the prompt, call nothing
|
|
|
|
Needs the MiniMax CLI ``mmx`` logged in (``mmx auth status``). Writes
|
|
|
|
sources/skirts/<id>.jpg the texture (1536 x 1536)
|
|
sources/skirts/<id>.json prompt, seed, vision notes -- for reproducing
|
|
|
|
and adds a default ``skirt`` block to the map in maps.json if it has none.
|
|
Then ``python tools/build.py --trim-only <id>`` re-renders the trimmed tiles.
|
|
|
|
MiniMax image-01 is text-to-image only: there is no inpainting, so the
|
|
texture cannot continue roads or buildings across the edge. It can match
|
|
terrain type, palette and rendering style, which is what the frame problem
|
|
is mostly about.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from PIL import Image, ImageDraw
|
|
|
|
from common import BUILD, CONFIG, ROOT, find_map, load_config
|
|
|
|
Image.MAX_IMAGE_PIXELS = None
|
|
|
|
SKIRTS = ROOT / "sources" / "skirts"
|
|
TEXTURE_SIZE = 1536
|
|
|
|
STYLE_SUFFIX = (
|
|
" Strictly orthographic top-down aerial view straight down (nadir), uniform "
|
|
"scale across the whole image, flat even overcast lighting with soft short "
|
|
"shadows, no perspective, no horizon, no vignette, no buildings, no roads, "
|
|
"no vehicles, no people, no text, no border, features evenly and uniformly "
|
|
"distributed over the entire image with no large-scale gradient, clearing "
|
|
"or focal point, seamless repeating texture, painterly-photoreal game map "
|
|
"rendering, natural daylight colours."
|
|
)
|
|
|
|
VISION_PROMPT = (
|
|
"These are crops from just inside the playable edge of a top-down video "
|
|
"game map. Write ONE text-to-image prompt (max 50 words, no preamble, no "
|
|
"quotes) for a seamless top-down aerial terrain texture that would continue "
|
|
"this ground naturally: name the vegetation/ground types with rough "
|
|
"proportions, the colour palette (e.g. 'olive green, ochre grass, grey-brown "
|
|
"earth'), and the rendering style. Ignore roads, buildings, water, objects "
|
|
"and map furniture."
|
|
)
|
|
|
|
DEFAULT_SKIRT = {
|
|
"image": None, # filled in
|
|
"scale": 0.6, # texture pixels -> map pixels
|
|
"featherIn": 80, # soft cut at the playable polygon, in map px
|
|
"fadeOut": 0.12, # fraction of the short side over which the skirt fades at the rect edge
|
|
"matchColours": True,
|
|
"soften": 1.5, # blur (map px) so the backdrop recedes and compresses well
|
|
}
|
|
|
|
|
|
def run(cmd: list[str], dry_run: bool) -> subprocess.CompletedProcess | None:
|
|
print(" $", " ".join(cmd if len(" ".join(cmd)) < 300 else cmd[:3] + ["…"]))
|
|
if dry_run:
|
|
return None
|
|
result = subprocess.run(cmd, capture_output=True, text=True)
|
|
if result.returncode != 0:
|
|
sys.stderr.write(result.stdout + result.stderr)
|
|
raise SystemExit(f"command failed ({result.returncode}): {cmd[0]} {cmd[1]} {cmd[2]}")
|
|
return result
|
|
|
|
|
|
def playable_polygon(m: dict, size: tuple[int, int]) -> list[tuple[int, int]] | None:
|
|
trim = m.get("trim")
|
|
points = trim.get("points", []) if isinstance(trim, dict) else []
|
|
if len(points) < 3:
|
|
return None
|
|
w, h = size
|
|
return [(round(float(x) * (w - 1)), round(float(y) * (h - 1))) for x, y in points]
|
|
|
|
|
|
def sample_sheet(m: dict, img: Image.Image, out: Path, crops: int = 6, crop_px: int = 384) -> Path:
|
|
"""A contact sheet of crops taken just inside the playable edge.
|
|
|
|
The VLM sees what the ground looks like where the skirt has to meet it,
|
|
not the middle of the map.
|
|
"""
|
|
w, h = img.size
|
|
polygon = playable_polygon(m, img.size)
|
|
mask = Image.new("L", img.size, 0)
|
|
if polygon:
|
|
ImageDraw.Draw(mask).polygon(polygon, fill=255)
|
|
else:
|
|
ImageDraw.Draw(mask).rectangle((0, 0, w - 1, h - 1), fill=255)
|
|
# Shrink the playable mask to find an inner band; sample along it.
|
|
from PIL import ImageFilter
|
|
|
|
inner = mask.resize((w // 8, h // 8), Image.BOX).filter(ImageFilter.MinFilter(9)).resize((w, h), Image.NEAREST)
|
|
band = Image.eval(mask, lambda v: v) ; band.paste(0, (0, 0), inner) # mask minus inner = edge band
|
|
bbox = band.getbbox() or (0, 0, w, h)
|
|
# Walk the band's bounding box perimeter and pick crop centres that lie in the band.
|
|
candidates = []
|
|
x0, y0, x1, y1 = bbox
|
|
steps = 40
|
|
for i in range(steps):
|
|
t = i / steps
|
|
for (cx, cy) in (
|
|
(x0 + (x1 - x0) * t, y0 + crop_px), (x0 + (x1 - x0) * t, y1 - crop_px),
|
|
(x0 + crop_px, y0 + (y1 - y0) * t), (x1 - crop_px, y0 + (y1 - y0) * t),
|
|
):
|
|
cx, cy = int(cx), int(cy)
|
|
if 0 <= cx < w and 0 <= cy < h and band.getpixel((cx, cy)) > 0 and mask.getpixel((cx, cy)) > 0:
|
|
candidates.append((cx, cy))
|
|
if not candidates:
|
|
candidates = [(w // 2, h // 2)]
|
|
chosen = [candidates[int(i * len(candidates) / crops)] for i in range(min(crops, len(candidates)))]
|
|
cols = 3
|
|
rows = (len(chosen) + cols - 1) // cols
|
|
sheet = Image.new("RGB", (cols * crop_px, rows * crop_px), (0, 0, 0))
|
|
for i, (cx, cy) in enumerate(chosen):
|
|
box = (max(0, cx - crop_px // 2), max(0, cy - crop_px // 2))
|
|
crop = img.crop((box[0], box[1], box[0] + crop_px, box[1] + crop_px)).convert("RGB")
|
|
sheet.paste(crop, ((i % cols) * crop_px, (i // cols) * crop_px))
|
|
sheet.thumbnail((1152, 1152))
|
|
sheet.save(out, quality=90)
|
|
return out
|
|
|
|
|
|
def vision_prompt(sheet: Path, dry_run: bool) -> str:
|
|
result = run(["mmx", "vision", "describe", "--non-interactive", "--quiet", "--output", "json",
|
|
"--image", str(sheet), "--prompt", VISION_PROMPT], dry_run)
|
|
if result is None:
|
|
return "(vision output)"
|
|
raw = result.stdout.strip()
|
|
try:
|
|
content = json.loads(raw).get("content", raw)
|
|
except json.JSONDecodeError:
|
|
content = raw
|
|
# One line, no quotes, no "Prompt:" preamble.
|
|
content = re.sub(r"^\W*prompt\W*", "", content.strip(), flags=re.IGNORECASE)
|
|
return " ".join(content.replace('"', "").split())
|
|
|
|
|
|
def generate(prompt: str, seed: int, out: Path, dry_run: bool) -> None:
|
|
out.parent.mkdir(parents=True, exist_ok=True)
|
|
run(["mmx", "image", "generate", "--non-interactive", "--quiet",
|
|
"--prompt", prompt, "--width", str(TEXTURE_SIZE), "--height", str(TEXTURE_SIZE),
|
|
"--seed", str(seed), "--out", str(out)], dry_run)
|
|
|
|
|
|
def generate_gemini(prompt: str, seed: int, out: Path, dry_run: bool) -> None:
|
|
out.parent.mkdir(parents=True, exist_ok=True)
|
|
if dry_run:
|
|
print(" (dry-run: would call tools.ai.gemini.generate)")
|
|
return
|
|
from tools.ai.gemini import generate as gemini_gen
|
|
img = gemini_gen(prompt, seed=seed)
|
|
img = img.resize((TEXTURE_SIZE, TEXTURE_SIZE), Image.LANCZOS)
|
|
img.convert("RGB").save(out, quality=92)
|
|
|
|
|
|
def ensure_config(map_id: str, image_rel: str) -> bool:
|
|
"""Add a default skirt block to maps.json if the map has none. Returns True if written."""
|
|
raw = json.loads(CONFIG.read_text(encoding="utf-8"))
|
|
for m in raw["maps"]:
|
|
if m["id"] == map_id:
|
|
if m.get("skirt"):
|
|
return False
|
|
m["skirt"] = {**DEFAULT_SKIRT, "image": image_rel}
|
|
break
|
|
CONFIG.write_text(json.dumps(raw, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
return True
|
|
|
|
|
|
def main(argv: list[str]) -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
parser.add_argument("map_id")
|
|
parser.add_argument("--seed", type=int, default=1)
|
|
parser.add_argument("--prompt", help="use this prompt verbatim (plus the style suffix); skips vision")
|
|
parser.add_argument("--no-suffix", action="store_true", help="do not append the orthographic style suffix")
|
|
parser.add_argument("--backend", choices=["minimax", "gemini"], default="gemini",
|
|
help="AI backend to generate textures (default: gemini)")
|
|
parser.add_argument("--dry-run", action="store_true")
|
|
args = parser.parse_args(argv)
|
|
|
|
if args.backend == "minimax" and shutil.which("mmx") is None and not args.dry_run:
|
|
raise SystemExit("mmx not found on PATH -- install the MiniMax CLI and run `mmx auth login`")
|
|
|
|
|
|
cfg = load_config()
|
|
m = find_map(cfg, args.map_id)
|
|
src = BUILD / m["id"] / "base.png"
|
|
if not src.exists():
|
|
raise SystemExit(f"{src.relative_to(ROOT)} missing -- run tools/build.py first")
|
|
img = Image.open(src).convert("RGBA")
|
|
if m.get("crop"):
|
|
img = img.crop(tuple(m["crop"]))
|
|
|
|
SKIRTS.mkdir(parents=True, exist_ok=True)
|
|
sheet = SKIRTS / f"{m['id']}.samples.jpg"
|
|
print(f"[{m['id']}] sampling the playable edge -> {sheet.relative_to(ROOT)}")
|
|
sample_sheet(m, img, sheet)
|
|
|
|
if args.prompt:
|
|
base_prompt = args.prompt.strip()
|
|
notes = None
|
|
else:
|
|
print(f"[{m['id']}] asking mmx vision what the ground looks like")
|
|
base_prompt = vision_prompt(sheet, args.dry_run)
|
|
notes = base_prompt
|
|
prompt = base_prompt if args.no_suffix else base_prompt + STYLE_SUFFIX
|
|
print(f"[{m['id']}] prompt: {prompt}\n")
|
|
|
|
out = SKIRTS / f"{m['id']}.jpg"
|
|
print(f"[{m['id']}] generating {TEXTURE_SIZE}x{TEXTURE_SIZE} texture ({args.backend}, seed {args.seed}) -> {out.relative_to(ROOT)}")
|
|
if args.backend == "gemini":
|
|
generate_gemini(prompt, args.seed, out, args.dry_run)
|
|
else:
|
|
generate(prompt, args.seed, out, args.dry_run)
|
|
if args.dry_run:
|
|
return
|
|
|
|
(SKIRTS / f"{m['id']}.json").write_text(json.dumps({
|
|
"map": m["id"], "seed": args.seed, "prompt": prompt, "visionNotes": notes,
|
|
"size": TEXTURE_SIZE, "tool": f"skirt.py ({args.backend})",
|
|
}, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
|
|
rel = out.relative_to(ROOT).as_posix()
|
|
if ensure_config(m["id"], rel):
|
|
print(f"[{m['id']}] added a default `skirt` block to maps.json")
|
|
else:
|
|
print(f"[{m['id']}] maps.json already has a `skirt` block; left as is")
|
|
print(f"\nnext: python tools/build.py --trim-only {m['id']}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main(sys.argv[1:])
|