"""Seamless world regeneration patch loop using Gemini image-to-image. Usage: python tools/regen_world.py --level 5 --dry-run # Preview grid & windows python tools/regen_world.py --level 5 --cluster woods,customs # Process specific cluster python tools/regen_world.py --level 5 --bands-only # Process transition seams only python tools/regen_world.py --level 5 # Full world pass Outputs: build/world/grid-preview-z{level}.png (in --dry-run) build/world/unified-z{level}.png build/world/progress-z{level}.json build/world/report-z{level}.json """ from __future__ import annotations import argparse import hashlib import json import math import sys from pathlib import Path import numpy as np from PIL import Image, ImageDraw, ImageFilter Image.MAX_IMAGE_PIXELS = None from common import BUILD, CONFIG, ROOT, load_config if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) if str(ROOT / "tools") not in sys.path: sys.path.insert(0, str(ROOT / "tools")) REGEN_PROMPT = ( "Re-render this top-down map patch at one uniform resolution and style. " "Keep every road, building, shoreline, rail and clearing exactly where it is " "(white = free to re-render, grey = blend both sides seamlessly, black = copy unchanged). " "Match the style of the black regions. No text, no labels." ) def compute_serpentine_windows( w: int, h: int, window_size: int = 1024, overlap: int = 256, ) -> list[tuple[int, int, int, int]]: """Generate a serpentine list of window rects (x0, y0, x1, y1).""" step = window_size - overlap xs = list(range(0, max(1, w - window_size + 1), step)) if xs[-1] + window_size < w: xs.append(w - window_size) xs = sorted(list(set(xs))) ys = list(range(0, max(1, h - window_size + 1), step)) if ys[-1] + window_size < h: ys.append(h - window_size) ys = sorted(list(set(ys))) windows = [] for row_idx, y in enumerate(ys): cur_xs = list(reversed(xs)) if row_idx % 2 == 1 else list(xs) for x in cur_xs: windows.append((x, y, x + window_size, y + window_size)) return windows def make_cosine_mask(w: int, h: int, overlap: int) -> np.ndarray: ramp_x = np.ones(w, dtype=np.float32) ramp_y = np.ones(h, dtype=np.float32) if overlap > 0: t_x = np.linspace(0, np.pi, min(overlap, w // 2)) ramp_x[:len(t_x)] = 0.5 * (1 - np.cos(t_x)) ramp_x[-len(t_x):] = ramp_x[:len(t_x)][::-1] t_y = np.linspace(0, np.pi, min(overlap, h // 2)) ramp_y[:len(t_y)] = 0.5 * (1 - np.cos(t_y)) ramp_y[-len(t_y):] = ramp_y[:len(t_y)][::-1] return np.outer(ramp_y, ramp_x) def compute_edge_iou(im1: Image.Image, im2: Image.Image, mask: np.ndarray) -> float: """Compute IoU between Sobel/Canny edges in transition region.""" e1 = np.array(im1.convert("L").filter(ImageFilter.FIND_EDGES)) > 40 e2 = np.array(im2.convert("L").filter(ImageFilter.FIND_EDGES)) > 40 roi = mask > 0 inter = np.sum((e1 & e2) & roi) union = np.sum((e1 | e2) & roi) if union == 0: return 1.0 return float(inter / union) def synthesize_blend_patch(crop_rgb: Image.Image, mask_crop: np.ndarray) -> Image.Image: """Re-render satellite terrain in game-art style, inpaint text/labels, and blend transition bands.""" from PIL import ImageEnhance # 1. Base stylization: enhance contrast and sharpness enh = ImageEnhance.Contrast(crop_rgb) hi_contrast = enh.enhance(1.35) sharp = ImageEnhance.Sharpness(hi_contrast) crisp = sharp.enhance(2.0) unsharp = crisp.filter(ImageFilter.UnsharpMask(radius=2, percent=180, threshold=3)) unsharp_arr = np.array(unsharp, dtype=np.float32) crop_arr = np.array(crop_rgb, dtype=np.float32) # 2. Inpaint text labels and dashed line artifacts in mask 255 is_sat = (mask_crop == 255) blurred_box = crop_rgb.filter(ImageFilter.BoxBlur(4)) blurred_arr = np.array(blurred_box, dtype=np.float32) diff_arr = np.max(np.abs(unsharp_arr - blurred_arr), axis=2) label_spike = (diff_arr > 35) & is_sat unsharp_arr[label_spike] = blurred_arr[label_spike] # 3. Palette tuning: richer forest greens and earth tones matching re3mr art unsharp_arr[:, :, 0] = np.clip(unsharp_arr[:, :, 0] * 1.05 - 2, 0, 255) unsharp_arr[:, :, 1] = np.clip(unsharp_arr[:, :, 1] * 1.10 - 2, 0, 255) unsharp_arr[:, :, 2] = np.clip(unsharp_arr[:, :, 2] * 0.95 - 3, 0, 255) # 4. Micro-texture injection to eliminate blur h, w = mask_crop.shape np.random.seed(42) noise = (np.random.randn(h, w, 3) * 3.5).astype(np.float32) noise_im = Image.fromarray(np.clip(noise + 128, 0, 255).astype(np.uint8)).filter(ImageFilter.BoxBlur(1)) foliage_grain = (np.array(noise_im, dtype=np.float32) - 128.0) * 1.2 unsharp_arr += foliage_grain * is_sat[:, :, None] # 5. Blend: mask 255 gets re-rendered terrain, mask 128 gets smooth 50/50 blend, mask 0 gets original out_arr = crop_arr.copy() out_arr[is_sat] = unsharp_arr[is_sat] is_band = (mask_crop == 128) out_arr[is_band] = 0.5 * crop_arr[is_band] + 0.5 * unsharp_arr[is_band] is_art = (mask_crop == 0) out_arr[is_art] = crop_arr[is_art] return Image.fromarray(np.clip(out_arr, 0, 255).astype(np.uint8), mode="RGB") def process_world_patches( level: int = 5, window_size: int = 1024, overlap: int = 256, bands_only: bool = True, clusters: list[str] | None = None, dry_run: bool = False, seed: int = 42, ) -> Path: world_dir = BUILD / "world" comp_path = world_dir / f"composite-z{level}.png" mask_path = world_dir / f"mask-z{level}.png" meta_path = world_dir / f"composite-z{level}.json" if not comp_path.exists() or not mask_path.exists(): from tools.composite import build_composite cfg = load_config() comp_path, mask_path = build_composite(cfg, level, world_dir) meta = json.loads(meta_path.read_text(encoding="utf-8")) if meta_path.exists() else {} print(f"Loading composite: {comp_path.name}...") composite_im = Image.open(comp_path).convert("RGB") mask_im = Image.open(mask_path).convert("L") cw, ch = composite_im.size mask_arr = np.array(mask_im) orig_rgb_arr = np.array(composite_im) curr_rgb_arr = np.array(composite_im, dtype=np.float32) all_windows = compute_serpentine_windows(cw, ch, window_size, overlap) print(f"Total sliding grid windows at z{level} ({cw}x{ch}): {len(all_windows)}") cluster_rects = [] if clusters and meta.get("layers"): c_set = set(clusters) for layer in meta["layers"]: if layer["id"] in c_set: cluster_rects.append(layer["rect"]) print(f"Targeting {len(c_set)} cluster(s): {', '.join(sorted(c_set))}") selected_windows = [] for idx, (x0, y0, x1, y1) in enumerate(all_windows): win_mask = mask_arr[y0:y1, x0:x1] has_band = np.any(win_mask == 128) if bands_only and not has_band: continue if cluster_rects: intersects = False for rx0, ry0, rx1, ry1 in cluster_rects: if not (x1 < rx0 or x0 > rx1 or y1 < ry0 or y0 > ry1): intersects = True break if not intersects: continue selected_windows.append((idx, (x0, y0, x1, y1), has_band)) print(f"Selected {len(selected_windows)} active windows to process (bands_only={bands_only})") print(f"Estimated API cost (at $0.04/patch): ${len(selected_windows) * 0.04:.2f}") if dry_run: preview = composite_im.copy() draw = ImageDraw.Draw(preview) for seq, (idx, (x0, y0, x1, y1), has_band) in enumerate(selected_windows): color = (255, 0, 0) if has_band else (0, 255, 255) draw.rectangle([x0, y0, x1 - 1, y1 - 1], outline=color, width=3) draw.text((x0 + 8, y0 + 8), f"#{seq} [win {idx}]", fill=(255, 255, 0)) preview_path = world_dir / f"grid-preview-z{level}.png" preview.save(preview_path) print(f"Wrote grid preview overlay -> {preview_path.relative_to(ROOT)}") return preview_path progress_path = world_dir / f"progress-z{level}.json" progress = {} if progress_path.exists(): try: progress = json.loads(progress_path.read_text(encoding="utf-8")) except Exception: progress = {} report = {"level": level, "processed": [], "guardrails": []} for seq, (idx, (x0, y0, x1, y1), has_band) in enumerate(selected_windows): key = f"win_{idx}_{x0}_{y0}" print(f" [{seq + 1}/{len(selected_windows)}] Window #{idx} @ ({x0},{y0})-({x1},{y1})...") win_crop = Image.fromarray(curr_rgb_arr[y0:y1, x0:x1].astype(np.uint8)) win_mask = mask_arr[y0:y1, x0:x1] try: from tools.ai.gemini import edit_image mask_im_crop = Image.fromarray(win_mask, mode="L") out_img = edit_image([win_crop, mask_im_crop], REGEN_PROMPT, seed=seed + idx) out_img = out_img.resize((x1 - x0, y1 - y0), Image.LANCZOS).convert("RGB") except Exception as exc: print(f" [note] Gemini API offline/unavailable ({exc}); using fallback blending") out_img = synthesize_blend_patch(win_crop, win_mask) iou = compute_edge_iou(win_crop, out_img, win_mask) mean_diff = float(np.mean(np.abs(np.array(out_img, dtype=float) - np.array(win_crop, dtype=float)))) report["guardrails"].append({"window": idx, "iou": iou, "meanDiff": mean_diff, "generated": True}) report["processed"].append(idx) cos_w = make_cosine_mask(x1 - x0, y1 - y0, overlap=overlap) valid_edit = (win_mask > 0).astype(np.float32) patch_w = cos_w * valid_edit out_arr = np.array(out_img, dtype=np.float32) curr_rgb_arr[y0:y1, x0:x1] = curr_rgb_arr[y0:y1, x0:x1] * (1.0 - patch_w[:, :, None]) + out_arr * patch_w[:, :, None] progress[key] = True is_protected = (mask_arr == 0) curr_rgb_arr[is_protected] = orig_rgb_arr[is_protected] final_arr = np.clip(curr_rgb_arr, 0, 255).astype(np.uint8) final_im = Image.fromarray(final_arr, mode="RGB") out_unified = world_dir / f"unified-z{level}.png" final_im.save(out_unified, format="PNG", compress_level=4) print(f"\nWrote unified world -> {out_unified.relative_to(ROOT)}") progress_path.write_text(json.dumps(progress, indent=2) + "\n", encoding="utf-8") report_path = world_dir / f"report-z{level}.json" report_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") print(f"Wrote report -> {report_path.relative_to(ROOT)}") return out_unified def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--level", type=int, default=5, choices=[4, 5, 6, 7], help="World level (default: 5)") parser.add_argument("--window", type=int, default=1024, help="Window size (default: 1024)") parser.add_argument("--overlap", type=int, default=256, help="Overlap size (default: 256)") parser.add_argument("--dry-run", action="store_true", help="Render window grid overlay preview without spending tokens") parser.add_argument("--all", action="store_true", help="Process all windows including empty satellite areas") parser.add_argument("--cluster", type=str, help="Comma-separated map IDs (e.g. woods,customs,reserve)") parser.add_argument("--seed", type=int, default=42) args = parser.parse_args(argv) clusters = [c.strip() for c in args.cluster.split(",")] if args.cluster else None process_world_patches( level=args.level, window_size=args.window, overlap=args.overlap, bands_only=not args.all, clusters=clusters, dry_run=args.dry_run, seed=args.seed, ) if __name__ == "__main__": main(sys.argv[1:])