Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / maps / planet-data / convert_planets.py

convert_planets.py223 lines · 9.5 KiBRaw
1#!/usr/bin/env python3
2"""Convert published planetary mosaics into the maps app's bundled raster sets.
3
4Same offline pipeline as the Moon pair (NASA SVS 4720, converted by the
5earlier `analysis/convert_moon.py`): every body ships as raw equirectangular
6assets under `maps/src/main/assets/<body>/` —
7
8 <body>_color_<W>.rgba RGBA8 colour, lon -180..180 / lat 90..-90
9 <body>_dem_<W>.rg RG8 packed uint16 DEM (rocky bodies only):
10 R = high byte, G = low byte of
11 packed = metres / 0.5 + 20000 (clamped 0..65535)
12 <body>_ring_1024.rgba 1024x1 RGBA radial ring strip (ringed giants only),
13 u = 0 at the ring inner radius, 1 at the outer
14 *.json sidecar pinning dimensions/format/source
15
16Sources, exact URLs, sizes and licences: see DATASETS.md in this directory.
17Nothing here runs at app runtime; the app is offline-first and only reads
18the converted assets.
19
20Usage:
21 python3 convert_planets.py --raw ~/planet-data/raw --all
22Requires: numpy, Pillow, tifffile (build-time only).
23"""
24import argparse
25import json
26import pathlib
27
28import numpy as np
29from PIL import Image
30
31ASSETS = pathlib.Path(__file__).resolve().parent.parent / "src" / "main" / "assets"
32
33DEM_OFFSET = 20000.0
34DEM_UNIT = 0.5 # metres per packed unit
35
36
37def write_sidecar(path: pathlib.Path, **fields):
38 path.write_text(json.dumps(fields, indent=2) + "\n")
39
40
41def save_rgba(img: Image.Image, out: pathlib.Path, source: str, w: int, h: int):
42 img = img.convert("RGBA")
43 if img.size != (w, h):
44 img = img.resize((w, h), Image.LANCZOS)
45 img.save(out.with_suffix(".tmp.png")) # placeholder replaced below
46 out.with_suffix(".tmp.png").unlink()
47 out.write_bytes(img.tobytes())
48 write_sidecar(
49 out.with_suffix(".json"),
50 width=w, height=h, format="RGBA8", projection="equirectangular",
51 lon_range=[-180, 180], lat_range=[-90, 90], source=source,
52 )
53 print(f"{out.name}: {w}x{h} {out.stat().st_size / 1e6:.1f} MB")
54
55
56def save_dem(metres: np.ndarray, out: pathlib.Path, source: str, radius_km: float):
57 h, w = metres.shape
58 packed = np.clip(metres / DEM_UNIT + DEM_OFFSET, 0, 65535).round().astype(np.uint16)
59 rg = np.empty((h, w, 2), dtype=np.uint8)
60 rg[..., 0] = (packed >> 8).astype(np.uint8)
61 rg[..., 1] = (packed & 0xFF).astype(np.uint8)
62 out.write_bytes(rg.tobytes())
63 write_sidecar(
64 out.with_suffix(".json"),
65 width=w, height=h, format="RG8 packed uint16",
66 units="half-metres + 20000 (i.e. metres = (v - 20000) / 2)",
67 radius_km=radius_km, projection="equirectangular",
68 lon_range=[-180, 180], lat_range=[-90, 90], source=source,
69 )
70 print(f"{out.name}: {w}x{h} {out.stat().st_size / 1e6:.1f} MB "
71 f"(elev {metres.min():.0f}..{metres.max():.0f} m)")
72
73
74def block_mean(arr: np.ndarray, out_w: int, out_h: int) -> np.ndarray:
75 """Box-downsample a 2D float array to (out_h, out_w) ignoring NaNs."""
76 in_h, in_w = arr.shape
77 fy, fx = in_h // out_h, in_w // out_w
78 cropped = arr[: fy * out_h, : fx * out_w]
79 blocks = cropped.reshape(out_h, fy, out_w, fx)
80 return np.nanmean(blocks, axis=(1, 3))
81
82
83def load_dem_tif(path: pathlib.Path, out_w: int, out_h: int) -> np.ndarray:
84 import tifffile
85
86 with tifffile.TiffFile(path) as tif:
87 arr = tif.asarray().astype(np.float32)
88 arr[arr == -32768] = np.nan # GDAL_NODATA
89 metres = block_mean(arr, out_w, out_h)
90 # Fill any residual no-data holes (polar gaps) with the global mean so
91 # the relief shading never sees a cliff at a data boundary.
92 holes = ~np.isfinite(metres)
93 if holes.any():
94 metres[holes] = np.nanmean(metres)
95 return metres
96
97
98def load_colour_tif(path: pathlib.Path, w: int, h: int) -> Image.Image:
99 import tifffile
100
101 with tifffile.TiffFile(path) as tif:
102 arr = tif.asarray() # (3, H, W) uint8, planar
103 rgb = np.moveaxis(arr, 0, -1)
104 return Image.fromarray(rgb, "RGB").resize((w, h), Image.LANCZOS)
105
106
107def load_colour_jpg(path: pathlib.Path, w: int, h: int) -> Image.Image:
108 return Image.open(path).convert("RGB").resize((w, h), Image.LANCZOS)
109
110
111def save_ring_strip(strip_rgba: np.ndarray, out: pathlib.Path, source: str,
112 inner: float, outer: float):
113 assert strip_rgba.shape == (1, 1024, 4) and strip_rgba.dtype == np.uint8
114 out.write_bytes(strip_rgba.tobytes())
115 write_sidecar(
116 out.with_suffix(".json"),
117 width=1024, height=1, format="RGBA8 radial strip",
118 ring_inner_radii=inner, ring_outer_radii=outer,
119 note="u = (radius - inner) / (outer - inner) in planetary radii",
120 source=source,
121 )
122 print(f"{out.name}: 1024x1 {out.stat().st_size} B")
123
124
125def saturn_ring(raw: pathlib.Path) -> np.ndarray:
126 """Collapse the Solar System Scope ring texture to a 1024x1 strip."""
127 img = Image.open(raw / "2k_saturn_ring_alpha.png").convert("RGBA")
128 arr = np.asarray(img).astype(np.float32)
129 alpha = arr[..., 3:4] / 255.0
130 rgb = (arr[..., :3] * alpha).sum(axis=0) / np.maximum(alpha.sum(axis=0), 1e-6)
131 a = arr[..., 3].mean(axis=0)
132 strip = np.zeros((1, 2048, 4), dtype=np.uint8)
133 strip[0, :, :3] = np.clip(rgb, 0, 255).astype(np.uint8)
134 strip[0, :, 3] = np.clip(a, 0, 255).astype(np.uint8)
135 # Box-downsample 2048 -> 1024.
136 return strip.reshape(1, 1024, 2, 4).mean(axis=2).round().astype(np.uint8)
137
138
139def procedural_ring(bands, rgb) -> np.ndarray:
140 """Thin-ring strip: gaussian bands at (centre_u, width_u, peak_alpha)."""
141 u = np.linspace(0.0, 1.0, 1024)
142 alpha = np.zeros(1024, dtype=np.float32)
143 for centre, width, peak in bands:
144 alpha += peak * np.exp(-0.5 * ((u - centre) / width) ** 2)
145 strip = np.zeros((1, 1024, 4), dtype=np.uint8)
146 strip[0, :, 0], strip[0, :, 1], strip[0, :, 2] = rgb
147 strip[0, :, 3] = np.clip(alpha, 0, 255).astype(np.uint8)
148 return strip
149
150
151def main():
152 ap = argparse.ArgumentParser()
153 ap.add_argument("--raw", required=True, help="directory with downloaded source files")
154 ap.add_argument("--all", action="store_true")
155 args = ap.parse_args()
156 raw = pathlib.Path(args.raw)
157
158 # Mercury: USGS MESSENGER MDIS enhanced-colour mosaic + USGS DEM (MLA +
159 # stereo), public domain (USGS/NASA). Colour 4096 wide like the Moon.
160 mercury = ASSETS / "mercury"
161 mercury.mkdir(parents=True, exist_ok=True)
162 save_rgba(
163 load_colour_tif(raw / "Mercury_MESSENGER_MDIS_Basemap_EnhancedColor_Mosaic_Global_665m.tif", 4096, 2048),
164 mercury / "mercury_color_4096.rgba",
165 "USGS MESSENGER MDIS Basemap EnhancedColor Mosaic Global 665m (PDS/ASC S3)", 4096, 2048)
166 save_dem(
167 load_dem_tif(raw / "Mercury_Messenger_USGS_DEM_Global_665m_v2.tif", 2048, 1024),
168 mercury / "mercury_dem_2048.rg",
169 "USGS Mercury MESSENGER DEM Global 665m v2 (MLA + stereo, rel 2439.4 km sphere)", 2439.4)
170
171 # Mars: USGS Viking colour mosaic + MGS MOLA DEM, public domain.
172 mars = ASSETS / "mars"
173 mars.mkdir(parents=True, exist_ok=True)
174 save_rgba(
175 load_colour_tif(raw / "Mars_Viking_ClrMosaic_global_925m.tif", 4096, 2048),
176 mars / "mars_color_4096.rgba",
177 "USGS Mars Viking ClrMosaic global 925m (PDS/ASC S3)", 4096, 2048)
178 save_dem(
179 load_dem_tif(raw / "Mars_MGS_MOLA_DEM_mosaic_global_463m.tif", 2048, 1024),
180 mars / "mars_dem_2048.rg",
181 "USGS Mars MGS MOLA DEM mosaic global 463m (rel areoid)", 3396.0)
182
183 # Gas/ice giants + Venus: colour spheres only (thick atmospheres, no
184 # usable global topography). Solar System Scope textures (CC BY 4.0,
185 # derived from NASA imagery), already 2048x1024.
186 for body, jpg, source in [
187 ("venus", "2k_venus_atmosphere.jpg", "Solar System Scope 2k Venus atmosphere (CC BY 4.0; NASA-based)"),
188 ("jupiter", "2k_jupiter.jpg", "Solar System Scope 2k Jupiter (CC BY 4.0; NASA-based)"),
189 ("saturn", "2k_saturn.jpg", "Solar System Scope 2k Saturn (CC BY 4.0; NASA-based)"),
190 ("uranus", "2k_uranus.jpg", "Solar System Scope 2k Uranus (CC BY 4.0; NASA-based)"),
191 ("neptune", "2k_neptune.jpg", "Solar System Scope 2k Neptune (CC BY 4.0; NASA-based)"),
192 ]:
193 dest = ASSETS / body
194 dest.mkdir(parents=True, exist_ok=True)
195 save_rgba(load_colour_jpg(raw / jpg, 2048, 1024), dest / f"{body}_color_2048.rgba", source, 2048, 1024)
196
197 # Rings. Saturn: real radial profile from the SSS ring texture, mapped
198 # onto 1.24..2.27 radii (C ring inner edge to A ring outer edge).
199 save_ring_strip(saturn_ring(raw), ASSETS / "saturn" / "saturn_ring_1024.rgba",
200 "Solar System Scope Saturn ring texture (CC BY 4.0), row-collapsed radial profile",
201 1.24, 2.27)
202 # Uranus: narrow dark rings (Voyager 2 / HST radii), procedural strip —
203 # no published global ring texture exists at usable licence/resolution.
204 save_ring_strip(
205 procedural_ring(
206 [(0.19, 0.004, 60), (0.36, 0.004, 70), (0.43, 0.004, 80), (0.51, 0.005, 90),
207 (0.66, 0.005, 80), (0.83, 0.006, 100), (0.94, 0.008, 160)],
208 (178, 196, 200)),
209 ASSETS / "uranus" / "uranus_ring_1024.rgba",
210 "Procedural: Voyager 2/HST Uranus ring radii (zeta..epsilon), faint narrow bands",
211 1.55, 2.02)
212 # Neptune: Galle/LeVerrier/Lassell/Adams rings, procedural strip.
213 save_ring_strip(
214 procedural_ring(
215 [(0.12, 0.05, 36), (0.47, 0.006, 90), (0.73, 0.03, 44), (0.92, 0.008, 110)],
216 (168, 186, 214)),
217 ASSETS / "neptune" / "neptune_ring_1024.rgba",
218 "Procedural: Voyager 2 Neptune ring radii (Galle, LeVerrier, Lassell, Adams)",
219 1.68, 2.32)
220
221
222if __name__ == "__main__":
223 main()