Skip to main content

egui_map_view/layers/
mod.rs

1//! Layers for the map view that can handle input, and draw on top of the map view different kinds of data.
2//!
3use egui::{Painter, Pos2, Response};
4use std::any::Any;
5
6use crate::projection::MapProjection;
7
8/// GeoJSON serialization and deserialization for layers.
9#[cfg(feature = "geojson")]
10pub mod geojson;
11
12/// Drawing layer
13#[cfg(feature = "drawing-layer")]
14pub mod drawing;
15
16/// Text layer
17#[cfg(feature = "text-layer")]
18pub mod text;
19
20/// SVG layer
21#[cfg(feature = "svg-layer")]
22pub mod svg;
23
24/// Area layer
25#[cfg(feature = "area-layer")]
26pub mod area;
27
28// Tile layer
29#[cfg(feature = "tile-layer")]
30pub mod tile;
31
32/// A module for serializing and deserializing `Color32` to and from hex strings.
33pub(crate) mod serde_color32 {
34    use egui::Color32;
35    use serde::{self, Deserialize, Deserializer, Serializer};
36
37    /// Serializes a `Color32` to a hex string.
38    pub fn serialize<S>(color: &Color32, serializer: S) -> Result<S::Ok, S::Error>
39    where
40        S: Serializer,
41    {
42        serializer.serialize_str(&color.to_hex())
43    }
44
45    /// Deserializes a `Color32` from a hex string.
46    pub fn deserialize<'de, D>(deserializer: D) -> Result<Color32, D::Error>
47    where
48        D: Deserializer<'de>,
49    {
50        let s = <String as Deserialize>::deserialize(deserializer)?;
51        Color32::from_hex(&s).map_err(|err| serde::de::Error::custom(format!("{err:?}")))
52    }
53}
54
55/// A module for serializing and deserializing `egui::Stroke`.
56pub(crate) mod serde_stroke {
57    use crate::layers::serde_color32;
58    use egui::{Color32, Stroke};
59    use serde::{self, Deserialize, Deserializer, Serialize, Serializer};
60
61    #[derive(Serialize, Deserialize)]
62    struct StrokeHelper {
63        width: f32,
64        #[serde(with = "serde_color32")]
65        color: Color32,
66    }
67
68    pub fn serialize<S>(stroke: &Stroke, serializer: S) -> Result<S::Ok, S::Error>
69    where
70        S: Serializer,
71    {
72        let helper = StrokeHelper {
73            width: stroke.width,
74            color: stroke.color,
75        };
76        helper.serialize(serializer)
77    }
78
79    pub fn deserialize<'de, D>(deserializer: D) -> Result<Stroke, D::Error>
80    where
81        D: Deserializer<'de>,
82    {
83        let helper = StrokeHelper::deserialize(deserializer)?;
84        Ok(Stroke {
85            width: helper.width,
86            color: helper.color,
87        })
88    }
89}
90
91/// A trait for map layers.
92pub trait Layer: Any {
93    /// Handles user input for the layer. Returns `true` if the input was handled and should not be
94    /// processed further by the map.
95    fn handle_input(&mut self, response: &Response, projection: &MapProjection) -> bool;
96
97    /// Draws the layer.
98    fn draw(&self, painter: &Painter, projection: &MapProjection);
99
100    /// Gets the layer as a `dyn Any`.
101    fn as_any(&self) -> &dyn Any;
102
103    /// Gets the layer as a mutable `dyn Any`.
104    fn as_any_mut(&mut self) -> &mut dyn Any;
105}
106
107/// Calculates the squared distance from a point to a line segment.
108pub(crate) fn dist_sq_to_segment(p: Pos2, a: Pos2, b: Pos2) -> f32 {
109    let ab = b - a;
110    let ap = p - a;
111    let l2 = ab.length_sq();
112
113    if l2 == 0.0 {
114        // The segment is a point.
115        return ap.length_sq();
116    }
117
118    // Project point p onto the line defined by a and b.
119    // `t` is the normalized distance from a to the projection.
120    let t = (ap.dot(ab) / l2).clamp(0.0, 1.0);
121
122    // The closest point on the line segment.
123    let closest_point = a + t * ab;
124
125    p.distance_sq(closest_point)
126}
127
128/// Calculates the projection factor of a point onto a line segment.
129/// Returns a value `t` from 0.0 to 1.0.
130pub(crate) fn projection_factor(p: Pos2, a: Pos2, b: Pos2) -> f32 {
131    let ab = b - a;
132    let ap = p - a;
133    let l2 = ab.length_sq();
134
135    if l2 == 0.0 {
136        return 0.0;
137    }
138
139    // Project point p onto the line defined by a and b.
140    (ap.dot(ab) / l2).clamp(0.0, 1.0)
141}
142
143/// Checks if two line segments intersect.
144pub(crate) fn segments_intersect(p1: Pos2, q1: Pos2, p2: Pos2, q2: Pos2) -> bool {
145    fn orientation(p: Pos2, q: Pos2, r: Pos2) -> i8 {
146        let val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
147        if val.abs() < 1e-6 {
148            0 // Collinear
149        } else if val > 0.0 {
150            1 // Clockwise
151        } else {
152            -1 // Counter-clockwise
153        }
154    }
155
156    let o1 = orientation(p1, q1, p2);
157    let o2 = orientation(p1, q1, q2);
158    let o3 = orientation(p2, q2, p1);
159    let o4 = orientation(p2, q2, q1);
160
161    // General case: segments cross each other.
162    if o1 != o2 && o3 != o4 {
163        return true;
164    }
165
166    // Special cases for collinear points are ignored for simplicity,
167    // as they are less critical for this UI interaction.
168    false
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use egui::pos2;
175
176    const EPSILON: f32 = 1e-6;
177
178    #[test]
179    fn test_dist_sq_to_segment() {
180        let a = pos2(0.0, 0.0);
181        let b = pos2(10.0, 0.0);
182
183        // Point on the segment
184        let p1 = pos2(5.0, 0.0);
185        assert!((dist_sq_to_segment(p1, a, b) - 0.0).abs() < EPSILON);
186
187        // Point off the segment, projection is on the segment
188        let p2 = pos2(5.0, 5.0);
189        assert!((dist_sq_to_segment(p2, a, b) - 25.0).abs() < EPSILON); // 5*5
190
191        // Point off the segment, projection is before 'a'
192        let p3 = pos2(-5.0, 5.0);
193        assert!((dist_sq_to_segment(p3, a, b) - 50.0).abs() < EPSILON); // dist^2 from (-5,5) to (0,0) is 25+25 = 50
194
195        // Point off the segment, projection is after 'b'
196        let p4 = pos2(15.0, 5.0);
197        assert!((dist_sq_to_segment(p4, a, b) - 50.0).abs() < EPSILON); // dist^2 from (15,5) to (10,0) is 25+25 = 50
198
199        // Zero-length segment
200        let c = pos2(5.0, 5.0);
201        let p5 = pos2(10.0, 10.0);
202        assert!((dist_sq_to_segment(p5, c, c) - 50.0).abs() < EPSILON); // dist^2 from (10,10) to (5,5) is 25+25 = 50
203    }
204
205    #[test]
206    fn test_projection_factor() {
207        let a = pos2(0.0, 0.0);
208        let b = pos2(10.0, 0.0);
209
210        // Point is 'a'
211        assert!((projection_factor(a, a, b) - 0.0).abs() < EPSILON);
212
213        // Point is 'b'
214        assert!((projection_factor(b, a, b) - 1.0).abs() < EPSILON);
215
216        // Point is midpoint
217        let p1 = pos2(5.0, 0.0);
218        assert!((projection_factor(p1, a, b) - 0.5).abs() < EPSILON);
219
220        // Point projects to midpoint
221        let p2 = pos2(5.0, 5.0);
222        assert!((projection_factor(p2, a, b) - 0.5).abs() < EPSILON);
223
224        // Point projects before 'a' (clamped)
225        let p3 = pos2(-5.0, 5.0);
226        assert!((projection_factor(p3, a, b) - 0.0).abs() < EPSILON);
227
228        // Point projects after 'b' (clamped)
229        let p4 = pos2(15.0, 5.0);
230        assert!((projection_factor(p4, a, b) - 1.0).abs() < EPSILON);
231
232        // Zero-length segment
233        let c = pos2(5.0, 5.0);
234        let p5 = pos2(10.0, 10.0);
235        assert!((projection_factor(p5, c, c) - 0.0).abs() < EPSILON);
236    }
237
238    #[test]
239    fn test_segments_intersect() {
240        // General intersection
241        let p1 = pos2(0.0, 0.0);
242        let q1 = pos2(10.0, 10.0);
243        let p2 = pos2(0.0, 10.0);
244        let q2 = pos2(10.0, 0.0);
245        assert!(segments_intersect(p1, q1, p2, q2), "General intersection");
246
247        // No intersection, parallel
248        let p1 = pos2(0.0, 0.0);
249        let q1 = pos2(10.0, 0.0);
250        let p2 = pos2(0.0, 5.0);
251        let q2 = pos2(10.0, 5.0);
252        assert!(
253            !segments_intersect(p1, q1, p2, q2),
254            "Parallel, no intersection"
255        );
256
257        // No intersection, not parallel
258        let p1 = pos2(0.0, 0.0);
259        let q1 = pos2(1.0, 1.0);
260        let p2 = pos2(2.0, 2.0);
261        let q2 = pos2(3.0, 0.0);
262        assert!(
263            !segments_intersect(p1, q1, p2, q2),
264            "Not parallel, no intersection"
265        );
266
267        // T-junction
268        let p1 = pos2(0.0, 5.0);
269        let q1 = pos2(10.0, 5.0);
270        let p2 = pos2(5.0, 0.0);
271        let q2 = pos2(5.0, 5.0);
272        assert!(segments_intersect(p1, q1, p2, q2), "T-junction");
273
274        // Segments meeting at an endpoint
275        let p1 = pos2(0.0, 0.0);
276        let q1 = pos2(5.0, 5.0);
277        let p2 = pos2(5.0, 5.0);
278        let q2 = pos2(10.0, 0.0);
279        assert!(segments_intersect(p1, q1, p2, q2), "Meeting at an endpoint");
280
281        // Collinear, overlapping
282        let p1 = pos2(0.0, 0.0);
283        let q1 = pos2(10.0, 0.0);
284        let p2 = pos2(5.0, 0.0);
285        let q2 = pos2(15.0, 0.0);
286        assert!(
287            !segments_intersect(p1, q1, p2, q2),
288            "Collinear, overlapping"
289        );
290
291        // Collinear, non-overlapping
292        let p1 = pos2(0.0, 0.0);
293        let q1 = pos2(10.0, 0.0);
294        let p2 = pos2(11.0, 0.0);
295        let q2 = pos2(20.0, 0.0);
296        assert!(
297            !segments_intersect(p1, q1, p2, q2),
298            "Collinear, non-overlapping"
299        );
300
301        // Collinear, one contains another
302        let p1 = pos2(0.0, 0.0);
303        let q1 = pos2(10.0, 0.0);
304        let p2 = pos2(2.0, 0.0);
305        let q2 = pos2(8.0, 0.0);
306        assert!(!segments_intersect(p1, q1, p2, q2), "Collinear, contained");
307
308        // One segment is a point on the other segment
309        let p1 = pos2(0.0, 0.0);
310        let q1 = pos2(10.0, 0.0);
311        let p2 = pos2(5.0, 0.0);
312        let q2 = pos2(5.0, 0.0);
313        assert!(!segments_intersect(p1, q1, p2, q2), "Point on segment");
314    }
315}