SPB Git

Repository Public

build_textures.py 19.2 KB 334 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : ORIX Cosmos10# File             : DataPipeline/textures/build_textures.py11# Description      : Builds the texture packs from the raw cache: compiles12#                    tools/imgtool.swift, converts every layer of layers.json13#                    to the ORIX map convention at each resolution level,14#                    distributes the files into15#                    Resources/Packs/textures-starter, textures-hd and16#                    sky-imagery, and writes each pack's manifest.json plus17#                    data/assets.json (the layer registry consumed by18#                    build_planetary.py). Standard library + swiftc only.19# Module           : DataPipeline20# Repository       : https://git.spboucher.ai/orix-cosmos21# Project Website  : https://www.orixlab.dev22# Created          : 2026-11-2423# Last Modified    : 2026-11-2424#25# =============================================================================26# AUTHOR & PROFESSIONAL AFFILIATION27# =============================================================================28#29# Author           : Simon-Pierre Boucher30# Position         : Professor of Finance31# Institution      : Université du Québec en Outaouais (UQO)32# Department       : Département des sciences administratives33# Organization     : SP Boucher34#35# Website          : https://spboucher.ai36# Git              : https://git.spboucher.ai37#38# =============================================================================39# OFFICIAL CONTACT DIRECTORY40# =============================================================================41#42# General          : info@spboucher.ai43# Professional     : contact@spboucher.ai44# Direct           : simon@spboucher.ai45# Research         : research@spboucher.ai46# Development      : dev@spboucher.ai47# Support          : support@spboucher.ai48# Security/Admin   : admin@spboucher.ai49# Notifications    : notifications@spboucher.ai50#51# Preferred Contact: support@spboucher.ai52#53# =============================================================================54# COPYRIGHT & INTELLECTUAL PROPERTY55# =============================================================================56#57# Copyright (c) 202658# Simon-Pierre Boucher59#60# All rights reserved where applicable.61#62# This file is governed by the applicable project license,63# copyright notices, institutional agreements and relevant law.64#65# Unless expressly authorized by the applicable license or66# rights holder, copying, redistribution, sublicensing,67# publication and commercial exploitation are not permitted.68#69# Existing third-party rights and notices remain unaffected.70#71# =============================================================================72# CONFIDENTIALITY & SECURITY73# =============================================================================74#75# Classification   : Public76# Distribution     : Public repository; use is governed by the project license77# Security Contact : admin@spboucher.ai78#79# Access to this source does not independently grant permission80# to redistribute or disclose confidential materials.81#82# Do not embed credentials, private keys, access tokens,83# certificates or confidential personal information.84#85# =============================================================================86# LICENSE & MAINTENANCE87# =============================================================================88#89# License          : None specified (no license file in this repository)90# Maintainer       : Simon-Pierre Boucher91# Technical Contact: dev@spboucher.ai92#93# =============================================================================94# END OF SP BOUCHER SOURCE HEADER95# =============================================================================9697"""Usage: build_textures.py <repository root> [--only <slug>[,<slug>...]] [--manifests-only]9899--manifests-only converts nothing: it re-reads the images already in the packs and rewrites the manifests (pack manifest100schema v1, DataPipeline/packs/schema/pack-manifest.v1.schema.json) and data/assets.json. No network in either mode.101102Levels up to 2048 pixels wide (1024 for elevation and normal maps) go to textures-starter, larger ones to textures-hd;103sky layers go to sky-imagery.104A layer whose raw source is missing is skipped and listed under "notBuilt" in data/assets.json (never substituted)."""105import datetime106import hashlib107import json108import os109import subprocess110import sys111112# Pack id -> schema v1 kind, title and description (English and Canadian French; \u00a0 = no-break space).113PACKS = {114    "textures-starter": {115        "kind": "textures",116        "title": {"en": "Planetary textures, starter set (up to 2048 pixels wide)",117                  "fr": "Textures planétaires, ensemble de départ (jusqu\u2019à 2\u00a0048 pixels de largeur)"},118        "description": {119            "en": "Surface, cloud, elevation and normal maps of the planets, moons and dwarf planets in the ORIX equirectangular "120                  "convention, at the resolution levels loaded by default. Derived (re-projected, resampled, re-encoded) from NASA, "121                  "USGS, PDS and STScI products; the nature and the credit line of each image are recorded per file.",122            "fr": "Cartes de surface, de nuages, d\u2019altitude et de normales des planètes, des lunes et des planètes naines dans la "123                  "convention équirectangulaire ORIX, aux niveaux de résolution chargés par défaut. Dérivées (reprojetées, "124                  "rééchantillonnées, réencodées) de produits de la NASA, de l\u2019USGS, du PDS et du STScI; la nature et la mention "125                  "de source de chaque image sont consignées par fichier."}},126    "textures-hd": {127        "kind": "textures",128        "title": {"en": "Planetary textures, high definition (4096 and 8192 pixels wide)",129                  "fr": "Textures planétaires, haute définition (4\u00a0096 et 8\u00a0192 pixels de largeur)"},130        "description": {131            "en": "Higher resolution levels of the planetary surface, elevation and normal maps of the starter set, in the same "132                  "ORIX equirectangular convention. Derived (re-projected, resampled, re-encoded) from NASA, USGS and PDS products; "133                  "the nature and the credit line of each image are recorded per file.",134            "fr": "Niveaux de résolution supérieurs des cartes planétaires de surface, d\u2019altitude et de normales de l\u2019ensemble de "135                  "départ, dans la même convention équirectangulaire ORIX. Dérivées (reprojetées, rééchantillonnées, réencodées) de "136                  "produits de la NASA, de l\u2019USGS et du PDS; la nature et la mention de source de chaque image sont consignées "137                  "par fichier."}},138    "sky-imagery": {139        "kind": "sky-imagery",140        "title": {"en": "Sky imagery: NASA SVS Deep Star Maps 2020 (rendered from Hipparcos-2, Tycho-2 and Gaia DR2)",141                  "fr": "Imagerie du ciel\u00a0: Deep Star Maps 2020 du NASA SVS (rendu à partir d\u2019Hipparcos-2, de Tycho-2 et de Gaia DR2)"},142        "description": {143            "en": "Star map and Milky Way background in ICRF right ascension and declination (plate carrée), at several resolution "144                  "levels. A rendered data product, not a photograph.",145            "fr": "Carte d\u2019étoiles et fond de la Voie lactée en ascension droite et déclinaison ICRF (plate carrée), à plusieurs "146                  "niveaux de résolution. Il s\u2019agit d\u2019un produit de données rendu, et non d\u2019une photographie."}},147}148# Licence keys of sources.json whose recorded statement quotes terms placing the material in the public domain.149# Every other key (NASA media guidelines "educational or informational purposes", tile service and PDS without licence150# text, OPAL terms to be confirmed) keeps a pack localBuildOnly until the owner decides.151QUOTED_PUBLIC_DOMAIN = {"usgs-pd"}152METHOD = ("Converted by DataPipeline/textures (longitude roll to the ORIX map convention, area-average resampling, re-encoding); "153          "see Documentation/modules/CosmosPlanetary.md.")154EXT = {"color": "jpg", "mono": "jpg", "hdr": "jpg", "data8": "png", "data16": "png", "mask": "png", "cloud": "png", "normal": "png"}155ENCODING = {"color": "sRGB 8-bit JPEG", "mono": "sRGB 8-bit JPEG (grey replicated to RGB)", "hdr": "sRGB 8-bit JPEG (tone-mapped from linear float)",156            "data8": "linear 8-bit grey PNG", "data16": "linear 16-bit grey PNG", "mask": "linear 8-bit grey PNG",157            "cloud": "8-bit RGBA PNG (white, alpha = coverage)", "normal": "linear 8-bit RGB PNG (tangent space: east, north, up)"}158159160def sha256(path):161    h = hashlib.sha256()162    with open(path, "rb") as f:163        for block in iter(lambda: f.read(1 << 20), b""):164            h.update(block)165    return h.hexdigest()166167168def pack_of(layer, width):169    if layer.get("pack"):170        return layer["pack"]171    # Elevation and normal maps are large: the starter set only carries their 1024-pixel level.172    limit = 1024 if layer["role"] in ("elevation", "normal") else 2048173    return "textures-starter" if width <= limit else "textures-hd"174175176def main():177    if len(sys.argv) < 2:178        raise SystemExit(__doc__)179    root = os.path.abspath(sys.argv[1])180    only = None181    manifests_only = "--manifests-only" in sys.argv182    if "--only" in sys.argv:183        only = set(sys.argv[sys.argv.index("--only") + 1].split(","))184    here = os.path.join(root, "DataPipeline", "textures")185    raw = os.path.join(root, "DataPipeline", "raw", "textures")186    packs_dir = os.environ.get("COSMOS_PACKS_DIR") or os.path.join(root, "Resources", "Packs")187    sources = json.load(open(os.path.join(here, "sources.json"), encoding="utf-8"))188    layers = json.load(open(os.path.join(here, "layers.json"), encoding="utf-8"))["layers"]189    facts = json.load(open(os.path.join(here, "data", "facts.json"), encoding="utf-8"))190    raw_index = json.load(open(os.path.join(raw, "RAW_INDEX.json")))191    by_id = {s["id"]: s for s in sources["sources"]}192    tool = os.path.join(raw, ".bin", "imgtool")193    tool_src = os.path.join(here, "tools", "imgtool.swift")194    if not os.path.exists(tool) or os.path.getmtime(tool) < os.path.getmtime(tool_src):195        os.makedirs(os.path.dirname(tool), exist_ok=True)196        subprocess.run(["swiftc", "-O", "-o", tool, tool_src], check=True)197198    registry, not_built = [], []199    for layer in layers:200        src = by_id[layer["source"]]201        slug, role, mode = layer["slug"], layer["role"], layer["mode"]202        ext = EXT[mode]203        entry = dict(layer)204        entry["encoding"] = ENCODING[mode]205        entry["files"] = []206        if src["id"] not in raw_index["sources"]:207            not_built.append({"body": layer["body"], "role": role, "source": src["id"], "reason": "raw source could not be obtained"})208            continue209        if mode == "normal":210            radius = facts["bodies"][layer["body"]]["properties"]["meanRadius"]["value"]211            entry["normal"] = {"radiusMeters": radius, "slopeExaggeration": layer["exaggeration"], "space": "tangent (east, north, up)"}212        in_path = os.path.join(raw, src["file"] if src["kind"] == "file" else src["dir"])213        outs = {w: os.path.join(packs_dir, pack_of(layer, w), slug, f"{role}_{w}.{ext}") for w in layer["levels"]}214        if not manifests_only and (only is None or slug in only):215            stage = os.path.join(raw, ".stage", slug)216            os.makedirs(stage, exist_ok=True)217            conv = layer["sourceConvention"]218            cmd = [tool, "build", "--in", in_path, "--mode", mode, "--levels", ",".join(str(w) for w in sorted(layer["levels"], reverse=True)),219                   "--out", os.path.join(stage, f"{role}_{{w}}.{ext}"), "--src-lon-left", str(conv["lonLeftEdgeDeg"])]220            if conv.get("westPositive"):221                cmd.append("--west-positive")222            if "validLatitudeRange" in layer:223                cmd += ["--valid-lat-top", str(layer["validLatitudeRange"]["northDeg"]), "--valid-lat-bottom", str(layer["validLatitudeRange"]["southDeg"])]224            if "raw16be" in layer:225                cmd += ["--raw16be", str(layer["raw16be"][0]), str(layer["raw16be"][1])]226            for key, opt in (("heightScale", "--height-scale"), ("heightOffset", "--height-offset"), ("outScale", "--out-scale"),227                             ("outOffset", "--out-offset"), ("exaggeration", "--exaggeration"), ("threshold", "--threshold"), ("exposure", "--exposure")):228                if key in layer:229                    cmd += [opt, str(layer[key])]230            if mode == "normal":231                cmd += ["--radius-m", str(entry["normal"]["radiusMeters"])]232            if mode in ("color", "mono", "hdr"):233                cmd += ["--quality", str(layer.get("quality", 0.9))]234            print(" ".join(os.path.basename(c) if c.startswith("/") else c for c in cmd), flush=True)235            subprocess.run(cmd, check=True)236            for w, dest in outs.items():237                os.makedirs(os.path.dirname(dest), exist_ok=True)238                os.replace(os.path.join(stage, f"{role}_{w}.{ext}"), dest)239        for w in sorted(layer["levels"]):240            dest = outs[w]241            if not os.path.exists(dest):242                not_built.append({"body": layer["body"], "role": role, "source": src["id"], "reason": f"level {w} not produced"})243                continue244            entry["files"].append({"pack": pack_of(layer, w), "path": f"{slug}/{role}_{w}.{ext}", "width": w, "height": w // 2,245                                   "bytes": os.path.getsize(dest), "sha256": sha256(dest)})246        registry.append(entry)247248    today = datetime.date.today().isoformat()249    licences = sources["licences"]250    totals = {}251    for pack_id, meta in PACKS.items():252        files, used = [], []253        for entry in registry:254            src = by_id[entry["source"]]255            for f in entry["files"]:256                if f["pack"] != pack_id:257                    continue258                if src["id"] not in used:259                    used.append(src["id"])260                # Licence and citation of a file are those of its source (sources[]); the credit line stays per file.261                files.append({262                    "path": f["path"], "size": f["bytes"], "sha256": f["sha256"],263                    "url": src.get("url") or src.get("endpoint"), "role": entry["role"], "source": src["id"],264                    "description": entry["description"], "credit": src["credit"],265                    "body": entry["body"], "nature": entry["nature"], "width": f["width"], "height": f["height"],266                    "encoding": entry["encoding"], "projection": sources["convention"]["id"],267                    "latitude": entry["sourceConvention"]["latitude"], "source_title": src["title"], "source_page": src["page"],268                    "source_retrieved": raw_index["sources"][src["id"]]["retrieved"], "source_sha256": raw_index["sources"][src["id"]]["sha256"],269                })270        if not files:271            continue272        files.sort(key=lambda f: f["path"])273        # Same records as the provenance table of data/planetary.json (build_planetary.py).274        source_records, keys = [], []275        for sid in sorted(used):276            src = by_id[sid]277            lic = licences[src["licence"]]278            if src["licence"] not in keys:279                keys.append(src["licence"])280            source_records.append({281                "id": sid, "name": src["title"], "version": raw_index["sources"][sid]["sha256"][:16],282                "retrieved": raw_index["sources"][sid]["retrieved"], "url": src["page"],283                "license": f"{lic['name']} ({lic['url']}): {lic['summary']}",284                "citation": f"{src['credit']}. {src['citation']}", "method": METHOD,285            })286        blocking = [k for k in keys if k not in QUOTED_PUBLIC_DOMAIN]287        if blocking:288            redistribution = "localBuildOnly"289            note = ("Derived works of the cited sources. The recorded statements of " + "; ".join(licences[k]["name"] for k in blocking)290                    + " quote no terms that explicitly permit redistribution of derived files (see sources[].license): marked "291                    "localBuildOnly until the owner decides (rebuild locally with DataPipeline/textures/build_all.sh).")292        else:293            redistribution = "redistributable"294            note = "Every source is covered by a recorded public-domain statement (see sources[].license); credit lines are kept per file."295        manifest = {296            "schemaVersion": 1, "id": pack_id, "version": "1.0.0", "kind": meta["kind"],297            "title": meta["title"], "description": meta["description"], "retrieved": today,298            "license": ("Mixed, per source: " if len(keys) > 1 else "") + "; ".join(licences[k]["name"] for k in keys) + ". The licence statement of each source is in "299                       "sources[], the credit line of each image in files[]. Processed (re-projected to one convention, resampled, "300                       "re-encoded) by DataPipeline/textures; the files are derived works of the cited sources.",301            "redistribution": redistribution, "redistributionNote": note,302            "acknowledgement": "Imagery and maps: " + "; ".join(dict.fromkeys(f["credit"] for f in files)) + ".",303            "convention": sources["convention"],304            "coverage": {"bodies": sorted({f["body"] for f in files}), "widths_px": sorted({f["width"] for f in files}),305                         "roles": sorted({f["role"] for f in files})},306            "installedSize": sum(f["size"] for f in files),307            "files": files,308            "sources": source_records,309        }310        os.makedirs(os.path.join(packs_dir, pack_id), exist_ok=True)311        with open(os.path.join(packs_dir, pack_id, "manifest.json"), "w", encoding="utf-8") as out:312            json.dump(manifest, out, indent=2, sort_keys=True, ensure_ascii=False)313            out.write("\n")314        totals[pack_id] = (len(files), manifest["installedSize"])315        # Remove images left over from earlier builds (a file that is not in the manifest must not ship).316        listed = {f["path"] for f in files}317        for folder, _, names in os.walk(os.path.join(packs_dir, pack_id)):318            for name in names:319                rel = os.path.relpath(os.path.join(folder, name), os.path.join(packs_dir, pack_id))320                if name.lower().endswith((".jpg", ".png")) and rel not in listed:321                    os.remove(os.path.join(folder, name))322    os.makedirs(os.path.join(here, "data"), exist_ok=True)323    with open(os.path.join(here, "data", "assets.json"), "w", encoding="utf-8") as out:324        json.dump({"format": 1, "built": today, "convention": sources["convention"], "layers": registry, "notBuilt": not_built}, out, indent=1, ensure_ascii=False)325        out.write("\n")326    for pack_id, (count, size) in totals.items():327        print(f"{pack_id}: {count} files, {size / 1e6:.1f} MB")328    if not_built:329        print("not built: " + "; ".join(f"{n['body']} {n['role']} ({n['reason']})" for n in not_built), file=sys.stderr)330331332if __name__ == "__main__":333    main()334
Files main
Menu

Theme