⏳ This skill is pending AI review.

Scores will appear once the review pipeline completes.

v1.2.0

procedural-terrain-art

dogum@dogum⭐ 12 stars· last commit 25d ago· 0 open issues

Turn any real mountain, volcano, range, canyon or island on Earth into high-resolution procedural art from actual elevation data, in six print styles (engraved ridgelines, topographic contours, moonlit nocturne, stipple, risograph, woodcut), plus looping orbit videos and a self-contained interactive web studio. Framing adapts to the landform, so cones, horns like the Matterhorn, massifs, ranges, canyons and islands all work. Use this whenever someone wants a mountain or landscape drawn with code

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

—/10

// RATINGS

⭐GitHub Stars
⭐⭐ 12 on GitHubGitHub ↗

Growing

🟢ProSkills Score
—
📍

Not yet listed on ClawHub or SkillsMP

// README

procedural-art

Real mountains, glass and paintings made with code and real elevation data. No image model.

Two Claude skills. Name any mountain on Earth and get an engraving, a woodcut, a photograph, or a painting of it.

CI Release License Claude Code plugin

Try any mountain in your browser · Showcase · Studios · Latest release · Changelog


It started as an attempt to recreate an AI-generated header of Mount Ararat with math instead of a model, drawn from the real mountain's elevation. From there it grew into two skills:

SkillWhat it makes
procedural-terrain-artAny real mountain, range, canyon or island in six print styles, looping orbit videos, and a self-contained interactive studio page.
procedural-realismPhotographic terrain (sky, haze, snow, lakes, forests, city lights, sun timelapses), a path tracer for glass and metal still lifes, and a painterly finisher for any image.

Every terrain pixel comes from SRTM-derived elevation, numpy and physics. Nothing is downloaded except elevation tiles, and no generative model is involved at any step.

Any mountain, in your browser

Any mountain is the terrain engine as a web page. Type a peak, volcano or canyon, drag the viewpoint on the map, pick a style, and save a 3000 × 1000 header (or a LinkedIn, YouTube or wallpaper size). The page downloads 20 to 40 elevation tiles and measures the landform itself, so there is no server; a copied link reopens the same mountain, view and style. It draws with the same code as the studios below. 94 well-known peaks come with their classic viewpoint; anything else found on OpenStreetMap gets an automatic one.

One mountain, six prints

Masis and Sis (Ararat) seen from Yerevan. Same elevation grid, same hidden-line buffer, six ways of drawing it.

Any landform

The engine measures the ground around the summit before it frames anything: how steep the peak is for its footprint, what stands in front of it, how rough it is, whether it sits below a plateau. Cone volcanoes keep the original framing; horns, ranges, canyons and islands get their own.

The first engine treated every mountain like Ararat, and the Matterhorn drowned in its own massif (top). Landform-aware framing raises the base from 1429 m to 2441 m and narrows the scene's half-width from 30.7 km to 10.8 km (bottom). Fuji, Ararat and Mauna Kea render identically before and after.

Toward a photograph

The same elevation, ray-marched through a physical atmosphere: Rayleigh and Mie scattering, soft terrain shadows, valley mist, a lenticular cloud with multiple scattering. Lakes reflect the terrain with Fresnel and ripple normals. Trees, villages, stone walls and fields are placed near the camera, and a city at dusk is lit along its real OpenStreetMap streets.

There's also a sunset timelapse along the real sun path for a date and place: every frame is rendered with the sun where it is at that moment, so shadows move across Yerevan as the sun sets behind Ararat and the street lights come on. A 4:5 version suits phones.

Glass, from scratch

A Monte Carlo path tracer in plain numpy. Scenes are small JSON files: spheres, boxes, prisms, cut gems, hollow glasses with liquid in them. Multiple importance sampling and adaptive sampling make glass converge about 6.7× faster and copper 12× faster than a plain sampler.

Then paint it

paint.py turns any image into oil, impasto, gouache, watercolour or ink, including a photo you give it. Brushes follow the contours of the picture; watercolour is built from transparent washes with wet edges and granulation.

Install

Claude Code (recommended)

/plugin

// HOW IT'S BUILT

// FILES

