aboutsummaryrefslogtreecommitdiffziptar.gz
path: root/mapgen/viewer_export.py
blob: e6f51b44e8cbbb9a045ff53be6510da87084a90f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""Viewer textures: colourised equirectangular JPEG layers + layers.json."""
from __future__ import annotations

import json
from pathlib import Path

import numpy as np
from PIL import Image


def hex_color(c) -> str:
    return "#%02x%02x%02x" % tuple(int(v) for v in list(c)[:3])


def categorical_legend(names, palette) -> dict:
    return {"type": "categorical",
            "items": [{"name": n, "color": hex_color(palette[i % len(palette)])} for i, n in enumerate(names)]}


def continuous_legend(unit, lo, hi, stops) -> dict:
    vals = np.linspace(lo, hi, len(stops))
    return {"type": "continuous", "unit": unit,
            "stops": [[round(float(v), 4), hex_color(s)] for v, s in zip(vals, stops)]}


def write_layer(vdir: Path, L: dict) -> dict:
    """Write one layer's JPEG; returns its layers.json entry."""
    vdir.mkdir(parents=True, exist_ok=True)
    Image.fromarray(np.ascontiguousarray(L["rgb"], dtype=np.uint8)).save(vdir / f"{L['id']}.jpg", quality=90)
    return {"id": L["id"], "name": L["name"], "file": f"{L['id']}.jpg", "legend": L["legend"]}


def write_index(vdir: Path, entries: list[dict]) -> None:
    vdir.mkdir(parents=True, exist_ok=True)
    (vdir / "layers.json").write_text(json.dumps(entries, indent=1))


def write_all(vdir: Path, layers: list[dict]) -> None:
    write_index(vdir, [write_layer(vdir, L) for L in layers])