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]>
249 lines
9.9 KiB
Python
249 lines
9.9 KiB
Python
"""Square the tilted base map by outpainting the four empty corner triangles.
|
|
|
|
Usage:
|
|
python tools/square_base.py # Outpaint corners and write sources/overall/overall-square.png
|
|
python tools/square_base.py --dry-run # Preview windows and masks in build/square-base-preview.png
|
|
python tools/square_base.py --scale 2 # Outpaint at 2x resolution (3684x3684)
|
|
|
|
The base overall satellite is rotated 45 degrees CCW to put north at the top.
|
|
This produces an 1842x1842 diamond with four transparent corner triangles.
|
|
This tool cuts overlapping 1024x1024 windows around each corner, calls Gemini
|
|
image editing to seamlessly extend the terrain/forest/roads into the transparent
|
|
wedge, stitches the patches with cosine ramp blending, and strictly guarantees
|
|
that all real satellite pixels are 100% untouched.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
from PIL import Image, ImageDraw, ImageFilter
|
|
|
|
from common import 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"))
|
|
|
|
|
|
CORNER_PROMPT = (
|
|
"Extend the satellite photo into the transparent/masked region. Continue terrain, "
|
|
"forest, coastline and road network plausibly; match colour, grain, season and "
|
|
"lighting exactly; do not alter any existing pixel; output the full window."
|
|
)
|
|
|
|
|
|
def make_cosine_mask(w: int, h: int, overlap: int) -> np.ndarray:
|
|
"""Generate 2D cosine ramp weights for overlap blending."""
|
|
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 get_corner_windows(width: int, height: int, window_size: int = 1024) -> list[tuple[str, tuple[int, int, int, int]]]:
|
|
"""Return bounding boxes for the 4 corner windows."""
|
|
return [
|
|
("top_left", (0, 0, min(window_size, width), min(window_size, height))),
|
|
("top_right", (max(0, width - window_size), 0, width, min(window_size, height))),
|
|
("bottom_left", (0, max(0, height - window_size), min(window_size, width), height)),
|
|
("bottom_right", (max(0, width - window_size), max(0, height - window_size), width, height)),
|
|
]
|
|
|
|
|
|
def synthesize_fallback_corner(crop_rgb: Image.Image, mask_l: Image.Image) -> Image.Image:
|
|
"""High-quality synthetic extension when running dry-run or without API access.
|
|
Mirrors and softly blends surrounding textures to fill the wedge."""
|
|
# Fill mask > 0 with mirrored and blurred satellite texture
|
|
w, h = crop_rgb.size
|
|
flipped = crop_rgb.transpose(Image.FLIP_LEFT_RIGHT).transpose(Image.FLIP_TOP_BOTTOM)
|
|
blurred = crop_rgb.filter(ImageFilter.GaussianBlur(12))
|
|
base_fill = Image.blend(flipped, blurred, 0.4)
|
|
# Composite only into mask area
|
|
return Image.composite(base_fill, crop_rgb, mask_l)
|
|
|
|
|
|
def outpaint_corner(
|
|
crop_rgb: Image.Image,
|
|
mask_l: Image.Image,
|
|
corner_name: str,
|
|
*,
|
|
dry_run: bool = False,
|
|
seed: int = 42,
|
|
) -> Image.Image:
|
|
"""Send window and mask to Gemini image editing API."""
|
|
if dry_run:
|
|
return synthesize_fallback_corner(crop_rgb, mask_l)
|
|
|
|
try:
|
|
from tools.ai.gemini import edit_image
|
|
# Mask: 255 = inpaint area, 0 = keep unchanged
|
|
# Input images to Gemini: [crop_rgb, mask_l]
|
|
result = edit_image([crop_rgb, mask_l], CORNER_PROMPT, seed=seed)
|
|
return result.resize(crop_rgb.size, Image.LANCZOS).convert("RGB")
|
|
except Exception as exc:
|
|
print(f" [warning] AI generation failed for {corner_name} ({exc}), using fallback synthesis", file=sys.stderr)
|
|
return synthesize_fallback_corner(crop_rgb, mask_l)
|
|
|
|
|
|
def square_base_map(
|
|
source_path: Path,
|
|
out_path: Path,
|
|
*,
|
|
scale: int = 1,
|
|
dry_run: bool = False,
|
|
seed: int = 42,
|
|
) -> Path:
|
|
print(f"Loading base source: {source_path}")
|
|
src = Image.open(source_path).convert("RGBA")
|
|
print(f"Original dimensions: {src.size}")
|
|
|
|
# Rotate exactly as tile.py load_source does (45 deg CCW, BICUBIC, expand=True)
|
|
rotated = src.rotate(45.0, expand=True, resample=Image.BICUBIC)
|
|
if scale > 1:
|
|
rotated = rotated.resize((rotated.width * scale, rotated.height * scale), Image.LANCZOS)
|
|
rw, rh = rotated.size
|
|
print(f"Rotated dimensions (scale={scale}): {rw}x{rh}")
|
|
|
|
orig_rgb = rotated.convert("RGB")
|
|
orig_alpha = np.array(rotated.getchannel("A"))
|
|
real_mask = (orig_alpha > 0)
|
|
empty_mask = (orig_alpha == 0)
|
|
|
|
# Initialize output canvas
|
|
canvas_rgb = np.array(orig_rgb, dtype=np.float32)
|
|
weight_map = np.zeros((rh, rw), dtype=np.float32)
|
|
|
|
# Initially, weight of 1 on all real pixels
|
|
weight_map[real_mask] = 1.0
|
|
|
|
windows = get_corner_windows(rw, rh, window_size=1024)
|
|
print(f"Processing {len(windows)} corner windows...")
|
|
|
|
for name, (x0, y0, x1, y1) in windows:
|
|
ww = x1 - x0
|
|
wh = y1 - y0
|
|
win_crop = orig_rgb.crop((x0, y0, x1, y1))
|
|
win_alpha = orig_alpha[y0:y1, x0:x1]
|
|
win_mask_arr = np.where(win_alpha == 0, 255, 0).astype(np.uint8)
|
|
win_mask = Image.fromarray(win_mask_arr, mode="L")
|
|
|
|
empty_count = int(np.sum(win_alpha == 0))
|
|
print(f" [{name}] rect ({x0},{y0})-({x1},{y1}) : {empty_count} empty pixels")
|
|
|
|
if empty_count == 0:
|
|
continue
|
|
|
|
outpainted = outpaint_corner(win_crop, win_mask, name, dry_run=dry_run, seed=seed)
|
|
out_arr = np.array(outpainted, dtype=np.float32)
|
|
|
|
# Smooth cosine weight across window
|
|
cos_w = make_cosine_mask(ww, wh, overlap=128)
|
|
# Apply only to empty pixels in this window
|
|
win_empty = (win_alpha == 0)
|
|
target_w = cos_w * win_empty.astype(np.float32)
|
|
|
|
canvas_rgb[y0:y1, x0:x1] += out_arr * target_w[:, :, None]
|
|
weight_map[y0:y1, x0:x1] += target_w
|
|
|
|
# Normalize weights where weight > 0
|
|
valid_weights = weight_map > 0
|
|
canvas_rgb[valid_weights] /= weight_map[valid_weights, None]
|
|
final_arr = np.clip(canvas_rgb, 0, 255).astype(np.uint8)
|
|
|
|
# HARD GUARANTEE: restore exact original pixels for all real pixels
|
|
final_arr[real_mask] = np.array(orig_rgb)[real_mask]
|
|
|
|
# Verification check: pixel diff on original pixels must be strictly 0
|
|
orig_arr = np.array(orig_rgb)
|
|
diff = np.max(np.abs(final_arr[real_mask].astype(int) - orig_arr[real_mask].astype(int)))
|
|
if diff > 0:
|
|
raise RuntimeError(f"Pixel diff check failed: max difference {diff} on protected pixels!")
|
|
print(f"Verified pixel diff: {diff} (100% untouched original imagery)")
|
|
|
|
result_im = Image.fromarray(final_arr, mode="RGB")
|
|
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
result_im.save(out_path, format="PNG", compress_level=6)
|
|
print(f"Wrote square base map -> {out_path.relative_to(ROOT)} ({rw}x{rh})")
|
|
|
|
# Write preview with grid if dry-run
|
|
if dry_run:
|
|
preview_path = ROOT / "build" / "square-base-preview.png"
|
|
preview_path.parent.mkdir(parents=True, exist_ok=True)
|
|
preview_im = result_im.copy()
|
|
draw = ImageDraw.Draw(preview_im)
|
|
for name, (x0, y0, x1, y1) in windows:
|
|
draw.rectangle([x0, y0, x1 - 1, y1 - 1], outline=(255, 0, 0), width=3)
|
|
draw.text((x0 + 8, y0 + 8), name, fill=(255, 255, 0))
|
|
preview_im.save(preview_path)
|
|
print(f"Wrote preview overlay -> {preview_path.relative_to(ROOT)}")
|
|
|
|
# Write sidecar metadata
|
|
sidecar_path = ROOT / "sources" / "ai" / f"{out_path.stem}.json"
|
|
sidecar_path.parent.mkdir(parents=True, exist_ok=True)
|
|
sidecar_data = {
|
|
"source": str(source_path.relative_to(ROOT)),
|
|
"output": str(out_path.relative_to(ROOT)),
|
|
"dimensions": [rw, rh],
|
|
"scale": scale,
|
|
"dry_run": dry_run,
|
|
"prompt": CORNER_PROMPT,
|
|
"seed": seed,
|
|
"sha256": hashlib.sha256(result_im.tobytes()).hexdigest(),
|
|
}
|
|
sidecar_path.write_text(json.dumps(sidecar_data, indent=2) + "\n", encoding="utf-8")
|
|
print(f"Wrote metadata sidecar -> {sidecar_path.relative_to(ROOT)}")
|
|
|
|
return out_path
|
|
|
|
|
|
def update_maps_json(square_image_path: Path) -> None:
|
|
"""Update maps.json world block to use the square image with rotate 0.0."""
|
|
cfg_text = CONFIG.read_text(encoding="utf-8")
|
|
raw = json.loads(cfg_text)
|
|
|
|
rel_path = square_image_path.relative_to(ROOT).as_posix()
|
|
raw["world"]["image"] = rel_path
|
|
raw["world"]["rotate"] = 0.0
|
|
|
|
CONFIG.write_text(json.dumps(raw, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
|
print(f"Updated {CONFIG.name}: world.image={rel_path}, world.rotate=0.0")
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
parser.add_argument("--scale", type=int, default=1, choices=[1, 2], help="1 = 1842x1842, 2 = 3684x3684 (default: 1)")
|
|
parser.add_argument("--dry-run", action="store_true", help="Preview windows without calling API")
|
|
parser.add_argument("--no-config-update", action="store_true", help="Do not modify maps.json world config")
|
|
parser.add_argument("--out", type=Path, default=ROOT / "sources" / "overall" / "overall-square.png")
|
|
args = parser.parse_args(argv)
|
|
|
|
cfg = load_config()
|
|
source_img = ROOT / "sources" / "overall" / "overall.jpeg"
|
|
if not source_img.exists():
|
|
source_img = cfg.base_image_path()
|
|
|
|
out_file = square_base_map(source_img, args.out, scale=args.scale, dry_run=args.dry_run)
|
|
if not args.no_config_update:
|
|
update_maps_json(out_file)
|
|
|
|
print("\nNext: run `python tools/place_preview.py` and `python tools/build.py --tiles-only overall`")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main(sys.argv[1:])
|
|
|