Bläddra i källkod

feat: add Mount Rainier terrain data generators

scripts/gen-topo.py traces contour lines of Mount Rainier from AWS
Terrain Tiles (Terrarium, USGS 3DEP) and writes a compact delta-encoded
public/data/rainier-topo.json for the page background.

scripts/gen-skyline.py ray-casts the same elevation data from Kerry
Park, Seattle, with earth curvature and atmospheric refraction, and
writes Rainier's real skyline, snowfield and foothills as SVG paths for
the Seattle sky widget.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QEPoSHwHCYMNpm2iKxY9hL
Claude 1 månad sedan
förälder
incheckning
b685286b36
4 ändrade filer med 458 tillägg och 0 borttagningar
  1. 16 0
      components/cards/rainier-skyline.ts
  2. 0 0
      public/data/rainier-topo.json
  3. 207 0
      scripts/gen-skyline.py
  4. 235 0
      scripts/gen-topo.py

+ 16 - 0
components/cards/rainier-skyline.ts

@@ -0,0 +1,16 @@
+// Generated by scripts/gen-skyline.py: Mount Rainier from Kerry Park, Seattle,
+// ray-cast over AWS Terrain Tiles (USGS 3DEP). Vertical scale exaggerated 1.8x.
+
+export const SKYLINE_SIZE = [1000, 230] as const;
+
+export const RAINIER =
+  "M0 230l0-92l3-1l13 1l2-2l8 3l3-1l6 3l5-1l3 1l4-2l4 4l6 3l8-6l5 1l10 3l8-3l2-2l5 0l8-3l6 2l4-3l4 1l4-1l2 3l12-2l3-2l3 2l3-2l5 1l4-2l7 2l8-1l5 2l6-5l5 1l4-1l5 3l5-1l7 4l4-1l4-3l5 3l7-1l7 1l2-4l10-3l8-3l6 4l6 3l3-2l3 0l3-2l7 3l3-1l6 0l7 3l7 0l5-4l8 3l2-1l4-3l6 2l8 0l2-3l5 3l3 0l2-2l6 2l7-3l12-1l14-7l5 3l3-2l9 5l9-2l18 0l2-1l4 1l6-3l7 0l16 5l3-2l3-4l3 2l4-3l10 0l5-5l9 3l12-4l5-3l8-7l3 2l8 0l4-5l5-2l4-3l9-12l4-4l7 7l1 1l3-1l4 2l16-15l35-40l9-3l6 0l3 2l3-1l5 4l6 1l6 6l5 7l7 4l10 13l18 17l9 11l5 4l5 1l2 3l8 2l10-1l11 9l13 5l6 1l9 4l5-3l10 7l9 2l10 5l3 1l4-1l2 2l9 2l5 3l12 2l2-2l3 0l7 7l16 3l6-3l3 2l18 3l4 3l6 0l19 7l3-2l4-5l4-2l3-6l4 0l4 4l6 2l7-6l7 2l3-2l6 5l9 0l0 78z";
+
+export const RAINIER_SNOW =
+  "M136 135l2-1l3 2l-3 1l-2-2zM150 135l3-2l5 2l-8 0zM174 135l4-4l6 1l4-1l5 3l5-1l5 3l-21-1l-2-1l-6 1zM211 134l2-1l0 1l-2 0zM232 136l2-4l10-3l8-3l6 4l6 3l3-2l3 0l3-2l6 3l-1 1l0-1l-2 1l-4 0l-3 1l-7 1l-1-1l-2 1l-4-2l-4-1l-3 3l-4-2l-4 2l-2 0l0-1l-3 2l-1-2l-2 2zM299 134l4 0l5-4l6 3l4-1l4-3l6 2l-4 2l-3 5l-10-6l-2 0l-5 4l-5-2zM331 131l5 0l2-3l7 3l3-2l5 2l4 0l4-3l12-1l14-7l5 3l3-2l9 5l9-2l18 0l2-1l4 1l6-3l7 0l16 5l3-2l3-4l1 1l-10 8l-5-3l-2 0l-8 6l-2-1l-1 1l-2-1l-4 1l-6-4l-1 2l-4-1l-1 2l-2-1l-1 1l-3 0l-3 1l-5-5l-7 3l-3-2l-3 5l-6-1l-1 2l-7-2l-1 2l-1-1l-8 1l-4-2l-7 3l-7-1l-6 0l-1-1l-1 1l-5-1l-2-2l-3 2l-5 1l-4-3zM489 119l5-5l9 3l13-5l4-2l8-7l3 2l8 0l4-5l5-2l4-3l9-12l4-4l7 7l1 1l3-1l4 2l16-15l35-40l8-3l7 0l3 2l3-1l5 4l6 1l6 6l5 7l7 4l10 13l18 17l9 11l5 4l5 1l2 3l8 2l10-1l2 1l4 4l13 8l11 2l9 4l5-3l10 7l9 2l10 5l3 1l4-1l2 2l13 4l-8-1l-4 0l-2-2l-1 1l0-2l-1 1l-2-2l-2 1l-4-2l-29 2l-7-1l0-1l-2 2l-3 0l-1-2l-1 2l-1-1l-2 1l-1 0l-1-2l-1 2l-1-1l-1 1l-1-1l-3 1l-1-1l-4 2l-5-1l-6-4l-6 0l-1-1l-3 2l-2-1l-3 1l-5-4l-2 0l-4-2l-4 0l0 1l-6 0l-3 1l-6-4l-7 3l-3-2l-5 1l-5-2l-5 2l-1-2l-1 2l-2-2l-1 1l-1-1l-1 1l-1-1l-3 2l-1-1l-10 0l-1-1l-1 0l-5-4l-11 5l-5-2l-2 3l-3-1l-5 4l-5 0l-4 0l-3-4l-5-3l-3 2l-5-2l-6 6l-12 3l-10-8l-14 3l-11-10l-2 2l-2 5l-7 5l-11 0l-1-1l-4 1l-1-1l-1 1l-5-1l-3-4l-5-1l-2-2l-5 2l-3 0l-4-3z";
+
+export const FOOTHILLS =
+  "M0 230l0-100l19 1l11-6l7 3l6 0l4-2l15 7l4-1l4 2l6-3l7 1l5 3l7-4l3 0l8-2l15 2l6-1l3 1l15 12l23 7l7-3l12 2l6-2l14 0l6-2l15 0l6 0l6 3l16 2l10 5l17 4l5-5l8-4l12-2l8 1l5-3l10-2l4-3l22-2l6-3l11 4l7 6l7-4l2 0l8 8l6 2l13-4l2 0l4-5l4-2l17-4l10-10l4-1l16 10l12 1l12 3l3-1l2 1l19 12l8-4l13 5l14 1l9-6l23 8l14 9l10 2l5 4l15 3l11-9l6 0l11-9l9-4l23-5l10 3l15-6l11 4l9 0l15 12l13 3l14 7l7 0l10 5l4-1l3 2l4-2l5 5l5-1l6-4l19-4l15 5l7 1l12-1l15 2l30-2l10 5l13 1l5 4l13-1l7-4l11 3l2 0l4-3l9 1l4 0l0 49z";
+
+export const SEATTLE_HILLS =
+  "M0 230l0-38l53 1l14 1l13-1l20 3l33 1l40 4l12-5l23 2l22-4l21-1l10 1l60-4l45 2l29 4l20 1l21-3l14-4l12-1l36-2l30 2l16-3l50-2l24 1l37 4l12 2l11-2l60 3l8 1l26 7l41 6l8-2l23 1l9-3l30-1l29 8l15-3l17-6l56-4l0 34z";

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 0
public/data/rainier-topo.json


