Skip to main content

atmos/os_lib/web_engine/
embed_map.rs

1//! OpenStreetMap 埋め込み(`<iframe src="https://www.openstreetmap.org/export/embed.html?bbox=..&marker=..">`)
2//! を、タイル画像を並べて描くための計算(純粋モジュール)。
3//!
4//! 【2026-09-26】現在の OSM 埋め込みページは MapLibre GL(WebGL で描画)で、AtmOS には WebGL が無いため
5//! iframe の中身をそのまま実行しても地図は出ない。一方、地図タイル自体は普通の PNG
6//! (`https://tile.openstreetmap.org/{z}/{x}/{y}.png`)なので、埋め込み URL の範囲(bbox)と
7//! マーカーから、表示に必要なタイルと配置を計算して**ネイティブに描く**(PDF を内蔵ビューアで
8//! 表示するのと同じ考え方)。ズームは MapLibre/Leaflet の `fitBounds` と同じく「範囲が枠に収まる
9//! 最大の整数ズーム」、中心は範囲の中心。
10//!
11//! 座標は Web メルカトル(EPSG:3857)。ズーム z の世界全体の大きさは 256·2^z ピクセル。
12
13extern crate alloc;
14use alloc::string::String;
15use alloc::vec::Vec;
16
17/// タイル 1 枚の大きさ(px)。
18pub const TILE: i32 = 256;
19/// OSM 標準タイルの最大ズーム。
20pub const MAX_ZOOM: u32 = 19;
21
22/// 埋め込み URL から読み取った情報。
23#[derive(Debug, Clone, PartialEq)]
24pub struct Embed {
25    /// 範囲(経度・緯度の最小・最大)。
26    pub min_lon: f64,
27    pub min_lat: f64,
28    pub max_lon: f64,
29    pub max_lat: f64,
30    /// マーカー(緯度, 経度)。
31    pub marker: Option<(f64, f64)>,
32}
33
34/// 描画計画。座標は iframe の左上を原点とする px。
35#[derive(Debug, Clone, PartialEq)]
36pub struct Plan {
37    pub zoom: u32,
38    /// (タイル URL, 左上 x, 左上 y)。
39    pub tiles: Vec<(String, i32, i32)>,
40    /// マーカーの位置(px)。
41    pub marker: Option<(i32, i32)>,
42}
43
44/// URL が地図の埋め込みページなら、その範囲とマーカーを返す。
45/// 地図の提供元ごとの URL の読み方はサイト別の対応(`site_hooks::map_embed`)にある。
46pub fn parse_embed_url(url: &str) -> Option<Embed> {
47    super::site_hooks::hooks().map_embed(url)
48}
49
50/// 経度・緯度 → ズーム z の世界ピクセル座標。
51pub fn project(lon: f64, lat: f64, z: u32) -> (f64, f64) {
52    let world = TILE as f64 * (1u64 << z) as f64;
53    let lat = lat.clamp(-85.051_128_78, 85.051_128_78);
54    let x = (lon + 180.0) / 360.0 * world;
55    let rad = lat * core::f64::consts::PI / 180.0;
56    let y = (1.0 - libm::log(libm::tan(rad) + 1.0 / libm::cos(rad)) / core::f64::consts::PI) / 2.0 * world;
57    (x, y)
58}
59
60/// 範囲が w×h の枠に収まる最大の整数ズーム(0〜MAX_ZOOM)。
61pub fn fit_zoom(e: &Embed, w: i32, h: i32) -> u32 {
62    let mut best = 0;
63    for z in 0..=MAX_ZOOM {
64        let (x0, y0) = project(e.min_lon, e.max_lat, z);
65        let (x1, y1) = project(e.max_lon, e.min_lat, z);
66        if (x1 - x0) <= w as f64 && (y1 - y0) <= h as f64 {
67            best = z;
68        } else {
69            break;
70        }
71    }
72    best
73}
74
75/// インタラクティブ操作(パン・ズーム)の状態。
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
77pub struct MapState {
78    /// パンオフセット X (px)。右ドラッグで正(地図が右へ動く=中心が西へ移動)。
79    pub pan_x: i32,
80    /// パンオフセット Y (px)。下ドラッグで正(地図が下へ動く=中心が北へ移動)。
81    pub pan_y: i32,
82    /// 明示的なズームレベル(None の場合は fit_zoom(e, w, h) を既定値として使用)。
83    pub zoom_level: Option<u32>,
84}
85
86impl MapState {
87    pub const fn new() -> Self {
88        Self {
89            pan_x: 0,
90            pan_y: 0,
91            zoom_level: None,
92        }
93    }
94
95    pub fn pan(&mut self, dx: i32, dy: i32) {
96        self.pan_x = self.pan_x.saturating_add(dx);
97        self.pan_y = self.pan_y.saturating_add(dy);
98    }
99
100    pub fn zoom_in(&mut self, current_zoom: u32) {
101        let z = self.zoom_level.unwrap_or(current_zoom);
102        self.zoom_level = Some((z + 1).min(MAX_ZOOM));
103        self.pan_x = self.pan_x.saturating_mul(2);
104        self.pan_y = self.pan_y.saturating_mul(2);
105    }
106
107    pub fn zoom_out(&mut self, current_zoom: u32) {
108        let z = self.zoom_level.unwrap_or(current_zoom);
109        self.zoom_level = Some(z.saturating_sub(1));
110        self.pan_x /= 2;
111        self.pan_y /= 2;
112    }
113
114    pub fn reset(&mut self) {
115        *self = Self::default();
116    }
117}
118
119/// ズームコントロールボタンのアクション種別。
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum MapControlAction {
122    ZoomIn,
123    ZoomOut,
124}
125
126pub const CTRL_BTN_SIZE: i32 = 28;
127pub const CTRL_BTN_MARGIN: i32 = 10;
128pub const CTRL_BTN_GAP: i32 = 4;
129
130/// 地図枠内における相対座標 (rel_x, rel_y) がズームボタン領域内にあるかを判定する。
131pub fn hit_test_controls(rel_x: i32, rel_y: i32) -> Option<MapControlAction> {
132    let left = CTRL_BTN_MARGIN;
133    let right = left + CTRL_BTN_SIZE;
134    if rel_x < left || rel_x >= right {
135        return None;
136    }
137    let top_in = CTRL_BTN_MARGIN;
138    let bottom_in = top_in + CTRL_BTN_SIZE;
139    if rel_y >= top_in && rel_y < bottom_in {
140        return Some(MapControlAction::ZoomIn);
141    }
142    let top_out = bottom_in + CTRL_BTN_GAP;
143    let bottom_out = top_out + CTRL_BTN_SIZE;
144    if rel_y >= top_out && rel_y < bottom_out {
145        return Some(MapControlAction::ZoomOut);
146    }
147    None
148}
149
150/// インタラクティブ状態(パン・ズーム指定)を反映して w×h の枠に地図を描く計画を立てる。枠が空なら None。
151pub fn plan_with_state(e: &Embed, w: i32, h: i32, state: &MapState) -> Option<Plan> {
152    if w <= 0 || h <= 0 {
153        return None;
154    }
155    let z = state
156        .zoom_level
157        .unwrap_or_else(|| fit_zoom(e, w, h))
158        .min(MAX_ZOOM);
159    let (x0, y0) = project(e.min_lon, e.max_lat, z);
160    let (x1, y1) = project(e.max_lon, e.min_lat, z);
161    let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
162    // pan_x/pan_y を考慮した画面左上世界座標
163    let left = libm::floor(cx - w as f64 / 2.0) as i64 - state.pan_x as i64;
164    let top = libm::floor(cy - h as f64 / 2.0) as i64 - state.pan_y as i64;
165    let n = 1i64 << z;
166    let t = TILE as i64;
167    let tx0 = left.div_euclid(t);
168    let tx1 = (left + w as i64 - 1).div_euclid(t);
169    let ty0 = top.div_euclid(t).clamp(0, n - 1);
170    let ty1 = (top + h as i64 - 1).div_euclid(t).clamp(0, n - 1);
171    let mut tiles = Vec::new();
172    if ty0 <= ty1 {
173        for ty in ty0..=ty1 {
174            for tx in tx0..=tx1 {
175                // 経度方向は世界を一周するので折り返す。
176                let wx = tx.rem_euclid(n);
177                let url = super::site_hooks::hooks().map_tile_url(z, wx, ty);
178                tiles.push((url, (tx * t - left) as i32, (ty * t - top) as i32));
179            }
180        }
181    }
182    let marker = e.marker.map(|(lat, lon)| {
183        let (mx, my) = project(lon, lat, z);
184        ((libm::floor(mx) as i64 - left) as i32, (libm::floor(my) as i64 - top) as i32)
185    });
186    Some(Plan { zoom: z, tiles, marker })
187}
188
189/// w×h の枠に地図を描く計画を立てる(既定状態)。枠が空なら None。
190pub fn plan(e: &Embed, w: i32, h: i32) -> Option<Plan> {
191    plan_with_state(e, w, h, &MapState::default())
192}
193