Maps with an "aligned" skirt paste their surroundings from build/world/unified-z6.png (z5/composite fallbacks), so Lighthouse's trimmed tiles still showed the AI-invented peninsula and the diamond seam west of the lighthouse island after overall-square.png was fixed. tools/sea_corner.py now accepts --image for a composite at another scale (masks scaled from the rotated source, feather from the image's own pixels, no full-size mgrid planes, no PNG optimize pass on 217 Mpx) and was applied to all four composites with a sampled sea colour. Lighthouse trimmed tiles rebuilt. Co-Authored-By: Claude Fable 5 <[email protected]>
218 lines
11 KiB
Python
218 lines
11 KiB
Python
"""Fill outpainted corner triangles of the square base map with flat sea colour.
|
|
|
|
python tools/sea_corner.py # bottom_left (the open-sea corner), flat #121818
|
|
python tools/sea_corner.py bottom_left bottom_right # several corners
|
|
python tools/sea_corner.py --color sample # per-corner median of the sea next to it
|
|
python tools/sea_corner.py --dry-run # write build/sea-corner-preview.png only
|
|
python tools/sea_corner.py --image build/world/unified-z6.png --color sample
|
|
# same corner on a world composite (skirts)
|
|
|
|
tools/square_base.py rotates sources/overall/overall.jpeg by 45 degrees and
|
|
outpaints the four empty corner triangles with AI imagery. But the source is
|
|
a feathered "cropped map" lying on a uniform dark sea background (its whole
|
|
left, bottom and right margins and most of the top are flat, median #121818),
|
|
so the invented coastline in the open-sea bottom-left corner is wrong. This
|
|
replaces a corner with one flat colour (default: bottom_left). The corner region
|
|
is exactly the rotated source's alpha == 0 area in that quadrant. The source's
|
|
own flat margin just inside the diamond is a little brighter than the fill in
|
|
places, which would draw the diamond outline, so --feather (default 96 px)
|
|
eases flat-background pixels next to a filled corner toward the fill colour;
|
|
textured map content is left alone (its hard edge against the sea is what
|
|
"sea outside the map" means). Real pixels are re-read from the rotated source
|
|
so the tool is idempotent. Re-run after regenerating overall-square.png, then
|
|
retile the base:
|
|
|
|
rm -rf web/tiles/overall && python tools/build.py overall
|
|
|
|
Maps with an "aligned" skirt (tile.py render_skirt) paste their surroundings
|
|
from build/world/unified-z6.png (or the z5/composite fallbacks), so the same
|
|
corner has to be filled there too or the skirt re-imports the invented land:
|
|
pass --image for each composite; masks are scaled from the rotated source and
|
|
the feather then blends the image's own pixels (not idempotent, run once).
|
|
Rebuild the trimmed tiles of every skirted map that touches the corner
|
|
afterwards, e.g. rm -rf web/tiles-trimmed/lighthouse && python tools/build.py
|
|
lighthouse --trim-only.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
from PIL import Image, ImageFilter
|
|
|
|
from common import CONFIG, ROOT
|
|
|
|
Image.MAX_IMAGE_PIXELS = None # the z6 world composites are 14736 x 14736
|
|
|
|
CORNERS = ("top_left", "top_right", "bottom_left", "bottom_right")
|
|
|
|
|
|
def corner_masks(source: Path, rotate: float, size: tuple[int, int], corners=CORNERS):
|
|
"""(rotated source RGB, its alpha, {corner: empty-triangle mask}, {corner: distance map}).
|
|
|
|
The distance map gives, for every pixel, its distance in px to the corner
|
|
triangle (0 inside it); the triangle's edge is a 45-degree line, so this
|
|
is just the offset along the diagonal axis.
|
|
"""
|
|
rotated = Image.open(source).convert("RGBA").rotate(rotate, expand=True, resample=Image.BICUBIC)
|
|
same_size = rotated.size == size
|
|
if not same_size:
|
|
ratio = size[0] / rotated.width
|
|
if abs(size[1] / rotated.height - ratio) > 1e-3:
|
|
raise SystemExit(f"rotated source is {rotated.size}, image is {size}: not the same "
|
|
"aspect; use the --source/--rotate square_base.py used")
|
|
print(f"image is {ratio:.3f}x the rotated source; scaling the corner masks to match")
|
|
rgb = np.array(rotated.convert("RGB")) if same_size else None
|
|
alpha_img = rotated.getchannel("A")
|
|
if not same_size:
|
|
# Nearest keeps the edge crisp; a fully opaque/transparent split is all we need.
|
|
alpha_img = alpha_img.resize(size, Image.NEAREST)
|
|
alpha = np.array(alpha_img)
|
|
h, w = alpha.shape
|
|
# Broadcast row/column vectors instead of full mgrid planes: the z6 world
|
|
# composites are 217 Mpx, so every full-size plane costs ~0.9 GB.
|
|
xs = np.arange(w, dtype=np.int32)[None, :]
|
|
ys = np.arange(h, dtype=np.int32)[:, None]
|
|
empty = alpha == 0
|
|
left = np.broadcast_to(xs < w / 2, (h, w))
|
|
top = np.broadcast_to(ys < h / 2, (h, w))
|
|
quadrants = {
|
|
"top_left": lambda: left & top,
|
|
"top_right": lambda: ~left & top,
|
|
"bottom_left": lambda: left & ~top,
|
|
"bottom_right": lambda: ~left & ~top,
|
|
}
|
|
diagonals = { # grows away from the corner point
|
|
"top_left": lambda: xs + ys,
|
|
"top_right": lambda: (w - 1 - xs) + ys,
|
|
"bottom_left": lambda: xs + (h - 1 - ys),
|
|
"bottom_right": lambda: (w - 1 - xs) + (h - 1 - ys),
|
|
}
|
|
masks, distances = {}, {}
|
|
for name in corners:
|
|
mask = empty & quadrants[name]()
|
|
masks[name] = mask
|
|
diagonal = diagonals[name]()
|
|
edge = int(diagonal[mask].max()) if mask.any() else -1
|
|
distances[name] = (np.clip(diagonal - edge, 0, None) / np.sqrt(2.0)).astype(np.float32)
|
|
return rgb, alpha, masks, distances
|
|
|
|
|
|
def flatness(rgb: np.ndarray) -> np.ndarray:
|
|
"""1 where the image is featureless background, 0 where it has texture."""
|
|
grey = Image.fromarray(rgb).convert("L")
|
|
g = np.array(grey, dtype=np.float32)
|
|
blur = np.array(grey.filter(ImageFilter.GaussianBlur(6)), dtype=np.float32)
|
|
detail = Image.fromarray(np.abs(g - blur).astype(np.uint8)).filter(ImageFilter.BoxBlur(8))
|
|
return np.clip(1.0 - np.array(detail, dtype=np.float32) / 4.0, 0.0, 1.0)
|
|
|
|
|
|
def sample_colour(rgb: np.ndarray, alpha: np.ndarray, corner: np.ndarray, band: int) -> tuple[int, int, int]:
|
|
"""Median of real pixels within `band` px of the corner's edge."""
|
|
dilated = np.array(Image.fromarray((corner * 255).astype(np.uint8))
|
|
.filter(ImageFilter.MaxFilter(2 * band + 1))) > 0
|
|
selection = dilated & (alpha > 0)
|
|
if not selection.any():
|
|
raise SystemExit("no real pixels next to that corner to sample from")
|
|
return tuple(int(v) for v in np.median(rgb[selection], axis=0))
|
|
|
|
|
|
def parse_colour(value: str) -> tuple[int, int, int] | None:
|
|
if value == "sample":
|
|
return None
|
|
value = value.lstrip("#")
|
|
if len(value) != 6:
|
|
raise argparse.ArgumentTypeError("colour must be #rrggbb")
|
|
return tuple(int(value[i:i + 2], 16) for i in (0, 2, 4))
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
|
parser.add_argument("corners", nargs="*", choices=CORNERS,
|
|
help="corners to fill (default: bottom_left)")
|
|
parser.add_argument("--image", type=Path, help="square base image (default: maps.json world.image)")
|
|
parser.add_argument("--source", type=Path, default=ROOT / "sources" / "overall" / "overall.jpeg",
|
|
help="unrotated source the square image was made from")
|
|
parser.add_argument("--rotate", type=float, default=45.0, help="degrees CCW square_base.py used")
|
|
parser.add_argument("--color", type=parse_colour, default=(0x12, 0x18, 0x18),
|
|
help="fill colour #rrggbb, or 'sample' for the per-corner median of "
|
|
"the real pixels next to the corner (default: #121818, the "
|
|
"source's flat background)")
|
|
parser.add_argument("--band", type=int, default=20, help="sampling band width in px")
|
|
parser.add_argument("--noise", type=float, default=0.0,
|
|
help="gaussian grain sigma to add to the fill (0 = perfectly flat)")
|
|
parser.add_argument("--feather", type=int, default=96,
|
|
help="px over which flat background next to a filled corner eases "
|
|
"into the fill colour (0 = leave every real pixel untouched)")
|
|
parser.add_argument("--dry-run", action="store_true", help="write a preview, keep the image")
|
|
args = parser.parse_args(argv)
|
|
|
|
image_path = args.image
|
|
if image_path is None:
|
|
raw = json.loads(CONFIG.read_text(encoding="utf-8"))
|
|
image_path = ROOT / raw["world"]["image"]
|
|
image_path = image_path.resolve()
|
|
image = Image.open(image_path).convert("RGB")
|
|
rgb = np.array(image)
|
|
corners = list(dict.fromkeys(args.corners or ["bottom_left"]))
|
|
source_rgb, alpha, masks, distances = corner_masks(args.source, args.rotate, image.size, corners)
|
|
if source_rgb is None:
|
|
source_rgb = rgb # scaled composite: feather from the image itself
|
|
real = alpha == 255
|
|
|
|
out = rgb.copy()
|
|
for corner in corners:
|
|
mask = masks[corner]
|
|
colour = args.color or sample_colour(rgb, alpha, mask, args.band)
|
|
fill = np.empty((int(mask.sum()), 3), dtype=np.float64)
|
|
fill[:] = colour
|
|
if args.noise > 0:
|
|
fill += np.random.default_rng(0).normal(0, args.noise, fill.shape)
|
|
out[mask] = np.clip(np.rint(fill), 0, 255).astype(np.uint8)
|
|
feathered = 0
|
|
if args.feather > 0:
|
|
band = real & (distances[corner] > 0) & (distances[corner] < args.feather)
|
|
rows, cols = np.nonzero(band)
|
|
if rows.size:
|
|
# Texture analysis only over the band's bounding box, padded
|
|
# for the blur footprint -- not the whole (possibly huge) image.
|
|
pad = 24
|
|
y0, y1 = max(0, rows.min() - pad), min(band.shape[0], rows.max() + pad + 1)
|
|
x0, x1 = max(0, cols.min() - pad), min(band.shape[1], cols.max() + pad + 1)
|
|
flat_box = flatness(np.ascontiguousarray(source_rgb[y0:y1, x0:x1]))
|
|
flat = flat_box[rows - y0, cols - x0]
|
|
weight = flat * (1.0 - distances[corner][band] / args.feather)
|
|
base = source_rgb[band].astype(np.float64) # untouched originals: idempotent
|
|
blended = base + (np.array(colour, dtype=np.float64) - base) * weight[:, None]
|
|
out[band] = np.clip(np.rint(blended), 0, 255).astype(np.uint8)
|
|
feathered = int((weight > 0.01).sum())
|
|
print(f"{corner}: {int(mask.sum())} px -> #{colour[0]:02x}{colour[1]:02x}{colour[2]:02x}"
|
|
+ (f" (+noise sigma {args.noise})" if args.noise > 0 else "")
|
|
+ (f", feathered {feathered} flat px" if feathered else ""))
|
|
|
|
if args.dry_run:
|
|
preview = ROOT / "build" / "sea-corner-preview.png"
|
|
Image.fromarray(out).save(preview)
|
|
print(f"preview written to {preview.relative_to(ROOT)}; {image_path.name} unchanged")
|
|
return
|
|
if args.feather <= 0:
|
|
assert np.array_equal(out[alpha > 0], rgb[alpha > 0]), "real pixels must not change"
|
|
if args.image is not None:
|
|
print("note: a scaled composite is feathered from its own pixels; do not re-run on it")
|
|
# optimize=True is worth it for the 1842 px base, far too slow for 217 Mpx.
|
|
small = out.shape[0] * out.shape[1] <= 20_000_000
|
|
Image.fromarray(out).save(image_path, optimize=small, compress_level=9 if small else 6)
|
|
try:
|
|
shown = image_path.relative_to(ROOT)
|
|
except ValueError:
|
|
shown = image_path
|
|
print(f"wrote {shown}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main(sys.argv[1:])
|