11 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • skills/procedural-terrain-art/SKILL.md17 KBab5f1c1a63edupstream ↗
    ---
    name: procedural-terrain-art
    description: Turn any real mountain, volcano, range, canyon or island on Earth into high-resolution procedural art from actual elevation data, in six print styles (engraved ridgelines, topographic contours, moonlit nocturne, stipple, risograph, woodcut), plus looping orbit videos and a self-contained interactive web studio. Framing adapts to the landform, so cones, horns like the Matterhorn, massifs, ranges, canyons and islands all work. Use this whenever someone wants a mountain or landscape drawn with code, a profile header or banner (X/Twitter, LinkedIn, YouTube), poster, wallpaper or print of a real place, Unknown Pleasures-style ridgeline art of a real mountain, topographic or contour-line art, or asks to recreate an AI-generated landscape with code, even if they never say "terrain" or "elevation". Not for copying the album cover itself, GIS work (hillshade, viewshed, QGIS maps), 3D-print models or logos. For photographic renders, lakes, night cities or painted looks, use procedural-realism.
    license: Apache-2.0
    metadata:
      version: "1.2.0"
      homepage: https://dogum.github.io/procedural-art/
    ---
    
    # Procedural terrain art
    
    This skill draws a real place, not an invented one. It downloads real elevation data, looks at the mountain from a real viewpoint, hides the lines that would be behind other terrain, and renders the result in a chosen print style. Everything is code, so any output can be re-rendered at any size, angle, light or palette.
    
    Requirements: Python 3 with numpy, scipy, matplotlib, pillow and contourpy; network access to AWS Terrain Tiles; ffmpeg for video (optional).
    
    Work in a writable folder (for example the session's outputs folder) and call the scripts by path. The skill folder itself may be read-only once installed, so nothing should be written there. In the commands below, `SK` is this skill's folder (the one containing this file). Images, DEM caches and video frames go next to `--out`, relative to the current folder.
    
    If the user wants a photographic look (atmosphere, lake reflections, forests, a city at blue hour) or a painted one (oil, watercolour, ink), that is the `procedural-realism` skill.
    
    ## What you can make
    
    | Output | Tool | Typical time |
    |---|---|---|
    | Still image, one style (PNG/JPG, any size) | `$SK/scripts/render.py --style <name>` | 5–15 s at 3000×1000 |
    | All six styles + contact sheet | `$SK/scripts/render.py --style all` | ~40–60 s |
    | Looping orbit video (MP4) | `$SK/scripts/animate.py` | 1–4 s per frame at 1500×500 |
    | Interactive web studio (sliders, six styles, orbit, PNG export) | `$SK/scripts/build_studio.py` | ~5 s to build |
    
    Styles: `survey` (engraved ridgelines on parchment, sun in the saddle), `topo` (true contour lines from a high camera, triangulation network), `nocturne` (moonlit lines, stars, crescent), `stipple` (pointillist dots), `riso` (two spot inks, halftone, misregistration), `woodcut` (solid ink mass with carved lines that widen in the light).
    
    ## Workflow
    
    1. **Pin down the place.** You need the summit's lat/lon and a viewpoint: the town or spot the famous view is from, passed as `--from lat,lon` (or `--facing <bearing>` if there's no obvious viewpoint). The viewpoint decides which side of the mountain faces the camera and which peak sits on the left or right. Look coordinates up with web search if you're not certain; don't guess. If the user shows an image, identify the mountain from its silhouette and work out the viewpoint from which peak is on which side.
    2. **Draft fast.** Run with `--quality 0.5` (and a smaller `--size` if you like) and look at the output (view a downscaled copy; the full file is too big to inspect well). The first run fetches elevation tiles and caches them next to the output as `dem_<lat>_<lon>.npz`. Later runs into the same folder (render, animate and the studio) reuse it if it covers the area they need, and fetch a larger one if it doesn't; `--dem` reuses a file from anywhere.
    3. **Frame it.** Framing is automatic for the landform (see below). Adjust with the knobs in the table, one or two at a time, looking at each result.
    4. **Render final** at `--quality 1` and the target size. Deliver the PNG plus a JPG if the PNG is over the platform's upload limit.
    5. **Offer the next step:** the other styles as a contact sheet, an orbit video, or the web studio.
    
    ```bash
    SK=/path/to/procedural-terrain-art          # this skill's folder; run from a writable folder
    # Ararat from Yerevan (two labelled peaks, Armenian names)
    python $SK/scripts/render.py --peak 39.7019,44.2986 --from 40.1792,44.4991 --style survey \
      --label "ՄԱՍԻՍ|5137 m" --label "ՍԻՍ|3896 [email protected],44.4011" --out out/ararat.png
    # Fuji from Lake Kawaguchi, every style + contact_sheet.jpg
    python $SK/scripts/render.py --peak 35.3606,138.7274 --from 35.5100,138.7550 --style all \
      --label "富士山|3776 m" --title "富士山" --out out/fuji/
    # A horn: the Matterhorn from Riffelsee (all framing automatic)
    python $SK/scripts/render.py --peak 45.97639,7.65861 --from 45.98333,7.76222 --style nocturne \
      --label "Matterhorn|4478 m" --out out/matterhorn.png
    # A canyon: Brahma Temple from Mather Point
    python $SK/scripts/render.py --peak 36.1304634,-112.0387030 --from 36.0616497,-112.1079463 --style riso \
      --label "Brahma Temple|2302 m" --label "Zoroaster Temple|2171 [email protected],-112.0452" \
      --title "Grand Canyon" --out out/canyon.png
    # An island volcano seen from the coast is a quiet dome; this manual framing gives it shape
    python $SK/scripts/render.py --peak 19.82056,-155.46806 --from 19.70556,-155.08583 --style topo \
      --yaw 40 --relief 1.3 --spacing 0.5 --pan-y -90 --label "Mauna Kea|4207 m" --out out/mauna_kea.png
    ```
    
    Labels: `"Name|subtitle"` labels the main summit; add `@lat,lon` for other peaks. `--title` is the big word in riso and woodcut, usually the name in the local script. `--footnote` replaces the coordinates line. The script ends with a JSON line: the summit it found, peak and base elevations, extent, the detected `kind` and the shape scores. Check the peak elevation against the real one: a large mismatch means the coordinates are off. (Tiles smooth sharp summits a little, so 1–3% low is normal: the Matterhorn comes out at 4350 m instead of 4478 m.)
    
    ## Landform-aware defaults
    
    Before framing, the renderer measures the terrain around the summit: how steep the peak is relative to its footprint, how much high ground sits between the peak and the viewer, how rough the surface is, and whether the target sits below the surrounding plateau.
    
    | `kind` | Example | What the defaults do |
    |---|---|---|
    | cone, shield | Fuji, Ararat, Mauna Kea | The standard framing, which the other rules adjust. Shields also thin ridgelines that pile up on screen, so their broad far flanks don't print as a solid slab |
    | horn | Matterhorn | Higher base, tighter scene, lower camera, so the peak owns the frame instead of the whole massif |
    | massif, range (rough) | Denali, Tetons | Slightly wider line spacing and a little smoothing. Topo is drawn like a survey map (below) |
    | canyon | Grand Canyon | Drawn from its floor to its rim, seen from just above the rim, no snow. Woodcut is carved by depth below the rim |
    
    Horns and canyons also get an automatic vertical pan (skyline below about 21% of the frame, foreground above 90%) and a softer left fade; shields get the softer fade too. Any explicit `--extent`, `--base`, `--relief`, `--spacing`, `--camh`, `--zoom` or `--pan-y` overrides the automatic value. `--no-shape` applies the cone rules to every landform, for comparison.
    
    - **Close viewpoints.** Pick the viewpoint the famous photo is taken from; for horns it changes the silhouette a lot. The Matterhorn from Riffelsee (45.98333, 7.76222) shows the familiar profile with the steep north face on the right; from Zermatt (46.0170, 7.7500) the same peak reads as a broader pyramid.
    - **Canyons.** Target a butte or temple inside the canyon and use a rim viewpoint. The summit refinement snaps to the highest point within 1.5 km, so label the peak it actually finds. The result is a flat far rim with the side canyons cut into it. In woodcut the inner gorge and shaded side canyons print black and the rim, buttes and lit walls stay paper with engraved lines. Topo is still the busiest style here, because every wall is a stack of contours.
    - **Topo on rough ground** (horns, ranges, canyons) is drawn like a survey map: every fifth contour is heavier, intermediate contours are dropped a whole visible piece at a time where they crowd closer than about 3 px (next to the index lines first), and short index pieces that peek over a ridge are drawn at intermediate weight instead of as dark ledges. Line weight follows the light (illuminated contours), so faces turned from the light print heavier and the peak reads as a solid. Cones and shields keep plain contours.
    - **Water.** Sea (elevation at or below 0 m, since the tiles clip ocean to 0) and lakes (patches the DEM holds exactly flat, 0.5 km² or more) are their own layer. Ridgelines fade out over water, a coastline is drawn, and each style marks the water its own way: sparse wave strokes (survey, nocturne), a thin shoreline plus a few sparse level lines (topo), dotted shore and waves (stipple), a flat blue tint (riso), a flat ink block with carved waves (woodcut). Views with no water render exactly as before. The default framing often keeps the sea out of view (Mauna Kea from Hilo shows none); a larger `--extent`, `--align center` or a coastal viewpoint (Vesuvius from Naples) brings it in. Dry land below sea level (Dead Sea shore, Death Valley) reads as water; `--no-water` turns the layer off.
    - **Detection is tuned on seven places** (Fuji, Ararat, Matterhorn, Denali, Tetons, Grand Canyon, Mauna Kea). A new landform can land between the rules; if the draft looks wrong, set `--base`/`--extent` by hand.
    
    ## Framing knobs
    
    | Symptom | Fix |
    |---|---|
    | Mountain too small or too big | `--zoom 1.3` / `--zoom 0.8` |
    | Looks flat, or too spiky | `--relief 1.3` / `--relief 0.8` (vertical exaggeration) |
    | Busy foreground ridges crowd the peak | `--extent` smaller (tighter scene), or `--base` higher (drops the foothills), or `--yaw ±15` |
    | A neighbouring peak should show / hide | `--yaw` (orbits around the summit, degrees) |
    | Want it centred (posters, wallpapers) | `--align center`; default `right` keeps the left third empty for header avatars and text |
    | Lines too dense / sparse | `--spacing 0.5` / `--spacing 0.28` (auto default 0.375, wider on rough terrain) |
    | Camera too high / low | `--camh` (normalised km, default 3.4; horns lower, canyons higher) |
    | Snow cap too big / small | `--snowline <metres>` |
    | Composition sits too high / low | `--pan-y 80` / `--pan-y -80` (reference px, 1000 = full height); an explicit value turns off the automatic fit |
    | Sun or labels in the way | `--no-sun`, `--no-labels`; `--network` adds the triangulation network to other styles |
    | Water drawn where there is none | `--no-water` |
    | Palette | `--paper #hex --ink #hex --accent #hex` |
    
    Everything is normalised to a reference mountain (4.3 km tall, 46 km half-width), so a 1 km hill and an 8 km giant both fill the frame the same way. `--relief` is how you restore or exaggerate real proportions.
    
    ## Sizes that work
    
    | Target | `--size` | Notes |
    |---|---|---|
    | X / Twitter header | `3000x1000` (2× of 1500×500) | Profile photo covers the bottom-left, hence `--align right`. Upload limit is about 5 MB, so ship a JPG if the PNG is bigger |
    | LinkedIn banner | `1584x396` or `3168x792` | Very wide; try `--zoom 1.2` |
    | YouTube banner | `2560x1440` | Safe area is the centre strip; use `--align center` |
    | Desktop wallpaper | `3840x2160` | `--align center` |
    | Print | e.g. `6000x2000` | Render time grows with pixel count |
    | Phone wallpaper (portrait) | e.g. `1170x2532` | Not a tuned layout: the scene is built for wide frames, so the mountain sits in a band across the middle. `--align center --zoom 2.5` fills the width; check the draft, or crop a wide render instead |
    
    ## Web studio
    
    ```bash
    python $SK/scripts/build_studio.py --peak 35.3606,138.7274 --from 35.5100,138.7550 --from-name "Lake Kawaguchi" \
      --name "Mount Fuji" --native "富士山" --label "富士山|3776 m" --out fuji-studio.html
    ```
    
    This produces one self-contained HTML file of about 0.8 MB. It embeds a 512×512 elevation grid, renders with plain Canvas 2D, and makes no network calls at runtime (Google Fonts only). It has all six styles, sliders for camera, light and colour, an orbit animation, and a 3000×1000 PNG export. The same landform-aware framing, water layer, sun placement and label lifting run in the page; `--no-shape` uses the cone rules and `--no-water` leaves water out. It takes `--from` or `--facing` like render.py and reuses the `dem_<lat>_<lon>.npz` next to `--out`. To publish it as a claude.ai artifact, declare the `downloads` capability so the Save button works; the page falls back to showing the image to save manually if the capability is unavailable. Verify it headless with Playwright if available: load it, click each style tile, and check for console errors.
    
    The studio's drawing code is shared with the public web app at https://dogum.github.io/procedural-art/app/, which fetches elevation for any mountain in the browser. If someone only wants to try a mountain quickly and has no Python, point them there.
    
    ## Video
    
    ```bash
    python $SK/scripts/animate.py --peak 39.7019,44.2986 --from 40.1792,44.4991 --style nocturne --out orbit.mp4   # 144 frames, 6 s loop
    python $SK/scripts/animate.py --peak 39.7019,44.2986 --from 40.1792,44.4991 --style nocturne --out orbit.mp4 --start 0 --end 50
    python $SK/scripts/animate.py --peak 39.7019,44.2986 --from 40.1792,44.4991 --style nocturne --out orbit.mp4 --start 50   # encodes when all exist
    ```
    
    Frames go to `<out>_frames/`; frames that already exist are skipped, so a killed run resumes where it stopped. The folder remembers the settings: rerunning the same `--out` with another style, size, label or amplitude clears the old frames first, and only frames 0 to `--frames`−1 are encoded. Other options: `--frames`, `--fps`, `--amplitude` (degrees of swing, default 28), `--size` (default 1500×500), `--quality` (default 0.6), `--label`, `--title`. Horn and canyon orbits keep one vertical framing, so they don't bob. Background processes may be killed when a shell call returns, so run chunks in the foreground.
    
    ## Things that bite
    
    - **Network.** Elevation comes from AWS Terrain Tiles (`s3.amazonaws.com/elevation-tiles-prod`), which needs no key and covers the whole globe, including ocean bathymetry (clipped to 0). If that domain is blocked, say so and ask the user to allow it. Void pixels in the tiles (±32768 m, seen around Denali) are filled from their neighbours when the DEM is loaded.
    - **DEM size matters for the analysis.** The landform measurements use rings out to 40 km, so a default run fetches a 65 km radius. A run with a small `--extent` fetches less; a later default run into the same folder sees that the cache is too small and fetches the full area again. An explicit `--dem` that is too small only prints a warning.
    - **Fonts for non-Latin labels.** The engine looks for Noto CJK (then Hiragino, Yu Gothic, MS Gothic and similar on macOS and Windows) for Chinese, Japanese and Korean, and uses DejaVu (bundled with matplotlib) for Latin, Cyrillic, Greek, Armenian and Georgian. If no CJK font is found it prints a warning and the labels render as boxes; other scripts need a font installed. Check the preview. The web studio loads the matching Noto family from Google Fonts; for Han-only labels such as 富士山 it picks Japanese, Korean, Traditional or Simplified glyph forms from the summit's location, or from `--lang ja|ko|zh-Hant|zh-Hans`.
    - **Contour lines need altitude.** Seen from eye level, contours collapse into horizontal stripes. The `topo` style therefore uses a high camera with 2.4× vertical exaggeration. Keep that if you tweak it. Horns still show some of the stepped-pyramid look in topo; the light-weighted lines soften it.
    - **Labels can fall outside the frame.** With `--align right`, a second peak far to the left of the summit (Mount Moran from Snake River Overlook, Mauna Loa from Hilo) may land in the faded zone, and its label is skipped. Use `--align center` or `--yaw` if it matters.
    - **Near-edge artefacts.** If vertical streaks appear under the terrain, something is sampling below the grid's front edge. The G-buffer masks those pixels; keep that mask if you edit the engine.
    - **Seeing the output.** Always view a downscaled preview before delivering. Two render passes with a look in between beat five blind tweaks.
    
    ## Extending
    
    Read `references/engine.md` before adding a style or changing the camera or the auto framing. It covers the data loader, the landform analysis, the coordinate frames (reference 3000×1000 space versus output pixels, which was the source of most bugs while building this), the floating horizon, the G-buffer, a template for a new style function, and how the web template mirrors the Python.
    
    `scripts/dem.py` (tile download, coverage check and loading with void filling) is shared with procedural-realism. Both skills ship an identical copy; if you change it, change both.
    
  • skills/procedural-terrain-art/scripts/animate.py4.7 KBf98585477017upstream ↗
    #!/usr/bin/env python3
    """
    animate.py — looping orbit video: the camera swings ±amplitude degrees around the summit.
    
      python animate.py --peak 39.7019,44.2986 --from 40.1792,44.4991 --style nocturne --out orbit.mp4
      # long renders: run in chunks (each call skips frames that already exist), encode on the last one
      python animate.py ... --start 0 --end 50 ; python animate.py ... --start 50 --end 144
    
    Frames go to <out>_frames/ with a params.json; a rerun with different settings clears the old frames first.
    Needs ffmpeg for encoding. ~1-4 s per frame at 1500x500 depending on style.
    """
    import argparse, glob, hashlib, json, os, subprocess, sys
    import numpy as np
    sys.dont_write_bytecode = True
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    from terrain_art import ensure_dem, load_dem
    import render as R
    
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--peak", required=True); ap.add_argument("--from", dest="view_from"); ap.add_argument("--facing", type=float)
    ap.add_argument("--style", default="nocturne", choices=R.STYLES); ap.add_argument("--out", required=True)
    ap.add_argument("--dem"); ap.add_argument("--size", default="1500x500"); ap.add_argument("--frames", type=int, default=144)
    ap.add_argument("--fps", type=int, default=24); ap.add_argument("--amplitude", type=float, default=28)
    ap.add_argument("--start", type=int, default=0); ap.add_argument("--end", type=int, default=None)
    ap.add_argument("--label", action="append", default=[]); ap.add_argument("--title", default="")
    ap.add_argument("--quality", type=float, default=0.6); ap.add_argument("--extent", type=float); ap.add_argument("--base", type=float)
    a = ap.parse_args()
    
    summit = R.parse_ll(a.peak); W, H = map(int, a.size.lower().split("x"))
    fdir = os.path.splitext(a.out)[0] + "_frames"; os.makedirs(fdir, exist_ok=True)
    # frames belong to one set of settings: a rerun with other settings starts the frame folder afresh
    _pk = {k: v for k, v in vars(a).items() if k not in ("out", "dem", "start", "end", "fps")}
    _ph = hashlib.md5(json.dumps(_pk, sort_keys=True).encode()).hexdigest()[:10]
    _pf = os.path.join(fdir, "params.json")
    _old = json.load(open(_pf)).get("hash") if os.path.exists(_pf) else None
    _stale = glob.glob(os.path.join(fdir, "*.png"))
    if _stale and _old != _ph:
        print(f"{fdir} holds frames made with other settings; removing {len(_stale)} old frames", flush=True)
        for x in _stale: os.remove(x)
    json.dump({"hash": _ph, "args": _pk}, open(_pf, "w"), indent=1)
    dem_path = a.dem or os.path.join(os.path.dirname(os.path.abspath(a.out)), f"dem_{summit[0]:.3f}_{summit[1]:.3f}.npz")
    ensure_dem(*summit, (a.extent or 45) * 1.45, dem_path, explicit=bool(a.dem), log=lambda m: print(m, flush=True))
    dem = load_dem(dem_path)
    peaks = []
    for L in a.label:
        name, _, rest = L.partition("|"); sub, _, ll = rest.partition("@")
        peaks.append(dict(name=name, sub=sub, latlon=R.parse_ll(ll) if ll else summit))
    end = min(a.end or a.frames, a.frames)
    # shape-aware vertical fit (horns, canyons): measure it once at yaw 0 so the frame doesn't bob during the orbit
    from terrain_art import terrain as _terrain
    _t = _terrain(dem, summit, view_from=R.parse_ll(a.view_from) if a.view_from else None, facing=a.facing, extent_km=a.extent,
                  base_m=a.base, NX=int(1400 * a.quality), NZ=int(520 * a.quality))
    _cfg = dict(W=W, H=H, align="right", labels=bool(peaks), relief=_t.shape.get("relief", 1.0), zoom=1.0)
    pan_y = R.fit_offset(R.scene_for(a.style, _t, dict(_cfg, pan_y=0.0)), _t, _cfg)
    for f in range(a.start, end):
        path = os.path.join(fdir, f"{f:04d}.png")
        if os.path.exists(path): continue
        yaw = a.amplitude * np.sin(2 * np.pi * f / a.frames)
        cfg = dict(summit=summit, view_from=R.parse_ll(a.view_from) if a.view_from else None, facing=a.facing, W=W, H=H,
                   align="right", peaks=[dict(p) for p in peaks], title=a.title, footnote="", extent=a.extent, base=a.base,
                   yaw=yaw, sun=True, labels=bool(peaks), network=False, seed=7, quality=a.quality, pan_y=pan_y)
        R.render(a.style, dem, cfg, path); print(f"frame {f}", flush=True)
    missing = [f for f in range(a.frames) if not os.path.exists(os.path.join(fdir, f"{f:04d}.png"))]
    if not missing:
        subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-framerate", str(a.fps), "-i", os.path.join(fdir, "%04d.png"),
                        "-frames:v", str(a.frames), "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2", "-c:v", "libx264", "-pix_fmt", "yuv420p",
                        "-crf", "18", a.out], check=True)
        print("video ->", a.out)
    else:
        print(f"{a.frames - len(missing)}/{a.frames} frames rendered (first missing: {missing[0]}); "
              "run again with --start 0 (finished frames are skipped) to continue")
    
  • skills/procedural-terrain-art/scripts/build_studio.py9.1 KB2796c6912615upstream ↗
    #!/usr/bin/env python3
    """
    build_studio.py — build the interactive, self-contained web studio for any mountain.
    
      python build_studio.py --peak 39.7019,44.2986 --from 40.1792,44.4991 --from-name Yerevan \
          --name "Masis & Sis" --native "ԱՐԱՐԱՏ" --native-h1 "Մասիս · Սիս" \
          --label "ՄԱՍԻՍ|5137 m" --label "ՍԻՍ|3896 [email protected],44.4011" --out ararat-studio.html
    
    The page (~0.8 MB) embeds a 512x512 elevation grid, renders live on Canvas 2D (no libraries), has
    six styles, orbit animation, light/camera/colour controls, and a 3000x1000 PNG export.
    Publish it as an artifact (declare the `downloads` capability so Save PNG works) or open it locally.
    """
    import argparse, base64, html as htmlmod, json, math, os, re, sys
    import numpy as np
    from scipy.ndimage import map_coordinates
    sys.dont_write_bytecode = True
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    from terrain_art import ensure_dem, load_dem, terrain, water_mask
    
    HERE = os.path.dirname(os.path.abspath(__file__))
    TEMPLATE = os.path.join(HERE, "..", "assets", "studio_template.html")
    
    # Google Fonts families per script (label font, big-title font)
    SCRIPT_FONTS = [
        (r"[԰-֏]", "Noto Serif Armenian", "Noto Sans Armenian"),
        (r"[Ⴀ-ჿ]", "Noto Serif Georgian", "Noto Sans Georgian"),
        (r"[぀-ヿ]", "Noto Serif JP", "Noto Sans JP"),
        (r"[가-힯]", "Noto Serif KR", "Noto Sans KR"),
        (r"[一-鿿]", "HAN", "HAN"),                         # Han only: resolved by --lang or location
        (r"[ऀ-ॿ]", "Noto Serif Devanagari", "Noto Sans Devanagari"),
        (r"[؀-ۿ]", "Noto Naskh Arabic", "Noto Sans Arabic"),
        (r"[֐-׿]", "Noto Serif Hebrew", "Noto Sans Hebrew"),
        (r"[฀-๿]", "Noto Serif Thai", "Noto Sans Thai"),
        (r"[ༀ-࿿]", "Noto Serif Tibetan", "Noto Sans Tibetan"),
    ]
    
    
    HAN_FONTS = {"ja": ("Noto Serif JP", "Noto Sans JP"), "ko": ("Noto Serif KR", "Noto Sans KR"),
                 "zh-Hans": ("Noto Serif SC", "Noto Sans SC"), "zh-Hant": ("Noto Serif TC", "Noto Sans TC")}
    
    
    def han_lang(lat, lon):
        """Kanji / hanja / hanzi share code points; pick the regional glyph forms from where the summit is."""
        if 24 <= lat <= 46 and 122.5 <= lon <= 154: return "ja"
        if 33 <= lat <= 39 and 124 <= lon <= 131: return "ko"
        if 21.8 <= lat <= 25.4 and 119.3 <= lon <= 122.1: return "zh-Hant"
        return "zh-Hans"
    
    
    def pick_fonts(text, lang=None, latlon=(0.0, 0.0)):
        for pat, serif, sans in SCRIPT_FONTS:
            if re.search(pat, text):
                if serif == "HAN": return HAN_FONTS[lang or han_lang(*latlon)]
                return serif, sans
        return "Noto Serif", "Noto Sans"
    
    
    def parse_ll(s):
        a, b = s.split(","); return float(a), float(b)
    
    
    def main():
        ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
        ap.add_argument("--peak", required=True)
        g = ap.add_mutually_exclusive_group(required=True)
        g.add_argument("--from", dest="view_from", help="lat,lon of the viewpoint (e.g. a town)")
        g.add_argument("--facing", type=float, help="compass bearing the camera looks toward (0 = north), if there is no obvious viewpoint")
        ap.add_argument("--from-name", default="the viewpoint")
        ap.add_argument("--name", required=True, help="page title / heading, Latin script")
        ap.add_argument("--native", default="", help="name in the local script (used as big title in riso/woodcut)")
        ap.add_argument("--native-h1", default=None, help="small subtitle next to the heading (default: --native)")
        ap.add_argument("--label", action="append", default=[], help='"Name|sub" or "Name|sub@lat,lon"')
        ap.add_argument("--extent", type=float); ap.add_argument("--base", type=float)
        ap.add_argument("--dem", help="cached .npz (default: dem_<lat>_<lon>.npz next to --out, the same file render.py uses)")
        ap.add_argument("--out", required=True)
        ap.add_argument("--lang", choices=sorted(HAN_FONTS), help="glyph forms for Han-only labels (default: from the summit's location)")
        ap.add_argument("--no-shape", action="store_true", help="cone framing rules for every landform (ignore the landform analysis)")
        ap.add_argument("--no-water", action="store_true", help="don't treat sea and lakes as a separate water layer")
        a = ap.parse_args()
    
        summit = parse_ll(a.peak); vf = parse_ll(a.view_from) if a.view_from else None
        dem_path = a.dem or os.path.join(os.path.dirname(os.path.abspath(a.out)), f"dem_{summit[0]:.3f}_{summit[1]:.3f}.npz")
        ensure_dem(*summit, (a.extent or 45) * 1.45, dem_path, explicit=bool(a.dem), log=lambda m: print(m, file=sys.stderr, flush=True))
        dem = load_dem(dem_path)
        t = terrain(dem, summit, view_from=vf, facing=a.facing, extent_km=a.extent, base_m=a.base, NX=64, NZ=32, shape_aware=not a.no_shape)
        la, lo = t.summit
        kx, ky = 111.32 * math.cos(math.radians(la)), 110.57
        R = t.extent_km * 1.36
        elev, lats, lons = dem
        N = 512
        e = np.linspace(-R, R, N); n = np.linspace(R, -R, N)
        EE, NN = np.meshgrid(e, n)
        ii = np.interp(la + NN / ky, lats[::-1], np.arange(len(lats))[::-1].astype(float))
        jj = (lo + EE / kx - lons[0]) / (lons[1] - lons[0])
        G = map_coordinates(elev, [ii, jj], order=1, mode="nearest").clip(0, 9000).astype("<u2")
        wm = None if a.no_water else water_mask(dem)
        if wm is not None:                          # bit 15 flags open water (elevations need only 14 bits)
            G[map_coordinates(wm.astype(np.float32), [ii, jj], order=1, mode="nearest") > 0.5] |= 0x8000
    
        peaks = []
        for L in a.label:
            name, _, rest = L.partition("|"); sub, _, ll = rest.partition("@")
            p = parse_ll(ll) if ll else (la, lo)
            peaks.append(dict(name=name, sub=sub, E=(p[1] - lo) * kx, N=(p[0] - la) * ky))
        if not peaks or abs(peaks[0]["E"]) + abs(peaks[0]["N"]) > 0.01:
            main_ = [p for p in peaks if abs(p["E"]) + abs(p["N"]) <= 0.01]
            others = [p for p in peaks if p not in main_]
            peaks = (main_ or [dict(name="", sub="", E=0.0, N=0.0)]) + others
        native = a.native or a.name
        alltext = native + (a.native_h1 or "") + "".join(p["name"] + p["sub"] for p in peaks)
        serif, sans = pick_fonts(alltext, a.lang, (la, lo))
        if vf is not None:
            view = [(vf[1] - lo) * kx, (vf[0] - la) * ky]
        else:                                        # --facing: a virtual viewpoint far behind the camera
            b = math.radians(a.facing); view = [-math.sin(b) * 100.0, -math.cos(b) * 100.0]
        fam = lambda f, w: "&family=" + f.replace(" ", "+") + f":wght@{w}"
        fonts = fam(serif, "400;500") + fam(sans, "500")
        sh = t.shape
        horn, canyon, shield = sh.get("horn", 0), sh.get("canyon", 0), sh.get("shield", 0)
        auto = dict(kind=sh.get("kind", "legacy"), relief=sh.get("relief", 1.0), spacing=sh.get("spacing", 1.0),
                    camh=sh.get("camh"), topoCamh=round(24 - 10 * horn, 2) if horn > 0.05 else None,
                    snowline=round(sh["snowline_m"]) if sh.get("snowline_m") else None, fit=bool(horn >= 0.05 or canyon >= 0.05),
                    fadePow=round(1 + min(1.0, horn + canyon + shield), 2),
                    crowd=round(max(horn, sh.get("rough_score", 0)), 2), canyon=round(canyon, 2), shield=round(shield, 2))
        cfg = dict(DN=N, R=R, k=t.k, hs=t.hs, base_km=t.base_m / 1000, peak_km=t.peak_m / 1000, v0=float(t.vs[0]), auto=auto,
                   view=view, peaks=peaks, name=a.name, native=native,
                   slug=re.sub(r"[^a-z0-9]+", "-", a.name.lower()).strip("-") or "mountain",
                   labelFont=f'"{serif}", Georgia, serif', titleFont=f'"{sans}", sans-serif',
                   footnote=f"{abs(la):.2f}°{'N' if la >= 0 else 'S'}  {abs(lo):.2f}°{'E' if lo >= 0 else 'W'}  ·  elevation data, viewed from {a.from_name}",
                   risoSub=f"{a.name.upper()}  ·  " + "  ·  ".join(p["sub"] for p in peaks if p["sub"]))
        html = open(TEMPLATE, encoding="utf-8").read()
        html = re.sub(r"/\* @@ENGINE-(BEGIN|END)\b.*?\*/\n", "", html, flags=re.S)   # engine markers, used by the web app build
        esc = htmlmod.escape                          # user text goes into HTML text and attributes
        subs = {"__CONFIG__": json.dumps(cfg, ensure_ascii=False).replace("</", "<\\/"),   # no </script> inside the JSON
                "__DEM__": base64.b64encode(G.tobytes()).decode(),
                "__PAGETITLE__": esc(f"{a.name} — a procedural terrain studio"), "__FONTS__": fonts,
                "__NATIVEFONT_CSS__": f'"{serif}"', "__H1__": esc(a.name),
                "__NATIVE_H1__": esc(a.native_h1 if a.native_h1 is not None else a.native),
                "__LEDE__": esc(f"{a.name} as seen from {a.from_name},"),
                "__RES__": str(int(round(2 * R / (N - 1) * 1000 / 10) * 10)), "__FROM__": esc(a.from_name), "__NAME__": esc(a.name)}
        for k, v in subs.items(): html = html.replace(k, v)
        left = [k for k in subs if k in html]
        if left: sys.exit(f"template placeholders not filled: {left}")
        os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
        open(a.out, "w", encoding="utf-8").write(html)
        print(json.dumps(dict(out=a.out, bytes=len(html), peak_m=round(t.peak_m), base_m=round(t.base_m), extent_km=round(t.extent_km, 1), auto=auto)))
    
    
    if __name__ == "__main__":
        main()
    
  • skills/procedural-terrain-art/scripts/dem.py5.0 KB8ab0f16fb457upstream ↗
    """dem.py: real elevation data for the procedural-art skills.
    
    procedural-terrain-art and procedural-realism each ship an identical copy of this file, so either skill
    installs on its own. Keep the two copies the same.
    
    Source: AWS Terrain Tiles, terrarium encoding (SRTM and other public sources, global, no key).
    Each pixel decodes as R*256 + G + B/256 - 32768 metres.
    """
    import io, math, os, sys, time, urllib.request, concurrent.futures as cf
    import numpy as np
    from PIL import Image
    
    TILE_URL = "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
    
    
    def _tile_xy(lat, lon, z):
        n = 2 ** z
        return (lon + 180) / 360 * n, (1 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2 * n
    
    
    def fetch_dem(lat, lon, radius_km, out_path, zoom_level=None, max_tiles=260, retries=3):
        """Download a square of elevation around (lat, lon) and save it as .npz (elev m, lats, lons, zoom, radius_km).
        The zoom level follows the radius (z13 up to 15 km, z12 up to 70 km, z11 up to 160 km) and drops
        until the square fits in max_tiles tiles. Rows are Web Mercator (non-linear in latitude).
        The file is written to exactly `out_path` (no .npz is appended), via a temporary file."""
        if zoom_level is None:
            zoom_level = 13 if radius_km <= 15 else 12 if radius_km <= 70 else 11 if radius_km <= 160 else 10
        dlat = radius_km / 110.57; dlon = radius_km / (111.32 * math.cos(math.radians(lat)))
        while True:
            x0, y0 = _tile_xy(lat + dlat, lon - dlon, zoom_level); x1, y1 = _tile_xy(lat - dlat, lon + dlon, zoom_level)
            tx, ty = range(math.floor(x0), math.floor(x1) + 1), range(int(y0), int(y1) + 1)
            if len(tx) * len(ty) <= max_tiles or zoom_level <= 8: break
            zoom_level -= 1
        n = 2 ** zoom_level
    
        def get(a):
            x, y = a
            url = TILE_URL.format(z=zoom_level, x=x % n, y=y)          # x % n wraps across the antimeridian
            for attempt in range(retries):
                try:
                    with urllib.request.urlopen(url, timeout=30) as r:
                        im = np.asarray(Image.open(io.BytesIO(r.read())).convert("RGB")).astype(float)
                    return a, im[..., 0] * 256 + im[..., 1] + im[..., 2] / 256 - 32768
                except Exception as e:                                   # network hiccup: wait and try again
                    if attempt == retries - 1:
                        raise RuntimeError(f"elevation tile {url} failed after {retries} tries: {e}") from e
                    time.sleep(1.5 * (attempt + 1))
    
        M = np.zeros((len(ty) * 256, len(tx) * 256), np.float32)
        with cf.ThreadPoolExecutor(16) as ex:
            for (x, y), e in ex.map(get, [(x, y) for x in tx for y in ty]):
                M[(y - ty[0]) * 256:(y - ty[0] + 1) * 256, (x - tx[0]) * 256:(x - tx[0] + 1) * 256] = e
        lons = (np.arange(M.shape[1]) / 256 + tx[0]) / n * 360 - 180
        lats = np.degrees(np.arctan(np.sinh(np.pi * (1 - 2 * (np.arange(M.shape[0]) / 256 + ty[0]) / n))))
        d = os.path.dirname(os.path.abspath(out_path)); os.makedirs(d, exist_ok=True)
        tmp = out_path + ".part"
        with open(tmp, "wb") as f:
            np.savez_compressed(f, elev=M, lats=lats, lons=lons, zoom=zoom_level, radius_km=float(radius_km),
                                center=np.array([lat, lon]))
        os.replace(tmp, out_path)
        return out_path
    
    
    def dem_coverage_km(path, lat, lon):
        """Distance (km) from (lat, lon) to the nearest edge of a cached DEM; 0 if the point is outside it."""
        d = np.load(path)
        la, lo = d["lats"], d["lons"]
        kx, ky = 111.32 * math.cos(math.radians(lat)), 110.57
        return max(0.0, min((la[0] - lat) * ky, (lat - la[-1]) * ky, (lon - lo[0]) * kx, (lo[-1] - lon) * kx))
    
    
    def ensure_dem(lat, lon, radius_km, path, explicit=False, log=print):
        """Fetch `path` unless it already covers `radius_km` around (lat, lon).
        A cache that is too small is refetched (and overwritten); an explicit --dem file is only warned about."""
        if os.path.exists(path):
            cov = dem_coverage_km(path, lat, lon)
            if cov >= radius_km * 0.98:
                return path
            if explicit:
                print(f"warning: {path} covers only {cov:.0f} km around the peak, {radius_km:.0f} km are needed; "
                      "framing and landform detection may differ from a full fetch", file=sys.stderr, flush=True)
                return path
            log(f"cached {os.path.basename(path)} covers {cov:.0f} km, {radius_km:.0f} km needed: fetching a larger one")
        log(f"fetching elevation, radius {radius_km:.0f} km …")
        return fetch_dem(lat, lon, radius_km, path)
    
    
    def load_dem(path):
        """Load a cached DEM -> (elev float32, lats, lons). Tiles occasionally carry void values (±32768);
        those pixels are filled from their nearest valid neighbour so they can't turn into spikes or pits."""
        d = np.load(path)
        elev = d["elev"].astype(np.float32)
        bad = ~np.isfinite(elev) | (elev < -12000) | (elev > 9000)
        if bad.any() and not bad.all():
            from scipy.ndimage import distance_transform_edt
            elev = elev[tuple(distance_transform_edt(bad, return_distances=False, return_indices=True))]
        return elev, d["lats"], d["lons"]
    
  • skills/procedural-terrain-art/scripts/render.py35 KB6ebe6b46e672upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skills/procedural-terrain-art/scripts/terrain_art.py34 KBffffee963c43upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skills/procedural-terrain-art/references/engine.md14 KB4d8affa21005upstream ↗
    # Engine internals
    
    Files: `scripts/dem.py` (elevation download and loading), `scripts/terrain_art.py` (landform analysis, terrain, camera, helpers), `scripts/render.py` (styles, framing fit, CLI), `scripts/animate.py` (orbit video), `scripts/build_studio.py` + `assets/studio_template.html` (the same engine ported to Canvas 2D JavaScript, config-driven).
    
    The scripts never write into the skill folder, which may be read-only: images, DEM caches and frames go next to `--out` (relative to the working folder), and `sys.dont_write_bytecode` keeps `__pycache__` out of it. Only `assets/` and the scripts themselves are read from the skill folder.
    
    ## 1. Data
    
    `scripts/dem.py` holds `fetch_dem()`, `ensure_dem()` and `load_dem()`. It is shared with procedural-realism: both skills ship a byte-identical copy, so each installs on its own. Change both or neither. `terrain_art.py` re-exports these functions.
    
    - `fetch_dem(lat, lon, radius_km, out)` downloads Terrarium PNG tiles from AWS Terrain Tiles and decodes each pixel as `R*256 + G + B/256 - 32768` metres. The zoom level is picked from the radius (z13 up to 15 km, z12 up to 70 km, z11 up to 160 km, z10 beyond) and lowered until the square fits in 260 tiles. Each tile is retried up to three times, and tile x wraps across the antimeridian. The mosaic is saved to exactly `out` (through a temporary file) as `.npz` with per-row latitudes (Web Mercator, non-linear), per-column longitudes (linear), the zoom and the requested radius.
    - `ensure_dem(lat, lon, radius_km, path, explicit)` reuses `path` when it covers `radius_km` around the point (measured from its lat/lon arrays, so older caches work too), and refetches it otherwise. For a user-given `--dem` (`explicit=True`) it only warns.
    - `load_dem(path)` returns `(elev, lats, lons)`. Void pixels (outside −12000..9000 m, such as the ±32768 values in the Denali tiles) are filled from their nearest valid neighbour, so they can't become spikes or pits. DEMs without voids come back unchanged.
    - `render.py`, `animate.py` and `build_studio.py` need a radius of `(extent or 45) × 1.45` km, 65 km by default, which the landform analysis needs. All three cache it as `dem_<lat>_<lon>.npz` next to `--out`.
    
    ## 2. Terrain grid (the view frame)
    
    `terrain()` builds a grid of `NZ` rows × `NX` columns aligned with the camera:
    - `u` runs left to right across the view, from -46 to 46.
    - `v` is depth away from the viewer, from -35 (near) to 30 (far). The summit sits at `(0, 0)`.
    - The view direction is the unit vector from `view_from` to the summit (or from `facing`), rotated by `yaw`. The right vector is that direction turned 90° clockwise.
    
    **Normalisation.** A real distance in km equals `u × k`, where `k = extent_km / 46`. The drawn height is `(elev − base) / 1000 × hs`, where `hs = 4.3 / (peak − base in km)`. Every tuned constant (fade widths, presence thresholds such as `(h − 0.15) / 0.9`, contour step 0.04, row spacing 0.375) lives in these normalised units, which is why any mountain works without retuning. Use `t.m_to_h(metres)` to convert real elevations such as the snowline, and `t.to_uv((lat, lon))` to place peaks.
    
    **Auto values.**
    - The summit is refined to the DEM maximum within 1.5 km of the given point.
    - `analyse_shape()` measures the landform on rings around the summit (see its docstring for the metrics) and returns four scores: `horn` (steep peak with high ground in front of it), `rough` (alpine texture), `canyon` (the target sits below the surrounding plateau) and `shield` (a broad, gentle dome, steepness under 0.5). Cones score 0 on all four. It also returns a `kind` label (canyon / horn / range / massif / shield / cone), which is only a label: the rules below use the scores.
    - Base: the 20th percentile on the 0.35..1 × 40 km ring (the cone rule), raised towards the local base in the viewer-facing sector by the horn score. For canyons, the 3rd percentile within 12 km (the floor).
    - Height scale: the peak, or for canyons the rim (90th percentile of the 3..20 km ring), maps to 4.3.
    - Extent: `clip(10.5 × height_km × (1 − 0.4·horn) × (1 − 0.1·rough), 8, 60)`, limited by how much DEM was fetched.
    - Relief, line spacing, extra smoothing and camera height come from the same scores. The analysis ignores `yaw`, so orbits keep one framing.
    - `terrain(..., shape_aware=False)` (CLI `--no-shape`) applies the cone rules to every landform. The analysis result is stored as `t.shape` (metrics, scores, suggested values) and `t.top_m`.
    
    **Water.** `water_mask(dem, window=...)` marks sea (elevation ≤ 0 m; the tiles clip ocean to 0 and keep bathymetry below it) and lakes (3×3 elevation range under 1 cm, dilated by a pixel), keeping connected pieces of 0.5 km² or more. `terrain()` runs it on the block of DEM under the view grid and samples it to `t.water` (0..1, smoothed like `h`), or leaves `t.water = None` when fewer than 0.2% of the grid cells are water. Every water code path is skipped when it is `None`, which is why dry views stay pixel-identical. `terrain(..., water=False)` / `--no-water` turns it off.
    
    **Checking a change.** Cones must stay pixel-identical. Before editing, render Fuji, Ararat and Mauna Kea in all six styles at draft quality with a fixed `--dem`, then render them again with the edited engine and compare the PNGs (maximum difference 0/255). Also look at one horn, one range and one canyon, since those use the shape rules.
    
    ## 3. Camera
    
    The camera is defined in a **reference frame 3000 wide × 1000 tall**. For a point `(u, v, h)`:
    
    ```
    d  = v − ZCAM                          (ZCAM = −95)
    sx = s · (cx + fx·u/d)
    sy = s · (hy − fy·(h·hmul − camh)/d)
    s  = W / 3000
    ```
    
    Defaults: `fx 4500`, `fy 10200` (about 2.3× vertical exaggeration on screen), `camh 3.4`, `cx 2150`, `hy 290`. The `topo` style uses `camh 24`, `fy 3000`, `hmul 2.4` and `hy −110`.
    
    For frames that aren't 3:1, `oy` shifts `hy` so the composition stays vertically centred. `fadeX = cx − 1150` is where the left-side fade begins, in reference px. It is disabled for `align=center`.
    
    `Scene.thin_dense` (set to the shape's `shield` score) fades a ridgeline where it sits less than 3 reference px above the previous drawn row, so the far flanks of a broad shield (Mauna Kea's saddle) don't stack into a solid slab with a hard left edge.
    
    `fit_offset()` in `render.py` pans vertically for horns and canyons only, so the skyline stays below 21% of the frame (12% without labels, leaving room for a label) and the foreground above 90%. `animate.py` measures it once at yaw 0 and passes it to every frame. `Scene.fade_pow` squares the left fade for those shapes and for shields, because their flattened plains are dense stacks of rows that otherwise start as a hard edge.
    
    **The one rule that prevents most bugs:** `cx`, `hy`, `fadeX` and every hard-coded offset are *reference* units, while `Y`, `CM`, silhouette values and pixel indices are *output* units. Convert with `× s` or `/ s`, always explicitly. Expressions like `sc.hy + 270 * s` mix the two frames and were the main source of mispositioned moons and fades while building this.
    
    ## 4. Floating horizon and G-buffer
    
    - `Y[i, px]` is the screen y of row `i` at column `px`, or `inf` where the row doesn't cover that column.
    - `CM = minimum.accumulate(Y)` over rows from near to far. `CM[i]` is the horizon after drawing rows `0..i`.
    - A ridgeline point on row `i` is visible if `Y[i] < CM[i-1] − 0.3·s`.
    - An arbitrary surface point (contours, network nodes) is visible if `sy ≤ CM[row_below] + tol`.
    - The **G-buffer** records, for each pixel, the owning row: the first row `i` with `CM[i] ≤ y`, found by `searchsorted` down each column. From the owning row and `u` you can sample any grid field (height, shade, snow) per pixel. Pixels below the nearest row's projection (`y > Y[0]`) are *not* terrain and must be masked; forgetting this causes vertical streaks when the foreground is hilly. `G["edge"]` holds the combined side, near and far fades. Multiply it into anything drawn from the G-buffer.
    
    ## 5. Lighting
    
    `light = (right, away, up)` is in view space, so it rotates with the camera. For example, `(-0.75, -0.25, 0.6)` is light from the left and slightly behind the viewer. `shade = max(0, n·L)`. The snow mask combines height above the snowline with a slope limit.
    
    ## 6. Writing a new style
    
    ```python
    def style_blueprint(t, sc, cfg):
        W, H, s = sc.W, sc.H, sc.s
        ink = hexrgb(cfg["ink"])
        def alpha(c):                      # c: i, px (array), u (array), v, depth 0..1
            hh = sc.sample(t.h, c["i"], c["px"]); sh = sc.sample(t.shade, c["i"], c["px"])
            pres = np.clip((hh - 0.15) / 0.9, 0, 1) * sc.edge_fade(c["u"], c["v"]) * sc.xfade(c["px"])
            return pres * (0.4 + 0.6 * (1 - sh))
        segs, cols, wids = sc.ridgelines(cfg["spacing"], alpha, lambda c: 1.2 - 0.5 * c["depth"], ink)
        bg = np.ones((H, W, 3)) * hexrgb(cfg["paper"])
        fig, ax = figure(bg); add_lines(ax, segs, cols, wids)
        return fig                         # or return an (H, W, 3) float array for pixel styles
    ```
    
    Then register it in `RENDERERS`, `STYLES` and `DEFAULTS` (palette and light), and in `CAM` if it needs its own camera.
    
    Tools already available:
    - `sc.gbuffer({...})` for per-pixel styles.
    - `sc.sky_mask()` to clip suns, moons and stars behind the silhouette.
    - `sc.peaks_screen(latlons)` for label and sun anchors, and `sun_anchor()` to place a sun in the saddle or beside a lone peak.
    - `sun_spot(sc, centre, r, peak, avoid)` keeps a sun or moon where the style put it unless the disc is mostly buried or sits on a jagged skyline, then searches along the skyline for a spot about 70% visible, away from the summit. Pass `label_spans(sc, peaks, pts)` as `avoid` if the style draws labels.
    - `draw_labels()` lifts a label above the skyline (with a longer leader) when the skyline would cross its text, and skips peaks in the faded left zone.
    - `parchment()`, `halftone()`, `draw_network()`, `draw_labels()`, `footnote()`.
    - Water: `sc.ridgelines(..., over_water=False)` already fades lines over `t.water`. `iso_lines(sc, field, levels)` gives visible iso-lines of any grid field on the terrain surface (the coastline is `t.water` at 0.5), `wave_marks(sc, G)` gives sparse horizontal strokes on visible water spaced in screen space (G needs a `water` field), and `draw_water()` in `render.py` puts coastline and waves on a ridgeline style.
    
    ## 6a. Topo on rough ground, canyon woodcut
    
    `style_topo` checks `crowd = max(horn, rough_score)`; at 0 (cones, shields) it draws the plain contours as before. Otherwise:
    - `contour_gap()` solves the projection's Jacobian per grid node to get the on-screen distance between neighbouring contours (0 where the surface folds).
    - Decisions are made per visible piece of a contour (`contour_runs()`), never per point, so a line is kept or dropped whole and nothing breaks along a ridge. Intermediates next to an index contour (levels 1 and 4 of 5) go when the piece's median gap is under 3.2 ref px, the middle ones (2 and 3) under 2.4 px, with a 0.6 px ramp.
    - An index piece shorter than 70 ref px (the bit that peeks over a ridge) is drawn at intermediate weight instead of as a dark ledge.
    - Illuminated contours: width × (0.55 + 0.9·tone) and alpha × (0.6 + 0.8·tone), where tone runs 0 (lit) to 1 (turned from the light) around the shade of flat ground.
    - Water is a thin shoreline (alpha 0.6, width 0.5) plus sparse `wave_marks()` level lines, never a bold ring.
    
    `style_woodcut` for canyons (`canyon` score > 0): `canyon_body()` is ink by depth below the rim (the rim maps to 4.3) plus shadow, thresholded per pixel by `carve()`. Carved paper lines are drawn where it is ink, engraved ink lines where it is paper, and the rim gets an inked skyline. The sun is hidden by the terrain itself rather than by the ink, since most of the rim is paper.
    
    Line widths passed to matplotlib are in points at 200 dpi, where 1 pt ≈ 2.8 px. `ridgelines()` already multiplies by `s`.
    
    ## 7. The web template
    
    `assets/studio_template.html` is the same pipeline in JavaScript. `build_studio.py` fills its placeholders:
    - `__CONFIG__`: grid radius `R`, normalisation `k` and `hs`, base and peak in km, viewer E/N offset, peaks with E/N and labels, fonts, name and slug. It also carries `v0` (the near-edge trim Python uses) and `auto` = {kind, relief, spacing, camh, topoCamh, snowline, fit, fadePow, crowd, canyon, shield}, all computed in Python with the shape analysis.
    - `__DEM__`: a base64 little-endian uint16 512×512 grid in metres, spanning ±R km east/north of the summit. Bit 15 flags water from `water_mask()` (elevations fit in 14 bits); the page rebuilds `t.water` from it with the same 0.2% rule. The studio grid is quantised to whole metres, which would make flat plains look like lakes, so detection stays in Python. A page that fetches float tiles itself can port `water_mask()` directly (sea ≤ 0 m, flat 3×3 patches, 0.5 km² components).
    - Text and font placeholders.
    
    Two differences from the Python version:
    - Ridgelines are grouped into `Path2D` buckets by (alpha, width) so each render needs only a few dozen `stroke()` calls.
    - Draft renders (60% size, fewer rows) run while a slider moves, and a full render follows after 260 ms idle.
    
    JS `autoPanY()` and `sunSpot()`/`labelSpans()` mirror `fit_offset()` and `sun_spot()`/`label_spans()`; `isoSegs()`/`isoLines()`, `waveMarks()`, `contourGap()` and `canyonBody()`/`carve()` mirror the water, topo and canyon code above. JS topo joins marching-squares segments that share a grid-edge id (union-find) to find the visible pieces, since it has no polylines; it smooths with a 3×3 mean where Python uses a gaussian. `bucketLines()` batches strokes by (alpha, width). Keep the two sides in step when you change either.
    
    To add a style to the web studio, add a preset to `PRESETS`, a render function to `RENDER`, and its name to `ORDER`.
    
    **Shared with the web app.** The code between `@@ENGINE-BEGIN` and `@@ENGINE-END` in the template is also the engine of the site's "Any mountain" page (`docs/app/` in the repository). `scripts/build-app.py` wraps it in `makeEngine(CFG, dem, wat)` and writes `docs/app/engine.js`; `build_studio.py` drops the two marker comments, so studio pages are unchanged. Keep page UI below the end marker. `P.align` (set only by the app) re-centres frames that aren't 3:1 and turns off the left fade for `center`, as `Scene` does in Python. The app ports the data side too (tile fetch, `analyse_shape()`, `terrain()` auto values, `water_mask()`, the 512 grid) in `docs/app/terrain.js`; change it along with `terrain_art.py` and `build_studio.py`, and rebuild with `python scripts/build-app.py`.
    
  • skills/procedural-terrain-art/assets/studio_template.html70 KB0b55ba240a36upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • skills/procedural-terrain-art/evals/evals.json4.6 KBd163cfac4460upstream ↗
    {
      "skill_name": "procedural-terrain-art",
      "evals": [
        {
          "id": 1,
          "prompt": "can you make me a twitter header of mount rainier the way it looks from seattle? something like those engraved line drawings, cream paper, maybe a sun. I'm going to put my profile pic bottom left",
          "expected_output": "A 3000x1000 survey-style render of Rainier from a Seattle viewpoint, peak on the right, left third clear, delivered as PNG plus a JPG under 5 MB.",
          "files": [],
          "expectations": [
            "Looked up Rainier's summit and a Seattle viewpoint instead of guessing coordinates",
            "Ran scripts/render.py with --style survey and --size 3000x1000 (default align right)",
            "Checked the printed peak elevation against the real ~4392 m",
            "Viewed a downscaled preview before delivering",
            "Delivered a JPG under 5 MB alongside or instead of an oversized PNG"
          ]
        },
        {
          "id": 2,
          "prompt": "I want a LinkedIn banner of the Grand Tetons as a black woodcut print. Big 'TETONS' title would be cool.",
          "expected_output": "A 1584x396 (or 3168x792) woodcut of the Teton Range with a title.",
          "files": [],
          "expectations": [
            "Used --style woodcut with a LinkedIn banner size (1584x396 or 3168x792)",
            "Passed a --title",
            "Picked a real viewpoint east of the range (e.g. Snake River Overlook or Jenny Lake area)",
            "The range, not a single peak, fills the frame"
          ]
        },
        {
          "id": 3,
          "prompt": "Desktop wallpaper please, 4K, Kilimanjaro at night with stars and a moon. centered composition",
          "expected_output": "A 3840x2160 nocturne render of Kilimanjaro, centred.",
          "files": [],
          "expectations": [
            "Used --style nocturne --size 3840x2160 --align center",
            "Looked up Kibo summit coordinates and a viewpoint (e.g. Amboseli)",
            "Moon sits in open sky, not buried behind terrain"
          ]
        },
        {
          "id": 4,
          "prompt": "Make a short looping video orbiting the Matterhorn, moonlit line style. I want to post it on Instagram.",
          "expected_output": "An MP4 orbit video (nocturne) of the Matterhorn, loopable.",
          "files": [],
          "expectations": [
            "Used scripts/animate.py with --style nocturne",
            "Used a classic Matterhorn viewpoint such as Riffelsee or Zermatt",
            "Rendered in foreground chunks if the shell has a time limit (--start/--end)",
            "Delivered an MP4 encoded with ffmpeg"
          ]
        },
        {
          "id": 5,
          "prompt": "Can you build me one of those interactive pages where I can play with Mount Hood from Portland in different styles and download a header?",
          "expected_output": "A self-contained HTML studio for Mount Hood built with build_studio.py.",
          "files": [],
          "expectations": [
            "Ran scripts/build_studio.py with --peak, --from, --from-name and --name",
            "Output is a single HTML file under about 1 MB with the DEM embedded",
            "If published as an artifact, declared the downloads capability",
            "Checked the page headless (Playwright) or explained how it was verified"
          ]
        },
        {
          "id": 6,
          "prompt": "topographic contour art of the grand canyon from the south rim, I'd like to print it 6000 px wide",
          "expected_output": "A canyon render in topo (or a better-suited style with an explanation) at ~6000x2000.",
          "files": [],
          "expectations": [
            "Targeted a butte or temple inside the canyon and a South Rim viewpoint (e.g. Mather Point)",
            "Rendered at --size 6000x2000",
            "Mentioned honestly if topo reads busy for canyons and offered survey, nocturne or riso"
          ]
        },
        {
          "id": 7,
          "prompt": "Show me Denali in every style you have so I can pick one",
          "expected_output": "Six Denali renders plus a contact sheet.",
          "files": [],
          "expectations": [
            "Ran render.py --style all",
            "Produced a contact sheet",
            "Presented the sheet and offered a full-size final of the chosen style"
          ]
        },
        {
          "id": 8,
          "prompt": "Everest from Kala Patthar, survey style, label it सगरमाथा with the height",
          "expected_output": "An Everest survey render with a Devanagari label that renders correctly (or a clear font fix).",
          "files": [],
          "expectations": [
            "Used a Kala Patthar viewpoint and Everest summit coordinates",
            "Checked the preview for missing-glyph boxes in the Devanagari label",
            "If glyphs were missing, installed or pointed to a Noto Devanagari font, or told the user plainly"
          ]
        }
      ]
    }
    
  • skills/procedural-terrain-art/evals/trigger_evals.json2.4 KB6c03f83a8646upstream ↗
    [
      {"query": "make me a banner for my youtube channel with Mt Shasta drawn in those thin ridge lines like the unknown pleasures cover", "should_trigger": true},
      {"query": "I found this AI generated mountain header on twitter and want to recreate it with code instead so it's actually mine. it's Ararat I think", "should_trigger": true},
      {"query": "risograph style print of Mount Fuji, pink and blue, with the japanese name big", "should_trigger": true},
      {"query": "can u do a topo contour poster of the matterhorn for my living room, 60x20 cm", "should_trigger": true},
      {"query": "I'd like a woodcut-looking image of the mountains around Banff for a coffee bag label", "should_trigger": true},
      {"query": "stipple / pointillism art of Mauna Kea please, white background", "should_trigger": true},
      {"query": "generate a 6 second looping orbit video of Kilimanjaro at night, line art", "should_trigger": true},
      {"query": "build an interactive page where I can rotate Mount St Helens and export a LinkedIn banner", "should_trigger": true},
      {"query": "linkedin cover image of the swiss alps from grindelwald, minimal and engraved", "should_trigger": true},
      {"query": "desktop wallpaper of Denali in a vintage survey-map style", "should_trigger": true},
      {"query": "photorealistic render of Mount Rainier at sunset with haze and a lenticular cloud, no AI image generation", "should_trigger": false},
      {"query": "turn my photo of the Dolomites into a watercolor painting", "should_trigger": false},
      {"query": "plot the elevation profile of my strava GPX from yesterday's hike as a line chart", "should_trigger": false},
      {"query": "write a Midjourney prompt for a moody mountain landscape header", "should_trigger": false},
      {"query": "how do I make hillshade and contours from a DEM in QGIS for my thesis map", "should_trigger": false},
      {"query": "design a simple flat SVG mountain logo for my hiking club, three triangles and a sun", "should_trigger": false},
      {"query": "compute the viewshed from this ridge to check where the new radio tower is visible", "should_trigger": false},
      {"query": "draw the Joy Division Unknown Pleasures album cover exactly", "should_trigger": false},
      {"query": "what is the elevation of Mount Elbrus and which side is easier to climb", "should_trigger": false},
      {"query": "make a 3D printable STL of Half Dome from elevation data", "should_trigger": false}
    ]
    
  • README.mdupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

Plain-text copy, no login: /skill-bundles/dogum-procedural-art-skills-procedural-terrain-art.md

// REPO STATS

12 stars
0 open issues
Last commit: 25d ago