+ 207 - 0
scripts/gen-skyline.py

@@ -0,0 +1,207 @@
+#!/usr/bin/env python3
+"""Generate Mount Rainier's skyline as seen from Kerry Park, Seattle.
+
+Casts rays over Terrarium elevation tiles from the AWS Open Data "Terrain
+Tiles" bucket (with earth curvature and atmospheric refraction), keeps the
+highest apparent angle per bearing, and writes SVG paths for the far massif,
+its snowfield, and the nearer foothills to components/cards/rainier-skyline.ts.
+
+Depends on numpy and Pillow. Run with: python3 scripts/gen-skyline.py
+Set TOPO_CACHE to a directory to reuse downloaded tiles.
+"""
+
+import io
+import math
+import os
+import urllib.request
+
+import numpy as np
+from PIL import Image
+
+VIEWER = (47.6295, -122.3599)  # Kerry Park, Queen Anne Hill
+EYE = 2.0  # metres above the ground
+SUMMIT = (46.8523, -121.7603)  # Columbia Crest
+ZOOM = 11
+FOV = 24.0  # degrees of bearing across the widget
+SUMMIT_AT = 0.64  # where the summit sits across the width (0..1)
+STEP_AZ = 0.02  # degrees between rays
+STEP_D = 40.0  # metres between samples along a ray
+MAX_D = 125_000.0
+FAR_FROM = 72_000.0  # samples beyond this belong to the Rainier massif
+MID_FROM = 22_000.0  # foothills between here and FAR_FROM; Seattle's hills nearer
+SNOWLINE = 1900.0  # metres; early autumn snow
+EARTH_R = 6_371_000.0
+K_REFRACTION = 0.13
+VIEW_W = 200.0
+EXAGGERATION = 1.8
+SCALE = 5  # output units per view unit, so coordinates can be integers
+TOLERANCE = 0.8  # RDP tolerance in output units
+TILE_URL = "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
+OUT = os.path.join(os.path.dirname(__file__), "..", "components", "cards", "rainier-skyline.ts")
+
+
+def fetch_tile(x, y, z):
+    cache = os.environ.get("TOPO_CACHE")
+    path = cache and os.path.join(cache, f"{z}-{x}-{y}.png")
+    if path and os.path.exists(path):
+        data = open(path, "rb").read()
+    else:
+        with urllib.request.urlopen(TILE_URL.format(z=z, x=x, y=y), timeout=60) as r:
+            data = r.read()
+        if path:
+            os.makedirs(cache, exist_ok=True)
+            open(path, "wb").write(data)
+    rgb = np.asarray(Image.open(io.BytesIO(data)).convert("RGB"), dtype=np.float64)
+    return rgb[:, :, 0] * 256 + rgb[:, :, 1] + rgb[:, :, 2] / 256 - 32768
+
+
+def global_px(lat, lon, z):
+    n = 256 * (1 << z)
+    x = (lon + 180.0) / 360.0 * n
+    r = np.radians(lat)
+    y = (1.0 - np.log(np.tan(r) + 1.0 / np.cos(r)) / math.pi) / 2.0 * n
+    return x, y
+
+
+def destination(lat, lon, bearing, d):
+    """Points d metres from (lat, lon) along each bearing (degrees), on a sphere."""
+    p1, l1, b = math.radians(lat), math.radians(lon), np.radians(bearing)
+    a = d / EARTH_R
+    p2 = np.arcsin(math.sin(p1) * np.cos(a) + math.cos(p1) * np.sin(a) * np.cos(b))
+    l2 = l1 + np.arctan2(np.sin(b) * np.sin(a) * math.cos(p1), np.cos(a) - math.sin(p1) * np.sin(p2))
+    return np.degrees(p2), np.degrees(l2)
+
+
+def bearing_to(a, b):
+    p1, p2 = math.radians(a[0]), math.radians(b[0])
+    dl = math.radians(b[1] - a[1])
+    y = math.sin(dl) * math.cos(p2)
+    x = math.cos(p1) * math.sin(p2) - math.sin(p1) * math.cos(p2) * math.cos(dl)
+    return (math.degrees(math.atan2(y, x)) + 360) % 360
+
+
+def rdp(points, eps):
+    if len(points) < 3:
+        return points
+    a, b = points[0], points[-1]
+    ab = b - a
+    norm = np.hypot(*ab)
+    d = np.abs(ab[0] * (points[:, 1] - a[1]) - ab[1] * (points[:, 0] - a[0])) / max(norm, 1e-9)
+    i = int(np.argmax(d))
+    if d[i] > eps:
+        return np.vstack([rdp(points[: i + 1], eps)[:-1], rdp(points[i:], eps)])
+    return np.array([a, b])
+
+
+def path(points):
+    """A compact closed SVG path in SCALE units, with relative segments.
+
+    The ring is split at its farthest point so RDP keeps its shape."""
+    ring = np.asarray(points, dtype=float) * SCALE
+    far = int(np.argmax(np.hypot(*(ring - ring[0]).T)))
+    pts = np.vstack([rdp(ring[: far + 1], TOLERANCE)[:-1], rdp(ring[far:], TOLERANCE)])
+    pts = np.round(pts).astype(int)
+    out = [f"M{pts[0][0]} {pts[0][1]}"]
+    for (x0, y0), (x1, y1) in zip(pts[:-1], pts[1:]):
+        if (x1, y1) != (x0, y0):
+            out.append(f"l{x1 - x0}{'' if y1 - y0 < 0 else ' '}{y1 - y0}")
+    return "".join(out) + "z"
+
+
+def main():
+    az0 = bearing_to(VIEWER, SUMMIT)
+    left = az0 - FOV * SUMMIT_AT
+    bearings = np.arange(left, left + FOV + STEP_AZ / 2, STEP_AZ)
+    dists = np.arange(300.0, MAX_D, STEP_D)
+
+    lat, lon = destination(VIEWER[0], VIEWER[1], bearings[:, None], dists[None, :])
+    gx, gy = global_px(lat, lon, ZOOM)
+    tx0, ty0 = int(gx.min() // 256), int(gy.min() // 256)
+    tx1, ty1 = int(gx.max() // 256), int(gy.max() // 256)
+    dem = np.zeros(((ty1 - ty0 + 1) * 256, (tx1 - tx0 + 1) * 256))
+    for ty in range(ty0, ty1 + 1):
+        for tx in range(tx0, tx1 + 1):
+            dem[(ty - ty0) * 256 : (ty - ty0 + 1) * 256, (tx - tx0) * 256 : (tx - tx0 + 1) * 256] = fetch_tile(tx, ty, ZOOM)
+
+    # Bilinear sample.
+    fx, fy = gx - tx0 * 256, gy - ty0 * 256
+    x0, y0 = np.floor(fx).astype(int), np.floor(fy).astype(int)
+    ax, ay = fx - x0, fy - y0
+    h = (
+        dem[y0, x0] * (1 - ax) * (1 - ay)
+        + dem[y0, x0 + 1] * ax * (1 - ay)
+        + dem[y0 + 1, x0] * (1 - ax) * ay
+        + dem[y0 + 1, x0 + 1] * ax * ay
+    )
+
+    gx0, gy0 = global_px(np.array(VIEWER[0]), np.array(VIEWER[1]), ZOOM)
+    eye = dem[int(gy0 - ty0 * 256), int(gx0 - tx0 * 256)] + EYE
+    r_eff = EARTH_R / (1 - K_REFRACTION)
+    angle = np.degrees(np.arctan2(h - eye - dists**2 / (2 * r_eff), dists))
+
+    far = dists >= FAR_FROM
+    mid = (dists >= MID_FROM) & ~far
+    near = dists < MID_FROM
+    far_sky = angle[:, far].max(axis=1)
+    mid_sky = angle[:, mid].max(axis=1)
+    near_sky = angle[:, near].max(axis=1)
+    front_sky = np.maximum(mid_sky, near_sky)
+
+    # Snow: visible far-field points above the snowline. A point is visible when
+    # nothing nearer along the ray rises above it.
+    running = np.maximum.accumulate(angle, axis=1)
+    visible = angle >= running - 1e-9
+    snowy = visible & far[None, :] & (h >= SNOWLINE)
+    snow_low = np.where(snowy, angle, np.inf).min(axis=1)
+
+    summit_angle = far_sky.max()
+    scale = (VIEW_W / FOV) * EXAGGERATION  # units per degree, vertically
+    top = 6.0  # leave headroom above the summit
+    horizon = top + summit_angle * scale
+
+    def y(a):
+        return horizon - a * scale
+
+    xs = (bearings - left) / FOV * VIEW_W
+    view_h = math.ceil(y(min(near_sky.min(), mid_sky.min())) + 4)
+
+    def layer(sky):
+        return path([(0, view_h)] + [(x, y(a)) for x, a in zip(xs, sky)] + [(VIEW_W, view_h)])
+
+    # Snowfield polygons over contiguous runs where snow is visible above the foothills.
+    snow_paths = []
+    has = np.isfinite(snow_low) & (far_sky > front_sky)
+    i = 0
+    while i < len(xs):
+        if not has[i]:
+            i += 1
+            continue
+        j = i
+        while j + 1 < len(xs) and has[j + 1]:
+            j += 1
+        if j - i >= 3:
+            low = np.maximum(snow_low[i : j + 1], front_sky[i : j + 1])
+            top_pts = [(xs[k], y(far_sky[k])) for k in range(i, j + 1)]
+            bottom_pts = [(xs[k], y(low[k - i])) for k in range(j, i - 1, -1)]
+            snow_paths.append(path(top_pts + bottom_pts))
+        i = j + 1
+
+    with open(OUT, "w") as f:
+        f.write(
+            "// Generated by scripts/gen-skyline.py: Mount Rainier from Kerry Park, Seattle,\n"
+            "// ray-cast over AWS Terrain Tiles (USGS 3DEP). Vertical scale exaggerated "
+            f"{EXAGGERATION}x.\n\n"
+            f"export const SKYLINE_SIZE = [{VIEW_W * SCALE:.0f}, {view_h * SCALE}] as const;\n\n"
+            f"export const RAINIER = \"{layer(far_sky)}\";\n\n"
+            f"export const RAINIER_SNOW = \"{''.join(snow_paths)}\";\n\n"
+            f"export const FOOTHILLS = \"{layer(mid_sky)}\";\n\n"
+            f"export const SEATTLE_HILLS = \"{layer(near_sky)}\";\n"
+        )
+    print(
+        f"bearing {az0:.2f}°, summit {summit_angle:.2f}° above horizon, "
+        f"eye {eye:.0f} m, tiles {(tx1 - tx0 + 1) * (ty1 - ty0 + 1)}, horizon y {horizon:.1f}, height {view_h}"
+    )
+
+
+if __name__ == "__main__":
+    main()

+ 235 - 0
scripts/gen-topo.py

@@ -0,0 +1,235 @@
+#!/usr/bin/env python3
+"""Generate the Mount Rainier contour lines used by the site background.
+
+Downloads Terrarium elevation tiles from the AWS Open Data "Terrain Tiles"
+bucket, traces contour lines with marching squares, simplifies them, and
+writes a compact delta-encoded JSON file to public/data/rainier-topo.json.
+
+Depends on numpy and Pillow. Run with: python3 scripts/gen-topo.py
+Data: Terrain Tiles (https://registry.opendata.aws/terrain-tiles/),
+sources include USGS 3DEP/NED and SRTM.
+"""
+
+import io
+import json
+import math
+import os
+import urllib.request
+import zlib
+from collections import defaultdict
+
+import numpy as np
+from PIL import Image
+
+SUMMIT = (46.8523, -121.7603)  # Columbia Crest
+LAT_SPAN = 0.17  # degrees each side of the summit
+LON_SPAN = 0.25
+ZOOM = 12
+GRID = 300  # output grid resolution (cells along the longer side)
+LEVEL_STEP = 150  # metres between contour lines
+MIN_LEVEL = 600
+SMOOTH_SIGMA = 1.6
+SIMPLIFY = 0.35  # Ramer-Douglas-Peucker tolerance in grid cells
+OUT_SCALE = 1000  # output coordinate space (longer side)
+TILE_URL = "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
+OUT = os.path.join(os.path.dirname(__file__), "..", "public", "data", "rainier-topo.json")
+
+
+def lon_to_x(lon, z):
+    return (lon + 180.0) / 360.0 * (1 << z)
+
+
+def lat_to_y(lat, z):
+    r = math.radians(lat)
+    return (1.0 - math.log(math.tan(r) + 1.0 / math.cos(r)) / math.pi) / 2.0 * (1 << z)
+
+
+def fetch_tile(x, y, z):
+    """Fetch one tile; set TOPO_CACHE to a directory to reuse downloads."""
+    cache = os.environ.get("TOPO_CACHE")
+    path = cache and os.path.join(cache, f"{z}-{x}-{y}.png")
+    if path and os.path.exists(path):
+        data = open(path, "rb").read()
+    else:
+        with urllib.request.urlopen(TILE_URL.format(z=z, x=x, y=y), timeout=60) as r:
+            data = r.read()
+        if path:
+            os.makedirs(cache, exist_ok=True)
+            open(path, "wb").write(data)
+    rgb = np.asarray(Image.open(io.BytesIO(data)).convert("RGB"), dtype=np.float64)
+    return rgb[:, :, 0] * 256 + rgb[:, :, 1] + rgb[:, :, 2] / 256 - 32768
+
+
+def gaussian(a, sigma):
+    radius = int(math.ceil(sigma * 3))
+    k = np.exp(-0.5 * (np.arange(-radius, radius + 1) / sigma) ** 2)
+    k /= k.sum()
+    pad = np.pad(a, radius, mode="edge")
+    tmp = np.apply_along_axis(lambda m: np.convolve(m, k, mode="valid"), 1, pad)
+    return np.apply_along_axis(lambda m: np.convolve(m, k, mode="valid"), 0, tmp)
+
+
+def marching_squares(grid, level):
+    """Return contour segments as (x0, y0, x1, y1) in grid coordinates."""
+    h, w = grid.shape
+    tl, tr = grid[:-1, :-1], grid[:-1, 1:]
+    bl, br = grid[1:, :-1], grid[1:, 1:]
+    idx = (tl > level) * 8 + (tr > level) * 4 + (br > level) * 2 + (bl > level) * 1
+    ys, xs = np.nonzero((idx > 0) & (idx < 15))
+    segs = []
+
+    def interp(a, b):
+        d = b - a
+        return 0.5 if d == 0 else (level - a) / d
+
+    for y, x in zip(ys, xs):
+        a, b, c, d = tl[y, x], tr[y, x], br[y, x], bl[y, x]
+        top = (x + interp(a, b), y)
+        right = (x + 1, y + interp(b, c))
+        bottom = (x + interp(d, c), y + 1)
+        left = (x, y + interp(a, d))
+        case = idx[y, x]
+        pairs = {
+            1: [(left, bottom)], 2: [(bottom, right)], 3: [(left, right)],
+            4: [(top, right)], 6: [(top, bottom)], 7: [(left, top)],
+            8: [(left, top)], 9: [(top, bottom)], 11: [(top, right)],
+            12: [(left, right)], 13: [(bottom, right)], 14: [(left, bottom)],
+            5: [(left, top), (bottom, right)], 10: [(top, right), (left, bottom)],
+        }[case]
+        segs.extend(pairs)
+    return segs
+
+
+def join_segments(segs):
+    key = lambda p: (round(p[0], 4), round(p[1], 4))
+    ends = defaultdict(list)
+    for i, (p, q) in enumerate(segs):
+        ends[key(p)].append(i)
+        ends[key(q)].append(i)
+    used = [False] * len(segs)
+    lines = []
+    for i in range(len(segs)):
+        if used[i]:
+            continue
+        used[i] = True
+        line = [segs[i][0], segs[i][1]]
+        for forward in (True, False):
+            while True:
+                tip = line[-1] if forward else line[0]
+                nxt = None
+                for j in ends[key(tip)]:
+                    if not used[j]:
+                        nxt = j
+                        break
+                if nxt is None:
+                    break
+                used[nxt] = True
+                p, q = segs[nxt]
+                other = q if key(p) == key(tip) else p
+                if forward:
+                    line.append(other)
+                else:
+                    line.insert(0, other)
+        lines.append(line)
+    return lines
+
+
+def rdp(points, eps):
+    if len(points) < 3:
+        return points
+    pts = np.asarray(points)
+    keep = np.zeros(len(pts), dtype=bool)
+    keep[0] = keep[-1] = True
+    stack = [(0, len(pts) - 1)]
+    while stack:
+        s, e = stack.pop()
+        if e <= s + 1:
+            continue
+        seg = pts[e] - pts[s]
+        norm = np.hypot(*seg)
+        v = pts[s + 1 : e] - pts[s]
+        if norm < 1e-9:  # closed ring: measure distance from the start point
+            d = np.hypot(v[:, 0], v[:, 1])
+        else:
+            d = np.abs(seg[0] * v[:, 1] - seg[1] * v[:, 0]) / norm
+        i = int(np.argmax(d))
+        if d[i] > eps:
+            keep[s + 1 + i] = True
+            stack.append((s, s + 1 + i))
+            stack.append((s + 1 + i, e))
+    return [tuple(p) for p in pts[keep]]
+
+
+def main():
+    lat0, lon0 = SUMMIT
+    north, south = lat0 + LAT_SPAN, lat0 - LAT_SPAN
+    west, east = lon0 - LON_SPAN, lon0 + LON_SPAN
+    fx0, fx1 = lon_to_x(west, ZOOM), lon_to_x(east, ZOOM)
+    fy0, fy1 = lat_to_y(north, ZOOM), lat_to_y(south, ZOOM)
+    tx0, tx1, ty0, ty1 = int(fx0), int(fx1), int(fy0), int(fy1)
+    rows = []
+    for ty in range(ty0, ty1 + 1):
+        row = []
+        for tx in range(tx0, tx1 + 1):
+            print(f"tile {ZOOM}/{tx}/{ty}")
+            row.append(fetch_tile(tx, ty, ZOOM))
+        rows.append(np.hstack(row))
+    mosaic = np.vstack(rows)
+    px0, px1 = int((fx0 - tx0) * 256), int((fx1 - tx0) * 256)
+    py0, py1 = int((fy0 - ty0) * 256), int((fy1 - ty0) * 256)
+    elev = mosaic[py0:py1, px0:px1]
+
+    # Resample so the longer side has GRID cells (block mean keeps it smooth).
+    h, w = elev.shape
+    step = max(h, w) / GRID
+    gh, gw = int(h / step), int(w / step)
+    ys = (np.arange(gh + 1) * step).astype(int)
+    xs = (np.arange(gw + 1) * step).astype(int)
+    grid = np.array([[elev[ys[i] : ys[i + 1], xs[j] : xs[j + 1]].mean() for j in range(gw)] for i in range(gh)])
+    grid = gaussian(grid, SMOOTH_SIGMA)
+
+    sy = (lat_to_y(lat0, ZOOM) - ty0) * 256 - py0
+    sx = (lon_to_x(lon0, ZOOM) - tx0) * 256 - px0
+    scale = OUT_SCALE / max(gw - 1, gh - 1)
+
+    levels = []
+    top = int(grid.max())
+    for level in range(MIN_LEVEL, top, LEVEL_STEP):
+        lines = join_segments(marching_squares(grid, level))
+        enc = []
+        for line in lines:
+            if len(line) < 6:
+                continue
+            simple = rdp(line, SIMPLIFY)
+            if len(simple) < 3:
+                continue
+            pts = [(round(x * scale), round(y * scale)) for x, y in simple]
+            flat, px, py = [], 0, 0
+            for i, (x, y) in enumerate(pts):
+                if i and x == px and y == py:
+                    continue
+                flat += [x - px, y - py] if i else [x, y]
+                px, py = x, y
+            if len(flat) >= 6:
+                enc.append(flat)
+        if enc:
+            levels.append({"e": level, "l": enc})
+        print(f"level {level}: {len(enc)} lines")
+
+    out = {
+        "w": round((gw - 1) * scale),
+        "h": round((gh - 1) * scale),
+        "summit": [round(sx / step * scale), round(sy / step * scale)],
+        "step": LEVEL_STEP,
+        "levels": levels,
+    }
+    os.makedirs(os.path.dirname(OUT), exist_ok=True)
+    with open(OUT, "w") as f:
+        json.dump(out, f, separators=(",", ":"))
+    raw = os.path.getsize(OUT)
+    gz = len(zlib.compress(open(OUT, "rb").read(), 9))
+    print(f"wrote {OUT}: {raw / 1024:.1f}KB raw, ~{gz / 1024:.1f}KB compressed, max elev {grid.max():.0f}m")
+
+
+if __name__ == "__main__":
+    main()

Vissa filer visades inte eftersom för många filer har ändrats